Spaces:
Sleeping
Sleeping
Upload models/mmdit
Browse files- models/mmdit/embeddings.py +57 -0
- models/mmdit/layers.py +294 -0
- models/mmdit/mmdit.py +174 -0
- models/mmdit/modules.py +86 -0
models/mmdit/embeddings.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
# https://github.com/facebookresearch/DiT
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TimestepEmbedder(nn.Module):
|
| 8 |
+
"""
|
| 9 |
+
Embeds scalar timesteps into vector representations.
|
| 10 |
+
"""
|
| 11 |
+
def __init__(self, dim, frequency_embedding_size, max_period):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.mlp = nn.Sequential(
|
| 14 |
+
nn.Linear(frequency_embedding_size, dim),
|
| 15 |
+
nn.SiLU(),
|
| 16 |
+
nn.Linear(dim, dim),
|
| 17 |
+
)
|
| 18 |
+
self.dim = dim
|
| 19 |
+
self.max_period = max_period
|
| 20 |
+
assert dim % 2 == 0, 'dim must be even.'
|
| 21 |
+
|
| 22 |
+
with torch.autocast('cuda', enabled=False):
|
| 23 |
+
self.freqs = nn.Buffer(
|
| 24 |
+
1.0 / (
|
| 25 |
+
10000**(
|
| 26 |
+
torch.arange(
|
| 27 |
+
0,
|
| 28 |
+
frequency_embedding_size,
|
| 29 |
+
2,
|
| 30 |
+
dtype=torch.float32
|
| 31 |
+
) / frequency_embedding_size
|
| 32 |
+
)
|
| 33 |
+
),
|
| 34 |
+
persistent=False
|
| 35 |
+
)
|
| 36 |
+
freq_scale = 10000 / max_period
|
| 37 |
+
self.freqs = freq_scale * self.freqs
|
| 38 |
+
|
| 39 |
+
def timestep_embedding(self, t):
|
| 40 |
+
"""
|
| 41 |
+
Create sinusoidal timestep embeddings.
|
| 42 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
| 43 |
+
These may be fractional.
|
| 44 |
+
:param dim: the dimension of the output.
|
| 45 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 46 |
+
:return: an (N, D) Tensor of positional embeddings.
|
| 47 |
+
"""
|
| 48 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 49 |
+
|
| 50 |
+
args = t[:, None].float() * self.freqs[None]
|
| 51 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 52 |
+
return embedding
|
| 53 |
+
|
| 54 |
+
def forward(self, t):
|
| 55 |
+
t_freq = self.timestep_embedding(t).to(t.dtype)
|
| 56 |
+
t_emb = self.mlp(t_freq)
|
| 57 |
+
return t_emb
|
models/mmdit/layers.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from einops.layers.torch import Rearrange
|
| 8 |
+
|
| 9 |
+
from .modules import MLP, ChannelLastConv1d, ConvMLP
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def apply_rope(x: torch.Tensor,
|
| 13 |
+
rot: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 14 |
+
with torch.amp.autocast(device_type='cuda', enabled=False):
|
| 15 |
+
_x = x.float()
|
| 16 |
+
_x = _x.view(*_x.shape[:-1], -1, 1, 2)
|
| 17 |
+
x_out = rot[..., 0] * _x[..., 0] + rot[..., 1] * _x[..., 1]
|
| 18 |
+
return x_out.reshape(*x.shape).to(dtype=x.dtype)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def compute_rope_rotations(
|
| 22 |
+
length: int,
|
| 23 |
+
dim: int,
|
| 24 |
+
theta: int,
|
| 25 |
+
*,
|
| 26 |
+
freq_scaling: float = 1.0,
|
| 27 |
+
device: torch.device | str = 'cpu'
|
| 28 |
+
) -> torch.Tensor:
|
| 29 |
+
assert dim % 2 == 0
|
| 30 |
+
|
| 31 |
+
with torch.amp.autocast(device_type='cuda', enabled=False):
|
| 32 |
+
pos = torch.arange(length, dtype=torch.float32, device=device)
|
| 33 |
+
freqs = 1.0 / (
|
| 34 |
+
theta**(
|
| 35 |
+
torch.arange(0, dim, 2, dtype=torch.float32, device=device) /
|
| 36 |
+
dim
|
| 37 |
+
)
|
| 38 |
+
)
|
| 39 |
+
freqs *= freq_scaling
|
| 40 |
+
|
| 41 |
+
rot = torch.einsum('..., f -> ... f', pos, freqs)
|
| 42 |
+
rot = torch.stack([
|
| 43 |
+
torch.cos(rot), -torch.sin(rot),
|
| 44 |
+
torch.sin(rot),
|
| 45 |
+
torch.cos(rot)
|
| 46 |
+
],
|
| 47 |
+
dim=-1)
|
| 48 |
+
rot = rearrange(rot, 'n d (i j) -> 1 n d i j', i=2, j=2)
|
| 49 |
+
return rot
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
|
| 53 |
+
return x * (1 + scale) + shift
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def attention(
|
| 57 |
+
q: torch.Tensor,
|
| 58 |
+
k: torch.Tensor,
|
| 59 |
+
v: torch.Tensor,
|
| 60 |
+
mask: Optional[torch.Tensor] = None
|
| 61 |
+
):
|
| 62 |
+
# training will crash without these contiguous calls and the CUDNN limitation
|
| 63 |
+
# I believe this is related to https://github.com/pytorch/pytorch/issues/133974
|
| 64 |
+
# unresolved at the time of writing
|
| 65 |
+
q = q.contiguous()
|
| 66 |
+
k = k.contiguous()
|
| 67 |
+
v = v.contiguous()
|
| 68 |
+
if mask is not None:
|
| 69 |
+
# Convert key padding mask [B, S] to a broadcastable attention mask
|
| 70 |
+
# shape [B, 1, 1, S] for SDPA.
|
| 71 |
+
if mask.ndim == 2:
|
| 72 |
+
mask = mask[:, None, None, :]
|
| 73 |
+
elif mask.ndim == 3:
|
| 74 |
+
# Allow [B, L, S] masks by inserting a head axis.
|
| 75 |
+
mask = mask[:, None, :, :]
|
| 76 |
+
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 77 |
+
out = rearrange(out, 'b h n d -> b n (h d)').contiguous()
|
| 78 |
+
return out
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class SelfAttention(nn.Module):
|
| 82 |
+
def __init__(self, dim: int, nheads: int):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.dim = dim
|
| 85 |
+
self.nheads = nheads
|
| 86 |
+
|
| 87 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=True)
|
| 88 |
+
self.q_norm = nn.RMSNorm(dim // nheads)
|
| 89 |
+
self.k_norm = nn.RMSNorm(dim // nheads)
|
| 90 |
+
|
| 91 |
+
self.split_into_heads = Rearrange(
|
| 92 |
+
'b n (h d j) -> b h n d j', h=nheads, d=dim // nheads, j=3
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def pre_attention(
|
| 96 |
+
self, x: torch.Tensor, rot: Optional[torch.Tensor]
|
| 97 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 98 |
+
# x: batch_size * n_tokens * n_channels
|
| 99 |
+
qkv = self.qkv(x)
|
| 100 |
+
q, k, v = self.split_into_heads(qkv).chunk(3, dim=-1)
|
| 101 |
+
q = q.squeeze(-1)
|
| 102 |
+
k = k.squeeze(-1)
|
| 103 |
+
v = v.squeeze(-1)
|
| 104 |
+
q = self.q_norm(q)
|
| 105 |
+
k = self.k_norm(k)
|
| 106 |
+
|
| 107 |
+
if rot is not None:
|
| 108 |
+
q = apply_rope(q, rot)
|
| 109 |
+
k = apply_rope(k, rot)
|
| 110 |
+
|
| 111 |
+
return q, k, v
|
| 112 |
+
|
| 113 |
+
def forward(
|
| 114 |
+
self,
|
| 115 |
+
x: torch.Tensor, # batch_size * n_tokens * n_channels
|
| 116 |
+
) -> torch.Tensor:
|
| 117 |
+
q, k, v = self.pre_attention(x)
|
| 118 |
+
out = attention(q, k, v)
|
| 119 |
+
return out
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class MMDitSingleBlock(nn.Module):
|
| 123 |
+
def __init__(
|
| 124 |
+
self,
|
| 125 |
+
dim: int,
|
| 126 |
+
nhead: int,
|
| 127 |
+
mlp_ratio: float = 4.0,
|
| 128 |
+
pre_only: bool = False,
|
| 129 |
+
kernel_size: int = 7,
|
| 130 |
+
padding: int = 3
|
| 131 |
+
):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.norm1 = nn.LayerNorm(dim, elementwise_affine=False)
|
| 134 |
+
self.attn = SelfAttention(dim, nhead)
|
| 135 |
+
|
| 136 |
+
self.pre_only = pre_only
|
| 137 |
+
if pre_only:
|
| 138 |
+
self.adaLN_modulation = nn.Sequential(
|
| 139 |
+
nn.SiLU(), nn.Linear(dim, 2 * dim, bias=True)
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
if kernel_size == 1:
|
| 143 |
+
self.linear1 = nn.Linear(dim, dim)
|
| 144 |
+
else:
|
| 145 |
+
self.linear1 = ChannelLastConv1d(
|
| 146 |
+
dim, dim, kernel_size=kernel_size, padding=padding
|
| 147 |
+
)
|
| 148 |
+
self.norm2 = nn.LayerNorm(dim, elementwise_affine=False)
|
| 149 |
+
|
| 150 |
+
if kernel_size == 1:
|
| 151 |
+
self.ffn = MLP(dim, int(dim * mlp_ratio))
|
| 152 |
+
else:
|
| 153 |
+
self.ffn = ConvMLP(
|
| 154 |
+
dim,
|
| 155 |
+
int(dim * mlp_ratio),
|
| 156 |
+
kernel_size=kernel_size,
|
| 157 |
+
padding=padding
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
self.adaLN_modulation = nn.Sequential(
|
| 161 |
+
nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True)
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def pre_attention(
|
| 165 |
+
self, x: torch.Tensor, c: torch.Tensor, rot: Optional[torch.Tensor]
|
| 166 |
+
):
|
| 167 |
+
# x: BS * N * D
|
| 168 |
+
# cond: BS * D
|
| 169 |
+
modulation = self.adaLN_modulation(c)
|
| 170 |
+
if self.pre_only:
|
| 171 |
+
(shift_msa, scale_msa) = modulation.chunk(2, dim=-1)
|
| 172 |
+
gate_msa = shift_mlp = scale_mlp = gate_mlp = None
|
| 173 |
+
else:
|
| 174 |
+
(shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp,
|
| 175 |
+
gate_mlp) = modulation.chunk(6, dim=-1)
|
| 176 |
+
|
| 177 |
+
x = modulate(self.norm1(x), shift_msa, scale_msa)
|
| 178 |
+
q, k, v = self.attn.pre_attention(x, rot)
|
| 179 |
+
return (q, k, v), (gate_msa, shift_mlp, scale_mlp, gate_mlp)
|
| 180 |
+
|
| 181 |
+
def post_attention(
|
| 182 |
+
self, x: torch.Tensor, attn_out: torch.Tensor, c: tuple[torch.Tensor]
|
| 183 |
+
):
|
| 184 |
+
if self.pre_only:
|
| 185 |
+
return x
|
| 186 |
+
|
| 187 |
+
(gate_msa, shift_mlp, scale_mlp, gate_mlp) = c
|
| 188 |
+
x = x + self.linear1(attn_out) * gate_msa
|
| 189 |
+
r = modulate(self.norm2(x), shift_mlp, scale_mlp)
|
| 190 |
+
x = x + self.ffn(r) * gate_mlp
|
| 191 |
+
|
| 192 |
+
return x
|
| 193 |
+
|
| 194 |
+
def forward(
|
| 195 |
+
self,
|
| 196 |
+
x: torch.Tensor,
|
| 197 |
+
cond: torch.Tensor,
|
| 198 |
+
rot: Optional[torch.Tensor],
|
| 199 |
+
mask: Optional[torch.Tensor] = None
|
| 200 |
+
) -> torch.Tensor:
|
| 201 |
+
# x: BS * N * D
|
| 202 |
+
# cond: BS * D
|
| 203 |
+
x_qkv, x_conditions = self.pre_attention(x, cond, rot)
|
| 204 |
+
attn_out = attention(*x_qkv, mask=mask)
|
| 205 |
+
x = self.post_attention(x, attn_out, x_conditions)
|
| 206 |
+
|
| 207 |
+
return x
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class JointBlock(nn.Module):
|
| 211 |
+
def __init__(
|
| 212 |
+
self,
|
| 213 |
+
dim: int,
|
| 214 |
+
nhead: int,
|
| 215 |
+
mlp_ratio: float = 4.0,
|
| 216 |
+
pre_only: bool = False
|
| 217 |
+
):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.pre_only = pre_only
|
| 220 |
+
self.latent_block = MMDitSingleBlock(
|
| 221 |
+
dim, nhead, mlp_ratio, pre_only=False, kernel_size=3, padding=1
|
| 222 |
+
)
|
| 223 |
+
self.nta_block = MMDitSingleBlock(
|
| 224 |
+
dim, nhead, mlp_ratio, pre_only=pre_only, kernel_size=1
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
def forward(
|
| 228 |
+
self,
|
| 229 |
+
latent: torch.Tensor,
|
| 230 |
+
nta_content: torch.Tensor,
|
| 231 |
+
nta_content_global: torch.Tensor,
|
| 232 |
+
ta_content: torch.Tensor,
|
| 233 |
+
latent_rot: torch.Tensor,
|
| 234 |
+
latent_mask: Optional[torch.Tensor] = None,
|
| 235 |
+
nta_content_mask: Optional[torch.Tensor] = None,
|
| 236 |
+
):
|
| 237 |
+
x_qkv, x_mod = self.latent_block.pre_attention(
|
| 238 |
+
latent, ta_content, latent_rot
|
| 239 |
+
)
|
| 240 |
+
nta_qkv, nta_mod = self.nta_block.pre_attention(
|
| 241 |
+
nta_content, nta_content_global, rot=None
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
latent_len = latent.shape[1]
|
| 245 |
+
|
| 246 |
+
joint_qkv = [
|
| 247 |
+
torch.cat([x_qkv[i], nta_qkv[i]], dim=2) for i in range(3)
|
| 248 |
+
]
|
| 249 |
+
|
| 250 |
+
attn_mask = None
|
| 251 |
+
if latent_mask is not None or nta_content_mask is not None:
|
| 252 |
+
if latent_mask is None:
|
| 253 |
+
latent_mask = torch.ones(
|
| 254 |
+
latent.shape[0],
|
| 255 |
+
latent.shape[1],
|
| 256 |
+
dtype=torch.bool,
|
| 257 |
+
device=latent.device
|
| 258 |
+
)
|
| 259 |
+
if nta_content_mask is None:
|
| 260 |
+
nta_content_mask = torch.ones(
|
| 261 |
+
nta_content.shape[0],
|
| 262 |
+
nta_content.shape[1],
|
| 263 |
+
dtype=torch.bool,
|
| 264 |
+
device=nta_content.device
|
| 265 |
+
)
|
| 266 |
+
attn_mask = torch.cat([latent_mask, nta_content_mask], dim=1)
|
| 267 |
+
|
| 268 |
+
attn_out = attention(*joint_qkv, mask=attn_mask)
|
| 269 |
+
x_attn_out = attn_out[:, :latent_len]
|
| 270 |
+
nta_attn_out = attn_out[:, latent_len:]
|
| 271 |
+
|
| 272 |
+
latent = self.latent_block.post_attention(latent, x_attn_out, x_mod)
|
| 273 |
+
if not self.pre_only:
|
| 274 |
+
nta_content = self.nta_block.post_attention(
|
| 275 |
+
nta_content, nta_attn_out, nta_mod
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
return latent, nta_content
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class FinalBlock(nn.Module):
|
| 282 |
+
def __init__(self, dim, out_dim):
|
| 283 |
+
super().__init__()
|
| 284 |
+
self.adaLN_modulation = nn.Sequential(
|
| 285 |
+
nn.SiLU(), nn.Linear(dim, 2 * dim, bias=True)
|
| 286 |
+
)
|
| 287 |
+
self.norm = nn.LayerNorm(dim, elementwise_affine=False)
|
| 288 |
+
self.conv = ChannelLastConv1d(dim, out_dim, kernel_size=7, padding=3)
|
| 289 |
+
|
| 290 |
+
def forward(self, latent, c):
|
| 291 |
+
shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
|
| 292 |
+
latent = modulate(self.norm(latent), shift, scale)
|
| 293 |
+
latent = self.conv(latent)
|
| 294 |
+
return latent
|
models/mmdit/mmdit.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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3 |
+
|
| 4 |
+
from .embeddings import TimestepEmbedder
|
| 5 |
+
from .layers import FinalBlock, JointBlock, MMDitSingleBlock, compute_rope_rotations
|
| 6 |
+
from .modules import ChannelLastConv1d, ConvMLP, MLP
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class MMDiT(nn.Module):
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
*,
|
| 13 |
+
latent_dim: int,
|
| 14 |
+
ta_context_dim: int,
|
| 15 |
+
context_dim: int,
|
| 16 |
+
embed_dim: int,
|
| 17 |
+
depth: int,
|
| 18 |
+
fused_depth: int,
|
| 19 |
+
num_heads: int,
|
| 20 |
+
mlp_ratio: float = 4.0,
|
| 21 |
+
use_checkpoint: bool = False
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
|
| 25 |
+
self.latent_dim = latent_dim
|
| 26 |
+
hidden_dim = embed_dim
|
| 27 |
+
self.hidden_dim = embed_dim
|
| 28 |
+
self.num_heads = num_heads
|
| 29 |
+
|
| 30 |
+
self.input_proj = nn.Sequential(
|
| 31 |
+
ChannelLastConv1d(
|
| 32 |
+
latent_dim, hidden_dim, kernel_size=7, padding=3
|
| 33 |
+
),
|
| 34 |
+
nn.SiLU(),
|
| 35 |
+
ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=7, padding=3),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
self.nta_proj = nn.Sequential(
|
| 39 |
+
nn.Linear(context_dim, hidden_dim),
|
| 40 |
+
nn.SiLU(),
|
| 41 |
+
ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=3, padding=1),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
self.ta_proj = nn.Sequential(
|
| 45 |
+
ChannelLastConv1d(
|
| 46 |
+
ta_context_dim, hidden_dim, kernel_size=7, padding=3
|
| 47 |
+
),
|
| 48 |
+
nn.SiLU(),
|
| 49 |
+
ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=7, padding=3),
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
self.nta_global_proj = nn.Linear(hidden_dim, hidden_dim)
|
| 53 |
+
|
| 54 |
+
self.final_layer = FinalBlock(hidden_dim, latent_dim)
|
| 55 |
+
|
| 56 |
+
self.t_embed = TimestepEmbedder(
|
| 57 |
+
hidden_dim, frequency_embedding_size=hidden_dim, max_period=1
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
self.joint_blocks = nn.ModuleList([
|
| 61 |
+
JointBlock(
|
| 62 |
+
hidden_dim,
|
| 63 |
+
num_heads,
|
| 64 |
+
mlp_ratio=mlp_ratio,
|
| 65 |
+
pre_only=(i == depth - fused_depth - 1)
|
| 66 |
+
) for i in range(depth - fused_depth)
|
| 67 |
+
])
|
| 68 |
+
|
| 69 |
+
self.fused_blocks = nn.ModuleList([
|
| 70 |
+
MMDitSingleBlock(
|
| 71 |
+
hidden_dim,
|
| 72 |
+
num_heads,
|
| 73 |
+
mlp_ratio=mlp_ratio,
|
| 74 |
+
kernel_size=3,
|
| 75 |
+
padding=1
|
| 76 |
+
) for i in range(fused_depth)
|
| 77 |
+
])
|
| 78 |
+
|
| 79 |
+
self.initialize_weights()
|
| 80 |
+
self._latent_seq_len_cached = None
|
| 81 |
+
|
| 82 |
+
def update_seq_lengths(self, latent_seq_len: int):
|
| 83 |
+
if latent_seq_len != self._latent_seq_len_cached:
|
| 84 |
+
self._latent_seq_len_cached = latent_seq_len
|
| 85 |
+
|
| 86 |
+
base_freq = 1.0
|
| 87 |
+
latent_rot = compute_rope_rotations(
|
| 88 |
+
latent_seq_len,
|
| 89 |
+
self.hidden_dim // self.num_heads,
|
| 90 |
+
10000,
|
| 91 |
+
freq_scaling=base_freq,
|
| 92 |
+
device=self.device
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
self.latent_rot = nn.Buffer(latent_rot, persistent=False)
|
| 96 |
+
|
| 97 |
+
def initialize_weights(self):
|
| 98 |
+
def _basic_init(module):
|
| 99 |
+
if isinstance(module, nn.Linear):
|
| 100 |
+
torch.nn.init.xavier_uniform_(module.weight)
|
| 101 |
+
if module.bias is not None:
|
| 102 |
+
nn.init.constant_(module.bias, 0)
|
| 103 |
+
|
| 104 |
+
self.apply(_basic_init)
|
| 105 |
+
|
| 106 |
+
# Initialize timestep embedding MLP:
|
| 107 |
+
nn.init.normal_(self.t_embed.mlp[0].weight, std=0.02)
|
| 108 |
+
nn.init.normal_(self.t_embed.mlp[2].weight, std=0.02)
|
| 109 |
+
|
| 110 |
+
# Zero-out adaLN modulation layers in DiT blocks:
|
| 111 |
+
for block in self.joint_blocks:
|
| 112 |
+
nn.init.constant_(
|
| 113 |
+
block.latent_block.adaLN_modulation[-1].weight, 0
|
| 114 |
+
)
|
| 115 |
+
nn.init.constant_(block.latent_block.adaLN_modulation[-1].bias, 0)
|
| 116 |
+
nn.init.constant_(block.nta_block.adaLN_modulation[-1].weight, 0)
|
| 117 |
+
nn.init.constant_(block.nta_block.adaLN_modulation[-1].bias, 0)
|
| 118 |
+
for block in self.fused_blocks:
|
| 119 |
+
nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
|
| 120 |
+
nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
|
| 121 |
+
|
| 122 |
+
# Zero-out output layers:
|
| 123 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
|
| 124 |
+
nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
|
| 125 |
+
nn.init.constant_(self.final_layer.conv.weight, 0)
|
| 126 |
+
nn.init.constant_(self.final_layer.conv.bias, 0)
|
| 127 |
+
|
| 128 |
+
def forward(
|
| 129 |
+
self,
|
| 130 |
+
x: torch.Tensor,
|
| 131 |
+
timesteps: torch.Tensor,
|
| 132 |
+
time_aligned_context: torch.Tensor,
|
| 133 |
+
context: torch.Tensor,
|
| 134 |
+
x_mask=None,
|
| 135 |
+
context_mask=None
|
| 136 |
+
) -> torch.Tensor:
|
| 137 |
+
|
| 138 |
+
if timesteps.dim() == 0:
|
| 139 |
+
timesteps = timesteps.expand(x.shape[0]
|
| 140 |
+
).to(x.device, dtype=x.dtype)
|
| 141 |
+
|
| 142 |
+
latent = self.input_proj(x.transpose(1, 2)) # (B, N, D)
|
| 143 |
+
context = self.nta_proj(context)
|
| 144 |
+
time_aligned_context = self.ta_proj(time_aligned_context)
|
| 145 |
+
|
| 146 |
+
global_c = self.nta_global_proj(context.mean(dim=1))
|
| 147 |
+
|
| 148 |
+
global_c = self.t_embed(timesteps).unsqueeze(1) + global_c.unsqueeze(
|
| 149 |
+
1
|
| 150 |
+
) # (B, D)
|
| 151 |
+
extended_c = global_c + time_aligned_context
|
| 152 |
+
|
| 153 |
+
self.update_seq_lengths(latent.shape[1])
|
| 154 |
+
|
| 155 |
+
for block in self.joint_blocks:
|
| 156 |
+
latent, context = block(
|
| 157 |
+
latent,
|
| 158 |
+
context,
|
| 159 |
+
global_c,
|
| 160 |
+
extended_c,
|
| 161 |
+
self.latent_rot,
|
| 162 |
+
latent_mask=x_mask,
|
| 163 |
+
nta_content_mask=context_mask,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
for block in self.fused_blocks:
|
| 167 |
+
latent = block(latent, extended_c, self.latent_rot, mask=x_mask)
|
| 168 |
+
|
| 169 |
+
flow = self.final_layer(latent, extended_c)
|
| 170 |
+
return flow.transpose(1, 2)
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def device(self) -> torch.device:
|
| 174 |
+
return self.nta_global_proj.weight.device
|
models/mmdit/modules.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 ChannelLastConv1d(nn.Conv1d):
|
| 7 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 8 |
+
x = x.permute(0, 2, 1)
|
| 9 |
+
x = super().forward(x)
|
| 10 |
+
x = x.permute(0, 2, 1)
|
| 11 |
+
return x
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# https://github.com/Stability-AI/sd3-ref
|
| 15 |
+
class MLP(nn.Module):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
dim: int,
|
| 19 |
+
hidden_dim: int,
|
| 20 |
+
multiple_of: int = 256,
|
| 21 |
+
):
|
| 22 |
+
"""
|
| 23 |
+
Initialize the FeedForward module.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
dim (int): Input dimension.
|
| 27 |
+
hidden_dim (int): Hidden dimension of the feedforward layer.
|
| 28 |
+
multiple_of (int): Value to ensure hidden dimension is a multiple of this value.
|
| 29 |
+
|
| 30 |
+
Attributes:
|
| 31 |
+
w1 (ColumnParallelLinear): Linear transformation for the first layer.
|
| 32 |
+
w2 (RowParallelLinear): Linear transformation for the second layer.
|
| 33 |
+
w3 (ColumnParallelLinear): Linear transformation for the third layer.
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
super().__init__()
|
| 37 |
+
hidden_dim = int(2 * hidden_dim / 3)
|
| 38 |
+
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) //
|
| 39 |
+
multiple_of)
|
| 40 |
+
|
| 41 |
+
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
|
| 42 |
+
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
| 43 |
+
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
|
| 44 |
+
|
| 45 |
+
def forward(self, x):
|
| 46 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ConvMLP(nn.Module):
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
dim: int,
|
| 53 |
+
hidden_dim: int,
|
| 54 |
+
multiple_of: int = 256,
|
| 55 |
+
kernel_size: int = 3,
|
| 56 |
+
padding: int = 1,
|
| 57 |
+
):
|
| 58 |
+
super().__init__()
|
| 59 |
+
hidden_dim = int(2 * hidden_dim / 3)
|
| 60 |
+
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) //
|
| 61 |
+
multiple_of)
|
| 62 |
+
|
| 63 |
+
self.w1 = ChannelLastConv1d(
|
| 64 |
+
dim,
|
| 65 |
+
hidden_dim,
|
| 66 |
+
bias=False,
|
| 67 |
+
kernel_size=kernel_size,
|
| 68 |
+
padding=padding
|
| 69 |
+
)
|
| 70 |
+
self.w2 = ChannelLastConv1d(
|
| 71 |
+
hidden_dim,
|
| 72 |
+
dim,
|
| 73 |
+
bias=False,
|
| 74 |
+
kernel_size=kernel_size,
|
| 75 |
+
padding=padding
|
| 76 |
+
)
|
| 77 |
+
self.w3 = ChannelLastConv1d(
|
| 78 |
+
dim,
|
| 79 |
+
hidden_dim,
|
| 80 |
+
bias=False,
|
| 81 |
+
kernel_size=kernel_size,
|
| 82 |
+
padding=padding
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def forward(self, x):
|
| 86 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|