| 1 | """ |
| 2 | ein notation: |
| 3 | b - batch |
| 4 | n - sequence |
| 5 | nt - text sequence |
| 6 | nw - raw wave length |
| 7 | d - dimension |
| 8 | """ |
| 9 | # ruff: noqa: F722 F821 |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import math |
| 14 | import warnings |
| 15 | from typing import Optional |
| 16 | |
| 17 | import torch |
| 18 | import torch.nn.functional as F |
| 19 | import torchaudio |
| 20 | from librosa.filters import mel as librosa_mel_fn |
| 21 | from torch import nn |
| 22 | from x_transformers.x_transformers import RotaryEmbedding as XRotaryEmbedding |
| 23 | from x_transformers.x_transformers import apply_rotary_pos_emb |
| 24 | |
| 25 | from f5_tts.model.utils import is_package_available |
| 26 | |
| 27 | |
| 28 | # raw wav to mel spec |
| 29 | |
| 30 | |
| 31 | mel_basis_cache = {} |
| 32 | hann_window_cache = {} |
| 33 | vocos_mel_stft_cache = {} |
| 34 | |
| 35 | |
| 36 | def get_bigvgan_mel_spectrogram( |
| 37 | waveform, |
| 38 | n_fft=1024, |
| 39 | n_mel_channels=100, |
| 40 | target_sample_rate=24000, |
| 41 | hop_length=256, |
| 42 | win_length=1024, |
| 43 | fmin=0, |
| 44 | fmax=None, |
| 45 | center=False, |
| 46 | ): # Copy from https://github.com/NVIDIA/BigVGAN/tree/main |
| 47 | device = waveform.device |
| 48 | key = f"{n_fft}_{n_mel_channels}_{target_sample_rate}_{hop_length}_{win_length}_{fmin}_{fmax}_{device}" |
| 49 | |
| 50 | if key not in mel_basis_cache: |
| 51 | mel = librosa_mel_fn(sr=target_sample_rate, n_fft=n_fft, n_mels=n_mel_channels, fmin=fmin, fmax=fmax) |
| 52 | mel_basis_cache[key] = torch.from_numpy(mel).float().to(device) # TODO: why they need .float()? |
| 53 | hann_window_cache[key] = torch.hann_window(win_length).to(device) |
| 54 | |
| 55 | mel_basis = mel_basis_cache[key] |
| 56 | hann_window = hann_window_cache[key] |
| 57 | |
| 58 | padding = (n_fft - hop_length) // 2 |
| 59 | waveform = torch.nn.functional.pad(waveform.unsqueeze(1), (padding, padding), mode="reflect").squeeze(1) |
| 60 | |
| 61 | spec = torch.stft( |
| 62 | waveform, |
| 63 | n_fft, |
| 64 | hop_length=hop_length, |
| 65 | win_length=win_length, |
| 66 | window=hann_window, |
| 67 | center=center, |
| 68 | pad_mode="reflect", |
| 69 | normalized=False, |
| 70 | onesided=True, |
| 71 | return_complex=True, |
| 72 | ) |
| 73 | spec = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9) |
| 74 | |
| 75 | mel_spec = torch.matmul(mel_basis, spec) |
| 76 | mel_spec = torch.log(torch.clamp(mel_spec, min=1e-5)) |
| 77 | |
| 78 | return mel_spec |
| 79 | |
| 80 | |
| 81 | def get_vocos_mel_spectrogram( |
| 82 | waveform, |
| 83 | n_fft=1024, |
| 84 | n_mel_channels=100, |
| 85 | target_sample_rate=24000, |
| 86 | hop_length=256, |
| 87 | win_length=1024, |
| 88 | ): |
| 89 | device = waveform.device |
| 90 | key = f"{n_fft}_{n_mel_channels}_{target_sample_rate}_{hop_length}_{win_length}_{device}" |
| 91 | if key not in vocos_mel_stft_cache: |
| 92 | vocos_mel_stft_cache[key] = torchaudio.transforms.MelSpectrogram( |
| 93 | sample_rate=target_sample_rate, |
| 94 | n_fft=n_fft, |
| 95 | win_length=win_length, |
| 96 | hop_length=hop_length, |
| 97 | n_mels=n_mel_channels, |
| 98 | power=1, |
| 99 | center=True, |
| 100 | normalized=False, |
| 101 | norm=None, |
| 102 | ).to(device) |
| 103 | if len(waveform.shape) == 3: |
| 104 | waveform = waveform.squeeze(1) # 'b 1 nw -> b nw' |
| 105 | |
| 106 | assert len(waveform.shape) == 2 |
| 107 | |
| 108 | mel = vocos_mel_stft_cache[key](waveform) |
| 109 | mel = mel.clamp(min=1e-5).log() |
| 110 | return mel |
| 111 | |
| 112 | |
| 113 | class MelSpec(nn.Module): |
| 114 | def __init__( |
| 115 | self, |
| 116 | n_fft=1024, |
| 117 | hop_length=256, |
| 118 | win_length=1024, |
| 119 | n_mel_channels=100, |
| 120 | target_sample_rate=24_000, |
| 121 | mel_spec_type="vocos", |
| 122 | ): |
| 123 | super().__init__() |
| 124 | assert mel_spec_type in ["vocos", "bigvgan"], print("We only support two extract mel backend: vocos or bigvgan") |
| 125 | |
| 126 | self.n_fft = n_fft |
| 127 | self.hop_length = hop_length |
| 128 | self.win_length = win_length |
| 129 | self.n_mel_channels = n_mel_channels |
| 130 | self.target_sample_rate = target_sample_rate |
| 131 | |
| 132 | if mel_spec_type == "vocos": |
| 133 | self.extractor = get_vocos_mel_spectrogram |
| 134 | elif mel_spec_type == "bigvgan": |
| 135 | self.extractor = get_bigvgan_mel_spectrogram |
| 136 | |
| 137 | self.register_buffer("dummy", torch.tensor(0), persistent=False) |
| 138 | |
| 139 | def forward(self, wav): |
| 140 | if self.dummy.device != wav.device: |
| 141 | self.to(wav.device) |
| 142 | |
| 143 | mel = self.extractor( |
| 144 | waveform=wav, |
| 145 | n_fft=self.n_fft, |
| 146 | n_mel_channels=self.n_mel_channels, |
| 147 | target_sample_rate=self.target_sample_rate, |
| 148 | hop_length=self.hop_length, |
| 149 | win_length=self.win_length, |
| 150 | ) |
| 151 | |
| 152 | return mel |
| 153 | |
| 154 | |
| 155 | # sinusoidal position embedding |
| 156 | |
| 157 | |
| 158 | class SinusPositionEmbedding(nn.Module): |
| 159 | def __init__(self, dim): |
| 160 | super().__init__() |
| 161 | self.dim = dim |
| 162 | |
| 163 | def forward(self, x, scale=1000): |
| 164 | device = x.device |
| 165 | half_dim = self.dim // 2 |
| 166 | emb = math.log(10000) / (half_dim - 1) |
| 167 | emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb) |
| 168 | emb = scale * x.unsqueeze(1) * emb.unsqueeze(0) |
| 169 | emb = torch.cat((emb.sin(), emb.cos()), dim=-1) |
| 170 | return emb |
| 171 | |
| 172 | |
| 173 | # convolutional position embedding |
| 174 | |
| 175 | |
| 176 | class ConvPositionEmbedding(nn.Module): |
| 177 | def __init__(self, dim, kernel_size=31, groups=16): |
| 178 | super().__init__() |
| 179 | assert kernel_size % 2 != 0 |
| 180 | self.conv1d = nn.Sequential( |
| 181 | nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2), |
| 182 | nn.Mish(), |
| 183 | nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=kernel_size // 2), |
| 184 | nn.Mish(), |
| 185 | ) |
| 186 | self.layer_need_mask_idx = [i for i, layer in enumerate(self.conv1d) if isinstance(layer, nn.Conv1d)] |
| 187 | |
| 188 | def forward(self, x: float["b n d"], mask: bool["b n"] | None = None): |
| 189 | if mask is not None: |
| 190 | mask = mask.unsqueeze(1) # [B 1 N] |
| 191 | x = x.permute(0, 2, 1) # [B D N] |
| 192 | |
| 193 | if mask is not None: |
| 194 | x = x.masked_fill(~mask, 0.0) |
| 195 | for i, block in enumerate(self.conv1d): |
| 196 | x = block(x) |
| 197 | if mask is not None and i in self.layer_need_mask_idx: |
| 198 | x = x.masked_fill(~mask, 0.0) |
| 199 | |
| 200 | x = x.permute(0, 2, 1) # [B N D] |
| 201 | |
| 202 | return x |
| 203 | |
| 204 | |
| 205 | # rotary positional embedding related |
| 206 | |
| 207 | |
| 208 | class RotaryEmbedding(XRotaryEmbedding): |
| 209 | def _apply(self, fn, *args, **kwargs): |
| 210 | # x-transformers uses the inverse frequency dtype for position indices too. |
| 211 | # Keep both in fp32 when the rest of the model is cast to half precision. |
| 212 | def convert(buffer): |
| 213 | converted = fn(buffer) |
| 214 | if converted.dtype in (torch.float16, torch.bfloat16): |
| 215 | return buffer.to(device=converted.device, dtype=torch.float32) |
| 216 | return converted |
| 217 | |
| 218 | return super()._apply(convert, *args, **kwargs) |
| 219 | |
| 220 | |
| 221 | def precompute_freqs_cis( |
| 222 | dim: int, end: int, theta: float = 10000.0, theta_rescale_factor=1.0, *, start: int = 0, device=None |
| 223 | ): |
| 224 | # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning |
| 225 | # has some connection to NTK literature |
| 226 | # https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/ |
| 227 | # https://github.com/lucidrains/rotary-embedding-torch/blob/main/rotary_embedding_torch/rotary_embedding_torch.py |
| 228 | theta *= theta_rescale_factor ** (dim / (dim - 2)) |
| 229 | freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device)[: (dim // 2)].float() / dim)) |
| 230 | t = torch.arange(start, end, device=freqs.device) |
| 231 | freqs = torch.outer(t, freqs).float() # type: ignore |
| 232 | freqs_cos = torch.cos(freqs) # real part |
| 233 | freqs_sin = torch.sin(freqs) # imaginary part |
| 234 | return torch.cat([freqs_cos, freqs_sin], dim=-1) |
| 235 | |
| 236 | |
| 237 | def get_pos_embed_indices(start, length, max_pos, scale=1.0): |
| 238 | # length = length if isinstance(length, int) else length.max() |
| 239 | scale = scale * torch.ones_like(start, dtype=torch.float32) # in case scale is a scalar |
| 240 | pos = ( |
| 241 | start.unsqueeze(1) |
| 242 | + (torch.arange(length, device=start.device, dtype=torch.float32).unsqueeze(0) * scale.unsqueeze(1)).long() |
| 243 | ) |
| 244 | # avoid extra long error. |
| 245 | pos = torch.where(pos < max_pos, pos, max_pos - 1) |
| 246 | return pos |
| 247 | |
| 248 | |
| 249 | # Global Response Normalization layer (Instance Normalization ?) |
| 250 | |
| 251 | |
| 252 | class GRN(nn.Module): |
| 253 | def __init__(self, dim): |
| 254 | super().__init__() |
| 255 | self.gamma = nn.Parameter(torch.zeros(1, 1, dim)) |
| 256 | self.beta = nn.Parameter(torch.zeros(1, 1, dim)) |
| 257 | |
| 258 | def forward(self, x): |
| 259 | Gx = torch.norm(x, p=2, dim=1, keepdim=True) |
| 260 | Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6) |
| 261 | return self.gamma * (x * Nx) + self.beta + x |
| 262 | |
| 263 | |
| 264 | # ConvNeXt-V2 Block https://github.com/facebookresearch/ConvNeXt-V2/blob/main/models/convnextv2.py |
| 265 | # ref: https://github.com/bfs18/e2_tts/blob/main/rfwave/modules.py#L108 |
| 266 | |
| 267 | |
| 268 | class ConvNeXtV2Block(nn.Module): |
| 269 | def __init__( |
| 270 | self, |
| 271 | dim: int, |
| 272 | intermediate_dim: int, |
| 273 | dilation: int = 1, |
| 274 | ): |
| 275 | super().__init__() |
| 276 | padding = (dilation * (7 - 1)) // 2 |
| 277 | self.dwconv = nn.Conv1d( |
| 278 | dim, dim, kernel_size=7, padding=padding, groups=dim, dilation=dilation |
| 279 | ) # depthwise conv |
| 280 | self.norm = nn.LayerNorm(dim, eps=1e-6) |
| 281 | self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers |
| 282 | self.act = nn.GELU() |
| 283 | self.grn = GRN(intermediate_dim) |
| 284 | self.pwconv2 = nn.Linear(intermediate_dim, dim) |
| 285 | |
| 286 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 287 | residual = x |
| 288 | x = x.transpose(1, 2) # b n d -> b d n |
| 289 | x = self.dwconv(x) |
| 290 | x = x.transpose(1, 2) # b d n -> b n d |
| 291 | x = self.norm(x) |
| 292 | x = self.pwconv1(x) |
| 293 | x = self.act(x) |
| 294 | x = self.grn(x) |
| 295 | x = self.pwconv2(x) |
| 296 | return residual + x |
| 297 | |
| 298 | |
| 299 | # RMSNorm |
| 300 | |
| 301 | |
| 302 | class RMSNorm(nn.Module): |
| 303 | def __init__(self, dim: int, eps: float): |
| 304 | super().__init__() |
| 305 | self.eps = eps |
| 306 | self.weight = nn.Parameter(torch.ones(dim)) |
| 307 | self.native_rms_norm = float(torch.__version__[:3]) >= 2.4 |
| 308 | |
| 309 | def forward(self, x): |
| 310 | if self.native_rms_norm: |
| 311 | if self.weight.dtype in [torch.float16, torch.bfloat16]: |
| 312 | x = x.to(self.weight.dtype) |
| 313 | x = F.rms_norm(x, normalized_shape=(x.shape[-1],), weight=self.weight, eps=self.eps) |
| 314 | else: |
| 315 | variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True) |
| 316 | x = x * torch.rsqrt(variance + self.eps) |
| 317 | if self.weight.dtype in [torch.float16, torch.bfloat16]: |
| 318 | x = x.to(self.weight.dtype) |
| 319 | x = x * self.weight |
| 320 | |
| 321 | return x |
| 322 | |
| 323 | |
| 324 | # AdaLayerNorm |
| 325 | # return with modulated x for attn input, and params for later mlp modulation |
| 326 | |
| 327 | |
| 328 | class AdaLayerNorm(nn.Module): |
| 329 | def __init__(self, dim): |
| 330 | super().__init__() |
| 331 | |
| 332 | self.silu = nn.SiLU() |
| 333 | self.linear = nn.Linear(dim, dim * 6) |
| 334 | |
| 335 | self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) |
| 336 | |
| 337 | def forward(self, x, emb=None): |
| 338 | emb = self.linear(self.silu(emb)) |
| 339 | shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = torch.chunk(emb, 6, dim=1) |
| 340 | |
| 341 | x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None] |
| 342 | return x, gate_msa, shift_mlp, scale_mlp, gate_mlp |
| 343 | |
| 344 | |
| 345 | # AdaLayerNorm for final layer |
| 346 | # return only with modulated x for attn input, cuz no more mlp modulation |
| 347 | |
| 348 | |
| 349 | class AdaLayerNorm_Final(nn.Module): |
| 350 | def __init__(self, dim): |
| 351 | super().__init__() |
| 352 | |
| 353 | self.silu = nn.SiLU() |
| 354 | self.linear = nn.Linear(dim, dim * 2) |
| 355 | |
| 356 | self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) |
| 357 | |
| 358 | def forward(self, x, emb): |
| 359 | emb = self.linear(self.silu(emb)) |
| 360 | scale, shift = torch.chunk(emb, 2, dim=1) |
| 361 | |
| 362 | x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :] |
| 363 | return x |
| 364 | |
| 365 | |
| 366 | # FeedForward |
| 367 | |
| 368 | |
| 369 | class FeedForward(nn.Module): |
| 370 | def __init__(self, dim, dim_out=None, mult=4, dropout=0.0, approximate: str = "none"): |
| 371 | super().__init__() |
| 372 | inner_dim = int(dim * mult) |
| 373 | dim_out = dim_out if dim_out is not None else dim |
| 374 | |
| 375 | activation = nn.GELU(approximate=approximate) |
| 376 | project_in = nn.Sequential(nn.Linear(dim, inner_dim), activation) |
| 377 | self.ff = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out)) |
| 378 | |
| 379 | def forward(self, x): |
| 380 | return self.ff(x) |
| 381 | |
| 382 | |
| 383 | # Attention with possible joint part |
| 384 | # modified from diffusers/src/diffusers/models/attention_processor.py |
| 385 | |
| 386 | |
| 387 | class Attention(nn.Module): |
| 388 | def __init__( |
| 389 | self, |
| 390 | processor: JointAttnProcessor | AttnProcessor, |
| 391 | dim: int, |
| 392 | heads: int = 8, |
| 393 | dim_head: int = 64, |
| 394 | dropout: float = 0.0, |
| 395 | context_dim: Optional[int] = None, # if not None -> joint attention |
| 396 | context_pre_only: bool = False, |
| 397 | qk_norm: Optional[str] = None, |
| 398 | ): |
| 399 | super().__init__() |
| 400 | |
| 401 | if not hasattr(F, "scaled_dot_product_attention"): |
| 402 | raise ImportError("Attention equires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") |
| 403 | |
| 404 | self.processor = processor |
| 405 | |
| 406 | self.dim = dim |
| 407 | self.heads = heads |
| 408 | self.inner_dim = dim_head * heads |
| 409 | self.dropout = dropout |
| 410 | |
| 411 | self.context_dim = context_dim |
| 412 | self.context_pre_only = context_pre_only |
| 413 | |
| 414 | self.to_q = nn.Linear(dim, self.inner_dim) |
| 415 | self.to_k = nn.Linear(dim, self.inner_dim) |
| 416 | self.to_v = nn.Linear(dim, self.inner_dim) |
| 417 | |
| 418 | if qk_norm is None: |
| 419 | self.q_norm = None |
| 420 | self.k_norm = None |
| 421 | elif qk_norm == "rms_norm": |
| 422 | self.q_norm = RMSNorm(dim_head, eps=1e-6) |
| 423 | self.k_norm = RMSNorm(dim_head, eps=1e-6) |
| 424 | else: |
| 425 | raise ValueError(f"Unimplemented qk_norm: {qk_norm}") |
| 426 | |
| 427 | if self.context_dim is not None: |
| 428 | self.to_q_c = nn.Linear(context_dim, self.inner_dim) |
| 429 | self.to_k_c = nn.Linear(context_dim, self.inner_dim) |
| 430 | self.to_v_c = nn.Linear(context_dim, self.inner_dim) |
| 431 | if qk_norm is None: |
| 432 | self.c_q_norm = None |
| 433 | self.c_k_norm = None |
| 434 | elif qk_norm == "rms_norm": |
| 435 | self.c_q_norm = RMSNorm(dim_head, eps=1e-6) |
| 436 | self.c_k_norm = RMSNorm(dim_head, eps=1e-6) |
| 437 | |
| 438 | self.to_out = nn.ModuleList([]) |
| 439 | self.to_out.append(nn.Linear(self.inner_dim, dim)) |
| 440 | self.to_out.append(nn.Dropout(dropout)) |
| 441 | |
| 442 | if self.context_dim is not None and not self.context_pre_only: |
| 443 | self.to_out_c = nn.Linear(self.inner_dim, context_dim) |
| 444 | |
| 445 | def forward( |
| 446 | self, |
| 447 | x: float["b n d"], # noised input x |
| 448 | c: float["b n d"] = None, # context c |
| 449 | mask: bool["b n"] | None = None, |
| 450 | rope=None, # rotary position embedding for x |
| 451 | c_rope=None, # rotary position embedding for c |
| 452 | c_mask: bool["b nt"] | None = None, # text mask |
| 453 | ) -> torch.Tensor: |
| 454 | if c is not None: |
| 455 | return self.processor(self, x, c=c, mask=mask, rope=rope, c_rope=c_rope, c_mask=c_mask) |
| 456 | else: |
| 457 | return self.processor(self, x, mask=mask, rope=rope) |
| 458 | |
| 459 | |
| 460 | # Attention processor |
| 461 | |
| 462 | if is_package_available("flash_attn"): |
| 463 | from flash_attn import flash_attn_func, flash_attn_varlen_func |
| 464 | from flash_attn.bert_padding import pad_input, unpad_input |
| 465 | |
| 466 | |
| 467 | class AttnProcessor: |
| 468 | def __init__( |
| 469 | self, |
| 470 | pe_attn_head: int | None = None, # number of attention head to apply rope, None for all |
| 471 | attn_backend: str = "torch", # "torch" or "flash_attn" |
| 472 | attn_mask_enabled: bool = True, |
| 473 | ): |
| 474 | if attn_backend == "flash_attn": |
| 475 | assert is_package_available("flash_attn"), "Please install flash-attn first." |
| 476 | if attn_backend == "torch" and attn_mask_enabled: |
| 477 | warnings.warn( |
| 478 | "attn_mask_enabled=True with attn_backend='torch' can consume large GPU memory. " |
| 479 | "Please switch attn_backend to 'flash_attn'.", |
| 480 | UserWarning, |
| 481 | ) |
| 482 | |
| 483 | self.pe_attn_head = pe_attn_head |
| 484 | self.attn_backend = attn_backend |
| 485 | self.attn_mask_enabled = attn_mask_enabled |
| 486 | |
| 487 | def __call__( |
| 488 | self, |
| 489 | attn: Attention, |
| 490 | x: float["b n d"], # noised input x |
| 491 | mask: bool["b n"] | None = None, |
| 492 | rope=None, # rotary position embedding |
| 493 | ) -> torch.FloatTensor: |
| 494 | batch_size = x.shape[0] |
| 495 | |
| 496 | # `sample` projections |
| 497 | query = attn.to_q(x) |
| 498 | key = attn.to_k(x) |
| 499 | value = attn.to_v(x) |
| 500 | |
| 501 | # attention |
| 502 | inner_dim = key.shape[-1] |
| 503 | head_dim = inner_dim // attn.heads |
| 504 | query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 505 | key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 506 | value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 507 | |
| 508 | # qk norm |
| 509 | if attn.q_norm is not None: |
| 510 | query = attn.q_norm(query) |
| 511 | if attn.k_norm is not None: |
| 512 | key = attn.k_norm(key) |
| 513 | |
| 514 | # apply rotary position embedding |
| 515 | if rope is not None: |
| 516 | freqs, xpos_scale = rope |
| 517 | q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0) |
| 518 | |
| 519 | if self.pe_attn_head is not None: |
| 520 | pn = self.pe_attn_head |
| 521 | query[:, :pn, :, :] = apply_rotary_pos_emb(query[:, :pn, :, :], freqs, q_xpos_scale) |
| 522 | key[:, :pn, :, :] = apply_rotary_pos_emb(key[:, :pn, :, :], freqs, k_xpos_scale) |
| 523 | else: |
| 524 | query = apply_rotary_pos_emb(query, freqs, q_xpos_scale) |
| 525 | key = apply_rotary_pos_emb(key, freqs, k_xpos_scale) |
| 526 | |
| 527 | if self.attn_backend == "torch": |
| 528 | # mask. e.g. inference got a batch with different target durations, mask out the padding |
| 529 | if self.attn_mask_enabled and mask is not None: |
| 530 | attn_mask = mask |
| 531 | attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n' |
| 532 | attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2]) |
| 533 | else: |
| 534 | attn_mask = None |
| 535 | x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False) |
| 536 | x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) |
| 537 | |
| 538 | elif self.attn_backend == "flash_attn": |
| 539 | query = query.transpose(1, 2) # [b, h, n, d] -> [b, n, h, d] |
| 540 | key = key.transpose(1, 2) |
| 541 | value = value.transpose(1, 2) |
| 542 | if self.attn_mask_enabled and mask is not None: |
| 543 | query, indices, q_cu_seqlens, q_max_seqlen_in_batch, _ = unpad_input(query, mask) |
| 544 | key, _, k_cu_seqlens, k_max_seqlen_in_batch, _ = unpad_input(key, mask) |
| 545 | value, _, _, _, _ = unpad_input(value, mask) |
| 546 | x = flash_attn_varlen_func( |
| 547 | query, |
| 548 | key, |
| 549 | value, |
| 550 | q_cu_seqlens, |
| 551 | k_cu_seqlens, |
| 552 | q_max_seqlen_in_batch, |
| 553 | k_max_seqlen_in_batch, |
| 554 | ) |
| 555 | x = pad_input(x, indices, batch_size, q_max_seqlen_in_batch) |
| 556 | x = x.reshape(batch_size, -1, attn.heads * head_dim) |
| 557 | else: |
| 558 | x = flash_attn_func(query, key, value, dropout_p=0.0, causal=False) |
| 559 | x = x.reshape(batch_size, -1, attn.heads * head_dim) |
| 560 | |
| 561 | x = x.to(query.dtype) |
| 562 | |
| 563 | # linear proj |
| 564 | x = attn.to_out[0](x) |
| 565 | # dropout |
| 566 | x = attn.to_out[1](x) |
| 567 | |
| 568 | if mask is not None: |
| 569 | mask = mask.unsqueeze(-1) |
| 570 | x = x.masked_fill(~mask, 0.0) |
| 571 | |
| 572 | return x |
| 573 | |
| 574 | |
| 575 | # Joint Attention processor for MM-DiT |
| 576 | # modified from diffusers/src/diffusers/models/attention_processor.py |
| 577 | |
| 578 | |
| 579 | class JointAttnProcessor: |
| 580 | def __init__( |
| 581 | self, |
| 582 | attn_backend: str = "torch", # "torch" or "flash_attn" |
| 583 | attn_mask_enabled: bool = True, |
| 584 | ): |
| 585 | if attn_backend == "flash_attn": |
| 586 | assert is_package_available("flash_attn"), "Please install flash-attn first." |
| 587 | if attn_backend == "torch" and attn_mask_enabled: |
| 588 | warnings.warn( |
| 589 | "attn_mask_enabled=True with attn_backend='torch' can consume large GPU memory. " |
| 590 | "Please switch attn_backend to 'flash_attn'.", |
| 591 | UserWarning, |
| 592 | ) |
| 593 | |
| 594 | self.attn_backend = attn_backend |
| 595 | self.attn_mask_enabled = attn_mask_enabled |
| 596 | |
| 597 | def __call__( |
| 598 | self, |
| 599 | attn: Attention, |
| 600 | x: float["b n d"], # noised input x |
| 601 | c: float["b nt d"] = None, # context c, here text |
| 602 | mask: bool["b n"] | None = None, |
| 603 | rope=None, # rotary position embedding for x |
| 604 | c_rope=None, # rotary position embedding for c |
| 605 | c_mask: bool["b nt"] | None = None, # text mask |
| 606 | ) -> torch.FloatTensor: |
| 607 | residual = x |
| 608 | audio_mask = mask |
| 609 | |
| 610 | batch_size = c.shape[0] |
| 611 | |
| 612 | # `sample` projections |
| 613 | query = attn.to_q(x) |
| 614 | key = attn.to_k(x) |
| 615 | value = attn.to_v(x) |
| 616 | |
| 617 | # `context` projections |
| 618 | c_query = attn.to_q_c(c) |
| 619 | c_key = attn.to_k_c(c) |
| 620 | c_value = attn.to_v_c(c) |
| 621 | |
| 622 | # attention |
| 623 | inner_dim = key.shape[-1] |
| 624 | head_dim = inner_dim // attn.heads |
| 625 | query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 626 | key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 627 | value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 628 | c_query = c_query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 629 | c_key = c_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 630 | c_value = c_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) |
| 631 | |
| 632 | # qk norm |
| 633 | if attn.q_norm is not None: |
| 634 | query = attn.q_norm(query) |
| 635 | if attn.k_norm is not None: |
| 636 | key = attn.k_norm(key) |
| 637 | if attn.c_q_norm is not None: |
| 638 | c_query = attn.c_q_norm(c_query) |
| 639 | if attn.c_k_norm is not None: |
| 640 | c_key = attn.c_k_norm(c_key) |
| 641 | |
| 642 | # apply rope for context and noised input independently |
| 643 | if rope is not None: |
| 644 | freqs, xpos_scale = rope |
| 645 | q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0) |
| 646 | query = apply_rotary_pos_emb(query, freqs, q_xpos_scale) |
| 647 | key = apply_rotary_pos_emb(key, freqs, k_xpos_scale) |
| 648 | if c_rope is not None: |
| 649 | freqs, xpos_scale = c_rope |
| 650 | q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0) |
| 651 | c_query = apply_rotary_pos_emb(c_query, freqs, q_xpos_scale) |
| 652 | c_key = apply_rotary_pos_emb(c_key, freqs, k_xpos_scale) |
| 653 | |
| 654 | # joint attention |
| 655 | query = torch.cat([query, c_query], dim=2) |
| 656 | key = torch.cat([key, c_key], dim=2) |
| 657 | value = torch.cat([value, c_value], dim=2) |
| 658 | |
| 659 | # build combined mask for joint attention: audio mask + text mask |
| 660 | if self.attn_mask_enabled and mask is not None: |
| 661 | if c_mask is not None: |
| 662 | mask = torch.cat([mask, c_mask], dim=1) |
| 663 | else: |
| 664 | mask = F.pad(mask, (0, c.shape[1]), value=True) |
| 665 | |
| 666 | if self.attn_backend == "torch": |
| 667 | # mask. e.g. inference got a batch with different target durations, mask out the padding |
| 668 | if self.attn_mask_enabled and mask is not None: |
| 669 | attn_mask = mask |
| 670 | attn_mask = attn_mask.unsqueeze(1).unsqueeze(1) # 'b n -> b 1 1 n' |
| 671 | attn_mask = attn_mask.expand(batch_size, attn.heads, query.shape[-2], key.shape[-2]) |
| 672 | else: |
| 673 | attn_mask = None |
| 674 | x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=0.0, is_causal=False) |
| 675 | x = x.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) |
| 676 | |
| 677 | elif self.attn_backend == "flash_attn": |
| 678 | query = query.transpose(1, 2) # [b, h, n, d] -> [b, n, h, d] |
| 679 | key = key.transpose(1, 2) |
| 680 | value = value.transpose(1, 2) |
| 681 | if self.attn_mask_enabled and mask is not None: |
| 682 | total_seq_len = query.shape[1] |
| 683 | query, indices, q_cu_seqlens, q_max_seqlen_in_batch, _ = unpad_input(query, mask) |
| 684 | key, _, k_cu_seqlens, k_max_seqlen_in_batch, _ = unpad_input(key, mask) |
| 685 | value, _, _, _, _ = unpad_input(value, mask) |
| 686 | x = flash_attn_varlen_func( |
| 687 | query, |
| 688 | key, |
| 689 | value, |
| 690 | q_cu_seqlens, |
| 691 | k_cu_seqlens, |
| 692 | q_max_seqlen_in_batch, |
| 693 | k_max_seqlen_in_batch, |
| 694 | ) |
| 695 | x = pad_input(x, indices, batch_size, total_seq_len) |
| 696 | x = x.reshape(batch_size, -1, attn.heads * head_dim) |
| 697 | else: |
| 698 | x = flash_attn_func(query, key, value, dropout_p=0.0, causal=False) |
| 699 | x = x.reshape(batch_size, -1, attn.heads * head_dim) |
| 700 | |
| 701 | x = x.to(query.dtype) |
| 702 | |
| 703 | # Split the attention outputs. |
| 704 | x, c = ( |
| 705 | x[:, : residual.shape[1]], |
| 706 | x[:, residual.shape[1] :], |
| 707 | ) |
| 708 | |
| 709 | # linear proj |
| 710 | x = attn.to_out[0](x) |
| 711 | # dropout |
| 712 | x = attn.to_out[1](x) |
| 713 | if not attn.context_pre_only: |
| 714 | c = attn.to_out_c(c) |
| 715 | |
| 716 | if audio_mask is not None: |
| 717 | x = x.masked_fill(~audio_mask.unsqueeze(-1), 0.0) |
| 718 | if c_mask is not None: |
| 719 | c = c.masked_fill(~c_mask.unsqueeze(-1), 0.0) |
| 720 | |
| 721 | return x, c |
| 722 | |
| 723 | |
| 724 | # DiT Block |
| 725 | |
| 726 | |
| 727 | class DiTBlock(nn.Module): |
| 728 | def __init__( |
| 729 | self, |
| 730 | dim, |
| 731 | heads, |
| 732 | dim_head, |
| 733 | ff_mult=4, |
| 734 | dropout=0.1, |
| 735 | qk_norm=None, |
| 736 | pe_attn_head=None, |
| 737 | attn_backend="torch", # "torch" or "flash_attn" |
| 738 | attn_mask_enabled=True, |
| 739 | ): |
| 740 | super().__init__() |
| 741 | |
| 742 | self.attn_norm = AdaLayerNorm(dim) |
| 743 | self.attn = Attention( |
| 744 | processor=AttnProcessor( |
| 745 | pe_attn_head=pe_attn_head, |
| 746 | attn_backend=attn_backend, |
| 747 | attn_mask_enabled=attn_mask_enabled, |
| 748 | ), |
| 749 | dim=dim, |
| 750 | heads=heads, |
| 751 | dim_head=dim_head, |
| 752 | dropout=dropout, |
| 753 | qk_norm=qk_norm, |
| 754 | ) |
| 755 | |
| 756 | self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) |
| 757 | self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh") |
| 758 | |
| 759 | def forward(self, x, t, mask=None, rope=None): # x: noised input, t: time embedding |
| 760 | # pre-norm & modulation for attention input |
| 761 | norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t) |
| 762 | |
| 763 | # attention |
| 764 | attn_output = self.attn(x=norm, mask=mask, rope=rope) |
| 765 | |
| 766 | # process attention output for input x |
| 767 | x = x + gate_msa.unsqueeze(1) * attn_output |
| 768 | |
| 769 | norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None] |
| 770 | ff_output = self.ff(norm) |
| 771 | x = x + gate_mlp.unsqueeze(1) * ff_output |
| 772 | |
| 773 | return x |
| 774 | |
| 775 | |
| 776 | # MMDiT Block https://arxiv.org/abs/2403.03206 |
| 777 | |
| 778 | |
| 779 | class MMDiTBlock(nn.Module): |
| 780 | r""" |
| 781 | modified from diffusers/src/diffusers/models/attention.py |
| 782 | |
| 783 | notes. |
| 784 | _c: context related. text, cond, etc. (left part in sd3 fig2.b) |
| 785 | _x: noised input related. (right part) |
| 786 | context_pre_only: last layer only do prenorm + modulation cuz no more ffn |
| 787 | """ |
| 788 | |
| 789 | def __init__( |
| 790 | self, |
| 791 | dim, |
| 792 | heads, |
| 793 | dim_head, |
| 794 | ff_mult=4, |
| 795 | dropout=0.1, |
| 796 | context_dim=None, |
| 797 | context_pre_only=False, |
| 798 | qk_norm=None, |
| 799 | attn_backend="torch", |
| 800 | attn_mask_enabled=False, |
| 801 | ): |
| 802 | super().__init__() |
| 803 | if context_dim is None: |
| 804 | context_dim = dim |
| 805 | self.context_pre_only = context_pre_only |
| 806 | |
| 807 | self.attn_norm_c = AdaLayerNorm_Final(context_dim) if context_pre_only else AdaLayerNorm(context_dim) |
| 808 | self.attn_norm_x = AdaLayerNorm(dim) |
| 809 | self.attn = Attention( |
| 810 | processor=JointAttnProcessor( |
| 811 | attn_backend=attn_backend, |
| 812 | attn_mask_enabled=attn_mask_enabled, |
| 813 | ), |
| 814 | dim=dim, |
| 815 | heads=heads, |
| 816 | dim_head=dim_head, |
| 817 | dropout=dropout, |
| 818 | context_dim=context_dim, |
| 819 | context_pre_only=context_pre_only, |
| 820 | qk_norm=qk_norm, |
| 821 | ) |
| 822 | |
| 823 | if not context_pre_only: |
| 824 | self.ff_norm_c = nn.LayerNorm(context_dim, elementwise_affine=False, eps=1e-6) |
| 825 | self.ff_c = FeedForward(dim=context_dim, mult=ff_mult, dropout=dropout, approximate="tanh") |
| 826 | else: |
| 827 | self.ff_norm_c = None |
| 828 | self.ff_c = None |
| 829 | self.ff_norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) |
| 830 | self.ff_x = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh") |
| 831 | |
| 832 | def forward( |
| 833 | self, x, c, t, mask=None, rope=None, c_rope=None, c_mask=None |
| 834 | ): # x: noised input, c: context, t: time embedding |
| 835 | # pre-norm & modulation for attention input |
| 836 | if self.context_pre_only: |
| 837 | norm_c = self.attn_norm_c(c, t) |
| 838 | else: |
| 839 | norm_c, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.attn_norm_c(c, emb=t) |
| 840 | norm_x, x_gate_msa, x_shift_mlp, x_scale_mlp, x_gate_mlp = self.attn_norm_x(x, emb=t) |
| 841 | |
| 842 | # attention |
| 843 | x_attn_output, c_attn_output = self.attn(x=norm_x, c=norm_c, mask=mask, rope=rope, c_rope=c_rope, c_mask=c_mask) |
| 844 | |
| 845 | # process attention output for context c |
| 846 | if self.context_pre_only: |
| 847 | c = None |
| 848 | else: # if not last layer |
| 849 | c = c + c_gate_msa.unsqueeze(1) * c_attn_output |
| 850 | |
| 851 | norm_c = self.ff_norm_c(c) * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None] |
| 852 | c_ff_output = self.ff_c(norm_c) |
| 853 | c = c + c_gate_mlp.unsqueeze(1) * c_ff_output |
| 854 | |
| 855 | # process attention output for input x |
| 856 | x = x + x_gate_msa.unsqueeze(1) * x_attn_output |
| 857 | |
| 858 | norm_x = self.ff_norm_x(x) * (1 + x_scale_mlp[:, None]) + x_shift_mlp[:, None] |
| 859 | x_ff_output = self.ff_x(norm_x) |
| 860 | x = x + x_gate_mlp.unsqueeze(1) * x_ff_output |
| 861 | |
| 862 | return c, x |
| 863 | |
| 864 | |
| 865 | # time step conditioning embedding |
| 866 | |
| 867 | |
| 868 | class TimestepEmbedding(nn.Module): |
| 869 | def __init__(self, dim, freq_embed_dim=256): |
| 870 | super().__init__() |
| 871 | self.time_embed = SinusPositionEmbedding(freq_embed_dim) |
| 872 | self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) |
| 873 | |
| 874 | def forward(self, timestep: float["b"]): |
| 875 | time_hidden = self.time_embed(timestep) |
| 876 | time_hidden = time_hidden.to(timestep.dtype) |
| 877 | time = self.time_mlp(time_hidden) # b d |
| 878 | return time |
| 879 |