comdoleger commited on
Commit
3110bc4
·
verified ·
1 Parent(s): eea6325

Upload extensions_built_in/diffusion_models/f_light/src/model.py with huggingface_hub

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