linoyts HF Staff commited on
Commit
9ad3d02
·
verified ·
1 Parent(s): 1e52c15

add optimizations (#1)

Browse files

- add optimizations (cd553592f38c4d0c88b7dbc1954dcce2dbbea904)
- Create optimization.py (e3a91f476ca5de28e821919c0ab2b00035eddb98)
- Create pipeline_qwenimage_edit_inpaint.py (8b940e398f22a47e81a9de1d73aecac6c019b1b0)
- Update requirements.txt (20bc7cb4d71b5ea952d163b6da9772085ab83120)
- Update app.py (9c5b32ac3806d306c93c022b652a53c410d3cf70)

app.py CHANGED
@@ -5,7 +5,12 @@ import torch
5
  import random
6
  import os
7
 
8
- from diffusers import QwenImageEditInpaintPipeline
 
 
 
 
 
9
  from PIL import Image
10
 
11
  # Set environment variable for parallel loading
@@ -16,8 +21,13 @@ MAX_IMAGE_SIZE = 2048
16
 
17
  # Initialize Qwen Image Edit pipeline
18
  pipe = QwenImageEditInpaintPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype=torch.bfloat16).to("cuda")
 
 
 
 
 
19
 
20
- @spaces.GPU
21
  def infer(edit_images, prompt, negative_prompt="", seed=42, randomize_seed=False, strength=1.0, num_inference_steps=35, true_cfg_scale=4.0, progress=gr.Progress(track_tqdm=True)):
22
  image = edit_images["background"]
23
  mask = edit_images["layers"][0]
@@ -55,9 +65,18 @@ css="""
55
  with gr.Blocks(css=css) as demo:
56
 
57
  with gr.Column(elem_id="col-container"):
58
- gr.Markdown(f"""# Qwen Image Edit Inpainting
59
- Advanced image inpainting using Qwen's Image Edit model
60
- [[model](https://huggingface.co/Qwen/Qwen-Image-Edit)] [[paper](https://arxiv.org/abs/2412.20710)]
 
 
 
 
 
 
 
 
 
61
  """)
62
  with gr.Row():
63
  with gr.Column():
 
5
  import random
6
  import os
7
 
8
+ # from diffusers import QwenImageEditInpaintPipeline
9
+ from optimization import optimize_pipeline_
10
+ from qwenimage.pipeline_qwen_image_edit import QwenImageEditInpaintPipeline
11
+ from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
12
+ from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3
13
+
14
  from PIL import Image
15
 
16
  # Set environment variable for parallel loading
 
21
 
22
  # Initialize Qwen Image Edit pipeline
23
  pipe = QwenImageEditInpaintPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype=torch.bfloat16).to("cuda")
24
+ pipe.transformer.__class__ = QwenImageTransformer2DModel
25
+ pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
26
+
27
+ # --- Ahead-of-time compilation ---
28
+ optimize_pipeline_(pipe, image=Image.new("RGB", (1024, 1024)), prompt="prompt")
29
 
30
+ @spaces.GPU(duration=120)
31
  def infer(edit_images, prompt, negative_prompt="", seed=42, randomize_seed=False, strength=1.0, num_inference_steps=35, true_cfg_scale=4.0, progress=gr.Progress(track_tqdm=True)):
32
  image = edit_images["background"]
33
  mask = edit_images["layers"][0]
 
65
  with gr.Blocks(css=css) as demo:
66
 
67
  with gr.Column(elem_id="col-container"):
68
+ gr.HTML("""
69
+ <div id="logo-title">
70
+ <img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_edit_logo.png" alt="Qwen-Image Edit Logo" width="400" style="display: block; margin: 0 auto;">
71
+ <h2 style="font-style: italic;color: #5b47d1;margin-top: -27px !important;margin-left: 133px;">Inapint</h2>
72
+ </div>
73
+ """)
74
+ gr.Markdown("""
75
+
76
+ Inpaint images with Qwen Image Edit. [Learn more](https://github.com/QwenLM/Qwen-Image) about the Qwen-Image series.
77
+
78
+ This demo uses the [Qwen-Image-Lightning](https://huggingface.co/lightx2v/Qwen-Image-Lightning) LoRA with AoT compilation and FA3 for accelerated 8-step inference.
79
+ Try on [Qwen Chat](https://chat.qwen.ai/), or [download model](https://huggingface.co/Qwen/Qwen-Image-Edit) to run locally with ComfyUI or diffusers.
80
  """)
81
  with gr.Row():
82
  with gr.Column():
optimization.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ """
3
+
4
+ from typing import Any
5
+ from typing import Callable
6
+ from typing import ParamSpec
7
+ from torchao.quantization import quantize_
8
+ from torchao.quantization import Float8DynamicActivationFloat8WeightConfig
9
+ import spaces
10
+ import torch
11
+ from torch.utils._pytree import tree_map
12
+
13
+
14
+ P = ParamSpec('P')
15
+
16
+
17
+ TRANSFORMER_IMAGE_SEQ_LENGTH_DIM = torch.export.Dim('image_seq_length')
18
+ TRANSFORMER_TEXT_SEQ_LENGTH_DIM = torch.export.Dim('text_seq_length')
19
+
20
+ TRANSFORMER_DYNAMIC_SHAPES = {
21
+ 'hidden_states': {
22
+ 1: TRANSFORMER_IMAGE_SEQ_LENGTH_DIM,
23
+ },
24
+ 'encoder_hidden_states': {
25
+ 1: TRANSFORMER_TEXT_SEQ_LENGTH_DIM,
26
+ },
27
+ 'encoder_hidden_states_mask': {
28
+ 1: TRANSFORMER_TEXT_SEQ_LENGTH_DIM,
29
+ },
30
+ 'image_rotary_emb': ({
31
+ 0: TRANSFORMER_IMAGE_SEQ_LENGTH_DIM,
32
+ }, {
33
+ 0: TRANSFORMER_TEXT_SEQ_LENGTH_DIM,
34
+ }),
35
+ }
36
+
37
+
38
+ INDUCTOR_CONFIGS = {
39
+ 'conv_1x1_as_mm': True,
40
+ 'epilogue_fusion': False,
41
+ 'coordinate_descent_tuning': True,
42
+ 'coordinate_descent_check_all_directions': True,
43
+ 'max_autotune': True,
44
+ 'triton.cudagraphs': True,
45
+ }
46
+
47
+
48
+ def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
49
+
50
+ @spaces.GPU(duration=1500)
51
+ def compile_transformer():
52
+
53
+ with spaces.aoti_capture(pipeline.transformer) as call:
54
+ pipeline(*args, **kwargs)
55
+
56
+ dynamic_shapes = tree_map(lambda t: None, call.kwargs)
57
+ dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
58
+
59
+ # quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())
60
+
61
+ exported = torch.export.export(
62
+ mod=pipeline.transformer,
63
+ args=call.args,
64
+ kwargs=call.kwargs,
65
+ dynamic_shapes=dynamic_shapes,
66
+ )
67
+
68
+ return spaces.aoti_compile(exported, INDUCTOR_CONFIGS)
69
+
70
+ spaces.aoti_apply(compile_transformer(), pipeline.transformer)
qwenimage/__init__.py ADDED
File without changes
qwenimage/pipeline_qwen_image_edit.py ADDED
@@ -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 diffusers.image_processor import PipelineImageInput, VaeImageProcessor
24
+ from diffusers.loaders import QwenImageLoraLoaderMixin
25
+ from diffusers.models import AutoencoderKLQwenImage, QwenImageTransformer2DModel
26
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
27
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
28
+ from diffusers.utils.torch_utils import randn_tensor
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.pipelines.qwenimage.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
+ image_rotary_emb = self.transformer.pos_embed(img_shapes, txt_seq_lens, device=latents.device)
752
+
753
+ # 6. Denoising loop
754
+ self.scheduler.set_begin_index(0)
755
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
756
+ for i, t in enumerate(timesteps):
757
+ if self.interrupt:
758
+ continue
759
+
760
+ self._current_timestep = t
761
+
762
+ latent_model_input = latents
763
+ if image_latents is not None:
764
+ latent_model_input = torch.cat([latents, image_latents], dim=1)
765
+
766
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
767
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
768
+ with self.transformer.cache_context("cond"):
769
+ noise_pred = self.transformer(
770
+ hidden_states=latent_model_input,
771
+ timestep=timestep / 1000,
772
+ guidance=guidance,
773
+ encoder_hidden_states_mask=prompt_embeds_mask,
774
+ encoder_hidden_states=prompt_embeds,
775
+ image_rotary_emb=image_rotary_emb,
776
+ attention_kwargs=self.attention_kwargs,
777
+ return_dict=False,
778
+ )[0]
779
+ noise_pred = noise_pred[:, : latents.size(1)]
780
+
781
+ if do_true_cfg:
782
+ with self.transformer.cache_context("uncond"):
783
+ neg_noise_pred = self.transformer(
784
+ hidden_states=latent_model_input,
785
+ timestep=timestep / 1000,
786
+ guidance=guidance,
787
+ encoder_hidden_states_mask=negative_prompt_embeds_mask,
788
+ encoder_hidden_states=negative_prompt_embeds,
789
+ image_rotary_emb=image_rotary_emb,
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)
qwenimage/pipeline_qwenimage_edit_inpaint.py ADDED
@@ -0,0 +1,1106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PIL.Image
21
+ import torch
22
+ from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer, Qwen2VLProcessor
23
+
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import QwenImageLoraLoaderMixin
26
+ from diffusers.models import AutoencoderKLQwenImage, QwenImageTransformer2DModel
27
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
28
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
29
+ from diffusers.utils.torch_utils import randn_tensor
30
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
31
+ from diffusers.pipelines.qwenimage.pipeline_output import QwenImagePipelineOutput
32
+
33
+
34
+ if is_torch_xla_available():
35
+ import torch_xla.core.xla_model as xm
36
+
37
+ XLA_AVAILABLE = True
38
+ else:
39
+ XLA_AVAILABLE = False
40
+
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ EXAMPLE_DOC_STRING = """
45
+ Examples:
46
+ ```py
47
+ >>> import torch
48
+ >>> from PIL import Image
49
+ >>> from diffusers import QwenImageEditInpaintPipeline
50
+ >>> from diffusers.utils import load_image
51
+
52
+ >>> pipe = QwenImageEditInpaintPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype=torch.bfloat16)
53
+ >>> pipe.to("cuda")
54
+ >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
55
+
56
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
57
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
58
+ >>> source = load_image(img_url)
59
+ >>> mask = load_image(mask_url)
60
+ >>> image = pipe(
61
+ ... prompt=prompt, negative_prompt=" ", image=source, mask_image=mask, strength=1.0, num_inference_steps=50
62
+ ... ).images[0]
63
+ >>> image.save("qwenimage_inpainting.png")
64
+ ```
65
+ """
66
+
67
+
68
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.calculate_shift
69
+ def calculate_shift(
70
+ image_seq_len,
71
+ base_seq_len: int = 256,
72
+ max_seq_len: int = 4096,
73
+ base_shift: float = 0.5,
74
+ max_shift: float = 1.15,
75
+ ):
76
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
77
+ b = base_shift - m * base_seq_len
78
+ mu = image_seq_len * m + b
79
+ return mu
80
+
81
+
82
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
83
+ def retrieve_timesteps(
84
+ scheduler,
85
+ num_inference_steps: Optional[int] = None,
86
+ device: Optional[Union[str, torch.device]] = None,
87
+ timesteps: Optional[List[int]] = None,
88
+ sigmas: Optional[List[float]] = None,
89
+ **kwargs,
90
+ ):
91
+ r"""
92
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
93
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
94
+
95
+ Args:
96
+ scheduler (`SchedulerMixin`):
97
+ The scheduler to get timesteps from.
98
+ num_inference_steps (`int`):
99
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
100
+ must be `None`.
101
+ device (`str` or `torch.device`, *optional*):
102
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
103
+ timesteps (`List[int]`, *optional*):
104
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
105
+ `num_inference_steps` and `sigmas` must be `None`.
106
+ sigmas (`List[float]`, *optional*):
107
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
108
+ `num_inference_steps` and `timesteps` must be `None`.
109
+
110
+ Returns:
111
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
112
+ second element is the number of inference steps.
113
+ """
114
+ if timesteps is not None and sigmas is not None:
115
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
116
+ if timesteps is not None:
117
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
118
+ if not accepts_timesteps:
119
+ raise ValueError(
120
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
121
+ f" timestep schedules. Please check whether you are using the correct scheduler."
122
+ )
123
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
124
+ timesteps = scheduler.timesteps
125
+ num_inference_steps = len(timesteps)
126
+ elif sigmas is not None:
127
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
128
+ if not accept_sigmas:
129
+ raise ValueError(
130
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
131
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
132
+ )
133
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
134
+ timesteps = scheduler.timesteps
135
+ num_inference_steps = len(timesteps)
136
+ else:
137
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
138
+ timesteps = scheduler.timesteps
139
+ return timesteps, num_inference_steps
140
+
141
+
142
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
143
+ def retrieve_latents(
144
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
145
+ ):
146
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
147
+ return encoder_output.latent_dist.sample(generator)
148
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
149
+ return encoder_output.latent_dist.mode()
150
+ elif hasattr(encoder_output, "latents"):
151
+ return encoder_output.latents
152
+ else:
153
+ raise AttributeError("Could not access latents of provided encoder_output")
154
+
155
+
156
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.calculate_dimensions
157
+ def calculate_dimensions(target_area, ratio):
158
+ width = math.sqrt(target_area * ratio)
159
+ height = width / ratio
160
+
161
+ width = round(width / 32) * 32
162
+ height = round(height / 32) * 32
163
+
164
+ return width, height, None
165
+
166
+
167
+ class QwenImageEditInpaintPipeline(DiffusionPipeline, QwenImageLoraLoaderMixin):
168
+ r"""
169
+ The Qwen-Image-Edit pipeline for image editing.
170
+
171
+ Args:
172
+ transformer ([`QwenImageTransformer2DModel`]):
173
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
174
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
175
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
176
+ vae ([`AutoencoderKL`]):
177
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
178
+ text_encoder ([`Qwen2.5-VL-7B-Instruct`]):
179
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the
180
+ [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant.
181
+ tokenizer (`QwenTokenizer`):
182
+ Tokenizer of class
183
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
184
+ """
185
+
186
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
187
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
188
+
189
+ def __init__(
190
+ self,
191
+ scheduler: FlowMatchEulerDiscreteScheduler,
192
+ vae: AutoencoderKLQwenImage,
193
+ text_encoder: Qwen2_5_VLForConditionalGeneration,
194
+ tokenizer: Qwen2Tokenizer,
195
+ processor: Qwen2VLProcessor,
196
+ transformer: QwenImageTransformer2DModel,
197
+ ):
198
+ super().__init__()
199
+
200
+ self.register_modules(
201
+ vae=vae,
202
+ text_encoder=text_encoder,
203
+ tokenizer=tokenizer,
204
+ processor=processor,
205
+ transformer=transformer,
206
+ scheduler=scheduler,
207
+ )
208
+ self.vae_scale_factor = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
209
+ self.latent_channels = self.vae.config.z_dim if getattr(self, "vae", None) else 16
210
+ # QwenImage latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible
211
+ # by the patch size. So the vae scale factor is multiplied by the patch size to account for this
212
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
213
+ self.mask_processor = VaeImageProcessor(
214
+ vae_scale_factor=self.vae_scale_factor * 2,
215
+ vae_latent_channels=self.latent_channels,
216
+ do_normalize=False,
217
+ do_binarize=True,
218
+ do_convert_grayscale=True,
219
+ )
220
+ self.vl_processor = processor
221
+ self.tokenizer_max_length = 1024
222
+
223
+ 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"
224
+ self.prompt_template_encode_start_idx = 64
225
+ self.default_sample_size = 128
226
+
227
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._extract_masked_hidden
228
+ def _extract_masked_hidden(self, hidden_states: torch.Tensor, mask: torch.Tensor):
229
+ bool_mask = mask.bool()
230
+ valid_lengths = bool_mask.sum(dim=1)
231
+ selected = hidden_states[bool_mask]
232
+ split_result = torch.split(selected, valid_lengths.tolist(), dim=0)
233
+
234
+ return split_result
235
+
236
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline._get_qwen_prompt_embeds
237
+ def _get_qwen_prompt_embeds(
238
+ self,
239
+ prompt: Union[str, List[str]] = None,
240
+ image: Optional[torch.Tensor] = None,
241
+ device: Optional[torch.device] = None,
242
+ dtype: Optional[torch.dtype] = None,
243
+ ):
244
+ device = device or self._execution_device
245
+ dtype = dtype or self.text_encoder.dtype
246
+
247
+ prompt = [prompt] if isinstance(prompt, str) else prompt
248
+
249
+ template = self.prompt_template_encode
250
+ drop_idx = self.prompt_template_encode_start_idx
251
+ txt = [template.format(e) for e in prompt]
252
+
253
+ model_inputs = self.processor(
254
+ text=txt,
255
+ images=image,
256
+ padding=True,
257
+ return_tensors="pt",
258
+ ).to(device)
259
+
260
+ outputs = self.text_encoder(
261
+ input_ids=model_inputs.input_ids,
262
+ attention_mask=model_inputs.attention_mask,
263
+ pixel_values=model_inputs.pixel_values,
264
+ image_grid_thw=model_inputs.image_grid_thw,
265
+ output_hidden_states=True,
266
+ )
267
+
268
+ hidden_states = outputs.hidden_states[-1]
269
+ split_hidden_states = self._extract_masked_hidden(hidden_states, model_inputs.attention_mask)
270
+ split_hidden_states = [e[drop_idx:] for e in split_hidden_states]
271
+ attn_mask_list = [torch.ones(e.size(0), dtype=torch.long, device=e.device) for e in split_hidden_states]
272
+ max_seq_len = max([e.size(0) for e in split_hidden_states])
273
+ prompt_embeds = torch.stack(
274
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0), u.size(1))]) for u in split_hidden_states]
275
+ )
276
+ encoder_attention_mask = torch.stack(
277
+ [torch.cat([u, u.new_zeros(max_seq_len - u.size(0))]) for u in attn_mask_list]
278
+ )
279
+
280
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
281
+
282
+ return prompt_embeds, encoder_attention_mask
283
+
284
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_edit.QwenImageEditPipeline.encode_prompt
285
+ def encode_prompt(
286
+ self,
287
+ prompt: Union[str, List[str]],
288
+ image: Optional[torch.Tensor] = None,
289
+ device: Optional[torch.device] = None,
290
+ num_images_per_prompt: int = 1,
291
+ prompt_embeds: Optional[torch.Tensor] = None,
292
+ prompt_embeds_mask: Optional[torch.Tensor] = None,
293
+ max_sequence_length: int = 1024,
294
+ ):
295
+ r"""
296
+
297
+ Args:
298
+ prompt (`str` or `List[str]`, *optional*):
299
+ prompt to be encoded
300
+ image (`torch.Tensor`, *optional*):
301
+ image to be encoded
302
+ device: (`torch.device`):
303
+ torch device
304
+ num_images_per_prompt (`int`):
305
+ number of images that should be generated per prompt
306
+ prompt_embeds (`torch.Tensor`, *optional*):
307
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
308
+ provided, text embeddings will be generated from `prompt` input argument.
309
+ """
310
+ device = device or self._execution_device
311
+
312
+ prompt = [prompt] if isinstance(prompt, str) else prompt
313
+ batch_size = len(prompt) if prompt_embeds is None else prompt_embeds.shape[0]
314
+
315
+ if prompt_embeds is None:
316
+ prompt_embeds, prompt_embeds_mask = self._get_qwen_prompt_embeds(prompt, image, device)
317
+
318
+ _, seq_len, _ = prompt_embeds.shape
319
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
320
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
321
+ prompt_embeds_mask = prompt_embeds_mask.repeat(1, num_images_per_prompt, 1)
322
+ prompt_embeds_mask = prompt_embeds_mask.view(batch_size * num_images_per_prompt, seq_len)
323
+
324
+ return prompt_embeds, prompt_embeds_mask
325
+
326
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_inpaint.QwenImageInpaintPipeline.check_inputs
327
+ def check_inputs(
328
+ self,
329
+ prompt,
330
+ image,
331
+ mask_image,
332
+ strength,
333
+ height,
334
+ width,
335
+ output_type,
336
+ negative_prompt=None,
337
+ prompt_embeds=None,
338
+ negative_prompt_embeds=None,
339
+ prompt_embeds_mask=None,
340
+ negative_prompt_embeds_mask=None,
341
+ callback_on_step_end_tensor_inputs=None,
342
+ padding_mask_crop=None,
343
+ max_sequence_length=None,
344
+ ):
345
+ if strength < 0 or strength > 1:
346
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
347
+
348
+ if height % (self.vae_scale_factor * 2) != 0 or width % (self.vae_scale_factor * 2) != 0:
349
+ logger.warning(
350
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor * 2} but are {height} and {width}. Dimensions will be resized accordingly"
351
+ )
352
+
353
+ if callback_on_step_end_tensor_inputs is not None and not all(
354
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
355
+ ):
356
+ raise ValueError(
357
+ 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]}"
358
+ )
359
+
360
+ if prompt is not None and prompt_embeds is not None:
361
+ raise ValueError(
362
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
363
+ " only forward one of the two."
364
+ )
365
+ elif prompt is None and prompt_embeds is None:
366
+ raise ValueError(
367
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
368
+ )
369
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
370
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
371
+
372
+ if negative_prompt is not None and negative_prompt_embeds is not None:
373
+ raise ValueError(
374
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
375
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
376
+ )
377
+
378
+ if prompt_embeds is not None and prompt_embeds_mask is None:
379
+ raise ValueError(
380
+ "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`."
381
+ )
382
+ if negative_prompt_embeds is not None and negative_prompt_embeds_mask is None:
383
+ raise ValueError(
384
+ "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`."
385
+ )
386
+ if padding_mask_crop is not None:
387
+ if not isinstance(image, PIL.Image.Image):
388
+ raise ValueError(
389
+ f"The image should be a PIL image when inpainting mask crop, but is of type {type(image)}."
390
+ )
391
+ if not isinstance(mask_image, PIL.Image.Image):
392
+ raise ValueError(
393
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
394
+ f" {type(mask_image)}."
395
+ )
396
+ if output_type != "pil":
397
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is {output_type}.")
398
+
399
+ if max_sequence_length is not None and max_sequence_length > 1024:
400
+ raise ValueError(f"`max_sequence_length` cannot be greater than 1024 but is {max_sequence_length}")
401
+
402
+ @staticmethod
403
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._pack_latents
404
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
405
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
406
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
407
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
408
+
409
+ return latents
410
+
411
+ @staticmethod
412
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage.QwenImagePipeline._unpack_latents
413
+ def _unpack_latents(latents, height, width, vae_scale_factor):
414
+ batch_size, num_patches, channels = latents.shape
415
+
416
+ # VAE applies 8x compression on images but we must also account for packing which requires
417
+ # latent height and width to be divisible by 2.
418
+ height = 2 * (int(height) // (vae_scale_factor * 2))
419
+ width = 2 * (int(width) // (vae_scale_factor * 2))
420
+
421
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
422
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
423
+
424
+ latents = latents.reshape(batch_size, channels // (2 * 2), 1, height, width)
425
+
426
+ return latents
427
+
428
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_img2img.QwenImageImg2ImgPipeline._encode_vae_image
429
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
430
+ if isinstance(generator, list):
431
+ image_latents = [
432
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
433
+ for i in range(image.shape[0])
434
+ ]
435
+ image_latents = torch.cat(image_latents, dim=0)
436
+ else:
437
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
438
+
439
+ latents_mean = (
440
+ torch.tensor(self.vae.config.latents_mean)
441
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
442
+ .to(image_latents.device, image_latents.dtype)
443
+ )
444
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
445
+ image_latents.device, image_latents.dtype
446
+ )
447
+
448
+ image_latents = (image_latents - latents_mean) * latents_std
449
+
450
+ return image_latents
451
+
452
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
453
+ def get_timesteps(self, num_inference_steps, strength, device):
454
+ # get the original timestep using init_timestep
455
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
456
+
457
+ t_start = int(max(num_inference_steps - init_timestep, 0))
458
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
459
+ if hasattr(self.scheduler, "set_begin_index"):
460
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
461
+
462
+ return timesteps, num_inference_steps - t_start
463
+
464
+ def enable_vae_slicing(self):
465
+ r"""
466
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
467
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
468
+ """
469
+ self.vae.enable_slicing()
470
+
471
+ def disable_vae_slicing(self):
472
+ r"""
473
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
474
+ computing decoding in one step.
475
+ """
476
+ self.vae.disable_slicing()
477
+
478
+ def enable_vae_tiling(self):
479
+ r"""
480
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
481
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
482
+ processing larger images.
483
+ """
484
+ self.vae.enable_tiling()
485
+
486
+ def disable_vae_tiling(self):
487
+ r"""
488
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
489
+ computing decoding in one step.
490
+ """
491
+ self.vae.disable_tiling()
492
+
493
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_inpaint.QwenImageInpaintPipeline.prepare_latents
494
+ def prepare_latents(
495
+ self,
496
+ image,
497
+ timestep,
498
+ batch_size,
499
+ num_channels_latents,
500
+ height,
501
+ width,
502
+ dtype,
503
+ device,
504
+ generator,
505
+ latents=None,
506
+ ):
507
+ if isinstance(generator, list) and len(generator) != batch_size:
508
+ raise ValueError(
509
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
510
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
511
+ )
512
+ # VAE applies 8x compression on images but we must also account for packing which requires
513
+ # latent height and width to be divisible by 2.
514
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
515
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
516
+
517
+ shape = (batch_size, 1, num_channels_latents, height, width)
518
+
519
+ # If image is [B,C,H,W] -> add T=1. If it's already [B,C,T,H,W], leave it.
520
+ if image.dim() == 4:
521
+ image = image.unsqueeze(2)
522
+ elif image.dim() != 5:
523
+ raise ValueError(f"Expected image dims 4 or 5, got {image.dim()}.")
524
+
525
+ if latents is not None:
526
+ return latents.to(device=device, dtype=dtype)
527
+
528
+ image = image.to(device=device, dtype=dtype)
529
+ if image.shape[1] != self.latent_channels:
530
+ image_latents = self._encode_vae_image(image=image, generator=generator) # [B,z,1,H',W']
531
+ else:
532
+ image_latents = image
533
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
534
+ # expand init_latents for batch_size
535
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
536
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
537
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
538
+ raise ValueError(
539
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
540
+ )
541
+ else:
542
+ image_latents = torch.cat([image_latents], dim=0)
543
+
544
+ image_latents = image_latents.transpose(1, 2) # [B,1,z,H',W']
545
+
546
+ if latents is None:
547
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
548
+ latents = self.scheduler.scale_noise(image_latents, timestep, noise)
549
+ else:
550
+ noise = latents.to(device)
551
+ latents = noise
552
+
553
+ noise = self._pack_latents(noise, batch_size, num_channels_latents, height, width)
554
+ image_latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height, width)
555
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
556
+
557
+ return latents, noise, image_latents
558
+
559
+ # Copied from diffusers.pipelines.qwenimage.pipeline_qwenimage_inpaint.QwenImageInpaintPipeline.prepare_mask_latents
560
+ def prepare_mask_latents(
561
+ self,
562
+ mask,
563
+ masked_image,
564
+ batch_size,
565
+ num_channels_latents,
566
+ num_images_per_prompt,
567
+ height,
568
+ width,
569
+ dtype,
570
+ device,
571
+ generator,
572
+ ):
573
+ # VAE applies 8x compression on images but we must also account for packing which requires
574
+ # latent height and width to be divisible by 2.
575
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
576
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
577
+ # resize the mask to latents shape as we concatenate the mask to the latents
578
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
579
+ # and half precision
580
+ mask = torch.nn.functional.interpolate(mask, size=(height, width))
581
+ mask = mask.to(device=device, dtype=dtype)
582
+
583
+ batch_size = batch_size * num_images_per_prompt
584
+
585
+ if masked_image.dim() == 4:
586
+ masked_image = masked_image.unsqueeze(2)
587
+ elif masked_image.dim() != 5:
588
+ raise ValueError(f"Expected image dims 4 or 5, got {masked_image.dim()}.")
589
+
590
+ masked_image = masked_image.to(device=device, dtype=dtype)
591
+
592
+ if masked_image.shape[1] == self.latent_channels:
593
+ masked_image_latents = masked_image
594
+ else:
595
+ masked_image_latents = self._encode_vae_image(image=masked_image, generator=generator)
596
+
597
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
598
+ if mask.shape[0] < batch_size:
599
+ if not batch_size % mask.shape[0] == 0:
600
+ raise ValueError(
601
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
602
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
603
+ " of masks that you pass is divisible by the total requested batch size."
604
+ )
605
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
606
+ if masked_image_latents.shape[0] < batch_size:
607
+ if not batch_size % masked_image_latents.shape[0] == 0:
608
+ raise ValueError(
609
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
610
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
611
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
612
+ )
613
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1, 1)
614
+
615
+ # aligning device to prevent device errors when concating it with the latent model input
616
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
617
+
618
+ masked_image_latents = self._pack_latents(
619
+ masked_image_latents,
620
+ batch_size,
621
+ num_channels_latents,
622
+ height,
623
+ width,
624
+ )
625
+ mask = self._pack_latents(
626
+ mask.repeat(1, num_channels_latents, 1, 1),
627
+ batch_size,
628
+ num_channels_latents,
629
+ height,
630
+ width,
631
+ )
632
+
633
+ return mask, masked_image_latents
634
+
635
+ @property
636
+ def guidance_scale(self):
637
+ return self._guidance_scale
638
+
639
+ @property
640
+ def attention_kwargs(self):
641
+ return self._attention_kwargs
642
+
643
+ @property
644
+ def num_timesteps(self):
645
+ return self._num_timesteps
646
+
647
+ @property
648
+ def current_timestep(self):
649
+ return self._current_timestep
650
+
651
+ @property
652
+ def interrupt(self):
653
+ return self._interrupt
654
+
655
+ @torch.no_grad()
656
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
657
+ def __call__(
658
+ self,
659
+ image: Optional[PipelineImageInput] = None,
660
+ prompt: Union[str, List[str]] = None,
661
+ negative_prompt: Union[str, List[str]] = None,
662
+ mask_image: PipelineImageInput = None,
663
+ masked_image_latents: PipelineImageInput = None,
664
+ true_cfg_scale: float = 4.0,
665
+ height: Optional[int] = None,
666
+ width: Optional[int] = None,
667
+ padding_mask_crop: Optional[int] = None,
668
+ strength: float = 0.6,
669
+ num_inference_steps: int = 50,
670
+ sigmas: Optional[List[float]] = None,
671
+ guidance_scale: Optional[float] = None,
672
+ num_images_per_prompt: int = 1,
673
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
674
+ latents: Optional[torch.Tensor] = None,
675
+ prompt_embeds: Optional[torch.Tensor] = None,
676
+ prompt_embeds_mask: Optional[torch.Tensor] = None,
677
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
678
+ negative_prompt_embeds_mask: Optional[torch.Tensor] = None,
679
+ output_type: Optional[str] = "pil",
680
+ return_dict: bool = True,
681
+ attention_kwargs: Optional[Dict[str, Any]] = None,
682
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
683
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
684
+ max_sequence_length: int = 512,
685
+ ):
686
+ r"""
687
+ Function invoked when calling the pipeline for generation.
688
+
689
+ Args:
690
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
691
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
692
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
693
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
694
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
695
+ latents as `image`, but if passing latents directly it is not encoded again.
696
+ prompt (`str` or `List[str]`, *optional*):
697
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
698
+ instead.
699
+ negative_prompt (`str` or `List[str]`, *optional*):
700
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
701
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
702
+ not greater than `1`).
703
+ true_cfg_scale (`float`, *optional*, defaults to 1.0):
704
+ true_cfg_scale (`float`, *optional*, defaults to 1.0): Guidance scale as defined in [Classifier-Free
705
+ Diffusion Guidance](https://huggingface.co/papers/2207.12598). `true_cfg_scale` is defined as `w` of
706
+ equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Classifier-free guidance is
707
+ enabled by setting `true_cfg_scale > 1` and a provided `negative_prompt`. Higher guidance scale
708
+ encourages to generate images that are closely linked to the text `prompt`, usually at the expense of
709
+ lower image quality.
710
+ mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
711
+ `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
712
+ are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
713
+ single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
714
+ color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
715
+ H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
716
+ 1)`, or `(H, W)`.
717
+ mask_image_latent (`torch.Tensor`, `List[torch.Tensor]`):
718
+ `Tensor` representing an image batch to mask `image` generated by VAE. If not provided, the mask
719
+ latents tensor will ge generated by `mask_image`.
720
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
721
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
722
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
723
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
724
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
725
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
726
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
727
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
728
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
729
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
730
+ the image is large and contain information irrelevant for inpainting, such as background.
731
+ strength (`float`, *optional*, defaults to 1.0):
732
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
733
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
734
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
735
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
736
+ essentially ignores `image`.
737
+ num_inference_steps (`int`, *optional*, defaults to 50):
738
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
739
+ expense of slower inference.
740
+ sigmas (`List[float]`, *optional*):
741
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
742
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
743
+ will be used.
744
+ guidance_scale (`float`, *optional*, defaults to None):
745
+ A guidance scale value for guidance distilled models. Unlike the traditional classifier-free guidance
746
+ where the guidance scale is applied during inference through noise prediction rescaling, guidance
747
+ distilled models take the guidance scale directly as an input parameter during forward pass. Guidance
748
+ scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images
749
+ that are closely linked to the text `prompt`, usually at the expense of lower image quality. This
750
+ parameter in the pipeline is there to support future guidance-distilled models when they come up. It is
751
+ ignored when not using guidance distilled models. To enable traditional classifier-free guidance,
752
+ please pass `true_cfg_scale > 1.0` and `negative_prompt` (even an empty negative prompt like " " should
753
+ enable classifier-free guidance computations).
754
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
755
+ The number of images to generate per prompt.
756
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
757
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
758
+ to make generation deterministic.
759
+ latents (`torch.Tensor`, *optional*):
760
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
761
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
762
+ tensor will be generated by sampling using the supplied random `generator`.
763
+ prompt_embeds (`torch.Tensor`, *optional*):
764
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
765
+ provided, text embeddings will be generated from `prompt` input argument.
766
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
767
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
768
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
769
+ argument.
770
+ output_type (`str`, *optional*, defaults to `"pil"`):
771
+ The output format of the generate image. Choose between
772
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
773
+ return_dict (`bool`, *optional*, defaults to `True`):
774
+ Whether or not to return a [`~pipelines.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple.
775
+ attention_kwargs (`dict`, *optional*):
776
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
777
+ `self.processor` in
778
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
779
+ callback_on_step_end (`Callable`, *optional*):
780
+ A function that calls at the end of each denoising steps during the inference. The function is called
781
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
782
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
783
+ `callback_on_step_end_tensor_inputs`.
784
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
785
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
786
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
787
+ `._callback_tensor_inputs` attribute of your pipeline class.
788
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
789
+
790
+ Examples:
791
+
792
+ Returns:
793
+ [`~pipelines.qwenimage.QwenImagePipelineOutput`] or `tuple`:
794
+ [`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
795
+ returning a tuple, the first element is a list with the generated images.
796
+ """
797
+ image_size = image[0].size if isinstance(image, list) else image.size
798
+ calculated_width, calculated_height, _ = calculate_dimensions(1024 * 1024, image_size[0] / image_size[1])
799
+
800
+ # height and width are the same as the calculated height and width
801
+ height = calculated_height
802
+ width = calculated_width
803
+
804
+ multiple_of = self.vae_scale_factor * 2
805
+ width = width // multiple_of * multiple_of
806
+ height = height // multiple_of * multiple_of
807
+
808
+ # 1. Check inputs. Raise error if not correct
809
+ self.check_inputs(
810
+ prompt,
811
+ image,
812
+ mask_image,
813
+ strength,
814
+ height,
815
+ width,
816
+ output_type=output_type,
817
+ negative_prompt=negative_prompt,
818
+ prompt_embeds=prompt_embeds,
819
+ negative_prompt_embeds=negative_prompt_embeds,
820
+ prompt_embeds_mask=prompt_embeds_mask,
821
+ negative_prompt_embeds_mask=negative_prompt_embeds_mask,
822
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
823
+ padding_mask_crop=padding_mask_crop,
824
+ max_sequence_length=max_sequence_length,
825
+ )
826
+
827
+ self._guidance_scale = guidance_scale
828
+ self._attention_kwargs = attention_kwargs
829
+ self._current_timestep = None
830
+ self._interrupt = False
831
+
832
+ # 2. Define call parameters
833
+ if prompt is not None and isinstance(prompt, str):
834
+ batch_size = 1
835
+ elif prompt is not None and isinstance(prompt, list):
836
+ batch_size = len(prompt)
837
+ else:
838
+ batch_size = prompt_embeds.shape[0]
839
+
840
+ device = self._execution_device
841
+ # 3. Preprocess image
842
+ if padding_mask_crop is not None:
843
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
844
+ resize_mode = "fill"
845
+ else:
846
+ crops_coords = None
847
+ resize_mode = "default"
848
+
849
+ if image is not None and not (isinstance(image, torch.Tensor) and image.size(1) == self.latent_channels):
850
+ image = self.image_processor.resize(image, calculated_height, calculated_width)
851
+ original_image = image
852
+ prompt_image = image
853
+ image = self.image_processor.preprocess(
854
+ image,
855
+ height=calculated_height,
856
+ width=calculated_width,
857
+ crops_coords=crops_coords,
858
+ resize_mode=resize_mode,
859
+ )
860
+ image = image.to(dtype=torch.float32)
861
+
862
+ has_neg_prompt = negative_prompt is not None or (
863
+ negative_prompt_embeds is not None and negative_prompt_embeds_mask is not None
864
+ )
865
+
866
+ if true_cfg_scale > 1 and not has_neg_prompt:
867
+ logger.warning(
868
+ f"true_cfg_scale is passed as {true_cfg_scale}, but classifier-free guidance is not enabled since no negative_prompt is provided."
869
+ )
870
+ elif true_cfg_scale <= 1 and has_neg_prompt:
871
+ logger.warning(
872
+ " negative_prompt is passed but classifier-free guidance is not enabled since true_cfg_scale <= 1"
873
+ )
874
+
875
+ do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
876
+ prompt_embeds, prompt_embeds_mask = self.encode_prompt(
877
+ image=prompt_image,
878
+ prompt=prompt,
879
+ prompt_embeds=prompt_embeds,
880
+ prompt_embeds_mask=prompt_embeds_mask,
881
+ device=device,
882
+ num_images_per_prompt=num_images_per_prompt,
883
+ max_sequence_length=max_sequence_length,
884
+ )
885
+ if do_true_cfg:
886
+ negative_prompt_embeds, negative_prompt_embeds_mask = self.encode_prompt(
887
+ image=prompt_image,
888
+ prompt=negative_prompt,
889
+ prompt_embeds=negative_prompt_embeds,
890
+ prompt_embeds_mask=negative_prompt_embeds_mask,
891
+ device=device,
892
+ num_images_per_prompt=num_images_per_prompt,
893
+ max_sequence_length=max_sequence_length,
894
+ )
895
+
896
+ # 4. Prepare timesteps
897
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
898
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
899
+ mu = calculate_shift(
900
+ image_seq_len,
901
+ self.scheduler.config.get("base_image_seq_len", 256),
902
+ self.scheduler.config.get("max_image_seq_len", 4096),
903
+ self.scheduler.config.get("base_shift", 0.5),
904
+ self.scheduler.config.get("max_shift", 1.15),
905
+ )
906
+ timesteps, num_inference_steps = retrieve_timesteps(
907
+ self.scheduler,
908
+ num_inference_steps,
909
+ device,
910
+ sigmas=sigmas,
911
+ mu=mu,
912
+ )
913
+
914
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
915
+
916
+ if num_inference_steps < 1:
917
+ raise ValueError(
918
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
919
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
920
+ )
921
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
922
+
923
+ # 5. Prepare latent variables
924
+ num_channels_latents = self.transformer.config.in_channels // 4
925
+ latents, noise, image_latents = self.prepare_latents(
926
+ image,
927
+ latent_timestep,
928
+ batch_size * num_images_per_prompt,
929
+ num_channels_latents,
930
+ height,
931
+ width,
932
+ prompt_embeds.dtype,
933
+ device,
934
+ generator,
935
+ latents,
936
+ )
937
+
938
+ mask_condition = self.mask_processor.preprocess(
939
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
940
+ )
941
+
942
+ if masked_image_latents is None:
943
+ masked_image = image * (mask_condition < 0.5)
944
+ else:
945
+ masked_image = masked_image_latents
946
+
947
+ mask, masked_image_latents = self.prepare_mask_latents(
948
+ mask_condition,
949
+ masked_image,
950
+ batch_size,
951
+ num_channels_latents,
952
+ num_images_per_prompt,
953
+ height,
954
+ width,
955
+ prompt_embeds.dtype,
956
+ device,
957
+ generator,
958
+ )
959
+
960
+ img_shapes = [
961
+ [
962
+ (1, height // self.vae_scale_factor // 2, width // self.vae_scale_factor // 2),
963
+ (1, calculated_height // self.vae_scale_factor // 2, calculated_width // self.vae_scale_factor // 2),
964
+ ]
965
+ ] * batch_size
966
+
967
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
968
+ self._num_timesteps = len(timesteps)
969
+
970
+ # handle guidance
971
+ if self.transformer.config.guidance_embeds and guidance_scale is None:
972
+ raise ValueError("guidance_scale is required for guidance-distilled model.")
973
+ elif self.transformer.config.guidance_embeds:
974
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
975
+ guidance = guidance.expand(latents.shape[0])
976
+ elif not self.transformer.config.guidance_embeds and guidance_scale is not None:
977
+ logger.warning(
978
+ f"guidance_scale is passed as {guidance_scale}, but ignored since the model is not guidance-distilled."
979
+ )
980
+ guidance = None
981
+ elif not self.transformer.config.guidance_embeds and guidance_scale is None:
982
+ guidance = None
983
+
984
+ if self.attention_kwargs is None:
985
+ self._attention_kwargs = {}
986
+
987
+ txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist() if prompt_embeds_mask is not None else None
988
+ negative_txt_seq_lens = (
989
+ negative_prompt_embeds_mask.sum(dim=1).tolist() if negative_prompt_embeds_mask is not None else None
990
+ )
991
+
992
+ # 6. Denoising loop
993
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
994
+ for i, t in enumerate(timesteps):
995
+ if self.interrupt:
996
+ continue
997
+
998
+ self._current_timestep = t
999
+
1000
+ latent_model_input = latents
1001
+ if image_latents is not None:
1002
+ latent_model_input = torch.cat([latents, image_latents], dim=1)
1003
+
1004
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1005
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
1006
+ with self.transformer.cache_context("cond"):
1007
+ noise_pred = self.transformer(
1008
+ hidden_states=latent_model_input,
1009
+ timestep=timestep / 1000,
1010
+ guidance=guidance,
1011
+ encoder_hidden_states_mask=prompt_embeds_mask,
1012
+ encoder_hidden_states=prompt_embeds,
1013
+ img_shapes=img_shapes,
1014
+ txt_seq_lens=txt_seq_lens,
1015
+ attention_kwargs=self.attention_kwargs,
1016
+ return_dict=False,
1017
+ )[0]
1018
+ noise_pred = noise_pred[:, : latents.size(1)]
1019
+
1020
+ if do_true_cfg:
1021
+ with self.transformer.cache_context("uncond"):
1022
+ neg_noise_pred = self.transformer(
1023
+ hidden_states=latent_model_input,
1024
+ timestep=timestep / 1000,
1025
+ guidance=guidance,
1026
+ encoder_hidden_states_mask=negative_prompt_embeds_mask,
1027
+ encoder_hidden_states=negative_prompt_embeds,
1028
+ img_shapes=img_shapes,
1029
+ txt_seq_lens=negative_txt_seq_lens,
1030
+ attention_kwargs=self.attention_kwargs,
1031
+ return_dict=False,
1032
+ )[0]
1033
+ neg_noise_pred = neg_noise_pred[:, : latents.size(1)]
1034
+ comb_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
1035
+
1036
+ cond_norm = torch.norm(noise_pred, dim=-1, keepdim=True)
1037
+ noise_norm = torch.norm(comb_pred, dim=-1, keepdim=True)
1038
+ noise_pred = comb_pred * (cond_norm / noise_norm)
1039
+
1040
+ # compute the previous noisy sample x_t -> x_t-1
1041
+ latents_dtype = latents.dtype
1042
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
1043
+
1044
+ # for 64 channel transformer only.
1045
+ init_latents_proper = image_latents
1046
+ init_mask = mask
1047
+
1048
+ if i < len(timesteps) - 1:
1049
+ noise_timestep = timesteps[i + 1]
1050
+ init_latents_proper = self.scheduler.scale_noise(
1051
+ init_latents_proper, torch.tensor([noise_timestep]), noise
1052
+ )
1053
+
1054
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1055
+
1056
+ if latents.dtype != latents_dtype:
1057
+ if torch.backends.mps.is_available():
1058
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1059
+ latents = latents.to(latents_dtype)
1060
+
1061
+ if callback_on_step_end is not None:
1062
+ callback_kwargs = {}
1063
+ for k in callback_on_step_end_tensor_inputs:
1064
+ callback_kwargs[k] = locals()[k]
1065
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1066
+
1067
+ latents = callback_outputs.pop("latents", latents)
1068
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1069
+
1070
+ # call the callback, if provided
1071
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1072
+ progress_bar.update()
1073
+
1074
+ if XLA_AVAILABLE:
1075
+ xm.mark_step()
1076
+
1077
+ self._current_timestep = None
1078
+ if output_type == "latent":
1079
+ image = latents
1080
+ else:
1081
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
1082
+ latents = latents.to(self.vae.dtype)
1083
+ latents_mean = (
1084
+ torch.tensor(self.vae.config.latents_mean)
1085
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
1086
+ .to(latents.device, latents.dtype)
1087
+ )
1088
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
1089
+ latents.device, latents.dtype
1090
+ )
1091
+ latents = latents / latents_std + latents_mean
1092
+ image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
1093
+ image = self.image_processor.postprocess(image, output_type=output_type)
1094
+
1095
+ if padding_mask_crop is not None:
1096
+ image = [
1097
+ self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image
1098
+ ]
1099
+
1100
+ # Offload all models
1101
+ self.maybe_free_model_hooks()
1102
+
1103
+ if not return_dict:
1104
+ return (image,)
1105
+
1106
+ return QwenImagePipelineOutput(images=image)
qwenimage/qwen_fa3_processor.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Paired with a good language model. Thanks!
3
+ """
4
+
5
+ import torch
6
+ from typing import Optional, Tuple
7
+ from diffusers.models.transformers.transformer_qwenimage import apply_rotary_emb_qwen
8
+
9
+ try:
10
+ from kernels import get_kernel
11
+ _k = get_kernel("kernels-community/vllm-flash-attn3")
12
+ _flash_attn_func = _k.flash_attn_func
13
+ except Exception as e:
14
+ _flash_attn_func = None
15
+ _kernels_err = e
16
+
17
+
18
+ def _ensure_fa3_available():
19
+ if _flash_attn_func is None:
20
+ raise ImportError(
21
+ "FlashAttention-3 via Hugging Face `kernels` is required. "
22
+ "Tried `get_kernel('kernels-community/vllm-flash-attn3')` and failed with:\n"
23
+ f"{_kernels_err}"
24
+ )
25
+
26
+ @torch.library.custom_op("flash::flash_attn_func", mutates_args=())
27
+ def flash_attn_func(
28
+ q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, causal: bool = False
29
+ ) -> torch.Tensor:
30
+ outputs, lse = _flash_attn_func(q, k, v, causal=causal)
31
+ return outputs
32
+
33
+ @flash_attn_func.register_fake
34
+ def _(q, k, v, **kwargs):
35
+ # two outputs:
36
+ # 1. output: (batch, seq_len, num_heads, head_dim)
37
+ # 2. softmax_lse: (batch, num_heads, seq_len) with dtype=torch.float32
38
+ meta_q = torch.empty_like(q).contiguous()
39
+ return meta_q #, q.new_empty((q.size(0), q.size(2), q.size(1)), dtype=torch.float32)
40
+
41
+
42
+ class QwenDoubleStreamAttnProcessorFA3:
43
+ """
44
+ FA3-based attention processor for Qwen double-stream architecture.
45
+ Computes joint attention over concatenated [text, image] streams using vLLM FlashAttention-3
46
+ accessed via Hugging Face `kernels`.
47
+
48
+ Notes / limitations:
49
+ - General attention masks are not supported here (FA3 path). `is_causal=False` and no arbitrary mask.
50
+ - Optional windowed attention / sink tokens / softcap can be plumbed through if you use those features.
51
+ - Expects an available `apply_rotary_emb_qwen` in scope (same as your non-FA3 processor).
52
+ """
53
+
54
+ _attention_backend = "fa3" # for parity with your other processors, not used internally
55
+
56
+ def __init__(self):
57
+ _ensure_fa3_available()
58
+
59
+ @torch.no_grad()
60
+ def __call__(
61
+ self,
62
+ attn, # Attention module with to_q/to_k/to_v/add_*_proj, norms, to_out, to_add_out, and .heads
63
+ hidden_states: torch.FloatTensor, # (B, S_img, D_model) image stream
64
+ encoder_hidden_states: torch.FloatTensor = None, # (B, S_txt, D_model) text stream
65
+ encoder_hidden_states_mask: torch.FloatTensor = None, # unused in FA3 path
66
+ attention_mask: Optional[torch.FloatTensor] = None, # unused in FA3 path
67
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # (img_freqs, txt_freqs)
68
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
69
+ if encoder_hidden_states is None:
70
+ raise ValueError("QwenDoubleStreamAttnProcessorFA3 requires encoder_hidden_states (text stream).")
71
+ if attention_mask is not None:
72
+ # FA3 kernel path here does not consume arbitrary masks; fail fast to avoid silent correctness issues.
73
+ raise NotImplementedError("attention_mask is not supported in this FA3 implementation.")
74
+
75
+ _ensure_fa3_available()
76
+
77
+ B, S_img, _ = hidden_states.shape
78
+ S_txt = encoder_hidden_states.shape[1]
79
+
80
+ # ---- QKV projections (image/sample stream) ----
81
+ img_q = attn.to_q(hidden_states) # (B, S_img, D)
82
+ img_k = attn.to_k(hidden_states)
83
+ img_v = attn.to_v(hidden_states)
84
+
85
+ # ---- QKV projections (text/context stream) ----
86
+ txt_q = attn.add_q_proj(encoder_hidden_states) # (B, S_txt, D)
87
+ txt_k = attn.add_k_proj(encoder_hidden_states)
88
+ txt_v = attn.add_v_proj(encoder_hidden_states)
89
+
90
+ # ---- Reshape to (B, S, H, D_h) ----
91
+ H = attn.heads
92
+ img_q = img_q.unflatten(-1, (H, -1))
93
+ img_k = img_k.unflatten(-1, (H, -1))
94
+ img_v = img_v.unflatten(-1, (H, -1))
95
+
96
+ txt_q = txt_q.unflatten(-1, (H, -1))
97
+ txt_k = txt_k.unflatten(-1, (H, -1))
98
+ txt_v = txt_v.unflatten(-1, (H, -1))
99
+
100
+ # ---- Q/K normalization (per your module contract) ----
101
+ if getattr(attn, "norm_q", None) is not None:
102
+ img_q = attn.norm_q(img_q)
103
+ if getattr(attn, "norm_k", None) is not None:
104
+ img_k = attn.norm_k(img_k)
105
+ if getattr(attn, "norm_added_q", None) is not None:
106
+ txt_q = attn.norm_added_q(txt_q)
107
+ if getattr(attn, "norm_added_k", None) is not None:
108
+ txt_k = attn.norm_added_k(txt_k)
109
+
110
+ # ---- RoPE (Qwen variant) ----
111
+ if image_rotary_emb is not None:
112
+ img_freqs, txt_freqs = image_rotary_emb
113
+ # expects tensors shaped (B, S, H, D_h)
114
+ img_q = apply_rotary_emb_qwen(img_q, img_freqs, use_real=False)
115
+ img_k = apply_rotary_emb_qwen(img_k, img_freqs, use_real=False)
116
+ txt_q = apply_rotary_emb_qwen(txt_q, txt_freqs, use_real=False)
117
+ txt_k = apply_rotary_emb_qwen(txt_k, txt_freqs, use_real=False)
118
+
119
+ # ---- Joint attention over [text, image] along sequence axis ----
120
+ # Shapes: (B, S_total, H, D_h)
121
+ q = torch.cat([txt_q, img_q], dim=1)
122
+ k = torch.cat([txt_k, img_k], dim=1)
123
+ v = torch.cat([txt_v, img_v], dim=1)
124
+
125
+ # FlashAttention-3 path expects (B, S, H, D_h) and returns (out, softmax_lse)
126
+ out = flash_attn_func(q, k, v, causal=False) # out: (B, S_total, H, D_h)
127
+
128
+ # ---- Back to (B, S, D_model) ----
129
+ out = out.flatten(2, 3).to(q.dtype)
130
+
131
+ # Split back to text / image segments
132
+ txt_attn_out = out[:, :S_txt, :]
133
+ img_attn_out = out[:, S_txt:, :]
134
+
135
+ # ---- Output projections ----
136
+ img_attn_out = attn.to_out[0](img_attn_out)
137
+ if len(attn.to_out) > 1:
138
+ img_attn_out = attn.to_out[1](img_attn_out) # dropout if present
139
+
140
+ txt_attn_out = attn.to_add_out(txt_attn_out)
141
+
142
+ return img_attn_out, txt_attn_out
qwenimage/transformer_qwenimage.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Qwen-Image Team, 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 functools
16
+ import math
17
+ from typing import Any, Dict, List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
25
+ from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
26
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
27
+ from diffusers.models.attention import FeedForward, AttentionMixin
28
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
29
+ from diffusers.models.attention_processor import Attention
30
+ from diffusers.models.cache_utils import CacheMixin
31
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
32
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
33
+ from diffusers.models.modeling_utils import ModelMixin
34
+ from diffusers.models.normalization import AdaLayerNormContinuous, RMSNorm
35
+
36
+
37
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
+
39
+
40
+ def get_timestep_embedding(
41
+ timesteps: torch.Tensor,
42
+ embedding_dim: int,
43
+ flip_sin_to_cos: bool = False,
44
+ downscale_freq_shift: float = 1,
45
+ scale: float = 1,
46
+ max_period: int = 10000,
47
+ ) -> torch.Tensor:
48
+ """
49
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
50
+
51
+ Args
52
+ timesteps (torch.Tensor):
53
+ a 1-D Tensor of N indices, one per batch element. These may be fractional.
54
+ embedding_dim (int):
55
+ the dimension of the output.
56
+ flip_sin_to_cos (bool):
57
+ Whether the embedding order should be `cos, sin` (if True) or `sin, cos` (if False)
58
+ downscale_freq_shift (float):
59
+ Controls the delta between frequencies between dimensions
60
+ scale (float):
61
+ Scaling factor applied to the embeddings.
62
+ max_period (int):
63
+ Controls the maximum frequency of the embeddings
64
+ Returns
65
+ torch.Tensor: an [N x dim] Tensor of positional embeddings.
66
+ """
67
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
68
+
69
+ half_dim = embedding_dim // 2
70
+ exponent = -math.log(max_period) * torch.arange(
71
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
72
+ )
73
+ exponent = exponent / (half_dim - downscale_freq_shift)
74
+
75
+ emb = torch.exp(exponent).to(timesteps.dtype)
76
+ emb = timesteps[:, None].float() * emb[None, :]
77
+
78
+ # scale embeddings
79
+ emb = scale * emb
80
+
81
+ # concat sine and cosine embeddings
82
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
83
+
84
+ # flip sine and cosine embeddings
85
+ if flip_sin_to_cos:
86
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
87
+
88
+ # zero pad
89
+ if embedding_dim % 2 == 1:
90
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
91
+ return emb
92
+
93
+
94
+ def apply_rotary_emb_qwen(
95
+ x: torch.Tensor,
96
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
97
+ use_real: bool = True,
98
+ use_real_unbind_dim: int = -1,
99
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
100
+ """
101
+ Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings
102
+ to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are
103
+ reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting
104
+ tensors contain rotary embeddings and are returned as real tensors.
105
+
106
+ Args:
107
+ x (`torch.Tensor`):
108
+ Query or key tensor to apply rotary embeddings. [B, S, H, D] xk (torch.Tensor): Key tensor to apply
109
+ freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],)
110
+
111
+ Returns:
112
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
113
+ """
114
+ if use_real:
115
+ cos, sin = freqs_cis # [S, D]
116
+ cos = cos[None, None]
117
+ sin = sin[None, None]
118
+ cos, sin = cos.to(x.device), sin.to(x.device)
119
+
120
+ if use_real_unbind_dim == -1:
121
+ # Used for flux, cogvideox, hunyuan-dit
122
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
123
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
124
+ elif use_real_unbind_dim == -2:
125
+ # Used for Stable Audio, OmniGen, CogView4 and Cosmos
126
+ x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2) # [B, S, H, D//2]
127
+ x_rotated = torch.cat([-x_imag, x_real], dim=-1)
128
+ else:
129
+ raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.")
130
+
131
+ out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
132
+
133
+ return out
134
+ else:
135
+ x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
136
+ freqs_cis = freqs_cis.unsqueeze(1)
137
+ x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3)
138
+
139
+ return x_out.type_as(x)
140
+
141
+
142
+ class QwenTimestepProjEmbeddings(nn.Module):
143
+ def __init__(self, embedding_dim):
144
+ super().__init__()
145
+
146
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0, scale=1000)
147
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
148
+
149
+ def forward(self, timestep, hidden_states):
150
+ timesteps_proj = self.time_proj(timestep)
151
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_states.dtype)) # (N, D)
152
+
153
+ conditioning = timesteps_emb
154
+
155
+ return conditioning
156
+
157
+
158
+ class QwenEmbedRope(nn.Module):
159
+ def __init__(self, theta: int, axes_dim: List[int], scale_rope=False):
160
+ super().__init__()
161
+ self.theta = theta
162
+ self.axes_dim = axes_dim
163
+ pos_index = torch.arange(4096)
164
+ neg_index = torch.arange(4096).flip(0) * -1 - 1
165
+ self.pos_freqs = torch.cat(
166
+ [
167
+ self.rope_params(pos_index, self.axes_dim[0], self.theta),
168
+ self.rope_params(pos_index, self.axes_dim[1], self.theta),
169
+ self.rope_params(pos_index, self.axes_dim[2], self.theta),
170
+ ],
171
+ dim=1,
172
+ )
173
+ self.neg_freqs = torch.cat(
174
+ [
175
+ self.rope_params(neg_index, self.axes_dim[0], self.theta),
176
+ self.rope_params(neg_index, self.axes_dim[1], self.theta),
177
+ self.rope_params(neg_index, self.axes_dim[2], self.theta),
178
+ ],
179
+ dim=1,
180
+ )
181
+ self.rope_cache = {}
182
+
183
+ # DO NOT USING REGISTER BUFFER HERE, IT WILL CAUSE COMPLEX NUMBERS LOSE ITS IMAGINARY PART
184
+ self.scale_rope = scale_rope
185
+
186
+ def rope_params(self, index, dim, theta=10000):
187
+ """
188
+ Args:
189
+ index: [0, 1, 2, 3] 1D Tensor representing the position index of the token
190
+ """
191
+ assert dim % 2 == 0
192
+ freqs = torch.outer(index, 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float32).div(dim)))
193
+ freqs = torch.polar(torch.ones_like(freqs), freqs)
194
+ return freqs
195
+
196
+ def forward(self, video_fhw, txt_seq_lens, device):
197
+ """
198
+ Args: video_fhw: [frame, height, width] a list of 3 integers representing the shape of the video Args:
199
+ txt_length: [bs] a list of 1 integers representing the length of the text
200
+ """
201
+ if self.pos_freqs.device != device:
202
+ self.pos_freqs = self.pos_freqs.to(device)
203
+ self.neg_freqs = self.neg_freqs.to(device)
204
+
205
+ if isinstance(video_fhw, list):
206
+ video_fhw = video_fhw[0]
207
+ if not isinstance(video_fhw, list):
208
+ video_fhw = [video_fhw]
209
+
210
+ vid_freqs = []
211
+ max_vid_index = 0
212
+ for idx, fhw in enumerate(video_fhw):
213
+ frame, height, width = fhw
214
+ rope_key = f"{idx}_{height}_{width}"
215
+
216
+ if not torch.compiler.is_compiling():
217
+ if rope_key not in self.rope_cache:
218
+ self.rope_cache[rope_key] = self._compute_video_freqs(frame, height, width, idx)
219
+ video_freq = self.rope_cache[rope_key]
220
+ else:
221
+ video_freq = self._compute_video_freqs(frame, height, width, idx)
222
+ video_freq = video_freq.to(device)
223
+ vid_freqs.append(video_freq)
224
+
225
+ if self.scale_rope:
226
+ max_vid_index = max(height // 2, width // 2, max_vid_index)
227
+ else:
228
+ max_vid_index = max(height, width, max_vid_index)
229
+
230
+ max_len = max(txt_seq_lens)
231
+ txt_freqs = self.pos_freqs[max_vid_index : max_vid_index + max_len, ...]
232
+ vid_freqs = torch.cat(vid_freqs, dim=0)
233
+
234
+ return vid_freqs, txt_freqs
235
+
236
+ @functools.lru_cache(maxsize=None)
237
+ def _compute_video_freqs(self, frame, height, width, idx=0):
238
+ seq_lens = frame * height * width
239
+ freqs_pos = self.pos_freqs.split([x // 2 for x in self.axes_dim], dim=1)
240
+ freqs_neg = self.neg_freqs.split([x // 2 for x in self.axes_dim], dim=1)
241
+
242
+ freqs_frame = freqs_pos[0][idx : idx + frame].view(frame, 1, 1, -1).expand(frame, height, width, -1)
243
+ if self.scale_rope:
244
+ freqs_height = torch.cat([freqs_neg[1][-(height - height // 2) :], freqs_pos[1][: height // 2]], dim=0)
245
+ freqs_height = freqs_height.view(1, height, 1, -1).expand(frame, height, width, -1)
246
+ freqs_width = torch.cat([freqs_neg[2][-(width - width // 2) :], freqs_pos[2][: width // 2]], dim=0)
247
+ freqs_width = freqs_width.view(1, 1, width, -1).expand(frame, height, width, -1)
248
+ else:
249
+ freqs_height = freqs_pos[1][:height].view(1, height, 1, -1).expand(frame, height, width, -1)
250
+ freqs_width = freqs_pos[2][:width].view(1, 1, width, -1).expand(frame, height, width, -1)
251
+
252
+ freqs = torch.cat([freqs_frame, freqs_height, freqs_width], dim=-1).reshape(seq_lens, -1)
253
+ return freqs.clone().contiguous()
254
+
255
+
256
+ class QwenDoubleStreamAttnProcessor2_0:
257
+ """
258
+ Attention processor for Qwen double-stream architecture, matching DoubleStreamLayerMegatron logic. This processor
259
+ implements joint attention computation where text and image streams are processed together.
260
+ """
261
+
262
+ _attention_backend = None
263
+
264
+ def __init__(self):
265
+ if not hasattr(F, "scaled_dot_product_attention"):
266
+ raise ImportError(
267
+ "QwenDoubleStreamAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
268
+ )
269
+
270
+ def __call__(
271
+ self,
272
+ attn: Attention,
273
+ hidden_states: torch.FloatTensor, # Image stream
274
+ encoder_hidden_states: torch.FloatTensor = None, # Text stream
275
+ encoder_hidden_states_mask: torch.FloatTensor = None,
276
+ attention_mask: Optional[torch.FloatTensor] = None,
277
+ image_rotary_emb: Optional[torch.Tensor] = None,
278
+ ) -> torch.FloatTensor:
279
+ if encoder_hidden_states is None:
280
+ raise ValueError("QwenDoubleStreamAttnProcessor2_0 requires encoder_hidden_states (text stream)")
281
+
282
+ seq_txt = encoder_hidden_states.shape[1]
283
+
284
+ # Compute QKV for image stream (sample projections)
285
+ img_query = attn.to_q(hidden_states)
286
+ img_key = attn.to_k(hidden_states)
287
+ img_value = attn.to_v(hidden_states)
288
+
289
+ # Compute QKV for text stream (context projections)
290
+ txt_query = attn.add_q_proj(encoder_hidden_states)
291
+ txt_key = attn.add_k_proj(encoder_hidden_states)
292
+ txt_value = attn.add_v_proj(encoder_hidden_states)
293
+
294
+ # Reshape for multi-head attention
295
+ img_query = img_query.unflatten(-1, (attn.heads, -1))
296
+ img_key = img_key.unflatten(-1, (attn.heads, -1))
297
+ img_value = img_value.unflatten(-1, (attn.heads, -1))
298
+
299
+ txt_query = txt_query.unflatten(-1, (attn.heads, -1))
300
+ txt_key = txt_key.unflatten(-1, (attn.heads, -1))
301
+ txt_value = txt_value.unflatten(-1, (attn.heads, -1))
302
+
303
+ # Apply QK normalization
304
+ if attn.norm_q is not None:
305
+ img_query = attn.norm_q(img_query)
306
+ if attn.norm_k is not None:
307
+ img_key = attn.norm_k(img_key)
308
+ if attn.norm_added_q is not None:
309
+ txt_query = attn.norm_added_q(txt_query)
310
+ if attn.norm_added_k is not None:
311
+ txt_key = attn.norm_added_k(txt_key)
312
+
313
+ # Apply RoPE
314
+ if image_rotary_emb is not None:
315
+ img_freqs, txt_freqs = image_rotary_emb
316
+ img_query = apply_rotary_emb_qwen(img_query, img_freqs, use_real=False)
317
+ img_key = apply_rotary_emb_qwen(img_key, img_freqs, use_real=False)
318
+ txt_query = apply_rotary_emb_qwen(txt_query, txt_freqs, use_real=False)
319
+ txt_key = apply_rotary_emb_qwen(txt_key, txt_freqs, use_real=False)
320
+
321
+ # Concatenate for joint attention
322
+ # Order: [text, image]
323
+ joint_query = torch.cat([txt_query, img_query], dim=1)
324
+ joint_key = torch.cat([txt_key, img_key], dim=1)
325
+ joint_value = torch.cat([txt_value, img_value], dim=1)
326
+
327
+ # Compute joint attention
328
+ joint_hidden_states = dispatch_attention_fn(
329
+ joint_query,
330
+ joint_key,
331
+ joint_value,
332
+ attn_mask=attention_mask,
333
+ dropout_p=0.0,
334
+ is_causal=False,
335
+ backend=self._attention_backend,
336
+ )
337
+
338
+ # Reshape back
339
+ joint_hidden_states = joint_hidden_states.flatten(2, 3)
340
+ joint_hidden_states = joint_hidden_states.to(joint_query.dtype)
341
+
342
+ # Split attention outputs back
343
+ txt_attn_output = joint_hidden_states[:, :seq_txt, :] # Text part
344
+ img_attn_output = joint_hidden_states[:, seq_txt:, :] # Image part
345
+
346
+ # Apply output projections
347
+ img_attn_output = attn.to_out[0](img_attn_output)
348
+ if len(attn.to_out) > 1:
349
+ img_attn_output = attn.to_out[1](img_attn_output) # dropout
350
+
351
+ txt_attn_output = attn.to_add_out(txt_attn_output)
352
+
353
+ return img_attn_output, txt_attn_output
354
+
355
+
356
+ @maybe_allow_in_graph
357
+ class QwenImageTransformerBlock(nn.Module):
358
+ def __init__(
359
+ self, dim: int, num_attention_heads: int, attention_head_dim: int, qk_norm: str = "rms_norm", eps: float = 1e-6
360
+ ):
361
+ super().__init__()
362
+
363
+ self.dim = dim
364
+ self.num_attention_heads = num_attention_heads
365
+ self.attention_head_dim = attention_head_dim
366
+
367
+ # Image processing modules
368
+ self.img_mod = nn.Sequential(
369
+ nn.SiLU(),
370
+ nn.Linear(dim, 6 * dim, bias=True), # For scale, shift, gate for norm1 and norm2
371
+ )
372
+ self.img_norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
373
+ self.attn = Attention(
374
+ query_dim=dim,
375
+ cross_attention_dim=None, # Enable cross attention for joint computation
376
+ added_kv_proj_dim=dim, # Enable added KV projections for text stream
377
+ dim_head=attention_head_dim,
378
+ heads=num_attention_heads,
379
+ out_dim=dim,
380
+ context_pre_only=False,
381
+ bias=True,
382
+ processor=QwenDoubleStreamAttnProcessor2_0(),
383
+ qk_norm=qk_norm,
384
+ eps=eps,
385
+ )
386
+ self.img_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
387
+ self.img_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
388
+
389
+ # Text processing modules
390
+ self.txt_mod = nn.Sequential(
391
+ nn.SiLU(),
392
+ nn.Linear(dim, 6 * dim, bias=True), # For scale, shift, gate for norm1 and norm2
393
+ )
394
+ self.txt_norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
395
+ # Text doesn't need separate attention - it's handled by img_attn joint computation
396
+ self.txt_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
397
+ self.txt_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
398
+
399
+ def _modulate(self, x, mod_params):
400
+ """Apply modulation to input tensor"""
401
+ shift, scale, gate = mod_params.chunk(3, dim=-1)
402
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1), gate.unsqueeze(1)
403
+
404
+ def forward(
405
+ self,
406
+ hidden_states: torch.Tensor,
407
+ encoder_hidden_states: torch.Tensor,
408
+ encoder_hidden_states_mask: torch.Tensor,
409
+ temb: torch.Tensor,
410
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
411
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
412
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
413
+ # Get modulation parameters for both streams
414
+ img_mod_params = self.img_mod(temb) # [B, 6*dim]
415
+ txt_mod_params = self.txt_mod(temb) # [B, 6*dim]
416
+
417
+ # Split modulation parameters for norm1 and norm2
418
+ img_mod1, img_mod2 = img_mod_params.chunk(2, dim=-1) # Each [B, 3*dim]
419
+ txt_mod1, txt_mod2 = txt_mod_params.chunk(2, dim=-1) # Each [B, 3*dim]
420
+
421
+ # Process image stream - norm1 + modulation
422
+ img_normed = self.img_norm1(hidden_states)
423
+ img_modulated, img_gate1 = self._modulate(img_normed, img_mod1)
424
+
425
+ # Process text stream - norm1 + modulation
426
+ txt_normed = self.txt_norm1(encoder_hidden_states)
427
+ txt_modulated, txt_gate1 = self._modulate(txt_normed, txt_mod1)
428
+
429
+ # Use QwenAttnProcessor2_0 for joint attention computation
430
+ # This directly implements the DoubleStreamLayerMegatron logic:
431
+ # 1. Computes QKV for both streams
432
+ # 2. Applies QK normalization and RoPE
433
+ # 3. Concatenates and runs joint attention
434
+ # 4. Splits results back to separate streams
435
+ joint_attention_kwargs = joint_attention_kwargs or {}
436
+ attn_output = self.attn(
437
+ hidden_states=img_modulated, # Image stream (will be processed as "sample")
438
+ encoder_hidden_states=txt_modulated, # Text stream (will be processed as "context")
439
+ encoder_hidden_states_mask=encoder_hidden_states_mask,
440
+ image_rotary_emb=image_rotary_emb,
441
+ **joint_attention_kwargs,
442
+ )
443
+
444
+ # QwenAttnProcessor2_0 returns (img_output, txt_output) when encoder_hidden_states is provided
445
+ img_attn_output, txt_attn_output = attn_output
446
+
447
+ # Apply attention gates and add residual (like in Megatron)
448
+ hidden_states = hidden_states + img_gate1 * img_attn_output
449
+ encoder_hidden_states = encoder_hidden_states + txt_gate1 * txt_attn_output
450
+
451
+ # Process image stream - norm2 + MLP
452
+ img_normed2 = self.img_norm2(hidden_states)
453
+ img_modulated2, img_gate2 = self._modulate(img_normed2, img_mod2)
454
+ img_mlp_output = self.img_mlp(img_modulated2)
455
+ hidden_states = hidden_states + img_gate2 * img_mlp_output
456
+
457
+ # Process text stream - norm2 + MLP
458
+ txt_normed2 = self.txt_norm2(encoder_hidden_states)
459
+ txt_modulated2, txt_gate2 = self._modulate(txt_normed2, txt_mod2)
460
+ txt_mlp_output = self.txt_mlp(txt_modulated2)
461
+ encoder_hidden_states = encoder_hidden_states + txt_gate2 * txt_mlp_output
462
+
463
+ # Clip to prevent overflow for fp16
464
+ if encoder_hidden_states.dtype == torch.float16:
465
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
466
+ if hidden_states.dtype == torch.float16:
467
+ hidden_states = hidden_states.clip(-65504, 65504)
468
+
469
+ return encoder_hidden_states, hidden_states
470
+
471
+
472
+ class QwenImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin):
473
+ """
474
+ The Transformer model introduced in Qwen.
475
+
476
+ Args:
477
+ patch_size (`int`, defaults to `2`):
478
+ Patch size to turn the input data into small patches.
479
+ in_channels (`int`, defaults to `64`):
480
+ The number of channels in the input.
481
+ out_channels (`int`, *optional*, defaults to `None`):
482
+ The number of channels in the output. If not specified, it defaults to `in_channels`.
483
+ num_layers (`int`, defaults to `60`):
484
+ The number of layers of dual stream DiT blocks to use.
485
+ attention_head_dim (`int`, defaults to `128`):
486
+ The number of dimensions to use for each attention head.
487
+ num_attention_heads (`int`, defaults to `24`):
488
+ The number of attention heads to use.
489
+ joint_attention_dim (`int`, defaults to `3584`):
490
+ The number of dimensions to use for the joint attention (embedding/channel dimension of
491
+ `encoder_hidden_states`).
492
+ guidance_embeds (`bool`, defaults to `False`):
493
+ Whether to use guidance embeddings for guidance-distilled variant of the model.
494
+ axes_dims_rope (`Tuple[int]`, defaults to `(16, 56, 56)`):
495
+ The dimensions to use for the rotary positional embeddings.
496
+ """
497
+
498
+ _supports_gradient_checkpointing = True
499
+ _no_split_modules = ["QwenImageTransformerBlock"]
500
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
501
+ _repeated_blocks = ["QwenImageTransformerBlock"]
502
+
503
+ @register_to_config
504
+ def __init__(
505
+ self,
506
+ patch_size: int = 2,
507
+ in_channels: int = 64,
508
+ out_channels: Optional[int] = 16,
509
+ num_layers: int = 60,
510
+ attention_head_dim: int = 128,
511
+ num_attention_heads: int = 24,
512
+ joint_attention_dim: int = 3584,
513
+ guidance_embeds: bool = False, # TODO: this should probably be removed
514
+ axes_dims_rope: Tuple[int, int, int] = (16, 56, 56),
515
+ ):
516
+ super().__init__()
517
+ self.out_channels = out_channels or in_channels
518
+ self.inner_dim = num_attention_heads * attention_head_dim
519
+
520
+ self.pos_embed = QwenEmbedRope(theta=10000, axes_dim=list(axes_dims_rope), scale_rope=True)
521
+
522
+ self.time_text_embed = QwenTimestepProjEmbeddings(embedding_dim=self.inner_dim)
523
+
524
+ self.txt_norm = RMSNorm(joint_attention_dim, eps=1e-6)
525
+
526
+ self.img_in = nn.Linear(in_channels, self.inner_dim)
527
+ self.txt_in = nn.Linear(joint_attention_dim, self.inner_dim)
528
+
529
+ self.transformer_blocks = nn.ModuleList(
530
+ [
531
+ QwenImageTransformerBlock(
532
+ dim=self.inner_dim,
533
+ num_attention_heads=num_attention_heads,
534
+ attention_head_dim=attention_head_dim,
535
+ )
536
+ for _ in range(num_layers)
537
+ ]
538
+ )
539
+
540
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
541
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
542
+
543
+ self.gradient_checkpointing = False
544
+
545
+ def forward(
546
+ self,
547
+ hidden_states: torch.Tensor,
548
+ encoder_hidden_states: torch.Tensor = None,
549
+ encoder_hidden_states_mask: torch.Tensor = None,
550
+ timestep: torch.LongTensor = None,
551
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
552
+ guidance: torch.Tensor = None, # TODO: this should probably be removed
553
+ attention_kwargs: Optional[Dict[str, Any]] = None,
554
+ return_dict: bool = True,
555
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
556
+ """
557
+ The [`QwenTransformer2DModel`] forward method.
558
+
559
+ Args:
560
+ hidden_states (`torch.Tensor` of shape `(batch_size, image_sequence_length, in_channels)`):
561
+ Input `hidden_states`.
562
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, text_sequence_length, joint_attention_dim)`):
563
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
564
+ encoder_hidden_states_mask (`torch.Tensor` of shape `(batch_size, text_sequence_length)`):
565
+ Mask of the input conditions.
566
+ timestep ( `torch.LongTensor`):
567
+ Used to indicate denoising step.
568
+ attention_kwargs (`dict`, *optional*):
569
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
570
+ `self.processor` in
571
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
572
+ return_dict (`bool`, *optional*, defaults to `True`):
573
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
574
+ tuple.
575
+
576
+ Returns:
577
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
578
+ `tuple` where the first element is the sample tensor.
579
+ """
580
+ if attention_kwargs is not None:
581
+ attention_kwargs = attention_kwargs.copy()
582
+ lora_scale = attention_kwargs.pop("scale", 1.0)
583
+ else:
584
+ lora_scale = 1.0
585
+
586
+ if USE_PEFT_BACKEND:
587
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
588
+ scale_lora_layers(self, lora_scale)
589
+ else:
590
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
591
+ logger.warning(
592
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
593
+ )
594
+
595
+ hidden_states = self.img_in(hidden_states)
596
+
597
+ timestep = timestep.to(hidden_states.dtype)
598
+ encoder_hidden_states = self.txt_norm(encoder_hidden_states)
599
+ encoder_hidden_states = self.txt_in(encoder_hidden_states)
600
+
601
+ if guidance is not None:
602
+ guidance = guidance.to(hidden_states.dtype) * 1000
603
+
604
+ temb = (
605
+ self.time_text_embed(timestep, hidden_states)
606
+ if guidance is None
607
+ else self.time_text_embed(timestep, guidance, hidden_states)
608
+ )
609
+
610
+ for index_block, block in enumerate(self.transformer_blocks):
611
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
612
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
613
+ block,
614
+ hidden_states,
615
+ encoder_hidden_states,
616
+ encoder_hidden_states_mask,
617
+ temb,
618
+ image_rotary_emb,
619
+ )
620
+
621
+ else:
622
+ encoder_hidden_states, hidden_states = block(
623
+ hidden_states=hidden_states,
624
+ encoder_hidden_states=encoder_hidden_states,
625
+ encoder_hidden_states_mask=encoder_hidden_states_mask,
626
+ temb=temb,
627
+ image_rotary_emb=image_rotary_emb,
628
+ joint_attention_kwargs=attention_kwargs,
629
+ )
630
+
631
+ # Use only the image part (hidden_states) from the dual-stream blocks
632
+ hidden_states = self.norm_out(hidden_states, temb)
633
+ output = self.proj_out(hidden_states)
634
+
635
+ if USE_PEFT_BACKEND:
636
+ # remove `lora_scale` from each PEFT layer
637
+ unscale_lora_layers(self, lora_scale)
638
+
639
+ if not return_dict:
640
+ return (output,)
641
+
642
+ return Transformer2DModelOutput(sample=output)
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
- git+https://github.com/huggingface/diffusers.git@main
2
  kernels
3
  torchao==0.11.0
4
  transformers
 
1
+ git+https://github.com/huggingface/diffusers.git@qwenimage-lru-cache-bypass
2
  kernels
3
  torchao==0.11.0
4
  transformers