diffusers 0.34.0__py3-none-any.whl → 0.35.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. diffusers/__init__.py +98 -1
  2. diffusers/callbacks.py +35 -0
  3. diffusers/commands/custom_blocks.py +134 -0
  4. diffusers/commands/diffusers_cli.py +2 -0
  5. diffusers/commands/fp16_safetensors.py +1 -1
  6. diffusers/configuration_utils.py +11 -2
  7. diffusers/dependency_versions_table.py +3 -3
  8. diffusers/guiders/__init__.py +41 -0
  9. diffusers/guiders/adaptive_projected_guidance.py +188 -0
  10. diffusers/guiders/auto_guidance.py +190 -0
  11. diffusers/guiders/classifier_free_guidance.py +141 -0
  12. diffusers/guiders/classifier_free_zero_star_guidance.py +152 -0
  13. diffusers/guiders/frequency_decoupled_guidance.py +327 -0
  14. diffusers/guiders/guider_utils.py +309 -0
  15. diffusers/guiders/perturbed_attention_guidance.py +271 -0
  16. diffusers/guiders/skip_layer_guidance.py +262 -0
  17. diffusers/guiders/smoothed_energy_guidance.py +251 -0
  18. diffusers/guiders/tangential_classifier_free_guidance.py +143 -0
  19. diffusers/hooks/__init__.py +17 -0
  20. diffusers/hooks/_common.py +56 -0
  21. diffusers/hooks/_helpers.py +293 -0
  22. diffusers/hooks/faster_cache.py +7 -6
  23. diffusers/hooks/first_block_cache.py +259 -0
  24. diffusers/hooks/group_offloading.py +292 -286
  25. diffusers/hooks/hooks.py +56 -1
  26. diffusers/hooks/layer_skip.py +263 -0
  27. diffusers/hooks/layerwise_casting.py +2 -7
  28. diffusers/hooks/pyramid_attention_broadcast.py +14 -11
  29. diffusers/hooks/smoothed_energy_guidance_utils.py +167 -0
  30. diffusers/hooks/utils.py +43 -0
  31. diffusers/loaders/__init__.py +6 -0
  32. diffusers/loaders/ip_adapter.py +255 -4
  33. diffusers/loaders/lora_base.py +63 -30
  34. diffusers/loaders/lora_conversion_utils.py +434 -53
  35. diffusers/loaders/lora_pipeline.py +834 -37
  36. diffusers/loaders/peft.py +28 -5
  37. diffusers/loaders/single_file_model.py +44 -11
  38. diffusers/loaders/single_file_utils.py +170 -2
  39. diffusers/loaders/transformer_flux.py +9 -10
  40. diffusers/loaders/transformer_sd3.py +6 -1
  41. diffusers/loaders/unet.py +22 -5
  42. diffusers/loaders/unet_loader_utils.py +5 -2
  43. diffusers/models/__init__.py +8 -0
  44. diffusers/models/attention.py +484 -3
  45. diffusers/models/attention_dispatch.py +1218 -0
  46. diffusers/models/attention_processor.py +105 -663
  47. diffusers/models/auto_model.py +2 -2
  48. diffusers/models/autoencoders/__init__.py +1 -0
  49. diffusers/models/autoencoders/autoencoder_dc.py +14 -1
  50. diffusers/models/autoencoders/autoencoder_kl.py +1 -1
  51. diffusers/models/autoencoders/autoencoder_kl_cosmos.py +3 -1
  52. diffusers/models/autoencoders/autoencoder_kl_qwenimage.py +1070 -0
  53. diffusers/models/autoencoders/autoencoder_kl_wan.py +370 -40
  54. diffusers/models/cache_utils.py +31 -9
  55. diffusers/models/controlnets/controlnet_flux.py +5 -5
  56. diffusers/models/controlnets/controlnet_union.py +4 -4
  57. diffusers/models/embeddings.py +26 -34
  58. diffusers/models/model_loading_utils.py +233 -1
  59. diffusers/models/modeling_flax_utils.py +1 -2
  60. diffusers/models/modeling_utils.py +159 -94
  61. diffusers/models/transformers/__init__.py +2 -0
  62. diffusers/models/transformers/transformer_chroma.py +16 -117
  63. diffusers/models/transformers/transformer_cogview4.py +36 -2
  64. diffusers/models/transformers/transformer_cosmos.py +11 -4
  65. diffusers/models/transformers/transformer_flux.py +372 -132
  66. diffusers/models/transformers/transformer_hunyuan_video.py +6 -0
  67. diffusers/models/transformers/transformer_ltx.py +104 -23
  68. diffusers/models/transformers/transformer_qwenimage.py +645 -0
  69. diffusers/models/transformers/transformer_skyreels_v2.py +607 -0
  70. diffusers/models/transformers/transformer_wan.py +298 -85
  71. diffusers/models/transformers/transformer_wan_vace.py +15 -21
  72. diffusers/models/unets/unet_2d_condition.py +2 -1
  73. diffusers/modular_pipelines/__init__.py +83 -0
  74. diffusers/modular_pipelines/components_manager.py +1068 -0
  75. diffusers/modular_pipelines/flux/__init__.py +66 -0
  76. diffusers/modular_pipelines/flux/before_denoise.py +689 -0
  77. diffusers/modular_pipelines/flux/decoders.py +109 -0
  78. diffusers/modular_pipelines/flux/denoise.py +227 -0
  79. diffusers/modular_pipelines/flux/encoders.py +412 -0
  80. diffusers/modular_pipelines/flux/modular_blocks.py +181 -0
  81. diffusers/modular_pipelines/flux/modular_pipeline.py +59 -0
  82. diffusers/modular_pipelines/modular_pipeline.py +2446 -0
  83. diffusers/modular_pipelines/modular_pipeline_utils.py +672 -0
  84. diffusers/modular_pipelines/node_utils.py +665 -0
  85. diffusers/modular_pipelines/stable_diffusion_xl/__init__.py +77 -0
  86. diffusers/modular_pipelines/stable_diffusion_xl/before_denoise.py +1874 -0
  87. diffusers/modular_pipelines/stable_diffusion_xl/decoders.py +208 -0
  88. diffusers/modular_pipelines/stable_diffusion_xl/denoise.py +771 -0
  89. diffusers/modular_pipelines/stable_diffusion_xl/encoders.py +887 -0
  90. diffusers/modular_pipelines/stable_diffusion_xl/modular_blocks.py +380 -0
  91. diffusers/modular_pipelines/stable_diffusion_xl/modular_pipeline.py +365 -0
  92. diffusers/modular_pipelines/wan/__init__.py +66 -0
  93. diffusers/modular_pipelines/wan/before_denoise.py +365 -0
  94. diffusers/modular_pipelines/wan/decoders.py +105 -0
  95. diffusers/modular_pipelines/wan/denoise.py +261 -0
  96. diffusers/modular_pipelines/wan/encoders.py +242 -0
  97. diffusers/modular_pipelines/wan/modular_blocks.py +144 -0
  98. diffusers/modular_pipelines/wan/modular_pipeline.py +90 -0
  99. diffusers/pipelines/__init__.py +31 -0
  100. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +2 -3
  101. diffusers/pipelines/auto_pipeline.py +17 -13
  102. diffusers/pipelines/chroma/pipeline_chroma.py +5 -5
  103. diffusers/pipelines/chroma/pipeline_chroma_img2img.py +5 -5
  104. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +9 -8
  105. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +9 -8
  106. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +10 -9
  107. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +9 -8
  108. diffusers/pipelines/cogview4/pipeline_cogview4.py +16 -15
  109. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +3 -2
  110. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +212 -93
  111. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +7 -3
  112. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +194 -92
  113. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +1 -1
  114. diffusers/pipelines/dit/pipeline_dit.py +3 -1
  115. diffusers/pipelines/flux/__init__.py +4 -0
  116. diffusers/pipelines/flux/pipeline_flux.py +34 -26
  117. diffusers/pipelines/flux/pipeline_flux_control.py +8 -8
  118. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +1 -1
  119. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1 -1
  120. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1 -1
  121. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +1 -1
  122. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1 -1
  123. diffusers/pipelines/flux/pipeline_flux_fill.py +1 -1
  124. diffusers/pipelines/flux/pipeline_flux_img2img.py +1 -1
  125. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1 -1
  126. diffusers/pipelines/flux/pipeline_flux_kontext.py +1134 -0
  127. diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py +1460 -0
  128. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +1 -1
  129. diffusers/pipelines/flux/pipeline_output.py +6 -4
  130. diffusers/pipelines/hidream_image/pipeline_hidream_image.py +5 -5
  131. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +25 -24
  132. diffusers/pipelines/ltx/pipeline_ltx.py +13 -12
  133. diffusers/pipelines/ltx/pipeline_ltx_condition.py +10 -9
  134. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +13 -12
  135. diffusers/pipelines/mochi/pipeline_mochi.py +9 -8
  136. diffusers/pipelines/pipeline_flax_utils.py +2 -2
  137. diffusers/pipelines/pipeline_loading_utils.py +24 -2
  138. diffusers/pipelines/pipeline_utils.py +22 -15
  139. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +3 -1
  140. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +20 -0
  141. diffusers/pipelines/qwenimage/__init__.py +55 -0
  142. diffusers/pipelines/qwenimage/pipeline_output.py +21 -0
  143. diffusers/pipelines/qwenimage/pipeline_qwenimage.py +726 -0
  144. diffusers/pipelines/qwenimage/pipeline_qwenimage_edit.py +849 -0
  145. diffusers/pipelines/qwenimage/pipeline_qwenimage_img2img.py +829 -0
  146. diffusers/pipelines/qwenimage/pipeline_qwenimage_inpaint.py +1015 -0
  147. diffusers/pipelines/sana/pipeline_sana_sprint.py +5 -5
  148. diffusers/pipelines/skyreels_v2/__init__.py +59 -0
  149. diffusers/pipelines/skyreels_v2/pipeline_output.py +20 -0
  150. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py +610 -0
  151. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py +978 -0
  152. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py +1059 -0
  153. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py +1063 -0
  154. diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py +745 -0
  155. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -1
  156. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -1
  157. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +1 -1
  158. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +2 -1
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +6 -5
  160. diffusers/pipelines/wan/pipeline_wan.py +78 -20
  161. diffusers/pipelines/wan/pipeline_wan_i2v.py +112 -32
  162. diffusers/pipelines/wan/pipeline_wan_vace.py +1 -2
  163. diffusers/quantizers/__init__.py +1 -177
  164. diffusers/quantizers/base.py +11 -0
  165. diffusers/quantizers/gguf/utils.py +92 -3
  166. diffusers/quantizers/pipe_quant_config.py +202 -0
  167. diffusers/quantizers/torchao/torchao_quantizer.py +26 -0
  168. diffusers/schedulers/scheduling_deis_multistep.py +8 -1
  169. diffusers/schedulers/scheduling_dpmsolver_multistep.py +6 -0
  170. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +6 -0
  171. diffusers/schedulers/scheduling_scm.py +0 -1
  172. diffusers/schedulers/scheduling_unipc_multistep.py +10 -1
  173. diffusers/schedulers/scheduling_utils.py +2 -2
  174. diffusers/schedulers/scheduling_utils_flax.py +1 -1
  175. diffusers/training_utils.py +78 -0
  176. diffusers/utils/__init__.py +10 -0
  177. diffusers/utils/constants.py +4 -0
  178. diffusers/utils/dummy_pt_objects.py +312 -0
  179. diffusers/utils/dummy_torch_and_transformers_objects.py +255 -0
  180. diffusers/utils/dynamic_modules_utils.py +84 -25
  181. diffusers/utils/hub_utils.py +33 -17
  182. diffusers/utils/import_utils.py +70 -0
  183. diffusers/utils/peft_utils.py +11 -8
  184. diffusers/utils/testing_utils.py +136 -10
  185. diffusers/utils/torch_utils.py +18 -0
  186. {diffusers-0.34.0.dist-info → diffusers-0.35.1.dist-info}/METADATA +6 -6
  187. {diffusers-0.34.0.dist-info → diffusers-0.35.1.dist-info}/RECORD +191 -127
  188. {diffusers-0.34.0.dist-info → diffusers-0.35.1.dist-info}/LICENSE +0 -0
  189. {diffusers-0.34.0.dist-info → diffusers-0.35.1.dist-info}/WHEEL +0 -0
  190. {diffusers-0.34.0.dist-info → diffusers-0.35.1.dist-info}/entry_points.txt +0 -0
  191. {diffusers-0.34.0.dist-info → diffusers-0.35.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,849 @@
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, Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer, Qwen2VLProcessor
22
+
23
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
24
+ from ...loaders import QwenImageLoraLoaderMixin
25
+ from ...models import AutoencoderKLQwenImage, QwenImageTransformer2DModel
26
+ from ...schedulers import FlowMatchEulerDiscreteScheduler
27
+ from ...utils import is_torch_xla_available, logging, replace_example_docstring
28
+ from ...utils.torch_utils import randn_tensor
29
+ from ..pipeline_utils import DiffusionPipeline
30
+ from .pipeline_output import QwenImagePipelineOutput
31
+
32
+
33
+ if is_torch_xla_available():
34
+ import torch_xla.core.xla_model as xm
35
+
36
+ XLA_AVAILABLE = True
37
+ else:
38
+ XLA_AVAILABLE = False
39
+
40
+
41
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
+
43
+ EXAMPLE_DOC_STRING = """
44
+ Examples:
45
+ ```py
46
+ >>> import torch
47
+ >>> from PIL import Image
48
+ >>> from diffusers import QwenImageEditPipeline
49
+ >>> from diffusers.utils import load_image
50
+
51
+ >>> pipe = QwenImageEditPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype=torch.bfloat16)
52
+ >>> pipe.to("cuda")
53
+ >>> image = load_image(
54
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
55
+ ... ).convert("RGB")
56
+ >>> prompt = (
57
+ ... "Make Pikachu hold a sign that says 'Qwen Edit is awesome', yarn art style, detailed, vibrant colors"
58
+ ... )
59
+ >>> # Depending on the variant being used, the pipeline call will slightly vary.
60
+ >>> # Refer to the pipeline documentation for more details.
61
+ >>> image = pipe(image, prompt, num_inference_steps=50).images[0]
62
+ >>> image.save("qwenimage_edit.png")
63
+ ```
64
+ """
65
+
66
+
67
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.calculate_shift
68
+ def calculate_shift(
69
+ image_seq_len,
70
+ base_seq_len: int = 256,
71
+ max_seq_len: int = 4096,
72
+ base_shift: float = 0.5,
73
+ max_shift: float = 1.15,
74
+ ):
75
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
76
+ b = base_shift - m * base_seq_len
77
+ mu = image_seq_len * m + b
78
+ return mu
79
+
80
+
81
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
82
+ def retrieve_timesteps(
83
+ scheduler,
84
+ num_inference_steps: Optional[int] = None,
85
+ device: Optional[Union[str, torch.device]] = None,
86
+ timesteps: Optional[List[int]] = None,
87
+ sigmas: Optional[List[float]] = None,
88
+ **kwargs,
89
+ ):
90
+ r"""
91
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
92
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
93
+
94
+ Args:
95
+ scheduler (`SchedulerMixin`):
96
+ The scheduler to get timesteps from.
97
+ num_inference_steps (`int`):
98
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
99
+ must be `None`.
100
+ device (`str` or `torch.device`, *optional*):
101
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
102
+ timesteps (`List[int]`, *optional*):
103
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
104
+ `num_inference_steps` and `sigmas` must be `None`.
105
+ sigmas (`List[float]`, *optional*):
106
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
107
+ `num_inference_steps` and `timesteps` must be `None`.
108
+
109
+ Returns:
110
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
111
+ second element is the number of inference steps.
112
+ """
113
+ if timesteps is not None and sigmas is not None:
114
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
115
+ if timesteps is not None:
116
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
117
+ if not accepts_timesteps:
118
+ raise ValueError(
119
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
120
+ f" timestep schedules. Please check whether you are using the correct scheduler."
121
+ )
122
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
123
+ timesteps = scheduler.timesteps
124
+ num_inference_steps = len(timesteps)
125
+ elif sigmas is not None:
126
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
127
+ if not accept_sigmas:
128
+ raise ValueError(
129
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
130
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
131
+ )
132
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
133
+ timesteps = scheduler.timesteps
134
+ num_inference_steps = len(timesteps)
135
+ else:
136
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
137
+ timesteps = scheduler.timesteps
138
+ return timesteps, num_inference_steps
139
+
140
+
141
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
142
+ def retrieve_latents(
143
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
144
+ ):
145
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
146
+ return encoder_output.latent_dist.sample(generator)
147
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
148
+ return encoder_output.latent_dist.mode()
149
+ elif hasattr(encoder_output, "latents"):
150
+ return encoder_output.latents
151
+ else:
152
+ raise AttributeError("Could not access latents of provided encoder_output")
153
+
154
+
155
+ def calculate_dimensions(target_area, ratio):
156
+ width = math.sqrt(target_area * ratio)
157
+ height = width / ratio
158
+
159
+ width = round(width / 32) * 32
160
+ height = round(height / 32) * 32
161
+
162
+ return width, height, None
163
+
164
+
165
+ class QwenImageEditPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
166
+ r"""
167
+ The Qwen-Image-Edit pipeline for image editing.
168
+
169
+ Args:
170
+ transformer ([`QwenImageTransformer2DModel`]):
171
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
172
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
173
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
174
+ vae ([`AutoencoderKL`]):
175
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
176
+ text_encoder ([`Qwen2.5-VL-7B-Instruct`]):
177
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the
178
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant.
179
+ tokenizer (`QwenTokenizer`):
180
+ Tokenizer of class
181
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
182
+ """
183
+
184
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
185
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
186
+
187
+ def __init__(
188
+ self,
189
+ scheduler: FlowMatchEulerDiscreteScheduler,
190
+ vae: AutoencoderKLQwenImage,
191
+ text_encoder: Qwen2_5_VLForConditionalGeneration,
192
+ tokenizer: Qwen2Tokenizer,
193
+ processor: Qwen2VLProcessor,
194
+ transformer: QwenImageTransformer2DModel,
195
+ ):
196
+ super().__init__()
197
+
198
+ self.register_modules(
199
+ vae=vae,
200
+ text_encoder=text_encoder,
201
+ tokenizer=tokenizer,
202
+ processor=processor,
203
+ transformer=transformer,
204
+ scheduler=scheduler,
205
+ )
206
+ self.vae_scale_factor = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
207
+ self.latent_channels = self.vae.config.z_dim if getattr(self, "vae", None) else 16
208
+ # QwenImage latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
209
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
210
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
211
+ self.vl_processor = processor
212
+ self.tokenizer_max_length = 1024
213
+
214
+ 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<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>\n<|im_start|>assistant\n"
215
+ self.prompt_template_encode_start_idx = 64
216
+ self.default_sample_size = 128
217
+
218
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._extract_masked_hidden
219
+ def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
220
+ bool_mask = mask.bool()
221
+ valid_lengths = bool_mask.sum(dim=1)
222
+ selected = hidden_states[bool_mask]
223
+ split_result = torch.split(selected, valid_lengths.tolist(), dim=0)
224
+
225
+ return split_result
226
+
227
+ def _get_qwen_prompt_embeds(
228
+ self,
229
+ prompt: Union[str, List[str]] = None,
230
+ image: Optional[torch.Tensor] = None,
231
+ device: Optional[torch.device] = None,
232
+ dtype: Optional[torch.dtype] = None,
233
+ ):
234
+ device = device or self._execution_device
235
+ dtype = dtype or self.text_encoder.dtype
236
+
237
+ prompt = [prompt] if isinstance(prompt, str) else prompt
238
+
239
+ template = self.prompt_template_encode
240
+ drop_idx = self.prompt_template_encode_start_idx
241
+ txt = [template.format(e) for e in prompt]
242
+
243
+ model_inputs = self.processor(
244
+ text=txt,
245
+ images=image,
246
+ padding=True,
247
+ return_tensors="pt",
248
+ ).to(device)
249
+
250
+ outputs = self.text_encoder(
251
+ input_ids=model_inputs.input_ids,
252
+ attention_mask=model_inputs.attention_mask,
253
+ pixel_values=model_inputs.pixel_values,
254
+ image_grid_thw=model_inputs.image_grid_thw,
255
+ output_hidden_states=True,
256
+ )
257
+
258
+ hidden_states = outputs.hidden_states[-1]
259
+ split_hidden_states = self._extract_masked_hidden(hidden_states, model_inputs.attention_mask)
260
+ split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
261
+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
262
+ max_seq_len = max([e.size(0) for e in split_hidden_states])
263
+ prompt_embeds = torch.stack(
264
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
265
+ )
266
+ encoder_attention_mask = torch.stack(
267
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]
268
+ )
269
+
270
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
271
+
272
+ return prompt_embeds, encoder_attention_mask
273
+
274
+ def encode_prompt(
275
+ self,
276
+ prompt: Union[str, List[str]],
277
+ image: Optional[torch.Tensor] = None,
278
+ device: Optional[torch.device] = None,
279
+ num_images_per_prompt: int = 1,
280
+ prompt_embeds: Optional[torch.Tensor] = None,
281
+ prompt_embeds_mask: Optional[torch.Tensor] = None,
282
+ max_sequence_length: int = 1024,
283
+ ):
284
+ r"""
285
+
286
+ Args:
287
+ prompt (`str` or `List[str]`, *optional*):
288
+ prompt to be encoded
289
+ image (`torch.Tensor`, *optional*):
290
+ image to be encoded
291
+ device: (`torch.device`):
292
+ torch device
293
+ num_images_per_prompt (`int`):
294
+ number of images that should be generated per prompt
295
+ prompt_embeds (`torch.Tensor`, *optional*):
296
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
297
+ provided, text embeddings will be generated from `prompt` input argument.
298
+ """
299
+ device = device or self._execution_device
300
+
301
+ prompt = [prompt] if isinstance(prompt, str) else prompt
302
+ batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
303
+
304
+ if prompt_embeds is None:
305
+ prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image, device)
306
+
307
+ _, seq_len, _ = prompt_embeds.shape
308
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
309
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
310
+ prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1)
311
+ prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len)
312
+
313
+ return prompt_embeds, prompt_embeds_mask
314
+
315
+ def check_inputs(
316
+ self,
317
+ prompt,
318
+ height,
319
+ width,
320
+ negative_prompt=None,
321
+ prompt_embeds=None,
322
+ negative_prompt_embeds=None,
323
+ prompt_embeds_mask=None,
324
+ negative_prompt_embeds_mask=None,
325
+ callback_on_step_end_tensor_inputs=None,
326
+ max_sequence_length=None,
327
+ ):
328
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
329
+ logger.warning(
330
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
331
+ )
332
+
333
+ if callback_on_step_end_tensor_inputs is not None and not all(
334
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
335
+ ):
336
+ raise ValueError(
337
+ 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]}"
338
+ )
339
+
340
+ if prompt is not None and prompt_embeds is not None:
341
+ raise ValueError(
342
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
343
+ " only forward one of the two."
344
+ )
345
+ elif prompt is None and prompt_embeds is None:
346
+ raise ValueError(
347
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
348
+ )
349
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
350
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
351
+
352
+ if negative_prompt is not None and negative_prompt_embeds is not None:
353
+ raise ValueError(
354
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
355
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
356
+ )
357
+
358
+ if prompt_embeds is not None and prompt_embeds_mask is None:
359
+ raise ValueError(
360
+ "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`."
361
+ )
362
+ if negative_prompt_embeds is not None and negative_prompt_embeds_mask is None:
363
+ raise ValueError(
364
+ "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`."
365
+ )
366
+
367
+ if max_sequence_length is not None and max_sequence_length > 1024:
368
+ raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
369
+
370
+ @staticmethod
371
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._pack_latents
372
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
373
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
374
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
375
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
376
+
377
+ return latents
378
+
379
+ @staticmethod
380
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._unpack_latents
381
+ def _unpack_latents(latents, height, width, vae_scale_factor):
382
+ batch_size, num_patches, channels = latents.shape
383
+
384
+ # VAE applies 8x compression on images but we must also account for packing which requires
385
+ # latent height and width to be divisible by 2.
386
+ height = 2 * (int(height) // (vae_scale_factor * 2))
387
+ width = 2 * (int(width) // (vae_scale_factor * 2))
388
+
389
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
390
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
391
+
392
+ latents = latents.reshape(batch_size, channels // (2 * 2), 1, height, width)
393
+
394
+ return latents
395
+
396
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
397
+ if isinstance(generator, list):
398
+ image_latents = [
399
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode="argmax")
400
+ for i in range(image.shape[0])
401
+ ]
402
+ image_latents = torch.cat(image_latents, dim=0)
403
+ else:
404
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax")
405
+ latents_mean = (
406
+ torch.tensor(self.vae.config.latents_mean)
407
+ .view(1, self.latent_channels, 1, 1, 1)
408
+ .to(image_latents.device, image_latents.dtype)
409
+ )
410
+ latents_std = (
411
+ torch.tensor(self.vae.config.latents_std)
412
+ .view(1, self.latent_channels, 1, 1, 1)
413
+ .to(image_latents.device, image_latents.dtype)
414
+ )
415
+ image_latents = (image_latents - latents_mean) / latents_std
416
+
417
+ return image_latents
418
+
419
+ def enable_vae_slicing(self):
420
+ r"""
421
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
422
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
423
+ """
424
+ self.vae.enable_slicing()
425
+
426
+ def disable_vae_slicing(self):
427
+ r"""
428
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
429
+ computing decoding in one step.
430
+ """
431
+ self.vae.disable_slicing()
432
+
433
+ def enable_vae_tiling(self):
434
+ r"""
435
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
436
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
437
+ processing larger images.
438
+ """
439
+ self.vae.enable_tiling()
440
+
441
+ def disable_vae_tiling(self):
442
+ r"""
443
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
444
+ computing decoding in one step.
445
+ """
446
+ self.vae.disable_tiling()
447
+
448
+ def prepare_latents(
449
+ self,
450
+ image,
451
+ batch_size,
452
+ num_channels_latents,
453
+ height,
454
+ width,
455
+ dtype,
456
+ device,
457
+ generator,
458
+ latents=None,
459
+ ):
460
+ # VAE applies 8x compression on images but we must also account for packing which requires
461
+ # latent height and width to be divisible by 2.
462
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
463
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
464
+
465
+ shape = (batch_size, 1, num_channels_latents, height, width)
466
+
467
+ image_latents = None
468
+ if image is not None:
469
+ image = image.to(device=device, dtype=dtype)
470
+ if image.shape[1] != self.latent_channels:
471
+ image_latents = self._encode_vae_image(image=image, generator=generator)
472
+ else:
473
+ image_latents = image
474
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
475
+ # expand init_latents for batch_size
476
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
477
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
478
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
479
+ raise ValueError(
480
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
481
+ )
482
+ else:
483
+ image_latents = torch.cat([image_latents], dim=0)
484
+
485
+ image_latent_height, image_latent_width = image_latents.shape[3:]
486
+ image_latents = self._pack_latents(
487
+ image_latents, batch_size, num_channels_latents, image_latent_height, image_latent_width
488
+ )
489
+
490
+ if isinstance(generator, list) and len(generator) != batch_size:
491
+ raise ValueError(
492
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
493
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
494
+ )
495
+ if latents is None:
496
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
497
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
498
+ else:
499
+ latents = latents.to(device=device, dtype=dtype)
500
+
501
+ return latents, image_latents
502
+
503
+ @property
504
+ def guidance_scale(self):
505
+ return self._guidance_scale
506
+
507
+ @property
508
+ def attention_kwargs(self):
509
+ return self._attention_kwargs
510
+
511
+ @property
512
+ def num_timesteps(self):
513
+ return self._num_timesteps
514
+
515
+ @property
516
+ def current_timestep(self):
517
+ return self._current_timestep
518
+
519
+ @property
520
+ def interrupt(self):
521
+ return self._interrupt
522
+
523
+ @torch.no_grad()
524
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
525
+ def __call__(
526
+ self,
527
+ image: Optional[PipelineImageInput] = None,
528
+ prompt: Union[str, List[str]] = None,
529
+ negative_prompt: Union[str, List[str]] = None,
530
+ true_cfg_scale: float = 4.0,
531
+ height: Optional[int] = None,
532
+ width: Optional[int] = None,
533
+ num_inference_steps: int = 50,
534
+ sigmas: Optional[List[float]] = None,
535
+ guidance_scale: float = 1.0,
536
+ num_images_per_prompt: int = 1,
537
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
538
+ latents: Optional[torch.Tensor] = None,
539
+ prompt_embeds: Optional[torch.Tensor] = None,
540
+ prompt_embeds_mask: Optional[torch.Tensor] = None,
541
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
542
+ negative_prompt_embeds_mask: Optional[torch.Tensor] = None,
543
+ output_type: Optional[str] = "pil",
544
+ return_dict: bool = True,
545
+ attention_kwargs: Optional[Dict[str, Any]] = None,
546
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
547
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
548
+ max_sequence_length: int = 512,
549
+ ):
550
+ r"""
551
+ Function invoked when calling the pipeline for generation.
552
+
553
+ Args:
554
+ prompt (`str` or `List[str]`, *optional*):
555
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
556
+ instead.
557
+ negative_prompt (`str` or `List[str]`, *optional*):
558
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
559
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
560
+ not greater than `1`).
561
+ true_cfg_scale (`float`, *optional*, defaults to 1.0):
562
+ When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
563
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
564
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
565
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
566
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
567
+ num_inference_steps (`int`, *optional*, defaults to 50):
568
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
569
+ expense of slower inference.
570
+ sigmas (`List[float]`, *optional*):
571
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
572
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
573
+ will be used.
574
+ guidance_scale (`float`, *optional*, defaults to 3.5):
575
+ Guidance scale as defined in [Classifier-Free Diffusion
576
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
577
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
578
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
579
+ the text `prompt`, usually at the expense of lower image quality.
580
+
581
+ This parameter in the pipeline is there to support future guidance-distilled models when they come up.
582
+ Note that passing `guidance_scale` to the pipeline is ineffective. To enable classifier-free guidance,
583
+ please pass `true_cfg_scale` and `negative_prompt` (even an empty negative prompt like " ") should
584
+ enable classifier-free guidance computations.
585
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
586
+ The number of images to generate per prompt.
587
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
588
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
589
+ to make generation deterministic.
590
+ latents (`torch.Tensor`, *optional*):
591
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
592
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
593
+ tensor will be generated by sampling using the supplied random `generator`.
594
+ prompt_embeds (`torch.Tensor`, *optional*):
595
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
596
+ provided, text embeddings will be generated from `prompt` input argument.
597
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
598
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
599
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
600
+ argument.
601
+ output_type (`str`, *optional*, defaults to `"pil"`):
602
+ The output format of the generate image. Choose between
603
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
604
+ return_dict (`bool`, *optional*, defaults to `True`):
605
+ Whether or not to return a [`~pipelines.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple.
606
+ attention_kwargs (`dict`, *optional*):
607
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
608
+ `self.processor` in
609
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
610
+ callback_on_step_end (`Callable`, *optional*):
611
+ A function that calls at the end of each denoising steps during the inference. The function is called
612
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
613
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
614
+ `callback_on_step_end_tensor_inputs`.
615
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
616
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
617
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
618
+ `._callback_tensor_inputs` attribute of your pipeline class.
619
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
620
+
621
+ Examples:
622
+
623
+ Returns:
624
+ [`~pipelines.qwenimage.QwenImagePipelineOutput`] or `tuple`:
625
+ [`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
626
+ returning a tuple, the first element is a list with the generated images.
627
+ """
628
+ image_size = image[0].size if isinstance(image, list) else image.size
629
+ calculated_width, calculated_height, _ = calculate_dimensions(1024 * 1024, image_size[0] / image_size[1])
630
+ height = height or calculated_height
631
+ width = width or calculated_width
632
+
633
+ multiple_of = self.vae_scale_factor * 2
634
+ width = width // multiple_of * multiple_of
635
+ height = height // multiple_of * multiple_of
636
+
637
+ # 1. Check inputs. Raise error if not correct
638
+ self.check_inputs(
639
+ prompt,
640
+ height,
641
+ width,
642
+ negative_prompt=negative_prompt,
643
+ prompt_embeds=prompt_embeds,
644
+ negative_prompt_embeds=negative_prompt_embeds,
645
+ prompt_embeds_mask=prompt_embeds_mask,
646
+ negative_prompt_embeds_mask=negative_prompt_embeds_mask,
647
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
648
+ max_sequence_length=max_sequence_length,
649
+ )
650
+
651
+ self._guidance_scale = guidance_scale
652
+ self._attention_kwargs = attention_kwargs
653
+ self._current_timestep = None
654
+ self._interrupt = False
655
+
656
+ # 2. Define call parameters
657
+ if prompt is not None and isinstance(prompt, str):
658
+ batch_size = 1
659
+ elif prompt is not None and isinstance(prompt, list):
660
+ batch_size = len(prompt)
661
+ else:
662
+ batch_size = prompt_embeds.shape[0]
663
+
664
+ device = self._execution_device
665
+ # 3. Preprocess image
666
+ if image is not None and not (isinstance(image, torch.Tensor) and image.size(1) == self.latent_channels):
667
+ image = self.image_processor.resize(image, calculated_height, calculated_width)
668
+ prompt_image = image
669
+ image = self.image_processor.preprocess(image, calculated_height, calculated_width)
670
+ image = image.unsqueeze(2)
671
+
672
+ has_neg_prompt = negative_prompt is not None or (
673
+ negative_prompt_embeds is not None and negative_prompt_embeds_mask is not None
674
+ )
675
+ do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
676
+ prompt_embeds, prompt_embeds_mask = self.encode_prompt(
677
+ image=prompt_image,
678
+ prompt=prompt,
679
+ prompt_embeds=prompt_embeds,
680
+ prompt_embeds_mask=prompt_embeds_mask,
681
+ device=device,
682
+ num_images_per_prompt=num_images_per_prompt,
683
+ max_sequence_length=max_sequence_length,
684
+ )
685
+ if do_true_cfg:
686
+ negative_prompt_embeds, negative_prompt_embeds_mask = self.encode_prompt(
687
+ image=prompt_image,
688
+ prompt=negative_prompt,
689
+ prompt_embeds=negative_prompt_embeds,
690
+ prompt_embeds_mask=negative_prompt_embeds_mask,
691
+ device=device,
692
+ num_images_per_prompt=num_images_per_prompt,
693
+ max_sequence_length=max_sequence_length,
694
+ )
695
+
696
+ # 4. Prepare latent variables
697
+ num_channels_latents = self.transformer.config.in_channels // 4
698
+ latents, image_latents = self.prepare_latents(
699
+ image,
700
+ batch_size * num_images_per_prompt,
701
+ num_channels_latents,
702
+ height,
703
+ width,
704
+ prompt_embeds.dtype,
705
+ device,
706
+ generator,
707
+ latents,
708
+ )
709
+ img_shapes = [
710
+ [
711
+ (1, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2),
712
+ (1, calculated_height // self.vae_scale_factor // 2, calculated_width // self.vae_scale_factor // 2),
713
+ ]
714
+ ] * batch_size
715
+
716
+ # 5. Prepare timesteps
717
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
718
+ image_seq_len = latents.shape[1]
719
+ mu = calculate_shift(
720
+ image_seq_len,
721
+ self.scheduler.config.get("base_image_seq_len", 256),
722
+ self.scheduler.config.get("max_image_seq_len", 4096),
723
+ self.scheduler.config.get("base_shift", 0.5),
724
+ self.scheduler.config.get("max_shift", 1.15),
725
+ )
726
+ timesteps, num_inference_steps = retrieve_timesteps(
727
+ self.scheduler,
728
+ num_inference_steps,
729
+ device,
730
+ sigmas=sigmas,
731
+ mu=mu,
732
+ )
733
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
734
+ self._num_timesteps = len(timesteps)
735
+
736
+ # handle guidance
737
+ if self.transformer.config.guidance_embeds:
738
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
739
+ guidance = guidance.expand(latents.shape[0])
740
+ else:
741
+ guidance = None
742
+
743
+ if self.attention_kwargs is None:
744
+ self._attention_kwargs = {}
745
+
746
+ txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist() if prompt_embeds_mask is not None else None
747
+ negative_txt_seq_lens = (
748
+ negative_prompt_embeds_mask.sum(dim=1).tolist() if negative_prompt_embeds_mask is not None else None
749
+ )
750
+
751
+ # 6. Denoising loop
752
+ self.scheduler.set_begin_index(0)
753
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
754
+ for i, t in enumerate(timesteps):
755
+ if self.interrupt:
756
+ continue
757
+
758
+ self._current_timestep = t
759
+
760
+ latent_model_input = latents
761
+ if image_latents is not None:
762
+ latent_model_input = torch.cat([latents, image_latents], dim=1)
763
+
764
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
765
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
766
+ with self.transformer.cache_context("cond"):
767
+ noise_pred = self.transformer(
768
+ hidden_states=latent_model_input,
769
+ timestep=timestep / 1000,
770
+ guidance=guidance,
771
+ encoder_hidden_states_mask=prompt_embeds_mask,
772
+ encoder_hidden_states=prompt_embeds,
773
+ img_shapes=img_shapes,
774
+ txt_seq_lens=txt_seq_lens,
775
+ attention_kwargs=self.attention_kwargs,
776
+ return_dict=False,
777
+ )[0]
778
+ noise_pred = noise_pred[:, : latents.size(1)]
779
+
780
+ if do_true_cfg:
781
+ with self.transformer.cache_context("uncond"):
782
+ neg_noise_pred = self.transformer(
783
+ hidden_states=latent_model_input,
784
+ timestep=timestep / 1000,
785
+ guidance=guidance,
786
+ encoder_hidden_states_mask=negative_prompt_embeds_mask,
787
+ encoder_hidden_states=negative_prompt_embeds,
788
+ img_shapes=img_shapes,
789
+ txt_seq_lens=negative_txt_seq_lens,
790
+ attention_kwargs=self.attention_kwargs,
791
+ return_dict=False,
792
+ )[0]
793
+ neg_noise_pred = neg_noise_pred[:, : latents.size(1)]
794
+ comb_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
795
+
796
+ cond_norm = torch.norm(noise_pred, dim=-1, keepdim=True)
797
+ noise_norm = torch.norm(comb_pred, dim=-1, keepdim=True)
798
+ noise_pred = comb_pred * (cond_norm / noise_norm)
799
+
800
+ # compute the previous noisy sample x_t -> x_t-1
801
+ latents_dtype = latents.dtype
802
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
803
+
804
+ if latents.dtype != latents_dtype:
805
+ if torch.backends.mps.is_available():
806
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
807
+ latents = latents.to(latents_dtype)
808
+
809
+ if callback_on_step_end is not None:
810
+ callback_kwargs = {}
811
+ for k in callback_on_step_end_tensor_inputs:
812
+ callback_kwargs[k] = locals()[k]
813
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
814
+
815
+ latents = callback_outputs.pop("latents", latents)
816
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
817
+
818
+ # call the callback, if provided
819
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
820
+ progress_bar.update()
821
+
822
+ if XLA_AVAILABLE:
823
+ xm.mark_step()
824
+
825
+ self._current_timestep = None
826
+ if output_type == "latent":
827
+ image = latents
828
+ else:
829
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
830
+ latents = latents.to(self.vae.dtype)
831
+ latents_mean = (
832
+ torch.tensor(self.vae.config.latents_mean)
833
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
834
+ .to(latents.device, latents.dtype)
835
+ )
836
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
837
+ latents.device, latents.dtype
838
+ )
839
+ latents = latents / latents_std + latents_mean
840
+ image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
841
+ image = self.image_processor.postprocess(image, output_type=output_type)
842
+
843
+ # Offload all models
844
+ self.maybe_free_model_hooks()
845
+
846
+ if not return_dict:
847
+ return (image,)
848
+
849
+ return QwenImagePipelineOutput(images=image)