File size: 10,240 Bytes
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c604
 
 
9ed9b88
a49d0a8
66ffc69
 
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e7e92c
a49d0a8
 
 
 
 
85817cd
a49d0a8
85817cd
b309037
876dc56
 
 
752a92c
876dc56
a49d0a8
 
 
 
0e7e92c
a49d0a8
 
 
 
 
b962858
a49d0a8
 
 
 
7d5e8b3
 
a49d0a8
 
 
 
 
 
0e7e92c
a49d0a8
8549840
1be8d25
0e7e92c
a49d0a8
1be8d25
b962858
a49d0a8
 
 
7d5e8b3
 
a49d0a8
113349b
627dbc0
6e50755
d8de5a4
a49d0a8
 
 
 
 
 
fc47e93
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
122437d
a49d0a8
 
 
85817cd
7d5e8b3
 
8418f39
752a92c
99d538e
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
876dc56
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc47e93
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
 
752a92c
94283f9
 
 
 
a49d0a8
9ed9b88
 
 
 
 
b309037
ec7cc12
ca2b88e
b309037
 
 
 
 
9ed9b88
a49d0a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb31867
a49d0a8
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import gc
import spaces
from safetensors.torch import load_file
from autoregressive.models.gpt_t2i import GPT_models
from tokenizer.tokenizer_image.vq_model import VQ_models
from language.t5 import T5Embedder
import torch
import numpy as np
import PIL
from PIL import Image
from condition.canny import CannyDetector
import time
from autoregressive.models.generate import generate
from condition.midas.depth import MidasDetector

# from controlnet_aux import (
#     MidasDetector,
# )

models = {
    "canny": "checkpoints/canny_MR.safetensors",
    "depth": "checkpoints/depth_MR.safetensors",
}


def resize_image_to_16_multiple(image, condition_type='canny'):
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)
    # image = Image.open(image_path)
    width, height = image.size

    if condition_type == 'depth':  # The depth model requires a side length that is a multiple of 32
        new_width = (width + 31) // 32 * 32
        new_height = (height + 31) // 32 * 32
    else:
        new_width = (width + 15) // 16 * 16
        new_height = (height + 15) // 16 * 16

    resized_image = image.resize((new_width, new_height))
    return resized_image


class Model:

    def __init__(self):
        self.device = torch.device(
            "cuda")
        self.base_model_id = ""
        self.task_name = ""
        self.vq_model = self.load_vq()
        self.t5_model = self.load_t5()
        self.gpt_model_canny = self.load_gpt(condition_type='canny')
        # self.gpt_model_depth = self.load_gpt(condition_type='depth')
        self.get_control_canny = CannyDetector()
        # self.get_control_depth = MidasDetector('cuda')
        # self.get_control_depth =  MidasDetector.from_pretrained("lllyasviel/Annotators")

    def to(self, device):
        self.gpt_model_canny.to('cuda')
        # print(next(self.gpt_model_canny.adapter.parameters()).device)
        # print(self.gpt_model_canny.device)

    def load_vq(self):
        vq_model = VQ_models["VQ-16"](codebook_size=16384,
                                      codebook_embed_dim=8)
        # vq_model.to('cuda')
        vq_model.eval()
        checkpoint = torch.load(f"checkpoints/vq_ds16_t2i.pt",
                                map_location="cpu")
        vq_model.load_state_dict(checkpoint["model"])
        del checkpoint
        print("image tokenizer is loaded")
        return vq_model

    def load_gpt(self, condition_type='canny'):
        gpt_ckpt = models[condition_type]
        # precision = torch.bfloat16
        precision = torch.float32
        latent_size = 768 // 16
        gpt_model = GPT_models["GPT-XL"](
            block_size=latent_size**2,
            cls_token_num=120,
            model_type='t2i',
            condition_type=condition_type,
        ).to(device='cpu', dtype=precision)

        model_weight = load_file(gpt_ckpt)
        print("prev:", model_weight['adapter.model.embeddings.patch_embeddings.projection.weight'])
        gpt_model.load_state_dict(model_weight, strict=True)
        gpt_model.eval()
        print("loaded:", gpt_model.adapter.model.embeddings.patch_embeddings.projection.weight)
        print("gpt model is loaded")
        return gpt_model

    def load_t5(self):
        # precision = torch.bfloat16
        precision = torch.float32
        t5_model = T5Embedder(
            device=self.device,
            local_cache=True,
            cache_dir='checkpoints/flan-t5-xl',
            dir_or_name='flan-t5-xl',
            torch_dtype=precision,
            model_max_length=120,
        )
        return t5_model

    @torch.no_grad()
    @spaces.GPU(enable_queue=True)
    def process_canny(
        self,
        image: np.ndarray,
        prompt: str,
        cfg_scale: float,
        temperature: float,
        top_k: int,
        top_p: int,
        seed: int,
        low_threshold: int,
        high_threshold: int,
    ) -> list[PIL.Image.Image]:
        print(image)
        image = resize_image_to_16_multiple(image, 'canny')
        W, H = image.size
        print(W, H)
        # self.gpt_model_depth.to('cpu')
        self.t5_model.model.to('cuda').to(torch.bfloat16)
        self.gpt_model_canny.to('cuda').to(torch.bfloat16)
        self.vq_model.to('cuda')
        # print("after cuda", self.gpt_model_canny.adapter.model.embeddings.patch_embeddings.projection.weight)

        condition_img = self.get_control_canny(np.array(image), low_threshold,
                                               high_threshold)
        condition_img = torch.from_numpy(condition_img[None, None,
                                                       ...]).repeat(
                                                           2, 3, 1, 1)
        condition_img = condition_img.to(self.device)
        condition_img = 2 * (condition_img / 255 - 0.5)
        prompts = [prompt] * 2
        caption_embs, emb_masks = self.t5_model.get_text_embeddings(prompts)

        print(f"processing left-padding...")
        new_emb_masks = torch.flip(emb_masks, dims=[-1])
        new_caption_embs = []
        for idx, (caption_emb,
                  emb_mask) in enumerate(zip(caption_embs, emb_masks)):
            valid_num = int(emb_mask.sum().item())
            print(f'  prompt {idx} token len: {valid_num}')
            new_caption_emb = torch.cat(
                [caption_emb[valid_num:], caption_emb[:valid_num]])
            new_caption_embs.append(new_caption_emb)
        new_caption_embs = torch.stack(new_caption_embs)
        c_indices = new_caption_embs * new_emb_masks[:, :, None]
        c_emb_masks = new_emb_masks
        qzshape = [len(c_indices), 8, H // 16, W // 16]
        t1 = time.time()
        print(caption_embs.device)
        index_sample = generate(
            self.gpt_model_canny,
            c_indices,
            (H // 16) * (W // 16),
            c_emb_masks,
            condition=condition_img,
            cfg_scale=cfg_scale,
            temperature=temperature,
            top_k=top_k,
            top_p=top_p,
            sample_logits=True,
        )
        sampling_time = time.time() - t1
        print(f"Full sampling takes about {sampling_time:.2f} seconds.")

        t2 = time.time()
        print(index_sample.shape)
        samples = self.vq_model.decode_code(
            index_sample, qzshape)  # output value is between [-1, 1]
        decoder_time = time.time() - t2
        print(f"decoder takes about {decoder_time:.2f} seconds.")

        samples = torch.cat((condition_img[0:1], samples), dim=0)
        samples = 255 * (samples * 0.5 + 0.5)
        samples = [image] + [
            Image.fromarray(
                sample.permute(1, 2, 0).cpu().detach().numpy().clip(
                    0, 255).astype(np.uint8)) for sample in samples
        ]
        del condition_img
        torch.cuda.empty_cache()
        return samples

    @torch.no_grad()
    @spaces.GPU(enable_queue=True)
    def process_depth(
        self,
        image: np.ndarray,
        prompt: str,
        cfg_scale: float,
        temperature: float,
        top_k: int,
        top_p: int,
        seed: int,
    ) -> list[PIL.Image.Image]:
        image = resize_image_to_16_multiple(image, 'depth')
        W, H = image.size
        print(W, H)
        self.gpt_model_canny.to('cpu')
        self.t5_model.model.to(self.device)
        self.gpt_model_depth.to(self.device)
        self.get_control_depth.model.to(self.device)
        self.vq_model.to(self.device)
        image_tensor = torch.from_numpy(np.array(image)).to(self.device)
        # condition_img = torch.from_numpy(
        #     self.get_control_depth(image_tensor)).unsqueeze(0)
        # condition_img = condition_img.unsqueeze(0).repeat(2, 3, 1, 1)
        # condition_img = condition_img.to(self.device)
        # condition_img = 2 * (condition_img / 255 - 0.5)
        condition_img = 2 * (image_tensor / 255 - 0.5)
        print(condition_img.shape)
        condition_img = condition_img.permute(2,0,1).unsqueeze(0).repeat(2, 1, 1, 1)
        # control_image = self.get_control_depth(
        #         image=image,
        #         image_resolution=512,
        #         detect_resolution=512,
        #     )
        
        prompts = [prompt] * 2
        caption_embs, emb_masks = self.t5_model.get_text_embeddings(prompts)

        print(f"processing left-padding...")
        new_emb_masks = torch.flip(emb_masks, dims=[-1])
        new_caption_embs = []
        for idx, (caption_emb,
                  emb_mask) in enumerate(zip(caption_embs, emb_masks)):
            valid_num = int(emb_mask.sum().item())
            print(f'  prompt {idx} token len: {valid_num}')
            new_caption_emb = torch.cat(
                [caption_emb[valid_num:], caption_emb[:valid_num]])
            new_caption_embs.append(new_caption_emb)
        new_caption_embs = torch.stack(new_caption_embs)

        c_indices = new_caption_embs * new_emb_masks[:, :, None]
        c_emb_masks = new_emb_masks
        qzshape = [len(c_indices), 8, H // 16, W // 16]
        t1 = time.time()
        index_sample = generate(
            self.gpt_model_depth,
            c_indices,
            (H // 16) * (W // 16),
            c_emb_masks,
            condition=condition_img,
            cfg_scale=cfg_scale,
            temperature=temperature,
            top_k=top_k,
            top_p=top_p,
            sample_logits=True,
        )
        sampling_time = time.time() - t1
        print(f"Full sampling takes about {sampling_time:.2f} seconds.")

        t2 = time.time()
        print(index_sample.shape)
        samples = self.vq_model.decode_code(index_sample, qzshape)
        decoder_time = time.time() - t2
        print(f"decoder takes about {decoder_time:.2f} seconds.")
        condition_img = condition_img.cpu()
        samples = samples.cpu()
        samples = torch.cat((condition_img[0:1], samples), dim=0)
        samples = 255 * (samples * 0.5 + 0.5)
        samples = [image] + [
            Image.fromarray(
                sample.permute(1, 2, 0).cpu().detach().numpy().clip(0, 255).astype(np.uint8))
            for sample in samples
        ]
        del image_tensor
        del condition_img
        torch.cuda.empty_cache()
        return samples