haiphamcse commited on
Commit
f2c29a3
·
verified ·
1 Parent(s): 7e4c5ac

Upload jit.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. jit.py +420 -0
jit.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Adapted from JiT: https://github.com/LTH14/JiT/blob/main/model_jit.py
3
+ # References: SiT, Lightning-DiT (see upstream repo)
4
+ #
5
+ # Unconditional variant: no class labels; conditioning is time t only.
6
+ # In-context tokens use learnable positional embeddings only (no label embedding).
7
+ # --------------------------------------------------------
8
+ from __future__ import annotations
9
+
10
+ import math
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+ try:
17
+ from .jit_model_util import RMSNorm, VisionRotaryEmbeddingFast, get_2d_sincos_pos_embed
18
+ except ImportError:
19
+ from jit_model_util import RMSNorm, VisionRotaryEmbeddingFast, get_2d_sincos_pos_embed
20
+
21
+
22
+ def modulate(x, shift, scale):
23
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
24
+
25
+
26
+ class BottleneckPatchEmbed(nn.Module):
27
+ """Image to patch embedding."""
28
+
29
+ def __init__(
30
+ self,
31
+ img_size=224,
32
+ patch_size=16,
33
+ in_chans=3,
34
+ pca_dim=768,
35
+ embed_dim=768,
36
+ bias=True,
37
+ ):
38
+ super().__init__()
39
+ img_size = (img_size, img_size)
40
+ patch_size = (patch_size, patch_size)
41
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
42
+ self.img_size = img_size
43
+ self.patch_size = patch_size
44
+ self.num_patches = num_patches
45
+
46
+ self.proj1 = nn.Conv2d(in_chans, pca_dim, kernel_size=patch_size, stride=patch_size, bias=False)
47
+ self.proj2 = nn.Conv2d(pca_dim, embed_dim, kernel_size=1, stride=1, bias=bias)
48
+
49
+ def forward(self, x):
50
+ b, c, h, w = x.shape
51
+ assert h == self.img_size[0] and w == self.img_size[1], (
52
+ f"Input image size ({h}*{w}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
53
+ )
54
+
55
+ x = self.proj2(self.proj1(x)).flatten(2).transpose(1, 2)
56
+ return x
57
+
58
+
59
+ class TimestepEmbedder(nn.Module):
60
+ """Embeds scalar timesteps into vector representations."""
61
+
62
+ def __init__(self, hidden_size, frequency_embedding_size=256):
63
+ super().__init__()
64
+ self.mlp = nn.Sequential(
65
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
66
+ nn.SiLU(),
67
+ nn.Linear(hidden_size, hidden_size, bias=True),
68
+ )
69
+ self.frequency_embedding_size = frequency_embedding_size
70
+
71
+ @staticmethod
72
+ def timestep_embedding(t, dim, max_period=10000):
73
+ half = dim // 2
74
+ freqs = torch.exp(
75
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half
76
+ )
77
+ args = t[:, None].float() * freqs[None]
78
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
79
+ if dim % 2:
80
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
81
+ return embedding
82
+
83
+ def forward(self, t):
84
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
85
+ return self.mlp(t_freq)
86
+
87
+
88
+ def scaled_dot_product_attention(
89
+ query: torch.Tensor,
90
+ key: torch.Tensor,
91
+ value: torch.Tensor,
92
+ dropout_p: float = 0.0,
93
+ training: bool = True,
94
+ ) -> torch.Tensor:
95
+ scale_factor = 1 / math.sqrt(query.size(-1))
96
+ with torch.cuda.amp.autocast(enabled=False):
97
+ attn_weight = query.float() @ key.float().transpose(-2, -1) * scale_factor
98
+ attn_weight = torch.softmax(attn_weight, dim=-1)
99
+ attn_weight = torch.dropout(attn_weight, dropout_p, train=training)
100
+ return attn_weight @ value
101
+
102
+
103
+ class Attention(nn.Module):
104
+ def __init__(self, dim, num_heads=8, qkv_bias=True, qk_norm=True, attn_drop=0.0, proj_drop=0.0):
105
+ super().__init__()
106
+ self.num_heads = num_heads
107
+ head_dim = dim // num_heads
108
+
109
+ self.q_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()
110
+ self.k_norm = RMSNorm(head_dim) if qk_norm else nn.Identity()
111
+
112
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
113
+ self.attn_drop = nn.Dropout(attn_drop)
114
+ self.proj = nn.Linear(dim, dim)
115
+ self.proj_drop = nn.Dropout(proj_drop)
116
+
117
+ def forward(self, x, rope):
118
+ b, n, c = x.shape
119
+ qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, c // self.num_heads).permute(2, 0, 3, 1, 4)
120
+ q, k, v = qkv[0], qkv[1], qkv[2]
121
+
122
+ q = self.q_norm(q)
123
+ k = self.k_norm(k)
124
+
125
+ q = rope(q)
126
+ k = rope(k)
127
+
128
+ x = scaled_dot_product_attention(
129
+ q,
130
+ k,
131
+ v,
132
+ dropout_p=self.attn_drop.p if self.training else 0.0,
133
+ training=self.training,
134
+ )
135
+
136
+ x = x.transpose(1, 2).reshape(b, n, c)
137
+
138
+ x = self.proj(x)
139
+ x = self.proj_drop(x)
140
+ return x
141
+
142
+
143
+ class SwiGLUFFN(nn.Module):
144
+ def __init__(self, dim: int, hidden_dim: int, drop=0.0, bias=True) -> None:
145
+ super().__init__()
146
+ hidden_dim = int(hidden_dim * 2 / 3)
147
+ self.w12 = nn.Linear(dim, 2 * hidden_dim, bias=bias)
148
+ self.w3 = nn.Linear(hidden_dim, dim, bias=bias)
149
+ self.ffn_dropout = nn.Dropout(drop)
150
+
151
+ def forward(self, x):
152
+ x12 = self.w12(x)
153
+ x1, x2 = x12.chunk(2, dim=-1)
154
+ hidden = F.silu(x1) * x2
155
+ return self.w3(self.ffn_dropout(hidden))
156
+
157
+
158
+ class FinalLayer(nn.Module):
159
+ """The final layer of JiT."""
160
+
161
+ def __init__(self, hidden_size, patch_size, out_channels):
162
+ super().__init__()
163
+ self.norm_final = RMSNorm(hidden_size)
164
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
165
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
166
+
167
+ def forward(self, x, c):
168
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
169
+ x = modulate(self.norm_final(x), shift, scale)
170
+ return self.linear(x)
171
+
172
+
173
+ class JiTBlock(nn.Module):
174
+ def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, attn_drop=0.0, proj_drop=0.0):
175
+ super().__init__()
176
+ self.norm1 = RMSNorm(hidden_size, eps=1e-6)
177
+ self.attn = Attention(
178
+ hidden_size,
179
+ num_heads=num_heads,
180
+ qkv_bias=True,
181
+ qk_norm=True,
182
+ attn_drop=attn_drop,
183
+ proj_drop=proj_drop,
184
+ )
185
+ self.norm2 = RMSNorm(hidden_size, eps=1e-6)
186
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
187
+ self.mlp = SwiGLUFFN(hidden_size, mlp_hidden_dim, drop=proj_drop)
188
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
189
+
190
+ def forward(self, x, c, feat_rope=None):
191
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1)
192
+ x = x + gate_msa.unsqueeze(1) * self.attn(
193
+ modulate(self.norm1(x), shift_msa, scale_msa), rope=feat_rope
194
+ )
195
+ x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
196
+ return x
197
+
198
+
199
+ class JiT(nn.Module):
200
+ """
201
+ Just image Transformer — unconditional (time embedding only).
202
+ """
203
+
204
+ def __init__(
205
+ self,
206
+ input_size=256,
207
+ patch_size=16,
208
+ in_channels=3,
209
+ hidden_size=1024,
210
+ depth=24,
211
+ num_heads=16,
212
+ mlp_ratio=4.0,
213
+ attn_drop=0.0,
214
+ proj_drop=0.0,
215
+ bottleneck_dim=128,
216
+ in_context_len=32,
217
+ in_context_start=8,
218
+ ):
219
+ super().__init__()
220
+ self.in_channels = in_channels
221
+ self.out_channels = in_channels
222
+ self.patch_size = patch_size
223
+ self.num_heads = num_heads
224
+ self.hidden_size = hidden_size
225
+ self.input_size = input_size
226
+ self.in_context_len = in_context_len
227
+ self.in_context_start = in_context_start
228
+
229
+ self.t_embedder = TimestepEmbedder(hidden_size)
230
+
231
+ self.x_embedder = BottleneckPatchEmbed(
232
+ input_size, patch_size, in_channels, bottleneck_dim, hidden_size, bias=True
233
+ )
234
+
235
+ num_patches = self.x_embedder.num_patches
236
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
237
+
238
+ if self.in_context_len > 0:
239
+ self.in_context_posemb = nn.Parameter(torch.zeros(1, self.in_context_len, hidden_size))
240
+ torch.nn.init.normal_(self.in_context_posemb, std=0.02)
241
+
242
+ half_head_dim = hidden_size // num_heads // 2
243
+ hw_seq_len = input_size // patch_size
244
+ self.feat_rope = VisionRotaryEmbeddingFast(
245
+ dim=half_head_dim, pt_seq_len=hw_seq_len, num_cls_token=0
246
+ )
247
+ self.feat_rope_incontext = VisionRotaryEmbeddingFast(
248
+ dim=half_head_dim, pt_seq_len=hw_seq_len, num_cls_token=self.in_context_len
249
+ )
250
+
251
+ self.blocks = nn.ModuleList(
252
+ [
253
+ JiTBlock(
254
+ hidden_size,
255
+ num_heads,
256
+ mlp_ratio=mlp_ratio,
257
+ attn_drop=attn_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,
258
+ proj_drop=proj_drop if (depth // 4 * 3 > i >= depth // 4) else 0.0,
259
+ )
260
+ for i in range(depth)
261
+ ]
262
+ )
263
+
264
+ self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)
265
+
266
+ self.initialize_weights()
267
+
268
+ def initialize_weights(self):
269
+ def _basic_init(module):
270
+ if isinstance(module, nn.Linear):
271
+ torch.nn.init.xavier_uniform_(module.weight)
272
+ if module.bias is not None:
273
+ nn.init.constant_(module.bias, 0)
274
+
275
+ self.apply(_basic_init)
276
+
277
+ pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5))
278
+ self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
279
+
280
+ w1 = self.x_embedder.proj1.weight.data
281
+ nn.init.xavier_uniform_(w1.view([w1.shape[0], -1]))
282
+ w2 = self.x_embedder.proj2.weight.data
283
+ nn.init.xavier_uniform_(w2.view([w2.shape[0], -1]))
284
+ nn.init.constant_(self.x_embedder.proj2.bias, 0)
285
+
286
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
287
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
288
+
289
+ for block in self.blocks:
290
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
291
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
292
+
293
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
294
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
295
+
296
+ nn.init.constant_(self.final_layer.linear.weight, 0)
297
+ nn.init.constant_(self.final_layer.linear.bias, 0)
298
+
299
+ def unpatchify(self, x, p):
300
+ c = self.out_channels
301
+ h = w = int(x.shape[1] ** 0.5)
302
+ assert h * w == x.shape[1]
303
+
304
+ x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
305
+ x = torch.einsum("nhwpqc->nchpwq", x)
306
+ imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))
307
+ return imgs
308
+
309
+ def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
310
+ """
311
+ Args:
312
+ x: (N, C, H, W)
313
+ t: (N,) timesteps in [0, 1] (or arbitrary floats, as in upstream)
314
+ Returns:
315
+ (N, C, H, W) predicted velocity / noise depending on training objective
316
+ """
317
+ c_emb = self.t_embedder(t)
318
+
319
+ x = self.x_embedder(x)
320
+ x = x + self.pos_embed
321
+
322
+ for i, block in enumerate(self.blocks):
323
+ if self.in_context_len > 0 and i == self.in_context_start:
324
+ b = x.shape[0]
325
+ in_context_tokens = self.in_context_posemb.expand(b, self.in_context_len, -1)
326
+ x = torch.cat([in_context_tokens, x], dim=1)
327
+ x = block(x, c_emb, self.feat_rope if i < self.in_context_start else self.feat_rope_incontext)
328
+
329
+ x = x[:, self.in_context_len :]
330
+
331
+ x = self.final_layer(x, c_emb)
332
+ return self.unpatchify(x, self.patch_size)
333
+
334
+
335
+ def JiT_B_16(**kwargs):
336
+ return JiT(
337
+ depth=12,
338
+ hidden_size=768,
339
+ num_heads=12,
340
+ bottleneck_dim=128,
341
+ in_context_len=32,
342
+ in_context_start=4,
343
+ patch_size=16,
344
+ **kwargs,
345
+ )
346
+
347
+
348
+ def JiT_B_32(**kwargs):
349
+ return JiT(
350
+ depth=12,
351
+ hidden_size=768,
352
+ num_heads=12,
353
+ bottleneck_dim=128,
354
+ in_context_len=32,
355
+ in_context_start=4,
356
+ patch_size=32,
357
+ **kwargs,
358
+ )
359
+
360
+
361
+ def JiT_L_16(**kwargs):
362
+ return JiT(
363
+ depth=24,
364
+ hidden_size=1024,
365
+ num_heads=16,
366
+ bottleneck_dim=128,
367
+ in_context_len=32,
368
+ in_context_start=8,
369
+ patch_size=16,
370
+ **kwargs,
371
+ )
372
+
373
+
374
+ def JiT_L_32(**kwargs):
375
+ return JiT(
376
+ depth=24,
377
+ hidden_size=1024,
378
+ num_heads=16,
379
+ bottleneck_dim=128,
380
+ in_context_len=32,
381
+ in_context_start=8,
382
+ patch_size=32,
383
+ **kwargs,
384
+ )
385
+
386
+
387
+ def JiT_H_16(**kwargs):
388
+ return JiT(
389
+ depth=32,
390
+ hidden_size=1280,
391
+ num_heads=16,
392
+ bottleneck_dim=256,
393
+ in_context_len=32,
394
+ in_context_start=10,
395
+ patch_size=16,
396
+ **kwargs,
397
+ )
398
+
399
+
400
+ def JiT_H_32(**kwargs):
401
+ return JiT(
402
+ depth=32,
403
+ hidden_size=1280,
404
+ num_heads=16,
405
+ bottleneck_dim=256,
406
+ in_context_len=32,
407
+ in_context_start=10,
408
+ patch_size=32,
409
+ **kwargs,
410
+ )
411
+
412
+
413
+ JiT_models = {
414
+ "JiT-B/16": JiT_B_16,
415
+ "JiT-B/32": JiT_B_32,
416
+ "JiT-L/16": JiT_L_16,
417
+ "JiT-L/32": JiT_L_32,
418
+ "JiT-H/16": JiT_H_16,
419
+ "JiT-H/32": JiT_H_32,
420
+ }