-
Notifications
You must be signed in to change notification settings - Fork 15
/
dit.py
437 lines (363 loc) · 13.8 KB
/
dit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# Code heavilty based on https://github.com/Alpha-VLLM/LLaMA2-Accessory
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def modulate(x, shift, scale):
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
class TimestepEmbedder(nn.Module):
def __init__(self, hidden_size, frequency_embedding_size=256):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size),
nn.SiLU(),
nn.Linear(hidden_size, hidden_size),
)
self.frequency_embedding_size = frequency_embedding_size
@staticmethod
def timestep_embedding(t, dim, max_period=10000):
half = dim // 2
freqs = torch.exp(
-math.log(max_period) * torch.arange(start=0, end=half) / half
).to(t.device)
args = t[:, None] * freqs[None]
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
if dim % 2:
embedding = torch.cat(
[embedding, torch.zeros_like(embedding[:, :1])], dim=-1
)
return embedding
def forward(self, t):
t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(
dtype=next(self.parameters()).dtype
)
t_emb = self.mlp(t_freq)
return t_emb
class LabelEmbedder(nn.Module):
def __init__(self, num_classes, hidden_size, dropout_prob):
super().__init__()
use_cfg_embedding = int(dropout_prob > 0)
self.embedding_table = nn.Embedding(
num_classes + use_cfg_embedding, hidden_size
)
self.num_classes = num_classes
self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None):
if force_drop_ids is None:
drop_ids = torch.rand(labels.shape[0]) < self.dropout_prob
drop_ids = drop_ids.cuda()
drop_ids = drop_ids.to(labels.device)
else:
drop_ids = force_drop_ids == 1
labels = torch.where(drop_ids, self.num_classes, labels)
return labels
def forward(self, labels, train, force_drop_ids=None):
use_dropout = self.dropout_prob > 0
if (train and use_dropout) or (force_drop_ids is not None):
labels = self.token_drop(labels, force_drop_ids)
embeddings = self.embedding_table(labels)
return embeddings
class Attention(nn.Module):
def __init__(self, dim, n_heads):
super().__init__()
self.n_heads = n_heads
self.n_rep = 1
self.head_dim = dim // n_heads
self.wq = nn.Linear(dim, n_heads * self.head_dim, bias=False)
self.wk = nn.Linear(dim, self.n_heads * self.head_dim, bias=False)
self.wv = nn.Linear(dim, self.n_heads * self.head_dim, bias=False)
self.wo = nn.Linear(n_heads * self.head_dim, dim, bias=False)
self.q_norm = nn.LayerNorm(self.n_heads * self.head_dim)
self.k_norm = nn.LayerNorm(self.n_heads * self.head_dim)
@staticmethod
def reshape_for_broadcast(freqs_cis, x):
ndim = x.ndim
assert 0 <= 1 < ndim
assert freqs_cis.shape == (x.shape[1], x.shape[-1])
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
return freqs_cis.view(*shape)
@staticmethod
def apply_rotary_emb(xq, xk, freqs_cis):
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
freqs_cis = Attention.reshape_for_broadcast(freqs_cis, xq_)
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
return xq_out, xk_out
def forward(self, x, freqs_cis):
bsz, seqlen, _ = x.shape
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
dtype = xq.dtype
xq = self.q_norm(xq)
xk = self.k_norm(xk)
xq = xq.view(bsz, seqlen, self.n_heads, self.head_dim)
xk = xk.view(bsz, seqlen, self.n_heads, self.head_dim)
xv = xv.view(bsz, seqlen, self.n_heads, self.head_dim)
xq, xk = self.apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
xq, xk = xq.to(dtype), xk.to(dtype)
output = F.scaled_dot_product_attention(
xq.permute(0, 2, 1, 3),
xk.permute(0, 2, 1, 3),
xv.permute(0, 2, 1, 3),
dropout_p=0.0,
is_causal=False,
).permute(0, 2, 1, 3)
output = output.flatten(-2)
return self.wo(output)
class FeedForward(nn.Module):
def __init__(self, dim, hidden_dim, multiple_of, ffn_dim_multiplier=None):
super().__init__()
hidden_dim = int(2 * hidden_dim / 3)
if ffn_dim_multiplier:
hidden_dim = int(ffn_dim_multiplier * hidden_dim)
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
def _forward_silu_gating(self, x1, x3):
return F.silu(x1) * x3
def forward(self, x):
return self.w2(self._forward_silu_gating(self.w1(x), self.w3(x)))
class TransformerBlock(nn.Module):
def __init__(
self,
layer_id,
dim,
n_heads,
multiple_of,
ffn_dim_multiplier,
norm_eps,
):
super().__init__()
self.dim = dim
self.head_dim = dim // n_heads
self.attention = Attention(dim, n_heads)
self.feed_forward = FeedForward(
dim=dim,
hidden_dim=4 * dim,
multiple_of=multiple_of,
ffn_dim_multiplier=ffn_dim_multiplier,
)
self.layer_id = layer_id
self.attention_norm = nn.LayerNorm(dim, eps=norm_eps)
self.ffn_norm = nn.LayerNorm(dim, eps=norm_eps)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
nn.Linear(min(dim, 1024), 6 * dim, bias=True),
)
def forward(self, x, freqs_cis, adaln_input=None):
if adaln_input is not None:
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
self.adaLN_modulation(adaln_input).chunk(6, dim=1)
)
x = x + gate_msa.unsqueeze(1) * self.attention(
modulate(self.attention_norm(x), shift_msa, scale_msa), freqs_cis
)
x = x + gate_mlp.unsqueeze(1) * self.feed_forward(
modulate(self.ffn_norm(x), shift_mlp, scale_mlp)
)
else:
x = x + self.attention(self.attention_norm(x), freqs_cis)
x = x + self.feed_forward(self.ffn_norm(x))
return x
class FinalLayer(nn.Module):
def __init__(self, hidden_size, patch_size, out_channels):
super().__init__()
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(
hidden_size, patch_size * patch_size * out_channels, bias=True
)
self.adaLN_modulation = nn.Sequential(
nn.SiLU(),
nn.Linear(min(hidden_size, 1024), 2 * hidden_size, bias=True),
)
# # init zero
nn.init.constant_(self.linear.weight, 0)
nn.init.constant_(self.linear.bias, 0)
def forward(self, x, c):
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
x = modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
return x
class DDiT_Llama(nn.Module):
def __init__(
self,
N=256,
dim=512,
n_layers=5,
n_heads=16,
multiple_of=256,
ffn_dim_multiplier=None,
norm_eps=1e-5,
learn_gating=False,
):
super().__init__()
self.N = N
self.learn_gating = learn_gating
if self.learn_gating:
self.out_channel = N * 2
else:
self.out_channel = N
self.embedder = nn.Embedding(N, dim)
self.t_embedder = TimestepEmbedder(min(dim, 1024))
self.layers = nn.ModuleList(
[
TransformerBlock(
layer_id,
dim,
n_heads,
multiple_of,
ffn_dim_multiplier,
norm_eps,
)
for layer_id in range(n_layers)
]
)
self.final_layer = FinalLayer(dim, 1, self.out_channel)
self.freqs_cis = DiT_Llama.precompute_freqs_cis(dim // n_heads, 4096)
def forward(self, x, t, cond=None):
self.freqs_cis = self.freqs_cis.to(x.device)
x_onehot = torch.nn.functional.one_hot(x, self.N).to(
x.device, dtype=next(self.parameters()).dtype
)
x = self.embedder(x)
adaln_input = self.t_embedder(t)
for layer in self.layers:
x = layer(x, self.freqs_cis[: x.size(1)], adaln_input=adaln_input)
x = self.final_layer(x, adaln_input)
if self.learn_gating:
x, gate = x.chunk(2, dim=-1)
return x + x_onehot * (1 + gate).abs()
else:
return x + x_onehot
class DiT_Llama(nn.Module):
def __init__(
self,
in_channels=3,
N=8,
input_size=32,
patch_size=2,
dim=512,
n_layers=5,
n_heads=16,
multiple_of=256,
ffn_dim_multiplier=None,
norm_eps=1e-5,
class_dropout_prob=0.1,
num_classes=10,
learn_sigma=True,
):
super().__init__()
self.N = N
self.learn_sigma = learn_sigma
self.in_channels = in_channels
self.out_channels = N * in_channels * 2
self.input_size = input_size
self.patch_size = patch_size
self.init_conv_seq = nn.Sequential(
nn.Conv2d(in_channels, dim // 2, kernel_size=5, padding=2, stride=1),
nn.SiLU(),
nn.GroupNorm(32, dim // 2),
nn.Conv2d(dim // 2, dim // 2, kernel_size=5, padding=2, stride=1),
nn.SiLU(),
nn.GroupNorm(32, dim // 2),
)
self.x_embedder = nn.Linear(patch_size * patch_size * dim // 2, dim, bias=True)
nn.init.constant_(self.x_embedder.bias, 0)
self.t_embedder = TimestepEmbedder(min(dim, 1024))
self.y_embedder = LabelEmbedder(num_classes, min(dim, 1024), class_dropout_prob)
self.layers = nn.ModuleList(
[
TransformerBlock(
layer_id,
dim,
n_heads,
multiple_of,
ffn_dim_multiplier,
norm_eps,
)
for layer_id in range(n_layers)
]
)
self.final_layer = FinalLayer(dim, patch_size, self.out_channels)
self.freqs_cis = DiT_Llama.precompute_freqs_cis(dim // n_heads, 4096)
def unpatchify(self, x):
c = self.out_channels
p = self.patch_size
h = w = int(x.shape[1] ** 0.5)
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
x = torch.einsum("nhwpqc->nchpwq", x)
imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
return imgs
def patchify(self, x):
B, C, H, W = x.size()
x = x.view(
B,
C,
H // self.patch_size,
self.patch_size,
W // self.patch_size,
self.patch_size,
)
x = x.permute(0, 2, 4, 1, 3, 5).flatten(-3).flatten(1, 2)
return x
def forward(self, x, t, y):
self.freqs_cis = self.freqs_cis.to(x.device)
x_onehot = torch.nn.functional.one_hot(x, self.N).float().to(x.device)
x = (2 * x.float() / (self.N - 1)) - 1.0
x = self.init_conv_seq(x)
x = self.patchify(x)
x = self.x_embedder(x)
t = self.t_embedder(t) # (N, D)
y = self.y_embedder(y, self.training) # (N, D)
adaln_input = t + y
for layer in self.layers:
x = layer(x, self.freqs_cis[: x.size(1)], adaln_input=adaln_input)
x = self.final_layer(x, adaln_input)
x = self.unpatchify(x) # (N, out_channels, H, W)
x, gate = (
x.reshape(x.shape[0], -1, self.N * 2, *x.shape[2:])
.transpose(2, -1)
.contiguous()
).chunk(2, dim=-1)
return x + x_onehot * (1 + gate).abs()
# x = (x.reshape(x.shape[0], -1, self.N, *x.shape[2:])
# .transpose(2, -1)
# .contiguous()
# )
# return x
def forward_with_cfg(self, x, t, y, cfg_scale):
half = x[: len(x) // 2]
combined = torch.cat([half, half], dim=0)
model_out = self.forward(combined, t, y)
eps, rest = model_out[:, : self.in_channels], model_out[:, self.in_channels :]
cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
eps = torch.cat([half_eps, half_eps], dim=0)
return torch.cat([eps, rest], dim=1)
@staticmethod
def precompute_freqs_cis(dim, end, theta=10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end)
freqs = torch.outer(t, freqs).float()
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
return freqs_cis
def DiT_Llama_600M_patch2(**kwargs):
return DiT_Llama(patch_size=2, dim=256, n_layers=16, n_heads=32, **kwargs)
def DiT_Llama_3B_patch2(**kwargs):
return DiT_Llama(patch_size=2, dim=3072, n_layers=32, n_heads=32, **kwargs)
if __name__ == "__main__":
model = DiT_Llama_600M_patch2()
model.eval()
x = torch.randint(0, 8, (4, 3, 32, 32))
t = torch.randint(0, 1000, (4,))
y = torch.randint(0, 10, (4,))
out = model(x, t, y)
print(out)
# cuda ver
model = model.cuda()
x = x.cuda()
t = t.cuda()
y = y.cuda()
out = model(x, t, y)
print(out)