-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
628 lines (559 loc) · 21.1 KB
/
example.py
File metadata and controls
628 lines (559 loc) · 21.1 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
from creativelib.modules.attn import AttnConfig, create_attn_from_cfg, AttnRuntime, create_attn_runtime
from creativelib.modules.core import SparseAttnConfig
import torch
import torch.nn as nn
from creativelib.utils.misc import align_up, div_up
from typing import Optional
import math
from creativelib.attn.rope import rope_apply_fused
def rope_params(max_seq_len, dim, theta=10000):
assert dim % 2 == 0
freqs = torch.outer(
torch.arange(max_seq_len),
1.0 / torch.pow(theta,
torch.arange(0, dim, 2).to(torch.float64).div(dim)))
freqs = torch.polar(torch.ones_like(freqs), freqs)
return freqs
def sinusoidal_embedding_1d(dim, position):
# preprocess
assert dim % 2 == 0
half = dim // 2
position = position.type(torch.float64)
# calculation
sinusoid = torch.outer(
position, torch.pow(10000, -torch.arange(half).to(position).div(half)))
x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
return x
def pad_freqs(original_tensor, target_len):
seq_len, s1, s2 = original_tensor.shape
pad_size = target_len - seq_len
padding_tensor = torch.ones(
pad_size,
s1,
s2,
dtype=original_tensor.dtype,
device=original_tensor.device)
padded_tensor = torch.cat([original_tensor, padding_tensor], dim=0)
return padded_tensor
def get_single_freq(freq_base, seq_length_after_cp, f, h, w, head_size: int = 128, reorder_inds: Optional[torch.Tensor] = None):
seq_len = f * h * w
c = head_size // 2
freq_base = freq_base.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
freqs_i = torch.cat([
freq_base[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
freq_base[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
freq_base[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
],
dim=-1).reshape(seq_len, 1, -1)
sp_size = 1
sp_rank = 0
if reorder_inds is not None:
freqs_i = freqs_i[reorder_inds]
# apply rotary embedding
freqs_i = pad_freqs(freqs_i, seq_length_after_cp * sp_size)
s_per_rank = seq_length_after_cp
freqs_i_rank = freqs_i[(sp_rank * s_per_rank):((sp_rank + 1) *
s_per_rank), :, :]
return freqs_i_rank.view(torch.float64).to(torch.float32)
class WanRMSNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super().__init__()
self.dim = dim
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
@torch.compile(fullgraph=True, dynamic=True)
def forward(self, x):
r"""
Args:
x(Tensor): Shape [B, L, C]
"""
return self._norm(x.float()).type_as(x) * self.weight
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
class WanLayerNorm(nn.LayerNorm):
def __init__(self, dim, eps=1e-6, elementwise_affine=False):
super().__init__(dim, elementwise_affine=elementwise_affine, eps=eps)
def forward(self, x):
r"""
Args:
x(Tensor): Shape [B, L, C]
"""
return super().forward(x.float()).type_as(x)
class WanSelfAttention(nn.Module):
def __init__(self,
dim,
num_heads,
window_size=(-1, -1),
qk_norm=True,
eps=1e-6,
attn_cfg: Optional[AttnConfig] = None):
assert dim % num_heads == 0
super().__init__()
self.dim = dim
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.window_size = window_size
self.qk_norm = qk_norm
self.eps = eps
# layers
self.q = nn.Linear(dim, dim)
self.k = nn.Linear(dim, dim)
self.v = nn.Linear(dim, dim)
self.o = nn.Linear(dim, dim)
self.norm_q = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
self.norm_k = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
if attn_cfg is None:
attn_cfg = AttnConfig("sdpa")
self.attn = create_attn_from_cfg(attn_cfg, num_heads, self.head_dim)
def forward(self, x, freqs, attn_runtime):
r"""
Args:
x(Tensor): Shape [B, L, num_heads, C / num_heads]
seq_lens(Tensor): Shape [B]
grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
"""
b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
# query, key, value function
def q_fn(x):
q = self.norm_q(self.q(x)).view(b, s, n, d)
q = rope_apply_fused(q, freqs)
return q
def k_fn(x):
k = self.norm_k(self.k(x)).view(b, s, n, d)
k = rope_apply_fused(k, freqs)
return k
def v_fn(x):
v = self.v(x).view(b, s, n, d)
return v
x = self.attn(
q_fn,
k_fn,
v_fn,
attn_runtime=attn_runtime,
x=x)
# output
x = x.flatten(2)
x = self.o(x)
return x
class WanAttentionBlock(nn.Module):
def __init__(self,
dim,
ffn_dim,
num_heads,
window_size=(-1, -1),
qk_norm=True,
cross_attn_norm=False,
eps=1e-6,
self_attn_cfg: Optional[AttnConfig] = None):
super().__init__()
self.dim = dim
self.ffn_dim = ffn_dim
self.num_heads = num_heads
self.window_size = window_size
self.qk_norm = qk_norm
self.cross_attn_norm = cross_attn_norm
self.eps = eps
# layers
self.norm1 = WanLayerNorm(dim, eps)
self.self_attn = WanSelfAttention(dim, num_heads, window_size, qk_norm,
eps, self_attn_cfg)
self.norm3 = WanLayerNorm(
dim, eps,
elementwise_affine=True) if cross_attn_norm else nn.Identity()
self.norm2 = WanLayerNorm(dim, eps)
self.ffn = nn.Sequential(
nn.Linear(dim, ffn_dim), nn.GELU(approximate='tanh'),
nn.Linear(ffn_dim, dim))
# modulation
self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
@torch.compile(dynamic=True)
def forward(
self,
x,
e,
seq_lens,
grid_sizes,
freqs,
context,
context_lens,
attn_runtime: AttnRuntime,
):
r"""
Args:
x(Tensor): Shape [B, L, C]
e(Tensor): Shape [B, 6, C]
seq_lens(Tensor): Shape [B], length of each sequence in batch
grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
"""
assert e.dtype == torch.float32
with torch.amp.autocast("cuda", dtype=torch.float32):
e = (self.modulation + e).chunk(6, dim=1)
assert e[0].dtype == torch.float32
# self-attention
y = self.self_attn(
self.norm1(x).float() * (1 + e[1]) + e[0], freqs, attn_runtime)
with torch.amp.autocast("cuda", dtype=torch.float32):
x = x + y * e[2]
# cross-attention & ffn function
def cross_attn_ffn(x, context, context_lens, e):
# for simplicity, we remove cross attn here.
x = x # + self.cross_attn(self.norm3(x), context, context_lens, is_uncond, context_nag, nag_params)
y = self.ffn(self.norm2(x).float() * (1 + e[4]) + e[3])
with torch.amp.autocast("cuda", dtype=torch.float32):
x = x + y * e[5]
return x
x = cross_attn_ffn(x, context, context_lens, e)
return x
class Head(nn.Module):
def __init__(self, dim, out_dim, patch_size, eps=1e-6):
super().__init__()
self.dim = dim
self.out_dim = out_dim
self.patch_size = patch_size
self.eps = eps
# layers
out_dim = math.prod(patch_size) * out_dim
self.norm = WanLayerNorm(dim, eps)
self.head = nn.Linear(dim, out_dim)
# modulation
self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
@torch.compile
def forward(self, x, e):
r"""
Args:
x(Tensor): Shape [B, L1, C]
e(Tensor): Shape [B, C]
"""
assert e.dtype == torch.float32
with torch.amp.autocast("cuda", dtype=torch.float32):
e = (self.modulation + e.unsqueeze(1)).chunk(2, dim=1)
x = (self.head(self.norm(x) * (1 + e[1]) + e[0]))
return x
class WanModel(nn.Module):
r"""
Wan diffusion backbone supporting both text-to-video and image-to-video.
"""
ignore_for_config = [
'patch_size', 'cross_attn_norm', 'qk_norm', 'text_dim', 'window_size'
]
_no_split_modules = ['WanAttentionBlock']
def __init__(self,
model_type='t2v',
patch_size=(1, 2, 2),
text_len=512,
in_dim=16,
dim=2048,
ffn_dim=8192,
freq_dim=256,
text_dim=4096,
out_dim=16,
num_heads=16,
num_layers=32,
window_size=(-1, -1),
qk_norm=True,
cross_attn_norm=True,
non_sparse_self_attn_cfg: Optional[AttnConfig] = None,
self_attn_cfg: Optional[AttnConfig] = None,
num_non_sparse_layers: int = 0,
# if empty use num_non_sparse_layers
non_sparse_layer_inds:Optional[list[int]] = None,
eps=1e-6):
super().__init__()
assert model_type in ['t2v', 'i2v']
self.model_type = model_type
self.patch_size = patch_size
self.text_len = text_len
self.in_dim = in_dim
self.dim = dim
self.ffn_dim = ffn_dim
self.freq_dim = freq_dim
self.text_dim = text_dim
self.out_dim = out_dim
self.num_heads = num_heads
self.num_layers = num_layers
self.window_size = window_size
self.qk_norm = qk_norm
self.cross_attn_norm = cross_attn_norm
self.eps = eps
if self_attn_cfg is None:
self_attn_cfg = AttnConfig("sdpa")
if non_sparse_self_attn_cfg is None:
non_sparse_self_attn_cfg = AttnConfig("sdpa")
self._self_attn_cfg = self_attn_cfg
self._non_sparse_self_attn_cfg = non_sparse_self_attn_cfg
num_dense_self_block = num_non_sparse_layers
# non_sparse_layer_inds = None
if non_sparse_layer_inds is None:
non_sparse_layer_inds = list(range(num_dense_self_block))
else:
assert non_sparse_layer_inds
for i in range(len(non_sparse_layer_inds)):
idx = non_sparse_layer_inds[i]
if idx < 0:
non_sparse_layer_inds[i] += num_layers
# embeddings
self.patch_embedding = nn.Conv3d(
in_dim, dim, kernel_size=patch_size, stride=patch_size)
self.text_embedding = nn.Sequential(
nn.Linear(text_dim, dim), nn.GELU(approximate='tanh'),
nn.Linear(dim, dim))
self.time_embedding = nn.Sequential(
nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6))
# blocks
attn_block_list: list[WanAttentionBlock] = []
for j in range(num_layers):
if j in non_sparse_layer_inds:
self_attn_cfg_layer = non_sparse_self_attn_cfg
else:
self_attn_cfg_layer = self_attn_cfg
attn_block_list.append(WanAttentionBlock(dim, ffn_dim, num_heads,
window_size, qk_norm, cross_attn_norm, eps,
self_attn_cfg_layer))
self.blocks = nn.ModuleList(attn_block_list)
# head
self.head = Head(dim, out_dim, patch_size, eps)
# buffers (don't use register_buffer otherwise dtype will be changed in to())
assert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0
d = dim // num_heads
with torch.device("cpu"):
# prevent outside meta init.
self.freqs = torch.cat([
rope_params(1024, d - 4 * (d // 6)),
rope_params(1024, 2 * (d // 6)),
rope_params(1024, 2 * (d // 6))
], dim=1)
def forward(
self,
x,
t,
context,
seq_len,
clip_fea=None,
y=None,
sparse_attn_cfg_override=None,
):
r"""
Forward pass through the diffusion model
Args:
x (List[Tensor]):
List of input video tensors, each with shape [C_in, F, H, W]
t (Tensor):
Diffusion timesteps tensor of shape [B]
context (List[Tensor]):
List of text embeddings each with shape [L, C]
seq_len (`int`):
Maximum sequence length for positional encoding
clip_fea (Tensor, *optional*):
CLIP image features for image-to-video mode
y (List[Tensor], *optional*):
Conditional video inputs for image-to-video mode, same shape as x
Returns:
List[Tensor]:
List of denoised video tensors with original input shapes [C_out, F, H / 8, W / 8]
"""
if self.model_type == 'i2v':
# assert clip_fea is not None and y is not None
assert y is not None
# params
device = self.patch_embedding.weight.device
if self.freqs.device != device:
self.freqs = self.freqs.to(device)
if y is not None:
x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)]
# embeddings
# run conv3d in f32 to avoid torch using slow native conv3d on 4090 + torch 2.9.1
print([u.shape for u in x])
x_tensor = torch.stack(x)
# run conv3d in f32 to avoid torch using slow native conv3d
with torch.amp.autocast("cuda", dtype=torch.float32):
x_tensor = self.patch_embedding(x_tensor)
grid_sizes = torch.stack(
[torch.tensor(u.shape[1:], dtype=torch.long) for u in x_tensor])
x_spatial_shapes = [x_tensor.shape[2:]]
x_seqlens = [x_tensor.shape[2] * x_tensor.shape[3] * x_tensor.shape[4]]
print(x_spatial_shapes, x_seqlens)
sparse_cfg = self._self_attn_cfg
if sparse_attn_cfg_override is not None:
sparse_cfg = sparse_attn_cfg_override
assert isinstance(sparse_cfg, AttnConfig)
attn_rt = create_attn_runtime([sparse_cfg, self._non_sparse_self_attn_cfg],
x_spatial_shapes, x_seqlens, x_seqlens, x[0].device)
x = x_tensor.flatten(2).transpose(1,2)
# x = [u.flatten(2).transpose(1, 2) for u in x]
seq_lens = torch.tensor([u.size(0) for u in x], dtype=torch.long)
assert seq_lens.max() <= seq_len
real_seqlen = x[0].size(0)
x = torch.stack([
torch.cat([u, u.new_zeros(seq_len - u.size(0), u.size(1))], dim=0)
for u in x
])
# time embeddings
with torch.amp.autocast("cuda", dtype=torch.float32):
e = self.time_embedding(
sinusoidal_embedding_1d(self.freq_dim, t).float())
e0 = self.time_projection(e).unflatten(1, (6, self.dim))
assert e.dtype == torch.float32 and e0.dtype == torch.float32
# context
context_lens = None
context = self.text_embedding(
torch.stack([
torch.cat(
[u, u.new_zeros(self.text_len - u.size(0), u.size(1))])
for u in context
]))
if clip_fea is not None and hasattr(self, 'img_emb'):
context_clip = self.img_emb(clip_fea) # bs x 257 x dim
context = torch.concat([context_clip, context], dim=1)
freqs_per_rank = get_single_freq(self.freqs, x.size(1), *grid_sizes[0].tolist(),
)
# arguments
kwargs = dict(
e=e0,
seq_lens=seq_lens,
grid_sizes=grid_sizes,
freqs=freqs_per_rank,
context=context,
context_lens=context_lens,
attn_runtime=attn_rt)
for block_idx, block in enumerate(self.blocks):
x = block(x, **kwargs)
# head
x = self.head(x, e)
# unpatchify
x = self.unpatchify(x, grid_sizes)
return [u.float() for u in x]
def unpatchify(self, x, grid_sizes):
r"""
Reconstruct video tensors from patch embeddings.
Args:
x (List[Tensor]):
List of patchified features, each with shape [L, C_out * prod(patch_size)]
grid_sizes (Tensor):
Original spatial-temporal grid dimensions before patching,
shape [B, 3] (3 dimensions correspond to F_patches, H_patches, W_patches)
Returns:
List[Tensor]:
Reconstructed video tensors with shape [C_out, F, H / 8, W / 8]
"""
c = self.out_dim
out = []
for u, v in zip(x, grid_sizes.tolist()):
u = u[:math.prod(v)].view(*v, *self.patch_size, c)
u = torch.einsum('fhwpqrc->cfphqwr', u)
u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)])
out.append(u)
return out
def main_simple():
sparse_cfg = SparseAttnConfig(
tile_size=[4, 4, 4],
enable_sta=False ,
sta_kernel_size=[3, 3, 3],
sta_separable=False,
enable_standalone_sta=False,
gate_per_head=False,
gate_use_sigmoid=False,
apply_gate_to_sparse=False,
always_attn_first=False,
coarse_attn_use_full_q=True,
use_mpsa=True,
use_coarse_bias=False,
use_selected_qk_in_coarse=False,
use_selected_qk_in_score=False,
scale_coarse_by_rate=True,
scale_range=[0.1, 4.0],
sparsity_override=0.8,
deterministic=False,
sage_quantization=True,
enable_tile=False,
# coarse_scale_factor=4.0,
enable_compact_tile=True,
compact_tile_d_last=True,
)
use_sparse_sage_attn = True
self_attn_cfg = AttnConfig(
type="sparse_video_attn" if use_sparse_sage_attn else "sage_gluon_4090",
vnsa_config=sparse_cfg,
)
dense_attn_cfg = AttnConfig(
type="sage_gluon_4090",
)
num_heads = 40
head_dim = 128
attn = create_attn_from_cfg(self_attn_cfg, num_heads, head_dim)
x_spatial_shapes = [[21, 52, 29]]
x_seqlens = [21 * 52 * 29]
x = torch.randn((1, x_seqlens[0], 5120), device="cuda", dtype=torch.bfloat16)
# it's recommend to use dense attn for first two transformer block.
attn_rt = create_attn_runtime([self_attn_cfg, dense_attn_cfg],
x_spatial_shapes, x_seqlens, x_seqlens, x.device)
b, s, n, d = *x.shape[:2], num_heads, head_dim
# functions is used for CP inference.
def q_fn(x):
q = x.view(b, s, n, d)
return q
def k_fn(x):
k = x.view(b, s, n, d)
return k
def v_fn(x):
v = x.view(b, s, n, d)
return v
x = attn(
q_fn,
k_fn,
v_fn,
attn_runtime=attn_rt,
x=x)
def main_wan():
sparse_cfg = SparseAttnConfig(
tile_size=[4, 4, 4],
enable_sta=False ,
sta_kernel_size=[3, 3, 3],
sta_separable=False,
enable_standalone_sta=False,
gate_per_head=False,
gate_use_sigmoid=False,
apply_gate_to_sparse=False,
always_attn_first=False,
coarse_attn_use_full_q=True,
use_mpsa=True,
use_coarse_bias=False,
use_selected_qk_in_coarse=False,
use_selected_qk_in_score=False,
scale_coarse_by_rate=True,
scale_range=[0.1, 4.0],
sparsity_override=0.8,
deterministic=False,
sage_quantization=True,
enable_tile=False,
# coarse_scale_factor=4.0,
enable_compact_tile=True,
compact_tile_d_last=True,
)
use_sparse_sage_attn = True
self_attn_cfg = AttnConfig(
type="sparse_video_attn" if use_sparse_sage_attn else "sage_gluon_4090",
vnsa_config=sparse_cfg,
)
dense_attn_cfg = AttnConfig(
type="sage_gluon_4090",
)
model = WanModel(
num_heads=16,
num_layers=8,
non_sparse_self_attn_cfg=dense_attn_cfg,
self_attn_cfg=self_attn_cfg,
num_non_sparse_layers=2, # it's recommend to use dense attn for first two transformer block.
).cuda().eval().bfloat16()
x = torch.rand(16, 21, 52 * 2, 29 * 2).cuda()
t = torch.randint(0, 1000, (1,)).cuda().float()
# quantization requires padded seqlen to be multiple of 128
padded_seqlen = align_up(21 * 52 * 29, 128)
context = [torch.rand(77, 4096).cuda()]
with torch.no_grad():
with torch.amp.autocast(dtype=torch.bfloat16, device_type="cuda"):
out = model([x], t, context, padded_seqlen)
if __name__ == "__main__":
main_wan()