linyq commited on
Commit
178903b
Β·
verified Β·
1 Parent(s): 0555521

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ processor/tokenizer.json filter=lfs diff=lfs merge=lfs -text
__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from pipeline_kiwi_edit import KiwiEditPipeline
2
+ from mllm_encoder import MLLMEncoder
3
+ from conditional_embedder import ConditionalEmbedder
4
+ from wan_video_vae import VAE
conditional_embedder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers import ModelMixin, ConfigMixin
4
+ from diffusers.configuration_utils import register_to_config
5
+
6
+
7
+ class ConditionalEmbedder(ModelMixin, ConfigMixin):
8
+ """
9
+ Patchifies VAE-encoded conditions (source video or reference image)
10
+ into the DiT hidden dimension space via a Conv3d layer.
11
+ """
12
+
13
+ @register_to_config
14
+ def __init__(
15
+ self,
16
+ in_dim: int = 48,
17
+ dim: int = 3072,
18
+ patch_size: list = [1, 2, 2],
19
+ zero_init: bool = True,
20
+ ref_pad_first: bool = False,
21
+ ):
22
+ super().__init__()
23
+ kernel_size = tuple(patch_size)
24
+ self.patch_embedding = nn.Conv3d(
25
+ in_dim, dim, kernel_size=kernel_size, stride=kernel_size
26
+ )
27
+ self.ref_pad_first = ref_pad_first
28
+ if zero_init:
29
+ nn.init.zeros_(self.patch_embedding.weight)
30
+ nn.init.zeros_(self.patch_embedding.bias)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ return self.patch_embedding(x)
mllm_encoder.py ADDED
The diff for this file is too large to render. See raw diff
 
mllm_encoder/config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MLLMEncoder",
3
+ "mllm_model_path": ".",
4
+ "dit_dim": 3072,
5
+ "hidden_size": 2048,
6
+ "num_image_queries": 256,
7
+ "num_video_queries": 512,
8
+ "num_ref_queries": 768,
9
+ "max_object_token": 768,
10
+ "max_frames": 16,
11
+ "max_pixels_per_frame": 262144
12
+ }
mllm_encoder/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:612131bc36e0dfa384a95941b0483de1cdc1d2a10f1c4f49796bef3f566a6fc3
3
+ size 69231584
mllm_encoder/generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 1e-06,
11
+ "transformers_version": "4.57.0"
12
+ }
mllm_encoder/mllm_encoder.py ADDED
The diff for this file is too large to render. See raw diff
 
mllm_encoder/model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4dd12239c2db267952735c5b0edf15c057491dc2139dfe0841ed0ab39a75ca90
3
+ size 4997750760
mllm_encoder/model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd9647e6ebf6a937937d3e3c39c2a54471b37dceedb9d20f9162152ee96c8108
3
+ size 2511587184
mllm_encoder/model.safetensors.index.json ADDED
@@ -0,0 +1,832 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_parameters": 3754622976,
4
+ "total_size": 7509245952
5
+ },
6
+ "weight_map": {
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
19
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
31
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.10.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.10.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
41
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.10.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
43
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.11.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.11.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
53
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.11.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
55
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.12.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.12.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
65
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.12.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
67
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.13.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.13.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
77
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.13.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
79
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.14.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.14.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
89
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.14.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
91
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.15.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.15.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
101
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.15.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
103
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
113
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
114
+ "model.layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
115
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.17.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.17.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
125
+ "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
126
+ "model.layers.17.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
127
+ "model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
129
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.18.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.18.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
137
+ "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.18.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
139
+ "model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
140
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
143
+ "model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
144
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.19.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.19.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
149
+ "model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.19.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
151
+ "model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
155
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
157
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
160
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
161
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
162
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
163
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
164
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
165
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
166
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
167
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
168
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
169
+ "model.layers.20.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
172
+ "model.layers.20.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
173
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
174
+ "model.layers.20.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
175
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
176
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
177
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
178
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
179
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
180
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
181
+ "model.layers.21.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
184
+ "model.layers.21.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
185
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
186
+ "model.layers.21.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
187
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
188
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
189
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
190
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
191
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
192
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
193
+ "model.layers.22.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
196
+ "model.layers.22.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
197
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
198
+ "model.layers.22.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
199
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
200
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
201
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
202
+ "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
203
+ "model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
204
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
205
+ "model.layers.23.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
208
+ "model.layers.23.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
209
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
210
+ "model.layers.23.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
211
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
212
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
213
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
214
+ "model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
215
+ "model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
216
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
217
+ "model.layers.24.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
218
+ "model.layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
219
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
220
+ "model.layers.24.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
221
+ "model.layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
222
+ "model.layers.24.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
223
+ "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
224
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
225
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
226
+ "model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
227
+ "model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
228
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
229
+ "model.layers.25.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
230
+ "model.layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
231
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
232
+ "model.layers.25.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
233
+ "model.layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
234
+ "model.layers.25.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
235
+ "model.layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
236
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
237
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
238
+ "model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
239
+ "model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
240
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
241
+ "model.layers.26.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
242
+ "model.layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
243
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
244
+ "model.layers.26.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
245
+ "model.layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
246
+ "model.layers.26.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
247
+ "model.layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
248
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
249
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
250
+ "model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
251
+ "model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
252
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
253
+ "model.layers.27.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
254
+ "model.layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
255
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
256
+ "model.layers.27.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
257
+ "model.layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
258
+ "model.layers.27.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
259
+ "model.layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
260
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
261
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
262
+ "model.layers.28.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
263
+ "model.layers.28.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
264
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
265
+ "model.layers.28.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
266
+ "model.layers.28.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
267
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
268
+ "model.layers.28.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
269
+ "model.layers.28.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
270
+ "model.layers.28.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
271
+ "model.layers.28.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
272
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
273
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
274
+ "model.layers.29.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
275
+ "model.layers.29.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
276
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
277
+ "model.layers.29.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
278
+ "model.layers.29.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
279
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
280
+ "model.layers.29.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
281
+ "model.layers.29.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
282
+ "model.layers.29.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
283
+ "model.layers.29.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
284
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
285
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
286
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
287
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
288
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
289
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
290
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
291
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
292
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
293
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
294
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
295
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
296
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
297
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
298
+ "model.layers.30.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
299
+ "model.layers.30.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
300
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
301
+ "model.layers.30.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
302
+ "model.layers.30.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
303
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
304
+ "model.layers.30.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
305
+ "model.layers.30.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
306
+ "model.layers.30.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
307
+ "model.layers.30.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
308
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
309
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
310
+ "model.layers.31.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
311
+ "model.layers.31.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
312
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
313
+ "model.layers.31.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
314
+ "model.layers.31.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
315
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
316
+ "model.layers.31.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
317
+ "model.layers.31.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
318
+ "model.layers.31.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
319
+ "model.layers.31.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
320
+ "model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors",
321
+ "model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
322
+ "model.layers.32.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
323
+ "model.layers.32.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
324
+ "model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
325
+ "model.layers.32.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
326
+ "model.layers.32.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
327
+ "model.layers.32.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
328
+ "model.layers.32.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
329
+ "model.layers.32.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
330
+ "model.layers.32.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
331
+ "model.layers.32.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
332
+ "model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors",
333
+ "model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
334
+ "model.layers.33.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
335
+ "model.layers.33.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
336
+ "model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
337
+ "model.layers.33.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
338
+ "model.layers.33.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
339
+ "model.layers.33.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
340
+ "model.layers.33.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
341
+ "model.layers.33.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
342
+ "model.layers.33.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
343
+ "model.layers.33.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
344
+ "model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors",
345
+ "model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
346
+ "model.layers.34.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
347
+ "model.layers.34.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
348
+ "model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
349
+ "model.layers.34.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
350
+ "model.layers.34.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
351
+ "model.layers.34.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
352
+ "model.layers.34.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
353
+ "model.layers.34.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
354
+ "model.layers.34.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
355
+ "model.layers.34.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
356
+ "model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors",
357
+ "model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
358
+ "model.layers.35.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
359
+ "model.layers.35.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
360
+ "model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
361
+ "model.layers.35.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
362
+ "model.layers.35.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
363
+ "model.layers.35.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
364
+ "model.layers.35.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
365
+ "model.layers.35.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
366
+ "model.layers.35.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
367
+ "model.layers.35.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
368
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
369
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
370
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
371
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
372
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
373
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
374
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
375
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
376
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
377
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
378
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
379
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
380
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
381
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
382
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
383
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
384
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
385
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
386
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
387
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
388
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
389
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
390
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
391
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
392
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
393
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
394
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
395
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
396
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
397
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
398
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
399
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
400
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
401
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
402
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
403
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
404
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
405
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
406
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
407
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
408
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
409
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
410
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
411
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
412
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
413
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
414
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
415
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
416
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
417
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
418
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
419
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
420
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
421
+ "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
422
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
423
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
424
+ "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
425
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
426
+ "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
427
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
428
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
429
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
430
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
431
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
432
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
433
+ "model.layers.9.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
434
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
435
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
436
+ "model.layers.9.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
437
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
438
+ "model.layers.9.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
439
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
440
+ "model.norm.weight": "model-00002-of-00002.safetensors",
441
+ "visual.blocks.0.attn.proj.bias": "model-00001-of-00002.safetensors",
442
+ "visual.blocks.0.attn.proj.weight": "model-00001-of-00002.safetensors",
443
+ "visual.blocks.0.attn.qkv.bias": "model-00001-of-00002.safetensors",
444
+ "visual.blocks.0.attn.qkv.weight": "model-00001-of-00002.safetensors",
445
+ "visual.blocks.0.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
446
+ "visual.blocks.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
447
+ "visual.blocks.0.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
448
+ "visual.blocks.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
449
+ "visual.blocks.0.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
450
+ "visual.blocks.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
451
+ "visual.blocks.0.norm1.weight": "model-00001-of-00002.safetensors",
452
+ "visual.blocks.0.norm2.weight": "model-00001-of-00002.safetensors",
453
+ "visual.blocks.1.attn.proj.bias": "model-00001-of-00002.safetensors",
454
+ "visual.blocks.1.attn.proj.weight": "model-00001-of-00002.safetensors",
455
+ "visual.blocks.1.attn.qkv.bias": "model-00001-of-00002.safetensors",
456
+ "visual.blocks.1.attn.qkv.weight": "model-00001-of-00002.safetensors",
457
+ "visual.blocks.1.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
458
+ "visual.blocks.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
459
+ "visual.blocks.1.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
460
+ "visual.blocks.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
461
+ "visual.blocks.1.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
462
+ "visual.blocks.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
463
+ "visual.blocks.1.norm1.weight": "model-00001-of-00002.safetensors",
464
+ "visual.blocks.1.norm2.weight": "model-00001-of-00002.safetensors",
465
+ "visual.blocks.10.attn.proj.bias": "model-00001-of-00002.safetensors",
466
+ "visual.blocks.10.attn.proj.weight": "model-00001-of-00002.safetensors",
467
+ "visual.blocks.10.attn.qkv.bias": "model-00001-of-00002.safetensors",
468
+ "visual.blocks.10.attn.qkv.weight": "model-00001-of-00002.safetensors",
469
+ "visual.blocks.10.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
470
+ "visual.blocks.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
471
+ "visual.blocks.10.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
472
+ "visual.blocks.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
473
+ "visual.blocks.10.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
474
+ "visual.blocks.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
475
+ "visual.blocks.10.norm1.weight": "model-00001-of-00002.safetensors",
476
+ "visual.blocks.10.norm2.weight": "model-00001-of-00002.safetensors",
477
+ "visual.blocks.11.attn.proj.bias": "model-00001-of-00002.safetensors",
478
+ "visual.blocks.11.attn.proj.weight": "model-00001-of-00002.safetensors",
479
+ "visual.blocks.11.attn.qkv.bias": "model-00001-of-00002.safetensors",
480
+ "visual.blocks.11.attn.qkv.weight": "model-00001-of-00002.safetensors",
481
+ "visual.blocks.11.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
482
+ "visual.blocks.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
483
+ "visual.blocks.11.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
484
+ "visual.blocks.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
485
+ "visual.blocks.11.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
486
+ "visual.blocks.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
487
+ "visual.blocks.11.norm1.weight": "model-00001-of-00002.safetensors",
488
+ "visual.blocks.11.norm2.weight": "model-00001-of-00002.safetensors",
489
+ "visual.blocks.12.attn.proj.bias": "model-00001-of-00002.safetensors",
490
+ "visual.blocks.12.attn.proj.weight": "model-00001-of-00002.safetensors",
491
+ "visual.blocks.12.attn.qkv.bias": "model-00001-of-00002.safetensors",
492
+ "visual.blocks.12.attn.qkv.weight": "model-00001-of-00002.safetensors",
493
+ "visual.blocks.12.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
494
+ "visual.blocks.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
495
+ "visual.blocks.12.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
496
+ "visual.blocks.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
497
+ "visual.blocks.12.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
498
+ "visual.blocks.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
499
+ "visual.blocks.12.norm1.weight": "model-00001-of-00002.safetensors",
500
+ "visual.blocks.12.norm2.weight": "model-00001-of-00002.safetensors",
501
+ "visual.blocks.13.attn.proj.bias": "model-00001-of-00002.safetensors",
502
+ "visual.blocks.13.attn.proj.weight": "model-00001-of-00002.safetensors",
503
+ "visual.blocks.13.attn.qkv.bias": "model-00001-of-00002.safetensors",
504
+ "visual.blocks.13.attn.qkv.weight": "model-00001-of-00002.safetensors",
505
+ "visual.blocks.13.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
506
+ "visual.blocks.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
507
+ "visual.blocks.13.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
508
+ "visual.blocks.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
509
+ "visual.blocks.13.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
510
+ "visual.blocks.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
511
+ "visual.blocks.13.norm1.weight": "model-00001-of-00002.safetensors",
512
+ "visual.blocks.13.norm2.weight": "model-00001-of-00002.safetensors",
513
+ "visual.blocks.14.attn.proj.bias": "model-00001-of-00002.safetensors",
514
+ "visual.blocks.14.attn.proj.weight": "model-00001-of-00002.safetensors",
515
+ "visual.blocks.14.attn.qkv.bias": "model-00001-of-00002.safetensors",
516
+ "visual.blocks.14.attn.qkv.weight": "model-00001-of-00002.safetensors",
517
+ "visual.blocks.14.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
518
+ "visual.blocks.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
519
+ "visual.blocks.14.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
520
+ "visual.blocks.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
521
+ "visual.blocks.14.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
522
+ "visual.blocks.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
523
+ "visual.blocks.14.norm1.weight": "model-00001-of-00002.safetensors",
524
+ "visual.blocks.14.norm2.weight": "model-00001-of-00002.safetensors",
525
+ "visual.blocks.15.attn.proj.bias": "model-00001-of-00002.safetensors",
526
+ "visual.blocks.15.attn.proj.weight": "model-00001-of-00002.safetensors",
527
+ "visual.blocks.15.attn.qkv.bias": "model-00001-of-00002.safetensors",
528
+ "visual.blocks.15.attn.qkv.weight": "model-00001-of-00002.safetensors",
529
+ "visual.blocks.15.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
530
+ "visual.blocks.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
531
+ "visual.blocks.15.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
532
+ "visual.blocks.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
533
+ "visual.blocks.15.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
534
+ "visual.blocks.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
535
+ "visual.blocks.15.norm1.weight": "model-00001-of-00002.safetensors",
536
+ "visual.blocks.15.norm2.weight": "model-00001-of-00002.safetensors",
537
+ "visual.blocks.16.attn.proj.bias": "model-00001-of-00002.safetensors",
538
+ "visual.blocks.16.attn.proj.weight": "model-00001-of-00002.safetensors",
539
+ "visual.blocks.16.attn.qkv.bias": "model-00001-of-00002.safetensors",
540
+ "visual.blocks.16.attn.qkv.weight": "model-00001-of-00002.safetensors",
541
+ "visual.blocks.16.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
542
+ "visual.blocks.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
543
+ "visual.blocks.16.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
544
+ "visual.blocks.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
545
+ "visual.blocks.16.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
546
+ "visual.blocks.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
547
+ "visual.blocks.16.norm1.weight": "model-00001-of-00002.safetensors",
548
+ "visual.blocks.16.norm2.weight": "model-00001-of-00002.safetensors",
549
+ "visual.blocks.17.attn.proj.bias": "model-00001-of-00002.safetensors",
550
+ "visual.blocks.17.attn.proj.weight": "model-00001-of-00002.safetensors",
551
+ "visual.blocks.17.attn.qkv.bias": "model-00001-of-00002.safetensors",
552
+ "visual.blocks.17.attn.qkv.weight": "model-00001-of-00002.safetensors",
553
+ "visual.blocks.17.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
554
+ "visual.blocks.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
555
+ "visual.blocks.17.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
556
+ "visual.blocks.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
557
+ "visual.blocks.17.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
558
+ "visual.blocks.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
559
+ "visual.blocks.17.norm1.weight": "model-00001-of-00002.safetensors",
560
+ "visual.blocks.17.norm2.weight": "model-00001-of-00002.safetensors",
561
+ "visual.blocks.18.attn.proj.bias": "model-00001-of-00002.safetensors",
562
+ "visual.blocks.18.attn.proj.weight": "model-00001-of-00002.safetensors",
563
+ "visual.blocks.18.attn.qkv.bias": "model-00001-of-00002.safetensors",
564
+ "visual.blocks.18.attn.qkv.weight": "model-00001-of-00002.safetensors",
565
+ "visual.blocks.18.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
566
+ "visual.blocks.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
567
+ "visual.blocks.18.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
568
+ "visual.blocks.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
569
+ "visual.blocks.18.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
570
+ "visual.blocks.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
571
+ "visual.blocks.18.norm1.weight": "model-00001-of-00002.safetensors",
572
+ "visual.blocks.18.norm2.weight": "model-00001-of-00002.safetensors",
573
+ "visual.blocks.19.attn.proj.bias": "model-00001-of-00002.safetensors",
574
+ "visual.blocks.19.attn.proj.weight": "model-00001-of-00002.safetensors",
575
+ "visual.blocks.19.attn.qkv.bias": "model-00001-of-00002.safetensors",
576
+ "visual.blocks.19.attn.qkv.weight": "model-00001-of-00002.safetensors",
577
+ "visual.blocks.19.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
578
+ "visual.blocks.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
579
+ "visual.blocks.19.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
580
+ "visual.blocks.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
581
+ "visual.blocks.19.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
582
+ "visual.blocks.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
583
+ "visual.blocks.19.norm1.weight": "model-00001-of-00002.safetensors",
584
+ "visual.blocks.19.norm2.weight": "model-00001-of-00002.safetensors",
585
+ "visual.blocks.2.attn.proj.bias": "model-00001-of-00002.safetensors",
586
+ "visual.blocks.2.attn.proj.weight": "model-00001-of-00002.safetensors",
587
+ "visual.blocks.2.attn.qkv.bias": "model-00001-of-00002.safetensors",
588
+ "visual.blocks.2.attn.qkv.weight": "model-00001-of-00002.safetensors",
589
+ "visual.blocks.2.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
590
+ "visual.blocks.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
591
+ "visual.blocks.2.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
592
+ "visual.blocks.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
593
+ "visual.blocks.2.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
594
+ "visual.blocks.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
595
+ "visual.blocks.2.norm1.weight": "model-00001-of-00002.safetensors",
596
+ "visual.blocks.2.norm2.weight": "model-00001-of-00002.safetensors",
597
+ "visual.blocks.20.attn.proj.bias": "model-00001-of-00002.safetensors",
598
+ "visual.blocks.20.attn.proj.weight": "model-00001-of-00002.safetensors",
599
+ "visual.blocks.20.attn.qkv.bias": "model-00001-of-00002.safetensors",
600
+ "visual.blocks.20.attn.qkv.weight": "model-00001-of-00002.safetensors",
601
+ "visual.blocks.20.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
602
+ "visual.blocks.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
603
+ "visual.blocks.20.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
604
+ "visual.blocks.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
605
+ "visual.blocks.20.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
606
+ "visual.blocks.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
607
+ "visual.blocks.20.norm1.weight": "model-00001-of-00002.safetensors",
608
+ "visual.blocks.20.norm2.weight": "model-00001-of-00002.safetensors",
609
+ "visual.blocks.21.attn.proj.bias": "model-00001-of-00002.safetensors",
610
+ "visual.blocks.21.attn.proj.weight": "model-00001-of-00002.safetensors",
611
+ "visual.blocks.21.attn.qkv.bias": "model-00001-of-00002.safetensors",
612
+ "visual.blocks.21.attn.qkv.weight": "model-00001-of-00002.safetensors",
613
+ "visual.blocks.21.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
614
+ "visual.blocks.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
615
+ "visual.blocks.21.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
616
+ "visual.blocks.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
617
+ "visual.blocks.21.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
618
+ "visual.blocks.21.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
619
+ "visual.blocks.21.norm1.weight": "model-00001-of-00002.safetensors",
620
+ "visual.blocks.21.norm2.weight": "model-00001-of-00002.safetensors",
621
+ "visual.blocks.22.attn.proj.bias": "model-00001-of-00002.safetensors",
622
+ "visual.blocks.22.attn.proj.weight": "model-00001-of-00002.safetensors",
623
+ "visual.blocks.22.attn.qkv.bias": "model-00001-of-00002.safetensors",
624
+ "visual.blocks.22.attn.qkv.weight": "model-00001-of-00002.safetensors",
625
+ "visual.blocks.22.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
626
+ "visual.blocks.22.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
627
+ "visual.blocks.22.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
628
+ "visual.blocks.22.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
629
+ "visual.blocks.22.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
630
+ "visual.blocks.22.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
631
+ "visual.blocks.22.norm1.weight": "model-00001-of-00002.safetensors",
632
+ "visual.blocks.22.norm2.weight": "model-00001-of-00002.safetensors",
633
+ "visual.blocks.23.attn.proj.bias": "model-00001-of-00002.safetensors",
634
+ "visual.blocks.23.attn.proj.weight": "model-00001-of-00002.safetensors",
635
+ "visual.blocks.23.attn.qkv.bias": "model-00001-of-00002.safetensors",
636
+ "visual.blocks.23.attn.qkv.weight": "model-00001-of-00002.safetensors",
637
+ "visual.blocks.23.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
638
+ "visual.blocks.23.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
639
+ "visual.blocks.23.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
640
+ "visual.blocks.23.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
641
+ "visual.blocks.23.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
642
+ "visual.blocks.23.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
643
+ "visual.blocks.23.norm1.weight": "model-00001-of-00002.safetensors",
644
+ "visual.blocks.23.norm2.weight": "model-00001-of-00002.safetensors",
645
+ "visual.blocks.24.attn.proj.bias": "model-00001-of-00002.safetensors",
646
+ "visual.blocks.24.attn.proj.weight": "model-00001-of-00002.safetensors",
647
+ "visual.blocks.24.attn.qkv.bias": "model-00001-of-00002.safetensors",
648
+ "visual.blocks.24.attn.qkv.weight": "model-00001-of-00002.safetensors",
649
+ "visual.blocks.24.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
650
+ "visual.blocks.24.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
651
+ "visual.blocks.24.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
652
+ "visual.blocks.24.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
653
+ "visual.blocks.24.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
654
+ "visual.blocks.24.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
655
+ "visual.blocks.24.norm1.weight": "model-00001-of-00002.safetensors",
656
+ "visual.blocks.24.norm2.weight": "model-00001-of-00002.safetensors",
657
+ "visual.blocks.25.attn.proj.bias": "model-00001-of-00002.safetensors",
658
+ "visual.blocks.25.attn.proj.weight": "model-00001-of-00002.safetensors",
659
+ "visual.blocks.25.attn.qkv.bias": "model-00001-of-00002.safetensors",
660
+ "visual.blocks.25.attn.qkv.weight": "model-00001-of-00002.safetensors",
661
+ "visual.blocks.25.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
662
+ "visual.blocks.25.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
663
+ "visual.blocks.25.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
664
+ "visual.blocks.25.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
665
+ "visual.blocks.25.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
666
+ "visual.blocks.25.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
667
+ "visual.blocks.25.norm1.weight": "model-00001-of-00002.safetensors",
668
+ "visual.blocks.25.norm2.weight": "model-00001-of-00002.safetensors",
669
+ "visual.blocks.26.attn.proj.bias": "model-00001-of-00002.safetensors",
670
+ "visual.blocks.26.attn.proj.weight": "model-00001-of-00002.safetensors",
671
+ "visual.blocks.26.attn.qkv.bias": "model-00001-of-00002.safetensors",
672
+ "visual.blocks.26.attn.qkv.weight": "model-00001-of-00002.safetensors",
673
+ "visual.blocks.26.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
674
+ "visual.blocks.26.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
675
+ "visual.blocks.26.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
676
+ "visual.blocks.26.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
677
+ "visual.blocks.26.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
678
+ "visual.blocks.26.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
679
+ "visual.blocks.26.norm1.weight": "model-00001-of-00002.safetensors",
680
+ "visual.blocks.26.norm2.weight": "model-00001-of-00002.safetensors",
681
+ "visual.blocks.27.attn.proj.bias": "model-00001-of-00002.safetensors",
682
+ "visual.blocks.27.attn.proj.weight": "model-00001-of-00002.safetensors",
683
+ "visual.blocks.27.attn.qkv.bias": "model-00001-of-00002.safetensors",
684
+ "visual.blocks.27.attn.qkv.weight": "model-00001-of-00002.safetensors",
685
+ "visual.blocks.27.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
686
+ "visual.blocks.27.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
687
+ "visual.blocks.27.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
688
+ "visual.blocks.27.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
689
+ "visual.blocks.27.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
690
+ "visual.blocks.27.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
691
+ "visual.blocks.27.norm1.weight": "model-00001-of-00002.safetensors",
692
+ "visual.blocks.27.norm2.weight": "model-00001-of-00002.safetensors",
693
+ "visual.blocks.28.attn.proj.bias": "model-00001-of-00002.safetensors",
694
+ "visual.blocks.28.attn.proj.weight": "model-00001-of-00002.safetensors",
695
+ "visual.blocks.28.attn.qkv.bias": "model-00001-of-00002.safetensors",
696
+ "visual.blocks.28.attn.qkv.weight": "model-00001-of-00002.safetensors",
697
+ "visual.blocks.28.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
698
+ "visual.blocks.28.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
699
+ "visual.blocks.28.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
700
+ "visual.blocks.28.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
701
+ "visual.blocks.28.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
702
+ "visual.blocks.28.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
703
+ "visual.blocks.28.norm1.weight": "model-00001-of-00002.safetensors",
704
+ "visual.blocks.28.norm2.weight": "model-00001-of-00002.safetensors",
705
+ "visual.blocks.29.attn.proj.bias": "model-00001-of-00002.safetensors",
706
+ "visual.blocks.29.attn.proj.weight": "model-00001-of-00002.safetensors",
707
+ "visual.blocks.29.attn.qkv.bias": "model-00001-of-00002.safetensors",
708
+ "visual.blocks.29.attn.qkv.weight": "model-00001-of-00002.safetensors",
709
+ "visual.blocks.29.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
710
+ "visual.blocks.29.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
711
+ "visual.blocks.29.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
712
+ "visual.blocks.29.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
713
+ "visual.blocks.29.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
714
+ "visual.blocks.29.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
715
+ "visual.blocks.29.norm1.weight": "model-00001-of-00002.safetensors",
716
+ "visual.blocks.29.norm2.weight": "model-00001-of-00002.safetensors",
717
+ "visual.blocks.3.attn.proj.bias": "model-00001-of-00002.safetensors",
718
+ "visual.blocks.3.attn.proj.weight": "model-00001-of-00002.safetensors",
719
+ "visual.blocks.3.attn.qkv.bias": "model-00001-of-00002.safetensors",
720
+ "visual.blocks.3.attn.qkv.weight": "model-00001-of-00002.safetensors",
721
+ "visual.blocks.3.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
722
+ "visual.blocks.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
723
+ "visual.blocks.3.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
724
+ "visual.blocks.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
725
+ "visual.blocks.3.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
726
+ "visual.blocks.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
727
+ "visual.blocks.3.norm1.weight": "model-00001-of-00002.safetensors",
728
+ "visual.blocks.3.norm2.weight": "model-00001-of-00002.safetensors",
729
+ "visual.blocks.30.attn.proj.bias": "model-00001-of-00002.safetensors",
730
+ "visual.blocks.30.attn.proj.weight": "model-00001-of-00002.safetensors",
731
+ "visual.blocks.30.attn.qkv.bias": "model-00001-of-00002.safetensors",
732
+ "visual.blocks.30.attn.qkv.weight": "model-00001-of-00002.safetensors",
733
+ "visual.blocks.30.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
734
+ "visual.blocks.30.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
735
+ "visual.blocks.30.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
736
+ "visual.blocks.30.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
737
+ "visual.blocks.30.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
738
+ "visual.blocks.30.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
739
+ "visual.blocks.30.norm1.weight": "model-00001-of-00002.safetensors",
740
+ "visual.blocks.30.norm2.weight": "model-00001-of-00002.safetensors",
741
+ "visual.blocks.31.attn.proj.bias": "model-00001-of-00002.safetensors",
742
+ "visual.blocks.31.attn.proj.weight": "model-00001-of-00002.safetensors",
743
+ "visual.blocks.31.attn.qkv.bias": "model-00001-of-00002.safetensors",
744
+ "visual.blocks.31.attn.qkv.weight": "model-00001-of-00002.safetensors",
745
+ "visual.blocks.31.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
746
+ "visual.blocks.31.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
747
+ "visual.blocks.31.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
748
+ "visual.blocks.31.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
749
+ "visual.blocks.31.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
750
+ "visual.blocks.31.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
751
+ "visual.blocks.31.norm1.weight": "model-00001-of-00002.safetensors",
752
+ "visual.blocks.31.norm2.weight": "model-00001-of-00002.safetensors",
753
+ "visual.blocks.4.attn.proj.bias": "model-00001-of-00002.safetensors",
754
+ "visual.blocks.4.attn.proj.weight": "model-00001-of-00002.safetensors",
755
+ "visual.blocks.4.attn.qkv.bias": "model-00001-of-00002.safetensors",
756
+ "visual.blocks.4.attn.qkv.weight": "model-00001-of-00002.safetensors",
757
+ "visual.blocks.4.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
758
+ "visual.blocks.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
759
+ "visual.blocks.4.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
760
+ "visual.blocks.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
761
+ "visual.blocks.4.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
762
+ "visual.blocks.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
763
+ "visual.blocks.4.norm1.weight": "model-00001-of-00002.safetensors",
764
+ "visual.blocks.4.norm2.weight": "model-00001-of-00002.safetensors",
765
+ "visual.blocks.5.attn.proj.bias": "model-00001-of-00002.safetensors",
766
+ "visual.blocks.5.attn.proj.weight": "model-00001-of-00002.safetensors",
767
+ "visual.blocks.5.attn.qkv.bias": "model-00001-of-00002.safetensors",
768
+ "visual.blocks.5.attn.qkv.weight": "model-00001-of-00002.safetensors",
769
+ "visual.blocks.5.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
770
+ "visual.blocks.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
771
+ "visual.blocks.5.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
772
+ "visual.blocks.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
773
+ "visual.blocks.5.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
774
+ "visual.blocks.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
775
+ "visual.blocks.5.norm1.weight": "model-00001-of-00002.safetensors",
776
+ "visual.blocks.5.norm2.weight": "model-00001-of-00002.safetensors",
777
+ "visual.blocks.6.attn.proj.bias": "model-00001-of-00002.safetensors",
778
+ "visual.blocks.6.attn.proj.weight": "model-00001-of-00002.safetensors",
779
+ "visual.blocks.6.attn.qkv.bias": "model-00001-of-00002.safetensors",
780
+ "visual.blocks.6.attn.qkv.weight": "model-00001-of-00002.safetensors",
781
+ "visual.blocks.6.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
782
+ "visual.blocks.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
783
+ "visual.blocks.6.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
784
+ "visual.blocks.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
785
+ "visual.blocks.6.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
786
+ "visual.blocks.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
787
+ "visual.blocks.6.norm1.weight": "model-00001-of-00002.safetensors",
788
+ "visual.blocks.6.norm2.weight": "model-00001-of-00002.safetensors",
789
+ "visual.blocks.7.attn.proj.bias": "model-00001-of-00002.safetensors",
790
+ "visual.blocks.7.attn.proj.weight": "model-00001-of-00002.safetensors",
791
+ "visual.blocks.7.attn.qkv.bias": "model-00001-of-00002.safetensors",
792
+ "visual.blocks.7.attn.qkv.weight": "model-00001-of-00002.safetensors",
793
+ "visual.blocks.7.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
794
+ "visual.blocks.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
795
+ "visual.blocks.7.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
796
+ "visual.blocks.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
797
+ "visual.blocks.7.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
798
+ "visual.blocks.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
799
+ "visual.blocks.7.norm1.weight": "model-00001-of-00002.safetensors",
800
+ "visual.blocks.7.norm2.weight": "model-00001-of-00002.safetensors",
801
+ "visual.blocks.8.attn.proj.bias": "model-00001-of-00002.safetensors",
802
+ "visual.blocks.8.attn.proj.weight": "model-00001-of-00002.safetensors",
803
+ "visual.blocks.8.attn.qkv.bias": "model-00001-of-00002.safetensors",
804
+ "visual.blocks.8.attn.qkv.weight": "model-00001-of-00002.safetensors",
805
+ "visual.blocks.8.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
806
+ "visual.blocks.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
807
+ "visual.blocks.8.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
808
+ "visual.blocks.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
809
+ "visual.blocks.8.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
810
+ "visual.blocks.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
811
+ "visual.blocks.8.norm1.weight": "model-00001-of-00002.safetensors",
812
+ "visual.blocks.8.norm2.weight": "model-00001-of-00002.safetensors",
813
+ "visual.blocks.9.attn.proj.bias": "model-00001-of-00002.safetensors",
814
+ "visual.blocks.9.attn.proj.weight": "model-00001-of-00002.safetensors",
815
+ "visual.blocks.9.attn.qkv.bias": "model-00001-of-00002.safetensors",
816
+ "visual.blocks.9.attn.qkv.weight": "model-00001-of-00002.safetensors",
817
+ "visual.blocks.9.mlp.down_proj.bias": "model-00001-of-00002.safetensors",
818
+ "visual.blocks.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
819
+ "visual.blocks.9.mlp.gate_proj.bias": "model-00001-of-00002.safetensors",
820
+ "visual.blocks.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
821
+ "visual.blocks.9.mlp.up_proj.bias": "model-00001-of-00002.safetensors",
822
+ "visual.blocks.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
823
+ "visual.blocks.9.norm1.weight": "model-00001-of-00002.safetensors",
824
+ "visual.blocks.9.norm2.weight": "model-00001-of-00002.safetensors",
825
+ "visual.merger.ln_q.weight": "model-00001-of-00002.safetensors",
826
+ "visual.merger.mlp.0.bias": "model-00001-of-00002.safetensors",
827
+ "visual.merger.mlp.0.weight": "model-00001-of-00002.safetensors",
828
+ "visual.merger.mlp.2.bias": "model-00001-of-00002.safetensors",
829
+ "visual.merger.mlp.2.weight": "model-00001-of-00002.safetensors",
830
+ "visual.patch_embed.proj.weight": "model-00001-of-00002.safetensors"
831
+ }
832
+ }
model_index.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": [
3
+ "pipeline_kiwi_edit",
4
+ "KiwiEditPipeline"
5
+ ],
6
+ "_diffusers_version": "0.32.0",
7
+ "processor": [
8
+ "transformers",
9
+ "AutoProcessor"
10
+ ],
11
+ "transformer": [
12
+ "diffusers",
13
+ "WanTransformer3DModel"
14
+ ],
15
+ "vae": [
16
+ "wan_video_vae",
17
+ "VAE"
18
+ ],
19
+ "scheduler": [
20
+ "diffusers",
21
+ "FlowMatchEulerDiscreteScheduler"
22
+ ],
23
+ "mllm_encoder": [
24
+ "mllm_encoder",
25
+ "MLLMEncoder"
26
+ ],
27
+ "source_embedder": [
28
+ "conditional_embedder",
29
+ "ConditionalEmbedder"
30
+ ],
31
+ "ref_embedder": [
32
+ "conditional_embedder",
33
+ "ConditionalEmbedder"
34
+ ]
35
+ }
pipeline_kiwi_edit.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import numpy as np
4
+ from typing import Optional, List, Union, Callable, Tuple
5
+ from PIL import Image, ImageOps
6
+ from einops import rearrange
7
+ from tqdm import tqdm
8
+ from diffusers import DiffusionPipeline
9
+
10
+
11
+ def sinusoidal_embedding_1d(dim, position):
12
+ """1D sinusoidal positional embedding for timesteps."""
13
+ sinusoid = torch.outer(
14
+ position.type(torch.float64),
15
+ torch.pow(
16
+ 10000,
17
+ -torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(
18
+ dim // 2
19
+ ),
20
+ ),
21
+ )
22
+ x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
23
+ return x.to(position.dtype)
24
+
25
+
26
+ def _build_rope_3d(rope_module, f, h, w, device):
27
+ """
28
+ Build 3D RoPE (cos, sin) for a given (f, h, w) grid using the
29
+ WanRotaryPosEmbed module's precomputed buffers.
30
+
31
+ Returns:
32
+ (freqs_cos, freqs_sin) each of shape [1, f*h*w, 1, head_dim]
33
+ """
34
+ split_sizes = [rope_module.t_dim, rope_module.h_dim, rope_module.w_dim]
35
+ cos_parts = rope_module.freqs_cos.split(split_sizes, dim=1)
36
+ sin_parts = rope_module.freqs_sin.split(split_sizes, dim=1)
37
+
38
+ cos_f = cos_parts[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1)
39
+ cos_h = cos_parts[1][:h].view(1, h, 1, -1).expand(f, h, w, -1)
40
+ cos_w = cos_parts[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
41
+
42
+ sin_f = sin_parts[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1)
43
+ sin_h = sin_parts[1][:h].view(1, h, 1, -1).expand(f, h, w, -1)
44
+ sin_w = sin_parts[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
45
+
46
+ freqs_cos = torch.cat([cos_f, cos_h, cos_w], dim=-1).reshape(1, f * h * w, 1, -1).to(device)
47
+ freqs_sin = torch.cat([sin_f, sin_h, sin_w], dim=-1).reshape(1, f * h * w, 1, -1).to(device)
48
+ return freqs_cos, freqs_sin
49
+
50
+
51
+ class KiwiEditPipeline(DiffusionPipeline):
52
+ """
53
+ Pipeline for reference-guided video and image editing using KiwiEdit.
54
+
55
+ This pipeline uses a Qwen2.5-VL multimodal LLM encoder for understanding
56
+ editing instructions with source visual context, a WanTransformer3DModel
57
+ for diffusion, and AutoencoderKLWan for VAE encoding/decoding.
58
+
59
+ Args:
60
+ transformer: WanTransformer3DModel - DiT backbone for denoising.
61
+ vae: AutoencoderKLWan - 3D causal VAE.
62
+ scheduler: FlowMatchEulerDiscreteScheduler or compatible scheduler.
63
+ mllm_encoder: MLLMEncoder - Qwen2.5-VL MLLM with learnable queries.
64
+ processor: AutoProcessor - Qwen2.5-VL processor/tokenizer bundle.
65
+ source_embedder: ConditionalEmbedder - VAE source conditioning.
66
+ ref_embedder: ConditionalEmbedder - VAE reference conditioning.
67
+ """
68
+
69
+ model_cpu_offload_seq = "mllm_encoder->source_embedder->ref_embedder->transformer->vae"
70
+
71
+ def __init__(
72
+ self,
73
+ transformer,
74
+ vae,
75
+ scheduler,
76
+ mllm_encoder,
77
+ source_embedder,
78
+ ref_embedder,
79
+ processor=None,
80
+ ):
81
+ super().__init__()
82
+ if isinstance(processor, (list, tuple)):
83
+ # Diffusers may pass the raw model_index spec; let MLLMEncoder resolve it later.
84
+ processor = None
85
+ self.register_modules(
86
+ transformer=transformer,
87
+ vae=vae,
88
+ scheduler=scheduler,
89
+ mllm_encoder=mllm_encoder,
90
+ processor=processor,
91
+ source_embedder=source_embedder,
92
+ ref_embedder=ref_embedder,
93
+ )
94
+ if processor is not None:
95
+ self.mllm_encoder.processor = processor
96
+
97
+ # ------------------------------------------------------------------ #
98
+ # Helper utilities #
99
+ # ------------------------------------------------------------------ #
100
+
101
+ @staticmethod
102
+ def _check_resize(height, width, num_frames, h_div=16, w_div=16, t_div=4, t_rem=1):
103
+ """Round height/width/num_frames to valid values."""
104
+ if height % h_div != 0:
105
+ height = (height + h_div - 1) // h_div * h_div
106
+ if width % w_div != 0:
107
+ width = (width + w_div - 1) // w_div * w_div
108
+ if num_frames % t_div != t_rem:
109
+ num_frames = (num_frames + t_div - 1) // t_div * t_div + t_rem
110
+ return height, width, num_frames
111
+
112
+ @staticmethod
113
+ def _preprocess_image(image: Image.Image, dtype, device):
114
+ """Convert PIL Image to tensor in [-1, 1]."""
115
+ arr = np.array(image, dtype=np.float32)
116
+ tensor = torch.from_numpy(arr).to(dtype=dtype, device=device)
117
+ tensor = tensor / 127.5 - 1.0 # [0, 255] -> [-1, 1]
118
+ tensor = tensor.permute(2, 0, 1) # H W C -> C H W
119
+ return tensor
120
+
121
+ def _preprocess_video(self, frames: List[Image.Image], dtype, device):
122
+ """Convert list of PIL Images to tensor [1, C, T, H, W] in [-1, 1]."""
123
+ tensors = [self._preprocess_image(f, dtype, device) for f in frames]
124
+ video = torch.stack(tensors, dim=1) # C T H W
125
+ return video.unsqueeze(0) # 1 C T H W
126
+
127
+ @staticmethod
128
+ def _vae_output_to_video(vae_output):
129
+ """Convert VAE output tensor to list of PIL Images."""
130
+ # vae_output shape: [B, C, T, H, W] or [T, H, W, C]
131
+ if vae_output.dim() == 5:
132
+ vae_output = vae_output.squeeze(0).permute(1, 2, 3, 0) # T H W C
133
+ frames = []
134
+ for t in range(vae_output.shape[0]):
135
+ frame = ((vae_output[t] + 1.0) * 127.5).clamp(0, 255)
136
+ frame = frame.to(device="cpu", dtype=torch.uint8).numpy()
137
+ frames.append(Image.fromarray(frame))
138
+ return frames
139
+
140
+ # ------------------------------------------------------------------ #
141
+ # Custom Flow Match Scheduler #
142
+ # ------------------------------------------------------------------ #
143
+
144
+ def _setup_scheduler(self, num_inference_steps, denoising_strength=1.0, shift=5.0):
145
+ """
146
+ Set up flow-match sigmas and timesteps matching the original diffsynth
147
+ FlowMatchScheduler with extra_one_step=True and shift.
148
+ """
149
+ sigma_min = 0.003 / 1.002
150
+ sigma_max = 1.0
151
+ sigma_start = sigma_min + (sigma_max - sigma_min) * denoising_strength
152
+ # extra_one_step: generate N+1 points, drop last
153
+ sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps + 1)[:-1]
154
+ # Apply shift
155
+ sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
156
+ timesteps = sigmas * 1000 # num_train_timesteps = 1000
157
+ return sigmas, timesteps
158
+
159
+ def _scheduler_step(self, model_output, sigmas, step_index, sample):
160
+ """Euler step for flow matching."""
161
+ sigma = sigmas[step_index]
162
+ if step_index + 1 >= len(sigmas):
163
+ sigma_next = 0.0
164
+ else:
165
+ sigma_next = sigmas[step_index + 1]
166
+ return sample + model_output * (sigma_next - sigma)
167
+
168
+ def _scheduler_add_noise(self, original_samples, noise, sigmas, step_index):
169
+ """Add noise at given timestep for img2img / video2video."""
170
+ sigma = sigmas[step_index]
171
+ return (1 - sigma) * original_samples + sigma * noise
172
+
173
+ def _scheduler_get_sigma(self, timestep, sigmas, timesteps):
174
+ """Get sigma for a given timestep."""
175
+ timestep_id = torch.argmin((timesteps - timestep).abs())
176
+ return sigmas[timestep_id]
177
+
178
+ # ------------------------------------------------------------------ #
179
+ # Transformer forward helpers #
180
+ # ------------------------------------------------------------------ #
181
+
182
+ def _model_forward(
183
+ self,
184
+ latents,
185
+ timestep,
186
+ context,
187
+ vae_source_input=None,
188
+ vae_ref_image=None,
189
+ sigmas=None,
190
+ timesteps_schedule=None,
191
+ ):
192
+ """
193
+ Custom DiT forward pass that handles source/ref conditioning.
194
+ Mirrors model_fn_wan_video from the original diffsynth pipeline.
195
+ """
196
+ device = latents.device
197
+ dtype = latents.dtype
198
+ t = self.transformer
199
+
200
+ # --- Timestep embedding ---
201
+ timestep_emb = sinusoidal_embedding_1d(
202
+ t.config.freq_dim, timestep
203
+ ).to(dtype)
204
+ time_emb = t.condition_embedder.time_embedder(timestep_emb)
205
+ # diffusers time_proj = Linear only (SiLU is applied separately)
206
+ t_mod = t.condition_embedder.time_proj(F.silu(time_emb)).unflatten(
207
+ 1, (6, t.config.num_attention_heads * t.config.attention_head_dim)
208
+ )
209
+
210
+ # --- Text/context embedding ---
211
+ # NOTE: Do NOT apply text_embedder here. The MLLM encoder's connector
212
+ # already projects to dit_dim. text_embedder is for raw text encoder
213
+ # output (text_dim β†’ dim), which doesn't apply to MLLM output.
214
+
215
+ # --- Patchify latents ---
216
+ x = latents
217
+ if vae_source_input is not None:
218
+ vae_source_cond = self.source_embedder(vae_source_input)
219
+ x = t.patch_embedding(x)
220
+ # Get sigma for this timestep
221
+ sigma = self._scheduler_get_sigma(timestep, sigmas, timesteps_schedule)
222
+ x = x + vae_source_cond * sigma
223
+ else:
224
+ x = t.patch_embedding(x)
225
+
226
+ f, h, w = x.shape[2:]
227
+ x = rearrange(x, "b c f h w -> b (f h w) c").contiguous()
228
+
229
+ # --- 3D RoPE frequencies (real-valued cos/sin format) ---
230
+ rotary_emb = _build_rope_3d(t.rope, f, h, w, device)
231
+
232
+ # --- Reference image conditioning ---
233
+ vae_ref_input_length = 0
234
+ if vae_ref_image is not None:
235
+ if len(vae_ref_image) > 1:
236
+ vae_ref = torch.cat(vae_ref_image, dim=2) # concat along temporal
237
+ else:
238
+ vae_ref = vae_ref_image[0]
239
+
240
+ vae_ref = self.ref_embedder(vae_ref)
241
+ ref_f, ref_h, ref_w = vae_ref.shape[2:]
242
+ vae_ref = rearrange(vae_ref, "b c f h w -> b (f h w) c").contiguous()
243
+
244
+ # Recompute RoPE for extended sequence (main + ref tokens)
245
+ total_f = f + ref_f
246
+ rotary_emb = _build_rope_3d(t.rope, total_f, h, w, device)
247
+
248
+ vae_ref_input_length = vae_ref.shape[1]
249
+
250
+ if self.ref_embedder.config.ref_pad_first:
251
+ x = torch.cat([vae_ref, x], dim=1)
252
+ else:
253
+ x = torch.cat([x, vae_ref], dim=1)
254
+
255
+ # --- Transformer blocks ---
256
+ for block in t.blocks:
257
+ x = block(x, context, t_mod, rotary_emb)
258
+
259
+ # --- Output head ---
260
+ # Match diffusers' FP32 norm + modulation + projection
261
+ table = t.scale_shift_table
262
+ shift, scale = (
263
+ table.to(device=device) + time_emb.unsqueeze(1)
264
+ ).chunk(2, dim=1)
265
+ shift = shift.to(device=x.device)
266
+ scale = scale.to(device=x.device)
267
+ x = (t.norm_out(x.float()) * (1 + scale) + shift).type_as(x)
268
+ x = t.proj_out(x)
269
+
270
+ # --- Remove ref tokens from output ---
271
+ if vae_ref_image is not None and vae_ref_input_length > 0:
272
+ if self.ref_embedder.config.ref_pad_first:
273
+ x = x[:, vae_ref_input_length:, :]
274
+ else:
275
+ x = x[:, :-vae_ref_input_length, :]
276
+
277
+ # --- Unpatchify ---
278
+ patch_size = t.config.patch_size
279
+ x = rearrange(
280
+ x,
281
+ "b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
282
+ f=f, h=h, w=w,
283
+ x=patch_size[0], y=patch_size[1], z=patch_size[2],
284
+ )
285
+ return x
286
+
287
+ # ------------------------------------------------------------------ #
288
+ # Main __call__ #
289
+ # ------------------------------------------------------------------ #
290
+
291
+ @torch.no_grad()
292
+ def __call__(
293
+ self,
294
+ prompt: str,
295
+ source_video: Optional[List[Image.Image]] = None,
296
+ source_input: Optional[List[Image.Image]] = None,
297
+ ref_image: Optional[List[Image.Image]] = None,
298
+ negative_prompt: Optional[str] = "",
299
+ input_video: Optional[List[Image.Image]] = None,
300
+ height: int = 480,
301
+ width: int = 832,
302
+ num_frames: int = 81,
303
+ num_inference_steps: int = 50,
304
+ guidance_scale: float = 1.0,
305
+ sigma_shift: float = 5.0,
306
+ denoising_strength: float = 1.0,
307
+ seed: Optional[int] = None,
308
+ tiled: bool = True,
309
+ tile_size: Tuple[int, int] = (30, 52),
310
+ tile_stride: Tuple[int, int] = (15, 26),
311
+ output_type: str = "pil",
312
+ progress_bar: Callable = tqdm,
313
+ ) -> List[Image.Image]:
314
+ """
315
+ Run KiwiEdit inference.
316
+
317
+ Args:
318
+ prompt: Editing instruction text.
319
+ source_video: Source video/image frames for MLLM context (also used as
320
+ source_input if source_input is not provided).
321
+ source_input: Source frames for VAE conditioning. If None but source_video
322
+ is provided, source_video is used.
323
+ ref_image: Optional reference image(s) for guided editing.
324
+ negative_prompt: Negative prompt for CFG.
325
+ input_video: Optional input video for video-to-video (adds noise then denoises).
326
+ height: Output height in pixels.
327
+ width: Output width in pixels.
328
+ num_frames: Number of output frames (1 for image editing).
329
+ num_inference_steps: Number of denoising steps.
330
+ guidance_scale: Classifier-free guidance scale.
331
+ sigma_shift: Flow matching shift parameter.
332
+ denoising_strength: How much noise to add (1.0 = full noise).
333
+ seed: Random seed for reproducibility.
334
+ tiled: Whether to use tiled VAE encoding/decoding.
335
+ tile_size: VAE tile size.
336
+ tile_stride: VAE tile stride.
337
+ output_type: "pil" for PIL Images, "latent" for raw latents.
338
+ progress_bar: Progress bar callable (e.g., tqdm).
339
+
340
+ Returns:
341
+ List of PIL Images (video frames).
342
+ """
343
+ device = self._execution_device
344
+ dtype = torch.bfloat16
345
+ # --- 1. Shape check ---
346
+ # VAE spatial factor is 16, transformer patch spatial is 2,
347
+ # so pixel dims must be multiples of 32.
348
+ height, width, num_frames = self._check_resize(
349
+ height, width, num_frames, h_div=32, w_div=32
350
+ )
351
+
352
+ # --- 2. Determine VAE parameters ---
353
+ z_dim = self.vae.config.z_dim
354
+ # Compute upsampling factor from VAE config
355
+ dim_mult = self.vae.config.get("dim_mult", [1, 2, 4, 4])
356
+ temporal_downsample = self.vae.config.get("temperal_downsample", [False, True, True])
357
+ # Wan VideoVAE spatial factor is 2^(len(dim_mult)) due to extra
358
+ # downsampling in the encoder beyond the level transitions.
359
+ spatial_factor = 2 ** len(dim_mult) # 16 for 4 levels
360
+ temporal_factor = 2 ** sum(temporal_downsample) # 4 for [F, T, T]
361
+
362
+ # --- 3. MLLM encoding ---
363
+ context = None
364
+ src_video_for_mllm = source_video
365
+ if src_video_for_mllm is not None:
366
+ self.mllm_encoder._ensure_qwen_loaded()
367
+ if ref_image is not None:
368
+ # Ref mode always uses the video path (even for a single frame)
369
+ context = self.mllm_encoder(
370
+ prompt, src_video=src_video_for_mllm, ref_image=ref_image
371
+ )
372
+ elif len(src_video_for_mllm) == 1:
373
+ context = self.mllm_encoder(
374
+ prompt, src_image=src_video_for_mllm
375
+ )
376
+ else:
377
+ context = self.mllm_encoder(
378
+ prompt, src_video=src_video_for_mllm
379
+ )
380
+ # For negative prompt: use zero context
381
+ context_nega = None
382
+
383
+ # --- 4. Setup scheduler ---
384
+ sigmas, timesteps = self._setup_scheduler(
385
+ num_inference_steps, denoising_strength, sigma_shift
386
+ )
387
+ sigmas = sigmas.to(device)
388
+ timesteps = timesteps.to(device)
389
+
390
+ # --- 5. Initialize noise ---
391
+ latent_length = (num_frames - 1) // temporal_factor + 1
392
+ latent_h = height // spatial_factor
393
+ latent_w = width // spatial_factor
394
+ shape = (1, z_dim, latent_length, latent_h, latent_w)
395
+
396
+ generator = None if seed is None else torch.Generator("cpu").manual_seed(seed)
397
+ noise = torch.randn(shape, generator=generator, device="cpu", dtype=torch.float32)
398
+ noise = noise.to(dtype=dtype, device=device)
399
+
400
+ # --- 6. Encode source input ---
401
+ vae_source_input = None
402
+ # Fall back to source_video if source_input not provided
403
+ src_for_vae = source_input if source_input is not None else source_video
404
+ if src_for_vae is not None:
405
+ src_frames = [src_for_vae[i] for i in range(min(num_frames, len(src_for_vae)))]
406
+ # Resize source frames to match the (possibly adjusted) target dimensions
407
+ src_frames = [f.resize((width, height), Image.LANCZOS) for f in src_frames]
408
+ src_tensor = self._preprocess_video(src_frames, dtype=torch.float32, device=device)
409
+ vae_source_input = self.vae.encode(src_tensor).latent_dist.sample()
410
+ vae_source_input = vae_source_input.to(dtype=dtype)
411
+
412
+ # --- 7. Encode reference images ---
413
+ vae_ref_image = None
414
+ if ref_image is not None:
415
+ vae_ref_image = []
416
+ for item in ref_image:
417
+ target_size = (width, height)
418
+ item = ImageOps.pad(item, target_size, color="white", centering=(0.5, 0.5))
419
+ ref_tensor = self._preprocess_video([item], dtype=torch.float32, device=device)
420
+ ref_latent = self.vae.encode(ref_tensor).latent_dist.sample()
421
+ vae_ref_image.append(ref_latent.to(dtype=dtype))
422
+
423
+ # --- 8. Handle input_video (video-to-video) ---
424
+ if input_video is not None:
425
+ input_tensor = self._preprocess_video(input_video, dtype=torch.float32, device=device)
426
+ input_latents = self.vae.encode(input_tensor).latent_dist.sample()
427
+ input_latents = input_latents.to(dtype=dtype)
428
+ latents = self._scheduler_add_noise(input_latents, noise, sigmas, 0)
429
+ else:
430
+ latents = noise
431
+
432
+ # --- 9. Denoising loop ---
433
+ for step_idx, timestep_val in enumerate(progress_bar(timesteps)):
434
+ timestep = timestep_val.unsqueeze(0).to(dtype=dtype, device=device)
435
+
436
+ # Positive prediction
437
+ noise_pred = self._model_forward(
438
+ latents=latents,
439
+ timestep=timestep,
440
+ context=context,
441
+ vae_source_input=vae_source_input,
442
+ vae_ref_image=vae_ref_image,
443
+ sigmas=sigmas,
444
+ timesteps_schedule=timesteps,
445
+ )
446
+
447
+ # CFG
448
+ # if guidance_scale != 1.0:
449
+ # noise_pred_nega = self._model_forward(
450
+ # latents=latents,
451
+ # timestep=timestep,
452
+ # context=context_nega,
453
+ # vae_source_input=vae_source_input,
454
+ # vae_ref_image=vae_ref_image,
455
+ # sigmas=sigmas,
456
+ # timesteps_schedule=timesteps,
457
+ # )
458
+ # noise_pred = noise_pred_nega + guidance_scale * (
459
+ # noise_pred_posi - noise_pred_nega
460
+ # )
461
+ # else:
462
+ # noise_pred = noise_pred_posi
463
+
464
+ # Scheduler step
465
+ latents = self._scheduler_step(noise_pred, sigmas, step_idx, latents)
466
+
467
+ # --- 10. Decode ---
468
+ if output_type == "latent":
469
+ return latents
470
+
471
+ video = self.vae.decode(latents).sample
472
+ video = self._vae_output_to_video(video)
473
+ return video
processor/added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
processor/chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
2
+ You are a helpful assistant.<|im_end|>
3
+ {% endif %}<|im_start|>{{ message['role'] }}
4
+ {% if message['content'] is string %}{{ message['content'] }}<|im_end|>
5
+ {% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
6
+ {% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
7
+ {% endif %}
processor/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
processor/preprocessor_config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": null,
3
+ "data_format": "channels_first",
4
+ "default_to_square": true,
5
+ "device": null,
6
+ "disable_grouping": null,
7
+ "do_center_crop": null,
8
+ "do_convert_rgb": true,
9
+ "do_normalize": true,
10
+ "do_pad": null,
11
+ "do_rescale": true,
12
+ "do_resize": true,
13
+ "image_mean": [
14
+ 0.48145466,
15
+ 0.4578275,
16
+ 0.40821073
17
+ ],
18
+ "image_processor_type": "Qwen2VLImageProcessorFast",
19
+ "image_std": [
20
+ 0.26862954,
21
+ 0.26130258,
22
+ 0.27577711
23
+ ],
24
+ "input_data_format": null,
25
+ "max_pixels": 12845056,
26
+ "merge_size": 2,
27
+ "min_pixels": 3136,
28
+ "pad_size": null,
29
+ "patch_size": 14,
30
+ "processor_class": "Qwen2_5_VLProcessor",
31
+ "resample": 3,
32
+ "rescale_factor": 0.00392156862745098,
33
+ "return_tensors": null,
34
+ "size": {
35
+ "longest_edge": 12845056,
36
+ "shortest_edge": 3136
37
+ },
38
+ "temporal_patch_size": 2
39
+ }
processor/qwen_config.json ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2_5_VLForConditionalGeneration"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "dtype": "bfloat16",
8
+ "eos_token_id": 151645,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 2048,
11
+ "image_token_id": 151655,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 11008,
14
+ "max_position_embeddings": 128000,
15
+ "max_window_layers": 70,
16
+ "model_type": "qwen2_5_vl",
17
+ "num_attention_heads": 16,
18
+ "num_hidden_layers": 36,
19
+ "num_key_value_heads": 2,
20
+ "rms_norm_eps": 1e-06,
21
+ "rope_scaling": {
22
+ "mrope_section": [
23
+ 16,
24
+ 24,
25
+ 24
26
+ ],
27
+ "rope_type": "default",
28
+ "type": "default"
29
+ },
30
+ "rope_theta": 1000000.0,
31
+ "sliding_window": 32768,
32
+ "text_config": {
33
+ "_name_or_path": "Qwen/Qwen2.5-VL-3B-Instruct",
34
+ "architectures": [
35
+ "Qwen2_5_VLForConditionalGeneration"
36
+ ],
37
+ "attention_dropout": 0.0,
38
+ "bos_token_id": 151643,
39
+ "dtype": "bfloat16",
40
+ "eos_token_id": 151645,
41
+ "hidden_act": "silu",
42
+ "hidden_size": 2048,
43
+ "initializer_range": 0.02,
44
+ "intermediate_size": 11008,
45
+ "layer_types": [
46
+ "full_attention",
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention",
52
+ "full_attention",
53
+ "full_attention",
54
+ "full_attention",
55
+ "full_attention",
56
+ "full_attention",
57
+ "full_attention",
58
+ "full_attention",
59
+ "full_attention",
60
+ "full_attention",
61
+ "full_attention",
62
+ "full_attention",
63
+ "full_attention",
64
+ "full_attention",
65
+ "full_attention",
66
+ "full_attention",
67
+ "full_attention",
68
+ "full_attention",
69
+ "full_attention",
70
+ "full_attention",
71
+ "full_attention",
72
+ "full_attention",
73
+ "full_attention",
74
+ "full_attention",
75
+ "full_attention",
76
+ "full_attention",
77
+ "full_attention",
78
+ "full_attention",
79
+ "full_attention",
80
+ "full_attention",
81
+ "full_attention"
82
+ ],
83
+ "max_position_embeddings": 128000,
84
+ "max_window_layers": 70,
85
+ "model_type": "qwen2_5_vl_text",
86
+ "num_attention_heads": 16,
87
+ "num_hidden_layers": 36,
88
+ "num_key_value_heads": 2,
89
+ "rms_norm_eps": 1e-06,
90
+ "rope_scaling": {
91
+ "mrope_section": [
92
+ 16,
93
+ 24,
94
+ 24
95
+ ],
96
+ "rope_type": "default",
97
+ "type": "default"
98
+ },
99
+ "rope_theta": 1000000.0,
100
+ "sliding_window": null,
101
+ "tie_word_embeddings": true,
102
+ "use_cache": true,
103
+ "use_sliding_window": false,
104
+ "vision_token_id": 151654,
105
+ "vocab_size": 151936
106
+ },
107
+ "transformers_version": "4.57.0",
108
+ "use_cache": true,
109
+ "use_sliding_window": false,
110
+ "video_token_id": 151656,
111
+ "vision_config": {
112
+ "depth": 32,
113
+ "dtype": "bfloat16",
114
+ "fullatt_block_indexes": [
115
+ 7,
116
+ 15,
117
+ 23,
118
+ 31
119
+ ],
120
+ "hidden_act": "silu",
121
+ "hidden_size": 1280,
122
+ "in_channels": 3,
123
+ "in_chans": 3,
124
+ "initializer_range": 0.02,
125
+ "intermediate_size": 3420,
126
+ "model_type": "qwen2_5_vl",
127
+ "num_heads": 16,
128
+ "out_hidden_size": 2048,
129
+ "patch_size": 14,
130
+ "spatial_merge_size": 2,
131
+ "spatial_patch_size": 14,
132
+ "temporal_patch_size": 2,
133
+ "tokens_per_second": 2,
134
+ "window_size": 112
135
+ },
136
+ "vision_end_token_id": 151653,
137
+ "vision_start_token_id": 151652,
138
+ "vision_token_id": 151654,
139
+ "vocab_size": 151936
140
+ }
processor/special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
processor/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
3
+ size 11421896
processor/tokenizer_config.json ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "clean_up_tokenization_spaces": false,
199
+ "eos_token": "<|im_end|>",
200
+ "errors": "replace",
201
+ "extra_special_tokens": {},
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "processor_class": "Qwen2_5_VLProcessor",
205
+ "split_special_tokens": false,
206
+ "tokenizer_class": "Qwen2Tokenizer",
207
+ "unk_token": null
208
+ }
processor/video_preprocessor_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": null,
3
+ "data_format": "channels_first",
4
+ "default_to_square": true,
5
+ "device": null,
6
+ "do_center_crop": null,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "do_sample_frames": false,
12
+ "fps": null,
13
+ "image_mean": [
14
+ 0.48145466,
15
+ 0.4578275,
16
+ 0.40821073
17
+ ],
18
+ "image_std": [
19
+ 0.26862954,
20
+ 0.26130258,
21
+ 0.27577711
22
+ ],
23
+ "input_data_format": null,
24
+ "max_frames": 768,
25
+ "max_pixels": 12845056,
26
+ "merge_size": 2,
27
+ "min_frames": 4,
28
+ "min_pixels": 3136,
29
+ "num_frames": null,
30
+ "pad_size": null,
31
+ "patch_size": 14,
32
+ "processor_class": "Qwen2_5_VLProcessor",
33
+ "resample": 3,
34
+ "rescale_factor": 0.00392156862745098,
35
+ "return_metadata": false,
36
+ "size": {
37
+ "longest_edge": 12845056,
38
+ "shortest_edge": 3136
39
+ },
40
+ "temporal_patch_size": 2,
41
+ "video_metadata": null,
42
+ "video_processor_type": "Qwen2VLVideoProcessor"
43
+ }
processor/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
ref_embedder/conditional_embedder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers import ModelMixin, ConfigMixin
4
+ from diffusers.configuration_utils import register_to_config
5
+
6
+
7
+ class ConditionalEmbedder(ModelMixin, ConfigMixin):
8
+ """
9
+ Patchifies VAE-encoded conditions (source video or reference image)
10
+ into the DiT hidden dimension space via a Conv3d layer.
11
+ """
12
+
13
+ @register_to_config
14
+ def __init__(
15
+ self,
16
+ in_dim: int = 48,
17
+ dim: int = 3072,
18
+ patch_size: list = [1, 2, 2],
19
+ zero_init: bool = True,
20
+ ref_pad_first: bool = False,
21
+ ):
22
+ super().__init__()
23
+ kernel_size = tuple(patch_size)
24
+ self.patch_embedding = nn.Conv3d(
25
+ in_dim, dim, kernel_size=kernel_size, stride=kernel_size
26
+ )
27
+ self.ref_pad_first = ref_pad_first
28
+ if zero_init:
29
+ nn.init.zeros_(self.patch_embedding.weight)
30
+ nn.init.zeros_(self.patch_embedding.bias)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ return self.patch_embedding(x)
ref_embedder/config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ConditionalEmbedder",
3
+ "in_dim": 48,
4
+ "dim": 3072,
5
+ "patch_size": [
6
+ 1,
7
+ 2,
8
+ 2
9
+ ],
10
+ "zero_init": true,
11
+ "ref_pad_first": false
12
+ }
ref_embedder/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c9ed11765605a34ef758e26182d6730374494fe56e40de57274c9b20354dca9
3
+ size 1185976
scheduler/scheduler_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "FlowMatchEulerDiscreteScheduler",
3
+ "shift": 5.0,
4
+ "num_train_timesteps": 1000,
5
+ "base_shift": 0.5,
6
+ "max_shift": 1.15
7
+ }
source_embedder/conditional_embedder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers import ModelMixin, ConfigMixin
4
+ from diffusers.configuration_utils import register_to_config
5
+
6
+
7
+ class ConditionalEmbedder(ModelMixin, ConfigMixin):
8
+ """
9
+ Patchifies VAE-encoded conditions (source video or reference image)
10
+ into the DiT hidden dimension space via a Conv3d layer.
11
+ """
12
+
13
+ @register_to_config
14
+ def __init__(
15
+ self,
16
+ in_dim: int = 48,
17
+ dim: int = 3072,
18
+ patch_size: list = [1, 2, 2],
19
+ zero_init: bool = True,
20
+ ref_pad_first: bool = False,
21
+ ):
22
+ super().__init__()
23
+ kernel_size = tuple(patch_size)
24
+ self.patch_embedding = nn.Conv3d(
25
+ in_dim, dim, kernel_size=kernel_size, stride=kernel_size
26
+ )
27
+ self.ref_pad_first = ref_pad_first
28
+ if zero_init:
29
+ nn.init.zeros_(self.patch_embedding.weight)
30
+ nn.init.zeros_(self.patch_embedding.bias)
31
+
32
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
33
+ return self.patch_embedding(x)
source_embedder/config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ConditionalEmbedder",
3
+ "in_dim": 48,
4
+ "dim": 3072,
5
+ "patch_size": [
6
+ 1,
7
+ 2,
8
+ 2
9
+ ],
10
+ "zero_init": true,
11
+ "ref_pad_first": false
12
+ }
source_embedder/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05635fdb7e5449ee24fb0f7e85e23e9ee5a347fc7bf3dc66ae013bd79248bbcb
3
+ size 1185976
transformer/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "WanTransformer3DModel",
3
+ "patch_size": [
4
+ 1,
5
+ 2,
6
+ 2
7
+ ],
8
+ "in_channels": 48,
9
+ "out_channels": 48,
10
+ "num_attention_heads": 24,
11
+ "attention_head_dim": 128,
12
+ "text_dim": 4096,
13
+ "freq_dim": 256,
14
+ "ffn_dim": 14336,
15
+ "num_layers": 30,
16
+ "cross_attn_norm": true,
17
+ "qk_norm": "rms_norm_across_heads",
18
+ "eps": 1e-06,
19
+ "rope_max_seq_len": 1024
20
+ }
transformer/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26d193a1ad14237ad691093f9415d32d866c19b164d4e0b74799e81d8d1c4bcf
3
+ size 9999660080
vae/config.json ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "VAE",
3
+ "z_dim": 48,
4
+ "dim": 160,
5
+ "dim_mult": [
6
+ 1,
7
+ 2,
8
+ 4,
9
+ 4
10
+ ],
11
+ "num_res_blocks": 2,
12
+ "attn_scales": [],
13
+ "temperal_downsample": [
14
+ false,
15
+ true,
16
+ true
17
+ ],
18
+ "dropout": 0.0,
19
+ "latents_mean": [
20
+ -0.2289,
21
+ -0.0052,
22
+ -0.1323,
23
+ -0.2339,
24
+ -0.2799,
25
+ 0.0174,
26
+ 0.1838,
27
+ 0.1557,
28
+ -0.1382,
29
+ 0.0542,
30
+ 0.2813,
31
+ 0.0891,
32
+ 0.157,
33
+ -0.0098,
34
+ 0.0375,
35
+ -0.1825,
36
+ -0.2246,
37
+ -0.1207,
38
+ -0.0698,
39
+ 0.5109,
40
+ 0.2665,
41
+ -0.2108,
42
+ -0.2158,
43
+ 0.2502,
44
+ -0.2055,
45
+ -0.0322,
46
+ 0.1109,
47
+ 0.1567,
48
+ -0.0729,
49
+ 0.0899,
50
+ -0.2799,
51
+ -0.123,
52
+ -0.0313,
53
+ -0.1649,
54
+ 0.0117,
55
+ 0.0723,
56
+ -0.2839,
57
+ -0.2083,
58
+ -0.052,
59
+ 0.3748,
60
+ 0.0152,
61
+ 0.1957,
62
+ 0.1433,
63
+ -0.2944,
64
+ 0.3573,
65
+ -0.0548,
66
+ -0.1681,
67
+ -0.0667
68
+ ],
69
+ "latents_std": [
70
+ 0.4765,
71
+ 1.0364,
72
+ 0.4514,
73
+ 1.1677,
74
+ 0.5313,
75
+ 0.499,
76
+ 0.4818,
77
+ 0.5013,
78
+ 0.8158,
79
+ 1.0344,
80
+ 0.5894,
81
+ 1.0901,
82
+ 0.6885,
83
+ 0.6165,
84
+ 0.8454,
85
+ 0.4978,
86
+ 0.5759,
87
+ 0.3523,
88
+ 0.7135,
89
+ 0.6804,
90
+ 0.5833,
91
+ 1.4146,
92
+ 0.8986,
93
+ 0.5659,
94
+ 0.7069,
95
+ 0.5338,
96
+ 0.4889,
97
+ 0.4917,
98
+ 0.4069,
99
+ 0.4999,
100
+ 0.6866,
101
+ 0.4093,
102
+ 0.5709,
103
+ 0.6065,
104
+ 0.6415,
105
+ 0.4944,
106
+ 0.5726,
107
+ 1.2042,
108
+ 0.5458,
109
+ 1.6887,
110
+ 0.3971,
111
+ 1.06,
112
+ 0.3943,
113
+ 0.5537,
114
+ 0.5444,
115
+ 0.4089,
116
+ 0.7468,
117
+ 0.7744
118
+ ],
119
+ "vae_pth": "diffusion_pytorch_model.safetensors"
120
+ }
vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c37b3dd8cbf4f01dbae62613fcff4e8ac499457665e2b5f6a03f9523b4f8c7c
3
+ size 2818778360
vae/wan_video_vae.py ADDED
@@ -0,0 +1,1486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional
3
+
4
+ from einops import rearrange, repeat
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from tqdm import tqdm
10
+ from diffusers import ModelMixin, ConfigMixin
11
+ from diffusers.configuration_utils import register_to_config
12
+
13
+ CACHE_T = 2
14
+
15
+
16
+ def check_is_instance(model, module_class):
17
+ if isinstance(model, module_class):
18
+ return True
19
+ if hasattr(model, "module") and isinstance(model.module, module_class):
20
+ return True
21
+ return False
22
+
23
+
24
+ def block_causal_mask(x, block_size):
25
+ # params
26
+ b, n, s, _, device = *x.size(), x.device
27
+ assert s % block_size == 0
28
+ num_blocks = s // block_size
29
+
30
+ # build mask
31
+ mask = torch.zeros(b, n, s, s, dtype=torch.bool, device=device)
32
+ for i in range(num_blocks):
33
+ mask[:, :,
34
+ i * block_size:(i + 1) * block_size, :(i + 1) * block_size] = 1
35
+ return mask
36
+
37
+
38
+ class CausalConv3d(nn.Conv3d):
39
+ """
40
+ Causal 3d convolusion.
41
+ """
42
+
43
+ def __init__(self, *args, **kwargs):
44
+ super().__init__(*args, **kwargs)
45
+ self._padding = (self.padding[2], self.padding[2], self.padding[1],
46
+ self.padding[1], 2 * self.padding[0], 0)
47
+ self.padding = (0, 0, 0)
48
+
49
+ def forward(self, x, cache_x=None):
50
+ padding = list(self._padding)
51
+ if cache_x is not None and self._padding[4] > 0:
52
+ cache_x = cache_x.to(x.device)
53
+ x = torch.cat([cache_x, x], dim=2)
54
+ padding[4] -= cache_x.shape[2]
55
+ x = F.pad(x, padding)
56
+
57
+ return super().forward(x)
58
+
59
+
60
+ class RMS_norm(nn.Module):
61
+
62
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
63
+ super().__init__()
64
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
65
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
66
+
67
+ self.channel_first = channel_first
68
+ self.scale = dim**0.5
69
+ self.gamma = nn.Parameter(torch.ones(shape))
70
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
71
+
72
+ def forward(self, x):
73
+ return F.normalize(
74
+ x, dim=(1 if self.channel_first else
75
+ -1)) * self.scale * self.gamma + self.bias
76
+
77
+
78
+ class Upsample(nn.Upsample):
79
+
80
+ def forward(self, x):
81
+ """
82
+ Fix bfloat16 support for nearest neighbor interpolation.
83
+ """
84
+ return super().forward(x.float()).type_as(x)
85
+
86
+
87
+ class Resample(nn.Module):
88
+
89
+ def __init__(self, dim, mode):
90
+ assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d',
91
+ 'downsample3d')
92
+ super().__init__()
93
+ self.dim = dim
94
+ self.mode = mode
95
+
96
+ # layers
97
+ if mode == 'upsample2d':
98
+ self.resample = nn.Sequential(
99
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
100
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
101
+ elif mode == 'upsample3d':
102
+ self.resample = nn.Sequential(
103
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
104
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
105
+ self.time_conv = CausalConv3d(dim,
106
+ dim * 2, (3, 1, 1),
107
+ padding=(1, 0, 0))
108
+
109
+ elif mode == 'downsample2d':
110
+ self.resample = nn.Sequential(
111
+ nn.ZeroPad2d((0, 1, 0, 1)),
112
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
113
+ elif mode == 'downsample3d':
114
+ self.resample = nn.Sequential(
115
+ nn.ZeroPad2d((0, 1, 0, 1)),
116
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
117
+ self.time_conv = CausalConv3d(dim,
118
+ dim, (3, 1, 1),
119
+ stride=(2, 1, 1),
120
+ padding=(0, 0, 0))
121
+
122
+ else:
123
+ self.resample = nn.Identity()
124
+
125
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
126
+ b, c, t, h, w = x.size()
127
+ if self.mode == 'upsample3d':
128
+ if feat_cache is not None:
129
+ idx = feat_idx[0]
130
+ if feat_cache[idx] is None:
131
+ feat_cache[idx] = 'Rep'
132
+ feat_idx[0] += 1
133
+ else:
134
+
135
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
136
+ if cache_x.shape[2] < 2 and feat_cache[
137
+ idx] is not None and feat_cache[idx] != 'Rep':
138
+ # cache last frame of last two chunk
139
+ cache_x = torch.cat([
140
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
141
+ cache_x.device), cache_x
142
+ ],
143
+ dim=2)
144
+ if cache_x.shape[2] < 2 and feat_cache[
145
+ idx] is not None and feat_cache[idx] == 'Rep':
146
+ cache_x = torch.cat([
147
+ torch.zeros_like(cache_x).to(cache_x.device),
148
+ cache_x
149
+ ],
150
+ dim=2)
151
+ if feat_cache[idx] == 'Rep':
152
+ x = self.time_conv(x)
153
+ else:
154
+ x = self.time_conv(x, feat_cache[idx])
155
+ feat_cache[idx] = cache_x
156
+ feat_idx[0] += 1
157
+
158
+ x = x.reshape(b, 2, c, t, h, w)
159
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
160
+ 3)
161
+ x = x.reshape(b, c, t * 2, h, w)
162
+ t = x.shape[2]
163
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
164
+ x = self.resample(x)
165
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=t)
166
+
167
+ if self.mode == 'downsample3d':
168
+ if feat_cache is not None:
169
+ idx = feat_idx[0]
170
+ if feat_cache[idx] is None:
171
+ feat_cache[idx] = x.clone()
172
+ feat_idx[0] += 1
173
+ else:
174
+ cache_x = x[:, :, -1:, :, :].clone()
175
+ x = self.time_conv(
176
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
177
+ feat_cache[idx] = cache_x
178
+ feat_idx[0] += 1
179
+ return x
180
+
181
+ def init_weight(self, conv):
182
+ conv_weight = conv.weight
183
+ nn.init.zeros_(conv_weight)
184
+ c1, c2, t, h, w = conv_weight.size()
185
+ one_matrix = torch.eye(c1, c2)
186
+ init_matrix = one_matrix
187
+ nn.init.zeros_(conv_weight)
188
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix
189
+ conv.weight.data.copy_(conv_weight)
190
+ nn.init.zeros_(conv.bias.data)
191
+
192
+ def init_weight2(self, conv):
193
+ conv_weight = conv.weight.data
194
+ nn.init.zeros_(conv_weight)
195
+ c1, c2, t, h, w = conv_weight.size()
196
+ init_matrix = torch.eye(c1 // 2, c2)
197
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
198
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
199
+ conv.weight.data.copy_(conv_weight)
200
+ nn.init.zeros_(conv.bias.data)
201
+
202
+
203
+
204
+ def patchify(x, patch_size):
205
+ if patch_size == 1:
206
+ return x
207
+ if x.dim() == 4:
208
+ x = rearrange(x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size)
209
+ elif x.dim() == 5:
210
+ x = rearrange(x,
211
+ "b c f (h q) (w r) -> b (c r q) f h w",
212
+ q=patch_size,
213
+ r=patch_size)
214
+ else:
215
+ raise ValueError(f"Invalid input shape: {x.shape}")
216
+ return x
217
+
218
+
219
+ def unpatchify(x, patch_size):
220
+ if patch_size == 1:
221
+ return x
222
+ if x.dim() == 4:
223
+ x = rearrange(x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size)
224
+ elif x.dim() == 5:
225
+ x = rearrange(x,
226
+ "b (c r q) f h w -> b c f (h q) (w r)",
227
+ q=patch_size,
228
+ r=patch_size)
229
+ return x
230
+
231
+
232
+ class Resample38(Resample):
233
+
234
+ def __init__(self, dim, mode):
235
+ assert mode in (
236
+ "none",
237
+ "upsample2d",
238
+ "upsample3d",
239
+ "downsample2d",
240
+ "downsample3d",
241
+ )
242
+ super(Resample, self).__init__()
243
+ self.dim = dim
244
+ self.mode = mode
245
+
246
+ # layers
247
+ if mode == "upsample2d":
248
+ self.resample = nn.Sequential(
249
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
250
+ nn.Conv2d(dim, dim, 3, padding=1),
251
+ )
252
+ elif mode == "upsample3d":
253
+ self.resample = nn.Sequential(
254
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
255
+ nn.Conv2d(dim, dim, 3, padding=1),
256
+ )
257
+ self.time_conv = CausalConv3d(dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
258
+ elif mode == "downsample2d":
259
+ self.resample = nn.Sequential(
260
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
261
+ )
262
+ elif mode == "downsample3d":
263
+ self.resample = nn.Sequential(
264
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
265
+ )
266
+ self.time_conv = CausalConv3d(
267
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0)
268
+ )
269
+ else:
270
+ self.resample = nn.Identity()
271
+
272
+ class ResidualBlock(nn.Module):
273
+
274
+ def __init__(self, in_dim, out_dim, dropout=0.0):
275
+ super().__init__()
276
+ self.in_dim = in_dim
277
+ self.out_dim = out_dim
278
+
279
+ # layers
280
+ self.residual = nn.Sequential(
281
+ RMS_norm(in_dim, images=False), nn.SiLU(),
282
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
283
+ RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout),
284
+ CausalConv3d(out_dim, out_dim, 3, padding=1))
285
+ self.shortcut = CausalConv3d(in_dim, out_dim, 1) \
286
+ if in_dim != out_dim else nn.Identity()
287
+
288
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
289
+ h = self.shortcut(x)
290
+ for layer in self.residual:
291
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
292
+ idx = feat_idx[0]
293
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
294
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
295
+ # cache last frame of last two chunk
296
+ cache_x = torch.cat([
297
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
298
+ cache_x.device), cache_x
299
+ ],
300
+ dim=2)
301
+ x = layer(x, feat_cache[idx])
302
+ feat_cache[idx] = cache_x
303
+ feat_idx[0] += 1
304
+ else:
305
+ x = layer(x)
306
+ return x + h
307
+
308
+
309
+ class AttentionBlock(nn.Module):
310
+ """
311
+ Causal self-attention with a single head.
312
+ """
313
+
314
+ def __init__(self, dim):
315
+ super().__init__()
316
+ self.dim = dim
317
+
318
+ # layers
319
+ self.norm = RMS_norm(dim)
320
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
321
+ self.proj = nn.Conv2d(dim, dim, 1)
322
+
323
+ # zero out the last layer params
324
+ nn.init.zeros_(self.proj.weight)
325
+
326
+ def forward(self, x):
327
+ identity = x
328
+ b, c, t, h, w = x.size()
329
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
330
+ x = self.norm(x)
331
+ # compute query, key, value
332
+ q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3, -1).permute(
333
+ 0, 1, 3, 2).contiguous().chunk(3, dim=-1)
334
+
335
+ # apply attention
336
+ x = F.scaled_dot_product_attention(
337
+ q,
338
+ k,
339
+ v,
340
+ #attn_mask=block_causal_mask(q, block_size=h * w)
341
+ )
342
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
343
+
344
+ # output
345
+ x = self.proj(x)
346
+ x = rearrange(x, '(b t) c h w-> b c t h w', t=t)
347
+ return x + identity
348
+
349
+
350
+ class AvgDown3D(nn.Module):
351
+ def __init__(
352
+ self,
353
+ in_channels,
354
+ out_channels,
355
+ factor_t,
356
+ factor_s=1,
357
+ ):
358
+ super().__init__()
359
+ self.in_channels = in_channels
360
+ self.out_channels = out_channels
361
+ self.factor_t = factor_t
362
+ self.factor_s = factor_s
363
+ self.factor = self.factor_t * self.factor_s * self.factor_s
364
+
365
+ assert in_channels * self.factor % out_channels == 0
366
+ self.group_size = in_channels * self.factor // out_channels
367
+
368
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
369
+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t
370
+ pad = (0, 0, 0, 0, pad_t, 0)
371
+ x = F.pad(x, pad)
372
+ B, C, T, H, W = x.shape
373
+ x = x.view(
374
+ B,
375
+ C,
376
+ T // self.factor_t,
377
+ self.factor_t,
378
+ H // self.factor_s,
379
+ self.factor_s,
380
+ W // self.factor_s,
381
+ self.factor_s,
382
+ )
383
+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()
384
+ x = x.view(
385
+ B,
386
+ C * self.factor,
387
+ T // self.factor_t,
388
+ H // self.factor_s,
389
+ W // self.factor_s,
390
+ )
391
+ x = x.view(
392
+ B,
393
+ self.out_channels,
394
+ self.group_size,
395
+ T // self.factor_t,
396
+ H // self.factor_s,
397
+ W // self.factor_s,
398
+ )
399
+ x = x.mean(dim=2)
400
+ return x
401
+
402
+
403
+ class DupUp3D(nn.Module):
404
+ def __init__(
405
+ self,
406
+ in_channels: int,
407
+ out_channels: int,
408
+ factor_t,
409
+ factor_s=1,
410
+ ):
411
+ super().__init__()
412
+ self.in_channels = in_channels
413
+ self.out_channels = out_channels
414
+
415
+ self.factor_t = factor_t
416
+ self.factor_s = factor_s
417
+ self.factor = self.factor_t * self.factor_s * self.factor_s
418
+
419
+ assert out_channels * self.factor % in_channels == 0
420
+ self.repeats = out_channels * self.factor // in_channels
421
+
422
+ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:
423
+ x = x.repeat_interleave(self.repeats, dim=1)
424
+ x = x.view(
425
+ x.size(0),
426
+ self.out_channels,
427
+ self.factor_t,
428
+ self.factor_s,
429
+ self.factor_s,
430
+ x.size(2),
431
+ x.size(3),
432
+ x.size(4),
433
+ )
434
+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
435
+ x = x.view(
436
+ x.size(0),
437
+ self.out_channels,
438
+ x.size(2) * self.factor_t,
439
+ x.size(4) * self.factor_s,
440
+ x.size(6) * self.factor_s,
441
+ )
442
+ if first_chunk:
443
+ x = x[:, :, self.factor_t - 1 :, :, :]
444
+ return x
445
+
446
+
447
+ class Down_ResidualBlock(nn.Module):
448
+ def __init__(
449
+ self, in_dim, out_dim, dropout, mult, temperal_downsample=False, down_flag=False
450
+ ):
451
+ super().__init__()
452
+
453
+ # Shortcut path with downsample
454
+ self.avg_shortcut = AvgDown3D(
455
+ in_dim,
456
+ out_dim,
457
+ factor_t=2 if temperal_downsample else 1,
458
+ factor_s=2 if down_flag else 1,
459
+ )
460
+
461
+ # Main path with residual blocks and downsample
462
+ downsamples = []
463
+ for _ in range(mult):
464
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
465
+ in_dim = out_dim
466
+
467
+ # Add the final downsample block
468
+ if down_flag:
469
+ mode = "downsample3d" if temperal_downsample else "downsample2d"
470
+ downsamples.append(Resample38(out_dim, mode=mode))
471
+
472
+ self.downsamples = nn.Sequential(*downsamples)
473
+
474
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
475
+ x_copy = x.clone()
476
+ for module in self.downsamples:
477
+ x = module(x, feat_cache, feat_idx)
478
+
479
+ return x + self.avg_shortcut(x_copy)
480
+
481
+
482
+ class Up_ResidualBlock(nn.Module):
483
+ def __init__(
484
+ self, in_dim, out_dim, dropout, mult, temperal_upsample=False, up_flag=False
485
+ ):
486
+ super().__init__()
487
+ # Shortcut path with upsample
488
+ if up_flag:
489
+ self.avg_shortcut = DupUp3D(
490
+ in_dim,
491
+ out_dim,
492
+ factor_t=2 if temperal_upsample else 1,
493
+ factor_s=2 if up_flag else 1,
494
+ )
495
+ else:
496
+ self.avg_shortcut = None
497
+
498
+ # Main path with residual blocks and upsample
499
+ upsamples = []
500
+ for _ in range(mult):
501
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
502
+ in_dim = out_dim
503
+
504
+ # Add the final upsample block
505
+ if up_flag:
506
+ mode = "upsample3d" if temperal_upsample else "upsample2d"
507
+ upsamples.append(Resample38(out_dim, mode=mode))
508
+
509
+ self.upsamples = nn.Sequential(*upsamples)
510
+
511
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
512
+ x_main = x.clone()
513
+ for module in self.upsamples:
514
+ x_main = module(x_main, feat_cache, feat_idx)
515
+ if self.avg_shortcut is not None:
516
+ x_shortcut = self.avg_shortcut(x, first_chunk)
517
+ return x_main + x_shortcut
518
+ else:
519
+ return x_main
520
+
521
+
522
+ class Encoder3d(nn.Module):
523
+
524
+ def __init__(self,
525
+ dim=128,
526
+ z_dim=4,
527
+ dim_mult=[1, 2, 4, 4],
528
+ num_res_blocks=2,
529
+ attn_scales=[],
530
+ temperal_downsample=[True, True, False],
531
+ dropout=0.0):
532
+ super().__init__()
533
+ self.dim = dim
534
+ self.z_dim = z_dim
535
+ self.dim_mult = dim_mult
536
+ self.num_res_blocks = num_res_blocks
537
+ self.attn_scales = attn_scales
538
+ self.temperal_downsample = temperal_downsample
539
+
540
+ # dimensions
541
+ dims = [dim * u for u in [1] + dim_mult]
542
+ scale = 1.0
543
+
544
+ # init block
545
+ self.conv1 = CausalConv3d(3, dims[0], 3, padding=1)
546
+
547
+ # downsample blocks
548
+ downsamples = []
549
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
550
+ # residual (+attention) blocks
551
+ for _ in range(num_res_blocks):
552
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
553
+ if scale in attn_scales:
554
+ downsamples.append(AttentionBlock(out_dim))
555
+ in_dim = out_dim
556
+
557
+ # downsample block
558
+ if i != len(dim_mult) - 1:
559
+ mode = 'downsample3d' if temperal_downsample[
560
+ i] else 'downsample2d'
561
+ downsamples.append(Resample(out_dim, mode=mode))
562
+ scale /= 2.0
563
+ self.downsamples = nn.Sequential(*downsamples)
564
+
565
+ # middle blocks
566
+ self.middle = nn.Sequential(ResidualBlock(out_dim, out_dim, dropout),
567
+ AttentionBlock(out_dim),
568
+ ResidualBlock(out_dim, out_dim, dropout))
569
+
570
+ # output blocks
571
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
572
+ CausalConv3d(out_dim, z_dim, 3, padding=1))
573
+
574
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
575
+ if feat_cache is not None:
576
+ idx = feat_idx[0]
577
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
578
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
579
+ # cache last frame of last two chunk
580
+ cache_x = torch.cat([
581
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
582
+ cache_x.device), cache_x
583
+ ],
584
+ dim=2)
585
+ x = self.conv1(x, feat_cache[idx])
586
+ feat_cache[idx] = cache_x
587
+ feat_idx[0] += 1
588
+ else:
589
+ x = self.conv1(x)
590
+
591
+ ## downsamples
592
+ for layer in self.downsamples:
593
+ if feat_cache is not None:
594
+ x = layer(x, feat_cache, feat_idx)
595
+ else:
596
+ x = layer(x)
597
+
598
+ ## middle
599
+ for layer in self.middle:
600
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
601
+ x = layer(x, feat_cache, feat_idx)
602
+ else:
603
+ x = layer(x)
604
+
605
+ ## head
606
+ for layer in self.head:
607
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
608
+ idx = feat_idx[0]
609
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
610
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
611
+ # cache last frame of last two chunk
612
+ cache_x = torch.cat([
613
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
614
+ cache_x.device), cache_x
615
+ ],
616
+ dim=2)
617
+ x = layer(x, feat_cache[idx])
618
+ feat_cache[idx] = cache_x
619
+ feat_idx[0] += 1
620
+ else:
621
+ x = layer(x)
622
+ return x
623
+
624
+
625
+ class Encoder3d_38(nn.Module):
626
+
627
+ def __init__(self,
628
+ dim=128,
629
+ z_dim=4,
630
+ dim_mult=[1, 2, 4, 4],
631
+ num_res_blocks=2,
632
+ attn_scales=[],
633
+ temperal_downsample=[False, True, True],
634
+ dropout=0.0):
635
+ super().__init__()
636
+ self.dim = dim
637
+ self.z_dim = z_dim
638
+ self.dim_mult = dim_mult
639
+ self.num_res_blocks = num_res_blocks
640
+ self.attn_scales = attn_scales
641
+ self.temperal_downsample = temperal_downsample
642
+
643
+ # dimensions
644
+ dims = [dim * u for u in [1] + dim_mult]
645
+ scale = 1.0
646
+
647
+ # init block
648
+ self.conv1 = CausalConv3d(12, dims[0], 3, padding=1)
649
+
650
+ # downsample blocks
651
+ downsamples = []
652
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
653
+ t_down_flag = (
654
+ temperal_downsample[i] if i < len(temperal_downsample) else False
655
+ )
656
+ downsamples.append(
657
+ Down_ResidualBlock(
658
+ in_dim=in_dim,
659
+ out_dim=out_dim,
660
+ dropout=dropout,
661
+ mult=num_res_blocks,
662
+ temperal_downsample=t_down_flag,
663
+ down_flag=i != len(dim_mult) - 1,
664
+ )
665
+ )
666
+ scale /= 2.0
667
+ self.downsamples = nn.Sequential(*downsamples)
668
+
669
+ # middle blocks
670
+ self.middle = nn.Sequential(
671
+ ResidualBlock(out_dim, out_dim, dropout),
672
+ AttentionBlock(out_dim),
673
+ ResidualBlock(out_dim, out_dim, dropout),
674
+ )
675
+
676
+ # # output blocks
677
+ self.head = nn.Sequential(
678
+ RMS_norm(out_dim, images=False),
679
+ nn.SiLU(),
680
+ CausalConv3d(out_dim, z_dim, 3, padding=1),
681
+ )
682
+
683
+
684
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
685
+
686
+ if feat_cache is not None:
687
+ idx = feat_idx[0]
688
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
689
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
690
+ cache_x = torch.cat(
691
+ [
692
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
693
+ cache_x,
694
+ ],
695
+ dim=2,
696
+ )
697
+ x = self.conv1(x, feat_cache[idx])
698
+ feat_cache[idx] = cache_x
699
+ feat_idx[0] += 1
700
+ else:
701
+ x = self.conv1(x)
702
+
703
+ ## downsamples
704
+ for layer in self.downsamples:
705
+ if feat_cache is not None:
706
+ x = layer(x, feat_cache, feat_idx)
707
+ else:
708
+ x = layer(x)
709
+
710
+ ## middle
711
+ for layer in self.middle:
712
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
713
+ x = layer(x, feat_cache, feat_idx)
714
+ else:
715
+ x = layer(x)
716
+
717
+ ## head
718
+ for layer in self.head:
719
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
720
+ idx = feat_idx[0]
721
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
722
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
723
+ cache_x = torch.cat(
724
+ [
725
+ feat_cache[idx][:, :, -1, :, :]
726
+ .unsqueeze(2)
727
+ .to(cache_x.device),
728
+ cache_x,
729
+ ],
730
+ dim=2,
731
+ )
732
+ x = layer(x, feat_cache[idx])
733
+ feat_cache[idx] = cache_x
734
+ feat_idx[0] += 1
735
+ else:
736
+ x = layer(x)
737
+
738
+ return x
739
+
740
+
741
+ class Decoder3d(nn.Module):
742
+
743
+ def __init__(self,
744
+ dim=128,
745
+ z_dim=4,
746
+ dim_mult=[1, 2, 4, 4],
747
+ num_res_blocks=2,
748
+ attn_scales=[],
749
+ temperal_upsample=[False, True, True],
750
+ dropout=0.0):
751
+ super().__init__()
752
+ self.dim = dim
753
+ self.z_dim = z_dim
754
+ self.dim_mult = dim_mult
755
+ self.num_res_blocks = num_res_blocks
756
+ self.attn_scales = attn_scales
757
+ self.temperal_upsample = temperal_upsample
758
+
759
+ # dimensions
760
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
761
+ scale = 1.0 / 2**(len(dim_mult) - 2)
762
+
763
+ # init block
764
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
765
+
766
+ # middle blocks
767
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
768
+ AttentionBlock(dims[0]),
769
+ ResidualBlock(dims[0], dims[0], dropout))
770
+
771
+ # upsample blocks
772
+ upsamples = []
773
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
774
+ # residual (+attention) blocks
775
+ if i == 1 or i == 2 or i == 3:
776
+ in_dim = in_dim // 2
777
+ for _ in range(num_res_blocks + 1):
778
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
779
+ if scale in attn_scales:
780
+ upsamples.append(AttentionBlock(out_dim))
781
+ in_dim = out_dim
782
+
783
+ # upsample block
784
+ if i != len(dim_mult) - 1:
785
+ mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d'
786
+ upsamples.append(Resample(out_dim, mode=mode))
787
+ scale *= 2.0
788
+ self.upsamples = nn.Sequential(*upsamples)
789
+
790
+ # output blocks
791
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
792
+ CausalConv3d(out_dim, 3, 3, padding=1))
793
+
794
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
795
+ ## conv1
796
+ if feat_cache is not None:
797
+ idx = feat_idx[0]
798
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
799
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
800
+ # cache last frame of last two chunk
801
+ cache_x = torch.cat([
802
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
803
+ cache_x.device), cache_x
804
+ ],
805
+ dim=2)
806
+ x = self.conv1(x, feat_cache[idx])
807
+ feat_cache[idx] = cache_x
808
+ feat_idx[0] += 1
809
+ else:
810
+ x = self.conv1(x)
811
+
812
+ ## middle
813
+ for layer in self.middle:
814
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
815
+ x = layer(x, feat_cache, feat_idx)
816
+ else:
817
+ x = layer(x)
818
+
819
+ ## upsamples
820
+ for layer in self.upsamples:
821
+ if feat_cache is not None:
822
+ x = layer(x, feat_cache, feat_idx)
823
+ else:
824
+ x = layer(x)
825
+
826
+ ## head
827
+ for layer in self.head:
828
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
829
+ idx = feat_idx[0]
830
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
831
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
832
+ # cache last frame of last two chunk
833
+ cache_x = torch.cat([
834
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
835
+ cache_x.device), cache_x
836
+ ],
837
+ dim=2)
838
+ x = layer(x, feat_cache[idx])
839
+ feat_cache[idx] = cache_x
840
+ feat_idx[0] += 1
841
+ else:
842
+ x = layer(x)
843
+ return x
844
+
845
+
846
+
847
+ class Decoder3d_38(nn.Module):
848
+
849
+ def __init__(self,
850
+ dim=128,
851
+ z_dim=4,
852
+ dim_mult=[1, 2, 4, 4],
853
+ num_res_blocks=2,
854
+ attn_scales=[],
855
+ temperal_upsample=[False, True, True],
856
+ dropout=0.0):
857
+ super().__init__()
858
+ self.dim = dim
859
+ self.z_dim = z_dim
860
+ self.dim_mult = dim_mult
861
+ self.num_res_blocks = num_res_blocks
862
+ self.attn_scales = attn_scales
863
+ self.temperal_upsample = temperal_upsample
864
+
865
+ # dimensions
866
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
867
+ scale = 1.0 / 2 ** (len(dim_mult) - 2)
868
+ # init block
869
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
870
+
871
+ # middle blocks
872
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
873
+ AttentionBlock(dims[0]),
874
+ ResidualBlock(dims[0], dims[0], dropout))
875
+
876
+ # upsample blocks
877
+ upsamples = []
878
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
879
+ t_up_flag = temperal_upsample[i] if i < len(temperal_upsample) else False
880
+ upsamples.append(
881
+ Up_ResidualBlock(in_dim=in_dim,
882
+ out_dim=out_dim,
883
+ dropout=dropout,
884
+ mult=num_res_blocks + 1,
885
+ temperal_upsample=t_up_flag,
886
+ up_flag=i != len(dim_mult) - 1))
887
+ self.upsamples = nn.Sequential(*upsamples)
888
+
889
+ # output blocks
890
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
891
+ CausalConv3d(out_dim, 12, 3, padding=1))
892
+
893
+
894
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
895
+ if feat_cache is not None:
896
+ idx = feat_idx[0]
897
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
898
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
899
+ cache_x = torch.cat(
900
+ [
901
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
902
+ cache_x,
903
+ ],
904
+ dim=2,
905
+ )
906
+ x = self.conv1(x, feat_cache[idx])
907
+ feat_cache[idx] = cache_x
908
+ feat_idx[0] += 1
909
+ else:
910
+ x = self.conv1(x)
911
+
912
+ for layer in self.middle:
913
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
914
+ x = layer(x, feat_cache, feat_idx)
915
+ else:
916
+ x = layer(x)
917
+
918
+ ## upsamples
919
+ for layer in self.upsamples:
920
+ if feat_cache is not None:
921
+ x = layer(x, feat_cache, feat_idx, first_chunk)
922
+ else:
923
+ x = layer(x)
924
+
925
+ ## head
926
+ for layer in self.head:
927
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
928
+ idx = feat_idx[0]
929
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
930
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
931
+ cache_x = torch.cat(
932
+ [
933
+ feat_cache[idx][:, :, -1, :, :]
934
+ .unsqueeze(2)
935
+ .to(cache_x.device),
936
+ cache_x,
937
+ ],
938
+ dim=2,
939
+ )
940
+ x = layer(x, feat_cache[idx])
941
+ feat_cache[idx] = cache_x
942
+ feat_idx[0] += 1
943
+ else:
944
+ x = layer(x)
945
+ return x
946
+
947
+
948
+ def count_conv3d(model):
949
+ count = 0
950
+ for m in model.modules():
951
+ if isinstance(m, CausalConv3d):
952
+ count += 1
953
+ return count
954
+
955
+
956
+ class VideoVAE_(nn.Module):
957
+
958
+ def __init__(self,
959
+ dim=96,
960
+ z_dim=16,
961
+ dim_mult=[1, 2, 4, 4],
962
+ num_res_blocks=2,
963
+ attn_scales=[],
964
+ temperal_downsample=[False, True, True],
965
+ dropout=0.0):
966
+ super().__init__()
967
+ self.dim = dim
968
+ self.z_dim = z_dim
969
+ self.dim_mult = dim_mult
970
+ self.num_res_blocks = num_res_blocks
971
+ self.attn_scales = attn_scales
972
+ self.temperal_downsample = temperal_downsample
973
+ self.temperal_upsample = temperal_downsample[::-1]
974
+
975
+ # modules
976
+ self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks,
977
+ attn_scales, self.temperal_downsample, dropout)
978
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
979
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
980
+ self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks,
981
+ attn_scales, self.temperal_upsample, dropout)
982
+
983
+ def forward(self, x):
984
+ mu, log_var = self.encode(x)
985
+ z = self.reparameterize(mu, log_var)
986
+ x_recon = self.decode(z)
987
+ return x_recon, mu, log_var
988
+
989
+ def encode(self, x, scale):
990
+ self.clear_cache()
991
+ ## cache
992
+ t = x.shape[2]
993
+ iter_ = 1 + (t - 1) // 4
994
+
995
+ for i in range(iter_):
996
+ self._enc_conv_idx = [0]
997
+ if i == 0:
998
+ out = self.encoder(x[:, :, :1, :, :],
999
+ feat_cache=self._enc_feat_map,
1000
+ feat_idx=self._enc_conv_idx)
1001
+ else:
1002
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1003
+ feat_cache=self._enc_feat_map,
1004
+ feat_idx=self._enc_conv_idx)
1005
+ out = torch.cat([out, out_], 2)
1006
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1007
+ if isinstance(scale[0], torch.Tensor):
1008
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1009
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1010
+ 1, self.z_dim, 1, 1, 1)
1011
+ else:
1012
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1013
+ mu = (mu - scale[0]) * scale[1]
1014
+ return mu
1015
+
1016
+ def decode(self, z, scale):
1017
+ self.clear_cache()
1018
+ # z: [b,c,t,h,w]
1019
+ if isinstance(scale[0], torch.Tensor):
1020
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1021
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1022
+ 1, self.z_dim, 1, 1, 1)
1023
+ else:
1024
+ scale = scale.to(dtype=z.dtype, device=z.device)
1025
+ z = z / scale[1] + scale[0]
1026
+ iter_ = z.shape[2]
1027
+ x = self.conv2(z)
1028
+ for i in range(iter_):
1029
+ self._conv_idx = [0]
1030
+ if i == 0:
1031
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1032
+ feat_cache=self._feat_map,
1033
+ feat_idx=self._conv_idx)
1034
+ else:
1035
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1036
+ feat_cache=self._feat_map,
1037
+ feat_idx=self._conv_idx)
1038
+ out = torch.cat([out, out_], 2) # may add tensor offload
1039
+ return out
1040
+
1041
+ def reparameterize(self, mu, log_var):
1042
+ std = torch.exp(0.5 * log_var)
1043
+ eps = torch.randn_like(std)
1044
+ return eps * std + mu
1045
+
1046
+ def sample(self, imgs, deterministic=False):
1047
+ mu, log_var = self.encode(imgs)
1048
+ if deterministic:
1049
+ return mu
1050
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
1051
+ return mu + std * torch.randn_like(std)
1052
+
1053
+ def clear_cache(self):
1054
+ self._conv_num = count_conv3d(self.decoder)
1055
+ self._conv_idx = [0]
1056
+ self._feat_map = [None] * self._conv_num
1057
+ # cache encode
1058
+ self._enc_conv_num = count_conv3d(self.encoder)
1059
+ self._enc_conv_idx = [0]
1060
+ self._enc_feat_map = [None] * self._enc_conv_num
1061
+
1062
+
1063
+ class WanVideoVAE(nn.Module):
1064
+
1065
+ def __init__(self, z_dim=16):
1066
+ super().__init__()
1067
+
1068
+ mean = [
1069
+ -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,
1070
+ 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921
1071
+ ]
1072
+ std = [
1073
+ 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743,
1074
+ 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160
1075
+ ]
1076
+ self.mean = torch.tensor(mean)
1077
+ self.std = torch.tensor(std)
1078
+ self.scale = [self.mean, 1.0 / self.std]
1079
+
1080
+ # init model
1081
+ self.model = VideoVAE_(z_dim=z_dim).eval().requires_grad_(False)
1082
+ self.upsampling_factor = 8
1083
+ self.z_dim = z_dim
1084
+
1085
+
1086
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
1087
+ x = torch.ones((length,))
1088
+ if not left_bound:
1089
+ x[:border_width] = (torch.arange(border_width) + 1) / border_width
1090
+ if not right_bound:
1091
+ x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,))
1092
+ return x
1093
+
1094
+
1095
+ def build_mask(self, data, is_bound, border_width):
1096
+ _, _, _, H, W = data.shape
1097
+ h = self.build_1d_mask(H, is_bound[0], is_bound[1], border_width[0])
1098
+ w = self.build_1d_mask(W, is_bound[2], is_bound[3], border_width[1])
1099
+
1100
+ h = repeat(h, "H -> H W", H=H, W=W)
1101
+ w = repeat(w, "W -> H W", H=H, W=W)
1102
+
1103
+ mask = torch.stack([h, w]).min(dim=0).values
1104
+ mask = rearrange(mask, "H W -> 1 1 1 H W")
1105
+ return mask
1106
+
1107
+
1108
+ def tiled_decode(self, hidden_states, device, tile_size, tile_stride):
1109
+ _, _, T, H, W = hidden_states.shape
1110
+ size_h, size_w = tile_size
1111
+ stride_h, stride_w = tile_stride
1112
+
1113
+ # Split tasks
1114
+ tasks = []
1115
+ for h in range(0, H, stride_h):
1116
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1117
+ for w in range(0, W, stride_w):
1118
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1119
+ h_, w_ = h + size_h, w + size_w
1120
+ tasks.append((h, h_, w, w_))
1121
+
1122
+ data_device = "cpu"
1123
+ computation_device = device
1124
+
1125
+ out_T = T * 4 - 3
1126
+ weight = torch.zeros((1, 1, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1127
+ values = torch.zeros((1, 3, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1128
+
1129
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE decoding"):
1130
+ hidden_states_batch = hidden_states[:, :, :, h:h_, w:w_].to(computation_device)
1131
+ hidden_states_batch = self.model.decode(hidden_states_batch, self.scale).to(data_device)
1132
+
1133
+ mask = self.build_mask(
1134
+ hidden_states_batch,
1135
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1136
+ border_width=((size_h - stride_h) * self.upsampling_factor, (size_w - stride_w) * self.upsampling_factor)
1137
+ ).to(dtype=hidden_states.dtype, device=data_device)
1138
+
1139
+ target_h = h * self.upsampling_factor
1140
+ target_w = w * self.upsampling_factor
1141
+ values[
1142
+ :,
1143
+ :,
1144
+ :,
1145
+ target_h:target_h + hidden_states_batch.shape[3],
1146
+ target_w:target_w + hidden_states_batch.shape[4],
1147
+ ] += hidden_states_batch * mask
1148
+ weight[
1149
+ :,
1150
+ :,
1151
+ :,
1152
+ target_h: target_h + hidden_states_batch.shape[3],
1153
+ target_w: target_w + hidden_states_batch.shape[4],
1154
+ ] += mask
1155
+ values = values / weight
1156
+ values = values.clamp_(-1, 1)
1157
+ return values
1158
+
1159
+
1160
+ def tiled_encode(self, video, device, tile_size, tile_stride):
1161
+ _, _, T, H, W = video.shape
1162
+ size_h, size_w = tile_size
1163
+ stride_h, stride_w = tile_stride
1164
+
1165
+ # Split tasks
1166
+ tasks = []
1167
+ for h in range(0, H, stride_h):
1168
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1169
+ for w in range(0, W, stride_w):
1170
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1171
+ h_, w_ = h + size_h, w + size_w
1172
+ tasks.append((h, h_, w, w_))
1173
+
1174
+ data_device = "cpu"
1175
+ computation_device = device
1176
+
1177
+ out_T = (T + 3) // 4
1178
+ weight = torch.zeros((1, 1, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1179
+ values = torch.zeros((1, self.z_dim, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1180
+
1181
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE encoding"):
1182
+ hidden_states_batch = video[:, :, :, h:h_, w:w_].to(computation_device)
1183
+ hidden_states_batch = self.model.encode(hidden_states_batch, self.scale).to(data_device)
1184
+
1185
+ mask = self.build_mask(
1186
+ hidden_states_batch,
1187
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1188
+ border_width=((size_h - stride_h) // self.upsampling_factor, (size_w - stride_w) // self.upsampling_factor)
1189
+ ).to(dtype=video.dtype, device=data_device)
1190
+
1191
+ target_h = h // self.upsampling_factor
1192
+ target_w = w // self.upsampling_factor
1193
+ values[
1194
+ :,
1195
+ :,
1196
+ :,
1197
+ target_h:target_h + hidden_states_batch.shape[3],
1198
+ target_w:target_w + hidden_states_batch.shape[4],
1199
+ ] += hidden_states_batch * mask
1200
+ weight[
1201
+ :,
1202
+ :,
1203
+ :,
1204
+ target_h: target_h + hidden_states_batch.shape[3],
1205
+ target_w: target_w + hidden_states_batch.shape[4],
1206
+ ] += mask
1207
+ values = values / weight
1208
+ return values
1209
+
1210
+
1211
+ def single_encode(self, video, device):
1212
+ video = video.to(device)
1213
+ x = self.model.encode(video, self.scale)
1214
+ return x
1215
+
1216
+
1217
+ def single_decode(self, hidden_state, device):
1218
+ hidden_state = hidden_state.to(device)
1219
+ video = self.model.decode(hidden_state, self.scale)
1220
+ return video.clamp_(-1, 1)
1221
+
1222
+
1223
+ def encode(self, videos, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1224
+ videos = [video.to("cpu") for video in videos]
1225
+ hidden_states = []
1226
+ for video in videos:
1227
+ video = video.unsqueeze(0)
1228
+ if tiled:
1229
+ tile_size = (tile_size[0] * self.upsampling_factor, tile_size[1] * self.upsampling_factor)
1230
+ tile_stride = (tile_stride[0] * self.upsampling_factor, tile_stride[1] * self.upsampling_factor)
1231
+ hidden_state = self.tiled_encode(video, device, tile_size, tile_stride)
1232
+ else:
1233
+ hidden_state = self.single_encode(video, device)
1234
+ hidden_state = hidden_state.squeeze(0)
1235
+ hidden_states.append(hidden_state)
1236
+ hidden_states = torch.stack(hidden_states)
1237
+ return hidden_states
1238
+
1239
+
1240
+ def decode(self, hidden_states, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1241
+ hidden_states = [hidden_state.to("cpu") for hidden_state in hidden_states]
1242
+ videos = []
1243
+ for hidden_state in hidden_states:
1244
+ hidden_state = hidden_state.unsqueeze(0)
1245
+ if tiled:
1246
+ video = self.tiled_decode(hidden_state, device, tile_size, tile_stride)
1247
+ else:
1248
+ video = self.single_decode(hidden_state, device)
1249
+ video = video.squeeze(0)
1250
+ videos.append(video)
1251
+ videos = torch.stack(videos)
1252
+ return videos
1253
+
1254
+
1255
+ @staticmethod
1256
+ def state_dict_converter():
1257
+ return WanVideoVAEStateDictConverter()
1258
+
1259
+
1260
+ class WanVideoVAEStateDictConverter:
1261
+
1262
+ def __init__(self):
1263
+ pass
1264
+
1265
+ def from_civitai(self, state_dict):
1266
+ state_dict_ = {}
1267
+ if 'model_state' in state_dict:
1268
+ state_dict = state_dict['model_state']
1269
+ for name in state_dict:
1270
+ state_dict_['model.' + name] = state_dict[name]
1271
+ return state_dict_
1272
+
1273
+
1274
+ class VideoVAE38_(VideoVAE_):
1275
+
1276
+ def __init__(self,
1277
+ dim=160,
1278
+ z_dim=48,
1279
+ dec_dim=256,
1280
+ dim_mult=[1, 2, 4, 4],
1281
+ num_res_blocks=2,
1282
+ attn_scales=[],
1283
+ temperal_downsample=[False, True, True],
1284
+ dropout=0.0):
1285
+ super(VideoVAE_, self).__init__()
1286
+ self.dim = dim
1287
+ self.z_dim = z_dim
1288
+ self.dim_mult = dim_mult
1289
+ self.num_res_blocks = num_res_blocks
1290
+ self.attn_scales = attn_scales
1291
+ self.temperal_downsample = temperal_downsample
1292
+ self.temperal_upsample = temperal_downsample[::-1]
1293
+
1294
+ # modules
1295
+ self.encoder = Encoder3d_38(dim, z_dim * 2, dim_mult, num_res_blocks,
1296
+ attn_scales, self.temperal_downsample, dropout)
1297
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
1298
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
1299
+ self.decoder = Decoder3d_38(dec_dim, z_dim, dim_mult, num_res_blocks,
1300
+ attn_scales, self.temperal_upsample, dropout)
1301
+
1302
+
1303
+ def encode(self, x, scale):
1304
+ self.clear_cache()
1305
+ x = patchify(x, patch_size=2)
1306
+ t = x.shape[2]
1307
+ iter_ = 1 + (t - 1) // 4
1308
+ for i in range(iter_):
1309
+ self._enc_conv_idx = [0]
1310
+ if i == 0:
1311
+ out = self.encoder(x[:, :, :1, :, :],
1312
+ feat_cache=self._enc_feat_map,
1313
+ feat_idx=self._enc_conv_idx)
1314
+ else:
1315
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1316
+ feat_cache=self._enc_feat_map,
1317
+ feat_idx=self._enc_conv_idx)
1318
+ out = torch.cat([out, out_], 2)
1319
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1320
+ if isinstance(scale[0], torch.Tensor):
1321
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1322
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1323
+ 1, self.z_dim, 1, 1, 1)
1324
+ else:
1325
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1326
+ mu = (mu - scale[0]) * scale[1]
1327
+ self.clear_cache()
1328
+ return mu
1329
+
1330
+
1331
+ def decode(self, z, scale):
1332
+ self.clear_cache()
1333
+ if isinstance(scale[0], torch.Tensor):
1334
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1335
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1336
+ 1, self.z_dim, 1, 1, 1)
1337
+ else:
1338
+ scale = scale.to(dtype=z.dtype, device=z.device)
1339
+ z = z / scale[1] + scale[0]
1340
+ iter_ = z.shape[2]
1341
+ x = self.conv2(z)
1342
+ for i in range(iter_):
1343
+ self._conv_idx = [0]
1344
+ if i == 0:
1345
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1346
+ feat_cache=self._feat_map,
1347
+ feat_idx=self._conv_idx,
1348
+ first_chunk=True)
1349
+ else:
1350
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1351
+ feat_cache=self._feat_map,
1352
+ feat_idx=self._conv_idx)
1353
+ out = torch.cat([out, out_], 2)
1354
+ out = unpatchify(out, patch_size=2)
1355
+ self.clear_cache()
1356
+ return out
1357
+
1358
+
1359
+ class WanVideoVAE38(WanVideoVAE):
1360
+
1361
+ def __init__(self, z_dim=48, dim=160):
1362
+ super(WanVideoVAE, self).__init__()
1363
+
1364
+ mean = [
1365
+ -0.2289, -0.0052, -0.1323, -0.2339, -0.2799, 0.0174, 0.1838, 0.1557,
1366
+ -0.1382, 0.0542, 0.2813, 0.0891, 0.1570, -0.0098, 0.0375, -0.1825,
1367
+ -0.2246, -0.1207, -0.0698, 0.5109, 0.2665, -0.2108, -0.2158, 0.2502,
1368
+ -0.2055, -0.0322, 0.1109, 0.1567, -0.0729, 0.0899, -0.2799, -0.1230,
1369
+ -0.0313, -0.1649, 0.0117, 0.0723, -0.2839, -0.2083, -0.0520, 0.3748,
1370
+ 0.0152, 0.1957, 0.1433, -0.2944, 0.3573, -0.0548, -0.1681, -0.0667
1371
+ ]
1372
+ std = [
1373
+ 0.4765, 1.0364, 0.4514, 1.1677, 0.5313, 0.4990, 0.4818, 0.5013,
1374
+ 0.8158, 1.0344, 0.5894, 1.0901, 0.6885, 0.6165, 0.8454, 0.4978,
1375
+ 0.5759, 0.3523, 0.7135, 0.6804, 0.5833, 1.4146, 0.8986, 0.5659,
1376
+ 0.7069, 0.5338, 0.4889, 0.4917, 0.4069, 0.4999, 0.6866, 0.4093,
1377
+ 0.5709, 0.6065, 0.6415, 0.4944, 0.5726, 1.2042, 0.5458, 1.6887,
1378
+ 0.3971, 1.0600, 0.3943, 0.5537, 0.5444, 0.4089, 0.7468, 0.7744
1379
+ ]
1380
+ self.mean = torch.tensor(mean)
1381
+ self.std = torch.tensor(std)
1382
+ self.scale = [self.mean, 1.0 / self.std]
1383
+
1384
+ # init model
1385
+ self.model = VideoVAE38_(z_dim=z_dim, dim=dim).eval().requires_grad_(False)
1386
+ self.upsampling_factor = 16
1387
+ self.z_dim = z_dim
1388
+
1389
+
1390
+ # ─────────────────────────────────────────────────────────────────────────────
1391
+ # Diffusers-compatible wrapper (formerly kiwi_vae.py)
1392
+ # ─────────────────────────────────��───────────────────────────────────────────
1393
+
1394
+ @dataclass
1395
+ class LatentDist:
1396
+ mu: torch.Tensor
1397
+
1398
+ def sample(self):
1399
+ return self.mu
1400
+
1401
+
1402
+ @dataclass
1403
+ class EncoderOutput:
1404
+ latent_dist: LatentDist
1405
+
1406
+
1407
+ @dataclass
1408
+ class DecoderOutput:
1409
+ sample: torch.Tensor
1410
+
1411
+
1412
+ class VAE(VideoVAE_, ModelMixin, ConfigMixin):
1413
+ """
1414
+ Diffusers-compatible VAE wrapper around the original Wan VideoVAE.
1415
+ Loads weights directly from diffusion_pytorch_model.safetensors.
1416
+ """
1417
+
1418
+ @register_to_config
1419
+ def __init__(
1420
+ self,
1421
+ z_dim: int = 48,
1422
+ dim: int = 160,
1423
+ dim_mult: List[int] = [1, 2, 4, 4],
1424
+ num_res_blocks: int = 2,
1425
+ attn_scales: List[float] = [],
1426
+ temperal_downsample: List[bool] = [False, True, True],
1427
+ dropout: float = 0.0,
1428
+ vae_pth: str = "wan_vae.pth",
1429
+ latents_mean: Optional[List[float]] = None,
1430
+ latents_std: Optional[List[float]] = None,
1431
+ ):
1432
+ # Build the actual VAE backbone so diffusers can load weights without mismatch.
1433
+ if z_dim == 48:
1434
+ VideoVAE38_.__init__(
1435
+ self,
1436
+ dim=dim,
1437
+ z_dim=z_dim,
1438
+ dim_mult=dim_mult,
1439
+ num_res_blocks=num_res_blocks,
1440
+ attn_scales=attn_scales,
1441
+ temperal_downsample=temperal_downsample,
1442
+ dropout=dropout,
1443
+ )
1444
+ self._use_38 = True
1445
+ self.upsampling_factor = 16
1446
+ else:
1447
+ VideoVAE_.__init__(
1448
+ self,
1449
+ dim=dim,
1450
+ z_dim=z_dim,
1451
+ dim_mult=dim_mult,
1452
+ num_res_blocks=num_res_blocks,
1453
+ attn_scales=attn_scales,
1454
+ temperal_downsample=temperal_downsample,
1455
+ dropout=dropout,
1456
+ )
1457
+ self._use_38 = False
1458
+ self.upsampling_factor = 8
1459
+
1460
+ # Keep for config compatibility; weights are loaded by diffusers.
1461
+ self._vae_pth = vae_pth
1462
+ self.z_dim = z_dim
1463
+
1464
+ # Build latent normalization scale: [mean, 1/std]
1465
+ if latents_mean is not None and latents_std is not None:
1466
+ mean = torch.tensor(latents_mean)
1467
+ std = torch.tensor(latents_std)
1468
+ self._scale = [mean, 1.0 / std]
1469
+ else:
1470
+ self._scale = [torch.zeros(z_dim), torch.ones(z_dim)]
1471
+
1472
+ def encode(self, x):
1473
+ x = x.to(dtype=next(self.parameters()).dtype)
1474
+ if self._use_38:
1475
+ mu = VideoVAE38_.encode(self, x, self._scale)
1476
+ else:
1477
+ mu = VideoVAE_.encode(self, x, self._scale)
1478
+ return EncoderOutput(latent_dist=LatentDist(mu=mu))
1479
+
1480
+ def decode(self, z):
1481
+ z = z.to(dtype=next(self.parameters()).dtype)
1482
+ if self._use_38:
1483
+ out = VideoVAE38_.decode(self, z, self._scale)
1484
+ else:
1485
+ out = VideoVAE_.decode(self, z, self._scale)
1486
+ return DecoderOutput(sample=out)
wan_video_vae.py ADDED
@@ -0,0 +1,1486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional
3
+
4
+ from einops import rearrange, repeat
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from tqdm import tqdm
10
+ from diffusers import ModelMixin, ConfigMixin
11
+ from diffusers.configuration_utils import register_to_config
12
+
13
+ CACHE_T = 2
14
+
15
+
16
+ def check_is_instance(model, module_class):
17
+ if isinstance(model, module_class):
18
+ return True
19
+ if hasattr(model, "module") and isinstance(model.module, module_class):
20
+ return True
21
+ return False
22
+
23
+
24
+ def block_causal_mask(x, block_size):
25
+ # params
26
+ b, n, s, _, device = *x.size(), x.device
27
+ assert s % block_size == 0
28
+ num_blocks = s // block_size
29
+
30
+ # build mask
31
+ mask = torch.zeros(b, n, s, s, dtype=torch.bool, device=device)
32
+ for i in range(num_blocks):
33
+ mask[:, :,
34
+ i * block_size:(i + 1) * block_size, :(i + 1) * block_size] = 1
35
+ return mask
36
+
37
+
38
+ class CausalConv3d(nn.Conv3d):
39
+ """
40
+ Causal 3d convolusion.
41
+ """
42
+
43
+ def __init__(self, *args, **kwargs):
44
+ super().__init__(*args, **kwargs)
45
+ self._padding = (self.padding[2], self.padding[2], self.padding[1],
46
+ self.padding[1], 2 * self.padding[0], 0)
47
+ self.padding = (0, 0, 0)
48
+
49
+ def forward(self, x, cache_x=None):
50
+ padding = list(self._padding)
51
+ if cache_x is not None and self._padding[4] > 0:
52
+ cache_x = cache_x.to(x.device)
53
+ x = torch.cat([cache_x, x], dim=2)
54
+ padding[4] -= cache_x.shape[2]
55
+ x = F.pad(x, padding)
56
+
57
+ return super().forward(x)
58
+
59
+
60
+ class RMS_norm(nn.Module):
61
+
62
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
63
+ super().__init__()
64
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
65
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
66
+
67
+ self.channel_first = channel_first
68
+ self.scale = dim**0.5
69
+ self.gamma = nn.Parameter(torch.ones(shape))
70
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
71
+
72
+ def forward(self, x):
73
+ return F.normalize(
74
+ x, dim=(1 if self.channel_first else
75
+ -1)) * self.scale * self.gamma + self.bias
76
+
77
+
78
+ class Upsample(nn.Upsample):
79
+
80
+ def forward(self, x):
81
+ """
82
+ Fix bfloat16 support for nearest neighbor interpolation.
83
+ """
84
+ return super().forward(x.float()).type_as(x)
85
+
86
+
87
+ class Resample(nn.Module):
88
+
89
+ def __init__(self, dim, mode):
90
+ assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d',
91
+ 'downsample3d')
92
+ super().__init__()
93
+ self.dim = dim
94
+ self.mode = mode
95
+
96
+ # layers
97
+ if mode == 'upsample2d':
98
+ self.resample = nn.Sequential(
99
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
100
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
101
+ elif mode == 'upsample3d':
102
+ self.resample = nn.Sequential(
103
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
104
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
105
+ self.time_conv = CausalConv3d(dim,
106
+ dim * 2, (3, 1, 1),
107
+ padding=(1, 0, 0))
108
+
109
+ elif mode == 'downsample2d':
110
+ self.resample = nn.Sequential(
111
+ nn.ZeroPad2d((0, 1, 0, 1)),
112
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
113
+ elif mode == 'downsample3d':
114
+ self.resample = nn.Sequential(
115
+ nn.ZeroPad2d((0, 1, 0, 1)),
116
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
117
+ self.time_conv = CausalConv3d(dim,
118
+ dim, (3, 1, 1),
119
+ stride=(2, 1, 1),
120
+ padding=(0, 0, 0))
121
+
122
+ else:
123
+ self.resample = nn.Identity()
124
+
125
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
126
+ b, c, t, h, w = x.size()
127
+ if self.mode == 'upsample3d':
128
+ if feat_cache is not None:
129
+ idx = feat_idx[0]
130
+ if feat_cache[idx] is None:
131
+ feat_cache[idx] = 'Rep'
132
+ feat_idx[0] += 1
133
+ else:
134
+
135
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
136
+ if cache_x.shape[2] < 2 and feat_cache[
137
+ idx] is not None and feat_cache[idx] != 'Rep':
138
+ # cache last frame of last two chunk
139
+ cache_x = torch.cat([
140
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
141
+ cache_x.device), cache_x
142
+ ],
143
+ dim=2)
144
+ if cache_x.shape[2] < 2 and feat_cache[
145
+ idx] is not None and feat_cache[idx] == 'Rep':
146
+ cache_x = torch.cat([
147
+ torch.zeros_like(cache_x).to(cache_x.device),
148
+ cache_x
149
+ ],
150
+ dim=2)
151
+ if feat_cache[idx] == 'Rep':
152
+ x = self.time_conv(x)
153
+ else:
154
+ x = self.time_conv(x, feat_cache[idx])
155
+ feat_cache[idx] = cache_x
156
+ feat_idx[0] += 1
157
+
158
+ x = x.reshape(b, 2, c, t, h, w)
159
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
160
+ 3)
161
+ x = x.reshape(b, c, t * 2, h, w)
162
+ t = x.shape[2]
163
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
164
+ x = self.resample(x)
165
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=t)
166
+
167
+ if self.mode == 'downsample3d':
168
+ if feat_cache is not None:
169
+ idx = feat_idx[0]
170
+ if feat_cache[idx] is None:
171
+ feat_cache[idx] = x.clone()
172
+ feat_idx[0] += 1
173
+ else:
174
+ cache_x = x[:, :, -1:, :, :].clone()
175
+ x = self.time_conv(
176
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
177
+ feat_cache[idx] = cache_x
178
+ feat_idx[0] += 1
179
+ return x
180
+
181
+ def init_weight(self, conv):
182
+ conv_weight = conv.weight
183
+ nn.init.zeros_(conv_weight)
184
+ c1, c2, t, h, w = conv_weight.size()
185
+ one_matrix = torch.eye(c1, c2)
186
+ init_matrix = one_matrix
187
+ nn.init.zeros_(conv_weight)
188
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix
189
+ conv.weight.data.copy_(conv_weight)
190
+ nn.init.zeros_(conv.bias.data)
191
+
192
+ def init_weight2(self, conv):
193
+ conv_weight = conv.weight.data
194
+ nn.init.zeros_(conv_weight)
195
+ c1, c2, t, h, w = conv_weight.size()
196
+ init_matrix = torch.eye(c1 // 2, c2)
197
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
198
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
199
+ conv.weight.data.copy_(conv_weight)
200
+ nn.init.zeros_(conv.bias.data)
201
+
202
+
203
+
204
+ def patchify(x, patch_size):
205
+ if patch_size == 1:
206
+ return x
207
+ if x.dim() == 4:
208
+ x = rearrange(x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size)
209
+ elif x.dim() == 5:
210
+ x = rearrange(x,
211
+ "b c f (h q) (w r) -> b (c r q) f h w",
212
+ q=patch_size,
213
+ r=patch_size)
214
+ else:
215
+ raise ValueError(f"Invalid input shape: {x.shape}")
216
+ return x
217
+
218
+
219
+ def unpatchify(x, patch_size):
220
+ if patch_size == 1:
221
+ return x
222
+ if x.dim() == 4:
223
+ x = rearrange(x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size)
224
+ elif x.dim() == 5:
225
+ x = rearrange(x,
226
+ "b (c r q) f h w -> b c f (h q) (w r)",
227
+ q=patch_size,
228
+ r=patch_size)
229
+ return x
230
+
231
+
232
+ class Resample38(Resample):
233
+
234
+ def __init__(self, dim, mode):
235
+ assert mode in (
236
+ "none",
237
+ "upsample2d",
238
+ "upsample3d",
239
+ "downsample2d",
240
+ "downsample3d",
241
+ )
242
+ super(Resample, self).__init__()
243
+ self.dim = dim
244
+ self.mode = mode
245
+
246
+ # layers
247
+ if mode == "upsample2d":
248
+ self.resample = nn.Sequential(
249
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
250
+ nn.Conv2d(dim, dim, 3, padding=1),
251
+ )
252
+ elif mode == "upsample3d":
253
+ self.resample = nn.Sequential(
254
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
255
+ nn.Conv2d(dim, dim, 3, padding=1),
256
+ )
257
+ self.time_conv = CausalConv3d(dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
258
+ elif mode == "downsample2d":
259
+ self.resample = nn.Sequential(
260
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
261
+ )
262
+ elif mode == "downsample3d":
263
+ self.resample = nn.Sequential(
264
+ nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2))
265
+ )
266
+ self.time_conv = CausalConv3d(
267
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0)
268
+ )
269
+ else:
270
+ self.resample = nn.Identity()
271
+
272
+ class ResidualBlock(nn.Module):
273
+
274
+ def __init__(self, in_dim, out_dim, dropout=0.0):
275
+ super().__init__()
276
+ self.in_dim = in_dim
277
+ self.out_dim = out_dim
278
+
279
+ # layers
280
+ self.residual = nn.Sequential(
281
+ RMS_norm(in_dim, images=False), nn.SiLU(),
282
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
283
+ RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout),
284
+ CausalConv3d(out_dim, out_dim, 3, padding=1))
285
+ self.shortcut = CausalConv3d(in_dim, out_dim, 1) \
286
+ if in_dim != out_dim else nn.Identity()
287
+
288
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
289
+ h = self.shortcut(x)
290
+ for layer in self.residual:
291
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
292
+ idx = feat_idx[0]
293
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
294
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
295
+ # cache last frame of last two chunk
296
+ cache_x = torch.cat([
297
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
298
+ cache_x.device), cache_x
299
+ ],
300
+ dim=2)
301
+ x = layer(x, feat_cache[idx])
302
+ feat_cache[idx] = cache_x
303
+ feat_idx[0] += 1
304
+ else:
305
+ x = layer(x)
306
+ return x + h
307
+
308
+
309
+ class AttentionBlock(nn.Module):
310
+ """
311
+ Causal self-attention with a single head.
312
+ """
313
+
314
+ def __init__(self, dim):
315
+ super().__init__()
316
+ self.dim = dim
317
+
318
+ # layers
319
+ self.norm = RMS_norm(dim)
320
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
321
+ self.proj = nn.Conv2d(dim, dim, 1)
322
+
323
+ # zero out the last layer params
324
+ nn.init.zeros_(self.proj.weight)
325
+
326
+ def forward(self, x):
327
+ identity = x
328
+ b, c, t, h, w = x.size()
329
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
330
+ x = self.norm(x)
331
+ # compute query, key, value
332
+ q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3, -1).permute(
333
+ 0, 1, 3, 2).contiguous().chunk(3, dim=-1)
334
+
335
+ # apply attention
336
+ x = F.scaled_dot_product_attention(
337
+ q,
338
+ k,
339
+ v,
340
+ #attn_mask=block_causal_mask(q, block_size=h * w)
341
+ )
342
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
343
+
344
+ # output
345
+ x = self.proj(x)
346
+ x = rearrange(x, '(b t) c h w-> b c t h w', t=t)
347
+ return x + identity
348
+
349
+
350
+ class AvgDown3D(nn.Module):
351
+ def __init__(
352
+ self,
353
+ in_channels,
354
+ out_channels,
355
+ factor_t,
356
+ factor_s=1,
357
+ ):
358
+ super().__init__()
359
+ self.in_channels = in_channels
360
+ self.out_channels = out_channels
361
+ self.factor_t = factor_t
362
+ self.factor_s = factor_s
363
+ self.factor = self.factor_t * self.factor_s * self.factor_s
364
+
365
+ assert in_channels * self.factor % out_channels == 0
366
+ self.group_size = in_channels * self.factor // out_channels
367
+
368
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
369
+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t
370
+ pad = (0, 0, 0, 0, pad_t, 0)
371
+ x = F.pad(x, pad)
372
+ B, C, T, H, W = x.shape
373
+ x = x.view(
374
+ B,
375
+ C,
376
+ T // self.factor_t,
377
+ self.factor_t,
378
+ H // self.factor_s,
379
+ self.factor_s,
380
+ W // self.factor_s,
381
+ self.factor_s,
382
+ )
383
+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()
384
+ x = x.view(
385
+ B,
386
+ C * self.factor,
387
+ T // self.factor_t,
388
+ H // self.factor_s,
389
+ W // self.factor_s,
390
+ )
391
+ x = x.view(
392
+ B,
393
+ self.out_channels,
394
+ self.group_size,
395
+ T // self.factor_t,
396
+ H // self.factor_s,
397
+ W // self.factor_s,
398
+ )
399
+ x = x.mean(dim=2)
400
+ return x
401
+
402
+
403
+ class DupUp3D(nn.Module):
404
+ def __init__(
405
+ self,
406
+ in_channels: int,
407
+ out_channels: int,
408
+ factor_t,
409
+ factor_s=1,
410
+ ):
411
+ super().__init__()
412
+ self.in_channels = in_channels
413
+ self.out_channels = out_channels
414
+
415
+ self.factor_t = factor_t
416
+ self.factor_s = factor_s
417
+ self.factor = self.factor_t * self.factor_s * self.factor_s
418
+
419
+ assert out_channels * self.factor % in_channels == 0
420
+ self.repeats = out_channels * self.factor // in_channels
421
+
422
+ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:
423
+ x = x.repeat_interleave(self.repeats, dim=1)
424
+ x = x.view(
425
+ x.size(0),
426
+ self.out_channels,
427
+ self.factor_t,
428
+ self.factor_s,
429
+ self.factor_s,
430
+ x.size(2),
431
+ x.size(3),
432
+ x.size(4),
433
+ )
434
+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
435
+ x = x.view(
436
+ x.size(0),
437
+ self.out_channels,
438
+ x.size(2) * self.factor_t,
439
+ x.size(4) * self.factor_s,
440
+ x.size(6) * self.factor_s,
441
+ )
442
+ if first_chunk:
443
+ x = x[:, :, self.factor_t - 1 :, :, :]
444
+ return x
445
+
446
+
447
+ class Down_ResidualBlock(nn.Module):
448
+ def __init__(
449
+ self, in_dim, out_dim, dropout, mult, temperal_downsample=False, down_flag=False
450
+ ):
451
+ super().__init__()
452
+
453
+ # Shortcut path with downsample
454
+ self.avg_shortcut = AvgDown3D(
455
+ in_dim,
456
+ out_dim,
457
+ factor_t=2 if temperal_downsample else 1,
458
+ factor_s=2 if down_flag else 1,
459
+ )
460
+
461
+ # Main path with residual blocks and downsample
462
+ downsamples = []
463
+ for _ in range(mult):
464
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
465
+ in_dim = out_dim
466
+
467
+ # Add the final downsample block
468
+ if down_flag:
469
+ mode = "downsample3d" if temperal_downsample else "downsample2d"
470
+ downsamples.append(Resample38(out_dim, mode=mode))
471
+
472
+ self.downsamples = nn.Sequential(*downsamples)
473
+
474
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
475
+ x_copy = x.clone()
476
+ for module in self.downsamples:
477
+ x = module(x, feat_cache, feat_idx)
478
+
479
+ return x + self.avg_shortcut(x_copy)
480
+
481
+
482
+ class Up_ResidualBlock(nn.Module):
483
+ def __init__(
484
+ self, in_dim, out_dim, dropout, mult, temperal_upsample=False, up_flag=False
485
+ ):
486
+ super().__init__()
487
+ # Shortcut path with upsample
488
+ if up_flag:
489
+ self.avg_shortcut = DupUp3D(
490
+ in_dim,
491
+ out_dim,
492
+ factor_t=2 if temperal_upsample else 1,
493
+ factor_s=2 if up_flag else 1,
494
+ )
495
+ else:
496
+ self.avg_shortcut = None
497
+
498
+ # Main path with residual blocks and upsample
499
+ upsamples = []
500
+ for _ in range(mult):
501
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
502
+ in_dim = out_dim
503
+
504
+ # Add the final upsample block
505
+ if up_flag:
506
+ mode = "upsample3d" if temperal_upsample else "upsample2d"
507
+ upsamples.append(Resample38(out_dim, mode=mode))
508
+
509
+ self.upsamples = nn.Sequential(*upsamples)
510
+
511
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
512
+ x_main = x.clone()
513
+ for module in self.upsamples:
514
+ x_main = module(x_main, feat_cache, feat_idx)
515
+ if self.avg_shortcut is not None:
516
+ x_shortcut = self.avg_shortcut(x, first_chunk)
517
+ return x_main + x_shortcut
518
+ else:
519
+ return x_main
520
+
521
+
522
+ class Encoder3d(nn.Module):
523
+
524
+ def __init__(self,
525
+ dim=128,
526
+ z_dim=4,
527
+ dim_mult=[1, 2, 4, 4],
528
+ num_res_blocks=2,
529
+ attn_scales=[],
530
+ temperal_downsample=[True, True, False],
531
+ dropout=0.0):
532
+ super().__init__()
533
+ self.dim = dim
534
+ self.z_dim = z_dim
535
+ self.dim_mult = dim_mult
536
+ self.num_res_blocks = num_res_blocks
537
+ self.attn_scales = attn_scales
538
+ self.temperal_downsample = temperal_downsample
539
+
540
+ # dimensions
541
+ dims = [dim * u for u in [1] + dim_mult]
542
+ scale = 1.0
543
+
544
+ # init block
545
+ self.conv1 = CausalConv3d(3, dims[0], 3, padding=1)
546
+
547
+ # downsample blocks
548
+ downsamples = []
549
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
550
+ # residual (+attention) blocks
551
+ for _ in range(num_res_blocks):
552
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
553
+ if scale in attn_scales:
554
+ downsamples.append(AttentionBlock(out_dim))
555
+ in_dim = out_dim
556
+
557
+ # downsample block
558
+ if i != len(dim_mult) - 1:
559
+ mode = 'downsample3d' if temperal_downsample[
560
+ i] else 'downsample2d'
561
+ downsamples.append(Resample(out_dim, mode=mode))
562
+ scale /= 2.0
563
+ self.downsamples = nn.Sequential(*downsamples)
564
+
565
+ # middle blocks
566
+ self.middle = nn.Sequential(ResidualBlock(out_dim, out_dim, dropout),
567
+ AttentionBlock(out_dim),
568
+ ResidualBlock(out_dim, out_dim, dropout))
569
+
570
+ # output blocks
571
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
572
+ CausalConv3d(out_dim, z_dim, 3, padding=1))
573
+
574
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
575
+ if feat_cache is not None:
576
+ idx = feat_idx[0]
577
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
578
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
579
+ # cache last frame of last two chunk
580
+ cache_x = torch.cat([
581
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
582
+ cache_x.device), cache_x
583
+ ],
584
+ dim=2)
585
+ x = self.conv1(x, feat_cache[idx])
586
+ feat_cache[idx] = cache_x
587
+ feat_idx[0] += 1
588
+ else:
589
+ x = self.conv1(x)
590
+
591
+ ## downsamples
592
+ for layer in self.downsamples:
593
+ if feat_cache is not None:
594
+ x = layer(x, feat_cache, feat_idx)
595
+ else:
596
+ x = layer(x)
597
+
598
+ ## middle
599
+ for layer in self.middle:
600
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
601
+ x = layer(x, feat_cache, feat_idx)
602
+ else:
603
+ x = layer(x)
604
+
605
+ ## head
606
+ for layer in self.head:
607
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
608
+ idx = feat_idx[0]
609
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
610
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
611
+ # cache last frame of last two chunk
612
+ cache_x = torch.cat([
613
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
614
+ cache_x.device), cache_x
615
+ ],
616
+ dim=2)
617
+ x = layer(x, feat_cache[idx])
618
+ feat_cache[idx] = cache_x
619
+ feat_idx[0] += 1
620
+ else:
621
+ x = layer(x)
622
+ return x
623
+
624
+
625
+ class Encoder3d_38(nn.Module):
626
+
627
+ def __init__(self,
628
+ dim=128,
629
+ z_dim=4,
630
+ dim_mult=[1, 2, 4, 4],
631
+ num_res_blocks=2,
632
+ attn_scales=[],
633
+ temperal_downsample=[False, True, True],
634
+ dropout=0.0):
635
+ super().__init__()
636
+ self.dim = dim
637
+ self.z_dim = z_dim
638
+ self.dim_mult = dim_mult
639
+ self.num_res_blocks = num_res_blocks
640
+ self.attn_scales = attn_scales
641
+ self.temperal_downsample = temperal_downsample
642
+
643
+ # dimensions
644
+ dims = [dim * u for u in [1] + dim_mult]
645
+ scale = 1.0
646
+
647
+ # init block
648
+ self.conv1 = CausalConv3d(12, dims[0], 3, padding=1)
649
+
650
+ # downsample blocks
651
+ downsamples = []
652
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
653
+ t_down_flag = (
654
+ temperal_downsample[i] if i < len(temperal_downsample) else False
655
+ )
656
+ downsamples.append(
657
+ Down_ResidualBlock(
658
+ in_dim=in_dim,
659
+ out_dim=out_dim,
660
+ dropout=dropout,
661
+ mult=num_res_blocks,
662
+ temperal_downsample=t_down_flag,
663
+ down_flag=i != len(dim_mult) - 1,
664
+ )
665
+ )
666
+ scale /= 2.0
667
+ self.downsamples = nn.Sequential(*downsamples)
668
+
669
+ # middle blocks
670
+ self.middle = nn.Sequential(
671
+ ResidualBlock(out_dim, out_dim, dropout),
672
+ AttentionBlock(out_dim),
673
+ ResidualBlock(out_dim, out_dim, dropout),
674
+ )
675
+
676
+ # # output blocks
677
+ self.head = nn.Sequential(
678
+ RMS_norm(out_dim, images=False),
679
+ nn.SiLU(),
680
+ CausalConv3d(out_dim, z_dim, 3, padding=1),
681
+ )
682
+
683
+
684
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
685
+
686
+ if feat_cache is not None:
687
+ idx = feat_idx[0]
688
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
689
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
690
+ cache_x = torch.cat(
691
+ [
692
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
693
+ cache_x,
694
+ ],
695
+ dim=2,
696
+ )
697
+ x = self.conv1(x, feat_cache[idx])
698
+ feat_cache[idx] = cache_x
699
+ feat_idx[0] += 1
700
+ else:
701
+ x = self.conv1(x)
702
+
703
+ ## downsamples
704
+ for layer in self.downsamples:
705
+ if feat_cache is not None:
706
+ x = layer(x, feat_cache, feat_idx)
707
+ else:
708
+ x = layer(x)
709
+
710
+ ## middle
711
+ for layer in self.middle:
712
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
713
+ x = layer(x, feat_cache, feat_idx)
714
+ else:
715
+ x = layer(x)
716
+
717
+ ## head
718
+ for layer in self.head:
719
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
720
+ idx = feat_idx[0]
721
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
722
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
723
+ cache_x = torch.cat(
724
+ [
725
+ feat_cache[idx][:, :, -1, :, :]
726
+ .unsqueeze(2)
727
+ .to(cache_x.device),
728
+ cache_x,
729
+ ],
730
+ dim=2,
731
+ )
732
+ x = layer(x, feat_cache[idx])
733
+ feat_cache[idx] = cache_x
734
+ feat_idx[0] += 1
735
+ else:
736
+ x = layer(x)
737
+
738
+ return x
739
+
740
+
741
+ class Decoder3d(nn.Module):
742
+
743
+ def __init__(self,
744
+ dim=128,
745
+ z_dim=4,
746
+ dim_mult=[1, 2, 4, 4],
747
+ num_res_blocks=2,
748
+ attn_scales=[],
749
+ temperal_upsample=[False, True, True],
750
+ dropout=0.0):
751
+ super().__init__()
752
+ self.dim = dim
753
+ self.z_dim = z_dim
754
+ self.dim_mult = dim_mult
755
+ self.num_res_blocks = num_res_blocks
756
+ self.attn_scales = attn_scales
757
+ self.temperal_upsample = temperal_upsample
758
+
759
+ # dimensions
760
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
761
+ scale = 1.0 / 2**(len(dim_mult) - 2)
762
+
763
+ # init block
764
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
765
+
766
+ # middle blocks
767
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
768
+ AttentionBlock(dims[0]),
769
+ ResidualBlock(dims[0], dims[0], dropout))
770
+
771
+ # upsample blocks
772
+ upsamples = []
773
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
774
+ # residual (+attention) blocks
775
+ if i == 1 or i == 2 or i == 3:
776
+ in_dim = in_dim // 2
777
+ for _ in range(num_res_blocks + 1):
778
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
779
+ if scale in attn_scales:
780
+ upsamples.append(AttentionBlock(out_dim))
781
+ in_dim = out_dim
782
+
783
+ # upsample block
784
+ if i != len(dim_mult) - 1:
785
+ mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d'
786
+ upsamples.append(Resample(out_dim, mode=mode))
787
+ scale *= 2.0
788
+ self.upsamples = nn.Sequential(*upsamples)
789
+
790
+ # output blocks
791
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
792
+ CausalConv3d(out_dim, 3, 3, padding=1))
793
+
794
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
795
+ ## conv1
796
+ if feat_cache is not None:
797
+ idx = feat_idx[0]
798
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
799
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
800
+ # cache last frame of last two chunk
801
+ cache_x = torch.cat([
802
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
803
+ cache_x.device), cache_x
804
+ ],
805
+ dim=2)
806
+ x = self.conv1(x, feat_cache[idx])
807
+ feat_cache[idx] = cache_x
808
+ feat_idx[0] += 1
809
+ else:
810
+ x = self.conv1(x)
811
+
812
+ ## middle
813
+ for layer in self.middle:
814
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
815
+ x = layer(x, feat_cache, feat_idx)
816
+ else:
817
+ x = layer(x)
818
+
819
+ ## upsamples
820
+ for layer in self.upsamples:
821
+ if feat_cache is not None:
822
+ x = layer(x, feat_cache, feat_idx)
823
+ else:
824
+ x = layer(x)
825
+
826
+ ## head
827
+ for layer in self.head:
828
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
829
+ idx = feat_idx[0]
830
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
831
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
832
+ # cache last frame of last two chunk
833
+ cache_x = torch.cat([
834
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
835
+ cache_x.device), cache_x
836
+ ],
837
+ dim=2)
838
+ x = layer(x, feat_cache[idx])
839
+ feat_cache[idx] = cache_x
840
+ feat_idx[0] += 1
841
+ else:
842
+ x = layer(x)
843
+ return x
844
+
845
+
846
+
847
+ class Decoder3d_38(nn.Module):
848
+
849
+ def __init__(self,
850
+ dim=128,
851
+ z_dim=4,
852
+ dim_mult=[1, 2, 4, 4],
853
+ num_res_blocks=2,
854
+ attn_scales=[],
855
+ temperal_upsample=[False, True, True],
856
+ dropout=0.0):
857
+ super().__init__()
858
+ self.dim = dim
859
+ self.z_dim = z_dim
860
+ self.dim_mult = dim_mult
861
+ self.num_res_blocks = num_res_blocks
862
+ self.attn_scales = attn_scales
863
+ self.temperal_upsample = temperal_upsample
864
+
865
+ # dimensions
866
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
867
+ scale = 1.0 / 2 ** (len(dim_mult) - 2)
868
+ # init block
869
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
870
+
871
+ # middle blocks
872
+ self.middle = nn.Sequential(ResidualBlock(dims[0], dims[0], dropout),
873
+ AttentionBlock(dims[0]),
874
+ ResidualBlock(dims[0], dims[0], dropout))
875
+
876
+ # upsample blocks
877
+ upsamples = []
878
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
879
+ t_up_flag = temperal_upsample[i] if i < len(temperal_upsample) else False
880
+ upsamples.append(
881
+ Up_ResidualBlock(in_dim=in_dim,
882
+ out_dim=out_dim,
883
+ dropout=dropout,
884
+ mult=num_res_blocks + 1,
885
+ temperal_upsample=t_up_flag,
886
+ up_flag=i != len(dim_mult) - 1))
887
+ self.upsamples = nn.Sequential(*upsamples)
888
+
889
+ # output blocks
890
+ self.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),
891
+ CausalConv3d(out_dim, 12, 3, padding=1))
892
+
893
+
894
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
895
+ if feat_cache is not None:
896
+ idx = feat_idx[0]
897
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
898
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
899
+ cache_x = torch.cat(
900
+ [
901
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device),
902
+ cache_x,
903
+ ],
904
+ dim=2,
905
+ )
906
+ x = self.conv1(x, feat_cache[idx])
907
+ feat_cache[idx] = cache_x
908
+ feat_idx[0] += 1
909
+ else:
910
+ x = self.conv1(x)
911
+
912
+ for layer in self.middle:
913
+ if check_is_instance(layer, ResidualBlock) and feat_cache is not None:
914
+ x = layer(x, feat_cache, feat_idx)
915
+ else:
916
+ x = layer(x)
917
+
918
+ ## upsamples
919
+ for layer in self.upsamples:
920
+ if feat_cache is not None:
921
+ x = layer(x, feat_cache, feat_idx, first_chunk)
922
+ else:
923
+ x = layer(x)
924
+
925
+ ## head
926
+ for layer in self.head:
927
+ if check_is_instance(layer, CausalConv3d) and feat_cache is not None:
928
+ idx = feat_idx[0]
929
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
930
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
931
+ cache_x = torch.cat(
932
+ [
933
+ feat_cache[idx][:, :, -1, :, :]
934
+ .unsqueeze(2)
935
+ .to(cache_x.device),
936
+ cache_x,
937
+ ],
938
+ dim=2,
939
+ )
940
+ x = layer(x, feat_cache[idx])
941
+ feat_cache[idx] = cache_x
942
+ feat_idx[0] += 1
943
+ else:
944
+ x = layer(x)
945
+ return x
946
+
947
+
948
+ def count_conv3d(model):
949
+ count = 0
950
+ for m in model.modules():
951
+ if isinstance(m, CausalConv3d):
952
+ count += 1
953
+ return count
954
+
955
+
956
+ class VideoVAE_(nn.Module):
957
+
958
+ def __init__(self,
959
+ dim=96,
960
+ z_dim=16,
961
+ dim_mult=[1, 2, 4, 4],
962
+ num_res_blocks=2,
963
+ attn_scales=[],
964
+ temperal_downsample=[False, True, True],
965
+ dropout=0.0):
966
+ super().__init__()
967
+ self.dim = dim
968
+ self.z_dim = z_dim
969
+ self.dim_mult = dim_mult
970
+ self.num_res_blocks = num_res_blocks
971
+ self.attn_scales = attn_scales
972
+ self.temperal_downsample = temperal_downsample
973
+ self.temperal_upsample = temperal_downsample[::-1]
974
+
975
+ # modules
976
+ self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks,
977
+ attn_scales, self.temperal_downsample, dropout)
978
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
979
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
980
+ self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks,
981
+ attn_scales, self.temperal_upsample, dropout)
982
+
983
+ def forward(self, x):
984
+ mu, log_var = self.encode(x)
985
+ z = self.reparameterize(mu, log_var)
986
+ x_recon = self.decode(z)
987
+ return x_recon, mu, log_var
988
+
989
+ def encode(self, x, scale):
990
+ self.clear_cache()
991
+ ## cache
992
+ t = x.shape[2]
993
+ iter_ = 1 + (t - 1) // 4
994
+
995
+ for i in range(iter_):
996
+ self._enc_conv_idx = [0]
997
+ if i == 0:
998
+ out = self.encoder(x[:, :, :1, :, :],
999
+ feat_cache=self._enc_feat_map,
1000
+ feat_idx=self._enc_conv_idx)
1001
+ else:
1002
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1003
+ feat_cache=self._enc_feat_map,
1004
+ feat_idx=self._enc_conv_idx)
1005
+ out = torch.cat([out, out_], 2)
1006
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1007
+ if isinstance(scale[0], torch.Tensor):
1008
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1009
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1010
+ 1, self.z_dim, 1, 1, 1)
1011
+ else:
1012
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1013
+ mu = (mu - scale[0]) * scale[1]
1014
+ return mu
1015
+
1016
+ def decode(self, z, scale):
1017
+ self.clear_cache()
1018
+ # z: [b,c,t,h,w]
1019
+ if isinstance(scale[0], torch.Tensor):
1020
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1021
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1022
+ 1, self.z_dim, 1, 1, 1)
1023
+ else:
1024
+ scale = scale.to(dtype=z.dtype, device=z.device)
1025
+ z = z / scale[1] + scale[0]
1026
+ iter_ = z.shape[2]
1027
+ x = self.conv2(z)
1028
+ for i in range(iter_):
1029
+ self._conv_idx = [0]
1030
+ if i == 0:
1031
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1032
+ feat_cache=self._feat_map,
1033
+ feat_idx=self._conv_idx)
1034
+ else:
1035
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1036
+ feat_cache=self._feat_map,
1037
+ feat_idx=self._conv_idx)
1038
+ out = torch.cat([out, out_], 2) # may add tensor offload
1039
+ return out
1040
+
1041
+ def reparameterize(self, mu, log_var):
1042
+ std = torch.exp(0.5 * log_var)
1043
+ eps = torch.randn_like(std)
1044
+ return eps * std + mu
1045
+
1046
+ def sample(self, imgs, deterministic=False):
1047
+ mu, log_var = self.encode(imgs)
1048
+ if deterministic:
1049
+ return mu
1050
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
1051
+ return mu + std * torch.randn_like(std)
1052
+
1053
+ def clear_cache(self):
1054
+ self._conv_num = count_conv3d(self.decoder)
1055
+ self._conv_idx = [0]
1056
+ self._feat_map = [None] * self._conv_num
1057
+ # cache encode
1058
+ self._enc_conv_num = count_conv3d(self.encoder)
1059
+ self._enc_conv_idx = [0]
1060
+ self._enc_feat_map = [None] * self._enc_conv_num
1061
+
1062
+
1063
+ class WanVideoVAE(nn.Module):
1064
+
1065
+ def __init__(self, z_dim=16):
1066
+ super().__init__()
1067
+
1068
+ mean = [
1069
+ -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,
1070
+ 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921
1071
+ ]
1072
+ std = [
1073
+ 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743,
1074
+ 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160
1075
+ ]
1076
+ self.mean = torch.tensor(mean)
1077
+ self.std = torch.tensor(std)
1078
+ self.scale = [self.mean, 1.0 / self.std]
1079
+
1080
+ # init model
1081
+ self.model = VideoVAE_(z_dim=z_dim).eval().requires_grad_(False)
1082
+ self.upsampling_factor = 8
1083
+ self.z_dim = z_dim
1084
+
1085
+
1086
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
1087
+ x = torch.ones((length,))
1088
+ if not left_bound:
1089
+ x[:border_width] = (torch.arange(border_width) + 1) / border_width
1090
+ if not right_bound:
1091
+ x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,))
1092
+ return x
1093
+
1094
+
1095
+ def build_mask(self, data, is_bound, border_width):
1096
+ _, _, _, H, W = data.shape
1097
+ h = self.build_1d_mask(H, is_bound[0], is_bound[1], border_width[0])
1098
+ w = self.build_1d_mask(W, is_bound[2], is_bound[3], border_width[1])
1099
+
1100
+ h = repeat(h, "H -> H W", H=H, W=W)
1101
+ w = repeat(w, "W -> H W", H=H, W=W)
1102
+
1103
+ mask = torch.stack([h, w]).min(dim=0).values
1104
+ mask = rearrange(mask, "H W -> 1 1 1 H W")
1105
+ return mask
1106
+
1107
+
1108
+ def tiled_decode(self, hidden_states, device, tile_size, tile_stride):
1109
+ _, _, T, H, W = hidden_states.shape
1110
+ size_h, size_w = tile_size
1111
+ stride_h, stride_w = tile_stride
1112
+
1113
+ # Split tasks
1114
+ tasks = []
1115
+ for h in range(0, H, stride_h):
1116
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1117
+ for w in range(0, W, stride_w):
1118
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1119
+ h_, w_ = h + size_h, w + size_w
1120
+ tasks.append((h, h_, w, w_))
1121
+
1122
+ data_device = "cpu"
1123
+ computation_device = device
1124
+
1125
+ out_T = T * 4 - 3
1126
+ weight = torch.zeros((1, 1, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1127
+ values = torch.zeros((1, 3, out_T, H * self.upsampling_factor, W * self.upsampling_factor), dtype=hidden_states.dtype, device=data_device)
1128
+
1129
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE decoding"):
1130
+ hidden_states_batch = hidden_states[:, :, :, h:h_, w:w_].to(computation_device)
1131
+ hidden_states_batch = self.model.decode(hidden_states_batch, self.scale).to(data_device)
1132
+
1133
+ mask = self.build_mask(
1134
+ hidden_states_batch,
1135
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1136
+ border_width=((size_h - stride_h) * self.upsampling_factor, (size_w - stride_w) * self.upsampling_factor)
1137
+ ).to(dtype=hidden_states.dtype, device=data_device)
1138
+
1139
+ target_h = h * self.upsampling_factor
1140
+ target_w = w * self.upsampling_factor
1141
+ values[
1142
+ :,
1143
+ :,
1144
+ :,
1145
+ target_h:target_h + hidden_states_batch.shape[3],
1146
+ target_w:target_w + hidden_states_batch.shape[4],
1147
+ ] += hidden_states_batch * mask
1148
+ weight[
1149
+ :,
1150
+ :,
1151
+ :,
1152
+ target_h: target_h + hidden_states_batch.shape[3],
1153
+ target_w: target_w + hidden_states_batch.shape[4],
1154
+ ] += mask
1155
+ values = values / weight
1156
+ values = values.clamp_(-1, 1)
1157
+ return values
1158
+
1159
+
1160
+ def tiled_encode(self, video, device, tile_size, tile_stride):
1161
+ _, _, T, H, W = video.shape
1162
+ size_h, size_w = tile_size
1163
+ stride_h, stride_w = tile_stride
1164
+
1165
+ # Split tasks
1166
+ tasks = []
1167
+ for h in range(0, H, stride_h):
1168
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
1169
+ for w in range(0, W, stride_w):
1170
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
1171
+ h_, w_ = h + size_h, w + size_w
1172
+ tasks.append((h, h_, w, w_))
1173
+
1174
+ data_device = "cpu"
1175
+ computation_device = device
1176
+
1177
+ out_T = (T + 3) // 4
1178
+ weight = torch.zeros((1, 1, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1179
+ values = torch.zeros((1, self.z_dim, out_T, H // self.upsampling_factor, W // self.upsampling_factor), dtype=video.dtype, device=data_device)
1180
+
1181
+ for h, h_, w, w_ in tqdm(tasks, desc="VAE encoding"):
1182
+ hidden_states_batch = video[:, :, :, h:h_, w:w_].to(computation_device)
1183
+ hidden_states_batch = self.model.encode(hidden_states_batch, self.scale).to(data_device)
1184
+
1185
+ mask = self.build_mask(
1186
+ hidden_states_batch,
1187
+ is_bound=(h==0, h_>=H, w==0, w_>=W),
1188
+ border_width=((size_h - stride_h) // self.upsampling_factor, (size_w - stride_w) // self.upsampling_factor)
1189
+ ).to(dtype=video.dtype, device=data_device)
1190
+
1191
+ target_h = h // self.upsampling_factor
1192
+ target_w = w // self.upsampling_factor
1193
+ values[
1194
+ :,
1195
+ :,
1196
+ :,
1197
+ target_h:target_h + hidden_states_batch.shape[3],
1198
+ target_w:target_w + hidden_states_batch.shape[4],
1199
+ ] += hidden_states_batch * mask
1200
+ weight[
1201
+ :,
1202
+ :,
1203
+ :,
1204
+ target_h: target_h + hidden_states_batch.shape[3],
1205
+ target_w: target_w + hidden_states_batch.shape[4],
1206
+ ] += mask
1207
+ values = values / weight
1208
+ return values
1209
+
1210
+
1211
+ def single_encode(self, video, device):
1212
+ video = video.to(device)
1213
+ x = self.model.encode(video, self.scale)
1214
+ return x
1215
+
1216
+
1217
+ def single_decode(self, hidden_state, device):
1218
+ hidden_state = hidden_state.to(device)
1219
+ video = self.model.decode(hidden_state, self.scale)
1220
+ return video.clamp_(-1, 1)
1221
+
1222
+
1223
+ def encode(self, videos, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1224
+ videos = [video.to("cpu") for video in videos]
1225
+ hidden_states = []
1226
+ for video in videos:
1227
+ video = video.unsqueeze(0)
1228
+ if tiled:
1229
+ tile_size = (tile_size[0] * self.upsampling_factor, tile_size[1] * self.upsampling_factor)
1230
+ tile_stride = (tile_stride[0] * self.upsampling_factor, tile_stride[1] * self.upsampling_factor)
1231
+ hidden_state = self.tiled_encode(video, device, tile_size, tile_stride)
1232
+ else:
1233
+ hidden_state = self.single_encode(video, device)
1234
+ hidden_state = hidden_state.squeeze(0)
1235
+ hidden_states.append(hidden_state)
1236
+ hidden_states = torch.stack(hidden_states)
1237
+ return hidden_states
1238
+
1239
+
1240
+ def decode(self, hidden_states, device, tiled=False, tile_size=(34, 34), tile_stride=(18, 16)):
1241
+ hidden_states = [hidden_state.to("cpu") for hidden_state in hidden_states]
1242
+ videos = []
1243
+ for hidden_state in hidden_states:
1244
+ hidden_state = hidden_state.unsqueeze(0)
1245
+ if tiled:
1246
+ video = self.tiled_decode(hidden_state, device, tile_size, tile_stride)
1247
+ else:
1248
+ video = self.single_decode(hidden_state, device)
1249
+ video = video.squeeze(0)
1250
+ videos.append(video)
1251
+ videos = torch.stack(videos)
1252
+ return videos
1253
+
1254
+
1255
+ @staticmethod
1256
+ def state_dict_converter():
1257
+ return WanVideoVAEStateDictConverter()
1258
+
1259
+
1260
+ class WanVideoVAEStateDictConverter:
1261
+
1262
+ def __init__(self):
1263
+ pass
1264
+
1265
+ def from_civitai(self, state_dict):
1266
+ state_dict_ = {}
1267
+ if 'model_state' in state_dict:
1268
+ state_dict = state_dict['model_state']
1269
+ for name in state_dict:
1270
+ state_dict_['model.' + name] = state_dict[name]
1271
+ return state_dict_
1272
+
1273
+
1274
+ class VideoVAE38_(VideoVAE_):
1275
+
1276
+ def __init__(self,
1277
+ dim=160,
1278
+ z_dim=48,
1279
+ dec_dim=256,
1280
+ dim_mult=[1, 2, 4, 4],
1281
+ num_res_blocks=2,
1282
+ attn_scales=[],
1283
+ temperal_downsample=[False, True, True],
1284
+ dropout=0.0):
1285
+ super(VideoVAE_, self).__init__()
1286
+ self.dim = dim
1287
+ self.z_dim = z_dim
1288
+ self.dim_mult = dim_mult
1289
+ self.num_res_blocks = num_res_blocks
1290
+ self.attn_scales = attn_scales
1291
+ self.temperal_downsample = temperal_downsample
1292
+ self.temperal_upsample = temperal_downsample[::-1]
1293
+
1294
+ # modules
1295
+ self.encoder = Encoder3d_38(dim, z_dim * 2, dim_mult, num_res_blocks,
1296
+ attn_scales, self.temperal_downsample, dropout)
1297
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
1298
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
1299
+ self.decoder = Decoder3d_38(dec_dim, z_dim, dim_mult, num_res_blocks,
1300
+ attn_scales, self.temperal_upsample, dropout)
1301
+
1302
+
1303
+ def encode(self, x, scale):
1304
+ self.clear_cache()
1305
+ x = patchify(x, patch_size=2)
1306
+ t = x.shape[2]
1307
+ iter_ = 1 + (t - 1) // 4
1308
+ for i in range(iter_):
1309
+ self._enc_conv_idx = [0]
1310
+ if i == 0:
1311
+ out = self.encoder(x[:, :, :1, :, :],
1312
+ feat_cache=self._enc_feat_map,
1313
+ feat_idx=self._enc_conv_idx)
1314
+ else:
1315
+ out_ = self.encoder(x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
1316
+ feat_cache=self._enc_feat_map,
1317
+ feat_idx=self._enc_conv_idx)
1318
+ out = torch.cat([out, out_], 2)
1319
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
1320
+ if isinstance(scale[0], torch.Tensor):
1321
+ scale = [s.to(dtype=mu.dtype, device=mu.device) for s in scale]
1322
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
1323
+ 1, self.z_dim, 1, 1, 1)
1324
+ else:
1325
+ scale = scale.to(dtype=mu.dtype, device=mu.device)
1326
+ mu = (mu - scale[0]) * scale[1]
1327
+ self.clear_cache()
1328
+ return mu
1329
+
1330
+
1331
+ def decode(self, z, scale):
1332
+ self.clear_cache()
1333
+ if isinstance(scale[0], torch.Tensor):
1334
+ scale = [s.to(dtype=z.dtype, device=z.device) for s in scale]
1335
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
1336
+ 1, self.z_dim, 1, 1, 1)
1337
+ else:
1338
+ scale = scale.to(dtype=z.dtype, device=z.device)
1339
+ z = z / scale[1] + scale[0]
1340
+ iter_ = z.shape[2]
1341
+ x = self.conv2(z)
1342
+ for i in range(iter_):
1343
+ self._conv_idx = [0]
1344
+ if i == 0:
1345
+ out = self.decoder(x[:, :, i:i + 1, :, :],
1346
+ feat_cache=self._feat_map,
1347
+ feat_idx=self._conv_idx,
1348
+ first_chunk=True)
1349
+ else:
1350
+ out_ = self.decoder(x[:, :, i:i + 1, :, :],
1351
+ feat_cache=self._feat_map,
1352
+ feat_idx=self._conv_idx)
1353
+ out = torch.cat([out, out_], 2)
1354
+ out = unpatchify(out, patch_size=2)
1355
+ self.clear_cache()
1356
+ return out
1357
+
1358
+
1359
+ class WanVideoVAE38(WanVideoVAE):
1360
+
1361
+ def __init__(self, z_dim=48, dim=160):
1362
+ super(WanVideoVAE, self).__init__()
1363
+
1364
+ mean = [
1365
+ -0.2289, -0.0052, -0.1323, -0.2339, -0.2799, 0.0174, 0.1838, 0.1557,
1366
+ -0.1382, 0.0542, 0.2813, 0.0891, 0.1570, -0.0098, 0.0375, -0.1825,
1367
+ -0.2246, -0.1207, -0.0698, 0.5109, 0.2665, -0.2108, -0.2158, 0.2502,
1368
+ -0.2055, -0.0322, 0.1109, 0.1567, -0.0729, 0.0899, -0.2799, -0.1230,
1369
+ -0.0313, -0.1649, 0.0117, 0.0723, -0.2839, -0.2083, -0.0520, 0.3748,
1370
+ 0.0152, 0.1957, 0.1433, -0.2944, 0.3573, -0.0548, -0.1681, -0.0667
1371
+ ]
1372
+ std = [
1373
+ 0.4765, 1.0364, 0.4514, 1.1677, 0.5313, 0.4990, 0.4818, 0.5013,
1374
+ 0.8158, 1.0344, 0.5894, 1.0901, 0.6885, 0.6165, 0.8454, 0.4978,
1375
+ 0.5759, 0.3523, 0.7135, 0.6804, 0.5833, 1.4146, 0.8986, 0.5659,
1376
+ 0.7069, 0.5338, 0.4889, 0.4917, 0.4069, 0.4999, 0.6866, 0.4093,
1377
+ 0.5709, 0.6065, 0.6415, 0.4944, 0.5726, 1.2042, 0.5458, 1.6887,
1378
+ 0.3971, 1.0600, 0.3943, 0.5537, 0.5444, 0.4089, 0.7468, 0.7744
1379
+ ]
1380
+ self.mean = torch.tensor(mean)
1381
+ self.std = torch.tensor(std)
1382
+ self.scale = [self.mean, 1.0 / self.std]
1383
+
1384
+ # init model
1385
+ self.model = VideoVAE38_(z_dim=z_dim, dim=dim).eval().requires_grad_(False)
1386
+ self.upsampling_factor = 16
1387
+ self.z_dim = z_dim
1388
+
1389
+
1390
+ # ─────────────────────────────────────────────────────────────────────────────
1391
+ # Diffusers-compatible wrapper (formerly kiwi_vae.py)
1392
+ # ─────────────────────────────────��───────────────────────────────────────────
1393
+
1394
+ @dataclass
1395
+ class LatentDist:
1396
+ mu: torch.Tensor
1397
+
1398
+ def sample(self):
1399
+ return self.mu
1400
+
1401
+
1402
+ @dataclass
1403
+ class EncoderOutput:
1404
+ latent_dist: LatentDist
1405
+
1406
+
1407
+ @dataclass
1408
+ class DecoderOutput:
1409
+ sample: torch.Tensor
1410
+
1411
+
1412
+ class VAE(VideoVAE_, ModelMixin, ConfigMixin):
1413
+ """
1414
+ Diffusers-compatible VAE wrapper around the original Wan VideoVAE.
1415
+ Loads weights directly from diffusion_pytorch_model.safetensors.
1416
+ """
1417
+
1418
+ @register_to_config
1419
+ def __init__(
1420
+ self,
1421
+ z_dim: int = 48,
1422
+ dim: int = 160,
1423
+ dim_mult: List[int] = [1, 2, 4, 4],
1424
+ num_res_blocks: int = 2,
1425
+ attn_scales: List[float] = [],
1426
+ temperal_downsample: List[bool] = [False, True, True],
1427
+ dropout: float = 0.0,
1428
+ vae_pth: str = "wan_vae.pth",
1429
+ latents_mean: Optional[List[float]] = None,
1430
+ latents_std: Optional[List[float]] = None,
1431
+ ):
1432
+ # Build the actual VAE backbone so diffusers can load weights without mismatch.
1433
+ if z_dim == 48:
1434
+ VideoVAE38_.__init__(
1435
+ self,
1436
+ dim=dim,
1437
+ z_dim=z_dim,
1438
+ dim_mult=dim_mult,
1439
+ num_res_blocks=num_res_blocks,
1440
+ attn_scales=attn_scales,
1441
+ temperal_downsample=temperal_downsample,
1442
+ dropout=dropout,
1443
+ )
1444
+ self._use_38 = True
1445
+ self.upsampling_factor = 16
1446
+ else:
1447
+ VideoVAE_.__init__(
1448
+ self,
1449
+ dim=dim,
1450
+ z_dim=z_dim,
1451
+ dim_mult=dim_mult,
1452
+ num_res_blocks=num_res_blocks,
1453
+ attn_scales=attn_scales,
1454
+ temperal_downsample=temperal_downsample,
1455
+ dropout=dropout,
1456
+ )
1457
+ self._use_38 = False
1458
+ self.upsampling_factor = 8
1459
+
1460
+ # Keep for config compatibility; weights are loaded by diffusers.
1461
+ self._vae_pth = vae_pth
1462
+ self.z_dim = z_dim
1463
+
1464
+ # Build latent normalization scale: [mean, 1/std]
1465
+ if latents_mean is not None and latents_std is not None:
1466
+ mean = torch.tensor(latents_mean)
1467
+ std = torch.tensor(latents_std)
1468
+ self._scale = [mean, 1.0 / std]
1469
+ else:
1470
+ self._scale = [torch.zeros(z_dim), torch.ones(z_dim)]
1471
+
1472
+ def encode(self, x):
1473
+ x = x.to(dtype=next(self.parameters()).dtype)
1474
+ if self._use_38:
1475
+ mu = VideoVAE38_.encode(self, x, self._scale)
1476
+ else:
1477
+ mu = VideoVAE_.encode(self, x, self._scale)
1478
+ return EncoderOutput(latent_dist=LatentDist(mu=mu))
1479
+
1480
+ def decode(self, z):
1481
+ z = z.to(dtype=next(self.parameters()).dtype)
1482
+ if self._use_38:
1483
+ out = VideoVAE38_.decode(self, z, self._scale)
1484
+ else:
1485
+ out = VideoVAE_.decode(self, z, self._scale)
1486
+ return DecoderOutput(sample=out)