comdoleger commited on
Commit
4ae4568
·
verified ·
1 Parent(s): fbfb150

Upload extensions_built_in/diffusion_models/hidream/src/models/transformers/transformer_hidream_image.py with huggingface_hub

Browse files
extensions_built_in/diffusion_models/hidream/src/models/transformers/transformer_hidream_image.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, Optional, Tuple, List
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import einops
6
+ from einops import repeat
7
+
8
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
9
+ from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
10
+ from diffusers.models.modeling_utils import ModelMixin
11
+ from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
12
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
13
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
14
+ from ..embeddings import PatchEmbed, PooledEmbed, TimestepEmbed, EmbedND, OutEmbed
15
+ from ..attention import HiDreamAttention, FeedForwardSwiGLU
16
+ from ..attention_processor import HiDreamAttnProcessor_flashattn
17
+ from ..moe import MOEFeedForwardSwiGLU
18
+
19
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
20
+
21
+ class TextProjection(nn.Module):
22
+ def __init__(self, in_features, hidden_size):
23
+ super().__init__()
24
+ self.linear = nn.Linear(in_features=in_features, out_features=hidden_size, bias=False)
25
+
26
+ def forward(self, caption):
27
+ hidden_states = self.linear(caption)
28
+ return hidden_states
29
+
30
+ class BlockType:
31
+ TransformerBlock = 1
32
+ SingleTransformerBlock = 2
33
+
34
+ @maybe_allow_in_graph
35
+ class HiDreamImageSingleTransformerBlock(nn.Module):
36
+ def __init__(
37
+ self,
38
+ dim: int,
39
+ num_attention_heads: int,
40
+ attention_head_dim: int,
41
+ num_routed_experts: int = 4,
42
+ num_activated_experts: int = 2
43
+ ):
44
+ super().__init__()
45
+ self.num_attention_heads = num_attention_heads
46
+ self.adaLN_modulation = nn.Sequential(
47
+ nn.SiLU(),
48
+ nn.Linear(dim, 6 * dim, bias=True)
49
+ )
50
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
51
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
52
+
53
+ # 1. Attention
54
+ self.norm1_i = nn.LayerNorm(dim, eps = 1e-06, elementwise_affine = False)
55
+ self.attn1 = HiDreamAttention(
56
+ query_dim=dim,
57
+ heads=num_attention_heads,
58
+ dim_head=attention_head_dim,
59
+ processor = HiDreamAttnProcessor_flashattn(),
60
+ single = True
61
+ )
62
+
63
+ # 3. Feed-forward
64
+ self.norm3_i = nn.LayerNorm(dim, eps = 1e-06, elementwise_affine = False)
65
+ if num_routed_experts > 0:
66
+ self.ff_i = MOEFeedForwardSwiGLU(
67
+ dim = dim,
68
+ hidden_dim = 4 * dim,
69
+ num_routed_experts = num_routed_experts,
70
+ num_activated_experts = num_activated_experts,
71
+ )
72
+ else:
73
+ self.ff_i = FeedForwardSwiGLU(dim = dim, hidden_dim = 4 * dim)
74
+
75
+ def forward(
76
+ self,
77
+ image_tokens: torch.FloatTensor,
78
+ image_tokens_masks: Optional[torch.FloatTensor] = None,
79
+ text_tokens: Optional[torch.FloatTensor] = None,
80
+ adaln_input: Optional[torch.FloatTensor] = None,
81
+ rope: torch.FloatTensor = None,
82
+
83
+ ) -> torch.FloatTensor:
84
+ wtype = image_tokens.dtype
85
+ shift_msa_i, scale_msa_i, gate_msa_i, shift_mlp_i, scale_mlp_i, gate_mlp_i = \
86
+ self.adaLN_modulation(adaln_input)[:,None].chunk(6, dim=-1)
87
+
88
+ # 1. MM-Attention
89
+ norm_image_tokens = self.norm1_i(image_tokens).to(dtype=wtype)
90
+ norm_image_tokens = norm_image_tokens * (1 + scale_msa_i) + shift_msa_i
91
+ attn_output_i = self.attn1(
92
+ norm_image_tokens,
93
+ image_tokens_masks,
94
+ rope = rope,
95
+ )
96
+ image_tokens = gate_msa_i * attn_output_i + image_tokens
97
+
98
+ # 2. Feed-forward
99
+ norm_image_tokens = self.norm3_i(image_tokens).to(dtype=wtype)
100
+ norm_image_tokens = norm_image_tokens * (1 + scale_mlp_i) + shift_mlp_i
101
+ ff_output_i = gate_mlp_i * self.ff_i(norm_image_tokens.to(dtype=wtype))
102
+ image_tokens = ff_output_i + image_tokens
103
+ return image_tokens
104
+
105
+ @maybe_allow_in_graph
106
+ class HiDreamImageTransformerBlock(nn.Module):
107
+ def __init__(
108
+ self,
109
+ dim: int,
110
+ num_attention_heads: int,
111
+ attention_head_dim: int,
112
+ num_routed_experts: int = 4,
113
+ num_activated_experts: int = 2
114
+ ):
115
+ super().__init__()
116
+ self.num_attention_heads = num_attention_heads
117
+ self.adaLN_modulation = nn.Sequential(
118
+ nn.SiLU(),
119
+ nn.Linear(dim, 12 * dim, bias=True)
120
+ )
121
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
122
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
123
+
124
+ # 1. Attention
125
+ self.norm1_i = nn.LayerNorm(dim, eps = 1e-06, elementwise_affine = False)
126
+ self.norm1_t = nn.LayerNorm(dim, eps = 1e-06, elementwise_affine = False)
127
+ self.attn1 = HiDreamAttention(
128
+ query_dim=dim,
129
+ heads=num_attention_heads,
130
+ dim_head=attention_head_dim,
131
+ processor = HiDreamAttnProcessor_flashattn(),
132
+ single = False
133
+ )
134
+
135
+ # 3. Feed-forward
136
+ self.norm3_i = nn.LayerNorm(dim, eps = 1e-06, elementwise_affine = False)
137
+ if num_routed_experts > 0:
138
+ self.ff_i = MOEFeedForwardSwiGLU(
139
+ dim = dim,
140
+ hidden_dim = 4 * dim,
141
+ num_routed_experts = num_routed_experts,
142
+ num_activated_experts = num_activated_experts,
143
+ )
144
+ else:
145
+ self.ff_i = FeedForwardSwiGLU(dim = dim, hidden_dim = 4 * dim)
146
+ self.norm3_t = nn.LayerNorm(dim, eps = 1e-06, elementwise_affine = False)
147
+ self.ff_t = FeedForwardSwiGLU(dim = dim, hidden_dim = 4 * dim)
148
+
149
+ def forward(
150
+ self,
151
+ image_tokens: torch.FloatTensor,
152
+ image_tokens_masks: Optional[torch.FloatTensor] = None,
153
+ text_tokens: Optional[torch.FloatTensor] = None,
154
+ adaln_input: Optional[torch.FloatTensor] = None,
155
+ rope: torch.FloatTensor = None,
156
+ ) -> torch.FloatTensor:
157
+ wtype = image_tokens.dtype
158
+ shift_msa_i, scale_msa_i, gate_msa_i, shift_mlp_i, scale_mlp_i, gate_mlp_i, \
159
+ shift_msa_t, scale_msa_t, gate_msa_t, shift_mlp_t, scale_mlp_t, gate_mlp_t = \
160
+ self.adaLN_modulation(adaln_input)[:,None].chunk(12, dim=-1)
161
+
162
+ # 1. MM-Attention
163
+ norm_image_tokens = self.norm1_i(image_tokens).to(dtype=wtype)
164
+ norm_image_tokens = norm_image_tokens * (1 + scale_msa_i) + shift_msa_i
165
+ norm_text_tokens = self.norm1_t(text_tokens).to(dtype=wtype)
166
+ norm_text_tokens = norm_text_tokens * (1 + scale_msa_t) + shift_msa_t
167
+
168
+ attn_output_i, attn_output_t = self.attn1(
169
+ norm_image_tokens,
170
+ image_tokens_masks,
171
+ norm_text_tokens,
172
+ rope = rope,
173
+ )
174
+
175
+ image_tokens = gate_msa_i * attn_output_i + image_tokens
176
+ text_tokens = gate_msa_t * attn_output_t + text_tokens
177
+
178
+ # 2. Feed-forward
179
+ norm_image_tokens = self.norm3_i(image_tokens).to(dtype=wtype)
180
+ norm_image_tokens = norm_image_tokens * (1 + scale_mlp_i) + shift_mlp_i
181
+ norm_text_tokens = self.norm3_t(text_tokens).to(dtype=wtype)
182
+ norm_text_tokens = norm_text_tokens * (1 + scale_mlp_t) + shift_mlp_t
183
+
184
+ ff_output_i = gate_mlp_i * self.ff_i(norm_image_tokens)
185
+ ff_output_t = gate_mlp_t * self.ff_t(norm_text_tokens)
186
+ image_tokens = ff_output_i + image_tokens
187
+ text_tokens = ff_output_t + text_tokens
188
+ return image_tokens, text_tokens
189
+
190
+ @maybe_allow_in_graph
191
+ class HiDreamImageBlock(nn.Module):
192
+ def __init__(
193
+ self,
194
+ dim: int,
195
+ num_attention_heads: int,
196
+ attention_head_dim: int,
197
+ num_routed_experts: int = 4,
198
+ num_activated_experts: int = 2,
199
+ block_type: BlockType = BlockType.TransformerBlock,
200
+ ):
201
+ super().__init__()
202
+ block_classes = {
203
+ BlockType.TransformerBlock: HiDreamImageTransformerBlock,
204
+ BlockType.SingleTransformerBlock: HiDreamImageSingleTransformerBlock,
205
+ }
206
+ self.block = block_classes[block_type](
207
+ dim,
208
+ num_attention_heads,
209
+ attention_head_dim,
210
+ num_routed_experts,
211
+ num_activated_experts
212
+ )
213
+
214
+ def forward(
215
+ self,
216
+ image_tokens: torch.FloatTensor,
217
+ image_tokens_masks: Optional[torch.FloatTensor] = None,
218
+ text_tokens: Optional[torch.FloatTensor] = None,
219
+ adaln_input: torch.FloatTensor = None,
220
+ rope: torch.FloatTensor = None,
221
+ ) -> torch.FloatTensor:
222
+ return self.block(
223
+ image_tokens,
224
+ image_tokens_masks,
225
+ text_tokens,
226
+ adaln_input,
227
+ rope,
228
+ )
229
+
230
+ class HiDreamImageTransformer2DModel(
231
+ ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin
232
+ ):
233
+ _supports_gradient_checkpointing = True
234
+ _no_split_modules = ["HiDreamImageBlock"]
235
+
236
+ @register_to_config
237
+ def __init__(
238
+ self,
239
+ patch_size: Optional[int] = None,
240
+ in_channels: int = 64,
241
+ out_channels: Optional[int] = None,
242
+ num_layers: int = 16,
243
+ num_single_layers: int = 32,
244
+ attention_head_dim: int = 128,
245
+ num_attention_heads: int = 20,
246
+ caption_channels: List[int] = None,
247
+ text_emb_dim: int = 2048,
248
+ num_routed_experts: int = 4,
249
+ num_activated_experts: int = 2,
250
+ axes_dims_rope: Tuple[int, int] = (32, 32),
251
+ max_resolution: Tuple[int, int] = (128, 128),
252
+ llama_layers: List[int] = None,
253
+ ):
254
+ super().__init__()
255
+ self.out_channels = out_channels or in_channels
256
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
257
+ self.llama_layers = llama_layers
258
+
259
+ self.t_embedder = TimestepEmbed(self.inner_dim)
260
+ self.p_embedder = PooledEmbed(text_emb_dim, self.inner_dim)
261
+ self.x_embedder = PatchEmbed(
262
+ patch_size = patch_size,
263
+ in_channels = in_channels,
264
+ out_channels = self.inner_dim,
265
+ )
266
+ self.pe_embedder = EmbedND(theta=10000, axes_dim=axes_dims_rope)
267
+
268
+ self.double_stream_blocks = nn.ModuleList(
269
+ [
270
+ HiDreamImageBlock(
271
+ dim = self.inner_dim,
272
+ num_attention_heads = self.config.num_attention_heads,
273
+ attention_head_dim = self.config.attention_head_dim,
274
+ num_routed_experts = num_routed_experts,
275
+ num_activated_experts = num_activated_experts,
276
+ block_type = BlockType.TransformerBlock
277
+ )
278
+ for i in range(self.config.num_layers)
279
+ ]
280
+ )
281
+
282
+ self.single_stream_blocks = nn.ModuleList(
283
+ [
284
+ HiDreamImageBlock(
285
+ dim = self.inner_dim,
286
+ num_attention_heads = self.config.num_attention_heads,
287
+ attention_head_dim = self.config.attention_head_dim,
288
+ num_routed_experts = num_routed_experts,
289
+ num_activated_experts = num_activated_experts,
290
+ block_type = BlockType.SingleTransformerBlock
291
+ )
292
+ for i in range(self.config.num_single_layers)
293
+ ]
294
+ )
295
+
296
+ self.final_layer = OutEmbed(self.inner_dim, patch_size, self.out_channels)
297
+
298
+ caption_channels = [caption_channels[1], ] * (num_layers + num_single_layers) + [caption_channels[0], ]
299
+ caption_projection = []
300
+ for caption_channel in caption_channels:
301
+ caption_projection.append(TextProjection(in_features = caption_channel, hidden_size = self.inner_dim))
302
+ self.caption_projection = nn.ModuleList(caption_projection)
303
+ self.max_seq = max_resolution[0] * max_resolution[1] // (patch_size * patch_size)
304
+
305
+ self.gradient_checkpointing = False
306
+
307
+
308
+ def expand_timesteps(self, timesteps, batch_size, device):
309
+ if not torch.is_tensor(timesteps):
310
+ is_mps = device.type == "mps"
311
+ if isinstance(timesteps, float):
312
+ dtype = torch.float32 if is_mps else torch.float64
313
+ else:
314
+ dtype = torch.int32 if is_mps else torch.int64
315
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=device)
316
+ elif len(timesteps.shape) == 0:
317
+ timesteps = timesteps[None].to(device)
318
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
319
+ timesteps = timesteps.expand(batch_size)
320
+ return timesteps
321
+
322
+ # the implementation on hidream during train was wrong, just use the inference one.
323
+ def unpatchify(self, x: torch.Tensor, img_sizes: List[Tuple[int, int]], is_training: bool) -> List[torch.Tensor]:
324
+ # Process all images in the batch according to their specific dimensions
325
+ x_arr = []
326
+ for i, img_size in enumerate(img_sizes):
327
+ pH, pW = img_size
328
+ x_arr.append(
329
+ einops.rearrange(
330
+ x[i, :pH*pW].reshape(1, pH, pW, -1),
331
+ 'B H W (p1 p2 C) -> B C (H p1) (W p2)',
332
+ p1=self.config.patch_size, p2=self.config.patch_size
333
+ )
334
+ )
335
+ x = torch.cat(x_arr, dim=0)
336
+ return x
337
+
338
+ def patchify(self, x, max_seq, img_sizes=None):
339
+ pz2 = self.config.patch_size * self.config.patch_size
340
+ if isinstance(x, torch.Tensor):
341
+ B, C = x.shape[0], x.shape[1]
342
+ device = x.device
343
+ dtype = x.dtype
344
+ else:
345
+ B, C = len(x), x[0].shape[0]
346
+ device = x[0].device
347
+ dtype = x[0].dtype
348
+ x_masks = torch.zeros((B, max_seq), dtype=dtype, device=device)
349
+
350
+ if img_sizes is not None:
351
+ for i, img_size in enumerate(img_sizes):
352
+ x_masks[i, 0:img_size[0] * img_size[1]] = 1
353
+ x = einops.rearrange(x, 'B C S p -> B S (p C)', p=pz2)
354
+ elif isinstance(x, torch.Tensor):
355
+ pH, pW = x.shape[-2] // self.config.patch_size, x.shape[-1] // self.config.patch_size
356
+ x = einops.rearrange(x, 'B C (H p1) (W p2) -> B (H W) (p1 p2 C)', p1=self.config.patch_size, p2=self.config.patch_size)
357
+ img_sizes = [[pH, pW]] * B
358
+ x_masks = None
359
+ else:
360
+ raise NotImplementedError
361
+ return x, x_masks, img_sizes
362
+
363
+ def forward(
364
+ self,
365
+ hidden_states: torch.Tensor,
366
+ timesteps: torch.LongTensor = None,
367
+ encoder_hidden_states: torch.Tensor = None,
368
+ pooled_embeds: torch.Tensor = None,
369
+ img_sizes: Optional[List[Tuple[int, int]]] = None,
370
+ img_ids: Optional[torch.Tensor] = None,
371
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
372
+ return_dict: bool = True,
373
+ ):
374
+ if joint_attention_kwargs is not None:
375
+ joint_attention_kwargs = joint_attention_kwargs.copy()
376
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
377
+ else:
378
+ lora_scale = 1.0
379
+
380
+ if USE_PEFT_BACKEND:
381
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
382
+ scale_lora_layers(self, lora_scale)
383
+ else:
384
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
385
+ logger.warning(
386
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
387
+ )
388
+
389
+ # spatial forward
390
+ batch_size = hidden_states.shape[0]
391
+ hidden_states_type = hidden_states.dtype
392
+
393
+ # 0. time
394
+ timesteps = self.expand_timesteps(timesteps, batch_size, hidden_states.device)
395
+ timesteps = self.t_embedder(timesteps, hidden_states_type)
396
+ p_embedder = self.p_embedder(pooled_embeds)
397
+ adaln_input = timesteps + p_embedder
398
+
399
+ hidden_states, image_tokens_masks, img_sizes = self.patchify(hidden_states, self.max_seq, img_sizes)
400
+ if image_tokens_masks is None:
401
+ pH, pW = img_sizes[0]
402
+ img_ids = torch.zeros(pH, pW, 3, device=hidden_states.device)
403
+ img_ids[..., 1] = img_ids[..., 1] + torch.arange(pH, device=hidden_states.device)[:, None]
404
+ img_ids[..., 2] = img_ids[..., 2] + torch.arange(pW, device=hidden_states.device)[None, :]
405
+ img_ids = repeat(img_ids, "h w c -> b (h w) c", b=batch_size)
406
+ hidden_states = self.x_embedder(hidden_states)
407
+
408
+ T5_encoder_hidden_states = encoder_hidden_states[0]
409
+ encoder_hidden_states = encoder_hidden_states[-1]
410
+ encoder_hidden_states = [encoder_hidden_states[k] for k in self.llama_layers]
411
+
412
+ if self.caption_projection is not None:
413
+ new_encoder_hidden_states = []
414
+ for i, enc_hidden_state in enumerate(encoder_hidden_states):
415
+ enc_hidden_state = self.caption_projection[i](enc_hidden_state)
416
+ enc_hidden_state = enc_hidden_state.view(batch_size, -1, hidden_states.shape[-1])
417
+ new_encoder_hidden_states.append(enc_hidden_state)
418
+ encoder_hidden_states = new_encoder_hidden_states
419
+ T5_encoder_hidden_states = self.caption_projection[-1](T5_encoder_hidden_states)
420
+ T5_encoder_hidden_states = T5_encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
421
+ encoder_hidden_states.append(T5_encoder_hidden_states)
422
+
423
+ txt_ids = torch.zeros(
424
+ batch_size,
425
+ encoder_hidden_states[-1].shape[1] + encoder_hidden_states[-2].shape[1] + encoder_hidden_states[0].shape[1],
426
+ 3,
427
+ device=img_ids.device, dtype=img_ids.dtype
428
+ )
429
+ ids = torch.cat((img_ids, txt_ids), dim=1)
430
+ rope = self.pe_embedder(ids)
431
+
432
+ # 2. Blocks
433
+ block_id = 0
434
+ initial_encoder_hidden_states = torch.cat([encoder_hidden_states[-1], encoder_hidden_states[-2]], dim=1)
435
+ initial_encoder_hidden_states_seq_len = initial_encoder_hidden_states.shape[1]
436
+ for bid, block in enumerate(self.double_stream_blocks):
437
+ cur_llama31_encoder_hidden_states = encoder_hidden_states[block_id].detach()
438
+ cur_encoder_hidden_states = torch.cat([initial_encoder_hidden_states, cur_llama31_encoder_hidden_states], dim=1)
439
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
440
+ hidden_states, initial_encoder_hidden_states = self._gradient_checkpointing_func(
441
+ block,
442
+ hidden_states,
443
+ image_tokens_masks,
444
+ cur_encoder_hidden_states,
445
+ adaln_input.clone(),
446
+ rope.clone(),
447
+ )
448
+
449
+ else:
450
+ hidden_states, initial_encoder_hidden_states = block(
451
+ image_tokens = hidden_states,
452
+ image_tokens_masks = image_tokens_masks,
453
+ text_tokens = cur_encoder_hidden_states,
454
+ adaln_input = adaln_input,
455
+ rope = rope,
456
+ )
457
+ initial_encoder_hidden_states = initial_encoder_hidden_states[:, :initial_encoder_hidden_states_seq_len]
458
+ block_id += 1
459
+
460
+ image_tokens_seq_len = hidden_states.shape[1]
461
+ hidden_states = torch.cat([hidden_states, initial_encoder_hidden_states], dim=1)
462
+ hidden_states_seq_len = hidden_states.shape[1]
463
+ if image_tokens_masks is not None:
464
+ encoder_attention_mask_ones = torch.ones(
465
+ (batch_size, initial_encoder_hidden_states.shape[1] + cur_llama31_encoder_hidden_states.shape[1]),
466
+ device=image_tokens_masks.device, dtype=image_tokens_masks.dtype
467
+ )
468
+ image_tokens_masks = torch.cat([image_tokens_masks, encoder_attention_mask_ones], dim=1)
469
+
470
+ for bid, block in enumerate(self.single_stream_blocks):
471
+ cur_llama31_encoder_hidden_states = encoder_hidden_states[block_id].detach()
472
+ hidden_states = torch.cat([hidden_states, cur_llama31_encoder_hidden_states], dim=1)
473
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
474
+ hidden_states = self._gradient_checkpointing_func(
475
+ block,
476
+ hidden_states,
477
+ image_tokens_masks,
478
+ None,
479
+ adaln_input.clone(),
480
+ rope.clone(),
481
+ )
482
+ else:
483
+ hidden_states = block(
484
+ image_tokens = hidden_states,
485
+ image_tokens_masks = image_tokens_masks,
486
+ text_tokens = None,
487
+ adaln_input = adaln_input,
488
+ rope = rope,
489
+ )
490
+ hidden_states = hidden_states[:, :hidden_states_seq_len]
491
+ block_id += 1
492
+
493
+ hidden_states = hidden_states[:, :image_tokens_seq_len, ...]
494
+ output = self.final_layer(hidden_states, adaln_input)
495
+ output = self.unpatchify(output, img_sizes, self.training)
496
+ if image_tokens_masks is not None:
497
+ image_tokens_masks = image_tokens_masks[:, :image_tokens_seq_len]
498
+
499
+ if USE_PEFT_BACKEND:
500
+ # remove `lora_scale` from each PEFT layer
501
+ unscale_lora_layers(self, lora_scale)
502
+
503
+ if not return_dict:
504
+ return (output, image_tokens_masks)
505
+ return Transformer2DModelOutput(sample=output, mask=image_tokens_masks)
506
+