Professional Noob commited on
Commit
c08afc1
·
verified ·
1 Parent(s): 62bf95e

Update qwenimage/pipeline_qwenimage_edit_plus.py

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