multimodalart HF Staff commited on
Commit
1d5b5ac
·
verified ·
1 Parent(s): f6f7ccc

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model_manager import *
attention.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange
3
+
4
+
5
+ def low_version_attention(query, key, value, attn_bias=None):
6
+ scale = 1 / query.shape[-1] ** 0.5
7
+ query = query * scale
8
+ attn = torch.matmul(query, key.transpose(-2, -1))
9
+ if attn_bias is not None:
10
+ attn = attn + attn_bias
11
+ attn = attn.softmax(-1)
12
+ return attn @ value
13
+
14
+
15
+ class Attention(torch.nn.Module):
16
+
17
+ def __init__(self, q_dim, num_heads, head_dim, kv_dim=None, bias_q=False, bias_kv=False, bias_out=False):
18
+ super().__init__()
19
+ dim_inner = head_dim * num_heads
20
+ kv_dim = kv_dim if kv_dim is not None else q_dim
21
+ self.num_heads = num_heads
22
+ self.head_dim = head_dim
23
+
24
+ self.to_q = torch.nn.Linear(q_dim, dim_inner, bias=bias_q)
25
+ self.to_k = torch.nn.Linear(kv_dim, dim_inner, bias=bias_kv)
26
+ self.to_v = torch.nn.Linear(kv_dim, dim_inner, bias=bias_kv)
27
+ self.to_out = torch.nn.Linear(dim_inner, q_dim, bias=bias_out)
28
+
29
+ def interact_with_ipadapter(self, hidden_states, q, ip_k, ip_v, scale=1.0):
30
+ batch_size = q.shape[0]
31
+ ip_k = ip_k.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
32
+ ip_v = ip_v.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
33
+ ip_hidden_states = torch.nn.functional.scaled_dot_product_attention(q, ip_k, ip_v)
34
+ hidden_states = hidden_states + scale * ip_hidden_states
35
+ return hidden_states
36
+
37
+ def torch_forward(self, hidden_states, encoder_hidden_states=None, attn_mask=None, ipadapter_kwargs=None, qkv_preprocessor=None):
38
+ if encoder_hidden_states is None:
39
+ encoder_hidden_states = hidden_states
40
+
41
+ batch_size = encoder_hidden_states.shape[0]
42
+
43
+ q = self.to_q(hidden_states)
44
+ k = self.to_k(encoder_hidden_states)
45
+ v = self.to_v(encoder_hidden_states)
46
+
47
+ q = q.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
48
+ k = k.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
49
+ v = v.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
50
+
51
+ if qkv_preprocessor is not None:
52
+ q, k, v = qkv_preprocessor(q, k, v)
53
+
54
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
55
+ if ipadapter_kwargs is not None:
56
+ hidden_states = self.interact_with_ipadapter(hidden_states, q, **ipadapter_kwargs)
57
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
58
+ hidden_states = hidden_states.to(q.dtype)
59
+
60
+ hidden_states = self.to_out(hidden_states)
61
+
62
+ return hidden_states
63
+
64
+ def xformers_forward(self, hidden_states, encoder_hidden_states=None, attn_mask=None):
65
+ if encoder_hidden_states is None:
66
+ encoder_hidden_states = hidden_states
67
+
68
+ q = self.to_q(hidden_states)
69
+ k = self.to_k(encoder_hidden_states)
70
+ v = self.to_v(encoder_hidden_states)
71
+
72
+ q = rearrange(q, "b f (n d) -> (b n) f d", n=self.num_heads)
73
+ k = rearrange(k, "b f (n d) -> (b n) f d", n=self.num_heads)
74
+ v = rearrange(v, "b f (n d) -> (b n) f d", n=self.num_heads)
75
+
76
+ if attn_mask is not None:
77
+ hidden_states = low_version_attention(q, k, v, attn_bias=attn_mask)
78
+ else:
79
+ import xformers.ops as xops
80
+ hidden_states = xops.memory_efficient_attention(q, k, v)
81
+ hidden_states = rearrange(hidden_states, "(b n) f d -> b f (n d)", n=self.num_heads)
82
+
83
+ hidden_states = hidden_states.to(q.dtype)
84
+ hidden_states = self.to_out(hidden_states)
85
+
86
+ return hidden_states
87
+
88
+ def forward(self, hidden_states, encoder_hidden_states=None, attn_mask=None, ipadapter_kwargs=None, qkv_preprocessor=None):
89
+ return self.torch_forward(hidden_states, encoder_hidden_states=encoder_hidden_states, attn_mask=attn_mask, ipadapter_kwargs=ipadapter_kwargs, qkv_preprocessor=qkv_preprocessor)
camera_encoder.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Camera Encoder for RT (Rotation-Translation) matrix injection.
3
+ CAM paper [2506.03141]: Maps camera pose to DiT hidden dimension for spatial attention conditioning.
4
+
5
+ Design notes:
6
+ - Primary purpose: dimension alignment (action/RT [12] -> DiT hidden D). One-layer MLP is sufficient; no need for deeper encoder.
7
+ - Per-frame MLP: each frame's RT [12] -> hidden_size independently (no temporal context).
8
+ - Optional zero-init scale: conditioning starts weak (scale=0) and grows with training for stability.
9
+ - shallow: single Linear(12, D) to match CAM "single-layer MLP" wording (ablation). When shallow=True
10
+ and separate_t_r=False, the encoder is exactly one layer (merged MLP): RT [12] -> D.
11
+ - separate_t_r: encode translation (t) and rotation (R) with separate MLPs then add, for scale balance.
12
+ Use shallow=True and separate_t_r=False for merged single-layer MLP (RT not split).
13
+ - explicit_yaw: add a signed yaw scalar branch (Z-only) so CW/CCW are explicitly encoded; helps when
14
+ the model is insensitive to rotation direction (Zhou et al. CVPR 2019, sign continuity).
15
+ - sincos_yaw: add [cos(yaw), sin(yaw)] branch (2D) for direction; sin carries sign explicitly.
16
+
17
+ Design limitations / caveats:
18
+ - No input normalization: t (translation) and R (rotation) have different scales; one Linear(12,D) may be
19
+ sensitive to units. Caller should use consistent RT scale or relative RT; optional input LayerNorm not implemented.
20
+ - Per-frame only: no temporal context (each frame encoded independently). Fine for CAM ablation; temporal modeling not supported.
21
+ - 16-dim input: layout for flattened 4x4 is unspecified; yaw branches are disabled. Prefer 12-dim in practice.
22
+ - explicit_yaw and sincos_yaw can both be True (redundant encoding of yaw); usually use one.
23
+ """
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ from typing import Optional
28
+
29
+ # For Z-only rotation: yaw = atan2(R_21, R_11); R is row-major [R_11,R_12,R_13, R_21,...]
30
+ def _yaw_from_rt_12(rt: torch.Tensor) -> torch.Tensor:
31
+ """rt [..., 12] -> yaw in [-1, 1] (normalized by pi)."""
32
+ R11 = rt[..., 3]
33
+ R21 = rt[..., 6]
34
+ yaw_rad = torch.atan2(R21, R11)
35
+ return yaw_rad / 3.141592653589793
36
+
37
+
38
+ def _sincos_yaw_from_rt_12(rt: torch.Tensor) -> torch.Tensor:
39
+ """rt [..., 12] -> [..., 2] (cos(yaw), sin(yaw))."""
40
+ R11 = rt[..., 3]
41
+ R21 = rt[..., 6]
42
+ yaw_rad = torch.atan2(R21, R11)
43
+ return torch.stack([torch.cos(yaw_rad), torch.sin(yaw_rad)], dim=-1)
44
+
45
+
46
+ class CameraEncoder(nn.Module):
47
+ """
48
+ Encode RT matrices (camera pose) to DiT hidden dimension.
49
+
50
+ Input: rt_matrices [B, F, 12] or [B, F, 16]
51
+ - 12: [t_x, t_y, t_z, R_11..R_33] (3 translation + 9 rotation), R row-major. No input normalization:
52
+ t and R often differ in scale (e.g. t in meters, R in [-1,1]); single Linear(12,D) may be sensitive to units.
53
+ - 16: 4x4 matrix flattened (layout/order unspecified; yaw branches disabled when rt_dim=16).
54
+ Output: camera_emb [B, F, D] where D = hidden_size (scaled by learnable scale, default 0-init).
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ rt_dim: int = 12,
60
+ hidden_size: int = 5120,
61
+ mlp_hidden_mult: int = 4,
62
+ eps: float = 1e-6,
63
+ zero_init_scale: bool = False,
64
+ full_zero_init: bool = False,
65
+ shallow: bool = False,
66
+ separate_t_r: bool = False,
67
+ explicit_yaw: bool = False,
68
+ sincos_yaw: bool = False,
69
+ conditioning_scale: float = 1.0,
70
+ r_mlp_no_layernorm: bool = False,
71
+ ):
72
+ super().__init__()
73
+ self.rt_dim = rt_dim
74
+ self.hidden_size = hidden_size
75
+ self.zero_init_scale = zero_init_scale
76
+ self.full_zero_init = full_zero_init
77
+ self.shallow = shallow
78
+ self.separate_t_r = separate_t_r
79
+ self.explicit_yaw = explicit_yaw and rt_dim == 12
80
+ self.sincos_yaw = sincos_yaw and rt_dim == 12
81
+ self.conditioning_scale = float(conditioning_scale)
82
+ self.r_mlp_no_layernorm = r_mlp_no_layernorm and separate_t_r
83
+ dtype = torch.get_default_dtype()
84
+
85
+ if separate_t_r:
86
+ # Plan B: separate t (3) and R (9) encoders for scale balance; only for rt_dim=12.
87
+ assert rt_dim == 12, "separate_t_r only supported for rt_dim=12"
88
+ mid = max(hidden_size // 2, 256)
89
+ self.t_mlp = nn.Sequential(
90
+ nn.Linear(3, mid),
91
+ nn.LayerNorm(mid, eps=eps),
92
+ nn.GELU(),
93
+ nn.Linear(mid, hidden_size),
94
+ nn.LayerNorm(hidden_size, eps=eps),
95
+ )
96
+ if r_mlp_no_layernorm:
97
+ # No LayerNorm on R so sign of R_12/R_21 (yaw direction) is not normalized away.
98
+ self.r_mlp = nn.Sequential(
99
+ nn.Linear(9, mid),
100
+ nn.GELU(),
101
+ nn.Linear(mid, hidden_size),
102
+ )
103
+ else:
104
+ self.r_mlp = nn.Sequential(
105
+ nn.Linear(9, mid),
106
+ nn.LayerNorm(mid, eps=eps),
107
+ nn.GELU(),
108
+ nn.Linear(mid, hidden_size),
109
+ nn.LayerNorm(hidden_size, eps=eps),
110
+ )
111
+ self.mlp = None
112
+ elif shallow:
113
+ # Merged single-layer MLP: one Linear(rt_dim, hidden_size), no separate t/R.
114
+ self.mlp = nn.Linear(rt_dim, hidden_size)
115
+ assert isinstance(self.mlp, nn.Linear), "shallow path must be exactly one Linear layer"
116
+ if full_zero_init:
117
+ nn.init.zeros_(self.mlp.weight)
118
+ nn.init.zeros_(self.mlp.bias)
119
+ else:
120
+ mid_dim = hidden_size * mlp_hidden_mult
121
+ self.mlp = nn.Sequential(
122
+ nn.Linear(rt_dim, mid_dim),
123
+ nn.LayerNorm(mid_dim, eps=eps),
124
+ nn.GELU(),
125
+ nn.Linear(mid_dim, mid_dim),
126
+ nn.LayerNorm(mid_dim, eps=eps),
127
+ nn.GELU(),
128
+ nn.Linear(mid_dim, hidden_size),
129
+ nn.LayerNorm(hidden_size, eps=eps),
130
+ )
131
+
132
+ if self.explicit_yaw:
133
+ self.yaw_embed = nn.Linear(1, hidden_size)
134
+ else:
135
+ self.yaw_embed = None
136
+ if self.sincos_yaw:
137
+ self.sincos_embed = nn.Linear(2, hidden_size)
138
+ else:
139
+ self.sincos_embed = None
140
+
141
+ # Learnable scale: when zero_init_scale=True, init to 0 so conditioning grows with training (stable).
142
+ # When full_zero_init=True, skip scale (GF-ICL style: Linear output directly, no extra scale).
143
+ if full_zero_init:
144
+ self.scale = None # no scale, use 1.0 in forward
145
+ else:
146
+ self.scale = nn.Parameter(torch.zeros(1) if zero_init_scale else torch.ones(1))
147
+
148
+ def is_single_layer_merged(self) -> bool:
149
+ """True if encoder is exactly one Linear(12, D) with no separate t/R (merged MLP)."""
150
+ return self.shallow and not self.separate_t_r and self.mlp is not None and isinstance(self.mlp, nn.Linear)
151
+
152
+ def forward(self, rt_matrices: torch.Tensor) -> torch.Tensor:
153
+ """
154
+ Args:
155
+ rt_matrices: [B, F, 12] or [B, F, 16]
156
+ Returns:
157
+ camera_emb: [B, F, hidden_size], scaled by self.scale.
158
+ """
159
+ d = rt_matrices.dtype
160
+ if self.separate_t_r:
161
+ t = rt_matrices[..., :3].to(d)
162
+ r = rt_matrices[..., 3:12].to(d)
163
+ out = self.t_mlp(t) + self.r_mlp(r)
164
+ else:
165
+ out = self.mlp(rt_matrices.to(d))
166
+ if self.yaw_embed is not None and rt_matrices.shape[-1] >= 12:
167
+ yaw_norm = _yaw_from_rt_12(rt_matrices[..., :12]).unsqueeze(-1).to(d)
168
+ out = out + self.yaw_embed(yaw_norm)
169
+ if self.sincos_embed is not None and rt_matrices.shape[-1] >= 12:
170
+ sincos = _sincos_yaw_from_rt_12(rt_matrices[..., :12]).to(d)
171
+ out = out + self.sincos_embed(sincos)
172
+ scale = self.scale.to(d) if self.scale is not None else torch.ones(1, device=out.device, dtype=out.dtype)
173
+ return out * scale * self.conditioning_scale
174
+
175
+
176
+ def expand_camera_emb_to_tokens(
177
+ camera_emb: torch.Tensor,
178
+ num_frames: int,
179
+ h: int,
180
+ w: int,
181
+ ) -> torch.Tensor:
182
+ """
183
+ Expand per-frame camera_emb [B, F, D] to per-token [B, N, D]
184
+ where N = F * h * w (tokens ordered as frame0_all_patches, frame1_all_patches, ...).
185
+
186
+ Dimension alignment (与 DiT patchify 一致):
187
+ - Encoder 输出: 每帧一个向量 [B, F, D],即相当于 [B, F, 1, D](F 帧每帧 1 个 embedding)。
188
+ - 对齐方式: 在空间维上把该 1 重复 H×W 次,得到 [B, F, h*w, D],再展平为 [B, F*h*w, D]。
189
+ - Token 顺序: frame0 的 h*w 个 token 共用 frame0 的 camera_emb,frame1 的 h*w 个 token 共用 frame1 的 camera_emb,与
190
+ wan_video_dit patchify 的 rearrange(..., 'b c f h w -> b (f h w) c') 顺序一致(帧优先,再空间)。
191
+
192
+ Args:
193
+ camera_emb: [B, F, D]
194
+ num_frames: F (must equal camera_emb.shape[1]; used for assertion only).
195
+ h, w: spatial grid (patches per frame)
196
+ Returns:
197
+ [B, F*h*w, D]
198
+ """
199
+ B, F, D = camera_emb.shape
200
+ if F != num_frames:
201
+ raise ValueError(f"expand_camera_emb_to_tokens: camera_emb has F={F}, num_frames={num_frames}")
202
+ # [B, F, D] -> [B, F, 1, D] (每帧 1 个) -> expand 到 [B, F, h*w, D] (每帧重复 H×W 次) -> [B, F*h*w, D]
203
+ return camera_emb.unsqueeze(2).expand(B, F, h * w, D).reshape(B, F * h * w, D)
cog_dit.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange, repeat
3
+ from .sd3_dit import TimestepEmbeddings
4
+ from .attention import Attention
5
+ from .utils import load_state_dict_from_folder
6
+ from .tiler import TileWorker2Dto3D
7
+ import numpy as np
8
+
9
+
10
+
11
+ class CogPatchify(torch.nn.Module):
12
+ def __init__(self, dim_in, dim_out, patch_size) -> None:
13
+ super().__init__()
14
+ self.proj = torch.nn.Conv3d(dim_in, dim_out, kernel_size=(1, patch_size, patch_size), stride=(1, patch_size, patch_size))
15
+
16
+ def forward(self, hidden_states):
17
+ hidden_states = self.proj(hidden_states)
18
+ hidden_states = rearrange(hidden_states, "B C T H W -> B (T H W) C")
19
+ return hidden_states
20
+
21
+
22
+
23
+ class CogAdaLayerNorm(torch.nn.Module):
24
+ def __init__(self, dim, dim_cond, single=False):
25
+ super().__init__()
26
+ self.single = single
27
+ self.linear = torch.nn.Linear(dim_cond, dim * (2 if single else 6))
28
+ self.norm = torch.nn.LayerNorm(dim, elementwise_affine=True, eps=1e-5)
29
+
30
+
31
+ def forward(self, hidden_states, prompt_emb, emb):
32
+ emb = self.linear(torch.nn.functional.silu(emb))
33
+ if self.single:
34
+ shift, scale = emb.unsqueeze(1).chunk(2, dim=2)
35
+ hidden_states = self.norm(hidden_states) * (1 + scale) + shift
36
+ return hidden_states
37
+ else:
38
+ shift_a, scale_a, gate_a, shift_b, scale_b, gate_b = emb.unsqueeze(1).chunk(6, dim=2)
39
+ hidden_states = self.norm(hidden_states) * (1 + scale_a) + shift_a
40
+ prompt_emb = self.norm(prompt_emb) * (1 + scale_b) + shift_b
41
+ return hidden_states, prompt_emb, gate_a, gate_b
42
+
43
+
44
+
45
+ class CogDiTBlock(torch.nn.Module):
46
+ def __init__(self, dim, dim_cond, num_heads):
47
+ super().__init__()
48
+ self.norm1 = CogAdaLayerNorm(dim, dim_cond)
49
+ self.attn1 = Attention(q_dim=dim, num_heads=48, head_dim=dim//num_heads, bias_q=True, bias_kv=True, bias_out=True)
50
+ self.norm_q = torch.nn.LayerNorm((dim//num_heads,), eps=1e-06, elementwise_affine=True)
51
+ self.norm_k = torch.nn.LayerNorm((dim//num_heads,), eps=1e-06, elementwise_affine=True)
52
+
53
+ self.norm2 = CogAdaLayerNorm(dim, dim_cond)
54
+ self.ff = torch.nn.Sequential(
55
+ torch.nn.Linear(dim, dim*4),
56
+ torch.nn.GELU(approximate="tanh"),
57
+ torch.nn.Linear(dim*4, dim)
58
+ )
59
+
60
+
61
+ def apply_rotary_emb(self, x, freqs_cis):
62
+ cos, sin = freqs_cis # [S, D]
63
+ cos = cos[None, None]
64
+ sin = sin[None, None]
65
+ cos, sin = cos.to(x.device), sin.to(x.device)
66
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
67
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
68
+ out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
69
+ return out
70
+
71
+
72
+ def process_qkv(self, q, k, v, image_rotary_emb, text_seq_length):
73
+ q = self.norm_q(q)
74
+ k = self.norm_k(k)
75
+ q[:, :, text_seq_length:] = self.apply_rotary_emb(q[:, :, text_seq_length:], image_rotary_emb)
76
+ k[:, :, text_seq_length:] = self.apply_rotary_emb(k[:, :, text_seq_length:], image_rotary_emb)
77
+ return q, k, v
78
+
79
+
80
+ def forward(self, hidden_states, prompt_emb, time_emb, image_rotary_emb):
81
+ # Attention
82
+ norm_hidden_states, norm_encoder_hidden_states, gate_a, gate_b = self.norm1(
83
+ hidden_states, prompt_emb, time_emb
84
+ )
85
+ attention_io = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
86
+ attention_io = self.attn1(
87
+ attention_io,
88
+ qkv_preprocessor=lambda q, k, v: self.process_qkv(q, k, v, image_rotary_emb, prompt_emb.shape[1])
89
+ )
90
+
91
+ hidden_states = hidden_states + gate_a * attention_io[:, prompt_emb.shape[1]:]
92
+ prompt_emb = prompt_emb + gate_b * attention_io[:, :prompt_emb.shape[1]]
93
+
94
+ # Feed forward
95
+ norm_hidden_states, norm_encoder_hidden_states, gate_a, gate_b = self.norm2(
96
+ hidden_states, prompt_emb, time_emb
97
+ )
98
+ ff_io = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
99
+ ff_io = self.ff(ff_io)
100
+
101
+ hidden_states = hidden_states + gate_a * ff_io[:, prompt_emb.shape[1]:]
102
+ prompt_emb = prompt_emb + gate_b * ff_io[:, :prompt_emb.shape[1]]
103
+
104
+ return hidden_states, prompt_emb
105
+
106
+
107
+
108
+ class CogDiT(torch.nn.Module):
109
+ def __init__(self):
110
+ super().__init__()
111
+ self.patchify = CogPatchify(16, 3072, 2)
112
+ self.time_embedder = TimestepEmbeddings(3072, 512)
113
+ self.context_embedder = torch.nn.Linear(4096, 3072)
114
+ self.blocks = torch.nn.ModuleList([CogDiTBlock(3072, 512, 48) for _ in range(42)])
115
+ self.norm_final = torch.nn.LayerNorm((3072,), eps=1e-05, elementwise_affine=True)
116
+ self.norm_out = CogAdaLayerNorm(3072, 512, single=True)
117
+ self.proj_out = torch.nn.Linear(3072, 64, bias=True)
118
+
119
+
120
+ def get_resize_crop_region_for_grid(self, src, tgt_width, tgt_height):
121
+ tw = tgt_width
122
+ th = tgt_height
123
+ h, w = src
124
+ r = h / w
125
+ if r > (th / tw):
126
+ resize_height = th
127
+ resize_width = int(round(th / h * w))
128
+ else:
129
+ resize_width = tw
130
+ resize_height = int(round(tw / w * h))
131
+
132
+ crop_top = int(round((th - resize_height) / 2.0))
133
+ crop_left = int(round((tw - resize_width) / 2.0))
134
+
135
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
136
+
137
+
138
+ def get_3d_rotary_pos_embed(
139
+ self, embed_dim, crops_coords, grid_size, temporal_size, theta: int = 10000, use_real: bool = True
140
+ ):
141
+ start, stop = crops_coords
142
+ grid_h = np.linspace(start[0], stop[0], grid_size[0], endpoint=False, dtype=np.float32)
143
+ grid_w = np.linspace(start[1], stop[1], grid_size[1], endpoint=False, dtype=np.float32)
144
+ grid_t = np.linspace(0, temporal_size, temporal_size, endpoint=False, dtype=np.float32)
145
+
146
+ # Compute dimensions for each axis
147
+ dim_t = embed_dim // 4
148
+ dim_h = embed_dim // 8 * 3
149
+ dim_w = embed_dim // 8 * 3
150
+
151
+ # Temporal frequencies
152
+ freqs_t = 1.0 / (theta ** (torch.arange(0, dim_t, 2).float() / dim_t))
153
+ grid_t = torch.from_numpy(grid_t).float()
154
+ freqs_t = torch.einsum("n , f -> n f", grid_t, freqs_t)
155
+ freqs_t = freqs_t.repeat_interleave(2, dim=-1)
156
+
157
+ # Spatial frequencies for height and width
158
+ freqs_h = 1.0 / (theta ** (torch.arange(0, dim_h, 2).float() / dim_h))
159
+ freqs_w = 1.0 / (theta ** (torch.arange(0, dim_w, 2).float() / dim_w))
160
+ grid_h = torch.from_numpy(grid_h).float()
161
+ grid_w = torch.from_numpy(grid_w).float()
162
+ freqs_h = torch.einsum("n , f -> n f", grid_h, freqs_h)
163
+ freqs_w = torch.einsum("n , f -> n f", grid_w, freqs_w)
164
+ freqs_h = freqs_h.repeat_interleave(2, dim=-1)
165
+ freqs_w = freqs_w.repeat_interleave(2, dim=-1)
166
+
167
+ # Broadcast and concatenate tensors along specified dimension
168
+ def broadcast(tensors, dim=-1):
169
+ num_tensors = len(tensors)
170
+ shape_lens = {len(t.shape) for t in tensors}
171
+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
172
+ shape_len = list(shape_lens)[0]
173
+ dim = (dim + shape_len) if dim < 0 else dim
174
+ dims = list(zip(*(list(t.shape) for t in tensors)))
175
+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
176
+ assert all(
177
+ [*(len(set(t[1])) <= 2 for t in expandable_dims)]
178
+ ), "invalid dimensions for broadcastable concatenation"
179
+ max_dims = [(t[0], max(t[1])) for t in expandable_dims]
180
+ expanded_dims = [(t[0], (t[1],) * num_tensors) for t in max_dims]
181
+ expanded_dims.insert(dim, (dim, dims[dim]))
182
+ expandable_shapes = list(zip(*(t[1] for t in expanded_dims)))
183
+ tensors = [t[0].expand(*t[1]) for t in zip(tensors, expandable_shapes)]
184
+ return torch.cat(tensors, dim=dim)
185
+
186
+ freqs = broadcast((freqs_t[:, None, None, :], freqs_h[None, :, None, :], freqs_w[None, None, :, :]), dim=-1)
187
+
188
+ t, h, w, d = freqs.shape
189
+ freqs = freqs.view(t * h * w, d)
190
+
191
+ # Generate sine and cosine components
192
+ sin = freqs.sin()
193
+ cos = freqs.cos()
194
+
195
+ if use_real:
196
+ return cos, sin
197
+ else:
198
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
199
+ return freqs_cis
200
+
201
+
202
+ def prepare_rotary_positional_embeddings(
203
+ self,
204
+ height: int,
205
+ width: int,
206
+ num_frames: int,
207
+ device: torch.device,
208
+ ):
209
+ grid_height = height // 2
210
+ grid_width = width // 2
211
+ base_size_width = 720 // (8 * 2)
212
+ base_size_height = 480 // (8 * 2)
213
+
214
+ grid_crops_coords = self.get_resize_crop_region_for_grid(
215
+ (grid_height, grid_width), base_size_width, base_size_height
216
+ )
217
+ freqs_cos, freqs_sin = self.get_3d_rotary_pos_embed(
218
+ embed_dim=64,
219
+ crops_coords=grid_crops_coords,
220
+ grid_size=(grid_height, grid_width),
221
+ temporal_size=num_frames,
222
+ use_real=True,
223
+ )
224
+
225
+ freqs_cos = freqs_cos.to(device=device)
226
+ freqs_sin = freqs_sin.to(device=device)
227
+ return freqs_cos, freqs_sin
228
+
229
+
230
+ def unpatchify(self, hidden_states, height, width):
231
+ hidden_states = rearrange(hidden_states, "B (T H W) (C P Q) -> B C T (H P) (W Q)", P=2, Q=2, H=height//2, W=width//2)
232
+ return hidden_states
233
+
234
+
235
+ def build_mask(self, T, H, W, dtype, device, is_bound):
236
+ t = repeat(torch.arange(T), "T -> T H W", T=T, H=H, W=W)
237
+ h = repeat(torch.arange(H), "H -> T H W", T=T, H=H, W=W)
238
+ w = repeat(torch.arange(W), "W -> T H W", T=T, H=H, W=W)
239
+ border_width = (H + W) // 4
240
+ pad = torch.ones_like(h) * border_width
241
+ mask = torch.stack([
242
+ pad if is_bound[0] else t + 1,
243
+ pad if is_bound[1] else T - t,
244
+ pad if is_bound[2] else h + 1,
245
+ pad if is_bound[3] else H - h,
246
+ pad if is_bound[4] else w + 1,
247
+ pad if is_bound[5] else W - w
248
+ ]).min(dim=0).values
249
+ mask = mask.clip(1, border_width)
250
+ mask = (mask / border_width).to(dtype=dtype, device=device)
251
+ mask = rearrange(mask, "T H W -> 1 1 T H W")
252
+ return mask
253
+
254
+
255
+ def tiled_forward(self, hidden_states, timestep, prompt_emb, tile_size=(60, 90), tile_stride=(30, 45)):
256
+ B, C, T, H, W = hidden_states.shape
257
+ value = torch.zeros((B, C, T, H, W), dtype=hidden_states.dtype, device=hidden_states.device)
258
+ weight = torch.zeros((B, C, T, H, W), dtype=hidden_states.dtype, device=hidden_states.device)
259
+
260
+ # Split tasks
261
+ tasks = []
262
+ for h in range(0, H, tile_stride):
263
+ for w in range(0, W, tile_stride):
264
+ if (h-tile_stride >= 0 and h-tile_stride+tile_size >= H) or (w-tile_stride >= 0 and w-tile_stride+tile_size >= W):
265
+ continue
266
+ h_, w_ = h + tile_size, w + tile_size
267
+ if h_ > H: h, h_ = max(H - tile_size, 0), H
268
+ if w_ > W: w, w_ = max(W - tile_size, 0), W
269
+ tasks.append((h, h_, w, w_))
270
+
271
+ # Run
272
+ for hl, hr, wl, wr in tasks:
273
+ mask = self.build_mask(
274
+ value.shape[2], (hr-hl), (wr-wl),
275
+ hidden_states.dtype, hidden_states.device,
276
+ is_bound=(True, True, hl==0, hr>=H, wl==0, wr>=W)
277
+ )
278
+ model_output = self.forward(hidden_states[:, :, :, hl:hr, wl:wr], timestep, prompt_emb)
279
+ value[:, :, :, hl:hr, wl:wr] += model_output * mask
280
+ weight[:, :, :, hl:hr, wl:wr] += mask
281
+ value = value / weight
282
+
283
+ return value
284
+
285
+
286
+ def forward(self, hidden_states, timestep, prompt_emb, image_rotary_emb=None, tiled=False, tile_size=90, tile_stride=30, use_gradient_checkpointing=False):
287
+ if tiled:
288
+ return TileWorker2Dto3D().tiled_forward(
289
+ forward_fn=lambda x: self.forward(x, timestep, prompt_emb),
290
+ model_input=hidden_states,
291
+ tile_size=tile_size, tile_stride=tile_stride,
292
+ tile_device=hidden_states.device, tile_dtype=hidden_states.dtype,
293
+ computation_device=self.context_embedder.weight.device, computation_dtype=self.context_embedder.weight.dtype
294
+ )
295
+ num_frames, height, width = hidden_states.shape[-3:]
296
+ if image_rotary_emb is None:
297
+ image_rotary_emb = self.prepare_rotary_positional_embeddings(height, width, num_frames, device=self.context_embedder.weight.device)
298
+ hidden_states = self.patchify(hidden_states)
299
+ time_emb = self.time_embedder(timestep, dtype=hidden_states.dtype)
300
+ prompt_emb = self.context_embedder(prompt_emb)
301
+
302
+ def create_custom_forward(module):
303
+ def custom_forward(*inputs):
304
+ return module(*inputs)
305
+ return custom_forward
306
+
307
+ for block in self.blocks:
308
+ if self.training and use_gradient_checkpointing:
309
+ hidden_states, prompt_emb = torch.utils.checkpoint.checkpoint(
310
+ create_custom_forward(block),
311
+ hidden_states, prompt_emb, time_emb, image_rotary_emb,
312
+ use_reentrant=False,
313
+ )
314
+ else:
315
+ hidden_states, prompt_emb = block(hidden_states, prompt_emb, time_emb, image_rotary_emb)
316
+
317
+ hidden_states = torch.cat([prompt_emb, hidden_states], dim=1)
318
+ hidden_states = self.norm_final(hidden_states)
319
+ hidden_states = hidden_states[:, prompt_emb.shape[1]:]
320
+ hidden_states = self.norm_out(hidden_states, prompt_emb, time_emb)
321
+ hidden_states = self.proj_out(hidden_states)
322
+ hidden_states = self.unpatchify(hidden_states, height, width)
323
+
324
+ return hidden_states
325
+
326
+
327
+ @staticmethod
328
+ def state_dict_converter():
329
+ return CogDiTStateDictConverter()
330
+
331
+
332
+ @staticmethod
333
+ def from_pretrained(file_path, torch_dtype=torch.bfloat16):
334
+ model = CogDiT().to(torch_dtype)
335
+ state_dict = load_state_dict_from_folder(file_path, torch_dtype=torch_dtype)
336
+ state_dict = CogDiT.state_dict_converter().from_diffusers(state_dict)
337
+ model.load_state_dict(state_dict)
338
+ return model
339
+
340
+
341
+
342
+ class CogDiTStateDictConverter:
343
+ def __init__(self):
344
+ pass
345
+
346
+
347
+ def from_diffusers(self, state_dict):
348
+ rename_dict = {
349
+ "patch_embed.proj.weight": "patchify.proj.weight",
350
+ "patch_embed.proj.bias": "patchify.proj.bias",
351
+ "patch_embed.text_proj.weight": "context_embedder.weight",
352
+ "patch_embed.text_proj.bias": "context_embedder.bias",
353
+ "time_embedding.linear_1.weight": "time_embedder.timestep_embedder.0.weight",
354
+ "time_embedding.linear_1.bias": "time_embedder.timestep_embedder.0.bias",
355
+ "time_embedding.linear_2.weight": "time_embedder.timestep_embedder.2.weight",
356
+ "time_embedding.linear_2.bias": "time_embedder.timestep_embedder.2.bias",
357
+
358
+ "norm_final.weight": "norm_final.weight",
359
+ "norm_final.bias": "norm_final.bias",
360
+ "norm_out.linear.weight": "norm_out.linear.weight",
361
+ "norm_out.linear.bias": "norm_out.linear.bias",
362
+ "norm_out.norm.weight": "norm_out.norm.weight",
363
+ "norm_out.norm.bias": "norm_out.norm.bias",
364
+ "proj_out.weight": "proj_out.weight",
365
+ "proj_out.bias": "proj_out.bias",
366
+ }
367
+ suffix_dict = {
368
+ "norm1.linear.weight": "norm1.linear.weight",
369
+ "norm1.linear.bias": "norm1.linear.bias",
370
+ "norm1.norm.weight": "norm1.norm.weight",
371
+ "norm1.norm.bias": "norm1.norm.bias",
372
+ "attn1.norm_q.weight": "norm_q.weight",
373
+ "attn1.norm_q.bias": "norm_q.bias",
374
+ "attn1.norm_k.weight": "norm_k.weight",
375
+ "attn1.norm_k.bias": "norm_k.bias",
376
+ "attn1.to_q.weight": "attn1.to_q.weight",
377
+ "attn1.to_q.bias": "attn1.to_q.bias",
378
+ "attn1.to_k.weight": "attn1.to_k.weight",
379
+ "attn1.to_k.bias": "attn1.to_k.bias",
380
+ "attn1.to_v.weight": "attn1.to_v.weight",
381
+ "attn1.to_v.bias": "attn1.to_v.bias",
382
+ "attn1.to_out.0.weight": "attn1.to_out.weight",
383
+ "attn1.to_out.0.bias": "attn1.to_out.bias",
384
+ "norm2.linear.weight": "norm2.linear.weight",
385
+ "norm2.linear.bias": "norm2.linear.bias",
386
+ "norm2.norm.weight": "norm2.norm.weight",
387
+ "norm2.norm.bias": "norm2.norm.bias",
388
+ "ff.net.0.proj.weight": "ff.0.weight",
389
+ "ff.net.0.proj.bias": "ff.0.bias",
390
+ "ff.net.2.weight": "ff.2.weight",
391
+ "ff.net.2.bias": "ff.2.bias",
392
+ }
393
+ state_dict_ = {}
394
+ for name, param in state_dict.items():
395
+ if name in rename_dict:
396
+ if name == "patch_embed.proj.weight":
397
+ param = param.unsqueeze(2)
398
+ state_dict_[rename_dict[name]] = param
399
+ else:
400
+ names = name.split(".")
401
+ if names[0] == "transformer_blocks":
402
+ suffix = ".".join(names[2:])
403
+ state_dict_[f"blocks.{names[1]}." + suffix_dict[suffix]] = param
404
+ return state_dict_
405
+
406
+
407
+ def from_civitai(self, state_dict):
408
+ return self.from_diffusers(state_dict)
cog_vae.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange, repeat
3
+ from .tiler import TileWorker2Dto3D
4
+
5
+
6
+
7
+ class Downsample3D(torch.nn.Module):
8
+ def __init__(
9
+ self,
10
+ in_channels: int,
11
+ out_channels: int,
12
+ kernel_size: int = 3,
13
+ stride: int = 2,
14
+ padding: int = 0,
15
+ compress_time: bool = False,
16
+ ):
17
+ super().__init__()
18
+
19
+ self.conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
20
+ self.compress_time = compress_time
21
+
22
+ def forward(self, x: torch.Tensor, xq: torch.Tensor) -> torch.Tensor:
23
+ if self.compress_time:
24
+ batch_size, channels, frames, height, width = x.shape
25
+
26
+ # (batch_size, channels, frames, height, width) -> (batch_size, height, width, channels, frames) -> (batch_size * height * width, channels, frames)
27
+ x = x.permute(0, 3, 4, 1, 2).reshape(batch_size * height * width, channels, frames)
28
+
29
+ if x.shape[-1] % 2 == 1:
30
+ x_first, x_rest = x[..., 0], x[..., 1:]
31
+ if x_rest.shape[-1] > 0:
32
+ # (batch_size * height * width, channels, frames - 1) -> (batch_size * height * width, channels, (frames - 1) // 2)
33
+ x_rest = torch.nn.functional.avg_pool1d(x_rest, kernel_size=2, stride=2)
34
+
35
+ x = torch.cat([x_first[..., None], x_rest], dim=-1)
36
+ # (batch_size * height * width, channels, (frames // 2) + 1) -> (batch_size, height, width, channels, (frames // 2) + 1) -> (batch_size, channels, (frames // 2) + 1, height, width)
37
+ x = x.reshape(batch_size, height, width, channels, x.shape[-1]).permute(0, 3, 4, 1, 2)
38
+ else:
39
+ # (batch_size * height * width, channels, frames) -> (batch_size * height * width, channels, frames // 2)
40
+ x = torch.nn.functional.avg_pool1d(x, kernel_size=2, stride=2)
41
+ # (batch_size * height * width, channels, frames // 2) -> (batch_size, height, width, channels, frames // 2) -> (batch_size, channels, frames // 2, height, width)
42
+ x = x.reshape(batch_size, height, width, channels, x.shape[-1]).permute(0, 3, 4, 1, 2)
43
+
44
+ # Pad the tensor
45
+ pad = (0, 1, 0, 1)
46
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
47
+ batch_size, channels, frames, height, width = x.shape
48
+ # (batch_size, channels, frames, height, width) -> (batch_size, frames, channels, height, width) -> (batch_size * frames, channels, height, width)
49
+ x = x.permute(0, 2, 1, 3, 4).reshape(batch_size * frames, channels, height, width)
50
+ x = self.conv(x)
51
+ # (batch_size * frames, channels, height, width) -> (batch_size, frames, channels, height, width) -> (batch_size, channels, frames, height, width)
52
+ x = x.reshape(batch_size, frames, x.shape[1], x.shape[2], x.shape[3]).permute(0, 2, 1, 3, 4)
53
+ return x
54
+
55
+
56
+
57
+ class Upsample3D(torch.nn.Module):
58
+ def __init__(
59
+ self,
60
+ in_channels: int,
61
+ out_channels: int,
62
+ kernel_size: int = 3,
63
+ stride: int = 1,
64
+ padding: int = 1,
65
+ compress_time: bool = False,
66
+ ) -> None:
67
+ super().__init__()
68
+ self.conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
69
+ self.compress_time = compress_time
70
+
71
+ def forward(self, inputs: torch.Tensor, xq: torch.Tensor) -> torch.Tensor:
72
+ if self.compress_time:
73
+ if inputs.shape[2] > 1 and inputs.shape[2] % 2 == 1:
74
+ # split first frame
75
+ x_first, x_rest = inputs[:, :, 0], inputs[:, :, 1:]
76
+
77
+ x_first = torch.nn.functional.interpolate(x_first, scale_factor=2.0)
78
+ x_rest = torch.nn.functional.interpolate(x_rest, scale_factor=2.0)
79
+ x_first = x_first[:, :, None, :, :]
80
+ inputs = torch.cat([x_first, x_rest], dim=2)
81
+ elif inputs.shape[2] > 1:
82
+ inputs = torch.nn.functional.interpolate(inputs, scale_factor=2.0)
83
+ else:
84
+ inputs = inputs.squeeze(2)
85
+ inputs = torch.nn.functional.interpolate(inputs, scale_factor=2.0)
86
+ inputs = inputs[:, :, None, :, :]
87
+ else:
88
+ # only interpolate 2D
89
+ b, c, t, h, w = inputs.shape
90
+ inputs = inputs.permute(0, 2, 1, 3, 4).reshape(b * t, c, h, w)
91
+ inputs = torch.nn.functional.interpolate(inputs, scale_factor=2.0)
92
+ inputs = inputs.reshape(b, t, c, *inputs.shape[2:]).permute(0, 2, 1, 3, 4)
93
+
94
+ b, c, t, h, w = inputs.shape
95
+ inputs = inputs.permute(0, 2, 1, 3, 4).reshape(b * t, c, h, w)
96
+ inputs = self.conv(inputs)
97
+ inputs = inputs.reshape(b, t, *inputs.shape[1:]).permute(0, 2, 1, 3, 4)
98
+
99
+ return inputs
100
+
101
+
102
+
103
+ class CogVideoXSpatialNorm3D(torch.nn.Module):
104
+ def __init__(self, f_channels, zq_channels, groups):
105
+ super().__init__()
106
+ self.norm_layer = torch.nn.GroupNorm(num_channels=f_channels, num_groups=groups, eps=1e-6, affine=True)
107
+ self.conv_y = torch.nn.Conv3d(zq_channels, f_channels, kernel_size=1, stride=1)
108
+ self.conv_b = torch.nn.Conv3d(zq_channels, f_channels, kernel_size=1, stride=1)
109
+
110
+
111
+ def forward(self, f: torch.Tensor, zq: torch.Tensor) -> torch.Tensor:
112
+ if f.shape[2] > 1 and f.shape[2] % 2 == 1:
113
+ f_first, f_rest = f[:, :, :1], f[:, :, 1:]
114
+ f_first_size, f_rest_size = f_first.shape[-3:], f_rest.shape[-3:]
115
+ z_first, z_rest = zq[:, :, :1], zq[:, :, 1:]
116
+ z_first = torch.nn.functional.interpolate(z_first, size=f_first_size)
117
+ z_rest = torch.nn.functional.interpolate(z_rest, size=f_rest_size)
118
+ zq = torch.cat([z_first, z_rest], dim=2)
119
+ else:
120
+ zq = torch.nn.functional.interpolate(zq, size=f.shape[-3:])
121
+
122
+ norm_f = self.norm_layer(f)
123
+ new_f = norm_f * self.conv_y(zq) + self.conv_b(zq)
124
+ return new_f
125
+
126
+
127
+
128
+ class Resnet3DBlock(torch.nn.Module):
129
+ def __init__(self, in_channels, out_channels, spatial_norm_dim, groups, eps=1e-6, use_conv_shortcut=False):
130
+ super().__init__()
131
+ self.nonlinearity = torch.nn.SiLU()
132
+ if spatial_norm_dim is None:
133
+ self.norm1 = torch.nn.GroupNorm(num_channels=in_channels, num_groups=groups, eps=eps)
134
+ self.norm2 = torch.nn.GroupNorm(num_channels=out_channels, num_groups=groups, eps=eps)
135
+ else:
136
+ self.norm1 = CogVideoXSpatialNorm3D(in_channels, spatial_norm_dim, groups)
137
+ self.norm2 = CogVideoXSpatialNorm3D(out_channels, spatial_norm_dim, groups)
138
+
139
+ self.conv1 = CachedConv3d(in_channels, out_channels, kernel_size=3, padding=(0, 1, 1))
140
+
141
+ self.conv2 = CachedConv3d(out_channels, out_channels, kernel_size=3, padding=(0, 1, 1))
142
+
143
+ if in_channels != out_channels:
144
+ if use_conv_shortcut:
145
+ self.conv_shortcut = CachedConv3d(in_channels, out_channels, kernel_size=3, padding=(0, 1, 1))
146
+ else:
147
+ self.conv_shortcut = torch.nn.Conv3d(in_channels, out_channels, kernel_size=1)
148
+ else:
149
+ self.conv_shortcut = lambda x: x
150
+
151
+
152
+ def forward(self, hidden_states, zq):
153
+ residual = hidden_states
154
+
155
+ hidden_states = self.norm1(hidden_states, zq) if isinstance(self.norm1, CogVideoXSpatialNorm3D) else self.norm1(hidden_states)
156
+ hidden_states = self.nonlinearity(hidden_states)
157
+ hidden_states = self.conv1(hidden_states)
158
+
159
+ hidden_states = self.norm2(hidden_states, zq) if isinstance(self.norm2, CogVideoXSpatialNorm3D) else self.norm2(hidden_states)
160
+ hidden_states = self.nonlinearity(hidden_states)
161
+ hidden_states = self.conv2(hidden_states)
162
+
163
+ hidden_states = hidden_states + self.conv_shortcut(residual)
164
+
165
+ return hidden_states
166
+
167
+
168
+
169
+ class CachedConv3d(torch.nn.Conv3d):
170
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):
171
+ super().__init__(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
172
+ self.cached_tensor = None
173
+
174
+
175
+ def clear_cache(self):
176
+ self.cached_tensor = None
177
+
178
+
179
+ def forward(self, input: torch.Tensor, use_cache = True) -> torch.Tensor:
180
+ if use_cache:
181
+ if self.cached_tensor is None:
182
+ self.cached_tensor = torch.concat([input[:, :, :1]] * 2, dim=2)
183
+ input = torch.concat([self.cached_tensor, input], dim=2)
184
+ self.cached_tensor = input[:, :, -2:]
185
+ return super().forward(input)
186
+
187
+
188
+
189
+ class CogVAEDecoder(torch.nn.Module):
190
+ def __init__(self):
191
+ super().__init__()
192
+ self.scaling_factor = 0.7
193
+ self.conv_in = CachedConv3d(16, 512, kernel_size=3, stride=1, padding=(0, 1, 1))
194
+
195
+ self.blocks = torch.nn.ModuleList([
196
+ Resnet3DBlock(512, 512, 16, 32),
197
+ Resnet3DBlock(512, 512, 16, 32),
198
+ Resnet3DBlock(512, 512, 16, 32),
199
+ Resnet3DBlock(512, 512, 16, 32),
200
+ Resnet3DBlock(512, 512, 16, 32),
201
+ Resnet3DBlock(512, 512, 16, 32),
202
+ Upsample3D(512, 512, compress_time=True),
203
+ Resnet3DBlock(512, 256, 16, 32),
204
+ Resnet3DBlock(256, 256, 16, 32),
205
+ Resnet3DBlock(256, 256, 16, 32),
206
+ Resnet3DBlock(256, 256, 16, 32),
207
+ Upsample3D(256, 256, compress_time=True),
208
+ Resnet3DBlock(256, 256, 16, 32),
209
+ Resnet3DBlock(256, 256, 16, 32),
210
+ Resnet3DBlock(256, 256, 16, 32),
211
+ Resnet3DBlock(256, 256, 16, 32),
212
+ Upsample3D(256, 256, compress_time=False),
213
+ Resnet3DBlock(256, 128, 16, 32),
214
+ Resnet3DBlock(128, 128, 16, 32),
215
+ Resnet3DBlock(128, 128, 16, 32),
216
+ Resnet3DBlock(128, 128, 16, 32),
217
+ ])
218
+
219
+ self.norm_out = CogVideoXSpatialNorm3D(128, 16, 32)
220
+ self.conv_act = torch.nn.SiLU()
221
+ self.conv_out = CachedConv3d(128, 3, kernel_size=3, stride=1, padding=(0, 1, 1))
222
+
223
+
224
+ def forward(self, sample):
225
+ sample = sample / self.scaling_factor
226
+ hidden_states = self.conv_in(sample)
227
+
228
+ for block in self.blocks:
229
+ hidden_states = block(hidden_states, sample)
230
+
231
+ hidden_states = self.norm_out(hidden_states, sample)
232
+ hidden_states = self.conv_act(hidden_states)
233
+ hidden_states = self.conv_out(hidden_states)
234
+
235
+ return hidden_states
236
+
237
+
238
+ def decode_video(self, sample, tiled=True, tile_size=(60, 90), tile_stride=(30, 45), progress_bar=lambda x:x):
239
+ if tiled:
240
+ B, C, T, H, W = sample.shape
241
+ return TileWorker2Dto3D().tiled_forward(
242
+ forward_fn=lambda x: self.decode_small_video(x),
243
+ model_input=sample,
244
+ tile_size=tile_size, tile_stride=tile_stride,
245
+ tile_device=sample.device, tile_dtype=sample.dtype,
246
+ computation_device=sample.device, computation_dtype=sample.dtype,
247
+ scales=(3/16, (T//2*8+T%2)/T, 8, 8),
248
+ progress_bar=progress_bar
249
+ )
250
+ else:
251
+ return self.decode_small_video(sample)
252
+
253
+
254
+ def decode_small_video(self, sample):
255
+ B, C, T, H, W = sample.shape
256
+ computation_device = self.conv_in.weight.device
257
+ computation_dtype = self.conv_in.weight.dtype
258
+ value = []
259
+ for i in range(T//2):
260
+ tl = i*2 + T%2 - (T%2 and i==0)
261
+ tr = i*2 + 2 + T%2
262
+ model_input = sample[:, :, tl: tr, :, :].to(dtype=computation_dtype, device=computation_device)
263
+ model_output = self.forward(model_input).to(dtype=sample.dtype, device=sample.device)
264
+ value.append(model_output)
265
+ value = torch.concat(value, dim=2)
266
+ for name, module in self.named_modules():
267
+ if isinstance(module, CachedConv3d):
268
+ module.clear_cache()
269
+ return value
270
+
271
+
272
+ @staticmethod
273
+ def state_dict_converter():
274
+ return CogVAEDecoderStateDictConverter()
275
+
276
+
277
+
278
+ class CogVAEEncoder(torch.nn.Module):
279
+ def __init__(self):
280
+ super().__init__()
281
+ self.scaling_factor = 0.7
282
+ self.conv_in = CachedConv3d(3, 128, kernel_size=3, stride=1, padding=(0, 1, 1))
283
+
284
+ self.blocks = torch.nn.ModuleList([
285
+ Resnet3DBlock(128, 128, None, 32),
286
+ Resnet3DBlock(128, 128, None, 32),
287
+ Resnet3DBlock(128, 128, None, 32),
288
+ Downsample3D(128, 128, compress_time=True),
289
+ Resnet3DBlock(128, 256, None, 32),
290
+ Resnet3DBlock(256, 256, None, 32),
291
+ Resnet3DBlock(256, 256, None, 32),
292
+ Downsample3D(256, 256, compress_time=True),
293
+ Resnet3DBlock(256, 256, None, 32),
294
+ Resnet3DBlock(256, 256, None, 32),
295
+ Resnet3DBlock(256, 256, None, 32),
296
+ Downsample3D(256, 256, compress_time=False),
297
+ Resnet3DBlock(256, 512, None, 32),
298
+ Resnet3DBlock(512, 512, None, 32),
299
+ Resnet3DBlock(512, 512, None, 32),
300
+ Resnet3DBlock(512, 512, None, 32),
301
+ Resnet3DBlock(512, 512, None, 32),
302
+ ])
303
+
304
+ self.norm_out = torch.nn.GroupNorm(32, 512, eps=1e-06, affine=True)
305
+ self.conv_act = torch.nn.SiLU()
306
+ self.conv_out = CachedConv3d(512, 32, kernel_size=3, stride=1, padding=(0, 1, 1))
307
+
308
+
309
+ def forward(self, sample):
310
+ hidden_states = self.conv_in(sample)
311
+
312
+ for block in self.blocks:
313
+ hidden_states = block(hidden_states, sample)
314
+
315
+ hidden_states = self.norm_out(hidden_states)
316
+ hidden_states = self.conv_act(hidden_states)
317
+ hidden_states = self.conv_out(hidden_states)[:, :16]
318
+ hidden_states = hidden_states * self.scaling_factor
319
+
320
+ return hidden_states
321
+
322
+
323
+ def encode_video(self, sample, tiled=True, tile_size=(60, 90), tile_stride=(30, 45), progress_bar=lambda x:x):
324
+ if tiled:
325
+ B, C, T, H, W = sample.shape
326
+ return TileWorker2Dto3D().tiled_forward(
327
+ forward_fn=lambda x: self.encode_small_video(x),
328
+ model_input=sample,
329
+ tile_size=(i * 8 for i in tile_size), tile_stride=(i * 8 for i in tile_stride),
330
+ tile_device=sample.device, tile_dtype=sample.dtype,
331
+ computation_device=sample.device, computation_dtype=sample.dtype,
332
+ scales=(16/3, (T//4+T%2)/T, 1/8, 1/8),
333
+ progress_bar=progress_bar
334
+ )
335
+ else:
336
+ return self.encode_small_video(sample)
337
+
338
+
339
+ def encode_small_video(self, sample):
340
+ B, C, T, H, W = sample.shape
341
+ computation_device = self.conv_in.weight.device
342
+ computation_dtype = self.conv_in.weight.dtype
343
+ value = []
344
+ for i in range(T//8):
345
+ t = i*8 + T%2 - (T%2 and i==0)
346
+ t_ = i*8 + 8 + T%2
347
+ model_input = sample[:, :, t: t_, :, :].to(dtype=computation_dtype, device=computation_device)
348
+ model_output = self.forward(model_input).to(dtype=sample.dtype, device=sample.device)
349
+ value.append(model_output)
350
+ value = torch.concat(value, dim=2)
351
+ for name, module in self.named_modules():
352
+ if isinstance(module, CachedConv3d):
353
+ module.clear_cache()
354
+ return value
355
+
356
+
357
+ @staticmethod
358
+ def state_dict_converter():
359
+ return CogVAEEncoderStateDictConverter()
360
+
361
+
362
+
363
+ class CogVAEEncoderStateDictConverter:
364
+ def __init__(self):
365
+ pass
366
+
367
+
368
+ def from_diffusers(self, state_dict):
369
+ rename_dict = {
370
+ "encoder.conv_in.conv.weight": "conv_in.weight",
371
+ "encoder.conv_in.conv.bias": "conv_in.bias",
372
+ "encoder.down_blocks.0.downsamplers.0.conv.weight": "blocks.3.conv.weight",
373
+ "encoder.down_blocks.0.downsamplers.0.conv.bias": "blocks.3.conv.bias",
374
+ "encoder.down_blocks.1.downsamplers.0.conv.weight": "blocks.7.conv.weight",
375
+ "encoder.down_blocks.1.downsamplers.0.conv.bias": "blocks.7.conv.bias",
376
+ "encoder.down_blocks.2.downsamplers.0.conv.weight": "blocks.11.conv.weight",
377
+ "encoder.down_blocks.2.downsamplers.0.conv.bias": "blocks.11.conv.bias",
378
+ "encoder.norm_out.weight": "norm_out.weight",
379
+ "encoder.norm_out.bias": "norm_out.bias",
380
+ "encoder.conv_out.conv.weight": "conv_out.weight",
381
+ "encoder.conv_out.conv.bias": "conv_out.bias",
382
+ }
383
+ prefix_dict = {
384
+ "encoder.down_blocks.0.resnets.0.": "blocks.0.",
385
+ "encoder.down_blocks.0.resnets.1.": "blocks.1.",
386
+ "encoder.down_blocks.0.resnets.2.": "blocks.2.",
387
+ "encoder.down_blocks.1.resnets.0.": "blocks.4.",
388
+ "encoder.down_blocks.1.resnets.1.": "blocks.5.",
389
+ "encoder.down_blocks.1.resnets.2.": "blocks.6.",
390
+ "encoder.down_blocks.2.resnets.0.": "blocks.8.",
391
+ "encoder.down_blocks.2.resnets.1.": "blocks.9.",
392
+ "encoder.down_blocks.2.resnets.2.": "blocks.10.",
393
+ "encoder.down_blocks.3.resnets.0.": "blocks.12.",
394
+ "encoder.down_blocks.3.resnets.1.": "blocks.13.",
395
+ "encoder.down_blocks.3.resnets.2.": "blocks.14.",
396
+ "encoder.mid_block.resnets.0.": "blocks.15.",
397
+ "encoder.mid_block.resnets.1.": "blocks.16.",
398
+ }
399
+ suffix_dict = {
400
+ "norm1.norm_layer.weight": "norm1.norm_layer.weight",
401
+ "norm1.norm_layer.bias": "norm1.norm_layer.bias",
402
+ "norm1.conv_y.conv.weight": "norm1.conv_y.weight",
403
+ "norm1.conv_y.conv.bias": "norm1.conv_y.bias",
404
+ "norm1.conv_b.conv.weight": "norm1.conv_b.weight",
405
+ "norm1.conv_b.conv.bias": "norm1.conv_b.bias",
406
+ "norm2.norm_layer.weight": "norm2.norm_layer.weight",
407
+ "norm2.norm_layer.bias": "norm2.norm_layer.bias",
408
+ "norm2.conv_y.conv.weight": "norm2.conv_y.weight",
409
+ "norm2.conv_y.conv.bias": "norm2.conv_y.bias",
410
+ "norm2.conv_b.conv.weight": "norm2.conv_b.weight",
411
+ "norm2.conv_b.conv.bias": "norm2.conv_b.bias",
412
+ "conv1.conv.weight": "conv1.weight",
413
+ "conv1.conv.bias": "conv1.bias",
414
+ "conv2.conv.weight": "conv2.weight",
415
+ "conv2.conv.bias": "conv2.bias",
416
+ "conv_shortcut.weight": "conv_shortcut.weight",
417
+ "conv_shortcut.bias": "conv_shortcut.bias",
418
+ "norm1.weight": "norm1.weight",
419
+ "norm1.bias": "norm1.bias",
420
+ "norm2.weight": "norm2.weight",
421
+ "norm2.bias": "norm2.bias",
422
+ }
423
+ state_dict_ = {}
424
+ for name, param in state_dict.items():
425
+ if name in rename_dict:
426
+ state_dict_[rename_dict[name]] = param
427
+ else:
428
+ for prefix in prefix_dict:
429
+ if name.startswith(prefix):
430
+ suffix = name[len(prefix):]
431
+ state_dict_[prefix_dict[prefix] + suffix_dict[suffix]] = param
432
+ return state_dict_
433
+
434
+
435
+ def from_civitai(self, state_dict):
436
+ return self.from_diffusers(state_dict)
437
+
438
+
439
+
440
+ class CogVAEDecoderStateDictConverter:
441
+ def __init__(self):
442
+ pass
443
+
444
+
445
+ def from_diffusers(self, state_dict):
446
+ rename_dict = {
447
+ "decoder.conv_in.conv.weight": "conv_in.weight",
448
+ "decoder.conv_in.conv.bias": "conv_in.bias",
449
+ "decoder.up_blocks.0.upsamplers.0.conv.weight": "blocks.6.conv.weight",
450
+ "decoder.up_blocks.0.upsamplers.0.conv.bias": "blocks.6.conv.bias",
451
+ "decoder.up_blocks.1.upsamplers.0.conv.weight": "blocks.11.conv.weight",
452
+ "decoder.up_blocks.1.upsamplers.0.conv.bias": "blocks.11.conv.bias",
453
+ "decoder.up_blocks.2.upsamplers.0.conv.weight": "blocks.16.conv.weight",
454
+ "decoder.up_blocks.2.upsamplers.0.conv.bias": "blocks.16.conv.bias",
455
+ "decoder.norm_out.norm_layer.weight": "norm_out.norm_layer.weight",
456
+ "decoder.norm_out.norm_layer.bias": "norm_out.norm_layer.bias",
457
+ "decoder.norm_out.conv_y.conv.weight": "norm_out.conv_y.weight",
458
+ "decoder.norm_out.conv_y.conv.bias": "norm_out.conv_y.bias",
459
+ "decoder.norm_out.conv_b.conv.weight": "norm_out.conv_b.weight",
460
+ "decoder.norm_out.conv_b.conv.bias": "norm_out.conv_b.bias",
461
+ "decoder.conv_out.conv.weight": "conv_out.weight",
462
+ "decoder.conv_out.conv.bias": "conv_out.bias"
463
+ }
464
+ prefix_dict = {
465
+ "decoder.mid_block.resnets.0.": "blocks.0.",
466
+ "decoder.mid_block.resnets.1.": "blocks.1.",
467
+ "decoder.up_blocks.0.resnets.0.": "blocks.2.",
468
+ "decoder.up_blocks.0.resnets.1.": "blocks.3.",
469
+ "decoder.up_blocks.0.resnets.2.": "blocks.4.",
470
+ "decoder.up_blocks.0.resnets.3.": "blocks.5.",
471
+ "decoder.up_blocks.1.resnets.0.": "blocks.7.",
472
+ "decoder.up_blocks.1.resnets.1.": "blocks.8.",
473
+ "decoder.up_blocks.1.resnets.2.": "blocks.9.",
474
+ "decoder.up_blocks.1.resnets.3.": "blocks.10.",
475
+ "decoder.up_blocks.2.resnets.0.": "blocks.12.",
476
+ "decoder.up_blocks.2.resnets.1.": "blocks.13.",
477
+ "decoder.up_blocks.2.resnets.2.": "blocks.14.",
478
+ "decoder.up_blocks.2.resnets.3.": "blocks.15.",
479
+ "decoder.up_blocks.3.resnets.0.": "blocks.17.",
480
+ "decoder.up_blocks.3.resnets.1.": "blocks.18.",
481
+ "decoder.up_blocks.3.resnets.2.": "blocks.19.",
482
+ "decoder.up_blocks.3.resnets.3.": "blocks.20.",
483
+ }
484
+ suffix_dict = {
485
+ "norm1.norm_layer.weight": "norm1.norm_layer.weight",
486
+ "norm1.norm_layer.bias": "norm1.norm_layer.bias",
487
+ "norm1.conv_y.conv.weight": "norm1.conv_y.weight",
488
+ "norm1.conv_y.conv.bias": "norm1.conv_y.bias",
489
+ "norm1.conv_b.conv.weight": "norm1.conv_b.weight",
490
+ "norm1.conv_b.conv.bias": "norm1.conv_b.bias",
491
+ "norm2.norm_layer.weight": "norm2.norm_layer.weight",
492
+ "norm2.norm_layer.bias": "norm2.norm_layer.bias",
493
+ "norm2.conv_y.conv.weight": "norm2.conv_y.weight",
494
+ "norm2.conv_y.conv.bias": "norm2.conv_y.bias",
495
+ "norm2.conv_b.conv.weight": "norm2.conv_b.weight",
496
+ "norm2.conv_b.conv.bias": "norm2.conv_b.bias",
497
+ "conv1.conv.weight": "conv1.weight",
498
+ "conv1.conv.bias": "conv1.bias",
499
+ "conv2.conv.weight": "conv2.weight",
500
+ "conv2.conv.bias": "conv2.bias",
501
+ "conv_shortcut.weight": "conv_shortcut.weight",
502
+ "conv_shortcut.bias": "conv_shortcut.bias",
503
+ }
504
+ state_dict_ = {}
505
+ for name, param in state_dict.items():
506
+ if name in rename_dict:
507
+ state_dict_[rename_dict[name]] = param
508
+ else:
509
+ for prefix in prefix_dict:
510
+ if name.startswith(prefix):
511
+ suffix = name[len(prefix):]
512
+ state_dict_[prefix_dict[prefix] + suffix_dict[suffix]] = param
513
+ return state_dict_
514
+
515
+
516
+ def from_civitai(self, state_dict):
517
+ return self.from_diffusers(state_dict)
518
+
downloader.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download
2
+ from modelscope import snapshot_download
3
+ import os, shutil
4
+ from typing_extensions import Literal, TypeAlias
5
+ from typing import List
6
+ from ..configs.model_config import preset_models_on_huggingface, preset_models_on_modelscope, Preset_model_id
7
+
8
+
9
+ def download_from_modelscope(model_id, origin_file_path, local_dir):
10
+ os.makedirs(local_dir, exist_ok=True)
11
+ file_name = os.path.basename(origin_file_path)
12
+ if file_name in os.listdir(local_dir):
13
+ print(f" {file_name} has been already in {local_dir}.")
14
+ else:
15
+ print(f" Start downloading {os.path.join(local_dir, file_name)}")
16
+ snapshot_download(model_id, allow_file_pattern=origin_file_path, local_dir=local_dir)
17
+ downloaded_file_path = os.path.join(local_dir, origin_file_path)
18
+ target_file_path = os.path.join(local_dir, os.path.split(origin_file_path)[-1])
19
+ if downloaded_file_path != target_file_path:
20
+ shutil.move(downloaded_file_path, target_file_path)
21
+ shutil.rmtree(os.path.join(local_dir, origin_file_path.split("/")[0]))
22
+
23
+
24
+ def download_from_huggingface(model_id, origin_file_path, local_dir):
25
+ os.makedirs(local_dir, exist_ok=True)
26
+ file_name = os.path.basename(origin_file_path)
27
+ if file_name in os.listdir(local_dir):
28
+ print(f" {file_name} has been already in {local_dir}.")
29
+ else:
30
+ print(f" Start downloading {os.path.join(local_dir, file_name)}")
31
+ hf_hub_download(model_id, origin_file_path, local_dir=local_dir)
32
+ downloaded_file_path = os.path.join(local_dir, origin_file_path)
33
+ target_file_path = os.path.join(local_dir, file_name)
34
+ if downloaded_file_path != target_file_path:
35
+ shutil.move(downloaded_file_path, target_file_path)
36
+ shutil.rmtree(os.path.join(local_dir, origin_file_path.split("/")[0]))
37
+
38
+
39
+ Preset_model_website: TypeAlias = Literal[
40
+ "HuggingFace",
41
+ "ModelScope",
42
+ ]
43
+ website_to_preset_models = {
44
+ "HuggingFace": preset_models_on_huggingface,
45
+ "ModelScope": preset_models_on_modelscope,
46
+ }
47
+ website_to_download_fn = {
48
+ "HuggingFace": download_from_huggingface,
49
+ "ModelScope": download_from_modelscope,
50
+ }
51
+
52
+
53
+ def download_customized_models(
54
+ model_id,
55
+ origin_file_path,
56
+ local_dir,
57
+ downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"],
58
+ ):
59
+ downloaded_files = []
60
+ for website in downloading_priority:
61
+ # Check if the file is downloaded.
62
+ file_to_download = os.path.join(local_dir, os.path.basename(origin_file_path))
63
+ if file_to_download in downloaded_files:
64
+ continue
65
+ # Download
66
+ website_to_download_fn[website](model_id, origin_file_path, local_dir)
67
+ if os.path.basename(origin_file_path) in os.listdir(local_dir):
68
+ downloaded_files.append(file_to_download)
69
+ return downloaded_files
70
+
71
+
72
+ def download_models(
73
+ model_id_list: List[Preset_model_id] = [],
74
+ downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"],
75
+ ):
76
+ print(f"Downloading models: {model_id_list}")
77
+ downloaded_files = []
78
+ load_files = []
79
+
80
+ for model_id in model_id_list:
81
+ for website in downloading_priority:
82
+ if model_id in website_to_preset_models[website]:
83
+
84
+ # Parse model metadata
85
+ model_metadata = website_to_preset_models[website][model_id]
86
+ if isinstance(model_metadata, list):
87
+ file_data = model_metadata
88
+ else:
89
+ file_data = model_metadata.get("file_list", [])
90
+
91
+ # Try downloading the model from this website.
92
+ model_files = []
93
+ for model_id, origin_file_path, local_dir in file_data:
94
+ # Check if the file is downloaded.
95
+ file_to_download = os.path.join(local_dir, os.path.basename(origin_file_path))
96
+ if file_to_download in downloaded_files:
97
+ continue
98
+ # Download
99
+ website_to_download_fn[website](model_id, origin_file_path, local_dir)
100
+ if os.path.basename(origin_file_path) in os.listdir(local_dir):
101
+ downloaded_files.append(file_to_download)
102
+ model_files.append(file_to_download)
103
+
104
+ # If the model is successfully downloaded, break.
105
+ if len(model_files) > 0:
106
+ if isinstance(model_metadata, dict) and "load_path" in model_metadata:
107
+ model_files = model_metadata["load_path"]
108
+ load_files.extend(model_files)
109
+ break
110
+
111
+ return load_files
flux_controlnet.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange, repeat
3
+ from .flux_dit import RoPEEmbedding, TimestepEmbeddings, FluxJointTransformerBlock, FluxSingleTransformerBlock, RMSNorm
4
+ from .utils import hash_state_dict_keys, init_weights_on_device
5
+
6
+
7
+
8
+ class FluxControlNet(torch.nn.Module):
9
+ def __init__(self, disable_guidance_embedder=False, num_joint_blocks=5, num_single_blocks=10, num_mode=0, mode_dict={}, additional_input_dim=0):
10
+ super().__init__()
11
+ self.pos_embedder = RoPEEmbedding(3072, 10000, [16, 56, 56])
12
+ self.time_embedder = TimestepEmbeddings(256, 3072)
13
+ self.guidance_embedder = None if disable_guidance_embedder else TimestepEmbeddings(256, 3072)
14
+ self.pooled_text_embedder = torch.nn.Sequential(torch.nn.Linear(768, 3072), torch.nn.SiLU(), torch.nn.Linear(3072, 3072))
15
+ self.context_embedder = torch.nn.Linear(4096, 3072)
16
+ self.x_embedder = torch.nn.Linear(64, 3072)
17
+
18
+ self.blocks = torch.nn.ModuleList([FluxJointTransformerBlock(3072, 24) for _ in range(num_joint_blocks)])
19
+ self.single_blocks = torch.nn.ModuleList([FluxSingleTransformerBlock(3072, 24) for _ in range(num_single_blocks)])
20
+
21
+ self.controlnet_blocks = torch.nn.ModuleList([torch.nn.Linear(3072, 3072) for _ in range(num_joint_blocks)])
22
+ self.controlnet_single_blocks = torch.nn.ModuleList([torch.nn.Linear(3072, 3072) for _ in range(num_single_blocks)])
23
+
24
+ self.mode_dict = mode_dict
25
+ self.controlnet_mode_embedder = torch.nn.Embedding(num_mode, 3072) if len(mode_dict) > 0 else None
26
+ self.controlnet_x_embedder = torch.nn.Linear(64 + additional_input_dim, 3072)
27
+
28
+
29
+ def prepare_image_ids(self, latents):
30
+ batch_size, _, height, width = latents.shape
31
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
32
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
33
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
34
+
35
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
36
+
37
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
38
+ latent_image_ids = latent_image_ids.reshape(
39
+ batch_size, latent_image_id_height * latent_image_id_width, latent_image_id_channels
40
+ )
41
+ latent_image_ids = latent_image_ids.to(device=latents.device, dtype=latents.dtype)
42
+
43
+ return latent_image_ids
44
+
45
+
46
+ def patchify(self, hidden_states):
47
+ hidden_states = rearrange(hidden_states, "B C (H P) (W Q) -> B (H W) (C P Q)", P=2, Q=2)
48
+ return hidden_states
49
+
50
+
51
+ def align_res_stack_to_original_blocks(self, res_stack, num_blocks, hidden_states):
52
+ if len(res_stack) == 0:
53
+ return [torch.zeros_like(hidden_states)] * num_blocks
54
+ interval = (num_blocks + len(res_stack) - 1) // len(res_stack)
55
+ aligned_res_stack = [res_stack[block_id // interval] for block_id in range(num_blocks)]
56
+ return aligned_res_stack
57
+
58
+
59
+ def forward(
60
+ self,
61
+ hidden_states,
62
+ controlnet_conditioning,
63
+ timestep, prompt_emb, pooled_prompt_emb, guidance, text_ids, image_ids=None,
64
+ processor_id=None,
65
+ tiled=False, tile_size=128, tile_stride=64,
66
+ **kwargs
67
+ ):
68
+ if image_ids is None:
69
+ image_ids = self.prepare_image_ids(hidden_states)
70
+
71
+ conditioning = self.time_embedder(timestep, hidden_states.dtype) + self.pooled_text_embedder(pooled_prompt_emb)
72
+ if self.guidance_embedder is not None:
73
+ guidance = guidance * 1000
74
+ conditioning = conditioning + self.guidance_embedder(guidance, hidden_states.dtype)
75
+ prompt_emb = self.context_embedder(prompt_emb)
76
+ if self.controlnet_mode_embedder is not None: # Different from FluxDiT
77
+ processor_id = torch.tensor([self.mode_dict[processor_id]], dtype=torch.int)
78
+ processor_id = repeat(processor_id, "D -> B D", B=1).to(text_ids.device)
79
+ prompt_emb = torch.concat([self.controlnet_mode_embedder(processor_id), prompt_emb], dim=1)
80
+ text_ids = torch.cat([text_ids[:, :1], text_ids], dim=1)
81
+ image_rotary_emb = self.pos_embedder(torch.cat((text_ids, image_ids), dim=1))
82
+
83
+ hidden_states = self.patchify(hidden_states)
84
+ hidden_states = self.x_embedder(hidden_states)
85
+ controlnet_conditioning = self.patchify(controlnet_conditioning) # Different from FluxDiT
86
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_conditioning) # Different from FluxDiT
87
+
88
+ controlnet_res_stack = []
89
+ for block, controlnet_block in zip(self.blocks, self.controlnet_blocks):
90
+ hidden_states, prompt_emb = block(hidden_states, prompt_emb, conditioning, image_rotary_emb)
91
+ controlnet_res_stack.append(controlnet_block(hidden_states))
92
+
93
+ controlnet_single_res_stack = []
94
+ hidden_states = torch.cat([prompt_emb, hidden_states], dim=1)
95
+ for block, controlnet_block in zip(self.single_blocks, self.controlnet_single_blocks):
96
+ hidden_states, prompt_emb = block(hidden_states, prompt_emb, conditioning, image_rotary_emb)
97
+ controlnet_single_res_stack.append(controlnet_block(hidden_states[:, prompt_emb.shape[1]:]))
98
+
99
+ controlnet_res_stack = self.align_res_stack_to_original_blocks(controlnet_res_stack, 19, hidden_states[:, prompt_emb.shape[1]:])
100
+ controlnet_single_res_stack = self.align_res_stack_to_original_blocks(controlnet_single_res_stack, 38, hidden_states[:, prompt_emb.shape[1]:])
101
+
102
+ return controlnet_res_stack, controlnet_single_res_stack
103
+
104
+
105
+ @staticmethod
106
+ def state_dict_converter():
107
+ return FluxControlNetStateDictConverter()
108
+
109
+ def quantize(self):
110
+ def cast_to(weight, dtype=None, device=None, copy=False):
111
+ if device is None or weight.device == device:
112
+ if not copy:
113
+ if dtype is None or weight.dtype == dtype:
114
+ return weight
115
+ return weight.to(dtype=dtype, copy=copy)
116
+
117
+ r = torch.empty_like(weight, dtype=dtype, device=device)
118
+ r.copy_(weight)
119
+ return r
120
+
121
+ def cast_weight(s, input=None, dtype=None, device=None):
122
+ if input is not None:
123
+ if dtype is None:
124
+ dtype = input.dtype
125
+ if device is None:
126
+ device = input.device
127
+ weight = cast_to(s.weight, dtype, device)
128
+ return weight
129
+
130
+ def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None):
131
+ if input is not None:
132
+ if dtype is None:
133
+ dtype = input.dtype
134
+ if bias_dtype is None:
135
+ bias_dtype = dtype
136
+ if device is None:
137
+ device = input.device
138
+ bias = None
139
+ weight = cast_to(s.weight, dtype, device)
140
+ bias = cast_to(s.bias, bias_dtype, device)
141
+ return weight, bias
142
+
143
+ class quantized_layer:
144
+ class QLinear(torch.nn.Linear):
145
+ def __init__(self, *args, **kwargs):
146
+ super().__init__(*args, **kwargs)
147
+
148
+ def forward(self,input,**kwargs):
149
+ weight,bias= cast_bias_weight(self,input)
150
+ return torch.nn.functional.linear(input,weight,bias)
151
+
152
+ class QRMSNorm(torch.nn.Module):
153
+ def __init__(self, module):
154
+ super().__init__()
155
+ self.module = module
156
+
157
+ def forward(self,hidden_states,**kwargs):
158
+ weight= cast_weight(self.module,hidden_states)
159
+ input_dtype = hidden_states.dtype
160
+ variance = hidden_states.to(torch.float32).square().mean(-1, keepdim=True)
161
+ hidden_states = hidden_states * torch.rsqrt(variance + self.module.eps)
162
+ hidden_states = hidden_states.to(input_dtype) * weight
163
+ return hidden_states
164
+
165
+ class QEmbedding(torch.nn.Embedding):
166
+ def __init__(self, *args, **kwargs):
167
+ super().__init__(*args, **kwargs)
168
+
169
+ def forward(self,input,**kwargs):
170
+ weight= cast_weight(self,input)
171
+ return torch.nn.functional.embedding(
172
+ input, weight, self.padding_idx, self.max_norm,
173
+ self.norm_type, self.scale_grad_by_freq, self.sparse)
174
+
175
+ def replace_layer(model):
176
+ for name, module in model.named_children():
177
+ if isinstance(module,quantized_layer.QRMSNorm):
178
+ continue
179
+ if isinstance(module, torch.nn.Linear):
180
+ with init_weights_on_device():
181
+ new_layer = quantized_layer.QLinear(module.in_features,module.out_features)
182
+ new_layer.weight = module.weight
183
+ if module.bias is not None:
184
+ new_layer.bias = module.bias
185
+ setattr(model, name, new_layer)
186
+ elif isinstance(module, RMSNorm):
187
+ if hasattr(module,"quantized"):
188
+ continue
189
+ module.quantized= True
190
+ new_layer = quantized_layer.QRMSNorm(module)
191
+ setattr(model, name, new_layer)
192
+ elif isinstance(module,torch.nn.Embedding):
193
+ rows, cols = module.weight.shape
194
+ new_layer = quantized_layer.QEmbedding(
195
+ num_embeddings=rows,
196
+ embedding_dim=cols,
197
+ _weight=module.weight,
198
+ # _freeze=module.freeze,
199
+ padding_idx=module.padding_idx,
200
+ max_norm=module.max_norm,
201
+ norm_type=module.norm_type,
202
+ scale_grad_by_freq=module.scale_grad_by_freq,
203
+ sparse=module.sparse)
204
+ setattr(model, name, new_layer)
205
+ else:
206
+ replace_layer(module)
207
+
208
+ replace_layer(self)
209
+
210
+
211
+
212
+ class FluxControlNetStateDictConverter:
213
+ def __init__(self):
214
+ pass
215
+
216
+ def from_diffusers(self, state_dict):
217
+ hash_value = hash_state_dict_keys(state_dict)
218
+ global_rename_dict = {
219
+ "context_embedder": "context_embedder",
220
+ "x_embedder": "x_embedder",
221
+ "time_text_embed.timestep_embedder.linear_1": "time_embedder.timestep_embedder.0",
222
+ "time_text_embed.timestep_embedder.linear_2": "time_embedder.timestep_embedder.2",
223
+ "time_text_embed.guidance_embedder.linear_1": "guidance_embedder.timestep_embedder.0",
224
+ "time_text_embed.guidance_embedder.linear_2": "guidance_embedder.timestep_embedder.2",
225
+ "time_text_embed.text_embedder.linear_1": "pooled_text_embedder.0",
226
+ "time_text_embed.text_embedder.linear_2": "pooled_text_embedder.2",
227
+ "norm_out.linear": "final_norm_out.linear",
228
+ "proj_out": "final_proj_out",
229
+ }
230
+ rename_dict = {
231
+ "proj_out": "proj_out",
232
+ "norm1.linear": "norm1_a.linear",
233
+ "norm1_context.linear": "norm1_b.linear",
234
+ "attn.to_q": "attn.a_to_q",
235
+ "attn.to_k": "attn.a_to_k",
236
+ "attn.to_v": "attn.a_to_v",
237
+ "attn.to_out.0": "attn.a_to_out",
238
+ "attn.add_q_proj": "attn.b_to_q",
239
+ "attn.add_k_proj": "attn.b_to_k",
240
+ "attn.add_v_proj": "attn.b_to_v",
241
+ "attn.to_add_out": "attn.b_to_out",
242
+ "ff.net.0.proj": "ff_a.0",
243
+ "ff.net.2": "ff_a.2",
244
+ "ff_context.net.0.proj": "ff_b.0",
245
+ "ff_context.net.2": "ff_b.2",
246
+ "attn.norm_q": "attn.norm_q_a",
247
+ "attn.norm_k": "attn.norm_k_a",
248
+ "attn.norm_added_q": "attn.norm_q_b",
249
+ "attn.norm_added_k": "attn.norm_k_b",
250
+ }
251
+ rename_dict_single = {
252
+ "attn.to_q": "a_to_q",
253
+ "attn.to_k": "a_to_k",
254
+ "attn.to_v": "a_to_v",
255
+ "attn.norm_q": "norm_q_a",
256
+ "attn.norm_k": "norm_k_a",
257
+ "norm.linear": "norm.linear",
258
+ "proj_mlp": "proj_in_besides_attn",
259
+ "proj_out": "proj_out",
260
+ }
261
+ state_dict_ = {}
262
+ for name, param in state_dict.items():
263
+ if name.endswith(".weight") or name.endswith(".bias"):
264
+ suffix = ".weight" if name.endswith(".weight") else ".bias"
265
+ prefix = name[:-len(suffix)]
266
+ if prefix in global_rename_dict:
267
+ state_dict_[global_rename_dict[prefix] + suffix] = param
268
+ elif prefix.startswith("transformer_blocks."):
269
+ names = prefix.split(".")
270
+ names[0] = "blocks"
271
+ middle = ".".join(names[2:])
272
+ if middle in rename_dict:
273
+ name_ = ".".join(names[:2] + [rename_dict[middle]] + [suffix[1:]])
274
+ state_dict_[name_] = param
275
+ elif prefix.startswith("single_transformer_blocks."):
276
+ names = prefix.split(".")
277
+ names[0] = "single_blocks"
278
+ middle = ".".join(names[2:])
279
+ if middle in rename_dict_single:
280
+ name_ = ".".join(names[:2] + [rename_dict_single[middle]] + [suffix[1:]])
281
+ state_dict_[name_] = param
282
+ else:
283
+ state_dict_[name] = param
284
+ else:
285
+ state_dict_[name] = param
286
+ for name in list(state_dict_.keys()):
287
+ if ".proj_in_besides_attn." in name:
288
+ name_ = name.replace(".proj_in_besides_attn.", ".to_qkv_mlp.")
289
+ param = torch.concat([
290
+ state_dict_[name.replace(".proj_in_besides_attn.", f".a_to_q.")],
291
+ state_dict_[name.replace(".proj_in_besides_attn.", f".a_to_k.")],
292
+ state_dict_[name.replace(".proj_in_besides_attn.", f".a_to_v.")],
293
+ state_dict_[name],
294
+ ], dim=0)
295
+ state_dict_[name_] = param
296
+ state_dict_.pop(name.replace(".proj_in_besides_attn.", f".a_to_q."))
297
+ state_dict_.pop(name.replace(".proj_in_besides_attn.", f".a_to_k."))
298
+ state_dict_.pop(name.replace(".proj_in_besides_attn.", f".a_to_v."))
299
+ state_dict_.pop(name)
300
+ for name in list(state_dict_.keys()):
301
+ for component in ["a", "b"]:
302
+ if f".{component}_to_q." in name:
303
+ name_ = name.replace(f".{component}_to_q.", f".{component}_to_qkv.")
304
+ param = torch.concat([
305
+ state_dict_[name.replace(f".{component}_to_q.", f".{component}_to_q.")],
306
+ state_dict_[name.replace(f".{component}_to_q.", f".{component}_to_k.")],
307
+ state_dict_[name.replace(f".{component}_to_q.", f".{component}_to_v.")],
308
+ ], dim=0)
309
+ state_dict_[name_] = param
310
+ state_dict_.pop(name.replace(f".{component}_to_q.", f".{component}_to_q."))
311
+ state_dict_.pop(name.replace(f".{component}_to_q.", f".{component}_to_k."))
312
+ state_dict_.pop(name.replace(f".{component}_to_q.", f".{component}_to_v."))
313
+ if hash_value == "78d18b9101345ff695f312e7e62538c0":
314
+ extra_kwargs = {"num_mode": 10, "mode_dict": {"canny": 0, "tile": 1, "depth": 2, "blur": 3, "pose": 4, "gray": 5, "lq": 6}}
315
+ elif hash_value == "b001c89139b5f053c715fe772362dd2a":
316
+ extra_kwargs = {"num_single_blocks": 0}
317
+ elif hash_value == "52357cb26250681367488a8954c271e8":
318
+ extra_kwargs = {"num_joint_blocks": 6, "num_single_blocks": 0, "additional_input_dim": 4}
319
+ elif hash_value == "0cfd1740758423a2a854d67c136d1e8c":
320
+ extra_kwargs = {"num_joint_blocks": 4, "num_single_blocks": 1}
321
+ elif hash_value == "7f9583eb8ba86642abb9a21a4b2c9e16":
322
+ extra_kwargs = {"num_joint_blocks": 4, "num_single_blocks": 10}
323
+ elif hash_value == "43ad5aaa27dd4ee01b832ed16773fa52":
324
+ extra_kwargs = {"num_joint_blocks": 6, "num_single_blocks": 0}
325
+ else:
326
+ extra_kwargs = {}
327
+ return state_dict_, extra_kwargs
328
+
329
+
330
+ def from_civitai(self, state_dict):
331
+ return self.from_diffusers(state_dict)
flux_dit.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd3_dit import TimestepEmbeddings, AdaLayerNorm, RMSNorm
3
+ from einops import rearrange
4
+ from .tiler import TileWorker
5
+ from .utils import init_weights_on_device
6
+
7
+ def interact_with_ipadapter(hidden_states, q, ip_k, ip_v, scale=1.0):
8
+ batch_size, num_tokens = hidden_states.shape[0:2]
9
+ ip_hidden_states = torch.nn.functional.scaled_dot_product_attention(q, ip_k, ip_v)
10
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, num_tokens, -1)
11
+ hidden_states = hidden_states + scale * ip_hidden_states
12
+ return hidden_states
13
+
14
+
15
+ class RoPEEmbedding(torch.nn.Module):
16
+ def __init__(self, dim, theta, axes_dim):
17
+ super().__init__()
18
+ self.dim = dim
19
+ self.theta = theta
20
+ self.axes_dim = axes_dim
21
+
22
+
23
+ def rope(self, pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
24
+ assert dim % 2 == 0, "The dimension must be even."
25
+
26
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
27
+ omega = 1.0 / (theta**scale)
28
+
29
+ batch_size, seq_length = pos.shape
30
+ out = torch.einsum("...n,d->...nd", pos, omega)
31
+ cos_out = torch.cos(out)
32
+ sin_out = torch.sin(out)
33
+
34
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
35
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
36
+ return out.float()
37
+
38
+
39
+ def forward(self, ids):
40
+ n_axes = ids.shape[-1]
41
+ emb = torch.cat([self.rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)], dim=-3)
42
+ return emb.unsqueeze(1)
43
+
44
+
45
+
46
+ class FluxJointAttention(torch.nn.Module):
47
+ def __init__(self, dim_a, dim_b, num_heads, head_dim, only_out_a=False):
48
+ super().__init__()
49
+ self.num_heads = num_heads
50
+ self.head_dim = head_dim
51
+ self.only_out_a = only_out_a
52
+
53
+ self.a_to_qkv = torch.nn.Linear(dim_a, dim_a * 3)
54
+ self.b_to_qkv = torch.nn.Linear(dim_b, dim_b * 3)
55
+
56
+ self.norm_q_a = RMSNorm(head_dim, eps=1e-6)
57
+ self.norm_k_a = RMSNorm(head_dim, eps=1e-6)
58
+ self.norm_q_b = RMSNorm(head_dim, eps=1e-6)
59
+ self.norm_k_b = RMSNorm(head_dim, eps=1e-6)
60
+
61
+ self.a_to_out = torch.nn.Linear(dim_a, dim_a)
62
+ if not only_out_a:
63
+ self.b_to_out = torch.nn.Linear(dim_b, dim_b)
64
+
65
+
66
+ def apply_rope(self, xq, xk, freqs_cis):
67
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
68
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
69
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
70
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
71
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
72
+
73
+ def forward(self, hidden_states_a, hidden_states_b, image_rotary_emb, attn_mask=None, ipadapter_kwargs_list=None):
74
+ batch_size = hidden_states_a.shape[0]
75
+
76
+ # Part A
77
+ qkv_a = self.a_to_qkv(hidden_states_a)
78
+ qkv_a = qkv_a.view(batch_size, -1, 3 * self.num_heads, self.head_dim).transpose(1, 2)
79
+ q_a, k_a, v_a = qkv_a.chunk(3, dim=1)
80
+ q_a, k_a = self.norm_q_a(q_a), self.norm_k_a(k_a)
81
+
82
+ # Part B
83
+ qkv_b = self.b_to_qkv(hidden_states_b)
84
+ qkv_b = qkv_b.view(batch_size, -1, 3 * self.num_heads, self.head_dim).transpose(1, 2)
85
+ q_b, k_b, v_b = qkv_b.chunk(3, dim=1)
86
+ q_b, k_b = self.norm_q_b(q_b), self.norm_k_b(k_b)
87
+
88
+ q = torch.concat([q_b, q_a], dim=2)
89
+ k = torch.concat([k_b, k_a], dim=2)
90
+ v = torch.concat([v_b, v_a], dim=2)
91
+
92
+ q, k = self.apply_rope(q, k, image_rotary_emb)
93
+
94
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
95
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
96
+ hidden_states = hidden_states.to(q.dtype)
97
+ hidden_states_b, hidden_states_a = hidden_states[:, :hidden_states_b.shape[1]], hidden_states[:, hidden_states_b.shape[1]:]
98
+ if ipadapter_kwargs_list is not None:
99
+ hidden_states_a = interact_with_ipadapter(hidden_states_a, q_a, **ipadapter_kwargs_list)
100
+ hidden_states_a = self.a_to_out(hidden_states_a)
101
+ if self.only_out_a:
102
+ return hidden_states_a
103
+ else:
104
+ hidden_states_b = self.b_to_out(hidden_states_b)
105
+ return hidden_states_a, hidden_states_b
106
+
107
+
108
+
109
+ class FluxJointTransformerBlock(torch.nn.Module):
110
+ def __init__(self, dim, num_attention_heads):
111
+ super().__init__()
112
+ self.norm1_a = AdaLayerNorm(dim)
113
+ self.norm1_b = AdaLayerNorm(dim)
114
+
115
+ self.attn = FluxJointAttention(dim, dim, num_attention_heads, dim // num_attention_heads)
116
+
117
+ self.norm2_a = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
118
+ self.ff_a = torch.nn.Sequential(
119
+ torch.nn.Linear(dim, dim*4),
120
+ torch.nn.GELU(approximate="tanh"),
121
+ torch.nn.Linear(dim*4, dim)
122
+ )
123
+
124
+ self.norm2_b = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
125
+ self.ff_b = torch.nn.Sequential(
126
+ torch.nn.Linear(dim, dim*4),
127
+ torch.nn.GELU(approximate="tanh"),
128
+ torch.nn.Linear(dim*4, dim)
129
+ )
130
+
131
+
132
+ def forward(self, hidden_states_a, hidden_states_b, temb, image_rotary_emb, attn_mask=None, ipadapter_kwargs_list=None):
133
+ norm_hidden_states_a, gate_msa_a, shift_mlp_a, scale_mlp_a, gate_mlp_a = self.norm1_a(hidden_states_a, emb=temb)
134
+ norm_hidden_states_b, gate_msa_b, shift_mlp_b, scale_mlp_b, gate_mlp_b = self.norm1_b(hidden_states_b, emb=temb)
135
+
136
+ # Attention
137
+ attn_output_a, attn_output_b = self.attn(norm_hidden_states_a, norm_hidden_states_b, image_rotary_emb, attn_mask, ipadapter_kwargs_list)
138
+
139
+ # Part A
140
+ hidden_states_a = hidden_states_a + gate_msa_a * attn_output_a
141
+ norm_hidden_states_a = self.norm2_a(hidden_states_a) * (1 + scale_mlp_a) + shift_mlp_a
142
+ hidden_states_a = hidden_states_a + gate_mlp_a * self.ff_a(norm_hidden_states_a)
143
+
144
+ # Part B
145
+ hidden_states_b = hidden_states_b + gate_msa_b * attn_output_b
146
+ norm_hidden_states_b = self.norm2_b(hidden_states_b) * (1 + scale_mlp_b) + shift_mlp_b
147
+ hidden_states_b = hidden_states_b + gate_mlp_b * self.ff_b(norm_hidden_states_b)
148
+
149
+ return hidden_states_a, hidden_states_b
150
+
151
+
152
+
153
+ class FluxSingleAttention(torch.nn.Module):
154
+ def __init__(self, dim_a, dim_b, num_heads, head_dim):
155
+ super().__init__()
156
+ self.num_heads = num_heads
157
+ self.head_dim = head_dim
158
+
159
+ self.a_to_qkv = torch.nn.Linear(dim_a, dim_a * 3)
160
+
161
+ self.norm_q_a = RMSNorm(head_dim, eps=1e-6)
162
+ self.norm_k_a = RMSNorm(head_dim, eps=1e-6)
163
+
164
+
165
+ def apply_rope(self, xq, xk, freqs_cis):
166
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
167
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
168
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
169
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
170
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
171
+
172
+
173
+ def forward(self, hidden_states, image_rotary_emb):
174
+ batch_size = hidden_states.shape[0]
175
+
176
+ qkv_a = self.a_to_qkv(hidden_states)
177
+ qkv_a = qkv_a.view(batch_size, -1, 3 * self.num_heads, self.head_dim).transpose(1, 2)
178
+ q_a, k_a, v = qkv_a.chunk(3, dim=1)
179
+ q_a, k_a = self.norm_q_a(q_a), self.norm_k_a(k_a)
180
+
181
+ q, k = self.apply_rope(q_a, k_a, image_rotary_emb)
182
+
183
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(q, k, v)
184
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
185
+ hidden_states = hidden_states.to(q.dtype)
186
+ return hidden_states
187
+
188
+
189
+
190
+ class AdaLayerNormSingle(torch.nn.Module):
191
+ def __init__(self, dim):
192
+ super().__init__()
193
+ self.silu = torch.nn.SiLU()
194
+ self.linear = torch.nn.Linear(dim, 3 * dim, bias=True)
195
+ self.norm = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
196
+
197
+
198
+ def forward(self, x, emb):
199
+ emb = self.linear(self.silu(emb))
200
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
201
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
202
+ return x, gate_msa
203
+
204
+
205
+
206
+ class FluxSingleTransformerBlock(torch.nn.Module):
207
+ def __init__(self, dim, num_attention_heads):
208
+ super().__init__()
209
+ self.num_heads = num_attention_heads
210
+ self.head_dim = dim // num_attention_heads
211
+ self.dim = dim
212
+
213
+ self.norm = AdaLayerNormSingle(dim)
214
+ self.to_qkv_mlp = torch.nn.Linear(dim, dim * (3 + 4))
215
+ self.norm_q_a = RMSNorm(self.head_dim, eps=1e-6)
216
+ self.norm_k_a = RMSNorm(self.head_dim, eps=1e-6)
217
+
218
+ self.proj_out = torch.nn.Linear(dim * 5, dim)
219
+
220
+
221
+ def apply_rope(self, xq, xk, freqs_cis):
222
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
223
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
224
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
225
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
226
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
227
+
228
+
229
+ def process_attention(self, hidden_states, image_rotary_emb, attn_mask=None, ipadapter_kwargs_list=None):
230
+ batch_size = hidden_states.shape[0]
231
+
232
+ qkv = hidden_states.view(batch_size, -1, 3 * self.num_heads, self.head_dim).transpose(1, 2)
233
+ q, k, v = qkv.chunk(3, dim=1)
234
+ q, k = self.norm_q_a(q), self.norm_k_a(k)
235
+
236
+ q, k = self.apply_rope(q, k, image_rotary_emb)
237
+
238
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
239
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
240
+ hidden_states = hidden_states.to(q.dtype)
241
+ if ipadapter_kwargs_list is not None:
242
+ hidden_states = interact_with_ipadapter(hidden_states, q, **ipadapter_kwargs_list)
243
+ return hidden_states
244
+
245
+
246
+ def forward(self, hidden_states_a, hidden_states_b, temb, image_rotary_emb, attn_mask=None, ipadapter_kwargs_list=None):
247
+ residual = hidden_states_a
248
+ norm_hidden_states, gate = self.norm(hidden_states_a, emb=temb)
249
+ hidden_states_a = self.to_qkv_mlp(norm_hidden_states)
250
+ attn_output, mlp_hidden_states = hidden_states_a[:, :, :self.dim * 3], hidden_states_a[:, :, self.dim * 3:]
251
+
252
+ attn_output = self.process_attention(attn_output, image_rotary_emb, attn_mask, ipadapter_kwargs_list)
253
+ mlp_hidden_states = torch.nn.functional.gelu(mlp_hidden_states, approximate="tanh")
254
+
255
+ hidden_states_a = torch.cat([attn_output, mlp_hidden_states], dim=2)
256
+ hidden_states_a = gate.unsqueeze(1) * self.proj_out(hidden_states_a)
257
+ hidden_states_a = residual + hidden_states_a
258
+
259
+ return hidden_states_a, hidden_states_b
260
+
261
+
262
+
263
+ class AdaLayerNormContinuous(torch.nn.Module):
264
+ def __init__(self, dim):
265
+ super().__init__()
266
+ self.silu = torch.nn.SiLU()
267
+ self.linear = torch.nn.Linear(dim, dim * 2, bias=True)
268
+ self.norm = torch.nn.LayerNorm(dim, eps=1e-6, elementwise_affine=False)
269
+
270
+ def forward(self, x, conditioning):
271
+ emb = self.linear(self.silu(conditioning))
272
+ scale, shift = torch.chunk(emb, 2, dim=1)
273
+ x = self.norm(x) * (1 + scale)[:, None] + shift[:, None]
274
+ return x
275
+
276
+
277
+
278
+ class FluxDiT(torch.nn.Module):
279
+ def __init__(self, disable_guidance_embedder=False, input_dim=64, num_blocks=19):
280
+ super().__init__()
281
+ self.pos_embedder = RoPEEmbedding(3072, 10000, [16, 56, 56])
282
+ self.time_embedder = TimestepEmbeddings(256, 3072)
283
+ self.guidance_embedder = None if disable_guidance_embedder else TimestepEmbeddings(256, 3072)
284
+ self.pooled_text_embedder = torch.nn.Sequential(torch.nn.Linear(768, 3072), torch.nn.SiLU(), torch.nn.Linear(3072, 3072))
285
+ self.context_embedder = torch.nn.Linear(4096, 3072)
286
+ self.x_embedder = torch.nn.Linear(input_dim, 3072)
287
+
288
+ self.blocks = torch.nn.ModuleList([FluxJointTransformerBlock(3072, 24) for _ in range(num_blocks)])
289
+ self.single_blocks = torch.nn.ModuleList([FluxSingleTransformerBlock(3072, 24) for _ in range(38)])
290
+
291
+ self.final_norm_out = AdaLayerNormContinuous(3072)
292
+ self.final_proj_out = torch.nn.Linear(3072, 64)
293
+
294
+ self.input_dim = input_dim
295
+
296
+
297
+ def patchify(self, hidden_states):
298
+ hidden_states = rearrange(hidden_states, "B C (H P) (W Q) -> B (H W) (C P Q)", P=2, Q=2)
299
+ return hidden_states
300
+
301
+
302
+ def unpatchify(self, hidden_states, height, width):
303
+ hidden_states = rearrange(hidden_states, "B (H W) (C P Q) -> B C (H P) (W Q)", P=2, Q=2, H=height//2, W=width//2)
304
+ return hidden_states
305
+
306
+
307
+ def prepare_image_ids(self, latents):
308
+ batch_size, _, height, width = latents.shape
309
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
310
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
311
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
312
+
313
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
314
+
315
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
316
+ latent_image_ids = latent_image_ids.reshape(
317
+ batch_size, latent_image_id_height * latent_image_id_width, latent_image_id_channels
318
+ )
319
+ latent_image_ids = latent_image_ids.to(device=latents.device, dtype=latents.dtype)
320
+
321
+ return latent_image_ids
322
+
323
+
324
+ def tiled_forward(
325
+ self,
326
+ hidden_states,
327
+ timestep, prompt_emb, pooled_prompt_emb, guidance, text_ids,
328
+ tile_size=128, tile_stride=64,
329
+ **kwargs
330
+ ):
331
+ # Due to the global positional embedding, we cannot implement layer-wise tiled forward.
332
+ hidden_states = TileWorker().tiled_forward(
333
+ lambda x: self.forward(x, timestep, prompt_emb, pooled_prompt_emb, guidance, text_ids, image_ids=None),
334
+ hidden_states,
335
+ tile_size,
336
+ tile_stride,
337
+ tile_device=hidden_states.device,
338
+ tile_dtype=hidden_states.dtype
339
+ )
340
+ return hidden_states
341
+
342
+
343
+ def construct_mask(self, entity_masks, prompt_seq_len, image_seq_len):
344
+ N = len(entity_masks)
345
+ batch_size = entity_masks[0].shape[0]
346
+ total_seq_len = N * prompt_seq_len + image_seq_len
347
+ patched_masks = [self.patchify(entity_masks[i]) for i in range(N)]
348
+ attention_mask = torch.ones((batch_size, total_seq_len, total_seq_len), dtype=torch.bool).to(device=entity_masks[0].device)
349
+
350
+ image_start = N * prompt_seq_len
351
+ image_end = N * prompt_seq_len + image_seq_len
352
+ # prompt-image mask
353
+ for i in range(N):
354
+ prompt_start = i * prompt_seq_len
355
+ prompt_end = (i + 1) * prompt_seq_len
356
+ image_mask = torch.sum(patched_masks[i], dim=-1) > 0
357
+ image_mask = image_mask.unsqueeze(1).repeat(1, prompt_seq_len, 1)
358
+ # prompt update with image
359
+ attention_mask[:, prompt_start:prompt_end, image_start:image_end] = image_mask
360
+ # image update with prompt
361
+ attention_mask[:, image_start:image_end, prompt_start:prompt_end] = image_mask.transpose(1, 2)
362
+ # prompt-prompt mask
363
+ for i in range(N):
364
+ for j in range(N):
365
+ if i != j:
366
+ prompt_start_i = i * prompt_seq_len
367
+ prompt_end_i = (i + 1) * prompt_seq_len
368
+ prompt_start_j = j * prompt_seq_len
369
+ prompt_end_j = (j + 1) * prompt_seq_len
370
+ attention_mask[:, prompt_start_i:prompt_end_i, prompt_start_j:prompt_end_j] = False
371
+
372
+ attention_mask = attention_mask.float()
373
+ attention_mask[attention_mask == 0] = float('-inf')
374
+ attention_mask[attention_mask == 1] = 0
375
+ return attention_mask
376
+
377
+
378
+ def process_entity_masks(self, hidden_states, prompt_emb, entity_prompt_emb, entity_masks, text_ids, image_ids):
379
+ repeat_dim = hidden_states.shape[1]
380
+ max_masks = 0
381
+ attention_mask = None
382
+ prompt_embs = [prompt_emb]
383
+ if entity_masks is not None:
384
+ # entity_masks
385
+ batch_size, max_masks = entity_masks.shape[0], entity_masks.shape[1]
386
+ entity_masks = entity_masks.repeat(1, 1, repeat_dim, 1, 1)
387
+ entity_masks = [entity_masks[:, i, None].squeeze(1) for i in range(max_masks)]
388
+ # global mask
389
+ global_mask = torch.ones_like(entity_masks[0]).to(device=hidden_states.device, dtype=hidden_states.dtype)
390
+ entity_masks = entity_masks + [global_mask] # append global to last
391
+ # attention mask
392
+ attention_mask = self.construct_mask(entity_masks, prompt_emb.shape[1], hidden_states.shape[1])
393
+ attention_mask = attention_mask.to(device=hidden_states.device, dtype=hidden_states.dtype)
394
+ attention_mask = attention_mask.unsqueeze(1)
395
+ # embds: n_masks * b * seq * d
396
+ local_embs = [entity_prompt_emb[:, i, None].squeeze(1) for i in range(max_masks)]
397
+ prompt_embs = local_embs + prompt_embs # append global to last
398
+ prompt_embs = [self.context_embedder(prompt_emb) for prompt_emb in prompt_embs]
399
+ prompt_emb = torch.cat(prompt_embs, dim=1)
400
+
401
+ # positional embedding
402
+ text_ids = torch.cat([text_ids] * (max_masks + 1), dim=1)
403
+ image_rotary_emb = self.pos_embedder(torch.cat((text_ids, image_ids), dim=1))
404
+ return prompt_emb, image_rotary_emb, attention_mask
405
+
406
+
407
+ def forward(
408
+ self,
409
+ hidden_states,
410
+ timestep, prompt_emb, pooled_prompt_emb, guidance, text_ids, image_ids=None,
411
+ tiled=False, tile_size=128, tile_stride=64, entity_prompt_emb=None, entity_masks=None,
412
+ use_gradient_checkpointing=False,
413
+ **kwargs
414
+ ):
415
+ if tiled:
416
+ return self.tiled_forward(
417
+ hidden_states,
418
+ timestep, prompt_emb, pooled_prompt_emb, guidance, text_ids,
419
+ tile_size=tile_size, tile_stride=tile_stride,
420
+ **kwargs
421
+ )
422
+
423
+ if image_ids is None:
424
+ image_ids = self.prepare_image_ids(hidden_states)
425
+
426
+ conditioning = self.time_embedder(timestep, hidden_states.dtype) + self.pooled_text_embedder(pooled_prompt_emb)
427
+ if self.guidance_embedder is not None:
428
+ guidance = guidance * 1000
429
+ conditioning = conditioning + self.guidance_embedder(guidance, hidden_states.dtype)
430
+
431
+ height, width = hidden_states.shape[-2:]
432
+ hidden_states = self.patchify(hidden_states)
433
+ hidden_states = self.x_embedder(hidden_states)
434
+
435
+ if entity_prompt_emb is not None and entity_masks is not None:
436
+ prompt_emb, image_rotary_emb, attention_mask = self.process_entity_masks(hidden_states, prompt_emb, entity_prompt_emb, entity_masks, text_ids, image_ids)
437
+ else:
438
+ prompt_emb = self.context_embedder(prompt_emb)
439
+ image_rotary_emb = self.pos_embedder(torch.cat((text_ids, image_ids), dim=1))
440
+ attention_mask = None
441
+
442
+ def create_custom_forward(module):
443
+ def custom_forward(*inputs):
444
+ return module(*inputs)
445
+ return custom_forward
446
+
447
+ for block in self.blocks:
448
+ if self.training and use_gradient_checkpointing:
449
+ hidden_states, prompt_emb = torch.utils.checkpoint.checkpoint(
450
+ create_custom_forward(block),
451
+ hidden_states, prompt_emb, conditioning, image_rotary_emb, attention_mask,
452
+ use_reentrant=False,
453
+ )
454
+ else:
455
+ hidden_states, prompt_emb = block(hidden_states, prompt_emb, conditioning, image_rotary_emb, attention_mask)
456
+
457
+ hidden_states = torch.cat([prompt_emb, hidden_states], dim=1)
458
+ for block in self.single_blocks:
459
+ if self.training and use_gradient_checkpointing:
460
+ hidden_states, prompt_emb = torch.utils.checkpoint.checkpoint(
461
+ create_custom_forward(block),
462
+ hidden_states, prompt_emb, conditioning, image_rotary_emb, attention_mask,
463
+ use_reentrant=False,
464
+ )
465
+ else:
466
+ hidden_states, prompt_emb = block(hidden_states, prompt_emb, conditioning, image_rotary_emb, attention_mask)
467
+ hidden_states = hidden_states[:, prompt_emb.shape[1]:]
468
+
469
+ hidden_states = self.final_norm_out(hidden_states, conditioning)
470
+ hidden_states = self.final_proj_out(hidden_states)
471
+ hidden_states = self.unpatchify(hidden_states, height, width)
472
+
473
+ return hidden_states
474
+
475
+
476
+ def quantize(self):
477
+ def cast_to(weight, dtype=None, device=None, copy=False):
478
+ if device is None or weight.device == device:
479
+ if not copy:
480
+ if dtype is None or weight.dtype == dtype:
481
+ return weight
482
+ return weight.to(dtype=dtype, copy=copy)
483
+
484
+ r = torch.empty_like(weight, dtype=dtype, device=device)
485
+ r.copy_(weight)
486
+ return r
487
+
488
+ def cast_weight(s, input=None, dtype=None, device=None):
489
+ if input is not None:
490
+ if dtype is None:
491
+ dtype = input.dtype
492
+ if device is None:
493
+ device = input.device
494
+ weight = cast_to(s.weight, dtype, device)
495
+ return weight
496
+
497
+ def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None):
498
+ if input is not None:
499
+ if dtype is None:
500
+ dtype = input.dtype
501
+ if bias_dtype is None:
502
+ bias_dtype = dtype
503
+ if device is None:
504
+ device = input.device
505
+ bias = None
506
+ weight = cast_to(s.weight, dtype, device)
507
+ bias = cast_to(s.bias, bias_dtype, device)
508
+ return weight, bias
509
+
510
+ class quantized_layer:
511
+ class Linear(torch.nn.Linear):
512
+ def __init__(self, *args, **kwargs):
513
+ super().__init__(*args, **kwargs)
514
+
515
+ def forward(self,input,**kwargs):
516
+ weight,bias= cast_bias_weight(self,input)
517
+ return torch.nn.functional.linear(input,weight,bias)
518
+
519
+ class RMSNorm(torch.nn.Module):
520
+ def __init__(self, module):
521
+ super().__init__()
522
+ self.module = module
523
+
524
+ def forward(self,hidden_states,**kwargs):
525
+ weight= cast_weight(self.module,hidden_states)
526
+ input_dtype = hidden_states.dtype
527
+ variance = hidden_states.to(torch.float32).square().mean(-1, keepdim=True)
528
+ hidden_states = hidden_states * torch.rsqrt(variance + self.module.eps)
529
+ hidden_states = hidden_states.to(input_dtype) * weight
530
+ return hidden_states
531
+
532
+ def replace_layer(model):
533
+ for name, module in model.named_children():
534
+ if isinstance(module, torch.nn.Linear):
535
+ with init_weights_on_device():
536
+ new_layer = quantized_layer.Linear(module.in_features,module.out_features)
537
+ new_layer.weight = module.weight
538
+ if module.bias is not None:
539
+ new_layer.bias = module.bias
540
+ # del module
541
+ setattr(model, name, new_layer)
542
+ elif isinstance(module, RMSNorm):
543
+ if hasattr(module,"quantized"):
544
+ continue
545
+ module.quantized= True
546
+ new_layer = quantized_layer.RMSNorm(module)
547
+ setattr(model, name, new_layer)
548
+ else:
549
+ replace_layer(module)
550
+
551
+ replace_layer(self)
552
+
553
+
554
+ @staticmethod
555
+ def state_dict_converter():
556
+ return FluxDiTStateDictConverter()
557
+
558
+
559
+ class FluxDiTStateDictConverter:
560
+ def __init__(self):
561
+ pass
562
+
563
+ def from_diffusers(self, state_dict):
564
+ global_rename_dict = {
565
+ "context_embedder": "context_embedder",
566
+ "x_embedder": "x_embedder",
567
+ "time_text_embed.timestep_embedder.linear_1": "time_embedder.timestep_embedder.0",
568
+ "time_text_embed.timestep_embedder.linear_2": "time_embedder.timestep_embedder.2",
569
+ "time_text_embed.guidance_embedder.linear_1": "guidance_embedder.timestep_embedder.0",
570
+ "time_text_embed.guidance_embedder.linear_2": "guidance_embedder.timestep_embedder.2",
571
+ "time_text_embed.text_embedder.linear_1": "pooled_text_embedder.0",
572
+ "time_text_embed.text_embedder.linear_2": "pooled_text_embedder.2",
573
+ "norm_out.linear": "final_norm_out.linear",
574
+ "proj_out": "final_proj_out",
575
+ }
576
+ rename_dict = {
577
+ "proj_out": "proj_out",
578
+ "norm1.linear": "norm1_a.linear",
579
+ "norm1_context.linear": "norm1_b.linear",
580
+ "attn.to_q": "attn.a_to_q",
581
+ "attn.to_k": "attn.a_to_k",
582
+ "attn.to_v": "attn.a_to_v",
583
+ "attn.to_out.0": "attn.a_to_out",
584
+ "attn.add_q_proj": "attn.b_to_q",
585
+ "attn.add_k_proj": "attn.b_to_k",
586
+ "attn.add_v_proj": "attn.b_to_v",
587
+ "attn.to_add_out": "attn.b_to_out",
588
+ "ff.net.0.proj": "ff_a.0",
589
+ "ff.net.2": "ff_a.2",
590
+ "ff_context.net.0.proj": "ff_b.0",
591
+ "ff_context.net.2": "ff_b.2",
592
+ "attn.norm_q": "attn.norm_q_a",
593
+ "attn.norm_k": "attn.norm_k_a",
594
+ "attn.norm_added_q": "attn.norm_q_b",
595
+ "attn.norm_added_k": "attn.norm_k_b",
596
+ }
597
+ rename_dict_single = {
598
+ "attn.to_q": "a_to_q",
599
+ "attn.to_k": "a_to_k",
600
+ "attn.to_v": "a_to_v",
601
+ "attn.norm_q": "norm_q_a",
602
+ "attn.norm_k": "norm_k_a",
603
+ "norm.linear": "norm.linear",
604
+ "proj_mlp": "proj_in_besides_attn",
605
+ "proj_out": "proj_out",
606
+ }
607
+ state_dict_ = {}
608
+ for name, param in state_dict.items():
609
+ if name.endswith(".weight") or name.endswith(".bias"):
610
+ suffix = ".weight" if name.endswith(".weight") else ".bias"
611
+ prefix = name[:-len(suffix)]
612
+ if prefix in global_rename_dict:
613
+ state_dict_[global_rename_dict[prefix] + suffix] = param
614
+ elif prefix.startswith("transformer_blocks."):
615
+ names = prefix.split(".")
616
+ names[0] = "blocks"
617
+ middle = ".".join(names[2:])
618
+ if middle in rename_dict:
619
+ name_ = ".".join(names[:2] + [rename_dict[middle]] + [suffix[1:]])
620
+ state_dict_[name_] = param
621
+ elif prefix.startswith("single_transformer_blocks."):
622
+ names = prefix.split(".")
623
+ names[0] = "single_blocks"
624
+ middle = ".".join(names[2:])
625
+ if middle in rename_dict_single:
626
+ name_ = ".".join(names[:2] + [rename_dict_single[middle]] + [suffix[1:]])
627
+ state_dict_[name_] = param
628
+ else:
629
+ pass
630
+ else:
631
+ pass
632
+ for name in list(state_dict_.keys()):
633
+ if "single_blocks." in name and ".a_to_q." in name:
634
+ mlp = state_dict_.get(name.replace(".a_to_q.", ".proj_in_besides_attn."), None)
635
+ if mlp is None:
636
+ mlp = torch.zeros(4 * state_dict_[name].shape[0],
637
+ *state_dict_[name].shape[1:],
638
+ dtype=state_dict_[name].dtype)
639
+ else:
640
+ state_dict_.pop(name.replace(".a_to_q.", ".proj_in_besides_attn."))
641
+ param = torch.concat([
642
+ state_dict_.pop(name),
643
+ state_dict_.pop(name.replace(".a_to_q.", ".a_to_k.")),
644
+ state_dict_.pop(name.replace(".a_to_q.", ".a_to_v.")),
645
+ mlp,
646
+ ], dim=0)
647
+ name_ = name.replace(".a_to_q.", ".to_qkv_mlp.")
648
+ state_dict_[name_] = param
649
+ for name in list(state_dict_.keys()):
650
+ for component in ["a", "b"]:
651
+ if f".{component}_to_q." in name:
652
+ name_ = name.replace(f".{component}_to_q.", f".{component}_to_qkv.")
653
+ param = torch.concat([
654
+ state_dict_[name.replace(f".{component}_to_q.", f".{component}_to_q.")],
655
+ state_dict_[name.replace(f".{component}_to_q.", f".{component}_to_k.")],
656
+ state_dict_[name.replace(f".{component}_to_q.", f".{component}_to_v.")],
657
+ ], dim=0)
658
+ state_dict_[name_] = param
659
+ state_dict_.pop(name.replace(f".{component}_to_q.", f".{component}_to_q."))
660
+ state_dict_.pop(name.replace(f".{component}_to_q.", f".{component}_to_k."))
661
+ state_dict_.pop(name.replace(f".{component}_to_q.", f".{component}_to_v."))
662
+ return state_dict_
663
+
664
+ def from_civitai(self, state_dict):
665
+ rename_dict = {
666
+ "time_in.in_layer.bias": "time_embedder.timestep_embedder.0.bias",
667
+ "time_in.in_layer.weight": "time_embedder.timestep_embedder.0.weight",
668
+ "time_in.out_layer.bias": "time_embedder.timestep_embedder.2.bias",
669
+ "time_in.out_layer.weight": "time_embedder.timestep_embedder.2.weight",
670
+ "txt_in.bias": "context_embedder.bias",
671
+ "txt_in.weight": "context_embedder.weight",
672
+ "vector_in.in_layer.bias": "pooled_text_embedder.0.bias",
673
+ "vector_in.in_layer.weight": "pooled_text_embedder.0.weight",
674
+ "vector_in.out_layer.bias": "pooled_text_embedder.2.bias",
675
+ "vector_in.out_layer.weight": "pooled_text_embedder.2.weight",
676
+ "final_layer.linear.bias": "final_proj_out.bias",
677
+ "final_layer.linear.weight": "final_proj_out.weight",
678
+ "guidance_in.in_layer.bias": "guidance_embedder.timestep_embedder.0.bias",
679
+ "guidance_in.in_layer.weight": "guidance_embedder.timestep_embedder.0.weight",
680
+ "guidance_in.out_layer.bias": "guidance_embedder.timestep_embedder.2.bias",
681
+ "guidance_in.out_layer.weight": "guidance_embedder.timestep_embedder.2.weight",
682
+ "img_in.bias": "x_embedder.bias",
683
+ "img_in.weight": "x_embedder.weight",
684
+ "final_layer.adaLN_modulation.1.weight": "final_norm_out.linear.weight",
685
+ "final_layer.adaLN_modulation.1.bias": "final_norm_out.linear.bias",
686
+ }
687
+ suffix_rename_dict = {
688
+ "img_attn.norm.key_norm.scale": "attn.norm_k_a.weight",
689
+ "img_attn.norm.query_norm.scale": "attn.norm_q_a.weight",
690
+ "img_attn.proj.bias": "attn.a_to_out.bias",
691
+ "img_attn.proj.weight": "attn.a_to_out.weight",
692
+ "img_attn.qkv.bias": "attn.a_to_qkv.bias",
693
+ "img_attn.qkv.weight": "attn.a_to_qkv.weight",
694
+ "img_mlp.0.bias": "ff_a.0.bias",
695
+ "img_mlp.0.weight": "ff_a.0.weight",
696
+ "img_mlp.2.bias": "ff_a.2.bias",
697
+ "img_mlp.2.weight": "ff_a.2.weight",
698
+ "img_mod.lin.bias": "norm1_a.linear.bias",
699
+ "img_mod.lin.weight": "norm1_a.linear.weight",
700
+ "txt_attn.norm.key_norm.scale": "attn.norm_k_b.weight",
701
+ "txt_attn.norm.query_norm.scale": "attn.norm_q_b.weight",
702
+ "txt_attn.proj.bias": "attn.b_to_out.bias",
703
+ "txt_attn.proj.weight": "attn.b_to_out.weight",
704
+ "txt_attn.qkv.bias": "attn.b_to_qkv.bias",
705
+ "txt_attn.qkv.weight": "attn.b_to_qkv.weight",
706
+ "txt_mlp.0.bias": "ff_b.0.bias",
707
+ "txt_mlp.0.weight": "ff_b.0.weight",
708
+ "txt_mlp.2.bias": "ff_b.2.bias",
709
+ "txt_mlp.2.weight": "ff_b.2.weight",
710
+ "txt_mod.lin.bias": "norm1_b.linear.bias",
711
+ "txt_mod.lin.weight": "norm1_b.linear.weight",
712
+
713
+ "linear1.bias": "to_qkv_mlp.bias",
714
+ "linear1.weight": "to_qkv_mlp.weight",
715
+ "linear2.bias": "proj_out.bias",
716
+ "linear2.weight": "proj_out.weight",
717
+ "modulation.lin.bias": "norm.linear.bias",
718
+ "modulation.lin.weight": "norm.linear.weight",
719
+ "norm.key_norm.scale": "norm_k_a.weight",
720
+ "norm.query_norm.scale": "norm_q_a.weight",
721
+ }
722
+ state_dict_ = {}
723
+ for name, param in state_dict.items():
724
+ if name.startswith("model.diffusion_model."):
725
+ name = name[len("model.diffusion_model."):]
726
+ names = name.split(".")
727
+ if name in rename_dict:
728
+ rename = rename_dict[name]
729
+ if name.startswith("final_layer.adaLN_modulation.1."):
730
+ param = torch.concat([param[3072:], param[:3072]], dim=0)
731
+ state_dict_[rename] = param
732
+ elif names[0] == "double_blocks":
733
+ rename = f"blocks.{names[1]}." + suffix_rename_dict[".".join(names[2:])]
734
+ state_dict_[rename] = param
735
+ elif names[0] == "single_blocks":
736
+ if ".".join(names[2:]) in suffix_rename_dict:
737
+ rename = f"single_blocks.{names[1]}." + suffix_rename_dict[".".join(names[2:])]
738
+ state_dict_[rename] = param
739
+ else:
740
+ pass
741
+ if "guidance_embedder.timestep_embedder.0.weight" not in state_dict_:
742
+ return state_dict_, {"disable_guidance_embedder": True}
743
+ elif "blocks.8.attn.norm_k_a.weight" not in state_dict_:
744
+ return state_dict_, {"input_dim": 196, "num_blocks": 8}
745
+ else:
746
+ return state_dict_
flux_infiniteyou.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ # FFN
7
+ def FeedForward(dim, mult=4):
8
+ inner_dim = int(dim * mult)
9
+ return nn.Sequential(
10
+ nn.LayerNorm(dim),
11
+ nn.Linear(dim, inner_dim, bias=False),
12
+ nn.GELU(),
13
+ nn.Linear(inner_dim, dim, bias=False),
14
+ )
15
+
16
+
17
+ def reshape_tensor(x, heads):
18
+ bs, length, width = x.shape
19
+ #(bs, length, width) --> (bs, length, n_heads, dim_per_head)
20
+ x = x.view(bs, length, heads, -1)
21
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
22
+ x = x.transpose(1, 2)
23
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
24
+ x = x.reshape(bs, heads, length, -1)
25
+ return x
26
+
27
+
28
+ class PerceiverAttention(nn.Module):
29
+
30
+ def __init__(self, *, dim, dim_head=64, heads=8):
31
+ super().__init__()
32
+ self.scale = dim_head**-0.5
33
+ self.dim_head = dim_head
34
+ self.heads = heads
35
+ inner_dim = dim_head * heads
36
+
37
+ self.norm1 = nn.LayerNorm(dim)
38
+ self.norm2 = nn.LayerNorm(dim)
39
+
40
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
41
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
42
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
43
+
44
+ def forward(self, x, latents):
45
+ """
46
+ Args:
47
+ x (torch.Tensor): image features
48
+ shape (b, n1, D)
49
+ latent (torch.Tensor): latent features
50
+ shape (b, n2, D)
51
+ """
52
+ x = self.norm1(x)
53
+ latents = self.norm2(latents)
54
+
55
+ b, l, _ = latents.shape
56
+
57
+ q = self.to_q(latents)
58
+ kv_input = torch.cat((x, latents), dim=-2)
59
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
60
+
61
+ q = reshape_tensor(q, self.heads)
62
+ k = reshape_tensor(k, self.heads)
63
+ v = reshape_tensor(v, self.heads)
64
+
65
+ # attention
66
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
67
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
68
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
69
+ out = weight @ v
70
+
71
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
72
+
73
+ return self.to_out(out)
74
+
75
+
76
+ class InfiniteYouImageProjector(nn.Module):
77
+
78
+ def __init__(
79
+ self,
80
+ dim=1280,
81
+ depth=4,
82
+ dim_head=64,
83
+ heads=20,
84
+ num_queries=8,
85
+ embedding_dim=512,
86
+ output_dim=4096,
87
+ ff_mult=4,
88
+ ):
89
+ super().__init__()
90
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
91
+ self.proj_in = nn.Linear(embedding_dim, dim)
92
+
93
+ self.proj_out = nn.Linear(dim, output_dim)
94
+ self.norm_out = nn.LayerNorm(output_dim)
95
+
96
+ self.layers = nn.ModuleList([])
97
+ for _ in range(depth):
98
+ self.layers.append(
99
+ nn.ModuleList([
100
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
101
+ FeedForward(dim=dim, mult=ff_mult),
102
+ ]))
103
+
104
+ def forward(self, x):
105
+
106
+ latents = self.latents.repeat(x.size(0), 1, 1)
107
+ latents = latents.to(dtype=x.dtype, device=x.device)
108
+
109
+ x = self.proj_in(x)
110
+
111
+ for attn, ff in self.layers:
112
+ latents = attn(x, latents) + latents
113
+ latents = ff(latents) + latents
114
+
115
+ latents = self.proj_out(latents)
116
+ return self.norm_out(latents)
117
+
118
+ @staticmethod
119
+ def state_dict_converter():
120
+ return FluxInfiniteYouImageProjectorStateDictConverter()
121
+
122
+
123
+ class FluxInfiniteYouImageProjectorStateDictConverter:
124
+
125
+ def __init__(self):
126
+ pass
127
+
128
+ def from_diffusers(self, state_dict):
129
+ return state_dict['image_proj']
flux_ipadapter.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .svd_image_encoder import SVDImageEncoder
2
+ from .sd3_dit import RMSNorm
3
+ from transformers import CLIPImageProcessor
4
+ import torch
5
+
6
+
7
+ class MLPProjModel(torch.nn.Module):
8
+ def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4):
9
+ super().__init__()
10
+
11
+ self.cross_attention_dim = cross_attention_dim
12
+ self.num_tokens = num_tokens
13
+
14
+ self.proj = torch.nn.Sequential(
15
+ torch.nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
16
+ torch.nn.GELU(),
17
+ torch.nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
18
+ )
19
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
20
+
21
+ def forward(self, id_embeds):
22
+ x = self.proj(id_embeds)
23
+ x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
24
+ x = self.norm(x)
25
+ return x
26
+
27
+ class IpAdapterModule(torch.nn.Module):
28
+ def __init__(self, num_attention_heads, attention_head_dim, input_dim):
29
+ super().__init__()
30
+ self.num_heads = num_attention_heads
31
+ self.head_dim = attention_head_dim
32
+ output_dim = num_attention_heads * attention_head_dim
33
+ self.to_k_ip = torch.nn.Linear(input_dim, output_dim, bias=False)
34
+ self.to_v_ip = torch.nn.Linear(input_dim, output_dim, bias=False)
35
+ self.norm_added_k = RMSNorm(attention_head_dim, eps=1e-5, elementwise_affine=False)
36
+
37
+
38
+ def forward(self, hidden_states):
39
+ batch_size = hidden_states.shape[0]
40
+ # ip_k
41
+ ip_k = self.to_k_ip(hidden_states)
42
+ ip_k = ip_k.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
43
+ ip_k = self.norm_added_k(ip_k)
44
+ # ip_v
45
+ ip_v = self.to_v_ip(hidden_states)
46
+ ip_v = ip_v.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
47
+ return ip_k, ip_v
48
+
49
+
50
+ class FluxIpAdapter(torch.nn.Module):
51
+ def __init__(self, num_attention_heads=24, attention_head_dim=128, cross_attention_dim=4096, num_tokens=128, num_blocks=57):
52
+ super().__init__()
53
+ self.ipadapter_modules = torch.nn.ModuleList([IpAdapterModule(num_attention_heads, attention_head_dim, cross_attention_dim) for _ in range(num_blocks)])
54
+ self.image_proj = MLPProjModel(cross_attention_dim=cross_attention_dim, id_embeddings_dim=1152, num_tokens=num_tokens)
55
+ self.set_adapter()
56
+
57
+ def set_adapter(self):
58
+ self.call_block_id = {i:i for i in range(len(self.ipadapter_modules))}
59
+
60
+ def forward(self, hidden_states, scale=1.0):
61
+ hidden_states = self.image_proj(hidden_states)
62
+ hidden_states = hidden_states.view(1, -1, hidden_states.shape[-1])
63
+ ip_kv_dict = {}
64
+ for block_id in self.call_block_id:
65
+ ipadapter_id = self.call_block_id[block_id]
66
+ ip_k, ip_v = self.ipadapter_modules[ipadapter_id](hidden_states)
67
+ ip_kv_dict[block_id] = {
68
+ "ip_k": ip_k,
69
+ "ip_v": ip_v,
70
+ "scale": scale
71
+ }
72
+ return ip_kv_dict
73
+
74
+ @staticmethod
75
+ def state_dict_converter():
76
+ return FluxIpAdapterStateDictConverter()
77
+
78
+
79
+ class FluxIpAdapterStateDictConverter:
80
+ def __init__(self):
81
+ pass
82
+
83
+ def from_diffusers(self, state_dict):
84
+ state_dict_ = {}
85
+ for name in state_dict["ip_adapter"]:
86
+ name_ = 'ipadapter_modules.' + name
87
+ state_dict_[name_] = state_dict["ip_adapter"][name]
88
+ for name in state_dict["image_proj"]:
89
+ name_ = "image_proj." + name
90
+ state_dict_[name_] = state_dict["image_proj"][name]
91
+ return state_dict_
92
+
93
+ def from_civitai(self, state_dict):
94
+ return self.from_diffusers(state_dict)
flux_lora_encoder.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_text_encoder import CLIPEncoderLayer
3
+
4
+
5
+ class LoRALayerBlock(torch.nn.Module):
6
+ def __init__(self, L, dim_in, dim_out):
7
+ super().__init__()
8
+ self.x = torch.nn.Parameter(torch.randn(1, L, dim_in))
9
+ self.layer_norm = torch.nn.LayerNorm(dim_out)
10
+
11
+ def forward(self, lora_A, lora_B):
12
+ x = self.x @ lora_A.T @ lora_B.T
13
+ x = self.layer_norm(x)
14
+ return x
15
+
16
+
17
+ class LoRAEmbedder(torch.nn.Module):
18
+ def __init__(self, lora_patterns=None, L=1, out_dim=2048):
19
+ super().__init__()
20
+ if lora_patterns is None:
21
+ lora_patterns = self.default_lora_patterns()
22
+
23
+ model_dict = {}
24
+ for lora_pattern in lora_patterns:
25
+ name, dim = lora_pattern["name"], lora_pattern["dim"]
26
+ model_dict[name.replace(".", "___")] = LoRALayerBlock(L, dim[0], dim[1])
27
+ self.model_dict = torch.nn.ModuleDict(model_dict)
28
+
29
+ proj_dict = {}
30
+ for lora_pattern in lora_patterns:
31
+ layer_type, dim = lora_pattern["type"], lora_pattern["dim"]
32
+ if layer_type not in proj_dict:
33
+ proj_dict[layer_type.replace(".", "___")] = torch.nn.Linear(dim[1], out_dim)
34
+ self.proj_dict = torch.nn.ModuleDict(proj_dict)
35
+
36
+ self.lora_patterns = lora_patterns
37
+
38
+
39
+ def default_lora_patterns(self):
40
+ lora_patterns = []
41
+ lora_dict = {
42
+ "attn.a_to_qkv": (3072, 9216), "attn.a_to_out": (3072, 3072), "ff_a.0": (3072, 12288), "ff_a.2": (12288, 3072), "norm1_a.linear": (3072, 18432),
43
+ "attn.b_to_qkv": (3072, 9216), "attn.b_to_out": (3072, 3072), "ff_b.0": (3072, 12288), "ff_b.2": (12288, 3072), "norm1_b.linear": (3072, 18432),
44
+ }
45
+ for i in range(19):
46
+ for suffix in lora_dict:
47
+ lora_patterns.append({
48
+ "name": f"blocks.{i}.{suffix}",
49
+ "dim": lora_dict[suffix],
50
+ "type": suffix,
51
+ })
52
+ lora_dict = {"to_qkv_mlp": (3072, 21504), "proj_out": (15360, 3072), "norm.linear": (3072, 9216)}
53
+ for i in range(38):
54
+ for suffix in lora_dict:
55
+ lora_patterns.append({
56
+ "name": f"single_blocks.{i}.{suffix}",
57
+ "dim": lora_dict[suffix],
58
+ "type": suffix,
59
+ })
60
+ return lora_patterns
61
+
62
+ def forward(self, lora):
63
+ lora_emb = []
64
+ for lora_pattern in self.lora_patterns:
65
+ name, layer_type = lora_pattern["name"], lora_pattern["type"]
66
+ lora_A = lora[name + ".lora_A.default.weight"]
67
+ lora_B = lora[name + ".lora_B.default.weight"]
68
+ lora_out = self.model_dict[name.replace(".", "___")](lora_A, lora_B)
69
+ lora_out = self.proj_dict[layer_type.replace(".", "___")](lora_out)
70
+ lora_emb.append(lora_out)
71
+ lora_emb = torch.concat(lora_emb, dim=1)
72
+ return lora_emb
73
+
74
+
75
+ class FluxLoRAEncoder(torch.nn.Module):
76
+ def __init__(self, embed_dim=4096, encoder_intermediate_size=8192, num_encoder_layers=1, num_embeds_per_lora=16, num_special_embeds=1):
77
+ super().__init__()
78
+ self.num_embeds_per_lora = num_embeds_per_lora
79
+ # embedder
80
+ self.embedder = LoRAEmbedder(L=num_embeds_per_lora, out_dim=embed_dim)
81
+
82
+ # encoders
83
+ self.encoders = torch.nn.ModuleList([CLIPEncoderLayer(embed_dim, encoder_intermediate_size, num_heads=32, head_dim=128) for _ in range(num_encoder_layers)])
84
+
85
+ # special embedding
86
+ self.special_embeds = torch.nn.Parameter(torch.randn(1, num_special_embeds, embed_dim))
87
+ self.num_special_embeds = num_special_embeds
88
+
89
+ # final layer
90
+ self.final_layer_norm = torch.nn.LayerNorm(embed_dim)
91
+ self.final_linear = torch.nn.Linear(embed_dim, embed_dim)
92
+
93
+ def forward(self, lora):
94
+ lora_embeds = self.embedder(lora)
95
+ special_embeds = self.special_embeds.to(dtype=lora_embeds.dtype, device=lora_embeds.device)
96
+ embeds = torch.concat([special_embeds, lora_embeds], dim=1)
97
+ for encoder_id, encoder in enumerate(self.encoders):
98
+ embeds = encoder(embeds)
99
+ embeds = embeds[:, :self.num_special_embeds]
100
+ embeds = self.final_layer_norm(embeds)
101
+ embeds = self.final_linear(embeds)
102
+ return embeds
103
+
104
+ @staticmethod
105
+ def state_dict_converter():
106
+ return FluxLoRAEncoderStateDictConverter()
107
+
108
+
109
+ class FluxLoRAEncoderStateDictConverter:
110
+ def from_civitai(self, state_dict):
111
+ return state_dict
flux_text_encoder.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import T5EncoderModel, T5Config
3
+ from .sd_text_encoder import SDTextEncoder
4
+
5
+
6
+
7
+ class FluxTextEncoder2(T5EncoderModel):
8
+ def __init__(self, config):
9
+ super().__init__(config)
10
+ self.eval()
11
+
12
+ def forward(self, input_ids):
13
+ outputs = super().forward(input_ids=input_ids)
14
+ prompt_emb = outputs.last_hidden_state
15
+ return prompt_emb
16
+
17
+ @staticmethod
18
+ def state_dict_converter():
19
+ return FluxTextEncoder2StateDictConverter()
20
+
21
+
22
+
23
+ class FluxTextEncoder2StateDictConverter():
24
+ def __init__(self):
25
+ pass
26
+
27
+ def from_diffusers(self, state_dict):
28
+ state_dict_ = state_dict
29
+ return state_dict_
30
+
31
+ def from_civitai(self, state_dict):
32
+ return self.from_diffusers(state_dict)
flux_vae.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .sd3_vae_encoder import SD3VAEEncoder, SDVAEEncoderStateDictConverter
2
+ from .sd3_vae_decoder import SD3VAEDecoder, SDVAEDecoderStateDictConverter
3
+
4
+
5
+ class FluxVAEEncoder(SD3VAEEncoder):
6
+ def __init__(self):
7
+ super().__init__()
8
+ self.scaling_factor = 0.3611
9
+ self.shift_factor = 0.1159
10
+
11
+ @staticmethod
12
+ def state_dict_converter():
13
+ return FluxVAEEncoderStateDictConverter()
14
+
15
+
16
+ class FluxVAEDecoder(SD3VAEDecoder):
17
+ def __init__(self):
18
+ super().__init__()
19
+ self.scaling_factor = 0.3611
20
+ self.shift_factor = 0.1159
21
+
22
+ @staticmethod
23
+ def state_dict_converter():
24
+ return FluxVAEDecoderStateDictConverter()
25
+
26
+
27
+ class FluxVAEEncoderStateDictConverter(SDVAEEncoderStateDictConverter):
28
+ def __init__(self):
29
+ pass
30
+
31
+ def from_civitai(self, state_dict):
32
+ rename_dict = {
33
+ "encoder.conv_in.bias": "conv_in.bias",
34
+ "encoder.conv_in.weight": "conv_in.weight",
35
+ "encoder.conv_out.bias": "conv_out.bias",
36
+ "encoder.conv_out.weight": "conv_out.weight",
37
+ "encoder.down.0.block.0.conv1.bias": "blocks.0.conv1.bias",
38
+ "encoder.down.0.block.0.conv1.weight": "blocks.0.conv1.weight",
39
+ "encoder.down.0.block.0.conv2.bias": "blocks.0.conv2.bias",
40
+ "encoder.down.0.block.0.conv2.weight": "blocks.0.conv2.weight",
41
+ "encoder.down.0.block.0.norm1.bias": "blocks.0.norm1.bias",
42
+ "encoder.down.0.block.0.norm1.weight": "blocks.0.norm1.weight",
43
+ "encoder.down.0.block.0.norm2.bias": "blocks.0.norm2.bias",
44
+ "encoder.down.0.block.0.norm2.weight": "blocks.0.norm2.weight",
45
+ "encoder.down.0.block.1.conv1.bias": "blocks.1.conv1.bias",
46
+ "encoder.down.0.block.1.conv1.weight": "blocks.1.conv1.weight",
47
+ "encoder.down.0.block.1.conv2.bias": "blocks.1.conv2.bias",
48
+ "encoder.down.0.block.1.conv2.weight": "blocks.1.conv2.weight",
49
+ "encoder.down.0.block.1.norm1.bias": "blocks.1.norm1.bias",
50
+ "encoder.down.0.block.1.norm1.weight": "blocks.1.norm1.weight",
51
+ "encoder.down.0.block.1.norm2.bias": "blocks.1.norm2.bias",
52
+ "encoder.down.0.block.1.norm2.weight": "blocks.1.norm2.weight",
53
+ "encoder.down.0.downsample.conv.bias": "blocks.2.conv.bias",
54
+ "encoder.down.0.downsample.conv.weight": "blocks.2.conv.weight",
55
+ "encoder.down.1.block.0.conv1.bias": "blocks.3.conv1.bias",
56
+ "encoder.down.1.block.0.conv1.weight": "blocks.3.conv1.weight",
57
+ "encoder.down.1.block.0.conv2.bias": "blocks.3.conv2.bias",
58
+ "encoder.down.1.block.0.conv2.weight": "blocks.3.conv2.weight",
59
+ "encoder.down.1.block.0.nin_shortcut.bias": "blocks.3.conv_shortcut.bias",
60
+ "encoder.down.1.block.0.nin_shortcut.weight": "blocks.3.conv_shortcut.weight",
61
+ "encoder.down.1.block.0.norm1.bias": "blocks.3.norm1.bias",
62
+ "encoder.down.1.block.0.norm1.weight": "blocks.3.norm1.weight",
63
+ "encoder.down.1.block.0.norm2.bias": "blocks.3.norm2.bias",
64
+ "encoder.down.1.block.0.norm2.weight": "blocks.3.norm2.weight",
65
+ "encoder.down.1.block.1.conv1.bias": "blocks.4.conv1.bias",
66
+ "encoder.down.1.block.1.conv1.weight": "blocks.4.conv1.weight",
67
+ "encoder.down.1.block.1.conv2.bias": "blocks.4.conv2.bias",
68
+ "encoder.down.1.block.1.conv2.weight": "blocks.4.conv2.weight",
69
+ "encoder.down.1.block.1.norm1.bias": "blocks.4.norm1.bias",
70
+ "encoder.down.1.block.1.norm1.weight": "blocks.4.norm1.weight",
71
+ "encoder.down.1.block.1.norm2.bias": "blocks.4.norm2.bias",
72
+ "encoder.down.1.block.1.norm2.weight": "blocks.4.norm2.weight",
73
+ "encoder.down.1.downsample.conv.bias": "blocks.5.conv.bias",
74
+ "encoder.down.1.downsample.conv.weight": "blocks.5.conv.weight",
75
+ "encoder.down.2.block.0.conv1.bias": "blocks.6.conv1.bias",
76
+ "encoder.down.2.block.0.conv1.weight": "blocks.6.conv1.weight",
77
+ "encoder.down.2.block.0.conv2.bias": "blocks.6.conv2.bias",
78
+ "encoder.down.2.block.0.conv2.weight": "blocks.6.conv2.weight",
79
+ "encoder.down.2.block.0.nin_shortcut.bias": "blocks.6.conv_shortcut.bias",
80
+ "encoder.down.2.block.0.nin_shortcut.weight": "blocks.6.conv_shortcut.weight",
81
+ "encoder.down.2.block.0.norm1.bias": "blocks.6.norm1.bias",
82
+ "encoder.down.2.block.0.norm1.weight": "blocks.6.norm1.weight",
83
+ "encoder.down.2.block.0.norm2.bias": "blocks.6.norm2.bias",
84
+ "encoder.down.2.block.0.norm2.weight": "blocks.6.norm2.weight",
85
+ "encoder.down.2.block.1.conv1.bias": "blocks.7.conv1.bias",
86
+ "encoder.down.2.block.1.conv1.weight": "blocks.7.conv1.weight",
87
+ "encoder.down.2.block.1.conv2.bias": "blocks.7.conv2.bias",
88
+ "encoder.down.2.block.1.conv2.weight": "blocks.7.conv2.weight",
89
+ "encoder.down.2.block.1.norm1.bias": "blocks.7.norm1.bias",
90
+ "encoder.down.2.block.1.norm1.weight": "blocks.7.norm1.weight",
91
+ "encoder.down.2.block.1.norm2.bias": "blocks.7.norm2.bias",
92
+ "encoder.down.2.block.1.norm2.weight": "blocks.7.norm2.weight",
93
+ "encoder.down.2.downsample.conv.bias": "blocks.8.conv.bias",
94
+ "encoder.down.2.downsample.conv.weight": "blocks.8.conv.weight",
95
+ "encoder.down.3.block.0.conv1.bias": "blocks.9.conv1.bias",
96
+ "encoder.down.3.block.0.conv1.weight": "blocks.9.conv1.weight",
97
+ "encoder.down.3.block.0.conv2.bias": "blocks.9.conv2.bias",
98
+ "encoder.down.3.block.0.conv2.weight": "blocks.9.conv2.weight",
99
+ "encoder.down.3.block.0.norm1.bias": "blocks.9.norm1.bias",
100
+ "encoder.down.3.block.0.norm1.weight": "blocks.9.norm1.weight",
101
+ "encoder.down.3.block.0.norm2.bias": "blocks.9.norm2.bias",
102
+ "encoder.down.3.block.0.norm2.weight": "blocks.9.norm2.weight",
103
+ "encoder.down.3.block.1.conv1.bias": "blocks.10.conv1.bias",
104
+ "encoder.down.3.block.1.conv1.weight": "blocks.10.conv1.weight",
105
+ "encoder.down.3.block.1.conv2.bias": "blocks.10.conv2.bias",
106
+ "encoder.down.3.block.1.conv2.weight": "blocks.10.conv2.weight",
107
+ "encoder.down.3.block.1.norm1.bias": "blocks.10.norm1.bias",
108
+ "encoder.down.3.block.1.norm1.weight": "blocks.10.norm1.weight",
109
+ "encoder.down.3.block.1.norm2.bias": "blocks.10.norm2.bias",
110
+ "encoder.down.3.block.1.norm2.weight": "blocks.10.norm2.weight",
111
+ "encoder.mid.attn_1.k.bias": "blocks.12.transformer_blocks.0.to_k.bias",
112
+ "encoder.mid.attn_1.k.weight": "blocks.12.transformer_blocks.0.to_k.weight",
113
+ "encoder.mid.attn_1.norm.bias": "blocks.12.norm.bias",
114
+ "encoder.mid.attn_1.norm.weight": "blocks.12.norm.weight",
115
+ "encoder.mid.attn_1.proj_out.bias": "blocks.12.transformer_blocks.0.to_out.bias",
116
+ "encoder.mid.attn_1.proj_out.weight": "blocks.12.transformer_blocks.0.to_out.weight",
117
+ "encoder.mid.attn_1.q.bias": "blocks.12.transformer_blocks.0.to_q.bias",
118
+ "encoder.mid.attn_1.q.weight": "blocks.12.transformer_blocks.0.to_q.weight",
119
+ "encoder.mid.attn_1.v.bias": "blocks.12.transformer_blocks.0.to_v.bias",
120
+ "encoder.mid.attn_1.v.weight": "blocks.12.transformer_blocks.0.to_v.weight",
121
+ "encoder.mid.block_1.conv1.bias": "blocks.11.conv1.bias",
122
+ "encoder.mid.block_1.conv1.weight": "blocks.11.conv1.weight",
123
+ "encoder.mid.block_1.conv2.bias": "blocks.11.conv2.bias",
124
+ "encoder.mid.block_1.conv2.weight": "blocks.11.conv2.weight",
125
+ "encoder.mid.block_1.norm1.bias": "blocks.11.norm1.bias",
126
+ "encoder.mid.block_1.norm1.weight": "blocks.11.norm1.weight",
127
+ "encoder.mid.block_1.norm2.bias": "blocks.11.norm2.bias",
128
+ "encoder.mid.block_1.norm2.weight": "blocks.11.norm2.weight",
129
+ "encoder.mid.block_2.conv1.bias": "blocks.13.conv1.bias",
130
+ "encoder.mid.block_2.conv1.weight": "blocks.13.conv1.weight",
131
+ "encoder.mid.block_2.conv2.bias": "blocks.13.conv2.bias",
132
+ "encoder.mid.block_2.conv2.weight": "blocks.13.conv2.weight",
133
+ "encoder.mid.block_2.norm1.bias": "blocks.13.norm1.bias",
134
+ "encoder.mid.block_2.norm1.weight": "blocks.13.norm1.weight",
135
+ "encoder.mid.block_2.norm2.bias": "blocks.13.norm2.bias",
136
+ "encoder.mid.block_2.norm2.weight": "blocks.13.norm2.weight",
137
+ "encoder.norm_out.bias": "conv_norm_out.bias",
138
+ "encoder.norm_out.weight": "conv_norm_out.weight",
139
+ }
140
+ state_dict_ = {}
141
+ for name in state_dict:
142
+ if name in rename_dict:
143
+ param = state_dict[name]
144
+ if "transformer_blocks" in rename_dict[name]:
145
+ param = param.squeeze()
146
+ state_dict_[rename_dict[name]] = param
147
+ return state_dict_
148
+
149
+
150
+
151
+ class FluxVAEDecoderStateDictConverter(SDVAEDecoderStateDictConverter):
152
+ def __init__(self):
153
+ pass
154
+
155
+ def from_civitai(self, state_dict):
156
+ rename_dict = {
157
+ "decoder.conv_in.bias": "conv_in.bias",
158
+ "decoder.conv_in.weight": "conv_in.weight",
159
+ "decoder.conv_out.bias": "conv_out.bias",
160
+ "decoder.conv_out.weight": "conv_out.weight",
161
+ "decoder.mid.attn_1.k.bias": "blocks.1.transformer_blocks.0.to_k.bias",
162
+ "decoder.mid.attn_1.k.weight": "blocks.1.transformer_blocks.0.to_k.weight",
163
+ "decoder.mid.attn_1.norm.bias": "blocks.1.norm.bias",
164
+ "decoder.mid.attn_1.norm.weight": "blocks.1.norm.weight",
165
+ "decoder.mid.attn_1.proj_out.bias": "blocks.1.transformer_blocks.0.to_out.bias",
166
+ "decoder.mid.attn_1.proj_out.weight": "blocks.1.transformer_blocks.0.to_out.weight",
167
+ "decoder.mid.attn_1.q.bias": "blocks.1.transformer_blocks.0.to_q.bias",
168
+ "decoder.mid.attn_1.q.weight": "blocks.1.transformer_blocks.0.to_q.weight",
169
+ "decoder.mid.attn_1.v.bias": "blocks.1.transformer_blocks.0.to_v.bias",
170
+ "decoder.mid.attn_1.v.weight": "blocks.1.transformer_blocks.0.to_v.weight",
171
+ "decoder.mid.block_1.conv1.bias": "blocks.0.conv1.bias",
172
+ "decoder.mid.block_1.conv1.weight": "blocks.0.conv1.weight",
173
+ "decoder.mid.block_1.conv2.bias": "blocks.0.conv2.bias",
174
+ "decoder.mid.block_1.conv2.weight": "blocks.0.conv2.weight",
175
+ "decoder.mid.block_1.norm1.bias": "blocks.0.norm1.bias",
176
+ "decoder.mid.block_1.norm1.weight": "blocks.0.norm1.weight",
177
+ "decoder.mid.block_1.norm2.bias": "blocks.0.norm2.bias",
178
+ "decoder.mid.block_1.norm2.weight": "blocks.0.norm2.weight",
179
+ "decoder.mid.block_2.conv1.bias": "blocks.2.conv1.bias",
180
+ "decoder.mid.block_2.conv1.weight": "blocks.2.conv1.weight",
181
+ "decoder.mid.block_2.conv2.bias": "blocks.2.conv2.bias",
182
+ "decoder.mid.block_2.conv2.weight": "blocks.2.conv2.weight",
183
+ "decoder.mid.block_2.norm1.bias": "blocks.2.norm1.bias",
184
+ "decoder.mid.block_2.norm1.weight": "blocks.2.norm1.weight",
185
+ "decoder.mid.block_2.norm2.bias": "blocks.2.norm2.bias",
186
+ "decoder.mid.block_2.norm2.weight": "blocks.2.norm2.weight",
187
+ "decoder.norm_out.bias": "conv_norm_out.bias",
188
+ "decoder.norm_out.weight": "conv_norm_out.weight",
189
+ "decoder.up.0.block.0.conv1.bias": "blocks.15.conv1.bias",
190
+ "decoder.up.0.block.0.conv1.weight": "blocks.15.conv1.weight",
191
+ "decoder.up.0.block.0.conv2.bias": "blocks.15.conv2.bias",
192
+ "decoder.up.0.block.0.conv2.weight": "blocks.15.conv2.weight",
193
+ "decoder.up.0.block.0.nin_shortcut.bias": "blocks.15.conv_shortcut.bias",
194
+ "decoder.up.0.block.0.nin_shortcut.weight": "blocks.15.conv_shortcut.weight",
195
+ "decoder.up.0.block.0.norm1.bias": "blocks.15.norm1.bias",
196
+ "decoder.up.0.block.0.norm1.weight": "blocks.15.norm1.weight",
197
+ "decoder.up.0.block.0.norm2.bias": "blocks.15.norm2.bias",
198
+ "decoder.up.0.block.0.norm2.weight": "blocks.15.norm2.weight",
199
+ "decoder.up.0.block.1.conv1.bias": "blocks.16.conv1.bias",
200
+ "decoder.up.0.block.1.conv1.weight": "blocks.16.conv1.weight",
201
+ "decoder.up.0.block.1.conv2.bias": "blocks.16.conv2.bias",
202
+ "decoder.up.0.block.1.conv2.weight": "blocks.16.conv2.weight",
203
+ "decoder.up.0.block.1.norm1.bias": "blocks.16.norm1.bias",
204
+ "decoder.up.0.block.1.norm1.weight": "blocks.16.norm1.weight",
205
+ "decoder.up.0.block.1.norm2.bias": "blocks.16.norm2.bias",
206
+ "decoder.up.0.block.1.norm2.weight": "blocks.16.norm2.weight",
207
+ "decoder.up.0.block.2.conv1.bias": "blocks.17.conv1.bias",
208
+ "decoder.up.0.block.2.conv1.weight": "blocks.17.conv1.weight",
209
+ "decoder.up.0.block.2.conv2.bias": "blocks.17.conv2.bias",
210
+ "decoder.up.0.block.2.conv2.weight": "blocks.17.conv2.weight",
211
+ "decoder.up.0.block.2.norm1.bias": "blocks.17.norm1.bias",
212
+ "decoder.up.0.block.2.norm1.weight": "blocks.17.norm1.weight",
213
+ "decoder.up.0.block.2.norm2.bias": "blocks.17.norm2.bias",
214
+ "decoder.up.0.block.2.norm2.weight": "blocks.17.norm2.weight",
215
+ "decoder.up.1.block.0.conv1.bias": "blocks.11.conv1.bias",
216
+ "decoder.up.1.block.0.conv1.weight": "blocks.11.conv1.weight",
217
+ "decoder.up.1.block.0.conv2.bias": "blocks.11.conv2.bias",
218
+ "decoder.up.1.block.0.conv2.weight": "blocks.11.conv2.weight",
219
+ "decoder.up.1.block.0.nin_shortcut.bias": "blocks.11.conv_shortcut.bias",
220
+ "decoder.up.1.block.0.nin_shortcut.weight": "blocks.11.conv_shortcut.weight",
221
+ "decoder.up.1.block.0.norm1.bias": "blocks.11.norm1.bias",
222
+ "decoder.up.1.block.0.norm1.weight": "blocks.11.norm1.weight",
223
+ "decoder.up.1.block.0.norm2.bias": "blocks.11.norm2.bias",
224
+ "decoder.up.1.block.0.norm2.weight": "blocks.11.norm2.weight",
225
+ "decoder.up.1.block.1.conv1.bias": "blocks.12.conv1.bias",
226
+ "decoder.up.1.block.1.conv1.weight": "blocks.12.conv1.weight",
227
+ "decoder.up.1.block.1.conv2.bias": "blocks.12.conv2.bias",
228
+ "decoder.up.1.block.1.conv2.weight": "blocks.12.conv2.weight",
229
+ "decoder.up.1.block.1.norm1.bias": "blocks.12.norm1.bias",
230
+ "decoder.up.1.block.1.norm1.weight": "blocks.12.norm1.weight",
231
+ "decoder.up.1.block.1.norm2.bias": "blocks.12.norm2.bias",
232
+ "decoder.up.1.block.1.norm2.weight": "blocks.12.norm2.weight",
233
+ "decoder.up.1.block.2.conv1.bias": "blocks.13.conv1.bias",
234
+ "decoder.up.1.block.2.conv1.weight": "blocks.13.conv1.weight",
235
+ "decoder.up.1.block.2.conv2.bias": "blocks.13.conv2.bias",
236
+ "decoder.up.1.block.2.conv2.weight": "blocks.13.conv2.weight",
237
+ "decoder.up.1.block.2.norm1.bias": "blocks.13.norm1.bias",
238
+ "decoder.up.1.block.2.norm1.weight": "blocks.13.norm1.weight",
239
+ "decoder.up.1.block.2.norm2.bias": "blocks.13.norm2.bias",
240
+ "decoder.up.1.block.2.norm2.weight": "blocks.13.norm2.weight",
241
+ "decoder.up.1.upsample.conv.bias": "blocks.14.conv.bias",
242
+ "decoder.up.1.upsample.conv.weight": "blocks.14.conv.weight",
243
+ "decoder.up.2.block.0.conv1.bias": "blocks.7.conv1.bias",
244
+ "decoder.up.2.block.0.conv1.weight": "blocks.7.conv1.weight",
245
+ "decoder.up.2.block.0.conv2.bias": "blocks.7.conv2.bias",
246
+ "decoder.up.2.block.0.conv2.weight": "blocks.7.conv2.weight",
247
+ "decoder.up.2.block.0.norm1.bias": "blocks.7.norm1.bias",
248
+ "decoder.up.2.block.0.norm1.weight": "blocks.7.norm1.weight",
249
+ "decoder.up.2.block.0.norm2.bias": "blocks.7.norm2.bias",
250
+ "decoder.up.2.block.0.norm2.weight": "blocks.7.norm2.weight",
251
+ "decoder.up.2.block.1.conv1.bias": "blocks.8.conv1.bias",
252
+ "decoder.up.2.block.1.conv1.weight": "blocks.8.conv1.weight",
253
+ "decoder.up.2.block.1.conv2.bias": "blocks.8.conv2.bias",
254
+ "decoder.up.2.block.1.conv2.weight": "blocks.8.conv2.weight",
255
+ "decoder.up.2.block.1.norm1.bias": "blocks.8.norm1.bias",
256
+ "decoder.up.2.block.1.norm1.weight": "blocks.8.norm1.weight",
257
+ "decoder.up.2.block.1.norm2.bias": "blocks.8.norm2.bias",
258
+ "decoder.up.2.block.1.norm2.weight": "blocks.8.norm2.weight",
259
+ "decoder.up.2.block.2.conv1.bias": "blocks.9.conv1.bias",
260
+ "decoder.up.2.block.2.conv1.weight": "blocks.9.conv1.weight",
261
+ "decoder.up.2.block.2.conv2.bias": "blocks.9.conv2.bias",
262
+ "decoder.up.2.block.2.conv2.weight": "blocks.9.conv2.weight",
263
+ "decoder.up.2.block.2.norm1.bias": "blocks.9.norm1.bias",
264
+ "decoder.up.2.block.2.norm1.weight": "blocks.9.norm1.weight",
265
+ "decoder.up.2.block.2.norm2.bias": "blocks.9.norm2.bias",
266
+ "decoder.up.2.block.2.norm2.weight": "blocks.9.norm2.weight",
267
+ "decoder.up.2.upsample.conv.bias": "blocks.10.conv.bias",
268
+ "decoder.up.2.upsample.conv.weight": "blocks.10.conv.weight",
269
+ "decoder.up.3.block.0.conv1.bias": "blocks.3.conv1.bias",
270
+ "decoder.up.3.block.0.conv1.weight": "blocks.3.conv1.weight",
271
+ "decoder.up.3.block.0.conv2.bias": "blocks.3.conv2.bias",
272
+ "decoder.up.3.block.0.conv2.weight": "blocks.3.conv2.weight",
273
+ "decoder.up.3.block.0.norm1.bias": "blocks.3.norm1.bias",
274
+ "decoder.up.3.block.0.norm1.weight": "blocks.3.norm1.weight",
275
+ "decoder.up.3.block.0.norm2.bias": "blocks.3.norm2.bias",
276
+ "decoder.up.3.block.0.norm2.weight": "blocks.3.norm2.weight",
277
+ "decoder.up.3.block.1.conv1.bias": "blocks.4.conv1.bias",
278
+ "decoder.up.3.block.1.conv1.weight": "blocks.4.conv1.weight",
279
+ "decoder.up.3.block.1.conv2.bias": "blocks.4.conv2.bias",
280
+ "decoder.up.3.block.1.conv2.weight": "blocks.4.conv2.weight",
281
+ "decoder.up.3.block.1.norm1.bias": "blocks.4.norm1.bias",
282
+ "decoder.up.3.block.1.norm1.weight": "blocks.4.norm1.weight",
283
+ "decoder.up.3.block.1.norm2.bias": "blocks.4.norm2.bias",
284
+ "decoder.up.3.block.1.norm2.weight": "blocks.4.norm2.weight",
285
+ "decoder.up.3.block.2.conv1.bias": "blocks.5.conv1.bias",
286
+ "decoder.up.3.block.2.conv1.weight": "blocks.5.conv1.weight",
287
+ "decoder.up.3.block.2.conv2.bias": "blocks.5.conv2.bias",
288
+ "decoder.up.3.block.2.conv2.weight": "blocks.5.conv2.weight",
289
+ "decoder.up.3.block.2.norm1.bias": "blocks.5.norm1.bias",
290
+ "decoder.up.3.block.2.norm1.weight": "blocks.5.norm1.weight",
291
+ "decoder.up.3.block.2.norm2.bias": "blocks.5.norm2.bias",
292
+ "decoder.up.3.block.2.norm2.weight": "blocks.5.norm2.weight",
293
+ "decoder.up.3.upsample.conv.bias": "blocks.6.conv.bias",
294
+ "decoder.up.3.upsample.conv.weight": "blocks.6.conv.weight",
295
+ }
296
+ state_dict_ = {}
297
+ for name in state_dict:
298
+ if name in rename_dict:
299
+ param = state_dict[name]
300
+ if "transformer_blocks" in rename_dict[name]:
301
+ param = param.squeeze()
302
+ state_dict_[rename_dict[name]] = param
303
+ return state_dict_
flux_value_control.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.models.svd_unet import TemporalTimesteps
3
+
4
+
5
+ class MultiValueEncoder(torch.nn.Module):
6
+ def __init__(self, encoders=()):
7
+ super().__init__()
8
+ self.encoders = torch.nn.ModuleList(encoders)
9
+
10
+ def __call__(self, values, dtype):
11
+ emb = []
12
+ for encoder, value in zip(self.encoders, values):
13
+ if value is not None:
14
+ value = value.unsqueeze(0)
15
+ emb.append(encoder(value, dtype))
16
+ emb = torch.concat(emb, dim=0)
17
+ return emb
18
+
19
+
20
+ class SingleValueEncoder(torch.nn.Module):
21
+ def __init__(self, dim_in=256, dim_out=4096, prefer_len=32, computation_device=None):
22
+ super().__init__()
23
+ self.prefer_len = prefer_len
24
+ self.prefer_proj = TemporalTimesteps(num_channels=dim_in, flip_sin_to_cos=True, downscale_freq_shift=0, computation_device=computation_device)
25
+ self.prefer_value_embedder = torch.nn.Sequential(
26
+ torch.nn.Linear(dim_in, dim_out), torch.nn.SiLU(), torch.nn.Linear(dim_out, dim_out)
27
+ )
28
+ self.positional_embedding = torch.nn.Parameter(
29
+ torch.randn(self.prefer_len, dim_out)
30
+ )
31
+ self._initialize_weights()
32
+
33
+ def _initialize_weights(self):
34
+ last_linear = self.prefer_value_embedder[-1]
35
+ torch.nn.init.zeros_(last_linear.weight)
36
+ torch.nn.init.zeros_(last_linear.bias)
37
+
38
+ def forward(self, value, dtype):
39
+ value = value * 1000
40
+ emb = self.prefer_proj(value).to(dtype)
41
+ emb = self.prefer_value_embedder(emb).squeeze(0)
42
+ base_embeddings = emb.expand(self.prefer_len, -1)
43
+ positional_embedding = self.positional_embedding.to(dtype=base_embeddings.dtype, device=base_embeddings.device)
44
+ learned_embeddings = base_embeddings + positional_embedding
45
+ return learned_embeddings
46
+
47
+ @staticmethod
48
+ def state_dict_converter():
49
+ return SingleValueEncoderStateDictConverter()
50
+
51
+
52
+ class SingleValueEncoderStateDictConverter:
53
+ def __init__(self):
54
+ pass
55
+
56
+ def from_diffusers(self, state_dict):
57
+ return state_dict
58
+
59
+ def from_civitai(self, state_dict):
60
+ return state_dict
hunyuan_dit.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .attention import Attention
2
+ from einops import repeat, rearrange
3
+ import math
4
+ import torch
5
+
6
+
7
+ class HunyuanDiTRotaryEmbedding(torch.nn.Module):
8
+
9
+ def __init__(self, q_norm_shape=88, k_norm_shape=88, rotary_emb_on_k=True):
10
+ super().__init__()
11
+ self.q_norm = torch.nn.LayerNorm((q_norm_shape,), elementwise_affine=True, eps=1e-06)
12
+ self.k_norm = torch.nn.LayerNorm((k_norm_shape,), elementwise_affine=True, eps=1e-06)
13
+ self.rotary_emb_on_k = rotary_emb_on_k
14
+ self.k_cache, self.v_cache = [], []
15
+
16
+ def reshape_for_broadcast(self, freqs_cis, x):
17
+ ndim = x.ndim
18
+ shape = [d if i == ndim - 2 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
19
+ return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape)
20
+
21
+ def rotate_half(self, x):
22
+ x_real, x_imag = x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
23
+ return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
24
+
25
+ def apply_rotary_emb(self, xq, xk, freqs_cis):
26
+ xk_out = None
27
+ cos, sin = self.reshape_for_broadcast(freqs_cis, xq)
28
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
29
+ xq_out = (xq.float() * cos + self.rotate_half(xq.float()) * sin).type_as(xq)
30
+ if xk is not None:
31
+ xk_out = (xk.float() * cos + self.rotate_half(xk.float()) * sin).type_as(xk)
32
+ return xq_out, xk_out
33
+
34
+ def forward(self, q, k, v, freqs_cis_img, to_cache=False):
35
+ # norm
36
+ q = self.q_norm(q)
37
+ k = self.k_norm(k)
38
+
39
+ # RoPE
40
+ if self.rotary_emb_on_k:
41
+ q, k = self.apply_rotary_emb(q, k, freqs_cis_img)
42
+ else:
43
+ q, _ = self.apply_rotary_emb(q, None, freqs_cis_img)
44
+
45
+ if to_cache:
46
+ self.k_cache.append(k)
47
+ self.v_cache.append(v)
48
+ elif len(self.k_cache) > 0 and len(self.v_cache) > 0:
49
+ k = torch.concat([k] + self.k_cache, dim=2)
50
+ v = torch.concat([v] + self.v_cache, dim=2)
51
+ self.k_cache, self.v_cache = [], []
52
+ return q, k, v
53
+
54
+
55
+ class FP32_Layernorm(torch.nn.LayerNorm):
56
+ def forward(self, inputs):
57
+ origin_dtype = inputs.dtype
58
+ return torch.nn.functional.layer_norm(inputs.float(), self.normalized_shape, self.weight.float(), self.bias.float(), self.eps).to(origin_dtype)
59
+
60
+
61
+ class FP32_SiLU(torch.nn.SiLU):
62
+ def forward(self, inputs):
63
+ origin_dtype = inputs.dtype
64
+ return torch.nn.functional.silu(inputs.float(), inplace=False).to(origin_dtype)
65
+
66
+
67
+ class HunyuanDiTFinalLayer(torch.nn.Module):
68
+ def __init__(self, final_hidden_size=1408, condition_dim=1408, patch_size=2, out_channels=8):
69
+ super().__init__()
70
+ self.norm_final = torch.nn.LayerNorm(final_hidden_size, elementwise_affine=False, eps=1e-6)
71
+ self.linear = torch.nn.Linear(final_hidden_size, patch_size * patch_size * out_channels, bias=True)
72
+ self.adaLN_modulation = torch.nn.Sequential(
73
+ FP32_SiLU(),
74
+ torch.nn.Linear(condition_dim, 2 * final_hidden_size, bias=True)
75
+ )
76
+
77
+ def modulate(self, x, shift, scale):
78
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
79
+
80
+ def forward(self, hidden_states, condition_emb):
81
+ shift, scale = self.adaLN_modulation(condition_emb).chunk(2, dim=1)
82
+ hidden_states = self.modulate(self.norm_final(hidden_states), shift, scale)
83
+ hidden_states = self.linear(hidden_states)
84
+ return hidden_states
85
+
86
+
87
+ class HunyuanDiTBlock(torch.nn.Module):
88
+
89
+ def __init__(
90
+ self,
91
+ hidden_dim=1408,
92
+ condition_dim=1408,
93
+ num_heads=16,
94
+ mlp_ratio=4.3637,
95
+ text_dim=1024,
96
+ skip_connection=False
97
+ ):
98
+ super().__init__()
99
+ self.norm1 = FP32_Layernorm((hidden_dim,), eps=1e-6, elementwise_affine=True)
100
+ self.rota1 = HunyuanDiTRotaryEmbedding(hidden_dim//num_heads, hidden_dim//num_heads)
101
+ self.attn1 = Attention(hidden_dim, num_heads, hidden_dim//num_heads, bias_q=True, bias_kv=True, bias_out=True)
102
+ self.norm2 = FP32_Layernorm((hidden_dim,), eps=1e-6, elementwise_affine=True)
103
+ self.rota2 = HunyuanDiTRotaryEmbedding(hidden_dim//num_heads, hidden_dim//num_heads, rotary_emb_on_k=False)
104
+ self.attn2 = Attention(hidden_dim, num_heads, hidden_dim//num_heads, kv_dim=text_dim, bias_q=True, bias_kv=True, bias_out=True)
105
+ self.norm3 = FP32_Layernorm((hidden_dim,), eps=1e-6, elementwise_affine=True)
106
+ self.modulation = torch.nn.Sequential(FP32_SiLU(), torch.nn.Linear(condition_dim, hidden_dim, bias=True))
107
+ self.mlp = torch.nn.Sequential(
108
+ torch.nn.Linear(hidden_dim, int(hidden_dim*mlp_ratio), bias=True),
109
+ torch.nn.GELU(approximate="tanh"),
110
+ torch.nn.Linear(int(hidden_dim*mlp_ratio), hidden_dim, bias=True)
111
+ )
112
+ if skip_connection:
113
+ self.skip_norm = FP32_Layernorm((hidden_dim * 2,), eps=1e-6, elementwise_affine=True)
114
+ self.skip_linear = torch.nn.Linear(hidden_dim * 2, hidden_dim, bias=True)
115
+ else:
116
+ self.skip_norm, self.skip_linear = None, None
117
+
118
+ def forward(self, hidden_states, condition_emb, text_emb, freq_cis_img, residual=None, to_cache=False):
119
+ # Long Skip Connection
120
+ if self.skip_norm is not None and self.skip_linear is not None:
121
+ hidden_states = torch.cat([hidden_states, residual], dim=-1)
122
+ hidden_states = self.skip_norm(hidden_states)
123
+ hidden_states = self.skip_linear(hidden_states)
124
+
125
+ # Self-Attention
126
+ shift_msa = self.modulation(condition_emb).unsqueeze(dim=1)
127
+ attn_input = self.norm1(hidden_states) + shift_msa
128
+ hidden_states = hidden_states + self.attn1(attn_input, qkv_preprocessor=lambda q, k, v: self.rota1(q, k, v, freq_cis_img, to_cache=to_cache))
129
+
130
+ # Cross-Attention
131
+ attn_input = self.norm3(hidden_states)
132
+ hidden_states = hidden_states + self.attn2(attn_input, text_emb, qkv_preprocessor=lambda q, k, v: self.rota2(q, k, v, freq_cis_img))
133
+
134
+ # FFN Layer
135
+ mlp_input = self.norm2(hidden_states)
136
+ hidden_states = hidden_states + self.mlp(mlp_input)
137
+ return hidden_states
138
+
139
+
140
+ class AttentionPool(torch.nn.Module):
141
+ def __init__(self, spacial_dim, embed_dim, num_heads, output_dim = None):
142
+ super().__init__()
143
+ self.positional_embedding = torch.nn.Parameter(torch.randn(spacial_dim + 1, embed_dim) / embed_dim ** 0.5)
144
+ self.k_proj = torch.nn.Linear(embed_dim, embed_dim)
145
+ self.q_proj = torch.nn.Linear(embed_dim, embed_dim)
146
+ self.v_proj = torch.nn.Linear(embed_dim, embed_dim)
147
+ self.c_proj = torch.nn.Linear(embed_dim, output_dim or embed_dim)
148
+ self.num_heads = num_heads
149
+
150
+ def forward(self, x):
151
+ x = x.permute(1, 0, 2) # NLC -> LNC
152
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (L+1)NC
153
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (L+1)NC
154
+ x, _ = torch.nn.functional.multi_head_attention_forward(
155
+ query=x[:1], key=x, value=x,
156
+ embed_dim_to_check=x.shape[-1],
157
+ num_heads=self.num_heads,
158
+ q_proj_weight=self.q_proj.weight,
159
+ k_proj_weight=self.k_proj.weight,
160
+ v_proj_weight=self.v_proj.weight,
161
+ in_proj_weight=None,
162
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
163
+ bias_k=None,
164
+ bias_v=None,
165
+ add_zero_attn=False,
166
+ dropout_p=0,
167
+ out_proj_weight=self.c_proj.weight,
168
+ out_proj_bias=self.c_proj.bias,
169
+ use_separate_proj_weight=True,
170
+ training=self.training,
171
+ need_weights=False
172
+ )
173
+ return x.squeeze(0)
174
+
175
+
176
+ class PatchEmbed(torch.nn.Module):
177
+ def __init__(
178
+ self,
179
+ patch_size=(2, 2),
180
+ in_chans=4,
181
+ embed_dim=1408,
182
+ bias=True,
183
+ ):
184
+ super().__init__()
185
+ self.proj = torch.nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
186
+
187
+ def forward(self, x):
188
+ x = self.proj(x)
189
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
190
+ return x
191
+
192
+
193
+ def timestep_embedding(t, dim, max_period=10000, repeat_only=False):
194
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
195
+ if not repeat_only:
196
+ half = dim // 2
197
+ freqs = torch.exp(
198
+ -math.log(max_period)
199
+ * torch.arange(start=0, end=half, dtype=torch.float32)
200
+ / half
201
+ ).to(device=t.device) # size: [dim/2], 一个指数衰减的曲线
202
+ args = t[:, None].float() * freqs[None]
203
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
204
+ if dim % 2:
205
+ embedding = torch.cat(
206
+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1
207
+ )
208
+ else:
209
+ embedding = repeat(t, "b -> b d", d=dim)
210
+ return embedding
211
+
212
+
213
+ class TimestepEmbedder(torch.nn.Module):
214
+ def __init__(self, hidden_size=1408, frequency_embedding_size=256):
215
+ super().__init__()
216
+ self.mlp = torch.nn.Sequential(
217
+ torch.nn.Linear(frequency_embedding_size, hidden_size, bias=True),
218
+ torch.nn.SiLU(),
219
+ torch.nn.Linear(hidden_size, hidden_size, bias=True),
220
+ )
221
+ self.frequency_embedding_size = frequency_embedding_size
222
+
223
+ def forward(self, t):
224
+ t_freq = timestep_embedding(t, self.frequency_embedding_size).type(self.mlp[0].weight.dtype)
225
+ t_emb = self.mlp(t_freq)
226
+ return t_emb
227
+
228
+
229
+ class HunyuanDiT(torch.nn.Module):
230
+ def __init__(self, num_layers_down=21, num_layers_up=19, in_channels=4, out_channels=8, hidden_dim=1408, text_dim=1024, t5_dim=2048, text_length=77, t5_length=256):
231
+ super().__init__()
232
+
233
+ # Embedders
234
+ self.text_emb_padding = torch.nn.Parameter(torch.randn(text_length + t5_length, text_dim, dtype=torch.float32))
235
+ self.t5_embedder = torch.nn.Sequential(
236
+ torch.nn.Linear(t5_dim, t5_dim * 4, bias=True),
237
+ FP32_SiLU(),
238
+ torch.nn.Linear(t5_dim * 4, text_dim, bias=True),
239
+ )
240
+ self.t5_pooler = AttentionPool(t5_length, t5_dim, num_heads=8, output_dim=1024)
241
+ self.style_embedder = torch.nn.Parameter(torch.randn(hidden_dim))
242
+ self.patch_embedder = PatchEmbed(in_chans=in_channels)
243
+ self.timestep_embedder = TimestepEmbedder()
244
+ self.extra_embedder = torch.nn.Sequential(
245
+ torch.nn.Linear(256 * 6 + 1024 + hidden_dim, hidden_dim * 4),
246
+ FP32_SiLU(),
247
+ torch.nn.Linear(hidden_dim * 4, hidden_dim),
248
+ )
249
+
250
+ # Transformer blocks
251
+ self.num_layers_down = num_layers_down
252
+ self.num_layers_up = num_layers_up
253
+ self.blocks = torch.nn.ModuleList(
254
+ [HunyuanDiTBlock(skip_connection=False) for _ in range(num_layers_down)] + \
255
+ [HunyuanDiTBlock(skip_connection=True) for _ in range(num_layers_up)]
256
+ )
257
+
258
+ # Output layers
259
+ self.final_layer = HunyuanDiTFinalLayer()
260
+ self.out_channels = out_channels
261
+
262
+ def prepare_text_emb(self, text_emb, text_emb_t5, text_emb_mask, text_emb_mask_t5):
263
+ text_emb_mask = text_emb_mask.bool()
264
+ text_emb_mask_t5 = text_emb_mask_t5.bool()
265
+ text_emb_t5 = self.t5_embedder(text_emb_t5)
266
+ text_emb = torch.cat([text_emb, text_emb_t5], dim=1)
267
+ text_emb_mask = torch.cat([text_emb_mask, text_emb_mask_t5], dim=-1)
268
+ text_emb = torch.where(text_emb_mask.unsqueeze(2), text_emb, self.text_emb_padding.to(text_emb))
269
+ return text_emb
270
+
271
+ def prepare_extra_emb(self, text_emb_t5, timestep, size_emb, dtype, batch_size):
272
+ # Text embedding
273
+ pooled_text_emb_t5 = self.t5_pooler(text_emb_t5)
274
+
275
+ # Timestep embedding
276
+ timestep_emb = self.timestep_embedder(timestep)
277
+
278
+ # Size embedding
279
+ size_emb = timestep_embedding(size_emb.view(-1), 256).to(dtype)
280
+ size_emb = size_emb.view(-1, 6 * 256)
281
+
282
+ # Style embedding
283
+ style_emb = repeat(self.style_embedder, "D -> B D", B=batch_size)
284
+
285
+ # Concatenate all extra vectors
286
+ extra_emb = torch.cat([pooled_text_emb_t5, size_emb, style_emb], dim=1)
287
+ condition_emb = timestep_emb + self.extra_embedder(extra_emb)
288
+
289
+ return condition_emb
290
+
291
+ def unpatchify(self, x, h, w):
292
+ return rearrange(x, "B (H W) (P Q C) -> B C (H P) (W Q)", H=h, W=w, P=2, Q=2)
293
+
294
+ def build_mask(self, data, is_bound):
295
+ _, _, H, W = data.shape
296
+ h = repeat(torch.arange(H), "H -> H W", H=H, W=W)
297
+ w = repeat(torch.arange(W), "W -> H W", H=H, W=W)
298
+ border_width = (H + W) // 4
299
+ pad = torch.ones_like(h) * border_width
300
+ mask = torch.stack([
301
+ pad if is_bound[0] else h + 1,
302
+ pad if is_bound[1] else H - h,
303
+ pad if is_bound[2] else w + 1,
304
+ pad if is_bound[3] else W - w
305
+ ]).min(dim=0).values
306
+ mask = mask.clip(1, border_width)
307
+ mask = (mask / border_width).to(dtype=data.dtype, device=data.device)
308
+ mask = rearrange(mask, "H W -> 1 H W")
309
+ return mask
310
+
311
+ def tiled_block_forward(self, block, hidden_states, condition_emb, text_emb, freq_cis_img, residual, torch_dtype, data_device, computation_device, tile_size, tile_stride):
312
+ B, C, H, W = hidden_states.shape
313
+
314
+ weight = torch.zeros((1, 1, H, W), dtype=torch_dtype, device=data_device)
315
+ values = torch.zeros((B, C, H, W), dtype=torch_dtype, device=data_device)
316
+
317
+ # Split tasks
318
+ tasks = []
319
+ for h in range(0, H, tile_stride):
320
+ for w in range(0, W, tile_stride):
321
+ if (h-tile_stride >= 0 and h-tile_stride+tile_size >= H) or (w-tile_stride >= 0 and w-tile_stride+tile_size >= W):
322
+ continue
323
+ h_, w_ = h + tile_size, w + tile_size
324
+ if h_ > H: h, h_ = H - tile_size, H
325
+ if w_ > W: w, w_ = W - tile_size, W
326
+ tasks.append((h, h_, w, w_))
327
+
328
+ # Run
329
+ for hl, hr, wl, wr in tasks:
330
+ hidden_states_batch = hidden_states[:, :, hl:hr, wl:wr].to(computation_device)
331
+ hidden_states_batch = rearrange(hidden_states_batch, "B C H W -> B (H W) C")
332
+ if residual is not None:
333
+ residual_batch = residual[:, :, hl:hr, wl:wr].to(computation_device)
334
+ residual_batch = rearrange(residual_batch, "B C H W -> B (H W) C")
335
+ else:
336
+ residual_batch = None
337
+
338
+ # Forward
339
+ hidden_states_batch = block(hidden_states_batch, condition_emb, text_emb, freq_cis_img, residual_batch).to(data_device)
340
+ hidden_states_batch = rearrange(hidden_states_batch, "B (H W) C -> B C H W", H=hr-hl)
341
+
342
+ mask = self.build_mask(hidden_states_batch, is_bound=(hl==0, hr>=H, wl==0, wr>=W))
343
+ values[:, :, hl:hr, wl:wr] += hidden_states_batch * mask
344
+ weight[:, :, hl:hr, wl:wr] += mask
345
+ values /= weight
346
+ return values
347
+
348
+ def forward(
349
+ self, hidden_states, text_emb, text_emb_t5, text_emb_mask, text_emb_mask_t5, timestep, size_emb, freq_cis_img,
350
+ tiled=False, tile_size=64, tile_stride=32,
351
+ to_cache=False,
352
+ use_gradient_checkpointing=False,
353
+ ):
354
+ # Embeddings
355
+ text_emb = self.prepare_text_emb(text_emb, text_emb_t5, text_emb_mask, text_emb_mask_t5)
356
+ condition_emb = self.prepare_extra_emb(text_emb_t5, timestep, size_emb, hidden_states.dtype, hidden_states.shape[0])
357
+
358
+ # Input
359
+ height, width = hidden_states.shape[-2], hidden_states.shape[-1]
360
+ hidden_states = self.patch_embedder(hidden_states)
361
+
362
+ # Blocks
363
+ def create_custom_forward(module):
364
+ def custom_forward(*inputs):
365
+ return module(*inputs)
366
+ return custom_forward
367
+ if tiled:
368
+ hidden_states = rearrange(hidden_states, "B (H W) C -> B C H W", H=height//2)
369
+ residuals = []
370
+ for block_id, block in enumerate(self.blocks):
371
+ residual = residuals.pop() if block_id >= self.num_layers_down else None
372
+ hidden_states = self.tiled_block_forward(
373
+ block, hidden_states, condition_emb, text_emb, freq_cis_img, residual,
374
+ torch_dtype=hidden_states.dtype, data_device=hidden_states.device, computation_device=hidden_states.device,
375
+ tile_size=tile_size, tile_stride=tile_stride
376
+ )
377
+ if block_id < self.num_layers_down - 2:
378
+ residuals.append(hidden_states)
379
+ hidden_states = rearrange(hidden_states, "B C H W -> B (H W) C")
380
+ else:
381
+ residuals = []
382
+ for block_id, block in enumerate(self.blocks):
383
+ residual = residuals.pop() if block_id >= self.num_layers_down else None
384
+ if self.training and use_gradient_checkpointing:
385
+ hidden_states = torch.utils.checkpoint.checkpoint(
386
+ create_custom_forward(block),
387
+ hidden_states, condition_emb, text_emb, freq_cis_img, residual,
388
+ use_reentrant=False,
389
+ )
390
+ else:
391
+ hidden_states = block(hidden_states, condition_emb, text_emb, freq_cis_img, residual, to_cache=to_cache)
392
+ if block_id < self.num_layers_down - 2:
393
+ residuals.append(hidden_states)
394
+
395
+ # Output
396
+ hidden_states = self.final_layer(hidden_states, condition_emb)
397
+ hidden_states = self.unpatchify(hidden_states, height//2, width//2)
398
+ hidden_states, _ = hidden_states.chunk(2, dim=1)
399
+ return hidden_states
400
+
401
+ @staticmethod
402
+ def state_dict_converter():
403
+ return HunyuanDiTStateDictConverter()
404
+
405
+
406
+
407
+ class HunyuanDiTStateDictConverter():
408
+ def __init__(self):
409
+ pass
410
+
411
+ def from_diffusers(self, state_dict):
412
+ state_dict_ = {}
413
+ for name, param in state_dict.items():
414
+ name_ = name
415
+ name_ = name_.replace(".default_modulation.", ".modulation.")
416
+ name_ = name_.replace(".mlp.fc1.", ".mlp.0.")
417
+ name_ = name_.replace(".mlp.fc2.", ".mlp.2.")
418
+ name_ = name_.replace(".attn1.q_norm.", ".rota1.q_norm.")
419
+ name_ = name_.replace(".attn2.q_norm.", ".rota2.q_norm.")
420
+ name_ = name_.replace(".attn1.k_norm.", ".rota1.k_norm.")
421
+ name_ = name_.replace(".attn2.k_norm.", ".rota2.k_norm.")
422
+ name_ = name_.replace(".q_proj.", ".to_q.")
423
+ name_ = name_.replace(".out_proj.", ".to_out.")
424
+ name_ = name_.replace("text_embedding_padding", "text_emb_padding")
425
+ name_ = name_.replace("mlp_t5.0.", "t5_embedder.0.")
426
+ name_ = name_.replace("mlp_t5.2.", "t5_embedder.2.")
427
+ name_ = name_.replace("pooler.", "t5_pooler.")
428
+ name_ = name_.replace("x_embedder.", "patch_embedder.")
429
+ name_ = name_.replace("t_embedder.", "timestep_embedder.")
430
+ name_ = name_.replace("t5_pooler.to_q.", "t5_pooler.q_proj.")
431
+ name_ = name_.replace("style_embedder.weight", "style_embedder")
432
+ if ".kv_proj." in name_:
433
+ param_k = param[:param.shape[0]//2]
434
+ param_v = param[param.shape[0]//2:]
435
+ state_dict_[name_.replace(".kv_proj.", ".to_k.")] = param_k
436
+ state_dict_[name_.replace(".kv_proj.", ".to_v.")] = param_v
437
+ elif ".Wqkv." in name_:
438
+ param_q = param[:param.shape[0]//3]
439
+ param_k = param[param.shape[0]//3:param.shape[0]//3*2]
440
+ param_v = param[param.shape[0]//3*2:]
441
+ state_dict_[name_.replace(".Wqkv.", ".to_q.")] = param_q
442
+ state_dict_[name_.replace(".Wqkv.", ".to_k.")] = param_k
443
+ state_dict_[name_.replace(".Wqkv.", ".to_v.")] = param_v
444
+ elif "style_embedder" in name_:
445
+ state_dict_[name_] = param.squeeze()
446
+ else:
447
+ state_dict_[name_] = param
448
+ return state_dict_
449
+
450
+ def from_civitai(self, state_dict):
451
+ return self.from_diffusers(state_dict)
hunyuan_dit_text_encoder.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import BertModel, BertConfig, T5EncoderModel, T5Config
2
+ import torch
3
+
4
+
5
+
6
+ class HunyuanDiTCLIPTextEncoder(BertModel):
7
+ def __init__(self):
8
+ config = BertConfig(
9
+ _name_or_path = "",
10
+ architectures = ["BertModel"],
11
+ attention_probs_dropout_prob = 0.1,
12
+ bos_token_id = 0,
13
+ classifier_dropout = None,
14
+ directionality = "bidi",
15
+ eos_token_id = 2,
16
+ hidden_act = "gelu",
17
+ hidden_dropout_prob = 0.1,
18
+ hidden_size = 1024,
19
+ initializer_range = 0.02,
20
+ intermediate_size = 4096,
21
+ layer_norm_eps = 1e-12,
22
+ max_position_embeddings = 512,
23
+ model_type = "bert",
24
+ num_attention_heads = 16,
25
+ num_hidden_layers = 24,
26
+ output_past = True,
27
+ pad_token_id = 0,
28
+ pooler_fc_size = 768,
29
+ pooler_num_attention_heads = 12,
30
+ pooler_num_fc_layers = 3,
31
+ pooler_size_per_head = 128,
32
+ pooler_type = "first_token_transform",
33
+ position_embedding_type = "absolute",
34
+ torch_dtype = "float32",
35
+ transformers_version = "4.37.2",
36
+ type_vocab_size = 2,
37
+ use_cache = True,
38
+ vocab_size = 47020
39
+ )
40
+ super().__init__(config, add_pooling_layer=False)
41
+ self.eval()
42
+
43
+ def forward(self, input_ids, attention_mask, clip_skip=1):
44
+ input_shape = input_ids.size()
45
+
46
+ batch_size, seq_length = input_shape
47
+ device = input_ids.device
48
+
49
+ past_key_values_length = 0
50
+
51
+ if attention_mask is None:
52
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
53
+
54
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
55
+
56
+ embedding_output = self.embeddings(
57
+ input_ids=input_ids,
58
+ position_ids=None,
59
+ token_type_ids=None,
60
+ inputs_embeds=None,
61
+ past_key_values_length=0,
62
+ )
63
+ encoder_outputs = self.encoder(
64
+ embedding_output,
65
+ attention_mask=extended_attention_mask,
66
+ head_mask=None,
67
+ encoder_hidden_states=None,
68
+ encoder_attention_mask=None,
69
+ past_key_values=None,
70
+ use_cache=False,
71
+ output_attentions=False,
72
+ output_hidden_states=True,
73
+ return_dict=True,
74
+ )
75
+ all_hidden_states = encoder_outputs.hidden_states
76
+ prompt_emb = all_hidden_states[-clip_skip]
77
+ if clip_skip > 1:
78
+ mean, std = all_hidden_states[-1].mean(), all_hidden_states[-1].std()
79
+ prompt_emb = (prompt_emb - prompt_emb.mean()) / prompt_emb.std() * std + mean
80
+ return prompt_emb
81
+
82
+ @staticmethod
83
+ def state_dict_converter():
84
+ return HunyuanDiTCLIPTextEncoderStateDictConverter()
85
+
86
+
87
+
88
+ class HunyuanDiTT5TextEncoder(T5EncoderModel):
89
+ def __init__(self):
90
+ config = T5Config(
91
+ _name_or_path = "../HunyuanDiT/t2i/mt5",
92
+ architectures = ["MT5ForConditionalGeneration"],
93
+ classifier_dropout = 0.0,
94
+ d_ff = 5120,
95
+ d_kv = 64,
96
+ d_model = 2048,
97
+ decoder_start_token_id = 0,
98
+ dense_act_fn = "gelu_new",
99
+ dropout_rate = 0.1,
100
+ eos_token_id = 1,
101
+ feed_forward_proj = "gated-gelu",
102
+ initializer_factor = 1.0,
103
+ is_encoder_decoder = True,
104
+ is_gated_act = True,
105
+ layer_norm_epsilon = 1e-06,
106
+ model_type = "t5",
107
+ num_decoder_layers = 24,
108
+ num_heads = 32,
109
+ num_layers = 24,
110
+ output_past = True,
111
+ pad_token_id = 0,
112
+ relative_attention_max_distance = 128,
113
+ relative_attention_num_buckets = 32,
114
+ tie_word_embeddings = False,
115
+ tokenizer_class = "T5Tokenizer",
116
+ transformers_version = "4.37.2",
117
+ use_cache = True,
118
+ vocab_size = 250112
119
+ )
120
+ super().__init__(config)
121
+ self.eval()
122
+
123
+ def forward(self, input_ids, attention_mask, clip_skip=1):
124
+ outputs = super().forward(
125
+ input_ids=input_ids,
126
+ attention_mask=attention_mask,
127
+ output_hidden_states=True,
128
+ )
129
+ prompt_emb = outputs.hidden_states[-clip_skip]
130
+ if clip_skip > 1:
131
+ mean, std = outputs.hidden_states[-1].mean(), outputs.hidden_states[-1].std()
132
+ prompt_emb = (prompt_emb - prompt_emb.mean()) / prompt_emb.std() * std + mean
133
+ return prompt_emb
134
+
135
+ @staticmethod
136
+ def state_dict_converter():
137
+ return HunyuanDiTT5TextEncoderStateDictConverter()
138
+
139
+
140
+
141
+ class HunyuanDiTCLIPTextEncoderStateDictConverter():
142
+ def __init__(self):
143
+ pass
144
+
145
+ def from_diffusers(self, state_dict):
146
+ state_dict_ = {name[5:]: param for name, param in state_dict.items() if name.startswith("bert.")}
147
+ return state_dict_
148
+
149
+ def from_civitai(self, state_dict):
150
+ return self.from_diffusers(state_dict)
151
+
152
+
153
+ class HunyuanDiTT5TextEncoderStateDictConverter():
154
+ def __init__(self):
155
+ pass
156
+
157
+ def from_diffusers(self, state_dict):
158
+ state_dict_ = {name: param for name, param in state_dict.items() if name.startswith("encoder.")}
159
+ state_dict_["shared.weight"] = state_dict["shared.weight"]
160
+ return state_dict_
161
+
162
+ def from_civitai(self, state_dict):
163
+ return self.from_diffusers(state_dict)
hunyuan_video_dit.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd3_dit import TimestepEmbeddings, RMSNorm
3
+ from .utils import init_weights_on_device
4
+ from einops import rearrange, repeat
5
+ from tqdm import tqdm
6
+ from typing import Union, Tuple, List
7
+ from .utils import hash_state_dict_keys
8
+
9
+
10
+ def HunyuanVideoRope(latents):
11
+ def _to_tuple(x, dim=2):
12
+ if isinstance(x, int):
13
+ return (x,) * dim
14
+ elif len(x) == dim:
15
+ return x
16
+ else:
17
+ raise ValueError(f"Expected length {dim} or int, but got {x}")
18
+
19
+
20
+ def get_meshgrid_nd(start, *args, dim=2):
21
+ """
22
+ Get n-D meshgrid with start, stop and num.
23
+
24
+ Args:
25
+ start (int or tuple): If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop,
26
+ step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num. For n-dim, start/stop/num
27
+ should be int or n-tuple. If n-tuple is provided, the meshgrid will be stacked following the dim order in
28
+ n-tuples.
29
+ *args: See above.
30
+ dim (int): Dimension of the meshgrid. Defaults to 2.
31
+
32
+ Returns:
33
+ grid (np.ndarray): [dim, ...]
34
+ """
35
+ if len(args) == 0:
36
+ # start is grid_size
37
+ num = _to_tuple(start, dim=dim)
38
+ start = (0,) * dim
39
+ stop = num
40
+ elif len(args) == 1:
41
+ # start is start, args[0] is stop, step is 1
42
+ start = _to_tuple(start, dim=dim)
43
+ stop = _to_tuple(args[0], dim=dim)
44
+ num = [stop[i] - start[i] for i in range(dim)]
45
+ elif len(args) == 2:
46
+ # start is start, args[0] is stop, args[1] is num
47
+ start = _to_tuple(start, dim=dim) # Left-Top eg: 12,0
48
+ stop = _to_tuple(args[0], dim=dim) # Right-Bottom eg: 20,32
49
+ num = _to_tuple(args[1], dim=dim) # Target Size eg: 32,124
50
+ else:
51
+ raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
52
+
53
+ # PyTorch implement of np.linspace(start[i], stop[i], num[i], endpoint=False)
54
+ axis_grid = []
55
+ for i in range(dim):
56
+ a, b, n = start[i], stop[i], num[i]
57
+ g = torch.linspace(a, b, n + 1, dtype=torch.float32)[:n]
58
+ axis_grid.append(g)
59
+ grid = torch.meshgrid(*axis_grid, indexing="ij") # dim x [W, H, D]
60
+ grid = torch.stack(grid, dim=0) # [dim, W, H, D]
61
+
62
+ return grid
63
+
64
+
65
+ def get_1d_rotary_pos_embed(
66
+ dim: int,
67
+ pos: Union[torch.FloatTensor, int],
68
+ theta: float = 10000.0,
69
+ use_real: bool = False,
70
+ theta_rescale_factor: float = 1.0,
71
+ interpolation_factor: float = 1.0,
72
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
73
+ """
74
+ Precompute the frequency tensor for complex exponential (cis) with given dimensions.
75
+ (Note: `cis` means `cos + i * sin`, where i is the imaginary unit.)
76
+
77
+ This function calculates a frequency tensor with complex exponential using the given dimension 'dim'
78
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
79
+ The returned tensor contains complex values in complex64 data type.
80
+
81
+ Args:
82
+ dim (int): Dimension of the frequency tensor.
83
+ pos (int or torch.FloatTensor): Position indices for the frequency tensor. [S] or scalar
84
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
85
+ use_real (bool, optional): If True, return real part and imaginary part separately.
86
+ Otherwise, return complex numbers.
87
+ theta_rescale_factor (float, optional): Rescale factor for theta. Defaults to 1.0.
88
+
89
+ Returns:
90
+ freqs_cis: Precomputed frequency tensor with complex exponential. [S, D/2]
91
+ freqs_cos, freqs_sin: Precomputed frequency tensor with real and imaginary parts separately. [S, D]
92
+ """
93
+ if isinstance(pos, int):
94
+ pos = torch.arange(pos).float()
95
+
96
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
97
+ # has some connection to NTK literature
98
+ if theta_rescale_factor != 1.0:
99
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
100
+
101
+ freqs = 1.0 / (
102
+ theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
103
+ ) # [D/2]
104
+ # assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}"
105
+ freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2]
106
+ if use_real:
107
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
108
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
109
+ return freqs_cos, freqs_sin
110
+ else:
111
+ freqs_cis = torch.polar(
112
+ torch.ones_like(freqs), freqs
113
+ ) # complex64 # [S, D/2]
114
+ return freqs_cis
115
+
116
+
117
+ def get_nd_rotary_pos_embed(
118
+ rope_dim_list,
119
+ start,
120
+ *args,
121
+ theta=10000.0,
122
+ use_real=False,
123
+ theta_rescale_factor: Union[float, List[float]] = 1.0,
124
+ interpolation_factor: Union[float, List[float]] = 1.0,
125
+ ):
126
+ """
127
+ This is a n-d version of precompute_freqs_cis, which is a RoPE for tokens with n-d structure.
128
+
129
+ Args:
130
+ rope_dim_list (list of int): Dimension of each rope. len(rope_dim_list) should equal to n.
131
+ sum(rope_dim_list) should equal to head_dim of attention layer.
132
+ start (int | tuple of int | list of int): If len(args) == 0, start is num; If len(args) == 1, start is start,
133
+ args[0] is stop, step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num.
134
+ *args: See above.
135
+ theta (float): Scaling factor for frequency computation. Defaults to 10000.0.
136
+ use_real (bool): If True, return real part and imaginary part separately. Otherwise, return complex numbers.
137
+ Some libraries such as TensorRT does not support complex64 data type. So it is useful to provide a real
138
+ part and an imaginary part separately.
139
+ theta_rescale_factor (float): Rescale factor for theta. Defaults to 1.0.
140
+
141
+ Returns:
142
+ pos_embed (torch.Tensor): [HW, D/2]
143
+ """
144
+
145
+ grid = get_meshgrid_nd(
146
+ start, *args, dim=len(rope_dim_list)
147
+ ) # [3, W, H, D] / [2, W, H]
148
+
149
+ if isinstance(theta_rescale_factor, int) or isinstance(theta_rescale_factor, float):
150
+ theta_rescale_factor = [theta_rescale_factor] * len(rope_dim_list)
151
+ elif isinstance(theta_rescale_factor, list) and len(theta_rescale_factor) == 1:
152
+ theta_rescale_factor = [theta_rescale_factor[0]] * len(rope_dim_list)
153
+ assert len(theta_rescale_factor) == len(
154
+ rope_dim_list
155
+ ), "len(theta_rescale_factor) should equal to len(rope_dim_list)"
156
+
157
+ if isinstance(interpolation_factor, int) or isinstance(interpolation_factor, float):
158
+ interpolation_factor = [interpolation_factor] * len(rope_dim_list)
159
+ elif isinstance(interpolation_factor, list) and len(interpolation_factor) == 1:
160
+ interpolation_factor = [interpolation_factor[0]] * len(rope_dim_list)
161
+ assert len(interpolation_factor) == len(
162
+ rope_dim_list
163
+ ), "len(interpolation_factor) should equal to len(rope_dim_list)"
164
+
165
+ # use 1/ndim of dimensions to encode grid_axis
166
+ embs = []
167
+ for i in range(len(rope_dim_list)):
168
+ emb = get_1d_rotary_pos_embed(
169
+ rope_dim_list[i],
170
+ grid[i].reshape(-1),
171
+ theta,
172
+ use_real=use_real,
173
+ theta_rescale_factor=theta_rescale_factor[i],
174
+ interpolation_factor=interpolation_factor[i],
175
+ ) # 2 x [WHD, rope_dim_list[i]]
176
+ embs.append(emb)
177
+
178
+ if use_real:
179
+ cos = torch.cat([emb[0] for emb in embs], dim=1) # (WHD, D/2)
180
+ sin = torch.cat([emb[1] for emb in embs], dim=1) # (WHD, D/2)
181
+ return cos, sin
182
+ else:
183
+ emb = torch.cat(embs, dim=1) # (WHD, D/2)
184
+ return emb
185
+
186
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
187
+ [16, 56, 56],
188
+ [latents.shape[2], latents.shape[3] // 2, latents.shape[4] // 2],
189
+ theta=256,
190
+ use_real=True,
191
+ theta_rescale_factor=1,
192
+ )
193
+ return freqs_cos, freqs_sin
194
+
195
+
196
+ class PatchEmbed(torch.nn.Module):
197
+ def __init__(self, patch_size=(1, 2, 2), in_channels=16, embed_dim=3072):
198
+ super().__init__()
199
+ self.proj = torch.nn.Conv3d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
200
+
201
+ def forward(self, x):
202
+ x = self.proj(x)
203
+ x = x.flatten(2).transpose(1, 2)
204
+ return x
205
+
206
+
207
+ class IndividualTokenRefinerBlock(torch.nn.Module):
208
+ def __init__(self, hidden_size=3072, num_heads=24):
209
+ super().__init__()
210
+ self.num_heads = num_heads
211
+ self.norm1 = torch.nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
212
+ self.self_attn_qkv = torch.nn.Linear(hidden_size, hidden_size * 3)
213
+ self.self_attn_proj = torch.nn.Linear(hidden_size, hidden_size)
214
+
215
+ self.norm2 = torch.nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
216
+ self.mlp = torch.nn.Sequential(
217
+ torch.nn.Linear(hidden_size, hidden_size * 4),
218
+ torch.nn.SiLU(),
219
+ torch.nn.Linear(hidden_size * 4, hidden_size)
220
+ )
221
+ self.adaLN_modulation = torch.nn.Sequential(
222
+ torch.nn.SiLU(),
223
+ torch.nn.Linear(hidden_size, hidden_size * 2, device="cuda", dtype=torch.bfloat16),
224
+ )
225
+
226
+ def forward(self, x, c, attn_mask=None):
227
+ gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=1)
228
+
229
+ norm_x = self.norm1(x)
230
+ qkv = self.self_attn_qkv(norm_x)
231
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads)
232
+
233
+ attn = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
234
+ attn = rearrange(attn, "B H L D -> B L (H D)")
235
+
236
+ x = x + self.self_attn_proj(attn) * gate_msa.unsqueeze(1)
237
+ x = x + self.mlp(self.norm2(x)) * gate_mlp.unsqueeze(1)
238
+
239
+ return x
240
+
241
+
242
+ class SingleTokenRefiner(torch.nn.Module):
243
+ def __init__(self, in_channels=4096, hidden_size=3072, depth=2):
244
+ super().__init__()
245
+ self.input_embedder = torch.nn.Linear(in_channels, hidden_size, bias=True)
246
+ self.t_embedder = TimestepEmbeddings(256, hidden_size, computation_device="cpu")
247
+ self.c_embedder = torch.nn.Sequential(
248
+ torch.nn.Linear(in_channels, hidden_size),
249
+ torch.nn.SiLU(),
250
+ torch.nn.Linear(hidden_size, hidden_size)
251
+ )
252
+ self.blocks = torch.nn.ModuleList([IndividualTokenRefinerBlock(hidden_size=hidden_size) for _ in range(depth)])
253
+
254
+ def forward(self, x, t, mask=None):
255
+ timestep_aware_representations = self.t_embedder(t, dtype=torch.float32)
256
+
257
+ mask_float = mask.float().unsqueeze(-1)
258
+ context_aware_representations = (x * mask_float).sum(dim=1) / mask_float.sum(dim=1)
259
+ context_aware_representations = self.c_embedder(context_aware_representations)
260
+ c = timestep_aware_representations + context_aware_representations
261
+
262
+ x = self.input_embedder(x)
263
+
264
+ mask = mask.to(device=x.device, dtype=torch.bool)
265
+ mask = repeat(mask, "B L -> B 1 D L", D=mask.shape[-1])
266
+ mask = mask & mask.transpose(2, 3)
267
+ mask[:, :, :, 0] = True
268
+
269
+ for block in self.blocks:
270
+ x = block(x, c, mask)
271
+
272
+ return x
273
+
274
+
275
+ class ModulateDiT(torch.nn.Module):
276
+ def __init__(self, hidden_size, factor=6):
277
+ super().__init__()
278
+ self.act = torch.nn.SiLU()
279
+ self.linear = torch.nn.Linear(hidden_size, factor * hidden_size)
280
+
281
+ def forward(self, x):
282
+ return self.linear(self.act(x))
283
+
284
+
285
+ def modulate(x, shift=None, scale=None, tr_shift=None, tr_scale=None, tr_token=None):
286
+ if tr_shift is not None:
287
+ x_zero = x[:, :tr_token] * (1 + tr_scale.unsqueeze(1)) + tr_shift.unsqueeze(1)
288
+ x_orig = x[:, tr_token:] * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
289
+ x = torch.concat((x_zero, x_orig), dim=1)
290
+ return x
291
+ if scale is None and shift is None:
292
+ return x
293
+ elif shift is None:
294
+ return x * (1 + scale.unsqueeze(1))
295
+ elif scale is None:
296
+ return x + shift.unsqueeze(1)
297
+ else:
298
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
299
+
300
+
301
+ def reshape_for_broadcast(
302
+ freqs_cis,
303
+ x: torch.Tensor,
304
+ head_first=False,
305
+ ):
306
+ ndim = x.ndim
307
+ assert 0 <= 1 < ndim
308
+
309
+ if isinstance(freqs_cis, tuple):
310
+ # freqs_cis: (cos, sin) in real space
311
+ if head_first:
312
+ assert freqs_cis[0].shape == (
313
+ x.shape[-2],
314
+ x.shape[-1],
315
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
316
+ shape = [
317
+ d if i == ndim - 2 or i == ndim - 1 else 1
318
+ for i, d in enumerate(x.shape)
319
+ ]
320
+ else:
321
+ assert freqs_cis[0].shape == (
322
+ x.shape[1],
323
+ x.shape[-1],
324
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
325
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
326
+ return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape)
327
+ else:
328
+ # freqs_cis: values in complex space
329
+ if head_first:
330
+ assert freqs_cis.shape == (
331
+ x.shape[-2],
332
+ x.shape[-1],
333
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
334
+ shape = [
335
+ d if i == ndim - 2 or i == ndim - 1 else 1
336
+ for i, d in enumerate(x.shape)
337
+ ]
338
+ else:
339
+ assert freqs_cis.shape == (
340
+ x.shape[1],
341
+ x.shape[-1],
342
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
343
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
344
+ return freqs_cis.view(*shape)
345
+
346
+
347
+ def rotate_half(x):
348
+ x_real, x_imag = (
349
+ x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
350
+ ) # [B, S, H, D//2]
351
+ return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
352
+
353
+
354
+ def apply_rotary_emb(
355
+ xq: torch.Tensor,
356
+ xk: torch.Tensor,
357
+ freqs_cis,
358
+ head_first: bool = False,
359
+ ):
360
+ xk_out = None
361
+ if isinstance(freqs_cis, tuple):
362
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
363
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
364
+ # real * cos - imag * sin
365
+ # imag * cos + real * sin
366
+ xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq)
367
+ xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk)
368
+ else:
369
+ # view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex)
370
+ xq_ = torch.view_as_complex(
371
+ xq.float().reshape(*xq.shape[:-1], -1, 2)
372
+ ) # [B, S, H, D//2]
373
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(
374
+ xq.device
375
+ ) # [S, D//2] --> [1, S, 1, D//2]
376
+ # (real, imag) * (cos, sin) = (real * cos - imag * sin, imag * cos + real * sin)
377
+ # view_as_real will expand [..., D/2](complex) to [..., D/2, 2](real)
378
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq)
379
+ xk_ = torch.view_as_complex(
380
+ xk.float().reshape(*xk.shape[:-1], -1, 2)
381
+ ) # [B, S, H, D//2]
382
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
383
+
384
+ return xq_out, xk_out
385
+
386
+
387
+ def attention(q, k, v):
388
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
389
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
390
+ x = x.transpose(1, 2).flatten(2, 3)
391
+ return x
392
+
393
+
394
+ def apply_gate(x, gate, tr_gate=None, tr_token=None):
395
+ if tr_gate is not None:
396
+ x_zero = x[:, :tr_token] * tr_gate.unsqueeze(1)
397
+ x_orig = x[:, tr_token:] * gate.unsqueeze(1)
398
+ return torch.concat((x_zero, x_orig), dim=1)
399
+ else:
400
+ return x * gate.unsqueeze(1)
401
+
402
+
403
+ class MMDoubleStreamBlockComponent(torch.nn.Module):
404
+ def __init__(self, hidden_size=3072, heads_num=24, mlp_width_ratio=4):
405
+ super().__init__()
406
+ self.heads_num = heads_num
407
+
408
+ self.mod = ModulateDiT(hidden_size)
409
+ self.norm1 = torch.nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
410
+
411
+ self.to_qkv = torch.nn.Linear(hidden_size, hidden_size * 3)
412
+ self.norm_q = RMSNorm(dim=hidden_size // heads_num, eps=1e-6)
413
+ self.norm_k = RMSNorm(dim=hidden_size // heads_num, eps=1e-6)
414
+ self.to_out = torch.nn.Linear(hidden_size, hidden_size)
415
+
416
+ self.norm2 = torch.nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
417
+ self.ff = torch.nn.Sequential(
418
+ torch.nn.Linear(hidden_size, hidden_size * mlp_width_ratio),
419
+ torch.nn.GELU(approximate="tanh"),
420
+ torch.nn.Linear(hidden_size * mlp_width_ratio, hidden_size)
421
+ )
422
+
423
+ def forward(self, hidden_states, conditioning, freqs_cis=None, token_replace_vec=None, tr_token=None):
424
+ mod1_shift, mod1_scale, mod1_gate, mod2_shift, mod2_scale, mod2_gate = self.mod(conditioning).chunk(6, dim=-1)
425
+ if token_replace_vec is not None:
426
+ assert tr_token is not None
427
+ tr_mod1_shift, tr_mod1_scale, tr_mod1_gate, tr_mod2_shift, tr_mod2_scale, tr_mod2_gate = self.mod(token_replace_vec).chunk(6, dim=-1)
428
+ else:
429
+ tr_mod1_shift, tr_mod1_scale, tr_mod1_gate, tr_mod2_shift, tr_mod2_scale, tr_mod2_gate = None, None, None, None, None, None
430
+
431
+ norm_hidden_states = self.norm1(hidden_states)
432
+ norm_hidden_states = modulate(norm_hidden_states, shift=mod1_shift, scale=mod1_scale,
433
+ tr_shift=tr_mod1_shift, tr_scale=tr_mod1_scale, tr_token=tr_token)
434
+ qkv = self.to_qkv(norm_hidden_states)
435
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
436
+
437
+ q = self.norm_q(q)
438
+ k = self.norm_k(k)
439
+
440
+ if freqs_cis is not None:
441
+ q, k = apply_rotary_emb(q, k, freqs_cis, head_first=False)
442
+ return (q, k, v), (mod1_gate, mod2_shift, mod2_scale, mod2_gate), (tr_mod1_gate, tr_mod2_shift, tr_mod2_scale, tr_mod2_gate)
443
+
444
+ def process_ff(self, hidden_states, attn_output, mod, mod_tr=None, tr_token=None):
445
+ mod1_gate, mod2_shift, mod2_scale, mod2_gate = mod
446
+ if mod_tr is not None:
447
+ tr_mod1_gate, tr_mod2_shift, tr_mod2_scale, tr_mod2_gate = mod_tr
448
+ else:
449
+ tr_mod1_gate, tr_mod2_shift, tr_mod2_scale, tr_mod2_gate = None, None, None, None
450
+ hidden_states = hidden_states + apply_gate(self.to_out(attn_output), mod1_gate, tr_mod1_gate, tr_token)
451
+ x = self.ff(modulate(self.norm2(hidden_states), shift=mod2_shift, scale=mod2_scale, tr_shift=tr_mod2_shift, tr_scale=tr_mod2_scale, tr_token=tr_token))
452
+ hidden_states = hidden_states + apply_gate(x, mod2_gate, tr_mod2_gate, tr_token)
453
+ return hidden_states
454
+
455
+
456
+ class MMDoubleStreamBlock(torch.nn.Module):
457
+ def __init__(self, hidden_size=3072, heads_num=24, mlp_width_ratio=4):
458
+ super().__init__()
459
+ self.component_a = MMDoubleStreamBlockComponent(hidden_size, heads_num, mlp_width_ratio)
460
+ self.component_b = MMDoubleStreamBlockComponent(hidden_size, heads_num, mlp_width_ratio)
461
+
462
+ def forward(self, hidden_states_a, hidden_states_b, conditioning, freqs_cis, token_replace_vec=None, tr_token=None, split_token=71):
463
+ (q_a, k_a, v_a), mod_a, mod_tr = self.component_a(hidden_states_a, conditioning, freqs_cis, token_replace_vec, tr_token)
464
+ (q_b, k_b, v_b), mod_b, _ = self.component_b(hidden_states_b, conditioning, freqs_cis=None)
465
+
466
+ q_a, q_b = torch.concat([q_a, q_b[:, :split_token]], dim=1), q_b[:, split_token:].contiguous()
467
+ k_a, k_b = torch.concat([k_a, k_b[:, :split_token]], dim=1), k_b[:, split_token:].contiguous()
468
+ v_a, v_b = torch.concat([v_a, v_b[:, :split_token]], dim=1), v_b[:, split_token:].contiguous()
469
+ attn_output_a = attention(q_a, k_a, v_a)
470
+ attn_output_b = attention(q_b, k_b, v_b)
471
+ attn_output_a, attn_output_b = attn_output_a[:, :-split_token].contiguous(), torch.concat([attn_output_a[:, -split_token:], attn_output_b], dim=1)
472
+
473
+ hidden_states_a = self.component_a.process_ff(hidden_states_a, attn_output_a, mod_a, mod_tr, tr_token)
474
+ hidden_states_b = self.component_b.process_ff(hidden_states_b, attn_output_b, mod_b)
475
+ return hidden_states_a, hidden_states_b
476
+
477
+
478
+ class MMSingleStreamBlockOriginal(torch.nn.Module):
479
+ def __init__(self, hidden_size=3072, heads_num=24, mlp_width_ratio=4):
480
+ super().__init__()
481
+ self.hidden_size = hidden_size
482
+ self.heads_num = heads_num
483
+ self.mlp_hidden_dim = hidden_size * mlp_width_ratio
484
+
485
+ self.linear1 = torch.nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)
486
+ self.linear2 = torch.nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)
487
+
488
+ self.q_norm = RMSNorm(dim=hidden_size // heads_num, eps=1e-6)
489
+ self.k_norm = RMSNorm(dim=hidden_size // heads_num, eps=1e-6)
490
+
491
+ self.pre_norm = torch.nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
492
+
493
+ self.mlp_act = torch.nn.GELU(approximate="tanh")
494
+ self.modulation = ModulateDiT(hidden_size, factor=3)
495
+
496
+ def forward(self, x, vec, freqs_cis=None, txt_len=256):
497
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
498
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
499
+ qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
500
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
501
+ q = self.q_norm(q)
502
+ k = self.k_norm(k)
503
+
504
+ q_a, q_b = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
505
+ k_a, k_b = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
506
+ q_a, k_a = apply_rotary_emb(q_a, k_a, freqs_cis, head_first=False)
507
+ q = torch.cat((q_a, q_b), dim=1)
508
+ k = torch.cat((k_a, k_b), dim=1)
509
+
510
+ attn_output_a = attention(q[:, :-185].contiguous(), k[:, :-185].contiguous(), v[:, :-185].contiguous())
511
+ attn_output_b = attention(q[:, -185:].contiguous(), k[:, -185:].contiguous(), v[:, -185:].contiguous())
512
+ attn_output = torch.concat([attn_output_a, attn_output_b], dim=1)
513
+
514
+ output = self.linear2(torch.cat((attn_output, self.mlp_act(mlp)), 2))
515
+ return x + output * mod_gate.unsqueeze(1)
516
+
517
+
518
+ class MMSingleStreamBlock(torch.nn.Module):
519
+ def __init__(self, hidden_size=3072, heads_num=24, mlp_width_ratio=4):
520
+ super().__init__()
521
+ self.heads_num = heads_num
522
+
523
+ self.mod = ModulateDiT(hidden_size, factor=3)
524
+ self.norm = torch.nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
525
+
526
+ self.to_qkv = torch.nn.Linear(hidden_size, hidden_size * 3)
527
+ self.norm_q = RMSNorm(dim=hidden_size // heads_num, eps=1e-6)
528
+ self.norm_k = RMSNorm(dim=hidden_size // heads_num, eps=1e-6)
529
+ self.to_out = torch.nn.Linear(hidden_size, hidden_size)
530
+
531
+ self.ff = torch.nn.Sequential(
532
+ torch.nn.Linear(hidden_size, hidden_size * mlp_width_ratio),
533
+ torch.nn.GELU(approximate="tanh"),
534
+ torch.nn.Linear(hidden_size * mlp_width_ratio, hidden_size, bias=False)
535
+ )
536
+
537
+ def forward(self, hidden_states, conditioning, freqs_cis=None, txt_len=256, token_replace_vec=None, tr_token=None, split_token=71):
538
+ mod_shift, mod_scale, mod_gate = self.mod(conditioning).chunk(3, dim=-1)
539
+ if token_replace_vec is not None:
540
+ assert tr_token is not None
541
+ tr_mod_shift, tr_mod_scale, tr_mod_gate = self.mod(token_replace_vec).chunk(3, dim=-1)
542
+ else:
543
+ tr_mod_shift, tr_mod_scale, tr_mod_gate = None, None, None
544
+
545
+ norm_hidden_states = self.norm(hidden_states)
546
+ norm_hidden_states = modulate(norm_hidden_states, shift=mod_shift, scale=mod_scale,
547
+ tr_shift=tr_mod_shift, tr_scale=tr_mod_scale, tr_token=tr_token)
548
+ qkv = self.to_qkv(norm_hidden_states)
549
+
550
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
551
+
552
+ q = self.norm_q(q)
553
+ k = self.norm_k(k)
554
+
555
+ q_a, q_b = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
556
+ k_a, k_b = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
557
+ q_a, k_a = apply_rotary_emb(q_a, k_a, freqs_cis, head_first=False)
558
+
559
+ v_len = txt_len - split_token
560
+ q_a, q_b = torch.concat([q_a, q_b[:, :split_token]], dim=1), q_b[:, split_token:].contiguous()
561
+ k_a, k_b = torch.concat([k_a, k_b[:, :split_token]], dim=1), k_b[:, split_token:].contiguous()
562
+ v_a, v_b = v[:, :-v_len].contiguous(), v[:, -v_len:].contiguous()
563
+
564
+ attn_output_a = attention(q_a, k_a, v_a)
565
+ attn_output_b = attention(q_b, k_b, v_b)
566
+ attn_output = torch.concat([attn_output_a, attn_output_b], dim=1)
567
+
568
+ hidden_states = hidden_states + apply_gate(self.to_out(attn_output), mod_gate, tr_mod_gate, tr_token)
569
+ hidden_states = hidden_states + apply_gate(self.ff(norm_hidden_states), mod_gate, tr_mod_gate, tr_token)
570
+ return hidden_states
571
+
572
+
573
+ class FinalLayer(torch.nn.Module):
574
+ def __init__(self, hidden_size=3072, patch_size=(1, 2, 2), out_channels=16):
575
+ super().__init__()
576
+
577
+ self.norm_final = torch.nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
578
+ self.linear = torch.nn.Linear(hidden_size, patch_size[0] * patch_size[1] * patch_size[2] * out_channels)
579
+
580
+ self.adaLN_modulation = torch.nn.Sequential(torch.nn.SiLU(), torch.nn.Linear(hidden_size, 2 * hidden_size))
581
+
582
+ def forward(self, x, c):
583
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
584
+ x = modulate(self.norm_final(x), shift=shift, scale=scale)
585
+ x = self.linear(x)
586
+ return x
587
+
588
+
589
+ class HunyuanVideoDiT(torch.nn.Module):
590
+ def __init__(self, in_channels=16, hidden_size=3072, text_dim=4096, num_double_blocks=20, num_single_blocks=40, guidance_embed=True):
591
+ super().__init__()
592
+ self.img_in = PatchEmbed(in_channels=in_channels, embed_dim=hidden_size)
593
+ self.txt_in = SingleTokenRefiner(in_channels=text_dim, hidden_size=hidden_size)
594
+ self.time_in = TimestepEmbeddings(256, hidden_size, computation_device="cpu")
595
+ self.vector_in = torch.nn.Sequential(
596
+ torch.nn.Linear(768, hidden_size),
597
+ torch.nn.SiLU(),
598
+ torch.nn.Linear(hidden_size, hidden_size)
599
+ )
600
+ self.guidance_in = TimestepEmbeddings(256, hidden_size, computation_device="cpu") if guidance_embed else None
601
+ self.double_blocks = torch.nn.ModuleList([MMDoubleStreamBlock(hidden_size) for _ in range(num_double_blocks)])
602
+ self.single_blocks = torch.nn.ModuleList([MMSingleStreamBlock(hidden_size) for _ in range(num_single_blocks)])
603
+ self.final_layer = FinalLayer(hidden_size)
604
+
605
+ # TODO: remove these parameters
606
+ self.dtype = torch.bfloat16
607
+ self.patch_size = [1, 2, 2]
608
+ self.hidden_size = 3072
609
+ self.heads_num = 24
610
+ self.rope_dim_list = [16, 56, 56]
611
+
612
+ def unpatchify(self, x, T, H, W):
613
+ x = rearrange(x, "B (T H W) (C pT pH pW) -> B C (T pT) (H pH) (W pW)", H=H, W=W, pT=1, pH=2, pW=2)
614
+ return x
615
+
616
+ def enable_block_wise_offload(self, warm_device="cuda", cold_device="cpu"):
617
+ self.warm_device = warm_device
618
+ self.cold_device = cold_device
619
+ self.to(self.cold_device)
620
+
621
+ def load_models_to_device(self, loadmodel_names=[], device="cpu"):
622
+ for model_name in loadmodel_names:
623
+ model = getattr(self, model_name)
624
+ if model is not None:
625
+ model.to(device)
626
+ torch.cuda.empty_cache()
627
+
628
+ def prepare_freqs(self, latents):
629
+ return HunyuanVideoRope(latents)
630
+
631
+ def forward(
632
+ self,
633
+ x: torch.Tensor,
634
+ t: torch.Tensor,
635
+ prompt_emb: torch.Tensor = None,
636
+ text_mask: torch.Tensor = None,
637
+ pooled_prompt_emb: torch.Tensor = None,
638
+ freqs_cos: torch.Tensor = None,
639
+ freqs_sin: torch.Tensor = None,
640
+ guidance: torch.Tensor = None,
641
+ **kwargs
642
+ ):
643
+ B, C, T, H, W = x.shape
644
+
645
+ vec = self.time_in(t, dtype=torch.float32) + self.vector_in(pooled_prompt_emb)
646
+ if self.guidance_in is not None:
647
+ vec += self.guidance_in(guidance * 1000, dtype=torch.float32)
648
+ img = self.img_in(x)
649
+ txt = self.txt_in(prompt_emb, t, text_mask)
650
+
651
+ for block in tqdm(self.double_blocks, desc="Double stream blocks"):
652
+ img, txt = block(img, txt, vec, (freqs_cos, freqs_sin))
653
+
654
+ x = torch.concat([img, txt], dim=1)
655
+ for block in tqdm(self.single_blocks, desc="Single stream blocks"):
656
+ x = block(x, vec, (freqs_cos, freqs_sin))
657
+
658
+ img = x[:, :-256]
659
+ img = self.final_layer(img, vec)
660
+ img = self.unpatchify(img, T=T//1, H=H//2, W=W//2)
661
+ return img
662
+
663
+
664
+ def enable_auto_offload(self, dtype=torch.bfloat16, device="cuda"):
665
+ def cast_to(weight, dtype=None, device=None, copy=False):
666
+ if device is None or weight.device == device:
667
+ if not copy:
668
+ if dtype is None or weight.dtype == dtype:
669
+ return weight
670
+ return weight.to(dtype=dtype, copy=copy)
671
+
672
+ r = torch.empty_like(weight, dtype=dtype, device=device)
673
+ r.copy_(weight)
674
+ return r
675
+
676
+ def cast_weight(s, input=None, dtype=None, device=None):
677
+ if input is not None:
678
+ if dtype is None:
679
+ dtype = input.dtype
680
+ if device is None:
681
+ device = input.device
682
+ weight = cast_to(s.weight, dtype, device)
683
+ return weight
684
+
685
+ def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None):
686
+ if input is not None:
687
+ if dtype is None:
688
+ dtype = input.dtype
689
+ if bias_dtype is None:
690
+ bias_dtype = dtype
691
+ if device is None:
692
+ device = input.device
693
+ weight = cast_to(s.weight, dtype, device)
694
+ bias = cast_to(s.bias, bias_dtype, device) if s.bias is not None else None
695
+ return weight, bias
696
+
697
+ class quantized_layer:
698
+ class Linear(torch.nn.Linear):
699
+ def __init__(self, *args, dtype=torch.bfloat16, device="cuda", **kwargs):
700
+ super().__init__(*args, **kwargs)
701
+ self.dtype = dtype
702
+ self.device = device
703
+
704
+ def block_forward_(self, x, i, j, dtype, device):
705
+ weight_ = cast_to(
706
+ self.weight[j * self.block_size: (j + 1) * self.block_size, i * self.block_size: (i + 1) * self.block_size],
707
+ dtype=dtype, device=device
708
+ )
709
+ if self.bias is None or i > 0:
710
+ bias_ = None
711
+ else:
712
+ bias_ = cast_to(self.bias[j * self.block_size: (j + 1) * self.block_size], dtype=dtype, device=device)
713
+ x_ = x[..., i * self.block_size: (i + 1) * self.block_size]
714
+ y_ = torch.nn.functional.linear(x_, weight_, bias_)
715
+ del x_, weight_, bias_
716
+ torch.cuda.empty_cache()
717
+ return y_
718
+
719
+ def block_forward(self, x, **kwargs):
720
+ # This feature can only reduce 2GB VRAM, so we disable it.
721
+ y = torch.zeros(x.shape[:-1] + (self.out_features,), dtype=x.dtype, device=x.device)
722
+ for i in range((self.in_features + self.block_size - 1) // self.block_size):
723
+ for j in range((self.out_features + self.block_size - 1) // self.block_size):
724
+ y[..., j * self.block_size: (j + 1) * self.block_size] += self.block_forward_(x, i, j, dtype=x.dtype, device=x.device)
725
+ return y
726
+
727
+ def forward(self, x, **kwargs):
728
+ weight, bias = cast_bias_weight(self, x, dtype=self.dtype, device=self.device)
729
+ return torch.nn.functional.linear(x, weight, bias)
730
+
731
+
732
+ class RMSNorm(torch.nn.Module):
733
+ def __init__(self, module, dtype=torch.bfloat16, device="cuda"):
734
+ super().__init__()
735
+ self.module = module
736
+ self.dtype = dtype
737
+ self.device = device
738
+
739
+ def forward(self, hidden_states, **kwargs):
740
+ input_dtype = hidden_states.dtype
741
+ variance = hidden_states.to(torch.float32).square().mean(-1, keepdim=True)
742
+ hidden_states = hidden_states * torch.rsqrt(variance + self.module.eps)
743
+ hidden_states = hidden_states.to(input_dtype)
744
+ if self.module.weight is not None:
745
+ weight = cast_weight(self.module, hidden_states, dtype=torch.bfloat16, device="cuda")
746
+ hidden_states = hidden_states * weight
747
+ return hidden_states
748
+
749
+ class Conv3d(torch.nn.Conv3d):
750
+ def __init__(self, *args, dtype=torch.bfloat16, device="cuda", **kwargs):
751
+ super().__init__(*args, **kwargs)
752
+ self.dtype = dtype
753
+ self.device = device
754
+
755
+ def forward(self, x):
756
+ weight, bias = cast_bias_weight(self, x, dtype=self.dtype, device=self.device)
757
+ return torch.nn.functional.conv3d(x, weight, bias, self.stride, self.padding, self.dilation, self.groups)
758
+
759
+ class LayerNorm(torch.nn.LayerNorm):
760
+ def __init__(self, *args, dtype=torch.bfloat16, device="cuda", **kwargs):
761
+ super().__init__(*args, **kwargs)
762
+ self.dtype = dtype
763
+ self.device = device
764
+
765
+ def forward(self, x):
766
+ if self.weight is not None and self.bias is not None:
767
+ weight, bias = cast_bias_weight(self, x, dtype=self.dtype, device=self.device)
768
+ return torch.nn.functional.layer_norm(x, self.normalized_shape, weight, bias, self.eps)
769
+ else:
770
+ return torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
771
+
772
+ def replace_layer(model, dtype=torch.bfloat16, device="cuda"):
773
+ for name, module in model.named_children():
774
+ if isinstance(module, torch.nn.Linear):
775
+ with init_weights_on_device():
776
+ new_layer = quantized_layer.Linear(
777
+ module.in_features, module.out_features, bias=module.bias is not None,
778
+ dtype=dtype, device=device
779
+ )
780
+ new_layer.load_state_dict(module.state_dict(), assign=True)
781
+ setattr(model, name, new_layer)
782
+ elif isinstance(module, torch.nn.Conv3d):
783
+ with init_weights_on_device():
784
+ new_layer = quantized_layer.Conv3d(
785
+ module.in_channels, module.out_channels, kernel_size=module.kernel_size, stride=module.stride,
786
+ dtype=dtype, device=device
787
+ )
788
+ new_layer.load_state_dict(module.state_dict(), assign=True)
789
+ setattr(model, name, new_layer)
790
+ elif isinstance(module, RMSNorm):
791
+ new_layer = quantized_layer.RMSNorm(
792
+ module,
793
+ dtype=dtype, device=device
794
+ )
795
+ setattr(model, name, new_layer)
796
+ elif isinstance(module, torch.nn.LayerNorm):
797
+ with init_weights_on_device():
798
+ new_layer = quantized_layer.LayerNorm(
799
+ module.normalized_shape, elementwise_affine=module.elementwise_affine, eps=module.eps,
800
+ dtype=dtype, device=device
801
+ )
802
+ new_layer.load_state_dict(module.state_dict(), assign=True)
803
+ setattr(model, name, new_layer)
804
+ else:
805
+ replace_layer(module, dtype=dtype, device=device)
806
+
807
+ replace_layer(self, dtype=dtype, device=device)
808
+
809
+ @staticmethod
810
+ def state_dict_converter():
811
+ return HunyuanVideoDiTStateDictConverter()
812
+
813
+
814
+ class HunyuanVideoDiTStateDictConverter:
815
+ def __init__(self):
816
+ pass
817
+
818
+ def from_civitai(self, state_dict):
819
+ origin_hash_key = hash_state_dict_keys(state_dict, with_shape=True)
820
+ if "module" in state_dict:
821
+ state_dict = state_dict["module"]
822
+ direct_dict = {
823
+ "img_in.proj": "img_in.proj",
824
+ "time_in.mlp.0": "time_in.timestep_embedder.0",
825
+ "time_in.mlp.2": "time_in.timestep_embedder.2",
826
+ "vector_in.in_layer": "vector_in.0",
827
+ "vector_in.out_layer": "vector_in.2",
828
+ "guidance_in.mlp.0": "guidance_in.timestep_embedder.0",
829
+ "guidance_in.mlp.2": "guidance_in.timestep_embedder.2",
830
+ "txt_in.input_embedder": "txt_in.input_embedder",
831
+ "txt_in.t_embedder.mlp.0": "txt_in.t_embedder.timestep_embedder.0",
832
+ "txt_in.t_embedder.mlp.2": "txt_in.t_embedder.timestep_embedder.2",
833
+ "txt_in.c_embedder.linear_1": "txt_in.c_embedder.0",
834
+ "txt_in.c_embedder.linear_2": "txt_in.c_embedder.2",
835
+ "final_layer.linear": "final_layer.linear",
836
+ "final_layer.adaLN_modulation.1": "final_layer.adaLN_modulation.1",
837
+ }
838
+ txt_suffix_dict = {
839
+ "norm1": "norm1",
840
+ "self_attn_qkv": "self_attn_qkv",
841
+ "self_attn_proj": "self_attn_proj",
842
+ "norm2": "norm2",
843
+ "mlp.fc1": "mlp.0",
844
+ "mlp.fc2": "mlp.2",
845
+ "adaLN_modulation.1": "adaLN_modulation.1",
846
+ }
847
+ double_suffix_dict = {
848
+ "img_mod.linear": "component_a.mod.linear",
849
+ "img_attn_qkv": "component_a.to_qkv",
850
+ "img_attn_q_norm": "component_a.norm_q",
851
+ "img_attn_k_norm": "component_a.norm_k",
852
+ "img_attn_proj": "component_a.to_out",
853
+ "img_mlp.fc1": "component_a.ff.0",
854
+ "img_mlp.fc2": "component_a.ff.2",
855
+ "txt_mod.linear": "component_b.mod.linear",
856
+ "txt_attn_qkv": "component_b.to_qkv",
857
+ "txt_attn_q_norm": "component_b.norm_q",
858
+ "txt_attn_k_norm": "component_b.norm_k",
859
+ "txt_attn_proj": "component_b.to_out",
860
+ "txt_mlp.fc1": "component_b.ff.0",
861
+ "txt_mlp.fc2": "component_b.ff.2",
862
+ }
863
+ single_suffix_dict = {
864
+ "linear1": ["to_qkv", "ff.0"],
865
+ "linear2": ["to_out", "ff.2"],
866
+ "q_norm": "norm_q",
867
+ "k_norm": "norm_k",
868
+ "modulation.linear": "mod.linear",
869
+ }
870
+ # single_suffix_dict = {
871
+ # "linear1": "linear1",
872
+ # "linear2": "linear2",
873
+ # "q_norm": "q_norm",
874
+ # "k_norm": "k_norm",
875
+ # "modulation.linear": "modulation.linear",
876
+ # }
877
+ state_dict_ = {}
878
+ for name, param in state_dict.items():
879
+ names = name.split(".")
880
+ direct_name = ".".join(names[:-1])
881
+ if direct_name in direct_dict:
882
+ name_ = direct_dict[direct_name] + "." + names[-1]
883
+ state_dict_[name_] = param
884
+ elif names[0] == "double_blocks":
885
+ prefix = ".".join(names[:2])
886
+ suffix = ".".join(names[2:-1])
887
+ name_ = prefix + "." + double_suffix_dict[suffix] + "." + names[-1]
888
+ state_dict_[name_] = param
889
+ elif names[0] == "single_blocks":
890
+ prefix = ".".join(names[:2])
891
+ suffix = ".".join(names[2:-1])
892
+ if isinstance(single_suffix_dict[suffix], list):
893
+ if suffix == "linear1":
894
+ name_a, name_b = single_suffix_dict[suffix]
895
+ param_a, param_b = torch.split(param, (3072*3, 3072*4), dim=0)
896
+ state_dict_[prefix + "." + name_a + "." + names[-1]] = param_a
897
+ state_dict_[prefix + "." + name_b + "." + names[-1]] = param_b
898
+ elif suffix == "linear2":
899
+ if names[-1] == "weight":
900
+ name_a, name_b = single_suffix_dict[suffix]
901
+ param_a, param_b = torch.split(param, (3072*1, 3072*4), dim=-1)
902
+ state_dict_[prefix + "." + name_a + "." + names[-1]] = param_a
903
+ state_dict_[prefix + "." + name_b + "." + names[-1]] = param_b
904
+ else:
905
+ name_a, name_b = single_suffix_dict[suffix]
906
+ state_dict_[prefix + "." + name_a + "." + names[-1]] = param
907
+ else:
908
+ pass
909
+ else:
910
+ name_ = prefix + "." + single_suffix_dict[suffix] + "." + names[-1]
911
+ state_dict_[name_] = param
912
+ elif names[0] == "txt_in":
913
+ prefix = ".".join(names[:4]).replace(".individual_token_refiner.", ".")
914
+ suffix = ".".join(names[4:-1])
915
+ name_ = prefix + "." + txt_suffix_dict[suffix] + "." + names[-1]
916
+ state_dict_[name_] = param
917
+ else:
918
+ pass
919
+
920
+ return state_dict_
hunyuan_video_text_encoder.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import LlamaModel, LlamaConfig, DynamicCache, LlavaForConditionalGeneration
2
+ from copy import deepcopy
3
+ import torch
4
+
5
+
6
+ class HunyuanVideoLLMEncoder(LlamaModel):
7
+
8
+ def __init__(self, config: LlamaConfig):
9
+ super().__init__(config)
10
+ self.auto_offload = False
11
+
12
+ def enable_auto_offload(self, **kwargs):
13
+ self.auto_offload = True
14
+
15
+ def forward(self, input_ids, attention_mask, hidden_state_skip_layer=2):
16
+ embed_tokens = deepcopy(self.embed_tokens).to(input_ids.device) if self.auto_offload else self.embed_tokens
17
+ inputs_embeds = embed_tokens(input_ids)
18
+
19
+ past_key_values = DynamicCache()
20
+
21
+ cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
22
+ position_ids = cache_position.unsqueeze(0)
23
+
24
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, None, False)
25
+ hidden_states = inputs_embeds
26
+
27
+ # create position embeddings to be shared across the decoder layers
28
+ rotary_emb = deepcopy(self.rotary_emb).to(input_ids.device) if self.auto_offload else self.rotary_emb
29
+ position_embeddings = rotary_emb(hidden_states, position_ids)
30
+
31
+ # decoder layers
32
+ for layer_id, decoder_layer in enumerate(self.layers):
33
+ if self.auto_offload:
34
+ decoder_layer = deepcopy(decoder_layer).to(hidden_states.device)
35
+ layer_outputs = decoder_layer(
36
+ hidden_states,
37
+ attention_mask=causal_mask,
38
+ position_ids=position_ids,
39
+ past_key_value=past_key_values,
40
+ output_attentions=False,
41
+ use_cache=True,
42
+ cache_position=cache_position,
43
+ position_embeddings=position_embeddings,
44
+ )
45
+ hidden_states = layer_outputs[0]
46
+ if layer_id + hidden_state_skip_layer + 1 >= len(self.layers):
47
+ break
48
+
49
+ return hidden_states
50
+
51
+
52
+ class HunyuanVideoMLLMEncoder(LlavaForConditionalGeneration):
53
+
54
+ def __init__(self, config):
55
+ super().__init__(config)
56
+ self.auto_offload = False
57
+
58
+ def enable_auto_offload(self, **kwargs):
59
+ self.auto_offload = True
60
+
61
+ # TODO: implement the low VRAM inference for MLLM.
62
+ def forward(self, input_ids, pixel_values, attention_mask, hidden_state_skip_layer=2):
63
+ outputs = super().forward(input_ids=input_ids,
64
+ attention_mask=attention_mask,
65
+ output_hidden_states=True,
66
+ pixel_values=pixel_values)
67
+ hidden_state = outputs.hidden_states[-(hidden_state_skip_layer + 1)]
68
+ return hidden_state
hunyuan_video_vae_decoder.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from einops import rearrange
5
+ import numpy as np
6
+ from tqdm import tqdm
7
+ from einops import repeat
8
+
9
+
10
+ class CausalConv3d(nn.Module):
11
+
12
+ def __init__(self, in_channel, out_channel, kernel_size, stride=1, dilation=1, pad_mode='replicate', **kwargs):
13
+ super().__init__()
14
+ self.pad_mode = pad_mode
15
+ self.time_causal_padding = (kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size - 1, 0
16
+ ) # W, H, T
17
+ self.conv = nn.Conv3d(in_channel, out_channel, kernel_size, stride=stride, dilation=dilation, **kwargs)
18
+
19
+ def forward(self, x):
20
+ x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
21
+ return self.conv(x)
22
+
23
+
24
+ class UpsampleCausal3D(nn.Module):
25
+
26
+ def __init__(self, channels, use_conv=False, out_channels=None, kernel_size=None, bias=True, upsample_factor=(2, 2, 2)):
27
+ super().__init__()
28
+ self.channels = channels
29
+ self.out_channels = out_channels or channels
30
+ self.upsample_factor = upsample_factor
31
+ self.conv = None
32
+ if use_conv:
33
+ kernel_size = 3 if kernel_size is None else kernel_size
34
+ self.conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, bias=bias)
35
+
36
+ def forward(self, hidden_states):
37
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
38
+ dtype = hidden_states.dtype
39
+ if dtype == torch.bfloat16:
40
+ hidden_states = hidden_states.to(torch.float32)
41
+
42
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
43
+ if hidden_states.shape[0] >= 64:
44
+ hidden_states = hidden_states.contiguous()
45
+
46
+ # interpolate
47
+ B, C, T, H, W = hidden_states.shape
48
+ first_h, other_h = hidden_states.split((1, T - 1), dim=2)
49
+ if T > 1:
50
+ other_h = F.interpolate(other_h, scale_factor=self.upsample_factor, mode="nearest")
51
+ first_h = F.interpolate(first_h.squeeze(2), scale_factor=self.upsample_factor[1:], mode="nearest").unsqueeze(2)
52
+ hidden_states = torch.cat((first_h, other_h), dim=2) if T > 1 else first_h
53
+
54
+ # If the input is bfloat16, we cast back to bfloat16
55
+ if dtype == torch.bfloat16:
56
+ hidden_states = hidden_states.to(dtype)
57
+
58
+ if self.conv:
59
+ hidden_states = self.conv(hidden_states)
60
+
61
+ return hidden_states
62
+
63
+
64
+ class ResnetBlockCausal3D(nn.Module):
65
+
66
+ def __init__(self, in_channels, out_channels=None, dropout=0.0, groups=32, eps=1e-6, conv_shortcut_bias=True):
67
+ super().__init__()
68
+ self.pre_norm = True
69
+ self.in_channels = in_channels
70
+ out_channels = in_channels if out_channels is None else out_channels
71
+ self.out_channels = out_channels
72
+
73
+ self.norm1 = nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
74
+ self.conv1 = CausalConv3d(in_channels, out_channels, kernel_size=3, stride=1)
75
+
76
+ self.norm2 = nn.GroupNorm(num_groups=groups, num_channels=out_channels, eps=eps, affine=True)
77
+ self.conv2 = CausalConv3d(out_channels, out_channels, kernel_size=3, stride=1)
78
+
79
+ self.dropout = nn.Dropout(dropout)
80
+ self.nonlinearity = nn.SiLU()
81
+
82
+ self.conv_shortcut = None
83
+ if in_channels != out_channels:
84
+ self.conv_shortcut = CausalConv3d(in_channels, out_channels, kernel_size=1, stride=1, bias=conv_shortcut_bias)
85
+
86
+ def forward(self, input_tensor):
87
+ hidden_states = input_tensor
88
+ # conv1
89
+ hidden_states = self.norm1(hidden_states)
90
+ hidden_states = self.nonlinearity(hidden_states)
91
+ hidden_states = self.conv1(hidden_states)
92
+
93
+ # conv2
94
+ hidden_states = self.norm2(hidden_states)
95
+ hidden_states = self.nonlinearity(hidden_states)
96
+ hidden_states = self.dropout(hidden_states)
97
+ hidden_states = self.conv2(hidden_states)
98
+ # shortcut
99
+ if self.conv_shortcut is not None:
100
+ input_tensor = (self.conv_shortcut(input_tensor))
101
+ # shortcut and scale
102
+ output_tensor = input_tensor + hidden_states
103
+
104
+ return output_tensor
105
+
106
+
107
+ def prepare_causal_attention_mask(n_frame, n_hw, dtype, device, batch_size=None):
108
+ seq_len = n_frame * n_hw
109
+ mask = torch.full((seq_len, seq_len), float("-inf"), dtype=dtype, device=device)
110
+ for i in range(seq_len):
111
+ i_frame = i // n_hw
112
+ mask[i, :(i_frame + 1) * n_hw] = 0
113
+ if batch_size is not None:
114
+ mask = mask.unsqueeze(0).expand(batch_size, -1, -1)
115
+ return mask
116
+
117
+
118
+ class Attention(nn.Module):
119
+
120
+ def __init__(self,
121
+ in_channels,
122
+ num_heads,
123
+ head_dim,
124
+ num_groups=32,
125
+ dropout=0.0,
126
+ eps=1e-6,
127
+ bias=True,
128
+ residual_connection=True):
129
+ super().__init__()
130
+ self.num_heads = num_heads
131
+ self.head_dim = head_dim
132
+ self.residual_connection = residual_connection
133
+ dim_inner = head_dim * num_heads
134
+ self.group_norm = nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=eps, affine=True)
135
+ self.to_q = nn.Linear(in_channels, dim_inner, bias=bias)
136
+ self.to_k = nn.Linear(in_channels, dim_inner, bias=bias)
137
+ self.to_v = nn.Linear(in_channels, dim_inner, bias=bias)
138
+ self.to_out = nn.Sequential(nn.Linear(dim_inner, in_channels, bias=bias), nn.Dropout(dropout))
139
+
140
+ def forward(self, input_tensor, attn_mask=None):
141
+ hidden_states = self.group_norm(input_tensor.transpose(1, 2)).transpose(1, 2)
142
+ batch_size = hidden_states.shape[0]
143
+
144
+ q = self.to_q(hidden_states)
145
+ k = self.to_k(hidden_states)
146
+ v = self.to_v(hidden_states)
147
+
148
+ q = q.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
149
+ k = k.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
150
+ v = v.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
151
+
152
+ if attn_mask is not None:
153
+ attn_mask = attn_mask.view(batch_size, self.num_heads, -1, attn_mask.shape[-1])
154
+ hidden_states = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
155
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
156
+ hidden_states = self.to_out(hidden_states)
157
+ if self.residual_connection:
158
+ output_tensor = input_tensor + hidden_states
159
+ return output_tensor
160
+
161
+
162
+ class UNetMidBlockCausal3D(nn.Module):
163
+
164
+ def __init__(self, in_channels, dropout=0.0, num_layers=1, eps=1e-6, num_groups=32, attention_head_dim=None):
165
+ super().__init__()
166
+ resnets = [
167
+ ResnetBlockCausal3D(
168
+ in_channels=in_channels,
169
+ out_channels=in_channels,
170
+ dropout=dropout,
171
+ groups=num_groups,
172
+ eps=eps,
173
+ )
174
+ ]
175
+ attentions = []
176
+ attention_head_dim = attention_head_dim or in_channels
177
+
178
+ for _ in range(num_layers):
179
+ attentions.append(
180
+ Attention(
181
+ in_channels,
182
+ num_heads=in_channels // attention_head_dim,
183
+ head_dim=attention_head_dim,
184
+ num_groups=num_groups,
185
+ dropout=dropout,
186
+ eps=eps,
187
+ bias=True,
188
+ residual_connection=True,
189
+ ))
190
+
191
+ resnets.append(
192
+ ResnetBlockCausal3D(
193
+ in_channels=in_channels,
194
+ out_channels=in_channels,
195
+ dropout=dropout,
196
+ groups=num_groups,
197
+ eps=eps,
198
+ ))
199
+
200
+ self.attentions = nn.ModuleList(attentions)
201
+ self.resnets = nn.ModuleList(resnets)
202
+
203
+ def forward(self, hidden_states):
204
+ hidden_states = self.resnets[0](hidden_states)
205
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
206
+ B, C, T, H, W = hidden_states.shape
207
+ hidden_states = rearrange(hidden_states, "b c f h w -> b (f h w) c")
208
+ attn_mask = prepare_causal_attention_mask(T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B)
209
+ hidden_states = attn(hidden_states, attn_mask=attn_mask)
210
+ hidden_states = rearrange(hidden_states, "b (f h w) c -> b c f h w", f=T, h=H, w=W)
211
+ hidden_states = resnet(hidden_states)
212
+
213
+ return hidden_states
214
+
215
+
216
+ class UpDecoderBlockCausal3D(nn.Module):
217
+
218
+ def __init__(
219
+ self,
220
+ in_channels,
221
+ out_channels,
222
+ dropout=0.0,
223
+ num_layers=1,
224
+ eps=1e-6,
225
+ num_groups=32,
226
+ add_upsample=True,
227
+ upsample_scale_factor=(2, 2, 2),
228
+ ):
229
+ super().__init__()
230
+ resnets = []
231
+ for i in range(num_layers):
232
+ cur_in_channel = in_channels if i == 0 else out_channels
233
+ resnets.append(
234
+ ResnetBlockCausal3D(
235
+ in_channels=cur_in_channel,
236
+ out_channels=out_channels,
237
+ groups=num_groups,
238
+ dropout=dropout,
239
+ eps=eps,
240
+ ))
241
+ self.resnets = nn.ModuleList(resnets)
242
+
243
+ self.upsamplers = None
244
+ if add_upsample:
245
+ self.upsamplers = nn.ModuleList([
246
+ UpsampleCausal3D(
247
+ out_channels,
248
+ use_conv=True,
249
+ out_channels=out_channels,
250
+ upsample_factor=upsample_scale_factor,
251
+ )
252
+ ])
253
+
254
+ def forward(self, hidden_states):
255
+ for resnet in self.resnets:
256
+ hidden_states = resnet(hidden_states)
257
+ if self.upsamplers is not None:
258
+ for upsampler in self.upsamplers:
259
+ hidden_states = upsampler(hidden_states)
260
+ return hidden_states
261
+
262
+
263
+ class DecoderCausal3D(nn.Module):
264
+
265
+ def __init__(
266
+ self,
267
+ in_channels=16,
268
+ out_channels=3,
269
+ eps=1e-6,
270
+ dropout=0.0,
271
+ block_out_channels=[128, 256, 512, 512],
272
+ layers_per_block=2,
273
+ num_groups=32,
274
+ time_compression_ratio=4,
275
+ spatial_compression_ratio=8,
276
+ gradient_checkpointing=False,
277
+ ):
278
+ super().__init__()
279
+ self.layers_per_block = layers_per_block
280
+
281
+ self.conv_in = CausalConv3d(in_channels, block_out_channels[-1], kernel_size=3, stride=1)
282
+ self.up_blocks = nn.ModuleList([])
283
+
284
+ # mid
285
+ self.mid_block = UNetMidBlockCausal3D(
286
+ in_channels=block_out_channels[-1],
287
+ dropout=dropout,
288
+ eps=eps,
289
+ num_groups=num_groups,
290
+ attention_head_dim=block_out_channels[-1],
291
+ )
292
+
293
+ # up
294
+ reversed_block_out_channels = list(reversed(block_out_channels))
295
+ output_channel = reversed_block_out_channels[0]
296
+ for i in range(len(block_out_channels)):
297
+ prev_output_channel = output_channel
298
+ output_channel = reversed_block_out_channels[i]
299
+ is_final_block = i == len(block_out_channels) - 1
300
+ num_spatial_upsample_layers = int(np.log2(spatial_compression_ratio))
301
+ num_time_upsample_layers = int(np.log2(time_compression_ratio))
302
+
303
+ add_spatial_upsample = bool(i < num_spatial_upsample_layers)
304
+ add_time_upsample = bool(i >= len(block_out_channels) - 1 - num_time_upsample_layers and not is_final_block)
305
+
306
+ upsample_scale_factor_HW = (2, 2) if add_spatial_upsample else (1, 1)
307
+ upsample_scale_factor_T = (2,) if add_time_upsample else (1,)
308
+ upsample_scale_factor = tuple(upsample_scale_factor_T + upsample_scale_factor_HW)
309
+
310
+ up_block = UpDecoderBlockCausal3D(
311
+ in_channels=prev_output_channel,
312
+ out_channels=output_channel,
313
+ dropout=dropout,
314
+ num_layers=layers_per_block + 1,
315
+ eps=eps,
316
+ num_groups=num_groups,
317
+ add_upsample=bool(add_spatial_upsample or add_time_upsample),
318
+ upsample_scale_factor=upsample_scale_factor,
319
+ )
320
+
321
+ self.up_blocks.append(up_block)
322
+ prev_output_channel = output_channel
323
+
324
+ # out
325
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups, eps=eps)
326
+ self.conv_act = nn.SiLU()
327
+ self.conv_out = CausalConv3d(block_out_channels[0], out_channels, kernel_size=3)
328
+
329
+ self.gradient_checkpointing = gradient_checkpointing
330
+
331
+ def forward(self, hidden_states):
332
+ hidden_states = self.conv_in(hidden_states)
333
+ if self.training and self.gradient_checkpointing:
334
+
335
+ def create_custom_forward(module):
336
+
337
+ def custom_forward(*inputs):
338
+ return module(*inputs)
339
+
340
+ return custom_forward
341
+
342
+ # middle
343
+ hidden_states = torch.utils.checkpoint.checkpoint(
344
+ create_custom_forward(self.mid_block),
345
+ hidden_states,
346
+ use_reentrant=False,
347
+ )
348
+ # up
349
+ for up_block in self.up_blocks:
350
+ hidden_states = torch.utils.checkpoint.checkpoint(
351
+ create_custom_forward(up_block),
352
+ hidden_states,
353
+ use_reentrant=False,
354
+ )
355
+ else:
356
+ # middle
357
+ hidden_states = self.mid_block(hidden_states)
358
+ # up
359
+ for up_block in self.up_blocks:
360
+ hidden_states = up_block(hidden_states)
361
+ # post-process
362
+ hidden_states = self.conv_norm_out(hidden_states)
363
+ hidden_states = self.conv_act(hidden_states)
364
+ hidden_states = self.conv_out(hidden_states)
365
+
366
+ return hidden_states
367
+
368
+
369
+ class HunyuanVideoVAEDecoder(nn.Module):
370
+
371
+ def __init__(
372
+ self,
373
+ in_channels=16,
374
+ out_channels=3,
375
+ eps=1e-6,
376
+ dropout=0.0,
377
+ block_out_channels=[128, 256, 512, 512],
378
+ layers_per_block=2,
379
+ num_groups=32,
380
+ time_compression_ratio=4,
381
+ spatial_compression_ratio=8,
382
+ gradient_checkpointing=False,
383
+ ):
384
+ super().__init__()
385
+ self.decoder = DecoderCausal3D(
386
+ in_channels=in_channels,
387
+ out_channels=out_channels,
388
+ eps=eps,
389
+ dropout=dropout,
390
+ block_out_channels=block_out_channels,
391
+ layers_per_block=layers_per_block,
392
+ num_groups=num_groups,
393
+ time_compression_ratio=time_compression_ratio,
394
+ spatial_compression_ratio=spatial_compression_ratio,
395
+ gradient_checkpointing=gradient_checkpointing,
396
+ )
397
+ self.post_quant_conv = nn.Conv3d(in_channels, in_channels, kernel_size=1)
398
+ self.scaling_factor = 0.476986
399
+
400
+
401
+ def forward(self, latents):
402
+ latents = latents / self.scaling_factor
403
+ latents = self.post_quant_conv(latents)
404
+ dec = self.decoder(latents)
405
+ return dec
406
+
407
+
408
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
409
+ x = torch.ones((length,))
410
+ if not left_bound:
411
+ x[:border_width] = (torch.arange(border_width) + 1) / border_width
412
+ if not right_bound:
413
+ x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,))
414
+ return x
415
+
416
+
417
+ def build_mask(self, data, is_bound, border_width):
418
+ _, _, T, H, W = data.shape
419
+ t = self.build_1d_mask(T, is_bound[0], is_bound[1], border_width[0])
420
+ h = self.build_1d_mask(H, is_bound[2], is_bound[3], border_width[1])
421
+ w = self.build_1d_mask(W, is_bound[4], is_bound[5], border_width[2])
422
+
423
+ t = repeat(t, "T -> T H W", T=T, H=H, W=W)
424
+ h = repeat(h, "H -> T H W", T=T, H=H, W=W)
425
+ w = repeat(w, "W -> T H W", T=T, H=H, W=W)
426
+
427
+ mask = torch.stack([t, h, w]).min(dim=0).values
428
+ mask = rearrange(mask, "T H W -> 1 1 T H W")
429
+ return mask
430
+
431
+
432
+ def tile_forward(self, hidden_states, tile_size, tile_stride):
433
+ B, C, T, H, W = hidden_states.shape
434
+ size_t, size_h, size_w = tile_size
435
+ stride_t, stride_h, stride_w = tile_stride
436
+
437
+ # Split tasks
438
+ tasks = []
439
+ for t in range(0, T, stride_t):
440
+ if (t-stride_t >= 0 and t-stride_t+size_t >= T): continue
441
+ for h in range(0, H, stride_h):
442
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
443
+ for w in range(0, W, stride_w):
444
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
445
+ t_, h_, w_ = t + size_t, h + size_h, w + size_w
446
+ tasks.append((t, t_, h, h_, w, w_))
447
+
448
+ # Run
449
+ torch_dtype = self.post_quant_conv.weight.dtype
450
+ data_device = hidden_states.device
451
+ computation_device = self.post_quant_conv.weight.device
452
+
453
+ weight = torch.zeros((1, 1, (T - 1) * 4 + 1, H * 8, W * 8), dtype=torch_dtype, device=data_device)
454
+ values = torch.zeros((B, 3, (T - 1) * 4 + 1, H * 8, W * 8), dtype=torch_dtype, device=data_device)
455
+
456
+ for t, t_, h, h_, w, w_ in tqdm(tasks, desc="VAE decoding"):
457
+ hidden_states_batch = hidden_states[:, :, t:t_, h:h_, w:w_].to(computation_device)
458
+ hidden_states_batch = self.forward(hidden_states_batch).to(data_device)
459
+ if t > 0:
460
+ hidden_states_batch = hidden_states_batch[:, :, 1:]
461
+
462
+ mask = self.build_mask(
463
+ hidden_states_batch,
464
+ is_bound=(t==0, t_>=T, h==0, h_>=H, w==0, w_>=W),
465
+ border_width=((size_t - stride_t) * 4, (size_h - stride_h) * 8, (size_w - stride_w) * 8)
466
+ ).to(dtype=torch_dtype, device=data_device)
467
+
468
+ target_t = 0 if t==0 else t * 4 + 1
469
+ target_h = h * 8
470
+ target_w = w * 8
471
+ values[
472
+ :,
473
+ :,
474
+ target_t: target_t + hidden_states_batch.shape[2],
475
+ target_h: target_h + hidden_states_batch.shape[3],
476
+ target_w: target_w + hidden_states_batch.shape[4],
477
+ ] += hidden_states_batch * mask
478
+ weight[
479
+ :,
480
+ :,
481
+ target_t: target_t + hidden_states_batch.shape[2],
482
+ target_h: target_h + hidden_states_batch.shape[3],
483
+ target_w: target_w + hidden_states_batch.shape[4],
484
+ ] += mask
485
+ return values / weight
486
+
487
+
488
+ def decode_video(self, latents, tile_size=(17, 32, 32), tile_stride=(12, 24, 24)):
489
+ latents = latents.to(self.post_quant_conv.weight.dtype)
490
+ return self.tile_forward(latents, tile_size=tile_size, tile_stride=tile_stride)
491
+
492
+ @staticmethod
493
+ def state_dict_converter():
494
+ return HunyuanVideoVAEDecoderStateDictConverter()
495
+
496
+
497
+ class HunyuanVideoVAEDecoderStateDictConverter:
498
+
499
+ def __init__(self):
500
+ pass
501
+
502
+ def from_diffusers(self, state_dict):
503
+ state_dict_ = {}
504
+ for name in state_dict:
505
+ if name.startswith('decoder.') or name.startswith('post_quant_conv.'):
506
+ state_dict_[name] = state_dict[name]
507
+ return state_dict_
hunyuan_video_vae_encoder.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from einops import rearrange, repeat
5
+ import numpy as np
6
+ from tqdm import tqdm
7
+ from .hunyuan_video_vae_decoder import CausalConv3d, ResnetBlockCausal3D, UNetMidBlockCausal3D
8
+
9
+
10
+ class DownsampleCausal3D(nn.Module):
11
+
12
+ def __init__(self, channels, out_channels, kernel_size=3, bias=True, stride=2):
13
+ super().__init__()
14
+ self.conv = CausalConv3d(channels, out_channels, kernel_size, stride=stride, bias=bias)
15
+
16
+ def forward(self, hidden_states):
17
+ hidden_states = self.conv(hidden_states)
18
+ return hidden_states
19
+
20
+
21
+ class DownEncoderBlockCausal3D(nn.Module):
22
+
23
+ def __init__(
24
+ self,
25
+ in_channels,
26
+ out_channels,
27
+ dropout=0.0,
28
+ num_layers=1,
29
+ eps=1e-6,
30
+ num_groups=32,
31
+ add_downsample=True,
32
+ downsample_stride=2,
33
+ ):
34
+
35
+ super().__init__()
36
+ resnets = []
37
+ for i in range(num_layers):
38
+ cur_in_channel = in_channels if i == 0 else out_channels
39
+ resnets.append(
40
+ ResnetBlockCausal3D(
41
+ in_channels=cur_in_channel,
42
+ out_channels=out_channels,
43
+ groups=num_groups,
44
+ dropout=dropout,
45
+ eps=eps,
46
+ ))
47
+ self.resnets = nn.ModuleList(resnets)
48
+
49
+ self.downsamplers = None
50
+ if add_downsample:
51
+ self.downsamplers = nn.ModuleList([DownsampleCausal3D(
52
+ out_channels,
53
+ out_channels,
54
+ stride=downsample_stride,
55
+ )])
56
+
57
+ def forward(self, hidden_states):
58
+ for resnet in self.resnets:
59
+ hidden_states = resnet(hidden_states)
60
+
61
+ if self.downsamplers is not None:
62
+ for downsampler in self.downsamplers:
63
+ hidden_states = downsampler(hidden_states)
64
+
65
+ return hidden_states
66
+
67
+
68
+ class EncoderCausal3D(nn.Module):
69
+
70
+ def __init__(
71
+ self,
72
+ in_channels: int = 3,
73
+ out_channels: int = 16,
74
+ eps=1e-6,
75
+ dropout=0.0,
76
+ block_out_channels=[128, 256, 512, 512],
77
+ layers_per_block=2,
78
+ num_groups=32,
79
+ time_compression_ratio: int = 4,
80
+ spatial_compression_ratio: int = 8,
81
+ gradient_checkpointing=False,
82
+ ):
83
+ super().__init__()
84
+ self.conv_in = CausalConv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1)
85
+ self.down_blocks = nn.ModuleList([])
86
+
87
+ # down
88
+ output_channel = block_out_channels[0]
89
+ for i in range(len(block_out_channels)):
90
+ input_channel = output_channel
91
+ output_channel = block_out_channels[i]
92
+ is_final_block = i == len(block_out_channels) - 1
93
+ num_spatial_downsample_layers = int(np.log2(spatial_compression_ratio))
94
+ num_time_downsample_layers = int(np.log2(time_compression_ratio))
95
+
96
+ add_spatial_downsample = bool(i < num_spatial_downsample_layers)
97
+ add_time_downsample = bool(i >= (len(block_out_channels) - 1 - num_time_downsample_layers) and not is_final_block)
98
+
99
+ downsample_stride_HW = (2, 2) if add_spatial_downsample else (1, 1)
100
+ downsample_stride_T = (2,) if add_time_downsample else (1,)
101
+ downsample_stride = tuple(downsample_stride_T + downsample_stride_HW)
102
+ down_block = DownEncoderBlockCausal3D(
103
+ in_channels=input_channel,
104
+ out_channels=output_channel,
105
+ dropout=dropout,
106
+ num_layers=layers_per_block,
107
+ eps=eps,
108
+ num_groups=num_groups,
109
+ add_downsample=bool(add_spatial_downsample or add_time_downsample),
110
+ downsample_stride=downsample_stride,
111
+ )
112
+ self.down_blocks.append(down_block)
113
+
114
+ # mid
115
+ self.mid_block = UNetMidBlockCausal3D(
116
+ in_channels=block_out_channels[-1],
117
+ dropout=dropout,
118
+ eps=eps,
119
+ num_groups=num_groups,
120
+ attention_head_dim=block_out_channels[-1],
121
+ )
122
+ # out
123
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=num_groups, eps=eps)
124
+ self.conv_act = nn.SiLU()
125
+ self.conv_out = CausalConv3d(block_out_channels[-1], 2 * out_channels, kernel_size=3)
126
+
127
+ self.gradient_checkpointing = gradient_checkpointing
128
+
129
+ def forward(self, hidden_states):
130
+ hidden_states = self.conv_in(hidden_states)
131
+ if self.training and self.gradient_checkpointing:
132
+
133
+ def create_custom_forward(module):
134
+
135
+ def custom_forward(*inputs):
136
+ return module(*inputs)
137
+
138
+ return custom_forward
139
+
140
+ # down
141
+ for down_block in self.down_blocks:
142
+ torch.utils.checkpoint.checkpoint(
143
+ create_custom_forward(down_block),
144
+ hidden_states,
145
+ use_reentrant=False,
146
+ )
147
+ # middle
148
+ hidden_states = torch.utils.checkpoint.checkpoint(
149
+ create_custom_forward(self.mid_block),
150
+ hidden_states,
151
+ use_reentrant=False,
152
+ )
153
+ else:
154
+ # down
155
+ for down_block in self.down_blocks:
156
+ hidden_states = down_block(hidden_states)
157
+ # middle
158
+ hidden_states = self.mid_block(hidden_states)
159
+ # post-process
160
+ hidden_states = self.conv_norm_out(hidden_states)
161
+ hidden_states = self.conv_act(hidden_states)
162
+ hidden_states = self.conv_out(hidden_states)
163
+
164
+ return hidden_states
165
+
166
+
167
+ class HunyuanVideoVAEEncoder(nn.Module):
168
+
169
+ def __init__(
170
+ self,
171
+ in_channels=3,
172
+ out_channels=16,
173
+ eps=1e-6,
174
+ dropout=0.0,
175
+ block_out_channels=[128, 256, 512, 512],
176
+ layers_per_block=2,
177
+ num_groups=32,
178
+ time_compression_ratio=4,
179
+ spatial_compression_ratio=8,
180
+ gradient_checkpointing=False,
181
+ ):
182
+ super().__init__()
183
+ self.encoder = EncoderCausal3D(
184
+ in_channels=in_channels,
185
+ out_channels=out_channels,
186
+ eps=eps,
187
+ dropout=dropout,
188
+ block_out_channels=block_out_channels,
189
+ layers_per_block=layers_per_block,
190
+ num_groups=num_groups,
191
+ time_compression_ratio=time_compression_ratio,
192
+ spatial_compression_ratio=spatial_compression_ratio,
193
+ gradient_checkpointing=gradient_checkpointing,
194
+ )
195
+ self.quant_conv = nn.Conv3d(2 * out_channels, 2 * out_channels, kernel_size=1)
196
+ self.scaling_factor = 0.476986
197
+
198
+
199
+ def forward(self, images):
200
+ latents = self.encoder(images)
201
+ latents = self.quant_conv(latents)
202
+ latents = latents[:, :16]
203
+ latents = latents * self.scaling_factor
204
+ return latents
205
+
206
+
207
+ def build_1d_mask(self, length, left_bound, right_bound, border_width):
208
+ x = torch.ones((length,))
209
+ if not left_bound:
210
+ x[:border_width] = (torch.arange(border_width) + 1) / border_width
211
+ if not right_bound:
212
+ x[-border_width:] = torch.flip((torch.arange(border_width) + 1) / border_width, dims=(0,))
213
+ return x
214
+
215
+
216
+ def build_mask(self, data, is_bound, border_width):
217
+ _, _, T, H, W = data.shape
218
+ t = self.build_1d_mask(T, is_bound[0], is_bound[1], border_width[0])
219
+ h = self.build_1d_mask(H, is_bound[2], is_bound[3], border_width[1])
220
+ w = self.build_1d_mask(W, is_bound[4], is_bound[5], border_width[2])
221
+
222
+ t = repeat(t, "T -> T H W", T=T, H=H, W=W)
223
+ h = repeat(h, "H -> T H W", T=T, H=H, W=W)
224
+ w = repeat(w, "W -> T H W", T=T, H=H, W=W)
225
+
226
+ mask = torch.stack([t, h, w]).min(dim=0).values
227
+ mask = rearrange(mask, "T H W -> 1 1 T H W")
228
+ return mask
229
+
230
+
231
+ def tile_forward(self, hidden_states, tile_size, tile_stride):
232
+ B, C, T, H, W = hidden_states.shape
233
+ size_t, size_h, size_w = tile_size
234
+ stride_t, stride_h, stride_w = tile_stride
235
+
236
+ # Split tasks
237
+ tasks = []
238
+ for t in range(0, T, stride_t):
239
+ if (t-stride_t >= 0 and t-stride_t+size_t >= T): continue
240
+ for h in range(0, H, stride_h):
241
+ if (h-stride_h >= 0 and h-stride_h+size_h >= H): continue
242
+ for w in range(0, W, stride_w):
243
+ if (w-stride_w >= 0 and w-stride_w+size_w >= W): continue
244
+ t_, h_, w_ = t + size_t, h + size_h, w + size_w
245
+ tasks.append((t, t_, h, h_, w, w_))
246
+
247
+ # Run
248
+ torch_dtype = self.quant_conv.weight.dtype
249
+ data_device = hidden_states.device
250
+ computation_device = self.quant_conv.weight.device
251
+
252
+ weight = torch.zeros((1, 1, (T - 1) // 4 + 1, H // 8, W // 8), dtype=torch_dtype, device=data_device)
253
+ values = torch.zeros((B, 16, (T - 1) // 4 + 1, H // 8, W // 8), dtype=torch_dtype, device=data_device)
254
+
255
+ for t, t_, h, h_, w, w_ in tqdm(tasks, desc="VAE encoding"):
256
+ hidden_states_batch = hidden_states[:, :, t:t_, h:h_, w:w_].to(computation_device)
257
+ hidden_states_batch = self.forward(hidden_states_batch).to(data_device)
258
+ if t > 0:
259
+ hidden_states_batch = hidden_states_batch[:, :, 1:]
260
+
261
+ mask = self.build_mask(
262
+ hidden_states_batch,
263
+ is_bound=(t==0, t_>=T, h==0, h_>=H, w==0, w_>=W),
264
+ border_width=((size_t - stride_t) // 4, (size_h - stride_h) // 8, (size_w - stride_w) // 8)
265
+ ).to(dtype=torch_dtype, device=data_device)
266
+
267
+ target_t = 0 if t==0 else t // 4 + 1
268
+ target_h = h // 8
269
+ target_w = w // 8
270
+ values[
271
+ :,
272
+ :,
273
+ target_t: target_t + hidden_states_batch.shape[2],
274
+ target_h: target_h + hidden_states_batch.shape[3],
275
+ target_w: target_w + hidden_states_batch.shape[4],
276
+ ] += hidden_states_batch * mask
277
+ weight[
278
+ :,
279
+ :,
280
+ target_t: target_t + hidden_states_batch.shape[2],
281
+ target_h: target_h + hidden_states_batch.shape[3],
282
+ target_w: target_w + hidden_states_batch.shape[4],
283
+ ] += mask
284
+ return values / weight
285
+
286
+
287
+ def encode_video(self, latents, tile_size=(65, 256, 256), tile_stride=(48, 192, 192)):
288
+ latents = latents.to(self.quant_conv.weight.dtype)
289
+ return self.tile_forward(latents, tile_size=tile_size, tile_stride=tile_stride)
290
+
291
+
292
+ @staticmethod
293
+ def state_dict_converter():
294
+ return HunyuanVideoVAEEncoderStateDictConverter()
295
+
296
+
297
+ class HunyuanVideoVAEEncoderStateDictConverter:
298
+
299
+ def __init__(self):
300
+ pass
301
+
302
+ def from_diffusers(self, state_dict):
303
+ state_dict_ = {}
304
+ for name in state_dict:
305
+ if name.startswith('encoder.') or name.startswith('quant_conv.'):
306
+ state_dict_[name] = state_dict[name]
307
+ return state_dict_
kolors_text_encoder.py ADDED
@@ -0,0 +1,1551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This model is copied from https://github.com/Kwai-Kolors/Kolors/tree/master/kolors/models.
3
+ We didn't modify this model.
4
+ The tensor operation is performed in the prompter.
5
+ """
6
+
7
+
8
+ """ PyTorch ChatGLM model. """
9
+
10
+ import math
11
+ import copy
12
+ import warnings
13
+ import re
14
+ import sys
15
+
16
+ import torch
17
+ import torch.utils.checkpoint
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+ from torch.nn import CrossEntropyLoss, LayerNorm
21
+ from torch.nn import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
22
+ from torch.nn.utils import skip_init
23
+ from typing import Optional, Tuple, Union, List, Callable, Dict, Any
24
+ from copy import deepcopy
25
+
26
+ from transformers.modeling_outputs import (
27
+ BaseModelOutputWithPast,
28
+ CausalLMOutputWithPast,
29
+ SequenceClassifierOutputWithPast,
30
+ )
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import logging
33
+ from transformers.generation.logits_process import LogitsProcessor
34
+ from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
35
+ from transformers import PretrainedConfig
36
+ from torch.nn.parameter import Parameter
37
+ import bz2
38
+ import torch
39
+ import base64
40
+ import ctypes
41
+ from transformers.utils import logging
42
+ from typing import List
43
+
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ try:
49
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
50
+
51
+
52
+ class Kernel:
53
+ def __init__(self, code: bytes, function_names: List[str]):
54
+ self.code = code
55
+ self._function_names = function_names
56
+ self._cmodule = LazyKernelCModule(self.code)
57
+
58
+ for name in self._function_names:
59
+ setattr(self, name, KernelFunction(self._cmodule, name))
60
+
61
+
62
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rxjwztHlnire3Nzc3N1wuBwOBwXBvZfoHpD7rFmR99V5vj3aXza3xdBbXMalubTg/jIv5dfAi54Pdc75j4z412n3Npj3Ld/ENm7a3b/Cod6h/ret1/5vn/C+l+gdslMvgPSLJ8d8q+U66fevYn/tW1chleEtNTGlcHCbLRlq0tHzF5tsbbZZfHjjLgZu42XCuC3NrdjTasZGNzgxPIrGqp7r3p7L2p5XjnpPSmTd5XtzqnB6U87zzg1Ol0zd0zsLszxR6lkxp35u6/teL0L0W922cR7Lu1lpL9CsHirzuM2T+BgsyViT6LHcm0/Vr6U/7LGGyJeqTEjt0PHWhF5mCT7R9mtlDwriYv0Tyr/OxYt6qp5r0mPVT0608TqnqMZaarU2nFwrTzzlrs1ed7z1ux60wyr4ydCaTi3enW8x68x0zU7tXSlcmPSW1mGpWJMg4zmPC2lK96tp0OE80y4MfEvnZj8zGluR6b22ki1Ou9V2nCd9xovcPvcYMZYy0lvN60ScZ45vN6yeCeeXFb1lVjnnCar5fwXwE2bzJ4HI1XVPXfXZMm44GUsMpYsmLB65TuVdm0cl0b+i/wGNN66XjeV7zuPpHcnK/juhhjdfId5jMdE5nN0dGmmm2zZs2cexD5n9p/dY352XsvXHaZNWWsmmS1atjR452nYudzvqv2HMRyvNNnlMcDl3R2+yx2uVrBubTW9icHDVtbNXlZm7jma1rM4VurZZd2y6nUau7ZXZ7bVU+mnoOVxZGMrVmvX60605JwmzGZhhhjTWtaaaMaaGTGmNMZasY0iX8VMUl8eepaIrzGSpemWOQyZORk2bNpjUybMmxqYmknCGCFynutfksaZpjTNMaaatM0xsxcGR0sociNqxNSmhhR1ZJPbsn8qyF0t2qH6iYBclclalbtTTcHTDsPaX6rlnElph2Jyumumtynv2Kk8GI7rsvXbIcJgHJOSaSXnnGaI3m87RtVXJOZ/YtgdTE6Wpha6ZlE8ayXkef1fh602r2WwvfMXtMdLlkfnLFdYYwYso+bWqm7yJqHXZGw2nrS5ZanSYnWlxBxMF1V940K2wdrI7R6OYf7DGGamMmTSbRhlS45xmVOumF1EyPCmHrrN8wwZOOrdNtLeMtzFzDlWnfTBxMk2NaXIZHBYxYLD4w8yju0ao65Vz1OIXoS9dLanwCe1PWrYuWMqf1if1z2k2yYfKJ741PDgno1ZQ8DRqvUny3mNoWTzGO6m1DkrJI8JiR5cSd+vZdGOO8nrMoc5+NDUFsMSXaZJeNlMmGLtJsovOsUp7I9S5VojKxF6bTVEelXqlfJobQr3LozSh2Jk7VcrVMfhXqszGWMzNqGhqZY0OadxkyyMssKugZR0KNFXBHlqwmJgTE/BNVMk6ItJXZMR0H47GpXv/DMOvNkmVuaV1PRfEdxuqc7Hcd+ZV/zTLaRxWk0nl9CdCeM6mn5rstHIBcpiuwmUZXeq81DacHI2rmrZ5SuE5mOZd6LQrZg9mx32TprA8BMo5jKN6yLTCi3WzQaZSuhzTtM1fUTGVpG8Tw+KXI0tjEpiWxtLYynOlktSbVlaI5kxP8TDH8kx50xoxi5KcA4pcja8KWLRlO/Ks6q06ergnvm1ca3Tq8Uw7LTUsmWyctXPWmpitl/uvGcWTGXGuAXDfhqazGmjkxcJW5hMMMMpYsXl2TZYtVOddG3XCarUt6Ptq9CZXSNzyuRzqRZOjsxdBbFVz6OA5HI43r1jityVlVpVkxmOsyaYWE1NTGq1sOVh36mHMcxtSvcy70edG0ZGR3I1Go1GRlV7mWWo1G0ZGRqlvH40l7o4m5xMWLLLYyNjnqc8556mdPqLJ31n/1nWOncxzG1tizrHs/Z+d2vP/B/l8wdJ6rHUn2nbbDq4p6htFtYzMMMTaZis1K5GKzGNmxhmUx2DDlZ/qNnIx41xnaMfCZWYaZWtNLTNW8ND4Fw1MyZOCdM428suKG1ehW8TesOydg7J+YYcD4cYR+8dFK6M4E3HM9ZfRNNL+Sn6rsl4DsrDl2HpPCnfxjGXtbZtYys1ttlyJ4T+BvexjGWRjMszK4Jpc77D3GyuVD7q0+G8m9G+2+rGm7cOR2y7FdtY2XUYx/oNlfRYxhMYyYZkyyg55enna9Kt/FFi6GMMwYwdwxWgxGMLKYmUyGExTKMZkMFhkymKuh0NOBNnBu+23LdwDoZYYzGGMxtORaTU1pjTGWTTGGtMrNWUsyyTTLLG1qy2ZjbK2DBllWqxMtBMaYZQmcE7zvvRcTkclUwdkxTaSdyySt/7fpL+T1v516Ji97fwr5JbLu305zMn5+GMTTZ9F+y7ExwmGVfG44yxn3dLv6l5i+Wth1jCrDq21nW9LqvvDzz3Vf3LLH/O/32TJ/erx3bXftO4eF+G956D952K/An4NfvOpjFjExjevP/UmE0fIoZXx6/w6lX/no3D0bLt+ixjieBM6ksRd0yB4Lt2SwYNE+gd1detlZWUnpiZfGfFaK+4PyCa/v18V8X75pe9fLXzp7l3VjF76vWZmHwGz1IZNWT7b8yddJ4q5kyrVdfru6atWc7bVYztL9Jf4GXvT+Y8m9/YsXP6H018a8D4XVOqvfzqeR+6yZOD8dPv0+U7/q5Pl+2dNb0MjzGVH5p6MNQ7cOWvw62U9aHE8DprDek+McLyvDz+te+9Zhq5+YTruufMcWMabqysTmZVWjKPfnK0wyVcrsuhjZRdLkHNvD72b9abriOSGIxiLixMOoalNPXzy+wT/tf+U6HHONfsz+xe8ufHBdQWWGWLA9if0rsnmrxK5LvRZQeWsTCsrmOYy8VteVfuRfcVTtDLItLIsMYxZLdU/DbtSemxF6Z6Zo5WBXE4tFdCyVMMXMTEMZXVlS6Xec2T4e0tHsRcEuWshcJ2YsNF5rUx1E8ifCq6Z+ZP7qdCeu/aTwFd53l16/o0NOw6O3dLavP4Hbi4RdmuDk6DoYaninC0+o4uZjbJ7Rxeu0/FbuFg+q7DVS6fQe0rZ6NDGUNNU6DEqOaLTicKnYZMnBWruljQxoaS3dZhocDge0bSTyOvdAbG5hxe2xji7E/L55xX13wWNDi6HCekcFxfCPGxY0MXC+s7afWaMdDyjyr+o8Rudm/NabOZvdl274zH4f5XK9z6On1Pe/K5TdPAslg77BjuO6Y3eO7GqvOPG/stknp1leyvLL0Z7bl9I4noMvLkzytLhWYzrOZzLXCORe028rORzOg4N/L0HlMOQ3Pgmnbb6KczlabORpu980q37TBqRu0/p3PO6234Bl03Ynuz+9W7gnsEcmvYaYY3aMYY0wx3pYd+ujsXauWdaY5Xkbtl23fPzFHiDB/QMo0yFjBllYxTQYYyxkrwn7JufwJ/PfgJ+C83X69ni6zvXcnyXabv0ncbLwsceS+RNlyN2mnneJtX0ngYO0+e+0+UnA+Wch3ji8hj5an4h+i6XBySU4n+R0roVcbw5yvHrmr4Yw8Y7x6c+9POPYHI5HI5HI5HI5HGXGww4nE4nrVyOR8XeqPEO7PLOiukYa3Novk5hV4cdtYZLI93e+uxff2jRo0aNGjRo0aNG1bVtW1dy3m83m8+tQ5ZzHw3nObwOu8La9Rc1dtkdS8A3eTk823tnktXWlxN6Oixe06zrN70Isd9jiOgZFq9yfkPqP/SLhN2Myl8jDM43bl1nbcb4cO57jlh8Jow6pzXZdL4dyODTuuhu77FyO27DdwdRxmvO+O+3N2+BdqyTwLHVczDVY4UPE4O66/ZO2cx1LFzVdSXtF7G4HMbrauOHRw6c8FdZ5m9fHZHYZXfTlZquyynSyTTKke6vcffSD9pzPA/G7n7jxPmuhc1DHMynPMrGL6AdewYmwu5ko+UUyTwrMv27rPH1v1nGqd87+p6N6LU8k3NEng53xXyHS97+44OSg/sy/hn+Se6yfYNjW0/uTgP+PvWYzLMmjhcLB/gGpri6H83/84eUXWT6T9Hsv7785z/7z4icpW+zfXypuR7rx/gMdZb1/wC678pcs8/2a3mDitGHxl9mfPlll5MafWWqxk/eYuTDgcNMzDGWLWvsuglNxs53GtN6uWpktlW1tZZYcuinMMWmnNnJydze3b2Y1McBxrBkXw799izLMZZYyy0TkbsGM4p03S2uVu5s/XXUdSdec6smVxZYYGpVmT8A+8ajuEyV5FatkvVru2x6uxGXXbH4A+jvgP4GMYy3iPLXzq/6z65+E005ey+cwMZD3fZcqc6xpjTFjQ0P3U+e++cPYmTIwj0nrK5NPTfl3WvpfLtXDcb2HQMudYOxFXQBor4L4T6vrOauFctYXJQ++NUWmJe5bmx1jDiZS1dTqWxo4GR8jm3fttpmPHppk9PEyv4/y8/sO07XacOmcqc0x2Vi9BvNJvN5oW8x4mOsydpidRxMYJPx06m1bqPzq9KtK8sxXNXFodD/+MYYaJTLwOhc9brCsV18oOR1i4tXChyTkq4lf4y1Ke+9axjDHqs1mfBbMXuP4Hzi+X7t8vzv7bHerrUPgPCxhjre4fXdfLNtNM+Jd+Zdh8xd8wP87uNPoPgv4W7/5P2BuxfsMabNnMnza+54Pdi5U671GPZY8CehX8Voeoo7FHpkeEc6715FwHZrIrUrHaviPUbPZHND+IhczrP6FcYvhOZ0Di/ETt0OI+YwNWR9r7tpf6WDeZKZDB1+z2IthOl1mPyb5FluvEx9h9d0NnM0Y1XPFkWIsk1WotJ0PBMmkvjvQTd0e71tfeV+8r8lQ/tpzpsmxJ+InrI/dj2UajUajVTUajatRqNRtGo1Go1Go4wjeMpZFMVV9CHbofPraLsJ3JpWV2XOoanCuFky4y3PPNxucK2uKC1Lbdb1eo+m5XomN6HfeZsabHLHRX/K+offtNGGmHWctcVcG44MdSqsOLY9VzX+Zxfxn2HPdWTpzWvkrtJ8M5zorrKcquRytJ5N5DZmcaW02l76nWO+BqPXm1A2Ry/0q71dH/mqrqeFjkYxjEXtsX8qubTk67rGycyqsdm4tZx5D6D5hhi0waaWmiaMP81Yjii5qxPlPuU/GfTL1Y5E6Jyfiq63qTa39A4J0sOGDgO9WF9bOXl0XfPRbsY2bPNKPy1YrFYrFYmRhhlTIyMjJWJYZHXuCXI8OoXsvfljGLFicNifpp2XunoPiG1wtx3p1Tah+/DD66OnVtVXP9rKbVxOnL0tR/rHtqB5UDErUVcl11D4qqvjpOcxX7armUNJB3LpW6bxVvD08e8h3odKKvyCFZBdSh2FVcST9xV3n3T8t1j7Kr9qgrqXg+13Pt5U7JCvFXVIV1YG5lRhkVYZJYYDDD4KOIMoHCp26WS8GB7uBh2zIdgq/PKyInjV2STShuoapUdCpX1yTwqq/z1VvET7Kh5nVPkO8YyxjLt2MaaMmWTLQvx3qnzltnXW0p2jxgbEtSny/Osv8Y9pLMXYoHVPAhkVdWVeODhR6q9/Sxe2liwwZWMVvFXfRkeIDxAePUPIrdJ4ey6yquzH+PD/bUOWAu05qVHtFd8rrKHSoeNIOUqrYr3FXyToqfYJgwmJdKpXXOwYYegNNGMzfZPp/t3t/DVs4zjNTN61rRqaWaa4NYbRjTa0tWwy2Y2tGN8ZO8ofNKq4j9SL7I+cSm4/6ovLV5HNXLI0jJidwrtk6ynCaP6Z++GjRlWS3tLeW129Mi9evxU9mtz6s5J3Z7M2ngTgnKvmpomxpaLCzPfmx0JWE+m3NLDDGOX47RctdYYNK5jakdqLkRlI39n590T5zctGSwwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
63
+
64
+ kernels = Kernel(
65
+ bz2.decompress(base64.b64decode(quantization_code)),
66
+ [
67
+ "int4WeightCompression",
68
+ "int4WeightExtractionFloat",
69
+ "int4WeightExtractionHalf",
70
+ "int8WeightExtractionFloat",
71
+ "int8WeightExtractionHalf",
72
+ ],
73
+ )
74
+ except Exception as exception:
75
+ kernels = None
76
+
77
+
78
+ class W8A16Linear(torch.autograd.Function):
79
+ @staticmethod
80
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
81
+ ctx.inp_shape = inp.size()
82
+ ctx.weight_bit_width = weight_bit_width
83
+ out_features = quant_w.size(0)
84
+ inp = inp.contiguous().view(-1, inp.size(-1))
85
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
86
+ ctx.weight_shape = weight.size()
87
+ output = inp.mm(weight.t())
88
+ ctx.save_for_backward(inp, quant_w, scale_w)
89
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
90
+
91
+ @staticmethod
92
+ def backward(ctx, grad_output: torch.Tensor):
93
+ inp, quant_w, scale_w = ctx.saved_tensors
94
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
95
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
96
+ grad_input = grad_output.mm(weight)
97
+ grad_weight = grad_output.t().mm(inp)
98
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None, None
99
+
100
+
101
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
102
+ with torch.cuda.device(weight.device):
103
+ n, m = weight.size(0), weight.size(1)
104
+ assert m % 2 == 0
105
+ m = m // 2
106
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
107
+ stream = torch.cuda.current_stream()
108
+
109
+ gridDim = (n, 1, 1)
110
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
111
+
112
+ kernels.int4WeightCompression(
113
+ gridDim,
114
+ blockDim,
115
+ 0,
116
+ stream,
117
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
118
+ )
119
+ return out
120
+
121
+
122
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
123
+ assert scale_list.dtype in [torch.half, torch.bfloat16]
124
+ assert weight.dtype in [torch.int8]
125
+ if source_bit_width == 8:
126
+ return weight.to(scale_list.dtype) * scale_list[:, None]
127
+ elif source_bit_width == 4:
128
+ func = (
129
+ kernels.int4WeightExtractionHalf if scale_list.dtype == torch.half else kernels.int4WeightExtractionBFloat16
130
+ )
131
+ else:
132
+ assert False, "Unsupported bit-width"
133
+
134
+ with torch.cuda.device(weight.device):
135
+ n, m = weight.size(0), weight.size(1)
136
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=scale_list.dtype, device="cuda")
137
+ stream = torch.cuda.current_stream()
138
+
139
+ gridDim = (n, 1, 1)
140
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
141
+
142
+ func(
143
+ gridDim,
144
+ blockDim,
145
+ 0,
146
+ stream,
147
+ [
148
+ ctypes.c_void_p(weight.data_ptr()),
149
+ ctypes.c_void_p(scale_list.data_ptr()),
150
+ ctypes.c_void_p(out.data_ptr()),
151
+ ctypes.c_int32(n),
152
+ ctypes.c_int32(m),
153
+ ],
154
+ )
155
+ return out
156
+
157
+
158
+ class QuantizedLinear(torch.nn.Module):
159
+ def __init__(self, weight_bit_width: int, weight, bias=None, device="cuda", dtype=None, empty_init=False):
160
+ super().__init__()
161
+ weight = weight.to(device) # ensure the weight is on the cuda device
162
+ assert str(weight.device).startswith(
163
+ 'cuda'), 'The weights that need to be quantified should be on the CUDA device'
164
+ self.weight_bit_width = weight_bit_width
165
+ shape = weight.shape
166
+
167
+ if weight is None or empty_init:
168
+ self.weight = torch.empty(shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=device)
169
+ self.weight_scale = torch.empty(shape[0], dtype=dtype, device=device)
170
+ else:
171
+ self.weight_scale = weight.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)
172
+ self.weight = torch.round(weight / self.weight_scale[:, None]).to(torch.int8)
173
+ if weight_bit_width == 4:
174
+ self.weight = compress_int4_weight(self.weight)
175
+
176
+ self.weight = Parameter(self.weight.to(device), requires_grad=False)
177
+ self.weight_scale = Parameter(self.weight_scale.to(device), requires_grad=False)
178
+ self.bias = Parameter(bias.to(device), requires_grad=False) if bias is not None else None
179
+
180
+ def forward(self, input):
181
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
182
+ if self.bias is not None:
183
+ output = output + self.bias
184
+ return output
185
+
186
+
187
+ def quantize(model, weight_bit_width, empty_init=False, device=None):
188
+ """Replace fp16 linear with quantized linear"""
189
+ for layer in model.layers:
190
+ layer.self_attention.query_key_value = QuantizedLinear(
191
+ weight_bit_width=weight_bit_width,
192
+ weight=layer.self_attention.query_key_value.weight,
193
+ bias=layer.self_attention.query_key_value.bias,
194
+ dtype=layer.self_attention.query_key_value.weight.dtype,
195
+ device=layer.self_attention.query_key_value.weight.device if device is None else device,
196
+ empty_init=empty_init
197
+ )
198
+ layer.self_attention.dense = QuantizedLinear(
199
+ weight_bit_width=weight_bit_width,
200
+ weight=layer.self_attention.dense.weight,
201
+ bias=layer.self_attention.dense.bias,
202
+ dtype=layer.self_attention.dense.weight.dtype,
203
+ device=layer.self_attention.dense.weight.device if device is None else device,
204
+ empty_init=empty_init
205
+ )
206
+ layer.mlp.dense_h_to_4h = QuantizedLinear(
207
+ weight_bit_width=weight_bit_width,
208
+ weight=layer.mlp.dense_h_to_4h.weight,
209
+ bias=layer.mlp.dense_h_to_4h.bias,
210
+ dtype=layer.mlp.dense_h_to_4h.weight.dtype,
211
+ device=layer.mlp.dense_h_to_4h.weight.device if device is None else device,
212
+ empty_init=empty_init
213
+ )
214
+ layer.mlp.dense_4h_to_h = QuantizedLinear(
215
+ weight_bit_width=weight_bit_width,
216
+ weight=layer.mlp.dense_4h_to_h.weight,
217
+ bias=layer.mlp.dense_4h_to_h.bias,
218
+ dtype=layer.mlp.dense_4h_to_h.weight.dtype,
219
+ device=layer.mlp.dense_4h_to_h.weight.device if device is None else device,
220
+ empty_init=empty_init
221
+ )
222
+
223
+ return model
224
+
225
+
226
+
227
+ class ChatGLMConfig(PretrainedConfig):
228
+ model_type = "chatglm"
229
+ def __init__(
230
+ self,
231
+ num_layers=28,
232
+ padded_vocab_size=65024,
233
+ hidden_size=4096,
234
+ ffn_hidden_size=13696,
235
+ kv_channels=128,
236
+ num_attention_heads=32,
237
+ seq_length=2048,
238
+ hidden_dropout=0.0,
239
+ classifier_dropout=None,
240
+ attention_dropout=0.0,
241
+ layernorm_epsilon=1e-5,
242
+ rmsnorm=True,
243
+ apply_residual_connection_post_layernorm=False,
244
+ post_layer_norm=True,
245
+ add_bias_linear=False,
246
+ add_qkv_bias=False,
247
+ bias_dropout_fusion=True,
248
+ multi_query_attention=False,
249
+ multi_query_group_num=1,
250
+ apply_query_key_layer_scaling=True,
251
+ attention_softmax_in_fp32=True,
252
+ fp32_residual_connection=False,
253
+ quantization_bit=0,
254
+ pre_seq_len=None,
255
+ prefix_projection=False,
256
+ **kwargs
257
+ ):
258
+ self.num_layers = num_layers
259
+ self.vocab_size = padded_vocab_size
260
+ self.padded_vocab_size = padded_vocab_size
261
+ self.hidden_size = hidden_size
262
+ self.ffn_hidden_size = ffn_hidden_size
263
+ self.kv_channels = kv_channels
264
+ self.num_attention_heads = num_attention_heads
265
+ self.seq_length = seq_length
266
+ self.hidden_dropout = hidden_dropout
267
+ self.classifier_dropout = classifier_dropout
268
+ self.attention_dropout = attention_dropout
269
+ self.layernorm_epsilon = layernorm_epsilon
270
+ self.rmsnorm = rmsnorm
271
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
272
+ self.post_layer_norm = post_layer_norm
273
+ self.add_bias_linear = add_bias_linear
274
+ self.add_qkv_bias = add_qkv_bias
275
+ self.bias_dropout_fusion = bias_dropout_fusion
276
+ self.multi_query_attention = multi_query_attention
277
+ self.multi_query_group_num = multi_query_group_num
278
+ self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
279
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
280
+ self.fp32_residual_connection = fp32_residual_connection
281
+ self.quantization_bit = quantization_bit
282
+ self.pre_seq_len = pre_seq_len
283
+ self.prefix_projection = prefix_projection
284
+ super().__init__(**kwargs)
285
+
286
+
287
+
288
+ # flags required to enable jit fusion kernels
289
+
290
+ if sys.platform != 'darwin':
291
+ torch._C._jit_set_profiling_mode(False)
292
+ torch._C._jit_set_profiling_executor(False)
293
+ torch._C._jit_override_can_fuse_on_cpu(True)
294
+ torch._C._jit_override_can_fuse_on_gpu(True)
295
+
296
+ logger = logging.get_logger(__name__)
297
+
298
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM"
299
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
300
+
301
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
302
+ "THUDM/chatglm3-6b-base",
303
+ # See all ChatGLM models at https://huggingface.co/models?filter=chatglm
304
+ ]
305
+
306
+
307
+ def default_init(cls, *args, **kwargs):
308
+ return cls(*args, **kwargs)
309
+
310
+
311
+ class InvalidScoreLogitsProcessor(LogitsProcessor):
312
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
313
+ if torch.isnan(scores).any() or torch.isinf(scores).any():
314
+ scores.zero_()
315
+ scores[..., 5] = 5e4
316
+ return scores
317
+
318
+
319
+ class PrefixEncoder(torch.nn.Module):
320
+ """
321
+ The torch.nn model to encode the prefix
322
+ Input shape: (batch-size, prefix-length)
323
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
324
+ """
325
+
326
+ def __init__(self, config: ChatGLMConfig):
327
+ super().__init__()
328
+ self.prefix_projection = config.prefix_projection
329
+ if self.prefix_projection:
330
+ # Use a two-layer MLP to encode the prefix
331
+ kv_size = config.num_layers * config.kv_channels * config.multi_query_group_num * 2
332
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, kv_size)
333
+ self.trans = torch.nn.Sequential(
334
+ torch.nn.Linear(kv_size, config.hidden_size),
335
+ torch.nn.Tanh(),
336
+ torch.nn.Linear(config.hidden_size, kv_size)
337
+ )
338
+ else:
339
+ self.embedding = torch.nn.Embedding(config.pre_seq_len,
340
+ config.num_layers * config.kv_channels * config.multi_query_group_num * 2)
341
+
342
+ def forward(self, prefix: torch.Tensor):
343
+ if self.prefix_projection:
344
+ prefix_tokens = self.embedding(prefix)
345
+ past_key_values = self.trans(prefix_tokens)
346
+ else:
347
+ past_key_values = self.embedding(prefix)
348
+ return past_key_values
349
+
350
+
351
+ def split_tensor_along_last_dim(
352
+ tensor: torch.Tensor,
353
+ num_partitions: int,
354
+ contiguous_split_chunks: bool = False,
355
+ ) -> List[torch.Tensor]:
356
+ """Split a tensor along its last dimension.
357
+
358
+ Arguments:
359
+ tensor: input tensor.
360
+ num_partitions: number of partitions to split the tensor
361
+ contiguous_split_chunks: If True, make each chunk contiguous
362
+ in memory.
363
+
364
+ Returns:
365
+ A list of Tensors
366
+ """
367
+ # Get the size and dimension.
368
+ last_dim = tensor.dim() - 1
369
+ last_dim_size = tensor.size()[last_dim] // num_partitions
370
+ # Split.
371
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
372
+ # Note: torch.split does not create contiguous tensors by default.
373
+ if contiguous_split_chunks:
374
+ return tuple(chunk.contiguous() for chunk in tensor_list)
375
+
376
+ return tensor_list
377
+
378
+
379
+ class RotaryEmbedding(nn.Module):
380
+ def __init__(self, dim, original_impl=False, device=None, dtype=None):
381
+ super().__init__()
382
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
383
+ self.register_buffer("inv_freq", inv_freq)
384
+ self.dim = dim
385
+ self.original_impl = original_impl
386
+
387
+ def forward_impl(
388
+ self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
389
+ ):
390
+ """Enhanced Transformer with Rotary Position Embedding.
391
+
392
+ Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
393
+ transformers/rope/__init__.py. MIT License:
394
+ https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
395
+ """
396
+ # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
397
+ theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
398
+
399
+ # Create position indexes `[0, 1, ..., seq_len - 1]`
400
+ seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
401
+
402
+ # Calculate the product of position index and $\theta_i$
403
+ idx_theta = torch.outer(seq_idx, theta).float()
404
+
405
+ cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
406
+
407
+ # this is to mimic the behaviour of complex32, else we will get different results
408
+ if dtype in (torch.float16, torch.bfloat16, torch.int8):
409
+ cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
410
+ return cache
411
+
412
+ def forward(self, max_seq_len, offset=0):
413
+ return self.forward_impl(
414
+ max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
415
+ )
416
+
417
+
418
+ @torch.jit.script
419
+ def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
420
+ # x: [sq, b, np, hn]
421
+ sq, b, np, hn = x.size(0), x.size(1), x.size(2), x.size(3)
422
+ rot_dim = rope_cache.shape[-2] * 2
423
+ x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
424
+ # truncate to support variable sizes
425
+ rope_cache = rope_cache[:sq]
426
+ xshaped = x.reshape(sq, -1, np, rot_dim // 2, 2)
427
+ rope_cache = rope_cache.view(sq, -1, 1, xshaped.size(3), 2)
428
+ x_out2 = torch.stack(
429
+ [
430
+ xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
431
+ xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
432
+ ],
433
+ -1,
434
+ )
435
+ x_out2 = x_out2.flatten(3)
436
+ return torch.cat((x_out2, x_pass), dim=-1)
437
+
438
+
439
+ class RMSNorm(torch.nn.Module):
440
+ def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
441
+ super().__init__()
442
+ self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
443
+ self.eps = eps
444
+
445
+ def forward(self, hidden_states: torch.Tensor):
446
+ input_dtype = hidden_states.dtype
447
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
448
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
449
+
450
+ return (self.weight * hidden_states).to(input_dtype)
451
+
452
+
453
+ class CoreAttention(torch.nn.Module):
454
+ def __init__(self, config: ChatGLMConfig, layer_number):
455
+ super(CoreAttention, self).__init__()
456
+
457
+ self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
458
+ self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
459
+ if self.apply_query_key_layer_scaling:
460
+ self.attention_softmax_in_fp32 = True
461
+ self.layer_number = max(1, layer_number)
462
+
463
+ projection_size = config.kv_channels * config.num_attention_heads
464
+
465
+ # Per attention head and per partition values.
466
+ self.hidden_size_per_partition = projection_size
467
+ self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
468
+ self.num_attention_heads_per_partition = config.num_attention_heads
469
+
470
+ coeff = None
471
+ self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
472
+ if self.apply_query_key_layer_scaling:
473
+ coeff = self.layer_number
474
+ self.norm_factor *= coeff
475
+ self.coeff = coeff
476
+
477
+ self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
478
+
479
+ def forward(self, query_layer, key_layer, value_layer, attention_mask):
480
+ pytorch_major_version = int(torch.__version__.split('.')[0])
481
+ if pytorch_major_version >= 2:
482
+ query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]]
483
+ if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
484
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
485
+ is_causal=True)
486
+ else:
487
+ if attention_mask is not None:
488
+ attention_mask = ~attention_mask
489
+ context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
490
+ attention_mask)
491
+ context_layer = context_layer.permute(2, 0, 1, 3)
492
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
493
+ context_layer = context_layer.reshape(*new_context_layer_shape)
494
+ else:
495
+ # Raw attention scores
496
+
497
+ # [b, np, sq, sk]
498
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
499
+
500
+ # [sq, b, np, hn] -> [sq, b * np, hn]
501
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
502
+ # [sk, b, np, hn] -> [sk, b * np, hn]
503
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
504
+
505
+ # preallocting input tensor: [b * np, sq, sk]
506
+ matmul_input_buffer = torch.empty(
507
+ output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
508
+ device=query_layer.device
509
+ )
510
+
511
+ # Raw attention scores. [b * np, sq, sk]
512
+ matmul_result = torch.baddbmm(
513
+ matmul_input_buffer,
514
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
515
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
516
+ beta=0.0,
517
+ alpha=(1.0 / self.norm_factor),
518
+ )
519
+
520
+ # change view to [b, np, sq, sk]
521
+ attention_scores = matmul_result.view(*output_size)
522
+
523
+ # ===========================
524
+ # Attention probs and dropout
525
+ # ===========================
526
+
527
+ # attention scores and attention mask [b, np, sq, sk]
528
+ if self.attention_softmax_in_fp32:
529
+ attention_scores = attention_scores.float()
530
+ if self.coeff is not None:
531
+ attention_scores = attention_scores * self.coeff
532
+ if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
533
+ attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
534
+ device=attention_scores.device, dtype=torch.bool)
535
+ attention_mask.tril_()
536
+ attention_mask = ~attention_mask
537
+ if attention_mask is not None:
538
+ attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
539
+ attention_probs = F.softmax(attention_scores, dim=-1)
540
+ attention_probs = attention_probs.type_as(value_layer)
541
+
542
+ # This is actually dropping out entire tokens to attend to, which might
543
+ # seem a bit unusual, but is taken from the original Transformer paper.
544
+ attention_probs = self.attention_dropout(attention_probs)
545
+ # =========================
546
+ # Context layer. [sq, b, hp]
547
+ # =========================
548
+
549
+ # value_layer -> context layer.
550
+ # [sk, b, np, hn] --> [b, np, sq, hn]
551
+
552
+ # context layer shape: [b, np, sq, hn]
553
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
554
+ # change view [sk, b * np, hn]
555
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
556
+ # change view [b * np, sq, sk]
557
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
558
+ # matmul: [b * np, sq, hn]
559
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
560
+ # change view [b, np, sq, hn]
561
+ context_layer = context_layer.view(*output_size)
562
+ # [b, np, sq, hn] --> [sq, b, np, hn]
563
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
564
+ # [sq, b, np, hn] --> [sq, b, hp]
565
+ new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
566
+ context_layer = context_layer.view(*new_context_layer_shape)
567
+
568
+ return context_layer
569
+
570
+
571
+ class SelfAttention(torch.nn.Module):
572
+ """Parallel self-attention layer abstract class.
573
+
574
+ Self-attention layer takes input with size [s, b, h]
575
+ and returns output of the same size.
576
+ """
577
+
578
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
579
+ super(SelfAttention, self).__init__()
580
+ self.layer_number = max(1, layer_number)
581
+
582
+ self.projection_size = config.kv_channels * config.num_attention_heads
583
+
584
+ # Per attention head and per partition values.
585
+ self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
586
+ self.num_attention_heads_per_partition = config.num_attention_heads
587
+
588
+ self.multi_query_attention = config.multi_query_attention
589
+ self.qkv_hidden_size = 3 * self.projection_size
590
+ if self.multi_query_attention:
591
+ self.num_multi_query_groups_per_partition = config.multi_query_group_num
592
+ self.qkv_hidden_size = (
593
+ self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
594
+ )
595
+ self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
596
+ bias=config.add_bias_linear or config.add_qkv_bias,
597
+ device=device, **_config_to_kwargs(config)
598
+ )
599
+
600
+ self.core_attention = CoreAttention(config, self.layer_number)
601
+
602
+ # Output.
603
+ self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
604
+ device=device, **_config_to_kwargs(config)
605
+ )
606
+
607
+ def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
608
+ if self.multi_query_attention:
609
+ num_attention_heads = self.num_multi_query_groups_per_partition
610
+ else:
611
+ num_attention_heads = self.num_attention_heads_per_partition
612
+ return torch.empty(
613
+ inference_max_sequence_len,
614
+ batch_size,
615
+ num_attention_heads,
616
+ self.hidden_size_per_attention_head,
617
+ dtype=dtype,
618
+ device=device,
619
+ )
620
+
621
+ def forward(
622
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
623
+ ):
624
+ # hidden_states: [sq, b, h]
625
+
626
+ # =================================================
627
+ # Pre-allocate memory for key-values for inference.
628
+ # =================================================
629
+ # =====================
630
+ # Query, Key, and Value
631
+ # =====================
632
+
633
+ # Attention heads [sq, b, h] --> [sq, b, (np * 3 * hn)]
634
+ mixed_x_layer = self.query_key_value(hidden_states)
635
+
636
+ if self.multi_query_attention:
637
+ (query_layer, key_layer, value_layer) = mixed_x_layer.split(
638
+ [
639
+ self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
640
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
641
+ self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
642
+ ],
643
+ dim=-1,
644
+ )
645
+ query_layer = query_layer.view(
646
+ query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
647
+ )
648
+ key_layer = key_layer.view(
649
+ key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
650
+ )
651
+ value_layer = value_layer.view(
652
+ value_layer.size()[:-1]
653
+ + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
654
+ )
655
+ else:
656
+ new_tensor_shape = mixed_x_layer.size()[:-1] + \
657
+ (self.num_attention_heads_per_partition,
658
+ 3 * self.hidden_size_per_attention_head)
659
+ mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
660
+
661
+ # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
662
+ (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
663
+
664
+ # apply relative positional encoding (rotary embedding)
665
+ if rotary_pos_emb is not None:
666
+ query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
667
+ key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
668
+
669
+ # adjust key and value for inference
670
+ if kv_cache is not None:
671
+ cache_k, cache_v = kv_cache
672
+ key_layer = torch.cat((cache_k, key_layer), dim=0)
673
+ value_layer = torch.cat((cache_v, value_layer), dim=0)
674
+ if use_cache:
675
+ kv_cache = (key_layer, value_layer)
676
+ else:
677
+ kv_cache = None
678
+
679
+ if self.multi_query_attention:
680
+ key_layer = key_layer.unsqueeze(-2)
681
+ key_layer = key_layer.expand(
682
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
683
+ )
684
+ key_layer = key_layer.contiguous().view(
685
+ key_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
686
+ )
687
+ value_layer = value_layer.unsqueeze(-2)
688
+ value_layer = value_layer.expand(
689
+ -1, -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1
690
+ )
691
+ value_layer = value_layer.contiguous().view(
692
+ value_layer.size()[:2] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
693
+ )
694
+
695
+ # ==================================
696
+ # core attention computation
697
+ # ==================================
698
+
699
+ context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
700
+
701
+ # =================
702
+ # Output. [sq, b, h]
703
+ # =================
704
+
705
+ output = self.dense(context_layer)
706
+
707
+ return output, kv_cache
708
+
709
+
710
+ def _config_to_kwargs(args):
711
+ common_kwargs = {
712
+ "dtype": args.torch_dtype,
713
+ }
714
+ return common_kwargs
715
+
716
+
717
+ class MLP(torch.nn.Module):
718
+ """MLP.
719
+
720
+ MLP will take the input with h hidden state, project it to 4*h
721
+ hidden dimension, perform nonlinear transformation, and project the
722
+ state back into h hidden dimension.
723
+ """
724
+
725
+ def __init__(self, config: ChatGLMConfig, device=None):
726
+ super(MLP, self).__init__()
727
+
728
+ self.add_bias = config.add_bias_linear
729
+
730
+ # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
731
+ self.dense_h_to_4h = nn.Linear(
732
+ config.hidden_size,
733
+ config.ffn_hidden_size * 2,
734
+ bias=self.add_bias,
735
+ device=device,
736
+ **_config_to_kwargs(config)
737
+ )
738
+
739
+ def swiglu(x):
740
+ x = torch.chunk(x, 2, dim=-1)
741
+ return F.silu(x[0]) * x[1]
742
+
743
+ self.activation_func = swiglu
744
+
745
+ # Project back to h.
746
+ self.dense_4h_to_h = nn.Linear(
747
+ config.ffn_hidden_size,
748
+ config.hidden_size,
749
+ bias=self.add_bias,
750
+ device=device,
751
+ **_config_to_kwargs(config)
752
+ )
753
+
754
+ def forward(self, hidden_states):
755
+ # [s, b, 4hp]
756
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
757
+ intermediate_parallel = self.activation_func(intermediate_parallel)
758
+ # [s, b, h]
759
+ output = self.dense_4h_to_h(intermediate_parallel)
760
+ return output
761
+
762
+
763
+ class GLMBlock(torch.nn.Module):
764
+ """A single transformer layer.
765
+
766
+ Transformer layer takes input with size [s, b, h] and returns an
767
+ output of the same size.
768
+ """
769
+
770
+ def __init__(self, config: ChatGLMConfig, layer_number, device=None):
771
+ super(GLMBlock, self).__init__()
772
+ self.layer_number = layer_number
773
+
774
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
775
+
776
+ self.fp32_residual_connection = config.fp32_residual_connection
777
+
778
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
779
+ # Layernorm on the input data.
780
+ self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
781
+ dtype=config.torch_dtype)
782
+
783
+ # Self attention.
784
+ self.self_attention = SelfAttention(config, layer_number, device=device)
785
+ self.hidden_dropout = config.hidden_dropout
786
+
787
+ # Layernorm on the attention output
788
+ self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
789
+ dtype=config.torch_dtype)
790
+
791
+ # MLP
792
+ self.mlp = MLP(config, device=device)
793
+
794
+ def forward(
795
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
796
+ ):
797
+ # hidden_states: [s, b, h]
798
+
799
+ # Layer norm at the beginning of the transformer layer.
800
+ layernorm_output = self.input_layernorm(hidden_states)
801
+ # Self attention.
802
+ attention_output, kv_cache = self.self_attention(
803
+ layernorm_output,
804
+ attention_mask,
805
+ rotary_pos_emb,
806
+ kv_cache=kv_cache,
807
+ use_cache=use_cache
808
+ )
809
+
810
+ # Residual connection.
811
+ if self.apply_residual_connection_post_layernorm:
812
+ residual = layernorm_output
813
+ else:
814
+ residual = hidden_states
815
+
816
+ layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
817
+ layernorm_input = residual + layernorm_input
818
+
819
+ # Layer norm post the self attention.
820
+ layernorm_output = self.post_attention_layernorm(layernorm_input)
821
+
822
+ # MLP.
823
+ mlp_output = self.mlp(layernorm_output)
824
+
825
+ # Second residual connection.
826
+ if self.apply_residual_connection_post_layernorm:
827
+ residual = layernorm_output
828
+ else:
829
+ residual = layernorm_input
830
+
831
+ output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
832
+ output = residual + output
833
+
834
+ return output, kv_cache
835
+
836
+
837
+ class GLMTransformer(torch.nn.Module):
838
+ """Transformer class."""
839
+
840
+ def __init__(self, config: ChatGLMConfig, device=None):
841
+ super(GLMTransformer, self).__init__()
842
+
843
+ self.fp32_residual_connection = config.fp32_residual_connection
844
+ self.post_layer_norm = config.post_layer_norm
845
+
846
+ # Number of layers.
847
+ self.num_layers = config.num_layers
848
+
849
+ # Transformer layers.
850
+ def build_layer(layer_number):
851
+ return GLMBlock(config, layer_number, device=device)
852
+
853
+ self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
854
+
855
+ if self.post_layer_norm:
856
+ LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
857
+ # Final layer norm before output.
858
+ self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
859
+ dtype=config.torch_dtype)
860
+
861
+ self.gradient_checkpointing = False
862
+
863
+ def _get_layer(self, layer_number):
864
+ return self.layers[layer_number]
865
+
866
+ def forward(
867
+ self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
868
+ use_cache: Optional[bool] = True,
869
+ output_hidden_states: Optional[bool] = False,
870
+ ):
871
+ if not kv_caches:
872
+ kv_caches = [None for _ in range(self.num_layers)]
873
+ presents = () if use_cache else None
874
+ if self.gradient_checkpointing and self.training:
875
+ if use_cache:
876
+ logger.warning_once(
877
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
878
+ )
879
+ use_cache = False
880
+
881
+ all_self_attentions = None
882
+ all_hidden_states = () if output_hidden_states else None
883
+ for index in range(self.num_layers):
884
+ if output_hidden_states:
885
+ all_hidden_states = all_hidden_states + (hidden_states,)
886
+
887
+ layer = self._get_layer(index)
888
+ if self.gradient_checkpointing and self.training:
889
+ layer_ret = torch.utils.checkpoint.checkpoint(
890
+ layer,
891
+ hidden_states,
892
+ attention_mask,
893
+ rotary_pos_emb,
894
+ kv_caches[index],
895
+ use_cache
896
+ )
897
+ else:
898
+ layer_ret = layer(
899
+ hidden_states,
900
+ attention_mask,
901
+ rotary_pos_emb,
902
+ kv_cache=kv_caches[index],
903
+ use_cache=use_cache
904
+ )
905
+ hidden_states, kv_cache = layer_ret
906
+ if use_cache:
907
+ presents = presents + (kv_cache,)
908
+
909
+ if output_hidden_states:
910
+ all_hidden_states = all_hidden_states + (hidden_states,)
911
+
912
+ # Final layer norm.
913
+ if self.post_layer_norm:
914
+ hidden_states = self.final_layernorm(hidden_states)
915
+
916
+ return hidden_states, presents, all_hidden_states, all_self_attentions
917
+
918
+
919
+ class ChatGLMPreTrainedModel(PreTrainedModel):
920
+ """
921
+ An abstract class to handle weights initialization and
922
+ a simple interface for downloading and loading pretrained models.
923
+ """
924
+
925
+ is_parallelizable = False
926
+ supports_gradient_checkpointing = True
927
+ config_class = ChatGLMConfig
928
+ base_model_prefix = "transformer"
929
+ _no_split_modules = ["GLMBlock"]
930
+
931
+ def _init_weights(self, module: nn.Module):
932
+ """Initialize the weights."""
933
+ return
934
+
935
+ def get_masks(self, input_ids, past_key_values, padding_mask=None):
936
+ batch_size, seq_length = input_ids.shape
937
+ full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
938
+ full_attention_mask.tril_()
939
+ past_length = 0
940
+ if past_key_values:
941
+ past_length = past_key_values[0][0].shape[0]
942
+ if past_length:
943
+ full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
944
+ device=input_ids.device), full_attention_mask), dim=-1)
945
+ if padding_mask is not None:
946
+ full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
947
+ if not past_length and padding_mask is not None:
948
+ full_attention_mask -= padding_mask.unsqueeze(-1) - 1
949
+ full_attention_mask = (full_attention_mask < 0.5).bool()
950
+ full_attention_mask.unsqueeze_(1)
951
+ return full_attention_mask
952
+
953
+ def get_position_ids(self, input_ids, device):
954
+ batch_size, seq_length = input_ids.shape
955
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
956
+ return position_ids
957
+
958
+ def _set_gradient_checkpointing(self, module, value=False):
959
+ if isinstance(module, GLMTransformer):
960
+ module.gradient_checkpointing = value
961
+
962
+
963
+ class Embedding(torch.nn.Module):
964
+ """Language model embeddings."""
965
+
966
+ def __init__(self, config: ChatGLMConfig, device=None):
967
+ super(Embedding, self).__init__()
968
+
969
+ self.hidden_size = config.hidden_size
970
+ # Word embeddings (parallel).
971
+ self.word_embeddings = nn.Embedding(
972
+ config.padded_vocab_size,
973
+ self.hidden_size,
974
+ dtype=config.torch_dtype,
975
+ device=device
976
+ )
977
+ self.fp32_residual_connection = config.fp32_residual_connection
978
+
979
+ def forward(self, input_ids):
980
+ # Embeddings.
981
+ words_embeddings = self.word_embeddings(input_ids)
982
+ embeddings = words_embeddings
983
+ # Data format change to avoid explicit transposes : [b s h] --> [s b h].
984
+ embeddings = embeddings.transpose(0, 1).contiguous()
985
+ # If the input flag for fp32 residual connection is set, convert for float.
986
+ if self.fp32_residual_connection:
987
+ embeddings = embeddings.float()
988
+ return embeddings
989
+
990
+
991
+ class ChatGLMModel(ChatGLMPreTrainedModel):
992
+ def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
993
+ super().__init__(config)
994
+ if empty_init:
995
+ init_method = skip_init
996
+ else:
997
+ init_method = default_init
998
+ init_kwargs = {}
999
+ if device is not None:
1000
+ init_kwargs["device"] = device
1001
+ self.embedding = init_method(Embedding, config, **init_kwargs)
1002
+ self.num_layers = config.num_layers
1003
+ self.multi_query_group_num = config.multi_query_group_num
1004
+ self.kv_channels = config.kv_channels
1005
+
1006
+ # Rotary positional embeddings
1007
+ self.seq_length = config.seq_length
1008
+ rotary_dim = (
1009
+ config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
1010
+ )
1011
+
1012
+ self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, original_impl=config.original_rope, device=device,
1013
+ dtype=config.torch_dtype)
1014
+ self.encoder = init_method(GLMTransformer, config, **init_kwargs)
1015
+ self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
1016
+ dtype=config.torch_dtype, **init_kwargs)
1017
+ self.pre_seq_len = config.pre_seq_len
1018
+ self.prefix_projection = config.prefix_projection
1019
+ if self.pre_seq_len is not None:
1020
+ for param in self.parameters():
1021
+ param.requires_grad = False
1022
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
1023
+ self.prefix_encoder = PrefixEncoder(config)
1024
+ self.dropout = torch.nn.Dropout(0.1)
1025
+
1026
+ def get_input_embeddings(self):
1027
+ return self.embedding.word_embeddings
1028
+
1029
+ def get_prompt(self, batch_size, device, dtype=torch.half):
1030
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
1031
+ past_key_values = self.prefix_encoder(prefix_tokens).type(dtype)
1032
+ past_key_values = past_key_values.view(
1033
+ batch_size,
1034
+ self.pre_seq_len,
1035
+ self.num_layers * 2,
1036
+ self.multi_query_group_num,
1037
+ self.kv_channels
1038
+ )
1039
+ # seq_len, b, nh, hidden_size
1040
+ past_key_values = self.dropout(past_key_values)
1041
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
1042
+ return past_key_values
1043
+
1044
+ def forward(
1045
+ self,
1046
+ input_ids,
1047
+ position_ids: Optional[torch.Tensor] = None,
1048
+ attention_mask: Optional[torch.BoolTensor] = None,
1049
+ full_attention_mask: Optional[torch.BoolTensor] = None,
1050
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1051
+ inputs_embeds: Optional[torch.Tensor] = None,
1052
+ use_cache: Optional[bool] = None,
1053
+ output_hidden_states: Optional[bool] = None,
1054
+ return_dict: Optional[bool] = None,
1055
+ ):
1056
+ output_hidden_states = (
1057
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1058
+ )
1059
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1060
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1061
+
1062
+ batch_size, seq_length = input_ids.shape
1063
+
1064
+ if inputs_embeds is None:
1065
+ inputs_embeds = self.embedding(input_ids)
1066
+
1067
+ if self.pre_seq_len is not None:
1068
+ if past_key_values is None:
1069
+ past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
1070
+ dtype=inputs_embeds.dtype)
1071
+ if attention_mask is not None:
1072
+ attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
1073
+ attention_mask], dim=-1)
1074
+
1075
+ if full_attention_mask is None:
1076
+ if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
1077
+ full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
1078
+
1079
+ # Rotary positional embeddings
1080
+ rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
1081
+ if position_ids is not None:
1082
+ rotary_pos_emb = rotary_pos_emb[position_ids]
1083
+ else:
1084
+ rotary_pos_emb = rotary_pos_emb[None, :seq_length]
1085
+ rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
1086
+
1087
+ # Run encoder.
1088
+ hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
1089
+ inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
1090
+ kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
1091
+ )
1092
+
1093
+ if not return_dict:
1094
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1095
+
1096
+ return BaseModelOutputWithPast(
1097
+ last_hidden_state=hidden_states,
1098
+ past_key_values=presents,
1099
+ hidden_states=all_hidden_states,
1100
+ attentions=all_self_attentions,
1101
+ )
1102
+
1103
+ def quantize(self, weight_bit_width: int):
1104
+ # from .quantization import quantize
1105
+ quantize(self.encoder, weight_bit_width)
1106
+ return self
1107
+
1108
+
1109
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1110
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1111
+ super().__init__(config)
1112
+
1113
+ self.max_sequence_length = config.max_length
1114
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1115
+ self.config = config
1116
+ self.quantized = False
1117
+
1118
+ if self.config.quantization_bit:
1119
+ self.quantize(self.config.quantization_bit, empty_init=True)
1120
+
1121
+ def _update_model_kwargs_for_generation(
1122
+ self,
1123
+ outputs: ModelOutput,
1124
+ model_kwargs: Dict[str, Any],
1125
+ is_encoder_decoder: bool = False,
1126
+ standardize_cache_format: bool = False,
1127
+ ) -> Dict[str, Any]:
1128
+ # update past_key_values
1129
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
1130
+ outputs, standardize_cache_format=standardize_cache_format
1131
+ )
1132
+
1133
+ # update attention mask
1134
+ if "attention_mask" in model_kwargs:
1135
+ attention_mask = model_kwargs["attention_mask"]
1136
+ model_kwargs["attention_mask"] = torch.cat(
1137
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
1138
+ )
1139
+
1140
+ # update position ids
1141
+ if "position_ids" in model_kwargs:
1142
+ position_ids = model_kwargs["position_ids"]
1143
+ new_position_id = position_ids[..., -1:].clone()
1144
+ new_position_id += 1
1145
+ model_kwargs["position_ids"] = torch.cat(
1146
+ [position_ids, new_position_id], dim=-1
1147
+ )
1148
+
1149
+ model_kwargs["is_first_forward"] = False
1150
+ return model_kwargs
1151
+
1152
+ def prepare_inputs_for_generation(
1153
+ self,
1154
+ input_ids: torch.LongTensor,
1155
+ past_key_values: Optional[torch.Tensor] = None,
1156
+ attention_mask: Optional[torch.Tensor] = None,
1157
+ position_ids: Optional[torch.Tensor] = None,
1158
+ use_cache: Optional[bool] = None,
1159
+ is_first_forward: bool = True,
1160
+ **kwargs
1161
+ ) -> dict:
1162
+ # only last token for input_ids if past is not None
1163
+ if position_ids is None:
1164
+ position_ids = self.get_position_ids(input_ids, device=input_ids.device)
1165
+ if not is_first_forward:
1166
+ if past_key_values is not None:
1167
+ position_ids = position_ids[..., -1:]
1168
+ input_ids = input_ids[:, -1:]
1169
+ return {
1170
+ "input_ids": input_ids,
1171
+ "past_key_values": past_key_values,
1172
+ "position_ids": position_ids,
1173
+ "attention_mask": attention_mask,
1174
+ "return_last_logit": True,
1175
+ "use_cache": use_cache
1176
+ }
1177
+
1178
+ def forward(
1179
+ self,
1180
+ input_ids: Optional[torch.Tensor] = None,
1181
+ position_ids: Optional[torch.Tensor] = None,
1182
+ attention_mask: Optional[torch.Tensor] = None,
1183
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1184
+ inputs_embeds: Optional[torch.Tensor] = None,
1185
+ labels: Optional[torch.Tensor] = None,
1186
+ use_cache: Optional[bool] = None,
1187
+ output_attentions: Optional[bool] = None,
1188
+ output_hidden_states: Optional[bool] = None,
1189
+ return_dict: Optional[bool] = None,
1190
+ return_last_logit: Optional[bool] = False,
1191
+ ):
1192
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1193
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1194
+
1195
+ transformer_outputs = self.transformer(
1196
+ input_ids=input_ids,
1197
+ position_ids=position_ids,
1198
+ attention_mask=attention_mask,
1199
+ past_key_values=past_key_values,
1200
+ inputs_embeds=inputs_embeds,
1201
+ use_cache=use_cache,
1202
+ output_hidden_states=output_hidden_states,
1203
+ return_dict=return_dict,
1204
+ )
1205
+
1206
+ hidden_states = transformer_outputs[0]
1207
+ if return_last_logit:
1208
+ hidden_states = hidden_states[-1:]
1209
+ lm_logits = self.transformer.output_layer(hidden_states)
1210
+ lm_logits = lm_logits.transpose(0, 1).contiguous()
1211
+
1212
+ loss = None
1213
+ if labels is not None:
1214
+ lm_logits = lm_logits.to(torch.float32)
1215
+
1216
+ # Shift so that tokens < n predict n
1217
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1218
+ shift_labels = labels[..., 1:].contiguous()
1219
+ # Flatten the tokens
1220
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1221
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1222
+
1223
+ lm_logits = lm_logits.to(hidden_states.dtype)
1224
+ loss = loss.to(hidden_states.dtype)
1225
+
1226
+ if not return_dict:
1227
+ output = (lm_logits,) + transformer_outputs[1:]
1228
+ return ((loss,) + output) if loss is not None else output
1229
+
1230
+ return CausalLMOutputWithPast(
1231
+ loss=loss,
1232
+ logits=lm_logits,
1233
+ past_key_values=transformer_outputs.past_key_values,
1234
+ hidden_states=transformer_outputs.hidden_states,
1235
+ attentions=transformer_outputs.attentions,
1236
+ )
1237
+
1238
+ @staticmethod
1239
+ def _reorder_cache(
1240
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1241
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1242
+ """
1243
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1244
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1245
+ beam_idx at every generation step.
1246
+
1247
+ Output shares the same memory storage as `past`.
1248
+ """
1249
+ return tuple(
1250
+ (
1251
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1252
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1253
+ )
1254
+ for layer_past in past
1255
+ )
1256
+
1257
+ def process_response(self, output, history):
1258
+ content = ""
1259
+ history = deepcopy(history)
1260
+ for response in output.split("<|assistant|>"):
1261
+ metadata, content = response.split("\n", maxsplit=1)
1262
+ if not metadata.strip():
1263
+ content = content.strip()
1264
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1265
+ content = content.replace("[[训练时间]]", "2023年")
1266
+ else:
1267
+ history.append({"role": "assistant", "metadata": metadata, "content": content})
1268
+ if history[0]["role"] == "system" and "tools" in history[0]:
1269
+ content = "\n".join(content.split("\n")[1:-1])
1270
+ def tool_call(**kwargs):
1271
+ return kwargs
1272
+ parameters = eval(content)
1273
+ content = {"name": metadata.strip(), "parameters": parameters}
1274
+ else:
1275
+ content = {"name": metadata.strip(), "content": content}
1276
+ return content, history
1277
+
1278
+ @torch.inference_mode()
1279
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, role: str = "user",
1280
+ max_length: int = 8192, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
1281
+ **kwargs):
1282
+ if history is None:
1283
+ history = []
1284
+ if logits_processor is None:
1285
+ logits_processor = LogitsProcessorList()
1286
+ logits_processor.append(InvalidScoreLogitsProcessor())
1287
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1288
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1289
+ inputs = tokenizer.build_chat_input(query, history=history, role=role)
1290
+ inputs = inputs.to(self.device)
1291
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
1292
+ tokenizer.get_command("<|observation|>")]
1293
+ outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
1294
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1295
+ response = tokenizer.decode(outputs)
1296
+ history.append({"role": role, "content": query})
1297
+ response, history = self.process_response(response, history)
1298
+ return response, history
1299
+
1300
+ @torch.inference_mode()
1301
+ def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, role: str = "user",
1302
+ past_key_values=None,max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8,
1303
+ logits_processor=None, return_past_key_values=False, **kwargs):
1304
+ if history is None:
1305
+ history = []
1306
+ if logits_processor is None:
1307
+ logits_processor = LogitsProcessorList()
1308
+ logits_processor.append(InvalidScoreLogitsProcessor())
1309
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
1310
+ tokenizer.get_command("<|observation|>")]
1311
+ gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
1312
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
1313
+ if past_key_values is None:
1314
+ inputs = tokenizer.build_chat_input(query, history=history, role=role)
1315
+ else:
1316
+ inputs = tokenizer.build_chat_input(query, role=role)
1317
+ inputs = inputs.to(self.device)
1318
+ if past_key_values is not None:
1319
+ past_length = past_key_values[0][0].shape[0]
1320
+ if self.transformer.pre_seq_len is not None:
1321
+ past_length -= self.transformer.pre_seq_len
1322
+ inputs.position_ids += past_length
1323
+ attention_mask = inputs.attention_mask
1324
+ attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
1325
+ inputs['attention_mask'] = attention_mask
1326
+ history.append({"role": role, "content": query})
1327
+ for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
1328
+ eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
1329
+ **gen_kwargs):
1330
+ if return_past_key_values:
1331
+ outputs, past_key_values = outputs
1332
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
1333
+ response = tokenizer.decode(outputs)
1334
+ if response and response[-1] != "�":
1335
+ response, new_history = self.process_response(response, history)
1336
+ if return_past_key_values:
1337
+ yield response, new_history, past_key_values
1338
+ else:
1339
+ yield response, new_history
1340
+
1341
+ @torch.inference_mode()
1342
+ def stream_generate(
1343
+ self,
1344
+ input_ids,
1345
+ generation_config: Optional[GenerationConfig] = None,
1346
+ logits_processor: Optional[LogitsProcessorList] = None,
1347
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
1348
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1349
+ return_past_key_values=False,
1350
+ **kwargs,
1351
+ ):
1352
+ batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
1353
+
1354
+ if generation_config is None:
1355
+ generation_config = self.generation_config
1356
+ generation_config = copy.deepcopy(generation_config)
1357
+ model_kwargs = generation_config.update(**kwargs)
1358
+ model_kwargs["use_cache"] = generation_config.use_cache
1359
+ bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
1360
+
1361
+ if isinstance(eos_token_id, int):
1362
+ eos_token_id = [eos_token_id]
1363
+ eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
1364
+
1365
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1366
+ if has_default_max_length and generation_config.max_new_tokens is None:
1367
+ warnings.warn(
1368
+ f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
1369
+ "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
1370
+ " recommend using `max_new_tokens` to control the maximum length of the generation.",
1371
+ UserWarning,
1372
+ )
1373
+ elif generation_config.max_new_tokens is not None:
1374
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
1375
+ if not has_default_max_length:
1376
+ logger.warning(
1377
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
1378
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
1379
+ "Please refer to the documentation for more information. "
1380
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
1381
+ UserWarning,
1382
+ )
1383
+
1384
+ if input_ids_seq_length >= generation_config.max_length:
1385
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1386
+ logger.warning(
1387
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
1388
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1389
+ " increasing `max_new_tokens`."
1390
+ )
1391
+
1392
+ # 2. Set generation parameters if not already defined
1393
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
1394
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
1395
+
1396
+ logits_processor = self._get_logits_processor(
1397
+ generation_config=generation_config,
1398
+ input_ids_seq_length=input_ids_seq_length,
1399
+ encoder_input_ids=input_ids,
1400
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
1401
+ logits_processor=logits_processor,
1402
+ )
1403
+
1404
+ stopping_criteria = self._get_stopping_criteria(
1405
+ generation_config=generation_config, stopping_criteria=stopping_criteria
1406
+ )
1407
+ logits_warper = self._get_logits_warper(generation_config)
1408
+
1409
+ unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
1410
+ scores = None
1411
+ while True:
1412
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
1413
+ # forward pass to get next token
1414
+ outputs = self(
1415
+ **model_inputs,
1416
+ return_dict=True,
1417
+ output_attentions=False,
1418
+ output_hidden_states=False,
1419
+ )
1420
+
1421
+ next_token_logits = outputs.logits[:, -1, :]
1422
+
1423
+ # pre-process distribution
1424
+ next_token_scores = logits_processor(input_ids, next_token_logits)
1425
+ next_token_scores = logits_warper(input_ids, next_token_scores)
1426
+
1427
+ # sample
1428
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
1429
+ if generation_config.do_sample:
1430
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
1431
+ else:
1432
+ next_tokens = torch.argmax(probs, dim=-1)
1433
+ # update generated ids, model inputs, and length for next step
1434
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
1435
+ model_kwargs = self._update_model_kwargs_for_generation(
1436
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
1437
+ )
1438
+ unfinished_sequences = unfinished_sequences.mul(
1439
+ next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
1440
+ )
1441
+ if return_past_key_values:
1442
+ yield input_ids, outputs.past_key_values
1443
+ else:
1444
+ yield input_ids
1445
+ # stop when each sentence is finished, or if we exceed the maximum length
1446
+ if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
1447
+ break
1448
+
1449
+ def quantize(self, bits: int, empty_init=False, device=None, **kwargs):
1450
+ if bits == 0:
1451
+ return
1452
+
1453
+ # from .quantization import quantize
1454
+
1455
+ if self.quantized:
1456
+ logger.info("Already quantized.")
1457
+ return self
1458
+
1459
+ self.quantized = True
1460
+
1461
+ self.config.quantization_bit = bits
1462
+
1463
+ self.transformer.encoder = quantize(self.transformer.encoder, bits, empty_init=empty_init, device=device,
1464
+ **kwargs)
1465
+ return self
1466
+
1467
+
1468
+ class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
1469
+ def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
1470
+ super().__init__(config)
1471
+
1472
+ self.num_labels = config.num_labels
1473
+ self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
1474
+
1475
+ self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
1476
+ if config.classifier_dropout is not None:
1477
+ self.dropout = nn.Dropout(config.classifier_dropout)
1478
+ else:
1479
+ self.dropout = None
1480
+ self.config = config
1481
+
1482
+ if self.config.quantization_bit:
1483
+ self.quantize(self.config.quantization_bit, empty_init=True)
1484
+
1485
+ def forward(
1486
+ self,
1487
+ input_ids: Optional[torch.LongTensor] = None,
1488
+ position_ids: Optional[torch.LongTensor] = None,
1489
+ attention_mask: Optional[torch.Tensor] = None,
1490
+ full_attention_mask: Optional[torch.Tensor] = None,
1491
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1492
+ inputs_embeds: Optional[torch.LongTensor] = None,
1493
+ labels: Optional[torch.LongTensor] = None,
1494
+ use_cache: Optional[bool] = None,
1495
+ output_hidden_states: Optional[bool] = None,
1496
+ return_dict: Optional[bool] = None,
1497
+ ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
1498
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1499
+
1500
+ transformer_outputs = self.transformer(
1501
+ input_ids=input_ids,
1502
+ position_ids=position_ids,
1503
+ attention_mask=attention_mask,
1504
+ full_attention_mask=full_attention_mask,
1505
+ past_key_values=past_key_values,
1506
+ inputs_embeds=inputs_embeds,
1507
+ use_cache=use_cache,
1508
+ output_hidden_states=output_hidden_states,
1509
+ return_dict=return_dict,
1510
+ )
1511
+
1512
+ hidden_states = transformer_outputs[0]
1513
+ pooled_hidden_states = hidden_states[-1]
1514
+ if self.dropout is not None:
1515
+ pooled_hidden_states = self.dropout(pooled_hidden_states)
1516
+ logits = self.classifier_head(pooled_hidden_states)
1517
+
1518
+ loss = None
1519
+ if labels is not None:
1520
+ if self.config.problem_type is None:
1521
+ if self.num_labels == 1:
1522
+ self.config.problem_type = "regression"
1523
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1524
+ self.config.problem_type = "single_label_classification"
1525
+ else:
1526
+ self.config.problem_type = "multi_label_classification"
1527
+
1528
+ if self.config.problem_type == "regression":
1529
+ loss_fct = MSELoss()
1530
+ if self.num_labels == 1:
1531
+ loss = loss_fct(logits.squeeze().float(), labels.squeeze())
1532
+ else:
1533
+ loss = loss_fct(logits.float(), labels)
1534
+ elif self.config.problem_type == "single_label_classification":
1535
+ loss_fct = CrossEntropyLoss()
1536
+ loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
1537
+ elif self.config.problem_type == "multi_label_classification":
1538
+ loss_fct = BCEWithLogitsLoss()
1539
+ loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
1540
+
1541
+ if not return_dict:
1542
+ output = (logits,) + transformer_outputs[1:]
1543
+ return ((loss,) + output) if loss is not None else output
1544
+
1545
+ return SequenceClassifierOutputWithPast(
1546
+ loss=loss,
1547
+ logits=logits,
1548
+ past_key_values=transformer_outputs.past_key_values,
1549
+ hidden_states=transformer_outputs.hidden_states,
1550
+ attentions=transformer_outputs.attentions,
1551
+ )
lora.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_unet import SDUNet
3
+ from .sdxl_unet import SDXLUNet
4
+ from .sd_text_encoder import SDTextEncoder
5
+ from .sdxl_text_encoder import SDXLTextEncoder, SDXLTextEncoder2
6
+ from .sd3_dit import SD3DiT
7
+ from .flux_dit import FluxDiT
8
+ from .hunyuan_dit import HunyuanDiT
9
+ from .cog_dit import CogDiT
10
+ from .hunyuan_video_dit import HunyuanVideoDiT
11
+ from .wan_video_dit import WanModel
12
+
13
+
14
+
15
+ class LoRAFromCivitai:
16
+ def __init__(self):
17
+ self.supported_model_classes = []
18
+ self.lora_prefix = []
19
+ self.renamed_lora_prefix = {}
20
+ self.special_keys = {}
21
+
22
+
23
+ def convert_state_dict(self, state_dict, lora_prefix="lora_unet_", alpha=1.0):
24
+ for key in state_dict:
25
+ if ".lora_up" in key:
26
+ return self.convert_state_dict_up_down(state_dict, lora_prefix, alpha)
27
+ return self.convert_state_dict_AB(state_dict, lora_prefix, alpha)
28
+
29
+
30
+ def convert_state_dict_up_down(self, state_dict, lora_prefix="lora_unet_", alpha=1.0):
31
+ renamed_lora_prefix = self.renamed_lora_prefix.get(lora_prefix, "")
32
+ state_dict_ = {}
33
+ for key in state_dict:
34
+ if ".lora_up" not in key:
35
+ continue
36
+ if not key.startswith(lora_prefix):
37
+ continue
38
+ weight_up = state_dict[key].to(device="cuda", dtype=torch.float16)
39
+ weight_down = state_dict[key.replace(".lora_up", ".lora_down")].to(device="cuda", dtype=torch.float16)
40
+ if len(weight_up.shape) == 4:
41
+ weight_up = weight_up.squeeze(3).squeeze(2).to(torch.float32)
42
+ weight_down = weight_down.squeeze(3).squeeze(2).to(torch.float32)
43
+ lora_weight = alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)
44
+ else:
45
+ lora_weight = alpha * torch.mm(weight_up, weight_down)
46
+ target_name = key.split(".")[0].replace(lora_prefix, renamed_lora_prefix).replace("_", ".") + ".weight"
47
+ for special_key in self.special_keys:
48
+ target_name = target_name.replace(special_key, self.special_keys[special_key])
49
+ state_dict_[target_name] = lora_weight.cpu()
50
+ return state_dict_
51
+
52
+
53
+ def convert_state_dict_AB(self, state_dict, lora_prefix="", alpha=1.0, device="cuda", torch_dtype=torch.float16):
54
+ state_dict_ = {}
55
+ for key in state_dict:
56
+ if ".lora_B." not in key:
57
+ continue
58
+ if not key.startswith(lora_prefix):
59
+ continue
60
+ weight_up = state_dict[key].to(device=device, dtype=torch_dtype)
61
+ weight_down = state_dict[key.replace(".lora_B.", ".lora_A.")].to(device=device, dtype=torch_dtype)
62
+ if len(weight_up.shape) == 4:
63
+ weight_up = weight_up.squeeze(3).squeeze(2)
64
+ weight_down = weight_down.squeeze(3).squeeze(2)
65
+ lora_weight = alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)
66
+ else:
67
+ lora_weight = alpha * torch.mm(weight_up, weight_down)
68
+ keys = key.split(".")
69
+ keys.pop(keys.index("lora_B"))
70
+ target_name = ".".join(keys)
71
+ target_name = target_name[len(lora_prefix):]
72
+ state_dict_[target_name] = lora_weight.cpu()
73
+ return state_dict_
74
+
75
+
76
+ def load(self, model, state_dict_lora, lora_prefix, alpha=1.0, model_resource=None):
77
+ state_dict_model = model.state_dict()
78
+ state_dict_lora = self.convert_state_dict(state_dict_lora, lora_prefix=lora_prefix, alpha=alpha)
79
+ if model_resource == "diffusers":
80
+ state_dict_lora = model.__class__.state_dict_converter().from_diffusers(state_dict_lora)
81
+ elif model_resource == "civitai":
82
+ state_dict_lora = model.__class__.state_dict_converter().from_civitai(state_dict_lora)
83
+ if isinstance(state_dict_lora, tuple):
84
+ state_dict_lora = state_dict_lora[0]
85
+ if len(state_dict_lora) > 0:
86
+ print(f" {len(state_dict_lora)} tensors are updated.")
87
+ for name in state_dict_lora:
88
+ fp8=False
89
+ if state_dict_model[name].dtype == torch.float8_e4m3fn:
90
+ state_dict_model[name]= state_dict_model[name].to(state_dict_lora[name].dtype)
91
+ fp8=True
92
+ state_dict_model[name] += state_dict_lora[name].to(
93
+ dtype=state_dict_model[name].dtype, device=state_dict_model[name].device)
94
+ if fp8:
95
+ state_dict_model[name] = state_dict_model[name].to(torch.float8_e4m3fn)
96
+ model.load_state_dict(state_dict_model)
97
+
98
+
99
+ def match(self, model, state_dict_lora):
100
+ for lora_prefix, model_class in zip(self.lora_prefix, self.supported_model_classes):
101
+ if not isinstance(model, model_class):
102
+ continue
103
+ state_dict_model = model.state_dict()
104
+ for model_resource in ["diffusers", "civitai"]:
105
+ try:
106
+ state_dict_lora_ = self.convert_state_dict(state_dict_lora, lora_prefix=lora_prefix, alpha=1.0)
107
+ converter_fn = model.__class__.state_dict_converter().from_diffusers if model_resource == "diffusers" \
108
+ else model.__class__.state_dict_converter().from_civitai
109
+ state_dict_lora_ = converter_fn(state_dict_lora_)
110
+ if isinstance(state_dict_lora_, tuple):
111
+ state_dict_lora_ = state_dict_lora_[0]
112
+ if len(state_dict_lora_) == 0:
113
+ continue
114
+ for name in state_dict_lora_:
115
+ if name not in state_dict_model:
116
+ break
117
+ else:
118
+ return lora_prefix, model_resource
119
+ except:
120
+ pass
121
+ return None
122
+
123
+
124
+
125
+ class SDLoRAFromCivitai(LoRAFromCivitai):
126
+ def __init__(self):
127
+ super().__init__()
128
+ self.supported_model_classes = [SDUNet, SDTextEncoder]
129
+ self.lora_prefix = ["lora_unet_", "lora_te_"]
130
+ self.special_keys = {
131
+ "down.blocks": "down_blocks",
132
+ "up.blocks": "up_blocks",
133
+ "mid.block": "mid_block",
134
+ "proj.in": "proj_in",
135
+ "proj.out": "proj_out",
136
+ "transformer.blocks": "transformer_blocks",
137
+ "to.q": "to_q",
138
+ "to.k": "to_k",
139
+ "to.v": "to_v",
140
+ "to.out": "to_out",
141
+ "text.model": "text_model",
142
+ "self.attn.q.proj": "self_attn.q_proj",
143
+ "self.attn.k.proj": "self_attn.k_proj",
144
+ "self.attn.v.proj": "self_attn.v_proj",
145
+ "self.attn.out.proj": "self_attn.out_proj",
146
+ "input.blocks": "model.diffusion_model.input_blocks",
147
+ "middle.block": "model.diffusion_model.middle_block",
148
+ "output.blocks": "model.diffusion_model.output_blocks",
149
+ }
150
+
151
+
152
+ class SDXLLoRAFromCivitai(LoRAFromCivitai):
153
+ def __init__(self):
154
+ super().__init__()
155
+ self.supported_model_classes = [SDXLUNet, SDXLTextEncoder, SDXLTextEncoder2]
156
+ self.lora_prefix = ["lora_unet_", "lora_te1_", "lora_te2_"]
157
+ self.renamed_lora_prefix = {"lora_te2_": "2"}
158
+ self.special_keys = {
159
+ "down.blocks": "down_blocks",
160
+ "up.blocks": "up_blocks",
161
+ "mid.block": "mid_block",
162
+ "proj.in": "proj_in",
163
+ "proj.out": "proj_out",
164
+ "transformer.blocks": "transformer_blocks",
165
+ "to.q": "to_q",
166
+ "to.k": "to_k",
167
+ "to.v": "to_v",
168
+ "to.out": "to_out",
169
+ "text.model": "conditioner.embedders.0.transformer.text_model",
170
+ "self.attn.q.proj": "self_attn.q_proj",
171
+ "self.attn.k.proj": "self_attn.k_proj",
172
+ "self.attn.v.proj": "self_attn.v_proj",
173
+ "self.attn.out.proj": "self_attn.out_proj",
174
+ "input.blocks": "model.diffusion_model.input_blocks",
175
+ "middle.block": "model.diffusion_model.middle_block",
176
+ "output.blocks": "model.diffusion_model.output_blocks",
177
+ "2conditioner.embedders.0.transformer.text_model.encoder.layers": "text_model.encoder.layers"
178
+ }
179
+
180
+
181
+ class FluxLoRAFromCivitai(LoRAFromCivitai):
182
+ def __init__(self):
183
+ super().__init__()
184
+ self.supported_model_classes = [FluxDiT, FluxDiT]
185
+ self.lora_prefix = ["lora_unet_", "transformer."]
186
+ self.renamed_lora_prefix = {}
187
+ self.special_keys = {
188
+ "single.blocks": "single_blocks",
189
+ "double.blocks": "double_blocks",
190
+ "img.attn": "img_attn",
191
+ "img.mlp": "img_mlp",
192
+ "img.mod": "img_mod",
193
+ "txt.attn": "txt_attn",
194
+ "txt.mlp": "txt_mlp",
195
+ "txt.mod": "txt_mod",
196
+ }
197
+
198
+
199
+
200
+ class GeneralLoRAFromPeft:
201
+ def __init__(self):
202
+ self.supported_model_classes = [SDUNet, SDXLUNet, SD3DiT, HunyuanDiT, FluxDiT, CogDiT, WanModel]
203
+
204
+
205
+ def get_name_dict(self, lora_state_dict):
206
+ lora_name_dict = {}
207
+ for key in lora_state_dict:
208
+ if ".lora_B." not in key:
209
+ continue
210
+ keys = key.split(".")
211
+ if len(keys) > keys.index("lora_B") + 2:
212
+ keys.pop(keys.index("lora_B") + 1)
213
+ keys.pop(keys.index("lora_B"))
214
+ if keys[0] == "diffusion_model":
215
+ keys.pop(0)
216
+ target_name = ".".join(keys)
217
+ lora_name_dict[target_name] = (key, key.replace(".lora_B.", ".lora_A."))
218
+ return lora_name_dict
219
+
220
+
221
+ def match(self, model: torch.nn.Module, state_dict_lora):
222
+ lora_name_dict = self.get_name_dict(state_dict_lora)
223
+ model_name_dict = {name: None for name, _ in model.named_parameters()}
224
+ matched_num = sum([i in model_name_dict for i in lora_name_dict])
225
+ if matched_num == len(lora_name_dict):
226
+ return "", ""
227
+ else:
228
+ return None
229
+
230
+
231
+ def fetch_device_and_dtype(self, state_dict):
232
+ device, dtype = None, None
233
+ for name, param in state_dict.items():
234
+ device, dtype = param.device, param.dtype
235
+ break
236
+ computation_device = device
237
+ computation_dtype = dtype
238
+ if computation_device == torch.device("cpu"):
239
+ if torch.cuda.is_available():
240
+ computation_device = torch.device("cuda")
241
+ if computation_dtype == torch.float8_e4m3fn:
242
+ computation_dtype = torch.float32
243
+ return device, dtype, computation_device, computation_dtype
244
+
245
+
246
+ def load(self, model, state_dict_lora, lora_prefix="", alpha=1.0, model_resource=""):
247
+ state_dict_model = model.state_dict()
248
+ device, dtype, computation_device, computation_dtype = self.fetch_device_and_dtype(state_dict_model)
249
+ lora_name_dict = self.get_name_dict(state_dict_lora)
250
+ for name in lora_name_dict:
251
+ weight_up = state_dict_lora[lora_name_dict[name][0]].to(device=computation_device, dtype=computation_dtype)
252
+ weight_down = state_dict_lora[lora_name_dict[name][1]].to(device=computation_device, dtype=computation_dtype)
253
+ if len(weight_up.shape) == 4:
254
+ weight_up = weight_up.squeeze(3).squeeze(2)
255
+ weight_down = weight_down.squeeze(3).squeeze(2)
256
+ weight_lora = alpha * torch.mm(weight_up, weight_down).unsqueeze(2).unsqueeze(3)
257
+ else:
258
+ weight_lora = alpha * torch.mm(weight_up, weight_down)
259
+ weight_model = state_dict_model[name].to(device=computation_device, dtype=computation_dtype)
260
+ weight_patched = weight_model + weight_lora
261
+ state_dict_model[name] = weight_patched.to(device=device, dtype=dtype)
262
+ print(f" {len(lora_name_dict)} tensors are updated.")
263
+ model.load_state_dict(state_dict_model)
264
+
265
+
266
+
267
+ class HunyuanVideoLoRAFromCivitai(LoRAFromCivitai):
268
+ def __init__(self):
269
+ super().__init__()
270
+ self.supported_model_classes = [HunyuanVideoDiT, HunyuanVideoDiT]
271
+ self.lora_prefix = ["diffusion_model.", "transformer."]
272
+ self.special_keys = {}
273
+
274
+
275
+ class FluxLoRAConverter:
276
+ def __init__(self):
277
+ pass
278
+
279
+ @staticmethod
280
+ def align_to_opensource_format(state_dict, alpha=None):
281
+ prefix_rename_dict = {
282
+ "single_blocks": "lora_unet_single_blocks",
283
+ "blocks": "lora_unet_double_blocks",
284
+ }
285
+ middle_rename_dict = {
286
+ "norm.linear": "modulation_lin",
287
+ "to_qkv_mlp": "linear1",
288
+ "proj_out": "linear2",
289
+
290
+ "norm1_a.linear": "img_mod_lin",
291
+ "norm1_b.linear": "txt_mod_lin",
292
+ "attn.a_to_qkv": "img_attn_qkv",
293
+ "attn.b_to_qkv": "txt_attn_qkv",
294
+ "attn.a_to_out": "img_attn_proj",
295
+ "attn.b_to_out": "txt_attn_proj",
296
+ "ff_a.0": "img_mlp_0",
297
+ "ff_a.2": "img_mlp_2",
298
+ "ff_b.0": "txt_mlp_0",
299
+ "ff_b.2": "txt_mlp_2",
300
+ }
301
+ suffix_rename_dict = {
302
+ "lora_B.weight": "lora_up.weight",
303
+ "lora_A.weight": "lora_down.weight",
304
+ }
305
+ state_dict_ = {}
306
+ for name, param in state_dict.items():
307
+ names = name.split(".")
308
+ if names[-2] != "lora_A" and names[-2] != "lora_B":
309
+ names.pop(-2)
310
+ prefix = names[0]
311
+ middle = ".".join(names[2:-2])
312
+ suffix = ".".join(names[-2:])
313
+ block_id = names[1]
314
+ if middle not in middle_rename_dict:
315
+ continue
316
+ rename = prefix_rename_dict[prefix] + "_" + block_id + "_" + middle_rename_dict[middle] + "." + suffix_rename_dict[suffix]
317
+ state_dict_[rename] = param
318
+ if rename.endswith("lora_up.weight"):
319
+ lora_alpha = alpha if alpha is not None else param.shape[-1]
320
+ state_dict_[rename.replace("lora_up.weight", "alpha")] = torch.tensor((lora_alpha,))[0]
321
+ return state_dict_
322
+
323
+ @staticmethod
324
+ def align_to_diffsynth_format(state_dict):
325
+ rename_dict = {
326
+ "lora_unet_double_blocks_blockid_img_mod_lin.lora_down.weight": "blocks.blockid.norm1_a.linear.lora_A.default.weight",
327
+ "lora_unet_double_blocks_blockid_img_mod_lin.lora_up.weight": "blocks.blockid.norm1_a.linear.lora_B.default.weight",
328
+ "lora_unet_double_blocks_blockid_txt_mod_lin.lora_down.weight": "blocks.blockid.norm1_b.linear.lora_A.default.weight",
329
+ "lora_unet_double_blocks_blockid_txt_mod_lin.lora_up.weight": "blocks.blockid.norm1_b.linear.lora_B.default.weight",
330
+ "lora_unet_double_blocks_blockid_img_attn_qkv.lora_down.weight": "blocks.blockid.attn.a_to_qkv.lora_A.default.weight",
331
+ "lora_unet_double_blocks_blockid_img_attn_qkv.lora_up.weight": "blocks.blockid.attn.a_to_qkv.lora_B.default.weight",
332
+ "lora_unet_double_blocks_blockid_txt_attn_qkv.lora_down.weight": "blocks.blockid.attn.b_to_qkv.lora_A.default.weight",
333
+ "lora_unet_double_blocks_blockid_txt_attn_qkv.lora_up.weight": "blocks.blockid.attn.b_to_qkv.lora_B.default.weight",
334
+ "lora_unet_double_blocks_blockid_img_attn_proj.lora_down.weight": "blocks.blockid.attn.a_to_out.lora_A.default.weight",
335
+ "lora_unet_double_blocks_blockid_img_attn_proj.lora_up.weight": "blocks.blockid.attn.a_to_out.lora_B.default.weight",
336
+ "lora_unet_double_blocks_blockid_txt_attn_proj.lora_down.weight": "blocks.blockid.attn.b_to_out.lora_A.default.weight",
337
+ "lora_unet_double_blocks_blockid_txt_attn_proj.lora_up.weight": "blocks.blockid.attn.b_to_out.lora_B.default.weight",
338
+ "lora_unet_double_blocks_blockid_img_mlp_0.lora_down.weight": "blocks.blockid.ff_a.0.lora_A.default.weight",
339
+ "lora_unet_double_blocks_blockid_img_mlp_0.lora_up.weight": "blocks.blockid.ff_a.0.lora_B.default.weight",
340
+ "lora_unet_double_blocks_blockid_img_mlp_2.lora_down.weight": "blocks.blockid.ff_a.2.lora_A.default.weight",
341
+ "lora_unet_double_blocks_blockid_img_mlp_2.lora_up.weight": "blocks.blockid.ff_a.2.lora_B.default.weight",
342
+ "lora_unet_double_blocks_blockid_txt_mlp_0.lora_down.weight": "blocks.blockid.ff_b.0.lora_A.default.weight",
343
+ "lora_unet_double_blocks_blockid_txt_mlp_0.lora_up.weight": "blocks.blockid.ff_b.0.lora_B.default.weight",
344
+ "lora_unet_double_blocks_blockid_txt_mlp_2.lora_down.weight": "blocks.blockid.ff_b.2.lora_A.default.weight",
345
+ "lora_unet_double_blocks_blockid_txt_mlp_2.lora_up.weight": "blocks.blockid.ff_b.2.lora_B.default.weight",
346
+ "lora_unet_single_blocks_blockid_modulation_lin.lora_down.weight": "single_blocks.blockid.norm.linear.lora_A.default.weight",
347
+ "lora_unet_single_blocks_blockid_modulation_lin.lora_up.weight": "single_blocks.blockid.norm.linear.lora_B.default.weight",
348
+ "lora_unet_single_blocks_blockid_linear1.lora_down.weight": "single_blocks.blockid.to_qkv_mlp.lora_A.default.weight",
349
+ "lora_unet_single_blocks_blockid_linear1.lora_up.weight": "single_blocks.blockid.to_qkv_mlp.lora_B.default.weight",
350
+ "lora_unet_single_blocks_blockid_linear2.lora_down.weight": "single_blocks.blockid.proj_out.lora_A.default.weight",
351
+ "lora_unet_single_blocks_blockid_linear2.lora_up.weight": "single_blocks.blockid.proj_out.lora_B.default.weight",
352
+ }
353
+ def guess_block_id(name):
354
+ names = name.split("_")
355
+ for i in names:
356
+ if i.isdigit():
357
+ return i, name.replace(f"_{i}_", "_blockid_")
358
+ return None, None
359
+ state_dict_ = {}
360
+ for name, param in state_dict.items():
361
+ block_id, source_name = guess_block_id(name)
362
+ if source_name in rename_dict:
363
+ target_name = rename_dict[source_name]
364
+ target_name = target_name.replace(".blockid.", f".{block_id}.")
365
+ state_dict_[target_name] = param
366
+ else:
367
+ state_dict_[name] = param
368
+ return state_dict_
369
+
370
+
371
+ class WanLoRAConverter:
372
+ def __init__(self):
373
+ pass
374
+
375
+ @staticmethod
376
+ def align_to_opensource_format(state_dict, **kwargs):
377
+ state_dict = {"diffusion_model." + name.replace(".default.", "."): param for name, param in state_dict.items()}
378
+ return state_dict
379
+
380
+ @staticmethod
381
+ def align_to_diffsynth_format(state_dict, **kwargs):
382
+ state_dict = {name.replace("diffusion_model.", "").replace(".lora_A.weight", ".lora_A.default.weight").replace(".lora_B.weight", ".lora_B.default.weight"): param for name, param in state_dict.items()}
383
+ return state_dict
384
+
385
+
386
+ def get_lora_loaders():
387
+ return [SDLoRAFromCivitai(), SDXLLoRAFromCivitai(), FluxLoRAFromCivitai(), HunyuanVideoLoRAFromCivitai(), GeneralLoRAFromPeft()]
memory/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .framepack_length import (
2
+ framepack_align_context_actions_to_latents,
3
+ framepack_length_compress_context_latents,
4
+ )
5
+ from .framepack_weight import apply_framepack_token_weights
6
+ from .spatial_grid_memory import (
7
+ SpatialCrossAttnReadout,
8
+ SpatialGridMemory,
9
+ apply_spatial_cross_attn_readout,
10
+ inject_spatial_memory,
11
+ )
12
+ from .videossm_hybrid import HybridStateSpaceMemory
13
+
14
+ from .block_wise_ssm import BlockWiseStateSpaceMemory
memory/block_wise_ssm.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class BlockWiseStateSpaceMemory(nn.Module):
6
+ """
7
+ Paper-aligned block-wise recurrent SSM.
8
+
9
+ This module is intentionally separate from VideoSSM hybrid. It performs a
10
+ recurrent state update along the latent time axis for each spatial token
11
+ trajectory, and is attached to selected DiT blocks.
12
+ """
13
+
14
+ def __init__(self, dim: int):
15
+ super().__init__()
16
+ self.dim = int(dim)
17
+ self.in_proj = nn.Linear(self.dim, self.dim * 2)
18
+ self.out_proj = nn.Linear(self.dim, self.dim)
19
+ self.decay_logit = nn.Parameter(torch.zeros(self.dim))
20
+ self.gate = nn.Parameter(torch.zeros(1))
21
+
22
+ def forward(self, x: torch.Tensor, f: int, **_kwargs):
23
+ # x: (B, F*S, D), where S is spatial tokens per latent frame.
24
+ if x is None or x.ndim != 3:
25
+ return x
26
+ b, n, d = x.shape
27
+ f = int(f or 0)
28
+ if d != self.dim or f <= 1 or n % f != 0:
29
+ return x
30
+
31
+ spatial = n // f
32
+ x_seq = x.reshape(b, f, spatial, d).permute(0, 2, 1, 3).reshape(b * spatial, f, d)
33
+ update, update_gate = self.in_proj(x_seq).chunk(2, dim=-1)
34
+ update = torch.tanh(update)
35
+ update_gate = torch.sigmoid(update_gate)
36
+ decay = torch.sigmoid(self.decay_logit).to(dtype=x.dtype, device=x.device).view(1, d)
37
+
38
+ state = torch.zeros(x_seq.shape[0], d, dtype=x.dtype, device=x.device)
39
+ outputs = []
40
+ for t in range(f):
41
+ state = decay * state + (1.0 - decay) * update[:, t, :]
42
+ outputs.append(state * update_gate[:, t, :])
43
+ y = torch.stack(outputs, dim=1)
44
+ y = self.out_proj(y)
45
+ y = y.reshape(b, spatial, f, d).permute(0, 2, 1, 3).reshape(b, n, d)
46
+ return x + torch.tanh(self.gate) * y
memory/framepack_length.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+
4
+
5
+ def _compress_weights(ratio: int, strategy: str = "distance_merge", recent_keep_ratio: float = 0.5, device=None, dtype=None):
6
+ if ratio <= 1:
7
+ return None
8
+ strategy = str(strategy or "distance_merge").lower()
9
+ # Baseline-aligned default: non-overlapping mean pool on each r-frame group.
10
+ if strategy in ("distance_merge", "mean", "uniform"):
11
+ return None
12
+ if strategy in ("recent_weighted", "weighted_recent"):
13
+ # Optional weighted variant (kept for compatibility experiments).
14
+ idx = torch.arange(ratio, device=device, dtype=dtype)
15
+ w = (1.0 - float(recent_keep_ratio)) + float(recent_keep_ratio) * ((idx + 1.0) / float(ratio))
16
+ w = w / w.sum()
17
+ return w
18
+ return torch.full((ratio,), 1.0 / float(ratio), device=device, dtype=dtype)
19
+
20
+
21
+ def framepack_length_compress_context_latents(
22
+ context_latents: torch.Tensor,
23
+ framepack_ratio: int,
24
+ strategy: str = "distance_merge",
25
+ recent_keep_ratio: float = 0.5,
26
+ multiscale_w2: float = 0.25,
27
+ multiscale_w4: float = 0.15,
28
+ ):
29
+ # context_latents: (B, C, K, H, W)
30
+ if context_latents is None:
31
+ return None, 0, 0, 0
32
+ if context_latents.ndim != 5:
33
+ raise ValueError(f"context_latents must be 5D (B,C,K,H,W), got {tuple(context_latents.shape)}")
34
+ r = int(framepack_ratio)
35
+ if r <= 1:
36
+ k = int(context_latents.shape[2])
37
+ return context_latents, k, k, k
38
+
39
+ b, c, k_orig, h, w = context_latents.shape
40
+ pad = (r - (k_orig % r)) % r
41
+ if pad > 0:
42
+ pad_lat = context_latents[:, :, -1:, :, :].repeat(1, 1, pad, 1, 1)
43
+ context_latents = torch.cat([context_latents, pad_lat], dim=2)
44
+ k_pad = int(context_latents.shape[2])
45
+ new_k = k_pad // r
46
+
47
+ grouped = context_latents.reshape(b, c, new_k, r, h, w)
48
+ strategy = str(strategy or "distance_merge").lower()
49
+ if strategy in ("packed_multiscale", "multiscale_packed", "multi_scale_packed"):
50
+ base = grouped.mean(dim=3)
51
+
52
+ # Base-code inspired approximation: aggregate history with extra low-res spatial views
53
+ # (1x/2x/4x) and fuse back to the packed latent stream.
54
+ x2 = F.avg_pool3d(context_latents, kernel_size=(1, 2, 2), stride=(1, 2, 2))
55
+ x4 = F.avg_pool3d(context_latents, kernel_size=(1, 4, 4), stride=(1, 4, 4))
56
+ x2 = F.interpolate(x2, size=(k_pad, h, w), mode="trilinear", align_corners=False)
57
+ x4 = F.interpolate(x4, size=(k_pad, h, w), mode="trilinear", align_corners=False)
58
+ b2 = x2.reshape(b, c, new_k, r, h, w).mean(dim=3)
59
+ b4 = x4.reshape(b, c, new_k, r, h, w).mean(dim=3)
60
+ w2 = float(multiscale_w2 or 0.0)
61
+ w4 = float(multiscale_w4 or 0.0)
62
+ w1 = max(1e-6, 1.0 - w2 - w4)
63
+ s = w1 + w2 + w4
64
+ out = (w1 * base + w2 * b2 + w4 * b4) / s
65
+ else:
66
+ cw = _compress_weights(r, strategy=strategy, recent_keep_ratio=recent_keep_ratio, device=context_latents.device, dtype=context_latents.dtype)
67
+ if cw is None:
68
+ out = grouped.mean(dim=3)
69
+ else:
70
+ out = (grouped * cw.view(1, 1, 1, r, 1, 1)).sum(dim=3)
71
+ return out, int(new_k), int(k_pad), int(k_orig)
72
+
73
+
74
+ def framepack_align_context_actions_to_latents(
75
+ context_actions,
76
+ K_orig_latent: int,
77
+ K_after_pad: int,
78
+ framepack_ratio: int,
79
+ device=None,
80
+ dtype=None,
81
+ strategy: str = "distance_merge",
82
+ recent_keep_ratio: float = 0.5,
83
+ ):
84
+ if context_actions is None:
85
+ return None
86
+ x = context_actions
87
+ if not isinstance(x, torch.Tensor):
88
+ x = torch.tensor(x, device=device, dtype=dtype or torch.float32)
89
+ else:
90
+ if device is not None:
91
+ x = x.to(device=device)
92
+ if dtype is not None:
93
+ x = x.to(dtype=dtype)
94
+ if x.ndim not in (2, 3):
95
+ raise ValueError(f"context_actions must be 2D/3D, got shape {tuple(x.shape)}")
96
+ r = int(framepack_ratio)
97
+ if r <= 1:
98
+ return x
99
+
100
+ if x.ndim == 2:
101
+ # (K, D)
102
+ k, d = x.shape
103
+ k_expected = int(K_orig_latent)
104
+ if k < k_expected:
105
+ raise ValueError(f"context_actions shorter than K_orig_latent: {k} < {k_expected}")
106
+ x = x[:k_expected, :]
107
+ pad = int(K_after_pad) - k_expected
108
+ if pad > 0:
109
+ x = torch.cat([x, x[-1:, :].repeat(pad, 1)], dim=0)
110
+ new_k = int(K_after_pad) // r
111
+ grouped = x.reshape(new_k, r, d)
112
+ cw = _compress_weights(r, strategy=str(strategy or "distance_merge").lower(), recent_keep_ratio=recent_keep_ratio, device=x.device, dtype=x.dtype)
113
+ return grouped.mean(dim=1) if cw is None else (grouped * cw.view(1, r, 1)).sum(dim=1)
114
+
115
+ # (B, K, D)
116
+ b, k, d = x.shape
117
+ k_expected = int(K_orig_latent)
118
+ if k < k_expected:
119
+ raise ValueError(f"context_actions shorter than K_orig_latent: {k} < {k_expected}")
120
+ x = x[:, :k_expected, :]
121
+ pad = int(K_after_pad) - k_expected
122
+ if pad > 0:
123
+ x = torch.cat([x, x[:, -1:, :].repeat(1, pad, 1)], dim=1)
124
+ new_k = int(K_after_pad) // r
125
+ grouped = x.reshape(b, new_k, r, d)
126
+ cw = _compress_weights(r, strategy=str(strategy or "distance_merge").lower(), recent_keep_ratio=recent_keep_ratio, device=x.device, dtype=x.dtype)
127
+ return grouped.mean(dim=2) if cw is None else (grouped * cw.view(1, 1, r, 1)).sum(dim=2)
128
+
memory/framepack_weight.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def apply_framepack_token_weights(
5
+ x: torch.Tensor,
6
+ num_context_frames: int,
7
+ f: int,
8
+ h: int,
9
+ w: int,
10
+ context_position: str = "prefix",
11
+ use_framepack_memory: bool = False,
12
+ context_temporal_decay: float = 1.0,
13
+ context_attention_weight: float = 1.0,
14
+ ):
15
+ if x is None or x.ndim != 3:
16
+ return x
17
+ if not use_framepack_memory or int(num_context_frames) <= 0:
18
+ return x
19
+ b, n, d = x.shape
20
+ f = int(f)
21
+ if f <= 0 or n != f * int(h) * int(w):
22
+ return x
23
+
24
+ hw = int(h) * int(w)
25
+ x4 = x.reshape(b, f, hw, d)
26
+ k = min(int(num_context_frames), f)
27
+ decay = float(context_temporal_decay)
28
+ gain = float(context_attention_weight)
29
+ if context_position == "suffix":
30
+ ctx_start = f - k
31
+ ctx_end = f
32
+ # Suffix: first context frame is nearest boundary to target.
33
+ distances = torch.arange(k, device=x.device, dtype=x.dtype)
34
+ else:
35
+ ctx_start = 0
36
+ ctx_end = k
37
+ # Prefix: last context frame is nearest boundary to target.
38
+ distances = torch.arange(k - 1, -1, -1, device=x.device, dtype=x.dtype)
39
+
40
+ weights = gain * torch.pow(torch.tensor(decay, device=x.device, dtype=x.dtype), distances)
41
+ x4[:, ctx_start:ctx_end, :, :] = x4[:, ctx_start:ctx_end, :, :] * weights.view(1, k, 1, 1)
42
+ return x4.reshape(b, n, d)
43
+
memory/spatial_grid_memory.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class SpatialGridMemory(nn.Module):
7
+ def __init__(self, dim: int, grid_size: int = 8, num_tokens: int = 64):
8
+ super().__init__()
9
+ self.dim = int(dim)
10
+ self.grid_size = int(grid_size)
11
+ self.num_tokens = int(num_tokens)
12
+ g2 = self.grid_size * self.grid_size
13
+ # Keep key name aligned with ckpt loading in loop_utils.py (spatial_to_tokens).
14
+ self.spatial_to_tokens = nn.Parameter(torch.zeros(g2, self.num_tokens))
15
+ nn.init.normal_(self.spatial_to_tokens, std=0.02)
16
+
17
+ @property
18
+ def mix(self):
19
+ # Backward compatibility for code that referenced the old attribute name.
20
+ return self.spatial_to_tokens
21
+
22
+ def forward(self, x_context: torch.Tensor, num_context_frames: int, h: int, w: int):
23
+ # x_context: (B, K*H*W, D)
24
+ if x_context is None or x_context.ndim != 3:
25
+ return x_context
26
+ b, n, d = x_context.shape
27
+ if d != self.dim:
28
+ raise ValueError(f"SpatialGridMemory dim mismatch: x={d} module={self.dim}")
29
+ k = max(int(num_context_frames), 1)
30
+ spatial = int(h) * int(w)
31
+ if n != k * spatial:
32
+ # Best effort fallback: treat x as a flat token map and pool directly.
33
+ x_mean = x_context
34
+ else:
35
+ x_mean = x_context.reshape(b, k, spatial, d).mean(dim=1) # (B, S, D)
36
+
37
+ g2 = self.grid_size * self.grid_size
38
+ pooled = F.adaptive_avg_pool1d(x_mean.transpose(1, 2), g2).transpose(1, 2) # (B, G2, D)
39
+ mix = torch.softmax(self.spatial_to_tokens, dim=0) # (G2, M)
40
+ mem = torch.einsum("bgd,gm->bmd", pooled, mix) # (B, M, D)
41
+ return mem
42
+
43
+ def load_state_dict(self, state_dict, strict: bool = True):
44
+ # Compatibility:
45
+ # - old local key: mix
46
+ # - current/baseline key: spatial_to_tokens
47
+ sd = dict(state_dict)
48
+ if "mix" in sd and "spatial_to_tokens" not in sd:
49
+ sd["spatial_to_tokens"] = sd.pop("mix")
50
+ # Ignore deprecated projection keys from prior experiments.
51
+ sd.pop("out.weight", None)
52
+ sd.pop("out.bias", None)
53
+ return super().load_state_dict(sd, strict=False if not strict else strict)
54
+
55
+
56
+ class SpatialCrossAttnReadout(nn.Module):
57
+ def __init__(self, dim: int, num_heads: int = 8):
58
+ super().__init__()
59
+ self.attn = nn.MultiheadAttention(embed_dim=int(dim), num_heads=int(num_heads), batch_first=True)
60
+ self.gate = nn.Parameter(torch.zeros(1))
61
+
62
+ def forward(self, x_target: torch.Tensor, mem_tokens: torch.Tensor):
63
+ if x_target is None or mem_tokens is None:
64
+ return x_target
65
+ if x_target.numel() == 0 or mem_tokens.numel() == 0:
66
+ return x_target
67
+ delta, _ = self.attn(x_target, mem_tokens, mem_tokens, need_weights=False)
68
+ return x_target + torch.tanh(self.gate) * delta
69
+
70
+
71
+ def apply_spatial_cross_attn_readout(x_target: torch.Tensor, mem_tokens: torch.Tensor, module: nn.Module = None):
72
+ if module is None:
73
+ module = SpatialCrossAttnReadout(dim=int(x_target.shape[-1]), num_heads=8).to(device=x_target.device, dtype=x_target.dtype)
74
+ return module(x_target, mem_tokens)
75
+
76
+
77
+ def inject_spatial_memory(context: torch.Tensor, mem_tokens: torch.Tensor, mode: str = "concat_text"):
78
+ mode = str(mode or "concat_text").lower()
79
+ if mem_tokens is None or mode == "none":
80
+ return context
81
+ if context is None:
82
+ return mem_tokens
83
+ if mode in ("concat_text", "cross_attn_readout"):
84
+ return torch.cat([context, mem_tokens], dim=1)
85
+ return context
86
+
memory/videossm_hybrid.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class HybridStateSpaceMemory(nn.Module):
6
+ """
7
+ Lightweight legacy VideoSSM hybrid block:
8
+ depthwise temporal conv over per-spatial token trajectories.
9
+ """
10
+
11
+ def __init__(self, dim: int, kernel_size: int = 3, expand: int = 2):
12
+ super().__init__()
13
+ self.dim = int(dim)
14
+ self.kernel_size = int(kernel_size)
15
+ hidden = int(dim) * max(int(expand), 1)
16
+ pad = self.kernel_size - 1 # causal-like left padding
17
+ self.in_proj = nn.Linear(self.dim, hidden)
18
+ self.dw = nn.Conv1d(hidden, hidden, kernel_size=self.kernel_size, groups=hidden, padding=pad)
19
+ self.out_proj = nn.Linear(hidden, self.dim)
20
+ self.gate = nn.Parameter(torch.zeros(1))
21
+
22
+ def forward(self, x: torch.Tensor, f: int, h: int, w: int, **_kwargs):
23
+ # x: (B, F*H*W, D)
24
+ if x is None or x.ndim != 3:
25
+ return x
26
+ b, n, d = x.shape
27
+ f = int(f)
28
+ hw = int(h) * int(w)
29
+ if d != self.dim or f <= 1 or n != f * hw:
30
+ return x
31
+ x4 = x.reshape(b, f, hw, d).permute(0, 2, 1, 3).reshape(b * hw, f, d) # (B*HW, F, D)
32
+ y = self.in_proj(x4)
33
+ y = y.transpose(1, 2) # (B*HW, hidden, F)
34
+ y = self.dw(y)[..., :f] # causal crop
35
+ y = y.transpose(1, 2)
36
+ y = self.out_proj(y)
37
+ y = y.reshape(b, hw, f, d).permute(0, 2, 1, 3).reshape(b, n, d)
38
+ return x + torch.tanh(self.gate) * y
39
+
model_manager.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, torch, json, importlib, logging
2
+ from typing import List
3
+
4
+ logger = logging.getLogger(__name__)
5
+
6
+ from .downloader import download_models, download_customized_models, Preset_model_id, Preset_model_website
7
+
8
+ from .sd_text_encoder import SDTextEncoder
9
+ from .sd_unet import SDUNet
10
+ from .sd_vae_encoder import SDVAEEncoder
11
+ from .sd_vae_decoder import SDVAEDecoder
12
+ from .lora import get_lora_loaders
13
+
14
+ from .sdxl_text_encoder import SDXLTextEncoder, SDXLTextEncoder2
15
+ from .sdxl_unet import SDXLUNet
16
+ from .sdxl_vae_decoder import SDXLVAEDecoder
17
+ from .sdxl_vae_encoder import SDXLVAEEncoder
18
+
19
+ from .sd3_text_encoder import SD3TextEncoder1, SD3TextEncoder2, SD3TextEncoder3
20
+ from .sd3_dit import SD3DiT
21
+ from .sd3_vae_decoder import SD3VAEDecoder
22
+ from .sd3_vae_encoder import SD3VAEEncoder
23
+
24
+ from .sd_controlnet import SDControlNet
25
+ from .sdxl_controlnet import SDXLControlNetUnion
26
+
27
+ from .sd_motion import SDMotionModel
28
+ from .sdxl_motion import SDXLMotionModel
29
+
30
+ from .svd_image_encoder import SVDImageEncoder
31
+ from .svd_unet import SVDUNet
32
+ from .svd_vae_decoder import SVDVAEDecoder
33
+ from .svd_vae_encoder import SVDVAEEncoder
34
+
35
+ from .sd_ipadapter import SDIpAdapter, IpAdapterCLIPImageEmbedder
36
+ from .sdxl_ipadapter import SDXLIpAdapter, IpAdapterXLCLIPImageEmbedder
37
+
38
+ from .hunyuan_dit_text_encoder import HunyuanDiTCLIPTextEncoder, HunyuanDiTT5TextEncoder
39
+ from .hunyuan_dit import HunyuanDiT
40
+ from .hunyuan_video_vae_decoder import HunyuanVideoVAEDecoder
41
+ from .hunyuan_video_vae_encoder import HunyuanVideoVAEEncoder
42
+
43
+ from .flux_dit import FluxDiT
44
+ from .flux_text_encoder import FluxTextEncoder2
45
+ from .flux_vae import FluxVAEEncoder, FluxVAEDecoder
46
+ from .flux_ipadapter import FluxIpAdapter
47
+
48
+ from .cog_vae import CogVAEEncoder, CogVAEDecoder
49
+ from .cog_dit import CogDiT
50
+
51
+ from ..extensions.RIFE import IFNet
52
+ from ..extensions.ESRGAN import RRDBNet
53
+
54
+ from ..configs.model_config import model_loader_configs, huggingface_model_loader_configs, patch_model_loader_configs
55
+ from .utils import load_state_dict, init_weights_on_device, hash_state_dict_keys, split_state_dict_with_prefix
56
+
57
+
58
+ def load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device):
59
+ loaded_model_names, loaded_models = [], []
60
+ for model_name, model_class in zip(model_names, model_classes):
61
+ print(f" model_name: {model_name} model_class: {model_class.__name__}")
62
+ state_dict_converter = model_class.state_dict_converter()
63
+ if model_resource == "civitai":
64
+ state_dict_results = state_dict_converter.from_civitai(state_dict)
65
+ elif model_resource == "diffusers":
66
+ state_dict_results = state_dict_converter.from_diffusers(state_dict)
67
+ if isinstance(state_dict_results, tuple):
68
+ model_state_dict, extra_kwargs = state_dict_results
69
+ print(f" This model is initialized with extra kwargs: {extra_kwargs}")
70
+ else:
71
+ model_state_dict, extra_kwargs = state_dict_results, {}
72
+ torch_dtype = torch.float32 if extra_kwargs.get("upcast_to_float32", False) else torch_dtype
73
+ with init_weights_on_device():
74
+ model = model_class(**extra_kwargs)
75
+ if hasattr(model, "eval"):
76
+ model = model.eval()
77
+ model.load_state_dict(model_state_dict, assign=True)
78
+ model = model.to(dtype=torch_dtype, device=device)
79
+ loaded_model_names.append(model_name)
80
+ loaded_models.append(model)
81
+ return loaded_model_names, loaded_models
82
+
83
+
84
+ def load_model_from_huggingface_folder(file_path, model_names, model_classes, torch_dtype, device):
85
+ loaded_model_names, loaded_models = [], []
86
+ for model_name, model_class in zip(model_names, model_classes):
87
+ if torch_dtype in [torch.float32, torch.float16, torch.bfloat16]:
88
+ model = model_class.from_pretrained(file_path, torch_dtype=torch_dtype).eval()
89
+ else:
90
+ model = model_class.from_pretrained(file_path).eval().to(dtype=torch_dtype)
91
+ if torch_dtype == torch.float16 and hasattr(model, "half"):
92
+ model = model.half()
93
+ try:
94
+ model = model.to(device=device)
95
+ except:
96
+ pass
97
+ loaded_model_names.append(model_name)
98
+ loaded_models.append(model)
99
+ return loaded_model_names, loaded_models
100
+
101
+
102
+ def load_single_patch_model_from_single_file(state_dict, model_name, model_class, base_model, extra_kwargs, torch_dtype, device):
103
+ print(f" model_name: {model_name} model_class: {model_class.__name__} extra_kwargs: {extra_kwargs}")
104
+ base_state_dict = base_model.state_dict()
105
+ base_model.to("cpu")
106
+ del base_model
107
+ model = model_class(**extra_kwargs)
108
+ model.load_state_dict(base_state_dict, strict=False)
109
+ model.load_state_dict(state_dict, strict=False)
110
+ model.to(dtype=torch_dtype, device=device)
111
+ return model
112
+
113
+
114
+ def load_patch_model_from_single_file(state_dict, model_names, model_classes, extra_kwargs, model_manager, torch_dtype, device):
115
+ loaded_model_names, loaded_models = [], []
116
+ for model_name, model_class in zip(model_names, model_classes):
117
+ while True:
118
+ for model_id in range(len(model_manager.model)):
119
+ base_model_name = model_manager.model_name[model_id]
120
+ if base_model_name == model_name:
121
+ base_model_path = model_manager.model_path[model_id]
122
+ base_model = model_manager.model[model_id]
123
+ print(f" Adding patch model to {base_model_name} ({base_model_path})")
124
+ patched_model = load_single_patch_model_from_single_file(
125
+ state_dict, model_name, model_class, base_model, extra_kwargs, torch_dtype, device)
126
+ loaded_model_names.append(base_model_name)
127
+ loaded_models.append(patched_model)
128
+ model_manager.model.pop(model_id)
129
+ model_manager.model_path.pop(model_id)
130
+ model_manager.model_name.pop(model_id)
131
+ break
132
+ else:
133
+ break
134
+ return loaded_model_names, loaded_models
135
+
136
+
137
+
138
+ class ModelDetectorTemplate:
139
+ def __init__(self):
140
+ pass
141
+
142
+ def match(self, file_path="", state_dict={}):
143
+ return False
144
+
145
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
146
+ return [], []
147
+
148
+
149
+
150
+ class ModelDetectorFromSingleFile:
151
+ def __init__(self, model_loader_configs=[]):
152
+ self.keys_hash_with_shape_dict = {}
153
+ self.keys_hash_dict = {}
154
+ for metadata in model_loader_configs:
155
+ self.add_model_metadata(*metadata)
156
+
157
+
158
+ def add_model_metadata(self, keys_hash, keys_hash_with_shape, model_names, model_classes, model_resource):
159
+ self.keys_hash_with_shape_dict[keys_hash_with_shape] = (model_names, model_classes, model_resource)
160
+ if keys_hash is not None:
161
+ self.keys_hash_dict[keys_hash] = (model_names, model_classes, model_resource)
162
+
163
+
164
+ def match(self, file_path="", state_dict={}):
165
+ if isinstance(file_path, str) and os.path.isdir(file_path):
166
+ return False
167
+ if state_dict is None or len(state_dict) == 0:
168
+ # Handle list of file paths (for split model files)
169
+ if isinstance(file_path, list):
170
+ state_dict = {}
171
+ for path in file_path:
172
+ state_dict.update(load_state_dict(path))
173
+ else:
174
+ state_dict = load_state_dict(file_path)
175
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
176
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
177
+ return True
178
+ keys_hash = hash_state_dict_keys(state_dict, with_shape=False)
179
+ if keys_hash in self.keys_hash_dict:
180
+ return True
181
+ # Debug: log hash if it's a list of files (merged model)
182
+ if isinstance(file_path, list) and len(state_dict) > 0:
183
+ logger.info(f" Debug: ModelDetectorFromSingleFile - hash_with_shape={keys_hash_with_shape}, hash={keys_hash}, keys_count={len(state_dict)}")
184
+ logger.info(f" Debug: Available hashes count: {len(self.keys_hash_with_shape_dict)}")
185
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
186
+ logger.info(f" Debug: Hash FOUND in keys_hash_with_shape_dict!")
187
+ else:
188
+ logger.warning(f" Debug: Hash NOT FOUND in keys_hash_with_shape_dict")
189
+ logger.info(f" Debug: Sample hashes in dict: {list(self.keys_hash_with_shape_dict.keys())[:5]}")
190
+ return False
191
+
192
+
193
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
194
+ if state_dict is None or len(state_dict) == 0:
195
+ # Handle list of file paths (for split model files)
196
+ if isinstance(file_path, list):
197
+ state_dict = {}
198
+ for path in file_path:
199
+ state_dict.update(load_state_dict(path))
200
+ else:
201
+ state_dict = load_state_dict(file_path)
202
+
203
+ # Load models with strict matching
204
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
205
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
206
+ model_names, model_classes, model_resource = self.keys_hash_with_shape_dict[keys_hash_with_shape]
207
+ loaded_model_names, loaded_models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device)
208
+ return loaded_model_names, loaded_models
209
+
210
+ # Load models without strict matching
211
+ # (the shape of parameters may be inconsistent, and the state_dict_converter will modify the model architecture)
212
+ keys_hash = hash_state_dict_keys(state_dict, with_shape=False)
213
+ if keys_hash in self.keys_hash_dict:
214
+ model_names, model_classes, model_resource = self.keys_hash_dict[keys_hash]
215
+ loaded_model_names, loaded_models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, torch_dtype, device)
216
+ return loaded_model_names, loaded_models
217
+
218
+ return [], []
219
+
220
+
221
+
222
+ class ModelDetectorFromSplitedSingleFile(ModelDetectorFromSingleFile):
223
+ def __init__(self, model_loader_configs=[]):
224
+ super().__init__(model_loader_configs)
225
+
226
+
227
+ def match(self, file_path="", state_dict={}):
228
+ if isinstance(file_path, str) and os.path.isdir(file_path):
229
+ return False
230
+ if state_dict is None or len(state_dict) == 0:
231
+ # Handle list of file paths (for split model files)
232
+ if isinstance(file_path, list):
233
+ state_dict = {}
234
+ for path in file_path:
235
+ state_dict.update(load_state_dict(path))
236
+ else:
237
+ state_dict = load_state_dict(file_path)
238
+ # First try to match the complete state_dict (for merged models)
239
+ if super().match(file_path, state_dict):
240
+ return True
241
+ # If complete match fails, try split matching
242
+ splited_state_dict = split_state_dict_with_prefix(state_dict)
243
+ for sub_state_dict in splited_state_dict:
244
+ if super().match(file_path, sub_state_dict):
245
+ return True
246
+ return False
247
+
248
+
249
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
250
+ # Load state_dict if empty
251
+ if state_dict is None or len(state_dict) == 0:
252
+ # Handle list of file paths (for split model files)
253
+ if isinstance(file_path, list):
254
+ state_dict = {}
255
+ for path in file_path:
256
+ state_dict.update(load_state_dict(path))
257
+ else:
258
+ state_dict = load_state_dict(file_path)
259
+ # First try to load the complete state_dict (for merged models)
260
+ if super().match(file_path, state_dict):
261
+ loaded_model_names, loaded_models = super().load(file_path, state_dict, device, torch_dtype, **kwargs)
262
+ if loaded_model_names:
263
+ return loaded_model_names, loaded_models
264
+ # If complete load fails, try split loading
265
+ splited_state_dict = split_state_dict_with_prefix(state_dict)
266
+ valid_state_dict = {}
267
+ for sub_state_dict in splited_state_dict:
268
+ if super().match(file_path, sub_state_dict):
269
+ valid_state_dict.update(sub_state_dict)
270
+ if super().match(file_path, valid_state_dict):
271
+ loaded_model_names, loaded_models = super().load(file_path, valid_state_dict, device, torch_dtype, **kwargs)
272
+ else:
273
+ loaded_model_names, loaded_models = [], []
274
+ for sub_state_dict in splited_state_dict:
275
+ if super().match(file_path, sub_state_dict):
276
+ loaded_model_names_, loaded_models_ = super().load(file_path, valid_state_dict, device, torch_dtype, **kwargs)
277
+ loaded_model_names += loaded_model_names_
278
+ loaded_models += loaded_models_
279
+ return loaded_model_names, loaded_models
280
+
281
+
282
+
283
+ class ModelDetectorFromHuggingfaceFolder:
284
+ def __init__(self, model_loader_configs=[]):
285
+ self.architecture_dict = {}
286
+ for metadata in model_loader_configs:
287
+ self.add_model_metadata(*metadata)
288
+
289
+
290
+ def add_model_metadata(self, architecture, huggingface_lib, model_name, redirected_architecture):
291
+ self.architecture_dict[architecture] = (huggingface_lib, model_name, redirected_architecture)
292
+
293
+
294
+ def match(self, file_path="", state_dict={}):
295
+ if not isinstance(file_path, str) or os.path.isfile(file_path):
296
+ return False
297
+ file_list = os.listdir(file_path)
298
+ if "config.json" not in file_list:
299
+ return False
300
+ with open(os.path.join(file_path, "config.json"), "r") as f:
301
+ config = json.load(f)
302
+ if "architectures" not in config and "_class_name" not in config:
303
+ return False
304
+ return True
305
+
306
+
307
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, **kwargs):
308
+ with open(os.path.join(file_path, "config.json"), "r") as f:
309
+ config = json.load(f)
310
+ loaded_model_names, loaded_models = [], []
311
+ architectures = config["architectures"] if "architectures" in config else [config["_class_name"]]
312
+ for architecture in architectures:
313
+ huggingface_lib, model_name, redirected_architecture = self.architecture_dict[architecture]
314
+ if redirected_architecture is not None:
315
+ architecture = redirected_architecture
316
+ model_class = importlib.import_module(huggingface_lib).__getattribute__(architecture)
317
+ loaded_model_names_, loaded_models_ = load_model_from_huggingface_folder(file_path, [model_name], [model_class], torch_dtype, device)
318
+ loaded_model_names += loaded_model_names_
319
+ loaded_models += loaded_models_
320
+ return loaded_model_names, loaded_models
321
+
322
+
323
+
324
+ class ModelDetectorFromPatchedSingleFile:
325
+ def __init__(self, model_loader_configs=[]):
326
+ self.keys_hash_with_shape_dict = {}
327
+ for metadata in model_loader_configs:
328
+ self.add_model_metadata(*metadata)
329
+
330
+
331
+ def add_model_metadata(self, keys_hash_with_shape, model_name, model_class, extra_kwargs):
332
+ self.keys_hash_with_shape_dict[keys_hash_with_shape] = (model_name, model_class, extra_kwargs)
333
+
334
+
335
+ def match(self, file_path="", state_dict={}):
336
+ if not isinstance(file_path, str) or os.path.isdir(file_path):
337
+ return False
338
+ if state_dict is None or len(state_dict) == 0:
339
+ state_dict = load_state_dict(file_path)
340
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
341
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
342
+ return True
343
+ return False
344
+
345
+
346
+ def load(self, file_path="", state_dict={}, device="cuda", torch_dtype=torch.float16, model_manager=None, **kwargs):
347
+ if state_dict is None or len(state_dict) == 0:
348
+ state_dict = load_state_dict(file_path)
349
+
350
+ # Load models with strict matching
351
+ loaded_model_names, loaded_models = [], []
352
+ keys_hash_with_shape = hash_state_dict_keys(state_dict, with_shape=True)
353
+ if keys_hash_with_shape in self.keys_hash_with_shape_dict:
354
+ model_names, model_classes, extra_kwargs = self.keys_hash_with_shape_dict[keys_hash_with_shape]
355
+ loaded_model_names_, loaded_models_ = load_patch_model_from_single_file(
356
+ state_dict, model_names, model_classes, extra_kwargs, model_manager, torch_dtype, device)
357
+ loaded_model_names += loaded_model_names_
358
+ loaded_models += loaded_models_
359
+ return loaded_model_names, loaded_models
360
+
361
+
362
+
363
+ class ModelManager:
364
+ def __init__(
365
+ self,
366
+ torch_dtype=torch.float16,
367
+ device="cuda",
368
+ model_id_list: List[Preset_model_id] = [],
369
+ downloading_priority: List[Preset_model_website] = ["ModelScope", "HuggingFace"],
370
+ file_path_list: List[str] = [],
371
+ ):
372
+ self.torch_dtype = torch_dtype
373
+ self.device = device
374
+ self.model = []
375
+ self.model_path = []
376
+ self.model_name = []
377
+ downloaded_files = download_models(model_id_list, downloading_priority) if len(model_id_list) > 0 else []
378
+ self.model_detector = [
379
+ ModelDetectorFromSingleFile(model_loader_configs),
380
+ ModelDetectorFromSplitedSingleFile(model_loader_configs),
381
+ ModelDetectorFromHuggingfaceFolder(huggingface_model_loader_configs),
382
+ ModelDetectorFromPatchedSingleFile(patch_model_loader_configs),
383
+ ]
384
+ self.load_models(downloaded_files + file_path_list)
385
+
386
+
387
+ def load_model_from_single_file(self, file_path="", state_dict={}, model_names=[], model_classes=[], model_resource=None):
388
+ print(f"Loading models from file: {file_path}")
389
+ if state_dict is None or len(state_dict) == 0:
390
+ state_dict = load_state_dict(file_path)
391
+ model_names, models = load_model_from_single_file(state_dict, model_names, model_classes, model_resource, self.torch_dtype, self.device)
392
+ for model_name, model in zip(model_names, models):
393
+ self.model.append(model)
394
+ self.model_path.append(file_path)
395
+ self.model_name.append(model_name)
396
+ print(f" The following models are loaded: {model_names}.")
397
+
398
+
399
+ def load_model_from_huggingface_folder(self, file_path="", model_names=[], model_classes=[]):
400
+ print(f"Loading models from folder: {file_path}")
401
+ model_names, models = load_model_from_huggingface_folder(file_path, model_names, model_classes, self.torch_dtype, self.device)
402
+ for model_name, model in zip(model_names, models):
403
+ self.model.append(model)
404
+ self.model_path.append(file_path)
405
+ self.model_name.append(model_name)
406
+ print(f" The following models are loaded: {model_names}.")
407
+
408
+
409
+ def load_patch_model_from_single_file(self, file_path="", state_dict={}, model_names=[], model_classes=[], extra_kwargs={}):
410
+ print(f"Loading patch models from file: {file_path}")
411
+ model_names, models = load_patch_model_from_single_file(
412
+ state_dict, model_names, model_classes, extra_kwargs, self, self.torch_dtype, self.device)
413
+ for model_name, model in zip(model_names, models):
414
+ self.model.append(model)
415
+ self.model_path.append(file_path)
416
+ self.model_name.append(model_name)
417
+ print(f" The following patched models are loaded: {model_names}.")
418
+
419
+
420
+ def load_lora(self, file_path="", state_dict={}, lora_alpha=1.0):
421
+ if isinstance(file_path, list):
422
+ for file_path_ in file_path:
423
+ self.load_lora(file_path_, state_dict=state_dict, lora_alpha=lora_alpha)
424
+ else:
425
+ print(f"Loading LoRA models from file: {file_path}")
426
+ is_loaded = False
427
+ if state_dict is None or len(state_dict) == 0:
428
+ state_dict = load_state_dict(file_path)
429
+ for model_name, model, model_path in zip(self.model_name, self.model, self.model_path):
430
+ for lora in get_lora_loaders():
431
+ match_results = lora.match(model, state_dict)
432
+ if match_results is not None:
433
+ print(f" Adding LoRA to {model_name} ({model_path}).")
434
+ lora_prefix, model_resource = match_results
435
+ lora.load(model, state_dict, lora_prefix, alpha=lora_alpha, model_resource=model_resource)
436
+ is_loaded = True
437
+ break
438
+ if not is_loaded:
439
+ print(f" Cannot load LoRA: {file_path}")
440
+
441
+
442
+ def load_model(self, file_path, model_names=None, device=None, torch_dtype=None):
443
+ print(f"Loading models from: {file_path}")
444
+ if device is None: device = self.device
445
+ if torch_dtype is None: torch_dtype = self.torch_dtype
446
+ if isinstance(file_path, list):
447
+ state_dict = {}
448
+ for path in file_path:
449
+ state_dict.update(load_state_dict(path))
450
+ logger.info(f" Merged state_dict from {len(file_path)} files, total keys: {len(state_dict)}")
451
+ elif os.path.isfile(file_path):
452
+ state_dict = load_state_dict(file_path)
453
+ else:
454
+ state_dict = None
455
+ for i, model_detector in enumerate(self.model_detector):
456
+ detector_name = model_detector.__class__.__name__
457
+ if model_detector.match(file_path, state_dict):
458
+ logger.info(f" Matched by {detector_name}")
459
+ model_names, models = model_detector.load(
460
+ file_path, state_dict,
461
+ device=device, torch_dtype=torch_dtype,
462
+ allowed_model_names=model_names, model_manager=self
463
+ )
464
+ for model_name, model in zip(model_names, models):
465
+ self.model.append(model)
466
+ self.model_path.append(file_path)
467
+ self.model_name.append(model_name)
468
+ print(f" The following models are loaded: {model_names}.")
469
+ break
470
+ else:
471
+ if isinstance(file_path, list) and len(state_dict) > 0:
472
+ logger.info(f" {detector_name} did not match")
473
+ else:
474
+ print(f" We cannot detect the model type. No models are loaded.")
475
+ if isinstance(file_path, list) and len(state_dict) > 0:
476
+ from .utils import hash_state_dict_keys
477
+ actual_hash = hash_state_dict_keys(state_dict, with_shape=True)
478
+ logger.warning(f" Debug: Actual hash = {actual_hash}")
479
+ logger.warning(f" Debug: First detector has {len(self.model_detector[0].keys_hash_with_shape_dict)} configured hashes")
480
+ # Check if hash exists in config
481
+ if actual_hash in self.model_detector[0].keys_hash_with_shape_dict:
482
+ logger.error(f" Debug: Hash EXISTS in detector but match() returned False!")
483
+ else:
484
+ logger.warning(f" Debug: Hash does NOT exist in detector config")
485
+ logger.info(f" Debug: Sample configured hashes: {list(self.model_detector[0].keys_hash_with_shape_dict.keys())[:10]}")
486
+
487
+
488
+ def load_models(self, file_path_list, model_names=None, device=None, torch_dtype=None):
489
+ for file_path in file_path_list:
490
+ self.load_model(file_path, model_names, device=device, torch_dtype=torch_dtype)
491
+
492
+
493
+ def fetch_model(self, model_name, file_path=None, require_model_path=False):
494
+ fetched_models = []
495
+ fetched_model_paths = []
496
+ for model, model_path, model_name_ in zip(self.model, self.model_path, self.model_name):
497
+ if file_path is not None and file_path != model_path:
498
+ continue
499
+ if model_name == model_name_:
500
+ fetched_models.append(model)
501
+ fetched_model_paths.append(model_path)
502
+ if len(fetched_models) == 0:
503
+ print(f"No {model_name} models available.")
504
+ return None
505
+ if len(fetched_models) == 1:
506
+ print(f"Using {model_name} from {fetched_model_paths[0]}.")
507
+ else:
508
+ print(f"More than one {model_name} models are loaded in model manager: {fetched_model_paths}. Using {model_name} from {fetched_model_paths[0]}.")
509
+ if require_model_path:
510
+ return fetched_models[0], fetched_model_paths[0]
511
+ else:
512
+ return fetched_models[0]
513
+
514
+
515
+ def to(self, device):
516
+ for model in self.model:
517
+ model.to(device)
518
+
omnigen.py ADDED
@@ -0,0 +1,803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The code is revised from DiT
2
+ import os
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ import math
7
+ from safetensors.torch import load_file
8
+ from typing import List, Optional, Tuple, Union
9
+ import torch.utils.checkpoint
10
+ from huggingface_hub import snapshot_download
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast
12
+ from transformers import Phi3Config, Phi3Model
13
+ from transformers.cache_utils import Cache, DynamicCache
14
+ from transformers.utils import logging
15
+
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ class Phi3Transformer(Phi3Model):
21
+ """
22
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
23
+ We only modified the attention mask
24
+ Args:
25
+ config: Phi3Config
26
+ """
27
+ def prefetch_layer(self, layer_idx: int, device: torch.device):
28
+ "Starts prefetching the next layer cache"
29
+ with torch.cuda.stream(self.prefetch_stream):
30
+ # Prefetch next layer tensors to GPU
31
+ for name, param in self.layers[layer_idx].named_parameters():
32
+ param.data = param.data.to(device, non_blocking=True)
33
+
34
+ def evict_previous_layer(self, layer_idx: int):
35
+ "Moves the previous layer cache to the CPU"
36
+ prev_layer_idx = layer_idx - 1
37
+ for name, param in self.layers[prev_layer_idx].named_parameters():
38
+ param.data = param.data.to("cpu", non_blocking=True)
39
+
40
+ def get_offlaod_layer(self, layer_idx: int, device: torch.device):
41
+ # init stream
42
+ if not hasattr(self, "prefetch_stream"):
43
+ self.prefetch_stream = torch.cuda.Stream()
44
+
45
+ # delete previous layer
46
+ torch.cuda.current_stream().synchronize()
47
+ self.evict_previous_layer(layer_idx)
48
+
49
+ # make sure the current layer is ready
50
+ torch.cuda.synchronize(self.prefetch_stream)
51
+
52
+ # load next layer
53
+ self.prefetch_layer((layer_idx + 1) % len(self.layers), device)
54
+
55
+
56
+ def forward(
57
+ self,
58
+ input_ids: torch.LongTensor = None,
59
+ attention_mask: Optional[torch.Tensor] = None,
60
+ position_ids: Optional[torch.LongTensor] = None,
61
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
62
+ inputs_embeds: Optional[torch.FloatTensor] = None,
63
+ use_cache: Optional[bool] = None,
64
+ output_attentions: Optional[bool] = None,
65
+ output_hidden_states: Optional[bool] = None,
66
+ return_dict: Optional[bool] = None,
67
+ cache_position: Optional[torch.LongTensor] = None,
68
+ offload_model: Optional[bool] = False,
69
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
70
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
71
+ output_hidden_states = (
72
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
73
+ )
74
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
75
+
76
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
77
+
78
+ if (input_ids is None) ^ (inputs_embeds is not None):
79
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
80
+
81
+ if self.gradient_checkpointing and self.training:
82
+ if use_cache:
83
+ logger.warning_once(
84
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
85
+ )
86
+ use_cache = False
87
+
88
+ # kept for BC (non `Cache` `past_key_values` inputs)
89
+ return_legacy_cache = False
90
+ if use_cache and not isinstance(past_key_values, Cache):
91
+ return_legacy_cache = True
92
+ if past_key_values is None:
93
+ past_key_values = DynamicCache()
94
+ else:
95
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
96
+ logger.warning_once(
97
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
98
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
99
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
100
+ )
101
+
102
+ # if inputs_embeds is None:
103
+ # inputs_embeds = self.embed_tokens(input_ids)
104
+
105
+ # if cache_position is None:
106
+ # past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
107
+ # cache_position = torch.arange(
108
+ # past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
109
+ # )
110
+ # if position_ids is None:
111
+ # position_ids = cache_position.unsqueeze(0)
112
+
113
+ if attention_mask is not None and attention_mask.dim() == 3:
114
+ dtype = inputs_embeds.dtype
115
+ min_dtype = torch.finfo(dtype).min
116
+ attention_mask = (1 - attention_mask) * min_dtype
117
+ attention_mask = attention_mask.unsqueeze(1).to(inputs_embeds.dtype)
118
+ else:
119
+ raise Exception("attention_mask parameter was unavailable or invalid")
120
+ # causal_mask = self._update_causal_mask(
121
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
122
+ # )
123
+
124
+ hidden_states = inputs_embeds
125
+
126
+ # decoder layers
127
+ all_hidden_states = () if output_hidden_states else None
128
+ all_self_attns = () if output_attentions else None
129
+ next_decoder_cache = None
130
+
131
+ layer_idx = -1
132
+ for decoder_layer in self.layers:
133
+ layer_idx += 1
134
+
135
+ if output_hidden_states:
136
+ all_hidden_states += (hidden_states,)
137
+
138
+ if self.gradient_checkpointing and self.training:
139
+ layer_outputs = self._gradient_checkpointing_func(
140
+ decoder_layer.__call__,
141
+ hidden_states,
142
+ attention_mask,
143
+ position_ids,
144
+ past_key_values,
145
+ output_attentions,
146
+ use_cache,
147
+ cache_position,
148
+ )
149
+ else:
150
+ if offload_model and not self.training:
151
+ self.get_offlaod_layer(layer_idx, device=inputs_embeds.device)
152
+ layer_outputs = decoder_layer(
153
+ hidden_states,
154
+ attention_mask=attention_mask,
155
+ position_ids=position_ids,
156
+ past_key_value=past_key_values,
157
+ output_attentions=output_attentions,
158
+ use_cache=use_cache,
159
+ cache_position=cache_position,
160
+ )
161
+
162
+ hidden_states = layer_outputs[0]
163
+
164
+ if use_cache:
165
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
166
+
167
+ if output_attentions:
168
+ all_self_attns += (layer_outputs[1],)
169
+
170
+ hidden_states = self.norm(hidden_states)
171
+
172
+ # add hidden states from the last decoder layer
173
+ if output_hidden_states:
174
+ print('************')
175
+ all_hidden_states += (hidden_states,)
176
+
177
+ next_cache = next_decoder_cache if use_cache else None
178
+ if return_legacy_cache:
179
+ next_cache = next_cache.to_legacy_cache()
180
+
181
+ if not return_dict:
182
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
183
+ return BaseModelOutputWithPast(
184
+ last_hidden_state=hidden_states,
185
+ past_key_values=next_cache,
186
+ hidden_states=all_hidden_states,
187
+ attentions=all_self_attns,
188
+ )
189
+
190
+
191
+ def modulate(x, shift, scale):
192
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
193
+
194
+
195
+ class TimestepEmbedder(nn.Module):
196
+ """
197
+ Embeds scalar timesteps into vector representations.
198
+ """
199
+ def __init__(self, hidden_size, frequency_embedding_size=256):
200
+ super().__init__()
201
+ self.mlp = nn.Sequential(
202
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
203
+ nn.SiLU(),
204
+ nn.Linear(hidden_size, hidden_size, bias=True),
205
+ )
206
+ self.frequency_embedding_size = frequency_embedding_size
207
+
208
+ @staticmethod
209
+ def timestep_embedding(t, dim, max_period=10000):
210
+ """
211
+ Create sinusoidal timestep embeddings.
212
+ :param t: a 1-D Tensor of N indices, one per batch element.
213
+ These may be fractional.
214
+ :param dim: the dimension of the output.
215
+ :param max_period: controls the minimum frequency of the embeddings.
216
+ :return: an (N, D) Tensor of positional embeddings.
217
+ """
218
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
219
+ half = dim // 2
220
+ freqs = torch.exp(
221
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
222
+ ).to(device=t.device)
223
+ args = t[:, None].float() * freqs[None]
224
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
225
+ if dim % 2:
226
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
227
+ return embedding
228
+
229
+ def forward(self, t, dtype=torch.float32):
230
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(dtype)
231
+ t_emb = self.mlp(t_freq)
232
+ return t_emb
233
+
234
+
235
+ class FinalLayer(nn.Module):
236
+ """
237
+ The final layer of DiT.
238
+ """
239
+ def __init__(self, hidden_size, patch_size, out_channels):
240
+ super().__init__()
241
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
242
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
243
+ self.adaLN_modulation = nn.Sequential(
244
+ nn.SiLU(),
245
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True)
246
+ )
247
+
248
+ def forward(self, x, c):
249
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
250
+ x = modulate(self.norm_final(x), shift, scale)
251
+ x = self.linear(x)
252
+ return x
253
+
254
+
255
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=1):
256
+ """
257
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
258
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
259
+ """
260
+ if isinstance(grid_size, int):
261
+ grid_size = (grid_size, grid_size)
262
+
263
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size) / interpolation_scale
264
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size) / interpolation_scale
265
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
266
+ grid = np.stack(grid, axis=0)
267
+
268
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
269
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
270
+ if cls_token and extra_tokens > 0:
271
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
272
+ return pos_embed
273
+
274
+
275
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
276
+ assert embed_dim % 2 == 0
277
+
278
+ # use half of dimensions to encode grid_h
279
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
280
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
281
+
282
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
283
+ return emb
284
+
285
+
286
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
287
+ """
288
+ embed_dim: output dimension for each position
289
+ pos: a list of positions to be encoded: size (M,)
290
+ out: (M, D)
291
+ """
292
+ assert embed_dim % 2 == 0
293
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
294
+ omega /= embed_dim / 2.
295
+ omega = 1. / 10000**omega # (D/2,)
296
+
297
+ pos = pos.reshape(-1) # (M,)
298
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
299
+
300
+ emb_sin = np.sin(out) # (M, D/2)
301
+ emb_cos = np.cos(out) # (M, D/2)
302
+
303
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
304
+ return emb
305
+
306
+
307
+ class PatchEmbedMR(nn.Module):
308
+ """ 2D Image to Patch Embedding
309
+ """
310
+ def __init__(
311
+ self,
312
+ patch_size: int = 2,
313
+ in_chans: int = 4,
314
+ embed_dim: int = 768,
315
+ bias: bool = True,
316
+ ):
317
+ super().__init__()
318
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
319
+
320
+ def forward(self, x):
321
+ x = self.proj(x)
322
+ x = x.flatten(2).transpose(1, 2) # NCHW -> NLC
323
+ return x
324
+
325
+
326
+ class OmniGenOriginalModel(nn.Module):
327
+ """
328
+ Diffusion model with a Transformer backbone.
329
+ """
330
+ def __init__(
331
+ self,
332
+ transformer_config: Phi3Config,
333
+ patch_size=2,
334
+ in_channels=4,
335
+ pe_interpolation: float = 1.0,
336
+ pos_embed_max_size: int = 192,
337
+ ):
338
+ super().__init__()
339
+ self.in_channels = in_channels
340
+ self.out_channels = in_channels
341
+ self.patch_size = patch_size
342
+ self.pos_embed_max_size = pos_embed_max_size
343
+
344
+ hidden_size = transformer_config.hidden_size
345
+
346
+ self.x_embedder = PatchEmbedMR(patch_size, in_channels, hidden_size, bias=True)
347
+ self.input_x_embedder = PatchEmbedMR(patch_size, in_channels, hidden_size, bias=True)
348
+
349
+ self.time_token = TimestepEmbedder(hidden_size)
350
+ self.t_embedder = TimestepEmbedder(hidden_size)
351
+
352
+ self.pe_interpolation = pe_interpolation
353
+ pos_embed = get_2d_sincos_pos_embed(hidden_size, pos_embed_max_size, interpolation_scale=self.pe_interpolation, base_size=64)
354
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=True)
355
+
356
+ self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)
357
+
358
+ self.initialize_weights()
359
+
360
+ self.llm = Phi3Transformer(config=transformer_config)
361
+ self.llm.config.use_cache = False
362
+
363
+ @classmethod
364
+ def from_pretrained(cls, model_name):
365
+ if not os.path.exists(model_name):
366
+ cache_folder = os.getenv('HF_HUB_CACHE')
367
+ model_name = snapshot_download(repo_id=model_name,
368
+ cache_dir=cache_folder,
369
+ ignore_patterns=['flax_model.msgpack', 'rust_model.ot', 'tf_model.h5'])
370
+ config = Phi3Config.from_pretrained(model_name)
371
+ model = cls(config)
372
+ if os.path.exists(os.path.join(model_name, 'model.safetensors')):
373
+ print("Loading safetensors")
374
+ ckpt = load_file(os.path.join(model_name, 'model.safetensors'))
375
+ else:
376
+ ckpt = torch.load(os.path.join(model_name, 'model.pt'), map_location='cpu')
377
+ model.load_state_dict(ckpt)
378
+ return model
379
+
380
+ def initialize_weights(self):
381
+ assert not hasattr(self, "llama")
382
+
383
+ # Initialize transformer layers:
384
+ def _basic_init(module):
385
+ if isinstance(module, nn.Linear):
386
+ torch.nn.init.xavier_uniform_(module.weight)
387
+ if module.bias is not None:
388
+ nn.init.constant_(module.bias, 0)
389
+ self.apply(_basic_init)
390
+
391
+ # Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
392
+ w = self.x_embedder.proj.weight.data
393
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
394
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
395
+
396
+ w = self.input_x_embedder.proj.weight.data
397
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
398
+ nn.init.constant_(self.x_embedder.proj.bias, 0)
399
+
400
+
401
+ # Initialize timestep embedding MLP:
402
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
403
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
404
+ nn.init.normal_(self.time_token.mlp[0].weight, std=0.02)
405
+ nn.init.normal_(self.time_token.mlp[2].weight, std=0.02)
406
+
407
+ # Zero-out output layers:
408
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
409
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
410
+ nn.init.constant_(self.final_layer.linear.weight, 0)
411
+ nn.init.constant_(self.final_layer.linear.bias, 0)
412
+
413
+ def unpatchify(self, x, h, w):
414
+ """
415
+ x: (N, T, patch_size**2 * C)
416
+ imgs: (N, H, W, C)
417
+ """
418
+ c = self.out_channels
419
+
420
+ x = x.reshape(shape=(x.shape[0], h//self.patch_size, w//self.patch_size, self.patch_size, self.patch_size, c))
421
+ x = torch.einsum('nhwpqc->nchpwq', x)
422
+ imgs = x.reshape(shape=(x.shape[0], c, h, w))
423
+ return imgs
424
+
425
+
426
+ def cropped_pos_embed(self, height, width):
427
+ """Crops positional embeddings for SD3 compatibility."""
428
+ if self.pos_embed_max_size is None:
429
+ raise ValueError("`pos_embed_max_size` must be set for cropping.")
430
+
431
+ height = height // self.patch_size
432
+ width = width // self.patch_size
433
+ if height > self.pos_embed_max_size:
434
+ raise ValueError(
435
+ f"Height ({height}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
436
+ )
437
+ if width > self.pos_embed_max_size:
438
+ raise ValueError(
439
+ f"Width ({width}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
440
+ )
441
+
442
+ top = (self.pos_embed_max_size - height) // 2
443
+ left = (self.pos_embed_max_size - width) // 2
444
+ spatial_pos_embed = self.pos_embed.reshape(1, self.pos_embed_max_size, self.pos_embed_max_size, -1)
445
+ spatial_pos_embed = spatial_pos_embed[:, top : top + height, left : left + width, :]
446
+ # print(top, top + height, left, left + width, spatial_pos_embed.size())
447
+ spatial_pos_embed = spatial_pos_embed.reshape(1, -1, spatial_pos_embed.shape[-1])
448
+ return spatial_pos_embed
449
+
450
+
451
+ def patch_multiple_resolutions(self, latents, padding_latent=None, is_input_images:bool=False):
452
+ if isinstance(latents, list):
453
+ return_list = False
454
+ if padding_latent is None:
455
+ padding_latent = [None] * len(latents)
456
+ return_list = True
457
+ patched_latents, num_tokens, shapes = [], [], []
458
+ for latent, padding in zip(latents, padding_latent):
459
+ height, width = latent.shape[-2:]
460
+ if is_input_images:
461
+ latent = self.input_x_embedder(latent)
462
+ else:
463
+ latent = self.x_embedder(latent)
464
+ pos_embed = self.cropped_pos_embed(height, width)
465
+ latent = latent + pos_embed
466
+ if padding is not None:
467
+ latent = torch.cat([latent, padding], dim=-2)
468
+ patched_latents.append(latent)
469
+
470
+ num_tokens.append(pos_embed.size(1))
471
+ shapes.append([height, width])
472
+ if not return_list:
473
+ latents = torch.cat(patched_latents, dim=0)
474
+ else:
475
+ latents = patched_latents
476
+ else:
477
+ height, width = latents.shape[-2:]
478
+ if is_input_images:
479
+ latents = self.input_x_embedder(latents)
480
+ else:
481
+ latents = self.x_embedder(latents)
482
+ pos_embed = self.cropped_pos_embed(height, width)
483
+ latents = latents + pos_embed
484
+ num_tokens = latents.size(1)
485
+ shapes = [height, width]
486
+ return latents, num_tokens, shapes
487
+
488
+
489
+ def forward(self, x, timestep, input_ids, input_img_latents, input_image_sizes, attention_mask, position_ids, padding_latent=None, past_key_values=None, return_past_key_values=True, offload_model:bool=False):
490
+ """
491
+
492
+ """
493
+ input_is_list = isinstance(x, list)
494
+ x, num_tokens, shapes = self.patch_multiple_resolutions(x, padding_latent)
495
+ time_token = self.time_token(timestep, dtype=x[0].dtype).unsqueeze(1)
496
+
497
+ if input_img_latents is not None:
498
+ input_latents, _, _ = self.patch_multiple_resolutions(input_img_latents, is_input_images=True)
499
+ if input_ids is not None:
500
+ condition_embeds = self.llm.embed_tokens(input_ids).clone()
501
+ input_img_inx = 0
502
+ for b_inx in input_image_sizes.keys():
503
+ for start_inx, end_inx in input_image_sizes[b_inx]:
504
+ condition_embeds[b_inx, start_inx: end_inx] = input_latents[input_img_inx]
505
+ input_img_inx += 1
506
+ if input_img_latents is not None:
507
+ assert input_img_inx == len(input_latents)
508
+
509
+ input_emb = torch.cat([condition_embeds, time_token, x], dim=1)
510
+ else:
511
+ input_emb = torch.cat([time_token, x], dim=1)
512
+ output = self.llm(inputs_embeds=input_emb, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, offload_model=offload_model)
513
+ output, past_key_values = output.last_hidden_state, output.past_key_values
514
+ if input_is_list:
515
+ image_embedding = output[:, -max(num_tokens):]
516
+ time_emb = self.t_embedder(timestep, dtype=x.dtype)
517
+ x = self.final_layer(image_embedding, time_emb)
518
+ latents = []
519
+ for i in range(x.size(0)):
520
+ latent = x[i:i+1, :num_tokens[i]]
521
+ latent = self.unpatchify(latent, shapes[i][0], shapes[i][1])
522
+ latents.append(latent)
523
+ else:
524
+ image_embedding = output[:, -num_tokens:]
525
+ time_emb = self.t_embedder(timestep, dtype=x.dtype)
526
+ x = self.final_layer(image_embedding, time_emb)
527
+ latents = self.unpatchify(x, shapes[0], shapes[1])
528
+
529
+ if return_past_key_values:
530
+ return latents, past_key_values
531
+ return latents
532
+
533
+ @torch.no_grad()
534
+ def forward_with_cfg(self, x, timestep, input_ids, input_img_latents, input_image_sizes, attention_mask, position_ids, cfg_scale, use_img_cfg, img_cfg_scale, past_key_values, use_kv_cache, offload_model):
535
+ self.llm.config.use_cache = use_kv_cache
536
+ model_out, past_key_values = self.forward(x, timestep, input_ids, input_img_latents, input_image_sizes, attention_mask, position_ids, past_key_values=past_key_values, return_past_key_values=True, offload_model=offload_model)
537
+ if use_img_cfg:
538
+ cond, uncond, img_cond = torch.split(model_out, len(model_out) // 3, dim=0)
539
+ cond = uncond + img_cfg_scale * (img_cond - uncond) + cfg_scale * (cond - img_cond)
540
+ model_out = [cond, cond, cond]
541
+ else:
542
+ cond, uncond = torch.split(model_out, len(model_out) // 2, dim=0)
543
+ cond = uncond + cfg_scale * (cond - uncond)
544
+ model_out = [cond, cond]
545
+
546
+ return torch.cat(model_out, dim=0), past_key_values
547
+
548
+
549
+ @torch.no_grad()
550
+ def forward_with_separate_cfg(self, x, timestep, input_ids, input_img_latents, input_image_sizes, attention_mask, position_ids, cfg_scale, use_img_cfg, img_cfg_scale, past_key_values, use_kv_cache, offload_model):
551
+ self.llm.config.use_cache = use_kv_cache
552
+ if past_key_values is None:
553
+ past_key_values = [None] * len(attention_mask)
554
+
555
+ x = torch.split(x, len(x) // len(attention_mask), dim=0)
556
+ timestep = timestep.to(x[0].dtype)
557
+ timestep = torch.split(timestep, len(timestep) // len(input_ids), dim=0)
558
+
559
+ model_out, pask_key_values = [], []
560
+ for i in range(len(input_ids)):
561
+ temp_out, temp_pask_key_values = self.forward(x[i], timestep[i], input_ids[i], input_img_latents[i], input_image_sizes[i], attention_mask[i], position_ids[i], past_key_values=past_key_values[i], return_past_key_values=True, offload_model=offload_model)
562
+ model_out.append(temp_out)
563
+ pask_key_values.append(temp_pask_key_values)
564
+
565
+ if len(model_out) == 3:
566
+ cond, uncond, img_cond = model_out
567
+ cond = uncond + img_cfg_scale * (img_cond - uncond) + cfg_scale * (cond - img_cond)
568
+ model_out = [cond, cond, cond]
569
+ elif len(model_out) == 2:
570
+ cond, uncond = model_out
571
+ cond = uncond + cfg_scale * (cond - uncond)
572
+ model_out = [cond, cond]
573
+ else:
574
+ return model_out[0]
575
+
576
+ return torch.cat(model_out, dim=0), pask_key_values
577
+
578
+
579
+
580
+ class OmniGenTransformer(OmniGenOriginalModel):
581
+ def __init__(self):
582
+ config = {
583
+ "_name_or_path": "Phi-3-vision-128k-instruct",
584
+ "architectures": [
585
+ "Phi3ForCausalLM"
586
+ ],
587
+ "attention_dropout": 0.0,
588
+ "bos_token_id": 1,
589
+ "eos_token_id": 2,
590
+ "hidden_act": "silu",
591
+ "hidden_size": 3072,
592
+ "initializer_range": 0.02,
593
+ "intermediate_size": 8192,
594
+ "max_position_embeddings": 131072,
595
+ "model_type": "phi3",
596
+ "num_attention_heads": 32,
597
+ "num_hidden_layers": 32,
598
+ "num_key_value_heads": 32,
599
+ "original_max_position_embeddings": 4096,
600
+ "rms_norm_eps": 1e-05,
601
+ "rope_scaling": {
602
+ "long_factor": [
603
+ 1.0299999713897705,
604
+ 1.0499999523162842,
605
+ 1.0499999523162842,
606
+ 1.0799999237060547,
607
+ 1.2299998998641968,
608
+ 1.2299998998641968,
609
+ 1.2999999523162842,
610
+ 1.4499999284744263,
611
+ 1.5999999046325684,
612
+ 1.6499998569488525,
613
+ 1.8999998569488525,
614
+ 2.859999895095825,
615
+ 3.68999981880188,
616
+ 5.419999599456787,
617
+ 5.489999771118164,
618
+ 5.489999771118164,
619
+ 9.09000015258789,
620
+ 11.579999923706055,
621
+ 15.65999984741211,
622
+ 15.769999504089355,
623
+ 15.789999961853027,
624
+ 18.360000610351562,
625
+ 21.989999771118164,
626
+ 23.079999923706055,
627
+ 30.009998321533203,
628
+ 32.35000228881836,
629
+ 32.590003967285156,
630
+ 35.56000518798828,
631
+ 39.95000457763672,
632
+ 53.840003967285156,
633
+ 56.20000457763672,
634
+ 57.95000457763672,
635
+ 59.29000473022461,
636
+ 59.77000427246094,
637
+ 59.920005798339844,
638
+ 61.190006256103516,
639
+ 61.96000671386719,
640
+ 62.50000762939453,
641
+ 63.3700065612793,
642
+ 63.48000717163086,
643
+ 63.48000717163086,
644
+ 63.66000747680664,
645
+ 63.850006103515625,
646
+ 64.08000946044922,
647
+ 64.760009765625,
648
+ 64.80001068115234,
649
+ 64.81001281738281,
650
+ 64.81001281738281
651
+ ],
652
+ "short_factor": [
653
+ 1.05,
654
+ 1.05,
655
+ 1.05,
656
+ 1.1,
657
+ 1.1,
658
+ 1.1,
659
+ 1.2500000000000002,
660
+ 1.2500000000000002,
661
+ 1.4000000000000004,
662
+ 1.4500000000000004,
663
+ 1.5500000000000005,
664
+ 1.8500000000000008,
665
+ 1.9000000000000008,
666
+ 2.000000000000001,
667
+ 2.000000000000001,
668
+ 2.000000000000001,
669
+ 2.000000000000001,
670
+ 2.000000000000001,
671
+ 2.000000000000001,
672
+ 2.000000000000001,
673
+ 2.000000000000001,
674
+ 2.000000000000001,
675
+ 2.000000000000001,
676
+ 2.000000000000001,
677
+ 2.000000000000001,
678
+ 2.000000000000001,
679
+ 2.000000000000001,
680
+ 2.000000000000001,
681
+ 2.000000000000001,
682
+ 2.000000000000001,
683
+ 2.000000000000001,
684
+ 2.000000000000001,
685
+ 2.1000000000000005,
686
+ 2.1000000000000005,
687
+ 2.2,
688
+ 2.3499999999999996,
689
+ 2.3499999999999996,
690
+ 2.3499999999999996,
691
+ 2.3499999999999996,
692
+ 2.3999999999999995,
693
+ 2.3999999999999995,
694
+ 2.6499999999999986,
695
+ 2.6999999999999984,
696
+ 2.8999999999999977,
697
+ 2.9499999999999975,
698
+ 3.049999999999997,
699
+ 3.049999999999997,
700
+ 3.049999999999997
701
+ ],
702
+ "type": "su"
703
+ },
704
+ "rope_theta": 10000.0,
705
+ "sliding_window": 131072,
706
+ "tie_word_embeddings": False,
707
+ "torch_dtype": "bfloat16",
708
+ "transformers_version": "4.38.1",
709
+ "use_cache": True,
710
+ "vocab_size": 32064,
711
+ "_attn_implementation": "sdpa"
712
+ }
713
+ config = Phi3Config(**config)
714
+ super().__init__(config)
715
+
716
+
717
+ def forward(self, x, timestep, input_ids, input_img_latents, input_image_sizes, attention_mask, position_ids, padding_latent=None, past_key_values=None, return_past_key_values=True, offload_model:bool=False):
718
+ input_is_list = isinstance(x, list)
719
+ x, num_tokens, shapes = self.patch_multiple_resolutions(x, padding_latent)
720
+ time_token = self.time_token(timestep, dtype=x[0].dtype).unsqueeze(1)
721
+
722
+ if input_img_latents is not None:
723
+ input_latents, _, _ = self.patch_multiple_resolutions(input_img_latents, is_input_images=True)
724
+ if input_ids is not None:
725
+ condition_embeds = self.llm.embed_tokens(input_ids).clone()
726
+ input_img_inx = 0
727
+ for b_inx in input_image_sizes.keys():
728
+ for start_inx, end_inx in input_image_sizes[b_inx]:
729
+ condition_embeds[b_inx, start_inx: end_inx] = input_latents[input_img_inx]
730
+ input_img_inx += 1
731
+ if input_img_latents is not None:
732
+ assert input_img_inx == len(input_latents)
733
+
734
+ input_emb = torch.cat([condition_embeds, time_token, x], dim=1)
735
+ else:
736
+ input_emb = torch.cat([time_token, x], dim=1)
737
+ output = self.llm(inputs_embeds=input_emb, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, offload_model=offload_model)
738
+ output, past_key_values = output.last_hidden_state, output.past_key_values
739
+ if input_is_list:
740
+ image_embedding = output[:, -max(num_tokens):]
741
+ time_emb = self.t_embedder(timestep, dtype=x.dtype)
742
+ x = self.final_layer(image_embedding, time_emb)
743
+ latents = []
744
+ for i in range(x.size(0)):
745
+ latent = x[i:i+1, :num_tokens[i]]
746
+ latent = self.unpatchify(latent, shapes[i][0], shapes[i][1])
747
+ latents.append(latent)
748
+ else:
749
+ image_embedding = output[:, -num_tokens:]
750
+ time_emb = self.t_embedder(timestep, dtype=x.dtype)
751
+ x = self.final_layer(image_embedding, time_emb)
752
+ latents = self.unpatchify(x, shapes[0], shapes[1])
753
+
754
+ if return_past_key_values:
755
+ return latents, past_key_values
756
+ return latents
757
+
758
+
759
+ @torch.no_grad()
760
+ def forward_with_separate_cfg(self, x, timestep, input_ids, input_img_latents, input_image_sizes, attention_mask, position_ids, cfg_scale, use_img_cfg, img_cfg_scale, past_key_values, use_kv_cache, offload_model):
761
+ self.llm.config.use_cache = use_kv_cache
762
+ if past_key_values is None:
763
+ past_key_values = [None] * len(attention_mask)
764
+
765
+ x = torch.split(x, len(x) // len(attention_mask), dim=0)
766
+ timestep = timestep.to(x[0].dtype)
767
+ timestep = torch.split(timestep, len(timestep) // len(input_ids), dim=0)
768
+
769
+ model_out, pask_key_values = [], []
770
+ for i in range(len(input_ids)):
771
+ temp_out, temp_pask_key_values = self.forward(x[i], timestep[i], input_ids[i], input_img_latents[i], input_image_sizes[i], attention_mask[i], position_ids[i], past_key_values=past_key_values[i], return_past_key_values=True, offload_model=offload_model)
772
+ model_out.append(temp_out)
773
+ pask_key_values.append(temp_pask_key_values)
774
+
775
+ if len(model_out) == 3:
776
+ cond, uncond, img_cond = model_out
777
+ cond = uncond + img_cfg_scale * (img_cond - uncond) + cfg_scale * (cond - img_cond)
778
+ model_out = [cond, cond, cond]
779
+ elif len(model_out) == 2:
780
+ cond, uncond = model_out
781
+ cond = uncond + cfg_scale * (cond - uncond)
782
+ model_out = [cond, cond]
783
+ else:
784
+ return model_out[0]
785
+
786
+ return torch.cat(model_out, dim=0), pask_key_values
787
+
788
+
789
+ @staticmethod
790
+ def state_dict_converter():
791
+ return OmniGenTransformerStateDictConverter()
792
+
793
+
794
+
795
+ class OmniGenTransformerStateDictConverter:
796
+ def __init__(self):
797
+ pass
798
+
799
+ def from_diffusers(self, state_dict):
800
+ return state_dict
801
+
802
+ def from_civitai(self, state_dict):
803
+ return state_dict
qwenvl.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class Qwen25VL_7b_Embedder(torch.nn.Module):
5
+ def __init__(self, model_path, max_length=640, dtype=torch.bfloat16, device="cuda"):
6
+ super(Qwen25VL_7b_Embedder, self).__init__()
7
+ self.max_length = max_length
8
+ self.dtype = dtype
9
+ self.device = device
10
+
11
+ from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
12
+
13
+ self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
14
+ model_path,
15
+ torch_dtype=dtype,
16
+ ).to(torch.cuda.current_device())
17
+
18
+ self.model.requires_grad_(False)
19
+ self.processor = AutoProcessor.from_pretrained(
20
+ model_path, min_pixels=256 * 28 * 28, max_pixels=324 * 28 * 28
21
+ )
22
+
23
+ Qwen25VL_7b_PREFIX = '''Given a user prompt, generate an "Enhanced prompt" that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:
24
+ - If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.
25
+ - If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.\n
26
+ Here are examples of how to transform or refine prompts:
27
+ - User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.
28
+ - User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.\n
29
+ Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:
30
+ User Prompt:'''
31
+
32
+ self.prefix = Qwen25VL_7b_PREFIX
33
+
34
+ @staticmethod
35
+ def from_pretrained(path, torch_dtype=torch.bfloat16, device="cuda"):
36
+ return Qwen25VL_7b_Embedder(path, dtype=torch_dtype, device=device)
37
+
38
+ def forward(self, caption, ref_images):
39
+ text_list = caption
40
+ embs = torch.zeros(
41
+ len(text_list),
42
+ self.max_length,
43
+ self.model.config.hidden_size,
44
+ dtype=torch.bfloat16,
45
+ device=torch.cuda.current_device(),
46
+ )
47
+ hidden_states = torch.zeros(
48
+ len(text_list),
49
+ self.max_length,
50
+ self.model.config.hidden_size,
51
+ dtype=torch.bfloat16,
52
+ device=torch.cuda.current_device(),
53
+ )
54
+ masks = torch.zeros(
55
+ len(text_list),
56
+ self.max_length,
57
+ dtype=torch.long,
58
+ device=torch.cuda.current_device(),
59
+ )
60
+ input_ids_list = []
61
+ attention_mask_list = []
62
+ emb_list = []
63
+
64
+ def split_string(s):
65
+ s = s.replace("“", '"').replace("”", '"').replace("'", '''"''') # use english quotes
66
+ result = []
67
+ in_quotes = False
68
+ temp = ""
69
+
70
+ for idx,char in enumerate(s):
71
+ if char == '"' and idx>155:
72
+ temp += char
73
+ if not in_quotes:
74
+ result.append(temp)
75
+ temp = ""
76
+
77
+ in_quotes = not in_quotes
78
+ continue
79
+ if in_quotes:
80
+ if char.isspace():
81
+ pass # have space token
82
+
83
+ result.append("“" + char + "”")
84
+ else:
85
+ temp += char
86
+
87
+ if temp:
88
+ result.append(temp)
89
+
90
+ return result
91
+
92
+ for idx, (txt, imgs) in enumerate(zip(text_list, ref_images)):
93
+
94
+ messages = [{"role": "user", "content": []}]
95
+
96
+ messages[0]["content"].append({"type": "text", "text": f"{self.prefix}"})
97
+
98
+ messages[0]["content"].append({"type": "image", "image": imgs})
99
+
100
+ # 再添加 text
101
+ messages[0]["content"].append({"type": "text", "text": f"{txt}"})
102
+
103
+ # Preparation for inference
104
+ text = self.processor.apply_chat_template(
105
+ messages, tokenize=False, add_generation_prompt=True, add_vision_id=True
106
+ )
107
+
108
+ image_inputs = [imgs]
109
+
110
+ inputs = self.processor(
111
+ text=[text],
112
+ images=image_inputs,
113
+ padding=True,
114
+ return_tensors="pt",
115
+ )
116
+
117
+ old_inputs_ids = inputs.input_ids
118
+ text_split_list = split_string(text)
119
+
120
+ token_list = []
121
+ for text_each in text_split_list:
122
+ txt_inputs = self.processor(
123
+ text=text_each,
124
+ images=None,
125
+ videos=None,
126
+ padding=True,
127
+ return_tensors="pt",
128
+ )
129
+ token_each = txt_inputs.input_ids
130
+ if token_each[0][0] == 2073 and token_each[0][-1] == 854:
131
+ token_each = token_each[:, 1:-1]
132
+ token_list.append(token_each)
133
+ else:
134
+ token_list.append(token_each)
135
+
136
+ new_txt_ids = torch.cat(token_list, dim=1).to("cuda")
137
+
138
+ new_txt_ids = new_txt_ids.to(old_inputs_ids.device)
139
+
140
+ idx1 = (old_inputs_ids == 151653).nonzero(as_tuple=True)[1][0]
141
+ idx2 = (new_txt_ids == 151653).nonzero(as_tuple=True)[1][0]
142
+ inputs.input_ids = (
143
+ torch.cat([old_inputs_ids[0, :idx1], new_txt_ids[0, idx2:]], dim=0)
144
+ .unsqueeze(0)
145
+ .to("cuda")
146
+ )
147
+ inputs.attention_mask = (inputs.input_ids > 0).long().to("cuda")
148
+ outputs = self.model(
149
+ input_ids=inputs.input_ids,
150
+ attention_mask=inputs.attention_mask,
151
+ pixel_values=inputs.pixel_values.to("cuda"),
152
+ image_grid_thw=inputs.image_grid_thw.to("cuda"),
153
+ output_hidden_states=True,
154
+ )
155
+
156
+ emb = outputs["hidden_states"][-1]
157
+
158
+ embs[idx, : min(self.max_length, emb.shape[1] - 217)] = emb[0, 217:][
159
+ : self.max_length
160
+ ]
161
+
162
+ masks[idx, : min(self.max_length, emb.shape[1] - 217)] = torch.ones(
163
+ (min(self.max_length, emb.shape[1] - 217)),
164
+ dtype=torch.long,
165
+ device=torch.cuda.current_device(),
166
+ )
167
+
168
+ return embs, masks
sd3_dit.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange
3
+ from .svd_unet import TemporalTimesteps
4
+ from .tiler import TileWorker
5
+
6
+
7
+
8
+ class RMSNorm(torch.nn.Module):
9
+ def __init__(self, dim, eps, elementwise_affine=True):
10
+ super().__init__()
11
+ self.eps = eps
12
+ if elementwise_affine:
13
+ self.weight = torch.nn.Parameter(torch.ones((dim,)))
14
+ else:
15
+ self.weight = None
16
+
17
+ def forward(self, hidden_states):
18
+ input_dtype = hidden_states.dtype
19
+ variance = hidden_states.to(torch.float32).square().mean(-1, keepdim=True)
20
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
21
+ hidden_states = hidden_states.to(input_dtype)
22
+ if self.weight is not None:
23
+ hidden_states = hidden_states * self.weight
24
+ return hidden_states
25
+
26
+
27
+
28
+ class PatchEmbed(torch.nn.Module):
29
+ def __init__(self, patch_size=2, in_channels=16, embed_dim=1536, pos_embed_max_size=192):
30
+ super().__init__()
31
+ self.pos_embed_max_size = pos_embed_max_size
32
+ self.patch_size = patch_size
33
+
34
+ self.proj = torch.nn.Conv2d(in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size)
35
+ self.pos_embed = torch.nn.Parameter(torch.zeros(1, self.pos_embed_max_size, self.pos_embed_max_size, embed_dim))
36
+
37
+ def cropped_pos_embed(self, height, width):
38
+ height = height // self.patch_size
39
+ width = width // self.patch_size
40
+ top = (self.pos_embed_max_size - height) // 2
41
+ left = (self.pos_embed_max_size - width) // 2
42
+ spatial_pos_embed = self.pos_embed[:, top : top + height, left : left + width, :].flatten(1, 2)
43
+ return spatial_pos_embed
44
+
45
+ def forward(self, latent):
46
+ height, width = latent.shape[-2:]
47
+ latent = self.proj(latent)
48
+ latent = latent.flatten(2).transpose(1, 2)
49
+ pos_embed = self.cropped_pos_embed(height, width)
50
+ return latent + pos_embed
51
+
52
+
53
+
54
+ class TimestepEmbeddings(torch.nn.Module):
55
+ def __init__(self, dim_in, dim_out, computation_device=None):
56
+ super().__init__()
57
+ self.time_proj = TemporalTimesteps(num_channels=dim_in, flip_sin_to_cos=True, downscale_freq_shift=0, computation_device=computation_device)
58
+ self.timestep_embedder = torch.nn.Sequential(
59
+ torch.nn.Linear(dim_in, dim_out), torch.nn.SiLU(), torch.nn.Linear(dim_out, dim_out)
60
+ )
61
+
62
+ def forward(self, timestep, dtype):
63
+ time_emb = self.time_proj(timestep).to(dtype)
64
+ time_emb = self.timestep_embedder(time_emb)
65
+ return time_emb
66
+
67
+
68
+
69
+ class AdaLayerNorm(torch.nn.Module):
70
+ def __init__(self, dim, single=False, dual=False):
71
+ super().__init__()
72
+ self.single = single
73
+ self.dual = dual
74
+ self.linear = torch.nn.Linear(dim, dim * [[6, 2][single], 9][dual])
75
+ self.norm = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
76
+
77
+ def forward(self, x, emb):
78
+ emb = self.linear(torch.nn.functional.silu(emb))
79
+ if self.single:
80
+ scale, shift = emb.unsqueeze(1).chunk(2, dim=2)
81
+ x = self.norm(x) * (1 + scale) + shift
82
+ return x
83
+ elif self.dual:
84
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp, shift_msa2, scale_msa2, gate_msa2 = emb.unsqueeze(1).chunk(9, dim=2)
85
+ norm_x = self.norm(x)
86
+ x = norm_x * (1 + scale_msa) + shift_msa
87
+ norm_x2 = norm_x * (1 + scale_msa2) + shift_msa2
88
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp, norm_x2, gate_msa2
89
+ else:
90
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.unsqueeze(1).chunk(6, dim=2)
91
+ x = self.norm(x) * (1 + scale_msa) + shift_msa
92
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
93
+
94
+
95
+
96
+ class JointAttention(torch.nn.Module):
97
+ def __init__(self, dim_a, dim_b, num_heads, head_dim, only_out_a=False, use_rms_norm=False):
98
+ super().__init__()
99
+ self.num_heads = num_heads
100
+ self.head_dim = head_dim
101
+ self.only_out_a = only_out_a
102
+
103
+ self.a_to_qkv = torch.nn.Linear(dim_a, dim_a * 3)
104
+ self.b_to_qkv = torch.nn.Linear(dim_b, dim_b * 3)
105
+
106
+ self.a_to_out = torch.nn.Linear(dim_a, dim_a)
107
+ if not only_out_a:
108
+ self.b_to_out = torch.nn.Linear(dim_b, dim_b)
109
+
110
+ if use_rms_norm:
111
+ self.norm_q_a = RMSNorm(head_dim, eps=1e-6)
112
+ self.norm_k_a = RMSNorm(head_dim, eps=1e-6)
113
+ self.norm_q_b = RMSNorm(head_dim, eps=1e-6)
114
+ self.norm_k_b = RMSNorm(head_dim, eps=1e-6)
115
+ else:
116
+ self.norm_q_a = None
117
+ self.norm_k_a = None
118
+ self.norm_q_b = None
119
+ self.norm_k_b = None
120
+
121
+
122
+ def process_qkv(self, hidden_states, to_qkv, norm_q, norm_k):
123
+ batch_size = hidden_states.shape[0]
124
+ qkv = to_qkv(hidden_states)
125
+ qkv = qkv.view(batch_size, -1, 3 * self.num_heads, self.head_dim).transpose(1, 2)
126
+ q, k, v = qkv.chunk(3, dim=1)
127
+ if norm_q is not None:
128
+ q = norm_q(q)
129
+ if norm_k is not None:
130
+ k = norm_k(k)
131
+ return q, k, v
132
+
133
+
134
+ def forward(self, hidden_states_a, hidden_states_b):
135
+ batch_size = hidden_states_a.shape[0]
136
+
137
+ qa, ka, va = self.process_qkv(hidden_states_a, self.a_to_qkv, self.norm_q_a, self.norm_k_a)
138
+ qb, kb, vb = self.process_qkv(hidden_states_b, self.b_to_qkv, self.norm_q_b, self.norm_k_b)
139
+ q = torch.concat([qa, qb], dim=2)
140
+ k = torch.concat([ka, kb], dim=2)
141
+ v = torch.concat([va, vb], dim=2)
142
+
143
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(q, k, v)
144
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
145
+ hidden_states = hidden_states.to(q.dtype)
146
+ hidden_states_a, hidden_states_b = hidden_states[:, :hidden_states_a.shape[1]], hidden_states[:, hidden_states_a.shape[1]:]
147
+ hidden_states_a = self.a_to_out(hidden_states_a)
148
+ if self.only_out_a:
149
+ return hidden_states_a
150
+ else:
151
+ hidden_states_b = self.b_to_out(hidden_states_b)
152
+ return hidden_states_a, hidden_states_b
153
+
154
+
155
+
156
+ class SingleAttention(torch.nn.Module):
157
+ def __init__(self, dim_a, num_heads, head_dim, use_rms_norm=False):
158
+ super().__init__()
159
+ self.num_heads = num_heads
160
+ self.head_dim = head_dim
161
+
162
+ self.a_to_qkv = torch.nn.Linear(dim_a, dim_a * 3)
163
+ self.a_to_out = torch.nn.Linear(dim_a, dim_a)
164
+
165
+ if use_rms_norm:
166
+ self.norm_q_a = RMSNorm(head_dim, eps=1e-6)
167
+ self.norm_k_a = RMSNorm(head_dim, eps=1e-6)
168
+ else:
169
+ self.norm_q_a = None
170
+ self.norm_k_a = None
171
+
172
+
173
+ def process_qkv(self, hidden_states, to_qkv, norm_q, norm_k):
174
+ batch_size = hidden_states.shape[0]
175
+ qkv = to_qkv(hidden_states)
176
+ qkv = qkv.view(batch_size, -1, 3 * self.num_heads, self.head_dim).transpose(1, 2)
177
+ q, k, v = qkv.chunk(3, dim=1)
178
+ if norm_q is not None:
179
+ q = norm_q(q)
180
+ if norm_k is not None:
181
+ k = norm_k(k)
182
+ return q, k, v
183
+
184
+
185
+ def forward(self, hidden_states_a):
186
+ batch_size = hidden_states_a.shape[0]
187
+ q, k, v = self.process_qkv(hidden_states_a, self.a_to_qkv, self.norm_q_a, self.norm_k_a)
188
+
189
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(q, k, v)
190
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.num_heads * self.head_dim)
191
+ hidden_states = hidden_states.to(q.dtype)
192
+ hidden_states = self.a_to_out(hidden_states)
193
+ return hidden_states
194
+
195
+
196
+
197
+ class DualTransformerBlock(torch.nn.Module):
198
+ def __init__(self, dim, num_attention_heads, use_rms_norm=False):
199
+ super().__init__()
200
+ self.norm1_a = AdaLayerNorm(dim, dual=True)
201
+ self.norm1_b = AdaLayerNorm(dim)
202
+
203
+ self.attn = JointAttention(dim, dim, num_attention_heads, dim // num_attention_heads, use_rms_norm=use_rms_norm)
204
+ self.attn2 = JointAttention(dim, dim, num_attention_heads, dim // num_attention_heads, use_rms_norm=use_rms_norm)
205
+
206
+ self.norm2_a = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
207
+ self.ff_a = torch.nn.Sequential(
208
+ torch.nn.Linear(dim, dim*4),
209
+ torch.nn.GELU(approximate="tanh"),
210
+ torch.nn.Linear(dim*4, dim)
211
+ )
212
+
213
+ self.norm2_b = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
214
+ self.ff_b = torch.nn.Sequential(
215
+ torch.nn.Linear(dim, dim*4),
216
+ torch.nn.GELU(approximate="tanh"),
217
+ torch.nn.Linear(dim*4, dim)
218
+ )
219
+
220
+
221
+ def forward(self, hidden_states_a, hidden_states_b, temb):
222
+ norm_hidden_states_a, gate_msa_a, shift_mlp_a, scale_mlp_a, gate_mlp_a, norm_hidden_states_a_2, gate_msa_a_2 = self.norm1_a(hidden_states_a, emb=temb)
223
+ norm_hidden_states_b, gate_msa_b, shift_mlp_b, scale_mlp_b, gate_mlp_b = self.norm1_b(hidden_states_b, emb=temb)
224
+
225
+ # Attention
226
+ attn_output_a, attn_output_b = self.attn(norm_hidden_states_a, norm_hidden_states_b)
227
+
228
+ # Part A
229
+ hidden_states_a = hidden_states_a + gate_msa_a * attn_output_a
230
+ hidden_states_a = hidden_states_a + gate_msa_a_2 * self.attn2(norm_hidden_states_a_2)
231
+ norm_hidden_states_a = self.norm2_a(hidden_states_a) * (1 + scale_mlp_a) + shift_mlp_a
232
+ hidden_states_a = hidden_states_a + gate_mlp_a * self.ff_a(norm_hidden_states_a)
233
+
234
+ # Part B
235
+ hidden_states_b = hidden_states_b + gate_msa_b * attn_output_b
236
+ norm_hidden_states_b = self.norm2_b(hidden_states_b) * (1 + scale_mlp_b) + shift_mlp_b
237
+ hidden_states_b = hidden_states_b + gate_mlp_b * self.ff_b(norm_hidden_states_b)
238
+
239
+ return hidden_states_a, hidden_states_b
240
+
241
+
242
+
243
+ class JointTransformerBlock(torch.nn.Module):
244
+ def __init__(self, dim, num_attention_heads, use_rms_norm=False, dual=False):
245
+ super().__init__()
246
+ self.norm1_a = AdaLayerNorm(dim, dual=dual)
247
+ self.norm1_b = AdaLayerNorm(dim)
248
+
249
+ self.attn = JointAttention(dim, dim, num_attention_heads, dim // num_attention_heads, use_rms_norm=use_rms_norm)
250
+ if dual:
251
+ self.attn2 = SingleAttention(dim, num_attention_heads, dim // num_attention_heads, use_rms_norm=use_rms_norm)
252
+
253
+ self.norm2_a = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
254
+ self.ff_a = torch.nn.Sequential(
255
+ torch.nn.Linear(dim, dim*4),
256
+ torch.nn.GELU(approximate="tanh"),
257
+ torch.nn.Linear(dim*4, dim)
258
+ )
259
+
260
+ self.norm2_b = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
261
+ self.ff_b = torch.nn.Sequential(
262
+ torch.nn.Linear(dim, dim*4),
263
+ torch.nn.GELU(approximate="tanh"),
264
+ torch.nn.Linear(dim*4, dim)
265
+ )
266
+
267
+
268
+ def forward(self, hidden_states_a, hidden_states_b, temb):
269
+ if self.norm1_a.dual:
270
+ norm_hidden_states_a, gate_msa_a, shift_mlp_a, scale_mlp_a, gate_mlp_a, norm_hidden_states_a_2, gate_msa_a_2 = self.norm1_a(hidden_states_a, emb=temb)
271
+ else:
272
+ norm_hidden_states_a, gate_msa_a, shift_mlp_a, scale_mlp_a, gate_mlp_a = self.norm1_a(hidden_states_a, emb=temb)
273
+ norm_hidden_states_b, gate_msa_b, shift_mlp_b, scale_mlp_b, gate_mlp_b = self.norm1_b(hidden_states_b, emb=temb)
274
+
275
+ # Attention
276
+ attn_output_a, attn_output_b = self.attn(norm_hidden_states_a, norm_hidden_states_b)
277
+
278
+ # Part A
279
+ hidden_states_a = hidden_states_a + gate_msa_a * attn_output_a
280
+ if self.norm1_a.dual:
281
+ hidden_states_a = hidden_states_a + gate_msa_a_2 * self.attn2(norm_hidden_states_a_2)
282
+ norm_hidden_states_a = self.norm2_a(hidden_states_a) * (1 + scale_mlp_a) + shift_mlp_a
283
+ hidden_states_a = hidden_states_a + gate_mlp_a * self.ff_a(norm_hidden_states_a)
284
+
285
+ # Part B
286
+ hidden_states_b = hidden_states_b + gate_msa_b * attn_output_b
287
+ norm_hidden_states_b = self.norm2_b(hidden_states_b) * (1 + scale_mlp_b) + shift_mlp_b
288
+ hidden_states_b = hidden_states_b + gate_mlp_b * self.ff_b(norm_hidden_states_b)
289
+
290
+ return hidden_states_a, hidden_states_b
291
+
292
+
293
+
294
+ class JointTransformerFinalBlock(torch.nn.Module):
295
+ def __init__(self, dim, num_attention_heads, use_rms_norm=False):
296
+ super().__init__()
297
+ self.norm1_a = AdaLayerNorm(dim)
298
+ self.norm1_b = AdaLayerNorm(dim, single=True)
299
+
300
+ self.attn = JointAttention(dim, dim, num_attention_heads, dim // num_attention_heads, only_out_a=True, use_rms_norm=use_rms_norm)
301
+
302
+ self.norm2_a = torch.nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
303
+ self.ff_a = torch.nn.Sequential(
304
+ torch.nn.Linear(dim, dim*4),
305
+ torch.nn.GELU(approximate="tanh"),
306
+ torch.nn.Linear(dim*4, dim)
307
+ )
308
+
309
+
310
+ def forward(self, hidden_states_a, hidden_states_b, temb):
311
+ norm_hidden_states_a, gate_msa_a, shift_mlp_a, scale_mlp_a, gate_mlp_a = self.norm1_a(hidden_states_a, emb=temb)
312
+ norm_hidden_states_b = self.norm1_b(hidden_states_b, emb=temb)
313
+
314
+ # Attention
315
+ attn_output_a = self.attn(norm_hidden_states_a, norm_hidden_states_b)
316
+
317
+ # Part A
318
+ hidden_states_a = hidden_states_a + gate_msa_a * attn_output_a
319
+ norm_hidden_states_a = self.norm2_a(hidden_states_a) * (1 + scale_mlp_a) + shift_mlp_a
320
+ hidden_states_a = hidden_states_a + gate_mlp_a * self.ff_a(norm_hidden_states_a)
321
+
322
+ return hidden_states_a, hidden_states_b
323
+
324
+
325
+
326
+ class SD3DiT(torch.nn.Module):
327
+ def __init__(self, embed_dim=1536, num_layers=24, use_rms_norm=False, num_dual_blocks=0, pos_embed_max_size=192):
328
+ super().__init__()
329
+ self.pos_embedder = PatchEmbed(patch_size=2, in_channels=16, embed_dim=embed_dim, pos_embed_max_size=pos_embed_max_size)
330
+ self.time_embedder = TimestepEmbeddings(256, embed_dim)
331
+ self.pooled_text_embedder = torch.nn.Sequential(torch.nn.Linear(2048, embed_dim), torch.nn.SiLU(), torch.nn.Linear(embed_dim, embed_dim))
332
+ self.context_embedder = torch.nn.Linear(4096, embed_dim)
333
+ self.blocks = torch.nn.ModuleList([JointTransformerBlock(embed_dim, embed_dim//64, use_rms_norm=use_rms_norm, dual=True) for _ in range(num_dual_blocks)]
334
+ + [JointTransformerBlock(embed_dim, embed_dim//64, use_rms_norm=use_rms_norm) for _ in range(num_layers-1-num_dual_blocks)]
335
+ + [JointTransformerFinalBlock(embed_dim, embed_dim//64, use_rms_norm=use_rms_norm)])
336
+ self.norm_out = AdaLayerNorm(embed_dim, single=True)
337
+ self.proj_out = torch.nn.Linear(embed_dim, 64)
338
+
339
+ def tiled_forward(self, hidden_states, timestep, prompt_emb, pooled_prompt_emb, tile_size=128, tile_stride=64):
340
+ # Due to the global positional embedding, we cannot implement layer-wise tiled forward.
341
+ hidden_states = TileWorker().tiled_forward(
342
+ lambda x: self.forward(x, timestep, prompt_emb, pooled_prompt_emb),
343
+ hidden_states,
344
+ tile_size,
345
+ tile_stride,
346
+ tile_device=hidden_states.device,
347
+ tile_dtype=hidden_states.dtype
348
+ )
349
+ return hidden_states
350
+
351
+ def forward(self, hidden_states, timestep, prompt_emb, pooled_prompt_emb, tiled=False, tile_size=128, tile_stride=64, use_gradient_checkpointing=False):
352
+ if tiled:
353
+ return self.tiled_forward(hidden_states, timestep, prompt_emb, pooled_prompt_emb, tile_size, tile_stride)
354
+ conditioning = self.time_embedder(timestep, hidden_states.dtype) + self.pooled_text_embedder(pooled_prompt_emb)
355
+ prompt_emb = self.context_embedder(prompt_emb)
356
+
357
+ height, width = hidden_states.shape[-2:]
358
+ hidden_states = self.pos_embedder(hidden_states)
359
+
360
+ def create_custom_forward(module):
361
+ def custom_forward(*inputs):
362
+ return module(*inputs)
363
+ return custom_forward
364
+
365
+ for block in self.blocks:
366
+ if self.training and use_gradient_checkpointing:
367
+ hidden_states, prompt_emb = torch.utils.checkpoint.checkpoint(
368
+ create_custom_forward(block),
369
+ hidden_states, prompt_emb, conditioning,
370
+ use_reentrant=False,
371
+ )
372
+ else:
373
+ hidden_states, prompt_emb = block(hidden_states, prompt_emb, conditioning)
374
+
375
+ hidden_states = self.norm_out(hidden_states, conditioning)
376
+ hidden_states = self.proj_out(hidden_states)
377
+ hidden_states = rearrange(hidden_states, "B (H W) (P Q C) -> B C (H P) (W Q)", P=2, Q=2, H=height//2, W=width//2)
378
+ return hidden_states
379
+
380
+ @staticmethod
381
+ def state_dict_converter():
382
+ return SD3DiTStateDictConverter()
383
+
384
+
385
+
386
+ class SD3DiTStateDictConverter:
387
+ def __init__(self):
388
+ pass
389
+
390
+ def infer_architecture(self, state_dict):
391
+ embed_dim = state_dict["blocks.0.ff_a.0.weight"].shape[1]
392
+ num_layers = 100
393
+ while num_layers > 0 and f"blocks.{num_layers-1}.ff_a.0.bias" not in state_dict:
394
+ num_layers -= 1
395
+ use_rms_norm = "blocks.0.attn.norm_q_a.weight" in state_dict
396
+ num_dual_blocks = 0
397
+ while f"blocks.{num_dual_blocks}.attn2.a_to_out.bias" in state_dict:
398
+ num_dual_blocks += 1
399
+ pos_embed_max_size = state_dict["pos_embedder.pos_embed"].shape[1]
400
+ return {
401
+ "embed_dim": embed_dim,
402
+ "num_layers": num_layers,
403
+ "use_rms_norm": use_rms_norm,
404
+ "num_dual_blocks": num_dual_blocks,
405
+ "pos_embed_max_size": pos_embed_max_size
406
+ }
407
+
408
+ def from_diffusers(self, state_dict):
409
+ rename_dict = {
410
+ "context_embedder": "context_embedder",
411
+ "pos_embed.pos_embed": "pos_embedder.pos_embed",
412
+ "pos_embed.proj": "pos_embedder.proj",
413
+ "time_text_embed.timestep_embedder.linear_1": "time_embedder.timestep_embedder.0",
414
+ "time_text_embed.timestep_embedder.linear_2": "time_embedder.timestep_embedder.2",
415
+ "time_text_embed.text_embedder.linear_1": "pooled_text_embedder.0",
416
+ "time_text_embed.text_embedder.linear_2": "pooled_text_embedder.2",
417
+ "norm_out.linear": "norm_out.linear",
418
+ "proj_out": "proj_out",
419
+
420
+ "norm1.linear": "norm1_a.linear",
421
+ "norm1_context.linear": "norm1_b.linear",
422
+ "attn.to_q": "attn.a_to_q",
423
+ "attn.to_k": "attn.a_to_k",
424
+ "attn.to_v": "attn.a_to_v",
425
+ "attn.to_out.0": "attn.a_to_out",
426
+ "attn.add_q_proj": "attn.b_to_q",
427
+ "attn.add_k_proj": "attn.b_to_k",
428
+ "attn.add_v_proj": "attn.b_to_v",
429
+ "attn.to_add_out": "attn.b_to_out",
430
+ "ff.net.0.proj": "ff_a.0",
431
+ "ff.net.2": "ff_a.2",
432
+ "ff_context.net.0.proj": "ff_b.0",
433
+ "ff_context.net.2": "ff_b.2",
434
+
435
+ "attn.norm_q": "attn.norm_q_a",
436
+ "attn.norm_k": "attn.norm_k_a",
437
+ "attn.norm_added_q": "attn.norm_q_b",
438
+ "attn.norm_added_k": "attn.norm_k_b",
439
+ }
440
+ state_dict_ = {}
441
+ for name, param in state_dict.items():
442
+ if name in rename_dict:
443
+ if name == "pos_embed.pos_embed":
444
+ param = param.reshape((1, 192, 192, param.shape[-1]))
445
+ state_dict_[rename_dict[name]] = param
446
+ elif name.endswith(".weight") or name.endswith(".bias"):
447
+ suffix = ".weight" if name.endswith(".weight") else ".bias"
448
+ prefix = name[:-len(suffix)]
449
+ if prefix in rename_dict:
450
+ state_dict_[rename_dict[prefix] + suffix] = param
451
+ elif prefix.startswith("transformer_blocks."):
452
+ names = prefix.split(".")
453
+ names[0] = "blocks"
454
+ middle = ".".join(names[2:])
455
+ if middle in rename_dict:
456
+ name_ = ".".join(names[:2] + [rename_dict[middle]] + [suffix[1:]])
457
+ state_dict_[name_] = param
458
+ merged_keys = [name for name in state_dict_ if ".a_to_q." in name or ".b_to_q." in name]
459
+ for key in merged_keys:
460
+ param = torch.concat([
461
+ state_dict_[key.replace("to_q", "to_q")],
462
+ state_dict_[key.replace("to_q", "to_k")],
463
+ state_dict_[key.replace("to_q", "to_v")],
464
+ ], dim=0)
465
+ name = key.replace("to_q", "to_qkv")
466
+ state_dict_.pop(key.replace("to_q", "to_q"))
467
+ state_dict_.pop(key.replace("to_q", "to_k"))
468
+ state_dict_.pop(key.replace("to_q", "to_v"))
469
+ state_dict_[name] = param
470
+ return state_dict_, self.infer_architecture(state_dict_)
471
+
472
+ def from_civitai(self, state_dict):
473
+ rename_dict = {
474
+ "model.diffusion_model.context_embedder.bias": "context_embedder.bias",
475
+ "model.diffusion_model.context_embedder.weight": "context_embedder.weight",
476
+ "model.diffusion_model.final_layer.linear.bias": "proj_out.bias",
477
+ "model.diffusion_model.final_layer.linear.weight": "proj_out.weight",
478
+
479
+ "model.diffusion_model.pos_embed": "pos_embedder.pos_embed",
480
+ "model.diffusion_model.t_embedder.mlp.0.bias": "time_embedder.timestep_embedder.0.bias",
481
+ "model.diffusion_model.t_embedder.mlp.0.weight": "time_embedder.timestep_embedder.0.weight",
482
+ "model.diffusion_model.t_embedder.mlp.2.bias": "time_embedder.timestep_embedder.2.bias",
483
+ "model.diffusion_model.t_embedder.mlp.2.weight": "time_embedder.timestep_embedder.2.weight",
484
+ "model.diffusion_model.x_embedder.proj.bias": "pos_embedder.proj.bias",
485
+ "model.diffusion_model.x_embedder.proj.weight": "pos_embedder.proj.weight",
486
+ "model.diffusion_model.y_embedder.mlp.0.bias": "pooled_text_embedder.0.bias",
487
+ "model.diffusion_model.y_embedder.mlp.0.weight": "pooled_text_embedder.0.weight",
488
+ "model.diffusion_model.y_embedder.mlp.2.bias": "pooled_text_embedder.2.bias",
489
+ "model.diffusion_model.y_embedder.mlp.2.weight": "pooled_text_embedder.2.weight",
490
+
491
+ "model.diffusion_model.joint_blocks.23.context_block.adaLN_modulation.1.weight": "blocks.23.norm1_b.linear.weight",
492
+ "model.diffusion_model.joint_blocks.23.context_block.adaLN_modulation.1.bias": "blocks.23.norm1_b.linear.bias",
493
+ "model.diffusion_model.final_layer.adaLN_modulation.1.weight": "norm_out.linear.weight",
494
+ "model.diffusion_model.final_layer.adaLN_modulation.1.bias": "norm_out.linear.bias",
495
+ }
496
+ for i in range(40):
497
+ rename_dict.update({
498
+ f"model.diffusion_model.joint_blocks.{i}.context_block.adaLN_modulation.1.bias": f"blocks.{i}.norm1_b.linear.bias",
499
+ f"model.diffusion_model.joint_blocks.{i}.context_block.adaLN_modulation.1.weight": f"blocks.{i}.norm1_b.linear.weight",
500
+ f"model.diffusion_model.joint_blocks.{i}.context_block.attn.proj.bias": f"blocks.{i}.attn.b_to_out.bias",
501
+ f"model.diffusion_model.joint_blocks.{i}.context_block.attn.proj.weight": f"blocks.{i}.attn.b_to_out.weight",
502
+ f"model.diffusion_model.joint_blocks.{i}.context_block.attn.qkv.bias": [f'blocks.{i}.attn.b_to_q.bias', f'blocks.{i}.attn.b_to_k.bias', f'blocks.{i}.attn.b_to_v.bias'],
503
+ f"model.diffusion_model.joint_blocks.{i}.context_block.attn.qkv.weight": [f'blocks.{i}.attn.b_to_q.weight', f'blocks.{i}.attn.b_to_k.weight', f'blocks.{i}.attn.b_to_v.weight'],
504
+ f"model.diffusion_model.joint_blocks.{i}.context_block.mlp.fc1.bias": f"blocks.{i}.ff_b.0.bias",
505
+ f"model.diffusion_model.joint_blocks.{i}.context_block.mlp.fc1.weight": f"blocks.{i}.ff_b.0.weight",
506
+ f"model.diffusion_model.joint_blocks.{i}.context_block.mlp.fc2.bias": f"blocks.{i}.ff_b.2.bias",
507
+ f"model.diffusion_model.joint_blocks.{i}.context_block.mlp.fc2.weight": f"blocks.{i}.ff_b.2.weight",
508
+ f"model.diffusion_model.joint_blocks.{i}.x_block.adaLN_modulation.1.bias": f"blocks.{i}.norm1_a.linear.bias",
509
+ f"model.diffusion_model.joint_blocks.{i}.x_block.adaLN_modulation.1.weight": f"blocks.{i}.norm1_a.linear.weight",
510
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn.proj.bias": f"blocks.{i}.attn.a_to_out.bias",
511
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn.proj.weight": f"blocks.{i}.attn.a_to_out.weight",
512
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn.qkv.bias": [f'blocks.{i}.attn.a_to_q.bias', f'blocks.{i}.attn.a_to_k.bias', f'blocks.{i}.attn.a_to_v.bias'],
513
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn.qkv.weight": [f'blocks.{i}.attn.a_to_q.weight', f'blocks.{i}.attn.a_to_k.weight', f'blocks.{i}.attn.a_to_v.weight'],
514
+ f"model.diffusion_model.joint_blocks.{i}.x_block.mlp.fc1.bias": f"blocks.{i}.ff_a.0.bias",
515
+ f"model.diffusion_model.joint_blocks.{i}.x_block.mlp.fc1.weight": f"blocks.{i}.ff_a.0.weight",
516
+ f"model.diffusion_model.joint_blocks.{i}.x_block.mlp.fc2.bias": f"blocks.{i}.ff_a.2.bias",
517
+ f"model.diffusion_model.joint_blocks.{i}.x_block.mlp.fc2.weight": f"blocks.{i}.ff_a.2.weight",
518
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn.ln_q.weight": f"blocks.{i}.attn.norm_q_a.weight",
519
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn.ln_k.weight": f"blocks.{i}.attn.norm_k_a.weight",
520
+ f"model.diffusion_model.joint_blocks.{i}.context_block.attn.ln_q.weight": f"blocks.{i}.attn.norm_q_b.weight",
521
+ f"model.diffusion_model.joint_blocks.{i}.context_block.attn.ln_k.weight": f"blocks.{i}.attn.norm_k_b.weight",
522
+
523
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn2.ln_q.weight": f"blocks.{i}.attn2.norm_q_a.weight",
524
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn2.ln_k.weight": f"blocks.{i}.attn2.norm_k_a.weight",
525
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn2.qkv.weight": f"blocks.{i}.attn2.a_to_qkv.weight",
526
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn2.qkv.bias": f"blocks.{i}.attn2.a_to_qkv.bias",
527
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn2.proj.weight": f"blocks.{i}.attn2.a_to_out.weight",
528
+ f"model.diffusion_model.joint_blocks.{i}.x_block.attn2.proj.bias": f"blocks.{i}.attn2.a_to_out.bias",
529
+ })
530
+ state_dict_ = {}
531
+ for name in state_dict:
532
+ if name in rename_dict:
533
+ param = state_dict[name]
534
+ if name == "model.diffusion_model.pos_embed":
535
+ pos_embed_max_size = int(param.shape[1] ** 0.5 + 0.4)
536
+ param = param.reshape((1, pos_embed_max_size, pos_embed_max_size, param.shape[-1]))
537
+ if isinstance(rename_dict[name], str):
538
+ state_dict_[rename_dict[name]] = param
539
+ else:
540
+ name_ = rename_dict[name][0].replace(".a_to_q.", ".a_to_qkv.").replace(".b_to_q.", ".b_to_qkv.")
541
+ state_dict_[name_] = param
542
+ extra_kwargs = self.infer_architecture(state_dict_)
543
+ num_layers = extra_kwargs["num_layers"]
544
+ for name in [
545
+ f"blocks.{num_layers-1}.norm1_b.linear.weight", f"blocks.{num_layers-1}.norm1_b.linear.bias", "norm_out.linear.weight", "norm_out.linear.bias",
546
+ ]:
547
+ param = state_dict_[name]
548
+ dim = param.shape[0] // 2
549
+ param = torch.concat([param[dim:], param[:dim]], axis=0)
550
+ state_dict_[name] = param
551
+ return state_dict_, self.infer_architecture(state_dict_)
sd3_text_encoder.py ADDED
The diff for this file is too large to render. See raw diff
 
sd3_vae_decoder.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_vae_decoder import VAEAttentionBlock, SDVAEDecoderStateDictConverter
3
+ from .sd_unet import ResnetBlock, UpSampler
4
+ from .tiler import TileWorker
5
+
6
+
7
+
8
+ class SD3VAEDecoder(torch.nn.Module):
9
+ def __init__(self):
10
+ super().__init__()
11
+ self.scaling_factor = 1.5305 # Different from SD 1.x
12
+ self.shift_factor = 0.0609 # Different from SD 1.x
13
+ self.conv_in = torch.nn.Conv2d(16, 512, kernel_size=3, padding=1) # Different from SD 1.x
14
+
15
+ self.blocks = torch.nn.ModuleList([
16
+ # UNetMidBlock2D
17
+ ResnetBlock(512, 512, eps=1e-6),
18
+ VAEAttentionBlock(1, 512, 512, 1, eps=1e-6),
19
+ ResnetBlock(512, 512, eps=1e-6),
20
+ # UpDecoderBlock2D
21
+ ResnetBlock(512, 512, eps=1e-6),
22
+ ResnetBlock(512, 512, eps=1e-6),
23
+ ResnetBlock(512, 512, eps=1e-6),
24
+ UpSampler(512),
25
+ # UpDecoderBlock2D
26
+ ResnetBlock(512, 512, eps=1e-6),
27
+ ResnetBlock(512, 512, eps=1e-6),
28
+ ResnetBlock(512, 512, eps=1e-6),
29
+ UpSampler(512),
30
+ # UpDecoderBlock2D
31
+ ResnetBlock(512, 256, eps=1e-6),
32
+ ResnetBlock(256, 256, eps=1e-6),
33
+ ResnetBlock(256, 256, eps=1e-6),
34
+ UpSampler(256),
35
+ # UpDecoderBlock2D
36
+ ResnetBlock(256, 128, eps=1e-6),
37
+ ResnetBlock(128, 128, eps=1e-6),
38
+ ResnetBlock(128, 128, eps=1e-6),
39
+ ])
40
+
41
+ self.conv_norm_out = torch.nn.GroupNorm(num_channels=128, num_groups=32, eps=1e-6)
42
+ self.conv_act = torch.nn.SiLU()
43
+ self.conv_out = torch.nn.Conv2d(128, 3, kernel_size=3, padding=1)
44
+
45
+ def tiled_forward(self, sample, tile_size=64, tile_stride=32):
46
+ hidden_states = TileWorker().tiled_forward(
47
+ lambda x: self.forward(x),
48
+ sample,
49
+ tile_size,
50
+ tile_stride,
51
+ tile_device=sample.device,
52
+ tile_dtype=sample.dtype
53
+ )
54
+ return hidden_states
55
+
56
+ def forward(self, sample, tiled=False, tile_size=64, tile_stride=32, **kwargs):
57
+ # For VAE Decoder, we do not need to apply the tiler on each layer.
58
+ if tiled:
59
+ return self.tiled_forward(sample, tile_size=tile_size, tile_stride=tile_stride)
60
+
61
+ # 1. pre-process
62
+ hidden_states = sample / self.scaling_factor + self.shift_factor
63
+ hidden_states = self.conv_in(hidden_states)
64
+ time_emb = None
65
+ text_emb = None
66
+ res_stack = None
67
+
68
+ # 2. blocks
69
+ for i, block in enumerate(self.blocks):
70
+ hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
71
+
72
+ # 3. output
73
+ hidden_states = self.conv_norm_out(hidden_states)
74
+ hidden_states = self.conv_act(hidden_states)
75
+ hidden_states = self.conv_out(hidden_states)
76
+
77
+ return hidden_states
78
+
79
+ @staticmethod
80
+ def state_dict_converter():
81
+ return SDVAEDecoderStateDictConverter()
sd3_vae_encoder.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_unet import ResnetBlock, DownSampler
3
+ from .sd_vae_encoder import VAEAttentionBlock, SDVAEEncoderStateDictConverter
4
+ from .tiler import TileWorker
5
+ from einops import rearrange
6
+
7
+
8
+ class SD3VAEEncoder(torch.nn.Module):
9
+ def __init__(self):
10
+ super().__init__()
11
+ self.scaling_factor = 1.5305 # Different from SD 1.x
12
+ self.shift_factor = 0.0609 # Different from SD 1.x
13
+ self.conv_in = torch.nn.Conv2d(3, 128, kernel_size=3, padding=1)
14
+
15
+ self.blocks = torch.nn.ModuleList([
16
+ # DownEncoderBlock2D
17
+ ResnetBlock(128, 128, eps=1e-6),
18
+ ResnetBlock(128, 128, eps=1e-6),
19
+ DownSampler(128, padding=0, extra_padding=True),
20
+ # DownEncoderBlock2D
21
+ ResnetBlock(128, 256, eps=1e-6),
22
+ ResnetBlock(256, 256, eps=1e-6),
23
+ DownSampler(256, padding=0, extra_padding=True),
24
+ # DownEncoderBlock2D
25
+ ResnetBlock(256, 512, eps=1e-6),
26
+ ResnetBlock(512, 512, eps=1e-6),
27
+ DownSampler(512, padding=0, extra_padding=True),
28
+ # DownEncoderBlock2D
29
+ ResnetBlock(512, 512, eps=1e-6),
30
+ ResnetBlock(512, 512, eps=1e-6),
31
+ # UNetMidBlock2D
32
+ ResnetBlock(512, 512, eps=1e-6),
33
+ VAEAttentionBlock(1, 512, 512, 1, eps=1e-6),
34
+ ResnetBlock(512, 512, eps=1e-6),
35
+ ])
36
+
37
+ self.conv_norm_out = torch.nn.GroupNorm(num_channels=512, num_groups=32, eps=1e-6)
38
+ self.conv_act = torch.nn.SiLU()
39
+ self.conv_out = torch.nn.Conv2d(512, 32, kernel_size=3, padding=1)
40
+
41
+ def tiled_forward(self, sample, tile_size=64, tile_stride=32):
42
+ hidden_states = TileWorker().tiled_forward(
43
+ lambda x: self.forward(x),
44
+ sample,
45
+ tile_size,
46
+ tile_stride,
47
+ tile_device=sample.device,
48
+ tile_dtype=sample.dtype
49
+ )
50
+ return hidden_states
51
+
52
+ def forward(self, sample, tiled=False, tile_size=64, tile_stride=32, **kwargs):
53
+ # For VAE Decoder, we do not need to apply the tiler on each layer.
54
+ if tiled:
55
+ return self.tiled_forward(sample, tile_size=tile_size, tile_stride=tile_stride)
56
+
57
+ # 1. pre-process
58
+ hidden_states = self.conv_in(sample)
59
+ time_emb = None
60
+ text_emb = None
61
+ res_stack = None
62
+
63
+ # 2. blocks
64
+ for i, block in enumerate(self.blocks):
65
+ hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
66
+
67
+ # 3. output
68
+ hidden_states = self.conv_norm_out(hidden_states)
69
+ hidden_states = self.conv_act(hidden_states)
70
+ hidden_states = self.conv_out(hidden_states)
71
+ hidden_states = hidden_states[:, :16]
72
+ hidden_states = (hidden_states - self.shift_factor) * self.scaling_factor
73
+
74
+ return hidden_states
75
+
76
+ def encode_video(self, sample, batch_size=8):
77
+ B = sample.shape[0]
78
+ hidden_states = []
79
+
80
+ for i in range(0, sample.shape[2], batch_size):
81
+
82
+ j = min(i + batch_size, sample.shape[2])
83
+ sample_batch = rearrange(sample[:,:,i:j], "B C T H W -> (B T) C H W")
84
+
85
+ hidden_states_batch = self(sample_batch)
86
+ hidden_states_batch = rearrange(hidden_states_batch, "(B T) C H W -> B C T H W", B=B)
87
+
88
+ hidden_states.append(hidden_states_batch)
89
+
90
+ hidden_states = torch.concat(hidden_states, dim=2)
91
+ return hidden_states
92
+
93
+ @staticmethod
94
+ def state_dict_converter():
95
+ return SDVAEEncoderStateDictConverter()
sd_controlnet.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_unet import Timesteps, ResnetBlock, AttentionBlock, PushBlock, DownSampler
3
+ from .tiler import TileWorker
4
+
5
+
6
+ class ControlNetConditioningLayer(torch.nn.Module):
7
+ def __init__(self, channels = (3, 16, 32, 96, 256, 320)):
8
+ super().__init__()
9
+ self.blocks = torch.nn.ModuleList([])
10
+ self.blocks.append(torch.nn.Conv2d(channels[0], channels[1], kernel_size=3, padding=1))
11
+ self.blocks.append(torch.nn.SiLU())
12
+ for i in range(1, len(channels) - 2):
13
+ self.blocks.append(torch.nn.Conv2d(channels[i], channels[i], kernel_size=3, padding=1))
14
+ self.blocks.append(torch.nn.SiLU())
15
+ self.blocks.append(torch.nn.Conv2d(channels[i], channels[i+1], kernel_size=3, padding=1, stride=2))
16
+ self.blocks.append(torch.nn.SiLU())
17
+ self.blocks.append(torch.nn.Conv2d(channels[-2], channels[-1], kernel_size=3, padding=1))
18
+
19
+ def forward(self, conditioning):
20
+ for block in self.blocks:
21
+ conditioning = block(conditioning)
22
+ return conditioning
23
+
24
+
25
+ class SDControlNet(torch.nn.Module):
26
+ def __init__(self, global_pool=False):
27
+ super().__init__()
28
+ self.time_proj = Timesteps(320)
29
+ self.time_embedding = torch.nn.Sequential(
30
+ torch.nn.Linear(320, 1280),
31
+ torch.nn.SiLU(),
32
+ torch.nn.Linear(1280, 1280)
33
+ )
34
+ self.conv_in = torch.nn.Conv2d(4, 320, kernel_size=3, padding=1)
35
+
36
+ self.controlnet_conv_in = ControlNetConditioningLayer(channels=(3, 16, 32, 96, 256, 320))
37
+
38
+ self.blocks = torch.nn.ModuleList([
39
+ # CrossAttnDownBlock2D
40
+ ResnetBlock(320, 320, 1280),
41
+ AttentionBlock(8, 40, 320, 1, 768),
42
+ PushBlock(),
43
+ ResnetBlock(320, 320, 1280),
44
+ AttentionBlock(8, 40, 320, 1, 768),
45
+ PushBlock(),
46
+ DownSampler(320),
47
+ PushBlock(),
48
+ # CrossAttnDownBlock2D
49
+ ResnetBlock(320, 640, 1280),
50
+ AttentionBlock(8, 80, 640, 1, 768),
51
+ PushBlock(),
52
+ ResnetBlock(640, 640, 1280),
53
+ AttentionBlock(8, 80, 640, 1, 768),
54
+ PushBlock(),
55
+ DownSampler(640),
56
+ PushBlock(),
57
+ # CrossAttnDownBlock2D
58
+ ResnetBlock(640, 1280, 1280),
59
+ AttentionBlock(8, 160, 1280, 1, 768),
60
+ PushBlock(),
61
+ ResnetBlock(1280, 1280, 1280),
62
+ AttentionBlock(8, 160, 1280, 1, 768),
63
+ PushBlock(),
64
+ DownSampler(1280),
65
+ PushBlock(),
66
+ # DownBlock2D
67
+ ResnetBlock(1280, 1280, 1280),
68
+ PushBlock(),
69
+ ResnetBlock(1280, 1280, 1280),
70
+ PushBlock(),
71
+ # UNetMidBlock2DCrossAttn
72
+ ResnetBlock(1280, 1280, 1280),
73
+ AttentionBlock(8, 160, 1280, 1, 768),
74
+ ResnetBlock(1280, 1280, 1280),
75
+ PushBlock()
76
+ ])
77
+
78
+ self.controlnet_blocks = torch.nn.ModuleList([
79
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1)),
80
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1), bias=False),
81
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1), bias=False),
82
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1), bias=False),
83
+ torch.nn.Conv2d(640, 640, kernel_size=(1, 1)),
84
+ torch.nn.Conv2d(640, 640, kernel_size=(1, 1), bias=False),
85
+ torch.nn.Conv2d(640, 640, kernel_size=(1, 1), bias=False),
86
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1)),
87
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1), bias=False),
88
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1), bias=False),
89
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1), bias=False),
90
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1), bias=False),
91
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1), bias=False),
92
+ ])
93
+
94
+ self.global_pool = global_pool
95
+
96
+ def forward(
97
+ self,
98
+ sample, timestep, encoder_hidden_states, conditioning,
99
+ tiled=False, tile_size=64, tile_stride=32,
100
+ **kwargs
101
+ ):
102
+ # 1. time
103
+ time_emb = self.time_proj(timestep).to(sample.dtype)
104
+ time_emb = self.time_embedding(time_emb)
105
+ time_emb = time_emb.repeat(sample.shape[0], 1)
106
+
107
+ # 2. pre-process
108
+ height, width = sample.shape[2], sample.shape[3]
109
+ hidden_states = self.conv_in(sample) + self.controlnet_conv_in(conditioning)
110
+ text_emb = encoder_hidden_states
111
+ res_stack = [hidden_states]
112
+
113
+ # 3. blocks
114
+ for i, block in enumerate(self.blocks):
115
+ if tiled and not isinstance(block, PushBlock):
116
+ _, _, inter_height, _ = hidden_states.shape
117
+ resize_scale = inter_height / height
118
+ hidden_states = TileWorker().tiled_forward(
119
+ lambda x: block(x, time_emb, text_emb, res_stack)[0],
120
+ hidden_states,
121
+ int(tile_size * resize_scale),
122
+ int(tile_stride * resize_scale),
123
+ tile_device=hidden_states.device,
124
+ tile_dtype=hidden_states.dtype
125
+ )
126
+ else:
127
+ hidden_states, _, _, _ = block(hidden_states, time_emb, text_emb, res_stack)
128
+
129
+ # 4. ControlNet blocks
130
+ controlnet_res_stack = [block(res) for block, res in zip(self.controlnet_blocks, res_stack)]
131
+
132
+ # pool
133
+ if self.global_pool:
134
+ controlnet_res_stack = [res.mean(dim=(2, 3), keepdim=True) for res in controlnet_res_stack]
135
+
136
+ return controlnet_res_stack
137
+
138
+ @staticmethod
139
+ def state_dict_converter():
140
+ return SDControlNetStateDictConverter()
141
+
142
+
143
+ class SDControlNetStateDictConverter:
144
+ def __init__(self):
145
+ pass
146
+
147
+ def from_diffusers(self, state_dict):
148
+ # architecture
149
+ block_types = [
150
+ 'ResnetBlock', 'AttentionBlock', 'PushBlock', 'ResnetBlock', 'AttentionBlock', 'PushBlock', 'DownSampler', 'PushBlock',
151
+ 'ResnetBlock', 'AttentionBlock', 'PushBlock', 'ResnetBlock', 'AttentionBlock', 'PushBlock', 'DownSampler', 'PushBlock',
152
+ 'ResnetBlock', 'AttentionBlock', 'PushBlock', 'ResnetBlock', 'AttentionBlock', 'PushBlock', 'DownSampler', 'PushBlock',
153
+ 'ResnetBlock', 'PushBlock', 'ResnetBlock', 'PushBlock',
154
+ 'ResnetBlock', 'AttentionBlock', 'ResnetBlock',
155
+ 'PopBlock', 'ResnetBlock', 'PopBlock', 'ResnetBlock', 'PopBlock', 'ResnetBlock', 'UpSampler',
156
+ 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'UpSampler',
157
+ 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'UpSampler',
158
+ 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'PopBlock', 'ResnetBlock', 'AttentionBlock', 'PopBlock', 'ResnetBlock', 'AttentionBlock'
159
+ ]
160
+
161
+ # controlnet_rename_dict
162
+ controlnet_rename_dict = {
163
+ "controlnet_cond_embedding.conv_in.weight": "controlnet_conv_in.blocks.0.weight",
164
+ "controlnet_cond_embedding.conv_in.bias": "controlnet_conv_in.blocks.0.bias",
165
+ "controlnet_cond_embedding.blocks.0.weight": "controlnet_conv_in.blocks.2.weight",
166
+ "controlnet_cond_embedding.blocks.0.bias": "controlnet_conv_in.blocks.2.bias",
167
+ "controlnet_cond_embedding.blocks.1.weight": "controlnet_conv_in.blocks.4.weight",
168
+ "controlnet_cond_embedding.blocks.1.bias": "controlnet_conv_in.blocks.4.bias",
169
+ "controlnet_cond_embedding.blocks.2.weight": "controlnet_conv_in.blocks.6.weight",
170
+ "controlnet_cond_embedding.blocks.2.bias": "controlnet_conv_in.blocks.6.bias",
171
+ "controlnet_cond_embedding.blocks.3.weight": "controlnet_conv_in.blocks.8.weight",
172
+ "controlnet_cond_embedding.blocks.3.bias": "controlnet_conv_in.blocks.8.bias",
173
+ "controlnet_cond_embedding.blocks.4.weight": "controlnet_conv_in.blocks.10.weight",
174
+ "controlnet_cond_embedding.blocks.4.bias": "controlnet_conv_in.blocks.10.bias",
175
+ "controlnet_cond_embedding.blocks.5.weight": "controlnet_conv_in.blocks.12.weight",
176
+ "controlnet_cond_embedding.blocks.5.bias": "controlnet_conv_in.blocks.12.bias",
177
+ "controlnet_cond_embedding.conv_out.weight": "controlnet_conv_in.blocks.14.weight",
178
+ "controlnet_cond_embedding.conv_out.bias": "controlnet_conv_in.blocks.14.bias",
179
+ }
180
+
181
+ # Rename each parameter
182
+ name_list = sorted([name for name in state_dict])
183
+ rename_dict = {}
184
+ block_id = {"ResnetBlock": -1, "AttentionBlock": -1, "DownSampler": -1, "UpSampler": -1}
185
+ last_block_type_with_id = {"ResnetBlock": "", "AttentionBlock": "", "DownSampler": "", "UpSampler": ""}
186
+ for name in name_list:
187
+ names = name.split(".")
188
+ if names[0] in ["conv_in", "conv_norm_out", "conv_out"]:
189
+ pass
190
+ elif name in controlnet_rename_dict:
191
+ names = controlnet_rename_dict[name].split(".")
192
+ elif names[0] == "controlnet_down_blocks":
193
+ names[0] = "controlnet_blocks"
194
+ elif names[0] == "controlnet_mid_block":
195
+ names = ["controlnet_blocks", "12", names[-1]]
196
+ elif names[0] in ["time_embedding", "add_embedding"]:
197
+ if names[0] == "add_embedding":
198
+ names[0] = "add_time_embedding"
199
+ names[1] = {"linear_1": "0", "linear_2": "2"}[names[1]]
200
+ elif names[0] in ["down_blocks", "mid_block", "up_blocks"]:
201
+ if names[0] == "mid_block":
202
+ names.insert(1, "0")
203
+ block_type = {"resnets": "ResnetBlock", "attentions": "AttentionBlock", "downsamplers": "DownSampler", "upsamplers": "UpSampler"}[names[2]]
204
+ block_type_with_id = ".".join(names[:4])
205
+ if block_type_with_id != last_block_type_with_id[block_type]:
206
+ block_id[block_type] += 1
207
+ last_block_type_with_id[block_type] = block_type_with_id
208
+ while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:
209
+ block_id[block_type] += 1
210
+ block_type_with_id = ".".join(names[:4])
211
+ names = ["blocks", str(block_id[block_type])] + names[4:]
212
+ if "ff" in names:
213
+ ff_index = names.index("ff")
214
+ component = ".".join(names[ff_index:ff_index+3])
215
+ component = {"ff.net.0": "act_fn", "ff.net.2": "ff"}[component]
216
+ names = names[:ff_index] + [component] + names[ff_index+3:]
217
+ if "to_out" in names:
218
+ names.pop(names.index("to_out") + 1)
219
+ else:
220
+ raise ValueError(f"Unknown parameters: {name}")
221
+ rename_dict[name] = ".".join(names)
222
+
223
+ # Convert state_dict
224
+ state_dict_ = {}
225
+ for name, param in state_dict.items():
226
+ if ".proj_in." in name or ".proj_out." in name:
227
+ param = param.squeeze()
228
+ if rename_dict[name] in [
229
+ "controlnet_blocks.1.bias", "controlnet_blocks.2.bias", "controlnet_blocks.3.bias", "controlnet_blocks.5.bias", "controlnet_blocks.6.bias",
230
+ "controlnet_blocks.8.bias", "controlnet_blocks.9.bias", "controlnet_blocks.10.bias", "controlnet_blocks.11.bias", "controlnet_blocks.12.bias"
231
+ ]:
232
+ continue
233
+ state_dict_[rename_dict[name]] = param
234
+ return state_dict_
235
+
236
+ def from_civitai(self, state_dict):
237
+ if "mid_block.resnets.1.time_emb_proj.weight" in state_dict:
238
+ # For controlnets in diffusers format
239
+ return self.from_diffusers(state_dict)
240
+ rename_dict = {
241
+ "control_model.time_embed.0.weight": "time_embedding.0.weight",
242
+ "control_model.time_embed.0.bias": "time_embedding.0.bias",
243
+ "control_model.time_embed.2.weight": "time_embedding.2.weight",
244
+ "control_model.time_embed.2.bias": "time_embedding.2.bias",
245
+ "control_model.input_blocks.0.0.weight": "conv_in.weight",
246
+ "control_model.input_blocks.0.0.bias": "conv_in.bias",
247
+ "control_model.input_blocks.1.0.in_layers.0.weight": "blocks.0.norm1.weight",
248
+ "control_model.input_blocks.1.0.in_layers.0.bias": "blocks.0.norm1.bias",
249
+ "control_model.input_blocks.1.0.in_layers.2.weight": "blocks.0.conv1.weight",
250
+ "control_model.input_blocks.1.0.in_layers.2.bias": "blocks.0.conv1.bias",
251
+ "control_model.input_blocks.1.0.emb_layers.1.weight": "blocks.0.time_emb_proj.weight",
252
+ "control_model.input_blocks.1.0.emb_layers.1.bias": "blocks.0.time_emb_proj.bias",
253
+ "control_model.input_blocks.1.0.out_layers.0.weight": "blocks.0.norm2.weight",
254
+ "control_model.input_blocks.1.0.out_layers.0.bias": "blocks.0.norm2.bias",
255
+ "control_model.input_blocks.1.0.out_layers.3.weight": "blocks.0.conv2.weight",
256
+ "control_model.input_blocks.1.0.out_layers.3.bias": "blocks.0.conv2.bias",
257
+ "control_model.input_blocks.1.1.norm.weight": "blocks.1.norm.weight",
258
+ "control_model.input_blocks.1.1.norm.bias": "blocks.1.norm.bias",
259
+ "control_model.input_blocks.1.1.proj_in.weight": "blocks.1.proj_in.weight",
260
+ "control_model.input_blocks.1.1.proj_in.bias": "blocks.1.proj_in.bias",
261
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn1.to_q.weight": "blocks.1.transformer_blocks.0.attn1.to_q.weight",
262
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn1.to_k.weight": "blocks.1.transformer_blocks.0.attn1.to_k.weight",
263
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn1.to_v.weight": "blocks.1.transformer_blocks.0.attn1.to_v.weight",
264
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.1.transformer_blocks.0.attn1.to_out.weight",
265
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.1.transformer_blocks.0.attn1.to_out.bias",
266
+ "control_model.input_blocks.1.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.1.transformer_blocks.0.act_fn.proj.weight",
267
+ "control_model.input_blocks.1.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.1.transformer_blocks.0.act_fn.proj.bias",
268
+ "control_model.input_blocks.1.1.transformer_blocks.0.ff.net.2.weight": "blocks.1.transformer_blocks.0.ff.weight",
269
+ "control_model.input_blocks.1.1.transformer_blocks.0.ff.net.2.bias": "blocks.1.transformer_blocks.0.ff.bias",
270
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn2.to_q.weight": "blocks.1.transformer_blocks.0.attn2.to_q.weight",
271
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn2.to_k.weight": "blocks.1.transformer_blocks.0.attn2.to_k.weight",
272
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn2.to_v.weight": "blocks.1.transformer_blocks.0.attn2.to_v.weight",
273
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.1.transformer_blocks.0.attn2.to_out.weight",
274
+ "control_model.input_blocks.1.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.1.transformer_blocks.0.attn2.to_out.bias",
275
+ "control_model.input_blocks.1.1.transformer_blocks.0.norm1.weight": "blocks.1.transformer_blocks.0.norm1.weight",
276
+ "control_model.input_blocks.1.1.transformer_blocks.0.norm1.bias": "blocks.1.transformer_blocks.0.norm1.bias",
277
+ "control_model.input_blocks.1.1.transformer_blocks.0.norm2.weight": "blocks.1.transformer_blocks.0.norm2.weight",
278
+ "control_model.input_blocks.1.1.transformer_blocks.0.norm2.bias": "blocks.1.transformer_blocks.0.norm2.bias",
279
+ "control_model.input_blocks.1.1.transformer_blocks.0.norm3.weight": "blocks.1.transformer_blocks.0.norm3.weight",
280
+ "control_model.input_blocks.1.1.transformer_blocks.0.norm3.bias": "blocks.1.transformer_blocks.0.norm3.bias",
281
+ "control_model.input_blocks.1.1.proj_out.weight": "blocks.1.proj_out.weight",
282
+ "control_model.input_blocks.1.1.proj_out.bias": "blocks.1.proj_out.bias",
283
+ "control_model.input_blocks.2.0.in_layers.0.weight": "blocks.3.norm1.weight",
284
+ "control_model.input_blocks.2.0.in_layers.0.bias": "blocks.3.norm1.bias",
285
+ "control_model.input_blocks.2.0.in_layers.2.weight": "blocks.3.conv1.weight",
286
+ "control_model.input_blocks.2.0.in_layers.2.bias": "blocks.3.conv1.bias",
287
+ "control_model.input_blocks.2.0.emb_layers.1.weight": "blocks.3.time_emb_proj.weight",
288
+ "control_model.input_blocks.2.0.emb_layers.1.bias": "blocks.3.time_emb_proj.bias",
289
+ "control_model.input_blocks.2.0.out_layers.0.weight": "blocks.3.norm2.weight",
290
+ "control_model.input_blocks.2.0.out_layers.0.bias": "blocks.3.norm2.bias",
291
+ "control_model.input_blocks.2.0.out_layers.3.weight": "blocks.3.conv2.weight",
292
+ "control_model.input_blocks.2.0.out_layers.3.bias": "blocks.3.conv2.bias",
293
+ "control_model.input_blocks.2.1.norm.weight": "blocks.4.norm.weight",
294
+ "control_model.input_blocks.2.1.norm.bias": "blocks.4.norm.bias",
295
+ "control_model.input_blocks.2.1.proj_in.weight": "blocks.4.proj_in.weight",
296
+ "control_model.input_blocks.2.1.proj_in.bias": "blocks.4.proj_in.bias",
297
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn1.to_q.weight": "blocks.4.transformer_blocks.0.attn1.to_q.weight",
298
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn1.to_k.weight": "blocks.4.transformer_blocks.0.attn1.to_k.weight",
299
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn1.to_v.weight": "blocks.4.transformer_blocks.0.attn1.to_v.weight",
300
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.4.transformer_blocks.0.attn1.to_out.weight",
301
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.4.transformer_blocks.0.attn1.to_out.bias",
302
+ "control_model.input_blocks.2.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.4.transformer_blocks.0.act_fn.proj.weight",
303
+ "control_model.input_blocks.2.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.4.transformer_blocks.0.act_fn.proj.bias",
304
+ "control_model.input_blocks.2.1.transformer_blocks.0.ff.net.2.weight": "blocks.4.transformer_blocks.0.ff.weight",
305
+ "control_model.input_blocks.2.1.transformer_blocks.0.ff.net.2.bias": "blocks.4.transformer_blocks.0.ff.bias",
306
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_q.weight": "blocks.4.transformer_blocks.0.attn2.to_q.weight",
307
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight": "blocks.4.transformer_blocks.0.attn2.to_k.weight",
308
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_v.weight": "blocks.4.transformer_blocks.0.attn2.to_v.weight",
309
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.4.transformer_blocks.0.attn2.to_out.weight",
310
+ "control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.4.transformer_blocks.0.attn2.to_out.bias",
311
+ "control_model.input_blocks.2.1.transformer_blocks.0.norm1.weight": "blocks.4.transformer_blocks.0.norm1.weight",
312
+ "control_model.input_blocks.2.1.transformer_blocks.0.norm1.bias": "blocks.4.transformer_blocks.0.norm1.bias",
313
+ "control_model.input_blocks.2.1.transformer_blocks.0.norm2.weight": "blocks.4.transformer_blocks.0.norm2.weight",
314
+ "control_model.input_blocks.2.1.transformer_blocks.0.norm2.bias": "blocks.4.transformer_blocks.0.norm2.bias",
315
+ "control_model.input_blocks.2.1.transformer_blocks.0.norm3.weight": "blocks.4.transformer_blocks.0.norm3.weight",
316
+ "control_model.input_blocks.2.1.transformer_blocks.0.norm3.bias": "blocks.4.transformer_blocks.0.norm3.bias",
317
+ "control_model.input_blocks.2.1.proj_out.weight": "blocks.4.proj_out.weight",
318
+ "control_model.input_blocks.2.1.proj_out.bias": "blocks.4.proj_out.bias",
319
+ "control_model.input_blocks.3.0.op.weight": "blocks.6.conv.weight",
320
+ "control_model.input_blocks.3.0.op.bias": "blocks.6.conv.bias",
321
+ "control_model.input_blocks.4.0.in_layers.0.weight": "blocks.8.norm1.weight",
322
+ "control_model.input_blocks.4.0.in_layers.0.bias": "blocks.8.norm1.bias",
323
+ "control_model.input_blocks.4.0.in_layers.2.weight": "blocks.8.conv1.weight",
324
+ "control_model.input_blocks.4.0.in_layers.2.bias": "blocks.8.conv1.bias",
325
+ "control_model.input_blocks.4.0.emb_layers.1.weight": "blocks.8.time_emb_proj.weight",
326
+ "control_model.input_blocks.4.0.emb_layers.1.bias": "blocks.8.time_emb_proj.bias",
327
+ "control_model.input_blocks.4.0.out_layers.0.weight": "blocks.8.norm2.weight",
328
+ "control_model.input_blocks.4.0.out_layers.0.bias": "blocks.8.norm2.bias",
329
+ "control_model.input_blocks.4.0.out_layers.3.weight": "blocks.8.conv2.weight",
330
+ "control_model.input_blocks.4.0.out_layers.3.bias": "blocks.8.conv2.bias",
331
+ "control_model.input_blocks.4.0.skip_connection.weight": "blocks.8.conv_shortcut.weight",
332
+ "control_model.input_blocks.4.0.skip_connection.bias": "blocks.8.conv_shortcut.bias",
333
+ "control_model.input_blocks.4.1.norm.weight": "blocks.9.norm.weight",
334
+ "control_model.input_blocks.4.1.norm.bias": "blocks.9.norm.bias",
335
+ "control_model.input_blocks.4.1.proj_in.weight": "blocks.9.proj_in.weight",
336
+ "control_model.input_blocks.4.1.proj_in.bias": "blocks.9.proj_in.bias",
337
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn1.to_q.weight": "blocks.9.transformer_blocks.0.attn1.to_q.weight",
338
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn1.to_k.weight": "blocks.9.transformer_blocks.0.attn1.to_k.weight",
339
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn1.to_v.weight": "blocks.9.transformer_blocks.0.attn1.to_v.weight",
340
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.9.transformer_blocks.0.attn1.to_out.weight",
341
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.9.transformer_blocks.0.attn1.to_out.bias",
342
+ "control_model.input_blocks.4.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.9.transformer_blocks.0.act_fn.proj.weight",
343
+ "control_model.input_blocks.4.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.9.transformer_blocks.0.act_fn.proj.bias",
344
+ "control_model.input_blocks.4.1.transformer_blocks.0.ff.net.2.weight": "blocks.9.transformer_blocks.0.ff.weight",
345
+ "control_model.input_blocks.4.1.transformer_blocks.0.ff.net.2.bias": "blocks.9.transformer_blocks.0.ff.bias",
346
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn2.to_q.weight": "blocks.9.transformer_blocks.0.attn2.to_q.weight",
347
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn2.to_k.weight": "blocks.9.transformer_blocks.0.attn2.to_k.weight",
348
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn2.to_v.weight": "blocks.9.transformer_blocks.0.attn2.to_v.weight",
349
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.9.transformer_blocks.0.attn2.to_out.weight",
350
+ "control_model.input_blocks.4.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.9.transformer_blocks.0.attn2.to_out.bias",
351
+ "control_model.input_blocks.4.1.transformer_blocks.0.norm1.weight": "blocks.9.transformer_blocks.0.norm1.weight",
352
+ "control_model.input_blocks.4.1.transformer_blocks.0.norm1.bias": "blocks.9.transformer_blocks.0.norm1.bias",
353
+ "control_model.input_blocks.4.1.transformer_blocks.0.norm2.weight": "blocks.9.transformer_blocks.0.norm2.weight",
354
+ "control_model.input_blocks.4.1.transformer_blocks.0.norm2.bias": "blocks.9.transformer_blocks.0.norm2.bias",
355
+ "control_model.input_blocks.4.1.transformer_blocks.0.norm3.weight": "blocks.9.transformer_blocks.0.norm3.weight",
356
+ "control_model.input_blocks.4.1.transformer_blocks.0.norm3.bias": "blocks.9.transformer_blocks.0.norm3.bias",
357
+ "control_model.input_blocks.4.1.proj_out.weight": "blocks.9.proj_out.weight",
358
+ "control_model.input_blocks.4.1.proj_out.bias": "blocks.9.proj_out.bias",
359
+ "control_model.input_blocks.5.0.in_layers.0.weight": "blocks.11.norm1.weight",
360
+ "control_model.input_blocks.5.0.in_layers.0.bias": "blocks.11.norm1.bias",
361
+ "control_model.input_blocks.5.0.in_layers.2.weight": "blocks.11.conv1.weight",
362
+ "control_model.input_blocks.5.0.in_layers.2.bias": "blocks.11.conv1.bias",
363
+ "control_model.input_blocks.5.0.emb_layers.1.weight": "blocks.11.time_emb_proj.weight",
364
+ "control_model.input_blocks.5.0.emb_layers.1.bias": "blocks.11.time_emb_proj.bias",
365
+ "control_model.input_blocks.5.0.out_layers.0.weight": "blocks.11.norm2.weight",
366
+ "control_model.input_blocks.5.0.out_layers.0.bias": "blocks.11.norm2.bias",
367
+ "control_model.input_blocks.5.0.out_layers.3.weight": "blocks.11.conv2.weight",
368
+ "control_model.input_blocks.5.0.out_layers.3.bias": "blocks.11.conv2.bias",
369
+ "control_model.input_blocks.5.1.norm.weight": "blocks.12.norm.weight",
370
+ "control_model.input_blocks.5.1.norm.bias": "blocks.12.norm.bias",
371
+ "control_model.input_blocks.5.1.proj_in.weight": "blocks.12.proj_in.weight",
372
+ "control_model.input_blocks.5.1.proj_in.bias": "blocks.12.proj_in.bias",
373
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn1.to_q.weight": "blocks.12.transformer_blocks.0.attn1.to_q.weight",
374
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn1.to_k.weight": "blocks.12.transformer_blocks.0.attn1.to_k.weight",
375
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn1.to_v.weight": "blocks.12.transformer_blocks.0.attn1.to_v.weight",
376
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.12.transformer_blocks.0.attn1.to_out.weight",
377
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.12.transformer_blocks.0.attn1.to_out.bias",
378
+ "control_model.input_blocks.5.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.12.transformer_blocks.0.act_fn.proj.weight",
379
+ "control_model.input_blocks.5.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.12.transformer_blocks.0.act_fn.proj.bias",
380
+ "control_model.input_blocks.5.1.transformer_blocks.0.ff.net.2.weight": "blocks.12.transformer_blocks.0.ff.weight",
381
+ "control_model.input_blocks.5.1.transformer_blocks.0.ff.net.2.bias": "blocks.12.transformer_blocks.0.ff.bias",
382
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn2.to_q.weight": "blocks.12.transformer_blocks.0.attn2.to_q.weight",
383
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn2.to_k.weight": "blocks.12.transformer_blocks.0.attn2.to_k.weight",
384
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn2.to_v.weight": "blocks.12.transformer_blocks.0.attn2.to_v.weight",
385
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.12.transformer_blocks.0.attn2.to_out.weight",
386
+ "control_model.input_blocks.5.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.12.transformer_blocks.0.attn2.to_out.bias",
387
+ "control_model.input_blocks.5.1.transformer_blocks.0.norm1.weight": "blocks.12.transformer_blocks.0.norm1.weight",
388
+ "control_model.input_blocks.5.1.transformer_blocks.0.norm1.bias": "blocks.12.transformer_blocks.0.norm1.bias",
389
+ "control_model.input_blocks.5.1.transformer_blocks.0.norm2.weight": "blocks.12.transformer_blocks.0.norm2.weight",
390
+ "control_model.input_blocks.5.1.transformer_blocks.0.norm2.bias": "blocks.12.transformer_blocks.0.norm2.bias",
391
+ "control_model.input_blocks.5.1.transformer_blocks.0.norm3.weight": "blocks.12.transformer_blocks.0.norm3.weight",
392
+ "control_model.input_blocks.5.1.transformer_blocks.0.norm3.bias": "blocks.12.transformer_blocks.0.norm3.bias",
393
+ "control_model.input_blocks.5.1.proj_out.weight": "blocks.12.proj_out.weight",
394
+ "control_model.input_blocks.5.1.proj_out.bias": "blocks.12.proj_out.bias",
395
+ "control_model.input_blocks.6.0.op.weight": "blocks.14.conv.weight",
396
+ "control_model.input_blocks.6.0.op.bias": "blocks.14.conv.bias",
397
+ "control_model.input_blocks.7.0.in_layers.0.weight": "blocks.16.norm1.weight",
398
+ "control_model.input_blocks.7.0.in_layers.0.bias": "blocks.16.norm1.bias",
399
+ "control_model.input_blocks.7.0.in_layers.2.weight": "blocks.16.conv1.weight",
400
+ "control_model.input_blocks.7.0.in_layers.2.bias": "blocks.16.conv1.bias",
401
+ "control_model.input_blocks.7.0.emb_layers.1.weight": "blocks.16.time_emb_proj.weight",
402
+ "control_model.input_blocks.7.0.emb_layers.1.bias": "blocks.16.time_emb_proj.bias",
403
+ "control_model.input_blocks.7.0.out_layers.0.weight": "blocks.16.norm2.weight",
404
+ "control_model.input_blocks.7.0.out_layers.0.bias": "blocks.16.norm2.bias",
405
+ "control_model.input_blocks.7.0.out_layers.3.weight": "blocks.16.conv2.weight",
406
+ "control_model.input_blocks.7.0.out_layers.3.bias": "blocks.16.conv2.bias",
407
+ "control_model.input_blocks.7.0.skip_connection.weight": "blocks.16.conv_shortcut.weight",
408
+ "control_model.input_blocks.7.0.skip_connection.bias": "blocks.16.conv_shortcut.bias",
409
+ "control_model.input_blocks.7.1.norm.weight": "blocks.17.norm.weight",
410
+ "control_model.input_blocks.7.1.norm.bias": "blocks.17.norm.bias",
411
+ "control_model.input_blocks.7.1.proj_in.weight": "blocks.17.proj_in.weight",
412
+ "control_model.input_blocks.7.1.proj_in.bias": "blocks.17.proj_in.bias",
413
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn1.to_q.weight": "blocks.17.transformer_blocks.0.attn1.to_q.weight",
414
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn1.to_k.weight": "blocks.17.transformer_blocks.0.attn1.to_k.weight",
415
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn1.to_v.weight": "blocks.17.transformer_blocks.0.attn1.to_v.weight",
416
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.17.transformer_blocks.0.attn1.to_out.weight",
417
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.17.transformer_blocks.0.attn1.to_out.bias",
418
+ "control_model.input_blocks.7.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.17.transformer_blocks.0.act_fn.proj.weight",
419
+ "control_model.input_blocks.7.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.17.transformer_blocks.0.act_fn.proj.bias",
420
+ "control_model.input_blocks.7.1.transformer_blocks.0.ff.net.2.weight": "blocks.17.transformer_blocks.0.ff.weight",
421
+ "control_model.input_blocks.7.1.transformer_blocks.0.ff.net.2.bias": "blocks.17.transformer_blocks.0.ff.bias",
422
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn2.to_q.weight": "blocks.17.transformer_blocks.0.attn2.to_q.weight",
423
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn2.to_k.weight": "blocks.17.transformer_blocks.0.attn2.to_k.weight",
424
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn2.to_v.weight": "blocks.17.transformer_blocks.0.attn2.to_v.weight",
425
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.17.transformer_blocks.0.attn2.to_out.weight",
426
+ "control_model.input_blocks.7.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.17.transformer_blocks.0.attn2.to_out.bias",
427
+ "control_model.input_blocks.7.1.transformer_blocks.0.norm1.weight": "blocks.17.transformer_blocks.0.norm1.weight",
428
+ "control_model.input_blocks.7.1.transformer_blocks.0.norm1.bias": "blocks.17.transformer_blocks.0.norm1.bias",
429
+ "control_model.input_blocks.7.1.transformer_blocks.0.norm2.weight": "blocks.17.transformer_blocks.0.norm2.weight",
430
+ "control_model.input_blocks.7.1.transformer_blocks.0.norm2.bias": "blocks.17.transformer_blocks.0.norm2.bias",
431
+ "control_model.input_blocks.7.1.transformer_blocks.0.norm3.weight": "blocks.17.transformer_blocks.0.norm3.weight",
432
+ "control_model.input_blocks.7.1.transformer_blocks.0.norm3.bias": "blocks.17.transformer_blocks.0.norm3.bias",
433
+ "control_model.input_blocks.7.1.proj_out.weight": "blocks.17.proj_out.weight",
434
+ "control_model.input_blocks.7.1.proj_out.bias": "blocks.17.proj_out.bias",
435
+ "control_model.input_blocks.8.0.in_layers.0.weight": "blocks.19.norm1.weight",
436
+ "control_model.input_blocks.8.0.in_layers.0.bias": "blocks.19.norm1.bias",
437
+ "control_model.input_blocks.8.0.in_layers.2.weight": "blocks.19.conv1.weight",
438
+ "control_model.input_blocks.8.0.in_layers.2.bias": "blocks.19.conv1.bias",
439
+ "control_model.input_blocks.8.0.emb_layers.1.weight": "blocks.19.time_emb_proj.weight",
440
+ "control_model.input_blocks.8.0.emb_layers.1.bias": "blocks.19.time_emb_proj.bias",
441
+ "control_model.input_blocks.8.0.out_layers.0.weight": "blocks.19.norm2.weight",
442
+ "control_model.input_blocks.8.0.out_layers.0.bias": "blocks.19.norm2.bias",
443
+ "control_model.input_blocks.8.0.out_layers.3.weight": "blocks.19.conv2.weight",
444
+ "control_model.input_blocks.8.0.out_layers.3.bias": "blocks.19.conv2.bias",
445
+ "control_model.input_blocks.8.1.norm.weight": "blocks.20.norm.weight",
446
+ "control_model.input_blocks.8.1.norm.bias": "blocks.20.norm.bias",
447
+ "control_model.input_blocks.8.1.proj_in.weight": "blocks.20.proj_in.weight",
448
+ "control_model.input_blocks.8.1.proj_in.bias": "blocks.20.proj_in.bias",
449
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn1.to_q.weight": "blocks.20.transformer_blocks.0.attn1.to_q.weight",
450
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn1.to_k.weight": "blocks.20.transformer_blocks.0.attn1.to_k.weight",
451
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn1.to_v.weight": "blocks.20.transformer_blocks.0.attn1.to_v.weight",
452
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.20.transformer_blocks.0.attn1.to_out.weight",
453
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.20.transformer_blocks.0.attn1.to_out.bias",
454
+ "control_model.input_blocks.8.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.20.transformer_blocks.0.act_fn.proj.weight",
455
+ "control_model.input_blocks.8.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.20.transformer_blocks.0.act_fn.proj.bias",
456
+ "control_model.input_blocks.8.1.transformer_blocks.0.ff.net.2.weight": "blocks.20.transformer_blocks.0.ff.weight",
457
+ "control_model.input_blocks.8.1.transformer_blocks.0.ff.net.2.bias": "blocks.20.transformer_blocks.0.ff.bias",
458
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn2.to_q.weight": "blocks.20.transformer_blocks.0.attn2.to_q.weight",
459
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn2.to_k.weight": "blocks.20.transformer_blocks.0.attn2.to_k.weight",
460
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn2.to_v.weight": "blocks.20.transformer_blocks.0.attn2.to_v.weight",
461
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.20.transformer_blocks.0.attn2.to_out.weight",
462
+ "control_model.input_blocks.8.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.20.transformer_blocks.0.attn2.to_out.bias",
463
+ "control_model.input_blocks.8.1.transformer_blocks.0.norm1.weight": "blocks.20.transformer_blocks.0.norm1.weight",
464
+ "control_model.input_blocks.8.1.transformer_blocks.0.norm1.bias": "blocks.20.transformer_blocks.0.norm1.bias",
465
+ "control_model.input_blocks.8.1.transformer_blocks.0.norm2.weight": "blocks.20.transformer_blocks.0.norm2.weight",
466
+ "control_model.input_blocks.8.1.transformer_blocks.0.norm2.bias": "blocks.20.transformer_blocks.0.norm2.bias",
467
+ "control_model.input_blocks.8.1.transformer_blocks.0.norm3.weight": "blocks.20.transformer_blocks.0.norm3.weight",
468
+ "control_model.input_blocks.8.1.transformer_blocks.0.norm3.bias": "blocks.20.transformer_blocks.0.norm3.bias",
469
+ "control_model.input_blocks.8.1.proj_out.weight": "blocks.20.proj_out.weight",
470
+ "control_model.input_blocks.8.1.proj_out.bias": "blocks.20.proj_out.bias",
471
+ "control_model.input_blocks.9.0.op.weight": "blocks.22.conv.weight",
472
+ "control_model.input_blocks.9.0.op.bias": "blocks.22.conv.bias",
473
+ "control_model.input_blocks.10.0.in_layers.0.weight": "blocks.24.norm1.weight",
474
+ "control_model.input_blocks.10.0.in_layers.0.bias": "blocks.24.norm1.bias",
475
+ "control_model.input_blocks.10.0.in_layers.2.weight": "blocks.24.conv1.weight",
476
+ "control_model.input_blocks.10.0.in_layers.2.bias": "blocks.24.conv1.bias",
477
+ "control_model.input_blocks.10.0.emb_layers.1.weight": "blocks.24.time_emb_proj.weight",
478
+ "control_model.input_blocks.10.0.emb_layers.1.bias": "blocks.24.time_emb_proj.bias",
479
+ "control_model.input_blocks.10.0.out_layers.0.weight": "blocks.24.norm2.weight",
480
+ "control_model.input_blocks.10.0.out_layers.0.bias": "blocks.24.norm2.bias",
481
+ "control_model.input_blocks.10.0.out_layers.3.weight": "blocks.24.conv2.weight",
482
+ "control_model.input_blocks.10.0.out_layers.3.bias": "blocks.24.conv2.bias",
483
+ "control_model.input_blocks.11.0.in_layers.0.weight": "blocks.26.norm1.weight",
484
+ "control_model.input_blocks.11.0.in_layers.0.bias": "blocks.26.norm1.bias",
485
+ "control_model.input_blocks.11.0.in_layers.2.weight": "blocks.26.conv1.weight",
486
+ "control_model.input_blocks.11.0.in_layers.2.bias": "blocks.26.conv1.bias",
487
+ "control_model.input_blocks.11.0.emb_layers.1.weight": "blocks.26.time_emb_proj.weight",
488
+ "control_model.input_blocks.11.0.emb_layers.1.bias": "blocks.26.time_emb_proj.bias",
489
+ "control_model.input_blocks.11.0.out_layers.0.weight": "blocks.26.norm2.weight",
490
+ "control_model.input_blocks.11.0.out_layers.0.bias": "blocks.26.norm2.bias",
491
+ "control_model.input_blocks.11.0.out_layers.3.weight": "blocks.26.conv2.weight",
492
+ "control_model.input_blocks.11.0.out_layers.3.bias": "blocks.26.conv2.bias",
493
+ "control_model.zero_convs.0.0.weight": "controlnet_blocks.0.weight",
494
+ "control_model.zero_convs.0.0.bias": "controlnet_blocks.0.bias",
495
+ "control_model.zero_convs.1.0.weight": "controlnet_blocks.1.weight",
496
+ "control_model.zero_convs.1.0.bias": "controlnet_blocks.0.bias",
497
+ "control_model.zero_convs.2.0.weight": "controlnet_blocks.2.weight",
498
+ "control_model.zero_convs.2.0.bias": "controlnet_blocks.0.bias",
499
+ "control_model.zero_convs.3.0.weight": "controlnet_blocks.3.weight",
500
+ "control_model.zero_convs.3.0.bias": "controlnet_blocks.0.bias",
501
+ "control_model.zero_convs.4.0.weight": "controlnet_blocks.4.weight",
502
+ "control_model.zero_convs.4.0.bias": "controlnet_blocks.4.bias",
503
+ "control_model.zero_convs.5.0.weight": "controlnet_blocks.5.weight",
504
+ "control_model.zero_convs.5.0.bias": "controlnet_blocks.4.bias",
505
+ "control_model.zero_convs.6.0.weight": "controlnet_blocks.6.weight",
506
+ "control_model.zero_convs.6.0.bias": "controlnet_blocks.4.bias",
507
+ "control_model.zero_convs.7.0.weight": "controlnet_blocks.7.weight",
508
+ "control_model.zero_convs.7.0.bias": "controlnet_blocks.7.bias",
509
+ "control_model.zero_convs.8.0.weight": "controlnet_blocks.8.weight",
510
+ "control_model.zero_convs.8.0.bias": "controlnet_blocks.7.bias",
511
+ "control_model.zero_convs.9.0.weight": "controlnet_blocks.9.weight",
512
+ "control_model.zero_convs.9.0.bias": "controlnet_blocks.7.bias",
513
+ "control_model.zero_convs.10.0.weight": "controlnet_blocks.10.weight",
514
+ "control_model.zero_convs.10.0.bias": "controlnet_blocks.7.bias",
515
+ "control_model.zero_convs.11.0.weight": "controlnet_blocks.11.weight",
516
+ "control_model.zero_convs.11.0.bias": "controlnet_blocks.7.bias",
517
+ "control_model.input_hint_block.0.weight": "controlnet_conv_in.blocks.0.weight",
518
+ "control_model.input_hint_block.0.bias": "controlnet_conv_in.blocks.0.bias",
519
+ "control_model.input_hint_block.2.weight": "controlnet_conv_in.blocks.2.weight",
520
+ "control_model.input_hint_block.2.bias": "controlnet_conv_in.blocks.2.bias",
521
+ "control_model.input_hint_block.4.weight": "controlnet_conv_in.blocks.4.weight",
522
+ "control_model.input_hint_block.4.bias": "controlnet_conv_in.blocks.4.bias",
523
+ "control_model.input_hint_block.6.weight": "controlnet_conv_in.blocks.6.weight",
524
+ "control_model.input_hint_block.6.bias": "controlnet_conv_in.blocks.6.bias",
525
+ "control_model.input_hint_block.8.weight": "controlnet_conv_in.blocks.8.weight",
526
+ "control_model.input_hint_block.8.bias": "controlnet_conv_in.blocks.8.bias",
527
+ "control_model.input_hint_block.10.weight": "controlnet_conv_in.blocks.10.weight",
528
+ "control_model.input_hint_block.10.bias": "controlnet_conv_in.blocks.10.bias",
529
+ "control_model.input_hint_block.12.weight": "controlnet_conv_in.blocks.12.weight",
530
+ "control_model.input_hint_block.12.bias": "controlnet_conv_in.blocks.12.bias",
531
+ "control_model.input_hint_block.14.weight": "controlnet_conv_in.blocks.14.weight",
532
+ "control_model.input_hint_block.14.bias": "controlnet_conv_in.blocks.14.bias",
533
+ "control_model.middle_block.0.in_layers.0.weight": "blocks.28.norm1.weight",
534
+ "control_model.middle_block.0.in_layers.0.bias": "blocks.28.norm1.bias",
535
+ "control_model.middle_block.0.in_layers.2.weight": "blocks.28.conv1.weight",
536
+ "control_model.middle_block.0.in_layers.2.bias": "blocks.28.conv1.bias",
537
+ "control_model.middle_block.0.emb_layers.1.weight": "blocks.28.time_emb_proj.weight",
538
+ "control_model.middle_block.0.emb_layers.1.bias": "blocks.28.time_emb_proj.bias",
539
+ "control_model.middle_block.0.out_layers.0.weight": "blocks.28.norm2.weight",
540
+ "control_model.middle_block.0.out_layers.0.bias": "blocks.28.norm2.bias",
541
+ "control_model.middle_block.0.out_layers.3.weight": "blocks.28.conv2.weight",
542
+ "control_model.middle_block.0.out_layers.3.bias": "blocks.28.conv2.bias",
543
+ "control_model.middle_block.1.norm.weight": "blocks.29.norm.weight",
544
+ "control_model.middle_block.1.norm.bias": "blocks.29.norm.bias",
545
+ "control_model.middle_block.1.proj_in.weight": "blocks.29.proj_in.weight",
546
+ "control_model.middle_block.1.proj_in.bias": "blocks.29.proj_in.bias",
547
+ "control_model.middle_block.1.transformer_blocks.0.attn1.to_q.weight": "blocks.29.transformer_blocks.0.attn1.to_q.weight",
548
+ "control_model.middle_block.1.transformer_blocks.0.attn1.to_k.weight": "blocks.29.transformer_blocks.0.attn1.to_k.weight",
549
+ "control_model.middle_block.1.transformer_blocks.0.attn1.to_v.weight": "blocks.29.transformer_blocks.0.attn1.to_v.weight",
550
+ "control_model.middle_block.1.transformer_blocks.0.attn1.to_out.0.weight": "blocks.29.transformer_blocks.0.attn1.to_out.weight",
551
+ "control_model.middle_block.1.transformer_blocks.0.attn1.to_out.0.bias": "blocks.29.transformer_blocks.0.attn1.to_out.bias",
552
+ "control_model.middle_block.1.transformer_blocks.0.ff.net.0.proj.weight": "blocks.29.transformer_blocks.0.act_fn.proj.weight",
553
+ "control_model.middle_block.1.transformer_blocks.0.ff.net.0.proj.bias": "blocks.29.transformer_blocks.0.act_fn.proj.bias",
554
+ "control_model.middle_block.1.transformer_blocks.0.ff.net.2.weight": "blocks.29.transformer_blocks.0.ff.weight",
555
+ "control_model.middle_block.1.transformer_blocks.0.ff.net.2.bias": "blocks.29.transformer_blocks.0.ff.bias",
556
+ "control_model.middle_block.1.transformer_blocks.0.attn2.to_q.weight": "blocks.29.transformer_blocks.0.attn2.to_q.weight",
557
+ "control_model.middle_block.1.transformer_blocks.0.attn2.to_k.weight": "blocks.29.transformer_blocks.0.attn2.to_k.weight",
558
+ "control_model.middle_block.1.transformer_blocks.0.attn2.to_v.weight": "blocks.29.transformer_blocks.0.attn2.to_v.weight",
559
+ "control_model.middle_block.1.transformer_blocks.0.attn2.to_out.0.weight": "blocks.29.transformer_blocks.0.attn2.to_out.weight",
560
+ "control_model.middle_block.1.transformer_blocks.0.attn2.to_out.0.bias": "blocks.29.transformer_blocks.0.attn2.to_out.bias",
561
+ "control_model.middle_block.1.transformer_blocks.0.norm1.weight": "blocks.29.transformer_blocks.0.norm1.weight",
562
+ "control_model.middle_block.1.transformer_blocks.0.norm1.bias": "blocks.29.transformer_blocks.0.norm1.bias",
563
+ "control_model.middle_block.1.transformer_blocks.0.norm2.weight": "blocks.29.transformer_blocks.0.norm2.weight",
564
+ "control_model.middle_block.1.transformer_blocks.0.norm2.bias": "blocks.29.transformer_blocks.0.norm2.bias",
565
+ "control_model.middle_block.1.transformer_blocks.0.norm3.weight": "blocks.29.transformer_blocks.0.norm3.weight",
566
+ "control_model.middle_block.1.transformer_blocks.0.norm3.bias": "blocks.29.transformer_blocks.0.norm3.bias",
567
+ "control_model.middle_block.1.proj_out.weight": "blocks.29.proj_out.weight",
568
+ "control_model.middle_block.1.proj_out.bias": "blocks.29.proj_out.bias",
569
+ "control_model.middle_block.2.in_layers.0.weight": "blocks.30.norm1.weight",
570
+ "control_model.middle_block.2.in_layers.0.bias": "blocks.30.norm1.bias",
571
+ "control_model.middle_block.2.in_layers.2.weight": "blocks.30.conv1.weight",
572
+ "control_model.middle_block.2.in_layers.2.bias": "blocks.30.conv1.bias",
573
+ "control_model.middle_block.2.emb_layers.1.weight": "blocks.30.time_emb_proj.weight",
574
+ "control_model.middle_block.2.emb_layers.1.bias": "blocks.30.time_emb_proj.bias",
575
+ "control_model.middle_block.2.out_layers.0.weight": "blocks.30.norm2.weight",
576
+ "control_model.middle_block.2.out_layers.0.bias": "blocks.30.norm2.bias",
577
+ "control_model.middle_block.2.out_layers.3.weight": "blocks.30.conv2.weight",
578
+ "control_model.middle_block.2.out_layers.3.bias": "blocks.30.conv2.bias",
579
+ "control_model.middle_block_out.0.weight": "controlnet_blocks.12.weight",
580
+ "control_model.middle_block_out.0.bias": "controlnet_blocks.7.bias",
581
+ }
582
+ state_dict_ = {}
583
+ for name in state_dict:
584
+ if name in rename_dict:
585
+ param = state_dict[name]
586
+ if ".proj_in." in name or ".proj_out." in name:
587
+ param = param.squeeze()
588
+ state_dict_[rename_dict[name]] = param
589
+ return state_dict_
sd_ipadapter.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .svd_image_encoder import SVDImageEncoder
2
+ from .sdxl_ipadapter import IpAdapterImageProjModel, IpAdapterModule, SDXLIpAdapterStateDictConverter
3
+ from transformers import CLIPImageProcessor
4
+ import torch
5
+
6
+
7
+ class IpAdapterCLIPImageEmbedder(SVDImageEncoder):
8
+ def __init__(self):
9
+ super().__init__()
10
+ self.image_processor = CLIPImageProcessor()
11
+
12
+ def forward(self, image):
13
+ pixel_values = self.image_processor(images=image, return_tensors="pt").pixel_values
14
+ pixel_values = pixel_values.to(device=self.embeddings.class_embedding.device, dtype=self.embeddings.class_embedding.dtype)
15
+ return super().forward(pixel_values)
16
+
17
+
18
+ class SDIpAdapter(torch.nn.Module):
19
+ def __init__(self):
20
+ super().__init__()
21
+ shape_list = [(768, 320)] * 2 + [(768, 640)] * 2 + [(768, 1280)] * 5 + [(768, 640)] * 3 + [(768, 320)] * 3 + [(768, 1280)] * 1
22
+ self.ipadapter_modules = torch.nn.ModuleList([IpAdapterModule(*shape) for shape in shape_list])
23
+ self.image_proj = IpAdapterImageProjModel(cross_attention_dim=768, clip_embeddings_dim=1024, clip_extra_context_tokens=4)
24
+ self.set_full_adapter()
25
+
26
+ def set_full_adapter(self):
27
+ block_ids = [1, 4, 9, 12, 17, 20, 40, 43, 46, 50, 53, 56, 60, 63, 66, 29]
28
+ self.call_block_id = {(i, 0): j for j, i in enumerate(block_ids)}
29
+
30
+ def set_less_adapter(self):
31
+ # IP-Adapter for SD v1.5 doesn't support this feature.
32
+ self.set_full_adapter()
33
+
34
+ def forward(self, hidden_states, scale=1.0):
35
+ hidden_states = self.image_proj(hidden_states)
36
+ hidden_states = hidden_states.view(1, -1, hidden_states.shape[-1])
37
+ ip_kv_dict = {}
38
+ for (block_id, transformer_id) in self.call_block_id:
39
+ ipadapter_id = self.call_block_id[(block_id, transformer_id)]
40
+ ip_k, ip_v = self.ipadapter_modules[ipadapter_id](hidden_states)
41
+ if block_id not in ip_kv_dict:
42
+ ip_kv_dict[block_id] = {}
43
+ ip_kv_dict[block_id][transformer_id] = {
44
+ "ip_k": ip_k,
45
+ "ip_v": ip_v,
46
+ "scale": scale
47
+ }
48
+ return ip_kv_dict
49
+
50
+ @staticmethod
51
+ def state_dict_converter():
52
+ return SDIpAdapterStateDictConverter()
53
+
54
+
55
+ class SDIpAdapterStateDictConverter(SDXLIpAdapterStateDictConverter):
56
+ def __init__(self):
57
+ pass
sd_motion.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .sd_unet import SDUNet, Attention, GEGLU
2
+ import torch
3
+ from einops import rearrange, repeat
4
+
5
+
6
+ class TemporalTransformerBlock(torch.nn.Module):
7
+
8
+ def __init__(self, dim, num_attention_heads, attention_head_dim, max_position_embeddings=32):
9
+ super().__init__()
10
+
11
+ # 1. Self-Attn
12
+ self.pe1 = torch.nn.Parameter(torch.zeros(1, max_position_embeddings, dim))
13
+ self.norm1 = torch.nn.LayerNorm(dim, elementwise_affine=True)
14
+ self.attn1 = Attention(q_dim=dim, num_heads=num_attention_heads, head_dim=attention_head_dim, bias_out=True)
15
+
16
+ # 2. Cross-Attn
17
+ self.pe2 = torch.nn.Parameter(torch.zeros(1, max_position_embeddings, dim))
18
+ self.norm2 = torch.nn.LayerNorm(dim, elementwise_affine=True)
19
+ self.attn2 = Attention(q_dim=dim, num_heads=num_attention_heads, head_dim=attention_head_dim, bias_out=True)
20
+
21
+ # 3. Feed-forward
22
+ self.norm3 = torch.nn.LayerNorm(dim, elementwise_affine=True)
23
+ self.act_fn = GEGLU(dim, dim * 4)
24
+ self.ff = torch.nn.Linear(dim * 4, dim)
25
+
26
+
27
+ def forward(self, hidden_states, batch_size=1):
28
+
29
+ # 1. Self-Attention
30
+ norm_hidden_states = self.norm1(hidden_states)
31
+ norm_hidden_states = rearrange(norm_hidden_states, "(b f) h c -> (b h) f c", b=batch_size)
32
+ attn_output = self.attn1(norm_hidden_states + self.pe1[:, :norm_hidden_states.shape[1]])
33
+ attn_output = rearrange(attn_output, "(b h) f c -> (b f) h c", b=batch_size)
34
+ hidden_states = attn_output + hidden_states
35
+
36
+ # 2. Cross-Attention
37
+ norm_hidden_states = self.norm2(hidden_states)
38
+ norm_hidden_states = rearrange(norm_hidden_states, "(b f) h c -> (b h) f c", b=batch_size)
39
+ attn_output = self.attn2(norm_hidden_states + self.pe2[:, :norm_hidden_states.shape[1]])
40
+ attn_output = rearrange(attn_output, "(b h) f c -> (b f) h c", b=batch_size)
41
+ hidden_states = attn_output + hidden_states
42
+
43
+ # 3. Feed-forward
44
+ norm_hidden_states = self.norm3(hidden_states)
45
+ ff_output = self.act_fn(norm_hidden_states)
46
+ ff_output = self.ff(ff_output)
47
+ hidden_states = ff_output + hidden_states
48
+
49
+ return hidden_states
50
+
51
+
52
+ class TemporalBlock(torch.nn.Module):
53
+
54
+ def __init__(self, num_attention_heads, attention_head_dim, in_channels, num_layers=1, norm_num_groups=32, eps=1e-5):
55
+ super().__init__()
56
+ inner_dim = num_attention_heads * attention_head_dim
57
+
58
+ self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=eps, affine=True)
59
+ self.proj_in = torch.nn.Linear(in_channels, inner_dim)
60
+
61
+ self.transformer_blocks = torch.nn.ModuleList([
62
+ TemporalTransformerBlock(
63
+ inner_dim,
64
+ num_attention_heads,
65
+ attention_head_dim
66
+ )
67
+ for d in range(num_layers)
68
+ ])
69
+
70
+ self.proj_out = torch.nn.Linear(inner_dim, in_channels)
71
+
72
+ def forward(self, hidden_states, time_emb, text_emb, res_stack, batch_size=1):
73
+ batch, _, height, width = hidden_states.shape
74
+ residual = hidden_states
75
+
76
+ hidden_states = self.norm(hidden_states)
77
+ inner_dim = hidden_states.shape[1]
78
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
79
+ hidden_states = self.proj_in(hidden_states)
80
+
81
+ for block in self.transformer_blocks:
82
+ hidden_states = block(
83
+ hidden_states,
84
+ batch_size=batch_size
85
+ )
86
+
87
+ hidden_states = self.proj_out(hidden_states)
88
+ hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
89
+ hidden_states = hidden_states + residual
90
+
91
+ return hidden_states, time_emb, text_emb, res_stack
92
+
93
+
94
+ class SDMotionModel(torch.nn.Module):
95
+ def __init__(self):
96
+ super().__init__()
97
+ self.motion_modules = torch.nn.ModuleList([
98
+ TemporalBlock(8, 40, 320, eps=1e-6),
99
+ TemporalBlock(8, 40, 320, eps=1e-6),
100
+ TemporalBlock(8, 80, 640, eps=1e-6),
101
+ TemporalBlock(8, 80, 640, eps=1e-6),
102
+ TemporalBlock(8, 160, 1280, eps=1e-6),
103
+ TemporalBlock(8, 160, 1280, eps=1e-6),
104
+ TemporalBlock(8, 160, 1280, eps=1e-6),
105
+ TemporalBlock(8, 160, 1280, eps=1e-6),
106
+ TemporalBlock(8, 160, 1280, eps=1e-6),
107
+ TemporalBlock(8, 160, 1280, eps=1e-6),
108
+ TemporalBlock(8, 160, 1280, eps=1e-6),
109
+ TemporalBlock(8, 160, 1280, eps=1e-6),
110
+ TemporalBlock(8, 160, 1280, eps=1e-6),
111
+ TemporalBlock(8, 160, 1280, eps=1e-6),
112
+ TemporalBlock(8, 160, 1280, eps=1e-6),
113
+ TemporalBlock(8, 80, 640, eps=1e-6),
114
+ TemporalBlock(8, 80, 640, eps=1e-6),
115
+ TemporalBlock(8, 80, 640, eps=1e-6),
116
+ TemporalBlock(8, 40, 320, eps=1e-6),
117
+ TemporalBlock(8, 40, 320, eps=1e-6),
118
+ TemporalBlock(8, 40, 320, eps=1e-6),
119
+ ])
120
+ self.call_block_id = {
121
+ 1: 0,
122
+ 4: 1,
123
+ 9: 2,
124
+ 12: 3,
125
+ 17: 4,
126
+ 20: 5,
127
+ 24: 6,
128
+ 26: 7,
129
+ 29: 8,
130
+ 32: 9,
131
+ 34: 10,
132
+ 36: 11,
133
+ 40: 12,
134
+ 43: 13,
135
+ 46: 14,
136
+ 50: 15,
137
+ 53: 16,
138
+ 56: 17,
139
+ 60: 18,
140
+ 63: 19,
141
+ 66: 20
142
+ }
143
+
144
+ def forward(self):
145
+ pass
146
+
147
+ @staticmethod
148
+ def state_dict_converter():
149
+ return SDMotionModelStateDictConverter()
150
+
151
+
152
+ class SDMotionModelStateDictConverter:
153
+ def __init__(self):
154
+ pass
155
+
156
+ def from_diffusers(self, state_dict):
157
+ rename_dict = {
158
+ "norm": "norm",
159
+ "proj_in": "proj_in",
160
+ "transformer_blocks.0.attention_blocks.0.to_q": "transformer_blocks.0.attn1.to_q",
161
+ "transformer_blocks.0.attention_blocks.0.to_k": "transformer_blocks.0.attn1.to_k",
162
+ "transformer_blocks.0.attention_blocks.0.to_v": "transformer_blocks.0.attn1.to_v",
163
+ "transformer_blocks.0.attention_blocks.0.to_out.0": "transformer_blocks.0.attn1.to_out",
164
+ "transformer_blocks.0.attention_blocks.0.pos_encoder": "transformer_blocks.0.pe1",
165
+ "transformer_blocks.0.attention_blocks.1.to_q": "transformer_blocks.0.attn2.to_q",
166
+ "transformer_blocks.0.attention_blocks.1.to_k": "transformer_blocks.0.attn2.to_k",
167
+ "transformer_blocks.0.attention_blocks.1.to_v": "transformer_blocks.0.attn2.to_v",
168
+ "transformer_blocks.0.attention_blocks.1.to_out.0": "transformer_blocks.0.attn2.to_out",
169
+ "transformer_blocks.0.attention_blocks.1.pos_encoder": "transformer_blocks.0.pe2",
170
+ "transformer_blocks.0.norms.0": "transformer_blocks.0.norm1",
171
+ "transformer_blocks.0.norms.1": "transformer_blocks.0.norm2",
172
+ "transformer_blocks.0.ff.net.0.proj": "transformer_blocks.0.act_fn.proj",
173
+ "transformer_blocks.0.ff.net.2": "transformer_blocks.0.ff",
174
+ "transformer_blocks.0.ff_norm": "transformer_blocks.0.norm3",
175
+ "proj_out": "proj_out",
176
+ }
177
+ name_list = sorted([i for i in state_dict if i.startswith("down_blocks.")])
178
+ name_list += sorted([i for i in state_dict if i.startswith("mid_block.")])
179
+ name_list += sorted([i for i in state_dict if i.startswith("up_blocks.")])
180
+ state_dict_ = {}
181
+ last_prefix, module_id = "", -1
182
+ for name in name_list:
183
+ names = name.split(".")
184
+ prefix_index = names.index("temporal_transformer") + 1
185
+ prefix = ".".join(names[:prefix_index])
186
+ if prefix != last_prefix:
187
+ last_prefix = prefix
188
+ module_id += 1
189
+ middle_name = ".".join(names[prefix_index:-1])
190
+ suffix = names[-1]
191
+ if "pos_encoder" in names:
192
+ rename = ".".join(["motion_modules", str(module_id), rename_dict[middle_name]])
193
+ else:
194
+ rename = ".".join(["motion_modules", str(module_id), rename_dict[middle_name], suffix])
195
+ state_dict_[rename] = state_dict[name]
196
+ return state_dict_
197
+
198
+ def from_civitai(self, state_dict):
199
+ return self.from_diffusers(state_dict)
sd_text_encoder.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .attention import Attention
3
+
4
+
5
+ class CLIPEncoderLayer(torch.nn.Module):
6
+ def __init__(self, embed_dim, intermediate_size, num_heads=12, head_dim=64, use_quick_gelu=True):
7
+ super().__init__()
8
+ self.attn = Attention(q_dim=embed_dim, num_heads=num_heads, head_dim=head_dim, bias_q=True, bias_kv=True, bias_out=True)
9
+ self.layer_norm1 = torch.nn.LayerNorm(embed_dim)
10
+ self.layer_norm2 = torch.nn.LayerNorm(embed_dim)
11
+ self.fc1 = torch.nn.Linear(embed_dim, intermediate_size)
12
+ self.fc2 = torch.nn.Linear(intermediate_size, embed_dim)
13
+
14
+ self.use_quick_gelu = use_quick_gelu
15
+
16
+ def quickGELU(self, x):
17
+ return x * torch.sigmoid(1.702 * x)
18
+
19
+ def forward(self, hidden_states, attn_mask=None):
20
+ residual = hidden_states
21
+
22
+ hidden_states = self.layer_norm1(hidden_states)
23
+ hidden_states = self.attn(hidden_states, attn_mask=attn_mask)
24
+ hidden_states = residual + hidden_states
25
+
26
+ residual = hidden_states
27
+ hidden_states = self.layer_norm2(hidden_states)
28
+ hidden_states = self.fc1(hidden_states)
29
+ if self.use_quick_gelu:
30
+ hidden_states = self.quickGELU(hidden_states)
31
+ else:
32
+ hidden_states = torch.nn.functional.gelu(hidden_states)
33
+ hidden_states = self.fc2(hidden_states)
34
+ hidden_states = residual + hidden_states
35
+
36
+ return hidden_states
37
+
38
+
39
+ class SDTextEncoder(torch.nn.Module):
40
+ def __init__(self, embed_dim=768, vocab_size=49408, max_position_embeddings=77, num_encoder_layers=12, encoder_intermediate_size=3072):
41
+ super().__init__()
42
+
43
+ # token_embedding
44
+ self.token_embedding = torch.nn.Embedding(vocab_size, embed_dim)
45
+
46
+ # position_embeds (This is a fixed tensor)
47
+ self.position_embeds = torch.nn.Parameter(torch.zeros(1, max_position_embeddings, embed_dim))
48
+
49
+ # encoders
50
+ self.encoders = torch.nn.ModuleList([CLIPEncoderLayer(embed_dim, encoder_intermediate_size) for _ in range(num_encoder_layers)])
51
+
52
+ # attn_mask
53
+ self.attn_mask = self.attention_mask(max_position_embeddings)
54
+
55
+ # final_layer_norm
56
+ self.final_layer_norm = torch.nn.LayerNorm(embed_dim)
57
+
58
+ def attention_mask(self, length):
59
+ mask = torch.empty(length, length)
60
+ mask.fill_(float("-inf"))
61
+ mask.triu_(1)
62
+ return mask
63
+
64
+ def forward(self, input_ids, clip_skip=1):
65
+ embeds = self.token_embedding(input_ids) + self.position_embeds
66
+ attn_mask = self.attn_mask.to(device=embeds.device, dtype=embeds.dtype)
67
+ for encoder_id, encoder in enumerate(self.encoders):
68
+ embeds = encoder(embeds, attn_mask=attn_mask)
69
+ if encoder_id + clip_skip == len(self.encoders):
70
+ break
71
+ embeds = self.final_layer_norm(embeds)
72
+ return embeds
73
+
74
+ @staticmethod
75
+ def state_dict_converter():
76
+ return SDTextEncoderStateDictConverter()
77
+
78
+
79
+ class SDTextEncoderStateDictConverter:
80
+ def __init__(self):
81
+ pass
82
+
83
+ def from_diffusers(self, state_dict):
84
+ rename_dict = {
85
+ "text_model.embeddings.token_embedding.weight": "token_embedding.weight",
86
+ "text_model.embeddings.position_embedding.weight": "position_embeds",
87
+ "text_model.final_layer_norm.weight": "final_layer_norm.weight",
88
+ "text_model.final_layer_norm.bias": "final_layer_norm.bias"
89
+ }
90
+ attn_rename_dict = {
91
+ "self_attn.q_proj": "attn.to_q",
92
+ "self_attn.k_proj": "attn.to_k",
93
+ "self_attn.v_proj": "attn.to_v",
94
+ "self_attn.out_proj": "attn.to_out",
95
+ "layer_norm1": "layer_norm1",
96
+ "layer_norm2": "layer_norm2",
97
+ "mlp.fc1": "fc1",
98
+ "mlp.fc2": "fc2",
99
+ }
100
+ state_dict_ = {}
101
+ for name in state_dict:
102
+ if name in rename_dict:
103
+ param = state_dict[name]
104
+ if name == "text_model.embeddings.position_embedding.weight":
105
+ param = param.reshape((1, param.shape[0], param.shape[1]))
106
+ state_dict_[rename_dict[name]] = param
107
+ elif name.startswith("text_model.encoder.layers."):
108
+ param = state_dict[name]
109
+ names = name.split(".")
110
+ layer_id, layer_type, tail = names[3], ".".join(names[4:-1]), names[-1]
111
+ name_ = ".".join(["encoders", layer_id, attn_rename_dict[layer_type], tail])
112
+ state_dict_[name_] = param
113
+ return state_dict_
114
+
115
+ def from_civitai(self, state_dict):
116
+ rename_dict = {
117
+ "cond_stage_model.transformer.text_model.embeddings.token_embedding.weight": "token_embedding.weight",
118
+ "cond_stage_model.transformer.text_model.encoder.layers.0.layer_norm1.bias": "encoders.0.layer_norm1.bias",
119
+ "cond_stage_model.transformer.text_model.encoder.layers.0.layer_norm1.weight": "encoders.0.layer_norm1.weight",
120
+ "cond_stage_model.transformer.text_model.encoder.layers.0.layer_norm2.bias": "encoders.0.layer_norm2.bias",
121
+ "cond_stage_model.transformer.text_model.encoder.layers.0.layer_norm2.weight": "encoders.0.layer_norm2.weight",
122
+ "cond_stage_model.transformer.text_model.encoder.layers.0.mlp.fc1.bias": "encoders.0.fc1.bias",
123
+ "cond_stage_model.transformer.text_model.encoder.layers.0.mlp.fc1.weight": "encoders.0.fc1.weight",
124
+ "cond_stage_model.transformer.text_model.encoder.layers.0.mlp.fc2.bias": "encoders.0.fc2.bias",
125
+ "cond_stage_model.transformer.text_model.encoder.layers.0.mlp.fc2.weight": "encoders.0.fc2.weight",
126
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.k_proj.bias": "encoders.0.attn.to_k.bias",
127
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.k_proj.weight": "encoders.0.attn.to_k.weight",
128
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.out_proj.bias": "encoders.0.attn.to_out.bias",
129
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.out_proj.weight": "encoders.0.attn.to_out.weight",
130
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.q_proj.bias": "encoders.0.attn.to_q.bias",
131
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.q_proj.weight": "encoders.0.attn.to_q.weight",
132
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.v_proj.bias": "encoders.0.attn.to_v.bias",
133
+ "cond_stage_model.transformer.text_model.encoder.layers.0.self_attn.v_proj.weight": "encoders.0.attn.to_v.weight",
134
+ "cond_stage_model.transformer.text_model.encoder.layers.1.layer_norm1.bias": "encoders.1.layer_norm1.bias",
135
+ "cond_stage_model.transformer.text_model.encoder.layers.1.layer_norm1.weight": "encoders.1.layer_norm1.weight",
136
+ "cond_stage_model.transformer.text_model.encoder.layers.1.layer_norm2.bias": "encoders.1.layer_norm2.bias",
137
+ "cond_stage_model.transformer.text_model.encoder.layers.1.layer_norm2.weight": "encoders.1.layer_norm2.weight",
138
+ "cond_stage_model.transformer.text_model.encoder.layers.1.mlp.fc1.bias": "encoders.1.fc1.bias",
139
+ "cond_stage_model.transformer.text_model.encoder.layers.1.mlp.fc1.weight": "encoders.1.fc1.weight",
140
+ "cond_stage_model.transformer.text_model.encoder.layers.1.mlp.fc2.bias": "encoders.1.fc2.bias",
141
+ "cond_stage_model.transformer.text_model.encoder.layers.1.mlp.fc2.weight": "encoders.1.fc2.weight",
142
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.k_proj.bias": "encoders.1.attn.to_k.bias",
143
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.k_proj.weight": "encoders.1.attn.to_k.weight",
144
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.out_proj.bias": "encoders.1.attn.to_out.bias",
145
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.out_proj.weight": "encoders.1.attn.to_out.weight",
146
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.q_proj.bias": "encoders.1.attn.to_q.bias",
147
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.q_proj.weight": "encoders.1.attn.to_q.weight",
148
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.v_proj.bias": "encoders.1.attn.to_v.bias",
149
+ "cond_stage_model.transformer.text_model.encoder.layers.1.self_attn.v_proj.weight": "encoders.1.attn.to_v.weight",
150
+ "cond_stage_model.transformer.text_model.encoder.layers.10.layer_norm1.bias": "encoders.10.layer_norm1.bias",
151
+ "cond_stage_model.transformer.text_model.encoder.layers.10.layer_norm1.weight": "encoders.10.layer_norm1.weight",
152
+ "cond_stage_model.transformer.text_model.encoder.layers.10.layer_norm2.bias": "encoders.10.layer_norm2.bias",
153
+ "cond_stage_model.transformer.text_model.encoder.layers.10.layer_norm2.weight": "encoders.10.layer_norm2.weight",
154
+ "cond_stage_model.transformer.text_model.encoder.layers.10.mlp.fc1.bias": "encoders.10.fc1.bias",
155
+ "cond_stage_model.transformer.text_model.encoder.layers.10.mlp.fc1.weight": "encoders.10.fc1.weight",
156
+ "cond_stage_model.transformer.text_model.encoder.layers.10.mlp.fc2.bias": "encoders.10.fc2.bias",
157
+ "cond_stage_model.transformer.text_model.encoder.layers.10.mlp.fc2.weight": "encoders.10.fc2.weight",
158
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.k_proj.bias": "encoders.10.attn.to_k.bias",
159
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.k_proj.weight": "encoders.10.attn.to_k.weight",
160
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.out_proj.bias": "encoders.10.attn.to_out.bias",
161
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.out_proj.weight": "encoders.10.attn.to_out.weight",
162
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.q_proj.bias": "encoders.10.attn.to_q.bias",
163
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.q_proj.weight": "encoders.10.attn.to_q.weight",
164
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.v_proj.bias": "encoders.10.attn.to_v.bias",
165
+ "cond_stage_model.transformer.text_model.encoder.layers.10.self_attn.v_proj.weight": "encoders.10.attn.to_v.weight",
166
+ "cond_stage_model.transformer.text_model.encoder.layers.11.layer_norm1.bias": "encoders.11.layer_norm1.bias",
167
+ "cond_stage_model.transformer.text_model.encoder.layers.11.layer_norm1.weight": "encoders.11.layer_norm1.weight",
168
+ "cond_stage_model.transformer.text_model.encoder.layers.11.layer_norm2.bias": "encoders.11.layer_norm2.bias",
169
+ "cond_stage_model.transformer.text_model.encoder.layers.11.layer_norm2.weight": "encoders.11.layer_norm2.weight",
170
+ "cond_stage_model.transformer.text_model.encoder.layers.11.mlp.fc1.bias": "encoders.11.fc1.bias",
171
+ "cond_stage_model.transformer.text_model.encoder.layers.11.mlp.fc1.weight": "encoders.11.fc1.weight",
172
+ "cond_stage_model.transformer.text_model.encoder.layers.11.mlp.fc2.bias": "encoders.11.fc2.bias",
173
+ "cond_stage_model.transformer.text_model.encoder.layers.11.mlp.fc2.weight": "encoders.11.fc2.weight",
174
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.k_proj.bias": "encoders.11.attn.to_k.bias",
175
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.k_proj.weight": "encoders.11.attn.to_k.weight",
176
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.out_proj.bias": "encoders.11.attn.to_out.bias",
177
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.out_proj.weight": "encoders.11.attn.to_out.weight",
178
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.q_proj.bias": "encoders.11.attn.to_q.bias",
179
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.q_proj.weight": "encoders.11.attn.to_q.weight",
180
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.v_proj.bias": "encoders.11.attn.to_v.bias",
181
+ "cond_stage_model.transformer.text_model.encoder.layers.11.self_attn.v_proj.weight": "encoders.11.attn.to_v.weight",
182
+ "cond_stage_model.transformer.text_model.encoder.layers.2.layer_norm1.bias": "encoders.2.layer_norm1.bias",
183
+ "cond_stage_model.transformer.text_model.encoder.layers.2.layer_norm1.weight": "encoders.2.layer_norm1.weight",
184
+ "cond_stage_model.transformer.text_model.encoder.layers.2.layer_norm2.bias": "encoders.2.layer_norm2.bias",
185
+ "cond_stage_model.transformer.text_model.encoder.layers.2.layer_norm2.weight": "encoders.2.layer_norm2.weight",
186
+ "cond_stage_model.transformer.text_model.encoder.layers.2.mlp.fc1.bias": "encoders.2.fc1.bias",
187
+ "cond_stage_model.transformer.text_model.encoder.layers.2.mlp.fc1.weight": "encoders.2.fc1.weight",
188
+ "cond_stage_model.transformer.text_model.encoder.layers.2.mlp.fc2.bias": "encoders.2.fc2.bias",
189
+ "cond_stage_model.transformer.text_model.encoder.layers.2.mlp.fc2.weight": "encoders.2.fc2.weight",
190
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.k_proj.bias": "encoders.2.attn.to_k.bias",
191
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.k_proj.weight": "encoders.2.attn.to_k.weight",
192
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.out_proj.bias": "encoders.2.attn.to_out.bias",
193
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.out_proj.weight": "encoders.2.attn.to_out.weight",
194
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.q_proj.bias": "encoders.2.attn.to_q.bias",
195
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.q_proj.weight": "encoders.2.attn.to_q.weight",
196
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.v_proj.bias": "encoders.2.attn.to_v.bias",
197
+ "cond_stage_model.transformer.text_model.encoder.layers.2.self_attn.v_proj.weight": "encoders.2.attn.to_v.weight",
198
+ "cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm1.bias": "encoders.3.layer_norm1.bias",
199
+ "cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm1.weight": "encoders.3.layer_norm1.weight",
200
+ "cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.bias": "encoders.3.layer_norm2.bias",
201
+ "cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.weight": "encoders.3.layer_norm2.weight",
202
+ "cond_stage_model.transformer.text_model.encoder.layers.3.mlp.fc1.bias": "encoders.3.fc1.bias",
203
+ "cond_stage_model.transformer.text_model.encoder.layers.3.mlp.fc1.weight": "encoders.3.fc1.weight",
204
+ "cond_stage_model.transformer.text_model.encoder.layers.3.mlp.fc2.bias": "encoders.3.fc2.bias",
205
+ "cond_stage_model.transformer.text_model.encoder.layers.3.mlp.fc2.weight": "encoders.3.fc2.weight",
206
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.k_proj.bias": "encoders.3.attn.to_k.bias",
207
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.k_proj.weight": "encoders.3.attn.to_k.weight",
208
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.out_proj.bias": "encoders.3.attn.to_out.bias",
209
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.out_proj.weight": "encoders.3.attn.to_out.weight",
210
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.q_proj.bias": "encoders.3.attn.to_q.bias",
211
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.q_proj.weight": "encoders.3.attn.to_q.weight",
212
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.v_proj.bias": "encoders.3.attn.to_v.bias",
213
+ "cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.v_proj.weight": "encoders.3.attn.to_v.weight",
214
+ "cond_stage_model.transformer.text_model.encoder.layers.4.layer_norm1.bias": "encoders.4.layer_norm1.bias",
215
+ "cond_stage_model.transformer.text_model.encoder.layers.4.layer_norm1.weight": "encoders.4.layer_norm1.weight",
216
+ "cond_stage_model.transformer.text_model.encoder.layers.4.layer_norm2.bias": "encoders.4.layer_norm2.bias",
217
+ "cond_stage_model.transformer.text_model.encoder.layers.4.layer_norm2.weight": "encoders.4.layer_norm2.weight",
218
+ "cond_stage_model.transformer.text_model.encoder.layers.4.mlp.fc1.bias": "encoders.4.fc1.bias",
219
+ "cond_stage_model.transformer.text_model.encoder.layers.4.mlp.fc1.weight": "encoders.4.fc1.weight",
220
+ "cond_stage_model.transformer.text_model.encoder.layers.4.mlp.fc2.bias": "encoders.4.fc2.bias",
221
+ "cond_stage_model.transformer.text_model.encoder.layers.4.mlp.fc2.weight": "encoders.4.fc2.weight",
222
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.k_proj.bias": "encoders.4.attn.to_k.bias",
223
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.k_proj.weight": "encoders.4.attn.to_k.weight",
224
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.out_proj.bias": "encoders.4.attn.to_out.bias",
225
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.out_proj.weight": "encoders.4.attn.to_out.weight",
226
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.q_proj.bias": "encoders.4.attn.to_q.bias",
227
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.q_proj.weight": "encoders.4.attn.to_q.weight",
228
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.v_proj.bias": "encoders.4.attn.to_v.bias",
229
+ "cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.v_proj.weight": "encoders.4.attn.to_v.weight",
230
+ "cond_stage_model.transformer.text_model.encoder.layers.5.layer_norm1.bias": "encoders.5.layer_norm1.bias",
231
+ "cond_stage_model.transformer.text_model.encoder.layers.5.layer_norm1.weight": "encoders.5.layer_norm1.weight",
232
+ "cond_stage_model.transformer.text_model.encoder.layers.5.layer_norm2.bias": "encoders.5.layer_norm2.bias",
233
+ "cond_stage_model.transformer.text_model.encoder.layers.5.layer_norm2.weight": "encoders.5.layer_norm2.weight",
234
+ "cond_stage_model.transformer.text_model.encoder.layers.5.mlp.fc1.bias": "encoders.5.fc1.bias",
235
+ "cond_stage_model.transformer.text_model.encoder.layers.5.mlp.fc1.weight": "encoders.5.fc1.weight",
236
+ "cond_stage_model.transformer.text_model.encoder.layers.5.mlp.fc2.bias": "encoders.5.fc2.bias",
237
+ "cond_stage_model.transformer.text_model.encoder.layers.5.mlp.fc2.weight": "encoders.5.fc2.weight",
238
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.k_proj.bias": "encoders.5.attn.to_k.bias",
239
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.k_proj.weight": "encoders.5.attn.to_k.weight",
240
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.out_proj.bias": "encoders.5.attn.to_out.bias",
241
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.out_proj.weight": "encoders.5.attn.to_out.weight",
242
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.q_proj.bias": "encoders.5.attn.to_q.bias",
243
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.q_proj.weight": "encoders.5.attn.to_q.weight",
244
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.v_proj.bias": "encoders.5.attn.to_v.bias",
245
+ "cond_stage_model.transformer.text_model.encoder.layers.5.self_attn.v_proj.weight": "encoders.5.attn.to_v.weight",
246
+ "cond_stage_model.transformer.text_model.encoder.layers.6.layer_norm1.bias": "encoders.6.layer_norm1.bias",
247
+ "cond_stage_model.transformer.text_model.encoder.layers.6.layer_norm1.weight": "encoders.6.layer_norm1.weight",
248
+ "cond_stage_model.transformer.text_model.encoder.layers.6.layer_norm2.bias": "encoders.6.layer_norm2.bias",
249
+ "cond_stage_model.transformer.text_model.encoder.layers.6.layer_norm2.weight": "encoders.6.layer_norm2.weight",
250
+ "cond_stage_model.transformer.text_model.encoder.layers.6.mlp.fc1.bias": "encoders.6.fc1.bias",
251
+ "cond_stage_model.transformer.text_model.encoder.layers.6.mlp.fc1.weight": "encoders.6.fc1.weight",
252
+ "cond_stage_model.transformer.text_model.encoder.layers.6.mlp.fc2.bias": "encoders.6.fc2.bias",
253
+ "cond_stage_model.transformer.text_model.encoder.layers.6.mlp.fc2.weight": "encoders.6.fc2.weight",
254
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.k_proj.bias": "encoders.6.attn.to_k.bias",
255
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.k_proj.weight": "encoders.6.attn.to_k.weight",
256
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.out_proj.bias": "encoders.6.attn.to_out.bias",
257
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.out_proj.weight": "encoders.6.attn.to_out.weight",
258
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.q_proj.bias": "encoders.6.attn.to_q.bias",
259
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.q_proj.weight": "encoders.6.attn.to_q.weight",
260
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.v_proj.bias": "encoders.6.attn.to_v.bias",
261
+ "cond_stage_model.transformer.text_model.encoder.layers.6.self_attn.v_proj.weight": "encoders.6.attn.to_v.weight",
262
+ "cond_stage_model.transformer.text_model.encoder.layers.7.layer_norm1.bias": "encoders.7.layer_norm1.bias",
263
+ "cond_stage_model.transformer.text_model.encoder.layers.7.layer_norm1.weight": "encoders.7.layer_norm1.weight",
264
+ "cond_stage_model.transformer.text_model.encoder.layers.7.layer_norm2.bias": "encoders.7.layer_norm2.bias",
265
+ "cond_stage_model.transformer.text_model.encoder.layers.7.layer_norm2.weight": "encoders.7.layer_norm2.weight",
266
+ "cond_stage_model.transformer.text_model.encoder.layers.7.mlp.fc1.bias": "encoders.7.fc1.bias",
267
+ "cond_stage_model.transformer.text_model.encoder.layers.7.mlp.fc1.weight": "encoders.7.fc1.weight",
268
+ "cond_stage_model.transformer.text_model.encoder.layers.7.mlp.fc2.bias": "encoders.7.fc2.bias",
269
+ "cond_stage_model.transformer.text_model.encoder.layers.7.mlp.fc2.weight": "encoders.7.fc2.weight",
270
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.k_proj.bias": "encoders.7.attn.to_k.bias",
271
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.k_proj.weight": "encoders.7.attn.to_k.weight",
272
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.out_proj.bias": "encoders.7.attn.to_out.bias",
273
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.out_proj.weight": "encoders.7.attn.to_out.weight",
274
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.q_proj.bias": "encoders.7.attn.to_q.bias",
275
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.q_proj.weight": "encoders.7.attn.to_q.weight",
276
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.v_proj.bias": "encoders.7.attn.to_v.bias",
277
+ "cond_stage_model.transformer.text_model.encoder.layers.7.self_attn.v_proj.weight": "encoders.7.attn.to_v.weight",
278
+ "cond_stage_model.transformer.text_model.encoder.layers.8.layer_norm1.bias": "encoders.8.layer_norm1.bias",
279
+ "cond_stage_model.transformer.text_model.encoder.layers.8.layer_norm1.weight": "encoders.8.layer_norm1.weight",
280
+ "cond_stage_model.transformer.text_model.encoder.layers.8.layer_norm2.bias": "encoders.8.layer_norm2.bias",
281
+ "cond_stage_model.transformer.text_model.encoder.layers.8.layer_norm2.weight": "encoders.8.layer_norm2.weight",
282
+ "cond_stage_model.transformer.text_model.encoder.layers.8.mlp.fc1.bias": "encoders.8.fc1.bias",
283
+ "cond_stage_model.transformer.text_model.encoder.layers.8.mlp.fc1.weight": "encoders.8.fc1.weight",
284
+ "cond_stage_model.transformer.text_model.encoder.layers.8.mlp.fc2.bias": "encoders.8.fc2.bias",
285
+ "cond_stage_model.transformer.text_model.encoder.layers.8.mlp.fc2.weight": "encoders.8.fc2.weight",
286
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.k_proj.bias": "encoders.8.attn.to_k.bias",
287
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.k_proj.weight": "encoders.8.attn.to_k.weight",
288
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.out_proj.bias": "encoders.8.attn.to_out.bias",
289
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.out_proj.weight": "encoders.8.attn.to_out.weight",
290
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.q_proj.bias": "encoders.8.attn.to_q.bias",
291
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.q_proj.weight": "encoders.8.attn.to_q.weight",
292
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.v_proj.bias": "encoders.8.attn.to_v.bias",
293
+ "cond_stage_model.transformer.text_model.encoder.layers.8.self_attn.v_proj.weight": "encoders.8.attn.to_v.weight",
294
+ "cond_stage_model.transformer.text_model.encoder.layers.9.layer_norm1.bias": "encoders.9.layer_norm1.bias",
295
+ "cond_stage_model.transformer.text_model.encoder.layers.9.layer_norm1.weight": "encoders.9.layer_norm1.weight",
296
+ "cond_stage_model.transformer.text_model.encoder.layers.9.layer_norm2.bias": "encoders.9.layer_norm2.bias",
297
+ "cond_stage_model.transformer.text_model.encoder.layers.9.layer_norm2.weight": "encoders.9.layer_norm2.weight",
298
+ "cond_stage_model.transformer.text_model.encoder.layers.9.mlp.fc1.bias": "encoders.9.fc1.bias",
299
+ "cond_stage_model.transformer.text_model.encoder.layers.9.mlp.fc1.weight": "encoders.9.fc1.weight",
300
+ "cond_stage_model.transformer.text_model.encoder.layers.9.mlp.fc2.bias": "encoders.9.fc2.bias",
301
+ "cond_stage_model.transformer.text_model.encoder.layers.9.mlp.fc2.weight": "encoders.9.fc2.weight",
302
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.k_proj.bias": "encoders.9.attn.to_k.bias",
303
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.k_proj.weight": "encoders.9.attn.to_k.weight",
304
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.out_proj.bias": "encoders.9.attn.to_out.bias",
305
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.out_proj.weight": "encoders.9.attn.to_out.weight",
306
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.q_proj.bias": "encoders.9.attn.to_q.bias",
307
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.q_proj.weight": "encoders.9.attn.to_q.weight",
308
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.v_proj.bias": "encoders.9.attn.to_v.bias",
309
+ "cond_stage_model.transformer.text_model.encoder.layers.9.self_attn.v_proj.weight": "encoders.9.attn.to_v.weight",
310
+ "cond_stage_model.transformer.text_model.final_layer_norm.bias": "final_layer_norm.bias",
311
+ "cond_stage_model.transformer.text_model.final_layer_norm.weight": "final_layer_norm.weight",
312
+ "cond_stage_model.transformer.text_model.embeddings.position_embedding.weight": "position_embeds"
313
+ }
314
+ state_dict_ = {}
315
+ for name in state_dict:
316
+ if name in rename_dict:
317
+ param = state_dict[name]
318
+ if name == "cond_stage_model.transformer.text_model.embeddings.position_embedding.weight":
319
+ param = param.reshape((1, param.shape[0], param.shape[1]))
320
+ state_dict_[rename_dict[name]] = param
321
+ return state_dict_
sd_unet.py ADDED
The diff for this file is too large to render. See raw diff
 
sd_vae_decoder.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .attention import Attention
3
+ from .sd_unet import ResnetBlock, UpSampler
4
+ from .tiler import TileWorker
5
+
6
+
7
+ class VAEAttentionBlock(torch.nn.Module):
8
+
9
+ def __init__(self, num_attention_heads, attention_head_dim, in_channels, num_layers=1, norm_num_groups=32, eps=1e-5):
10
+ super().__init__()
11
+ inner_dim = num_attention_heads * attention_head_dim
12
+
13
+ self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=eps, affine=True)
14
+
15
+ self.transformer_blocks = torch.nn.ModuleList([
16
+ Attention(
17
+ inner_dim,
18
+ num_attention_heads,
19
+ attention_head_dim,
20
+ bias_q=True,
21
+ bias_kv=True,
22
+ bias_out=True
23
+ )
24
+ for d in range(num_layers)
25
+ ])
26
+
27
+ def forward(self, hidden_states, time_emb, text_emb, res_stack):
28
+ batch, _, height, width = hidden_states.shape
29
+ residual = hidden_states
30
+
31
+ hidden_states = self.norm(hidden_states)
32
+ inner_dim = hidden_states.shape[1]
33
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
34
+
35
+ for block in self.transformer_blocks:
36
+ hidden_states = block(hidden_states)
37
+
38
+ hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
39
+ hidden_states = hidden_states + residual
40
+
41
+ return hidden_states, time_emb, text_emb, res_stack
42
+
43
+
44
+ class SDVAEDecoder(torch.nn.Module):
45
+ def __init__(self):
46
+ super().__init__()
47
+ self.scaling_factor = 0.18215
48
+ self.post_quant_conv = torch.nn.Conv2d(4, 4, kernel_size=1)
49
+ self.conv_in = torch.nn.Conv2d(4, 512, kernel_size=3, padding=1)
50
+
51
+ self.blocks = torch.nn.ModuleList([
52
+ # UNetMidBlock2D
53
+ ResnetBlock(512, 512, eps=1e-6),
54
+ VAEAttentionBlock(1, 512, 512, 1, eps=1e-6),
55
+ ResnetBlock(512, 512, eps=1e-6),
56
+ # UpDecoderBlock2D
57
+ ResnetBlock(512, 512, eps=1e-6),
58
+ ResnetBlock(512, 512, eps=1e-6),
59
+ ResnetBlock(512, 512, eps=1e-6),
60
+ UpSampler(512),
61
+ # UpDecoderBlock2D
62
+ ResnetBlock(512, 512, eps=1e-6),
63
+ ResnetBlock(512, 512, eps=1e-6),
64
+ ResnetBlock(512, 512, eps=1e-6),
65
+ UpSampler(512),
66
+ # UpDecoderBlock2D
67
+ ResnetBlock(512, 256, eps=1e-6),
68
+ ResnetBlock(256, 256, eps=1e-6),
69
+ ResnetBlock(256, 256, eps=1e-6),
70
+ UpSampler(256),
71
+ # UpDecoderBlock2D
72
+ ResnetBlock(256, 128, eps=1e-6),
73
+ ResnetBlock(128, 128, eps=1e-6),
74
+ ResnetBlock(128, 128, eps=1e-6),
75
+ ])
76
+
77
+ self.conv_norm_out = torch.nn.GroupNorm(num_channels=128, num_groups=32, eps=1e-5)
78
+ self.conv_act = torch.nn.SiLU()
79
+ self.conv_out = torch.nn.Conv2d(128, 3, kernel_size=3, padding=1)
80
+
81
+ def tiled_forward(self, sample, tile_size=64, tile_stride=32):
82
+ hidden_states = TileWorker().tiled_forward(
83
+ lambda x: self.forward(x),
84
+ sample,
85
+ tile_size,
86
+ tile_stride,
87
+ tile_device=sample.device,
88
+ tile_dtype=sample.dtype
89
+ )
90
+ return hidden_states
91
+
92
+ def forward(self, sample, tiled=False, tile_size=64, tile_stride=32, **kwargs):
93
+ original_dtype = sample.dtype
94
+ sample = sample.to(dtype=next(iter(self.parameters())).dtype)
95
+ # For VAE Decoder, we do not need to apply the tiler on each layer.
96
+ if tiled:
97
+ return self.tiled_forward(sample, tile_size=tile_size, tile_stride=tile_stride)
98
+
99
+ # 1. pre-process
100
+ sample = sample / self.scaling_factor
101
+ hidden_states = self.post_quant_conv(sample)
102
+ hidden_states = self.conv_in(hidden_states)
103
+ time_emb = None
104
+ text_emb = None
105
+ res_stack = None
106
+
107
+ # 2. blocks
108
+ for i, block in enumerate(self.blocks):
109
+ hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
110
+
111
+ # 3. output
112
+ hidden_states = self.conv_norm_out(hidden_states)
113
+ hidden_states = self.conv_act(hidden_states)
114
+ hidden_states = self.conv_out(hidden_states)
115
+ hidden_states = hidden_states.to(original_dtype)
116
+
117
+ return hidden_states
118
+
119
+ @staticmethod
120
+ def state_dict_converter():
121
+ return SDVAEDecoderStateDictConverter()
122
+
123
+
124
+ class SDVAEDecoderStateDictConverter:
125
+ def __init__(self):
126
+ pass
127
+
128
+ def from_diffusers(self, state_dict):
129
+ # architecture
130
+ block_types = [
131
+ 'ResnetBlock', 'VAEAttentionBlock', 'ResnetBlock',
132
+ 'ResnetBlock', 'ResnetBlock', 'ResnetBlock', 'UpSampler',
133
+ 'ResnetBlock', 'ResnetBlock', 'ResnetBlock', 'UpSampler',
134
+ 'ResnetBlock', 'ResnetBlock', 'ResnetBlock', 'UpSampler',
135
+ 'ResnetBlock', 'ResnetBlock', 'ResnetBlock'
136
+ ]
137
+
138
+ # Rename each parameter
139
+ local_rename_dict = {
140
+ "post_quant_conv": "post_quant_conv",
141
+ "decoder.conv_in": "conv_in",
142
+ "decoder.mid_block.attentions.0.group_norm": "blocks.1.norm",
143
+ "decoder.mid_block.attentions.0.to_q": "blocks.1.transformer_blocks.0.to_q",
144
+ "decoder.mid_block.attentions.0.to_k": "blocks.1.transformer_blocks.0.to_k",
145
+ "decoder.mid_block.attentions.0.to_v": "blocks.1.transformer_blocks.0.to_v",
146
+ "decoder.mid_block.attentions.0.to_out.0": "blocks.1.transformer_blocks.0.to_out",
147
+ "decoder.mid_block.resnets.0.norm1": "blocks.0.norm1",
148
+ "decoder.mid_block.resnets.0.conv1": "blocks.0.conv1",
149
+ "decoder.mid_block.resnets.0.norm2": "blocks.0.norm2",
150
+ "decoder.mid_block.resnets.0.conv2": "blocks.0.conv2",
151
+ "decoder.mid_block.resnets.1.norm1": "blocks.2.norm1",
152
+ "decoder.mid_block.resnets.1.conv1": "blocks.2.conv1",
153
+ "decoder.mid_block.resnets.1.norm2": "blocks.2.norm2",
154
+ "decoder.mid_block.resnets.1.conv2": "blocks.2.conv2",
155
+ "decoder.conv_norm_out": "conv_norm_out",
156
+ "decoder.conv_out": "conv_out",
157
+ }
158
+ name_list = sorted([name for name in state_dict])
159
+ rename_dict = {}
160
+ block_id = {"ResnetBlock": 2, "DownSampler": 2, "UpSampler": 2}
161
+ last_block_type_with_id = {"ResnetBlock": "", "DownSampler": "", "UpSampler": ""}
162
+ for name in name_list:
163
+ names = name.split(".")
164
+ name_prefix = ".".join(names[:-1])
165
+ if name_prefix in local_rename_dict:
166
+ rename_dict[name] = local_rename_dict[name_prefix] + "." + names[-1]
167
+ elif name.startswith("decoder.up_blocks"):
168
+ block_type = {"resnets": "ResnetBlock", "downsamplers": "DownSampler", "upsamplers": "UpSampler"}[names[3]]
169
+ block_type_with_id = ".".join(names[:5])
170
+ if block_type_with_id != last_block_type_with_id[block_type]:
171
+ block_id[block_type] += 1
172
+ last_block_type_with_id[block_type] = block_type_with_id
173
+ while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:
174
+ block_id[block_type] += 1
175
+ block_type_with_id = ".".join(names[:5])
176
+ names = ["blocks", str(block_id[block_type])] + names[5:]
177
+ rename_dict[name] = ".".join(names)
178
+
179
+ # Convert state_dict
180
+ state_dict_ = {}
181
+ for name, param in state_dict.items():
182
+ if name in rename_dict:
183
+ state_dict_[rename_dict[name]] = param
184
+ return state_dict_
185
+
186
+ def from_civitai(self, state_dict):
187
+ rename_dict = {
188
+ "first_stage_model.decoder.conv_in.bias": "conv_in.bias",
189
+ "first_stage_model.decoder.conv_in.weight": "conv_in.weight",
190
+ "first_stage_model.decoder.conv_out.bias": "conv_out.bias",
191
+ "first_stage_model.decoder.conv_out.weight": "conv_out.weight",
192
+ "first_stage_model.decoder.mid.attn_1.k.bias": "blocks.1.transformer_blocks.0.to_k.bias",
193
+ "first_stage_model.decoder.mid.attn_1.k.weight": "blocks.1.transformer_blocks.0.to_k.weight",
194
+ "first_stage_model.decoder.mid.attn_1.norm.bias": "blocks.1.norm.bias",
195
+ "first_stage_model.decoder.mid.attn_1.norm.weight": "blocks.1.norm.weight",
196
+ "first_stage_model.decoder.mid.attn_1.proj_out.bias": "blocks.1.transformer_blocks.0.to_out.bias",
197
+ "first_stage_model.decoder.mid.attn_1.proj_out.weight": "blocks.1.transformer_blocks.0.to_out.weight",
198
+ "first_stage_model.decoder.mid.attn_1.q.bias": "blocks.1.transformer_blocks.0.to_q.bias",
199
+ "first_stage_model.decoder.mid.attn_1.q.weight": "blocks.1.transformer_blocks.0.to_q.weight",
200
+ "first_stage_model.decoder.mid.attn_1.v.bias": "blocks.1.transformer_blocks.0.to_v.bias",
201
+ "first_stage_model.decoder.mid.attn_1.v.weight": "blocks.1.transformer_blocks.0.to_v.weight",
202
+ "first_stage_model.decoder.mid.block_1.conv1.bias": "blocks.0.conv1.bias",
203
+ "first_stage_model.decoder.mid.block_1.conv1.weight": "blocks.0.conv1.weight",
204
+ "first_stage_model.decoder.mid.block_1.conv2.bias": "blocks.0.conv2.bias",
205
+ "first_stage_model.decoder.mid.block_1.conv2.weight": "blocks.0.conv2.weight",
206
+ "first_stage_model.decoder.mid.block_1.norm1.bias": "blocks.0.norm1.bias",
207
+ "first_stage_model.decoder.mid.block_1.norm1.weight": "blocks.0.norm1.weight",
208
+ "first_stage_model.decoder.mid.block_1.norm2.bias": "blocks.0.norm2.bias",
209
+ "first_stage_model.decoder.mid.block_1.norm2.weight": "blocks.0.norm2.weight",
210
+ "first_stage_model.decoder.mid.block_2.conv1.bias": "blocks.2.conv1.bias",
211
+ "first_stage_model.decoder.mid.block_2.conv1.weight": "blocks.2.conv1.weight",
212
+ "first_stage_model.decoder.mid.block_2.conv2.bias": "blocks.2.conv2.bias",
213
+ "first_stage_model.decoder.mid.block_2.conv2.weight": "blocks.2.conv2.weight",
214
+ "first_stage_model.decoder.mid.block_2.norm1.bias": "blocks.2.norm1.bias",
215
+ "first_stage_model.decoder.mid.block_2.norm1.weight": "blocks.2.norm1.weight",
216
+ "first_stage_model.decoder.mid.block_2.norm2.bias": "blocks.2.norm2.bias",
217
+ "first_stage_model.decoder.mid.block_2.norm2.weight": "blocks.2.norm2.weight",
218
+ "first_stage_model.decoder.norm_out.bias": "conv_norm_out.bias",
219
+ "first_stage_model.decoder.norm_out.weight": "conv_norm_out.weight",
220
+ "first_stage_model.decoder.up.0.block.0.conv1.bias": "blocks.15.conv1.bias",
221
+ "first_stage_model.decoder.up.0.block.0.conv1.weight": "blocks.15.conv1.weight",
222
+ "first_stage_model.decoder.up.0.block.0.conv2.bias": "blocks.15.conv2.bias",
223
+ "first_stage_model.decoder.up.0.block.0.conv2.weight": "blocks.15.conv2.weight",
224
+ "first_stage_model.decoder.up.0.block.0.nin_shortcut.bias": "blocks.15.conv_shortcut.bias",
225
+ "first_stage_model.decoder.up.0.block.0.nin_shortcut.weight": "blocks.15.conv_shortcut.weight",
226
+ "first_stage_model.decoder.up.0.block.0.norm1.bias": "blocks.15.norm1.bias",
227
+ "first_stage_model.decoder.up.0.block.0.norm1.weight": "blocks.15.norm1.weight",
228
+ "first_stage_model.decoder.up.0.block.0.norm2.bias": "blocks.15.norm2.bias",
229
+ "first_stage_model.decoder.up.0.block.0.norm2.weight": "blocks.15.norm2.weight",
230
+ "first_stage_model.decoder.up.0.block.1.conv1.bias": "blocks.16.conv1.bias",
231
+ "first_stage_model.decoder.up.0.block.1.conv1.weight": "blocks.16.conv1.weight",
232
+ "first_stage_model.decoder.up.0.block.1.conv2.bias": "blocks.16.conv2.bias",
233
+ "first_stage_model.decoder.up.0.block.1.conv2.weight": "blocks.16.conv2.weight",
234
+ "first_stage_model.decoder.up.0.block.1.norm1.bias": "blocks.16.norm1.bias",
235
+ "first_stage_model.decoder.up.0.block.1.norm1.weight": "blocks.16.norm1.weight",
236
+ "first_stage_model.decoder.up.0.block.1.norm2.bias": "blocks.16.norm2.bias",
237
+ "first_stage_model.decoder.up.0.block.1.norm2.weight": "blocks.16.norm2.weight",
238
+ "first_stage_model.decoder.up.0.block.2.conv1.bias": "blocks.17.conv1.bias",
239
+ "first_stage_model.decoder.up.0.block.2.conv1.weight": "blocks.17.conv1.weight",
240
+ "first_stage_model.decoder.up.0.block.2.conv2.bias": "blocks.17.conv2.bias",
241
+ "first_stage_model.decoder.up.0.block.2.conv2.weight": "blocks.17.conv2.weight",
242
+ "first_stage_model.decoder.up.0.block.2.norm1.bias": "blocks.17.norm1.bias",
243
+ "first_stage_model.decoder.up.0.block.2.norm1.weight": "blocks.17.norm1.weight",
244
+ "first_stage_model.decoder.up.0.block.2.norm2.bias": "blocks.17.norm2.bias",
245
+ "first_stage_model.decoder.up.0.block.2.norm2.weight": "blocks.17.norm2.weight",
246
+ "first_stage_model.decoder.up.1.block.0.conv1.bias": "blocks.11.conv1.bias",
247
+ "first_stage_model.decoder.up.1.block.0.conv1.weight": "blocks.11.conv1.weight",
248
+ "first_stage_model.decoder.up.1.block.0.conv2.bias": "blocks.11.conv2.bias",
249
+ "first_stage_model.decoder.up.1.block.0.conv2.weight": "blocks.11.conv2.weight",
250
+ "first_stage_model.decoder.up.1.block.0.nin_shortcut.bias": "blocks.11.conv_shortcut.bias",
251
+ "first_stage_model.decoder.up.1.block.0.nin_shortcut.weight": "blocks.11.conv_shortcut.weight",
252
+ "first_stage_model.decoder.up.1.block.0.norm1.bias": "blocks.11.norm1.bias",
253
+ "first_stage_model.decoder.up.1.block.0.norm1.weight": "blocks.11.norm1.weight",
254
+ "first_stage_model.decoder.up.1.block.0.norm2.bias": "blocks.11.norm2.bias",
255
+ "first_stage_model.decoder.up.1.block.0.norm2.weight": "blocks.11.norm2.weight",
256
+ "first_stage_model.decoder.up.1.block.1.conv1.bias": "blocks.12.conv1.bias",
257
+ "first_stage_model.decoder.up.1.block.1.conv1.weight": "blocks.12.conv1.weight",
258
+ "first_stage_model.decoder.up.1.block.1.conv2.bias": "blocks.12.conv2.bias",
259
+ "first_stage_model.decoder.up.1.block.1.conv2.weight": "blocks.12.conv2.weight",
260
+ "first_stage_model.decoder.up.1.block.1.norm1.bias": "blocks.12.norm1.bias",
261
+ "first_stage_model.decoder.up.1.block.1.norm1.weight": "blocks.12.norm1.weight",
262
+ "first_stage_model.decoder.up.1.block.1.norm2.bias": "blocks.12.norm2.bias",
263
+ "first_stage_model.decoder.up.1.block.1.norm2.weight": "blocks.12.norm2.weight",
264
+ "first_stage_model.decoder.up.1.block.2.conv1.bias": "blocks.13.conv1.bias",
265
+ "first_stage_model.decoder.up.1.block.2.conv1.weight": "blocks.13.conv1.weight",
266
+ "first_stage_model.decoder.up.1.block.2.conv2.bias": "blocks.13.conv2.bias",
267
+ "first_stage_model.decoder.up.1.block.2.conv2.weight": "blocks.13.conv2.weight",
268
+ "first_stage_model.decoder.up.1.block.2.norm1.bias": "blocks.13.norm1.bias",
269
+ "first_stage_model.decoder.up.1.block.2.norm1.weight": "blocks.13.norm1.weight",
270
+ "first_stage_model.decoder.up.1.block.2.norm2.bias": "blocks.13.norm2.bias",
271
+ "first_stage_model.decoder.up.1.block.2.norm2.weight": "blocks.13.norm2.weight",
272
+ "first_stage_model.decoder.up.1.upsample.conv.bias": "blocks.14.conv.bias",
273
+ "first_stage_model.decoder.up.1.upsample.conv.weight": "blocks.14.conv.weight",
274
+ "first_stage_model.decoder.up.2.block.0.conv1.bias": "blocks.7.conv1.bias",
275
+ "first_stage_model.decoder.up.2.block.0.conv1.weight": "blocks.7.conv1.weight",
276
+ "first_stage_model.decoder.up.2.block.0.conv2.bias": "blocks.7.conv2.bias",
277
+ "first_stage_model.decoder.up.2.block.0.conv2.weight": "blocks.7.conv2.weight",
278
+ "first_stage_model.decoder.up.2.block.0.norm1.bias": "blocks.7.norm1.bias",
279
+ "first_stage_model.decoder.up.2.block.0.norm1.weight": "blocks.7.norm1.weight",
280
+ "first_stage_model.decoder.up.2.block.0.norm2.bias": "blocks.7.norm2.bias",
281
+ "first_stage_model.decoder.up.2.block.0.norm2.weight": "blocks.7.norm2.weight",
282
+ "first_stage_model.decoder.up.2.block.1.conv1.bias": "blocks.8.conv1.bias",
283
+ "first_stage_model.decoder.up.2.block.1.conv1.weight": "blocks.8.conv1.weight",
284
+ "first_stage_model.decoder.up.2.block.1.conv2.bias": "blocks.8.conv2.bias",
285
+ "first_stage_model.decoder.up.2.block.1.conv2.weight": "blocks.8.conv2.weight",
286
+ "first_stage_model.decoder.up.2.block.1.norm1.bias": "blocks.8.norm1.bias",
287
+ "first_stage_model.decoder.up.2.block.1.norm1.weight": "blocks.8.norm1.weight",
288
+ "first_stage_model.decoder.up.2.block.1.norm2.bias": "blocks.8.norm2.bias",
289
+ "first_stage_model.decoder.up.2.block.1.norm2.weight": "blocks.8.norm2.weight",
290
+ "first_stage_model.decoder.up.2.block.2.conv1.bias": "blocks.9.conv1.bias",
291
+ "first_stage_model.decoder.up.2.block.2.conv1.weight": "blocks.9.conv1.weight",
292
+ "first_stage_model.decoder.up.2.block.2.conv2.bias": "blocks.9.conv2.bias",
293
+ "first_stage_model.decoder.up.2.block.2.conv2.weight": "blocks.9.conv2.weight",
294
+ "first_stage_model.decoder.up.2.block.2.norm1.bias": "blocks.9.norm1.bias",
295
+ "first_stage_model.decoder.up.2.block.2.norm1.weight": "blocks.9.norm1.weight",
296
+ "first_stage_model.decoder.up.2.block.2.norm2.bias": "blocks.9.norm2.bias",
297
+ "first_stage_model.decoder.up.2.block.2.norm2.weight": "blocks.9.norm2.weight",
298
+ "first_stage_model.decoder.up.2.upsample.conv.bias": "blocks.10.conv.bias",
299
+ "first_stage_model.decoder.up.2.upsample.conv.weight": "blocks.10.conv.weight",
300
+ "first_stage_model.decoder.up.3.block.0.conv1.bias": "blocks.3.conv1.bias",
301
+ "first_stage_model.decoder.up.3.block.0.conv1.weight": "blocks.3.conv1.weight",
302
+ "first_stage_model.decoder.up.3.block.0.conv2.bias": "blocks.3.conv2.bias",
303
+ "first_stage_model.decoder.up.3.block.0.conv2.weight": "blocks.3.conv2.weight",
304
+ "first_stage_model.decoder.up.3.block.0.norm1.bias": "blocks.3.norm1.bias",
305
+ "first_stage_model.decoder.up.3.block.0.norm1.weight": "blocks.3.norm1.weight",
306
+ "first_stage_model.decoder.up.3.block.0.norm2.bias": "blocks.3.norm2.bias",
307
+ "first_stage_model.decoder.up.3.block.0.norm2.weight": "blocks.3.norm2.weight",
308
+ "first_stage_model.decoder.up.3.block.1.conv1.bias": "blocks.4.conv1.bias",
309
+ "first_stage_model.decoder.up.3.block.1.conv1.weight": "blocks.4.conv1.weight",
310
+ "first_stage_model.decoder.up.3.block.1.conv2.bias": "blocks.4.conv2.bias",
311
+ "first_stage_model.decoder.up.3.block.1.conv2.weight": "blocks.4.conv2.weight",
312
+ "first_stage_model.decoder.up.3.block.1.norm1.bias": "blocks.4.norm1.bias",
313
+ "first_stage_model.decoder.up.3.block.1.norm1.weight": "blocks.4.norm1.weight",
314
+ "first_stage_model.decoder.up.3.block.1.norm2.bias": "blocks.4.norm2.bias",
315
+ "first_stage_model.decoder.up.3.block.1.norm2.weight": "blocks.4.norm2.weight",
316
+ "first_stage_model.decoder.up.3.block.2.conv1.bias": "blocks.5.conv1.bias",
317
+ "first_stage_model.decoder.up.3.block.2.conv1.weight": "blocks.5.conv1.weight",
318
+ "first_stage_model.decoder.up.3.block.2.conv2.bias": "blocks.5.conv2.bias",
319
+ "first_stage_model.decoder.up.3.block.2.conv2.weight": "blocks.5.conv2.weight",
320
+ "first_stage_model.decoder.up.3.block.2.norm1.bias": "blocks.5.norm1.bias",
321
+ "first_stage_model.decoder.up.3.block.2.norm1.weight": "blocks.5.norm1.weight",
322
+ "first_stage_model.decoder.up.3.block.2.norm2.bias": "blocks.5.norm2.bias",
323
+ "first_stage_model.decoder.up.3.block.2.norm2.weight": "blocks.5.norm2.weight",
324
+ "first_stage_model.decoder.up.3.upsample.conv.bias": "blocks.6.conv.bias",
325
+ "first_stage_model.decoder.up.3.upsample.conv.weight": "blocks.6.conv.weight",
326
+ "first_stage_model.post_quant_conv.bias": "post_quant_conv.bias",
327
+ "first_stage_model.post_quant_conv.weight": "post_quant_conv.weight",
328
+ }
329
+ state_dict_ = {}
330
+ for name in state_dict:
331
+ if name in rename_dict:
332
+ param = state_dict[name]
333
+ if "transformer_blocks" in rename_dict[name]:
334
+ param = param.squeeze()
335
+ state_dict_[rename_dict[name]] = param
336
+ return state_dict_
sd_vae_encoder.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_unet import ResnetBlock, DownSampler
3
+ from .sd_vae_decoder import VAEAttentionBlock
4
+ from .tiler import TileWorker
5
+ from einops import rearrange
6
+
7
+
8
+ class SDVAEEncoder(torch.nn.Module):
9
+ def __init__(self):
10
+ super().__init__()
11
+ self.scaling_factor = 0.18215
12
+ self.quant_conv = torch.nn.Conv2d(8, 8, kernel_size=1)
13
+ self.conv_in = torch.nn.Conv2d(3, 128, kernel_size=3, padding=1)
14
+
15
+ self.blocks = torch.nn.ModuleList([
16
+ # DownEncoderBlock2D
17
+ ResnetBlock(128, 128, eps=1e-6),
18
+ ResnetBlock(128, 128, eps=1e-6),
19
+ DownSampler(128, padding=0, extra_padding=True),
20
+ # DownEncoderBlock2D
21
+ ResnetBlock(128, 256, eps=1e-6),
22
+ ResnetBlock(256, 256, eps=1e-6),
23
+ DownSampler(256, padding=0, extra_padding=True),
24
+ # DownEncoderBlock2D
25
+ ResnetBlock(256, 512, eps=1e-6),
26
+ ResnetBlock(512, 512, eps=1e-6),
27
+ DownSampler(512, padding=0, extra_padding=True),
28
+ # DownEncoderBlock2D
29
+ ResnetBlock(512, 512, eps=1e-6),
30
+ ResnetBlock(512, 512, eps=1e-6),
31
+ # UNetMidBlock2D
32
+ ResnetBlock(512, 512, eps=1e-6),
33
+ VAEAttentionBlock(1, 512, 512, 1, eps=1e-6),
34
+ ResnetBlock(512, 512, eps=1e-6),
35
+ ])
36
+
37
+ self.conv_norm_out = torch.nn.GroupNorm(num_channels=512, num_groups=32, eps=1e-6)
38
+ self.conv_act = torch.nn.SiLU()
39
+ self.conv_out = torch.nn.Conv2d(512, 8, kernel_size=3, padding=1)
40
+
41
+ def tiled_forward(self, sample, tile_size=64, tile_stride=32):
42
+ hidden_states = TileWorker().tiled_forward(
43
+ lambda x: self.forward(x),
44
+ sample,
45
+ tile_size,
46
+ tile_stride,
47
+ tile_device=sample.device,
48
+ tile_dtype=sample.dtype
49
+ )
50
+ return hidden_states
51
+
52
+ def forward(self, sample, tiled=False, tile_size=64, tile_stride=32, **kwargs):
53
+ original_dtype = sample.dtype
54
+ sample = sample.to(dtype=next(iter(self.parameters())).dtype)
55
+ # For VAE Decoder, we do not need to apply the tiler on each layer.
56
+ if tiled:
57
+ return self.tiled_forward(sample, tile_size=tile_size, tile_stride=tile_stride)
58
+
59
+ # 1. pre-process
60
+ hidden_states = self.conv_in(sample)
61
+ time_emb = None
62
+ text_emb = None
63
+ res_stack = None
64
+
65
+ # 2. blocks
66
+ for i, block in enumerate(self.blocks):
67
+ hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)
68
+
69
+ # 3. output
70
+ hidden_states = self.conv_norm_out(hidden_states)
71
+ hidden_states = self.conv_act(hidden_states)
72
+ hidden_states = self.conv_out(hidden_states)
73
+ hidden_states = self.quant_conv(hidden_states)
74
+ hidden_states = hidden_states[:, :4]
75
+ hidden_states *= self.scaling_factor
76
+ hidden_states = hidden_states.to(original_dtype)
77
+
78
+ return hidden_states
79
+
80
+ def encode_video(self, sample, batch_size=8):
81
+ B = sample.shape[0]
82
+ hidden_states = []
83
+
84
+ for i in range(0, sample.shape[2], batch_size):
85
+
86
+ j = min(i + batch_size, sample.shape[2])
87
+ sample_batch = rearrange(sample[:,:,i:j], "B C T H W -> (B T) C H W")
88
+
89
+ hidden_states_batch = self(sample_batch)
90
+ hidden_states_batch = rearrange(hidden_states_batch, "(B T) C H W -> B C T H W", B=B)
91
+
92
+ hidden_states.append(hidden_states_batch)
93
+
94
+ hidden_states = torch.concat(hidden_states, dim=2)
95
+ return hidden_states
96
+
97
+ @staticmethod
98
+ def state_dict_converter():
99
+ return SDVAEEncoderStateDictConverter()
100
+
101
+
102
+ class SDVAEEncoderStateDictConverter:
103
+ def __init__(self):
104
+ pass
105
+
106
+ def from_diffusers(self, state_dict):
107
+ # architecture
108
+ block_types = [
109
+ 'ResnetBlock', 'ResnetBlock', 'DownSampler',
110
+ 'ResnetBlock', 'ResnetBlock', 'DownSampler',
111
+ 'ResnetBlock', 'ResnetBlock', 'DownSampler',
112
+ 'ResnetBlock', 'ResnetBlock',
113
+ 'ResnetBlock', 'VAEAttentionBlock', 'ResnetBlock'
114
+ ]
115
+
116
+ # Rename each parameter
117
+ local_rename_dict = {
118
+ "quant_conv": "quant_conv",
119
+ "encoder.conv_in": "conv_in",
120
+ "encoder.mid_block.attentions.0.group_norm": "blocks.12.norm",
121
+ "encoder.mid_block.attentions.0.to_q": "blocks.12.transformer_blocks.0.to_q",
122
+ "encoder.mid_block.attentions.0.to_k": "blocks.12.transformer_blocks.0.to_k",
123
+ "encoder.mid_block.attentions.0.to_v": "blocks.12.transformer_blocks.0.to_v",
124
+ "encoder.mid_block.attentions.0.to_out.0": "blocks.12.transformer_blocks.0.to_out",
125
+ "encoder.mid_block.resnets.0.norm1": "blocks.11.norm1",
126
+ "encoder.mid_block.resnets.0.conv1": "blocks.11.conv1",
127
+ "encoder.mid_block.resnets.0.norm2": "blocks.11.norm2",
128
+ "encoder.mid_block.resnets.0.conv2": "blocks.11.conv2",
129
+ "encoder.mid_block.resnets.1.norm1": "blocks.13.norm1",
130
+ "encoder.mid_block.resnets.1.conv1": "blocks.13.conv1",
131
+ "encoder.mid_block.resnets.1.norm2": "blocks.13.norm2",
132
+ "encoder.mid_block.resnets.1.conv2": "blocks.13.conv2",
133
+ "encoder.conv_norm_out": "conv_norm_out",
134
+ "encoder.conv_out": "conv_out",
135
+ }
136
+ name_list = sorted([name for name in state_dict])
137
+ rename_dict = {}
138
+ block_id = {"ResnetBlock": -1, "DownSampler": -1, "UpSampler": -1}
139
+ last_block_type_with_id = {"ResnetBlock": "", "DownSampler": "", "UpSampler": ""}
140
+ for name in name_list:
141
+ names = name.split(".")
142
+ name_prefix = ".".join(names[:-1])
143
+ if name_prefix in local_rename_dict:
144
+ rename_dict[name] = local_rename_dict[name_prefix] + "." + names[-1]
145
+ elif name.startswith("encoder.down_blocks"):
146
+ block_type = {"resnets": "ResnetBlock", "downsamplers": "DownSampler", "upsamplers": "UpSampler"}[names[3]]
147
+ block_type_with_id = ".".join(names[:5])
148
+ if block_type_with_id != last_block_type_with_id[block_type]:
149
+ block_id[block_type] += 1
150
+ last_block_type_with_id[block_type] = block_type_with_id
151
+ while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:
152
+ block_id[block_type] += 1
153
+ block_type_with_id = ".".join(names[:5])
154
+ names = ["blocks", str(block_id[block_type])] + names[5:]
155
+ rename_dict[name] = ".".join(names)
156
+
157
+ # Convert state_dict
158
+ state_dict_ = {}
159
+ for name, param in state_dict.items():
160
+ if name in rename_dict:
161
+ state_dict_[rename_dict[name]] = param
162
+ return state_dict_
163
+
164
+ def from_civitai(self, state_dict):
165
+ rename_dict = {
166
+ "first_stage_model.encoder.conv_in.bias": "conv_in.bias",
167
+ "first_stage_model.encoder.conv_in.weight": "conv_in.weight",
168
+ "first_stage_model.encoder.conv_out.bias": "conv_out.bias",
169
+ "first_stage_model.encoder.conv_out.weight": "conv_out.weight",
170
+ "first_stage_model.encoder.down.0.block.0.conv1.bias": "blocks.0.conv1.bias",
171
+ "first_stage_model.encoder.down.0.block.0.conv1.weight": "blocks.0.conv1.weight",
172
+ "first_stage_model.encoder.down.0.block.0.conv2.bias": "blocks.0.conv2.bias",
173
+ "first_stage_model.encoder.down.0.block.0.conv2.weight": "blocks.0.conv2.weight",
174
+ "first_stage_model.encoder.down.0.block.0.norm1.bias": "blocks.0.norm1.bias",
175
+ "first_stage_model.encoder.down.0.block.0.norm1.weight": "blocks.0.norm1.weight",
176
+ "first_stage_model.encoder.down.0.block.0.norm2.bias": "blocks.0.norm2.bias",
177
+ "first_stage_model.encoder.down.0.block.0.norm2.weight": "blocks.0.norm2.weight",
178
+ "first_stage_model.encoder.down.0.block.1.conv1.bias": "blocks.1.conv1.bias",
179
+ "first_stage_model.encoder.down.0.block.1.conv1.weight": "blocks.1.conv1.weight",
180
+ "first_stage_model.encoder.down.0.block.1.conv2.bias": "blocks.1.conv2.bias",
181
+ "first_stage_model.encoder.down.0.block.1.conv2.weight": "blocks.1.conv2.weight",
182
+ "first_stage_model.encoder.down.0.block.1.norm1.bias": "blocks.1.norm1.bias",
183
+ "first_stage_model.encoder.down.0.block.1.norm1.weight": "blocks.1.norm1.weight",
184
+ "first_stage_model.encoder.down.0.block.1.norm2.bias": "blocks.1.norm2.bias",
185
+ "first_stage_model.encoder.down.0.block.1.norm2.weight": "blocks.1.norm2.weight",
186
+ "first_stage_model.encoder.down.0.downsample.conv.bias": "blocks.2.conv.bias",
187
+ "first_stage_model.encoder.down.0.downsample.conv.weight": "blocks.2.conv.weight",
188
+ "first_stage_model.encoder.down.1.block.0.conv1.bias": "blocks.3.conv1.bias",
189
+ "first_stage_model.encoder.down.1.block.0.conv1.weight": "blocks.3.conv1.weight",
190
+ "first_stage_model.encoder.down.1.block.0.conv2.bias": "blocks.3.conv2.bias",
191
+ "first_stage_model.encoder.down.1.block.0.conv2.weight": "blocks.3.conv2.weight",
192
+ "first_stage_model.encoder.down.1.block.0.nin_shortcut.bias": "blocks.3.conv_shortcut.bias",
193
+ "first_stage_model.encoder.down.1.block.0.nin_shortcut.weight": "blocks.3.conv_shortcut.weight",
194
+ "first_stage_model.encoder.down.1.block.0.norm1.bias": "blocks.3.norm1.bias",
195
+ "first_stage_model.encoder.down.1.block.0.norm1.weight": "blocks.3.norm1.weight",
196
+ "first_stage_model.encoder.down.1.block.0.norm2.bias": "blocks.3.norm2.bias",
197
+ "first_stage_model.encoder.down.1.block.0.norm2.weight": "blocks.3.norm2.weight",
198
+ "first_stage_model.encoder.down.1.block.1.conv1.bias": "blocks.4.conv1.bias",
199
+ "first_stage_model.encoder.down.1.block.1.conv1.weight": "blocks.4.conv1.weight",
200
+ "first_stage_model.encoder.down.1.block.1.conv2.bias": "blocks.4.conv2.bias",
201
+ "first_stage_model.encoder.down.1.block.1.conv2.weight": "blocks.4.conv2.weight",
202
+ "first_stage_model.encoder.down.1.block.1.norm1.bias": "blocks.4.norm1.bias",
203
+ "first_stage_model.encoder.down.1.block.1.norm1.weight": "blocks.4.norm1.weight",
204
+ "first_stage_model.encoder.down.1.block.1.norm2.bias": "blocks.4.norm2.bias",
205
+ "first_stage_model.encoder.down.1.block.1.norm2.weight": "blocks.4.norm2.weight",
206
+ "first_stage_model.encoder.down.1.downsample.conv.bias": "blocks.5.conv.bias",
207
+ "first_stage_model.encoder.down.1.downsample.conv.weight": "blocks.5.conv.weight",
208
+ "first_stage_model.encoder.down.2.block.0.conv1.bias": "blocks.6.conv1.bias",
209
+ "first_stage_model.encoder.down.2.block.0.conv1.weight": "blocks.6.conv1.weight",
210
+ "first_stage_model.encoder.down.2.block.0.conv2.bias": "blocks.6.conv2.bias",
211
+ "first_stage_model.encoder.down.2.block.0.conv2.weight": "blocks.6.conv2.weight",
212
+ "first_stage_model.encoder.down.2.block.0.nin_shortcut.bias": "blocks.6.conv_shortcut.bias",
213
+ "first_stage_model.encoder.down.2.block.0.nin_shortcut.weight": "blocks.6.conv_shortcut.weight",
214
+ "first_stage_model.encoder.down.2.block.0.norm1.bias": "blocks.6.norm1.bias",
215
+ "first_stage_model.encoder.down.2.block.0.norm1.weight": "blocks.6.norm1.weight",
216
+ "first_stage_model.encoder.down.2.block.0.norm2.bias": "blocks.6.norm2.bias",
217
+ "first_stage_model.encoder.down.2.block.0.norm2.weight": "blocks.6.norm2.weight",
218
+ "first_stage_model.encoder.down.2.block.1.conv1.bias": "blocks.7.conv1.bias",
219
+ "first_stage_model.encoder.down.2.block.1.conv1.weight": "blocks.7.conv1.weight",
220
+ "first_stage_model.encoder.down.2.block.1.conv2.bias": "blocks.7.conv2.bias",
221
+ "first_stage_model.encoder.down.2.block.1.conv2.weight": "blocks.7.conv2.weight",
222
+ "first_stage_model.encoder.down.2.block.1.norm1.bias": "blocks.7.norm1.bias",
223
+ "first_stage_model.encoder.down.2.block.1.norm1.weight": "blocks.7.norm1.weight",
224
+ "first_stage_model.encoder.down.2.block.1.norm2.bias": "blocks.7.norm2.bias",
225
+ "first_stage_model.encoder.down.2.block.1.norm2.weight": "blocks.7.norm2.weight",
226
+ "first_stage_model.encoder.down.2.downsample.conv.bias": "blocks.8.conv.bias",
227
+ "first_stage_model.encoder.down.2.downsample.conv.weight": "blocks.8.conv.weight",
228
+ "first_stage_model.encoder.down.3.block.0.conv1.bias": "blocks.9.conv1.bias",
229
+ "first_stage_model.encoder.down.3.block.0.conv1.weight": "blocks.9.conv1.weight",
230
+ "first_stage_model.encoder.down.3.block.0.conv2.bias": "blocks.9.conv2.bias",
231
+ "first_stage_model.encoder.down.3.block.0.conv2.weight": "blocks.9.conv2.weight",
232
+ "first_stage_model.encoder.down.3.block.0.norm1.bias": "blocks.9.norm1.bias",
233
+ "first_stage_model.encoder.down.3.block.0.norm1.weight": "blocks.9.norm1.weight",
234
+ "first_stage_model.encoder.down.3.block.0.norm2.bias": "blocks.9.norm2.bias",
235
+ "first_stage_model.encoder.down.3.block.0.norm2.weight": "blocks.9.norm2.weight",
236
+ "first_stage_model.encoder.down.3.block.1.conv1.bias": "blocks.10.conv1.bias",
237
+ "first_stage_model.encoder.down.3.block.1.conv1.weight": "blocks.10.conv1.weight",
238
+ "first_stage_model.encoder.down.3.block.1.conv2.bias": "blocks.10.conv2.bias",
239
+ "first_stage_model.encoder.down.3.block.1.conv2.weight": "blocks.10.conv2.weight",
240
+ "first_stage_model.encoder.down.3.block.1.norm1.bias": "blocks.10.norm1.bias",
241
+ "first_stage_model.encoder.down.3.block.1.norm1.weight": "blocks.10.norm1.weight",
242
+ "first_stage_model.encoder.down.3.block.1.norm2.bias": "blocks.10.norm2.bias",
243
+ "first_stage_model.encoder.down.3.block.1.norm2.weight": "blocks.10.norm2.weight",
244
+ "first_stage_model.encoder.mid.attn_1.k.bias": "blocks.12.transformer_blocks.0.to_k.bias",
245
+ "first_stage_model.encoder.mid.attn_1.k.weight": "blocks.12.transformer_blocks.0.to_k.weight",
246
+ "first_stage_model.encoder.mid.attn_1.norm.bias": "blocks.12.norm.bias",
247
+ "first_stage_model.encoder.mid.attn_1.norm.weight": "blocks.12.norm.weight",
248
+ "first_stage_model.encoder.mid.attn_1.proj_out.bias": "blocks.12.transformer_blocks.0.to_out.bias",
249
+ "first_stage_model.encoder.mid.attn_1.proj_out.weight": "blocks.12.transformer_blocks.0.to_out.weight",
250
+ "first_stage_model.encoder.mid.attn_1.q.bias": "blocks.12.transformer_blocks.0.to_q.bias",
251
+ "first_stage_model.encoder.mid.attn_1.q.weight": "blocks.12.transformer_blocks.0.to_q.weight",
252
+ "first_stage_model.encoder.mid.attn_1.v.bias": "blocks.12.transformer_blocks.0.to_v.bias",
253
+ "first_stage_model.encoder.mid.attn_1.v.weight": "blocks.12.transformer_blocks.0.to_v.weight",
254
+ "first_stage_model.encoder.mid.block_1.conv1.bias": "blocks.11.conv1.bias",
255
+ "first_stage_model.encoder.mid.block_1.conv1.weight": "blocks.11.conv1.weight",
256
+ "first_stage_model.encoder.mid.block_1.conv2.bias": "blocks.11.conv2.bias",
257
+ "first_stage_model.encoder.mid.block_1.conv2.weight": "blocks.11.conv2.weight",
258
+ "first_stage_model.encoder.mid.block_1.norm1.bias": "blocks.11.norm1.bias",
259
+ "first_stage_model.encoder.mid.block_1.norm1.weight": "blocks.11.norm1.weight",
260
+ "first_stage_model.encoder.mid.block_1.norm2.bias": "blocks.11.norm2.bias",
261
+ "first_stage_model.encoder.mid.block_1.norm2.weight": "blocks.11.norm2.weight",
262
+ "first_stage_model.encoder.mid.block_2.conv1.bias": "blocks.13.conv1.bias",
263
+ "first_stage_model.encoder.mid.block_2.conv1.weight": "blocks.13.conv1.weight",
264
+ "first_stage_model.encoder.mid.block_2.conv2.bias": "blocks.13.conv2.bias",
265
+ "first_stage_model.encoder.mid.block_2.conv2.weight": "blocks.13.conv2.weight",
266
+ "first_stage_model.encoder.mid.block_2.norm1.bias": "blocks.13.norm1.bias",
267
+ "first_stage_model.encoder.mid.block_2.norm1.weight": "blocks.13.norm1.weight",
268
+ "first_stage_model.encoder.mid.block_2.norm2.bias": "blocks.13.norm2.bias",
269
+ "first_stage_model.encoder.mid.block_2.norm2.weight": "blocks.13.norm2.weight",
270
+ "first_stage_model.encoder.norm_out.bias": "conv_norm_out.bias",
271
+ "first_stage_model.encoder.norm_out.weight": "conv_norm_out.weight",
272
+ "first_stage_model.quant_conv.bias": "quant_conv.bias",
273
+ "first_stage_model.quant_conv.weight": "quant_conv.weight",
274
+ }
275
+ state_dict_ = {}
276
+ for name in state_dict:
277
+ if name in rename_dict:
278
+ param = state_dict[name]
279
+ if "transformer_blocks" in rename_dict[name]:
280
+ param = param.squeeze()
281
+ state_dict_[rename_dict[name]] = param
282
+ return state_dict_
sdxl_controlnet.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_unet import Timesteps, ResnetBlock, AttentionBlock, PushBlock, DownSampler
3
+ from .sdxl_unet import SDXLUNet
4
+ from .tiler import TileWorker
5
+ from .sd_controlnet import ControlNetConditioningLayer
6
+ from collections import OrderedDict
7
+
8
+
9
+
10
+ class QuickGELU(torch.nn.Module):
11
+
12
+ def forward(self, x: torch.Tensor):
13
+ return x * torch.sigmoid(1.702 * x)
14
+
15
+
16
+
17
+ class ResidualAttentionBlock(torch.nn.Module):
18
+
19
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
20
+ super().__init__()
21
+
22
+ self.attn = torch.nn.MultiheadAttention(d_model, n_head)
23
+ self.ln_1 = torch.nn.LayerNorm(d_model)
24
+ self.mlp = torch.nn.Sequential(OrderedDict([
25
+ ("c_fc", torch.nn.Linear(d_model, d_model * 4)),
26
+ ("gelu", QuickGELU()),
27
+ ("c_proj", torch.nn.Linear(d_model * 4, d_model))
28
+ ]))
29
+ self.ln_2 = torch.nn.LayerNorm(d_model)
30
+ self.attn_mask = attn_mask
31
+
32
+ def attention(self, x: torch.Tensor):
33
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
34
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
35
+
36
+ def forward(self, x: torch.Tensor):
37
+ x = x + self.attention(self.ln_1(x))
38
+ x = x + self.mlp(self.ln_2(x))
39
+ return x
40
+
41
+
42
+
43
+ class SDXLControlNetUnion(torch.nn.Module):
44
+ def __init__(self, global_pool=False):
45
+ super().__init__()
46
+ self.time_proj = Timesteps(320)
47
+ self.time_embedding = torch.nn.Sequential(
48
+ torch.nn.Linear(320, 1280),
49
+ torch.nn.SiLU(),
50
+ torch.nn.Linear(1280, 1280)
51
+ )
52
+ self.add_time_proj = Timesteps(256)
53
+ self.add_time_embedding = torch.nn.Sequential(
54
+ torch.nn.Linear(2816, 1280),
55
+ torch.nn.SiLU(),
56
+ torch.nn.Linear(1280, 1280)
57
+ )
58
+ self.control_type_proj = Timesteps(256)
59
+ self.control_type_embedding = torch.nn.Sequential(
60
+ torch.nn.Linear(256 * 8, 1280),
61
+ torch.nn.SiLU(),
62
+ torch.nn.Linear(1280, 1280)
63
+ )
64
+ self.conv_in = torch.nn.Conv2d(4, 320, kernel_size=3, padding=1)
65
+
66
+ self.controlnet_conv_in = ControlNetConditioningLayer(channels=(3, 16, 32, 96, 256, 320))
67
+ self.controlnet_transformer = ResidualAttentionBlock(320, 8)
68
+ self.task_embedding = torch.nn.Parameter(torch.randn(8, 320))
69
+ self.spatial_ch_projs = torch.nn.Linear(320, 320)
70
+
71
+ self.blocks = torch.nn.ModuleList([
72
+ # DownBlock2D
73
+ ResnetBlock(320, 320, 1280),
74
+ PushBlock(),
75
+ ResnetBlock(320, 320, 1280),
76
+ PushBlock(),
77
+ DownSampler(320),
78
+ PushBlock(),
79
+ # CrossAttnDownBlock2D
80
+ ResnetBlock(320, 640, 1280),
81
+ AttentionBlock(10, 64, 640, 2, 2048),
82
+ PushBlock(),
83
+ ResnetBlock(640, 640, 1280),
84
+ AttentionBlock(10, 64, 640, 2, 2048),
85
+ PushBlock(),
86
+ DownSampler(640),
87
+ PushBlock(),
88
+ # CrossAttnDownBlock2D
89
+ ResnetBlock(640, 1280, 1280),
90
+ AttentionBlock(20, 64, 1280, 10, 2048),
91
+ PushBlock(),
92
+ ResnetBlock(1280, 1280, 1280),
93
+ AttentionBlock(20, 64, 1280, 10, 2048),
94
+ PushBlock(),
95
+ # UNetMidBlock2DCrossAttn
96
+ ResnetBlock(1280, 1280, 1280),
97
+ AttentionBlock(20, 64, 1280, 10, 2048),
98
+ ResnetBlock(1280, 1280, 1280),
99
+ PushBlock()
100
+ ])
101
+
102
+ self.controlnet_blocks = torch.nn.ModuleList([
103
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1)),
104
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1)),
105
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1)),
106
+ torch.nn.Conv2d(320, 320, kernel_size=(1, 1)),
107
+ torch.nn.Conv2d(640, 640, kernel_size=(1, 1)),
108
+ torch.nn.Conv2d(640, 640, kernel_size=(1, 1)),
109
+ torch.nn.Conv2d(640, 640, kernel_size=(1, 1)),
110
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1)),
111
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1)),
112
+ torch.nn.Conv2d(1280, 1280, kernel_size=(1, 1)),
113
+ ])
114
+
115
+ self.global_pool = global_pool
116
+
117
+ # 0 -- openpose
118
+ # 1 -- depth
119
+ # 2 -- hed/pidi/scribble/ted
120
+ # 3 -- canny/lineart/anime_lineart/mlsd
121
+ # 4 -- normal
122
+ # 5 -- segment
123
+ # 6 -- tile
124
+ # 7 -- repaint
125
+ self.task_id = {
126
+ "openpose": 0,
127
+ "depth": 1,
128
+ "softedge": 2,
129
+ "canny": 3,
130
+ "lineart": 3,
131
+ "lineart_anime": 3,
132
+ "tile": 6,
133
+ "inpaint": 7
134
+ }
135
+
136
+
137
+ def fuse_condition_to_input(self, hidden_states, task_id, conditioning):
138
+ controlnet_cond = self.controlnet_conv_in(conditioning)
139
+ feat_seq = torch.mean(controlnet_cond, dim=(2, 3))
140
+ feat_seq = feat_seq + self.task_embedding[task_id]
141
+ x = torch.stack([feat_seq, torch.mean(hidden_states, dim=(2, 3))], dim=1)
142
+ x = self.controlnet_transformer(x)
143
+
144
+ alpha = self.spatial_ch_projs(x[:,0]).unsqueeze(-1).unsqueeze(-1)
145
+ controlnet_cond_fuser = controlnet_cond + alpha
146
+
147
+ hidden_states = hidden_states + controlnet_cond_fuser
148
+ return hidden_states
149
+
150
+
151
+ def forward(
152
+ self,
153
+ sample, timestep, encoder_hidden_states,
154
+ conditioning, processor_id, add_time_id, add_text_embeds,
155
+ tiled=False, tile_size=64, tile_stride=32,
156
+ unet:SDXLUNet=None,
157
+ **kwargs
158
+ ):
159
+ task_id = self.task_id[processor_id]
160
+
161
+ # 1. time
162
+ t_emb = self.time_proj(timestep).to(sample.dtype)
163
+ t_emb = self.time_embedding(t_emb)
164
+
165
+ time_embeds = self.add_time_proj(add_time_id)
166
+ time_embeds = time_embeds.reshape((add_text_embeds.shape[0], -1))
167
+ add_embeds = torch.concat([add_text_embeds, time_embeds], dim=-1)
168
+ add_embeds = add_embeds.to(sample.dtype)
169
+ if unet is not None and unet.is_kolors:
170
+ add_embeds = unet.add_time_embedding(add_embeds)
171
+ else:
172
+ add_embeds = self.add_time_embedding(add_embeds)
173
+
174
+ control_type = torch.zeros((sample.shape[0], 8), dtype=sample.dtype, device=sample.device)
175
+ control_type[:, task_id] = 1
176
+ control_embeds = self.control_type_proj(control_type.flatten())
177
+ control_embeds = control_embeds.reshape((sample.shape[0], -1))
178
+ control_embeds = control_embeds.to(sample.dtype)
179
+ control_embeds = self.control_type_embedding(control_embeds)
180
+ time_emb = t_emb + add_embeds + control_embeds
181
+
182
+ # 2. pre-process
183
+ height, width = sample.shape[2], sample.shape[3]
184
+ hidden_states = self.conv_in(sample)
185
+ hidden_states = self.fuse_condition_to_input(hidden_states, task_id, conditioning)
186
+ text_emb = encoder_hidden_states
187
+ if unet is not None and unet.is_kolors:
188
+ text_emb = unet.text_intermediate_proj(text_emb)
189
+ res_stack = [hidden_states]
190
+
191
+ # 3. blocks
192
+ for i, block in enumerate(self.blocks):
193
+ if tiled and not isinstance(block, PushBlock):
194
+ _, _, inter_height, _ = hidden_states.shape
195
+ resize_scale = inter_height / height
196
+ hidden_states = TileWorker().tiled_forward(
197
+ lambda x: block(x, time_emb, text_emb, res_stack)[0],
198
+ hidden_states,
199
+ int(tile_size * resize_scale),
200
+ int(tile_stride * resize_scale),
201
+ tile_device=hidden_states.device,
202
+ tile_dtype=hidden_states.dtype
203
+ )
204
+ else:
205
+ hidden_states, _, _, _ = block(hidden_states, time_emb, text_emb, res_stack)
206
+
207
+ # 4. ControlNet blocks
208
+ controlnet_res_stack = [block(res) for block, res in zip(self.controlnet_blocks, res_stack)]
209
+
210
+ # pool
211
+ if self.global_pool:
212
+ controlnet_res_stack = [res.mean(dim=(2, 3), keepdim=True) for res in controlnet_res_stack]
213
+
214
+ return controlnet_res_stack
215
+
216
+ @staticmethod
217
+ def state_dict_converter():
218
+ return SDXLControlNetUnionStateDictConverter()
219
+
220
+
221
+
222
+ class SDXLControlNetUnionStateDictConverter:
223
+ def __init__(self):
224
+ pass
225
+
226
+ def from_diffusers(self, state_dict):
227
+ # architecture
228
+ block_types = [
229
+ "ResnetBlock", "PushBlock", "ResnetBlock", "PushBlock", "DownSampler", "PushBlock",
230
+ "ResnetBlock", "AttentionBlock", "PushBlock", "ResnetBlock", "AttentionBlock", "PushBlock", "DownSampler", "PushBlock",
231
+ "ResnetBlock", "AttentionBlock", "PushBlock", "ResnetBlock", "AttentionBlock", "PushBlock",
232
+ "ResnetBlock", "AttentionBlock", "ResnetBlock", "PushBlock"
233
+ ]
234
+
235
+ # controlnet_rename_dict
236
+ controlnet_rename_dict = {
237
+ "controlnet_cond_embedding.conv_in.weight": "controlnet_conv_in.blocks.0.weight",
238
+ "controlnet_cond_embedding.conv_in.bias": "controlnet_conv_in.blocks.0.bias",
239
+ "controlnet_cond_embedding.blocks.0.weight": "controlnet_conv_in.blocks.2.weight",
240
+ "controlnet_cond_embedding.blocks.0.bias": "controlnet_conv_in.blocks.2.bias",
241
+ "controlnet_cond_embedding.blocks.1.weight": "controlnet_conv_in.blocks.4.weight",
242
+ "controlnet_cond_embedding.blocks.1.bias": "controlnet_conv_in.blocks.4.bias",
243
+ "controlnet_cond_embedding.blocks.2.weight": "controlnet_conv_in.blocks.6.weight",
244
+ "controlnet_cond_embedding.blocks.2.bias": "controlnet_conv_in.blocks.6.bias",
245
+ "controlnet_cond_embedding.blocks.3.weight": "controlnet_conv_in.blocks.8.weight",
246
+ "controlnet_cond_embedding.blocks.3.bias": "controlnet_conv_in.blocks.8.bias",
247
+ "controlnet_cond_embedding.blocks.4.weight": "controlnet_conv_in.blocks.10.weight",
248
+ "controlnet_cond_embedding.blocks.4.bias": "controlnet_conv_in.blocks.10.bias",
249
+ "controlnet_cond_embedding.blocks.5.weight": "controlnet_conv_in.blocks.12.weight",
250
+ "controlnet_cond_embedding.blocks.5.bias": "controlnet_conv_in.blocks.12.bias",
251
+ "controlnet_cond_embedding.conv_out.weight": "controlnet_conv_in.blocks.14.weight",
252
+ "controlnet_cond_embedding.conv_out.bias": "controlnet_conv_in.blocks.14.bias",
253
+ "control_add_embedding.linear_1.weight": "control_type_embedding.0.weight",
254
+ "control_add_embedding.linear_1.bias": "control_type_embedding.0.bias",
255
+ "control_add_embedding.linear_2.weight": "control_type_embedding.2.weight",
256
+ "control_add_embedding.linear_2.bias": "control_type_embedding.2.bias",
257
+ }
258
+
259
+ # Rename each parameter
260
+ name_list = sorted([name for name in state_dict])
261
+ rename_dict = {}
262
+ block_id = {"ResnetBlock": -1, "AttentionBlock": -1, "DownSampler": -1, "UpSampler": -1}
263
+ last_block_type_with_id = {"ResnetBlock": "", "AttentionBlock": "", "DownSampler": "", "UpSampler": ""}
264
+ for name in name_list:
265
+ names = name.split(".")
266
+ if names[0] in ["conv_in", "conv_norm_out", "conv_out", "task_embedding", "spatial_ch_projs"]:
267
+ pass
268
+ elif name in controlnet_rename_dict:
269
+ names = controlnet_rename_dict[name].split(".")
270
+ elif names[0] == "controlnet_down_blocks":
271
+ names[0] = "controlnet_blocks"
272
+ elif names[0] == "controlnet_mid_block":
273
+ names = ["controlnet_blocks", "9", names[-1]]
274
+ elif names[0] in ["time_embedding", "add_embedding"]:
275
+ if names[0] == "add_embedding":
276
+ names[0] = "add_time_embedding"
277
+ names[1] = {"linear_1": "0", "linear_2": "2"}[names[1]]
278
+ elif names[0] == "control_add_embedding":
279
+ names[0] = "control_type_embedding"
280
+ elif names[0] == "transformer_layes":
281
+ names[0] = "controlnet_transformer"
282
+ names.pop(1)
283
+ elif names[0] in ["down_blocks", "mid_block", "up_blocks"]:
284
+ if names[0] == "mid_block":
285
+ names.insert(1, "0")
286
+ block_type = {"resnets": "ResnetBlock", "attentions": "AttentionBlock", "downsamplers": "DownSampler", "upsamplers": "UpSampler"}[names[2]]
287
+ block_type_with_id = ".".join(names[:4])
288
+ if block_type_with_id != last_block_type_with_id[block_type]:
289
+ block_id[block_type] += 1
290
+ last_block_type_with_id[block_type] = block_type_with_id
291
+ while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:
292
+ block_id[block_type] += 1
293
+ block_type_with_id = ".".join(names[:4])
294
+ names = ["blocks", str(block_id[block_type])] + names[4:]
295
+ if "ff" in names:
296
+ ff_index = names.index("ff")
297
+ component = ".".join(names[ff_index:ff_index+3])
298
+ component = {"ff.net.0": "act_fn", "ff.net.2": "ff"}[component]
299
+ names = names[:ff_index] + [component] + names[ff_index+3:]
300
+ if "to_out" in names:
301
+ names.pop(names.index("to_out") + 1)
302
+ else:
303
+ print(name, state_dict[name].shape)
304
+ # raise ValueError(f"Unknown parameters: {name}")
305
+ rename_dict[name] = ".".join(names)
306
+
307
+ # Convert state_dict
308
+ state_dict_ = {}
309
+ for name, param in state_dict.items():
310
+ if name not in rename_dict:
311
+ continue
312
+ if ".proj_in." in name or ".proj_out." in name:
313
+ param = param.squeeze()
314
+ state_dict_[rename_dict[name]] = param
315
+ return state_dict_
316
+
317
+ def from_civitai(self, state_dict):
318
+ return self.from_diffusers(state_dict)
sdxl_ipadapter.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .svd_image_encoder import SVDImageEncoder
2
+ from transformers import CLIPImageProcessor
3
+ import torch
4
+
5
+
6
+ class IpAdapterXLCLIPImageEmbedder(SVDImageEncoder):
7
+ def __init__(self):
8
+ super().__init__(embed_dim=1664, encoder_intermediate_size=8192, projection_dim=1280, num_encoder_layers=48, num_heads=16, head_dim=104)
9
+ self.image_processor = CLIPImageProcessor()
10
+
11
+ def forward(self, image):
12
+ pixel_values = self.image_processor(images=image, return_tensors="pt").pixel_values
13
+ pixel_values = pixel_values.to(device=self.embeddings.class_embedding.device, dtype=self.embeddings.class_embedding.dtype)
14
+ return super().forward(pixel_values)
15
+
16
+
17
+ class IpAdapterImageProjModel(torch.nn.Module):
18
+ def __init__(self, cross_attention_dim=2048, clip_embeddings_dim=1280, clip_extra_context_tokens=4):
19
+ super().__init__()
20
+ self.cross_attention_dim = cross_attention_dim
21
+ self.clip_extra_context_tokens = clip_extra_context_tokens
22
+ self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
23
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
24
+
25
+ def forward(self, image_embeds):
26
+ clip_extra_context_tokens = self.proj(image_embeds).reshape(-1, self.clip_extra_context_tokens, self.cross_attention_dim)
27
+ clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
28
+ return clip_extra_context_tokens
29
+
30
+
31
+ class IpAdapterModule(torch.nn.Module):
32
+ def __init__(self, input_dim, output_dim):
33
+ super().__init__()
34
+ self.to_k_ip = torch.nn.Linear(input_dim, output_dim, bias=False)
35
+ self.to_v_ip = torch.nn.Linear(input_dim, output_dim, bias=False)
36
+
37
+ def forward(self, hidden_states):
38
+ ip_k = self.to_k_ip(hidden_states)
39
+ ip_v = self.to_v_ip(hidden_states)
40
+ return ip_k, ip_v
41
+
42
+
43
+ class SDXLIpAdapter(torch.nn.Module):
44
+ def __init__(self):
45
+ super().__init__()
46
+ shape_list = [(2048, 640)] * 4 + [(2048, 1280)] * 50 + [(2048, 640)] * 6 + [(2048, 1280)] * 10
47
+ self.ipadapter_modules = torch.nn.ModuleList([IpAdapterModule(*shape) for shape in shape_list])
48
+ self.image_proj = IpAdapterImageProjModel()
49
+ self.set_full_adapter()
50
+
51
+ def set_full_adapter(self):
52
+ map_list = sum([
53
+ [(7, i) for i in range(2)],
54
+ [(10, i) for i in range(2)],
55
+ [(15, i) for i in range(10)],
56
+ [(18, i) for i in range(10)],
57
+ [(25, i) for i in range(10)],
58
+ [(28, i) for i in range(10)],
59
+ [(31, i) for i in range(10)],
60
+ [(35, i) for i in range(2)],
61
+ [(38, i) for i in range(2)],
62
+ [(41, i) for i in range(2)],
63
+ [(21, i) for i in range(10)],
64
+ ], [])
65
+ self.call_block_id = {i: j for j, i in enumerate(map_list)}
66
+
67
+ def set_less_adapter(self):
68
+ map_list = sum([
69
+ [(7, i) for i in range(2)],
70
+ [(10, i) for i in range(2)],
71
+ [(15, i) for i in range(10)],
72
+ [(18, i) for i in range(10)],
73
+ [(25, i) for i in range(10)],
74
+ [(28, i) for i in range(10)],
75
+ [(31, i) for i in range(10)],
76
+ [(35, i) for i in range(2)],
77
+ [(38, i) for i in range(2)],
78
+ [(41, i) for i in range(2)],
79
+ [(21, i) for i in range(10)],
80
+ ], [])
81
+ self.call_block_id = {i: j for j, i in enumerate(map_list) if j>=34 and j<44}
82
+
83
+ def forward(self, hidden_states, scale=1.0):
84
+ hidden_states = self.image_proj(hidden_states)
85
+ hidden_states = hidden_states.view(1, -1, hidden_states.shape[-1])
86
+ ip_kv_dict = {}
87
+ for (block_id, transformer_id) in self.call_block_id:
88
+ ipadapter_id = self.call_block_id[(block_id, transformer_id)]
89
+ ip_k, ip_v = self.ipadapter_modules[ipadapter_id](hidden_states)
90
+ if block_id not in ip_kv_dict:
91
+ ip_kv_dict[block_id] = {}
92
+ ip_kv_dict[block_id][transformer_id] = {
93
+ "ip_k": ip_k,
94
+ "ip_v": ip_v,
95
+ "scale": scale
96
+ }
97
+ return ip_kv_dict
98
+
99
+ @staticmethod
100
+ def state_dict_converter():
101
+ return SDXLIpAdapterStateDictConverter()
102
+
103
+
104
+ class SDXLIpAdapterStateDictConverter:
105
+ def __init__(self):
106
+ pass
107
+
108
+ def from_diffusers(self, state_dict):
109
+ state_dict_ = {}
110
+ for name in state_dict["ip_adapter"]:
111
+ names = name.split(".")
112
+ layer_id = str(int(names[0]) // 2)
113
+ name_ = ".".join(["ipadapter_modules"] + [layer_id] + names[1:])
114
+ state_dict_[name_] = state_dict["ip_adapter"][name]
115
+ for name in state_dict["image_proj"]:
116
+ name_ = "image_proj." + name
117
+ state_dict_[name_] = state_dict["image_proj"][name]
118
+ return state_dict_
119
+
120
+ def from_civitai(self, state_dict):
121
+ return self.from_diffusers(state_dict)
122
+
sdxl_motion.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .sd_motion import TemporalBlock
2
+ import torch
3
+
4
+
5
+
6
+ class SDXLMotionModel(torch.nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+ self.motion_modules = torch.nn.ModuleList([
10
+ TemporalBlock(8, 320//8, 320, eps=1e-6),
11
+ TemporalBlock(8, 320//8, 320, eps=1e-6),
12
+
13
+ TemporalBlock(8, 640//8, 640, eps=1e-6),
14
+ TemporalBlock(8, 640//8, 640, eps=1e-6),
15
+
16
+ TemporalBlock(8, 1280//8, 1280, eps=1e-6),
17
+ TemporalBlock(8, 1280//8, 1280, eps=1e-6),
18
+
19
+ TemporalBlock(8, 1280//8, 1280, eps=1e-6),
20
+ TemporalBlock(8, 1280//8, 1280, eps=1e-6),
21
+ TemporalBlock(8, 1280//8, 1280, eps=1e-6),
22
+
23
+ TemporalBlock(8, 640//8, 640, eps=1e-6),
24
+ TemporalBlock(8, 640//8, 640, eps=1e-6),
25
+ TemporalBlock(8, 640//8, 640, eps=1e-6),
26
+
27
+ TemporalBlock(8, 320//8, 320, eps=1e-6),
28
+ TemporalBlock(8, 320//8, 320, eps=1e-6),
29
+ TemporalBlock(8, 320//8, 320, eps=1e-6),
30
+ ])
31
+ self.call_block_id = {
32
+ 0: 0,
33
+ 2: 1,
34
+ 7: 2,
35
+ 10: 3,
36
+ 15: 4,
37
+ 18: 5,
38
+ 25: 6,
39
+ 28: 7,
40
+ 31: 8,
41
+ 35: 9,
42
+ 38: 10,
43
+ 41: 11,
44
+ 44: 12,
45
+ 46: 13,
46
+ 48: 14,
47
+ }
48
+
49
+ def forward(self):
50
+ pass
51
+
52
+ @staticmethod
53
+ def state_dict_converter():
54
+ return SDMotionModelStateDictConverter()
55
+
56
+
57
+ class SDMotionModelStateDictConverter:
58
+ def __init__(self):
59
+ pass
60
+
61
+ def from_diffusers(self, state_dict):
62
+ rename_dict = {
63
+ "norm": "norm",
64
+ "proj_in": "proj_in",
65
+ "transformer_blocks.0.attention_blocks.0.to_q": "transformer_blocks.0.attn1.to_q",
66
+ "transformer_blocks.0.attention_blocks.0.to_k": "transformer_blocks.0.attn1.to_k",
67
+ "transformer_blocks.0.attention_blocks.0.to_v": "transformer_blocks.0.attn1.to_v",
68
+ "transformer_blocks.0.attention_blocks.0.to_out.0": "transformer_blocks.0.attn1.to_out",
69
+ "transformer_blocks.0.attention_blocks.0.pos_encoder": "transformer_blocks.0.pe1",
70
+ "transformer_blocks.0.attention_blocks.1.to_q": "transformer_blocks.0.attn2.to_q",
71
+ "transformer_blocks.0.attention_blocks.1.to_k": "transformer_blocks.0.attn2.to_k",
72
+ "transformer_blocks.0.attention_blocks.1.to_v": "transformer_blocks.0.attn2.to_v",
73
+ "transformer_blocks.0.attention_blocks.1.to_out.0": "transformer_blocks.0.attn2.to_out",
74
+ "transformer_blocks.0.attention_blocks.1.pos_encoder": "transformer_blocks.0.pe2",
75
+ "transformer_blocks.0.norms.0": "transformer_blocks.0.norm1",
76
+ "transformer_blocks.0.norms.1": "transformer_blocks.0.norm2",
77
+ "transformer_blocks.0.ff.net.0.proj": "transformer_blocks.0.act_fn.proj",
78
+ "transformer_blocks.0.ff.net.2": "transformer_blocks.0.ff",
79
+ "transformer_blocks.0.ff_norm": "transformer_blocks.0.norm3",
80
+ "proj_out": "proj_out",
81
+ }
82
+ name_list = sorted([i for i in state_dict if i.startswith("down_blocks.")])
83
+ name_list += sorted([i for i in state_dict if i.startswith("mid_block.")])
84
+ name_list += sorted([i for i in state_dict if i.startswith("up_blocks.")])
85
+ state_dict_ = {}
86
+ last_prefix, module_id = "", -1
87
+ for name in name_list:
88
+ names = name.split(".")
89
+ prefix_index = names.index("temporal_transformer") + 1
90
+ prefix = ".".join(names[:prefix_index])
91
+ if prefix != last_prefix:
92
+ last_prefix = prefix
93
+ module_id += 1
94
+ middle_name = ".".join(names[prefix_index:-1])
95
+ suffix = names[-1]
96
+ if "pos_encoder" in names:
97
+ rename = ".".join(["motion_modules", str(module_id), rename_dict[middle_name]])
98
+ else:
99
+ rename = ".".join(["motion_modules", str(module_id), rename_dict[middle_name], suffix])
100
+ state_dict_[rename] = state_dict[name]
101
+ return state_dict_
102
+
103
+ def from_civitai(self, state_dict):
104
+ return self.from_diffusers(state_dict)
sdxl_text_encoder.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .sd_text_encoder import CLIPEncoderLayer
3
+
4
+
5
+ class SDXLTextEncoder(torch.nn.Module):
6
+ def __init__(self, embed_dim=768, vocab_size=49408, max_position_embeddings=77, num_encoder_layers=11, encoder_intermediate_size=3072):
7
+ super().__init__()
8
+
9
+ # token_embedding
10
+ self.token_embedding = torch.nn.Embedding(vocab_size, embed_dim)
11
+
12
+ # position_embeds (This is a fixed tensor)
13
+ self.position_embeds = torch.nn.Parameter(torch.zeros(1, max_position_embeddings, embed_dim))
14
+
15
+ # encoders
16
+ self.encoders = torch.nn.ModuleList([CLIPEncoderLayer(embed_dim, encoder_intermediate_size) for _ in range(num_encoder_layers)])
17
+
18
+ # attn_mask
19
+ self.attn_mask = self.attention_mask(max_position_embeddings)
20
+
21
+ # The text encoder is different to that in Stable Diffusion 1.x.
22
+ # It does not include final_layer_norm.
23
+
24
+ def attention_mask(self, length):
25
+ mask = torch.empty(length, length)
26
+ mask.fill_(float("-inf"))
27
+ mask.triu_(1)
28
+ return mask
29
+
30
+ def forward(self, input_ids, clip_skip=1):
31
+ embeds = self.token_embedding(input_ids) + self.position_embeds
32
+ attn_mask = self.attn_mask.to(device=embeds.device, dtype=embeds.dtype)
33
+ for encoder_id, encoder in enumerate(self.encoders):
34
+ embeds = encoder(embeds, attn_mask=attn_mask)
35
+ if encoder_id + clip_skip == len(self.encoders):
36
+ break
37
+ return embeds
38
+
39
+ @staticmethod
40
+ def state_dict_converter():
41
+ return SDXLTextEncoderStateDictConverter()
42
+
43
+
44
+ class SDXLTextEncoder2(torch.nn.Module):
45
+ def __init__(self, embed_dim=1280, vocab_size=49408, max_position_embeddings=77, num_encoder_layers=32, encoder_intermediate_size=5120):
46
+ super().__init__()
47
+
48
+ # token_embedding
49
+ self.token_embedding = torch.nn.Embedding(vocab_size, embed_dim)
50
+
51
+ # position_embeds (This is a fixed tensor)
52
+ self.position_embeds = torch.nn.Parameter(torch.zeros(1, max_position_embeddings, embed_dim))
53
+
54
+ # encoders
55
+ self.encoders = torch.nn.ModuleList([CLIPEncoderLayer(embed_dim, encoder_intermediate_size, num_heads=20, head_dim=64, use_quick_gelu=False) for _ in range(num_encoder_layers)])
56
+
57
+ # attn_mask
58
+ self.attn_mask = self.attention_mask(max_position_embeddings)
59
+
60
+ # final_layer_norm
61
+ self.final_layer_norm = torch.nn.LayerNorm(embed_dim)
62
+
63
+ # text_projection
64
+ self.text_projection = torch.nn.Linear(embed_dim, embed_dim, bias=False)
65
+
66
+ def attention_mask(self, length):
67
+ mask = torch.empty(length, length)
68
+ mask.fill_(float("-inf"))
69
+ mask.triu_(1)
70
+ return mask
71
+
72
+ def forward(self, input_ids, clip_skip=2):
73
+ embeds = self.token_embedding(input_ids) + self.position_embeds
74
+ attn_mask = self.attn_mask.to(device=embeds.device, dtype=embeds.dtype)
75
+ for encoder_id, encoder in enumerate(self.encoders):
76
+ embeds = encoder(embeds, attn_mask=attn_mask)
77
+ if encoder_id + clip_skip == len(self.encoders):
78
+ hidden_states = embeds
79
+ embeds = self.final_layer_norm(embeds)
80
+ pooled_embeds = embeds[torch.arange(embeds.shape[0]), input_ids.to(dtype=torch.int).argmax(dim=-1)]
81
+ pooled_embeds = self.text_projection(pooled_embeds)
82
+ return pooled_embeds, hidden_states
83
+
84
+ @staticmethod
85
+ def state_dict_converter():
86
+ return SDXLTextEncoder2StateDictConverter()
87
+
88
+
89
+ class SDXLTextEncoderStateDictConverter:
90
+ def __init__(self):
91
+ pass
92
+
93
+ def from_diffusers(self, state_dict):
94
+ rename_dict = {
95
+ "text_model.embeddings.token_embedding.weight": "token_embedding.weight",
96
+ "text_model.embeddings.position_embedding.weight": "position_embeds",
97
+ "text_model.final_layer_norm.weight": "final_layer_norm.weight",
98
+ "text_model.final_layer_norm.bias": "final_layer_norm.bias"
99
+ }
100
+ attn_rename_dict = {
101
+ "self_attn.q_proj": "attn.to_q",
102
+ "self_attn.k_proj": "attn.to_k",
103
+ "self_attn.v_proj": "attn.to_v",
104
+ "self_attn.out_proj": "attn.to_out",
105
+ "layer_norm1": "layer_norm1",
106
+ "layer_norm2": "layer_norm2",
107
+ "mlp.fc1": "fc1",
108
+ "mlp.fc2": "fc2",
109
+ }
110
+ state_dict_ = {}
111
+ for name in state_dict:
112
+ if name in rename_dict:
113
+ param = state_dict[name]
114
+ if name == "text_model.embeddings.position_embedding.weight":
115
+ param = param.reshape((1, param.shape[0], param.shape[1]))
116
+ state_dict_[rename_dict[name]] = param
117
+ elif name.startswith("text_model.encoder.layers."):
118
+ param = state_dict[name]
119
+ names = name.split(".")
120
+ layer_id, layer_type, tail = names[3], ".".join(names[4:-1]), names[-1]
121
+ name_ = ".".join(["encoders", layer_id, attn_rename_dict[layer_type], tail])
122
+ state_dict_[name_] = param
123
+ return state_dict_
124
+
125
+ def from_civitai(self, state_dict):
126
+ rename_dict = {
127
+ "conditioner.embedders.0.transformer.text_model.embeddings.position_embedding.weight": "position_embeds",
128
+ "conditioner.embedders.0.transformer.text_model.embeddings.token_embedding.weight": "token_embedding.weight",
129
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm1.bias": "encoders.0.layer_norm1.bias",
130
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm1.weight": "encoders.0.layer_norm1.weight",
131
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm2.bias": "encoders.0.layer_norm2.bias",
132
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.layer_norm2.weight": "encoders.0.layer_norm2.weight",
133
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc1.bias": "encoders.0.fc1.bias",
134
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc1.weight": "encoders.0.fc1.weight",
135
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc2.bias": "encoders.0.fc2.bias",
136
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.mlp.fc2.weight": "encoders.0.fc2.weight",
137
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.k_proj.bias": "encoders.0.attn.to_k.bias",
138
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.k_proj.weight": "encoders.0.attn.to_k.weight",
139
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.out_proj.bias": "encoders.0.attn.to_out.bias",
140
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.out_proj.weight": "encoders.0.attn.to_out.weight",
141
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.q_proj.bias": "encoders.0.attn.to_q.bias",
142
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.q_proj.weight": "encoders.0.attn.to_q.weight",
143
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.v_proj.bias": "encoders.0.attn.to_v.bias",
144
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.0.self_attn.v_proj.weight": "encoders.0.attn.to_v.weight",
145
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.layer_norm1.bias": "encoders.1.layer_norm1.bias",
146
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.layer_norm1.weight": "encoders.1.layer_norm1.weight",
147
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.layer_norm2.bias": "encoders.1.layer_norm2.bias",
148
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.layer_norm2.weight": "encoders.1.layer_norm2.weight",
149
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.mlp.fc1.bias": "encoders.1.fc1.bias",
150
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.mlp.fc1.weight": "encoders.1.fc1.weight",
151
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.mlp.fc2.bias": "encoders.1.fc2.bias",
152
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.mlp.fc2.weight": "encoders.1.fc2.weight",
153
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.k_proj.bias": "encoders.1.attn.to_k.bias",
154
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.k_proj.weight": "encoders.1.attn.to_k.weight",
155
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.out_proj.bias": "encoders.1.attn.to_out.bias",
156
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.out_proj.weight": "encoders.1.attn.to_out.weight",
157
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.q_proj.bias": "encoders.1.attn.to_q.bias",
158
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.q_proj.weight": "encoders.1.attn.to_q.weight",
159
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.v_proj.bias": "encoders.1.attn.to_v.bias",
160
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.1.self_attn.v_proj.weight": "encoders.1.attn.to_v.weight",
161
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.layer_norm1.bias": "encoders.10.layer_norm1.bias",
162
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.layer_norm1.weight": "encoders.10.layer_norm1.weight",
163
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.layer_norm2.bias": "encoders.10.layer_norm2.bias",
164
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.layer_norm2.weight": "encoders.10.layer_norm2.weight",
165
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.mlp.fc1.bias": "encoders.10.fc1.bias",
166
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.mlp.fc1.weight": "encoders.10.fc1.weight",
167
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.mlp.fc2.bias": "encoders.10.fc2.bias",
168
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.mlp.fc2.weight": "encoders.10.fc2.weight",
169
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.k_proj.bias": "encoders.10.attn.to_k.bias",
170
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.k_proj.weight": "encoders.10.attn.to_k.weight",
171
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.out_proj.bias": "encoders.10.attn.to_out.bias",
172
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.out_proj.weight": "encoders.10.attn.to_out.weight",
173
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.q_proj.bias": "encoders.10.attn.to_q.bias",
174
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.q_proj.weight": "encoders.10.attn.to_q.weight",
175
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.v_proj.bias": "encoders.10.attn.to_v.bias",
176
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.10.self_attn.v_proj.weight": "encoders.10.attn.to_v.weight",
177
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.layer_norm1.bias": "encoders.2.layer_norm1.bias",
178
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.layer_norm1.weight": "encoders.2.layer_norm1.weight",
179
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.layer_norm2.bias": "encoders.2.layer_norm2.bias",
180
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.layer_norm2.weight": "encoders.2.layer_norm2.weight",
181
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.mlp.fc1.bias": "encoders.2.fc1.bias",
182
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.mlp.fc1.weight": "encoders.2.fc1.weight",
183
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.mlp.fc2.bias": "encoders.2.fc2.bias",
184
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.mlp.fc2.weight": "encoders.2.fc2.weight",
185
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.k_proj.bias": "encoders.2.attn.to_k.bias",
186
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.k_proj.weight": "encoders.2.attn.to_k.weight",
187
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.out_proj.bias": "encoders.2.attn.to_out.bias",
188
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.out_proj.weight": "encoders.2.attn.to_out.weight",
189
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.q_proj.bias": "encoders.2.attn.to_q.bias",
190
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.q_proj.weight": "encoders.2.attn.to_q.weight",
191
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.v_proj.bias": "encoders.2.attn.to_v.bias",
192
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.2.self_attn.v_proj.weight": "encoders.2.attn.to_v.weight",
193
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.layer_norm1.bias": "encoders.3.layer_norm1.bias",
194
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.layer_norm1.weight": "encoders.3.layer_norm1.weight",
195
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.layer_norm2.bias": "encoders.3.layer_norm2.bias",
196
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.layer_norm2.weight": "encoders.3.layer_norm2.weight",
197
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.mlp.fc1.bias": "encoders.3.fc1.bias",
198
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.mlp.fc1.weight": "encoders.3.fc1.weight",
199
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.mlp.fc2.bias": "encoders.3.fc2.bias",
200
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.mlp.fc2.weight": "encoders.3.fc2.weight",
201
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.k_proj.bias": "encoders.3.attn.to_k.bias",
202
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.k_proj.weight": "encoders.3.attn.to_k.weight",
203
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.out_proj.bias": "encoders.3.attn.to_out.bias",
204
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.out_proj.weight": "encoders.3.attn.to_out.weight",
205
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.q_proj.bias": "encoders.3.attn.to_q.bias",
206
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.q_proj.weight": "encoders.3.attn.to_q.weight",
207
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.v_proj.bias": "encoders.3.attn.to_v.bias",
208
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.3.self_attn.v_proj.weight": "encoders.3.attn.to_v.weight",
209
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.layer_norm1.bias": "encoders.4.layer_norm1.bias",
210
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.layer_norm1.weight": "encoders.4.layer_norm1.weight",
211
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.layer_norm2.bias": "encoders.4.layer_norm2.bias",
212
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.layer_norm2.weight": "encoders.4.layer_norm2.weight",
213
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.mlp.fc1.bias": "encoders.4.fc1.bias",
214
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.mlp.fc1.weight": "encoders.4.fc1.weight",
215
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.mlp.fc2.bias": "encoders.4.fc2.bias",
216
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.mlp.fc2.weight": "encoders.4.fc2.weight",
217
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.k_proj.bias": "encoders.4.attn.to_k.bias",
218
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.k_proj.weight": "encoders.4.attn.to_k.weight",
219
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.out_proj.bias": "encoders.4.attn.to_out.bias",
220
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.out_proj.weight": "encoders.4.attn.to_out.weight",
221
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.q_proj.bias": "encoders.4.attn.to_q.bias",
222
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.q_proj.weight": "encoders.4.attn.to_q.weight",
223
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.v_proj.bias": "encoders.4.attn.to_v.bias",
224
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.4.self_attn.v_proj.weight": "encoders.4.attn.to_v.weight",
225
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.layer_norm1.bias": "encoders.5.layer_norm1.bias",
226
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.layer_norm1.weight": "encoders.5.layer_norm1.weight",
227
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.layer_norm2.bias": "encoders.5.layer_norm2.bias",
228
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.layer_norm2.weight": "encoders.5.layer_norm2.weight",
229
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.mlp.fc1.bias": "encoders.5.fc1.bias",
230
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.mlp.fc1.weight": "encoders.5.fc1.weight",
231
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.mlp.fc2.bias": "encoders.5.fc2.bias",
232
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.mlp.fc2.weight": "encoders.5.fc2.weight",
233
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.k_proj.bias": "encoders.5.attn.to_k.bias",
234
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.k_proj.weight": "encoders.5.attn.to_k.weight",
235
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.out_proj.bias": "encoders.5.attn.to_out.bias",
236
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.out_proj.weight": "encoders.5.attn.to_out.weight",
237
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.q_proj.bias": "encoders.5.attn.to_q.bias",
238
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.q_proj.weight": "encoders.5.attn.to_q.weight",
239
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.v_proj.bias": "encoders.5.attn.to_v.bias",
240
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.5.self_attn.v_proj.weight": "encoders.5.attn.to_v.weight",
241
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.layer_norm1.bias": "encoders.6.layer_norm1.bias",
242
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.layer_norm1.weight": "encoders.6.layer_norm1.weight",
243
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.layer_norm2.bias": "encoders.6.layer_norm2.bias",
244
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.layer_norm2.weight": "encoders.6.layer_norm2.weight",
245
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.mlp.fc1.bias": "encoders.6.fc1.bias",
246
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.mlp.fc1.weight": "encoders.6.fc1.weight",
247
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.mlp.fc2.bias": "encoders.6.fc2.bias",
248
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.mlp.fc2.weight": "encoders.6.fc2.weight",
249
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.k_proj.bias": "encoders.6.attn.to_k.bias",
250
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.k_proj.weight": "encoders.6.attn.to_k.weight",
251
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.out_proj.bias": "encoders.6.attn.to_out.bias",
252
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.out_proj.weight": "encoders.6.attn.to_out.weight",
253
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.q_proj.bias": "encoders.6.attn.to_q.bias",
254
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.q_proj.weight": "encoders.6.attn.to_q.weight",
255
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.v_proj.bias": "encoders.6.attn.to_v.bias",
256
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.6.self_attn.v_proj.weight": "encoders.6.attn.to_v.weight",
257
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.layer_norm1.bias": "encoders.7.layer_norm1.bias",
258
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.layer_norm1.weight": "encoders.7.layer_norm1.weight",
259
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.layer_norm2.bias": "encoders.7.layer_norm2.bias",
260
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.layer_norm2.weight": "encoders.7.layer_norm2.weight",
261
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.mlp.fc1.bias": "encoders.7.fc1.bias",
262
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.mlp.fc1.weight": "encoders.7.fc1.weight",
263
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.mlp.fc2.bias": "encoders.7.fc2.bias",
264
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.mlp.fc2.weight": "encoders.7.fc2.weight",
265
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.k_proj.bias": "encoders.7.attn.to_k.bias",
266
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.k_proj.weight": "encoders.7.attn.to_k.weight",
267
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.out_proj.bias": "encoders.7.attn.to_out.bias",
268
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.out_proj.weight": "encoders.7.attn.to_out.weight",
269
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.q_proj.bias": "encoders.7.attn.to_q.bias",
270
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.q_proj.weight": "encoders.7.attn.to_q.weight",
271
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.v_proj.bias": "encoders.7.attn.to_v.bias",
272
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.7.self_attn.v_proj.weight": "encoders.7.attn.to_v.weight",
273
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.layer_norm1.bias": "encoders.8.layer_norm1.bias",
274
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.layer_norm1.weight": "encoders.8.layer_norm1.weight",
275
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.layer_norm2.bias": "encoders.8.layer_norm2.bias",
276
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.layer_norm2.weight": "encoders.8.layer_norm2.weight",
277
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.mlp.fc1.bias": "encoders.8.fc1.bias",
278
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.mlp.fc1.weight": "encoders.8.fc1.weight",
279
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.mlp.fc2.bias": "encoders.8.fc2.bias",
280
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.mlp.fc2.weight": "encoders.8.fc2.weight",
281
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.k_proj.bias": "encoders.8.attn.to_k.bias",
282
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.k_proj.weight": "encoders.8.attn.to_k.weight",
283
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.out_proj.bias": "encoders.8.attn.to_out.bias",
284
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.out_proj.weight": "encoders.8.attn.to_out.weight",
285
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.q_proj.bias": "encoders.8.attn.to_q.bias",
286
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.q_proj.weight": "encoders.8.attn.to_q.weight",
287
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.v_proj.bias": "encoders.8.attn.to_v.bias",
288
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.8.self_attn.v_proj.weight": "encoders.8.attn.to_v.weight",
289
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.layer_norm1.bias": "encoders.9.layer_norm1.bias",
290
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.layer_norm1.weight": "encoders.9.layer_norm1.weight",
291
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.layer_norm2.bias": "encoders.9.layer_norm2.bias",
292
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.layer_norm2.weight": "encoders.9.layer_norm2.weight",
293
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.mlp.fc1.bias": "encoders.9.fc1.bias",
294
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.mlp.fc1.weight": "encoders.9.fc1.weight",
295
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.mlp.fc2.bias": "encoders.9.fc2.bias",
296
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.mlp.fc2.weight": "encoders.9.fc2.weight",
297
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.k_proj.bias": "encoders.9.attn.to_k.bias",
298
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.k_proj.weight": "encoders.9.attn.to_k.weight",
299
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.out_proj.bias": "encoders.9.attn.to_out.bias",
300
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.out_proj.weight": "encoders.9.attn.to_out.weight",
301
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.q_proj.bias": "encoders.9.attn.to_q.bias",
302
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.q_proj.weight": "encoders.9.attn.to_q.weight",
303
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.v_proj.bias": "encoders.9.attn.to_v.bias",
304
+ "conditioner.embedders.0.transformer.text_model.encoder.layers.9.self_attn.v_proj.weight": "encoders.9.attn.to_v.weight",
305
+ }
306
+ state_dict_ = {}
307
+ for name in state_dict:
308
+ if name in rename_dict:
309
+ param = state_dict[name]
310
+ if name == "conditioner.embedders.0.transformer.text_model.embeddings.position_embedding.weight":
311
+ param = param.reshape((1, param.shape[0], param.shape[1]))
312
+ state_dict_[rename_dict[name]] = param
313
+ return state_dict_
314
+
315
+
316
+ class SDXLTextEncoder2StateDictConverter:
317
+ def __init__(self):
318
+ pass
319
+
320
+ def from_diffusers(self, state_dict):
321
+ rename_dict = {
322
+ "text_model.embeddings.token_embedding.weight": "token_embedding.weight",
323
+ "text_model.embeddings.position_embedding.weight": "position_embeds",
324
+ "text_model.final_layer_norm.weight": "final_layer_norm.weight",
325
+ "text_model.final_layer_norm.bias": "final_layer_norm.bias",
326
+ "text_projection.weight": "text_projection.weight"
327
+ }
328
+ attn_rename_dict = {
329
+ "self_attn.q_proj": "attn.to_q",
330
+ "self_attn.k_proj": "attn.to_k",
331
+ "self_attn.v_proj": "attn.to_v",
332
+ "self_attn.out_proj": "attn.to_out",
333
+ "layer_norm1": "layer_norm1",
334
+ "layer_norm2": "layer_norm2",
335
+ "mlp.fc1": "fc1",
336
+ "mlp.fc2": "fc2",
337
+ }
338
+ state_dict_ = {}
339
+ for name in state_dict:
340
+ if name in rename_dict:
341
+ param = state_dict[name]
342
+ if name == "text_model.embeddings.position_embedding.weight":
343
+ param = param.reshape((1, param.shape[0], param.shape[1]))
344
+ state_dict_[rename_dict[name]] = param
345
+ elif name.startswith("text_model.encoder.layers."):
346
+ param = state_dict[name]
347
+ names = name.split(".")
348
+ layer_id, layer_type, tail = names[3], ".".join(names[4:-1]), names[-1]
349
+ name_ = ".".join(["encoders", layer_id, attn_rename_dict[layer_type], tail])
350
+ state_dict_[name_] = param
351
+ return state_dict_
352
+
353
+ def from_civitai(self, state_dict):
354
+ rename_dict = {
355
+ "conditioner.embedders.1.model.ln_final.bias": "final_layer_norm.bias",
356
+ "conditioner.embedders.1.model.ln_final.weight": "final_layer_norm.weight",
357
+ "conditioner.embedders.1.model.positional_embedding": "position_embeds",
358
+ "conditioner.embedders.1.model.token_embedding.weight": "token_embedding.weight",
359
+ "conditioner.embedders.1.model.transformer.resblocks.0.attn.in_proj_bias": ['encoders.0.attn.to_q.bias', 'encoders.0.attn.to_k.bias', 'encoders.0.attn.to_v.bias'],
360
+ "conditioner.embedders.1.model.transformer.resblocks.0.attn.in_proj_weight": ['encoders.0.attn.to_q.weight', 'encoders.0.attn.to_k.weight', 'encoders.0.attn.to_v.weight'],
361
+ "conditioner.embedders.1.model.transformer.resblocks.0.attn.out_proj.bias": "encoders.0.attn.to_out.bias",
362
+ "conditioner.embedders.1.model.transformer.resblocks.0.attn.out_proj.weight": "encoders.0.attn.to_out.weight",
363
+ "conditioner.embedders.1.model.transformer.resblocks.0.ln_1.bias": "encoders.0.layer_norm1.bias",
364
+ "conditioner.embedders.1.model.transformer.resblocks.0.ln_1.weight": "encoders.0.layer_norm1.weight",
365
+ "conditioner.embedders.1.model.transformer.resblocks.0.ln_2.bias": "encoders.0.layer_norm2.bias",
366
+ "conditioner.embedders.1.model.transformer.resblocks.0.ln_2.weight": "encoders.0.layer_norm2.weight",
367
+ "conditioner.embedders.1.model.transformer.resblocks.0.mlp.c_fc.bias": "encoders.0.fc1.bias",
368
+ "conditioner.embedders.1.model.transformer.resblocks.0.mlp.c_fc.weight": "encoders.0.fc1.weight",
369
+ "conditioner.embedders.1.model.transformer.resblocks.0.mlp.c_proj.bias": "encoders.0.fc2.bias",
370
+ "conditioner.embedders.1.model.transformer.resblocks.0.mlp.c_proj.weight": "encoders.0.fc2.weight",
371
+ "conditioner.embedders.1.model.transformer.resblocks.1.attn.in_proj_bias": ['encoders.1.attn.to_q.bias', 'encoders.1.attn.to_k.bias', 'encoders.1.attn.to_v.bias'],
372
+ "conditioner.embedders.1.model.transformer.resblocks.1.attn.in_proj_weight": ['encoders.1.attn.to_q.weight', 'encoders.1.attn.to_k.weight', 'encoders.1.attn.to_v.weight'],
373
+ "conditioner.embedders.1.model.transformer.resblocks.1.attn.out_proj.bias": "encoders.1.attn.to_out.bias",
374
+ "conditioner.embedders.1.model.transformer.resblocks.1.attn.out_proj.weight": "encoders.1.attn.to_out.weight",
375
+ "conditioner.embedders.1.model.transformer.resblocks.1.ln_1.bias": "encoders.1.layer_norm1.bias",
376
+ "conditioner.embedders.1.model.transformer.resblocks.1.ln_1.weight": "encoders.1.layer_norm1.weight",
377
+ "conditioner.embedders.1.model.transformer.resblocks.1.ln_2.bias": "encoders.1.layer_norm2.bias",
378
+ "conditioner.embedders.1.model.transformer.resblocks.1.ln_2.weight": "encoders.1.layer_norm2.weight",
379
+ "conditioner.embedders.1.model.transformer.resblocks.1.mlp.c_fc.bias": "encoders.1.fc1.bias",
380
+ "conditioner.embedders.1.model.transformer.resblocks.1.mlp.c_fc.weight": "encoders.1.fc1.weight",
381
+ "conditioner.embedders.1.model.transformer.resblocks.1.mlp.c_proj.bias": "encoders.1.fc2.bias",
382
+ "conditioner.embedders.1.model.transformer.resblocks.1.mlp.c_proj.weight": "encoders.1.fc2.weight",
383
+ "conditioner.embedders.1.model.transformer.resblocks.10.attn.in_proj_bias": ['encoders.10.attn.to_q.bias', 'encoders.10.attn.to_k.bias', 'encoders.10.attn.to_v.bias'],
384
+ "conditioner.embedders.1.model.transformer.resblocks.10.attn.in_proj_weight": ['encoders.10.attn.to_q.weight', 'encoders.10.attn.to_k.weight', 'encoders.10.attn.to_v.weight'],
385
+ "conditioner.embedders.1.model.transformer.resblocks.10.attn.out_proj.bias": "encoders.10.attn.to_out.bias",
386
+ "conditioner.embedders.1.model.transformer.resblocks.10.attn.out_proj.weight": "encoders.10.attn.to_out.weight",
387
+ "conditioner.embedders.1.model.transformer.resblocks.10.ln_1.bias": "encoders.10.layer_norm1.bias",
388
+ "conditioner.embedders.1.model.transformer.resblocks.10.ln_1.weight": "encoders.10.layer_norm1.weight",
389
+ "conditioner.embedders.1.model.transformer.resblocks.10.ln_2.bias": "encoders.10.layer_norm2.bias",
390
+ "conditioner.embedders.1.model.transformer.resblocks.10.ln_2.weight": "encoders.10.layer_norm2.weight",
391
+ "conditioner.embedders.1.model.transformer.resblocks.10.mlp.c_fc.bias": "encoders.10.fc1.bias",
392
+ "conditioner.embedders.1.model.transformer.resblocks.10.mlp.c_fc.weight": "encoders.10.fc1.weight",
393
+ "conditioner.embedders.1.model.transformer.resblocks.10.mlp.c_proj.bias": "encoders.10.fc2.bias",
394
+ "conditioner.embedders.1.model.transformer.resblocks.10.mlp.c_proj.weight": "encoders.10.fc2.weight",
395
+ "conditioner.embedders.1.model.transformer.resblocks.11.attn.in_proj_bias": ['encoders.11.attn.to_q.bias', 'encoders.11.attn.to_k.bias', 'encoders.11.attn.to_v.bias'],
396
+ "conditioner.embedders.1.model.transformer.resblocks.11.attn.in_proj_weight": ['encoders.11.attn.to_q.weight', 'encoders.11.attn.to_k.weight', 'encoders.11.attn.to_v.weight'],
397
+ "conditioner.embedders.1.model.transformer.resblocks.11.attn.out_proj.bias": "encoders.11.attn.to_out.bias",
398
+ "conditioner.embedders.1.model.transformer.resblocks.11.attn.out_proj.weight": "encoders.11.attn.to_out.weight",
399
+ "conditioner.embedders.1.model.transformer.resblocks.11.ln_1.bias": "encoders.11.layer_norm1.bias",
400
+ "conditioner.embedders.1.model.transformer.resblocks.11.ln_1.weight": "encoders.11.layer_norm1.weight",
401
+ "conditioner.embedders.1.model.transformer.resblocks.11.ln_2.bias": "encoders.11.layer_norm2.bias",
402
+ "conditioner.embedders.1.model.transformer.resblocks.11.ln_2.weight": "encoders.11.layer_norm2.weight",
403
+ "conditioner.embedders.1.model.transformer.resblocks.11.mlp.c_fc.bias": "encoders.11.fc1.bias",
404
+ "conditioner.embedders.1.model.transformer.resblocks.11.mlp.c_fc.weight": "encoders.11.fc1.weight",
405
+ "conditioner.embedders.1.model.transformer.resblocks.11.mlp.c_proj.bias": "encoders.11.fc2.bias",
406
+ "conditioner.embedders.1.model.transformer.resblocks.11.mlp.c_proj.weight": "encoders.11.fc2.weight",
407
+ "conditioner.embedders.1.model.transformer.resblocks.12.attn.in_proj_bias": ['encoders.12.attn.to_q.bias', 'encoders.12.attn.to_k.bias', 'encoders.12.attn.to_v.bias'],
408
+ "conditioner.embedders.1.model.transformer.resblocks.12.attn.in_proj_weight": ['encoders.12.attn.to_q.weight', 'encoders.12.attn.to_k.weight', 'encoders.12.attn.to_v.weight'],
409
+ "conditioner.embedders.1.model.transformer.resblocks.12.attn.out_proj.bias": "encoders.12.attn.to_out.bias",
410
+ "conditioner.embedders.1.model.transformer.resblocks.12.attn.out_proj.weight": "encoders.12.attn.to_out.weight",
411
+ "conditioner.embedders.1.model.transformer.resblocks.12.ln_1.bias": "encoders.12.layer_norm1.bias",
412
+ "conditioner.embedders.1.model.transformer.resblocks.12.ln_1.weight": "encoders.12.layer_norm1.weight",
413
+ "conditioner.embedders.1.model.transformer.resblocks.12.ln_2.bias": "encoders.12.layer_norm2.bias",
414
+ "conditioner.embedders.1.model.transformer.resblocks.12.ln_2.weight": "encoders.12.layer_norm2.weight",
415
+ "conditioner.embedders.1.model.transformer.resblocks.12.mlp.c_fc.bias": "encoders.12.fc1.bias",
416
+ "conditioner.embedders.1.model.transformer.resblocks.12.mlp.c_fc.weight": "encoders.12.fc1.weight",
417
+ "conditioner.embedders.1.model.transformer.resblocks.12.mlp.c_proj.bias": "encoders.12.fc2.bias",
418
+ "conditioner.embedders.1.model.transformer.resblocks.12.mlp.c_proj.weight": "encoders.12.fc2.weight",
419
+ "conditioner.embedders.1.model.transformer.resblocks.13.attn.in_proj_bias": ['encoders.13.attn.to_q.bias', 'encoders.13.attn.to_k.bias', 'encoders.13.attn.to_v.bias'],
420
+ "conditioner.embedders.1.model.transformer.resblocks.13.attn.in_proj_weight": ['encoders.13.attn.to_q.weight', 'encoders.13.attn.to_k.weight', 'encoders.13.attn.to_v.weight'],
421
+ "conditioner.embedders.1.model.transformer.resblocks.13.attn.out_proj.bias": "encoders.13.attn.to_out.bias",
422
+ "conditioner.embedders.1.model.transformer.resblocks.13.attn.out_proj.weight": "encoders.13.attn.to_out.weight",
423
+ "conditioner.embedders.1.model.transformer.resblocks.13.ln_1.bias": "encoders.13.layer_norm1.bias",
424
+ "conditioner.embedders.1.model.transformer.resblocks.13.ln_1.weight": "encoders.13.layer_norm1.weight",
425
+ "conditioner.embedders.1.model.transformer.resblocks.13.ln_2.bias": "encoders.13.layer_norm2.bias",
426
+ "conditioner.embedders.1.model.transformer.resblocks.13.ln_2.weight": "encoders.13.layer_norm2.weight",
427
+ "conditioner.embedders.1.model.transformer.resblocks.13.mlp.c_fc.bias": "encoders.13.fc1.bias",
428
+ "conditioner.embedders.1.model.transformer.resblocks.13.mlp.c_fc.weight": "encoders.13.fc1.weight",
429
+ "conditioner.embedders.1.model.transformer.resblocks.13.mlp.c_proj.bias": "encoders.13.fc2.bias",
430
+ "conditioner.embedders.1.model.transformer.resblocks.13.mlp.c_proj.weight": "encoders.13.fc2.weight",
431
+ "conditioner.embedders.1.model.transformer.resblocks.14.attn.in_proj_bias": ['encoders.14.attn.to_q.bias', 'encoders.14.attn.to_k.bias', 'encoders.14.attn.to_v.bias'],
432
+ "conditioner.embedders.1.model.transformer.resblocks.14.attn.in_proj_weight": ['encoders.14.attn.to_q.weight', 'encoders.14.attn.to_k.weight', 'encoders.14.attn.to_v.weight'],
433
+ "conditioner.embedders.1.model.transformer.resblocks.14.attn.out_proj.bias": "encoders.14.attn.to_out.bias",
434
+ "conditioner.embedders.1.model.transformer.resblocks.14.attn.out_proj.weight": "encoders.14.attn.to_out.weight",
435
+ "conditioner.embedders.1.model.transformer.resblocks.14.ln_1.bias": "encoders.14.layer_norm1.bias",
436
+ "conditioner.embedders.1.model.transformer.resblocks.14.ln_1.weight": "encoders.14.layer_norm1.weight",
437
+ "conditioner.embedders.1.model.transformer.resblocks.14.ln_2.bias": "encoders.14.layer_norm2.bias",
438
+ "conditioner.embedders.1.model.transformer.resblocks.14.ln_2.weight": "encoders.14.layer_norm2.weight",
439
+ "conditioner.embedders.1.model.transformer.resblocks.14.mlp.c_fc.bias": "encoders.14.fc1.bias",
440
+ "conditioner.embedders.1.model.transformer.resblocks.14.mlp.c_fc.weight": "encoders.14.fc1.weight",
441
+ "conditioner.embedders.1.model.transformer.resblocks.14.mlp.c_proj.bias": "encoders.14.fc2.bias",
442
+ "conditioner.embedders.1.model.transformer.resblocks.14.mlp.c_proj.weight": "encoders.14.fc2.weight",
443
+ "conditioner.embedders.1.model.transformer.resblocks.15.attn.in_proj_bias": ['encoders.15.attn.to_q.bias', 'encoders.15.attn.to_k.bias', 'encoders.15.attn.to_v.bias'],
444
+ "conditioner.embedders.1.model.transformer.resblocks.15.attn.in_proj_weight": ['encoders.15.attn.to_q.weight', 'encoders.15.attn.to_k.weight', 'encoders.15.attn.to_v.weight'],
445
+ "conditioner.embedders.1.model.transformer.resblocks.15.attn.out_proj.bias": "encoders.15.attn.to_out.bias",
446
+ "conditioner.embedders.1.model.transformer.resblocks.15.attn.out_proj.weight": "encoders.15.attn.to_out.weight",
447
+ "conditioner.embedders.1.model.transformer.resblocks.15.ln_1.bias": "encoders.15.layer_norm1.bias",
448
+ "conditioner.embedders.1.model.transformer.resblocks.15.ln_1.weight": "encoders.15.layer_norm1.weight",
449
+ "conditioner.embedders.1.model.transformer.resblocks.15.ln_2.bias": "encoders.15.layer_norm2.bias",
450
+ "conditioner.embedders.1.model.transformer.resblocks.15.ln_2.weight": "encoders.15.layer_norm2.weight",
451
+ "conditioner.embedders.1.model.transformer.resblocks.15.mlp.c_fc.bias": "encoders.15.fc1.bias",
452
+ "conditioner.embedders.1.model.transformer.resblocks.15.mlp.c_fc.weight": "encoders.15.fc1.weight",
453
+ "conditioner.embedders.1.model.transformer.resblocks.15.mlp.c_proj.bias": "encoders.15.fc2.bias",
454
+ "conditioner.embedders.1.model.transformer.resblocks.15.mlp.c_proj.weight": "encoders.15.fc2.weight",
455
+ "conditioner.embedders.1.model.transformer.resblocks.16.attn.in_proj_bias": ['encoders.16.attn.to_q.bias', 'encoders.16.attn.to_k.bias', 'encoders.16.attn.to_v.bias'],
456
+ "conditioner.embedders.1.model.transformer.resblocks.16.attn.in_proj_weight": ['encoders.16.attn.to_q.weight', 'encoders.16.attn.to_k.weight', 'encoders.16.attn.to_v.weight'],
457
+ "conditioner.embedders.1.model.transformer.resblocks.16.attn.out_proj.bias": "encoders.16.attn.to_out.bias",
458
+ "conditioner.embedders.1.model.transformer.resblocks.16.attn.out_proj.weight": "encoders.16.attn.to_out.weight",
459
+ "conditioner.embedders.1.model.transformer.resblocks.16.ln_1.bias": "encoders.16.layer_norm1.bias",
460
+ "conditioner.embedders.1.model.transformer.resblocks.16.ln_1.weight": "encoders.16.layer_norm1.weight",
461
+ "conditioner.embedders.1.model.transformer.resblocks.16.ln_2.bias": "encoders.16.layer_norm2.bias",
462
+ "conditioner.embedders.1.model.transformer.resblocks.16.ln_2.weight": "encoders.16.layer_norm2.weight",
463
+ "conditioner.embedders.1.model.transformer.resblocks.16.mlp.c_fc.bias": "encoders.16.fc1.bias",
464
+ "conditioner.embedders.1.model.transformer.resblocks.16.mlp.c_fc.weight": "encoders.16.fc1.weight",
465
+ "conditioner.embedders.1.model.transformer.resblocks.16.mlp.c_proj.bias": "encoders.16.fc2.bias",
466
+ "conditioner.embedders.1.model.transformer.resblocks.16.mlp.c_proj.weight": "encoders.16.fc2.weight",
467
+ "conditioner.embedders.1.model.transformer.resblocks.17.attn.in_proj_bias": ['encoders.17.attn.to_q.bias', 'encoders.17.attn.to_k.bias', 'encoders.17.attn.to_v.bias'],
468
+ "conditioner.embedders.1.model.transformer.resblocks.17.attn.in_proj_weight": ['encoders.17.attn.to_q.weight', 'encoders.17.attn.to_k.weight', 'encoders.17.attn.to_v.weight'],
469
+ "conditioner.embedders.1.model.transformer.resblocks.17.attn.out_proj.bias": "encoders.17.attn.to_out.bias",
470
+ "conditioner.embedders.1.model.transformer.resblocks.17.attn.out_proj.weight": "encoders.17.attn.to_out.weight",
471
+ "conditioner.embedders.1.model.transformer.resblocks.17.ln_1.bias": "encoders.17.layer_norm1.bias",
472
+ "conditioner.embedders.1.model.transformer.resblocks.17.ln_1.weight": "encoders.17.layer_norm1.weight",
473
+ "conditioner.embedders.1.model.transformer.resblocks.17.ln_2.bias": "encoders.17.layer_norm2.bias",
474
+ "conditioner.embedders.1.model.transformer.resblocks.17.ln_2.weight": "encoders.17.layer_norm2.weight",
475
+ "conditioner.embedders.1.model.transformer.resblocks.17.mlp.c_fc.bias": "encoders.17.fc1.bias",
476
+ "conditioner.embedders.1.model.transformer.resblocks.17.mlp.c_fc.weight": "encoders.17.fc1.weight",
477
+ "conditioner.embedders.1.model.transformer.resblocks.17.mlp.c_proj.bias": "encoders.17.fc2.bias",
478
+ "conditioner.embedders.1.model.transformer.resblocks.17.mlp.c_proj.weight": "encoders.17.fc2.weight",
479
+ "conditioner.embedders.1.model.transformer.resblocks.18.attn.in_proj_bias": ['encoders.18.attn.to_q.bias', 'encoders.18.attn.to_k.bias', 'encoders.18.attn.to_v.bias'],
480
+ "conditioner.embedders.1.model.transformer.resblocks.18.attn.in_proj_weight": ['encoders.18.attn.to_q.weight', 'encoders.18.attn.to_k.weight', 'encoders.18.attn.to_v.weight'],
481
+ "conditioner.embedders.1.model.transformer.resblocks.18.attn.out_proj.bias": "encoders.18.attn.to_out.bias",
482
+ "conditioner.embedders.1.model.transformer.resblocks.18.attn.out_proj.weight": "encoders.18.attn.to_out.weight",
483
+ "conditioner.embedders.1.model.transformer.resblocks.18.ln_1.bias": "encoders.18.layer_norm1.bias",
484
+ "conditioner.embedders.1.model.transformer.resblocks.18.ln_1.weight": "encoders.18.layer_norm1.weight",
485
+ "conditioner.embedders.1.model.transformer.resblocks.18.ln_2.bias": "encoders.18.layer_norm2.bias",
486
+ "conditioner.embedders.1.model.transformer.resblocks.18.ln_2.weight": "encoders.18.layer_norm2.weight",
487
+ "conditioner.embedders.1.model.transformer.resblocks.18.mlp.c_fc.bias": "encoders.18.fc1.bias",
488
+ "conditioner.embedders.1.model.transformer.resblocks.18.mlp.c_fc.weight": "encoders.18.fc1.weight",
489
+ "conditioner.embedders.1.model.transformer.resblocks.18.mlp.c_proj.bias": "encoders.18.fc2.bias",
490
+ "conditioner.embedders.1.model.transformer.resblocks.18.mlp.c_proj.weight": "encoders.18.fc2.weight",
491
+ "conditioner.embedders.1.model.transformer.resblocks.19.attn.in_proj_bias": ['encoders.19.attn.to_q.bias', 'encoders.19.attn.to_k.bias', 'encoders.19.attn.to_v.bias'],
492
+ "conditioner.embedders.1.model.transformer.resblocks.19.attn.in_proj_weight": ['encoders.19.attn.to_q.weight', 'encoders.19.attn.to_k.weight', 'encoders.19.attn.to_v.weight'],
493
+ "conditioner.embedders.1.model.transformer.resblocks.19.attn.out_proj.bias": "encoders.19.attn.to_out.bias",
494
+ "conditioner.embedders.1.model.transformer.resblocks.19.attn.out_proj.weight": "encoders.19.attn.to_out.weight",
495
+ "conditioner.embedders.1.model.transformer.resblocks.19.ln_1.bias": "encoders.19.layer_norm1.bias",
496
+ "conditioner.embedders.1.model.transformer.resblocks.19.ln_1.weight": "encoders.19.layer_norm1.weight",
497
+ "conditioner.embedders.1.model.transformer.resblocks.19.ln_2.bias": "encoders.19.layer_norm2.bias",
498
+ "conditioner.embedders.1.model.transformer.resblocks.19.ln_2.weight": "encoders.19.layer_norm2.weight",
499
+ "conditioner.embedders.1.model.transformer.resblocks.19.mlp.c_fc.bias": "encoders.19.fc1.bias",
500
+ "conditioner.embedders.1.model.transformer.resblocks.19.mlp.c_fc.weight": "encoders.19.fc1.weight",
501
+ "conditioner.embedders.1.model.transformer.resblocks.19.mlp.c_proj.bias": "encoders.19.fc2.bias",
502
+ "conditioner.embedders.1.model.transformer.resblocks.19.mlp.c_proj.weight": "encoders.19.fc2.weight",
503
+ "conditioner.embedders.1.model.transformer.resblocks.2.attn.in_proj_bias": ['encoders.2.attn.to_q.bias', 'encoders.2.attn.to_k.bias', 'encoders.2.attn.to_v.bias'],
504
+ "conditioner.embedders.1.model.transformer.resblocks.2.attn.in_proj_weight": ['encoders.2.attn.to_q.weight', 'encoders.2.attn.to_k.weight', 'encoders.2.attn.to_v.weight'],
505
+ "conditioner.embedders.1.model.transformer.resblocks.2.attn.out_proj.bias": "encoders.2.attn.to_out.bias",
506
+ "conditioner.embedders.1.model.transformer.resblocks.2.attn.out_proj.weight": "encoders.2.attn.to_out.weight",
507
+ "conditioner.embedders.1.model.transformer.resblocks.2.ln_1.bias": "encoders.2.layer_norm1.bias",
508
+ "conditioner.embedders.1.model.transformer.resblocks.2.ln_1.weight": "encoders.2.layer_norm1.weight",
509
+ "conditioner.embedders.1.model.transformer.resblocks.2.ln_2.bias": "encoders.2.layer_norm2.bias",
510
+ "conditioner.embedders.1.model.transformer.resblocks.2.ln_2.weight": "encoders.2.layer_norm2.weight",
511
+ "conditioner.embedders.1.model.transformer.resblocks.2.mlp.c_fc.bias": "encoders.2.fc1.bias",
512
+ "conditioner.embedders.1.model.transformer.resblocks.2.mlp.c_fc.weight": "encoders.2.fc1.weight",
513
+ "conditioner.embedders.1.model.transformer.resblocks.2.mlp.c_proj.bias": "encoders.2.fc2.bias",
514
+ "conditioner.embedders.1.model.transformer.resblocks.2.mlp.c_proj.weight": "encoders.2.fc2.weight",
515
+ "conditioner.embedders.1.model.transformer.resblocks.20.attn.in_proj_bias": ['encoders.20.attn.to_q.bias', 'encoders.20.attn.to_k.bias', 'encoders.20.attn.to_v.bias'],
516
+ "conditioner.embedders.1.model.transformer.resblocks.20.attn.in_proj_weight": ['encoders.20.attn.to_q.weight', 'encoders.20.attn.to_k.weight', 'encoders.20.attn.to_v.weight'],
517
+ "conditioner.embedders.1.model.transformer.resblocks.20.attn.out_proj.bias": "encoders.20.attn.to_out.bias",
518
+ "conditioner.embedders.1.model.transformer.resblocks.20.attn.out_proj.weight": "encoders.20.attn.to_out.weight",
519
+ "conditioner.embedders.1.model.transformer.resblocks.20.ln_1.bias": "encoders.20.layer_norm1.bias",
520
+ "conditioner.embedders.1.model.transformer.resblocks.20.ln_1.weight": "encoders.20.layer_norm1.weight",
521
+ "conditioner.embedders.1.model.transformer.resblocks.20.ln_2.bias": "encoders.20.layer_norm2.bias",
522
+ "conditioner.embedders.1.model.transformer.resblocks.20.ln_2.weight": "encoders.20.layer_norm2.weight",
523
+ "conditioner.embedders.1.model.transformer.resblocks.20.mlp.c_fc.bias": "encoders.20.fc1.bias",
524
+ "conditioner.embedders.1.model.transformer.resblocks.20.mlp.c_fc.weight": "encoders.20.fc1.weight",
525
+ "conditioner.embedders.1.model.transformer.resblocks.20.mlp.c_proj.bias": "encoders.20.fc2.bias",
526
+ "conditioner.embedders.1.model.transformer.resblocks.20.mlp.c_proj.weight": "encoders.20.fc2.weight",
527
+ "conditioner.embedders.1.model.transformer.resblocks.21.attn.in_proj_bias": ['encoders.21.attn.to_q.bias', 'encoders.21.attn.to_k.bias', 'encoders.21.attn.to_v.bias'],
528
+ "conditioner.embedders.1.model.transformer.resblocks.21.attn.in_proj_weight": ['encoders.21.attn.to_q.weight', 'encoders.21.attn.to_k.weight', 'encoders.21.attn.to_v.weight'],
529
+ "conditioner.embedders.1.model.transformer.resblocks.21.attn.out_proj.bias": "encoders.21.attn.to_out.bias",
530
+ "conditioner.embedders.1.model.transformer.resblocks.21.attn.out_proj.weight": "encoders.21.attn.to_out.weight",
531
+ "conditioner.embedders.1.model.transformer.resblocks.21.ln_1.bias": "encoders.21.layer_norm1.bias",
532
+ "conditioner.embedders.1.model.transformer.resblocks.21.ln_1.weight": "encoders.21.layer_norm1.weight",
533
+ "conditioner.embedders.1.model.transformer.resblocks.21.ln_2.bias": "encoders.21.layer_norm2.bias",
534
+ "conditioner.embedders.1.model.transformer.resblocks.21.ln_2.weight": "encoders.21.layer_norm2.weight",
535
+ "conditioner.embedders.1.model.transformer.resblocks.21.mlp.c_fc.bias": "encoders.21.fc1.bias",
536
+ "conditioner.embedders.1.model.transformer.resblocks.21.mlp.c_fc.weight": "encoders.21.fc1.weight",
537
+ "conditioner.embedders.1.model.transformer.resblocks.21.mlp.c_proj.bias": "encoders.21.fc2.bias",
538
+ "conditioner.embedders.1.model.transformer.resblocks.21.mlp.c_proj.weight": "encoders.21.fc2.weight",
539
+ "conditioner.embedders.1.model.transformer.resblocks.22.attn.in_proj_bias": ['encoders.22.attn.to_q.bias', 'encoders.22.attn.to_k.bias', 'encoders.22.attn.to_v.bias'],
540
+ "conditioner.embedders.1.model.transformer.resblocks.22.attn.in_proj_weight": ['encoders.22.attn.to_q.weight', 'encoders.22.attn.to_k.weight', 'encoders.22.attn.to_v.weight'],
541
+ "conditioner.embedders.1.model.transformer.resblocks.22.attn.out_proj.bias": "encoders.22.attn.to_out.bias",
542
+ "conditioner.embedders.1.model.transformer.resblocks.22.attn.out_proj.weight": "encoders.22.attn.to_out.weight",
543
+ "conditioner.embedders.1.model.transformer.resblocks.22.ln_1.bias": "encoders.22.layer_norm1.bias",
544
+ "conditioner.embedders.1.model.transformer.resblocks.22.ln_1.weight": "encoders.22.layer_norm1.weight",
545
+ "conditioner.embedders.1.model.transformer.resblocks.22.ln_2.bias": "encoders.22.layer_norm2.bias",
546
+ "conditioner.embedders.1.model.transformer.resblocks.22.ln_2.weight": "encoders.22.layer_norm2.weight",
547
+ "conditioner.embedders.1.model.transformer.resblocks.22.mlp.c_fc.bias": "encoders.22.fc1.bias",
548
+ "conditioner.embedders.1.model.transformer.resblocks.22.mlp.c_fc.weight": "encoders.22.fc1.weight",
549
+ "conditioner.embedders.1.model.transformer.resblocks.22.mlp.c_proj.bias": "encoders.22.fc2.bias",
550
+ "conditioner.embedders.1.model.transformer.resblocks.22.mlp.c_proj.weight": "encoders.22.fc2.weight",
551
+ "conditioner.embedders.1.model.transformer.resblocks.23.attn.in_proj_bias": ['encoders.23.attn.to_q.bias', 'encoders.23.attn.to_k.bias', 'encoders.23.attn.to_v.bias'],
552
+ "conditioner.embedders.1.model.transformer.resblocks.23.attn.in_proj_weight": ['encoders.23.attn.to_q.weight', 'encoders.23.attn.to_k.weight', 'encoders.23.attn.to_v.weight'],
553
+ "conditioner.embedders.1.model.transformer.resblocks.23.attn.out_proj.bias": "encoders.23.attn.to_out.bias",
554
+ "conditioner.embedders.1.model.transformer.resblocks.23.attn.out_proj.weight": "encoders.23.attn.to_out.weight",
555
+ "conditioner.embedders.1.model.transformer.resblocks.23.ln_1.bias": "encoders.23.layer_norm1.bias",
556
+ "conditioner.embedders.1.model.transformer.resblocks.23.ln_1.weight": "encoders.23.layer_norm1.weight",
557
+ "conditioner.embedders.1.model.transformer.resblocks.23.ln_2.bias": "encoders.23.layer_norm2.bias",
558
+ "conditioner.embedders.1.model.transformer.resblocks.23.ln_2.weight": "encoders.23.layer_norm2.weight",
559
+ "conditioner.embedders.1.model.transformer.resblocks.23.mlp.c_fc.bias": "encoders.23.fc1.bias",
560
+ "conditioner.embedders.1.model.transformer.resblocks.23.mlp.c_fc.weight": "encoders.23.fc1.weight",
561
+ "conditioner.embedders.1.model.transformer.resblocks.23.mlp.c_proj.bias": "encoders.23.fc2.bias",
562
+ "conditioner.embedders.1.model.transformer.resblocks.23.mlp.c_proj.weight": "encoders.23.fc2.weight",
563
+ "conditioner.embedders.1.model.transformer.resblocks.24.attn.in_proj_bias": ['encoders.24.attn.to_q.bias', 'encoders.24.attn.to_k.bias', 'encoders.24.attn.to_v.bias'],
564
+ "conditioner.embedders.1.model.transformer.resblocks.24.attn.in_proj_weight": ['encoders.24.attn.to_q.weight', 'encoders.24.attn.to_k.weight', 'encoders.24.attn.to_v.weight'],
565
+ "conditioner.embedders.1.model.transformer.resblocks.24.attn.out_proj.bias": "encoders.24.attn.to_out.bias",
566
+ "conditioner.embedders.1.model.transformer.resblocks.24.attn.out_proj.weight": "encoders.24.attn.to_out.weight",
567
+ "conditioner.embedders.1.model.transformer.resblocks.24.ln_1.bias": "encoders.24.layer_norm1.bias",
568
+ "conditioner.embedders.1.model.transformer.resblocks.24.ln_1.weight": "encoders.24.layer_norm1.weight",
569
+ "conditioner.embedders.1.model.transformer.resblocks.24.ln_2.bias": "encoders.24.layer_norm2.bias",
570
+ "conditioner.embedders.1.model.transformer.resblocks.24.ln_2.weight": "encoders.24.layer_norm2.weight",
571
+ "conditioner.embedders.1.model.transformer.resblocks.24.mlp.c_fc.bias": "encoders.24.fc1.bias",
572
+ "conditioner.embedders.1.model.transformer.resblocks.24.mlp.c_fc.weight": "encoders.24.fc1.weight",
573
+ "conditioner.embedders.1.model.transformer.resblocks.24.mlp.c_proj.bias": "encoders.24.fc2.bias",
574
+ "conditioner.embedders.1.model.transformer.resblocks.24.mlp.c_proj.weight": "encoders.24.fc2.weight",
575
+ "conditioner.embedders.1.model.transformer.resblocks.25.attn.in_proj_bias": ['encoders.25.attn.to_q.bias', 'encoders.25.attn.to_k.bias', 'encoders.25.attn.to_v.bias'],
576
+ "conditioner.embedders.1.model.transformer.resblocks.25.attn.in_proj_weight": ['encoders.25.attn.to_q.weight', 'encoders.25.attn.to_k.weight', 'encoders.25.attn.to_v.weight'],
577
+ "conditioner.embedders.1.model.transformer.resblocks.25.attn.out_proj.bias": "encoders.25.attn.to_out.bias",
578
+ "conditioner.embedders.1.model.transformer.resblocks.25.attn.out_proj.weight": "encoders.25.attn.to_out.weight",
579
+ "conditioner.embedders.1.model.transformer.resblocks.25.ln_1.bias": "encoders.25.layer_norm1.bias",
580
+ "conditioner.embedders.1.model.transformer.resblocks.25.ln_1.weight": "encoders.25.layer_norm1.weight",
581
+ "conditioner.embedders.1.model.transformer.resblocks.25.ln_2.bias": "encoders.25.layer_norm2.bias",
582
+ "conditioner.embedders.1.model.transformer.resblocks.25.ln_2.weight": "encoders.25.layer_norm2.weight",
583
+ "conditioner.embedders.1.model.transformer.resblocks.25.mlp.c_fc.bias": "encoders.25.fc1.bias",
584
+ "conditioner.embedders.1.model.transformer.resblocks.25.mlp.c_fc.weight": "encoders.25.fc1.weight",
585
+ "conditioner.embedders.1.model.transformer.resblocks.25.mlp.c_proj.bias": "encoders.25.fc2.bias",
586
+ "conditioner.embedders.1.model.transformer.resblocks.25.mlp.c_proj.weight": "encoders.25.fc2.weight",
587
+ "conditioner.embedders.1.model.transformer.resblocks.26.attn.in_proj_bias": ['encoders.26.attn.to_q.bias', 'encoders.26.attn.to_k.bias', 'encoders.26.attn.to_v.bias'],
588
+ "conditioner.embedders.1.model.transformer.resblocks.26.attn.in_proj_weight": ['encoders.26.attn.to_q.weight', 'encoders.26.attn.to_k.weight', 'encoders.26.attn.to_v.weight'],
589
+ "conditioner.embedders.1.model.transformer.resblocks.26.attn.out_proj.bias": "encoders.26.attn.to_out.bias",
590
+ "conditioner.embedders.1.model.transformer.resblocks.26.attn.out_proj.weight": "encoders.26.attn.to_out.weight",
591
+ "conditioner.embedders.1.model.transformer.resblocks.26.ln_1.bias": "encoders.26.layer_norm1.bias",
592
+ "conditioner.embedders.1.model.transformer.resblocks.26.ln_1.weight": "encoders.26.layer_norm1.weight",
593
+ "conditioner.embedders.1.model.transformer.resblocks.26.ln_2.bias": "encoders.26.layer_norm2.bias",
594
+ "conditioner.embedders.1.model.transformer.resblocks.26.ln_2.weight": "encoders.26.layer_norm2.weight",
595
+ "conditioner.embedders.1.model.transformer.resblocks.26.mlp.c_fc.bias": "encoders.26.fc1.bias",
596
+ "conditioner.embedders.1.model.transformer.resblocks.26.mlp.c_fc.weight": "encoders.26.fc1.weight",
597
+ "conditioner.embedders.1.model.transformer.resblocks.26.mlp.c_proj.bias": "encoders.26.fc2.bias",
598
+ "conditioner.embedders.1.model.transformer.resblocks.26.mlp.c_proj.weight": "encoders.26.fc2.weight",
599
+ "conditioner.embedders.1.model.transformer.resblocks.27.attn.in_proj_bias": ['encoders.27.attn.to_q.bias', 'encoders.27.attn.to_k.bias', 'encoders.27.attn.to_v.bias'],
600
+ "conditioner.embedders.1.model.transformer.resblocks.27.attn.in_proj_weight": ['encoders.27.attn.to_q.weight', 'encoders.27.attn.to_k.weight', 'encoders.27.attn.to_v.weight'],
601
+ "conditioner.embedders.1.model.transformer.resblocks.27.attn.out_proj.bias": "encoders.27.attn.to_out.bias",
602
+ "conditioner.embedders.1.model.transformer.resblocks.27.attn.out_proj.weight": "encoders.27.attn.to_out.weight",
603
+ "conditioner.embedders.1.model.transformer.resblocks.27.ln_1.bias": "encoders.27.layer_norm1.bias",
604
+ "conditioner.embedders.1.model.transformer.resblocks.27.ln_1.weight": "encoders.27.layer_norm1.weight",
605
+ "conditioner.embedders.1.model.transformer.resblocks.27.ln_2.bias": "encoders.27.layer_norm2.bias",
606
+ "conditioner.embedders.1.model.transformer.resblocks.27.ln_2.weight": "encoders.27.layer_norm2.weight",
607
+ "conditioner.embedders.1.model.transformer.resblocks.27.mlp.c_fc.bias": "encoders.27.fc1.bias",
608
+ "conditioner.embedders.1.model.transformer.resblocks.27.mlp.c_fc.weight": "encoders.27.fc1.weight",
609
+ "conditioner.embedders.1.model.transformer.resblocks.27.mlp.c_proj.bias": "encoders.27.fc2.bias",
610
+ "conditioner.embedders.1.model.transformer.resblocks.27.mlp.c_proj.weight": "encoders.27.fc2.weight",
611
+ "conditioner.embedders.1.model.transformer.resblocks.28.attn.in_proj_bias": ['encoders.28.attn.to_q.bias', 'encoders.28.attn.to_k.bias', 'encoders.28.attn.to_v.bias'],
612
+ "conditioner.embedders.1.model.transformer.resblocks.28.attn.in_proj_weight": ['encoders.28.attn.to_q.weight', 'encoders.28.attn.to_k.weight', 'encoders.28.attn.to_v.weight'],
613
+ "conditioner.embedders.1.model.transformer.resblocks.28.attn.out_proj.bias": "encoders.28.attn.to_out.bias",
614
+ "conditioner.embedders.1.model.transformer.resblocks.28.attn.out_proj.weight": "encoders.28.attn.to_out.weight",
615
+ "conditioner.embedders.1.model.transformer.resblocks.28.ln_1.bias": "encoders.28.layer_norm1.bias",
616
+ "conditioner.embedders.1.model.transformer.resblocks.28.ln_1.weight": "encoders.28.layer_norm1.weight",
617
+ "conditioner.embedders.1.model.transformer.resblocks.28.ln_2.bias": "encoders.28.layer_norm2.bias",
618
+ "conditioner.embedders.1.model.transformer.resblocks.28.ln_2.weight": "encoders.28.layer_norm2.weight",
619
+ "conditioner.embedders.1.model.transformer.resblocks.28.mlp.c_fc.bias": "encoders.28.fc1.bias",
620
+ "conditioner.embedders.1.model.transformer.resblocks.28.mlp.c_fc.weight": "encoders.28.fc1.weight",
621
+ "conditioner.embedders.1.model.transformer.resblocks.28.mlp.c_proj.bias": "encoders.28.fc2.bias",
622
+ "conditioner.embedders.1.model.transformer.resblocks.28.mlp.c_proj.weight": "encoders.28.fc2.weight",
623
+ "conditioner.embedders.1.model.transformer.resblocks.29.attn.in_proj_bias": ['encoders.29.attn.to_q.bias', 'encoders.29.attn.to_k.bias', 'encoders.29.attn.to_v.bias'],
624
+ "conditioner.embedders.1.model.transformer.resblocks.29.attn.in_proj_weight": ['encoders.29.attn.to_q.weight', 'encoders.29.attn.to_k.weight', 'encoders.29.attn.to_v.weight'],
625
+ "conditioner.embedders.1.model.transformer.resblocks.29.attn.out_proj.bias": "encoders.29.attn.to_out.bias",
626
+ "conditioner.embedders.1.model.transformer.resblocks.29.attn.out_proj.weight": "encoders.29.attn.to_out.weight",
627
+ "conditioner.embedders.1.model.transformer.resblocks.29.ln_1.bias": "encoders.29.layer_norm1.bias",
628
+ "conditioner.embedders.1.model.transformer.resblocks.29.ln_1.weight": "encoders.29.layer_norm1.weight",
629
+ "conditioner.embedders.1.model.transformer.resblocks.29.ln_2.bias": "encoders.29.layer_norm2.bias",
630
+ "conditioner.embedders.1.model.transformer.resblocks.29.ln_2.weight": "encoders.29.layer_norm2.weight",
631
+ "conditioner.embedders.1.model.transformer.resblocks.29.mlp.c_fc.bias": "encoders.29.fc1.bias",
632
+ "conditioner.embedders.1.model.transformer.resblocks.29.mlp.c_fc.weight": "encoders.29.fc1.weight",
633
+ "conditioner.embedders.1.model.transformer.resblocks.29.mlp.c_proj.bias": "encoders.29.fc2.bias",
634
+ "conditioner.embedders.1.model.transformer.resblocks.29.mlp.c_proj.weight": "encoders.29.fc2.weight",
635
+ "conditioner.embedders.1.model.transformer.resblocks.3.attn.in_proj_bias": ['encoders.3.attn.to_q.bias', 'encoders.3.attn.to_k.bias', 'encoders.3.attn.to_v.bias'],
636
+ "conditioner.embedders.1.model.transformer.resblocks.3.attn.in_proj_weight": ['encoders.3.attn.to_q.weight', 'encoders.3.attn.to_k.weight', 'encoders.3.attn.to_v.weight'],
637
+ "conditioner.embedders.1.model.transformer.resblocks.3.attn.out_proj.bias": "encoders.3.attn.to_out.bias",
638
+ "conditioner.embedders.1.model.transformer.resblocks.3.attn.out_proj.weight": "encoders.3.attn.to_out.weight",
639
+ "conditioner.embedders.1.model.transformer.resblocks.3.ln_1.bias": "encoders.3.layer_norm1.bias",
640
+ "conditioner.embedders.1.model.transformer.resblocks.3.ln_1.weight": "encoders.3.layer_norm1.weight",
641
+ "conditioner.embedders.1.model.transformer.resblocks.3.ln_2.bias": "encoders.3.layer_norm2.bias",
642
+ "conditioner.embedders.1.model.transformer.resblocks.3.ln_2.weight": "encoders.3.layer_norm2.weight",
643
+ "conditioner.embedders.1.model.transformer.resblocks.3.mlp.c_fc.bias": "encoders.3.fc1.bias",
644
+ "conditioner.embedders.1.model.transformer.resblocks.3.mlp.c_fc.weight": "encoders.3.fc1.weight",
645
+ "conditioner.embedders.1.model.transformer.resblocks.3.mlp.c_proj.bias": "encoders.3.fc2.bias",
646
+ "conditioner.embedders.1.model.transformer.resblocks.3.mlp.c_proj.weight": "encoders.3.fc2.weight",
647
+ "conditioner.embedders.1.model.transformer.resblocks.30.attn.in_proj_bias": ['encoders.30.attn.to_q.bias', 'encoders.30.attn.to_k.bias', 'encoders.30.attn.to_v.bias'],
648
+ "conditioner.embedders.1.model.transformer.resblocks.30.attn.in_proj_weight": ['encoders.30.attn.to_q.weight', 'encoders.30.attn.to_k.weight', 'encoders.30.attn.to_v.weight'],
649
+ "conditioner.embedders.1.model.transformer.resblocks.30.attn.out_proj.bias": "encoders.30.attn.to_out.bias",
650
+ "conditioner.embedders.1.model.transformer.resblocks.30.attn.out_proj.weight": "encoders.30.attn.to_out.weight",
651
+ "conditioner.embedders.1.model.transformer.resblocks.30.ln_1.bias": "encoders.30.layer_norm1.bias",
652
+ "conditioner.embedders.1.model.transformer.resblocks.30.ln_1.weight": "encoders.30.layer_norm1.weight",
653
+ "conditioner.embedders.1.model.transformer.resblocks.30.ln_2.bias": "encoders.30.layer_norm2.bias",
654
+ "conditioner.embedders.1.model.transformer.resblocks.30.ln_2.weight": "encoders.30.layer_norm2.weight",
655
+ "conditioner.embedders.1.model.transformer.resblocks.30.mlp.c_fc.bias": "encoders.30.fc1.bias",
656
+ "conditioner.embedders.1.model.transformer.resblocks.30.mlp.c_fc.weight": "encoders.30.fc1.weight",
657
+ "conditioner.embedders.1.model.transformer.resblocks.30.mlp.c_proj.bias": "encoders.30.fc2.bias",
658
+ "conditioner.embedders.1.model.transformer.resblocks.30.mlp.c_proj.weight": "encoders.30.fc2.weight",
659
+ "conditioner.embedders.1.model.transformer.resblocks.31.attn.in_proj_bias": ['encoders.31.attn.to_q.bias', 'encoders.31.attn.to_k.bias', 'encoders.31.attn.to_v.bias'],
660
+ "conditioner.embedders.1.model.transformer.resblocks.31.attn.in_proj_weight": ['encoders.31.attn.to_q.weight', 'encoders.31.attn.to_k.weight', 'encoders.31.attn.to_v.weight'],
661
+ "conditioner.embedders.1.model.transformer.resblocks.31.attn.out_proj.bias": "encoders.31.attn.to_out.bias",
662
+ "conditioner.embedders.1.model.transformer.resblocks.31.attn.out_proj.weight": "encoders.31.attn.to_out.weight",
663
+ "conditioner.embedders.1.model.transformer.resblocks.31.ln_1.bias": "encoders.31.layer_norm1.bias",
664
+ "conditioner.embedders.1.model.transformer.resblocks.31.ln_1.weight": "encoders.31.layer_norm1.weight",
665
+ "conditioner.embedders.1.model.transformer.resblocks.31.ln_2.bias": "encoders.31.layer_norm2.bias",
666
+ "conditioner.embedders.1.model.transformer.resblocks.31.ln_2.weight": "encoders.31.layer_norm2.weight",
667
+ "conditioner.embedders.1.model.transformer.resblocks.31.mlp.c_fc.bias": "encoders.31.fc1.bias",
668
+ "conditioner.embedders.1.model.transformer.resblocks.31.mlp.c_fc.weight": "encoders.31.fc1.weight",
669
+ "conditioner.embedders.1.model.transformer.resblocks.31.mlp.c_proj.bias": "encoders.31.fc2.bias",
670
+ "conditioner.embedders.1.model.transformer.resblocks.31.mlp.c_proj.weight": "encoders.31.fc2.weight",
671
+ "conditioner.embedders.1.model.transformer.resblocks.4.attn.in_proj_bias": ['encoders.4.attn.to_q.bias', 'encoders.4.attn.to_k.bias', 'encoders.4.attn.to_v.bias'],
672
+ "conditioner.embedders.1.model.transformer.resblocks.4.attn.in_proj_weight": ['encoders.4.attn.to_q.weight', 'encoders.4.attn.to_k.weight', 'encoders.4.attn.to_v.weight'],
673
+ "conditioner.embedders.1.model.transformer.resblocks.4.attn.out_proj.bias": "encoders.4.attn.to_out.bias",
674
+ "conditioner.embedders.1.model.transformer.resblocks.4.attn.out_proj.weight": "encoders.4.attn.to_out.weight",
675
+ "conditioner.embedders.1.model.transformer.resblocks.4.ln_1.bias": "encoders.4.layer_norm1.bias",
676
+ "conditioner.embedders.1.model.transformer.resblocks.4.ln_1.weight": "encoders.4.layer_norm1.weight",
677
+ "conditioner.embedders.1.model.transformer.resblocks.4.ln_2.bias": "encoders.4.layer_norm2.bias",
678
+ "conditioner.embedders.1.model.transformer.resblocks.4.ln_2.weight": "encoders.4.layer_norm2.weight",
679
+ "conditioner.embedders.1.model.transformer.resblocks.4.mlp.c_fc.bias": "encoders.4.fc1.bias",
680
+ "conditioner.embedders.1.model.transformer.resblocks.4.mlp.c_fc.weight": "encoders.4.fc1.weight",
681
+ "conditioner.embedders.1.model.transformer.resblocks.4.mlp.c_proj.bias": "encoders.4.fc2.bias",
682
+ "conditioner.embedders.1.model.transformer.resblocks.4.mlp.c_proj.weight": "encoders.4.fc2.weight",
683
+ "conditioner.embedders.1.model.transformer.resblocks.5.attn.in_proj_bias": ['encoders.5.attn.to_q.bias', 'encoders.5.attn.to_k.bias', 'encoders.5.attn.to_v.bias'],
684
+ "conditioner.embedders.1.model.transformer.resblocks.5.attn.in_proj_weight": ['encoders.5.attn.to_q.weight', 'encoders.5.attn.to_k.weight', 'encoders.5.attn.to_v.weight'],
685
+ "conditioner.embedders.1.model.transformer.resblocks.5.attn.out_proj.bias": "encoders.5.attn.to_out.bias",
686
+ "conditioner.embedders.1.model.transformer.resblocks.5.attn.out_proj.weight": "encoders.5.attn.to_out.weight",
687
+ "conditioner.embedders.1.model.transformer.resblocks.5.ln_1.bias": "encoders.5.layer_norm1.bias",
688
+ "conditioner.embedders.1.model.transformer.resblocks.5.ln_1.weight": "encoders.5.layer_norm1.weight",
689
+ "conditioner.embedders.1.model.transformer.resblocks.5.ln_2.bias": "encoders.5.layer_norm2.bias",
690
+ "conditioner.embedders.1.model.transformer.resblocks.5.ln_2.weight": "encoders.5.layer_norm2.weight",
691
+ "conditioner.embedders.1.model.transformer.resblocks.5.mlp.c_fc.bias": "encoders.5.fc1.bias",
692
+ "conditioner.embedders.1.model.transformer.resblocks.5.mlp.c_fc.weight": "encoders.5.fc1.weight",
693
+ "conditioner.embedders.1.model.transformer.resblocks.5.mlp.c_proj.bias": "encoders.5.fc2.bias",
694
+ "conditioner.embedders.1.model.transformer.resblocks.5.mlp.c_proj.weight": "encoders.5.fc2.weight",
695
+ "conditioner.embedders.1.model.transformer.resblocks.6.attn.in_proj_bias": ['encoders.6.attn.to_q.bias', 'encoders.6.attn.to_k.bias', 'encoders.6.attn.to_v.bias'],
696
+ "conditioner.embedders.1.model.transformer.resblocks.6.attn.in_proj_weight": ['encoders.6.attn.to_q.weight', 'encoders.6.attn.to_k.weight', 'encoders.6.attn.to_v.weight'],
697
+ "conditioner.embedders.1.model.transformer.resblocks.6.attn.out_proj.bias": "encoders.6.attn.to_out.bias",
698
+ "conditioner.embedders.1.model.transformer.resblocks.6.attn.out_proj.weight": "encoders.6.attn.to_out.weight",
699
+ "conditioner.embedders.1.model.transformer.resblocks.6.ln_1.bias": "encoders.6.layer_norm1.bias",
700
+ "conditioner.embedders.1.model.transformer.resblocks.6.ln_1.weight": "encoders.6.layer_norm1.weight",
701
+ "conditioner.embedders.1.model.transformer.resblocks.6.ln_2.bias": "encoders.6.layer_norm2.bias",
702
+ "conditioner.embedders.1.model.transformer.resblocks.6.ln_2.weight": "encoders.6.layer_norm2.weight",
703
+ "conditioner.embedders.1.model.transformer.resblocks.6.mlp.c_fc.bias": "encoders.6.fc1.bias",
704
+ "conditioner.embedders.1.model.transformer.resblocks.6.mlp.c_fc.weight": "encoders.6.fc1.weight",
705
+ "conditioner.embedders.1.model.transformer.resblocks.6.mlp.c_proj.bias": "encoders.6.fc2.bias",
706
+ "conditioner.embedders.1.model.transformer.resblocks.6.mlp.c_proj.weight": "encoders.6.fc2.weight",
707
+ "conditioner.embedders.1.model.transformer.resblocks.7.attn.in_proj_bias": ['encoders.7.attn.to_q.bias', 'encoders.7.attn.to_k.bias', 'encoders.7.attn.to_v.bias'],
708
+ "conditioner.embedders.1.model.transformer.resblocks.7.attn.in_proj_weight": ['encoders.7.attn.to_q.weight', 'encoders.7.attn.to_k.weight', 'encoders.7.attn.to_v.weight'],
709
+ "conditioner.embedders.1.model.transformer.resblocks.7.attn.out_proj.bias": "encoders.7.attn.to_out.bias",
710
+ "conditioner.embedders.1.model.transformer.resblocks.7.attn.out_proj.weight": "encoders.7.attn.to_out.weight",
711
+ "conditioner.embedders.1.model.transformer.resblocks.7.ln_1.bias": "encoders.7.layer_norm1.bias",
712
+ "conditioner.embedders.1.model.transformer.resblocks.7.ln_1.weight": "encoders.7.layer_norm1.weight",
713
+ "conditioner.embedders.1.model.transformer.resblocks.7.ln_2.bias": "encoders.7.layer_norm2.bias",
714
+ "conditioner.embedders.1.model.transformer.resblocks.7.ln_2.weight": "encoders.7.layer_norm2.weight",
715
+ "conditioner.embedders.1.model.transformer.resblocks.7.mlp.c_fc.bias": "encoders.7.fc1.bias",
716
+ "conditioner.embedders.1.model.transformer.resblocks.7.mlp.c_fc.weight": "encoders.7.fc1.weight",
717
+ "conditioner.embedders.1.model.transformer.resblocks.7.mlp.c_proj.bias": "encoders.7.fc2.bias",
718
+ "conditioner.embedders.1.model.transformer.resblocks.7.mlp.c_proj.weight": "encoders.7.fc2.weight",
719
+ "conditioner.embedders.1.model.transformer.resblocks.8.attn.in_proj_bias": ['encoders.8.attn.to_q.bias', 'encoders.8.attn.to_k.bias', 'encoders.8.attn.to_v.bias'],
720
+ "conditioner.embedders.1.model.transformer.resblocks.8.attn.in_proj_weight": ['encoders.8.attn.to_q.weight', 'encoders.8.attn.to_k.weight', 'encoders.8.attn.to_v.weight'],
721
+ "conditioner.embedders.1.model.transformer.resblocks.8.attn.out_proj.bias": "encoders.8.attn.to_out.bias",
722
+ "conditioner.embedders.1.model.transformer.resblocks.8.attn.out_proj.weight": "encoders.8.attn.to_out.weight",
723
+ "conditioner.embedders.1.model.transformer.resblocks.8.ln_1.bias": "encoders.8.layer_norm1.bias",
724
+ "conditioner.embedders.1.model.transformer.resblocks.8.ln_1.weight": "encoders.8.layer_norm1.weight",
725
+ "conditioner.embedders.1.model.transformer.resblocks.8.ln_2.bias": "encoders.8.layer_norm2.bias",
726
+ "conditioner.embedders.1.model.transformer.resblocks.8.ln_2.weight": "encoders.8.layer_norm2.weight",
727
+ "conditioner.embedders.1.model.transformer.resblocks.8.mlp.c_fc.bias": "encoders.8.fc1.bias",
728
+ "conditioner.embedders.1.model.transformer.resblocks.8.mlp.c_fc.weight": "encoders.8.fc1.weight",
729
+ "conditioner.embedders.1.model.transformer.resblocks.8.mlp.c_proj.bias": "encoders.8.fc2.bias",
730
+ "conditioner.embedders.1.model.transformer.resblocks.8.mlp.c_proj.weight": "encoders.8.fc2.weight",
731
+ "conditioner.embedders.1.model.transformer.resblocks.9.attn.in_proj_bias": ['encoders.9.attn.to_q.bias', 'encoders.9.attn.to_k.bias', 'encoders.9.attn.to_v.bias'],
732
+ "conditioner.embedders.1.model.transformer.resblocks.9.attn.in_proj_weight": ['encoders.9.attn.to_q.weight', 'encoders.9.attn.to_k.weight', 'encoders.9.attn.to_v.weight'],
733
+ "conditioner.embedders.1.model.transformer.resblocks.9.attn.out_proj.bias": "encoders.9.attn.to_out.bias",
734
+ "conditioner.embedders.1.model.transformer.resblocks.9.attn.out_proj.weight": "encoders.9.attn.to_out.weight",
735
+ "conditioner.embedders.1.model.transformer.resblocks.9.ln_1.bias": "encoders.9.layer_norm1.bias",
736
+ "conditioner.embedders.1.model.transformer.resblocks.9.ln_1.weight": "encoders.9.layer_norm1.weight",
737
+ "conditioner.embedders.1.model.transformer.resblocks.9.ln_2.bias": "encoders.9.layer_norm2.bias",
738
+ "conditioner.embedders.1.model.transformer.resblocks.9.ln_2.weight": "encoders.9.layer_norm2.weight",
739
+ "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_fc.bias": "encoders.9.fc1.bias",
740
+ "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_fc.weight": "encoders.9.fc1.weight",
741
+ "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.bias": "encoders.9.fc2.bias",
742
+ "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.weight": "encoders.9.fc2.weight",
743
+ "conditioner.embedders.1.model.text_projection": "text_projection.weight",
744
+ }
745
+ state_dict_ = {}
746
+ for name in state_dict:
747
+ if name in rename_dict:
748
+ param = state_dict[name]
749
+ if name == "conditioner.embedders.1.model.positional_embedding":
750
+ param = param.reshape((1, param.shape[0], param.shape[1]))
751
+ elif name == "conditioner.embedders.1.model.text_projection":
752
+ param = param.T
753
+ if isinstance(rename_dict[name], str):
754
+ state_dict_[rename_dict[name]] = param
755
+ else:
756
+ length = param.shape[0] // 3
757
+ for i, rename in enumerate(rename_dict[name]):
758
+ state_dict_[rename] = param[i*length: i*length+length]
759
+ return state_dict_
sdxl_unet.py ADDED
The diff for this file is too large to render. See raw diff
 
sdxl_vae_decoder.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .sd_vae_decoder import SDVAEDecoder, SDVAEDecoderStateDictConverter
2
+
3
+
4
+ class SDXLVAEDecoder(SDVAEDecoder):
5
+ def __init__(self, upcast_to_float32=True):
6
+ super().__init__()
7
+ self.scaling_factor = 0.13025
8
+
9
+ @staticmethod
10
+ def state_dict_converter():
11
+ return SDXLVAEDecoderStateDictConverter()
12
+
13
+
14
+ class SDXLVAEDecoderStateDictConverter(SDVAEDecoderStateDictConverter):
15
+ def __init__(self):
16
+ super().__init__()
17
+
18
+ def from_diffusers(self, state_dict):
19
+ state_dict = super().from_diffusers(state_dict)
20
+ return state_dict, {"upcast_to_float32": True}
21
+
22
+ def from_civitai(self, state_dict):
23
+ state_dict = super().from_civitai(state_dict)
24
+ return state_dict, {"upcast_to_float32": True}
sdxl_vae_encoder.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .sd_vae_encoder import SDVAEEncoderStateDictConverter, SDVAEEncoder
2
+
3
+
4
+ class SDXLVAEEncoder(SDVAEEncoder):
5
+ def __init__(self, upcast_to_float32=True):
6
+ super().__init__()
7
+ self.scaling_factor = 0.13025
8
+
9
+ @staticmethod
10
+ def state_dict_converter():
11
+ return SDXLVAEEncoderStateDictConverter()
12
+
13
+
14
+ class SDXLVAEEncoderStateDictConverter(SDVAEEncoderStateDictConverter):
15
+ def __init__(self):
16
+ super().__init__()
17
+
18
+ def from_diffusers(self, state_dict):
19
+ state_dict = super().from_diffusers(state_dict)
20
+ return state_dict, {"upcast_to_float32": True}
21
+
22
+ def from_civitai(self, state_dict):
23
+ state_dict = super().from_civitai(state_dict)
24
+ return state_dict, {"upcast_to_float32": True}
spatial_grid_memory.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .memory.spatial_grid_memory import * # backward-compat re-export
2
+