[Model] Enable Higgs Audio v3 MRV2 streaming and fix mixed-prefill capture bounds (#8226)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-09-30 11:32:27 +00:00
1 parent b44b2f981c
commit 56763cd6c3
35 files changed
+3231 -90

No files matched your search

@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""HiggsAudio codec decoder kernel for higgs-audio v2.
This module hosts the parameter-side building blocks for the higgs-audio-v2
@@ -16,11 +16,14 @@ from __future__ import annotations
import json
import os
import types
from typing import Any
import torch
import torch.nn as nn
from vllm_omni.platforms import current_omni_platform
__all__ = [
"HiggsAudioVQLayer",
"HiggsAudioRVQ",
@@ -99,6 +102,138 @@ class _Snake1d(nn.Module):
return _snake(x, self.alpha)
class _FusedDacSnake1d(nn.Module):
"""Drop-in for ``transformers`` ``DacModel`` Snake1d with a fused CUDA kernel.
Same ``alpha`` parameter, so checkpoints load unchanged. Inference on CUDA
runs one bit-identical kernel instead of about seven elementwise launches;
everything else keeps the transformers expression.
"""
def __init__(self, channels: int):
super().__init__()
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
self._inverse: tuple[tuple[int, int], torch.Tensor] | None = None
def can_fuse(self, x: torch.Tensor) -> bool:
# The kernel uses NVIDIA PTX and float32 intermediates. ROCm tensors
# also report is_cuda; retain the eager path there and for float64.
return (
current_omni_platform.is_cuda()
and x.is_cuda
and x.dim() == 3
and not torch.is_grad_enabled()
and x.dtype in (torch.float16, torch.bfloat16, torch.float32)
and x.dtype == self.alpha.dtype
)
def fused(
self,
x: torch.Tensor,
bias: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
write_sum: bool = False,
) -> tuple[torch.Tensor | None, torch.Tensor]:
"""Snake of ``residual + (x + bias)`` in one kernel; see ``fused_snake1d``."""
from .snake_kernel import fused_snake1d
alpha = self.alpha.detach()
try:
key = (alpha.data_ptr(), alpha._version)
except RuntimeError: # inference tensors carry no version counter
key = None
if key is not None and self._inverse is not None and self._inverse[0] == key:
inverse = self._inverse[1]
else:
# The eager (alpha + 1e-9).reciprocal(), computed once per weight
# update in the same dtype instead of on every call.
inverse = (alpha + 1e-9).reciprocal().reshape(-1).contiguous()
self._inverse = None if key is None else (key, inverse)
return fused_snake1d(x, alpha.reshape(-1), inverse, bias=bias, residual=residual, write_sum=write_sum)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.can_fuse(x):
return self.fused(x)[1]
shape = x.shape
x = x.reshape(shape[0], shape[1], -1)
x = x + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * x).pow(2)
return x.reshape(shape)
def _conv_without_bias(conv: nn.Module, x: torch.Tensor) -> torch.Tensor:
# cuDNN convolutions add the bias as a separate kernel anyway, so leaving
# it to the next fused Snake changes no bits.
if isinstance(conv, nn.ConvTranspose1d):
return nn.functional.conv_transpose1d(
x, conv.weight, None, conv.stride, conv.padding, conv.output_padding, conv.groups, conv.dilation
)
return conv._conv_forward(x, conv.weight, None)
def _fused_dac_decoder_forward(decoder: nn.Module, hidden_state: torch.Tensor) -> torch.Tensor:
"""transformers ``DacDecoder.forward`` with conv biases and residual adds
folded into the Snake kernels (5 elementwise passes per residual unit -> 2).
A value is carried as ``residual + (raw + bias)`` until the next Snake
consumes it, and only materialized where a residual connection needs it.
"""
if not decoder.snake1.can_fuse(hidden_state):
return type(decoder).forward(decoder, hidden_state)
raw, bias, residual = _conv_without_bias(decoder.conv1, hidden_state), decoder.conv1.bias, None
for block in decoder.block:
_, act = block.snake1.fused(raw, bias, residual)
raw, bias, residual = _conv_without_bias(block.conv_t1, act), block.conv_t1.bias, None
for unit in (block.res_unit1, block.res_unit2, block.res_unit3):
residual, act = unit.snake1.fused(raw, bias, residual, write_sum=True)
_, act = unit.snake2.fused(_conv_without_bias(unit.conv1, act), unit.conv1.bias)
raw, bias = _conv_without_bias(unit.conv2, act), unit.conv2.bias
_, act = decoder.snake1.fused(raw, bias, residual)
return decoder.tanh(decoder.conv2(act))
def _fuse_dac_decoder(decoder: nn.Module) -> int:
"""Swap transformers DAC Snake1d modules for fused ones (before weights
load) and, when the decoder has the stock layout, fuse its forward."""
try:
from transformers.models.dac.modeling_dac import DacDecoder
from transformers.models.dac.modeling_dac import Snake1d as DacSnake1d
except ImportError:
return 0
replaced = 0
for module in list(decoder.modules()):
for name, child in list(module.named_children()):
if isinstance(child, DacSnake1d):
fused = _FusedDacSnake1d(int(child.alpha.shape[1]))
fused.to(device=child.alpha.device, dtype=child.alpha.dtype)
setattr(module, name, fused)
replaced += 1
if type(decoder) is DacDecoder and _has_fusable_dac_layout(decoder):
decoder.forward = types.MethodType(_fused_dac_decoder_forward, decoder)
return replaced
def _has_fusable_dac_layout(decoder: nn.Module) -> bool:
convs = [decoder.conv1]
for block in decoder.block:
units = (block.res_unit1, block.res_unit2, block.res_unit3)
convs.append(block.conv_t1)
for unit in units:
conv1, conv2 = unit.conv1, unit.conv2
# Length-preserving convs, so the residual add needs no crop.
if conv1.stride[0] != 1 or 2 * conv1.padding[0] != conv1.dilation[0] * (conv1.kernel_size[0] - 1):
return False
if conv2.stride[0] != 1 or conv2.kernel_size[0] != 1 or conv2.padding[0] != 0:
return False
convs += [conv1, conv2]
if not all(isinstance(m, _FusedDacSnake1d) for m in (block.snake1, *(u.snake1 for u in units))):
return False
if not all(isinstance(u.snake2, _FusedDacSnake1d) for u in units):
return False
return isinstance(decoder.snake1, _FusedDacSnake1d) and all(
conv.bias is not None and conv.padding_mode == "zeros" for conv in convs
)
def _wn_conv1d(*args: Any, **kwargs: Any) -> nn.Module:
from torch.nn.utils import weight_norm
@@ -248,6 +383,7 @@ def build_higgs_audio_acoustic_decoder(
dac_cfg = DacConfig(**tokenizer_config["acoustic_model_config"])
dac_model = DacModel(dac_cfg)
decoder = dac_model.decoder.to(device)
_fuse_dac_decoder(decoder)
adjust_conv_transpose_output_padding(decoder)
if hasattr(decoder, "tanh"):
decoder.tanh = nn.Identity()
@@ -0,0 +1,113 @@
# ruff: noqa: N803
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Fused DAC Snake activation: ``x + 1 / (alpha + 1e-9) * sin(alpha * x) ** 2``.
The eager expression launches about seven elementwise kernels per call, each
reading and writing the whole activation; in the codec's CUDA graphs they are
most of its GPU time. This kernel reads ``x`` once and rounds every
intermediate to the tensor dtype exactly where the eager ops do, so outputs are
bit-identical to the unfused expression. It can also absorb the preceding conv
bias add and residual add, which are otherwise two more full passes each.
"""
import torch
from vllm.triton_utils import tl, tldevice, triton
@triton.jit
def _mul_rn(a, b):
# Explicit round-to-nearest ops are never contracted into FMA, so each
# product/sum rounds exactly where the separate eager kernels round.
return tl.inline_asm_elementwise("mul.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, is_pure=True, pack=1)
@triton.jit
def _add_rn(a, b):
return tl.inline_asm_elementwise("add.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, is_pure=True, pack=1)
@triton.jit
def _dac_snake_kernel(
x_ptr,
bias_ptr,
residual_ptr,
alpha_ptr,
inverse_ptr,
sum_ptr,
out_ptr,
stride_b,
stride_c,
t_len,
HAS_BIAS: tl.constexpr,
HAS_RESIDUAL: tl.constexpr,
WRITE_SUM: tl.constexpr,
BLOCK_T: tl.constexpr,
):
batch = tl.program_id(0).to(tl.int64)
channel = tl.program_id(1).to(tl.int64)
t = tl.program_id(2) * BLOCK_T + tl.arange(0, BLOCK_T)
mask = t < t_len
offset = batch * stride_b + channel * stride_c + t
x = tl.load(x_ptr + offset, mask=mask, other=0.0)
dtype = x.dtype
xf = x.to(tl.float32)
if HAS_BIAS:
# The conv bias add that cuDNN convolutions run as a separate kernel.
xf = _add_rn(xf, tl.load(bias_ptr + channel).to(tl.float32)).to(dtype).to(tl.float32)
if HAS_RESIDUAL:
residual = tl.load(residual_ptr + offset, mask=mask, other=0.0).to(tl.float32)
xf = _add_rn(residual, xf).to(dtype).to(tl.float32)
if WRITE_SUM:
tl.store(sum_ptr + offset, xf.to(dtype), mask=mask)
alpha = tl.load(alpha_ptr + channel).to(tl.float32)
inverse = tl.load(inverse_ptr + channel).to(tl.float32)
scaled = _mul_rn(alpha, xf).to(dtype).to(tl.float32)
# libdevice sinf, as the eager CUDA kernel (tl.sin is the approximation).
sine = tldevice.sin(scaled).to(dtype).to(tl.float32)
square = _mul_rn(sine, sine).to(dtype).to(tl.float32)
term = _mul_rn(inverse, square).to(dtype).to(tl.float32)
tl.store(out_ptr + offset, _add_rn(xf, term).to(dtype), mask=mask)
def fused_snake1d(
x: torch.Tensor,
alpha: torch.Tensor,
inverse: torch.Tensor,
*,
bias: torch.Tensor | None = None,
residual: torch.Tensor | None = None,
write_sum: bool = False,
) -> tuple[torch.Tensor | None, torch.Tensor]:
"""Snake of ``residual + (x + bias)``, rounded as the separate eager ops.
x, residual: (B, C, T); alpha, inverse, bias: (C,), all in x's dtype.
Returns ``(sum, snake(sum))``; ``sum`` is only materialized when
``write_sum`` is set (for the next residual connection), else None.
"""
x = x.contiguous()
if residual is not None:
residual = residual.contiguous()
batch, channels, t_len = x.shape
out = torch.empty_like(x)
total = torch.empty_like(x) if write_sum else None
if x.numel() == 0:
return total, out
block = min(triton.next_power_of_2(t_len), 2048)
_dac_snake_kernel[(batch, channels, triton.cdiv(t_len, block))](
x,
x if bias is None else bias,
x if residual is None else residual,
alpha,
inverse,
out if total is None else total,
out,
x.stride(0),
x.stride(1),
t_len,
HAS_BIAS=bias is not None,
HAS_RESIDUAL=residual is not None,
WRITE_SUM=write_sum,
BLOCK_T=block,
)
return total, out
@@ -0,0 +1,332 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Dense decode sampler graphs captured and parity-checked during startup.
Capture compares eager and captured state transitions with identical noise.
Serving only replays warmed shapes and preserves request torch RNG draws. CPU payload staging
remains outside capture. This module does not handle mixed prefill batches.
"""
import copy
import time
import torch
from vllm.logger import init_logger
from vllm.v1.outputs import SamplerOutput
logger = init_logger(__name__)
_STATE = (
"_decode_last_codes",
"_decode_has_codes",
"_decode_delay_count",
"_decode_eoc_countdown",
"_decode_generation_done",
)
_BUCKETS = (1, 2, 4, 8, 16, 24, 32, 40, 48, 56, 64, 96, 128)
_FIELDS = ("temperature", "top_k", "top_p")
def _graph_key(model, batch, hidden, force_audio_inputs, metadata):
return (
batch,
hidden.dtype,
hidden.device,
bool(force_audio_inputs),
bool(metadata.all_greedy),
tuple(getattr(metadata, f) is None for f in _FIELDS),
tuple(getattr(model, name).data_ptr() for name in _STATE),
)
def _replay_captured(model, hidden, metadata, force_audio_inputs):
"""Replay an already captured (bucket) graph writing inputs in place.
The capture path below pads through temporaries on every call. Once a
graph exists, only the live rows are written into its static inputs:
padded rows keep finite values from earlier steps and own no request
state, forced-audio inputs are constants, sampling parameters are copied
only when the cached metadata changes, and request noise is drawn directly
into the graph's noise input.
"""
cache = getattr(model, "_dense_sample_graphs", None)
if not cache:
return None
batch = hidden.shape[0]
bucket = batch
if getattr(model.config, "audio_mrv2_sample_graph_buckets", False):
bucket = next((n for n in _BUCKETS if n >= batch), batch)
model._ensure_decode_state_capacity(bucket, hidden.device)
key = _graph_key(model, bucket, hidden, force_audio_inputs, metadata)
entry = cache.get(key)
if entry is None:
return None
graph, static_hidden, static_input_ids, static_noise, static_metadata, output, staging, keepalive = entry
books = model.num_codebooks
static_hidden[:batch].copy_(hidden)
if not force_audio_inputs:
static_input_ids[:batch].copy_(model._last_step_input_ids)
if batch < bucket:
static_input_ids[batch:].fill_(model._audio_continuation_id)
if metadata.generators:
from vllm_omni.utils.seeded_exponential import fill_exponential_rows
fill_exponential_rows(static_noise[: batch * books], [metadata.generators.get(i) for i in range(batch)])
else:
static_noise[: batch * books].exponential_()
sources = getattr(model, "_dense_sample_metadata_sources", None)
if sources is None:
sources = model._dense_sample_metadata_sources = {}
if sources.get(key) is not metadata:
for name in _FIELDS:
value = getattr(metadata, name)
if value is not None:
getattr(static_metadata, name)[:batch].copy_(value)
sources[key] = metadata
graph.replay()
model._finish_audio_staging(staging[:batch], batch, hidden.device, batch)
return SamplerOutput(sampled_token_ids=output.sampled_token_ids[:batch].clone(), logprobs_tensors=None)
def run_dense_sample(model, hidden, logits, metadata, force_audio_inputs=False, active_batch=None):
batch = hidden.shape[0]
if active_batch is None:
replayed = _replay_captured(model, hidden, metadata, force_audio_inputs)
if replayed is not None:
return replayed
# Serving never captures a new shape. Unsupported shapes/metadata use the
# regular sampler; startup owns capture and its parity checks.
if not getattr(model, "_warming_sample_graphs", False):
return None
if active_batch is None and getattr(model.config, "audio_mrv2_sample_graph_buckets", False):
bucket = next((n for n in (1, 2, 4, 8, 16, 24, 32, 40, 48, 56, 64, 96, 128) if n >= batch), batch)
if bucket != batch:
# Dummy rows own no request state. The batch-state gather replaces
# these rows before any later request can use them.
model._ensure_decode_state_capacity(bucket, hidden.device)
padded_hidden = hidden.new_zeros((bucket, hidden.shape[1]))
padded_hidden[:batch].copy_(hidden)
padded_metadata = copy.copy(metadata)
for name in ("temperature", "top_k", "top_p"):
value = getattr(metadata, name)
if value is not None:
padded = value.new_ones(bucket)
padded[:batch].copy_(value)
setattr(padded_metadata, name, padded)
original_ids = model._last_step_input_ids
padded_ids = original_ids.new_full((bucket,), model._audio_continuation_id)
if not force_audio_inputs:
padded_ids[:batch].copy_(original_ids)
model._last_step_input_ids = padded_ids
try:
output = run_dense_sample(
model,
padded_hidden,
logits.new_empty((bucket, logits.shape[1])),
padded_metadata,
force_audio_inputs=force_audio_inputs,
active_batch=batch,
)
finally:
model._last_step_input_ids = original_ids
return SamplerOutput(sampled_token_ids=output.sampled_token_ids[:batch], logprobs_tensors=None)
actual = batch if active_batch is None else active_batch
effective_ids = (
torch.full((batch,), model._audio_continuation_id, dtype=model._last_step_input_ids.dtype, device=hidden.device)
if force_audio_inputs
else model._last_step_input_ids
)
books = model.num_codebooks
vocab = model.modality_head.vocab_size
noise = torch.empty((batch * books, vocab), dtype=torch.float32, device=hidden.device)
if actual < batch:
noise[actual * books :].fill_(1)
if metadata.generators:
from vllm_omni.utils.seeded_exponential import fill_exponential_rows
fill_exponential_rows(noise[: actual * books], [metadata.generators.get(i) for i in range(actual)])
else:
noise[: actual * books].exponential_()
fields = _FIELDS
# force_audio_inputs controls capture-time Python branches (including
# the mixed-tail assertion). Never reuse that graph for real EOS inputs.
key = _graph_key(model, batch, hidden, force_audio_inputs, metadata)
cache = getattr(model, "_dense_sample_graphs", None)
if cache is None:
cache = model._dense_sample_graphs = {}
entry = cache.get(key)
if entry is None:
static_hidden = hidden.clone()
static_input_ids = effective_ids.clone()
static_noise = noise.clone()
static_metadata = copy.copy(metadata)
for name in fields:
value = getattr(metadata, name)
setattr(static_metadata, name, None if value is None else value.clone())
# Ensure the reusable staging exists before capture. Each graph keeps
# its own reference if a later larger batch grows the model buffer.
staging = model._get_audio_gpu_staging_buffer(batch, hidden.device)
state = {name: getattr(model, name).clone() for name in _STATE}
original_ids = model._last_step_input_ids
original_qsl = model._last_step_query_start_loc
original_mode_rows = getattr(model, "_step_audio_mode_rows", 0)
original_tail_rows = getattr(model, "_step_audio_tail_rows", 0)
original_direct_rows = getattr(model, "_fast_audio_direct_rows", 0)
# Dense decode has one token per row. Own this input instead of
# capturing a view of the runner's resizable staging buffer.
static_qsl = torch.arange(batch + 1, dtype=torch.int32, device=hidden.device)
def restore():
for name, value in state.items():
getattr(model, name).copy_(value)
try:
model._in_audio_sample_graph = True
# Outer eligibility and real-input validation already ran. The
# owned graph inputs represent exactly one audio-state row each.
# Normalize capture-time host dispatch; never capture an outer
# mixed-batch assertion or a stock-sampler branch into this graph.
model._step_audio_mode_rows = 0
model._step_audio_tail_rows = 0
model._fast_audio_direct_rows = batch
model._audio_graph_noise = static_noise
model._last_step_input_ids = static_input_ids
model._last_step_query_start_loc = static_qsl
model._last_logits_hidden = static_hidden
reference = model.sample(logits, static_metadata)
expected_ids = reference.sampled_token_ids.clone()
expected_staging = staging.clone()
expected_state = {name: getattr(model, name).clone() for name in _STATE}
restore()
model._last_logits_hidden = static_hidden
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
output = model.sample(logits, static_metadata)
# CUDA capture records work; it does not execute the transition.
# Validate only after replay from the preserved initial state.
restore()
graph.replay()
torch.testing.assert_close(output.sampled_token_ids, expected_ids, atol=0, rtol=0)
torch.testing.assert_close(staging, expected_staging, atol=0, rtol=0)
for name, expected in expected_state.items():
torch.testing.assert_close(getattr(model, name), expected, atol=0, rtol=0)
restore()
logger.debug("Higgs sample graph parity checked for batch=%d", batch)
finally:
model._in_audio_sample_graph = False
model._step_audio_mode_rows = original_mode_rows
model._step_audio_tail_rows = original_tail_rows
model._fast_audio_direct_rows = original_direct_rows
model._audio_graph_noise = None
model._last_step_input_ids = original_ids
model._last_step_query_start_loc = original_qsl
model._last_logits_hidden = None
# Graphs reference storage, not Python owners. Model caches and state
# can grow after capture; keep their original allocations alive.
keepalive = [getattr(model, name) for name in _STATE]
for name in ("_row_index_cache", "_codebook_index_cache", "_boc_frame_cache"):
keepalive.extend(getattr(model, name).values())
keepalive.append(static_qsl)
entry = (graph, static_hidden, static_input_ids, static_noise, static_metadata, output, staging, keepalive)
cache[key] = entry
graph, static_hidden, static_input_ids, static_noise, static_metadata, output, staging, keepalive = entry
static_hidden.copy_(hidden)
static_input_ids.copy_(effective_ids)
static_noise.copy_(noise)
for name in fields:
value = getattr(metadata, name)
if value is not None:
getattr(static_metadata, name).copy_(value)
graph.replay()
model._finish_audio_staging(staging[:actual], actual, hidden.device, actual)
return SamplerOutput(sampled_token_ids=output.sampled_token_ids.clone(), logprobs_tensors=None)
@torch.inference_mode()
def capture_sample_graphs(model, max_num_reqs):
"""Warm the MRv2 sampler without consuming request RNG or decode state."""
if not model._sample_graph_enabled or getattr(model, "_sample_graphs_ready", False):
return
from vllm.v1.sample.logits_processor import LogitsProcessors
from vllm.v1.sample.metadata import SamplingMetadata
device = model.model.embed_tokens.weight.device
if device.type != "cuda":
return
start = time.perf_counter()
memory_before = torch.accelerator.memory_allocated(device)
reserved_before = torch.accelerator.memory_reserved(device)
model._resolve_token_ids()
buckets = (
sorted({next((b for b in _BUCKETS if b >= n), n) for n in range(1, max_num_reqs + 1)})
if getattr(model.config, "audio_mrv2_sample_graph_buckets", False)
else range(1, max_num_reqs + 1)
)
model._ensure_decode_state_capacity(max(buckets), device)
model._get_audio_gpu_staging_buffer(max(buckets), device)
saved_state = {name: getattr(model, name).clone() for name in _STATE}
fields = (
"_last_step_input_ids",
"_last_step_query_start_loc",
"_last_logits_hidden",
"_step_audio_mode_rows",
"_step_audio_tail_rows",
"_fast_audio_direct_rows",
)
saved = {name: getattr(model, name, None) for name in fields}
try:
model._warming_sample_graphs = True
with torch.random.fork_rng(devices=[device.index]):
for batch in buckets:
hidden = model.model.embed_tokens.weight.new_zeros((batch, model.model.embed_tokens.weight.shape[1]))
logits = hidden.new_empty((batch, model.config.text_config.vocab_size))
model._last_step_input_ids = torch.full(
(batch,), model._audio_continuation_id, device=device, dtype=torch.long
)
model._last_step_query_start_loc = torch.arange(batch + 1, device=device, dtype=torch.int32)
ones = torch.ones(batch, device=device)
zeros = torch.zeros_like(ones)
for greedy in (False, True):
metadata = SamplingMetadata(
temperature=zeros if greedy else ones,
all_greedy=greedy,
all_random=not greedy,
top_p=ones,
top_k=torch.full((batch,), -1, device=device, dtype=torch.long),
generators={},
max_num_logprobs=None,
no_penalties=True,
prompt_token_ids=None,
frequency_penalties=zeros,
presence_penalties=zeros,
repetition_penalties=ones,
output_token_ids=[[] for _ in range(batch)],
allowed_token_ids_mask=None,
bad_words_token_ids={},
logitsprocs=LogitsProcessors(),
)
for forced in (False, True):
run_dense_sample(model, hidden, logits, metadata, force_audio_inputs=forced)
finally:
for name, value in saved_state.items():
getattr(model, name).copy_(value)
for name, value in saved.items():
setattr(model, name, value)
model._warming_sample_graphs = False
model._clear_last_audio_outputs()
model._async_audio_gpu_staging = None
model._dense_sample_metadata_sources = {}
torch.accelerator.synchronize()
model._sample_graphs_ready = True
logger.info(
"Higgs sampler captured %d CUDA graphs in %.2f s "
"(allocated delta %.1f MiB, reserved delta %.1f MiB, reserved total %.1f MiB)",
len(model._dense_sample_graphs),
time.perf_counter() - start,
(torch.accelerator.memory_allocated(device) - memory_before) / 2**20,
(torch.accelerator.memory_reserved(device) - reserved_before) / 2**20,
torch.accelerator.memory_reserved(device) / 2**20,
)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Stage 1 (codec decoder) for higgs-audio v3.
Reuses higgs-audio-v2's RVQ + DAC codec decoder but loads weights from the
@@ -10,6 +10,7 @@ prefix) rather than from a standalone tokenizer repo.
from __future__ import annotations
import os
import time
from typing import Any
import torch
@@ -57,6 +58,9 @@ class HiggsAudioV3Code2Wav(nn.Module):
input_modalities = "audio"
supports_native_payload_input = True
batched_gpu_staging_keys = {("codes", "audio")}
def __init__(
self,
config: HiggsAudioV3Config | None = None,
@@ -81,6 +85,11 @@ class HiggsAudioV3Code2Wav(nn.Module):
self._model_path = None
self.vllm_config = None
_, self._codec_graph_enabled = self.config.resolve_graph_defaults(
use_v2_model_runner=bool(
getattr(getattr(self.vllm_config, "model_config", None), "use_v2_model_runner", False)
)
)
self.sample_rate: int = int(self.config.sample_rate)
self.num_codebooks: int = int(self.config.num_codebooks)
self.num_real_codes: int = int(self.config.num_real_codes)
@@ -97,6 +106,8 @@ class HiggsAudioV3Code2Wav(nn.Module):
self.quantizer: HiggsAudioRVQ | None = None
self.fc2: nn.Linear | None = None
self.acoustic_decoder: nn.Module | None = None
self._decode_graphs: dict[tuple[int, int], tuple[Any, torch.Tensor, torch.Tensor]] = {}
self._decode_graphs_initialized = False
self._loaded: bool = False
# Do NOT eagerly load from standalone tokenizer here.
# load_weights() will try bundled V3 codec first, then fall back.
@@ -452,6 +463,30 @@ class HiggsAudioV3Code2Wav(nn.Module):
self._ensure_codec_loaded()
codes = self._validate_codes(audio_codes)
if codes.is_cuda and self._codec_graph_enabled:
batch, _, frames = codes.shape
entry = self._decode_graphs.get((batch, frames))
if entry is not None:
graph, static_codes, static_audio = entry
static_codes[:batch].copy_(codes)
graph.replay()
# The next group may replay the same graph. Own the output
# before reusing its storage or shared graph memory pool.
return static_audio[:batch].clone()
return self._decode_codes_impl(codes)
@torch.inference_mode()
def capture_auxiliary_graphs(self) -> None:
"""Capture exact codec shapes before the generation worker is ready."""
if not self._codec_graph_enabled or self._decode_graphs_initialized:
return
if not self._loaded:
self._ensure_codec_loaded()
device = self.fc2.weight.device
if device.type == "cuda":
self._capture_decode_graphs(device)
def _decode_codes_impl(self, codes: torch.Tensor) -> torch.Tensor:
rvq_codes = codes.transpose(0, 1).long()
quantized = self.quantizer.decode(rvq_codes)
quantized = quantized.to(dtype=self.fc2.weight.dtype)
@@ -464,6 +499,55 @@ class HiggsAudioV3Code2Wav(nn.Module):
audio = audio.unsqueeze(1)
return audio.to(codes.device)
def _decode_graph_shapes(self) -> list[tuple[int, int]]:
single_max = int(getattr(self.config, "codec_graph_single_max_frames", 150))
batches = getattr(self.config, "codec_graph_batch_sizes", (2, 4, 8, 16))
frames = getattr(self.config, "codec_graph_frame_sizes", (5, 29, 54))
if single_max < 1 or any(int(n) < 1 for n in (*batches, *frames)):
raise ValueError("Higgs codec graph dimensions must be positive")
return sorted({(1, n) for n in range(1, single_max + 1)} | {(int(b), int(f)) for b in batches for f in frames})
@torch.inference_mode()
def _capture_decode_graphs(self, device: torch.device) -> None:
# Never pad time: convolution boundary conditions must stay exact.
# Batch size also stays exact: padding can change convolution
# algorithms and rounding. Uncovered shapes retain the eager path.
start = time.perf_counter()
memory_before = torch.accelerator.memory_allocated(device)
reserved_before = torch.accelerator.memory_reserved(device)
shapes = self._decode_graph_shapes()
previous_device = current_omni_platform.current_device()
current_omni_platform.set_device(device)
try:
stream = torch.cuda.Stream(device=device)
stream.wait_stream(torch.cuda.current_stream(device))
pool = torch.cuda.graph_pool_handle()
for batch, frames in shapes:
codes = torch.zeros((batch, self.num_codebooks, frames), device=device, dtype=torch.long)
stream.wait_stream(torch.cuda.current_stream(device))
with torch.cuda.stream(stream):
for _ in range(3):
self._decode_codes_impl(codes)
stream.synchronize()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, pool=pool, stream=stream):
audio = self._decode_codes_impl(codes)
self._decode_graphs[batch, frames] = (graph, codes, audio)
torch.cuda.current_stream(device).wait_stream(stream)
finally:
current_omni_platform.set_device(torch.device(device.type, previous_device))
self._decode_graphs_initialized = True
torch.accelerator.synchronize()
logger.info(
"Higgs codec captured %d exact-frame CUDA graphs in %.2f s "
"(allocated delta %.1f MiB, reserved delta %.1f MiB, reserved total %.1f MiB)",
len(self._decode_graphs),
time.perf_counter() - start,
(torch.accelerator.memory_allocated(device) - memory_before) / 2**20,
(torch.accelerator.memory_reserved(device) - reserved_before) / 2**20,
torch.accelerator.memory_reserved(device) / 2**20,
)
@torch.inference_mode()
def forward_chunk(
self,
@@ -518,6 +602,18 @@ class HiggsAudioV3Code2Wav(nn.Module):
ids = input_ids.reshape(-1).to(dtype=torch.long)
request_ids_list = self._split_request_ids(ids, kwargs.get("seq_token_counts"))
# Native MRV2 uses token placeholders for scheduling. The connector
# payload owns the actual codebook-major codec sequence, including an
# empty terminal payload which must not decode a placeholder token.
if runtime_additional_information is not None:
for i, info in enumerate(runtime_additional_information):
if i >= len(request_ids_list):
break
codes = info.get("codes", {}) if isinstance(info, dict) else {}
audio = codes.get("audio") if isinstance(codes, dict) else None
if isinstance(audio, torch.Tensor):
request_ids_list[i] = audio.reshape(-1).to(device=ids.device, dtype=torch.long)
left_context_size = [0] * len(request_ids_list)
right_holdback_size = [0] * len(request_ids_list)
if runtime_additional_information is not None:
@@ -530,11 +626,14 @@ class HiggsAudioV3Code2Wav(nn.Module):
if "right_holdback_size" in meta:
right_holdback_size[i] = int(meta["right_holdback_size"])
wavs: list[torch.Tensor] = []
wavs: list[torch.Tensor] = [empty] * len(request_ids_list)
# Requests with identical codec windows are independent along B. Keep
# time lengths and overlap trims exact rather than padding the temporal
# axis, which could change the convolution boundary conditions.
groups: dict[tuple[int, int, int], list[tuple[int, torch.Tensor]]] = {}
for i, req_ids in enumerate(request_ids_list):
n = int(req_ids.numel())
if n == 0:
wavs.append(empty)
continue
if n % self.num_codebooks != 0:
logger.warning(
@@ -542,23 +641,43 @@ class HiggsAudioV3Code2Wav(nn.Module):
n,
self.num_codebooks,
)
wavs.append(empty)
continue
frames = n // self.num_codebooks
codes_qf = req_ids.reshape(self.num_codebooks, frames)
codes_bqf = codes_qf.unsqueeze(0)
key = (frames, left_context_size[i], right_holdback_size[i])
groups.setdefault(key, []).append((i, req_ids.reshape(self.num_codebooks, frames)))
for (_, left, right), group in groups.items():
codes_bqf = group[0][1].unsqueeze(0) if len(group) == 1 else torch.stack([codes for _, codes in group])
try:
pcm = self.forward_chunk(
codes_bqf,
left_context_size=left_context_size[i],
right_holdback_size=right_holdback_size[i],
left_context_size=left,
right_holdback_size=right,
hop_length=self.hop_length,
)
except ValueError as exc:
logger.warning("HiggsAudioV3Code2Wav: decode skipped (%s)", exc)
wavs.append(empty)
if len(group) == 1:
logger.warning("HiggsAudioV3Code2Wav: decode skipped (%s)", exc)
continue
# An invalid row must not discard valid peers. This slow path
# retains the previous per-request validation/error behavior.
for index, codes in group:
try:
row_pcm = self.forward_chunk(
codes.unsqueeze(0),
left_context_size=left,
right_holdback_size=right,
hop_length=self.hop_length,
)
wavs[index] = row_pcm[0, 0].to(torch.float32)
except ValueError as row_exc:
logger.warning("HiggsAudioV3Code2Wav: decode skipped (%s)", row_exc)
continue
wavs.append(pcm.squeeze(0).squeeze(0).to(torch.float32).cpu())
pcm = pcm.to(torch.float32)
for row, (index, _) in enumerate(group):
# The generation runner owns the batched pinned D2H copy and
# its completion event; avoid blocking once per request here.
wavs[index] = pcm[row, 0]
return OmniOutput(
text_hidden_states=None,
@@ -108,12 +108,26 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
prefer_model_sampler: bool = True
# Tell the runner to call postprocess() to emit per-step audio codes.
have_multimodal_outputs: bool = True
has_postprocess: bool = True
has_postprocess: bool = False
skips_model_sampler_output_token_history: bool = True
postprocess_uses_hidden_states: bool = False
postprocess_uses_multimodal_outputs: bool = False
postprocess_uses_req_infos: bool = False
supports_omni_query_start_loc: bool = True
requires_cpu_input_tail_ids: bool = True
# The codec stage consumes audio codes, never backbone hidden states.
omni_pooler_payload_include_hidden: bool = False
def capture_auxiliary_graphs(self) -> None:
from .full_sample_graph import capture_sample_graphs
scheduler = self.vllm_config.scheduler_config
capture_sample_graphs(self, scheduler.max_num_seqs)
def create_omni_model_state(self, vllm_config, encoder_cache, device):
from .model_state import HiggsModelState
return HiggsModelState(vllm_config, self, encoder_cache, device)
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -122,6 +136,17 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
self.config = hf_config
else:
self.config = HiggsAudioV3Config(**hf_config.to_dict())
self._sample_graph_enabled, _ = self.config.resolve_graph_defaults(
use_v2_model_runner=bool(getattr(vllm_config.model_config, "use_v2_model_runner", False))
)
self.use_async_omni_output = getattr(self.config, "audio_async_payload", False) is True
self.supports_async_whole_payload = self.use_async_omni_output
if self.use_async_omni_output:
if not vllm_config.scheduler_config.async_scheduling:
raise ValueError("audio_async_payload requires async scheduling")
if getattr(self.config, "audio_async_prompt_mode", False) is not True:
raise ValueError("audio_async_payload requires audio prompt mode classification")
self._async_audio_gpu_staging = None
model_config = getattr(vllm_config, "model_config", None)
compilation_config = getattr(vllm_config, "compilation_config", None)
cudagraph_mode = getattr(compilation_config, "cudagraph_mode", None)
@@ -345,10 +370,26 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
inputs_embeds: torch.Tensor | None = None,
omni_query_start_loc: torch.Tensor | None = None,
req_ids: list[str] | None = None,
cpu_input_tail_ids: list[int] | None = None,
audio_prompt_mode_rows: int = 0,
**_: Any,
) -> None:
"""Update per-step metadata before runner forward or CUDA graph replay."""
_ = positions, inputs_embeds
self._step_audio_mode_rows = (
audio_prompt_mode_rows if getattr(self.config, "audio_async_prompt_mode", False) is True else 0
)
self._step_audio_tail_rows = 0
if cpu_input_tail_ids:
self._resolve_token_ids()
if (
cpu_input_tail_ids
and self._audio_continuation_id is not None
and req_ids is not None
and len(cpu_input_tail_ids) == len(req_ids)
and all(token == self._audio_continuation_id for token in cpu_input_tail_ids)
):
self._step_audio_tail_rows = len(cpu_input_tail_ids)
if input_ids is not None:
self._last_step_input_ids = input_ids
if self._use_external_decode_cudagraph and input_ids.is_cuda and input_ids.ndim >= 1:
@@ -359,6 +400,9 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
if req_ids is not None:
self._sync_decode_state_with_batch(req_ids)
def finish_decode_step_forward(self) -> None:
self._decode_step_metadata_from_runner = False
def _ensure_state_pool_capacity(self, num_rows: int, device: torch.device) -> None:
if not hasattr(self, "_state_pool_indices"):
self._state_pool_indices: dict[str, int] = {}
@@ -387,17 +431,53 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
self._state_pool_eoc_countdown = resize(self._state_pool_eoc_countdown, -1)
self._state_pool_generation_done = resize(self._state_pool_generation_done, False)
def _state_indices(self, rows: list[int], device: torch.device) -> torch.Tensor:
# A fresh pinned allocation is owned by PyTorch's host allocator until
# its asynchronous copy completes; never overwrite a shared CPU staging
# buffer while the previous decode step may still be reading it.
if device.type == "cuda" and getattr(self.config, "audio_mrv2_async_state_indices", False):
return torch.tensor(rows, dtype=torch.long, pin_memory=True).to(device, non_blocking=True)
return torch.tensor(rows, dtype=torch.long, device=device)
def _sync_decode_state_with_batch(self, req_ids: list[str]) -> None:
device = self._decode_has_codes.device
self._ensure_state_pool_capacity(len(req_ids), device)
previous_req_ids = getattr(self, "_last_batch_req_ids", [])
if (
device.type == "cuda"
and getattr(self.config, "audio_mrv2_fused_state", False)
and (previous_req_ids != req_ids or any(r not in self._state_pool_indices for r in req_ids))
):
from .mrv2_state_kernels import sync_state
previous_rows = [row for row, req_id in enumerate(previous_req_ids) if req_id in self._state_pool_indices]
pool_rows = [self._state_pool_indices[previous_req_ids[row]] for row in previous_rows]
current_rows = []
for req_id in req_ids:
fresh = req_id not in self._state_pool_indices
if fresh:
slot = (
self._free_state_pool_indices.pop()
if self._free_state_pool_indices
else len(self._state_pool_indices)
)
self._ensure_state_pool_capacity(slot + 1, device)
self._state_pool_indices[req_id] = slot
slot = self._state_pool_indices[req_id]
current_rows.append(-slot - 1 if fresh else slot)
self._ensure_decode_state_capacity(len(req_ids), device)
if req_ids or previous_rows:
sync_state(self, previous_rows, pool_rows, current_rows)
self._last_batch_req_ids = list(req_ids)
return
if previous_req_ids != req_ids or any(req_id not in self._state_pool_indices for req_id in req_ids):
previous_rows = [row for row, req_id in enumerate(previous_req_ids) if req_id in self._state_pool_indices]
if previous_rows:
pool_rows = [self._state_pool_indices[previous_req_ids[row]] for row in previous_rows]
src = torch.tensor(previous_rows, dtype=torch.long, device=device)
dst = torch.tensor(pool_rows, dtype=torch.long, device=device)
src = self._state_indices(previous_rows, device)
dst = self._state_indices(pool_rows, device)
self._state_pool_has_codes[dst] = self._decode_has_codes[src]
self._state_pool_last_codes[dst] = self._decode_last_codes[src]
self._state_pool_delay_count[dst] = self._decode_delay_count[src]
@@ -420,10 +500,9 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
self._state_pool_generation_done[pool_row] = False
self._ensure_decode_state_capacity(len(req_ids), device)
pool_rows = torch.tensor(
pool_rows = self._state_indices(
[self._state_pool_indices[req_id] for req_id in req_ids],
dtype=torch.long,
device=device,
device,
)
self._decode_has_codes[: len(req_ids)] = self._state_pool_has_codes[pool_rows]
self._decode_last_codes[: len(req_ids)] = self._state_pool_last_codes[pool_rows]
@@ -450,8 +529,9 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
inputs_embeds: torch.Tensor | None = None,
**kwargs: Any,
) -> torch.Tensor:
# A runner invocation may call forward repeatedly while warming and
# capturing a graph. Keep its metadata authoritative for that scope.
metadata_from_runner = self._decode_step_metadata_from_runner
self._decode_step_metadata_from_runner = False
info_dicts = kwargs.get("model_intermediate_buffer")
if info_dicts is None:
@@ -501,7 +581,7 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
and inputs_embeds is None
and not self._is_single_token_decode_step(int(hidden_states.shape[0]))
)
if is_prefill and info_dicts:
if is_prefill and info_dicts and inputs_embeds is None:
# Voice clone: replace marked prompt positions with ref audio embeddings.
hidden_states = self._apply_ref_audio_substitution(hidden_states, input_ids, positions, info_dicts)
@@ -515,6 +595,11 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
return self._run_qwen3_layers_eager(positions, hidden_states)
def _run_qwen3_layers_eager(self, positions: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
if self._use_external_decode_cudagraph:
# Enter Qwen3Model's compilation boundary before the runner
# captures the decode graph. Audio feedback stays outside it.
return self.model(input_ids=None, positions=positions, inputs_embeds=hidden_states)
residual: torch.Tensor | None = None
for layer in self.model.layers:
hidden_states, residual = layer(positions, hidden_states, residual)
@@ -619,6 +704,25 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
def compute_logits(self, hidden_states: torch.Tensor, sampling_metadata: Any = None) -> torch.Tensor:
self._last_logits_hidden = hidden_states
ids = getattr(self, "_last_step_input_ids", None)
rows = int(hidden_states.shape[0])
if (
self._audio_continuation_id is not None
and sampling_metadata is not None
and getattr(sampling_metadata, "no_penalties", False)
and (
(isinstance(ids, torch.Tensor) and ids.numel() == rows and self._fast_audio_direct_rows == rows)
or getattr(self, "_step_audio_tail_rows", 0) == rows
or getattr(self, "_step_audio_mode_rows", 0) == rows
)
and getattr(sampling_metadata, "max_num_logprobs", None) is None
and getattr(sampling_metadata, "allowed_token_ids_mask", None) is None
and not getattr(sampling_metadata, "bad_words_token_ids", None)
):
# sample() already selects continuation/EOS directly in this
# state, using the audio head rather than the text head. Keep
# the normal vocabulary shape for runner-side processors.
return hidden_states.new_empty((rows, self._text_vocab_size), dtype=torch.float32)
return self.logits_processor(self.lm_head, hidden_states)
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
@@ -656,7 +760,9 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
``audio_placeholder_positions`` ([T] absolute prompt positions). Legacy
callers that still submit -100 token IDs remain supported.
"""
if not info_dicts:
if not info_dicts or not any(
isinstance(info, dict) and info.get("audio_input_ids") is not None for info in info_dicts
):
return hidden_states
flat_ids = input_ids.reshape(-1)
@@ -788,10 +894,6 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
if self._decode_active_audio_count == 0 and not external_decode_graph:
return hidden_states
req_rows, token_positions = self._decode_request_token_positions(num_tokens, hidden_states.device)
if int(req_rows.numel()) == 0:
return hidden_states
num_reqs = self._step_request_count(num_tokens)
self._ensure_decode_state_capacity(num_reqs, hidden_states.device)
@@ -800,6 +902,9 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
has_codes = self._decode_has_codes[:num_tokens].unsqueeze(-1)
current_hidden = hidden_states
else:
req_rows, token_positions = self._decode_request_token_positions(num_tokens, hidden_states.device)
if int(req_rows.numel()) == 0:
return hidden_states
codes_slice = self._decode_last_codes.index_select(0, req_rows)
has_codes = self._decode_has_codes.index_select(0, req_rows).unsqueeze(-1)
current_hidden = hidden_states.index_select(0, token_positions)
@@ -932,6 +1037,44 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
return None
return tail_ids == int(audio_id)
def _step_tail_guard(self, num_rows: int, *, prompt_mode: bool, decode_only: bool) -> None:
from .step_kernels import step_tail_guard
error = getattr(self, "_decode_tail_guard_error", None)
device = self._decode_has_codes.device
if error is None or error.device != device:
error = self._decode_tail_guard_error = torch.zeros(1, dtype=torch.int32, device=device)
step_tail_guard(
self._last_step_input_ids.reshape(-1),
None if decode_only else self._last_step_query_start_loc,
self._decode_has_codes[:num_rows],
self._decode_generation_done[:num_rows],
self._decode_delay_count[:num_rows],
self._decode_eoc_countdown[:num_rows],
error,
audio_id=int(self._audio_continuation_id),
eos_id=int(self._eos_token_id),
prompt_mode=prompt_mode,
)
torch._assert_async(error[0] == 0, "CPU/GPU Higgs graph audio tail mismatch")
def _restore_terminal_audio_rows(self, num_rows):
# Async scheduling can execute one final in-flight EOS row after
# request retirement has released its state slot. EOS is terminal:
# never resurrect that row as a new audio stream with a forced input.
eos_id = self._eos_token_id
if eos_id is None:
return
ids = self._last_step_input_ids.reshape(-1)
qsl = self._last_step_query_start_loc
if isinstance(qsl, torch.Tensor) and qsl.numel() == num_rows + 1:
tail = ids.index_select(0, (qsl[1:].long() - 1).clamp_min(0))
elif ids.numel() == num_rows:
tail = ids
else:
raise RuntimeError("Cannot validate terminal audio rows")
self._decode_generation_done[:num_rows].logical_or_(tail == eos_id)
def _fast_audio_sampler_gpu_fallback_reason(
self,
*,
@@ -997,6 +1140,7 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
and accumulate per-request state.
"""
self._resolve_token_ids()
self._async_audio_gpu_staging = None
audio_id = self._audio_continuation_id
@@ -1020,6 +1164,56 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
self._ensure_decode_state_capacity(num_rows, hidden.device)
ids = getattr(self, "_last_step_input_ids", None)
decode_only = isinstance(ids, torch.Tensor) and int(ids.numel()) == num_rows
prompt_mode_rows = getattr(self, "_step_audio_mode_rows", 0) == num_rows
graph_forced_audio = getattr(self, "_step_audio_tail_rows", 0) == num_rows or prompt_mode_rows
use_sample_graph = bool(
getattr(self, "_sample_graph_enabled", False)
and not getattr(self, "_in_audio_sample_graph", False)
and hidden.is_cuda
and (graph_forced_audio or (decode_only and self._fast_audio_direct_rows == num_rows))
and getattr(sampling_metadata, "no_penalties", False)
and self._fast_audio_sampler_gpu_fallback_reason(
logits=logits, sampling_metadata=sampling_metadata, num_rows=num_rows
)
is None
)
qsl = self._last_step_query_start_loc
fused_guard = (
use_sample_graph
and graph_forced_audio
and self._eos_token_id is not None
and (decode_only or (isinstance(qsl, torch.Tensor) and int(qsl.numel()) == num_rows + 1))
)
if fused_guard:
# One launch restores terminal EOS rows, resets new prefill rows
# and validates the audio tail (~20 small eager kernels before).
self._step_tail_guard(num_rows, prompt_mode=prompt_mode_rows, decode_only=decode_only)
elif prompt_mode_rows:
self._restore_terminal_audio_rows(num_rows)
if use_sample_graph:
from .full_sample_graph import run_dense_sample
if not fused_guard and graph_forced_audio:
actual_audio = self._audio_seed_mask_from_step_input(num_rows, hidden.device)
if getattr(self, "_step_audio_mode_rows", 0) == num_rows:
# Reset new prefill rows before accepting old active state.
if not decode_only:
self._reset_decode_state_rows(
self._prefill_row_mask(num_rows, hidden.device), num_rows, hidden.device
)
actual_audio = (
actual_audio | self._decode_has_codes[:num_rows] | self._decode_generation_done[:num_rows]
)
torch._assert_async(actual_audio.all(), "CPU/GPU Higgs graph audio tail mismatch")
if not decode_only:
if not fused_guard:
pfmask = self._prefill_row_mask(num_rows, hidden.device)
self._reset_decode_state_rows(pfmask, num_rows, hidden.device)
self._fast_audio_direct_rows = num_rows
sampled = run_dense_sample(self, hidden, logits, sampling_metadata, force_audio_inputs=graph_forced_audio)
if sampled is not None:
return sampled
self._last_logits_hidden = None
if not decode_only:
self._fast_audio_direct_rows = 0
pfmask = self._prefill_row_mask(num_rows, hidden.device)
@@ -1042,6 +1236,17 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
if fast_fallback_reason is None:
direct_audio_batch = decode_only and self._fast_audio_direct_rows == num_rows
mixed_direct = (
getattr(self, "_step_audio_tail_rows", 0) == num_rows
or getattr(self, "_step_audio_mode_rows", 0) == num_rows
) and getattr(sampling_metadata, "no_penalties", False)
if mixed_direct:
# Guard the CPU classification against runner/device drift.
torch._assert_async(
(audio_mask if getattr(self, "_step_audio_mode_rows", 0) == num_rows else prev_audio_mask).all(),
"CPU/GPU Higgs audio tail mismatch",
)
direct_audio_batch = True
if direct_audio_batch:
self._fast_audio_direct_rows = num_rows
@@ -1194,6 +1399,62 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
self._boc_frame_cache[key] = buf
return buf[:num_rows]
def post_sample_multimodal_outputs(self, *, req_ids, invalid_req_indices, multimodal_outputs):
"""Export current-step codes by current batch row, with owned CPU storage.
Forward-time payloads refer to previous request-buffer rows, which may
be reordered or overwritten when the sampler reuses its host staging.
Export only after sampling, before the runner takes its output snapshot.
"""
if getattr(self, "use_async_omni_output", False):
staging = self._async_audio_gpu_staging
self._async_audio_gpu_staging = None
self._fast_audio_direct_rows = 0
if staging is None:
return None
if staging.shape[0] != len(req_ids):
raise RuntimeError("Higgs async snapshot row mismatch")
return {"_higgs_audio_snapshot": staging, "_higgs_invalid_rows": tuple(invalid_req_indices)}
staging = self._last_audio_host_staging
if staging is None:
self._fast_audio_direct_rows = 0
return None
if staging.shape[0] != len(req_ids):
raise RuntimeError("Higgs audio staging rows do not match the sampled request batch")
event = self._last_audio_staging_event
if event is not None:
event.synchronize()
self._last_audio_staging_event = None
codes = staging[:, : self.num_codebooks].clone()
valid = staging[:, self.num_codebooks].tolist()
done = staging[:, self.num_codebooks + 1].tolist()
invalid = set(invalid_req_indices)
self._fast_audio_direct_rows = len(req_ids) if not invalid and all(v or d for v, d in zip(valid, done)) else 0
# Keep the codec-row rank on terminal/invalid steps: a 1-D empty
# value would replace previously accumulated full-response rows.
empty = codes.new_empty((0, self.num_codebooks))
rows = [codes[i : i + 1] if valid[i] and i not in invalid else empty for i in range(len(req_ids))]
return {"codes": {"audio": rows}}
def finalize_multimodal_outputs_from_cpu_snapshot(self, payload):
"""Pure per-step conversion; never reads mutable decode/request state."""
if not payload or "_higgs_audio_snapshot" not in payload:
return payload
staging = payload["_higgs_audio_snapshot"]
if staging.device.type != "cpu":
raise RuntimeError("Higgs snapshot finalized before D2H")
codes = staging[:, : self.num_codebooks].clone()
valid = staging[:, self.num_codebooks].tolist()
invalid = set(payload["_higgs_invalid_rows"])
# Keep the codec-row rank on terminal/invalid steps: a 1-D empty
# value would replace previously accumulated full-response rows.
empty = codes.new_empty((0, self.num_codebooks))
return {
"codes": {
"audio": [codes[i : i + 1] if valid[i] and i not in invalid else empty for i in range(staging.shape[0])]
}
}
# ------------------------------------------------------------------ postprocess
def postprocess(
self,
@@ -1450,6 +1711,20 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
staging[:, num_codebooks].copy_(valid_full.to(torch.int32))
staging[:, num_codebooks + 1].copy_(done_full.to(torch.int32))
self._finish_audio_staging(staging, num_rows, device, num_rows if all_rows else int(rows.numel()))
def _finish_audio_staging(self, staging, num_rows, device, active_rows):
if getattr(self, "_in_audio_sample_graph", False):
return
if getattr(self, "use_async_omni_output", False):
# Own this step's GPU values before the next graph replay. The
# runner copies the snapshot on its output stream and waits there.
self._async_audio_gpu_staging = staging[:num_rows].clone()
self._last_audio_host_staging = None
self._last_audio_staging_event = None
self._last_audio_codes = None
self._decode_active_audio_count = active_rows
return
host = self._get_audio_host_staging_buffer(num_rows)
host.copy_(staging, non_blocking=True)
if device.type == "cuda":
@@ -1459,7 +1734,7 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
else:
self._last_audio_staging_event = None
self._decode_active_audio_count = num_rows if all_rows else int(rows.numel())
self._decode_active_audio_count = active_rows
# Host staging is the authoritative postprocess path. Keeping another
# full GPU codes buffer alive adds fill/copy work on the hot path.
self._last_audio_codes = None
@@ -1514,7 +1789,24 @@ class HiggsAudioV3TalkerForConditionalGeneration(nn.Module):
fallback = x.argmax(dim=-1)
safe_x = torch.where(all_masked.unsqueeze(-1), torch.zeros_like(x), x)
probs = safe_x.softmax(dim=-1)
if sampling_metadata.generators:
if getattr(self, "_audio_graph_noise", None) is not None:
torch._assert_async(torch.isfinite(probs).all(), "Audio sampling probabilities must be finite")
sampled = probs.div(self._audio_graph_noise).argmax(dim=-1)
elif probs.is_cuda:
# Match torch.multinomial's single-sample exponential race, but
# validate the whole batch asynchronously. The original per-request
# calls each copy validation scalars to the host before drawing.
torch._assert_async(torch.isfinite(probs).all(), "Audio sampling probabilities must be finite")
q = torch.empty_like(probs)
if sampling_metadata.generators:
from vllm_omni.utils.seeded_exponential import fill_exponential_rows
rows = int(probs.shape[0]) // num_codebooks
fill_exponential_rows(q, [sampling_metadata.generators.get(i) for i in range(rows)])
else:
q.exponential_()
sampled = probs.div(q).argmax(dim=-1)
elif sampling_metadata.generators:
sampled = torch.cat(
[
torch.multinomial(
@@ -0,0 +1,320 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Higgs delay-pattern sampling and owned audio output on Model Runner V2."""
from typing import Any
import numpy as np
import torch
from vllm.logger import init_logger
from vllm.v1.sample.logits_processor import LogitsProcessors
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.worker.gpu.input_batch import get_num_sampled_and_rejected
from vllm.v1.worker.gpu.sample.output import SamplerOutput
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
from vllm_omni.worker_v2.omni_sampler import OmniSampler, OmniSamplingOutput
logger = init_logger(__name__)
class HiggsModelState(OmniModelState):
def __init__(self, vllm_config, model, encoder_cache, device):
super().__init__(vllm_config, model, encoder_cache, device)
model._use_external_decode_cudagraph = True
# Fix decode-state addresses before any sampling graph can capture them.
model._ensure_decode_state_capacity(max(self.max_num_tokens, 128), device)
logger.info("Higgs MRV2 custom sampler and owned audio snapshots enabled")
if getattr(model.config, "audio_mrv2_static_inputs", False):
self._static_inputs_embeds = torch.zeros(
(self.max_num_tokens, model.model.embed_tokens.weight.shape[1]),
dtype=self.dtype,
device=device,
)
self.direct_payload = bool(getattr(model.config, "audio_mrv2_direct_payload", False))
self.sampling_slots = None
self.request_slots = {}
if getattr(model.config, "audio_mrv2_slot_parameters", False):
capacity = self.scheduler_config.max_num_seqs
self.sampling_slots = {
"temperature": torch.zeros(capacity, device=device),
"top_p": torch.ones(capacity, device=device),
"top_k": torch.full((capacity,), -1, dtype=torch.long, device=device),
"zeros": torch.zeros(capacity, device=device),
"ones": torch.ones(capacity, device=device),
}
self.requests = {}
self.generators = {}
self._ensure_slot_capacity(self.scheduler_config.max_num_seqs)
self.metadata_key = None
self.metadata = None
logger.info(
"Higgs MRV2 options: static=%s slot_parameters=%s direct_payload=%s",
self._static_inputs_embeds is not None,
self.sampling_slots is not None,
self.direct_payload,
)
if not model.use_async_omni_output:
raise ValueError("Higgs MRV2 requires audio_async_payload; use higgs_multimodal_qwen3_mrv2_h200.yaml")
def _ensure_slot_capacity(self, slots):
"""Per-slot prompt facts for vectorized step classification."""
current = getattr(self, "prompt_len_np", None)
if current is not None and len(current) >= slots:
return
size = max(slots, 2 * (0 if current is None else len(current)))
old_len, old_tail = current, getattr(self, "prompt_audio_tail_np", None)
self.prompt_len_np = np.zeros(size, dtype=np.int64)
self.prompt_audio_tail_np = np.zeros(size, dtype=bool)
if current is not None:
self.prompt_len_np[: len(old_len)] = old_len
self.prompt_audio_tail_np[: len(old_tail)] = old_tail
def add_request(self, req_index, new_req_data):
params = new_req_data.sampling_params
is_warmup = str(new_req_data.req_id).startswith("_warmup_")
if not is_warmup and (
params.frequency_penalty != 0
or params.presence_penalty != 0
or params.repetition_penalty != 1
or params.logprobs is not None
or params.prompt_logprobs is not None
or params.min_tokens != 0
or params.allowed_token_ids
or params.bad_words
or params.logit_bias
or params.min_p != 0
):
raise ValueError("Higgs MRV2 currently supports temperature/top-k/top-p sampling without text penalties")
super().add_request(req_index, new_req_data)
self.requests[new_req_data.req_id] = new_req_data
self.request_slots[new_req_data.req_id] = req_index
if self.sampling_slots is not None:
for name in ("temperature", "top_p", "top_k"):
self.sampling_slots[name][req_index : req_index + 1].fill_(getattr(params, name))
self.metadata_key = None
prompt = new_req_data.prompt_token_ids or []
self._ensure_slot_capacity(req_index + 1)
self.prompt_len_np[req_index] = len(prompt)
self.model._resolve_token_ids()
self.prompt_audio_tail_np[req_index] = bool(prompt) and prompt[-1] == self.model._audio_continuation_id
if params.seed is not None:
self.generators[new_req_data.req_id] = torch.Generator(device=self.device).manual_seed(params.seed)
def remove_request(self, req_index_or_id):
index = self._resolve_req_index(req_index_or_id)
if index is not None:
req_id = self.intermediate_buffer.buffers[index].get("req_id")
if req_id is not None:
self.model.on_requests_finished({req_id})
self.requests.pop(req_id, None)
self.request_slots.pop(req_id, None)
self.generators.pop(req_id, None)
self.metadata_key = None
super().remove_request(req_index_or_id)
def run_preprocess(self, input_batch, model_inputs, req_states=None, mtp_batch_descriptor_dispatcher=None):
model = self.model
model._resolve_token_ids()
# Every row must have an audio-continuation prompt whose prefill ends
# within this step; one vectorized check replaces a per-row loop.
n = input_batch.num_reqs
slots = input_batch.idx_mapping_np[:n]
end = req_states.num_computed_prefill_tokens[slots] + input_batch.num_scheduled_tokens[:n]
audio_mode = bool(np.all(self.prompt_audio_tail_np[slots] & (end >= self.prompt_len_np[slots])))
model.update_decode_step_metadata(
input_ids=model_inputs["input_ids"][: input_batch.num_tokens],
positions=input_batch.positions,
omni_query_start_loc=input_batch.query_start_loc[: input_batch.num_reqs + 1],
req_ids=input_batch.req_ids,
audio_prompt_mode_rows=input_batch.num_reqs if audio_mode else 0,
)
if self._static_inputs_embeds is not None:
self._prepare_static_embeddings(input_batch, model_inputs)
def _prepare_static_embeddings(self, input_batch, model_inputs):
# Feedback and reference substitution are request-dependent and belong
# outside the captured backbone. Use only actual tokens: graph padding
# must not change the one-token-per-request decode classification.
n = input_batch.num_tokens
ids = model_inputs["input_ids"][:n]
if self._fused_decode_embeddings(input_batch, ids):
return
safe_ids = torch.where(ids < 0, torch.zeros_like(ids), ids)
embeds = self.model.model.embed_tokens(safe_ids)
info = model_inputs.get("model_intermediate_buffer")
if input_batch.has_prefill and info:
embeds = self.model._apply_ref_audio_substitution(
embeds,
ids,
input_batch.positions[:n],
info,
)
embeds = self._apply_audio_feedback(embeds, ids, input_batch)
self._static_inputs_embeds[:n].copy_(embeds)
padded = input_batch.num_tokens_after_padding
self._static_inputs_embeds[n:padded].zero_()
def _fused_decode_embeddings(self, input_batch, ids) -> bool:
"""Pure decode steps: token/feedback embeddings and padding in one launch."""
model = self.model
if (
input_batch.has_prefill
or input_batch.num_tokens != input_batch.num_reqs
or not ids.is_cuda
or not getattr(model, "_use_external_decode_cudagraph", False)
):
return False
text = getattr(model.model.embed_tokens, "weight", None)
audio = getattr(model.multimodal_embedding, "weight", None)
if text is None or audio is None or text.dtype != self._static_inputs_embeds.dtype:
return False
from .step_kernels import decode_embeddings
n = int(ids.numel())
model._ensure_decode_state_capacity(n, ids.device)
decode_embeddings(
self._static_inputs_embeds,
ids,
text,
audio,
model._decode_last_codes,
model._decode_has_codes,
int(input_batch.num_tokens_after_padding),
int(model.multimodal_embedding.vocab_size),
)
return True
def _apply_audio_feedback(self, embeds, ids, input_batch):
if input_batch.num_tokens == input_batch.num_reqs:
return self.model._apply_audio_feedback(embeds, ids)
# Every scheduled request has a nonempty span. Gather its first token
# for all rows, then mask on-device. Boolean indexing would first ask
# the GPU how many rows matched, synchronizing every mixed prefill.
n = input_batch.num_reqs
qsl = input_batch.query_start_loc[: n + 1]
starts = qsl[:-1].long()
model = self.model
model._ensure_decode_state_capacity(n, embeds.device)
audio = model.multimodal_embedding(model._decode_last_codes[:n]).to(embeds.dtype)
use_audio = model._decode_has_codes[:n] & ((qsl[1:] - qsl[:-1]) == 1)
current = embeds.index_select(0, starts)
result = embeds.clone()
result.index_copy_(0, starts, torch.where(use_audio[:, None], audio, current))
return result
def run_postprocess(self, hidden_states, input_batch):
self.model.finish_decode_step_forward()
def postprocess_model_output(self, model_output, input_batch, req_states):
return model_output, None
def sampling_metadata(self, req_ids, slots=None):
key = tuple(req_ids)
if self.metadata_key != key:
params = [self.requests[r].sampling_params for r in req_ids]
n = len(params)
if self.sampling_slots is not None:
if slots is None:
slots = torch.tensor([self.request_slots[r] for r in req_ids], device=self.device)
temperature, top_p, top_k = (
self.sampling_slots[name].index_select(0, slots) for name in ("temperature", "top_p", "top_k")
)
zeros = self.sampling_slots["zeros"][:n]
ones = self.sampling_slots["ones"][:n]
else:
temperature = torch.tensor([p.temperature for p in params], device=self.device)
top_p = torch.tensor([p.top_p for p in params], device=self.device)
top_k = torch.tensor([p.top_k for p in params], device=self.device)
zeros = torch.zeros(n, device=self.device)
ones = torch.ones(n, device=self.device)
self.metadata = SamplingMetadata(
temperature=temperature,
all_greedy=all(p.temperature == 0 for p in params),
all_random=all(p.temperature != 0 for p in params),
top_p=top_p,
top_k=top_k,
generators={i: self.generators[r] for i, r in enumerate(req_ids) if r in self.generators},
max_num_logprobs=None,
no_penalties=True,
prompt_token_ids=None,
frequency_penalties=zeros,
presence_penalties=zeros,
repetition_penalties=ones,
output_token_ids=[[] for _ in params],
allowed_token_ids_mask=None,
bad_words_token_ids={},
logitsprocs=LogitsProcessors(),
)
self.metadata_key = key
return self.metadata
def custom_sampler(self, sampler):
return HiggsSampler(sampler, self), None
def finalize_audio_snapshot(self, payload: dict[str, Any], num_sampled: list[int]):
if payload and "_higgs_audio_snapshot" in payload and getattr(self, "direct_payload", False):
from vllm_omni.worker_v2.output_snapshot import RequestOutputSnapshot
snapshot = payload["_higgs_audio_snapshot"]
if snapshot.device.type != "cpu":
raise RuntimeError("Higgs snapshot finalized before D2H")
codes = snapshot[:, : self.model.num_codebooks].clone()
valid = snapshot[:, self.model.num_codebooks].tolist()
invalid = set(payload.get("_higgs_invalid_rows", ()))
# One split creates every row view; per-row slicing cost one
# dispatcher call per request on the output-materialization path.
rows = torch.split(codes, 1)
return RequestOutputSnapshot(
[
{"codes.audio": rows[i]} if valid[i] and n and i not in invalid else None
for i, n in enumerate(num_sampled)
]
)
if payload and "_higgs_audio_snapshot" in payload:
payload = dict(payload)
payload["_higgs_invalid_rows"] = tuple(i for i, n in enumerate(num_sampled) if n == 0)
return self.model.finalize_multimodal_outputs_from_cpu_snapshot(payload)
class HiggsSampler(OmniSampler):
"""Higgs audio sampling registered through the upstream sampler factory."""
def __init__(self, base_sampler, state: HiggsModelState):
super().__init__(base_sampler)
self.state = state
def sample_step(self, hidden_states, input_batch, req_states, grammar_output, standard_sample):
# Upstream warmup exercises its text sampler, including grammar and
# penalties, with synthetic non-audio prompts. Keep that path intact.
if all(str(r).startswith("_warmup_") for r in input_batch.req_ids):
return super().sample_step(hidden_states, input_batch, req_states, grammar_output, standard_sample)
if grammar_output is not None or input_batch.num_draft_tokens:
raise ValueError("Higgs MRV2 does not support grammar or speculative sampling")
metadata = self.state.sampling_metadata(input_batch.req_ids, input_batch.idx_mapping[: input_batch.num_reqs])
hidden = hidden_states[input_batch.logits_indices]
logits = self.state.model.compute_logits(hidden, metadata)
sampled = self.state.model.sample(logits, metadata)
count, rejected = get_num_sampled_and_rejected(
torch.ones(input_batch.num_reqs, dtype=torch.int32, device=hidden.device),
input_batch.seq_lens,
input_batch.cu_num_logits,
input_batch.idx_mapping,
req_states.prefill_len.gpu,
)
output = SamplerOutput(sampled.sampled_token_ids, sampled.logprobs_tensors, None, count, rejected)
payload = self.state.model.post_sample_multimodal_outputs(
req_ids=input_batch.req_ids,
invalid_req_indices=[],
multimodal_outputs=None,
)
return OmniSamplingOutput(
output,
count,
rejected,
payload,
include_hidden_states=False,
owns_multimodal_outputs=True,
finalize_multimodal=self.state.finalize_audio_snapshot,
)
@@ -0,0 +1,68 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Fused movement of model-owned delay state when a request batch changes."""
import torch
from vllm.triton_utils import tl
from vllm.triton_utils import triton as tr
@tr.jit(do_not_specialize=["count"])
def _move(
indices,
source_codes,
source_has,
source_delay,
source_eoc,
source_done,
dest_codes,
dest_has,
dest_delay,
dest_eoc,
dest_done,
count,
books: tl.constexpr,
gather: tl.constexpr,
block: tl.constexpr,
):
row = tl.program_id(0)
col = tl.arange(0, block)
if gather:
encoded = tl.load(indices + row)
fresh = encoded < 0
src = tl.where(fresh, -encoded - 1, encoded)
dst = row
else:
src = tl.load(indices + row)
dst = tl.load(indices + count + row)
fresh = False
codes = tl.load(source_codes + src * books + col, col < books, 0)
has = tl.load(source_has + src)
delay = tl.load(source_delay + src)
eoc = tl.load(source_eoc + src)
done = tl.load(source_done + src)
tl.store(dest_codes + dst * books + col, tl.where(fresh, 0, codes), col < books)
tl.store(dest_has + dst, tl.where(fresh, 0, has))
tl.store(dest_delay + dst, tl.where(fresh, 0, delay))
tl.store(dest_eoc + dst, tl.where(fresh, -1, eoc))
tl.store(dest_done + dst, tl.where(fresh, 0, done))
def sync_state(model, previous_rows, pool_rows, current_rows):
# One owned pinned upload, ordered on the decode stream. Separate scatter
# and gather kernels provide a global ordering point for moved pool rows.
device = model._decode_has_codes.device
packed = torch.tensor(previous_rows + pool_rows + current_rows, dtype=torch.int64, pin_memory=True).to(
device, non_blocking=True
)
names = ("last_codes", "has_codes", "delay_count", "eoc_countdown", "generation_done")
decode = [getattr(model, "_decode_" + name) for name in names]
pool = [getattr(model, "_state_pool_" + name) for name in names]
n = len(previous_rows)
block = tr.next_power_of_2(model.num_codebooks)
if n:
_move[(n,)](packed, *decode, *pool, n, model.num_codebooks, False, block)
if current_rows:
_move[(len(current_rows),)](
packed[2 * n :], *pool, *decode, len(current_rows), model.num_codebooks, True, block
)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""higgs-audio v3 pipeline: Talker (text -> 8-codebook codec) -> Code2Wav (codec -> 24 kHz PCM).
Two delivery modes are wired here:
@@ -19,6 +19,9 @@ from vllm_omni.config.stage_config import (
StageExecutionType,
StagePipelineConfig,
)
from vllm_omni.outputs.output_modality import TensorAccumulationStrategy, register_key_accumulation_strategy
register_key_accumulation_strategy("codes.audio", TensorAccumulationStrategy.CONCAT_DIM0)
_PROC = "vllm_omni.model_executor.stage_input_processors.higgs_audio_v3"
@@ -34,6 +37,8 @@ HIGGS_AUDIO_V3_PIPELINE = PipelineConfig(
execution_type=StageExecutionType.LLM_AR,
input_sources=(),
owns_tokenizer=True,
supports_native_mrv2_data_plane=True,
custom_process_next_stage_input_func=f"{_PROC}.talker2code2wav_full_payload",
engine_output_type="latent",
# stop_token_ids: the model-owned sampler forces eos at ramp-down
# completion. Safety stops from the actual V3 checkpoint:
@@ -54,7 +59,9 @@ HIGGS_AUDIO_V3_PIPELINE = PipelineConfig(
final_output_type="audio",
engine_output_type="audio",
model_arch="HiggsAudioV3Code2WavForConditionalGeneration",
sync_process_input_func=f"{_PROC}.talker2code2wav",
sync_process_input_func=f"{_PROC}.talker2code2wav_token_only",
supports_native_mrv2_data_plane=True,
requires_full_payload_input=True,
sampling_constraints={"detokenize": True},
),
),
@@ -0,0 +1,150 @@
# ruff: noqa: N803
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Fused per-step Higgs kernels for the MRV2 decode loop.
Each replaces a chain of small eager launches that ran on every model step
(terminal-row restore, prefill reset and audio-tail validation before dense
sampling; token and feedback embeddings on pure decode steps).
"""
import torch
from vllm.triton_utils import tl, triton
@triton.jit
def _step_tail_guard_kernel(
ids_ptr,
qsl_ptr,
has_codes_ptr,
done_ptr,
delay_ptr,
eoc_ptr,
error_ptr,
num_rows,
audio_id,
eos_id,
HAS_QSL: tl.constexpr,
PROMPT_MODE: tl.constexpr,
BLOCK: tl.constexpr,
):
rows = tl.arange(0, BLOCK)
mask = rows < num_rows
if HAS_QSL:
start = tl.load(qsl_ptr + rows, mask=mask, other=0)
end = tl.load(qsl_ptr + rows + 1, mask=mask, other=1)
valid = end > 0
tail = tl.load(ids_ptr + tl.maximum(end - 1, 0), mask=mask, other=audio_id)
prefill = mask & ((end - start) > 1)
else:
valid = mask
tail = tl.load(ids_ptr + rows, mask=mask, other=audio_id)
prefill = rows < 0
done = tl.load(done_ptr + rows, mask=mask, other=0) != 0
has = tl.load(has_codes_ptr + rows, mask=mask, other=0) != 0
if PROMPT_MODE:
# An in-flight EOS row after retirement is terminal, never a new stream.
done = done | (tail == eos_id)
# New prefill rows start a fresh delay-pattern stream.
done = done & ~prefill
has = has & ~prefill
tl.store(done_ptr + rows, done, mask=mask)
tl.store(has_codes_ptr + rows, has, mask=mask)
tl.store(delay_ptr + rows, 0, mask=prefill)
tl.store(eoc_ptr + rows, -1, mask=prefill)
ok = (tail == audio_id) & valid
if PROMPT_MODE:
ok = ok | has | done
tl.store(error_ptr, tl.max((mask & ~ok).to(tl.int32), axis=0))
def step_tail_guard(
ids: torch.Tensor,
qsl: torch.Tensor | None,
has_codes: torch.Tensor,
done: torch.Tensor,
delay: torch.Tensor,
eoc: torch.Tensor,
error: torch.Tensor,
*,
audio_id: int,
eos_id: int,
prompt_mode: bool,
) -> None:
"""Fused terminal-row restore, prefill reset and audio-tail validation.
One launch replaces the index/compare/reset chains that ran before every
dense sample, for pure decode and mixed prefill steps alike; ``error``
becomes nonzero if any row is not an audio row. ``qsl`` (query start
locations) selects each row's last token; ``None`` means one token per row.
"""
rows = int(has_codes.numel())
_step_tail_guard_kernel[(1,)](
ids,
ids if qsl is None else qsl,
has_codes,
done,
delay,
eoc,
error,
rows,
audio_id,
eos_id,
HAS_QSL=qsl is not None,
PROMPT_MODE=prompt_mode,
BLOCK=max(16, triton.next_power_of_2(rows)),
)
@triton.jit
def _decode_embeddings_kernel(
out_ptr,
ids_ptr,
text_weight_ptr,
audio_weight_ptr,
codes_ptr,
has_codes_ptr,
num_rows,
hidden,
audio_vocab,
BOOKS: tl.constexpr,
BLOCK: tl.constexpr,
):
row = tl.program_id(0)
cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
mask = cols < hidden
out = out_ptr + row.to(tl.int64) * hidden + cols
if row >= num_rows:
# Graph padding rows own no request and must stay zero.
tl.store(out, tl.zeros((BLOCK,), dtype=out_ptr.dtype.element_ty), mask=mask)
return
if tl.load(has_codes_ptr + row) != 0:
# Audio feedback: sum of the previous frame's codebook embeddings,
# accumulated in float32 and rounded once like ``embedding(...).sum()``.
acc = tl.zeros((BLOCK,), dtype=tl.float32)
for book in range(BOOKS):
code = tl.load(codes_ptr + row * BOOKS + book).to(tl.int64) + book * audio_vocab
acc += tl.load(audio_weight_ptr + code * hidden + cols, mask=mask, other=0.0).to(tl.float32)
tl.store(out, acc.to(out_ptr.dtype.element_ty), mask=mask)
else:
token = tl.maximum(tl.load(ids_ptr + row), 0).to(tl.int64)
tl.store(out, tl.load(text_weight_ptr + token * hidden + cols, mask=mask), mask=mask)
def decode_embeddings(
out: torch.Tensor,
ids: torch.Tensor,
text_weight: torch.Tensor,
audio_weight: torch.Tensor,
codes: torch.Tensor,
has_codes: torch.Tensor,
padded_rows: int,
audio_vocab: int,
) -> None:
"""One-token-per-row input embeddings with audio feedback, into ``out[:padded_rows]``."""
rows, hidden = int(ids.numel()), int(out.shape[1])
books = int(codes.shape[1])
block = 1024
_decode_embeddings_kernel[(padded_rows, triton.cdiv(hidden, block))](
out, ids, text_weight, audio_weight, codes, has_codes, rows, hidden, audio_vocab, BOOKS=books, BLOCK=block
)