witcherderivia commited on
Commit
10e235d
·
verified ·
1 Parent(s): c645dde

Create pipeline_qwenimage_edit_plus

Browse files
Files changed (1) hide show
  1. pipeline_qwenimage_edit_plus +905 -0
pipeline_qwenimage_edit_plus ADDED
@@ -0,0 +1,905 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Qwen-Image Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import math
17
+ from typing import Any, Callable
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer, Qwen2VLProcessor
22
+
23
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
24
+ from diffusers.loaders import QwenImageLoraLoaderMixin
25
+ from diffusers.models import AutoencoderKLQwenImage, QwenImageTransformer2DModel
26
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
27
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
28
+ from diffusers.utils.torch_utils import randn_tensor
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ #from diffusers.pipelines.pipeline_output import QwenImagePipelineOutput
31
+ from diffusers.pipelines.qwenimage import QwenImagePipelineOutput
32
+
33
+ '''
34
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
35
+ from ...loaders import QwenImageLoraLoaderMixin
36
+ from ...models import AutoencoderKLQwenImage, QwenImageTransformer2DModel
37
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
38
+ from ...utils import is_torch_xla_available, logging, replace_example_docstring
39
+ from ...utils.torch_utils import randn_tensor
40
+ from ..pipeline_utils import DiffusionPipeline
41
+ from .pipeline_output import QwenImagePipelineOutput
42
+ '''
43
+
44
+
45
+ if is_torch_xla_available():
46
+ import torch_xla.core.xla_model as xm
47
+
48
+ XLA_AVAILABLE = True
49
+ else:
50
+ XLA_AVAILABLE = False
51
+
52
+
53
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
54
+
55
+ EXAMPLE_DOC_STRING = """
56
+ Examples:
57
+ ```py
58
+ >>> import torch
59
+ >>> from PIL import Image
60
+ >>> from diffusers import QwenImageEditPlusPipeline
61
+ >>> from diffusers.utils import load_image
62
+
63
+ >>> pipe = QwenImageEditPlusPipeline.from_pretrained("Qwen/Qwen-Image-Edit-2509", torch_dtype=torch.bfloat16)
64
+ >>> pipe.to("cuda")
65
+ >>> image = load_image(
66
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
67
+ ... ).convert("RGB")
68
+ >>> prompt = (
69
+ ... "Make Pikachu hold a sign that says 'Qwen Edit is awesome', yarn art style, detailed, vibrant colors"
70
+ ... )
71
+ >>> # Depending on the variant being used, the pipeline call will slightly vary.
72
+ >>> # Refer to the pipeline documentation for more details.
73
+ >>> image = pipe(image, prompt, num_inference_steps=50).images[0]
74
+ >>> image.save("qwenimage_edit_plus.png")
75
+ ```
76
+ """
77
+
78
+ CONDITION_IMAGE_SIZE = 384 * 384
79
+ VAE_IMAGE_SIZE = 1024 * 1024
80
+
81
+
82
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.calculate_shift
83
+ def calculate_shift(
84
+ image_seq_len,
85
+ base_seq_len: int = 256,
86
+ max_seq_len: int = 4096,
87
+ base_shift: float = 0.5,
88
+ max_shift: float = 1.15,
89
+ ):
90
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
91
+ b = base_shift - m * base_seq_len
92
+ mu = image_seq_len * m + b
93
+ return mu
94
+
95
+
96
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
97
+ def retrieve_timesteps(
98
+ scheduler,
99
+ num_inference_steps: int | None = None,
100
+ device: str | torch.device | None = None,
101
+ timesteps: list[int] | None = None,
102
+ sigmas: list[float] | None = None,
103
+ **kwargs,
104
+ ):
105
+ r"""
106
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
107
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
108
+
109
+ Args:
110
+ scheduler (`SchedulerMixin`):
111
+ The scheduler to get timesteps from.
112
+ num_inference_steps (`int`):
113
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
114
+ must be `None`.
115
+ device (`str` or `torch.device`, *optional*):
116
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
117
+ timesteps (`list[int]`, *optional*):
118
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
119
+ `num_inference_steps` and `sigmas` must be `None`.
120
+ sigmas (`list[float]`, *optional*):
121
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
122
+ `num_inference_steps` and `timesteps` must be `None`.
123
+
124
+ Returns:
125
+ `tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
126
+ second element is the number of inference steps.
127
+ """
128
+ if timesteps is not None and sigmas is not None:
129
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
130
+ if timesteps is not None:
131
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
132
+ if not accepts_timesteps:
133
+ raise ValueError(
134
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
135
+ f" timestep schedules. Please check whether you are using the correct scheduler."
136
+ )
137
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
138
+ timesteps = scheduler.timesteps
139
+ num_inference_steps = len(timesteps)
140
+ elif sigmas is not None:
141
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
142
+ if not accept_sigmas:
143
+ raise ValueError(
144
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
145
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
146
+ )
147
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
148
+ timesteps = scheduler.timesteps
149
+ num_inference_steps = len(timesteps)
150
+ else:
151
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
152
+ timesteps = scheduler.timesteps
153
+ return timesteps, num_inference_steps
154
+
155
+
156
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
157
+ def retrieve_latents(
158
+ encoder_output: torch.Tensor, generator: torch.Generator | None = None, sample_mode: str = "sample"
159
+ ):
160
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
161
+ return encoder_output.latent_dist.sample(generator)
162
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
163
+ return encoder_output.latent_dist.mode()
164
+ elif hasattr(encoder_output, "latents"):
165
+ return encoder_output.latents
166
+ else:
167
+ raise AttributeError("Could not access latents of provided encoder_output")
168
+
169
+
170
+ def calculate_dimensions(target_area, ratio):
171
+ width = math.sqrt(target_area * ratio)
172
+ height = width / ratio
173
+
174
+ width = round(width / 32) * 32
175
+ height = round(height / 32) * 32
176
+
177
+ return width, height
178
+
179
+
180
+ class QwenImageEditPlusPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
181
+ r"""
182
+ The Qwen-Image-Edit pipeline for image editing.
183
+
184
+ Args:
185
+ transformer ([`QwenImageTransformer2DModel`]):
186
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
187
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
188
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
189
+ vae ([`AutoencoderKL`]):
190
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
191
+ text_encoder ([`Qwen2.5-VL-7B-Instruct`]):
192
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the
193
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant.
194
+ tokenizer (`QwenTokenizer`):
195
+ Tokenizer of class
196
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
197
+ """
198
+
199
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
200
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
201
+
202
+ def __init__(
203
+ self,
204
+ scheduler: FlowMatchEulerDiscreteScheduler,
205
+ vae: AutoencoderKLQwenImage,
206
+ text_encoder: Qwen2_5_VLForConditionalGeneration,
207
+ tokenizer: Qwen2Tokenizer,
208
+ processor: Qwen2VLProcessor,
209
+ transformer: QwenImageTransformer2DModel,
210
+ ):
211
+ super().__init__()
212
+
213
+ self.register_modules(
214
+ vae=vae,
215
+ text_encoder=text_encoder,
216
+ tokenizer=tokenizer,
217
+ processor=processor,
218
+ transformer=transformer,
219
+ scheduler=scheduler,
220
+ )
221
+ self.vae_scale_factor = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
222
+ self.latent_channels = self.vae.config.z_dim if getattr(self, "vae", None) else 16
223
+ # QwenImage latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
224
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
225
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
226
+ self.tokenizer_max_length = 1024
227
+
228
+ self.prompt_template_encode = "<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
229
+ self.prompt_template_encode_start_idx = 64
230
+ self.default_sample_size = 128
231
+
232
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._extract_masked_hidden
233
+ def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
234
+ bool_mask = mask.bool()
235
+ valid_lengths = bool_mask.sum(dim=1)
236
+ selected = hidden_states[bool_mask]
237
+ split_result = torch.split(selected, valid_lengths.tolist(), dim=0)
238
+
239
+ return split_result
240
+
241
+ def _get_qwen_prompt_embeds(
242
+ self,
243
+ prompt: str | list[str] = None,
244
+ image: torch.Tensor | None = None,
245
+ device: torch.device | None = None,
246
+ dtype: torch.dtype | None = None,
247
+ ):
248
+ device = device or self._execution_device
249
+ dtype = dtype or self.text_encoder.dtype
250
+
251
+ prompt = [prompt] if isinstance(prompt, str) else prompt
252
+ img_prompt_template = "Picture {}: <|vision_start|><|image_pad|><|vision_end|>"
253
+ if isinstance(image, list):
254
+ base_img_prompt = ""
255
+ for i, img in enumerate(image):
256
+ base_img_prompt += img_prompt_template.format(i + 1)
257
+ elif image is not None:
258
+ base_img_prompt = img_prompt_template.format(1)
259
+ else:
260
+ base_img_prompt = ""
261
+
262
+ template = self.prompt_template_encode
263
+
264
+ drop_idx = self.prompt_template_encode_start_idx
265
+ txt = [template.format(base_img_prompt + e) for e in prompt]
266
+
267
+ model_inputs = self.processor(
268
+ text=txt,
269
+ images=image,
270
+ padding=True,
271
+ return_tensors="pt",
272
+ ).to(device)
273
+
274
+ outputs = self.text_encoder(
275
+ input_ids=model_inputs["input_ids"],
276
+ attention_mask=model_inputs["attention_mask"],
277
+ pixel_values=model_inputs.get("pixel_values"),
278
+ image_grid_thw=model_inputs.get("image_grid_thw"),
279
+ output_hidden_states=True,
280
+ )
281
+
282
+ hidden_states = outputs.hidden_states[-1]
283
+ split_hidden_states = self._extract_masked_hidden(hidden_states, model_inputs["attention_mask"])
284
+ split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
285
+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
286
+ max_seq_len = max([e.size(0) for e in split_hidden_states])
287
+ prompt_embeds = torch.stack(
288
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
289
+ )
290
+ encoder_attention_mask = torch.stack(
291
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]
292
+ )
293
+
294
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
295
+
296
+ return prompt_embeds, encoder_attention_mask
297
+
298
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline.encode_prompt
299
+ def encode_prompt(
300
+ self,
301
+ prompt: str | list[str],
302
+ image: torch.Tensor | None = None,
303
+ device: torch.device | None = None,
304
+ num_images_per_prompt: int = 1,
305
+ prompt_embeds: torch.Tensor | None = None,
306
+ prompt_embeds_mask: torch.Tensor | None = None,
307
+ max_sequence_length: int = 1024,
308
+ ):
309
+ r"""
310
+
311
+ Args:
312
+ prompt (`str` or `list[str]`, *optional*):
313
+ prompt to be encoded
314
+ image (`torch.Tensor`, *optional*):
315
+ image to be encoded
316
+ device: (`torch.device`):
317
+ torch device
318
+ num_images_per_prompt (`int`):
319
+ number of images that should be generated per prompt
320
+ prompt_embeds (`torch.Tensor`, *optional*):
321
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
322
+ provided, text embeddings will be generated from `prompt` input argument.
323
+ """
324
+ device = device or self._execution_device
325
+
326
+ prompt = [prompt] if isinstance(prompt, str) else prompt
327
+ batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
328
+
329
+ if prompt_embeds is None:
330
+ prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image, device)
331
+
332
+ _, seq_len, _ = prompt_embeds.shape
333
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
334
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
335
+
336
+ if prompt_embeds_mask is not None:
337
+ prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1)
338
+ prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len)
339
+
340
+ if prompt_embeds_mask.all():
341
+ prompt_embeds_mask = None
342
+
343
+ return prompt_embeds, prompt_embeds_mask
344
+
345
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline.check_inputs
346
+ def check_inputs(
347
+ self,
348
+ prompt,
349
+ height,
350
+ width,
351
+ negative_prompt=None,
352
+ prompt_embeds=None,
353
+ negative_prompt_embeds=None,
354
+ prompt_embeds_mask=None,
355
+ negative_prompt_embeds_mask=None,
356
+ callback_on_step_end_tensor_inputs=None,
357
+ max_sequence_length=None,
358
+ ):
359
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
360
+ logger.warning(
361
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
362
+ )
363
+
364
+ if callback_on_step_end_tensor_inputs is not None and not all(
365
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
366
+ ):
367
+ raise ValueError(
368
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
369
+ )
370
+
371
+ if prompt is not None and prompt_embeds is not None:
372
+ raise ValueError(
373
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
374
+ " only forward one of the two."
375
+ )
376
+ elif prompt is None and prompt_embeds is None:
377
+ raise ValueError(
378
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
379
+ )
380
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
381
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
382
+
383
+ if negative_prompt is not None and negative_prompt_embeds is not None:
384
+ raise ValueError(
385
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
386
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
387
+ )
388
+
389
+ if prompt_embeds is not None and prompt_embeds_mask is None:
390
+ logger.warning(
391
+ "`prompt_embeds` is provided and `prompt_embeds_mask` is not provided, so the model will treat all"
392
+ " prompt tokens as valid. If `prompt_embeds` contains padding, you should provide the padding mask as"
393
+ " `prompt_embeds_mask`. Make sure to generate `prompt_embeds_mask` from the same text encoder that was"
394
+ " used to generate `prompt_embeds`."
395
+ )
396
+
397
+ if negative_prompt_embeds is not None and negative_prompt_embeds_mask is None:
398
+ logger.warning(
399
+ "`negative_prompt_embeds` is provided and `negative_prompt_embeds_mask` is not provided, so the model will treat all"
400
+ " negative prompt tokens as valid. If `negative_prompt_embeds` contains padding, you should provide the padding mask as"
401
+ " `negative_prompt_embeds_mask`. Make sure to generate `negative_prompt_embeds_mask` from the same text encoder that was"
402
+ " used to generate `negative_prompt_embeds`."
403
+ )
404
+
405
+ if max_sequence_length is not None and max_sequence_length > 1024:
406
+ raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
407
+
408
+ @staticmethod
409
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._pack_latents
410
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
411
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
412
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
413
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
414
+
415
+ return latents
416
+
417
+ @staticmethod
418
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._unpack_latents
419
+ def _unpack_latents(latents, height, width, vae_scale_factor):
420
+ batch_size, num_patches, channels = latents.shape
421
+
422
+ # VAE applies 8x compression on images but we must also account for packing which requires
423
+ # latent height and width to be divisible by 2.
424
+ height = 2 * (int(height) // (vae_scale_factor * 2))
425
+ width = 2 * (int(width) // (vae_scale_factor * 2))
426
+
427
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
428
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
429
+
430
+ latents = latents.reshape(batch_size, channels // (2 * 2), 1, height, width)
431
+
432
+ return latents
433
+
434
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline._encode_vae_image
435
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
436
+ if isinstance(generator, list):
437
+ image_latents = [
438
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode="argmax")
439
+ for i in range(image.shape[0])
440
+ ]
441
+ image_latents = torch.cat(image_latents, dim=0)
442
+ else:
443
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax")
444
+ latents_mean = (
445
+ torch.tensor(self.vae.config.latents_mean)
446
+ .view(1, self.latent_channels, 1, 1, 1)
447
+ .to(image_latents.device, image_latents.dtype)
448
+ )
449
+ latents_std = (
450
+ torch.tensor(self.vae.config.latents_std)
451
+ .view(1, self.latent_channels, 1, 1, 1)
452
+ .to(image_latents.device, image_latents.dtype)
453
+ )
454
+ image_latents = (image_latents - latents_mean) / latents_std
455
+
456
+ return image_latents
457
+
458
+ def prepare_latents(
459
+ self,
460
+ images,
461
+ batch_size,
462
+ num_channels_latents,
463
+ height,
464
+ width,
465
+ dtype,
466
+ device,
467
+ generator,
468
+ latents=None,
469
+ ):
470
+ # VAE applies 8x compression on images but we must also account for packing which requires
471
+ # latent height and width to be divisible by 2.
472
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
473
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
474
+
475
+ shape = (batch_size, 1, num_channels_latents, height, width)
476
+
477
+ image_latents = None
478
+ if images is not None:
479
+ if not isinstance(images, list):
480
+ images = [images]
481
+ all_image_latents = []
482
+ for image in images:
483
+ image = image.to(device=device, dtype=dtype)
484
+ if image.shape[1] != self.latent_channels:
485
+ image_latents = self._encode_vae_image(image=image, generator=generator)
486
+ else:
487
+ image_latents = image
488
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
489
+ # expand init_latents for batch_size
490
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
491
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
492
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
493
+ raise ValueError(
494
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
495
+ )
496
+ else:
497
+ image_latents = torch.cat([image_latents], dim=0)
498
+
499
+ image_latent_height, image_latent_width = image_latents.shape[3:]
500
+ image_latents = self._pack_latents(
501
+ image_latents, batch_size, num_channels_latents, image_latent_height, image_latent_width
502
+ )
503
+ all_image_latents.append(image_latents)
504
+ image_latents = torch.cat(all_image_latents, dim=1)
505
+
506
+ if isinstance(generator, list) and len(generator) != batch_size:
507
+ raise ValueError(
508
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
509
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
510
+ )
511
+ if latents is None:
512
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
513
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
514
+ else:
515
+ latents = latents.to(device=device, dtype=dtype)
516
+
517
+ return latents, image_latents
518
+
519
+ @property
520
+ def guidance_scale(self):
521
+ return self._guidance_scale
522
+
523
+ @property
524
+ def attention_kwargs(self):
525
+ return self._attention_kwargs
526
+
527
+ @property
528
+ def num_timesteps(self):
529
+ return self._num_timesteps
530
+
531
+ @property
532
+ def current_timestep(self):
533
+ return self._current_timestep
534
+
535
+ @property
536
+ def interrupt(self):
537
+ return self._interrupt
538
+
539
+ @torch.no_grad()
540
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
541
+ def __call__(
542
+ self,
543
+ image: PipelineImageInput | None = None,
544
+ prompt: str | list[str] = None,
545
+ negative_prompt: str | list[str] = None,
546
+ true_cfg_scale: float = 4.0,
547
+ height: int | None = None,
548
+ width: int | None = None,
549
+ num_inference_steps: int = 50,
550
+ sigmas: list[float] | None = None,
551
+ guidance_scale: float | None = None,
552
+ num_images_per_prompt: int = 1,
553
+ generator: torch.Generator | list[torch.Generator] | None = None,
554
+ latents: torch.Tensor | None = None,
555
+ prompt_embeds: torch.Tensor | None = None,
556
+ prompt_embeds_mask: torch.Tensor | None = None,
557
+ negative_prompt_embeds: torch.Tensor | None = None,
558
+ negative_prompt_embeds_mask: torch.Tensor | None = None,
559
+ output_type: str | None = "pil",
560
+ return_dict: bool = True,
561
+ attention_kwargs: dict[str, Any] | None = None,
562
+ callback_on_step_end: Callable[[int, int], None] | None = None,
563
+ callback_on_step_end_tensor_inputs: list[str] = ["latents"],
564
+ max_sequence_length: int = 512,
565
+ ):
566
+ r"""
567
+ Function invoked when calling the pipeline for generation.
568
+
569
+ Args:
570
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, or `list[np.ndarray]`):
571
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
572
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
573
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
574
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
575
+ latents as `image`, but if passing latents directly it is not encoded again.
576
+ prompt (`str` or `list[str]`, *optional*):
577
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
578
+ instead.
579
+ negative_prompt (`str` or `list[str]`, *optional*):
580
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
581
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
582
+ not greater than `1`).
583
+ true_cfg_scale (`float`, *optional*, defaults to 1.0):
584
+ true_cfg_scale (`float`, *optional*, defaults to 1.0): Guidance scale as defined in [Classifier-Free
585
+ Diffusion Guidance](https://huggingface.co/papers/2207.12598). `true_cfg_scale` is defined as `w` of
586
+ equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Classifier-free guidance is
587
+ enabled by setting `true_cfg_scale > 1` and a provided `negative_prompt`. Higher guidance scale
588
+ encourages to generate images that are closely linked to the text `prompt`, usually at the expense of
589
+ lower image quality.
590
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
591
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
592
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
593
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
594
+ num_inference_steps (`int`, *optional*, defaults to 50):
595
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
596
+ expense of slower inference.
597
+ sigmas (`list[float]`, *optional*):
598
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
599
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
600
+ will be used.
601
+ guidance_scale (`float`, *optional*, defaults to None):
602
+ A guidance scale value for guidance distilled models. Unlike the traditional classifier-free guidance
603
+ where the guidance scale is applied during inference through noise prediction rescaling, guidance
604
+ distilled models take the guidance scale directly as an input parameter during forward pass. Guidance
605
+ scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images
606
+ that are closely linked to the text `prompt`, usually at the expense of lower image quality. This
607
+ parameter in the pipeline is there to support future guidance-distilled models when they come up. It is
608
+ ignored when not using guidance distilled models. To enable traditional classifier-free guidance,
609
+ please pass `true_cfg_scale > 1.0` and `negative_prompt` (even an empty negative prompt like " " should
610
+ enable classifier-free guidance computations).
611
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
612
+ The number of images to generate per prompt.
613
+ generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
614
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
615
+ to make generation deterministic.
616
+ latents (`torch.Tensor`, *optional*):
617
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
618
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
619
+ tensor will be generated by sampling using the supplied random `generator`.
620
+ prompt_embeds (`torch.Tensor`, *optional*):
621
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
622
+ provided, text embeddings will be generated from `prompt` input argument.
623
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
624
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
625
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
626
+ argument.
627
+ output_type (`str`, *optional*, defaults to `"pil"`):
628
+ The output format of the generate image. Choose between
629
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
630
+ return_dict (`bool`, *optional*, defaults to `True`):
631
+ Whether or not to return a [`~pipelines.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple.
632
+ attention_kwargs (`dict`, *optional*):
633
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
634
+ `self.processor` in
635
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
636
+ callback_on_step_end (`Callable`, *optional*):
637
+ A function that calls at the end of each denoising steps during the inference. The function is called
638
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
639
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
640
+ `callback_on_step_end_tensor_inputs`.
641
+ callback_on_step_end_tensor_inputs (`list`, *optional*):
642
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
643
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
644
+ `._callback_tensor_inputs` attribute of your pipeline class.
645
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
646
+
647
+ Examples:
648
+
649
+ Returns:
650
+ [`~pipelines.qwenimage.QwenImagePipelineOutput`] or `tuple`:
651
+ [`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
652
+ returning a tuple, the first element is a list with the generated images.
653
+ """
654
+ image_size = image[-1].size if isinstance(image, list) else image.size
655
+ calculated_width, calculated_height = calculate_dimensions(1024 * 1024, image_size[0] / image_size[1])
656
+ height = height or calculated_height
657
+ width = width or calculated_width
658
+
659
+ multiple_of = self.vae_scale_factor * 2
660
+ width = width // multiple_of * multiple_of
661
+ height = height // multiple_of * multiple_of
662
+
663
+ # 1. Check inputs. Raise error if not correct
664
+ self.check_inputs(
665
+ prompt,
666
+ height,
667
+ width,
668
+ negative_prompt=negative_prompt,
669
+ prompt_embeds=prompt_embeds,
670
+ negative_prompt_embeds=negative_prompt_embeds,
671
+ prompt_embeds_mask=prompt_embeds_mask,
672
+ negative_prompt_embeds_mask=negative_prompt_embeds_mask,
673
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
674
+ max_sequence_length=max_sequence_length,
675
+ )
676
+
677
+ self._guidance_scale = guidance_scale
678
+ self._attention_kwargs = attention_kwargs
679
+ self._current_timestep = None
680
+ self._interrupt = False
681
+
682
+ # 2. Define call parameters
683
+ if prompt is not None and isinstance(prompt, str):
684
+ batch_size = 1
685
+ elif prompt is not None and isinstance(prompt, list):
686
+ batch_size = len(prompt)
687
+ else:
688
+ batch_size = prompt_embeds.shape[0]
689
+
690
+ # QwenImageEditPlusPipeline does not currently support batch_size > 1
691
+ if batch_size > 1:
692
+ raise ValueError(
693
+ f"QwenImageEditPlusPipeline currently only supports batch_size=1, but received batch_size={batch_size}. "
694
+ "Please process prompts one at a time."
695
+ )
696
+
697
+ device = self._execution_device
698
+ # 3. Preprocess image
699
+ if image is not None and not (isinstance(image, torch.Tensor) and image.size(1) == self.latent_channels):
700
+ if not isinstance(image, list):
701
+ image = [image]
702
+ condition_image_sizes = []
703
+ condition_images = []
704
+ vae_image_sizes = []
705
+ vae_images = []
706
+ for img in image:
707
+ image_width, image_height = img.size
708
+ condition_width, condition_height = calculate_dimensions(
709
+ CONDITION_IMAGE_SIZE, image_width / image_height
710
+ )
711
+ vae_width, vae_height = img.size#calculate_dimensions(VAE_IMAGE_SIZE, image_width / image_height)
712
+ condition_image_sizes.append((condition_width, condition_height))
713
+ vae_image_sizes.append((vae_width, vae_height))
714
+ condition_images.append(self.image_processor.resize(img, condition_height, condition_width))
715
+ vae_images.append(self.image_processor.preprocess(img, vae_height, vae_width).unsqueeze(2))
716
+
717
+ has_neg_prompt = negative_prompt is not None or negative_prompt_embeds is not None
718
+
719
+ if true_cfg_scale > 1 and not has_neg_prompt:
720
+ logger.warning(
721
+ f"true_cfg_scale is passed as {true_cfg_scale}, but classifier-free guidance is not enabled since no negative_prompt is provided."
722
+ )
723
+ elif true_cfg_scale <= 1 and has_neg_prompt:
724
+ logger.warning(
725
+ " negative_prompt is passed but classifier-free guidance is not enabled since true_cfg_scale <= 1"
726
+ )
727
+
728
+ do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
729
+ prompt_embeds, prompt_embeds_mask = self.encode_prompt(
730
+ image=condition_images,
731
+ prompt=prompt,
732
+ prompt_embeds=prompt_embeds,
733
+ prompt_embeds_mask=prompt_embeds_mask,
734
+ device=device,
735
+ num_images_per_prompt=num_images_per_prompt,
736
+ max_sequence_length=max_sequence_length,
737
+ )
738
+ if do_true_cfg:
739
+ negative_prompt_embeds, negative_prompt_embeds_mask = self.encode_prompt(
740
+ image=condition_images,
741
+ prompt=negative_prompt,
742
+ prompt_embeds=negative_prompt_embeds,
743
+ prompt_embeds_mask=negative_prompt_embeds_mask,
744
+ device=device,
745
+ num_images_per_prompt=num_images_per_prompt,
746
+ max_sequence_length=max_sequence_length,
747
+ )
748
+
749
+ # 4. Prepare latent variables
750
+ num_channels_latents = self.transformer.config.in_channels // 4
751
+ latents, image_latents = self.prepare_latents(
752
+ vae_images,
753
+ batch_size * num_images_per_prompt,
754
+ num_channels_latents,
755
+ height,
756
+ width,
757
+ prompt_embeds.dtype,
758
+ device,
759
+ generator,
760
+ latents,
761
+ )
762
+ img_shapes = [
763
+ [
764
+ (1, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2),
765
+ *[
766
+ (1, vae_height // self.vae_scale_factor // 2, vae_width // self.vae_scale_factor // 2)
767
+ for vae_width, vae_height in vae_image_sizes
768
+ ],
769
+ ]
770
+ ] * batch_size
771
+
772
+ # 5. Prepare timesteps
773
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
774
+ image_seq_len = latents.shape[1]
775
+ mu = calculate_shift(
776
+ image_seq_len,
777
+ self.scheduler.config.get("base_image_seq_len", 256),
778
+ self.scheduler.config.get("max_image_seq_len", 4096),
779
+ self.scheduler.config.get("base_shift", 0.5),
780
+ self.scheduler.config.get("max_shift", 1.15),
781
+ )
782
+ timesteps, num_inference_steps = retrieve_timesteps(
783
+ self.scheduler,
784
+ num_inference_steps,
785
+ device,
786
+ sigmas=sigmas,
787
+ mu=mu,
788
+ )
789
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
790
+ self._num_timesteps = len(timesteps)
791
+
792
+ # handle guidance
793
+ if self.transformer.config.guidance_embeds and guidance_scale is None:
794
+ raise ValueError("guidance_scale is required for guidance-distilled model.")
795
+ elif self.transformer.config.guidance_embeds:
796
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
797
+ guidance = guidance.expand(latents.shape[0])
798
+ elif not self.transformer.config.guidance_embeds and guidance_scale is not None:
799
+ logger.warning(
800
+ f"guidance_scale is passed as {guidance_scale}, but ignored since the model is not guidance-distilled."
801
+ )
802
+ guidance = None
803
+ elif not self.transformer.config.guidance_embeds and guidance_scale is None:
804
+ guidance = None
805
+
806
+ if self.attention_kwargs is None:
807
+ self._attention_kwargs = {}
808
+
809
+ # 6. Denoising loop
810
+ self.scheduler.set_begin_index(0)
811
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
812
+ for i, t in enumerate(timesteps):
813
+ if self.interrupt:
814
+ continue
815
+
816
+ self._current_timestep = t
817
+
818
+ latent_model_input = latents
819
+ if image_latents is not None:
820
+ latent_model_input = torch.cat([latents, image_latents], dim=1)
821
+
822
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
823
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
824
+ with self.transformer.cache_context("cond"):
825
+ noise_pred = self.transformer(
826
+ hidden_states=latent_model_input,
827
+ timestep=timestep / 1000,
828
+ guidance=guidance,
829
+ encoder_hidden_states_mask=prompt_embeds_mask,
830
+ encoder_hidden_states=prompt_embeds,
831
+ img_shapes=img_shapes,
832
+ attention_kwargs=self.attention_kwargs,
833
+ return_dict=False,
834
+ )[0]
835
+ noise_pred = noise_pred[:, : latents.size(1)]
836
+
837
+ if do_true_cfg:
838
+ with self.transformer.cache_context("uncond"):
839
+ neg_noise_pred = self.transformer(
840
+ hidden_states=latent_model_input,
841
+ timestep=timestep / 1000,
842
+ guidance=guidance,
843
+ encoder_hidden_states_mask=negative_prompt_embeds_mask,
844
+ encoder_hidden_states=negative_prompt_embeds,
845
+ img_shapes=img_shapes,
846
+ attention_kwargs=self.attention_kwargs,
847
+ return_dict=False,
848
+ )[0]
849
+ neg_noise_pred = neg_noise_pred[:, : latents.size(1)]
850
+ comb_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
851
+
852
+ cond_norm = torch.norm(noise_pred, dim=-1, keepdim=True)
853
+ noise_norm = torch.norm(comb_pred, dim=-1, keepdim=True)
854
+ noise_pred = comb_pred * (cond_norm / noise_norm)
855
+
856
+ # compute the previous noisy sample x_t -> x_t-1
857
+ latents_dtype = latents.dtype
858
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
859
+
860
+ if latents.dtype != latents_dtype:
861
+ if torch.backends.mps.is_available():
862
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
863
+ latents = latents.to(latents_dtype)
864
+
865
+ if callback_on_step_end is not None:
866
+ callback_kwargs = {}
867
+ for k in callback_on_step_end_tensor_inputs:
868
+ callback_kwargs[k] = locals()[k]
869
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
870
+
871
+ latents = callback_outputs.pop("latents", latents)
872
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
873
+
874
+ # call the callback, if provided
875
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
876
+ progress_bar.update()
877
+
878
+ if XLA_AVAILABLE:
879
+ xm.mark_step()
880
+
881
+ self._current_timestep = None
882
+ if output_type == "latent":
883
+ image = latents
884
+ else:
885
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
886
+ latents = latents.to(self.vae.dtype)
887
+ latents_mean = (
888
+ torch.tensor(self.vae.config.latents_mean)
889
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
890
+ .to(latents.device, latents.dtype)
891
+ )
892
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
893
+ latents.device, latents.dtype
894
+ )
895
+ latents = latents / latents_std + latents_mean
896
+ image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
897
+ image = self.image_processor.postprocess(image, output_type=output_type)
898
+
899
+ # Offload all models
900
+ self.maybe_free_model_hooks()
901
+
902
+ if not return_dict:
903
+ return (image,)
904
+
905
+ return QwenImagePipelineOutput(images=image)