Upload folder using huggingface_hub
Browse files- config.json +23 -0
- configuration_dasheng_tokenizer.py +54 -0
- model.safetensors +3 -0
- modeling_dasheng_encoder.py +248 -0
- modeling_dasheng_tokenizer.py +191 -0
- vocos.py +327 -0
config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"DashengTokenizerModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_dasheng_tokenizer.DashengTokenizerConfig",
|
| 7 |
+
"AutoModel": "modeling_dasheng_tokenizer.DashengTokenizerModel"
|
| 8 |
+
},
|
| 9 |
+
"decoder_depth": 12,
|
| 10 |
+
"decoder_embed_dim": 1280,
|
| 11 |
+
"decoder_intermediate_size": 5120,
|
| 12 |
+
"depth": 32,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"embed_dim": 1280,
|
| 15 |
+
"hop_length": 160,
|
| 16 |
+
"istft_hop": 320,
|
| 17 |
+
"istft_n_fft": 1280,
|
| 18 |
+
"model_type": "dashengtokenizer",
|
| 19 |
+
"n_mels_patch": 128,
|
| 20 |
+
"num_heads": 16,
|
| 21 |
+
"transformers_version": "5.1.0",
|
| 22 |
+
"upsample_tokens": 2
|
| 23 |
+
}
|
configuration_dasheng_tokenizer.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dasheng Audio Tokenizer Configuration
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from transformers import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
class DashengTokenizerConfig(PretrainedConfig):
|
| 8 |
+
"""
|
| 9 |
+
Configuration class for DashEng Audio Tokenizer.
|
| 10 |
+
|
| 11 |
+
This configuration is used to initialize the DashEng model with the same
|
| 12 |
+
parameters as the original implementation in models.py.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
target_nmels (int): Number of Mel bins for the frontend. Default: 100
|
| 16 |
+
decoder_embed_dim (int): Decoder embedding dimension. Default: 768
|
| 17 |
+
decoder_depth (int): Number of decoder layers. Default: 8
|
| 18 |
+
decoder_intermediate_size (int): Decoder intermediate size. Default: 1536
|
| 19 |
+
istft_n_fft (int): ISTFT n_fft parameter. Default: 1280
|
| 20 |
+
istft_hop (int): ISTFT hop parameter. Default: 640
|
| 21 |
+
upsample_tokens (int): Upsample factor for tokens. Default: 1
|
| 22 |
+
n_mels_patch (int): Number of Mel bins for patch embedding. Default: 100
|
| 23 |
+
hop_length (int): Hop length for Mel spectrogram. Default: 160
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
model_type = "dashengtokenizer"
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
embed_dim: int = 1280,
|
| 31 |
+
depth:int = 32,
|
| 32 |
+
num_heads: int = 16,
|
| 33 |
+
decoder_embed_dim: int = 1280,
|
| 34 |
+
decoder_depth: int = 12,
|
| 35 |
+
decoder_intermediate_size: int = 5120,
|
| 36 |
+
istft_n_fft: int = 1280,
|
| 37 |
+
istft_hop: int = 320, # 20ms
|
| 38 |
+
upsample_tokens: int = 2,
|
| 39 |
+
n_mels_patch: int = 128, # acoustic nmel
|
| 40 |
+
hop_length: int = 160, # acoustic hop
|
| 41 |
+
**kwargs,
|
| 42 |
+
):
|
| 43 |
+
super().__init__(**kwargs)
|
| 44 |
+
self.embed_dim = embed_dim
|
| 45 |
+
self.depth = depth
|
| 46 |
+
self.num_heads = num_heads
|
| 47 |
+
self.decoder_embed_dim = decoder_embed_dim
|
| 48 |
+
self.decoder_depth = decoder_depth
|
| 49 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 50 |
+
self.istft_n_fft = istft_n_fft
|
| 51 |
+
self.istft_hop = istft_hop
|
| 52 |
+
self.upsample_tokens = upsample_tokens
|
| 53 |
+
self.n_mels_patch = n_mels_patch
|
| 54 |
+
self.hop_length = hop_length
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c930d33c7fb5358c01f2e9e4522f6242da76c3d7eabd5e60f2af841bbe42161d
|
| 3 |
+
size 3220079760
|
modeling_dasheng_encoder.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from einops import rearrange
|
| 2 |
+
from einops.layers.torch import Rearrange
|
| 3 |
+
import torchaudio.transforms as audio_transforms
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from typing import Optional, Type
|
| 7 |
+
|
| 8 |
+
class FrontEnd(nn.Sequential):
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
f_min: int = 0,
|
| 12 |
+
sample_rate: int = 16000,
|
| 13 |
+
win_size: int = 512,
|
| 14 |
+
center: bool = True,
|
| 15 |
+
n_fft: int = 512,
|
| 16 |
+
f_max: Optional[int] = 8000,
|
| 17 |
+
hop_size: int = 160,
|
| 18 |
+
n_mels: int = 64,
|
| 19 |
+
):
|
| 20 |
+
self.f_min = f_min
|
| 21 |
+
self.sample_rate = sample_rate
|
| 22 |
+
self.win_size = win_size
|
| 23 |
+
self.center = center
|
| 24 |
+
self.n_fft = n_fft
|
| 25 |
+
self.f_max = f_max
|
| 26 |
+
self.hop_size = hop_size
|
| 27 |
+
self.n_mels = n_mels
|
| 28 |
+
|
| 29 |
+
with torch.device("cpu"):
|
| 30 |
+
super().__init__(
|
| 31 |
+
audio_transforms.MelSpectrogram(
|
| 32 |
+
f_min=self.f_min,
|
| 33 |
+
sample_rate=self.sample_rate,
|
| 34 |
+
win_length=self.win_size,
|
| 35 |
+
center=self.center,
|
| 36 |
+
n_fft=self.n_fft,
|
| 37 |
+
f_max=self.f_max,
|
| 38 |
+
hop_length=self.hop_size,
|
| 39 |
+
n_mels=self.n_mels,
|
| 40 |
+
),
|
| 41 |
+
audio_transforms.AmplitudeToDB(top_db=120),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
@torch.autocast(enabled=False, device_type="cuda")
|
| 45 |
+
def forward(self, x, attention_mask=None):
|
| 46 |
+
"""
|
| 47 |
+
Forward pass of the frontend.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
x: Audio tensor of shape (batch_size, num_samples)
|
| 51 |
+
attention_mask: Optional attention mask of shape (batch_size, num_samples)
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
features: Mel spectrogram features of shape (batch_size, n_mels, num_frames)
|
| 55 |
+
attention_mask: Downsampled attention mask of shape (batch_size, num_frames)
|
| 56 |
+
"""
|
| 57 |
+
features = super().forward(x)
|
| 58 |
+
if attention_mask is not None:
|
| 59 |
+
lengths = attention_mask.float().sum(-1) // self.hop_size
|
| 60 |
+
attention_mask = (torch.arange(features.shape[-1], device=features.device) < lengths.unsqueeze(-1)).int()
|
| 61 |
+
return features, attention_mask
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Mlp(nn.Module):
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
in_features: int,
|
| 68 |
+
hidden_features: Optional[int] = None,
|
| 69 |
+
out_features: Optional[int] = None,
|
| 70 |
+
act_layer: Type[torch.nn.Module] = nn.GELU,
|
| 71 |
+
drop: float = 0.0,
|
| 72 |
+
):
|
| 73 |
+
super().__init__()
|
| 74 |
+
out_features = out_features or in_features
|
| 75 |
+
hidden_features = hidden_features or in_features
|
| 76 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
| 77 |
+
self.act = act_layer()
|
| 78 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
| 79 |
+
self.drop = nn.Dropout(drop)
|
| 80 |
+
|
| 81 |
+
def forward(self, x):
|
| 82 |
+
x = self.fc1(x)
|
| 83 |
+
x = self.act(x)
|
| 84 |
+
x = self.drop(x)
|
| 85 |
+
x = self.fc2(x)
|
| 86 |
+
x = self.drop(x)
|
| 87 |
+
return x
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Attention(nn.Module):
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
dim: int,
|
| 94 |
+
num_heads: int = 8,
|
| 95 |
+
qkv_bias: bool = True,
|
| 96 |
+
attn_drop: float = 0.0,
|
| 97 |
+
proj_drop: float = 0.0,
|
| 98 |
+
causal: bool = False,
|
| 99 |
+
):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.num_heads = num_heads
|
| 102 |
+
self.scale = (dim // num_heads) ** -0.5
|
| 103 |
+
self.causal = causal
|
| 104 |
+
|
| 105 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 106 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 107 |
+
self.proj = nn.Linear(dim, dim)
|
| 108 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 109 |
+
|
| 110 |
+
def forward(self, x, mask: Optional[torch.Tensor] = None):
|
| 111 |
+
B, N, C = x.shape
|
| 112 |
+
# qkv: [3, B, heads, N, head_dim]
|
| 113 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 114 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
| 115 |
+
|
| 116 |
+
attn = (q @ k.transpose(-2, -1)) * self.scale
|
| 117 |
+
|
| 118 |
+
# Apply Causal Mask
|
| 119 |
+
if self.causal:
|
| 120 |
+
c_mask = torch.ones(N, N, device=x.device, dtype=torch.bool).triu(1)
|
| 121 |
+
attn = attn.masked_fill(c_mask, float("-inf"))
|
| 122 |
+
|
| 123 |
+
# Apply Padding Mask (B, N) -> (B, 1, 1, N)
|
| 124 |
+
if mask is not None:
|
| 125 |
+
if mask.dtype != torch.bool:
|
| 126 |
+
padding_mask = (mask == 0)
|
| 127 |
+
else:
|
| 128 |
+
padding_mask = mask
|
| 129 |
+
padding_mask = padding_mask.view(B, 1, 1, N)
|
| 130 |
+
attn = attn.masked_fill(padding_mask, float("-inf"))
|
| 131 |
+
attn = attn.softmax(dim=-1).nan_to_num()
|
| 132 |
+
attn = self.attn_drop(attn)
|
| 133 |
+
|
| 134 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 135 |
+
return self.proj_drop(self.proj(x))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class Block(nn.Module):
|
| 139 |
+
def __init__(
|
| 140 |
+
self,
|
| 141 |
+
dim: int,
|
| 142 |
+
num_heads: int,
|
| 143 |
+
mlp_ratio: float = 4.0,
|
| 144 |
+
qkv_bias: bool = True,
|
| 145 |
+
drop: float = 0.0,
|
| 146 |
+
attn_drop: float = 0.0,
|
| 147 |
+
):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.norm1 = nn.LayerNorm(dim, eps=1e-6)
|
| 150 |
+
self.attn = Attention(dim, num_heads, qkv_bias, attn_drop, drop)
|
| 151 |
+
self.norm2 = nn.LayerNorm(dim, eps=1e-6)
|
| 152 |
+
self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=nn.GELU, drop=drop)
|
| 153 |
+
|
| 154 |
+
def forward(self, x, mask=None):
|
| 155 |
+
x = x + self.attn(self.norm1(x), mask=mask)
|
| 156 |
+
x = x + self.mlp(self.norm2(x))
|
| 157 |
+
return x
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class AudioPatchEmbed(torch.nn.Module):
|
| 161 |
+
|
| 162 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.stride = kwargs.get('stride', [None, 4])[-1]
|
| 165 |
+
self.proj = nn.Conv2d(*args, **kwargs)
|
| 166 |
+
|
| 167 |
+
def forward(self, x:torch.Tensor, attention_mask:torch.Tensor | None =None):
|
| 168 |
+
x = self.proj(x)
|
| 169 |
+
if attention_mask is not None:
|
| 170 |
+
lengths = attention_mask.float().sum(-1) // self.stride
|
| 171 |
+
attention_mask = (torch.arange(x.shape[-1], device=x.device) < lengths.unsqueeze(-1)).int()
|
| 172 |
+
return x, attention_mask
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class DashengEncoder(nn.Module):
|
| 178 |
+
def __init__(
|
| 179 |
+
self,
|
| 180 |
+
embed_dim: int = 1280,
|
| 181 |
+
depth: int = 32,
|
| 182 |
+
num_heads: int = 20,
|
| 183 |
+
patch_size=[64, 4],
|
| 184 |
+
patch_stride=[64, 4],
|
| 185 |
+
target_length=1008,
|
| 186 |
+
):
|
| 187 |
+
super().__init__()
|
| 188 |
+
self.embed_dim = embed_dim
|
| 189 |
+
self.time_patches = patch_stride[-1]
|
| 190 |
+
self.front_end = FrontEnd()
|
| 191 |
+
self.target_length = target_length
|
| 192 |
+
self.max_t_tokens = target_length // patch_stride[-1]
|
| 193 |
+
self.patch_embed = AudioPatchEmbed(1, embed_dim, kernel_size=patch_size, stride=patch_stride)
|
| 194 |
+
self.init_bn = nn.Sequential(
|
| 195 |
+
Rearrange("b c f t -> b f c t"),
|
| 196 |
+
torch.nn.BatchNorm2d(self.front_end.n_mels, momentum=0.01),
|
| 197 |
+
Rearrange("b f c t -> b c f t"),
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
self.time_pos_embed = nn.Parameter(torch.randn(1, embed_dim, 1, target_length // self.time_patches) * 0.02)
|
| 201 |
+
self.freq_pos_embed = nn.Parameter(torch.randn(1, embed_dim, 1, 1) * 0.02)
|
| 202 |
+
|
| 203 |
+
self.blocks = nn.ModuleList([Block(embed_dim, num_heads) for _ in range(depth)])
|
| 204 |
+
self.norm = nn.LayerNorm(embed_dim, eps=1e-6)
|
| 205 |
+
|
| 206 |
+
def _forward_main(self, x, attention_mask, mask_to_zero:bool = False):
|
| 207 |
+
x, attention_mask = self.patch_embed(x, attention_mask)
|
| 208 |
+
t = x.shape[-1]
|
| 209 |
+
x = x + self.time_pos_embed[:, :, :, :t] + self.freq_pos_embed
|
| 210 |
+
x = rearrange(x, "b c f t -> b (f t) c")
|
| 211 |
+
for block in self.blocks:
|
| 212 |
+
x = block(x, mask=attention_mask)
|
| 213 |
+
x = self.norm(x)
|
| 214 |
+
if attention_mask is not None and mask_to_zero:
|
| 215 |
+
x = x * attention_mask.unsqueeze(-1) # Zero out all samples that were masked, but only after first chunk
|
| 216 |
+
return x
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def forward(self, x: torch.Tensor, attention_mask=None):
|
| 220 |
+
"""
|
| 221 |
+
Forward pass of the AudioTransformer.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
x: Audio tensor of shape (batch_size, num_samples)
|
| 225 |
+
attention_mask: Optional attention mask of shape (batch_size, num_samples)
|
| 226 |
+
where True indicates valid samples and False indicates padding
|
| 227 |
+
|
| 228 |
+
Returns:
|
| 229 |
+
embeddings: Token embeddings of shape (batch_size, num_tokens, embed_dim)
|
| 230 |
+
"""
|
| 231 |
+
# Process through frontend - returns features and downsampled mask
|
| 232 |
+
x, attention_mask = self.front_end(x, attention_mask)
|
| 233 |
+
|
| 234 |
+
# Rearrange features for patch embedding: (b f t) -> (b 1 f t)
|
| 235 |
+
x = rearrange(x, "b f t -> b 1 f t")
|
| 236 |
+
x = self.init_bn(x)
|
| 237 |
+
|
| 238 |
+
input_splits = x.split(self.target_length, dim=-1)
|
| 239 |
+
masks = [None for _ in range(len(input_splits))]
|
| 240 |
+
if attention_mask is not None:
|
| 241 |
+
masks = attention_mask.split(self.target_length, dim=-1)
|
| 242 |
+
|
| 243 |
+
outputs = []
|
| 244 |
+
for i, (input_split_x, mask) in enumerate(zip(input_splits, masks)):
|
| 245 |
+
output = self._forward_main(input_split_x, attention_mask=mask, mask_to_zero=i != 0)
|
| 246 |
+
outputs.append(output)
|
| 247 |
+
x = torch.cat(outputs, dim=1)
|
| 248 |
+
return x
|
modeling_dasheng_tokenizer.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ashengTokenizerConfig
|
| 2 |
+
from .modeling_dasheng_encoder import DashengEncoder
|
| 3 |
+
from .vocos import VocosModel
|
| 4 |
+
from typing import Optional, Tuple, Union
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
import torchaudio
|
| 9 |
+
from transformers import PreTrainedModel
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class VocosMelSpec(torch.nn.Module):
|
| 13 |
+
"""MelSpectrogram frontend for Vocos."""
|
| 14 |
+
def __init__(self, sample_rate=16000, n_fft=1024, hop_length=256, n_mels=100, padding="center"):
|
| 15 |
+
super().__init__()
|
| 16 |
+
if padding not in ["center", "same"]:
|
| 17 |
+
raise ValueError("Padding must be 'center' or 'same'.")
|
| 18 |
+
self.padding = padding
|
| 19 |
+
self.sample_rate = sample_rate
|
| 20 |
+
self.n_fft = n_fft
|
| 21 |
+
self.hop_length = hop_length
|
| 22 |
+
self.n_mels = n_mels
|
| 23 |
+
with torch.device("cpu"):
|
| 24 |
+
self.mel_spec = torchaudio.transforms.MelSpectrogram(
|
| 25 |
+
sample_rate=self.sample_rate,
|
| 26 |
+
n_fft=self.n_fft,
|
| 27 |
+
hop_length=self.hop_length,
|
| 28 |
+
n_mels=self.n_mels,
|
| 29 |
+
center=self.padding == "center",
|
| 30 |
+
power=1,)
|
| 31 |
+
|
| 32 |
+
def forward(self, audio, **kwargs):
|
| 33 |
+
if self.padding == "same":
|
| 34 |
+
pad = self.mel_spec.win_length - self.mel_spec.hop_length
|
| 35 |
+
audio = torch.nn.functional.pad(audio, (pad // 2, pad // 2), mode="reflect")
|
| 36 |
+
mel = self.mel_spec(audio)
|
| 37 |
+
return torch.log(torch.clip(mel, min=1e-7))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DashengTokenizerEncoder(torch.nn.Module):
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
embed_dim: int = 1280,
|
| 44 |
+
depth:int = 32,
|
| 45 |
+
num_heads: int = 16,
|
| 46 |
+
n_mels_patch: int = 128,
|
| 47 |
+
hop_length: int = 160,
|
| 48 |
+
**kwargs,
|
| 49 |
+
):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.model = DashengEncoder(embed_dim=embed_dim, depth=depth, num_heads=num_heads)
|
| 52 |
+
self.embed_dim = int(self.model.embed_dim)
|
| 53 |
+
self.model.outputlayer = torch.nn.Identity()
|
| 54 |
+
|
| 55 |
+
self.front_end = VocosMelSpec(hop_length=hop_length, n_mels=n_mels_patch)
|
| 56 |
+
self.patch_embed = torch.nn.Conv2d(
|
| 57 |
+
1, self.model.embed_dim, (n_mels_patch, 4), (n_mels_patch, 4)
|
| 58 |
+
)
|
| 59 |
+
self.norm = torch.nn.LayerNorm(self.model.embed_dim)
|
| 60 |
+
|
| 61 |
+
# Store parameters for reference
|
| 62 |
+
self.n_fft = self.model.front_end.n_fft
|
| 63 |
+
self.hop_size = self.model.front_end.hop_size
|
| 64 |
+
|
| 65 |
+
@torch.no_grad()
|
| 66 |
+
def forward(
|
| 67 |
+
self,
|
| 68 |
+
input: torch.Tensor,
|
| 69 |
+
input_attn_mask: torch.Tensor | None = None,
|
| 70 |
+
) -> torch.Tensor:
|
| 71 |
+
"""
|
| 72 |
+
Forward pass of the encoder.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
input: Audio tensor of shape (batch_size, num_samples)
|
| 76 |
+
input_attn_mask: Optional attention mask
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
Combined embeddings of shape (batch_size, num_tokens, embed_dim)
|
| 80 |
+
"""
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
semantic_emb = self.model(input, input_attn_mask)
|
| 83 |
+
|
| 84 |
+
# acoustic part
|
| 85 |
+
mel = self.front_end(input).unsqueeze(1)
|
| 86 |
+
mel_emb = self.patch_embed(mel)
|
| 87 |
+
acoustic_emb = rearrange(mel_emb, "b c f t -> b (f t) c")
|
| 88 |
+
acoustic_emb = self.norm(acoustic_emb)
|
| 89 |
+
|
| 90 |
+
semantic_emb = semantic_emb[:, : acoustic_emb.shape[1], :]
|
| 91 |
+
emb = semantic_emb + acoustic_emb
|
| 92 |
+
return emb
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class DashengTokenizerPreTrainedModel(PreTrainedModel):
|
| 96 |
+
|
| 97 |
+
config_class = DashengTokenizerConfig
|
| 98 |
+
supports_gradient_checkpointing = True
|
| 99 |
+
|
| 100 |
+
class DashengTokenizerModel(DashengTokenizerPreTrainedModel):
|
| 101 |
+
"""
|
| 102 |
+
HuggingFace-compatible DashEng Tokenizer Model (Encoder + Decoder).
|
| 103 |
+
|
| 104 |
+
This model includes both the encoder and decoder for end-to-end audio processing.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __init__(self, config: DashengTokenizerConfig):
|
| 108 |
+
super().__init__(config)
|
| 109 |
+
self.config = config
|
| 110 |
+
|
| 111 |
+
self.encoder = DashengTokenizerEncoder(
|
| 112 |
+
embed_dim=config.embed_dim,
|
| 113 |
+
depth = config.depth,
|
| 114 |
+
num_heads=config.num_heads,
|
| 115 |
+
n_mels_patch=config.n_mels_patch,
|
| 116 |
+
hop_length=config.hop_length,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
self.embed_dim = self.encoder.embed_dim
|
| 120 |
+
|
| 121 |
+
# Upsampler (if needed)
|
| 122 |
+
self.upsampler = None
|
| 123 |
+
if config.upsample_tokens > 1:
|
| 124 |
+
self.upsampler = torch.nn.ConvTranspose1d(
|
| 125 |
+
self.embed_dim, self.embed_dim,
|
| 126 |
+
kernel_size=config.upsample_tokens,
|
| 127 |
+
stride=config.upsample_tokens
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Decoder
|
| 131 |
+
self.decoder = VocosModel(
|
| 132 |
+
input_channels=self.embed_dim,
|
| 133 |
+
hidden_dim=config.decoder_embed_dim,
|
| 134 |
+
intermediate_dim=config.decoder_intermediate_size,
|
| 135 |
+
vocos_istft_hop=config.istft_hop,
|
| 136 |
+
vocos_n_fft=config.istft_n_fft,
|
| 137 |
+
num_layers=config.decoder_depth,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
self.post_init()
|
| 141 |
+
|
| 142 |
+
def encode(
|
| 143 |
+
self,
|
| 144 |
+
audio: torch.Tensor,
|
| 145 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 146 |
+
) -> torch.Tensor:
|
| 147 |
+
"""Encode audio into embeddings."""
|
| 148 |
+
return self.encoder(audio, attention_mask)
|
| 149 |
+
|
| 150 |
+
def decode(self, embeddings: torch.Tensor) -> torch.Tensor:
|
| 151 |
+
"""Decode embeddings back to audio."""
|
| 152 |
+
if self.upsampler is not None:
|
| 153 |
+
embeddings = self.upsampler(embeddings.transpose(-2, -1)).transpose(-2, -1)
|
| 154 |
+
output = self.decoder(embeddings.transpose(-2, -1))
|
| 155 |
+
return output
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self,
|
| 159 |
+
audio: torch.Tensor,
|
| 160 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 161 |
+
return_dict: Optional[bool] = None,
|
| 162 |
+
) -> Union[Tuple[torch.Tensor], dict]:
|
| 163 |
+
"""
|
| 164 |
+
Forward pass of the DashEng tokenizer.
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
audio: Audio tensor of shape (batch_size, num_samples)
|
| 168 |
+
attention_mask: Optional attention mask
|
| 169 |
+
output_attentions: Whether to return attention weights
|
| 170 |
+
output_hidden_states: Whether to return hidden states
|
| 171 |
+
return_dict: Whether to return a dict
|
| 172 |
+
|
| 173 |
+
Returns:
|
| 174 |
+
Reconstructed audio of shape (batch_size, num_samples)
|
| 175 |
+
"""
|
| 176 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 177 |
+
|
| 178 |
+
# Encode
|
| 179 |
+
embeddings = self.encoder(audio, attention_mask)
|
| 180 |
+
|
| 181 |
+
# Decode
|
| 182 |
+
audio_reconstructed = self.decode(embeddings)
|
| 183 |
+
|
| 184 |
+
if not return_dict:
|
| 185 |
+
return (audio_reconstructed,)
|
| 186 |
+
|
| 187 |
+
return {
|
| 188 |
+
"audio": audio_reconstructed,
|
| 189 |
+
"embeddings": embeddings,
|
| 190 |
+
}
|
| 191 |
+
|
vocos.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Standalone Vocos implementation for DashEng HuggingFace models.
|
| 3 |
+
|
| 4 |
+
This is a minimal, self-contained implementation of Vocos that doesn't depend
|
| 5 |
+
on external vocos libraries, making it suitable for HuggingFace Hub publication.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
from typing import Optional, Tuple
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class AdaLayerNorm(nn.Module):
|
| 14 |
+
"""
|
| 15 |
+
Adaptive Layer Normalization module with learnable embeddings per `num_embeddings` classes
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
num_embeddings (int): Number of embeddings.
|
| 19 |
+
embedding_dim (int): Dimension of the embeddings.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, eps: float = 1e-6):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.eps = eps
|
| 25 |
+
self.dim = embedding_dim
|
| 26 |
+
self.scale = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim)
|
| 27 |
+
self.shift = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim)
|
| 28 |
+
torch.nn.init.ones_(self.scale.weight)
|
| 29 |
+
torch.nn.init.zeros_(self.shift.weight)
|
| 30 |
+
|
| 31 |
+
def forward(self, x: torch.Tensor, cond_embedding_id: torch.Tensor) -> torch.Tensor:
|
| 32 |
+
scale = self.scale(cond_embedding_id)
|
| 33 |
+
shift = self.shift(cond_embedding_id)
|
| 34 |
+
x = nn.functional.layer_norm(x, (self.dim,), eps=self.eps)
|
| 35 |
+
x = x * scale + shift
|
| 36 |
+
return x
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ConvNeXtBlock(nn.Module):
|
| 40 |
+
"""ConvNeXt Block adapted from https://github.com/facebookresearch/ConvNeXt to 1D audio signal.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
dim (int): Number of input channels.
|
| 44 |
+
intermediate_dim (int): Dimensionality of the intermediate layer.
|
| 45 |
+
layer_scale_init_value (float, optional): Initial value for the layer scale. None means no scaling.
|
| 46 |
+
Defaults to None.
|
| 47 |
+
adanorm_num_embeddings (int, optional): Number of embeddings for AdaLayerNorm.
|
| 48 |
+
None means non-conditional LayerNorm. Defaults to None.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
dim: int,
|
| 54 |
+
intermediate_dim: int,
|
| 55 |
+
layer_scale_init_value: float,
|
| 56 |
+
adanorm_num_embeddings: Optional[int] = None,
|
| 57 |
+
):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.dwconv = nn.Conv1d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
|
| 60 |
+
self.adanorm = adanorm_num_embeddings is not None
|
| 61 |
+
if adanorm_num_embeddings:
|
| 62 |
+
self.norm = AdaLayerNorm(adanorm_num_embeddings, dim, eps=1e-6)
|
| 63 |
+
else:
|
| 64 |
+
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
| 65 |
+
self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers
|
| 66 |
+
self.act = nn.GELU()
|
| 67 |
+
self.pwconv2 = nn.Linear(intermediate_dim, dim)
|
| 68 |
+
self.gamma = (
|
| 69 |
+
nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
|
| 70 |
+
if layer_scale_init_value > 0
|
| 71 |
+
else None
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def forward(
|
| 75 |
+
self,
|
| 76 |
+
x: torch.Tensor,
|
| 77 |
+
cond_embedding_id: Optional[torch.Tensor] = None,
|
| 78 |
+
speaker_embedding: Optional[torch.Tensor] = None,
|
| 79 |
+
) -> torch.Tensor:
|
| 80 |
+
residual = x
|
| 81 |
+
x = self.dwconv(x)
|
| 82 |
+
x = x.transpose(1, 2) # (B, C, T) -> (B, T, C)
|
| 83 |
+
if self.adanorm:
|
| 84 |
+
assert cond_embedding_id is not None
|
| 85 |
+
x = self.norm(x, cond_embedding_id)
|
| 86 |
+
else:
|
| 87 |
+
x = self.norm(x)
|
| 88 |
+
x = self.pwconv1(x)
|
| 89 |
+
if speaker_embedding is not None:
|
| 90 |
+
x = x + speaker_embedding.unsqueeze(1) # same speaker across all frames
|
| 91 |
+
x = self.act(x)
|
| 92 |
+
x = self.pwconv2(x)
|
| 93 |
+
if self.gamma is not None:
|
| 94 |
+
x = self.gamma * x
|
| 95 |
+
x = x.transpose(1, 2) # (B, T, C) -> (B, C, T)
|
| 96 |
+
|
| 97 |
+
x = residual + x
|
| 98 |
+
return x
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ISTFT(nn.Module):
|
| 102 |
+
"""
|
| 103 |
+
Custom implementation of ISTFT since torch.istft doesn't allow custom padding (other than `center=True`) with
|
| 104 |
+
windowing. This is because the NOLA (Nonzero Overlap Add) check fails at the edges.
|
| 105 |
+
See issue: https://github.com/pytorch/pytorch/issues/62323
|
| 106 |
+
Specifically, in the context of neural vocoding we are interested in "same" padding analogous to CNNs.
|
| 107 |
+
The NOLA constraint is met as we trim padded samples anyway.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
n_fft (int): Size of Fourier transform.
|
| 111 |
+
hop_length (int): The distance between neighboring sliding window frames.
|
| 112 |
+
win_length (int): The size of window frame and STFT filter.
|
| 113 |
+
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
def __init__(self, n_fft: int, hop_length: int, win_length: int, padding: str = "same"):
|
| 117 |
+
super().__init__()
|
| 118 |
+
if padding not in ["center", "same"]:
|
| 119 |
+
raise ValueError("Padding must be 'center' or 'same'.")
|
| 120 |
+
self.padding = padding
|
| 121 |
+
self.n_fft = n_fft
|
| 122 |
+
self.hop_length = hop_length
|
| 123 |
+
self.win_length = win_length
|
| 124 |
+
window = torch.hann_window(win_length)
|
| 125 |
+
self.register_buffer("window", window)
|
| 126 |
+
|
| 127 |
+
def forward(self, spec: torch.Tensor) -> torch.Tensor:
|
| 128 |
+
"""
|
| 129 |
+
Compute the Inverse Short Time Fourier Transform (ISTFT) of a complex spectrogram.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
spec (Tensor): Input complex spectrogram of shape (B, N, T), where B is the batch size,
|
| 133 |
+
N is the number of frequency bins, and T is the number of time frames.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
Tensor: Reconstructed time-domain signal of shape (B, L), where L is the length of the output signal.
|
| 137 |
+
"""
|
| 138 |
+
if self.padding == "center":
|
| 139 |
+
# Fallback to pytorch native implementation
|
| 140 |
+
return torch.istft(spec, self.n_fft, self.hop_length, self.win_length, self.window, center=True)
|
| 141 |
+
elif self.padding == "same":
|
| 142 |
+
pad = (self.win_length - self.hop_length) // 2
|
| 143 |
+
else:
|
| 144 |
+
raise ValueError("Padding must be 'center' or 'same'.")
|
| 145 |
+
|
| 146 |
+
assert spec.dim() == 3, "Expected a 3D tensor as input"
|
| 147 |
+
B, N, T = spec.shape
|
| 148 |
+
|
| 149 |
+
# Inverse FFT
|
| 150 |
+
ifft = torch.fft.irfft(spec, self.n_fft, dim=1, norm="backward")
|
| 151 |
+
ifft = ifft * self.window[None, :, None]
|
| 152 |
+
|
| 153 |
+
# Overlap and Add
|
| 154 |
+
output_size = (T - 1) * self.hop_length + self.win_length
|
| 155 |
+
y = torch.nn.functional.fold(
|
| 156 |
+
ifft,
|
| 157 |
+
output_size=(1, output_size),
|
| 158 |
+
kernel_size=(1, self.win_length),
|
| 159 |
+
stride=(1, self.hop_length),
|
| 160 |
+
)[:, 0, 0, pad:-pad]
|
| 161 |
+
|
| 162 |
+
# Window envelope
|
| 163 |
+
window_sq = self.window.square().expand(1, T, -1).transpose(1, 2)
|
| 164 |
+
window_envelope = torch.nn.functional.fold(
|
| 165 |
+
window_sq,
|
| 166 |
+
output_size=(1, output_size),
|
| 167 |
+
kernel_size=(1, self.win_length),
|
| 168 |
+
stride=(1, self.hop_length),
|
| 169 |
+
).squeeze()[pad:-pad]
|
| 170 |
+
|
| 171 |
+
# Normalize
|
| 172 |
+
assert (window_envelope > 1e-11).all()
|
| 173 |
+
y = y / window_envelope
|
| 174 |
+
|
| 175 |
+
return y
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class ISTFTHead(nn.Module):
|
| 179 |
+
"""
|
| 180 |
+
ISTFT Head module for predicting STFT complex coefficients.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
dim (int): Hidden dimension of the model.
|
| 184 |
+
n_fft (int): Size of Fourier transform.
|
| 185 |
+
hop_length (int): The distance between neighboring sliding window frames, which should align with
|
| 186 |
+
the resolution of the input features.
|
| 187 |
+
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
def __init__(self, dim: int, n_fft: int, hop_length: int, padding: str = "same"):
|
| 191 |
+
super().__init__()
|
| 192 |
+
out_dim = n_fft + 2
|
| 193 |
+
self.out = torch.nn.Linear(dim, out_dim)
|
| 194 |
+
self.istft = ISTFT(n_fft=n_fft, hop_length=hop_length, win_length=n_fft, padding=padding)
|
| 195 |
+
|
| 196 |
+
@torch.autocast(device_type="cuda", enabled=False)
|
| 197 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 198 |
+
"""
|
| 199 |
+
Forward pass of the ISTFTHead module.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
x (Tensor): Input tensor of shape (B, L, H), where B is the batch size,
|
| 203 |
+
L is the sequence length, and H denotes the model dimension.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
Tensor: Reconstructed time-domain audio signal of shape (B, T), where T is the length of the output signal.
|
| 207 |
+
"""
|
| 208 |
+
x = self.out(x).transpose(1, 2)
|
| 209 |
+
mag, p = x.chunk(2, dim=1)
|
| 210 |
+
mag = torch.exp(mag)
|
| 211 |
+
mag = torch.clip(mag, max=1e2) # safeguard to prevent excessively large magnitudes
|
| 212 |
+
# wrapping happens here. These two lines produce real and imaginary value
|
| 213 |
+
x = torch.cos(p)
|
| 214 |
+
y = torch.sin(p)
|
| 215 |
+
# recalculating phase here does not produce anything new
|
| 216 |
+
# only costs time
|
| 217 |
+
# phase = torch.atan2(y, x)
|
| 218 |
+
# S = mag * torch.exp(phase * 1j)
|
| 219 |
+
# better directly produce the complex value
|
| 220 |
+
S = mag * (x + 1j * y)
|
| 221 |
+
audio = self.istft(S)
|
| 222 |
+
return audio
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class VocosBackbone(nn.Module):
|
| 226 |
+
"""
|
| 227 |
+
Vocos backbone module built with ConvNeXt blocks. Supports additional conditioning with Adaptive Layer Normalization
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
input_channels (int): Number of input features channels.
|
| 231 |
+
dim (int): Hidden dimension of the model.
|
| 232 |
+
intermediate_dim (int): Intermediate dimension used in ConvNeXtBlock.
|
| 233 |
+
num_layers (int): Number of ConvNeXtBlock layers.
|
| 234 |
+
layer_scale_init_value (float, optional): Initial value for layer scaling. Defaults to `1 / num_layers`.
|
| 235 |
+
adanorm_num_embeddings (int, optional): Number of embeddings for AdaLayerNorm.
|
| 236 |
+
None means non-conditional model. Defaults to None.
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
def __init__(
|
| 240 |
+
self,
|
| 241 |
+
input_channels: int,
|
| 242 |
+
dim: int,
|
| 243 |
+
intermediate_dim: int,
|
| 244 |
+
num_layers: int,
|
| 245 |
+
layer_scale_init_value: Optional[float] = None,
|
| 246 |
+
adanorm_num_embeddings: Optional[int] = None,
|
| 247 |
+
):
|
| 248 |
+
super().__init__()
|
| 249 |
+
self.input_channels = input_channels
|
| 250 |
+
self.embed = nn.Conv1d(input_channels, dim, kernel_size=7, padding=3)
|
| 251 |
+
self.adanorm = adanorm_num_embeddings is not None
|
| 252 |
+
if adanorm_num_embeddings:
|
| 253 |
+
self.norm = AdaLayerNorm(adanorm_num_embeddings, dim, eps=1e-6)
|
| 254 |
+
else:
|
| 255 |
+
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
| 256 |
+
layer_scale_init_value = layer_scale_init_value or 1 / num_layers
|
| 257 |
+
self.convnext = nn.ModuleList(
|
| 258 |
+
[
|
| 259 |
+
ConvNeXtBlock(
|
| 260 |
+
dim=dim,
|
| 261 |
+
intermediate_dim=intermediate_dim,
|
| 262 |
+
layer_scale_init_value=layer_scale_init_value,
|
| 263 |
+
adanorm_num_embeddings=adanorm_num_embeddings,
|
| 264 |
+
)
|
| 265 |
+
for _ in range(num_layers)
|
| 266 |
+
]
|
| 267 |
+
)
|
| 268 |
+
self.final_layer_norm = nn.LayerNorm(dim, eps=1e-6)
|
| 269 |
+
self.apply(self._init_weights)
|
| 270 |
+
|
| 271 |
+
def _init_weights(self, m):
|
| 272 |
+
if isinstance(m, (nn.Conv1d, nn.Linear)):
|
| 273 |
+
nn.init.trunc_normal_(m.weight, std=0.02)
|
| 274 |
+
nn.init.constant_(m.bias, 0)
|
| 275 |
+
|
| 276 |
+
def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor:
|
| 277 |
+
bandwidth_id = kwargs.get("bandwidth_id", None)
|
| 278 |
+
speaker_embedding = kwargs.get("speaker_embedding", None)
|
| 279 |
+
x = self.embed(x)
|
| 280 |
+
if self.adanorm:
|
| 281 |
+
assert bandwidth_id is not None
|
| 282 |
+
x = self.norm(x.transpose(1, 2), cond_embedding_id=bandwidth_id)
|
| 283 |
+
else:
|
| 284 |
+
x = self.norm(x.transpose(1, 2))
|
| 285 |
+
x = x.transpose(1, 2)
|
| 286 |
+
for conv_block in self.convnext:
|
| 287 |
+
x = conv_block(x, cond_embedding_id=bandwidth_id, speaker_embedding=speaker_embedding)
|
| 288 |
+
x = self.final_layer_norm(x.transpose(1, 2))
|
| 289 |
+
return x
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class VocosModel(torch.nn.Module):
|
| 293 |
+
"""
|
| 294 |
+
Vocos model for audio synthesis from learned representations.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
input_channels (int): Number of input feature channels.
|
| 298 |
+
hidden_dim (int): Hidden dimension of the model.
|
| 299 |
+
intermediate_dim (int): Intermediate dimension used in ConvNeXtBlock.
|
| 300 |
+
num_layers (int): Number of ConvNeXtBlock layers.
|
| 301 |
+
vocos_istft_hop (int): Hop length for ISTFT.
|
| 302 |
+
vocos_n_fft (int): FFT size for ISTFT.
|
| 303 |
+
padding (str, optional): Type of padding. Options are "center" or "same". Defaults to "same".
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
def __init__(
|
| 307 |
+
self,
|
| 308 |
+
input_channels: int = 1024,
|
| 309 |
+
hidden_dim: int = 512,
|
| 310 |
+
intermediate_dim: int = 1536,
|
| 311 |
+
num_layers: int = 8,
|
| 312 |
+
vocos_istft_hop: int = 256,
|
| 313 |
+
vocos_n_fft: int = 1024,
|
| 314 |
+
padding: str = "same",
|
| 315 |
+
**kwargs,
|
| 316 |
+
) -> None:
|
| 317 |
+
super().__init__()
|
| 318 |
+
default_kwargs = dict(
|
| 319 |
+
input_channels=input_channels, dim=hidden_dim, intermediate_dim=intermediate_dim, num_layers=num_layers
|
| 320 |
+
)
|
| 321 |
+
self.backbone = VocosBackbone(**default_kwargs)
|
| 322 |
+
self.head = ISTFTHead(**dict(dim=hidden_dim, n_fft=vocos_n_fft, hop_length=vocos_istft_hop, padding=padding))
|
| 323 |
+
|
| 324 |
+
def forward(self, x, **kwargs):
|
| 325 |
+
x = self.backbone(x, **kwargs)
|
| 326 |
+
audio_output = self.head(x)
|
| 327 |
+
return audio_output
|