[New Model] support nemotron Audex (#4976)

Signed-off-by: Yuekai Zhang <zhangyuekai@foxmail.com>
Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-07-28 03:58:22 +00:00
1 parent f2c5152df0
commit 5014fea4a0
64 files changed
+7760 -39

No files matched your search

+3 -1
View File
@@ -852,7 +852,9 @@ def run_headless(args: TrackingNamespace) -> None:
model,
stage_configs_path,
args_dict,
trust_remote_code=bool(getattr(args, "trust_remote_code", False)),
# store_true cannot express an explicit False: absent maps to None
# ("not specified") so the deploy yaml's per-stage value applies.
trust_remote_code=getattr(args, "trust_remote_code", None) or None,
deploy_config_path=args_dict.get("deploy_config"),
stage_overrides=stage_overrides,
strategy_config_path=args_dict.get("strategy_config"),
@@ -100,6 +100,10 @@ _HIGGS_V3_TTS_MODEL_STAGES = {"higgs_audio_v3"}
_GLM_TTS_MODEL_STAGES = {"glm_tts"}
_STEP_AUDIO2_TTS_MODEL_STAGES = {"step_audio2_thinker"}
_INDEXTTS2_TTS_MODEL_STAGES = {"indextts2_talker"}
# audex_omni covers the audex_s2s S2S deployment, whose
# TTS pass uses the same /v1/audio/speech surface.
_AUDEX_TTS_MODEL_STAGES = {"audex_thinker", "audex_omni"}
_AUDEX_TTA_MODEL_STAGES = {"audex_tta_thinker"}
_TTS_MODEL_STAGES: set[str] = (
_VOXTRAL_TTS_MODEL_STAGES
| _QWEN3_TTS_MODEL_STAGES
@@ -117,6 +121,8 @@ _TTS_MODEL_STAGES: set[str] = (
| _GLM_TTS_MODEL_STAGES
| _STEP_AUDIO2_TTS_MODEL_STAGES
| _INDEXTTS2_TTS_MODEL_STAGES
| _AUDEX_TTS_MODEL_STAGES
| _AUDEX_TTA_MODEL_STAGES
)
_SAMPLING_MAX_TOKENS_TTS_MODEL_TYPES = {
"fish_tts",
@@ -127,7 +133,13 @@ _SAMPLING_MAX_TOKENS_TTS_MODEL_TYPES = {
"higgs_audio_v2",
"higgs_audio_v3",
"indextts2",
"audex",
"audex_tta",
}
# Audex contract: zero-codec / invalid generations arrive as empty terminal
# payloads and must fail the request, never serialize as a successful empty
# WAV. Covers both the TTS ("audex") and TTA ("audex_tta") pipelines.
_AUDEX_NO_AUDIO_GUARD_MODEL_TYPES = frozenset({"audex", "audex_tta"})
_TTS_LANGUAGES = frozenset(
{
"Auto",
@@ -493,6 +505,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
self._tts_tokenizer = None
self._voxcpm2_tokenizer = None
self._audex_tokenizer = None
self._audex_tta_rvq = None
self._voxcpm2_split_map: dict[int, list[int]] = {}
logger.info("Loaded %d supported speakers: %s", len(self.supported_speakers), sorted(self.supported_speakers))
@@ -673,12 +687,19 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
def _find_tts_stage(self):
"""Find and return the TTS stage config, or None if not found."""
all_stages = {getattr(stage.engine_args, "model_stage", None) for stage in self.engine_client.stage_configs}
for stage in self.engine_client.stage_configs:
engine_args = stage.engine_args
model_stage = engine_args.model_stage
model_arch = getattr(engine_args, "model_arch", None)
worker_type = getattr(engine_args, "worker_type", None)
if model_stage in _TTS_MODEL_STAGES:
# The audio-capable Audex thinker is only speech-capable when
# deployed WITH the speech decoder (audex_s2s);
# the thinker-only deployment is text-final and must not
# accept /v1/audio/speech requests.
if model_stage == "audex_omni" and "audex_code2wav" not in all_stages:
continue
return stage
# Ming dense identifies its AR entry stage by architecture because
# it does not use a dedicated TTS model_stage value.
@@ -729,6 +750,10 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return "step_audio2"
if model_stage in _INDEXTTS2_TTS_MODEL_STAGES:
return "indextts2"
if model_stage in _AUDEX_TTS_MODEL_STAGES:
return "audex"
if model_stage in _AUDEX_TTA_MODEL_STAGES:
return "audex_tta"
return None
def _get_custom_voice_dir(self) -> str | None:
@@ -2318,6 +2343,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
if chunk_np.ndim > 1:
chunk_np = chunk_np.squeeze()
if self._tts_model_type in _AUDEX_NO_AUDIO_GUARD_MODEL_TYPES and int(np.size(chunk_np)) == 0:
# Zero-size chunks must not emit a WAV header or count
# as first audio; the post-loop guard below needs to
# see an audio-less stream to fail the request.
continue
# For WAV format, emit header before first audio chunk
if response_format == "wav" and first_chunk:
# Assert that sample rate has been set from chunk metadata (not just default)
@@ -2349,6 +2379,10 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
yield audio_bytes, sample_rate_val
else:
yield audio_bytes
if self._tts_model_type in _AUDEX_NO_AUDIO_GUARD_MODEL_TYPES and first_audio_chunk_s is None:
# Audex contract: zero codec tokens must abort the stream, not
# complete it cleanly with zero audio bytes.
raise ValueError("Audex produced no audio (the thinker emitted zero or invalid codec tokens)")
self._mark_ref_audio_artifact_ready_for_request(request_id)
artifact_ready = True
total_ms = (time.perf_counter() - stream_start_s) * 1000.0
@@ -2822,6 +2856,140 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
return {"prompt_token_ids": prompt_ids}
def _get_audex_tokenizer(self):
"""Load (once per process) the Audex thinker tokenizer for CFG/TTA prompts.
The folder follows the serving stage: the full-pipeline thinker
(``audex_omni``) tokenizes with ``checkpoint_folder_full``; the TTS
and TTA thinkers use ``checkpoint_folder_audiogen``.
"""
if self._audex_tokenizer is None:
from transformers import AutoTokenizer
from vllm_omni.model_executor.models.audex.checkpoint import ensure_audex_snapshot
stage = getattr(getattr(self._tts_stage, "engine_args", None), "model_stage", None)
if stage == "audex_omni":
profile, folder = "full", "checkpoint_folder_full"
elif stage == "audex_tta_thinker":
profile, folder = "tta", "checkpoint_folder_audiogen"
else:
profile, folder = "tts", "checkpoint_folder_audiogen"
# The serving model_config may already hold the RESOLVED per-stage
# checkpoint folder (stage init joins model_subdir onto the
# snapshot root); joining again would produce a non-existent path
# that transformers then mistakes for a repo id.
model_path = os.path.normpath(self.engine_client.model_config.model)
if os.path.basename(model_path).startswith("checkpoint_folder"):
root = os.path.dirname(model_path)
else:
root = ensure_audex_snapshot(model_path, profile=profile)
self._audex_tokenizer = AutoTokenizer.from_pretrained(os.path.join(root, folder))
return self._audex_tokenizer
def _inject_audex_tta_args(self, request_id: str, prompt: Any, stage0_params: Any) -> Any:
"""Complete the Audex TTA contract on a CLONE of the stage-0 params.
Always attaches the RVQ phase-mask contract (required for token
validity) and the CFG pair contract at the official default scale
3.0 unless the caller passed ``cfg_scale`` (1.0 disables guidance).
Returns the cloned params; the input is never mutated. On the
no-extra_params online path the input is an element of the engine's
SHARED ``default_sampling_params_list`` — writing per-request pair
state (``cfg_pair_id``/``cfg_null_prompt``) into it would race
concurrent requests and leak stale CFG metadata into later ones.
"""
import copy
from vllm_omni.model_executor.models.audex.prompt import build_tta_null_prompt
from vllm_omni.model_executor.models.audex.tta import build_tta_phase_token_ids
cond_prompt = prompt.get("prompt") if isinstance(prompt, dict) else prompt
if not isinstance(cond_prompt, str) or not cond_prompt:
raise ValueError("Audex TTA requires the adapter-built caption prompt")
stage0_params = copy.deepcopy(stage0_params)
tokenizer = self._get_audex_tokenizer()
if self._audex_tta_rvq is None:
phase_token_ids, start_tid, end_tid = build_tta_phase_token_ids(tokenizer)
self._audex_tta_rvq = {
"phase_token_ids": phase_token_ids,
"start_tid": start_tid,
"end_tid": end_tid,
# Official generation cap (decode truncates at 500 frames).
"codec_cap": 4000,
# The TTA prompt ends with <audiogen_start>.
"start_in_prompt": True,
}
extra_args = getattr(stage0_params, "extra_args", None)
if extra_args is None:
extra_args = {}
stage0_params.extra_args = extra_args
extra_args["tta_rvq"] = self._audex_tta_rvq
cfg_scale = extra_args.get("cfg_scale")
cfg_scale = 3.0 if cfg_scale is None else float(cfg_scale)
if cfg_scale <= 1.0:
extra_args.pop("cfg_scale", None)
return stage0_params
extra_args.update(
{
"cfg_scale": cfg_scale,
"cfg_role": "cond",
"cfg_pair_id": request_id,
"cfg_null_prompt": build_tta_null_prompt(cond_prompt, tokenizer),
}
)
return stage0_params
def _inject_audex_cfg_pair_args(self, request_id: str, prompt: Any, stage0_params: Any) -> Any:
"""Complete the Audex CFG contract on a CLONE of the stage-0 params.
The adapter validated ``cfg_scale``; here (where the final request id
exists) the cond role, pair id, and the length-matched null prompt are
attached. ``cfg_scale`` absent/1.0 returns a clone value-identical to
the non-CFG flow (the key is dropped rather than forwarded).
Returns the cloned params; the input is never mutated (it may be an
element of the engine's shared ``default_sampling_params_list`` —
see ``_inject_audex_tta_args``).
"""
import copy
stage0_params = copy.deepcopy(stage0_params)
extra_args = getattr(stage0_params, "extra_args", None)
if not extra_args or extra_args.get("cfg_scale") is None:
if extra_args:
extra_args.pop("cfg_scale", None)
return stage0_params
cfg_scale = float(extra_args["cfg_scale"])
if cfg_scale <= 1.0:
extra_args.pop("cfg_scale", None)
return stage0_params
from vllm_omni.model_executor.models.audex.prompt import build_null_prompt
cond_prompt = prompt.get("prompt") if isinstance(prompt, dict) else prompt
if not isinstance(cond_prompt, str) or not cond_prompt:
raise ValueError("Audex CFG requires the adapter-built text prompt")
null_prompt = build_null_prompt(cond_prompt, self._get_audex_tokenizer())
extra_args.update(
{
"cfg_scale": cfg_scale,
"cfg_role": "cond",
"cfg_pair_id": request_id,
"cfg_null_prompt": null_prompt,
}
)
# Guided decoding sharpens the distribution; the unguided default
# temperature (0.1) adds excess sampling noise under CFG. Measured
# on the en-24 gate corpus at cfg 1.5: temp 0.1 -> CER 7.31%,
# temp 0.05 -> CER 6.87% (unguided baseline 7.24%).
stage0_params.temperature = 0.05
return stage0_params
def _apply_cosyvoice3_dynamic_tokens(
self,
sampling_params_list: list,
@@ -3205,6 +3373,17 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
sampling_params_list[0].extra_args.update(request.extra_params)
logger.info("Applied extra_params: %s", request.extra_params)
# Audex CFG: turn an adapter-validated cfg_scale into the engine-side
# pair contract. This must run here (not in the adapter) because the
# pair id is the final request_id, which the adapter never sees.
# The injectors return a CLONE: without extra_params above,
# sampling_params_list still holds the engine's shared default params,
# which must never carry per-request CFG state.
if self._tts_model_type == "audex" and sampling_params_list:
sampling_params_list[0] = self._inject_audex_cfg_pair_args(request_id, prompt, sampling_params_list[0])
elif self._tts_model_type == "audex_tta" and sampling_params_list:
sampling_params_list[0] = self._inject_audex_tta_args(request_id, prompt, sampling_params_list[0])
# Some TTS model defaults come from deploy YAML. Their AR
# generation length is controlled by SamplingParams.max_tokens, so only
# override it when the caller explicitly requests max_new_tokens.
@@ -3405,6 +3584,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if audio_tensor.ndim > 1:
audio_tensor = audio_tensor.squeeze()
if self._tts_model_type in _AUDEX_NO_AUDIO_GUARD_MODEL_TYPES and int(np.size(audio_tensor)) == 0:
# Audex contract: zero codec tokens must fail the request, not
# serialize as an empty-but-successful WAV.
raise ValueError("Audex produced no audio (the thinker emitted zero or invalid codec tokens)")
audio_obj = CreateAudio(
audio_tensor=audio_tensor,
sample_rate=sample_rate,
@@ -51,6 +51,8 @@ def resolve_adapter(model_type: str | None) -> type[TTSModelAdapter] | None:
# Import adapter modules for their registration side effects. Keep at the bottom
# so the registry helpers above are defined first.
from vllm_omni.entrypoints.openai.tts_adapters import ( # noqa: E402,F401
audex,
audex_tta,
cosyvoice3,
covo_audio,
fish_speech,
@@ -0,0 +1,67 @@
# SPDX-License-Identifier: Apache-2.0
"""Audex (Nemotron-Labs-Audex-2B) TTS serving adapter."""
from typing import TYPE_CHECKING
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
from vllm_omni.entrypoints.openai.tts_adapters.base import ARTTSAdapter, PreparedRequest
from vllm_omni.model_executor.models.audex.prompt import build_cond_prompt
if TYPE_CHECKING:
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
# Classifier-free guidance strength accepted on /v1/audio/speech via
# extra_params. 1.0 disables guidance (identical to omitting it); the
# official TTS quality setting is 1.5.
AUDEX_CFG_SCALE_MIN = 1.0
AUDEX_CFG_SCALE_MAX = 10.0
# Internal CFG pair-plumbing keys; injected by the serving layer once the
# request id exists, never accepted from callers.
_AUDEX_INTERNAL_CFG_KEYS = ("cfg_role", "cfg_pair_id", "cfg_null_prompt")
@register_tts_adapter
class AudexAdapter(ARTTSAdapter):
"""Plain English TTS: single built-in voice, no reference audio, optional CFG."""
stage_keys = frozenset({"audex_thinker", "audex_omni"})
name = "audex"
def validate(self, request: "OpenAICreateSpeechRequest") -> str | None:
if not request.input or not request.input.strip():
return "Audex TTS requires non-empty input text"
voice = (request.voice or "").strip().lower()
if voice not in ("", "default"):
return (
f"Audex has a single built-in voice and no voice cloning; got voice={request.voice!r}. "
"Omit 'voice' or pass 'default'."
)
if request.ref_audio is not None:
return "Audex does not support reference audio (no voice cloning)."
extra = request.extra_params or {}
for key in _AUDEX_INTERNAL_CFG_KEYS:
if key in extra:
return f"extra_params.{key} is managed internally by the server; only cfg_scale may be set."
cfg_scale = extra.get("cfg_scale")
if cfg_scale is not None:
try:
cfg_value = float(cfg_scale)
except (TypeError, ValueError):
return (
f"extra_params.cfg_scale must be a number in "
f"[{AUDEX_CFG_SCALE_MIN}, {AUDEX_CFG_SCALE_MAX}]; got {cfg_scale!r}."
)
if not (AUDEX_CFG_SCALE_MIN <= cfg_value <= AUDEX_CFG_SCALE_MAX):
return (
f"extra_params.cfg_scale must be within [{AUDEX_CFG_SCALE_MIN}, {AUDEX_CFG_SCALE_MAX}]; "
f"got {cfg_scale!r}. 1.0 disables guidance; 1.5 is the recommended quality setting."
)
return None
async def build(
self, request: "OpenAICreateSpeechRequest", sampling_params_list: list, has_inline_ref_audio: bool
) -> PreparedRequest:
prompt = {"prompt": build_cond_prompt(request.input)}
return PreparedRequest(prompt=prompt, tts_params={}, model_type="audex")
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: Apache-2.0
"""Audex (Nemotron-Labs-Audex-2B) text-to-audio serving adapter.
Caption → general audio through the ``audex_tta`` pipeline.
The adapter builds the TTA prompt; the serving layer completes the request
after the final request id exists: the RVQ phase-mask contract
(``extra_args["tta_rvq"]``) and the CFG pair contract (official default
scale 3.0 — guidance is effectively mandatory for TTA quality).
"""
from typing import TYPE_CHECKING
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
from vllm_omni.entrypoints.openai.tts_adapters.base import ARTTSAdapter, PreparedRequest
from vllm_omni.model_executor.models.audex.prompt import build_tta_cond_prompt
if TYPE_CHECKING:
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
AUDEX_TTA_DEFAULT_CFG_SCALE = 3.0
AUDEX_TTA_CFG_SCALE_MIN = 1.0
AUDEX_TTA_CFG_SCALE_MAX = 10.0
# Internal plumbing keys; injected by the serving layer, never accepted
# from callers.
_INTERNAL_KEYS = ("cfg_role", "cfg_pair_id", "cfg_null_prompt", "tta_rvq")
@register_tts_adapter
class AudexTTAAdapter(ARTTSAdapter):
"""Caption-conditioned general audio: no voices, no reference audio."""
stage_keys = frozenset({"audex_tta_thinker"})
name = "audex_tta"
def validate(self, request: "OpenAICreateSpeechRequest") -> str | None:
if not request.input or not request.input.strip():
return "Audex TTA requires a non-empty caption"
voice = (request.voice or "").strip().lower()
if voice not in ("", "default"):
return f"Audex TTA generates general audio and has no voices; got voice={request.voice!r}."
if request.ref_audio is not None:
return "Audex TTA does not support reference audio."
extra = request.extra_params or {}
for key in _INTERNAL_KEYS:
if key in extra:
return f"extra_params.{key} is managed internally by the server; only cfg_scale may be set."
cfg_scale = extra.get("cfg_scale")
if cfg_scale is not None:
try:
cfg_value = float(cfg_scale)
except (TypeError, ValueError):
return (
f"extra_params.cfg_scale must be a number in "
f"[{AUDEX_TTA_CFG_SCALE_MIN}, {AUDEX_TTA_CFG_SCALE_MAX}]; got {cfg_scale!r}."
)
if not (AUDEX_TTA_CFG_SCALE_MIN <= cfg_value <= AUDEX_TTA_CFG_SCALE_MAX):
return (
f"extra_params.cfg_scale must be within "
f"[{AUDEX_TTA_CFG_SCALE_MIN}, {AUDEX_TTA_CFG_SCALE_MAX}]; got {cfg_scale!r}. "
f"The official TTA setting is {AUDEX_TTA_DEFAULT_CFG_SCALE}; 1.0 disables guidance."
)
return None
async def build(
self, request: "OpenAICreateSpeechRequest", sampling_params_list: list, has_inline_ref_audio: bool
) -> PreparedRequest:
prompt = {"prompt": build_tta_cond_prompt(request.input)}
return PreparedRequest(prompt=prompt, tts_params={}, model_type="audex_tta")
+13 -13
View File
@@ -12,7 +12,7 @@ from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm.transformers_utils.config import get_config, get_hf_file_to_dict
from vllm.transformers_utils.repo_utils import file_or_path_exists
from vllm_omni.config.config_factory import StageConfigFactory
from vllm_omni.config.config_factory import StageConfigFactory, with_trust_remote_code_override
from vllm_omni.config.yaml_util import create_config, load_yaml_config, merge_configs
from vllm_omni.diffusion.utils.hf_utils import _looks_like_dreamzero
from vllm_omni.entrypoints.stage_utils import _to_dict
@@ -103,12 +103,7 @@ def _filter_dict_like_object(obj: dict | Any) -> dict:
return True
return isinstance(
value,
(
types.FunctionType,
types.MethodType,
types.BuiltinFunctionType,
types.BuiltinMethodType,
),
types.FunctionType | types.MethodType | types.BuiltinFunctionType | types.BuiltinMethodType,
)
result = {}
@@ -193,10 +188,10 @@ def _convert_dataclasses_to_dict(obj: Any) -> Any:
if callable(obj):
return None
# Handle lists and tuples (recurse into items)
if isinstance(obj, (list, tuple)):
if isinstance(obj, list | tuple):
return type(obj)(_convert_dataclasses_to_dict(item) for item in obj if not callable(item))
# Try to convert any dict-like object (has keys/values methods) to dict
if hasattr(obj, "keys") and hasattr(obj, "values") and not isinstance(obj, (str, bytes)):
if hasattr(obj, "keys") and hasattr(obj, "values") and not isinstance(obj, str | bytes):
try:
return _filter_dict_like_object(obj)
except (TypeError, ValueError, AttributeError):
@@ -315,7 +310,7 @@ def resolve_model_config_path(model: str) -> str:
def load_stage_configs_from_model(
model: str,
*,
trust_remote_code: bool,
trust_remote_code: bool | None,
base_engine_args: dict | None = None,
deploy_config_path: str | None = None,
stage_overrides: dict[str, dict[str, Any]] | None = None,
@@ -349,7 +344,12 @@ def load_stage_configs_from_model(
base_engine_args = {}
cli_overrides = _convert_dataclasses_to_dict(dict(base_engine_args))
cli_overrides["trust_remote_code"] = trust_remote_code
# A False inherited from the engine-args dump is the store_true flag's
# default, not an explicit choice — drop it so only the tri-state
# parameter below decides (see with_trust_remote_code_override).
if not cli_overrides.get("trust_remote_code"):
cli_overrides.pop("trust_remote_code", None)
cli_overrides = with_trust_remote_code_override(cli_overrides, trust_remote_code)
if stage_overrides:
for stage_id_str, overrides in stage_overrides.items():
for key, val in overrides.items():
@@ -559,7 +559,7 @@ def load_and_resolve_stage_configs(
stage_configs_path: str | None,
kwargs: dict | None,
*,
trust_remote_code: bool,
trust_remote_code: bool | None,
default_stage_cfg_factory: Any = None,
deploy_config_path: str | None = None,
stage_overrides: dict[str, dict[str, Any]] | None = None,
@@ -728,7 +728,7 @@ def filter_dataclass_kwargs(cls: Any, kwargs: dict) -> dict:
if origin in (list, tuple, set):
args = get_args(annotation)
inner = args[0] if args else None
if isinstance(value, (list, tuple, set)):
if isinstance(value, list | tuple | set):
return type(value)(_filter_value(v, inner) for v in value)
return value