honghong3 commited on
Commit
b2e0abf
·
verified ·
1 Parent(s): ea34a87

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +411 -0
model.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ '''
7
+ [Model Overview]
8
+
9
+ Input: (B, 4, 64, 64) - VAE latent
10
+
11
+ 1. PatchEmbedding
12
+ Conv2d(patch_size=2) → flatten → transpose
13
+ (B, 4, 64, 64) → (B, 1024 tokens, 1024 d_model)
14
+
15
+ 2. Condition Embedding
16
+ ├── Sigma → SinusoidalPosEmb → MLP → sigma_emb # noise level (timestep)
17
+ └── Text → Linear → MLP → text_token_emb # tokens for cross attention
18
+ Text → mean pooling → MLP → pooled_text # global condition for adaLN
19
+
20
+ cond_emb = sigma_emb + pooled_text → adaLN modulation coefficients
21
+
22
+ 3. DiT Block × num_layers
23
+ each block receives shift/scale modulation from cond_emb (adaLN):
24
+ ├── Self Attention + RoPE 2D # spatial relationships between patches
25
+ ├── Text Cross Attention # text tokens ↔ image patches
26
+ └── FFN # feature transformation
27
+
28
+ 4. Final modulation + Output projection
29
+ LayerNorm → adaLN shift/scale → Linear → unpatchify
30
+
31
+ Output: pred_velocity (B, 4, 64, 64) - direction vector from noise → clean
32
+ '''
33
+
34
+ class SinusoidalPosEmb(nn.Module):
35
+ def __init__(self, dim, sinusoid_rope_hz):
36
+ super().__init__()
37
+ self.sinusoid_rope_hz = sinusoid_rope_hz
38
+ self.dim = dim
39
+
40
+ def forward(self, x):
41
+ device = x.device
42
+ half_dim = self.dim // 2
43
+
44
+ emb = math.log(self.sinusoid_rope_hz) / max(half_dim - 1, 1)
45
+ emb = torch.exp(torch.arange(half_dim, device=device, dtype=torch.float32) * -emb)
46
+
47
+ emb = x[:, None].float() * emb[None, :]
48
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
49
+
50
+ return emb
51
+
52
+ class RotaryPositionalEmbedding2D(nn.Module):
53
+ def __init__(self, dim, base):
54
+ super().__init__()
55
+ self.dim = dim
56
+ self.rope_dim_per_coord = dim // 2
57
+
58
+ inv_freq_h = 1.0 / (base ** (torch.arange(0, self.rope_dim_per_coord, 2).float() / self.rope_dim_per_coord))
59
+ self.register_buffer('inv_freq_h', inv_freq_h)
60
+
61
+ inv_freq_w = 1.0 / (base ** (torch.arange(0, self.rope_dim_per_coord, 2).float() / self.rope_dim_per_coord))
62
+ self.register_buffer('inv_freq_w', inv_freq_w)
63
+
64
+ def forward(self, q, k, H_p, W_p):
65
+ t_idx = torch.arange(H_p * W_p, device=q.device)
66
+ h_idx = t_idx // W_p
67
+ w_idx = t_idx % W_p
68
+
69
+ freqs_h = torch.einsum('i,j->ij', h_idx.float(), self.inv_freq_h)
70
+ freqs_w = torch.einsum('i,j->ij', w_idx.float(), self.inv_freq_w)
71
+
72
+ freqs_h = torch.cat((freqs_h, freqs_h), dim=-1)
73
+ freqs_w = torch.cat((freqs_w, freqs_w), dim=-1)
74
+
75
+ cos_cached_h = freqs_h.cos().view(1, 1, H_p * W_p, self.rope_dim_per_coord)
76
+ sin_cached_h = freqs_h.sin().view(1, 1, H_p * W_p, self.rope_dim_per_coord)
77
+ cos_cached_w = freqs_w.cos().view(1, 1, H_p * W_p, self.rope_dim_per_coord)
78
+ sin_cached_w = freqs_w.sin().view(1, 1, H_p * W_p, self.rope_dim_per_coord)
79
+
80
+ q_h, q_w = q.chunk(2, dim=-1)
81
+ k_h, k_w = k.chunk(2, dim=-1)
82
+
83
+ q_h_rot = (q_h * cos_cached_h) + (self._rotate_half(q_h) * sin_cached_h)
84
+ k_h_rot = (k_h * cos_cached_h) + (self._rotate_half(k_h) * sin_cached_h)
85
+
86
+ q_w_rot = (q_w * cos_cached_w) + (self._rotate_half(q_w) * sin_cached_w)
87
+ k_w_rot = (k_w * cos_cached_w) + (self._rotate_half(k_w) * sin_cached_w)
88
+
89
+ q_rot = torch.cat((q_h_rot, q_w_rot), dim=-1)
90
+ k_rot = torch.cat((k_h_rot, k_w_rot), dim=-1)
91
+
92
+ return q_rot, k_rot
93
+
94
+ def _rotate_half(self, x):
95
+ x1, x2 = x.chunk(2, dim=-1)
96
+ return torch.cat((-x2, x1), dim=-1)
97
+
98
+ class PatchEmbedding(nn.Module):
99
+ def __init__(self, in_channels: int, patch_size: int, d_model: int):
100
+ super().__init__()
101
+ self.patch_size = patch_size
102
+ self.in_channels = in_channels
103
+ self.proj = nn.Conv2d(
104
+ in_channels,
105
+ d_model,
106
+ kernel_size=patch_size,
107
+ stride=patch_size
108
+ )
109
+
110
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
111
+ x = self.proj(x)
112
+ x = x.flatten(2)
113
+ x = x.transpose(1, 2).contiguous()
114
+ return x
115
+
116
+ def patchify(self, x: torch.Tensor) -> torch.Tensor:
117
+ B, C, H, W = x.shape
118
+ p = self.patch_size
119
+ x = x.reshape(B, C, H // p, p, W // p, p)
120
+ x = x.permute(0, 2, 4, 1, 3, 5).contiguous()
121
+ x = x.reshape(B, -1, p * p * C)
122
+ return x
123
+
124
+ def unpatchify(self, x: torch.Tensor, H, W):
125
+ B = x.shape[0]
126
+ p = self.patch_size
127
+ C = self.in_channels
128
+ h, w = H // p, W // p
129
+ x = x.reshape(B, h, w, C, p, p)
130
+ x = x.permute(0, 3, 1, 4, 2, 5).contiguous()
131
+ x = x.reshape(B, C, h * p, w * p)
132
+ return x
133
+
134
+
135
+ class Block(nn.Module):
136
+ def __init__(self, d_model, nhead, dim_feedforward, dropout, rope_hz):
137
+ super().__init__()
138
+
139
+ self.nhead = nhead
140
+ self.d_model = d_model
141
+
142
+ # [수정] gate 제거 → shift/scale 6개만
143
+ self.adaLN_modulation = nn.Sequential(
144
+ nn.SiLU(),
145
+ nn.Linear(d_model, d_model * 6)
146
+ )
147
+
148
+ # self attention
149
+ self.self_norm = nn.LayerNorm(d_model)
150
+ self.qkv = nn.Linear(d_model, d_model * 3)
151
+ self.out_proj = nn.Linear(d_model, d_model)
152
+ self.rope = RotaryPositionalEmbedding2D(d_model // nhead, rope_hz)
153
+
154
+ # text cross
155
+ self.text_norm = nn.LayerNorm(d_model)
156
+ self.text_cross_q = nn.Linear(d_model, d_model)
157
+ self.text_cross_kv = nn.Linear(d_model, d_model * 2)
158
+ self.text_cross_out = nn.Linear(d_model, d_model)
159
+
160
+ # ffn
161
+ self.ffn_norm = nn.LayerNorm(d_model)
162
+ self.ff1 = nn.Linear(d_model, dim_feedforward)
163
+ self.ff2 = nn.Linear(dim_feedforward, d_model)
164
+
165
+ self.dropout = nn.Dropout(dropout)
166
+ self.q_norm = nn.LayerNorm(d_model // nhead)
167
+ self.k_norm = nn.LayerNorm(d_model // nhead)
168
+
169
+ def self_attention(self, x_norm, H, W):
170
+ B, T, D = x_norm.shape
171
+ N = self.nhead
172
+ d_k = D // N
173
+
174
+ qkv = self.qkv(x_norm)
175
+ Q, K, V = qkv.chunk(3, dim=-1)
176
+
177
+ Q = Q.reshape(B, T, N, d_k).transpose(1, 2)
178
+ K = K.reshape(B, T, N, d_k).transpose(1, 2)
179
+ V = V.reshape(B, T, N, d_k).transpose(1, 2)
180
+
181
+ Q = self.q_norm(Q)
182
+ K = self.k_norm(K)
183
+
184
+ Q_rot, K_rot = self.rope(Q, K, H, W)
185
+
186
+ attn_out = F.scaled_dot_product_attention(
187
+ Q_rot, K_rot, V,
188
+ dropout_p=0.0,
189
+ is_causal=False,
190
+ )
191
+
192
+ attn_out = attn_out.transpose(1, 2).reshape(B, T, D)
193
+ attn_out = self.out_proj(attn_out)
194
+ return attn_out
195
+
196
+ def _cross_attention_impl(self, x_norm, cond, q_proj, kv_proj, out_proj, H, W, attn_mask=None):
197
+ B, T, D = x_norm.shape
198
+ Bc, L, Dc = cond.shape
199
+
200
+ Q = q_proj(x_norm)
201
+ kv = kv_proj(cond)
202
+ K, V = kv.chunk(2, dim=-1)
203
+
204
+ N = self.nhead
205
+ d_k = D // N
206
+
207
+ Q = Q.reshape(B, T, N, d_k).transpose(1, 2)
208
+ K = K.reshape(B, L, N, d_k).transpose(1, 2)
209
+ V = V.reshape(B, L, N, d_k).transpose(1, 2)
210
+
211
+ if attn_mask is not None:
212
+ attn_mask = attn_mask.to(device=Q.device, dtype=torch.bool)
213
+ attn_mask = attn_mask[:, None, None, :]
214
+
215
+ out = F.scaled_dot_product_attention(
216
+ Q, K, V,
217
+ attn_mask=attn_mask,
218
+ dropout_p=0.0,
219
+ is_causal=False,
220
+ )
221
+
222
+ out = out.transpose(1, 2).reshape(B, T, D)
223
+ out = out_proj(out)
224
+ return out
225
+
226
+ def text_cross_attention(self, x_norm, text_emb, text_mask, H, W):
227
+ return self._cross_attention_impl(
228
+ x_norm=x_norm,
229
+ cond=text_emb,
230
+ q_proj=self.text_cross_q,
231
+ kv_proj=self.text_cross_kv,
232
+ out_proj=self.text_cross_out,
233
+ H=H,
234
+ W=W,
235
+ attn_mask=text_mask,
236
+ )
237
+
238
+ def forward(self, x, cond_emb, text_emb, text_mask=None, H=None, W=None, key=None):
239
+ B, T, D = x.shape
240
+
241
+ # [수정] shift/scale 6개만
242
+ c = cond_emb.squeeze(1)
243
+ chunks = self.adaLN_modulation(c).chunk(6, dim=-1)
244
+ shift_msa, scale_msa = chunks[0], chunks[1]
245
+ shift_cross, scale_cross = chunks[2], chunks[3]
246
+ shift_mlp, scale_mlp = chunks[4], chunks[5]
247
+
248
+ # 1. Self Attention (gate 제거)
249
+ x_norm = self.self_norm(x)
250
+ x_norm = x_norm * (1 + scale_msa[:, None, :]) + shift_msa[:, None, :]
251
+ self_out = self.self_attention(x_norm=x_norm, H=H, W=W)
252
+ x = x + self.dropout(self_out)
253
+
254
+ # 2. Text Cross Attention (gate 제거)
255
+ x_norm = self.text_norm(x)
256
+ x_norm = x_norm * (1 + scale_cross[:, None, :]) + shift_cross[:, None, :]
257
+ text_cross_out = self.text_cross_attention(
258
+ x_norm=x_norm,
259
+ text_emb=text_emb,
260
+ text_mask=text_mask,
261
+ H=H,
262
+ W=W,
263
+ )
264
+ x = x + self.dropout(text_cross_out)
265
+
266
+ # 3. FFN (gate 제거)
267
+ x_norm = self.ffn_norm(x)
268
+ x_norm = x_norm * (1 + scale_mlp[:, None, :]) + shift_mlp[:, None, :]
269
+ ffn = self.ff1(x_norm)
270
+ ffn = F.gelu(ffn, approximate="tanh")
271
+ ffn = self.ff2(ffn)
272
+ x = x + self.dropout(ffn)
273
+
274
+ with torch.no_grad():
275
+ self_std = self_out.float().std().item()
276
+ text_std = text_cross_out.float().std().item()
277
+ ffn_std = ffn.float().std().item()
278
+
279
+ state = {
280
+ "key": key,
281
+ "self_out": self_std,
282
+ "text_out": text_std,
283
+ "ffn_out": ffn_std,
284
+ }
285
+
286
+ return x, state
287
+
288
+
289
+ class Model(nn.Module):
290
+ def __init__(self, d_model, nhead, num_layers, dropout, sigma_emb_hz, in_channels, patch_size, text_dim, rope_hz, **kwargs):
291
+ super().__init__()
292
+ dim_feedforward = 4 * d_model
293
+ self.patch_size = patch_size
294
+ self.in_channels = in_channels
295
+
296
+ # patch
297
+ self.patch_embedding = PatchEmbedding(
298
+ in_channels=in_channels,
299
+ patch_size=patch_size,
300
+ d_model=d_model
301
+ )
302
+ self.patch_norm = nn.LayerNorm(d_model)
303
+
304
+ # sigma
305
+ self.sigma_proj = SinusoidalPosEmb(d_model, sigma_emb_hz)
306
+ self.sigma_embed = nn.Sequential(
307
+ nn.Linear(d_model, d_model),
308
+ nn.SiLU(),
309
+ nn.Linear(d_model, d_model),
310
+ )
311
+ self.sigma_norm = nn.LayerNorm(d_model)
312
+
313
+ # text token (cross attention용)
314
+ self.text_proj = nn.Linear(text_dim, d_model)
315
+ self.text_embed = nn.Sequential(
316
+ nn.Linear(d_model, d_model),
317
+ nn.SiLU(),
318
+ nn.Linear(d_model, d_model),
319
+ )
320
+ self.text_norm = nn.LayerNorm(d_model)
321
+
322
+ # pooled text (adaLN용)
323
+ self.pooled_text_proj = nn.Sequential(
324
+ nn.Linear(text_dim, d_model),
325
+ nn.SiLU(),
326
+ nn.Linear(d_model, d_model),
327
+ )
328
+ self.pooled_text_norm = nn.LayerNorm(d_model)
329
+
330
+ self.blocks = nn.ModuleList([
331
+ Block(
332
+ d_model=d_model,
333
+ nhead=nhead,
334
+ dim_feedforward=dim_feedforward,
335
+ dropout=dropout,
336
+ rope_hz=rope_hz
337
+ )
338
+ for _ in range(num_layers)
339
+ ])
340
+
341
+ self.cond_norm = nn.LayerNorm(d_model)
342
+ self.cond_proj = nn.Linear(d_model, d_model)
343
+
344
+ self.norm = nn.LayerNorm(d_model)
345
+
346
+ self.final_mod = nn.Sequential(
347
+ nn.SiLU(),
348
+ nn.Linear(d_model, d_model * 2)
349
+ )
350
+
351
+ self.output_proj = nn.Linear(
352
+ d_model,
353
+ patch_size * patch_size * in_channels
354
+ )
355
+
356
+ def forward(self, x, sigma, text_emb, text_mask=None):
357
+ B, C, H, W = x.shape
358
+ H_p = H // self.patch_size
359
+ W_p = W // self.patch_size
360
+
361
+ sigma = sigma.to(device=x.device, dtype=torch.float32)
362
+
363
+ # 1. 패치 임베딩
364
+ x_emb = self.patch_norm(self.patch_embedding(x))
365
+
366
+ # 2. sigma 임베딩
367
+ sigma_emb = self.sigma_proj(sigma)
368
+ sigma_emb = self.sigma_embed(sigma_emb)
369
+ sigma_emb = self.sigma_norm(sigma_emb)
370
+
371
+ # 3. 텍스트 토큰 임베딩 (cross attention용)
372
+ text_token_emb = self.text_proj(text_emb)
373
+ text_token_emb = self.text_embed(text_token_emb)
374
+ text_token_emb = self.text_norm(text_token_emb)
375
+
376
+ # 4. pooled text 임베딩 (adaLN용)
377
+ if text_mask is not None:
378
+ mask_float = text_mask.float().unsqueeze(-1)
379
+ pooled_text = (text_emb * mask_float).sum(dim=1) / mask_float.sum(dim=1).clamp(min=1)
380
+ else:
381
+ pooled_text = text_emb.mean(dim=1)
382
+
383
+ pooled_text = self.pooled_text_proj(pooled_text)
384
+ pooled_text = self.pooled_text_norm(pooled_text)
385
+
386
+ # sigma + pooled_text → adaLN 컨디션
387
+ cond_emb = self.cond_norm(self.cond_proj(sigma_emb + pooled_text))
388
+ cond_emb = cond_emb[:, None, :]
389
+
390
+ # 5. 블록 연산
391
+ layer_states = []
392
+ for i, block in enumerate(self.blocks):
393
+ x_emb, state = block(
394
+ x=x_emb,
395
+ cond_emb=cond_emb,
396
+ text_emb=text_token_emb,
397
+ text_mask=text_mask,
398
+ H=H_p,
399
+ W=W_p,
400
+ key=i,
401
+ )
402
+ layer_states.append(state)
403
+
404
+ # 6. 최종 출력
405
+ shift, scale = self.final_mod(cond_emb.squeeze(1)).chunk(2, dim=-1)
406
+ x_final = self.norm(x_emb)
407
+ x_final = x_final * (1 + scale[:, None, :]) + shift[:, None, :]
408
+
409
+ pred_velocity = self.output_proj(x_final)
410
+ pred_velocity = self.patch_embedding.unpatchify(pred_velocity, H, W)
411
+ return pred_velocity, layer_states