comdoleger commited on
Commit
34c1a0f
·
verified ·
1 Parent(s): 1ef8369

Upload extensions_built_in/diffusion_models/qwen_image/qwen_image_edit.py with huggingface_hub

Browse files
extensions_built_in/diffusion_models/qwen_image/qwen_image_edit.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from .qwen_image import QwenImageModel
4
+ import os
5
+ from typing import TYPE_CHECKING, List, Optional
6
+ import yaml
7
+ from toolkit import train_tools
8
+ from toolkit.config_modules import GenerateImageConfig, ModelConfig
9
+ from PIL import Image
10
+ from toolkit.models.base_model import BaseModel
11
+ from toolkit.basic import flush
12
+ from toolkit.prompt_utils import PromptEmbeds
13
+ from toolkit.samplers.custom_flowmatch_sampler import (
14
+ CustomFlowMatchEulerDiscreteScheduler,
15
+ )
16
+ from toolkit.accelerator import get_accelerator, unwrap_model
17
+ from optimum.quanto import freeze, QTensor
18
+ from toolkit.util.quantize import quantize, get_qtype, quantize_model
19
+ import torch.nn.functional as F
20
+
21
+ from diffusers import (
22
+ QwenImagePipeline,
23
+ QwenImageTransformer2DModel,
24
+ AutoencoderKLQwenImage,
25
+ )
26
+ from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer
27
+ from tqdm import tqdm
28
+
29
+ if TYPE_CHECKING:
30
+ from toolkit.data_transfer_object.data_loader import DataLoaderBatchDTO
31
+
32
+ try:
33
+ from diffusers import QwenImageEditPipeline
34
+ except ImportError:
35
+ raise ImportError(
36
+ "QwenImageEditPipeline not found. Update diffusers to the latest version by doing pip uninstall diffusers and then pip install -r requirements.txt"
37
+ )
38
+
39
+
40
+ class QwenImageEditModel(QwenImageModel):
41
+ arch = "qwen_image_edit"
42
+ _qwen_image_keep_visual = True
43
+ _qwen_pipeline = QwenImageEditPipeline
44
+
45
+ def __init__(
46
+ self,
47
+ device,
48
+ model_config: ModelConfig,
49
+ dtype="bf16",
50
+ custom_pipeline=None,
51
+ noise_scheduler=None,
52
+ **kwargs,
53
+ ):
54
+ super().__init__(
55
+ device, model_config, dtype, custom_pipeline, noise_scheduler, **kwargs
56
+ )
57
+ self.is_flow_matching = True
58
+ self.is_transformer = True
59
+ self.target_lora_modules = ["QwenImageTransformer2DModel"]
60
+
61
+ # set true for models that encode control image into text embeddings
62
+ self.encode_control_in_text_embeddings = True
63
+
64
+ def load_model(self):
65
+ super().load_model()
66
+
67
+ def get_generation_pipeline(self):
68
+ scheduler = QwenImageModel.get_train_scheduler()
69
+
70
+ pipeline: QwenImageEditPipeline = QwenImageEditPipeline(
71
+ scheduler=scheduler,
72
+ text_encoder=unwrap_model(self.text_encoder[0]),
73
+ tokenizer=self.tokenizer[0],
74
+ processor=self.processor,
75
+ vae=unwrap_model(self.vae),
76
+ transformer=unwrap_model(self.transformer),
77
+ )
78
+
79
+ pipeline = pipeline.to(self.device_torch)
80
+
81
+ return pipeline
82
+
83
+ def generate_single_image(
84
+ self,
85
+ pipeline: QwenImageEditPipeline,
86
+ gen_config: GenerateImageConfig,
87
+ conditional_embeds: PromptEmbeds,
88
+ unconditional_embeds: PromptEmbeds,
89
+ generator: torch.Generator,
90
+ extra: dict,
91
+ ):
92
+ self.model.to(self.device_torch, dtype=self.torch_dtype)
93
+ sc = self.get_bucket_divisibility()
94
+ gen_config.width = int(gen_config.width // sc * sc)
95
+ gen_config.height = int(gen_config.height // sc * sc)
96
+
97
+ control_img = None
98
+ if gen_config.ctrl_img is not None:
99
+ control_img = Image.open(gen_config.ctrl_img)
100
+ control_img = control_img.convert("RGB")
101
+ # resize to width and height
102
+ if control_img.size != (gen_config.width, gen_config.height):
103
+ control_img = control_img.resize(
104
+ (gen_config.width, gen_config.height), Image.BILINEAR
105
+ )
106
+
107
+ # flush for low vram if we are doing that
108
+ flush_between_steps = self.model_config.low_vram
109
+
110
+ # Fix a bug in diffusers/torch
111
+ def callback_on_step_end(pipe, i, t, callback_kwargs):
112
+ if flush_between_steps:
113
+ flush()
114
+ latents = callback_kwargs["latents"]
115
+
116
+ return {"latents": latents}
117
+
118
+ img = pipeline(
119
+ image=control_img,
120
+ prompt_embeds=conditional_embeds.text_embeds,
121
+ prompt_embeds_mask=conditional_embeds.attention_mask.to(
122
+ self.device_torch, dtype=torch.int64
123
+ ),
124
+ negative_prompt_embeds=unconditional_embeds.text_embeds,
125
+ negative_prompt_embeds_mask=unconditional_embeds.attention_mask.to(
126
+ self.device_torch, dtype=torch.int64
127
+ ),
128
+ height=gen_config.height,
129
+ width=gen_config.width,
130
+ num_inference_steps=gen_config.num_inference_steps,
131
+ true_cfg_scale=gen_config.guidance_scale,
132
+ latents=gen_config.latents,
133
+ generator=generator,
134
+ callback_on_step_end=callback_on_step_end,
135
+ **extra,
136
+ ).images[0]
137
+ return img
138
+
139
+ def condition_noisy_latents(
140
+ self, latents: torch.Tensor, batch: "DataLoaderBatchDTO"
141
+ ):
142
+ with torch.no_grad():
143
+ control_tensor = batch.control_tensor
144
+ if control_tensor is not None:
145
+ self.vae.to(self.device_torch)
146
+ # we are not packed here, so we just need to pass them so we can pack them later
147
+ control_tensor = control_tensor * 2 - 1
148
+ control_tensor = control_tensor.to(
149
+ self.vae_device_torch, dtype=self.torch_dtype
150
+ )
151
+
152
+ # if it is not the size of batch.tensor, (bs,ch,h,w) then we need to resize it
153
+ if batch.tensor is not None:
154
+ target_h, target_w = batch.tensor.shape[2], batch.tensor.shape[3]
155
+ else:
156
+ # When caching latents, batch.tensor is None. We get the size from the file_items instead.
157
+ target_h = batch.file_items[0].crop_height
158
+ target_w = batch.file_items[0].crop_width
159
+
160
+ if (
161
+ control_tensor.shape[2] != target_h
162
+ or control_tensor.shape[3] != target_w
163
+ ):
164
+ control_tensor = F.interpolate(
165
+ control_tensor, size=(target_h, target_w), mode="bilinear"
166
+ )
167
+
168
+ control_latent = self.encode_images(control_tensor).to(
169
+ latents.device, latents.dtype
170
+ )
171
+ latents = torch.cat((latents, control_latent), dim=1)
172
+
173
+ return latents.detach()
174
+
175
+ def get_prompt_embeds(self, prompt: str, control_images=None) -> PromptEmbeds:
176
+ if self.pipeline.text_encoder.device != self.device_torch:
177
+ self.pipeline.text_encoder.to(self.device_torch)
178
+
179
+ if control_images is not None:
180
+ # control images are 0 - 1 scale, shape (bs, ch, height, width)
181
+ # images are always run through at 1MP, based on diffusers inference code.
182
+ target_area = 1024 * 1024
183
+ ratio = control_images.shape[2] / control_images.shape[3]
184
+ width = math.sqrt(target_area * ratio)
185
+ height = width / ratio
186
+
187
+ width = round(width / 32) * 32
188
+ height = round(height / 32) * 32
189
+
190
+ control_images = F.interpolate(
191
+ control_images, size=(height, width), mode="bilinear"
192
+ )
193
+
194
+ prompt_embeds, prompt_embeds_mask = self.pipeline.encode_prompt(
195
+ prompt,
196
+ image=control_images,
197
+ device=self.device_torch,
198
+ num_images_per_prompt=1,
199
+ )
200
+ pe = PromptEmbeds(prompt_embeds)
201
+ pe.attention_mask = prompt_embeds_mask
202
+ return pe
203
+
204
+ def get_noise_prediction(
205
+ self,
206
+ latent_model_input: torch.Tensor,
207
+ timestep: torch.Tensor, # 0 to 1000 scale
208
+ text_embeddings: PromptEmbeds,
209
+ **kwargs,
210
+ ):
211
+ # control is stacked on channels, move it to the batch dimension for packing
212
+ latent_model_input, control = torch.chunk(latent_model_input, 2, 1)
213
+
214
+ batch_size, num_channels_latents, height, width = latent_model_input.shape
215
+ (
216
+ control_batch_size,
217
+ control_num_channels_latents,
218
+ control_height,
219
+ control_width,
220
+ ) = control.shape
221
+
222
+ # pack image tokens
223
+ latent_model_input = latent_model_input.view(
224
+ batch_size, num_channels_latents, height // 2, 2, width // 2, 2
225
+ )
226
+ latent_model_input = latent_model_input.permute(0, 2, 4, 1, 3, 5)
227
+ latent_model_input = latent_model_input.reshape(
228
+ batch_size, (height // 2) * (width // 2), num_channels_latents * 4
229
+ )
230
+
231
+ # pack control
232
+ control = control.view(
233
+ batch_size, num_channels_latents, height // 2, 2, width // 2, 2
234
+ )
235
+ control = control.permute(0, 2, 4, 1, 3, 5)
236
+ control = control.reshape(
237
+ batch_size, (height // 2) * (width // 2), num_channels_latents * 4
238
+ )
239
+
240
+ img_h2, img_w2 = height // 2, width // 2
241
+ control_img_h2, control_img_w2 = control_height // 2, control_width // 2
242
+
243
+ img_shapes = [[(1, img_h2, img_w2), (1, control_img_h2, control_img_w2)]] * batch_size
244
+
245
+ latents = latent_model_input
246
+ latent_model_input = torch.cat([latent_model_input, control], dim=1)
247
+ batch_size = latent_model_input.shape[0]
248
+
249
+ prompt_embeds_mask = text_embeddings.attention_mask.to(
250
+ self.device_torch, dtype=torch.int64
251
+ )
252
+ txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist()
253
+ enc_hs = text_embeddings.text_embeds.to(self.device_torch, self.torch_dtype)
254
+ prompt_embeds_mask = text_embeddings.attention_mask.to(self.device_torch, dtype=torch.int64)
255
+
256
+ noise_pred = self.transformer(
257
+ hidden_states=latent_model_input.to(self.device_torch, self.torch_dtype),
258
+ timestep=timestep / 1000,
259
+ guidance=None,
260
+ encoder_hidden_states=enc_hs,
261
+ encoder_hidden_states_mask=prompt_embeds_mask,
262
+ img_shapes=img_shapes,
263
+ txt_seq_lens=txt_seq_lens,
264
+ return_dict=False,
265
+ **kwargs,
266
+ )[0]
267
+
268
+ noise_pred = noise_pred[:, : latents.size(1)]
269
+
270
+ # unpack
271
+ noise_pred = noise_pred.view(
272
+ batch_size, height // 2, width // 2, num_channels_latents, 2, 2
273
+ )
274
+ noise_pred = noise_pred.permute(0, 3, 1, 4, 2, 5)
275
+ noise_pred = noise_pred.reshape(batch_size, num_channels_latents, height, width)
276
+ return noise_pred