bep40 commited on
Commit
6b1ff6f
·
verified ·
1 Parent(s): 222a449

Upload qwenimage/transformer_qwenimage.py

Browse files
Files changed (1) hide show
  1. qwenimage/transformer_qwenimage.py +361 -0
qwenimage/transformer_qwenimage.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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__)
38
+
39
+
40
+ def get_timestep_embedding(
41
+ timesteps: torch.Tensor, embedding_dim: int,
42
+ flip_sin_to_cos: bool = False, downscale_freq_shift: float = 1,
43
+ scale: float = 1, max_period: int = 10000,
44
+ ) -> torch.Tensor:
45
+ """Create sinusoidal timestep embeddings."""
46
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
47
+ half_dim = embedding_dim // 2
48
+ exponent = -math.log(max_period) * torch.arange(
49
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
50
+ )
51
+ exponent = exponent / (half_dim - downscale_freq_shift)
52
+ emb = torch.exp(exponent).to(timesteps.dtype)
53
+ emb = timesteps[:, None].float() * emb[None, :]
54
+ emb = scale * emb
55
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
56
+ if flip_sin_to_cos:
57
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
58
+ if embedding_dim % 2 == 1:
59
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
60
+ return emb
61
+
62
+
63
+ def apply_rotary_emb_qwen(
64
+ x: torch.Tensor, freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
65
+ use_real: bool = True, use_real_unbind_dim: int = -1,
66
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
67
+ """Apply rotary embeddings to input tensors using the given frequency tensor."""
68
+ if use_real:
69
+ cos, sin = freqs_cis
70
+ cos = cos[None, None]
71
+ sin = sin[None, None]
72
+ cos, sin = cos.to(x.device), sin.to(x.device)
73
+ if use_real_unbind_dim == -1:
74
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1)
75
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
76
+ elif use_real_unbind_dim == -2:
77
+ x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2)
78
+ x_rotated = torch.cat([-x_imag, x_real], dim=-1)
79
+ else:
80
+ raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.")
81
+ out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
82
+ return out
83
+ else:
84
+ x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
85
+ freqs_cis = freqs_cis.unsqueeze(1)
86
+ x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3)
87
+ return x_out.type_as(x)
88
+
89
+
90
+ class QwenTimestepProjEmbeddings(nn.Module):
91
+ def __init__(self, embedding_dim):
92
+ super().__init__()
93
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0, scale=1000)
94
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
95
+
96
+ def forward(self, timestep, hidden_states):
97
+ timesteps_proj = self.time_proj(timestep)
98
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_states.dtype))
99
+ return timesteps_emb
100
+
101
+
102
+ class QwenEmbedRope(nn.Module):
103
+ def __init__(self, theta: int, axes_dim: List[int], scale_rope=False):
104
+ super().__init__()
105
+ self.theta = theta
106
+ self.axes_dim = axes_dim
107
+ pos_index = torch.arange(4096)
108
+ neg_index = torch.arange(4096).flip(0) * -1 - 1
109
+ self.pos_freqs = torch.cat([
110
+ self.rope_params(pos_index, self.axes_dim[0], self.theta),
111
+ self.rope_params(pos_index, self.axes_dim[1], self.theta),
112
+ self.rope_params(pos_index, self.axes_dim[2], self.theta),
113
+ ], dim=1)
114
+ self.neg_freqs = torch.cat([
115
+ self.rope_params(neg_index, self.axes_dim[0], self.theta),
116
+ self.rope_params(neg_index, self.axes_dim[1], self.theta),
117
+ self.rope_params(neg_index, self.axes_dim[2], self.theta),
118
+ ], dim=1)
119
+ self.rope_cache = {}
120
+ self.scale_rope = scale_rope
121
+
122
+ def rope_params(self, index, dim, theta=10000):
123
+ assert dim % 2 == 0
124
+ freqs = torch.outer(index, 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float32).div(dim)))
125
+ freqs = torch.polar(torch.ones_like(freqs), freqs)
126
+ return freqs
127
+
128
+ def forward(self, video_fhw, txt_seq_lens, device):
129
+ if self.pos_freqs.device != device:
130
+ self.pos_freqs = self.pos_freqs.to(device)
131
+ self.neg_freqs = self.neg_freqs.to(device)
132
+ if isinstance(video_fhw, list):
133
+ video_fhw = video_fhw[0]
134
+ if not isinstance(video_fhw, list):
135
+ video_fhw = [video_fhw]
136
+ vid_freqs = []
137
+ max_vid_index = 0
138
+ for idx, fhw in enumerate(video_fhw):
139
+ frame, height, width = fhw
140
+ rope_key = f"{idx}_{height}_{width}"
141
+ if not torch.compiler.is_compiling():
142
+ if rope_key not in self.rope_cache:
143
+ self.rope_cache[rope_key] = self._compute_video_freqs(frame, height, width, idx)
144
+ video_freq = self.rope_cache[rope_key]
145
+ else:
146
+ video_freq = self._compute_video_freqs(frame, height, width, idx)
147
+ video_freq = video_freq.to(device)
148
+ vid_freqs.append(video_freq)
149
+ if self.scale_rope:
150
+ max_vid_index = max(height // 2, width // 2, max_vid_index)
151
+ else:
152
+ max_vid_index = max(height, width, max_vid_index)
153
+ max_len = max(txt_seq_lens)
154
+ txt_freqs = self.pos_freqs[max_vid_index: max_vid_index + max_len, ...]
155
+ vid_freqs = torch.cat(vid_freqs, dim=0)
156
+ return vid_freqs, txt_freqs
157
+
158
+ @functools.lru_cache(maxsize=None)
159
+ def _compute_video_freqs(self, frame, height, width, idx=0):
160
+ seq_lens = frame * height * width
161
+ freqs_pos = self.pos_freqs.split([x // 2 for x in self.axes_dim], dim=1)
162
+ freqs_neg = self.neg_freqs.split([x // 2 for x in self.axes_dim], dim=1)
163
+ freqs_frame = freqs_pos[0][idx: idx + frame].view(frame, 1, 1, -1).expand(frame, height, width, -1)
164
+ if self.scale_rope:
165
+ freqs_height = torch.cat([freqs_neg[1][-(height - height // 2):], freqs_pos[1][:height // 2]], dim=0)
166
+ freqs_height = freqs_height.view(1, height, 1, -1).expand(frame, height, width, -1)
167
+ freqs_width = torch.cat([freqs_neg[2][-(width - width // 2):], freqs_pos[2][:width // 2]], dim=0)
168
+ freqs_width = freqs_width.view(1, 1, width, -1).expand(frame, height, width, -1)
169
+ else:
170
+ freqs_height = freqs_pos[1][:height].view(1, height, 1, -1).expand(frame, height, width, -1)
171
+ freqs_width = freqs_pos[2][:width].view(1, 1, width, -1).expand(frame, height, width, -1)
172
+ freqs = torch.cat([freqs_frame, freqs_height, freqs_width], dim=-1).reshape(seq_lens, -1)
173
+ return freqs.clone().contiguous()
174
+
175
+
176
+ class QwenDoubleStreamAttnProcessor2_0:
177
+ """Attention processor for Qwen double-stream architecture."""
178
+
179
+ _attention_backend = None
180
+
181
+ def __init__(self):
182
+ if not hasattr(F, "scaled_dot_product_attention"):
183
+ raise ImportError("QwenDoubleStreamAttnProcessor2_0 requires PyTorch 2.0.")
184
+
185
+ def __call__(self, attn, hidden_states, encoder_hidden_states=None,
186
+ encoder_hidden_states_mask=None, attention_mask=None,
187
+ image_rotary_emb=None):
188
+ if encoder_hidden_states is None:
189
+ raise ValueError("QwenDoubleStreamAttnProcessor2_0 requires encoder_hidden_states (text stream)")
190
+ seq_txt = encoder_hidden_states.shape[1]
191
+ img_query = attn.to_q(hidden_states)
192
+ img_key = attn.to_k(hidden_states)
193
+ img_value = attn.to_v(hidden_states)
194
+ txt_query = attn.add_q_proj(encoder_hidden_states)
195
+ txt_key = attn.add_k_proj(encoder_hidden_states)
196
+ txt_value = attn.add_v_proj(encoder_hidden_states)
197
+ img_query = img_query.unflatten(-1, (attn.heads, -1))
198
+ img_key = img_key.unflatten(-1, (attn.heads, -1))
199
+ img_value = img_value.unflatten(-1, (attn.heads, -1))
200
+ txt_query = txt_query.unflatten(-1, (attn.heads, -1))
201
+ txt_key = txt_key.unflatten(-1, (attn.heads, -1))
202
+ txt_value = txt_value.unflatten(-1, (attn.heads, -1))
203
+ if attn.norm_q is not None:
204
+ img_query = attn.norm_q(img_query)
205
+ if attn.norm_k is not None:
206
+ img_key = attn.norm_k(img_key)
207
+ if attn.norm_added_q is not None:
208
+ txt_query = attn.norm_added_q(txt_query)
209
+ if attn.norm_added_k is not None:
210
+ txt_key = attn.norm_added_k(txt_key)
211
+ if image_rotary_emb is not None:
212
+ img_freqs, txt_freqs = image_rotary_emb
213
+ img_query = apply_rotary_emb_qwen(img_query, img_freqs, use_real=False)
214
+ img_key = apply_rotary_emb_qwen(img_key, img_freqs, use_real=False)
215
+ txt_query = apply_rotary_emb_qwen(txt_query, txt_freqs, use_real=False)
216
+ txt_key = apply_rotary_emb_qwen(txt_key, txt_freqs, use_real=False)
217
+ joint_query = torch.cat([txt_query, img_query], dim=1)
218
+ joint_key = torch.cat([txt_key, img_key], dim=1)
219
+ joint_value = torch.cat([txt_value, img_value], dim=1)
220
+ joint_hidden_states = dispatch_attention_fn(
221
+ joint_query, joint_key, joint_value,
222
+ attn_mask=attention_mask, dropout_p=0.0,
223
+ is_causal=False, backend=self._attention_backend,
224
+ )
225
+ joint_hidden_states = joint_hidden_states.flatten(2, 3)
226
+ joint_hidden_states = joint_hidden_states.to(joint_query.dtype)
227
+ txt_attn_output = joint_hidden_states[:, :seq_txt, :]
228
+ img_attn_output = joint_hidden_states[:, seq_txt:, :]
229
+ img_attn_output = attn.to_out[0](img_attn_output)
230
+ if len(attn.to_out) > 1:
231
+ img_attn_output = attn.to_out[1](img_attn_output)
232
+ txt_attn_output = attn.to_add_out(txt_attn_output)
233
+ return img_attn_output, txt_attn_output
234
+
235
+
236
+ @maybe_allow_in_graph
237
+ class QwenImageTransformerBlock(nn.Module):
238
+ def __init__(self, dim: int, num_attention_heads: int, attention_head_dim: int, qk_norm: str = "rms_norm", eps: float = 1e-6):
239
+ super().__init__()
240
+ self.dim = dim
241
+ self.num_attention_heads = num_attention_heads
242
+ self.attention_head_dim = attention_head_dim
243
+ self.img_mod = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True))
244
+ self.img_norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
245
+ self.attn = Attention(
246
+ query_dim=dim, cross_attention_dim=None, added_kv_proj_dim=dim,
247
+ dim_head=attention_head_dim, heads=num_attention_heads, out_dim=dim,
248
+ context_pre_only=False, bias=True, processor=QwenDoubleStreamAttnProcessor2_0(),
249
+ qk_norm=qk_norm, eps=eps,
250
+ )
251
+ self.img_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
252
+ self.img_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
253
+ self.txt_mod = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True))
254
+ self.txt_norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
255
+ self.txt_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
256
+ self.txt_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
257
+
258
+ def _modulate(self, x, mod_params):
259
+ shift, scale, gate = mod_params.chunk(3, dim=-1)
260
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1), gate.unsqueeze(1)
261
+
262
+ def forward(self, hidden_states, encoder_hidden_states, encoder_hidden_states_mask, temb,
263
+ image_rotary_emb=None, joint_attention_kwargs=None):
264
+ img_mod_params = self.img_mod(temb)
265
+ txt_mod_params = self.txt_mod(temb)
266
+ img_mod1, img_mod2 = img_mod_params.chunk(2, dim=-1)
267
+ txt_mod1, txt_mod2 = txt_mod_params.chunk(2, dim=-1)
268
+ img_normed = self.img_norm1(hidden_states)
269
+ img_modulated, img_gate1 = self._modulate(img_normed, img_mod1)
270
+ txt_normed = self.txt_norm1(encoder_hidden_states)
271
+ txt_modulated, txt_gate1 = self._modulate(txt_normed, txt_mod1)
272
+ joint_attention_kwargs = joint_attention_kwargs or {}
273
+ attn_output = self.attn(
274
+ hidden_states=img_modulated, encoder_hidden_states=txt_modulated,
275
+ encoder_hidden_states_mask=encoder_hidden_states_mask,
276
+ image_rotary_emb=image_rotary_emb, **joint_attention_kwargs,
277
+ )
278
+ img_attn_output, txt_attn_output = attn_output
279
+ hidden_states = hidden_states + img_gate1 * img_attn_output
280
+ encoder_hidden_states = encoder_hidden_states + txt_gate1 * txt_attn_output
281
+ img_normed2 = self.img_norm2(hidden_states)
282
+ img_modulated2, img_gate2 = self._modulate(img_normed2, img_mod2)
283
+ img_mlp_output = self.img_mlp(img_modulated2)
284
+ hidden_states = hidden_states + img_gate2 * img_mlp_output
285
+ txt_normed2 = self.txt_norm2(encoder_hidden_states)
286
+ txt_modulated2, txt_gate2 = self._modulate(txt_normed2, txt_mod2)
287
+ txt_mlp_output = self.txt_mlp(txt_modulated2)
288
+ encoder_hidden_states = encoder_hidden_states + txt_gate2 * txt_mlp_output
289
+ if encoder_hidden_states.dtype == torch.float16:
290
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
291
+ if hidden_states.dtype == torch.float16:
292
+ hidden_states = hidden_states.clip(-65504, 65504)
293
+ return encoder_hidden_states, hidden_states
294
+
295
+
296
+ class QwenImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin):
297
+ _supports_gradient_checkpointing = True
298
+ _no_split_modules = ["QwenImageTransformerBlock"]
299
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
300
+ _repeated_blocks = ["QwenImageTransformerBlock"]
301
+
302
+ @register_to_config
303
+ def __init__(self, patch_size: int = 2, in_channels: int = 64, out_channels: Optional[int] = 16,
304
+ num_layers: int = 60, attention_head_dim: int = 128, num_attention_heads: int = 24,
305
+ joint_attention_dim: int = 3584, guidance_embeds: bool = False,
306
+ axes_dims_rope: Tuple[int, int, int] = (16, 56, 56)):
307
+ super().__init__()
308
+ self.out_channels = out_channels or in_channels
309
+ self.inner_dim = num_attention_heads * attention_head_dim
310
+ self.pos_embed = QwenEmbedRope(theta=10000, axes_dim=list(axes_dims_rope), scale_rope=True)
311
+ self.time_text_embed = QwenTimestepProjEmbeddings(embedding_dim=self.inner_dim)
312
+ self.txt_norm = RMSNorm(joint_attention_dim, eps=1e-6)
313
+ self.img_in = nn.Linear(in_channels, self.inner_dim)
314
+ self.txt_in = nn.Linear(joint_attention_dim, self.inner_dim)
315
+ self.transformer_blocks = nn.ModuleList([
316
+ QwenImageTransformerBlock(
317
+ dim=self.inner_dim, num_attention_heads=num_attention_heads,
318
+ attention_head_dim=attention_head_dim,
319
+ ) for _ in range(num_layers)
320
+ ])
321
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
322
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
323
+ self.gradient_checkpointing = False
324
+
325
+ def forward(self, hidden_states, encoder_hidden_states=None, encoder_hidden_states_mask=None,
326
+ timestep=None, image_rotary_emb=None, guidance=None, attention_kwargs=None, return_dict=True):
327
+ if attention_kwargs is not None:
328
+ attention_kwargs = attention_kwargs.copy()
329
+ lora_scale = attention_kwargs.pop("scale", 1.0)
330
+ else:
331
+ lora_scale = 1.0
332
+ if USE_PEFT_BACKEND:
333
+ scale_lora_layers(self, lora_scale)
334
+ else:
335
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
336
+ logger.warning("Passing `scale` via joint_attention_kwargs when not using PEFT backend is ineffective.")
337
+ hidden_states = self.img_in(hidden_states)
338
+ timestep = timestep.to(hidden_states.dtype)
339
+ encoder_hidden_states = self.txt_norm(encoder_hidden_states)
340
+ encoder_hidden_states = self.txt_in(encoder_hidden_states)
341
+ if guidance is not None:
342
+ guidance = guidance.to(hidden_states.dtype) * 1000
343
+ temb = self.time_text_embed(timestep, hidden_states) if guidance is None else self.time_text_embed(timestep, guidance, hidden_states)
344
+ for index_block, block in enumerate(self.transformer_blocks):
345
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
346
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
347
+ block, hidden_states, encoder_hidden_states, encoder_hidden_states_mask, temb, image_rotary_emb,
348
+ )
349
+ else:
350
+ encoder_hidden_states, hidden_states = block(
351
+ hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states,
352
+ encoder_hidden_states_mask=encoder_hidden_states_mask, temb=temb,
353
+ image_rotary_emb=image_rotary_emb, joint_attention_kwargs=attention_kwargs,
354
+ )
355
+ hidden_states = self.norm_out(hidden_states, temb)
356
+ output = self.proj_out(hidden_states)
357
+ if USE_PEFT_BACKEND:
358
+ unscale_lora_layers(self, lora_scale)
359
+ if not return_dict:
360
+ return (output,)
361
+ return Transformer2DModelOutput(sample=output)