ideprado commited on
Commit
eea9761
·
1 Parent(s): 908e1dd

Revert "Upload f_lite.model.py (#8)"

Browse files

This reverts commit 908e1ddce50dfc02bbcc7eb88494ecd72d79ffad because it makes original inference way stop working

Files changed (1) hide show
  1. dit_model/f_lite.model.py +0 -455
dit_model/f_lite.model.py DELETED
@@ -1,455 +0,0 @@
1
- # DiT with cross attention
2
-
3
- import math
4
-
5
- import torch
6
- import torch.nn.functional as F
7
- import torch.utils.checkpoint
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.accelerate_utils import apply_forward_hook
12
- from einops import rearrange
13
- from peft import get_peft_model_state_dict, set_peft_model_state_dict
14
- from torch import nn
15
-
16
-
17
- def timestep_embedding(t, dim, max_period=10000):
18
- half = dim // 2
19
- freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
20
- device=t.device
21
- )
22
- args = t[:, None].float() * freqs[None]
23
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
24
-
25
- return embedding
26
-
27
-
28
- class RMSNorm(nn.Module):
29
- def __init__(self, dim, eps=1e-6, trainable=False):
30
- super().__init__()
31
- self.eps = eps
32
- if trainable:
33
- self.weight = nn.Parameter(torch.ones(dim))
34
- else:
35
- self.weight = None
36
-
37
- def forward(self, x):
38
- x_dtype = x.dtype
39
- x = x.float()
40
- norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
41
- if self.weight is not None:
42
- return (x * norm * self.weight).to(dtype=x_dtype)
43
- else:
44
- return (x * norm).to(dtype=x_dtype)
45
-
46
-
47
- class QKNorm(nn.Module):
48
- """Normalizing the query and the key independently, as Flux proposes"""
49
-
50
- def __init__(self, dim, trainable=False):
51
- super().__init__()
52
- self.query_norm = RMSNorm(dim, trainable=trainable)
53
- self.key_norm = RMSNorm(dim, trainable=trainable)
54
-
55
- def forward(self, q, k):
56
- q = self.query_norm(q)
57
- k = self.key_norm(k)
58
- return q, k
59
-
60
-
61
- class Attention(nn.Module):
62
- def __init__(
63
- self,
64
- dim,
65
- num_heads=8,
66
- qkv_bias=False,
67
- is_self_attn=True,
68
- cross_attn_input_size=None,
69
- residual_v=False,
70
- dynamic_softmax_temperature=False,
71
- ):
72
- super().__init__()
73
- assert dim % num_heads == 0
74
- self.num_heads = num_heads
75
- self.head_dim = dim // num_heads
76
- self.scale = self.head_dim**-0.5
77
- self.is_self_attn = is_self_attn
78
- self.residual_v = residual_v
79
- self.dynamic_softmax_temperature = dynamic_softmax_temperature
80
-
81
- if is_self_attn:
82
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
83
- else:
84
- self.q = nn.Linear(dim, dim, bias=qkv_bias)
85
- self.context_kv = nn.Linear(cross_attn_input_size, dim * 2, bias=qkv_bias)
86
-
87
- self.proj = nn.Linear(dim, dim, bias=False)
88
-
89
- if residual_v:
90
- self.lambda_param = nn.Parameter(torch.tensor(0.5).reshape(1))
91
-
92
- self.qk_norm = QKNorm(self.head_dim)
93
-
94
- def forward(self, x, context=None, v_0=None, rope=None):
95
- if self.is_self_attn:
96
- qkv = self.qkv(x)
97
- qkv = rearrange(qkv, "b l (k h d) -> k b h l d", k=3, h=self.num_heads)
98
- q, k, v = qkv.unbind(0)
99
-
100
- if self.residual_v and v_0 is not None:
101
- v = self.lambda_param * v + (1 - self.lambda_param) * v_0
102
-
103
- if rope is not None:
104
- # print(q.shape, rope[0].shape, rope[1].shape)
105
- q = apply_rotary_emb(q, rope[0], rope[1])
106
- k = apply_rotary_emb(k, rope[0], rope[1])
107
-
108
- # https://arxiv.org/abs/2306.08645
109
- # https://arxiv.org/abs/2410.01104
110
- # ratioonale is that if tokens get larger, categorical distribution get more uniform
111
- # so you want to enlargen entropy.
112
-
113
- token_length = q.shape[2]
114
- if self.dynamic_softmax_temperature:
115
- ratio = math.sqrt(math.log(token_length) / math.log(1040.0)) # 1024 + 16
116
- k = k * ratio
117
- q, k = self.qk_norm(q, k)
118
-
119
- else:
120
- q = rearrange(self.q(x), "b l (h d) -> b h l d", h=self.num_heads)
121
- kv = rearrange(
122
- self.context_kv(context),
123
- "b l (k h d) -> k b h l d",
124
- k=2,
125
- h=self.num_heads,
126
- )
127
- k, v = kv.unbind(0)
128
- q, k = self.qk_norm(q, k)
129
-
130
- x = F.scaled_dot_product_attention(q, k, v)
131
- x = rearrange(x, "b h l d -> b l (h d)")
132
- x = self.proj(x)
133
- return x, v if self.is_self_attn else None
134
-
135
-
136
- class DiTBlock(nn.Module):
137
- def __init__(
138
- self,
139
- hidden_size,
140
- cross_attn_input_size,
141
- num_heads,
142
- mlp_ratio=4.0,
143
- qkv_bias=True,
144
- residual_v=False,
145
- dynamic_softmax_temperature=False,
146
- ):
147
- super().__init__()
148
- self.hidden_size = hidden_size
149
- self.norm1 = RMSNorm(hidden_size, trainable=qkv_bias)
150
- self.self_attn = Attention(
151
- hidden_size,
152
- num_heads=num_heads,
153
- qkv_bias=qkv_bias,
154
- is_self_attn=True,
155
- residual_v=residual_v,
156
- dynamic_softmax_temperature=dynamic_softmax_temperature,
157
- )
158
-
159
- if cross_attn_input_size is not None:
160
- self.norm2 = RMSNorm(hidden_size, trainable=qkv_bias)
161
- self.cross_attn = Attention(
162
- hidden_size,
163
- num_heads=num_heads,
164
- qkv_bias=qkv_bias,
165
- is_self_attn=False,
166
- cross_attn_input_size=cross_attn_input_size,
167
- dynamic_softmax_temperature=dynamic_softmax_temperature,
168
- )
169
- else:
170
- self.norm2 = None
171
- self.cross_attn = None
172
-
173
- self.norm3 = RMSNorm(hidden_size, trainable=qkv_bias)
174
- mlp_hidden = int(hidden_size * mlp_ratio)
175
- self.mlp = nn.Sequential(
176
- nn.Linear(hidden_size, mlp_hidden),
177
- nn.GELU(),
178
- nn.Linear(mlp_hidden, hidden_size),
179
- )
180
-
181
- self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 9 * hidden_size, bias=True))
182
-
183
- self.adaLN_modulation[-1].weight.data.zero_()
184
- self.adaLN_modulation[-1].bias.data.zero_()
185
-
186
- # @torch.compile(mode='reduce-overhead')
187
- def forward(self, x, context, c, v_0=None, rope=None):
188
- (
189
- shift_sa,
190
- scale_sa,
191
- gate_sa,
192
- shift_ca,
193
- scale_ca,
194
- gate_ca,
195
- shift_mlp,
196
- scale_mlp,
197
- gate_mlp,
198
- ) = self.adaLN_modulation(c).chunk(9, dim=1)
199
-
200
- scale_sa = scale_sa[:, None, :]
201
- scale_ca = scale_ca[:, None, :]
202
- scale_mlp = scale_mlp[:, None, :]
203
-
204
- shift_sa = shift_sa[:, None, :]
205
- shift_ca = shift_ca[:, None, :]
206
- shift_mlp = shift_mlp[:, None, :]
207
-
208
- gate_sa = gate_sa[:, None, :]
209
- gate_ca = gate_ca[:, None, :]
210
- gate_mlp = gate_mlp[:, None, :]
211
-
212
- norm_x = self.norm1(x.clone())
213
- norm_x = norm_x * (1 + scale_sa) + shift_sa
214
- attn_out, v = self.self_attn(norm_x, v_0=v_0, rope=rope)
215
- x = x + attn_out * gate_sa
216
-
217
- if self.norm2 is not None:
218
- norm_x = self.norm2(x)
219
- norm_x = norm_x * (1 + scale_ca) + shift_ca
220
- x = x + self.cross_attn(norm_x, context)[0] * gate_ca
221
-
222
- norm_x = self.norm3(x)
223
- norm_x = norm_x * (1 + scale_mlp) + shift_mlp
224
- x = x + self.mlp(norm_x) * gate_mlp
225
-
226
- return x, v
227
-
228
-
229
- class PatchEmbed(nn.Module):
230
- def __init__(self, patch_size=16, in_channels=3, embed_dim=768):
231
- super().__init__()
232
- self.patch_proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
233
- self.patch_size = patch_size
234
-
235
- def forward(self, x):
236
- B, C, H, W = x.shape
237
- x = self.patch_proj(x)
238
- x = rearrange(x, "b c h w -> b (h w) c")
239
- return x
240
-
241
-
242
- class TwoDimRotary(torch.nn.Module):
243
- def __init__(self, dim, base=10000, h=256, w=256):
244
- super().__init__()
245
- self.inv_freq = torch.FloatTensor([1.0 / (base ** (i / dim)) for i in range(0, dim, 2)])
246
- self.h = h
247
- self.w = w
248
-
249
- t_h = torch.arange(h, dtype=torch.float32)
250
- t_w = torch.arange(w, dtype=torch.float32)
251
-
252
- freqs_h = torch.outer(t_h, self.inv_freq).unsqueeze(1) # h, 1, d / 2
253
- freqs_w = torch.outer(t_w, self.inv_freq).unsqueeze(0) # 1, w, d / 2
254
- freqs_h = freqs_h.repeat(1, w, 1) # h, w, d / 2
255
- freqs_w = freqs_w.repeat(h, 1, 1) # h, w, d / 2
256
- freqs_hw = torch.cat([freqs_h, freqs_w], 2) # h, w, d
257
-
258
- self.register_buffer("freqs_hw_cos", freqs_hw.cos())
259
- self.register_buffer("freqs_hw_sin", freqs_hw.sin())
260
-
261
- def forward(self, x, height_width=None, extend_with_register_tokens=0):
262
- if height_width is not None:
263
- this_h, this_w = height_width
264
- else:
265
- this_hw = x.shape[1]
266
- this_h, this_w = int(this_hw**0.5), int(this_hw**0.5)
267
-
268
- cos = self.freqs_hw_cos[0 : this_h, 0 : this_w]
269
- sin = self.freqs_hw_sin[0 : this_h, 0 : this_w]
270
-
271
- cos = cos.clone().reshape(this_h * this_w, -1)
272
- sin = sin.clone().reshape(this_h * this_w, -1)
273
-
274
- # append N of zero-attn tokens
275
- if extend_with_register_tokens > 0:
276
- cos = torch.cat(
277
- [
278
- torch.ones(extend_with_register_tokens, cos.shape[1]).to(cos.device),
279
- cos,
280
- ],
281
- 0,
282
- )
283
- sin = torch.cat(
284
- [
285
- torch.zeros(extend_with_register_tokens, sin.shape[1]).to(sin.device),
286
- sin,
287
- ],
288
- 0,
289
- )
290
-
291
- return cos[None, None, :, :], sin[None, None, :, :] # [1, 1, T + N, Attn-dim]
292
-
293
-
294
- def apply_rotary_emb(x, cos, sin):
295
- orig_dtype = x.dtype
296
- x = x.to(dtype=torch.float32)
297
- assert x.ndim == 4 # multihead attention
298
- d = x.shape[3] // 2
299
- x1 = x[..., :d]
300
- x2 = x[..., d:]
301
- y1 = x1 * cos + x2 * sin
302
- y2 = x1 * (-sin) + x2 * cos
303
- return torch.cat([y1, y2], 3).to(dtype=orig_dtype)
304
-
305
-
306
- class DiT(ModelMixin, ConfigMixin, FromOriginalModelMixin, PeftAdapterMixin): # type: ignore[misc]
307
- @register_to_config
308
- def __init__(
309
- self,
310
- in_channels=4,
311
- patch_size=2,
312
- hidden_size=1152,
313
- depth=28,
314
- num_heads=16,
315
- mlp_ratio=4.0,
316
- cross_attn_input_size=128,
317
- residual_v=False,
318
- train_bias_and_rms=True,
319
- use_rope=True,
320
- gradient_checkpoint=False,
321
- dynamic_softmax_temperature=False,
322
- rope_base=10000,
323
- ):
324
- super().__init__()
325
-
326
- self.patch_embed = PatchEmbed(patch_size, in_channels, hidden_size)
327
-
328
- if use_rope:
329
- self.rope = TwoDimRotary(hidden_size // (2 * num_heads), base=rope_base, h=512, w=512)
330
- else:
331
- self.positional_embedding = nn.Parameter(torch.zeros(1, 2048, hidden_size))
332
-
333
- self.register_tokens = nn.Parameter(torch.randn(1, 16, hidden_size))
334
-
335
- self.time_embed = nn.Sequential(
336
- nn.Linear(hidden_size, 4 * hidden_size),
337
- nn.SiLU(),
338
- nn.Linear(4 * hidden_size, hidden_size),
339
- )
340
-
341
- self.blocks = nn.ModuleList(
342
- [
343
- DiTBlock(
344
- hidden_size=hidden_size,
345
- num_heads=num_heads,
346
- mlp_ratio=mlp_ratio,
347
- cross_attn_input_size=cross_attn_input_size,
348
- residual_v=residual_v,
349
- qkv_bias=train_bias_and_rms,
350
- dynamic_softmax_temperature=dynamic_softmax_temperature,
351
- )
352
- for _ in range(depth)
353
- ]
354
- )
355
-
356
- self.final_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
357
-
358
- self.final_norm = RMSNorm(hidden_size, trainable=train_bias_and_rms)
359
- self.final_proj = nn.Linear(hidden_size, patch_size * patch_size * in_channels)
360
- nn.init.zeros_(self.final_modulation[-1].weight)
361
- nn.init.zeros_(self.final_modulation[-1].bias)
362
- nn.init.zeros_(self.final_proj.weight)
363
- nn.init.zeros_(self.final_proj.bias)
364
- self.paramstatus = {}
365
- for n, p in self.named_parameters():
366
- self.paramstatus[n] = {
367
- "shape": p.shape,
368
- "requires_grad": p.requires_grad,
369
- }
370
-
371
- def save_lora_weights(self, save_directory):
372
- """Save LoRA weights to a file"""
373
- lora_state_dict = get_peft_model_state_dict(self)
374
- torch.save(lora_state_dict, f"{save_directory}/lora_weights.pt")
375
-
376
- def load_lora_weights(self, load_directory):
377
- """Load LoRA weights from a file"""
378
- lora_state_dict = torch.load(f"{load_directory}/lora_weights.pt")
379
- set_peft_model_state_dict(self, lora_state_dict)
380
-
381
- @apply_forward_hook
382
- def forward(self, x, context, timesteps):
383
- b, c, h, w = x.shape
384
- x = self.patch_embed(x) # b, T, d
385
-
386
- x = torch.cat([self.register_tokens.repeat(b, 1, 1), x], 1) # b, T + N, d
387
-
388
- if self.config.use_rope:
389
- cos, sin = self.rope(
390
- x,
391
- extend_with_register_tokens=16,
392
- height_width=(h // self.config.patch_size, w // self.config.patch_size),
393
- )
394
- else:
395
- x = x + self.positional_embedding.repeat(b, 1, 1)[:, : x.shape[1], :]
396
- cos, sin = None, None
397
-
398
- t_emb = timestep_embedding(timesteps * 1000, self.config.hidden_size).to(x.device, dtype=x.dtype)
399
- t_emb = self.time_embed(t_emb)
400
-
401
- v_0 = None
402
-
403
- for _idx, block in enumerate(self.blocks):
404
- if self.config.gradient_checkpoint:
405
- x, v = torch.utils.checkpoint.checkpoint(
406
- block,
407
- x,
408
- context,
409
- t_emb,
410
- v_0,
411
- (cos, sin),
412
- use_reentrant=False,
413
- )
414
- else:
415
- x, v = block(x, context, t_emb, v_0, (cos, sin))
416
- if v_0 is None:
417
- v_0 = v
418
-
419
- x = x[:, 16:, :]
420
- final_shift, final_scale = self.final_modulation(t_emb).chunk(2, dim=1)
421
- x = self.final_norm(x)
422
- x = x * (1 + final_scale[:, None, :]) + final_shift[:, None, :]
423
- x = self.final_proj(x)
424
-
425
- x = rearrange(
426
- x,
427
- "b (h w) (p1 p2 c) -> b c (h p1) (w p2)",
428
- h=h // self.config.patch_size,
429
- w=w // self.config.patch_size,
430
- p1=self.config.patch_size,
431
- p2=self.config.patch_size,
432
- )
433
- return x
434
-
435
-
436
- if __name__ == "__main__":
437
- model = DiT(
438
- in_channels=4,
439
- patch_size=2,
440
- hidden_size=1152,
441
- depth=28,
442
- num_heads=16,
443
- mlp_ratio=4.0,
444
- cross_attn_input_size=128,
445
- residual_v=False,
446
- train_bias_and_rms=True,
447
- use_rope=True,
448
- ).cuda()
449
- print(
450
- model(
451
- torch.randn(1, 4, 64, 64).cuda(),
452
- torch.randn(1, 37, 128).cuda(),
453
- torch.tensor([1.0]).cuda(),
454
- )
455
- )