[Model] Add single-stage Qwen3-TTS with in-Talker streaming codec decode (#8259)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-10-02 21:34:30 +10:00
1 parent 596487fe62
commit e84014dffb
43 files changed
+3565 -90

No files matched your search

@@ -954,7 +954,13 @@ class CodePredictorWrapper(nn.Module):
extra_cfg = connector_cfg.get("extra", connector_cfg)
else:
extra_cfg = getattr(connector_cfg, "extra", None)
return extra_cfg if isinstance(extra_cfg, dict) else {}
extra_cfg = extra_cfg if isinstance(extra_cfg, dict) else {}
# A single-stage deployment has no connector edge to carry model
# options; it sets them in the stage's ``additional_config``.
additional = getattr(vllm_config, "additional_config", None)
if isinstance(additional, dict) and additional:
return {**additional, **extra_cfg}
return extra_cfg
@staticmethod
def _parse_bool_config(value: object) -> bool:
@@ -1332,6 +1338,21 @@ class CodePredictorWrapper(nn.Module):
scaled = scaled.masked_fill(scaled < topk_vals[:, -1:], float("-inf"))
return self._sample_codes_gumbel(scaled, generator=generator, uniforms=uniforms)
def _validate_sampling_inputs(
self,
bsz: int,
generators: Sequence[torch.Generator | None] | None,
sample_uniforms: torch.Tensor | None,
) -> None:
if generators is not None and len(generators) != bsz:
raise ValueError(f"generators must have one entry per row: got {len(generators)} for batch {bsz}")
if sample_uniforms is not None:
expected_shape = (bsz, self._num_groups - 1, int(self.config.vocab_size))
if tuple(sample_uniforms.shape) != expected_shape:
raise ValueError(
f"sample_uniforms must have shape {expected_shape}, got {tuple(sample_uniforms.shape)}"
)
@torch.inference_mode()
def forward(
self,
@@ -1349,14 +1370,7 @@ class CodePredictorWrapper(nn.Module):
"""Predict residual codebooks 1..G-1 autoregressively via re-prefill."""
bsz = int(layer0_code.shape[0])
num_groups = self._num_groups
if generators is not None and len(generators) != bsz:
raise ValueError(f"generators must have one entry per row: got {len(generators)} for batch {bsz}")
if sample_uniforms is not None:
expected_shape = (bsz, num_groups - 1, int(self.config.vocab_size))
if tuple(sample_uniforms.shape) != expected_shape:
raise ValueError(
f"sample_uniforms must have shape {expected_shape}, got {tuple(sample_uniforms.shape)}"
)
self._validate_sampling_inputs(bsz, generators, sample_uniforms)
sample_generator: _GeneratorLike = generators if generators is not None else generator
device = layer0_code.device
@@ -0,0 +1,312 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803 - Triton constexpr parameters use kernel-style capitals.
"""Fused residual-codebook predictor for Qwen3-TTS (CUDA, BF16).
Same computation as the frame-local-KV predictor with per-call top-k Gumbel
sampling, restructured to issue few kernels per residual step, since at serving
batch sizes each of the 15 dependent steps is launch- and latency-bound:
- Per layer: RMSNorm, one QKV GEMM, one attention kernel (q/k RMSNorm, RoPE,
this call's K/V write and attention over the frame's keys), O projection
accumulated into the residual stream (``addmm_``), RMSNorm, gate/up GEMM,
SiLU-mul, down projection accumulated into the stream.
- The embedding of each sampled code followed by ``small_to_mtp_projection``
is linear, so it folds at load into one ``[vocab, hidden]`` table per
codebook; the sampling kernel writes the next step's input row directly.
- Sampling finds the top-k threshold by bisection over the BF16 order keys
(exact k-th largest, ties kept) instead of a sort.
"""
from __future__ import annotations
import torch
from vllm.triton_utils import tl, tldevice, triton
from .tokenizer_12hz.streaming_decoder import _silu_mul_kernel
@triton.jit
def _rms_rows_kernel(x_ptr, x_stride, w_ptr, out_ptr, eps, N: tl.constexpr):
row = tl.program_id(0).to(tl.int64)
offs = tl.arange(0, N)
x = tl.load(x_ptr + row * x_stride + offs).to(tl.float32)
var = tl.sum(x * x, axis=0) / N
dt = out_ptr.dtype.element_ty
y = (x * tl.rsqrt(var + eps)).to(dt).to(tl.float32)
w = tl.load(w_ptr + offs).to(tl.float32)
tl.store(out_ptr + row * N + offs, (w * y).to(dt))
@triton.jit
def _bf(x):
return x.to(tl.bfloat16).to(tl.float32)
@triton.jit
def _head_norm_rope(x1, x2, w1, w2, c1, c2, s1, s2, eps, HD: tl.constexpr):
"""HF RMSNorm (``weight * normed.to(bf16)``) then RoPE in BF16 elementwise steps, on the two halves."""
var = (tl.sum(x1 * x1, axis=0) + tl.sum(x2 * x2, axis=0)) / HD
r = tl.rsqrt(var + eps)
n1 = _bf(w1 * _bf(x1 * r))
n2 = _bf(w2 * _bf(x2 * r))
# rotate_half(n) = [-n2, n1]
o1 = _bf(_bf(n1 * c1) + _bf(-n2 * s1))
o2 = _bf(_bf(n2 * c2) + _bf(n1 * s2))
return o1, o2
@triton.jit
def _cp_attention_kernel(
qkv_ptr, # [B * NQ, (H + 2 * KVH) * HD]
kc_ptr, # [Bmax, KVH, MAXP, HD]
vc_ptr,
qw_ptr,
kw_ptr,
cos_ptr, # [MAXP, HD] bf16
sin_ptr,
out_ptr, # [B * NQ, H * HD]
first,
eps,
scale,
NQ: tl.constexpr,
H: tl.constexpr,
KVH: tl.constexpr,
HD: tl.constexpr,
MAXP: tl.constexpr,
BK: tl.constexpr,
):
b = tl.program_id(0)
h = tl.program_id(1)
qi = tl.program_id(2)
kvh = h // (H // KVH)
W: tl.constexpr = (H + 2 * KVH) * HD
HALF: tl.constexpr = HD // 2
d = tl.arange(0, HALF)
p = first + qi
row = (b * NQ + qi).to(tl.int64)
qw1 = tl.load(qw_ptr + d).to(tl.float32)
qw2 = tl.load(qw_ptr + HALF + d).to(tl.float32)
kw1 = tl.load(kw_ptr + d).to(tl.float32)
kw2 = tl.load(kw_ptr + HALF + d).to(tl.float32)
qb = qkv_ptr + row * W + h * HD
q1, q2 = _head_norm_rope(
tl.load(qb + d).to(tl.float32), tl.load(qb + HALF + d).to(tl.float32), qw1, qw2,
tl.load(cos_ptr + p * HD + d).to(tl.float32), tl.load(cos_ptr + p * HD + HALF + d).to(tl.float32),
tl.load(sin_ptr + p * HD + d).to(tl.float32), tl.load(sin_ptr + p * HD + HALF + d).to(tl.float32),
eps, HD,
) # fmt: skip
j = tl.arange(0, BK)
cache = ((b * KVH + kvh) * MAXP).to(tl.int64) * HD
old = (j < first)[:, None]
kp = kc_ptr + cache + j[:, None] * HD + d[None, :]
vp = vc_ptr + cache + j[:, None] * HD + d[None, :]
k1 = tl.load(kp, mask=old, other=0.0).to(tl.float32)
k2 = tl.load(kp + HALF, mask=old, other=0.0).to(tl.float32)
v1 = tl.load(vp, mask=old, other=0.0).to(tl.float32)
v2 = tl.load(vp + HALF, mask=old, other=0.0).to(tl.float32)
for n in tl.static_range(NQ):
# this call's position first + n, computed from its own QKV row
on = first + n
kb = qkv_ptr + (b * NQ + n).to(tl.int64) * W + (H + kvh) * HD
vb = qkv_ptr + (b * NQ + n).to(tl.int64) * W + (H + KVH + kvh) * HD
kn1, kn2 = _head_norm_rope(
tl.load(kb + d).to(tl.float32), tl.load(kb + HALF + d).to(tl.float32), kw1, kw2,
tl.load(cos_ptr + on * HD + d).to(tl.float32), tl.load(cos_ptr + on * HD + HALF + d).to(tl.float32),
tl.load(sin_ptr + on * HD + d).to(tl.float32), tl.load(sin_ptr + on * HD + HALF + d).to(tl.float32),
eps, HD,
) # fmt: skip
vn1 = tl.load(vb + d).to(tl.float32)
vn2 = tl.load(vb + HALF + d).to(tl.float32)
sel = (j == on)[:, None]
k1 = tl.where(sel, kn1[None, :], k1)
k2 = tl.where(sel, kn2[None, :], k2)
v1 = tl.where(sel, vn1[None, :], v1)
v2 = tl.where(sel, vn2[None, :], v2)
wm = (d < HALF) & (qi == n) & (h % (H // KVH) == 0)
dtc = kc_ptr.dtype.element_ty
tl.store(kc_ptr + cache + on * HD + d, kn1.to(dtc), mask=wm)
tl.store(kc_ptr + cache + on * HD + HALF + d, kn2.to(dtc), mask=wm)
tl.store(vc_ptr + cache + on * HD + d, vn1.to(dtc), mask=wm)
tl.store(vc_ptr + cache + on * HD + HALF + d, vn2.to(dtc), mask=wm)
km = j <= p
s = (tl.sum(k1 * q1[None, :], axis=1) + tl.sum(k2 * q2[None, :], axis=1)) * scale
s = tl.where(km, s, -float("inf"))
e = tl.exp(s - tl.max(s, axis=0))
e = tl.where(km, e, 0.0)
w = e / tl.sum(e, axis=0)
ob = out_ptr + row * (H * HD) + h * HD
dto = out_ptr.dtype.element_ty
tl.store(ob + d, tl.sum(v1 * w[:, None], axis=0).to(dto))
tl.store(ob + HALF + d, tl.sum(v2 * w[:, None], axis=0).to(dto))
@triton.jit
def _cp_sample_kernel(
logits_ptr, # [B, V] bf16
u_ptr, # uniforms, row stride u_stride, contiguous over V
u_stride,
codes_ptr, # [B, G] int64
step,
G: tl.constexpr,
table_ptr, # [V, HID] next-step input table, or dummy
next_ptr, # [B, HID]
inv_temperature,
V: tl.constexpr,
TOPK: tl.constexpr,
HID: tl.constexpr,
HAS_NEXT: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
idx = tl.arange(0, V)
value = tl.load(logits_ptr + row * V + idx)
scaled = (value.to(tl.float32) * inv_temperature).to(value.dtype)
if TOPK > 0:
# order-preserving 16-bit keys of the BF16 values
bits = scaled.to(tl.int16, bitcast=True).to(tl.int32) & 0xFFFF
# Top-k keeps all numeric ties at the cutoff, including both zeros.
bits = tl.where((bits & 0x7FFF) == 0, 0, bits)
key = tl.where(bits >= 0x8000, 0xFFFF - bits, bits | 0x8000)
the = 0
for bit in tl.static_range(15, -1, -1):
cand = the | (1 << bit)
cnt = tl.sum((key >= cand).to(tl.int32), axis=0)
the = tl.where(cnt >= TOPK, cand, the)
sf = tl.where(key >= the, scaled.to(tl.float32), -float("inf"))
else:
sf = scaled.to(tl.float32)
u = tl.load(u_ptr + row * u_stride + idx)
score = sf - tldevice.log(-tldevice.log(u))
max_score = tl.max(score, 0)
chosen = tl.min(tl.where(score == max_score, idx, V), 0)
first_nan = tl.min(tl.where(score != score, idx, V), 0)
code = tl.where(first_nan < V, first_nan, chosen)
tl.store(codes_ptr + row * G + step, code.to(tl.int64))
if HAS_NEXT:
c = tl.arange(0, HID)
tl.store(next_ptr + row * HID + c, tl.load(table_ptr + code.to(tl.int64) * HID + c))
class FusedCodePredictor:
"""Execution object built from a loaded ``Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM``."""
def __init__(self, predictor, max_batch: int) -> None:
model = predictor.model
weight = next(model.parameters())
dev, dt = weight.device, weight.dtype
if dt != torch.bfloat16:
raise ValueError("fused code predictor requires BF16 weights")
cfg = predictor.config
self.groups = int(cfg.num_code_groups)
self.vocab = int(cfg.vocab_size)
self.hidden = int(cfg.hidden_size)
attn0 = model.layers[0].self_attn
self.heads, self.kv_heads, self.head_dim = attn0.num_heads, attn0.num_kv_heads, attn0.head_dim
self.scale = attn0.scaling
self.eps = float(model.norm.variance_epsilon)
self.max_pos = attn0.max_seq
self.max_batch = max_batch
f32 = lambda t: t.detach().to(device=dev, dtype=torch.float32) # noqa: E731
c = lambda t: t.to(dt).contiguous() # noqa: E731
proj = predictor.small_to_mtp_projection
if isinstance(proj, torch.nn.Identity):
pw, pb = None, None
else:
pw, pb = f32(proj.weight), f32(proj.bias)
self.proj_wt = c(pw.t()) if pw is not None else None
self.proj_b = c(pb) if pb is not None else None
tables = []
for emb in model.codec_embedding:
e = f32(emb.weight)
tables.append(c(e @ pw.t() + pb) if pw is not None else c(e))
self.tables = tables
self.layers = []
for layer in model.layers:
a = layer.self_attn
self.layers.append(
dict(
ln1=c(f32(layer.input_layernorm.weight)),
ln2=c(f32(layer.post_attention_layernorm.weight)),
eps1=float(layer.input_layernorm.variance_epsilon),
eps2=float(layer.post_attention_layernorm.variance_epsilon),
qkv=c(f32(a.qkv_proj.weight).t()),
qn=c(f32(a.q_norm.weight)),
kn=c(f32(a.k_norm.weight)),
head_eps=float(a.q_norm.variance_epsilon),
o=c(f32(a.o_proj.weight).t()),
gu=c(f32(layer.mlp.gate_up_proj.weight).t()),
down=c(f32(layer.mlp.down_proj.weight).t()),
)
)
if a.qkv_proj.bias is not None:
raise ValueError("fused code predictor assumes bias-free attention")
self.norm_w = c(f32(model.norm.weight))
self.lm_heads = [c(f32(h.weight).t()) for h in predictor.lm_head]
rot = model.rotary_emb
self.cos = rot.cos_cached.to(device=dev, dtype=dt).contiguous()
self.sin = rot.sin_cached.to(device=dev, dtype=dt).contiguous()
kv = (len(self.layers), 2, max_batch, self.kv_heads, self.max_pos, self.head_dim)
self.cache = torch.zeros(kv, device=dev, dtype=dt)
self._dummy = torch.zeros(1, device=dev, dtype=dt)
def _layer(self, x: torch.Tensor, li: int, B: int, nq: int, first: int) -> None:
L = self.layers[li]
rows = x.shape[0]
h = torch.empty_like(x)
_rms_rows_kernel[(rows,)](x, x.stride(0), L["ln1"], h, L["eps1"], N=self.hidden)
qkv = torch.mm(h, L["qkv"])
att = torch.empty(rows, self.heads * self.head_dim, device=x.device, dtype=x.dtype)
_cp_attention_kernel[(B, self.heads, nq)](
qkv, self.cache[li, 0], self.cache[li, 1], L["qn"], L["kn"], self.cos, self.sin, att,
first, L["head_eps"], self.scale,
NQ=nq, H=self.heads, KVH=self.kv_heads, HD=self.head_dim, MAXP=self.max_pos,
BK=triton.next_power_of_2(self.max_pos), num_warps=1,
) # fmt: skip
x.addmm_(att, L["o"])
_rms_rows_kernel[(rows,)](x, x.stride(0), L["ln2"], h, L["eps2"], N=self.hidden)
gu = torch.mm(h, L["gu"])
inter = gu.shape[1] // 2
a = torch.empty(rows, inter, device=x.device, dtype=x.dtype)
_silu_mul_kernel[(rows, triton.cdiv(inter, 1024))](gu, a, N=inter, BN=1024)
x.addmm_(a, L["down"])
@torch.inference_mode()
def __call__(
self,
layer0_code: torch.Tensor,
layer0_embed: torch.Tensor,
last_talker_hidden: torch.Tensor,
inv_temperature: float,
top_k: int,
sample_uniforms: torch.Tensor,
) -> torch.Tensor:
B = int(layer0_code.shape[0])
if B > self.max_batch:
raise ValueError("fused code predictor batch exceeds its capacity")
dev, dt = layer0_embed.device, self.norm_w.dtype
inp = torch.stack([last_talker_hidden.reshape(B, -1), layer0_embed.reshape(B, -1)], 1).to(dt)
inp = inp.reshape(2 * B, -1)
x = torch.addmm(self.proj_b, inp, self.proj_wt) if self.proj_wt is not None else inp.clone()
codes = torch.empty(B, self.groups, device=dev, dtype=torch.int64)
codes[:, 0] = layer0_code.reshape(B)
u = sample_uniforms
nq, first = 2, 0
for step in range(1, self.groups):
for li in range(len(self.layers)):
self._layer(x, li, B, nq, first)
last = x[nq - 1 :: nq] if nq > 1 else x
hf = torch.empty(B, self.hidden, device=dev, dtype=dt)
_rms_rows_kernel[(B,)](last, last.stride(0), self.norm_w, hf, self.eps, N=self.hidden)
logits = torch.mm(hf, self.lm_heads[step - 1])
has_next = step < self.groups - 1
nxt = torch.empty(B, self.hidden, device=dev, dtype=dt) if has_next else self._dummy
us = u[:, step - 1]
_cp_sample_kernel[(B,)](
logits, us, us.stride(0), codes, step, self.groups,
self.tables[step - 1] if has_next else self._dummy, nxt, inv_temperature,
V=self.vocab, TOPK=top_k, HID=self.hidden, HAS_NEXT=has_next, num_warps=4,
) # fmt: skip
x = nxt
first = step + 1
nq = 1
return codes
@@ -72,3 +72,33 @@ QWEN3_TTS_PIPELINE = PipelineConfig(
),
),
)
# Single-stage variant: the Talker decodes each frame with the stateful
# streaming codec decoder and emits PCM as the final output (enable with the
# ``talker_stream_decode`` model option). No Code2Wav stage, no connector.
QWEN3_TTS_FUSED_PIPELINE = PipelineConfig(
model_type="qwen3_tts_fused",
default_deploy_config_name="qwen3_tts_fused_single_gpu.yaml",
single_stage_async_chunk=True,
model_arch="Qwen3TTSTalkerForConditionalGeneration",
stages=(
StagePipelineConfig(
stage_id=0,
model_stage="qwen3_tts",
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
final_output=True,
final_output_type="audio",
# The API output processor tags ``model_outputs`` by this modality.
engine_output_type="audio",
supports_running_prefix_cache_reset=False,
supports_native_mrv2_data_plane=True,
sampling_constraints={
"detokenize": False,
"stop_token_ids": [2150],
},
),
),
)
@@ -42,6 +42,7 @@ from vllm.logger import init_logger
from vllm.multimodal.audio import AudioResampler
from vllm_omni.utils.audio import mel_filter_bank
from vllm_omni.utils.device_copy import index_to_device, to_device_nonblocking
if TYPE_CHECKING:
from .configuration_qwen3_tts import Qwen3TTSConfig, Qwen3TTSTalkerConfig
@@ -160,7 +161,7 @@ def coerce_token_ids(value: object, *, device: torch.device) -> torch.Tensor | N
ids = ids.unsqueeze(0)
if ids.ndim != 2 or ids.numel() == 0:
return None
return ids.to(device=device, dtype=torch.long).contiguous()
return to_device_nonblocking(ids.to(dtype=torch.long).contiguous(), device)
# ---------------------------------------------------------------------------
@@ -366,6 +367,9 @@ class Qwen3TTSPromptEmbedsBuilder:
# Reusing them avoids launching the embedding/projection pair once per
# request during prompt construction.
self._projected_token_cache: dict[tuple[str, tuple[int, ...]], torch.Tensor] = {}
# CustomVoice prompt pieces that do not depend on the text, per
# (device, speaker, language): bounded by the model's voices.
self._custom_voice_prompt_cache: dict[tuple, tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = {}
self._ref_audio_artifact_cache_max_entries = int(ref_audio_artifact_cache_max_entries)
self._ref_audio_artifact_cache: OrderedDict[str, dict[str, torch.Tensor | bool]] = OrderedDict()
@@ -1024,7 +1028,9 @@ class Qwen3TTSPromptEmbedsBuilder:
dev = self._device()
input_ids = coerce_token_ids(info_dict.pop(PRECOMPUTED_TEXT_IDS_KEY, None), device=dev)
if input_ids is None:
input_ids = tok(build_assistant_text(text), return_tensors="pt", padding=False)["input_ids"].to(device=dev)
input_ids = to_device_nonblocking(
tok(build_assistant_text(text), return_tensors="pt", padding=False)["input_ids"], dev
)
# Optional instruct prefix.
instruct = (info_dict.get("instruct") or [""])[0]
@@ -1411,35 +1417,44 @@ class Qwen3TTSPromptEmbedsBuilder:
raise ValueError(f"Unsupported speaker: {speaker}")
spk_id = spk_id_map[speaker]
# Keep it at least 1D; embedding on a 0-d tensor can return 1D.
spk_tensor = torch.tensor([spk_id], device=input_ids.device, dtype=torch.long)
spk_tensor = index_to_device([spk_id], input_ids.device)
spk_embed = codec_embed(spk_tensor)
if spk_embed.ndim in (1, 2):
spk_embed = spk_embed.view(1, 1, -1)
speaker_embed = spk_embed
codec_input = torch.cat([codec_input_0, speaker_embed, codec_input_1], dim=1)
role_embed = text_projection(text_embedding(input_ids[:, :3]))
codec_prefix = torch.cat((tts_pad_embed.expand(-1, codec_input.shape[1] - 2, -1), tts_bos_embed), dim=1)
codec_prefix = codec_prefix + codec_input[:, :-1]
talker_prompt = torch.cat((role_embed, codec_prefix), dim=1)
# The role tokens, speaker/language codec prefix, codec pad row and
# closing row do not depend on the text: cache them per speaker and
# language so a request only embeds and projects its own text.
# A text starting with whitespace could merge with the template's
# newline token, so it keeps the per-request role embedding.
cache_key = None
if non_streaming_mode and instruct_embed is None and not text[:1].isspace():
cache_key = (
str(input_ids.device),
int(spk_id),
codec_prefill_list[0][2] if len(codec_prefill_list[0]) == 4 else None,
)
cv_cache = self._custom_voice_prompt_cache
cached = cv_cache.get(cache_key) if cache_key is not None else None
if cached is None:
role_embed = text_projection(text_embedding(input_ids[:, :3]))
codec_prefix = torch.cat((tts_pad_embed.expand(-1, codec_input.shape[1] - 2, -1), tts_bos_embed), dim=1)
codec_prefix = codec_prefix + codec_input[:, :-1]
prefix = torch.cat((role_embed, codec_prefix), dim=1)
pad_row = codec_embed(self._long_tensor([talker_config.codec_pad_id], input_ids.device)).view(1, 1, -1)
tail = tts_pad_embed + codec_embed(self._long_tensor([talker_config.codec_bos_id], input_ids.device))
if cache_key is not None:
cv_cache[cache_key] = (prefix, pad_row, tail)
else:
prefix, pad_row, tail = cached
talker_prompt = prefix
if non_streaming_mode:
text_all = text_projection(text_embedding(input_ids[:, 3:-5]))
text_all = torch.cat([text_all, tts_eos_embed], dim=1)
pad_ids = torch.full(
(1, int(text_all.shape[1])),
int(talker_config.codec_pad_id),
device=input_ids.device,
dtype=torch.long,
)
talker_prompt = torch.cat(
[
talker_prompt,
text_all + codec_embed(pad_ids),
tts_pad_embed + codec_embed(self._long_tensor([talker_config.codec_bos_id], input_ids.device)),
],
dim=1,
)
talker_prompt = torch.cat([talker_prompt, text_all + pad_row, tail], dim=1)
trailing_text_hidden = tts_pad_embed
else:
first_text = text_projection(text_embedding(input_ids[:, 3:4])) + codec_input[:, -1:]
@@ -65,6 +65,8 @@ class Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM(CodePredictorWrapp
self._kv_requested = self._parse_bool_config(extra.get("code_predictor_kv_cache"))
self._fused_sampling = self._parse_bool_config(extra.get("code_predictor_fused_sampling"))
self._frame_cache: FrameLocalKVCache | None = None
self._fused_requested = self._parse_bool_config(extra.get("code_predictor_fused"))
self._fused = None
def _setup_compile(self) -> None:
if self._compiled_model_fwd is not None:
@@ -100,11 +102,73 @@ class Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM(CodePredictorWrapp
cache(self._proj_buf, batch, step)
self._synchronize_warmup(weight.device)
self._frame_cache = cache
if self._fused_requested:
from .fused_code_predictor import FusedCodePredictor
self._fused = FusedCodePredictor(self, max_batch)
# Compile every kernel variant outside any graph capture.
hidden = int(self.talker_config.hidden_size)
for batch in range(1, min(2, max_batch) + 1):
zeros = torch.zeros(batch, 1, hidden, device=weight.device, dtype=weight.dtype)
uniforms = torch.full(
(batch, self._num_groups - 1, int(self.config.vocab_size)), 0.5, device=weight.device
)
codes = torch.zeros(batch, 1, device=weight.device, dtype=torch.long)
self._fused(codes, zeros, zeros, 1.0, 50, uniforms)
self._synchronize_warmup(weight.device)
logger.info("Qwen3-TTS fused code predictor enabled (capacity %d)", max_batch)
# Preserve the shared wrapper's initialization sentinel. Its full
# re-prefill callable is unused while _frame_cache is active.
self._compiled_model_fwd = self.model.forward
logger.info("Qwen3-TTS frame-local KV warmed for batches %s", self._bucket_sizes)
@torch.inference_mode()
def forward(
self,
layer0_code: torch.Tensor,
layer0_embed: torch.Tensor,
last_talker_hidden: torch.Tensor,
do_sample: bool = True,
temperature: float = 0.9,
top_k: int = 50,
top_p: float = 1.0,
generator: torch.Generator | None = None,
generators: Sequence[torch.Generator | None] | None = None,
sample_uniforms: torch.Tensor | None = None,
):
self._validate_sampling_inputs(int(layer0_code.shape[0]), generators, sample_uniforms)
if self._fused_requested:
self._setup_compile()
if (
self._fused is not None
and do_sample
and temperature > 0
and top_p == 1.0
and sample_uniforms is not None
and sample_uniforms.dtype == torch.float32
and sample_uniforms.is_contiguous()
):
return self._fused(
layer0_code,
layer0_embed,
last_talker_hidden,
1.0 / temperature,
int(top_k),
sample_uniforms,
)
return super().forward(
layer0_code,
layer0_embed,
last_talker_hidden,
do_sample=do_sample,
temperature=temperature,
top_k=top_k,
top_p=top_p,
generator=generator,
generators=generators,
sample_uniforms=sample_uniforms,
)
def _predict_step_logits(
self,
proj_buf: torch.Tensor,
@@ -27,6 +27,7 @@ from vllm.sequence import IntermediateTensors
from vllm_omni.data_entry_keys import OmniPayload
from vllm_omni.model_executor.models.output_templates import OmniOutput, OwnedBatchTensor
from vllm_omni.utils.device_copy import index_to_device, to_device_nonblocking
from vllm_omni.utils.speaker_cache import (
get_speaker_cache,
iter_custom_voice_profiles,
@@ -39,6 +40,7 @@ from .configuration_qwen3_tts import Qwen3TTSConfig, Qwen3TTSSpeakerEncoderConfi
from .first_audio import talker_first_audio_enabled
from .prompt_embeds_builder import PRECOMPUTED_TEXT_IDS_KEY, Qwen3TTSPromptEmbedsBuilder, resolve_x_vector_only
from .qwen3_tts_code_predictor_vllm import Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM
from .stream_decode import stream_ref_context_frames, talker_stream_decode_enabled
from .tokenizer_12hz.configuration_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Config
from .tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import Qwen3TTSTokenizerV2Encoder
@@ -411,7 +413,21 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# A frame's residual codebooks depend only on the Talker hidden and
# CB0 of the step that sampled it, so MRV2 may complete the frame at
# the end of that step instead of in the next step's preprocess.
self.mtp_eager_frames = talker_first_audio_enabled(vllm_config)
self.stream_decode = talker_stream_decode_enabled(vllm_config)
predictor = Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM
extra = predictor._stage_connector_extra_config(vllm_config)
self.stream_first_audio = self.stream_decode and predictor._parse_bool_config(
extra.get("talker_stream_first_audio")
)
# Model-local voice-clone priming boundary; each deployment selects
# its reference context independently of the two-stage codec profile.
self.stream_ref_context_frames = stream_ref_context_frames(vllm_config) if self.stream_decode else 0
self.mtp_eager_frames = talker_first_audio_enabled(vllm_config) or self.stream_decode
self.stream_decoder = None
self.stream_graphs = None
self.stream_prime_graphs = None
self.stream_sample_rate = 0
self.stream_chunk_frames = 25
# The runners bypass only the outer whole-MTP graph when explicit
# generators are present, so seeded requests can still share one raw
# batched MTP call with independent per-row streams.
@@ -718,6 +734,11 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
# -------------------- Omni multimodal output plumbing --------------------
@property
def mm_outputs_fresh_per_step(self) -> bool:
"""Stream-decode outputs come from :meth:`_make_eager_omni_output`, allocated per step."""
return self.stream_decoder is not None and self.eager_frames_active
def make_omni_output(self, model_outputs: torch.Tensor | OmniOutput, **kwargs: Any) -> OmniOutput:
if isinstance(model_outputs, OmniOutput):
return model_outputs
@@ -895,6 +916,13 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
"first_audio": torch.zeros((num_tokens,), dtype=torch.int8, device=hidden.device),
},
}
if self.stream_decoder is not None:
# Filled per sampled row by the runner's eager MTP; token-major so
# each request's slice is its frames of this step.
spf = int(self.stream_decoder.spf)
mm["model_outputs"] = torch.zeros((num_tokens, spf), dtype=torch.float32, device=hidden.device)
sr = torch.tensor(self.stream_sample_rate, dtype=torch.int32)
mm["sr"] = [sr] * len(info_dicts)
ref_rows = [
index
for index, info in enumerate(info_dicts)
@@ -1442,8 +1470,72 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
self.first_frame_decoder = Qwen3TTSFirstFrameDecoder(self.model_path)
decoder_loaded = self.first_frame_decoder.load(self.vllm_config)
loaded = set(loaded) | {f"first_frame_decoder.{name}" for name in decoder_loaded}
elif self.stream_decode:
# The in-stage decoder owns every frame. Optional first-audio
# delivery uses its PCM; later chunks use regular step outputs.
from .first_frame_decoder import Qwen3TTSFirstFrameDecoder
from .tokenizer_12hz.streaming_decoder import StreamingCodecDecoder
holder = Qwen3TTSFirstFrameDecoder(self.model_path)
decoder_loaded = holder.load(self.vllm_config)
loaded = set(loaded) | {f"stream_decoder.{name}" for name in decoder_loaded}
slots = int(self.vllm_config.scheduler_config.max_num_seqs)
self.stream_decoder = StreamingCodecDecoder(holder.decoder, num_slots=slots, dtype=torch.bfloat16)
self.stream_sample_rate = int(holder.sample_rate)
logger.info("Qwen3-TTS Talker stream decode enabled (%d slots)", slots)
return loaded
def capture_stream_decode_graphs(self, batch_sizes: list[int]) -> None:
if self.stream_decoder is None or self.stream_graphs is not None:
return
from .tokenizer_12hz.streaming_decoder import StreamingDecodeGraphs
with torch.inference_mode():
self.stream_graphs = StreamingDecodeGraphs(self.stream_decoder, batch_sizes)
frames = min(self.stream_ref_context_frames, self.stream_chunk_frames, self.stream_decoder.max_frames)
if self.config.tts_model_type == "base" and frames > 1:
# Bound the multi-frame graph workspace by the configured
# token budget; larger priming groups keep the eager path.
budget = max(1, self.vllm_config.scheduler_config.max_num_batched_tokens // frames)
prime_sizes = sorted({1, *(size for size in batch_sizes if size <= budget)})
self.stream_prime_graphs = StreamingDecodeGraphs(self.stream_decoder, prime_sizes, frames=frames)
logger.info("Captured Talker stream decode graphs for batch sizes %s", self.stream_graphs.sizes)
if self.stream_prime_graphs is not None:
logger.info(
"Captured Talker reference priming graphs for %d frames and batch sizes %s",
self.stream_prime_graphs.frames,
self.stream_prime_graphs.sizes,
)
def get_stream_ref_context(self, info: OmniPayload) -> torch.Tensor | None:
"""Model-owned reference-code layout and context boundary for a PCM slot."""
codes = info.get("codes")
ref = codes.get("ref") if isinstance(codes, dict) else None
if not isinstance(ref, torch.Tensor) or not ref.numel():
return None
return ref.reshape(-1, int(self.talker_config.num_code_groups))[-self.stream_ref_context_frames :]
def prime_stream_decoder(self, primes: list[tuple[int, torch.Tensor]]) -> None:
"""Prime equal-length reference groups without padding or aliasing live slots."""
if not primes:
return
stream = self.stream_decoder
if stream is None:
raise RuntimeError("Reference priming requires the single-stage PCM decoder")
groups: dict[int, list[tuple[int, torch.Tensor]]] = {}
for req_idx, ref in primes:
groups.setdefault(int(ref.shape[0]), []).append((req_idx, ref))
for items in groups.values():
codes = to_device_nonblocking(torch.stack([ref for _idx, ref in items]), stream.device).to(torch.int32)
n = len(items)
slots = index_to_device([idx for idx, _ref in items], stream.device, dtype=torch.int32)
for t0 in range(0, int(codes.shape[1]), self.stream_chunk_frames):
pos = index_to_device([t0] * n, stream.device, dtype=torch.int32)
chunk = codes[:, t0 : t0 + self.stream_chunk_frames].contiguous()
graphs = self.stream_prime_graphs
decode = graphs if graphs is not None and chunk.shape[1] == graphs.frames else stream
decode(chunk, slots, pos)
def _build_stacked_codec_embed(self) -> None:
embeds = self.code_predictor.get_input_embeddings()
if not embeds:
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Eligibility and model options for the single-stage CUDA PCM pipeline."""
import torch
from vllm.config import VllmConfig
from vllm_omni.platforms import current_omni_platform
def talker_stream_decode_enabled(vllm_config: VllmConfig) -> bool:
"""The Talker decodes every frame itself and emits PCM as its final output."""
from .qwen3_tts_code_predictor_vllm import Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM as Predictor
extra = Predictor._stage_connector_extra_config(vllm_config)
model = vllm_config.model_config
parallel = vllm_config.parallel_config
requested = Predictor._parse_bool_config(extra.get("talker_stream_decode"))
if not requested:
if getattr(model, "engine_output_type", None) == "audio":
raise ValueError("The single-stage Qwen3-TTS pipeline requires talker_stream_decode=True")
if Predictor._parse_bool_config(extra.get("talker_stream_first_audio")):
raise ValueError("talker_stream_first_audio requires the single-stage talker_stream_decode path")
return False
if getattr(model, "engine_output_type", None) != "audio" or not getattr(model, "final_output", False):
raise ValueError(
"talker_stream_decode requires a final audio-output Talker; "
"select qwen3_tts_fused_single_gpu.yaml instead of enabling it on the two-stage pipeline"
)
if getattr(model, "supports_running_prefix_cache_reset", True):
raise ValueError(
"The single-stage PCM pipeline must disable running prefix-cache reset; "
"select qwen3_tts_fused_single_gpu.yaml"
)
if not (
current_omni_platform.is_cuda()
and torch.device(vllm_config.device_config.device).type == "cuda"
and bool(getattr(model, "use_v2_model_runner", False))
and bool(getattr(model, "async_chunk", False))
and parallel.tensor_parallel_size == 1
and parallel.pipeline_parallel_size == 1
and parallel.distributed_executor_backend in (None, "uni")
and not vllm_config.cache_config.enable_prefix_caching
):
raise ValueError(
"talker_stream_decode requires CUDA, MRv2, async_chunk=True, TP=PP=1, "
"an in-process worker and enable_prefix_caching=False; "
"use qwen3_tts_fused_single_gpu.yaml"
)
if Predictor._parse_bool_config(extra.get("talker_first_audio")):
raise ValueError("talker_stream_decode and talker_first_audio are mutually exclusive")
return True
def stream_ref_context_frames(vllm_config: VllmConfig) -> int:
"""Reference-code context frames for voice-clone priming in the Talker."""
from .qwen3_tts_code_predictor_vllm import Qwen3TTSTalkerCodePredictorForConditionalGenerationVLLM as Predictor
extra = Predictor._stage_connector_extra_config(vllm_config)
return int(extra.get("ref_code_context_frames") or extra.get("codec_left_context_frames", 25))
@@ -0,0 +1,799 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# ruff: noqa: N803 - Triton constexpr parameters use kernel-style capitals.
"""Stateful, fused streaming decoder for the Qwen3-TTS 12 Hz codec.
Every layer of the codec decoder is causal, so what a new frame needs from the
past is small and fixed: each causal conv's last ``(k - 1) * dilation`` input
rows, each overlapping transposed conv's last GEMM row, and each attention
layer's last ``sliding_window`` keys and values. A request owns a slot of
per-layer state holding exactly that, and a call decodes ``T`` new frames for
each of ``B`` requests, reading and advancing the state. The output equals the
whole-utterance decode (``Qwen3TTSTokenizerV2Decoder._forward_exact``) frame by
frame, up to floating point rounding: nothing is recomputed and nothing is
truncated.
Layout and fusion:
- Activations are time-major ``[rows, C]``; every dense conv is a tap-major
im2col (one Triton kernel that also applies the pending bias and SnakeBeta,
and reads/writes the history) followed by one cuBLAS GEMM.
- Linear chains fold at load: the RVQ output projections, ``pre_conv`` and the
transformer's ``input_proj`` become one ``k = 3`` conv over the concatenated
codebook embeddings; LayerScale folds into ``o_proj``/``down_proj``; ConvNeXt
``gamma`` folds into ``pwconv2``.
- A bias that feeds a residual stream is carried to that stream's consumer
(the next im2col or transposed-conv GEMM) instead of being added in place.
- Residual branches accumulate into their stream with in-place ``addmm_``.
History buffers are double-buffered per slot: a call reads half ``parity[slot]``
and writes the other half, then flips the parity, so no kernel overwrites rows
another program of the same launch still reads. A row whose first frame index
``pos`` is 0 reads zeros, which are the convs' causal padding, and attention
only looks back ``min(pos + 1, window)`` positions, so a new request needs no
state reset.
"""
from __future__ import annotations
from dataclasses import dataclass
import torch
from torch import nn
from vllm.triton_utils import tl, triton
from vllm_omni.platforms import current_omni_platform
_KERNEL = 7
# --------------------------------------------------------------------------- kernels
@triton.jit
def _rvq_gather_kernel(codes_ptr, books_ptr, out_ptr, NQ: tl.constexpr, CB: tl.constexpr, HALF: tl.constexpr):
row = tl.program_id(0)
offs = tl.arange(0, HALF)
c0 = tl.load(codes_ptr + row * NQ).to(tl.int64)
c0 = tl.where((c0 >= 0) & (c0 < CB), c0, 0) # EOS/special rows decode as code 0; callers drop them
first = tl.load(books_ptr + c0 * HALF + offs).to(tl.float32)
acc = tl.zeros([HALF], dtype=tl.float32)
for q in range(1, NQ):
c = tl.load(codes_ptr + row * NQ + q).to(tl.int64)
c = tl.where((c >= 0) & (c < CB), c, 0)
acc += tl.load(books_ptr + (q * CB + c) * HALF + offs).to(tl.float32)
dt = out_ptr.dtype.element_ty
tl.store(out_ptr + row * 2 * HALF + offs, first.to(dt))
tl.store(out_ptr + row * 2 * HALF + HALF + offs, acc.to(dt))
@triton.jit
def _fast_sin(y):
# Two-step reduction to [-pi, pi], then the hardware approximation
# (absolute error ~4e-7 there): accurate sin's instruction count, not
# memory, bounds every kernel that applies SnakeBeta.
k = tl.extra.cuda.libdevice.rint(y * 0.15915494309189535)
r = tl.fma(-k, -1.7484555314695172e-07, tl.fma(-k, 6.2831854820251465, y))
return tl.inline_asm_elementwise("sin.approx.f32 $0, $1;", "=r,r", [r], dtype=tl.float32, is_pure=True, pack=1)
@triton.jit
def _snake(v, a, ib):
s = _fast_sin(v * a)
return v + ib * s * s
@triton.jit
def _im2col_kernel(
x_ptr, # [B * T, C] layer input rows
bias_ptr, # [C] pending bias (added to x rows only) or dummy
alpha_ptr, # [C] exp(alpha) or dummy
ibeta_ptr, # [C] 1 / (exp(beta) + eps) or dummy
hist_ptr, # [2, S, H, C] transformed history rows
slots_ptr,
pos_ptr,
par_ptr,
col_ptr, # [B * T, K * C]
T,
S,
C: tl.constexpr,
K: tl.constexpr,
D: tl.constexpr,
H: tl.constexpr,
HAS_BIAS: tl.constexpr,
HAS_SNAKE: tl.constexpr,
BU: tl.constexpr,
BC: tl.constexpr,
EXT: tl.constexpr = False,
):
"""Source row ``u`` of ``[history (H) | x (T)]``: scatter to every tap that reads it, save the last H."""
b = tl.program_id(0)
u = tl.program_id(1) * BU + tl.arange(0, BU)
c = tl.program_id(2) * BC + tl.arange(0, BC)
cm = c < C
n_src = H + T
um = u < n_src
slot = tl.load(slots_ptr + b).to(tl.int64)
live = tl.load(pos_ptr + b) != 0
par = tl.load(par_ptr + slot).to(tl.int64)
# history rows
from_hist = u < H
hrow = tl.where(from_hist, u, 0)
hv = tl.load(
hist_ptr + ((par * S + slot) * H + hrow)[:, None] * C + c[None, :],
mask=(from_hist & um & live)[:, None] & cm[None, :],
other=0.0,
).to(tl.float32)
xrow = tl.where(from_hist, 0, u - H)
xv = tl.load(
x_ptr + (b * T + xrow).to(tl.int64)[:, None] * C + c[None, :],
mask=((~from_hist) & um)[:, None] & cm[None, :],
other=0.0,
).to(tl.float32)
if HAS_BIAS:
xv += tl.load(bias_ptr + c, mask=cm, other=0.0).to(tl.float32)[None, :]
if HAS_SNAKE:
a = tl.load(alpha_ptr + c, mask=cm, other=0.0).to(tl.float32)[None, :]
ib = tl.load(ibeta_ptr + c, mask=cm, other=0.0).to(tl.float32)[None, :]
xv = _snake(xv, a, ib)
dt = col_ptr.dtype.element_ty
v = tl.where(from_hist[:, None], hv, xv.to(dt).to(tl.float32)).to(dt)
if EXT:
tl.store(col_ptr + (b * n_src + u).to(tl.int64)[:, None] * C + c[None, :], v, mask=um[:, None] & cm[None, :])
else:
for j in tl.static_range(K):
t = u - j * D
tm = (t >= 0) & (t < T) & um
tl.store(
col_ptr + (b * T + tl.where(tm, t, 0)).to(tl.int64)[:, None] * (K * C) + j * C + c[None, :],
v,
mask=tm[:, None] & cm[None, :],
)
if H > 0:
hm = (u >= T) & um
tl.store(
hist_ptr + (((1 - par) * S + slot) * H + tl.where(hm, u - T, 0))[:, None] * C + c[None, :],
v,
mask=hm[:, None] & cm[None, :],
)
@triton.jit
def _rms_norm_kernel(x_ptr, w_ptr, out_ptr, eps, N: tl.constexpr):
row = tl.program_id(0).to(tl.int64)
offs = tl.arange(0, N)
x = tl.load(x_ptr + row * N + offs).to(tl.float32)
var = tl.sum(x * x, axis=0) / N
dt = out_ptr.dtype.element_ty
y = (x * tl.rsqrt(var + eps)).to(dt).to(tl.float32)
w = tl.load(w_ptr + offs).to(tl.float32)
tl.store(out_ptr + row * N + offs, (w * y).to(dt))
@triton.jit
def _rope_kv_write_kernel(
qkv_ptr, # [B * T, 3 * NH * HD]
q_ptr, # [B * T, NH * HD]
k_ring_ptr, # [S, RING, NH * HD]
v_ring_ptr,
slots_ptr,
pos_ptr,
T,
theta,
NH: tl.constexpr,
HD: tl.constexpr,
RING: tl.constexpr,
):
r = tl.program_id(0)
h = tl.program_id(1)
b = r // T
p = tl.load(pos_ptr + b) + r % T
slot = tl.load(slots_ptr + b).to(tl.int64)
half: tl.constexpr = HD // 2
i = tl.arange(0, half)
inv_freq = tl.exp(-(2.0 * i.to(tl.float32) / HD) * tl.log(theta))
ang = p.to(tl.float32) * inv_freq
dt = q_ptr.dtype.element_ty
cos = tl.cos(ang).to(dt).to(tl.float32)
sin = tl.sin(ang).to(dt).to(tl.float32)
W: tl.constexpr = NH * HD
base = qkv_ptr + r.to(tl.int64) * 3 * W + h * HD
q1 = tl.load(base + i).to(tl.float32)
q2 = tl.load(base + half + i).to(tl.float32)
k1 = tl.load(base + W + i).to(tl.float32)
k2 = tl.load(base + W + half + i).to(tl.float32)
vv = tl.arange(0, HD)
v = tl.load(base + 2 * W + vv)
qo = q_ptr + r.to(tl.int64) * W + h * HD
tl.store(qo + i, (q1 * cos - q2 * sin).to(dt))
tl.store(qo + half + i, (q2 * cos + q1 * sin).to(dt))
ring = (slot * RING + p % RING) * W + h * HD
tl.store(k_ring_ptr + ring + i, (k1 * cos - k2 * sin).to(dt))
tl.store(k_ring_ptr + ring + half + i, (k2 * cos + k1 * sin).to(dt))
tl.store(v_ring_ptr + ring + vv, v)
@triton.jit
def _attend_kernel(
q_ptr, # [B * T, NH * HD]
k_ring_ptr,
v_ring_ptr,
out_ptr, # [B * T, NH * HD]
slots_ptr,
pos_ptr,
T,
scale,
NH: tl.constexpr,
HD: tl.constexpr,
RING: tl.constexpr,
WINDOW: tl.constexpr,
BK: tl.constexpr,
):
r = tl.program_id(0)
h = tl.program_id(1)
b = r // T
p = tl.load(pos_ptr + b) + r % T
slot = tl.load(slots_ptr + b).to(tl.int64)
W: tl.constexpr = NH * HD
d = tl.arange(0, HD)
q = tl.load(q_ptr + r.to(tl.int64) * W + h * HD + d).to(tl.float32)
j = tl.arange(0, BK)
n = tl.minimum(p + 1, WINDOW)
km = j < n
kp = p - j # key positions p, p-1, ...
idx = (slot * RING + tl.where(km, kp, 0) % RING) * W + h * HD
k = tl.load(k_ring_ptr + idx[:, None] + d[None, :], mask=km[:, None], other=0.0).to(tl.float32)
s = tl.sum(k * q[None, :], axis=1) * scale
s = tl.where(km, s, -float("inf"))
m = tl.max(s, axis=0)
e = tl.exp(s - m)
e = tl.where(km, e, 0.0)
w = e / tl.sum(e, axis=0)
dt = out_ptr.dtype.element_ty
w = w.to(dt).to(tl.float32)
v = tl.load(v_ring_ptr + idx[:, None] + d[None, :], mask=km[:, None], other=0.0).to(tl.float32)
o = tl.sum(v * w[:, None], axis=0)
tl.store(out_ptr + r.to(tl.int64) * W + h * HD + d, o.to(dt))
@triton.jit
def _silu_mul_kernel(gu_ptr, out_ptr, N: tl.constexpr, BN: tl.constexpr):
row = tl.program_id(0).to(tl.int64)
offs = tl.program_id(1) * BN + tl.arange(0, BN)
m = offs < N
g = tl.load(gu_ptr + row * 2 * N + offs, mask=m).to(tl.float32)
u = tl.load(gu_ptr + row * 2 * N + N + offs, mask=m).to(tl.float32)
dt = out_ptr.dtype.element_ty
sg = (g / (1.0 + tl.exp(-g))).to(dt).to(tl.float32)
tl.store(out_ptr + row * N + offs, (sg * u).to(dt), mask=m)
@triton.jit
def _dwconv_ln_kernel(
z_ptr, # [B * T, C] ConvNeXt input rows (true values)
w_ptr, # [K, C]
b_ptr, # [C]
lnw_ptr,
lnb_ptr,
hist_ptr, # [2, S, K - 1, C]
slots_ptr,
pos_ptr,
par_ptr,
out_ptr, # [B * T, C] LayerNorm output
T,
S,
eps,
C: tl.constexpr,
K: tl.constexpr,
):
b = tl.program_id(0)
t = tl.program_id(1) # 0 .. max(T, K - 1)
H: tl.constexpr = K - 1
c = tl.arange(0, C)
slot = tl.load(slots_ptr + b).to(tl.int64)
live = tl.load(pos_ptr + b) != 0
par = tl.load(par_ptr + slot).to(tl.int64)
dt = out_ptr.dtype.element_ty
hbase = hist_ptr + (par * S + slot) * H * C
acc = tl.load(b_ptr + c).to(tl.float32)
for j in tl.static_range(K):
u = t + j # index into [hist (H) | z (T)]
fh = u < H
hv = tl.load(hbase + tl.where(fh, u, 0) * C + c, mask=(c < C) & fh & live, other=0.0).to(tl.float32)
zrow = (b * T + tl.where(fh, 0, u - H)).to(tl.int64)
zv = tl.load(z_ptr + zrow * C + c, mask=(c < C) & (~fh) & (t < T), other=0.0).to(tl.float32)
acc += tl.where(fh, hv, zv) * tl.load(w_ptr + j * C + c).to(tl.float32)
h = acc.to(dt).to(tl.float32)
mean = tl.sum(h, axis=0) / C
hc = h - mean
var = tl.sum(hc * hc, axis=0) / C
y = hc * tl.rsqrt(var + eps) * tl.load(lnw_ptr + c).to(tl.float32) + tl.load(lnb_ptr + c).to(tl.float32)
tl.store(out_ptr + (b * T + t).to(tl.int64) * C + c, y.to(dt), mask=(c < C) & (t < T))
# new history row t: source row T + t of [hist | z]
u = T + t
fh = u < H
hv = tl.load(hbase + tl.where(fh, u, 0) * C + c, mask=(c < C) & fh & live & (t < H), other=0.0)
zrow = (b * T + tl.where(fh, 0, u - H)).to(tl.int64)
zv = tl.load(z_ptr + zrow * C + c, mask=(c < C) & (~fh) & (t < H), other=0.0)
tl.store(
hist_ptr + (((1 - par) * S + slot) * H + tl.where(t < H, t, 0)) * C + c,
tl.where(fh, hv, zv).to(dt),
mask=(c < C) & (t < H),
)
@triton.jit
def _bias_gelu_kernel(x_ptr, b_ptr, N: tl.constexpr, BN: tl.constexpr):
row = tl.program_id(0).to(tl.int64)
offs = tl.program_id(1) * BN + tl.arange(0, BN)
m = offs < N
x = tl.load(x_ptr + row * N + offs, mask=m).to(tl.float32) + tl.load(b_ptr + offs, mask=m).to(tl.float32)
dt = x_ptr.dtype.element_ty
x = x.to(dt).to(tl.float32)
y = 0.5 * x * (1.0 + tl.erf(x * 0.7071067811865476))
tl.store(x_ptr + row * N + offs, y.to(dt), mask=m)
@triton.jit
def _col2im_kernel(
z_ptr, # [B * T, 2 * R, C] transposed-conv GEMM rows
bias_ptr, # [C]
prev_ptr, # [2, S, R, C] previous call's last GEMM row, second half
slots_ptr,
pos_ptr,
par_ptr,
out_ptr, # [B * T * R, C]
T,
S,
R: tl.constexpr,
C: tl.constexpr,
BC: tl.constexpr,
):
row = tl.program_id(0) # b * T + t
j = tl.program_id(1) # 0 .. R - 1
c = tl.program_id(2) * BC + tl.arange(0, BC)
cm = c < C
b = row // T
t = row % T
slot = tl.load(slots_ptr + b).to(tl.int64)
live = tl.load(pos_ptr + b) != 0
par = tl.load(par_ptr + slot).to(tl.int64)
zr = z_ptr + row.to(tl.int64) * 2 * R * C
cur = tl.load(zr + j * C + c, mask=cm).to(tl.float32)
prev_in = tl.load(zr - 2 * R * C + (R + j) * C + c, mask=cm & (t > 0), other=0.0).to(tl.float32)
prev_st = tl.load(prev_ptr + ((par * S + slot) * R + j) * C + c, mask=cm & (t == 0) & live, other=0.0).to(
tl.float32
)
y = cur + tl.where(t > 0, prev_in, prev_st) + tl.load(bias_ptr + c, mask=cm).to(tl.float32)
dt = out_ptr.dtype.element_ty
tl.store(out_ptr + (row.to(tl.int64) * R + j) * C + c, y.to(dt), mask=cm)
last = tl.load(zr + (R + j) * C + c, mask=cm & (t == T - 1))
tl.store(prev_ptr + (((1 - par) * S + slot) * R + j) * C + c, last, mask=cm & (t == T - 1))
@triton.jit
def _conv_out_kernel(
ext_ptr, # [B, H + T, C] transformed rows: history then this call's
w_ptr, # [K, C]
wb, # conv bias (float)
out_ptr, # [B, T] float32 waveform
T,
C: tl.constexpr,
K: tl.constexpr,
BT: tl.constexpr,
CP: tl.constexpr,
):
b = tl.program_id(0)
t = tl.program_id(1) * BT + tl.arange(0, BT)
c = tl.arange(0, CP)
cm = c < C
tm = t < T
base = ext_ptr + b.to(tl.int64) * (T + K - 1) * C
acc = tl.zeros([BT], dtype=tl.float32)
for j in tl.static_range(K):
v = tl.load(base + (t + j)[:, None] * C + c[None, :], mask=tm[:, None] & cm[None, :], other=0.0).to(tl.float32)
acc += tl.sum(v * tl.load(w_ptr + j * C + c, mask=cm, other=0.0).to(tl.float32)[None, :], axis=1)
dt = ext_ptr.dtype.element_ty
y = acc.to(dt).to(tl.float32) + wb
y = tl.minimum(tl.maximum(y.to(dt).to(tl.float32), -1.0), 1.0)
tl.store(out_ptr + b.to(tl.int64) * T + t, y, mask=tm)
@triton.jit
def _flip_kernel(par_ptr, slots_ptr):
slot = tl.load(slots_ptr + tl.program_id(0)).to(tl.int64)
tl.store(par_ptr + slot, 1 - tl.load(par_ptr + slot))
# --------------------------------------------------------------------------- module
@dataclass
class _ConvSpec:
weight: torch.Tensor # [K * C_in, C_out] tap-major
c_in: int
k: int
d: int
hist: torch.Tensor | None = None # [2, S, H, C_in]
def _conv_taps(w: torch.Tensor) -> torch.Tensor:
"""``[C_out, C_in, K]`` -> ``[K * C_in, C_out]``."""
c_out, c_in, k = w.shape
return w.permute(2, 1, 0).reshape(k * c_in, c_out)
def _snake_params(module) -> tuple[torch.Tensor, torch.Tensor]:
# SnakeBeta: x + 1 / (exp(beta) + 1e-9) * sin(exp(alpha) * x) ** 2
alpha = module.alpha.detach().float()
beta = module.beta.detach().float()
return torch.exp(alpha).contiguous(), (1.0 / (torch.exp(beta) + 1e-9)).contiguous()
class StreamingCodecDecoder(nn.Module):
"""Frame-exact stateful decoder built from a loaded ``Qwen3TTSTokenizerV2Decoder``."""
RING = 128 # KV ring positions; a call may carry up to RING - window + 1 frames
def __init__(self, decoder: nn.Module, num_slots: int, dtype: torch.dtype | None = None) -> None:
super().__init__()
cfg = decoder.config
dev = next(decoder.parameters()).device
dtype = dtype or next(decoder.parameters()).dtype
self.dtype, self.device = dtype, dev
self.num_slots = num_slots + 1 # last slot: scratch for padding rows
self.scratch_slot = num_slots
S = self.num_slots
self.nq = int(cfg.num_quantizers)
self.cb = int(cfg.codebook_size)
self.half = int(cfg.codebook_dim) // 2
self.hidden = int(cfg.hidden_size)
self.heads = int(cfg.num_attention_heads)
self.head_dim = int(cfg.head_dim)
self.window = int(cfg.sliding_window)
self.theta = float(cfg.rope_theta)
self.eps = float(cfg.rms_norm_eps)
self.max_frames = self.RING - self.window + 1
self.spf = int(decoder.total_upsample)
if self.heads != int(cfg.num_key_value_heads):
raise ValueError("streaming codec decoder assumes no grouped KV")
f32 = lambda t: t.detach().to(device=dev, dtype=torch.float32) # noqa: E731
cast = lambda t: t.to(dtype).contiguous() # noqa: E731
def hist(h: int, c: int) -> torch.Tensor:
return torch.zeros(2, S, h, c, device=dev, dtype=dtype)
# RVQ books, pre-divided by usage: [NQ * CB, HALF]
q = decoder.quantizer
books = []
for vq in [q.rvq_first.vq.layers[0]] + list(q.rvq_rest.vq.layers):
cbk = vq._codebook
books.append(f32(cbk.embedding_sum) / f32(cbk.cluster_usage).clamp(min=cbk.epsilon)[:, None])
self.books = cast(torch.cat(books))
w_rvq = torch.cat(
[f32(q.rvq_first.output_proj.weight)[:, :, 0], f32(q.rvq_rest.output_proj.weight)[:, :, 0]], 1
)
# pre_conv (k=3) and input_proj folded onto the embedding concat
pre_w, pre_b = f32(decoder.pre_conv.conv.weight), f32(decoder.pre_conv.conv.bias)
pt = decoder.pre_transformer
in_w, in_b = f32(pt.input_proj.weight), f32(pt.input_proj.bias)
taps = torch.stack([in_w @ pre_w[:, :, j] @ w_rvq for j in range(pre_w.shape[2])], dim=2) # [hid, 2H, 3]
self.pre = _ConvSpec(cast(_conv_taps(taps)), 2 * self.half, 3, 1, hist(2, 2 * self.half))
self.pre_b = cast(in_w @ pre_b + in_b)
# transformer
self.layers = []
qd = self.heads * self.head_dim
for layer in pt.layers:
a = layer.self_attn
qkv = torch.cat([f32(a.q_proj.weight), f32(a.k_proj.weight), f32(a.v_proj.weight)], 0)
o = f32(a.o_proj.weight) * f32(layer.self_attn_layer_scale.scale)[:, None]
gu = torch.cat([f32(layer.mlp.gate_proj.weight), f32(layer.mlp.up_proj.weight)], 0)
down = f32(layer.mlp.down_proj.weight) * f32(layer.mlp_layer_scale.scale)[:, None]
self.layers.append(
dict(
ln1=cast(f32(layer.input_layernorm.weight)),
ln2=cast(f32(layer.post_attention_layernorm.weight)),
qkv=cast(qkv.t()),
o=cast(o.t()),
gu=cast(gu.t()),
down=cast(down.t()),
k_ring=torch.zeros(S, self.RING, qd, device=dev, dtype=dtype),
v_ring=torch.zeros(S, self.RING, qd, device=dev, dtype=dtype),
)
)
self.norm_w = cast(f32(pt.norm.weight))
self.out_w = cast(f32(pt.output_proj.weight).t())
self.out_b = cast(f32(pt.output_proj.bias))
# upsample: transposed conv (kernel = stride, no overlap) + ConvNeXt
self.ups = []
latent = int(cfg.latent_dim)
pending = torch.zeros(latent, device=dev, dtype=torch.float32)
for trans, block in decoder.upsample:
tw = f32(trans.conv.weight) # [C_in, C_out, r]
r = tw.shape[2]
w = tw.permute(0, 2, 1).reshape(latent, r * latent) # [C_in, r * C_out]
bias = (pending @ w).view(r, latent) + f32(trans.conv.bias)[None, :]
dw = block.dwconv.conv
gamma = f32(block.gamma)
self.ups.append(
dict(
r=r,
w=cast(w),
b=cast(bias.reshape(-1)),
dw_w=cast(f32(dw.weight)[:, 0, :].t()),
dw_b=cast(f32(dw.bias)),
ln_w=cast(f32(block.norm.weight)),
ln_b=cast(f32(block.norm.bias)),
ln_eps=float(block.norm.eps),
pw1=cast(f32(block.pwconv1.weight).t()),
pw1_b=cast(f32(block.pwconv1.bias)),
pw2=cast((f32(block.pwconv2.weight) * gamma[:, None]).t()),
hist=hist(_KERNEL - 1, latent),
)
)
pending = f32(block.pwconv2.bias) * gamma
# conv_in (pending bias of the last ConvNeXt added on load)
dec = decoder.decoder
cin = dec[0].conv
self.conv_in = _ConvSpec(cast(_conv_taps(f32(cin.weight))), latent, _KERNEL, 1, hist(_KERNEL - 1, latent))
self.conv_in_pb = cast(pending)
pending = f32(cin.bias)
# decoder blocks
self.blocks = []
for i, blk in enumerate(dec[1:-2]):
snake, trans, *units = blk.block
c_in = trans.conv.in_channels
c_out = trans.conv.out_channels
rate = trans.conv.stride[0]
tw = f32(trans.conv.weight) # [C_in, C_out, 2 * rate]
entry = dict(
pb=cast(pending),
snake=_snake_params(snake),
rate=rate,
c_in=c_in,
c_out=c_out,
w=cast(tw.permute(0, 2, 1).reshape(c_in, 2 * rate * c_out)),
b=cast(f32(trans.conv.bias)),
prev=torch.zeros(2, S, rate, c_out, device=dev, dtype=dtype),
units=[],
)
pending = torch.zeros(c_out, device=dev, dtype=torch.float32)
for u in units:
c1, c2 = u.conv1.conv, u.conv2.conv
entry["units"].append(
dict(
pb=cast(pending),
act1=_snake_params(u.act1),
conv1=_ConvSpec(
cast(_conv_taps(f32(c1.weight))),
c_out,
_KERNEL,
c1.dilation[0],
hist((_KERNEL - 1) * c1.dilation[0], c_out),
),
b1=cast(f32(c1.bias)),
conv1_w4=(
cast(f32(c1.weight)).unsqueeze(2).contiguous(memory_format=torch.channels_last)
if c1.dilation[0] == 1
else None
),
act2=_snake_params(u.act2),
w2=cast(f32(c2.weight)[:, :, 0].t()),
)
)
pending = pending + f32(c2.bias)
self.blocks.append(entry)
self.out_pb = cast(pending)
self.out_snake = _snake_params(dec[-2])
co = dec[-1].conv
self.out_c = co.in_channels
self.conv_out_w = cast(f32(co.weight)[0].t()) # [K, C]
self.conv_out_b = float(f32(co.bias)[0])
self.conv_out = _ConvSpec(self.conv_out_w, self.out_c, _KERNEL, 1, hist(_KERNEL - 1, self.out_c))
self.parity = torch.zeros(S, device=dev, dtype=torch.int32)
self._dummy = torch.zeros(1, device=dev, dtype=dtype)
def _slot_state(self, slot: int) -> list[torch.Tensor]:
state = [self.parity[slot : slot + 1]]
for layer in self.layers:
state.extend((layer["k_ring"][slot], layer["v_ring"][slot]))
for spec in (self.pre, self.conv_in, self.conv_out):
assert spec.hist is not None
state.append(spec.hist[:, slot])
for up in self.ups:
state.append(up["hist"][:, slot])
for block in self.blocks:
state.append(block["prev"][:, slot])
for unit in block["units"]:
state.append(unit["conv1"].hist[:, slot])
return state
def save_slot(self, slot: int) -> list[torch.Tensor]:
"""Offload a preempted request before its runner slot is recycled."""
return [tensor.to(device="cpu", copy=True) for tensor in self._slot_state(slot)]
def restore_slot(self, slot: int, state: list[torch.Tensor]) -> None:
for target, saved in zip(self._slot_state(slot), state, strict=True):
target.copy_(saved)
# ------------------------------------------------------------------ helpers
def _im2col(self, x, spec: _ConvSpec, T, slots, pos, bias=None, snake=None, ext=False):
k = spec.k
d = spec.d
c = x.shape[1]
h = (k - 1) * d
B = slots.shape[0]
if ext:
col = torch.empty(B * (h + T), c, device=x.device, dtype=self.dtype)
else:
col = torch.empty(B * T, k * c, device=x.device, dtype=self.dtype)
bu = 32
bc = min(128, triton.next_power_of_2(c))
grid = (B, triton.cdiv(h + T, bu), triton.cdiv(c, bc))
a, ib = snake if snake is not None else (self._dummy, self._dummy)
_im2col_kernel[grid](
x, bias if bias is not None else self._dummy, a, ib,
spec.hist if h > 0 else self._dummy, slots, pos, self.parity, col,
T, self.num_slots, C=c, K=k, D=d, H=h,
HAS_BIAS=bias is not None, HAS_SNAKE=snake is not None, BU=bu, BC=bc, EXT=ext,
) # fmt: skip
return col
def _conv_cudnn(self, x, u, T, slots, pos):
"""Undilated unit conv: one source-row pass, then cuDNN on its channels-last view.
The im2col path writes a ``K``-times patch matrix; cuDNN reads the
``[history | new]`` rows directly (same result up to summation order).
"""
spec = u["conv1"]
ext = self._im2col(x, spec, T, slots, pos, bias=u["pb"], snake=u["act1"], ext=True)
b = slots.shape[0]
c = x.shape[1]
x4 = ext.view(b, -1, c).permute(0, 2, 1).unsqueeze(2) # [B, C, 1, H + T], channels-last memory
y = torch.nn.functional.conv2d(x4, u["conv1_w4"]) # [B, N, 1, T], channels-last memory
return y.permute(0, 2, 3, 1).reshape(b * T, -1)
def _snake(self, x, snake, bias):
n, c = x.shape
out = torch.empty_like(x)
bu, bc = 32, min(128, triton.next_power_of_2(c))
one = torch.zeros(1, device=x.device, dtype=torch.int32)
_im2col_kernel[(1, triton.cdiv(n, bu), triton.cdiv(c, bc))](
x, bias, snake[0], snake[1], self._dummy, one, one, self.parity, out,
n, self.num_slots, C=c, K=1, D=1, H=0, HAS_BIAS=True, HAS_SNAKE=True, BU=bu, BC=bc,
) # fmt: skip
return out
# ------------------------------------------------------------------ forward
@torch.no_grad()
def forward(self, codes: torch.Tensor, slots: torch.Tensor, pos: torch.Tensor) -> torch.Tensor:
"""``codes`` [B, T, NQ] int, ``slots``/``pos`` [B] int32 -> waveform [B, T * spf] float32.
``pos[b]`` is the index of the row's first frame in its stream; 0 starts
a new stream in ``slots[b]``. Frames beyond ``max_frames`` per call must
be split by the caller.
"""
B, T, _ = codes.shape
if T > self.max_frames:
raise ValueError(f"at most {self.max_frames} frames per call, got {T}")
dev, dt = codes.device, self.dtype
codes = codes.reshape(B * T, self.nq).to(torch.int32).contiguous()
emb = torch.empty(B * T, 2 * self.half, device=dev, dtype=dt)
_rvq_gather_kernel[(B * T,)](codes, self.books, emb, NQ=self.nq, CB=self.cb, HALF=self.half)
x = torch.addmm(self.pre_b, self._im2col(emb, self.pre, T, slots, pos), self.pre.weight)
hid, qd = self.hidden, self.heads * self.head_dim
rows = B * T
h = torch.empty(rows, hid, device=dev, dtype=dt)
q = torch.empty(rows, qd, device=dev, dtype=dt)
att = torch.empty(rows, qd, device=dev, dtype=dt)
a = torch.empty(rows, self.layers[0]["down"].shape[0], device=dev, dtype=dt)
inter = a.shape[1]
scale = self.head_dim**-0.5
for L in self.layers:
_rms_norm_kernel[(rows,)](x, L["ln1"], h, self.eps, N=hid)
qkv = torch.mm(h, L["qkv"])
_rope_kv_write_kernel[(rows, self.heads)](
qkv, q, L["k_ring"], L["v_ring"], slots, pos, T, self.theta,
NH=self.heads, HD=self.head_dim, RING=self.RING,
) # fmt: skip
_attend_kernel[(rows, self.heads)](
q, L["k_ring"], L["v_ring"], att, slots, pos, T, scale,
NH=self.heads, HD=self.head_dim, RING=self.RING, WINDOW=self.window,
BK=triton.next_power_of_2(self.window),
) # fmt: skip
x.addmm_(att, L["o"])
_rms_norm_kernel[(rows,)](x, L["ln2"], h, self.eps, N=hid)
gu = torch.mm(h, L["gu"])
_silu_mul_kernel[(rows, triton.cdiv(inter, 1024))](gu, a, N=inter, BN=1024)
x.addmm_(a, L["down"])
_rms_norm_kernel[(rows,)](x, self.norm_w, h, self.eps, N=hid)
y = torch.addmm(self.out_b, h, self.out_w) # [rows, latent]
t_rows = T
for U in self.ups:
r = U["r"]
z = torch.addmm(U["b"], y, U["w"]).view(rows * r, -1)
rows, t_rows = rows * r, t_rows * r
c = z.shape[1]
n = torch.empty_like(z)
_dwconv_ln_kernel[(B, max(t_rows, _KERNEL - 1))](
z, U["dw_w"], U["dw_b"], U["ln_w"], U["ln_b"], U["hist"], slots, pos, self.parity, n,
t_rows, self.num_slots, U["ln_eps"], C=c, K=_KERNEL,
) # fmt: skip
p1 = torch.mm(n, U["pw1"])
_bias_gelu_kernel[(rows, triton.cdiv(p1.shape[1], 1024))](p1, U["pw1_b"], N=p1.shape[1], BN=1024)
z.addmm_(p1, U["pw2"])
y = z
x = torch.mm(self._im2col(y, self.conv_in, t_rows, slots, pos, bias=self.conv_in_pb), self.conv_in.weight)
for blk in self.blocks:
s = self._snake(x, blk["snake"], blk["pb"])
zt = torch.mm(s, blk["w"]) # [rows, 2 * rate * c_out]
r, c_out = blk["rate"], blk["c_out"]
x = torch.empty(rows * r, c_out, device=dev, dtype=dt)
bc = min(128, triton.next_power_of_2(c_out))
_col2im_kernel[(rows, r, triton.cdiv(c_out, bc))](
zt, blk["b"], blk["prev"], slots, pos, self.parity, x, t_rows, self.num_slots,
R=r, C=c_out, BC=bc,
) # fmt: skip
rows, t_rows = rows * r, t_rows * r
for u in blk["units"]:
if u.get("conv1_w4") is not None:
c1 = self._conv_cudnn(x, u, t_rows, slots, pos)
else:
col = self._im2col(x, u["conv1"], t_rows, slots, pos, bias=u["pb"], snake=u["act1"])
c1 = torch.mm(col, u["conv1"].weight)
s2 = self._snake(c1, u["act2"], u["b1"])
x.addmm_(s2, u["w2"])
ext = self._im2col(x, self.conv_out, t_rows, slots, pos, bias=self.out_pb, snake=self.out_snake, ext=True)
wav = torch.empty(B, t_rows, device=dev, dtype=torch.float32)
_conv_out_kernel[(B, triton.cdiv(t_rows, 256))](
ext, self.conv_out_w, self.conv_out_b, wav, t_rows,
C=self.out_c, K=_KERNEL, BT=256, CP=triton.next_power_of_2(self.out_c),
) # fmt: skip
_flip_kernel[(B,)](self.parity, slots)
return wav
class StreamingDecodeGraphs:
"""CUDA graphs of ``StreamingCodecDecoder`` for a fixed frame count per batch bucket."""
def __init__(self, sd: StreamingCodecDecoder, batch_sizes: list[int], frames: int = 1) -> None:
self.sd, self.frames = sd, frames
self.graphs: dict[int, tuple] = {}
dev = sd.device
pool = torch.cuda.graph_pool_handle()
for bsz in sorted(set(batch_sizes)):
codes = torch.zeros(bsz, frames, sd.nq, dtype=torch.int32, device=dev)
slots = torch.full((bsz,), sd.scratch_slot, dtype=torch.int32, device=dev)
pos = torch.zeros(bsz, dtype=torch.int32, device=dev)
sd(codes, slots, pos)
current_omni_platform.synchronize()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, pool=pool):
out = sd(codes, slots, pos)
self.graphs[bsz] = (graph, codes, slots, pos, out)
self.sizes = sorted(self.graphs)
def __call__(self, codes: torch.Tensor, slots: torch.Tensor, pos: torch.Tensor) -> torch.Tensor:
"""``codes`` [n, frames, NQ], ``slots``/``pos`` [n] on device -> waveform view [n, frames * spf]."""
n = int(codes.shape[0])
size = next((b for b in self.sizes if b >= n), None)
if size is None:
return self.sd(codes, slots.to(torch.int32), pos.to(torch.int32))
graph, s_codes, s_slots, s_pos, out = self.graphs[size]
s_codes[:n].copy_(codes)
s_slots[:n].copy_(slots)
s_pos[:n].copy_(pos)
if n < size:
s_slots[n:].fill_(self.sd.scratch_slot)
s_pos[n:].zero_()
graph.replay()
return out[:n]