BlueSourceJY commited on
Commit
7672ea4
·
verified ·
1 Parent(s): e6a2ef1

Upload models/lightningdit_rot_head.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. models/lightningdit_rot_head.py +684 -0
models/lightningdit_rot_head.py ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lightning DiT's codes are built from original DiT & SiT.
3
+ (https://github.com/facebookresearch/DiT; https://github.com/willisma/SiT)
4
+ It demonstrates that a advanced DiT together with advanced diffusion skills
5
+ could also achieve a very promising result with 1.35 FID on ImageNet 256 generation.
6
+
7
+ Enjoy everyone, DiT strikes back!
8
+
9
+ by Maple (Jingfeng Yao) from HUST-VL
10
+ """
11
+
12
+ import os
13
+ import math
14
+ import numpy as np
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from torch.utils.checkpoint import checkpoint
20
+
21
+ from timm.models.vision_transformer import PatchEmbed, Mlp
22
+ from models.swiglu_ffn import SwiGLUFFN
23
+ from models.pos_embed import VisionRotaryEmbeddingFast
24
+ from models.rmsnorm import RMSNorm
25
+ from visualize_attention import visualize_attention_matrix
26
+
27
+ # def rot_by_head(q,k,v,num_rot):
28
+ # # q, k, v: (B, num_heads, N, head_dim)
29
+ # # q1, q2, q3, q4 = torch.chunk(q, 4, dim=1)
30
+ # # k1, k2, k3, k4 = torch.chunk(k, 4, dim=1)
31
+ # # v1, v2, v3, v4 = torch.chunk(v, 4, dim=1)
32
+ # q_list = torch.chunk(q, num_rot, dim=1)
33
+ # k_list = torch.chunk(k, num_rot, dim=1)
34
+ # v_list = torch.chunk(v, num_rot, dim=1)
35
+ # q_rot_list = []
36
+ # k_rot_list = []
37
+ # v_rot_list = []
38
+ # c = int(4 / num_rot)
39
+ # for i, (q_i, k_i, v_i) in enumerate(zip(q_list, k_list, v_list)):
40
+ # if i != 0:
41
+ # B, num_heads_i, N, head_dim_i = q_i.shape
42
+ # H = W = int(N ** 0.5)
43
+ # q_i = q_i.reshape(B, num_heads_i, H, W, head_dim_i)
44
+ # k_i = k_i.reshape(B, num_heads_i, H, W, head_dim_i)
45
+ # v_i = v_i.reshape(B, num_heads_i, H, W, head_dim_i)
46
+ # k = c*i
47
+ # q_i_rot = torch.rot90(q_i, k=k, dims=(3, 2))
48
+ # k_i_rot = torch.rot90(k_i, k=k, dims=(3, 2))
49
+ # v_i_rot = torch.rot90(v_i, k=k, dims=(3, 2))
50
+ # q_rot_list.append(q_i_rot.reshape(B, num_heads_i, N, head_dim_i))
51
+ # k_rot_list.append(k_i_rot.reshape(B, num_heads_i, N, head_dim_i))
52
+ # v_rot_list.append(v_i_rot.reshape(B, num_heads_i, N, head_dim_i))
53
+ # else:
54
+ # q_rot_list.append(q_i)
55
+ # k_rot_list.append(k_i)
56
+ # v_rot_list.append(v_i)
57
+ # q_rot = torch.cat(q_rot_list, dim=1)
58
+ # k_rot = torch.cat(k_rot_list, dim=1)
59
+ # v_rot = torch.cat(v_rot_list, dim=1)
60
+
61
+ # return q_rot, k_rot, v_rot
62
+
63
+ # def recover(x_rot, num_rot):
64
+ # x_rot_list = torch.chunk(x_rot, num_rot, dim=1)
65
+ # x_list = []
66
+ # c = int(4 / num_rot)
67
+ # for i, x_i in enumerate(x_rot_list):
68
+ # if i != 0:
69
+ # B, num_heads_i, N, head_dim_i = x_i.shape
70
+ # H = W = int(N ** 0.5)
71
+ # x_i = x_i.reshape(B, num_heads_i, H, W, head_dim_i)
72
+ # k = -c*i
73
+ # x_i_recov = torch.rot90(x_i, k=k, dims=(3, 2))
74
+ # x_list.append(x_i_recov.reshape(B, num_heads_i, N, head_dim_i))
75
+ # else:
76
+ # x_list.append(x_i)
77
+
78
+ # return torch.cat(x_list, dim=1)
79
+
80
+ #----#
81
+ # import torch
82
+ @torch.compile
83
+ def rot_by_head(q, k, v, num_rot):
84
+ # q, k, v: (B, num_heads, N, head_dim)
85
+ B, num_heads, N, head_dim = q.shape
86
+ H = W = int(N ** 0.5)
87
+
88
+ # 1. 合并处理 q, k, v -> (3, B, num_heads, N, head_dim)
89
+ combined = torch.stack([q, k, v])
90
+
91
+ # 2. 变形为 7 维以进行批量旋转
92
+ # 维度索引: 0:3, 1:B, 2:num_rot, 3:heads_per_group, 4:H, 5:W, 6:head_dim
93
+ heads_per_group = num_heads // num_rot
94
+ combined = combined.view(3, B, num_rot, heads_per_group, H, W, head_dim)
95
+
96
+ c = 4 // num_rot
97
+ results = []
98
+
99
+ for i in range(num_rot):
100
+ if i == 0:
101
+ results.append(combined[:, :, i]) # (3, B, heads_per_group, H, W, head_dim)
102
+ else:
103
+ k_rot = c * i
104
+ # k_rot=i
105
+ # 修正点:在 6 维张量中,H 和 W 分别是 index 3 和 4
106
+ # 原代码 dims=(3, 2) 对应 H, W 旋转,这里对应 (4, 3)
107
+ rotated = torch.rot90(combined[:, :, i], k=k_rot, dims=(5, 4)) # 这里的 5, 4 是相对于 (3, B, heads_per_group, H, W, head_dim) 的 H, W
108
+ # 纠正:对于 combined[:, :, i] 来说,shape 是 (3, B, heads_per_group, H, W, head_dim)
109
+ # H 是 dim 3, W 是 dim 4。所以 dims 应为 (4, 3)
110
+ rotated = torch.rot90(combined[:, :, i], k=k_rot, dims=(4, 3))
111
+ results.append(rotated)
112
+
113
+ # 3. 合并回原始形状
114
+ # cat 之后 shape: (3, B, num_heads, H, W, head_dim)
115
+ out = torch.cat(results, dim=2)
116
+ out = out.reshape(3, B, num_heads, N, head_dim) # 使用 reshape 比 view 更稳健
117
+
118
+ return out[0], out[1], out[2]
119
+
120
+ @torch.compile
121
+ def recover(x_rot, num_rot):
122
+ # x_rot: (B, num_heads, N, head_dim)
123
+ B, num_heads, N, head_dim = x_rot.shape
124
+ H = W = int(N ** 0.5)
125
+
126
+ heads_per_group = num_heads // num_rot
127
+ # 维度索引: 0:B, 1:num_rot, 2:heads_per_group, 3:H, 4:W, 5:head_dim
128
+ x_grouped = x_rot.view(B, num_rot, heads_per_group, H, W, head_dim)
129
+
130
+ c = 4 // num_rot
131
+ results = []
132
+
133
+ for i in range(num_rot):
134
+ if i == 0:
135
+ results.append(x_grouped[:, i])
136
+ else:
137
+ k_rot = -c * i
138
+ # 在 5 维张量 (B, heads_per_group, H, W, head_dim) 中,H 是 2, W 是 3
139
+ rotated = torch.rot90(x_grouped[:, i], k=k_rot, dims=(3, 2))
140
+ results.append(rotated)
141
+
142
+ # 合并并还原
143
+ out = torch.cat(results, dim=1)
144
+ return out.reshape(B, num_heads, N, head_dim)
145
+ #----#
146
+
147
+ @torch.compile
148
+ def modulate(x, shift, scale):
149
+ if shift is None:
150
+ return x * (1 + scale.unsqueeze(1))
151
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
152
+
153
+ class Attention(nn.Module):
154
+ """
155
+ Attention module of LightningDiT.
156
+ """
157
+ def __init__(
158
+ self,
159
+ dim: int,
160
+ num_heads: int = 8,
161
+ qkv_bias: bool = False,
162
+ qk_norm: bool = False,
163
+ attn_drop: float = 0.,
164
+ proj_drop: float = 0.,
165
+ norm_layer: nn.Module = nn.LayerNorm,
166
+ fused_attn: bool = True,
167
+ use_rmsnorm: bool = False,
168
+ num_rot: int = 4
169
+ ) -> None:
170
+ super().__init__()
171
+ assert dim % num_heads == 0, 'dim should be divisible by num_heads'
172
+
173
+ self.num_heads = num_heads
174
+ self.head_dim = dim // num_heads
175
+ self.scale = self.head_dim ** -0.5
176
+ self.fused_attn = fused_attn
177
+
178
+ if use_rmsnorm:
179
+ norm_layer = RMSNorm
180
+
181
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
182
+ self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
183
+ self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
184
+ self.attn_drop = nn.Dropout(attn_drop)
185
+ self.proj = nn.Linear(dim, dim)
186
+ self.proj_drop = nn.Dropout(proj_drop)
187
+
188
+ self.num_rot = num_rot
189
+
190
+ def forward(self, x: torch.Tensor, rope=None) -> torch.Tensor:
191
+ B, N, C = x.shape
192
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
193
+ q, k, v = qkv.unbind(0)
194
+ q, k = self.q_norm(q), self.k_norm(k)
195
+
196
+ if rope is not None:
197
+ q = rope(q)
198
+ k = rope(k) #(B, self.num_heads, N, self.head_dim)
199
+
200
+ # divide into groups by heads
201
+ assert self.num_rot==4
202
+ # q_rot, k_rot, v_rot = rot_by_head(q, k, v, self.num_rot) #(B, self.num_heads, N, self.head_dim)
203
+ q_rot, k_rot, v_rot = rot_by_head(q, k, v, self.num_rot) #(B, self.num_heads, N, self.head_dim)
204
+
205
+ if self.fused_attn:
206
+ x = F.scaled_dot_product_attention(
207
+ q_rot, k_rot, v_rot,
208
+ is_causal=True,
209
+ dropout_p=self.attn_drop.p if self.training else 0.,
210
+ )
211
+ else:
212
+ q = q * self.scale
213
+ attn = q @ k.transpose(-2, -1)
214
+ attn = attn.softmax(dim=-1)
215
+ attn = self.attn_drop(attn)
216
+ x = attn @ v
217
+
218
+ # x = recover(x, self.num_rot) #(B, self.num_heads, N, self.head_dim)
219
+ x = recover(x, self.num_rot)
220
+
221
+ # #------Store attention map for visualization------#
222
+ # q_vis = q * self.scale
223
+ # attn_vis = q_vis @ k.transpose(-2, -1)
224
+ # attn_vis = attn_vis.softmax(dim=-1)
225
+ # print("**************")
226
+ # print("q.shape:", q_vis.shape) # (B, num_heads=16, N=256, head_dim=72)
227
+ # print("k.shape:", k.shape) # (B, num_heads=16, N=256, head_dim=72)
228
+ # print("attn_vis.shape:", attn_vis.shape) # (B, num_heads=16, N=256, N=256)
229
+ # print("**************")
230
+
231
+
232
+ # Save attention weights as class attribute for visualization
233
+ # self.attn_weights = attn_vis.detach()
234
+ # #-------------------------------------------------#
235
+
236
+
237
+ x = x.transpose(1, 2).reshape(B, N, C)
238
+ x = self.proj(x)
239
+ x = self.proj_drop(x)
240
+ return x
241
+
242
+
243
+ class TimestepEmbedder(nn.Module):
244
+ """
245
+ Embeds scalar timesteps into vector representations.
246
+ Same as DiT.
247
+ """
248
+ def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None:
249
+ super().__init__()
250
+ self.frequency_embedding_size = frequency_embedding_size
251
+ self.mlp = nn.Sequential(
252
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
253
+ nn.SiLU(),
254
+ nn.Linear(hidden_size, hidden_size, bias=True),
255
+ )
256
+
257
+ @staticmethod
258
+ def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor:
259
+ """
260
+ Create sinusoidal timestep embeddings.
261
+ Args:
262
+ t: A 1-D Tensor of N indices, one per batch element. These may be fractional.
263
+ dim: The dimension of the output.
264
+ max_period: Controls the minimum frequency of the embeddings.
265
+ Returns:
266
+ An (N, D) Tensor of positional embeddings.
267
+ """
268
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
269
+ half = dim // 2
270
+ freqs = torch.exp(
271
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
272
+ ).to(device=t.device)
273
+
274
+ args = t[:, None].float() * freqs[None]
275
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
276
+
277
+ if dim % 2:
278
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
279
+
280
+ return embedding
281
+
282
+ @torch.compile
283
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
284
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
285
+ t_emb = self.mlp(t_freq)
286
+ return t_emb
287
+
288
+
289
+ class LabelEmbedder(nn.Module):
290
+ """
291
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
292
+ Same as DiT.
293
+ """
294
+ def __init__(self, num_classes, hidden_size, dropout_prob):
295
+ super().__init__()
296
+ use_cfg_embedding = dropout_prob > 0
297
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
298
+ self.num_classes = num_classes
299
+ self.dropout_prob = dropout_prob
300
+
301
+ def token_drop(self, labels, force_drop_ids=None):
302
+ """
303
+ Drops labels to enable classifier-free guidance.
304
+ """
305
+ if force_drop_ids is None:
306
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
307
+ else:
308
+ drop_ids = force_drop_ids == 1
309
+ labels = torch.where(drop_ids, self.num_classes, labels)
310
+ return labels
311
+
312
+ @torch.compile
313
+ def forward(self, labels, train, force_drop_ids=None):
314
+ use_dropout = self.dropout_prob > 0
315
+ if (train and use_dropout) or (force_drop_ids is not None):
316
+ labels = self.token_drop(labels, force_drop_ids)
317
+ embeddings = self.embedding_table(labels)
318
+ return embeddings
319
+
320
+ class LightningDiTBlock(nn.Module):
321
+ """
322
+ Lightning DiT Block. We add features including:
323
+ - ROPE
324
+ - QKNorm
325
+ - RMSNorm
326
+ - SwiGLU
327
+ - No shift AdaLN.
328
+ Not all of them are used in the final model, please refer to the paper for more details.
329
+ """
330
+ def __init__(
331
+ self,
332
+ hidden_size,
333
+ num_heads,
334
+ mlp_ratio=4.0,
335
+ use_qknorm=False,
336
+ use_swiglu=False,
337
+ use_rmsnorm=False,
338
+ wo_shift=False,
339
+ num_rot=4,
340
+ **block_kwargs
341
+ ):
342
+ super().__init__()
343
+
344
+ # Initialize normalization layers
345
+ if not use_rmsnorm:
346
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
347
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
348
+ else:
349
+ self.norm1 = RMSNorm(hidden_size)
350
+ self.norm2 = RMSNorm(hidden_size)
351
+
352
+ # Initialize attention layer
353
+ self.attn = Attention(
354
+ hidden_size,
355
+ num_heads=num_heads,
356
+ qkv_bias=True,
357
+ qk_norm=use_qknorm,
358
+ use_rmsnorm=use_rmsnorm,
359
+ num_rot=num_rot,
360
+ **block_kwargs
361
+ )
362
+
363
+ # Initialize MLP layer
364
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
365
+ approx_gelu = lambda: nn.GELU(approximate="tanh")
366
+ if use_swiglu:
367
+ # here we did not use SwiGLU from xformers because it is not compatible with torch.compile for now.
368
+ self.mlp = SwiGLUFFN(hidden_size, int(2/3 * mlp_hidden_dim))
369
+ else:
370
+ self.mlp = Mlp(
371
+ in_features=hidden_size,
372
+ hidden_features=mlp_hidden_dim,
373
+ act_layer=approx_gelu,
374
+ drop=0
375
+ )
376
+
377
+ # Initialize AdaLN modulation
378
+ if wo_shift:
379
+ self.adaLN_modulation = nn.Sequential(
380
+ nn.SiLU(),
381
+ nn.Linear(hidden_size, 4 * hidden_size, bias=True)
382
+ )
383
+ else:
384
+ self.adaLN_modulation = nn.Sequential(
385
+ nn.SiLU(),
386
+ nn.Linear(hidden_size, 6 * hidden_size, bias=True)
387
+ )
388
+ self.wo_shift = wo_shift
389
+
390
+ @torch.compile
391
+ def forward(self, x, c, feat_rope=None):
392
+ if self.wo_shift:
393
+ scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1)
394
+ shift_msa = None
395
+ shift_mlp = None
396
+ else:
397
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)
398
+
399
+ x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope)
400
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
401
+ return x
402
+
403
+ class FinalLayer(nn.Module):
404
+ """
405
+ The final layer of LightningDiT.
406
+ """
407
+ def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False):
408
+ super().__init__()
409
+ if not use_rmsnorm:
410
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
411
+ else:
412
+ self.norm_final = RMSNorm(hidden_size)
413
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
414
+ self.adaLN_modulation = nn.Sequential(
415
+ nn.SiLU(),
416
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True)
417
+ )
418
+ @torch.compile
419
+ def forward(self, x, c):
420
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
421
+ x = modulate(self.norm_final(x), shift, scale)
422
+ x = self.linear(x)
423
+ return x
424
+
425
+
426
+ class LightningDiT(nn.Module):
427
+ """
428
+ Diffusion model with a Transformer backbone.
429
+ """
430
+ def __init__(
431
+ self,
432
+ input_size=32,
433
+ patch_size=2,
434
+ in_channels=32,
435
+ hidden_size=1152,
436
+ depth=28,
437
+ num_heads=16,
438
+ mlp_ratio=4.0,
439
+ class_dropout_prob=0.1,
440
+ num_classes=1000,
441
+ learn_sigma=False,
442
+ use_qknorm=False,
443
+ use_swiglu=False,
444
+ use_rope=False,
445
+ use_rmsnorm=False,
446
+ wo_shift=False,
447
+ num_rot=4,
448
+ use_checkpoint=False,
449
+ ):
450
+ super().__init__()
451
+ self.learn_sigma = learn_sigma
452
+ self.in_channels = in_channels
453
+ self.out_channels = in_channels if not learn_sigma else in_channels * 2
454
+ self.patch_size = patch_size
455
+ self.num_heads = num_heads
456
+ self.use_rope = use_rope
457
+ self.use_rmsnorm = use_rmsnorm
458
+ self.depth = depth
459
+ self.hidden_size = hidden_size
460
+ self.use_checkpoint = use_checkpoint
461
+ self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)
462
+ self.t_embedder = TimestepEmbedder(hidden_size)
463
+ self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)
464
+ num_patches = self.x_embedder.num_patches
465
+ # Will use fixed sin-cos embedding:
466
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
467
+
468
+ # use rotary position encoding, borrow from EVA
469
+ if self.use_rope:
470
+ half_head_dim = hidden_size // num_heads // 2
471
+ hw_seq_len = input_size // patch_size
472
+ self.feat_rope = VisionRotaryEmbeddingFast(
473
+ dim=half_head_dim,
474
+ pt_seq_len=hw_seq_len,
475
+ )
476
+ else:
477
+ self.feat_rope = None
478
+
479
+ self.blocks = nn.ModuleList([
480
+ LightningDiTBlock(hidden_size,
481
+ num_heads,
482
+ mlp_ratio=mlp_ratio,
483
+ use_qknorm=use_qknorm,
484
+ use_swiglu=use_swiglu,
485
+ use_rmsnorm=use_rmsnorm,
486
+ wo_shift=wo_shift,
487
+ num_rot=num_rot,
488
+ ) for _ in range(depth)
489
+ ])
490
+ self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, use_rmsnorm=use_rmsnorm)
491
+ self.initialize_weights()
492
+
493
+ def initialize_weights(self):
494
+ # Initialize transformer layers:
495
+ def _basic_init(module):
496
+ if isinstance(module, nn.Linear):
497
+ torch.nn.init.xavier_uniform_(module.weight)
498
+ if module.bias is not None:
499
+ nn.init.constant_(module.bias, 0)
500
+ self.apply(_basic_init)
501
+
502
+ # Initialize (and freeze) pos_embed by sin-cos embedding:
503
+ pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))
504
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
505
+
506
+ # Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
507
+ w = self.x_embedder.proj.weight.data
508
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
509
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
510
+
511
+ # Initialize label embedding table:
512
+ nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
513
+
514
+ # Initialize timestep embedding MLP:
515
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
516
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
517
+
518
+ # Zero-out adaLN modulation layers in LightningDiT blocks:
519
+ for block in self.blocks:
520
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
521
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
522
+
523
+ # Zero-out output layers:
524
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
525
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
526
+ nn.init.constant_(self.final_layer.linear.weight, 0)
527
+ nn.init.constant_(self.final_layer.linear.bias, 0)
528
+
529
+ def unpatchify(self, x):
530
+ """
531
+ x: (N, T, patch_size**2 * C)
532
+ imgs: (N, H, W, C)
533
+ """
534
+ c = self.out_channels
535
+ p = self.x_embedder.patch_size[0]
536
+ h = w = int(x.shape[1] ** 0.5)
537
+ assert h * w == x.shape[1]
538
+
539
+ x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
540
+ x = torch.einsum('nhwpqc->nchpwq', x)
541
+ imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
542
+ return imgs
543
+
544
+ def forward(self, x, t=None, y=None):
545
+ """
546
+ Forward pass of LightningDiT.
547
+ x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
548
+ t: (N,) tensor of diffusion timesteps
549
+ y: (N,) tensor of class labels
550
+ use_checkpoint: boolean to toggle checkpointing
551
+ """
552
+
553
+ use_checkpoint = self.use_checkpoint
554
+ # print("x.shape:", x.shape) # (N, C, H, W)
555
+ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2
556
+ t = self.t_embedder(t) # (N, D)
557
+ y = self.y_embedder(y, self.training) # (N, D)
558
+ c = t + y # (N, D)
559
+
560
+ for block in self.blocks:
561
+ if use_checkpoint:
562
+ x = checkpoint(block, x, c, self.feat_rope, use_reentrant=True)
563
+ else:
564
+ x = block(x, c, self.feat_rope)
565
+
566
+ x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels)
567
+ x = self.unpatchify(x) # (N, out_channels, H, W)
568
+
569
+ if self.learn_sigma:
570
+ x, _ = x.chunk(2, dim=1)
571
+ return x
572
+
573
+ def forward_with_cfg(self, x, t, y, cfg_scale, cfg_interval=None, cfg_interval_start=None):
574
+ """
575
+ Forward pass of LightningDiT, but also batches the unconditional forward pass for classifier-free guidance.
576
+ """
577
+ # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
578
+ half = x[: len(x) // 2]
579
+ combined = torch.cat([half, half], dim=0)
580
+ model_out = self.forward(combined, t, y)
581
+ # For exact reproducibility reasons, we apply classifier-free guidance on only
582
+ # three channels by default. The standard approach to cfg applies it to all channels.
583
+ # This can be done by uncommenting the following line and commenting-out the line following that.
584
+ # eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]
585
+ eps, rest = model_out[:, :3], model_out[:, 3:]
586
+ cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
587
+ half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
588
+
589
+ if cfg_interval is True:
590
+ timestep = t[0]
591
+ if timestep < cfg_interval_start:
592
+ half_eps = cond_eps
593
+
594
+ eps = torch.cat([half_eps, half_eps], dim=0)
595
+ return torch.cat([eps, rest], dim=1)
596
+
597
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
598
+ """
599
+ grid_size: int of the grid height and width
600
+ return:
601
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
602
+ """
603
+ grid_h = np.arange(grid_size, dtype=np.float32)
604
+ grid_w = np.arange(grid_size, dtype=np.float32)
605
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
606
+ grid = np.stack(grid, axis=0)
607
+
608
+ grid = grid.reshape([2, 1, grid_size, grid_size])
609
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
610
+ if cls_token and extra_tokens > 0:
611
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
612
+ return pos_embed
613
+
614
+
615
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
616
+ assert embed_dim % 2 == 0
617
+
618
+ # use half of dimensions to encode grid_h
619
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
620
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
621
+
622
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
623
+ return emb
624
+
625
+
626
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
627
+ """
628
+ embed_dim: output dimension for each position
629
+ pos: a list of positions to be encoded: size (M,)
630
+ out: (M, D)
631
+ """
632
+ assert embed_dim % 2 == 0
633
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
634
+ omega /= embed_dim / 2.
635
+ omega = 1. / 10000**omega # (D/2,)
636
+
637
+ pos = pos.reshape(-1) # (M,)
638
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
639
+
640
+ emb_sin = np.sin(out) # (M, D/2)
641
+ emb_cos = np.cos(out) # (M, D/2)
642
+
643
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
644
+ return emb
645
+
646
+
647
+ #################################################################################
648
+ # LightningDiT Configs #
649
+ #################################################################################
650
+
651
+ def LightningDiT_XL_1(**kwargs):
652
+ return LightningDiT(depth=28, hidden_size=1152, patch_size=1, num_heads=16, **kwargs)
653
+
654
+ def LightningDiT_XL_2(**kwargs):
655
+ return LightningDiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)
656
+
657
+ def LightningDiT_L_2(**kwargs):
658
+ return LightningDiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)
659
+
660
+ def LightningDiT_B_1(**kwargs):
661
+ return LightningDiT(depth=12, hidden_size=768, patch_size=1, num_heads=12, **kwargs)
662
+
663
+ def LightningDiT_B_2(**kwargs):
664
+ return LightningDiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)
665
+
666
+ def LightningDiT_1p0B_1(**kwargs):
667
+ return LightningDiT(depth=24, hidden_size=1536, patch_size=1, num_heads=24, **kwargs)
668
+
669
+ def LightningDiT_1p0B_2(**kwargs):
670
+ return LightningDiT(depth=24, hidden_size=1536, patch_size=2, num_heads=24, **kwargs)
671
+
672
+ def LightningDiT_1p6B_1(**kwargs):
673
+ return LightningDiT(depth=28, hidden_size=1792, patch_size=1, num_heads=28, **kwargs)
674
+
675
+ def LightningDiT_1p6B_2(**kwargs):
676
+ return LightningDiT(depth=28, hidden_size=1792, patch_size=2, num_heads=28, **kwargs)
677
+
678
+ LightningDiT_models = {
679
+ 'LightningDiT-B/1': LightningDiT_B_1, 'LightningDiT-B/2': LightningDiT_B_2,
680
+ 'LightningDiT-L/2': LightningDiT_L_2,
681
+ 'LightningDiT-XL/1': LightningDiT_XL_1, 'LightningDiT-XL/2': LightningDiT_XL_2,
682
+ 'LightningDiT-1p0B/1': LightningDiT_1p0B_1, 'LightningDiT-1p0B/2': LightningDiT_1p0B_2,
683
+ 'LightningDiT-1p6B/1': LightningDiT_1p6B_1, 'LightningDiT-1p6B/2': LightningDiT_1p6B_2,
684
+ }