bep40 commited on
Commit
4da7422
·
verified ·
1 Parent(s): 146a974

Add transformer_qwenimage.py

Browse files
Files changed (1) hide show
  1. qwenimage/transformer_qwenimage.py +3 -642
qwenimage/transformer_qwenimage.py CHANGED
@@ -1,642 +1,3 @@
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)
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8aa45a4f3d58d4b83dc64f1adc3e870c3f6e359145e8893d16348d30633e06dd
3
+ size 27689