Spaces:
Runtime error
Runtime error
Delete models/denoiser/nextdit/modeling_nextdit.py with huggingface_hub
Browse files
models/denoiser/nextdit/modeling_nextdit.py
DELETED
|
@@ -1,571 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
-
import torch.nn.functional as F
|
| 5 |
-
import numpy as np
|
| 6 |
-
import einops
|
| 7 |
-
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 8 |
-
from diffusers.models.modeling_utils import ModelMixin
|
| 9 |
-
from typing import Any, Tuple, Optional
|
| 10 |
-
from flash_attn import flash_attn_varlen_func
|
| 11 |
-
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
| 12 |
-
|
| 13 |
-
from .layers import LLamaFeedForward, RMSNorm
|
| 14 |
-
|
| 15 |
-
# import frasch
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def modulate(x, scale):
|
| 19 |
-
return x * (1 + scale)
|
| 20 |
-
|
| 21 |
-
class TimestepEmbedder(nn.Module):
|
| 22 |
-
"""
|
| 23 |
-
Embeds scalar timesteps into vector representations.
|
| 24 |
-
"""
|
| 25 |
-
def __init__(self, hidden_size, frequency_embedding_size=256):
|
| 26 |
-
super().__init__()
|
| 27 |
-
self.hidden_size = hidden_size
|
| 28 |
-
self.frequency_embedding_size = frequency_embedding_size
|
| 29 |
-
self.mlp = nn.Sequential(
|
| 30 |
-
nn.Linear(self.frequency_embedding_size, self.hidden_size),
|
| 31 |
-
nn.SiLU(),
|
| 32 |
-
nn.Linear(self.hidden_size, self.hidden_size),
|
| 33 |
-
)
|
| 34 |
-
|
| 35 |
-
@staticmethod
|
| 36 |
-
def timestep_embedding(t, dim, max_period=10000):
|
| 37 |
-
"""
|
| 38 |
-
Create sinusoidal timestep embeddings.
|
| 39 |
-
:param t: a 1-D Tensor of N indices, one per batch element.
|
| 40 |
-
:param dim: the dimension of the output.
|
| 41 |
-
:param max_period: controls the minimum frequency of the embeddings.
|
| 42 |
-
:return: an (N, D) Tensor of positional embeddings.
|
| 43 |
-
"""
|
| 44 |
-
half = dim // 2
|
| 45 |
-
freqs = torch.exp(
|
| 46 |
-
-np.log(max_period) * torch.arange(0, half, dtype=t.dtype) / half
|
| 47 |
-
).to(t.device)
|
| 48 |
-
args = t[:, :, None] * freqs[None, :]
|
| 49 |
-
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 50 |
-
if dim % 2:
|
| 51 |
-
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :, :1])], dim=-1)
|
| 52 |
-
return embedding
|
| 53 |
-
|
| 54 |
-
def forward(self, t):
|
| 55 |
-
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 56 |
-
t_freq = t_freq.to(self.mlp[0].weight.dtype)
|
| 57 |
-
return self.mlp(t_freq)
|
| 58 |
-
|
| 59 |
-
class FinalLayer(nn.Module):
|
| 60 |
-
def __init__(self, hidden_size, num_patches, out_channels):
|
| 61 |
-
super().__init__()
|
| 62 |
-
self.norm_final = nn.LayerNorm(hidden_size, eps=1e-6, elementwise_affine=False)
|
| 63 |
-
self.linear = nn.Linear(hidden_size, num_patches * out_channels)
|
| 64 |
-
self.adaLN_modulation = nn.Sequential(
|
| 65 |
-
nn.SiLU(),
|
| 66 |
-
nn.Linear(min(hidden_size, 1024), hidden_size),
|
| 67 |
-
)
|
| 68 |
-
|
| 69 |
-
def forward(self, x, c):
|
| 70 |
-
scale = self.adaLN_modulation(c)
|
| 71 |
-
x = modulate(self.norm_final(x), scale)
|
| 72 |
-
x = self.linear(x)
|
| 73 |
-
return x
|
| 74 |
-
|
| 75 |
-
class Attention(nn.Module):
|
| 76 |
-
def __init__(
|
| 77 |
-
self,
|
| 78 |
-
dim,
|
| 79 |
-
n_heads,
|
| 80 |
-
n_kv_heads=None,
|
| 81 |
-
qk_norm=False,
|
| 82 |
-
y_dim=0,
|
| 83 |
-
base_seqlen=None,
|
| 84 |
-
proportional_attn=False,
|
| 85 |
-
attention_dropout=0.0,
|
| 86 |
-
max_position_embeddings=384,
|
| 87 |
-
):
|
| 88 |
-
super().__init__()
|
| 89 |
-
self.dim = dim
|
| 90 |
-
self.n_heads = n_heads
|
| 91 |
-
self.n_kv_heads = n_kv_heads or n_heads
|
| 92 |
-
self.qk_norm = qk_norm
|
| 93 |
-
self.y_dim = y_dim
|
| 94 |
-
self.base_seqlen = base_seqlen
|
| 95 |
-
self.proportional_attn = proportional_attn
|
| 96 |
-
self.attention_dropout = attention_dropout
|
| 97 |
-
self.max_position_embeddings = max_position_embeddings
|
| 98 |
-
|
| 99 |
-
self.head_dim = dim // n_heads
|
| 100 |
-
|
| 101 |
-
self.wq = nn.Linear(dim, n_heads * self.head_dim, bias=False)
|
| 102 |
-
self.wk = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=False)
|
| 103 |
-
self.wv = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=False)
|
| 104 |
-
|
| 105 |
-
if y_dim > 0:
|
| 106 |
-
self.wk_y = nn.Linear(y_dim, self.n_kv_heads * self.head_dim, bias=False)
|
| 107 |
-
self.wv_y = nn.Linear(y_dim, self.n_kv_heads * self.head_dim, bias=False)
|
| 108 |
-
self.gate = nn.Parameter(torch.zeros(n_heads))
|
| 109 |
-
|
| 110 |
-
self.wo = nn.Linear(n_heads * self.head_dim, dim, bias=False)
|
| 111 |
-
|
| 112 |
-
if qk_norm:
|
| 113 |
-
self.q_norm = nn.LayerNorm(self.n_heads * self.head_dim)
|
| 114 |
-
self.k_norm = nn.LayerNorm(self.n_kv_heads * self.head_dim)
|
| 115 |
-
if y_dim > 0:
|
| 116 |
-
self.ky_norm = nn.LayerNorm(self.n_kv_heads * self.head_dim, eps=1e-6)
|
| 117 |
-
else:
|
| 118 |
-
self.ky_norm = nn.Identity()
|
| 119 |
-
else:
|
| 120 |
-
self.q_norm = nn.Identity()
|
| 121 |
-
self.k_norm = nn.Identity()
|
| 122 |
-
self.ky_norm = nn.Identity()
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
@staticmethod
|
| 126 |
-
def apply_rotary_emb(xq, xk, freqs_cis):
|
| 127 |
-
# xq, xk: [batch_size, seq_len, n_heads, head_dim]
|
| 128 |
-
# freqs_cis: [1, seq_len, 1, head_dim]
|
| 129 |
-
xq_ = xq.float().reshape(*xq.shape[:-1], -1, 2)
|
| 130 |
-
xk_ = xk.float().reshape(*xk.shape[:-1], -1, 2)
|
| 131 |
-
|
| 132 |
-
xq_complex = torch.view_as_complex(xq_)
|
| 133 |
-
xk_complex = torch.view_as_complex(xk_)
|
| 134 |
-
|
| 135 |
-
freqs_cis = freqs_cis.unsqueeze(2)
|
| 136 |
-
|
| 137 |
-
# Apply freqs_cis
|
| 138 |
-
xq_out = xq_complex * freqs_cis
|
| 139 |
-
xk_out = xk_complex * freqs_cis
|
| 140 |
-
|
| 141 |
-
# Convert back to real numbers
|
| 142 |
-
xq_out = torch.view_as_real(xq_out).flatten(-2)
|
| 143 |
-
xk_out = torch.view_as_real(xk_out).flatten(-2)
|
| 144 |
-
|
| 145 |
-
return xq_out.type_as(xq), xk_out.type_as(xk)
|
| 146 |
-
|
| 147 |
-
# copied from huggingface modeling_llama.py
|
| 148 |
-
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
| 149 |
-
def _get_unpad_data(attention_mask):
|
| 150 |
-
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
| 151 |
-
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 152 |
-
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
| 153 |
-
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
| 154 |
-
return (
|
| 155 |
-
indices,
|
| 156 |
-
cu_seqlens,
|
| 157 |
-
max_seqlen_in_batch,
|
| 158 |
-
)
|
| 159 |
-
|
| 160 |
-
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
| 161 |
-
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
| 162 |
-
|
| 163 |
-
key_layer = index_first_axis(
|
| 164 |
-
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
| 165 |
-
indices_k,
|
| 166 |
-
)
|
| 167 |
-
value_layer = index_first_axis(
|
| 168 |
-
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
| 169 |
-
indices_k,
|
| 170 |
-
)
|
| 171 |
-
if query_length == kv_seq_len:
|
| 172 |
-
query_layer = index_first_axis(
|
| 173 |
-
query_layer.reshape(batch_size * kv_seq_len, self.n_heads, head_dim),
|
| 174 |
-
indices_k,
|
| 175 |
-
)
|
| 176 |
-
cu_seqlens_q = cu_seqlens_k
|
| 177 |
-
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 178 |
-
indices_q = indices_k
|
| 179 |
-
elif query_length == 1:
|
| 180 |
-
max_seqlen_in_batch_q = 1
|
| 181 |
-
cu_seqlens_q = torch.arange(
|
| 182 |
-
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 183 |
-
) # There is a memcpy here, that is very bad.
|
| 184 |
-
indices_q = cu_seqlens_q[:-1]
|
| 185 |
-
query_layer = query_layer.squeeze(1)
|
| 186 |
-
else:
|
| 187 |
-
# The -q_len: slice assumes left padding.
|
| 188 |
-
attention_mask = attention_mask[:, -query_length:]
|
| 189 |
-
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 190 |
-
|
| 191 |
-
return (
|
| 192 |
-
query_layer,
|
| 193 |
-
key_layer,
|
| 194 |
-
value_layer,
|
| 195 |
-
indices_q,
|
| 196 |
-
(cu_seqlens_q, cu_seqlens_k),
|
| 197 |
-
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 198 |
-
)
|
| 199 |
-
|
| 200 |
-
def forward(
|
| 201 |
-
self,
|
| 202 |
-
x,
|
| 203 |
-
x_mask,
|
| 204 |
-
freqs_cis,
|
| 205 |
-
y=None,
|
| 206 |
-
y_mask=None,
|
| 207 |
-
init_cache=False,
|
| 208 |
-
):
|
| 209 |
-
bsz, seqlen, _ = x.size()
|
| 210 |
-
xq = self.wq(x)
|
| 211 |
-
xk = self.wk(x)
|
| 212 |
-
xv = self.wv(x)
|
| 213 |
-
|
| 214 |
-
if x_mask is None:
|
| 215 |
-
x_mask = torch.ones(bsz, seqlen, dtype=torch.bool, device=x.device)
|
| 216 |
-
inp_dtype = xq.dtype
|
| 217 |
-
|
| 218 |
-
xq = self.q_norm(xq)
|
| 219 |
-
xk = self.k_norm(xk)
|
| 220 |
-
|
| 221 |
-
xq = xq.view(bsz, seqlen, self.n_heads, self.head_dim)
|
| 222 |
-
xk = xk.view(bsz, seqlen, self.n_kv_heads, self.head_dim)
|
| 223 |
-
xv = xv.view(bsz, seqlen, self.n_kv_heads, self.head_dim)
|
| 224 |
-
|
| 225 |
-
if self.n_kv_heads != self.n_heads:
|
| 226 |
-
n_rep = self.n_heads // self.n_kv_heads
|
| 227 |
-
xk = xk.repeat_interleave(n_rep, dim=2)
|
| 228 |
-
xv = xv.repeat_interleave(n_rep, dim=2)
|
| 229 |
-
|
| 230 |
-
freqs_cis = freqs_cis.to(xq.device)
|
| 231 |
-
xq, xk = self.apply_rotary_emb(xq, xk, freqs_cis)
|
| 232 |
-
|
| 233 |
-
if inp_dtype in [torch.float16, torch.bfloat16]:
|
| 234 |
-
# begin var_len flash attn
|
| 235 |
-
(
|
| 236 |
-
query_states,
|
| 237 |
-
key_states,
|
| 238 |
-
value_states,
|
| 239 |
-
indices_q,
|
| 240 |
-
cu_seq_lens,
|
| 241 |
-
max_seq_lens,
|
| 242 |
-
) = self._upad_input(xq, xk, xv, x_mask, seqlen)
|
| 243 |
-
|
| 244 |
-
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 245 |
-
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 246 |
-
|
| 247 |
-
attn_output_unpad = flash_attn_varlen_func(
|
| 248 |
-
query_states.to(inp_dtype),
|
| 249 |
-
key_states.to(inp_dtype),
|
| 250 |
-
value_states.to(inp_dtype),
|
| 251 |
-
cu_seqlens_q=cu_seqlens_q,
|
| 252 |
-
cu_seqlens_k=cu_seqlens_k,
|
| 253 |
-
max_seqlen_q=max_seqlen_in_batch_q,
|
| 254 |
-
max_seqlen_k=max_seqlen_in_batch_k,
|
| 255 |
-
dropout_p=0.0,
|
| 256 |
-
causal=False,
|
| 257 |
-
softmax_scale=None,
|
| 258 |
-
softcap=30,
|
| 259 |
-
)
|
| 260 |
-
output = pad_input(attn_output_unpad, indices_q, bsz, seqlen)
|
| 261 |
-
else:
|
| 262 |
-
output = (
|
| 263 |
-
F.scaled_dot_product_attention(
|
| 264 |
-
xq.permute(0, 2, 1, 3),
|
| 265 |
-
xk.permute(0, 2, 1, 3),
|
| 266 |
-
xv.permute(0, 2, 1, 3),
|
| 267 |
-
attn_mask=x_mask.bool().view(bsz, 1, 1, seqlen).expand(-1, self.n_heads, seqlen, -1),
|
| 268 |
-
scale=None,
|
| 269 |
-
)
|
| 270 |
-
.permute(0, 2, 1, 3)
|
| 271 |
-
.to(inp_dtype)
|
| 272 |
-
) #ok
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
if hasattr(self, "wk_y"):
|
| 276 |
-
yk = self.ky_norm(self.wk_y(y)).view(bsz, -1, self.n_kv_heads, self.head_dim)
|
| 277 |
-
yv = self.wv_y(y).view(bsz, -1, self.n_kv_heads, self.head_dim)
|
| 278 |
-
n_rep = self.n_heads // self.n_kv_heads
|
| 279 |
-
# if n_rep >= 1:
|
| 280 |
-
# yk = yk.unsqueeze(3).repeat(1, 1, 1, n_rep, 1).flatten(2, 3)
|
| 281 |
-
# yv = yv.unsqueeze(3).repeat(1, 1, 1, n_rep, 1).flatten(2, 3)
|
| 282 |
-
if n_rep >= 1:
|
| 283 |
-
yk = einops.repeat(yk, "b l h d -> b l (repeat h) d", repeat=n_rep)
|
| 284 |
-
yv = einops.repeat(yv, "b l h d -> b l (repeat h) d", repeat=n_rep)
|
| 285 |
-
output_y = F.scaled_dot_product_attention(
|
| 286 |
-
xq.permute(0, 2, 1, 3),
|
| 287 |
-
yk.permute(0, 2, 1, 3),
|
| 288 |
-
yv.permute(0, 2, 1, 3),
|
| 289 |
-
y_mask.view(bsz, 1, 1, -1).expand(bsz, self.n_heads, seqlen, -1).to(torch.bool),
|
| 290 |
-
).permute(0, 2, 1, 3)
|
| 291 |
-
output_y = output_y * self.gate.tanh().view(1, 1, -1, 1)
|
| 292 |
-
output = output + output_y
|
| 293 |
-
|
| 294 |
-
output = output.flatten(-2)
|
| 295 |
-
output = self.wo(output)
|
| 296 |
-
|
| 297 |
-
return output.to(inp_dtype)
|
| 298 |
-
|
| 299 |
-
class TransformerBlock(nn.Module):
|
| 300 |
-
"""
|
| 301 |
-
Corresponds to the Transformer block in the JAX code.
|
| 302 |
-
"""
|
| 303 |
-
def __init__(
|
| 304 |
-
self,
|
| 305 |
-
dim,
|
| 306 |
-
n_heads,
|
| 307 |
-
n_kv_heads,
|
| 308 |
-
multiple_of,
|
| 309 |
-
ffn_dim_multiplier,
|
| 310 |
-
norm_eps,
|
| 311 |
-
qk_norm,
|
| 312 |
-
y_dim,
|
| 313 |
-
max_position_embeddings,
|
| 314 |
-
):
|
| 315 |
-
super().__init__()
|
| 316 |
-
self.attention = Attention(dim, n_heads, n_kv_heads, qk_norm, y_dim=y_dim, max_position_embeddings=max_position_embeddings)
|
| 317 |
-
self.feed_forward = LLamaFeedForward(
|
| 318 |
-
dim=dim,
|
| 319 |
-
hidden_dim=4 * dim,
|
| 320 |
-
multiple_of=multiple_of,
|
| 321 |
-
ffn_dim_multiplier=ffn_dim_multiplier,
|
| 322 |
-
)
|
| 323 |
-
self.attention_norm1 = RMSNorm(dim, eps=norm_eps)
|
| 324 |
-
self.attention_norm2 = RMSNorm(dim, eps=norm_eps)
|
| 325 |
-
self.ffn_norm1 = RMSNorm(dim, eps=norm_eps)
|
| 326 |
-
self.ffn_norm2 = RMSNorm(dim, eps=norm_eps)
|
| 327 |
-
self.adaLN_modulation = nn.Sequential(
|
| 328 |
-
nn.SiLU(),
|
| 329 |
-
nn.Linear(min(dim, 1024), 4 * dim),
|
| 330 |
-
)
|
| 331 |
-
self.attention_y_norm = RMSNorm(y_dim, eps=norm_eps)
|
| 332 |
-
|
| 333 |
-
def forward(
|
| 334 |
-
self,
|
| 335 |
-
x,
|
| 336 |
-
x_mask,
|
| 337 |
-
freqs_cis,
|
| 338 |
-
y,
|
| 339 |
-
y_mask,
|
| 340 |
-
adaln_input=None,
|
| 341 |
-
):
|
| 342 |
-
if adaln_input is not None:
|
| 343 |
-
scales_gates = self.adaLN_modulation(adaln_input)
|
| 344 |
-
# TODO: Duong - check the dimension of chunking
|
| 345 |
-
# scale_msa, gate_msa, scale_mlp, gate_mlp = scales_gates.chunk(4, dim=-1)
|
| 346 |
-
scale_msa, gate_msa, scale_mlp, gate_mlp = scales_gates.chunk(4, dim=-1)
|
| 347 |
-
x = x + torch.tanh(gate_msa) * self.attention_norm2(
|
| 348 |
-
self.attention(
|
| 349 |
-
modulate(self.attention_norm1(x), scale_msa), # ok
|
| 350 |
-
x_mask,
|
| 351 |
-
freqs_cis,
|
| 352 |
-
self.attention_y_norm(y), # ok
|
| 353 |
-
y_mask,
|
| 354 |
-
)
|
| 355 |
-
)
|
| 356 |
-
x = x + torch.tanh(gate_mlp) * self.ffn_norm2(
|
| 357 |
-
self.feed_forward(
|
| 358 |
-
modulate(self.ffn_norm1(x), scale_mlp),
|
| 359 |
-
)
|
| 360 |
-
)
|
| 361 |
-
else:
|
| 362 |
-
x = x + self.attention_norm2(
|
| 363 |
-
self.attention(
|
| 364 |
-
self.attention_norm1(x),
|
| 365 |
-
x_mask,
|
| 366 |
-
freqs_cis,
|
| 367 |
-
self.attention_y_norm(y),
|
| 368 |
-
y_mask,
|
| 369 |
-
)
|
| 370 |
-
)
|
| 371 |
-
x = x + self.ffn_norm2(self.feed_forward(self.ffn_norm1(x)))
|
| 372 |
-
return x
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
class NextDiT(ModelMixin, ConfigMixin):
|
| 376 |
-
"""
|
| 377 |
-
Diffusion model with a Transformer backbone for joint image-video training.
|
| 378 |
-
"""
|
| 379 |
-
@register_to_config
|
| 380 |
-
def __init__(
|
| 381 |
-
self,
|
| 382 |
-
input_size=(1, 32, 32),
|
| 383 |
-
patch_size=(1, 2, 2),
|
| 384 |
-
in_channels=16,
|
| 385 |
-
hidden_size=4096,
|
| 386 |
-
depth=32,
|
| 387 |
-
num_heads=32,
|
| 388 |
-
num_kv_heads=None,
|
| 389 |
-
multiple_of=256,
|
| 390 |
-
ffn_dim_multiplier=None,
|
| 391 |
-
norm_eps=1e-5,
|
| 392 |
-
pred_sigma=False,
|
| 393 |
-
caption_channels=4096,
|
| 394 |
-
qk_norm=False,
|
| 395 |
-
norm_type="rms",
|
| 396 |
-
model_max_length=120,
|
| 397 |
-
rotary_max_length=384,
|
| 398 |
-
rotary_max_length_t=None
|
| 399 |
-
):
|
| 400 |
-
super().__init__()
|
| 401 |
-
self.input_size = input_size
|
| 402 |
-
self.patch_size = patch_size
|
| 403 |
-
self.in_channels = in_channels
|
| 404 |
-
self.hidden_size = hidden_size
|
| 405 |
-
self.depth = depth
|
| 406 |
-
self.num_heads = num_heads
|
| 407 |
-
self.num_kv_heads = num_kv_heads or num_heads
|
| 408 |
-
self.multiple_of = multiple_of
|
| 409 |
-
self.ffn_dim_multiplier = ffn_dim_multiplier
|
| 410 |
-
self.norm_eps = norm_eps
|
| 411 |
-
self.pred_sigma = pred_sigma
|
| 412 |
-
self.caption_channels = caption_channels
|
| 413 |
-
self.qk_norm = qk_norm
|
| 414 |
-
self.norm_type = norm_type
|
| 415 |
-
self.model_max_length = model_max_length
|
| 416 |
-
self.rotary_max_length = rotary_max_length
|
| 417 |
-
self.rotary_max_length_t = rotary_max_length_t
|
| 418 |
-
self.out_channels = in_channels * 2 if pred_sigma else in_channels
|
| 419 |
-
|
| 420 |
-
self.x_embedder = nn.Linear(np.prod(self.patch_size) * in_channels, hidden_size)
|
| 421 |
-
|
| 422 |
-
self.t_embedder = TimestepEmbedder(min(hidden_size, 1024))
|
| 423 |
-
self.y_embedder = nn.Sequential(
|
| 424 |
-
nn.LayerNorm(caption_channels, eps=1e-6),
|
| 425 |
-
nn.Linear(caption_channels, min(hidden_size, 1024)),
|
| 426 |
-
)
|
| 427 |
-
|
| 428 |
-
self.layers = nn.ModuleList([
|
| 429 |
-
TransformerBlock(
|
| 430 |
-
dim=hidden_size,
|
| 431 |
-
n_heads=num_heads,
|
| 432 |
-
n_kv_heads=self.num_kv_heads,
|
| 433 |
-
multiple_of=multiple_of,
|
| 434 |
-
ffn_dim_multiplier=ffn_dim_multiplier,
|
| 435 |
-
norm_eps=norm_eps,
|
| 436 |
-
qk_norm=qk_norm,
|
| 437 |
-
y_dim=caption_channels,
|
| 438 |
-
max_position_embeddings=rotary_max_length,
|
| 439 |
-
)
|
| 440 |
-
for _ in range(depth)
|
| 441 |
-
])
|
| 442 |
-
|
| 443 |
-
self.final_layer = FinalLayer(
|
| 444 |
-
hidden_size=hidden_size,
|
| 445 |
-
num_patches=np.prod(patch_size),
|
| 446 |
-
out_channels=self.out_channels,
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
-
assert (hidden_size // num_heads) % 6 == 0, "3d rope needs head dim to be divisible by 6"
|
| 450 |
-
|
| 451 |
-
self.freqs_cis = self.precompute_freqs_cis(
|
| 452 |
-
hidden_size // num_heads,
|
| 453 |
-
self.rotary_max_length,
|
| 454 |
-
end_t=self.rotary_max_length_t
|
| 455 |
-
)
|
| 456 |
-
|
| 457 |
-
def to(self, *args, **kwargs):
|
| 458 |
-
self = super().to(*args, **kwargs)
|
| 459 |
-
# self.freqs_cis = self.freqs_cis.to(*args, **kwargs)
|
| 460 |
-
return self
|
| 461 |
-
|
| 462 |
-
@staticmethod
|
| 463 |
-
def precompute_freqs_cis(
|
| 464 |
-
dim: int,
|
| 465 |
-
end: int,
|
| 466 |
-
end_t: int = None,
|
| 467 |
-
theta: float = 10000.0,
|
| 468 |
-
scale_factor: float = 1.0,
|
| 469 |
-
scale_watershed: float = 1.0,
|
| 470 |
-
timestep: float = 1.0,
|
| 471 |
-
):
|
| 472 |
-
if timestep < scale_watershed:
|
| 473 |
-
linear_factor = scale_factor
|
| 474 |
-
ntk_factor = 1.0
|
| 475 |
-
else:
|
| 476 |
-
linear_factor = 1.0
|
| 477 |
-
ntk_factor = scale_factor
|
| 478 |
-
|
| 479 |
-
theta = theta * ntk_factor
|
| 480 |
-
freqs = 1.0 / (theta ** (torch.arange(0, dim, 6)[: (dim // 6)] / dim)) / linear_factor
|
| 481 |
-
|
| 482 |
-
timestep = torch.arange(end, dtype=torch.float32)
|
| 483 |
-
freqs = torch.outer(timestep, freqs).float()
|
| 484 |
-
freqs_cis = torch.exp(1j * freqs)
|
| 485 |
-
|
| 486 |
-
if end_t is not None:
|
| 487 |
-
freqs_t = 1.0 / (theta ** (torch.arange(0, dim, 6)[: (dim // 6)] / dim)) / linear_factor
|
| 488 |
-
timestep_t = torch.arange(end_t, dtype=torch.float32)
|
| 489 |
-
freqs_t = torch.outer(timestep_t, freqs_t).float()
|
| 490 |
-
freqs_cis_t = torch.exp(1j * freqs_t)
|
| 491 |
-
freqs_cis_t = freqs_cis_t.view(end_t, 1, 1, dim // 6).repeat(1, end, end, 1)
|
| 492 |
-
else:
|
| 493 |
-
end_t = end
|
| 494 |
-
freqs_cis_t = freqs_cis.view(end_t, 1, 1, dim // 6).repeat(1, end, end, 1)
|
| 495 |
-
|
| 496 |
-
freqs_cis_h = freqs_cis.view(1, end, 1, dim // 6).repeat(end_t, 1, end, 1)
|
| 497 |
-
freqs_cis_w = freqs_cis.view(1, 1, end, dim // 6).repeat(end_t, end, 1, 1)
|
| 498 |
-
freqs_cis = torch.cat([freqs_cis_t, freqs_cis_h, freqs_cis_w], dim=-1).view(end_t, end, end, -1)
|
| 499 |
-
return freqs_cis
|
| 500 |
-
|
| 501 |
-
def forward(
|
| 502 |
-
self,
|
| 503 |
-
samples,
|
| 504 |
-
timesteps,
|
| 505 |
-
encoder_hidden_states,
|
| 506 |
-
encoder_attention_mask,
|
| 507 |
-
scale_factor: float = 1.0, # scale_factor for rotary embedding
|
| 508 |
-
scale_watershed: float = 1.0, # scale_watershed for rotary embedding
|
| 509 |
-
):
|
| 510 |
-
if samples.ndim == 4: # B C H W
|
| 511 |
-
samples = samples[:, None, ...] # B F C H W
|
| 512 |
-
|
| 513 |
-
precomputed_freqs_cis = None
|
| 514 |
-
if scale_factor != 1 or scale_watershed != 1:
|
| 515 |
-
precomputed_freqs_cis = self.precompute_freqs_cis(
|
| 516 |
-
self.hidden_size // self.num_heads,
|
| 517 |
-
self.rotary_max_length,
|
| 518 |
-
end_t=self.rotary_max_length_t,
|
| 519 |
-
scale_factor=scale_factor,
|
| 520 |
-
scale_watershed=scale_watershed,
|
| 521 |
-
timestep=torch.max(timesteps.cpu()).item()
|
| 522 |
-
)
|
| 523 |
-
|
| 524 |
-
if len(timesteps.shape) == 5:
|
| 525 |
-
t, *_ = self.patchify(timesteps, precomputed_freqs_cis)
|
| 526 |
-
timesteps = t.mean(dim=-1)
|
| 527 |
-
elif len(timesteps.shape) == 1:
|
| 528 |
-
timesteps = timesteps[:, None, None, None, None].expand_as(samples)
|
| 529 |
-
t, *_ = self.patchify(timesteps, precomputed_freqs_cis)
|
| 530 |
-
timesteps = t.mean(dim=-1)
|
| 531 |
-
samples, T, H, W, freqs_cis = self.patchify(samples, precomputed_freqs_cis)
|
| 532 |
-
samples = self.x_embedder(samples)
|
| 533 |
-
t = self.t_embedder(timesteps)
|
| 534 |
-
|
| 535 |
-
encoder_attention_mask_float = encoder_attention_mask[..., None].float()
|
| 536 |
-
encoder_hidden_states_pool = (encoder_hidden_states * encoder_attention_mask_float).sum(dim=1) / (encoder_attention_mask_float.sum(dim=1) + 1e-8)
|
| 537 |
-
encoder_hidden_states_pool = encoder_hidden_states_pool.to(samples.dtype)
|
| 538 |
-
y = self.y_embedder(encoder_hidden_states_pool)
|
| 539 |
-
y = y.unsqueeze(1).expand(-1, samples.size(1), -1)
|
| 540 |
-
|
| 541 |
-
adaln_input = t + y
|
| 542 |
-
|
| 543 |
-
for block in self.layers:
|
| 544 |
-
samples = block(samples, None, freqs_cis, encoder_hidden_states, encoder_attention_mask, adaln_input)
|
| 545 |
-
|
| 546 |
-
samples = self.final_layer(samples, adaln_input)
|
| 547 |
-
samples = self.unpatchify(samples, T, H, W)
|
| 548 |
-
|
| 549 |
-
return samples
|
| 550 |
-
|
| 551 |
-
def patchify(self, x, precompute_freqs_cis=None):
|
| 552 |
-
# pytorch is C, H, W
|
| 553 |
-
B, T, C, H, W = x.size()
|
| 554 |
-
pT, pH, pW = self.patch_size
|
| 555 |
-
x = x.view(B, T // pT, pT, C, H // pH, pH, W // pW, pW)
|
| 556 |
-
x = x.permute(0, 1, 4, 6, 2, 5, 7, 3)
|
| 557 |
-
x = x.reshape(B, -1, pT * pH * pW * C)
|
| 558 |
-
if precompute_freqs_cis is None:
|
| 559 |
-
freqs_cis = self.freqs_cis[: T // pT, :H // pH, :W // pW].reshape(-1, * self.freqs_cis.shape[3:])[None].to(x.device)
|
| 560 |
-
else:
|
| 561 |
-
freqs_cis = precompute_freqs_cis[: T // pT, :H // pH, :W // pW].reshape(-1, * precompute_freqs_cis.shape[3:])[None].to(x.device)
|
| 562 |
-
return x, T // pT, H // pH, W // pW, freqs_cis
|
| 563 |
-
|
| 564 |
-
def unpatchify(self, x, T, H, W):
|
| 565 |
-
B = x.size(0)
|
| 566 |
-
C = self.out_channels
|
| 567 |
-
pT, pH, pW = self.patch_size
|
| 568 |
-
x = x.view(B, T, H, W, pT, pH, pW, C)
|
| 569 |
-
x = x.permute(0, 1, 4, 7, 2, 5, 3, 6)
|
| 570 |
-
x = x.reshape(B, T * pT, C, H * pH, W * pW)
|
| 571 |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