Text Generation
Transformers
Safetensors
English
nemotron_labs_audex
nvidia
nemotron-labs-audex
reasoning
general-purpose
SFT
audio-language-modeling
audio-understanding
text-to-speech
text-to-audio
speech-recognition
speech-translation
Instructions to use Arsh9210/Nemotron-Labs-Audex-2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Arsh9210/Nemotron-Labs-Audex-2B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Arsh9210/Nemotron-Labs-Audex-2B")# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Arsh9210/Nemotron-Labs-Audex-2B", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Arsh9210/Nemotron-Labs-Audex-2B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Arsh9210/Nemotron-Labs-Audex-2B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Arsh9210/Nemotron-Labs-Audex-2B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Arsh9210/Nemotron-Labs-Audex-2B
- SGLang
How to use Arsh9210/Nemotron-Labs-Audex-2B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Arsh9210/Nemotron-Labs-Audex-2B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Arsh9210/Nemotron-Labs-Audex-2B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Arsh9210/Nemotron-Labs-Audex-2B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Arsh9210/Nemotron-Labs-Audex-2B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Arsh9210/Nemotron-Labs-Audex-2B with Docker Model Runner:
docker model run hf.co/Arsh9210/Nemotron-Labs-Audex-2B
Added audex_causal_speech_decoder/modeling_audex_causal_speech_decoder.py
Browse files
audex_causal_speech_decoder/modeling_audex_causal_speech_decoder.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from collections.abc import Iterator, Sequence
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from torch import Tensor
|
| 24 |
+
from transformers import PreTrainedModel
|
| 25 |
+
|
| 26 |
+
from .configuration_audex_causal_speech_decoder import AudexCausalSpeechDecoderConfig
|
| 27 |
+
from .streaming_utils import load_audex_causal_speech_decoder as _load_decoder_for_remote_code
|
| 28 |
+
|
| 29 |
+
REMOTE_CODE_IMPORTS = (_load_decoder_for_remote_code,)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class RotaryPositionalEmbeddings(nn.Module):
|
| 33 |
+
def __init__(self, dim: int, max_seq_len: int = 4096, base: int = 10_000) -> None:
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.dim = dim
|
| 36 |
+
self.base = base
|
| 37 |
+
self.max_seq_len = max_seq_len
|
| 38 |
+
self.rope_init()
|
| 39 |
+
self._rope_ready = False
|
| 40 |
+
|
| 41 |
+
def rope_init(self, device: "torch.device | None" = None) -> None:
|
| 42 |
+
theta = 1.0 / (
|
| 43 |
+
self.base
|
| 44 |
+
** (torch.arange(0, self.dim, 2, device=device)[: (self.dim // 2)].float() / self.dim)
|
| 45 |
+
)
|
| 46 |
+
self.register_buffer("theta", theta, persistent=False)
|
| 47 |
+
self.build_rope_cache(self.max_seq_len)
|
| 48 |
+
|
| 49 |
+
def build_rope_cache(self, max_seq_len: int = 4096) -> None:
|
| 50 |
+
self.max_seq_len = max_seq_len
|
| 51 |
+
seq_idx = torch.arange(max_seq_len, dtype=self.theta.dtype, device=self.theta.device)
|
| 52 |
+
idx_theta = torch.einsum("i, j -> ij", seq_idx, self.theta).float()
|
| 53 |
+
cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
|
| 54 |
+
self.register_buffer("cache", cache, persistent=False)
|
| 55 |
+
|
| 56 |
+
def forward(self, x: torch.Tensor, *, input_pos: torch.Tensor | None = None) -> torch.Tensor:
|
| 57 |
+
seq_len = x.size(1)
|
| 58 |
+
needed_seq_len = seq_len if input_pos is None else int(input_pos.max().item()) + 1
|
| 59 |
+
if (
|
| 60 |
+
not getattr(self, "_rope_ready", False)
|
| 61 |
+
or self.theta.device != x.device
|
| 62 |
+
or needed_seq_len > self.cache.size(0)
|
| 63 |
+
):
|
| 64 |
+
self.rope_init(device=x.device)
|
| 65 |
+
if needed_seq_len > self.cache.size(0):
|
| 66 |
+
self.build_rope_cache(max(needed_seq_len, self.cache.size(0) * 2))
|
| 67 |
+
self._rope_ready = True
|
| 68 |
+
|
| 69 |
+
rope_cache = self.cache[:seq_len] if input_pos is None else self.cache[input_pos]
|
| 70 |
+
xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
|
| 71 |
+
rope_cache = rope_cache.view(-1, xshaped.size(1), 1, xshaped.size(3), 2)
|
| 72 |
+
x_out = torch.stack(
|
| 73 |
+
[
|
| 74 |
+
xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
|
| 75 |
+
xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
|
| 76 |
+
],
|
| 77 |
+
-1,
|
| 78 |
+
)
|
| 79 |
+
return x_out.flatten(3).type_as(x)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class CausalCodecDecoderCache:
|
| 83 |
+
def __init__(self) -> None:
|
| 84 |
+
self.key_values: dict[int, tuple[Tensor, Tensor]] = {}
|
| 85 |
+
self.position = 0
|
| 86 |
+
|
| 87 |
+
def input_positions(self, length: int, device: torch.device) -> Tensor:
|
| 88 |
+
return torch.arange(self.position, self.position + length, device=device).unsqueeze(0)
|
| 89 |
+
|
| 90 |
+
def update(self, layer_idx: int, key: Tensor, value: Tensor) -> tuple[Tensor, Tensor]:
|
| 91 |
+
if layer_idx in self.key_values:
|
| 92 |
+
prev_key, prev_value = self.key_values[layer_idx]
|
| 93 |
+
key = torch.cat([prev_key, key], dim=2)
|
| 94 |
+
value = torch.cat([prev_value, value], dim=2)
|
| 95 |
+
self.key_values[layer_idx] = (key, value)
|
| 96 |
+
return key, value
|
| 97 |
+
|
| 98 |
+
def advance(self, length: int) -> None:
|
| 99 |
+
self.position += length
|
| 100 |
+
|
| 101 |
+
def reset(self) -> None:
|
| 102 |
+
self.key_values.clear()
|
| 103 |
+
self.position = 0
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class RMSNorm(nn.Module):
|
| 107 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 108 |
+
super().__init__()
|
| 109 |
+
self.eps = eps
|
| 110 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 111 |
+
|
| 112 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 113 |
+
norm_x = torch.mean(x**2, dim=-1, keepdim=True)
|
| 114 |
+
return x * torch.rsqrt(norm_x + self.eps) * self.weight
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class MLP(nn.Module):
|
| 118 |
+
def __init__(self, dim: int) -> None:
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.fc1 = nn.Linear(dim, 4 * dim, bias=False)
|
| 121 |
+
self.silu = nn.SiLU()
|
| 122 |
+
self.fc2 = nn.Linear(4 * dim, dim, bias=False)
|
| 123 |
+
|
| 124 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 125 |
+
return self.fc2(self.silu(self.fc1(x)))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class Attention(nn.Module):
|
| 129 |
+
def __init__(self, dim: int, n_heads: int, rotary_embed: RotaryPositionalEmbeddings, layer_idx: int):
|
| 130 |
+
super().__init__()
|
| 131 |
+
if dim % n_heads != 0:
|
| 132 |
+
raise ValueError(f"dim must be divisible by n_heads, got dim={dim}, n_heads={n_heads}")
|
| 133 |
+
self.n_heads = n_heads
|
| 134 |
+
self.layer_idx = layer_idx
|
| 135 |
+
self.rotary_embed = rotary_embed
|
| 136 |
+
self.c_attn = nn.Linear(dim, 3 * dim, bias=False)
|
| 137 |
+
self.c_proj = nn.Linear(dim, dim, bias=False)
|
| 138 |
+
|
| 139 |
+
def forward(
|
| 140 |
+
self,
|
| 141 |
+
x: torch.Tensor,
|
| 142 |
+
cache: CausalCodecDecoderCache | None = None,
|
| 143 |
+
input_pos: Tensor | None = None,
|
| 144 |
+
) -> torch.Tensor:
|
| 145 |
+
batch_size, seq_len, _ = x.shape
|
| 146 |
+
qkv = self.c_attn(x)
|
| 147 |
+
head_dim = qkv.size(-1) // (3 * self.n_heads)
|
| 148 |
+
qkv = qkv.view(batch_size, seq_len, 3, self.n_heads, head_dim).permute(2, 0, 3, 1, 4)
|
| 149 |
+
q, k, v = qkv.unbind(0)
|
| 150 |
+
|
| 151 |
+
q = self.rotary_embed(q.transpose(1, 2), input_pos=input_pos).transpose(1, 2)
|
| 152 |
+
k = self.rotary_embed(k.transpose(1, 2), input_pos=input_pos).transpose(1, 2)
|
| 153 |
+
if cache is None:
|
| 154 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 155 |
+
else:
|
| 156 |
+
if input_pos is None:
|
| 157 |
+
raise ValueError("input_pos is required when cache is set")
|
| 158 |
+
k, v = cache.update(self.layer_idx, k, v)
|
| 159 |
+
key_pos = torch.arange(k.size(2), device=x.device).view(1, 1, 1, -1)
|
| 160 |
+
attn_mask = key_pos <= input_pos.view(input_pos.size(0), 1, -1, 1)
|
| 161 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
|
| 162 |
+
return self.c_proj(y.transpose(1, 2).contiguous().view(batch_size, seq_len, -1))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class TransformerBlock(nn.Module):
|
| 166 |
+
def __init__(self, dim: int, n_heads: int, rotary_embed: RotaryPositionalEmbeddings, layer_idx: int):
|
| 167 |
+
super().__init__()
|
| 168 |
+
self.att_norm = RMSNorm(dim)
|
| 169 |
+
self.ffn_norm = RMSNorm(dim)
|
| 170 |
+
self.att = Attention(dim=dim, n_heads=n_heads, rotary_embed=rotary_embed, layer_idx=layer_idx)
|
| 171 |
+
self.mlp = MLP(dim=dim)
|
| 172 |
+
|
| 173 |
+
def forward(
|
| 174 |
+
self,
|
| 175 |
+
x: torch.Tensor,
|
| 176 |
+
cache: CausalCodecDecoderCache | None = None,
|
| 177 |
+
input_pos: Tensor | None = None,
|
| 178 |
+
) -> torch.Tensor:
|
| 179 |
+
x = x + self.att(self.att_norm(x), cache=cache, input_pos=input_pos)
|
| 180 |
+
return x + self.mlp(self.ffn_norm(x))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class PatchHead(nn.Module):
|
| 184 |
+
def __init__(self, dim: int, hop_length: int = 320):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.proj = nn.Linear(dim, hop_length, bias=False)
|
| 187 |
+
|
| 188 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 189 |
+
x = torch.tanh(self.proj(x))
|
| 190 |
+
return x.reshape(x.size(0), 1, -1)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class CausalVocosBackbone(nn.Module):
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
hidden_dim: int = 2048,
|
| 197 |
+
depth: int = 12,
|
| 198 |
+
heads: int = 32,
|
| 199 |
+
pos_meb_dim: int = 64,
|
| 200 |
+
):
|
| 201 |
+
super().__init__()
|
| 202 |
+
rotary_embed = RotaryPositionalEmbeddings(dim=pos_meb_dim)
|
| 203 |
+
self.transformers = nn.ModuleList(
|
| 204 |
+
[
|
| 205 |
+
TransformerBlock(dim=hidden_dim, n_heads=heads, rotary_embed=rotary_embed, layer_idx=idx)
|
| 206 |
+
for idx in range(depth)
|
| 207 |
+
]
|
| 208 |
+
)
|
| 209 |
+
self.final_layer_norm = RMSNorm(hidden_dim)
|
| 210 |
+
|
| 211 |
+
def forward(self, x: torch.Tensor, cache: CausalCodecDecoderCache | None = None) -> torch.Tensor:
|
| 212 |
+
input_pos = None
|
| 213 |
+
if cache is not None:
|
| 214 |
+
input_pos = cache.input_positions(x.size(1), x.device).expand(x.size(0), -1)
|
| 215 |
+
for block in self.transformers:
|
| 216 |
+
x = block(x, cache=cache, input_pos=input_pos)
|
| 217 |
+
if cache is not None:
|
| 218 |
+
cache.advance(x.size(1))
|
| 219 |
+
return self.final_layer_norm(x)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class CausalCodecDecoderVocos(nn.Module):
|
| 223 |
+
def __init__(
|
| 224 |
+
self,
|
| 225 |
+
hidden_dim: int = 2048,
|
| 226 |
+
depth: int = 12,
|
| 227 |
+
heads: int = 32,
|
| 228 |
+
pos_meb_dim: int = 64,
|
| 229 |
+
hop_length: int = 320,
|
| 230 |
+
vq_dim: int = 2048,
|
| 231 |
+
lookahead_steps: int = 0,
|
| 232 |
+
):
|
| 233 |
+
super().__init__()
|
| 234 |
+
if lookahead_steps < 0:
|
| 235 |
+
raise ValueError(f"lookahead_steps must be >= 0, got {lookahead_steps}")
|
| 236 |
+
|
| 237 |
+
self.wav_proj = nn.Linear(hop_length, hidden_dim, bias=False)
|
| 238 |
+
self.fc_post_a = nn.Linear(vq_dim, hidden_dim, bias=False)
|
| 239 |
+
self.lookahead_steps = lookahead_steps
|
| 240 |
+
if lookahead_steps > 0:
|
| 241 |
+
self.lookahead_conv = nn.Conv1d(
|
| 242 |
+
hidden_dim,
|
| 243 |
+
hidden_dim,
|
| 244 |
+
kernel_size=lookahead_steps + 1,
|
| 245 |
+
padding=0,
|
| 246 |
+
groups=hidden_dim,
|
| 247 |
+
bias=False,
|
| 248 |
+
)
|
| 249 |
+
self.lookahead_act = nn.SiLU()
|
| 250 |
+
self.lookahead_proj = nn.Conv1d(hidden_dim, hidden_dim, kernel_size=1, bias=False)
|
| 251 |
+
nn.init.zeros_(self.lookahead_proj.weight)
|
| 252 |
+
else:
|
| 253 |
+
self.lookahead_conv = None
|
| 254 |
+
self.lookahead_act = None
|
| 255 |
+
self.lookahead_proj = None
|
| 256 |
+
self.backbone = CausalVocosBackbone(hidden_dim, depth, heads, pos_meb_dim)
|
| 257 |
+
self.head = PatchHead(hidden_dim, hop_length)
|
| 258 |
+
|
| 259 |
+
def _project_tokens(self, vq_emb: torch.Tensor) -> torch.Tensor:
|
| 260 |
+
return self.fc_post_a(vq_emb)
|
| 261 |
+
|
| 262 |
+
def _apply_lookahead(self, x: torch.Tensor) -> torch.Tensor:
|
| 263 |
+
if self.lookahead_conv is None:
|
| 264 |
+
return x
|
| 265 |
+
if self.lookahead_act is None or self.lookahead_proj is None:
|
| 266 |
+
raise RuntimeError("lookahead modules are not initialized")
|
| 267 |
+
h = F.pad(x.transpose(1, 2), (0, self.lookahead_steps))
|
| 268 |
+
h = self.lookahead_proj(self.lookahead_act(self.lookahead_conv(h)))
|
| 269 |
+
return x + h.transpose(1, 2)
|
| 270 |
+
|
| 271 |
+
def _apply_lookahead_window(self, x: torch.Tensor) -> torch.Tensor:
|
| 272 |
+
if self.lookahead_conv is None:
|
| 273 |
+
return x
|
| 274 |
+
if self.lookahead_act is None or self.lookahead_proj is None:
|
| 275 |
+
raise RuntimeError("lookahead modules are not initialized")
|
| 276 |
+
if x.size(1) <= self.lookahead_steps:
|
| 277 |
+
raise ValueError(f"lookahead window needs more than {self.lookahead_steps} frames, got {x.size(1)}")
|
| 278 |
+
h = self.lookahead_proj(self.lookahead_act(self.lookahead_conv(x.transpose(1, 2))))
|
| 279 |
+
return x[:, : h.size(2)] + h.transpose(1, 2)
|
| 280 |
+
|
| 281 |
+
def decode_cached(
|
| 282 |
+
self,
|
| 283 |
+
vq_emb: torch.Tensor,
|
| 284 |
+
cache: CausalCodecDecoderCache,
|
| 285 |
+
lookahead_vq_emb: torch.Tensor | None = None,
|
| 286 |
+
) -> torch.Tensor:
|
| 287 |
+
x = self._project_tokens(vq_emb)
|
| 288 |
+
if self.lookahead_steps > 0:
|
| 289 |
+
if lookahead_vq_emb is None:
|
| 290 |
+
lookahead_vq_emb = vq_emb.new_zeros(vq_emb.size(0), self.lookahead_steps, vq_emb.size(-1))
|
| 291 |
+
if lookahead_vq_emb.size(1) != self.lookahead_steps:
|
| 292 |
+
raise ValueError(
|
| 293 |
+
f"lookahead_vq_emb must have {self.lookahead_steps} frames, got {lookahead_vq_emb.size(1)}"
|
| 294 |
+
)
|
| 295 |
+
lookahead_x = self._project_tokens(lookahead_vq_emb)
|
| 296 |
+
x = self._apply_lookahead_window(torch.cat([x, lookahead_x], dim=1))
|
| 297 |
+
x = self.backbone(x, cache=cache)
|
| 298 |
+
return self.head(x)
|
| 299 |
+
|
| 300 |
+
def forward(
|
| 301 |
+
self,
|
| 302 |
+
vq_emb: torch.Tensor,
|
| 303 |
+
patched_wav: torch.Tensor | None = None,
|
| 304 |
+
alpha: float = 0.0,
|
| 305 |
+
) -> torch.Tensor:
|
| 306 |
+
x = self._project_tokens(vq_emb)
|
| 307 |
+
x = self._apply_lookahead(x)
|
| 308 |
+
if patched_wav is not None:
|
| 309 |
+
h = self.wav_proj(patched_wav)
|
| 310 |
+
mask = torch.bernoulli(
|
| 311 |
+
torch.full(
|
| 312 |
+
(x.size(0), x.size(1), 1),
|
| 313 |
+
min(max(alpha, 0.0), 1.0),
|
| 314 |
+
device=x.device,
|
| 315 |
+
dtype=x.dtype,
|
| 316 |
+
)
|
| 317 |
+
)
|
| 318 |
+
x = x + h * mask
|
| 319 |
+
return self.head(self.backbone(x))
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class AudexSpeechTokenEmbedder(nn.Module):
|
| 323 |
+
def __init__(
|
| 324 |
+
self,
|
| 325 |
+
output_dim: int,
|
| 326 |
+
token_embed_dim: int,
|
| 327 |
+
codebook_levels: Sequence[int],
|
| 328 |
+
) -> None:
|
| 329 |
+
super().__init__()
|
| 330 |
+
if len(codebook_levels) != token_embed_dim:
|
| 331 |
+
raise ValueError(
|
| 332 |
+
f"token_embed_dim={token_embed_dim} must match codebook_levels length={len(codebook_levels)}"
|
| 333 |
+
)
|
| 334 |
+
self.codebook_levels = tuple(int(level) for level in codebook_levels)
|
| 335 |
+
self.project_out = nn.Linear(token_embed_dim, output_dim)
|
| 336 |
+
|
| 337 |
+
def forward(self, indices: torch.Tensor) -> torch.Tensor:
|
| 338 |
+
if indices.size(-1) != 1:
|
| 339 |
+
raise ValueError(f"indices last dimension must be 1, got {indices.size(-1)}")
|
| 340 |
+
levels = torch.tensor(self.codebook_levels, dtype=torch.long, device=indices.device)
|
| 341 |
+
basis = torch.cumprod(torch.cat([levels.new_ones(1), levels[:-1]]), dim=0)
|
| 342 |
+
level_indices = (indices.long() // basis) % levels
|
| 343 |
+
dtype = self.project_out.weight.dtype
|
| 344 |
+
codes = level_indices.to(dtype=dtype)
|
| 345 |
+
levels = levels.to(dtype=dtype)
|
| 346 |
+
codes = codes * (2.0 / (levels - 1.0)) - 1.0
|
| 347 |
+
return self.project_out(codes)
|
| 348 |
+
|
| 349 |
+
def get_output_from_indices(self, indices: torch.Tensor) -> torch.Tensor:
|
| 350 |
+
return self(indices)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class AudexCausalSpeechDecoderModel(PreTrainedModel):
|
| 354 |
+
config_class = AudexCausalSpeechDecoderConfig
|
| 355 |
+
base_model_prefix = "module"
|
| 356 |
+
all_tied_weights_keys: dict[str, Any] = {}
|
| 357 |
+
Cache = CausalCodecDecoderCache
|
| 358 |
+
|
| 359 |
+
def __init__(self, config: AudexCausalSpeechDecoderConfig):
|
| 360 |
+
super().__init__(config)
|
| 361 |
+
self.audex_speech_token_embedder = AudexSpeechTokenEmbedder(
|
| 362 |
+
output_dim=config.vq_dim,
|
| 363 |
+
token_embed_dim=config.token_embed_dim,
|
| 364 |
+
codebook_levels=config.codebook_levels,
|
| 365 |
+
)
|
| 366 |
+
self.module = CausalCodecDecoderVocos(
|
| 367 |
+
hidden_dim=config.hidden_dim,
|
| 368 |
+
depth=config.depth,
|
| 369 |
+
heads=config.heads,
|
| 370 |
+
pos_meb_dim=config.pos_meb_dim,
|
| 371 |
+
hop_length=config.hop_length,
|
| 372 |
+
vq_dim=config.vq_dim,
|
| 373 |
+
lookahead_steps=config.lookahead_steps,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
@property
|
| 377 |
+
def lookahead_steps(self) -> int:
|
| 378 |
+
return self.module.lookahead_steps
|
| 379 |
+
|
| 380 |
+
def create_cache(self) -> CausalCodecDecoderCache:
|
| 381 |
+
return CausalCodecDecoderCache()
|
| 382 |
+
|
| 383 |
+
def decode_cached(
|
| 384 |
+
self,
|
| 385 |
+
vq_emb: torch.Tensor,
|
| 386 |
+
cache: CausalCodecDecoderCache,
|
| 387 |
+
lookahead_vq_emb: torch.Tensor | None = None,
|
| 388 |
+
) -> torch.Tensor:
|
| 389 |
+
return self.module.decode_cached(vq_emb, cache, lookahead_vq_emb=lookahead_vq_emb)
|
| 390 |
+
|
| 391 |
+
def create_session(
|
| 392 |
+
self,
|
| 393 |
+
*,
|
| 394 |
+
chunk_frames: int = 1,
|
| 395 |
+
sample_rate: int | None = None,
|
| 396 |
+
return_numpy: bool = True,
|
| 397 |
+
) -> "AudexCausalSpeechDecoderSession":
|
| 398 |
+
return AudexCausalSpeechDecoderSession(
|
| 399 |
+
decoder=self,
|
| 400 |
+
chunk_frames=chunk_frames,
|
| 401 |
+
sample_rate=sample_rate or self.config.sample_rate,
|
| 402 |
+
return_numpy=return_numpy,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
def forward(
|
| 406 |
+
self,
|
| 407 |
+
vq_emb: torch.Tensor,
|
| 408 |
+
patched_wav: torch.Tensor | None = None,
|
| 409 |
+
alpha: float = 0.0,
|
| 410 |
+
) -> torch.Tensor:
|
| 411 |
+
return self.module(vq_emb, patched_wav=patched_wav, alpha=alpha)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class AudexCausalSpeechDecoderSession:
|
| 415 |
+
def __init__(
|
| 416 |
+
self,
|
| 417 |
+
decoder: AudexCausalSpeechDecoderModel,
|
| 418 |
+
*,
|
| 419 |
+
chunk_frames: int,
|
| 420 |
+
sample_rate: int,
|
| 421 |
+
return_numpy: bool,
|
| 422 |
+
):
|
| 423 |
+
if chunk_frames <= 0:
|
| 424 |
+
raise ValueError(f"chunk_frames must be positive, got {chunk_frames}")
|
| 425 |
+
self.decoder = decoder
|
| 426 |
+
self.chunk_frames = chunk_frames
|
| 427 |
+
self.sample_rate = sample_rate
|
| 428 |
+
self.return_numpy = return_numpy
|
| 429 |
+
self.cache = decoder.create_cache()
|
| 430 |
+
self.buffer: list[list[int]] = []
|
| 431 |
+
|
| 432 |
+
@property
|
| 433 |
+
def device(self) -> torch.device:
|
| 434 |
+
return next(self.decoder.parameters()).device
|
| 435 |
+
|
| 436 |
+
def reset(self) -> None:
|
| 437 |
+
self.cache = self.decoder.create_cache()
|
| 438 |
+
self.buffer.clear()
|
| 439 |
+
|
| 440 |
+
def push(self, token_frames: Sequence[Sequence[int]]) -> Iterator[tuple[int, Any]]:
|
| 441 |
+
self.buffer.extend(list(frame) for frame in token_frames)
|
| 442 |
+
yield from self._drain(flush=False)
|
| 443 |
+
|
| 444 |
+
def flush(self) -> Iterator[tuple[int, Any]]:
|
| 445 |
+
yield from self._drain(flush=True)
|
| 446 |
+
|
| 447 |
+
def _drain(self, *, flush: bool) -> Iterator[tuple[int, Any]]:
|
| 448 |
+
ready_frames = len(self.buffer) - self.decoder.lookahead_steps
|
| 449 |
+
while self.buffer and (flush or ready_frames >= self.chunk_frames):
|
| 450 |
+
emit_frames = min(self.chunk_frames, len(self.buffer)) if flush else self.chunk_frames
|
| 451 |
+
wav = self._decode_buffered_frames(emit_frames, flush=flush)
|
| 452 |
+
del self.buffer[:emit_frames]
|
| 453 |
+
ready_frames = len(self.buffer) - self.decoder.lookahead_steps
|
| 454 |
+
yield self.sample_rate, self._format_chunk(wav)
|
| 455 |
+
|
| 456 |
+
def _embed_speech_token_frames(self, token_frames: Sequence[Sequence[int]]) -> torch.Tensor:
|
| 457 |
+
indices = torch.tensor(token_frames, dtype=torch.long, device=self.device).unsqueeze(0)
|
| 458 |
+
return self.decoder.audex_speech_token_embedder.get_output_from_indices(indices)
|
| 459 |
+
|
| 460 |
+
def _decode_buffered_frames(self, emit_frames: int, *, flush: bool) -> torch.Tensor:
|
| 461 |
+
with torch.inference_mode():
|
| 462 |
+
vq_emb = self._embed_speech_token_frames(self.buffer[:emit_frames])
|
| 463 |
+
lookahead_vq_emb = None
|
| 464 |
+
if self.decoder.lookahead_steps > 0:
|
| 465 |
+
future_frames = self.buffer[emit_frames : emit_frames + self.decoder.lookahead_steps]
|
| 466 |
+
future_parts = []
|
| 467 |
+
if future_frames:
|
| 468 |
+
future_parts.append(self._embed_speech_token_frames(future_frames))
|
| 469 |
+
missing_frames = self.decoder.lookahead_steps - len(future_frames) if flush else 0
|
| 470 |
+
if missing_frames > 0:
|
| 471 |
+
future_parts.append(vq_emb.new_zeros(vq_emb.size(0), missing_frames, vq_emb.size(-1)))
|
| 472 |
+
lookahead_vq_emb = torch.cat(future_parts, dim=1) if future_parts else None
|
| 473 |
+
return self.decoder.decode_cached(vq_emb, self.cache, lookahead_vq_emb=lookahead_vq_emb)
|
| 474 |
+
|
| 475 |
+
def _format_chunk(self, wav: torch.Tensor) -> Any:
|
| 476 |
+
chunk = wav.squeeze().float().detach().cpu()
|
| 477 |
+
if not self.return_numpy:
|
| 478 |
+
return chunk
|
| 479 |
+
|
| 480 |
+
import numpy as np
|
| 481 |
+
|
| 482 |
+
return chunk.numpy().astype(np.float32, copy=False)
|