Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: add higgs, moss, and minimax audio models

Etherlc5b234381668
diff --git a/cli.py b/cli.py
index c3fd954b52c..ab2a006282e 100644
--- a/cli.py
+++ b/cli.py
@@ -3,9 +3,7 @@
import sys
-# unsloth_cli only runs its console-script setup (stream encoding, `-np<N>`,
-# the Windows folder guard) for argv[0] == "unsloth", and it must precede the
-# command imports: commands.studio resolves STUDIO_HOME at import time.
+# Match the console-script setup before importing commands.
if __name__ == "__main__":
sys.argv[0] = "unsloth"
diff --git a/scripts/lint_workflow_triggers.py b/scripts/lint_workflow_triggers.py
index 4875671c259..0603301b63d 100644
--- a/scripts/lint_workflow_triggers.py
+++ b/scripts/lint_workflow_triggers.py
@@ -38,14 +38,10 @@ DEFAULT_WORKFLOWS_DIR = REPO_ROOT / ".github" / "workflows"
BANNED_TRIGGERS: tuple[str, ...] = ("pull_request_target",)
RESTRICTED_TRIGGERS: tuple[str, ...] = ("workflow_run",)
-# Stem, not filename: `.yaml` is scanned too, and a renamed publisher must
-# still be classified as one.
+# Match both workflow extensions by stem.
PUBLISH_WORKFLOW_STEMS: tuple[str, ...] = ("release-desktop",)
-# A workflow running this script is a "host". `pull_request` resolves the
-# workflow file from the PR merge ref, so any narrowing a PR adds to its host
-# applies to that same PR, and the gate misses the change it exists to review.
-# Hence: a bare `pull_request:`, and a step that can fail.
+# The host must run on every PR and be able to fail.
LINT_SCRIPT_NAME = "lint_workflow_triggers.py"
@@ -76,7 +72,7 @@ def _extract_cache_keys(path: Path) -> list[str]:
def _on_field(yaml_doc):
- # PyYAML resolves a bare `on:` key to the boolean True.
+ # PyYAML parses a bare `on:` key as True.
on = yaml_doc.get(True) if isinstance(yaml_doc, dict) else None
if on is None and isinstance(yaml_doc, dict):
on = yaml_doc.get("on")
@@ -87,18 +83,12 @@ def _trigger_set(yaml_doc) -> set[str]:
return _normalise_on(_on_field(yaml_doc))
-# A host runs this repo's script as a plain command with no arguments. Each
-# clause below is a way that looked satisfied while nothing was enforced: a
-# decoy path, a fake interpreter, a `|| true` (the default `run:` shell is
-# `bash -e`, no pipefail), or an argument that makes it exit early.
+# Accept only a plain invocation of this script; fail closed on wrappers.
_PYTHON_BASENAME = re.compile(r"python(3(\.\d+)?)?")
-# Allowlist, not denylist: too many flags skip the file or mask its status
-# (-c, -m, --version, and -i, which exits 0 from the REPL even after
-# sys.exit(1)). Anything unrecognised fails closed.
+# Allow only flags that preserve script execution.
_SAFE_OPTS = ("-u", "-E", "-s", "-S", "-B", "-O", "-OO", "-q")
LINT_SCRIPT_PATH = f"scripts/{LINT_SCRIPT_NAME}"
-# Safe, but they consume the next token, so the script path is not mistaken
-# for their value.
+# These options consume the next token.
_OPTS_WITH_VALUE = ("-X", "-W", "--check-hash-based-pycs")
_SHELL_OPERATORS = ("|", "&", ";", ">", "<", "`", "$(")
@@ -139,8 +129,7 @@ def _classify_lint_line(line: str) -> tuple[bool, str | None]:
return False, None
rest = args[i:]
- # Exactly the repo-relative path. A suffix match would accept a decoy at
- # /tmp/scripts/lint_workflow_triggers.py.
+ # Require the repository-relative path, not a suffix match.
if not rest or rest[0] not in (LINT_SCRIPT_PATH, f"./{LINT_SCRIPT_PATH}"):
return False, None
if len(rest) == 1:
@@ -159,13 +148,7 @@ def _classify_lint_line(line: str) -> tuple[bool, str | None]:
def _lint_step_report(run: str) -> tuple[bool, list[str]]:
- """(an enforcing invocation is present, problems with lint-ish commands).
-
- The step body must be the lint command and nothing else. Judging lines in
- isolation cannot tell a call from a definition, so an invocation parked in
- an uncalled function or a here-document would read as enforcing while
- executing nothing. Requiring a single command sidesteps shell parsing.
- """
+ """Return whether the step enforces the lint and any problems found."""
lines = [line for line in run.splitlines() if line.strip() and not line.strip().startswith("#")]
mentions = [line for line in lines if LINT_SCRIPT_NAME in line]
if not mentions:
@@ -182,11 +165,10 @@ def _lint_step_report(run: str) -> tuple[bool, list[str]]:
return enforcing, problems
-# A `shell:` template can wrap the command, e.g. `bash -c '"{0}" || true'`.
+# Shell templates can wrap the command and hide its status.
SAFE_SHELLS: tuple[str, ...] = ("bash", "sh")
-# Redirect execution without changing the command: bash sources BASH_ENV
-# before the step script, and PATH picks the interpreter.
+# These variables can redirect execution before the script runs.
UNSAFE_ENV_KEYS: tuple[str, ...] = (
"BASH_ENV",
"ENV",
@@ -235,12 +217,7 @@ def _pull_request_config_problem(yaml_doc) -> str | None:
def _lint_steps(yaml_doc) -> list[tuple[dict, dict, bool, list[str]]]:
- """(job, step, enforcing, problems) for every step that runs the lint.
-
- Reads the parsed steps rather than the raw text: a commented-out
- `# - run: python3 scripts/lint_workflow_triggers.py` executes nothing, and
- counting it as a host would let a deleted gate look wired.
- """
+ """Return every step that runs the lint and its enforcement status."""
jobs = yaml_doc.get("jobs") if isinstance(yaml_doc, dict) else None
if not isinstance(jobs, dict):
return []
@@ -304,8 +281,7 @@ def _is_truthy(value) -> bool:
def main() -> int:
- # No abbreviations: `--workflows-d` must not silently mean
- # `--workflows-dir`, or a host could smuggle it past review.
+ # Do not let abbreviated options bypass the gate.
parser = argparse.ArgumentParser(description = __doc__, allow_abbrev = False)
parser.add_argument(
"--workflows-dir",
@@ -335,9 +311,7 @@ def main() -> int:
require_host = workflows_dir.resolve() == DEFAULT_WORKFLOWS_DIR.resolve()
findings: list[str] = []
- # GitHub Actions loads BOTH `.yml` and `.yaml` from .github/workflows/, so
- # scanning only `*.yml` leaves a rename-away bypass: `evil.yaml` with
- # `pull_request_target` would run for real and lint clean.
+ # GitHub Actions loads both workflow extensions.
workflows = sorted(list(workflows_dir.glob("*.yml")) + list(workflows_dir.glob("*.yaml")))
pr_triggered: list[tuple[Path, list[str]]] = []
publish_triggered: list[tuple[Path, list[str]]] = []
diff --git a/scripts/virustotal_scan.py b/scripts/virustotal_scan.py
index af302c6a03a..58b43cc7cf2 100644
--- a/scripts/virustotal_scan.py
+++ b/scripts/virustotal_scan.py
@@ -199,14 +199,7 @@ SUMMARY_HEADING = "### VirusTotal release asset scan"
def submission_packet_lines(detected: Sequence[FileReport]) -> list[str]:
- """Pre-fill a false-positive submission for every flagged asset.
-
- The build job assembles one too, but only for the Windows `-setup.exe`, so the detection
- that actually arrived -- `Trojan:Script/Wacatac.B!ml` on the 0.1.701-beta Linux AppImage --
- produced nothing to submit. Anything flagged here gets a packet, whatever built it.
-
- Engine names are not repeated: third-party text, already escaped under "Flagging engines".
- """
+ """Build a false-positive submission packet for every flagged asset."""
lines = [
"",
"#### False-positive submission packet",
@@ -268,9 +261,7 @@ def render_markdown(reports: Sequence[FileReport], threshold: int) -> str:
for report in notes:
lines.append(f"- `{_md_code(report.name)}`: {_md_text(report.note)}")
- # Keyed on the counts, not the engine list: stats and results are separate fields of the
- # same response, so an asset can carry a flagged count with no readable results map. The
- # table would report it and the packet would skip it, which is the one asset that needs one.
+ # Use the flagged count because the results map may be absent.
flagged = [report for report in reports if report.stats is not None and report.stats.flagged]
if flagged:
lines += submission_packet_lines(flagged)
diff --git a/studio/backend/assets/configs/inference_defaults.json b/studio/backend/assets/configs/inference_defaults.json
index 31358b02074..798cbf9d0db 100644
--- a/studio/backend/assets/configs/inference_defaults.json
+++ b/studio/backend/assets/configs/inference_defaults.json
@@ -1,6 +1,20 @@
{
"_comment": "Per-model-family inference parameter defaults. Sources: (1) Ollama params blobs, (2) Existing Unsloth Studio YAML configs. Patterns ordered longest-match-first.",
"families": {
+ "moss-tts-local-transformer-v1.5": {
+ "temperature": 1.7,
+ "top_p": 0.8,
+ "top_k": 25,
+ "min_p": 0.0,
+ "repetition_penalty": 1.0
+ },
+ "moss-tts-nano": {
+ "temperature": 1.7,
+ "top_p": 0.8,
+ "top_k": 25,
+ "min_p": 0.0,
+ "repetition_penalty": 1.0
+ },
"qwen3.8": {
"temperature": 0.7,
"top_p": 0.8,
@@ -413,6 +427,7 @@
}
},
"patterns": [
+ "moss-tts-local-transformer-v1.5", "moss-tts-nano",
"qwen3.8", "qwen3.6", "qwen3.5",
"qwen3-coder", "qwen3-next", "qwen3-vl", "qwen3",
"qwen2.5-coder", "qwen2.5-vl", "qwen2.5-omni", "qwen2.5-math", "qwen2.5",
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index fa60b89bc33..19b02a7e5b4 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -187,6 +187,10 @@ _TURN_BOUNDARY_MARKUP = re.compile(
# closer truncates or garbles the audio. Per codec, and deliberately NOT the chat sweep: this
# text is meant to be SPOKEN, so "please say <s>hello</s>" must reach the tokenizer as typed
# (#7066).
+_MOSS_TTS_MARKUP = re.compile(
+ r"<(?=/?user_inst>|\|(?:im_(?:start|end)|audio(?:_start|_end|_pad)?"
+ r"|vision_pad|video_pad)\|>)"
+)
_TTS_MARKUP_BY_CODEC = {
# <custom_token_3>{text}<|eot_id|><custom_token_4>, stop <custom_token_2>. Those three
# only, not any number: the transformers path spells the same ones as bare ids
@@ -210,6 +214,24 @@ _TTS_MARKUP_BY_CODEC = {
# (model_config.py:992-995), and add_special_tokens = True makes the document boundaries
# forgeable from the text too (#7066).
"csm": re.compile(r"\[(?=\d+\])|<(?=\|(?:AUDIO|audio_eos|begin_of_text|end_of_text)\|>)"),
+ # Higgs TTS 2 renders scene and chat-role boundaries before opening the audio stream.
+ # Both the spoken text and the scene description are inserted verbatim by its template.
+ "higgs_tts2": re.compile(
+ r"<(?=\|(?:begin_of_text|end_of_text|start_header_id|end_header_id"
+ r"|scene_desc_start|scene_desc_end|eot_id|audio_out_bos|AUDIO_OUT"
+ r"|audio_eos|reserved_special_token_6)\|>)"
+ ),
+ # Higgs v3 tokenizes user text directly before adding its own <|audio|> boundary.
+ "higgs_tts3": re.compile(r"<(?=\|(?:tts|ref_audio|ref_text|text|audio)\|>)"),
+ # minimax wraps lyrics with chatml, caption, lyric, and audio stream boundaries.
+ "minimax_music3": re.compile(
+ r"<(?=\|(?:im_(?:start|end)|caption_(?:start|end)|lyrics_(?:start|end)"
+ r"|audio_(?:start|end|cfg))\|>)"
+ ),
+ # MOSS Local and Nano wrap client text in a user_inst block inside a ChatML turn.
+ # The remaining sentinels are codec placeholders accepted by their processors.
+ "moss_tts_local": _MOSS_TTS_MARKUP,
+ "moss_tts_nano": _MOSS_TTS_MARKUP,
}
# An unrecognised codec gets the union: still far narrower than the chat sweep, but it does
# not assume a prompt shape this module has not seen.
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 4b2ece0881e..3be49c97e2d 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -6359,6 +6359,7 @@ class ExternalProviderClient:
voice: Optional[str] = None,
response_format: str = "wav",
speed: Optional[float] = None,
+ instructions: Optional[str] = None,
) -> tuple[bytes, str]:
"""POST /audio/speech (OpenAI CreateSpeech). Returns (audio_bytes, media_type)."""
body: dict[str, Any] = {
@@ -6370,6 +6371,8 @@ class ExternalProviderClient:
body["voice"] = voice
if speed is not None:
body["speed"] = speed
+ if instructions is not None:
+ body["instructions"] = instructions
response = await _http_client.post(
_append_provider_path(self.base_url, "/audio/speech"),
headers = self._auth_headers(),
diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.py
index 7048e2377fc..14373dc819b 100644
--- a/studio/backend/core/inference/gpu_arbiter.py
+++ b/studio/backend/core/inference/gpu_arbiter.py
@@ -24,6 +24,11 @@ VIDEO = "video"
_lock = threading.Lock()
_owner: Optional[str] = None
+_owner_epoch = 0
+
+
+class OwnerChangedError(RuntimeError):
+ """The outgoing GPU owner changed after a pre-handoff capacity snapshot."""
def _evict_chat() -> None:
@@ -79,6 +84,7 @@ def acquire_for(
owner: str,
register: Optional[Callable[[], Any]] = None,
*,
+ expected_current: Optional[tuple[Optional[str], int]] = None,
allow_evict: bool = True,
) -> Any:
"""Make ``owner`` the sole GPU owner, evicting the other if it holds it.
@@ -89,25 +95,29 @@ def acquire_for(
letting both loaders allocate VRAM at once. It must be quick and not re-enter the arbiter; if it
raises, ownership stays with ``owner``.
"""
- global _owner
+ global _owner, _owner_epoch
if owner not in _EVICTORS:
raise ValueError(f"unknown GPU owner: {owner!r}")
with _lock:
+ if expected_current is not None and (_owner, _owner_epoch) != expected_current:
+ raise OwnerChangedError("The resident GPU model changed; retry the load.")
if _owner is not None and _owner != owner:
if not allow_evict:
raise GpuOwnerBusyError(_owner)
logger.info("gpu_arbiter: evicting %s for %s", _owner, owner)
_EVICTORS[_owner]()
_owner = owner
+ _owner_epoch += 1
return register() if register is not None else None
def release(owner: str) -> None:
"""Drop ``owner``'s claim (no-op if it isn't the current owner)."""
- global _owner
+ global _owner, _owner_epoch
with _lock:
if _owner == owner:
_owner = None
+ _owner_epoch += 1
def release_if(owner: str, predicate: Callable[[], bool]) -> bool:
@@ -117,13 +127,19 @@ def release_if(owner: str, predicate: Callable[[], bool]) -> bool:
whose ``acquire_for(register=...)`` re-registers ownership under this lock; evaluating the
predicate under the lock keeps them atomic so ``release`` never clears the newer claim.
``predicate`` must be quick and not re-enter the arbiter. Returns True iff ownership was dropped."""
- global _owner
+ global _owner, _owner_epoch
with _lock:
if _owner != owner or not predicate():
return False
_owner = None
+ _owner_epoch += 1
return True
def current_owner() -> Optional[str]:
return _owner
+
+
+def owner_snapshot() -> tuple[Optional[str], int]:
+ with _lock:
+ return _owner, _owner_epoch
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 51e9ed9c0e6..e0d25daecfd 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -2062,10 +2062,16 @@ class InferenceBackend:
repetition_penalty: float = 1.0,
use_adapter: Optional[Union[bool, str]] = None,
cancel_event = None,
+ instructions: Optional[str] = None,
+ language: Optional[str] = None,
+ seed: Optional[int] = None,
) -> Tuple[bytes, int]:
"""Generate audio from text for TTS models.
Returns (wav_bytes, sample_rate). Blocking — full audio before return.
"""
+ # Reserved for native audio architectures; codec-backed TTS models do
+ # not currently expose scene instructions or deterministic seeding.
+ del instructions, language, seed
if not self.active_model_name:
raise RuntimeError("No active model")
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 1420fea8817..cfa89079283 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -657,6 +657,11 @@ _GPU_OFFLOAD_MARKERS = (
_OFFLOADED_LAYERS_RE = re.compile(
r"offloaded\s+(\d+)\s*/\s*(\d+)\s+layers?\s+to\s+gpu", re.IGNORECASE
)
+_GPU_MODEL_BUFFER_RE = re.compile(
+ r"\b(?:CUDA|ROCm|ROCM|HIP|SYCL)(\d+)\s+model buffer size\s*=\s*"
+ r"([0-9]+(?:\.[0-9]+)?)\s+MiB\b",
+ re.IGNORECASE,
+)
_DEVICE_ROW_RE = re.compile(
r"-\s*(CUDA|ROCm|ROCM|HIP|Metal|Vulkan|SYCL|OpenCL|MUSA|CANN|CPU)\w*\s*:",
re.IGNORECASE,
@@ -5414,6 +5419,11 @@ class LlamaCppBackend:
self._arch_gate_forced_cpu: bool = False
# User-picked physical GPU indices (None = automatic selection).
self._gpu_ids: Optional[List[int]] = None
+ # Physical GPU ids in the exact ordinal order exposed to the current
+ # llama-server child. Automatic placement deliberately leaves
+ # ``_gpu_ids`` unset, so reclaim accounting must not infer this mapping
+ # from status state after a fit/arch gate narrowed the child mask.
+ self._child_gpu_physical_ids: Optional[tuple[int, ...]] = None
# RAW requested GPU pin, before the fit narrowed it. self._gpu_ids records the
# EFFECTIVE (fit-narrowed) pin for /status; dedupe compares this raw value so a
# [0, 1] narrowed to [0] and re-sent as [0, 1] still matches (#7239).
@@ -5588,6 +5598,34 @@ class LlamaCppBackend:
"""True if a llama-server process exists (loading or loaded)."""
return self._process is not None
+ def reclaimable_gpu_memory_gb(self) -> Optional[dict[int, float]]:
+ """Stable GPU model buffers the disposable llama-server will release.
+
+ The startup log sizes only resident model buffers, so this is a
+ conservative lower bound: KV/compute buffers remain charged. Unlike a
+ live process-memory sample, the value cannot race a short generation
+ that grows or clears its cache between the free-memory and owner reads.
+ """
+ process = self._process
+ if process is None or process.poll() is not None:
+ return None
+ physical_ids = list(getattr(self, "_child_gpu_physical_ids", None) or ())
+ if not physical_ids:
+ return None
+ reported: dict[int, float] = {}
+ for line in list(self._stdout_lines):
+ match = _GPU_MODEL_BUFFER_RE.search(line)
+ if match is None:
+ continue
+ ordinal = int(match.group(1))
+ if ordinal >= len(physical_ids):
+ return None
+ physical = int(physical_ids[ordinal])
+ reported[physical] = reported.get(physical, 0.0) + float(match.group(2)) / 1024.0
+ if self._process is not process or process.poll() is not None:
+ return None
+ return reported or None
+
@property
def base_url(self) -> str:
return f"http://127.0.0.1:{self._port}"
@@ -7386,7 +7424,16 @@ class LlamaCppBackend:
logger.debug("Failed to set ROCm visibility env vars for child: %s", e)
@staticmethod
- def _pin_visible_gpu_order_for_split(env: dict) -> None:
+ def _unmasked_child_gpu_physical_ids() -> Optional[tuple[int, ...]]:
+ from utils.hardware import get_parent_visible_gpu_ids
+
+ parent_gpu_ids = get_parent_visible_gpu_ids()
+ if len(parent_gpu_ids) == 1:
+ return (int(parent_gpu_ids[0]),)
+ return None
+
+ @staticmethod
+ def _pin_visible_gpu_order_for_split(env: dict) -> Optional[tuple[int, ...]]:
"""Pin the child's GPU enumeration to the picker's order for a manual
``--tensor-split`` across the whole visible set. CUDA's default
FASTEST_FIRST enumeration applies the shares to the wrong cards on
@@ -7403,7 +7450,7 @@ class LlamaCppBackend:
env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
inherited = LlamaCppBackend._resolve_visible_physical_ids()
if not inherited:
- return
+ return None
order = None
try:
from utils.hardware import get_backend_visible_gpu_info
@@ -7431,6 +7478,7 @@ class LlamaCppBackend:
LlamaCppBackend._emit_child_gpu_visibility(
env, ",".join(str(i) for i in order), prefer_rocr = prefer_rocr
)
+ return tuple(int(i) for i in order)
@staticmethod
def _vulkan_targets_are_igpus(binary: Optional[str], gpu_indices = None) -> bool:
@@ -16628,7 +16676,9 @@ class LlamaCppBackend:
out[ki] = "<redacted>"
return out
- def _start_llama_process(self, cmd: list[str], env: dict) -> None:
+ def _start_llama_process(
+ self, cmd: list[str], env: dict, *, child_gpu_physical_ids: Optional[tuple[int, ...]]
+ ) -> None:
"""Spawn llama-server from cmd and start draining its output.
Caller holds self._lock. Resets the stdout buffer, opens a fresh
@@ -16640,6 +16690,7 @@ class LlamaCppBackend:
# stored a Popen handle here, drop that orphan before we overwrite
# the reference. See issue #5161.
self._kill_process()
+ self._child_gpu_physical_ids = child_gpu_physical_ids
self._stdout_lines = []
# Tee llama-server output to a dedicated log file so a post-mortem
@@ -17737,6 +17788,7 @@ class LlamaCppBackend:
# UnboundLocalError on the path that reaches it most often.
_spill_inputs: Optional[dict] = None
total_by_idx: dict[int, int] = {}
+ _gpu_mem: list[tuple[int, int, int]] = []
model_size = None # set in the fit try; used by the APU RAM guard
# "none" once the fit proves the load needs no demand paging, else None
# for llama.cpp's own default. Bound before the try like the verdict
@@ -21532,6 +21584,10 @@ class LlamaCppBackend:
and not is_vulkan_backend
and not self._zero_offload_keeps_gpu_visible(cmd, env)
)
+ _child_gpu_physical_ids: Optional[tuple[int, ...]] = None
+ if not is_vulkan_backend and _gpu_mem:
+ _child_gpu_physical_ids = self._unmasked_child_gpu_physical_ids()
+
# The CUDA SM gate goes here, where the child's GPU visibility is
# finally known: both arms below write CUDA_VISIBLE_DEVICES=-1, so no
# kernel image loads and the abort this pre-empts cannot happen.
@@ -21550,6 +21606,7 @@ class LlamaCppBackend:
# None there, so this branch writes the mask.
if _cpu_only_zero_offload or _arch_gate_forced_cpu:
self._emit_child_gpu_visibility(env, "-1")
+ _child_gpu_physical_ids = ()
# Manual mode admits tensor parallelism on the FULL device count,
# which still counts the dropped cards, so --split-mode tensor can
# reach a child that sees none. llama_prepare_model_devices then
@@ -21593,6 +21650,7 @@ class LlamaCppBackend:
self._emit_child_gpu_visibility(
env, ",".join(str(i) for i in gpu_indices), prefer_rocr = True
)
+ _child_gpu_physical_ids = tuple(int(i) for i in gpu_indices)
_launch_pinned_ids = list(gpu_indices)
elif not is_vulkan_backend and not gpu_ids:
# Nothing above pinned the child. Two shapes land here and the gate
@@ -21665,6 +21723,7 @@ class LlamaCppBackend:
self._emit_child_gpu_visibility(
env, ",".join(str(i) for i in _survivors), prefer_rocr = True
)
+ _child_gpu_physical_ids = tuple(int(i) for i in _survivors)
# Narrower than any pin above, so it replaces it.
_launch_pinned_ids = list(_survivors)
elif manual_tensor_split_emitted:
@@ -21672,7 +21731,7 @@ class LlamaCppBackend:
# no mask above): the UI built --tensor-split in ascending
# physical/PCI order, so pin the child's enumeration to match.
# The whole visible set stays in use, only its order is fixed.
- self._pin_visible_gpu_order_for_split(env)
+ _child_gpu_physical_ids = self._pin_visible_gpu_order_for_split(env)
_child_has_no_gpu = (
# each names a device present but unusable, so it owns the empty pool
@@ -21863,6 +21922,7 @@ class LlamaCppBackend:
# have stored before we overwrite the reference (#5161).
# Also reaps the crashed first attempt on the retry pass.
self._kill_process()
+ self._child_gpu_physical_ids = _child_gpu_physical_ids
self._stdout_lines = []
# Tee llama-server output to a dedicated log file so a
@@ -22555,6 +22615,7 @@ class LlamaCppBackend:
self._emit_child_gpu_visibility(
env, ",".join(str(i) for i in _remaining), prefer_rocr = True
)
+ _child_gpu_physical_ids = tuple(int(i) for i in _remaining)
# Same for the inherited env twins of the flags dropped
# below: the new mask re-indexes the survivors under them.
self._clear_split_placement_env(env)
@@ -23100,7 +23161,11 @@ class LlamaCppBackend:
_last_spawn_cmd = list(cmd)
self._is_vision = False
self._mmproj_has_audio = False
- self._start_llama_process(cmd, env)
+ self._start_llama_process(
+ cmd,
+ env,
+ child_gpu_physical_ids = _child_gpu_physical_ids,
+ )
if self._wait_for_health(timeout = 600.0, cancelled = _load_cancelled):
healthy = True
# The child that serves this session never read the
@@ -24340,6 +24405,7 @@ class LlamaCppBackend:
# Cleared before the early return, not in the finally below, so a stale split never
# outlives its runner even when there was no process to kill.
self._diffusion_requested_ngl = None
+ self._child_gpu_physical_ids = None
if self._process is None:
return
# Not every _process is a Popen: tests stand one in to mean "a server is
diff --git a/studio/backend/core/inference/native_audio.py b/studio/backend/core/inference/native_audio.py
new file mode 100644
index 00000000000..602e21c23f3
--- /dev/null
+++ b/studio/backend/core/inference/native_audio.py
@@ -0,0 +1,1330 @@
+# Unsloth Zoo - Utilities for Unsloth
+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+"""Native Transformers/Diffusers audio generation backends.
+
+This module intentionally has no ML imports at module import time. The worker uses
+``is_native_audio_model`` before choosing its MLX or Unsloth runtime, including on
+Apple Silicon, and imports torch/transformers only after the normal version and
+remote-code security gates have run.
+"""
+
+from __future__ import annotations
+
+import gc
+import io
+import json
+import logging
+import re
+import sys
+import tempfile
+import threading
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Any, Optional, Tuple
+
+logger = logging.getLogger(__name__)
+
+
+NATIVE_AUDIO_MODEL_IDS = {
+ "bosonai/higgs-tts-2-3b-base": "higgs_tts2",
+ "openmoss-team/moss-tts-local-transformer-v1.5": "moss_tts_local",
+ "openmoss-team/moss-tts-nano-100m": "moss_tts_nano",
+ "multimodalart/higgs-audio-v3-tts-4b-transformers": "higgs_tts3",
+ "minimaxai/minimax-music3": "minimax_music3",
+}
+
+NATIVE_AUDIO_MODEL_TYPES = {
+ "higgs_audio_v2": "higgs_tts2",
+ "moss_tts_local": "moss_tts_local",
+ "moss_tts_nano": "moss_tts_nano",
+ "higgs_multimodal_qwen3": "higgs_tts3",
+ "minimax_music3": "minimax_music3",
+}
+
+NATIVE_AUDIO_TYPES = frozenset(NATIVE_AUDIO_MODEL_TYPES.values())
+REMOTE_CODE_AUDIO_TYPES = frozenset(("moss_tts_local", "moss_tts_nano", "higgs_tts3"))
+PYTHON310_AUDIO_TYPES = frozenset(("higgs_tts2", "higgs_tts3", "minimax_music3"))
+MOSS_LOCAL_CODEC_REPO = "OpenMOSS-Team/MOSS-Audio-Tokenizer-v2"
+MOSS_NANO_CODEC_REPO = "OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano"
+MOSS_NANO_TEXT_TEMPERATURE = 1.5
+MOSS_NANO_TEXT_TOP_P = 1.0
+MOSS_NANO_TEXT_TOP_K = 50
+HIGGS_TTS2_CODEC_REPO = "bosonai/higgs-audio-v2-tokenizer"
+HIGGS_TTS3_CODEC_REPO = "bosonai/higgs-audio-v2-tokenizer"
+NATIVE_AUDIO_COMPANION_REPOS = {
+ "higgs_tts2": (HIGGS_TTS2_CODEC_REPO,),
+ "moss_tts_local": (MOSS_LOCAL_CODEC_REPO,),
+ "moss_tts_nano": (MOSS_NANO_CODEC_REPO,),
+ "higgs_tts3": (HIGGS_TTS3_CODEC_REPO,),
+}
+
+_MINIMAX_MODULAR_CLASSES = (
+ "MiniMaxMusic3ModularPipeline",
+ "MiniMaxMusic3Blocks",
+)
+_MINIMAX_LEADING_LYRIC_TAGS = re.compile(r"^\s*((?:\[[^\]\r\n]+\]\s*)+)(\S.*)$")
+
+
+def _minimax_lyrics_for_pipeline(lyrics: str) -> str:
+ """Keep words that follow a MiniMax section tag on the same input line."""
+ normalized = []
+ for line in str(lyrics or "").splitlines():
+ match = _MINIMAX_LEADING_LYRIC_TAGS.match(line)
+ if match is None:
+ normalized.append(line)
+ continue
+ normalized.extend(re.findall(r"\[[^\]\r\n]+\]", match.group(1)))
+ normalized.append(match.group(2))
+ return "\n".join(normalized)
+
+
+_MINIMAX_DOWNLOAD_COMPONENTS = frozenset(
+ (
+ "condition_encoder",
+ "language_model",
+ "rvq_depth_decoder",
+ "scheduler",
+ "tokenizer",
+ "transformer",
+ "vocoder",
+ )
+)
+_MOSS_CONFIG_COMPAT_LOCK = threading.Lock()
+_MOSS_NANO_SAVE_LOCK = threading.Lock()
+_MAX_AUDIO_METADATA_BYTES = 1_000_000
+
+
+class _AudioMetadataTooLarge(ValueError):
+ pass
+
+
+def _read_local_audio_metadata(
+ path: Path,
+ filename: str,
+ *,
+ reject_oversized: bool = False,
+) -> dict[str, Any]:
+ metadata_path = path / filename
+ if not metadata_path.is_file():
+ return {}
+ with metadata_path.open("rb") as handle:
+ raw = handle.read(_MAX_AUDIO_METADATA_BYTES + 1)
+ if len(raw) > _MAX_AUDIO_METADATA_BYTES:
+ if reject_oversized:
+ raise _AudioMetadataTooLarge(
+ f"{filename} exceeds the {_MAX_AUDIO_METADATA_BYTES}-byte security inspection limit."
+ )
+ return {}
+ value = json.loads(raw.decode("utf-8-sig"))
+ return value if isinstance(value, dict) else {}
+
+
+def _read_audio_metadata(
+ model_name: str,
+ filename: str,
+ hf_token: Optional[str] = None,
+ *,
+ reject_oversized: bool = False,
+) -> dict[str, Any]:
+ """Read one bounded metadata file from a local checkpoint or Hub repo."""
+ normalized = str(model_name or "").strip()
+ if not normalized:
+ return {}
+ try:
+ path = Path(normalized).expanduser()
+ if path.is_file():
+ path = path.parent
+ if path.is_dir():
+ return _read_local_audio_metadata(
+ path,
+ filename,
+ reject_oversized = reject_oversized,
+ )
+
+ from huggingface_hub import hf_hub_download
+ from utils.hf_cache_settings import active_hf_hub_cache
+
+ metadata_path = Path(
+ hf_hub_download(
+ repo_id = normalized,
+ filename = filename,
+ token = hf_token,
+ cache_dir = active_hf_hub_cache(),
+ )
+ )
+ return _read_local_audio_metadata(
+ metadata_path.parent,
+ metadata_path.name,
+ reject_oversized = reject_oversized,
+ )
+ except _AudioMetadataTooLarge:
+ raise
+ except Exception as exc:
+ logger.debug(
+ "Could not read native audio metadata %s from %s: %s", filename, normalized, exc
+ )
+ return {}
+
+
+def _moss_local_codec_target(model_name: str, hf_token: Optional[str] = None) -> str:
+ """Resolve and freeze the codec source the publisher processor will load."""
+ processor_config = _read_audio_metadata(
+ model_name, "processor_config.json", hf_token, reject_oversized = True
+ )
+ model_config = _read_audio_metadata(model_name, "config.json", hf_token, reject_oversized = True)
+ nested = processor_config.get("audio_tokenizer")
+ candidates = (
+ processor_config.get("audio_tokenizer_name_or_path"),
+ nested.get("audio_tokenizer_name_or_path") if isinstance(nested, dict) else None,
+ model_config.get("audio_tokenizer_name_or_path"),
+ )
+ for candidate in candidates:
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return MOSS_LOCAL_CODEC_REPO
+
+
+def _higgs_tts2_codec_target(model_name: str, hf_token: Optional[str] = None) -> str:
+ """Resolve the codec source that the Higgs TTS 2 processor will load."""
+ audio_tokenizer_config = _read_audio_metadata(
+ model_name, "audio_tokenizer_config.json", hf_token, reject_oversized = True
+ )
+ processor_config = _read_audio_metadata(
+ model_name, "processor_config.json", hf_token, reject_oversized = True
+ )
+ nested = processor_config.get("audio_tokenizer")
+ candidates = (
+ audio_tokenizer_config.get("audio_tokenizer_name_or_path"),
+ processor_config.get("audio_tokenizer_name_or_path"),
+ nested.get("audio_tokenizer_name_or_path") if isinstance(nested, dict) else None,
+ )
+ for candidate in candidates:
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return HIGGS_TTS2_CODEC_REPO
+
+
+def _higgs_tts3_codec_target(model_name: str, hf_token: Optional[str] = None) -> str:
+ """Resolve the codec source that the Higgs TTS 3 remote model will load."""
+ model_config = _read_audio_metadata(model_name, "config.json", hf_token, reject_oversized = True)
+ candidate = model_config.get("audio_tokenizer_id")
+ if isinstance(candidate, str) and candidate.strip():
+ return candidate.strip()
+ return HIGGS_TTS3_CODEC_REPO
+
+
+def native_audio_type_from_local_path(model_name: str) -> Optional[str]:
+ """Recognize a local native-audio checkpoint from bounded metadata files."""
+ normalized = str(model_name or "").strip()
+ if not normalized:
+ return None
+ try:
+ path = Path(normalized).expanduser()
+ if path.is_file():
+ path = path.parent
+ config = _read_local_audio_metadata(path, "config.json")
+ audio_type = NATIVE_AUDIO_MODEL_TYPES.get(str(config.get("model_type") or "").lower())
+ if audio_type:
+ return audio_type
+ modular_index = _read_local_audio_metadata(path, "modular_model_index.json")
+ classes = (
+ modular_index.get("_class_name"),
+ modular_index.get("_blocks_class_name"),
+ )
+ if classes == _MINIMAX_MODULAR_CLASSES:
+ return "minimax_music3"
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
+ pass
+ return None
+
+
+def _native_audio_type(model_name: str) -> Optional[str]:
+ normalized = str(model_name or "").strip()
+ curated = NATIVE_AUDIO_MODEL_IDS.get(normalized.lower())
+ if curated:
+ return curated
+ return native_audio_type_from_local_path(normalized)
+
+
+def is_native_audio_model(model_name: str) -> bool:
+ """Whether ``model_name`` belongs in the portable native-audio worker.
+
+ Curated Hub IDs are answered without network access. Local checkpoints are
+ recognized from small metadata files; model weights are not opened.
+ """
+ return _native_audio_type(model_name) is not None
+
+
+def native_audio_security_targets(
+ model_name: str,
+ audio_type: Optional[str] = None,
+ hf_token: Optional[str] = None,
+) -> list[str]:
+ """Repositories whose code or weights are loaded for this audio model."""
+ targets = [model_name]
+ resolved_type = audio_type or _native_audio_type(model_name)
+ if resolved_type == "moss_tts_local":
+ targets.append(_moss_local_codec_target(model_name, hf_token))
+ elif resolved_type == "higgs_tts2":
+ targets.append(_higgs_tts2_codec_target(model_name, hf_token))
+ elif resolved_type == "higgs_tts3":
+ targets.append(_higgs_tts3_codec_target(model_name, hf_token))
+ else:
+ targets.extend(NATIVE_AUDIO_COMPANION_REPOS.get(resolved_type, ()))
+ return targets
+
+
+def _kv_config_memory_gb(config: dict[str, Any]) -> float:
+ def positive_int(*names: str) -> int:
+ for name in names:
+ try:
+ value = int(config.get(name) or 0)
+ except (TypeError, ValueError):
+ continue
+ if value > 0:
+ return value
+ return 0
+
+ context = positive_int(
+ "max_position_embeddings",
+ "max_sequence_length",
+ "max_seq_length",
+ "n_positions",
+ "n_ctx",
+ "seq_length",
+ )
+ layers = positive_int("num_hidden_layers", "n_layer")
+ attention_heads = positive_int("num_attention_heads", "n_head")
+ kv_heads = positive_int("num_key_value_heads", "n_head") or attention_heads
+ head_dim = positive_int("head_dim")
+ if not head_dim:
+ hidden_size = positive_int("hidden_size", "n_embd")
+ if hidden_size and attention_heads:
+ head_dim = hidden_size // attention_heads
+ if not all((context, layers, kv_heads, head_dim)):
+ return 0.0
+ # One key and one value per layer. Native MOSS GPU runtimes use BF16/FP16.
+ return 2 * layers * kv_heads * head_dim * context * 2 / (1024**3)
+
+
+def native_audio_kv_memory_gb(
+ model_name: str,
+ audio_type: Optional[str] = None,
+ hf_token: Optional[str] = None,
+) -> float:
+ """Full-context MOSS KV footprint omitted by the generic weight estimator."""
+ resolved_type = audio_type or _native_audio_type(model_name)
+ if resolved_type not in ("moss_tts_local", "moss_tts_nano"):
+ return 0.0
+ config = _read_audio_metadata(model_name, "config.json", hf_token)
+ if resolved_type == "moss_tts_local":
+ candidates = (config.get("qwen3_config"), config.get("gpt2_config"))
+ else:
+ candidates = (config.get("gpt2_config"),)
+ return sum(
+ _kv_config_memory_gb(candidate) for candidate in candidates if isinstance(candidate, dict)
+ )
+
+
+def _moss_transformers5_config_compat(codec_source: str, token_kwargs: dict[str, Any]) -> None:
+ """Import a MOSS codec config with the pre-Transformers-5 subclass contract.
+
+ Transformers 5 turns every ``PreTrainedConfig`` subclass into a dataclass.
+ The published MOSS codec configs have required fields (including
+ ``sampling_rate``) after inherited default fields, which Python dataclasses
+ reject before any model weights are read. The remote configs already own
+ their constructors, so briefly suppressing only that automatic conversion
+ restores the contract they were published against. The base hook is always
+ restored before the actual model load begins.
+ """
+ import transformers
+
+ try:
+ major = int(str(getattr(transformers, "__version__", "0")).split(".", 1)[0])
+ except (TypeError, ValueError):
+ return
+ if major < 5:
+ return
+
+ auto_config = getattr(transformers, "AutoConfig", None)
+ base_config = getattr(transformers, "PreTrainedConfig", None)
+ if auto_config is None or base_config is None:
+ return
+ original = base_config.__dict__.get("__init_subclass__")
+ if original is None:
+ return
+
+ with _MOSS_CONFIG_COMPAT_LOCK:
+ setattr(
+ base_config,
+ "__init_subclass__",
+ classmethod(lambda cls, *args, **kwargs: None),
+ )
+ try:
+ auto_config.from_pretrained(
+ codec_source,
+ trust_remote_code = True,
+ **token_kwargs,
+ )
+ finally:
+ setattr(base_config, "__init_subclass__", original)
+
+
+def _repair_moss_nano_rotary_buffers(model) -> None:
+ """Rebuild buffers that Transformers 5 leaves uninitialized after meta loading."""
+ import torch
+ for decoder_name in ("transformer", "local_transformer"):
+ decoder = getattr(model, decoder_name, None)
+ config = getattr(decoder, "config", None)
+ if decoder is None or config is None:
+ continue
+ base = float(getattr(config, "rope_base", 10000.0))
+ for module in decoder.modules():
+ rotary = getattr(module, "rotary_emb", None)
+ inv_freq = getattr(rotary, "inv_freq", None)
+ if inv_freq is None:
+ continue
+ dimension = int(inv_freq.numel()) * 2
+ rotary.inv_freq = 1.0 / (
+ base
+ ** (
+ torch.arange(
+ 0,
+ dimension,
+ 2,
+ dtype = torch.float32,
+ device = inv_freq.device,
+ )
+ / dimension
+ )
+ )
+
+
+@contextmanager
+def _seeded_torch_rng(seed: Optional[int], device: str):
+ """Seed one request and restore the process RNG states afterward."""
+ import torch
+
+ if seed is None:
+ yield
+ return
+
+ device_type = torch.device(device).type
+ accelerator = getattr(torch, device_type, None) if device_type != "cpu" else None
+ devices = list(range(accelerator.device_count())) if accelerator is not None else []
+ fork_device_type = device_type if accelerator is not None else "cuda"
+ with torch.random.fork_rng(devices = devices, device_type = fork_device_type):
+ torch.random.default_generator.manual_seed(int(seed))
+ if accelerator is not None:
+ manual_seed_all = getattr(accelerator, "manual_seed_all", None)
+ if manual_seed_all is not None:
+ manual_seed_all(int(seed))
+ else:
+ accelerator.manual_seed(int(seed))
+ yield
+
+
+@contextmanager
+def _moss_nano_soundfile_save(model):
+ """Route the publisher's unconditional torchaudio save through soundfile."""
+ remote_module = sys.modules.get(model.__class__.__module__)
+ original_torchaudio = getattr(remote_module, "torchaudio", None)
+ if remote_module is None or original_torchaudio is None:
+ raise RuntimeError("MOSS TTS Nano remote module does not expose torchaudio")
+
+ class SoundfileSaveProxy:
+ def __getattr__(self, name):
+ return getattr(original_torchaudio, name)
+
+ @staticmethod
+ def save(uri, source, sample_rate, *_args, **_kwargs):
+ payload = _as_wav_bytes(source, sample_rate)
+ if hasattr(uri, "write"):
+ uri.write(payload)
+ else:
+ Path(uri).write_bytes(payload)
+
+ with _MOSS_NANO_SAVE_LOCK:
+ remote_module.torchaudio = SoundfileSaveProxy()
+ try:
+ yield
+ finally:
+ remote_module.torchaudio = original_torchaudio
+
+
+def _native_audio_file_size(sibling: Any) -> int:
+ size = getattr(sibling, "size", None)
+ if size is None:
+ lfs = getattr(sibling, "lfs", None)
+ size = getattr(lfs, "size", None) if lfs is not None else None
+ try:
+ return max(0, int(size or 0))
+ except (TypeError, ValueError):
+ return 0
+
+
+def _native_audio_file_is_cached(
+ repo_id: str, filename: str, revision: Optional[str], expected_size: int
+) -> bool:
+ """Require a complete current-revision hit in a cache the loaders reuse."""
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ from utils.hf_cache_settings import active_hf_hub_cache
+
+ roots: list[Optional[str]] = [str(active_hf_hub_cache()), None]
+ seen: set[Optional[str]] = set()
+ for root in roots:
+ if root in seen:
+ continue
+ seen.add(root)
+ current = try_to_load_from_cache(
+ repo_id,
+ filename,
+ cache_dir = root,
+ revision = revision,
+ )
+ default = try_to_load_from_cache(repo_id, filename, cache_dir = root)
+ if not isinstance(current, str) or not isinstance(default, str):
+ continue
+ current_path = Path(current)
+ default_path = Path(default)
+ if not current_path.is_file() or not default_path.is_file():
+ continue
+ try:
+ if current_path.resolve() != default_path.resolve():
+ continue
+ if expected_size > 0 and default_path.stat().st_size != expected_size:
+ continue
+ except OSError:
+ continue
+ return True
+ except Exception:
+ return False
+ return False
+
+
+def _native_audio_repo_files(
+ audio_type: Optional[str], checkpoint: bool, siblings: list[Any]
+) -> list[Any]:
+ if audio_type != "minimax_music3" or not checkpoint:
+ return [s for s in siblings if str(getattr(s, "rfilename", "")).strip()]
+
+ required = []
+ for sibling in siblings:
+ name = str(getattr(sibling, "rfilename", "")).strip()
+ if not name:
+ continue
+ root = name.split("/", 1)[0]
+ if (
+ root in _MINIMAX_DOWNLOAD_COMPONENTS
+ or name == "modular_model_index.json"
+ or ("/" not in name and Path(name).suffix.lower() in (".json", ".py"))
+ ):
+ required.append(sibling)
+ return required
+
+
+def native_audio_download_plan(model_name: str, hf_token: Optional[str] = None) -> dict[str, Any]:
+ """Return uncached Hub files for an Audio-page TTS load.
+
+ Native models add their companion codec repositories and MiniMax excludes
+ legacy weights its modular index never references. Other TTS repositories
+ use a full snapshot, matching Chat's safe generic fallback.
+ """
+ normalized = str(model_name or "").strip()
+ if not normalized:
+ raise ValueError("A model repository is required.")
+ local_checkpoint = Path(normalized).expanduser().exists()
+ audio_type = _native_audio_type(normalized)
+ if audio_type in PYTHON310_AUDIO_TYPES and sys.version_info < (3, 10):
+ family = "Higgs TTS" if audio_type.startswith("higgs_") else "MiniMax Music 3"
+ raise ValueError(f"{family} requires Python 3.10 or newer in Studio.")
+ if local_checkpoint and audio_type is None:
+ return {
+ "entries": [],
+ "total_bytes": 0,
+ "required_bytes": 0,
+ "checkpoint_bytes": 0,
+ }
+
+ from huggingface_hub import HfApi
+
+ api = HfApi(token = hf_token or None)
+ entries = []
+ total_bytes = 0
+ required_bytes = 0
+ checkpoint_bytes = 0
+ targets = (
+ list(dict.fromkeys(native_audio_security_targets(normalized, audio_type, hf_token)))
+ if audio_type is not None
+ else [normalized]
+ )
+ for index, repo_id in enumerate(targets):
+ checkpoint = index == 0
+ if checkpoint and local_checkpoint:
+ continue
+ info = api.model_info(repo_id, files_metadata = True)
+ siblings = _native_audio_repo_files(
+ audio_type,
+ checkpoint,
+ list(getattr(info, "siblings", None) or []),
+ )
+ if not siblings:
+ raise ValueError(f"{repo_id} does not publish files required by its audio loader.")
+ revision = str(getattr(info, "sha", "") or "") or None
+ missing_files = []
+ missing_bytes = 0
+ repo_bytes = 0
+ for sibling in siblings:
+ filename = str(getattr(sibling, "rfilename", ""))
+ size = _native_audio_file_size(sibling)
+ repo_bytes += size
+ if not _native_audio_file_is_cached(repo_id, filename, revision, size):
+ missing_files.append(filename)
+ missing_bytes += size
+ required_bytes += repo_bytes
+ if checkpoint:
+ checkpoint_bytes += repo_bytes
+ if missing_files:
+ entries.append(
+ {
+ "repo_id": repo_id,
+ "files": missing_files,
+ "bytes": missing_bytes,
+ "gguf_filename": None,
+ "checkpoint": checkpoint,
+ }
+ )
+ total_bytes += missing_bytes
+ return {
+ "entries": entries,
+ "total_bytes": total_bytes,
+ "required_bytes": required_bytes,
+ "checkpoint_bytes": checkpoint_bytes,
+ }
+
+
+class _CancelStoppingCriteria:
+ """Small adapter constructed without inheriting until Transformers is active."""
+
+ def __init__(self, cancel_event) -> None:
+ self.cancel_event = cancel_event
+
+ def __call__(self, _input_ids, _scores, **_kwargs) -> bool:
+ return bool(self.cancel_event is not None and self.cancel_event.is_set())
+
+
+def _stopping_criteria(cancel_event):
+ if cancel_event is None:
+ return None
+ from transformers import StoppingCriteria, StoppingCriteriaList
+
+ class EventStoppingCriteria(StoppingCriteria):
+ def __init__(self, event) -> None:
+ self._delegate = _CancelStoppingCriteria(event)
+
+ def __call__(self, input_ids, scores, **kwargs) -> bool:
+ return self._delegate(input_ids, scores, **kwargs)
+
+ return StoppingCriteriaList([EventStoppingCriteria(cancel_event)])
+
+
+def _raise_if_cancelled(cancel_event) -> None:
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Audio generation cancelled")
+
+
+def _as_wav_bytes(audio, sample_rate: int) -> bytes:
+ """Serialize mono ``[samples]`` or channel-first stereo to a PCM WAV."""
+ import numpy as np
+ import soundfile as sf
+
+ if hasattr(audio, "detach"):
+ audio = audio.detach().float().cpu().numpy()
+ array = np.asarray(audio, dtype = np.float32)
+ while array.ndim > 2 and array.shape[0] == 1:
+ array = array[0]
+ if array.ndim == 2 and array.shape[0] <= 8 and array.shape[1] > array.shape[0]:
+ array = array.T
+ if array.ndim not in (1, 2):
+ raise RuntimeError(f"Audio decoder returned unsupported shape {array.shape}")
+
+ buffer = io.BytesIO()
+ sf.write(buffer, array, int(sample_rate), format = "WAV", subtype = "PCM_16")
+ return buffer.getvalue()
+
+
+class NativeAudioBackend:
+ """One-model backend for the five curated native audio architectures."""
+
+ def __init__(self) -> None:
+ import torch
+
+ if torch.cuda.is_available():
+ self.device = "cuda"
+ elif hasattr(torch, "xpu") and torch.xpu.is_available():
+ self.device = "xpu"
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
+ self.device = "mps"
+ else:
+ self.device = "cpu"
+
+ self.models: dict[str, dict[str, Any]] = {}
+ self.active_model_name: Optional[str] = None
+ self.loading_models: set[str] = set()
+
+ @staticmethod
+ def _token_kwargs(hf_token: Optional[str]) -> dict[str, str]:
+ token = str(hf_token or "").strip()
+ return {"token": token} if token else {}
+
+ def _dtype(self):
+ import torch
+
+ if self.device == "cuda":
+ if getattr(torch.version, "hip", None):
+ supports_bf16 = torch.cuda.is_bf16_supported()
+ else:
+ try:
+ major, _minor = torch.cuda.get_device_capability()
+ supports_bf16 = major >= 8 and torch.cuda.is_bf16_supported()
+ except Exception:
+ supports_bf16 = False
+ return torch.bfloat16 if supports_bf16 else torch.float16
+ if self.device == "xpu":
+ supports_bf16 = getattr(torch.xpu, "is_bf16_supported", None)
+ return torch.bfloat16 if supports_bf16 is None or supports_bf16() else torch.float16
+ if self.device == "mps":
+ return torch.float16
+ return torch.float32
+
+ @staticmethod
+ def _context_length(entry: dict[str, Any], requested: int, audio_type: str) -> int:
+ if audio_type == "minimax_music3":
+ return 0
+ model = entry.get("model")
+ config = getattr(model, "config", None)
+ detected = 0
+ nested_configs = (
+ getattr(config, "language_config", None),
+ getattr(config, "qwen3_config", None),
+ getattr(config, "text_config", None),
+ )
+ for candidate in (*nested_configs, config):
+ if candidate is None:
+ continue
+ for name in (
+ "max_position_embeddings",
+ "max_sequence_length",
+ "max_seq_length",
+ "n_positions",
+ "seq_length",
+ ):
+ try:
+ raw_value = (
+ candidate.get(name, 0)
+ if isinstance(candidate, dict)
+ else getattr(candidate, name, 0)
+ )
+ value = int(raw_value or 0)
+ except (TypeError, ValueError):
+ continue
+ if value > 0:
+ detected = value
+ break
+ if detected:
+ break
+ requested = max(0, int(requested or 0))
+ if detected and audio_type in ("moss_tts_local", "moss_tts_nano"):
+ return detected
+ if detected and requested:
+ return min(detected, requested)
+ return detected or requested
+
+ def _move(self, model):
+ model = model.to(self.device)
+ if hasattr(model, "eval"):
+ model.eval()
+ return model
+
+ @staticmethod
+ def _configure_moss_cuda_sdpa() -> None:
+ import torch
+
+ if getattr(torch.version, "hip", None):
+ return
+ torch.backends.cuda.enable_flash_sdp(True)
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
+ torch.backends.cuda.enable_math_sdp(True)
+ torch.backends.cuda.enable_cudnn_sdp(False)
+
+ def load_model(
+ self,
+ config,
+ max_seq_length: int = 2048,
+ dtype = None,
+ load_in_4bit: bool = False,
+ hf_token: Optional[str] = None,
+ trust_remote_code: bool = False,
+ gpu_ids: Optional[list[int]] = None,
+ ) -> bool:
+ del dtype, load_in_4bit
+ model_name = config.identifier
+ audio_type = config.audio_type
+ if audio_type not in NATIVE_AUDIO_TYPES:
+ raise RuntimeError(f"Unsupported native audio architecture: {audio_type or model_name}")
+ if audio_type in REMOTE_CODE_AUDIO_TYPES and not trust_remote_code:
+ raise RuntimeError(
+ f"Model '{model_name}' requires trust_remote_code=True before its custom "
+ "Transformers classes can be loaded."
+ )
+ if gpu_ids is not None and len(gpu_ids) > 1:
+ raise RuntimeError(
+ "Native audio models currently require a single selected GPU; "
+ "multi-GPU sharding is not supported yet."
+ )
+ if audio_type == "minimax_music3" and self.device != "cuda":
+ raise RuntimeError(
+ "MiniMax Music 3 currently requires an NVIDIA CUDA GPU in its official "
+ "local runtime. It is not available on CPU, Apple Silicon, AMD, or Intel XPU."
+ )
+ if audio_type == "minimax_music3":
+ import torch
+ if getattr(torch.version, "hip", None):
+ raise RuntimeError(
+ "MiniMax Music 3 currently requires an NVIDIA CUDA GPU; "
+ "its official local runtime does not support AMD ROCm."
+ )
+ if audio_type == "minimax_music3" and sys.version_info < (3, 10):
+ raise RuntimeError("MiniMax Music 3 requires Python 3.10 or newer in Studio.")
+
+ if model_name in self.models:
+ self.active_model_name = model_name
+ return True
+
+ self.loading_models.add(model_name)
+ try:
+ source = config.path or config.identifier
+ entry: dict[str, Any] = {
+ "is_audio": True,
+ "audio_type": audio_type,
+ "has_audio_input": False,
+ "model_path": source,
+ "context_length": 0,
+ }
+ if audio_type == "higgs_tts2":
+ self._load_higgs_tts2(entry, source, hf_token)
+ elif audio_type == "moss_tts_local":
+ self._load_moss_local(entry, source, hf_token, trust_remote_code)
+ elif audio_type == "moss_tts_nano":
+ self._load_moss_nano(entry, source, hf_token, trust_remote_code)
+ elif audio_type == "higgs_tts3":
+ self._load_higgs_tts3(entry, source, hf_token, trust_remote_code)
+ elif audio_type == "minimax_music3":
+ self._load_minimax_music3(entry, source, hf_token)
+
+ entry["context_length"] = self._context_length(entry, max_seq_length, audio_type)
+
+ self.models[model_name] = entry
+ self.active_model_name = model_name
+ return True
+ finally:
+ self.loading_models.discard(model_name)
+
+ def _load_higgs_tts2(self, entry: dict[str, Any], source: str, hf_token: Optional[str]) -> None:
+ from transformers import AutoProcessor, HiggsAudioV2ForConditionalGeneration
+
+ token_kwargs = self._token_kwargs(hf_token)
+ processor = AutoProcessor.from_pretrained(source, **token_kwargs)
+ audio_tokenizer = getattr(processor, "audio_tokenizer", None)
+ if audio_tokenizer is not None and hasattr(audio_tokenizer, "to"):
+ processor.audio_tokenizer = self._move(audio_tokenizer)
+ model = HiggsAudioV2ForConditionalGeneration.from_pretrained(
+ source,
+ torch_dtype = self._dtype(),
+ **token_kwargs,
+ )
+ entry.update(model = self._move(model), processor = processor, sample_rate = 24000)
+
+ def _load_moss_local(
+ self, entry: dict[str, Any], source: str, hf_token: Optional[str], trust_remote_code: bool
+ ) -> None:
+ from transformers import AutoModel, AutoProcessor
+
+ token_kwargs = self._token_kwargs(hf_token)
+ codec_source = _moss_local_codec_target(source, hf_token)
+ _moss_transformers5_config_compat(codec_source, token_kwargs)
+ processor = AutoProcessor.from_pretrained(
+ source,
+ trust_remote_code = trust_remote_code,
+ codec_path = codec_source,
+ **token_kwargs,
+ )
+ audio_tokenizer = getattr(processor, "audio_tokenizer", None)
+ if audio_tokenizer is not None and hasattr(audio_tokenizer, "to"):
+ processor.audio_tokenizer = audio_tokenizer.to(self.device)
+ attention = "sdpa" if self.device == "cuda" else "eager"
+ if self.device == "cuda":
+ self._configure_moss_cuda_sdpa()
+ model = AutoModel.from_pretrained(
+ source,
+ trust_remote_code = trust_remote_code,
+ attn_implementation = attention,
+ torch_dtype = self._dtype(),
+ **token_kwargs,
+ )
+ sample_rate = int(getattr(processor.model_config, "sampling_rate", 48000))
+ entry.update(model = self._move(model), processor = processor, sample_rate = sample_rate)
+
+ def _load_moss_nano(
+ self, entry: dict[str, Any], source: str, hf_token: Optional[str], trust_remote_code: bool
+ ) -> None:
+ from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
+
+ token_kwargs = self._token_kwargs(hf_token)
+ _moss_transformers5_config_compat(MOSS_NANO_CODEC_REPO, token_kwargs)
+ attention = "sdpa" if self.device == "cuda" else "eager"
+ if self.device == "cuda":
+ self._configure_moss_cuda_sdpa()
+ model = AutoModelForCausalLM.from_pretrained(
+ source,
+ trust_remote_code = trust_remote_code,
+ attn_implementation = attention,
+ local_transformer_attn_implementation = attention,
+ torch_dtype = self._dtype(),
+ **token_kwargs,
+ )
+ _repair_moss_nano_rotary_buffers(model)
+ codec = AutoModel.from_pretrained(
+ MOSS_NANO_CODEC_REPO,
+ trust_remote_code = trust_remote_code,
+ **token_kwargs,
+ )
+ tokenizer = AutoTokenizer.from_pretrained(
+ source, trust_remote_code = trust_remote_code, **token_kwargs
+ )
+ entry.update(
+ model = self._move(model),
+ processor = tokenizer,
+ audio_codec = self._move(codec),
+ sample_rate = 48000,
+ )
+
+ def _load_higgs_tts3(
+ self, entry: dict[str, Any], source: str, hf_token: Optional[str], trust_remote_code: bool
+ ) -> None:
+ import torch
+ from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer
+
+ token_kwargs = self._token_kwargs(hf_token)
+ codec_source = _higgs_tts3_codec_target(source, hf_token)
+ tokenizer = AutoTokenizer.from_pretrained(source, **token_kwargs)
+ model = AutoModelForCausalLM.from_pretrained(
+ source,
+ trust_remote_code = trust_remote_code,
+ torch_dtype = self._dtype(),
+ **token_kwargs,
+ )
+ model = self._move(model)
+ codec = AutoModel.from_pretrained(
+ codec_source,
+ trust_remote_code = trust_remote_code,
+ dtype = torch.float32,
+ **token_kwargs,
+ )
+ codec = self._move(codec)
+ for parameter in codec.parameters():
+ parameter.requires_grad_(False)
+ model._audio_codec = codec
+ sample_rate = int(getattr(model.config, "sample_rate", 24000))
+ entry.update(model = model, processor = tokenizer, sample_rate = sample_rate)
+
+ def _load_minimax_music3(
+ self, entry: dict[str, Any], source: str, hf_token: Optional[str]
+ ) -> None:
+ from diffusers import ModularPipeline
+
+ token_kwargs = self._token_kwargs(hf_token)
+ pipeline = ModularPipeline.from_pretrained(source, **token_kwargs)
+ pipeline.load_components(
+ pretrained_model_name_or_path = source,
+ dtype = self._dtype(),
+ **token_kwargs,
+ )
+ pipeline.to(self.device)
+ entry.update(pipeline = pipeline, sample_rate = int(pipeline.sampling_rate))
+
+ def generate_audio_response(
+ self,
+ text: str,
+ temperature: float = 0.6,
+ top_p: float = 0.95,
+ top_k: int = 50,
+ min_p: float = 0.0,
+ max_new_tokens: int = 2048,
+ repetition_penalty: float = 1.0,
+ use_adapter = None,
+ cancel_event = None,
+ instructions: Optional[str] = None,
+ language: Optional[str] = None,
+ seed: Optional[int] = None,
+ ) -> Tuple[bytes, int]:
+ del min_p, use_adapter
+ if not self.active_model_name or self.active_model_name not in self.models:
+ raise RuntimeError("No active audio model")
+ _raise_if_cancelled(cancel_event)
+ entry = self.models[self.active_model_name]
+ audio_type = entry["audio_type"]
+ top_k = max(0, int(top_k))
+
+ request_seed = None if audio_type == "minimax_music3" else seed
+ with _seeded_torch_rng(request_seed, self.device):
+ if audio_type == "higgs_tts2":
+ audio, sample_rate = self._generate_higgs_tts2(
+ entry,
+ text,
+ instructions,
+ temperature,
+ top_p,
+ top_k,
+ max_new_tokens,
+ cancel_event,
+ )
+ elif audio_type == "moss_tts_local":
+ audio, sample_rate = self._generate_moss_local(
+ entry,
+ text,
+ instructions,
+ language,
+ temperature,
+ top_p,
+ top_k,
+ max_new_tokens,
+ repetition_penalty,
+ cancel_event,
+ )
+ elif audio_type == "moss_tts_nano":
+ return self._generate_moss_nano(
+ entry,
+ text,
+ temperature,
+ top_p,
+ top_k,
+ max_new_tokens,
+ repetition_penalty,
+ cancel_event,
+ )
+ elif audio_type == "higgs_tts3":
+ audio, sample_rate = self._generate_higgs_tts3(
+ entry,
+ text,
+ temperature,
+ top_p,
+ top_k,
+ max_new_tokens,
+ cancel_event,
+ )
+ elif audio_type == "minimax_music3":
+ audio, sample_rate = self._generate_minimax_music3(
+ entry,
+ text,
+ instructions,
+ max_new_tokens,
+ seed,
+ cancel_event,
+ )
+ else:
+ raise RuntimeError(f"Unsupported native audio architecture: {audio_type}")
+
+ _raise_if_cancelled(cancel_event)
+ return _as_wav_bytes(audio, sample_rate), sample_rate
+
+ def _generate_higgs_tts2(
+ self, entry, text, instructions, temperature, top_p, top_k, max_new_tokens, cancel_event
+ ):
+ from core.inference.chat_template_helpers import neutralize_tts_prompt_text
+
+ processor = entry["processor"]
+ model = entry["model"]
+ text = neutralize_tts_prompt_text(text, "higgs_tts2")
+ scene = neutralize_tts_prompt_text(
+ instructions or "Audio is recorded from a quiet room.", "higgs_tts2"
+ )
+ conversation = [
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": "Generate audio following instruction."}],
+ },
+ {
+ "role": "scene",
+ "content": [
+ {
+ "type": "text",
+ "text": scene,
+ }
+ ],
+ },
+ {"role": "user", "content": [{"type": "text", "text": text}]},
+ ]
+ inputs = processor.apply_chat_template(
+ conversation,
+ add_generation_prompt = True,
+ tokenize = True,
+ return_dict = True,
+ sampling_rate = entry["sample_rate"],
+ return_tensors = "pt",
+ ).to(model.device)
+ kwargs = {
+ "max_new_tokens": int(max_new_tokens),
+ "do_sample": float(temperature) > 0,
+ }
+ if kwargs["do_sample"]:
+ kwargs.update(temperature = float(temperature), top_p = float(top_p), top_k = int(top_k))
+ stopping = _stopping_criteria(cancel_event)
+ if stopping is not None:
+ kwargs["stopping_criteria"] = stopping
+ outputs = model.generate(**inputs, **kwargs)
+ decoded = processor.batch_decode(outputs)
+ return decoded[0], entry["sample_rate"]
+
+ def _generate_moss_local(
+ self,
+ entry,
+ text,
+ instructions,
+ language,
+ temperature,
+ top_p,
+ top_k,
+ max_new_tokens,
+ repetition_penalty,
+ cancel_event,
+ ):
+ from core.inference.chat_template_helpers import neutralize_tts_prompt_text
+
+ text = neutralize_tts_prompt_text(text, "moss_tts_local")
+ if instructions is not None:
+ instructions = neutralize_tts_prompt_text(instructions, "moss_tts_local")
+ if language is not None:
+ language = neutralize_tts_prompt_text(language, "moss_tts_local")
+ processor = entry["processor"]
+ batch = processor(
+ [
+ [
+ processor.build_user_message(
+ text = text,
+ instruction = instructions,
+ language = language,
+ )
+ ]
+ ],
+ mode = "generation",
+ )
+ kwargs = {
+ "input_ids": batch["input_ids"].to(self.device),
+ "attention_mask": batch["attention_mask"].to(self.device),
+ "max_new_tokens": int(max_new_tokens),
+ "do_sample": float(temperature) > 0,
+ "audio_temperature": max(0.0, float(temperature)),
+ "audio_top_p": float(top_p),
+ "audio_top_k": int(top_k),
+ "audio_repetition_penalty": float(repetition_penalty),
+ }
+ model = entry["model"]
+ cancel_hooks = []
+ if cancel_event is not None:
+ for target in (
+ getattr(model, "transformer", None),
+ getattr(model, "local_transformer", None),
+ ):
+ if target is not None and hasattr(target, "register_forward_pre_hook"):
+ cancel_hooks.append(
+ target.register_forward_pre_hook(
+ lambda _module, _args: _raise_if_cancelled(cancel_event)
+ )
+ )
+ try:
+ outputs = model.generate(**kwargs)
+ finally:
+ for cancel_hook in cancel_hooks:
+ cancel_hook.remove()
+ message = next((item for item in processor.decode(outputs) if item is not None), None)
+ if message is None or not message.audio_codes_list:
+ raise RuntimeError("MOSS TTS Local returned no audio")
+ return message.audio_codes_list[0], entry["sample_rate"]
+
+ def _generate_moss_nano(
+ self,
+ entry,
+ text,
+ temperature,
+ top_p,
+ top_k,
+ max_new_tokens,
+ repetition_penalty,
+ cancel_event,
+ ) -> Tuple[bytes, int]:
+ from core.inference.chat_template_helpers import neutralize_tts_prompt_text
+ text = neutralize_tts_prompt_text(text, "moss_tts_nano")
+ with tempfile.TemporaryDirectory(prefix = "unsloth-moss-nano-") as temp_dir:
+ output_path = Path(temp_dir) / "speech.wav"
+ model = entry["model"]
+ cancel_hooks = []
+ if cancel_event is not None:
+ targets = (
+ getattr(model, "transformer", None),
+ getattr(model, "local_transformer", None),
+ entry["audio_codec"],
+ )
+ seen_targets = set()
+ for target in targets:
+ if id(target) in seen_targets or not hasattr(
+ target, "register_forward_pre_hook"
+ ):
+ continue
+ seen_targets.add(id(target))
+ cancel_hooks.append(
+ target.register_forward_pre_hook(
+ lambda _module, _args: _raise_if_cancelled(cancel_event)
+ )
+ )
+ try:
+ with _moss_nano_soundfile_save(model):
+ result = model.inference(
+ text = text,
+ output_audio_path = output_path,
+ mode = "continuation",
+ text_tokenizer = entry["processor"],
+ audio_tokenizer = entry["audio_codec"],
+ device = self.device,
+ max_new_frames = int(max_new_tokens),
+ do_sample = float(temperature) > 0,
+ text_temperature = MOSS_NANO_TEXT_TEMPERATURE,
+ text_top_p = MOSS_NANO_TEXT_TOP_P,
+ text_top_k = MOSS_NANO_TEXT_TOP_K,
+ audio_temperature = max(0.0, float(temperature)),
+ audio_top_p = float(top_p),
+ audio_top_k = int(top_k),
+ audio_repetition_penalty = float(repetition_penalty),
+ use_kv_cache = True,
+ )
+ finally:
+ for cancel_hook in cancel_hooks:
+ cancel_hook.remove()
+ _raise_if_cancelled(cancel_event)
+ sample_rate = int(result.get("sample_rate") or entry["sample_rate"])
+ return output_path.read_bytes(), sample_rate
+
+ @staticmethod
+ def _generate_higgs_tts3(entry, text, temperature, top_p, top_k, max_new_tokens, cancel_event):
+ from core.inference.chat_template_helpers import neutralize_tts_prompt_text
+
+ text = neutralize_tts_prompt_text(text, "higgs_tts3")
+ model = entry["model"]
+ cancel_hook = None
+ forward_model = getattr(model, "model", model)
+ if cancel_event is not None and hasattr(forward_model, "register_forward_pre_hook"):
+ cancel_hook = forward_model.register_forward_pre_hook(
+ lambda _module, _args: _raise_if_cancelled(cancel_event)
+ )
+ try:
+ audio = model.generate_speech(
+ text,
+ entry["processor"],
+ max_new_tokens = int(max_new_tokens),
+ temperature = max(0.0, float(temperature)),
+ top_p = float(top_p),
+ top_k = int(top_k),
+ )
+ finally:
+ if cancel_hook is not None:
+ cancel_hook.remove()
+ return audio, entry["sample_rate"]
+
+ def _generate_minimax_music3(
+ self, entry, lyrics, instructions, max_new_tokens, seed, cancel_event
+ ):
+ import torch
+ from core.inference.chat_template_helpers import neutralize_tts_prompt_text
+
+ prompt = str(instructions or "").strip()
+ if not prompt:
+ raise RuntimeError("MiniMax Music 3 requires a music description in addition to lyrics")
+ lyrics = neutralize_tts_prompt_text(lyrics, "minimax_music3")
+ generator = None
+ if seed is not None:
+ generator = torch.Generator(self.device).manual_seed(int(seed))
+ pipeline = entry["pipeline"]
+ frame_rate = float(getattr(pipeline, "frame_rate", 25.0) or 25.0)
+ audio_duration = float(max(1, int(max_new_tokens))) / frame_rate
+ pipeline_kwargs = dict(
+ prompt = prompt,
+ lyrics = _minimax_lyrics_for_pipeline(lyrics),
+ audio_duration = audio_duration,
+ output = "audios",
+ )
+ if generator is not None:
+ pipeline_kwargs["generator"] = generator
+ cancel_hooks = []
+ if cancel_event is not None:
+ language_model = getattr(pipeline, "language_model", None)
+ targets = (
+ getattr(language_model, "model", None),
+ getattr(pipeline, "rvq_depth_decoder", None),
+ getattr(pipeline, "condition_encoder", None),
+ getattr(pipeline, "transformer", None),
+ getattr(pipeline, "vocoder", None),
+ )
+ seen_targets = set()
+ for target in targets:
+ if id(target) in seen_targets or not hasattr(target, "register_forward_pre_hook"):
+ continue
+ seen_targets.add(id(target))
+ cancel_hooks.append(
+ target.register_forward_pre_hook(
+ lambda _module, _args: _raise_if_cancelled(cancel_event)
+ )
+ )
+ try:
+ audio = pipeline(**pipeline_kwargs)[0]
+ finally:
+ for cancel_hook in cancel_hooks:
+ cancel_hook.remove()
+ return audio, entry["sample_rate"]
+
+ def unload_model(self, model_name: str) -> bool:
+ entry = self.models.pop(model_name, None)
+ if entry is not None:
+ entry.clear()
+ if self.active_model_name == model_name:
+ self.active_model_name = None
+ self.reset_generation_state()
+ return True
+
+ def reset_generation_state(self, caller_cancel_event = None) -> None:
+ del caller_cancel_event
+ gc.collect()
+ try:
+ import torch
+ if self.device == "cuda":
+ torch.cuda.empty_cache()
+ elif self.device == "xpu" and hasattr(torch, "xpu"):
+ torch.xpu.empty_cache()
+ elif self.device == "mps" and hasattr(torch, "mps"):
+ torch.mps.empty_cache()
+ except Exception:
+ logger.debug("Could not clear native audio device cache", exc_info = True)
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index af065b89d82..14c5ed250a8 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -73,6 +73,8 @@ _DISPATCH_DRAIN_TIMEOUT = 5.0
_AUDIO_GENERATION_TIMEOUT = 900.0
_AUDIO_GENERATION_BASE_TOKENS = 2048
AUDIO_GENERATION_MAX_TOKENS = 8192
+MOSS_TTS_MAX_FRAMES = 32768
+MINIMAX_MUSIC_MAX_FRAMES = 9000
_AUDIO_CANCEL_DRAIN_TIMEOUT = 5.0
# Before audio_started there is nobody to receive the cancel, and a prefill pass (a 3B TTS
# model on CPU, or OuteTTS's per-token Python repetition penalty) routinely outlasts the
@@ -84,7 +86,11 @@ _AUDIO_CANCEL_TEARDOWN_TIMEOUT = 30.0
_UNLOAD_GEN_LOCK_TIMEOUT = 15.0
-def _audio_generation_timeout(max_new_tokens: int, base: Optional[float] = None) -> float:
+def _audio_generation_timeout(
+ max_new_tokens: int,
+ base: Optional[float] = None,
+ max_tokens: Optional[int] = None,
+) -> float:
"""Scale a floor by the requested token count.
``base`` differs per backend by an order of magnitude: the Transformers subprocess
@@ -97,7 +103,9 @@ def _audio_generation_timeout(max_new_tokens: int, base: Optional[float] = None)
"""
if base is None:
base = _AUDIO_GENERATION_TIMEOUT
- max_new_tokens = min(AUDIO_GENERATION_MAX_TOKENS, max(1, int(max_new_tokens)))
+ if max_tokens is None:
+ max_tokens = AUDIO_GENERATION_MAX_TOKENS
+ max_new_tokens = min(max(1, int(max_tokens)), max(1, int(max_new_tokens)))
token_scale = max(1.0, max_new_tokens / _AUDIO_GENERATION_BASE_TOKENS)
return base * token_scale
@@ -247,6 +255,10 @@ class InferenceOrchestrator:
# lane for the whole TTS request so its shared cancel event cannot hit a sibling.
# Mutated under _dispatcher_lifecycle_lock while holding _gen_lock.
self._exclusive_tts_pending = False
+ # A live VRAM probe is another exclusive worker command. Compare-mode
+ # requests bypass _gen_lock, so reserve their admission lane while the
+ # parent asks the idle worker for allocator-owned bytes.
+ self._exclusive_vram_probe_pending = False
# Dispatcher state for compare mode (adapter-controlled requests):
# bypass _gen_lock, send commands directly, read from per-request
@@ -466,6 +478,82 @@ class InferenceOrchestrator:
proc = self._proc
return proc is not None and proc.is_alive()
+ def post_handoff_gpu_availability_gb(
+ self,
+ ) -> Optional[tuple[dict[int, float], dict[int, float], dict[int, float]]]:
+ """Atomically snapshot live free, total and disposable-worker VRAM.
+
+ The worker is queried only while idle. This avoids retaining a load-time
+ allocator value after reset_generation_state() releases cache, and it keeps
+ compare-mode's queue reader from consuming the probe response. The send
+ lock spans the system and worker reads, so a reset cannot make the same
+ cache bytes appear in both values.
+ """
+ proc = self._proc
+ active = self.active_model_name
+ if proc is None or not proc.is_alive() or not active:
+ return None
+
+ with self._dispatcher_lifecycle_lock:
+ if self._exclusive_tts_pending or getattr(self, "_exclusive_vram_probe_pending", False):
+ return None
+ self._exclusive_vram_probe_pending = True
+ acquired = False
+ try:
+ if not self._wait_dispatcher_idle():
+ return None
+ acquired = self._gen_lock.acquire(timeout = 5.0)
+ if not acquired:
+ return None
+ with self._active_cancel_lock:
+ if self._active_cancel_events:
+ return None
+ if self._proc is not proc or not proc.is_alive() or self.active_model_name != active:
+ return None
+ request_id = str(uuid.uuid4())
+ with self._send_order_lock:
+ from utils.hardware import get_visible_gpu_utilization
+
+ live_free: dict[int, float] = {}
+ total_by_index: dict[int, float] = {}
+ for device in get_visible_gpu_utilization().get("devices", []):
+ try:
+ index = int(device["index"])
+ total = float(device["vram_total_gb"])
+ used = float(device["vram_used_gb"])
+ except (KeyError, TypeError, ValueError):
+ continue
+ live_free[index] = max(total - used, 0.0)
+ total_by_index[index] = total
+ if not live_free:
+ return None
+ self._send_cmd({"type": "gpu_memory", "request_id": request_id})
+ response = self._wait_response(
+ "gpu_memory",
+ timeout = 5.0,
+ expected_request_id = request_id,
+ )
+ if self._proc is not proc or not proc.is_alive() or self.active_model_name != active:
+ return None
+ reported = response.get("reclaimable_gpu_gb")
+ if not isinstance(reported, dict):
+ return None
+ try:
+ reclaimable = {
+ int(index): max(float(value), 0.0) for index, value in reported.items()
+ }
+ return live_free, total_by_index, reclaimable
+ except (TypeError, ValueError):
+ return None
+ except Exception as exc:
+ logger.warning("Could not query inference worker GPU memory: %s", exc)
+ return None
+ finally:
+ if acquired:
+ self._gen_lock.release()
+ with self._dispatcher_lifecycle_lock:
+ self._exclusive_vram_probe_pending = False
+
def _shutdown_subprocess(self, timeout: float = 10.0) -> bool:
with self._subprocess_shutdown_lock:
return self._shutdown_subprocess_locked(timeout)
@@ -544,6 +632,81 @@ class InferenceOrchestrator:
logger.info("Inference subprocess shut down")
return True
+ @staticmethod
+ def _wait_for_worker_vram_settle(
+ since_kill: float,
+ *,
+ expected_free_gb: Optional[dict[int, float]] = None,
+ max_wait: float = 2.0,
+ interval: float = 0.25,
+ tolerance_mib: int = 256,
+ ) -> bool:
+ """Poll cross-platform live telemetry until dead-worker VRAM stabilises."""
+ from utils.hardware import get_visible_gpu_utilization
+
+ if since_kill <= 0:
+ return not expected_free_gb
+ deadline = time.monotonic() + max(max_wait, 0.0)
+
+ def _probe() -> Optional[dict[int, int]]:
+ if time.monotonic() >= deadline:
+ return None
+ try:
+ result: dict[int, int] = {}
+ for device in get_visible_gpu_utilization().get("devices", []):
+ index = int(device["index"])
+ total = float(device["vram_total_gb"])
+ used = float(device["vram_used_gb"])
+ result[index] = max(int((total - used) * 1024), 0)
+ return result or None
+ except (KeyError, TypeError, ValueError, OverflowError):
+ return None
+
+ previous = _probe()
+ if not previous:
+ return not expected_free_gb
+ expected_mib = {
+ int(index): max(int(float(value) * 1024), 0)
+ for index, value in (expected_free_gb or {}).items()
+ }
+
+ def _threshold_reached(sample: dict[int, int]) -> bool:
+ return bool(expected_mib) and all(
+ sample.get(index, -1) >= required for index, required in expected_mib.items()
+ )
+
+ if _threshold_reached(previous):
+ return True
+ observed_reclaim = False
+ while time.monotonic() < deadline:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ time.sleep(min(interval, remaining))
+ current = _probe()
+ if not current or current.keys() != previous.keys():
+ return not expected_free_gb
+ if any(
+ current[index] - previous[index]
+ >= max(tolerance_mib, int(max(current[index], previous[index]) * 0.02))
+ for index in current
+ ):
+ observed_reclaim = True
+ if _threshold_reached(current):
+ return True
+ stable = all(
+ abs(current[index] - previous[index])
+ < max(tolerance_mib, int(max(current[index], previous[index]) * 0.02))
+ for index in current
+ )
+ # Two unchanged low samples can precede delayed driver reclaim.
+ # Stability is meaningful only after an upward release was observed;
+ # otherwise consume the full bounded window.
+ if stable and observed_reclaim and not expected_mib:
+ return True
+ previous = current
+ return not expected_free_gb
+
def _reset_worker_scoped_state(self) -> None:
"""Drop bookkeeping that only means anything for the worker that just died.
@@ -632,6 +795,7 @@ class InferenceOrchestrator:
self,
expected_type: str,
timeout: float = 300.0,
+ expected_request_id: Optional[str] = None,
cancel_event: Optional[threading.Event] = None,
) -> dict:
"""Block until a response of the expected type arrives.
@@ -664,7 +828,9 @@ class InferenceOrchestrator:
rtype = resp.get("type", "")
- if rtype == expected_type:
+ if rtype == expected_type and (
+ expected_request_id is None or resp.get("request_id") == expected_request_id
+ ):
return resp
if rtype == "error":
@@ -965,7 +1131,11 @@ class InferenceOrchestrator:
# after the stop, become the resp_queue reader, and consume the
# worker's "unloaded" reply (unroutable, so dropped) before
# unload_model's _wait_response sees it -- hanging the unload 300s.
- if self._unload_pending or self._exclusive_tts_pending:
+ if (
+ self._unload_pending
+ or self._exclusive_tts_pending
+ or getattr(self, "_exclusive_vram_probe_pending", False)
+ ):
return False
if self._dispatcher_thread is not None and self._dispatcher_thread.is_alive():
return False
@@ -1161,7 +1331,8 @@ class InferenceOrchestrator:
or not dispatcher_alive
)
tts_reserved = self._exclusive_tts_pending
- blocked = unloading or tts_reserved
+ probe_reserved = getattr(self, "_exclusive_vram_probe_pending", False)
+ blocked = unloading or tts_reserved or probe_reserved
if not blocked:
self._mailboxes[request_id] = mailbox
if cancel_event is not None:
@@ -1181,6 +1352,8 @@ class InferenceOrchestrator:
detail = (
"Error: audio generation is in progress"
if tts_reserved
+ else "Error: model switch is checking GPU memory"
+ if probe_reserved
else "Error: model is being unloaded"
)
yield GenStreamError(detail, public = True)
@@ -1367,6 +1540,7 @@ class InferenceOrchestrator:
mlx_kv_bits: Optional[int] = None,
chat_template_override: Optional[str] = None,
load_cancel_event: Optional[threading.Event] = None,
+ post_handoff_expected_free_gb: Optional[dict[int, float]] = None,
) -> bool:
"""Load a model for inference.
@@ -1441,6 +1615,8 @@ class InferenceOrchestrator:
# Always kill the existing subprocess and spawn fresh: reusing one
# after unsloth patches torch internals breaks getsource on reload.
+ had_worker_handle = self._proc is not None
+ worker_shutdown_at = 0.0
if self._ensure_subprocess_alive():
self._cancel_generation()
time.sleep(0.3)
@@ -1453,8 +1629,31 @@ class InferenceOrchestrator:
"The current inference worker did not exit and still holds GPU "
"memory; not starting a new model over it. Retry shortly."
)
+ worker_shutdown_at = time.monotonic()
elif self._proc is not None:
self._shutdown_subprocess(timeout = 2)
+ if self._proc is None:
+ worker_shutdown_at = time.monotonic()
+
+ if had_worker_handle or post_handoff_expected_free_gb:
+ expected_free_gb = post_handoff_expected_free_gb
+ if (
+ expected_free_gb is None
+ and len(resolved_gpu_ids or ()) == 1
+ and isinstance(gpu_selection, dict)
+ ):
+ required_gb = gpu_selection.get("required_gb")
+ if required_gb is not None:
+ expected_free_gb = {int(resolved_gpu_ids[0]): float(required_gb)}
+ settled = self._wait_for_worker_vram_settle(
+ worker_shutdown_at or time.monotonic(),
+ expected_free_gb = expected_free_gb,
+ )
+ if expected_free_gb is not None and not settled:
+ raise RuntimeError(
+ "GPU memory from the previous inference worker was not released; "
+ "not starting the replacement model. Retry shortly."
+ )
disable_xet = sub_config.get("disable_xet", False) or (
os.environ.get("HF_HUB_DISABLE_XET") == "1"
@@ -2252,7 +2451,8 @@ class InferenceOrchestrator:
if not self._ensure_subprocess_alive():
return
try:
- self._send_cmd({"type": "reset"})
+ with self._send_order_lock:
+ self._send_cmd({"type": "reset"})
except RuntimeError:
pass
@@ -2271,6 +2471,9 @@ class InferenceOrchestrator:
repetition_penalty: float = 1.0,
use_adapter: Optional[Union[bool, str]] = None,
cancel_event = None,
+ instructions: Optional[str] = None,
+ language: Optional[str] = None,
+ seed: Optional[int] = None,
) -> Tuple[bytes, int]:
"""Generate TTS audio. Returns (wav_bytes, sample_rate).
@@ -2305,11 +2508,25 @@ class InferenceOrchestrator:
# Bound public API integers before either enqueuing work or
# calculating the floating-point watchdog deadline.
+ model_info = self.models.get(expected_model, {})
+ audio_type = model_info.get("audio_type")
+ max_token_ceiling = AUDIO_GENERATION_MAX_TOKENS
+ if audio_type in ("moss_tts_local", "moss_tts_nano"):
+ try:
+ detected_context = int(model_info.get("context_length") or 0)
+ except (TypeError, ValueError):
+ detected_context = 0
+ max_token_ceiling = detected_context or MOSS_TTS_MAX_FRAMES
+ elif audio_type == "minimax_music3":
+ max_token_ceiling = MINIMAX_MUSIC_MAX_FRAMES
max_new_tokens = min(
- AUDIO_GENERATION_MAX_TOKENS,
+ max_token_ceiling,
max(1, int(max_new_tokens)),
)
- generation_timeout = _audio_generation_timeout(max_new_tokens)
+ generation_timeout = _audio_generation_timeout(
+ max_new_tokens,
+ max_tokens = max_token_ceiling,
+ )
request_id = str(uuid.uuid4())
cmd = {
@@ -2325,6 +2542,12 @@ class InferenceOrchestrator:
}
if use_adapter is not None:
cmd["use_adapter"] = use_adapter
+ if instructions is not None:
+ cmd["instructions"] = instructions
+ if language is not None:
+ cmd["language"] = language
+ if seed is not None:
+ cmd["seed"] = int(seed)
# Same shared-queue hazard as _generate_inner: see _direct_reader.
read_one, _drain, release_mailbox = self._direct_reader(request_id)
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 88ab33e9848..d541169b229 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -885,6 +885,10 @@ class _SdState:
# ``offload_flags`` still describe the build the load committed to. None on the server path,
# which asks the same question at start time against its own local copy.
sd_accelerator: Optional[str] = None
+ # Physical card behind the server's single resolved CUDA/ROCm backend.
+ # None for CPU/Metal/Vulkan, an unresolved pin, automatic multi-GPU, and
+ # one-shot mode; those shapes cannot safely consume the startup VRAM floor.
+ physical_gpu_id: Optional[int] = None
def _offload_with_device_pin_impl(
@@ -897,6 +901,42 @@ def _offload_with_device_pin_impl(
return [*flags, *device_backend_flags(sd_cpp_device_name_for_ordinal(binary, ordinal), flags)]
+def _resolved_server_physical_gpu_id(
+ binary: Optional[str], device: str, ordinal: Optional[int], committed_flags: tuple[str, ...]
+) -> Optional[int]:
+ """Physical id for a provably single-device resident sd-server."""
+ if device != "cuda" or "--offload-to-cpu" in committed_flags:
+ return None
+ try:
+ from utils.hardware import get_parent_visible_gpu_ids
+ visible = [int(i) for i in get_parent_visible_gpu_ids()]
+ except Exception:
+ return None
+ local_ordinal = ordinal
+ if local_ordinal is None:
+ if len(visible) != 1:
+ return None
+ local_ordinal = 0
+ if local_ordinal < 0 or local_ordinal >= len(visible):
+ return None
+ device_name = sd_cpp_device_name_for_ordinal(binary, local_ordinal)
+ if device_name is None:
+ return None
+ if ordinal is not None:
+ # An explicit request is attributable only when the committed argv
+ # actually contains the resolved per-module pin. If the probe failed,
+ # sd.cpp falls back to its own default and the requested ordinal is not
+ # evidence of placement.
+ specs = [
+ committed_flags[index + 1]
+ for index, flag in enumerate(committed_flags[:-1])
+ if flag == "--backend"
+ ]
+ if not any(device_name in spec for spec in specs):
+ return None
+ return visible[local_ordinal]
+
+
def _memory_policy(memory_mode: Optional[str], cpu_offload: bool) -> str:
"""Map the diffusers memory knobs onto an sd-cli offload policy. Only meaningful
off-CPU (forced sd_cpp / MPS); on CPU everything is resident in RAM anyway."""
@@ -1664,6 +1704,13 @@ class SdCppDiffusionBackend:
"The stable-diffusion.cpp binary was replaced by an install for a "
"different accelerator while this model was loading. Try the load again."
)
+ committed_offload_flags = tuple(
+ _offload_with_device_pin_impl(
+ offload,
+ server_binary if mode == "server" else getattr(engine, "binary", None),
+ gpu_ordinal,
+ )
+ )
state = _SdState(
repo_id = repo_id,
base_repo = base,
@@ -1674,13 +1721,7 @@ class SdCppDiffusionBackend:
native_speed = native_speed,
# Pinned against the binary this load COMMITTED to, which a deferred install or
# a one-shot fallback may have changed since the policy was built.
- offload_flags = tuple(
- _offload_with_device_pin_impl(
- offload,
- server_binary if mode == "server" else getattr(engine, "binary", None),
- gpu_ordinal,
- )
- ),
+ offload_flags = committed_offload_flags,
# One-shot sd-cli reads this per generation; pin to physical cores.
threads = _default_threads(),
sampling_method = fam.sd_cpp_sampling_method,
@@ -1693,6 +1734,16 @@ class SdCppDiffusionBackend:
# Only the one-shot path needs to carry it: it re-resolves sd-cli per image,
# long after this decision, and has nothing else to check the answer against.
sd_accelerator = engine_accelerator if mode == "oneshot" else None,
+ physical_gpu_id = (
+ _resolved_server_physical_gpu_id(
+ server_binary,
+ device,
+ gpu_ordinal,
+ committed_offload_flags,
+ )
+ if mode == "server"
+ else None
+ ),
)
superseded = False
orphan: Optional[SdCppServer] = None
diff --git a/studio/backend/core/inference/sd_cpp_server.py b/studio/backend/core/inference/sd_cpp_server.py
index b8f61561d4d..85f4474abb1 100644
--- a/studio/backend/core/inference/sd_cpp_server.py
+++ b/studio/backend/core/inference/sd_cpp_server.py
@@ -34,6 +34,7 @@ from __future__ import annotations
import atexit
import base64
import logging
+import re
import shutil
import socket
import subprocess
@@ -71,6 +72,14 @@ _READY_PATH = "/v1/models"
_IMG_GEN_PATH = "/sdcpp/v1/img_gen"
_JOBS_PATH = "/sdcpp/v1/jobs"
+# Stable parameter residency reported once during startup. Compute-buffer
+# lines are deliberately excluded: those allocations can change between
+# generations, while this floor lives until the server process exits.
+_TOTAL_PARAMS_VRAM_RE = re.compile(
+ r"total params memory size\s*=\s*[0-9.]+\s*MB\s*\(\s*VRAM\s+([0-9]+(?:\.[0-9]+)?)\s*MB\b",
+ re.IGNORECASE,
+)
+
_TERMINAL_OK = "completed"
_TERMINAL_FAIL = "failed"
_TERMINAL_CANCELLED = "cancelled"
@@ -151,6 +160,7 @@ class SdCppServer:
self.host = host
self.port: Optional[int] = None
self._process: Optional[subprocess.Popen] = None
+ self._resident_params_vram_gb: Optional[float] = None
# Bounded tail buffer shared by the drain thread (appends) and readers (diagnostics).
self._tail: deque[str] = deque(maxlen = 200)
self._stdout_thread: Optional[threading.Thread] = None
@@ -234,6 +244,7 @@ class SdCppServer:
logger.info("starting sd-server: %s", " ".join(cmd))
# Clear in place; reassigning [] would drop the maxlen bound and grow unbounded.
self._tail.clear()
+ self._resident_params_vram_gb = None
self._spawn_error: Optional[Exception] = None
spawned = threading.Event()
@@ -366,6 +377,11 @@ class SdCppServer:
if not line:
continue
self._tail.append(line)
+ match = _TOTAL_PARAMS_VRAM_RE.search(line)
+ if match is not None:
+ value = float(match.group(1)) / 1024.0
+ if value > 0:
+ self._resident_params_vram_gb = value
logger.debug("[sd-server] %s", line)
cb = self._step_listener
if cb is not None:
@@ -376,6 +392,25 @@ class SdCppServer:
except Exception: # noqa: BLE001 -- drain thread must never raise (pipe closed at teardown)
pass
+ def reclaimable_params_vram_gb(
+ self, physical_gpu_id: Optional[int]
+ ) -> Optional[dict[int, float]]:
+ """Stable resident parameter floor released when this server stops.
+
+ Device attribution is supplied by the backend that resolved the
+ CUDA/ROCm child pin. Missing attribution or a changing/dead process
+ fails closed.
+ """
+ process = self._process
+ if physical_gpu_id is None or process is None or process.poll() is not None:
+ return None
+ value = self._resident_params_vram_gb
+ if value is None or value <= 0:
+ return None
+ if self._process is not process or process.poll() is not None:
+ return None
+ return {int(physical_gpu_id): float(value)}
+
def stop(self) -> None:
"""Terminate the server (SIGTERM -> SIGKILL), join the drain, and release the HTTP
client + atexit handler. Idempotent."""
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index cf7d23e5738..20b96f209b4 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -47,6 +47,24 @@ def _ensure_backend_on_path() -> None:
sys.path.insert(0, _BACKEND_PATH)
+def _native_audio_security_targets_or_error(
+ model_name: str, hf_token: str | None, resp_queue: Any
+) -> list[str] | None:
+ try:
+ from core.inference.native_audio import native_audio_security_targets
+ return native_audio_security_targets(model_name, hf_token = hf_token)
+ except Exception as exc:
+ _send_response(
+ resp_queue,
+ {
+ "type": "error",
+ "error": f"Failed to inspect native audio security metadata: {exc}",
+ "stack": traceback.format_exc(limit = 20),
+ },
+ )
+ return None
+
+
def _recorded_local_base(model_name) -> "tuple[str | None, bool]":
"""``(base, needs_hub)`` for the base this checkpoint records on disk.
@@ -341,6 +359,28 @@ def _run_security_gates(
return True
+def _worker_reclaimable_gpu_gb(config: dict) -> dict[str, float] | None:
+ """Live allocator-owned VRAM this disposable worker will release."""
+ resolved_gpu_ids = config.get("resolved_gpu_ids")
+ device_backend = str(config.get("device_backend") or "")
+ if not resolved_gpu_ids or device_backend not in ("cuda", "xpu"):
+ return None
+ try:
+ import torch
+
+ device_module = torch.cuda if device_backend == "cuda" else torch.xpu
+ memory_reserved = getattr(device_module, "memory_reserved", None)
+ if not callable(memory_reserved):
+ return None
+ return {
+ str(int(physical_id)): int(memory_reserved(local_ordinal)) / float(1024**3)
+ for local_ordinal, physical_id in enumerate(resolved_gpu_ids)
+ }
+ except Exception as exc:
+ logger.warning("Could not report worker-owned GPU memory: %s", exc)
+ return None
+
+
def _handle_load(backend, config: dict, resp_queue: Any) -> None:
"""Handle a load command: load a model into the backend."""
try:
@@ -370,7 +410,11 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
# Authoritative gates over the model + the LoRA base resolved via mc. Must run before
# the SSM install so a blocked model never triggers a native kernel build.
- targets = [config["model_name"]]
+ from core.inference.native_audio import native_audio_security_targets
+
+ targets = native_audio_security_targets(
+ config["model_name"], getattr(mc, "audio_type", None), hf_token
+ )
if mc.is_lora and getattr(mc, "base_model", None):
targets.append(str(mc.base_model))
if not _run_security_gates(
@@ -773,6 +817,9 @@ def _handle_generate_audio(backend, cmd: dict, resp_queue: Any, cancel_event) ->
repetition_penalty = cmd.get("repetition_penalty", 1.0),
use_adapter = cmd.get("use_adapter"),
cancel_event = cancel_event,
+ instructions = cmd.get("instructions"),
+ language = cmd.get("language"),
+ seed = cmd.get("seed"),
)
# Send WAV bytes as base64 (bytes can't go through mp.Queue directly).
@@ -999,6 +1046,13 @@ def run_inference_process(
model_name = config["model_name"]
+ # These architectures use their publishers' native Transformers/Diffusers
+ # interfaces. Select that backend before the Apple MLX fast-path and before
+ # importing Unsloth; native_audio itself has no eager ML imports.
+ from core.inference.native_audio import is_native_audio_model
+
+ _native_audio_worker = is_native_audio_model(model_name)
+
# ── 0. MLX fast-path — skip torch/transformers ──
_ensure_backend_on_path()
@@ -1018,7 +1072,7 @@ def run_inference_process(
from utils.hardware import hardware as _hw
_hw.detect_hardware()
- if _hw.DEVICE == _hw.DeviceType.MLX:
+ if _hw.DEVICE == _hw.DeviceType.MLX and not _native_audio_worker:
try:
from core.inference.mlx_inference import MLXInferenceBackend, _init_mlx_distributed
@@ -1126,6 +1180,15 @@ def run_inference_process(
cancel_event.set()
backend.reset_generation_state()
_send_response(resp_queue, {"type": "reset_ack"})
+ elif cmd_type == "gpu_memory":
+ _send_response(
+ resp_queue,
+ {
+ "type": "gpu_memory",
+ "request_id": cmd.get("request_id"),
+ "reclaimable_gpu_gb": _worker_reclaimable_gpu_gb(config),
+ },
+ )
elif cmd_type == "status":
_send_response(
resp_queue,
@@ -1236,7 +1299,9 @@ def run_inference_process(
# are metadata-only, so run them first and refuse a blocked model before any native build.
# Gate only the model + a genuine LoRA base (matching _handle_load), never a full fine-tune's
# unloaded base; _handle_load re-runs the authoritative gates with the mc base.
- _gate_targets = [model_name]
+ _gate_targets = _native_audio_security_targets_or_error(model_name, _hf_token, resp_queue)
+ if _gate_targets is None:
+ return
if _lora_base:
_gate_targets.append(_lora_base)
_trust_remote_code = config.get("trust_remote_code", False) or _needs_nemotron_trust(
@@ -1266,18 +1331,24 @@ def run_inference_process(
resp_queue,
{
"type": "status",
- "message": "Importing Unsloth...",
+ "message": (
+ "Importing native audio runtime..."
+ if _native_audio_worker
+ else "Importing Unsloth..."
+ ),
},
)
_ensure_backend_on_path()
- # Recover from any namespace-package shadow before importing Unsloth.
- from core.import_guards import ensure_real_packages
-
- ensure_real_packages("unsloth_zoo", "unsloth")
+ if _native_audio_worker:
+ from core.inference.native_audio import NativeAudioBackend as InferenceBackend
+ else:
+ # Recover from any namespace-package shadow before importing Unsloth.
+ from core.import_guards import ensure_real_packages
+ ensure_real_packages("unsloth_zoo", "unsloth")
- from core.inference.inference import InferenceBackend
+ from core.inference.inference import InferenceBackend
import transformers
@@ -1388,6 +1459,16 @@ def run_inference_process(
},
)
+ elif cmd_type == "gpu_memory":
+ _send_response(
+ resp_queue,
+ {
+ "type": "gpu_memory",
+ "request_id": cmd.get("request_id"),
+ "reclaimable_gpu_gb": _worker_reclaimable_gpu_gb(config),
+ },
+ )
+
elif cmd_type == "status":
_send_response(
resp_queue,
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index 60ebf862ebb..04a6bc60c7d 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -163,7 +163,7 @@ class LocalModelInfo(BaseModel):
)
audio_type: Optional[str] = Field(
None,
- description = "Detected output-audio codec used to decide whether Audio can run the row",
+ description = "Detected output-audio architecture or codec used by Audio runtime policy",
)
base_model: Optional[str] = Field(
None,
@@ -264,6 +264,7 @@ class CachedGgufResponse(BaseModel):
class CachedModelRepo(CachedRepoBase):
+ audio_type: Optional[str] = None
quant_method: Optional[str] = None
pipeline_tag: Optional[str] = None
library_name: Optional[str] = None
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 3533ea41323..b1633572d63 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -443,8 +443,9 @@ def _cache_inventory_fields(
capabilities["supports_vision"] = False
capabilities["can_chat"] = False
# Same rule for the speech-emitting half of the Audio page. The codec probe in
- # _local_transformers_can_chat covers uncurated safetensors copies; a GGUF repo ships
- # no tokenizer_config to probe, so the curated ids answer for those.
+ # _local_transformers_can_chat covers uncurated safetensors copies; native audio
+ # architectures are also passed explicitly. A GGUF repo ships no tokenizer_config
+ # to probe, so the curated ids answer for those.
if tts_only or is_curated_tts_repo_id(repo_id):
capabilities["can_chat"] = False
if hidden_infra:
@@ -477,8 +478,8 @@ def _is_hidden_infra_repo(*values: str | None) -> bool:
return is_hidden_model(*values)
-def _cached_row_companion(repo_id: str) -> bool:
- """Whether this row is an sd.cpp companion mirror (VAE / text encoders, no denoiser).
+def _cached_row_companion(repo_id: str, snapshot: Optional[Path] = None) -> bool:
+ """Whether this row is infrastructure for another load, not a checkpoint.
Same classifier the models API uses. The chat picker is backed by THIS endpoint, so a flag set
only on the legacy route arrives as undefined here and the filter never fires -- the same trap
@@ -486,7 +487,39 @@ def _cached_row_companion(repo_id: str) -> bool:
"""
try:
from core.inference.diffusion_families import sd_cpp_companion_only_repo_ids
- return (repo_id or "").strip().lower() in sd_cpp_companion_only_repo_ids()
+
+ normalized = (repo_id or "").strip().lower()
+ if normalized in sd_cpp_companion_only_repo_ids():
+ return True
+
+ from core.inference.native_audio import NATIVE_AUDIO_COMPANION_REPOS
+
+ native_companions = {
+ companion.strip().lower()
+ for companions in NATIVE_AUDIO_COMPANION_REPOS.values()
+ for companion in companions
+ }
+ if normalized in native_companions:
+ return True
+
+ # MOSS Local may name a different compatible tokenizer in its processor
+ # config. Classify the codec architecture too, so that dynamically
+ # resolved companion cannot surface as a chat checkpoint after download.
+ config = _read_json_object(snapshot / "config.json") if snapshot is not None else {}
+ model_type = str(config.get("model_type") or "").strip().lower()
+ if model_type in {
+ "moss-audio-tokenizer",
+ "moss-audio-tokenizer-nano",
+ "moss_audio_tokenizer",
+ "speech_tokenizer",
+ "higgs_audio_v2_tokenizer",
+ }:
+ return True
+ architectures = config.get("architectures")
+ return isinstance(architectures, list) and any(
+ str(name) in {"MossAudioTokenizerModel", "HiggsAudioV2TokenizerModel"}
+ for name in architectures
+ )
except Exception: # noqa: BLE001 -- a classification failure never hides a row
return False
@@ -881,6 +914,9 @@ def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:
# config.json), payload_snapshots came back empty, and every cached diffusion base
# pipeline was force-flagged partial and dropped from the On Device lists.
("model_index.json", "has_config"),
+ # Modular Diffusers pipelines use this root manifest instead. Saved or custom
+ # modular snapshots may omit both conventional root manifests.
+ ("modular_model_index.json", "has_config"),
("adapter_config.json", "has_adapter_config"),
):
try:
@@ -1102,7 +1138,6 @@ def _scan_cached_models(
)
is_whisper_stt = local_metadata.pop("_hidden_stt", False)
tts_audio_type = local_metadata.pop("_tts_audio_type", None)
- is_tts = tts_audio_type is not None
# Scoped to the row's snapshot, so an incomplete newer revision cannot flip can_chat.
download_partial = hf_cache_scan.is_snapshot_partial(
"model",
@@ -1129,6 +1164,13 @@ def _scan_cached_models(
# serves the row and it would reach for the Hub.
if not payload.payload_snapshots:
snapshot_partial = True
+ try:
+ from core.inference.native_audio import native_audio_type_from_local_path
+ native_audio_type = native_audio_type_from_local_path(str(load_snapshot or ""))
+ except Exception:
+ native_audio_type = None
+ audio_type = native_audio_type or tts_audio_type
+ is_output_audio = audio_type is not None
row_task = (
"automatic-speech-recognition"
if is_whisper_stt
@@ -1136,7 +1178,7 @@ def _scan_cached_models(
"text-to-speech"
# The probe answers for a repo whose card says nothing, so the
# Audio page, which selects by task, still lists it.
- if is_tts or local_metadata.get("pipeline_tag") == "text-to-speech"
+ if is_output_audio or local_metadata.get("pipeline_tag") == "text-to-speech"
else _cached_row_task(repo_info, gguf = False, selected = load_snapshot)
)
)
@@ -1152,7 +1194,7 @@ def _scan_cached_models(
"size_bytes": payload.size_bytes,
"cache_path": str(repo_info.repo_path),
"task": row_task,
- "audio_type": tts_audio_type,
+ "audio_type": audio_type,
"partial": snapshot_partial,
"partial_transport": (
hf_cache_scan.partial_transport_for(
@@ -1182,7 +1224,7 @@ def _scan_cached_models(
),
# Listed so tens of GB of companion weights stay visible and deletable, but
# flagged so no picker offers a denoiser-less repo as a load.
- "companion": _cached_row_companion(repo_id),
+ "companion": _cached_row_companion(repo_id, load_snapshot),
"diffusers": _cached_row_is_diffusers(repo_info, load_snapshot),
**local_metadata,
}
@@ -1201,9 +1243,14 @@ def _scan_cached_models(
hidden_infra = is_hidden_infra,
companion = bool(row["companion"]),
stt_only = bool(is_whisper_stt),
- tts_only = is_tts,
+ tts_only = is_output_audio,
)
)
+ # Native backend selection reads the load identity itself. A custom native
+ # fork addressed only by repo id is indistinguishable from an ordinary LLM,
+ # even though this inventory row detected its architecture from the snapshot.
+ if native_audio_type and load_snapshot is not None:
+ row["load_id"] = str(load_snapshot)
if _prefer_cache_row(row, existing):
seen_lower[key] = row
elif last_modified > existing.get("last_modified", 0.0):
diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.py
index 6220df48790..23fc04722c7 100644
--- a/studio/backend/hub/services/models/catalog_classification.py
+++ b/studio/backend/hub/services/models/catalog_classification.py
@@ -406,6 +406,12 @@ def _local_model_task(model) -> Optional[str]:
id_hints = (model.model_id, model.display_name, model.id)
if model.model_format == "gguf" or Path(path).suffix.lower() == ".gguf":
return _gguf_path_task(path, id_hints)
+ try:
+ from core.inference.native_audio import native_audio_type_from_local_path
+ if native_audio_type_from_local_path(path):
+ return "text-to-speech"
+ except Exception:
+ pass
if not _local_is_diffusers(model):
return None
try:
@@ -441,6 +447,13 @@ def _local_model_audio_type(model) -> Optional[str]:
path = model.path
if model.model_format == "gguf" or Path(path).suffix.lower() == ".gguf":
return _gguf_path_audio_type(path, (model.model_id, model.display_name, model.id))
+ try:
+ from core.inference.native_audio import native_audio_type_from_local_path
+ native_audio_type = native_audio_type_from_local_path(path)
+ if native_audio_type is not None:
+ return native_audio_type
+ except Exception:
+ pass
try:
from utils.audio_tokens import detect_local_tts_audio_type
return detect_local_tts_audio_type(path)
@@ -448,17 +461,23 @@ def _local_model_audio_type(model) -> Optional[str]:
return None
-def _local_model_classification(model) -> tuple[Optional[str], Optional[str]]:
- """Return picker task and decoder provenance from one local-row probe."""
- task = _local_model_task(model)
+def _local_model_classification_for_task(
+ model, task: Optional[str]
+) -> tuple[Optional[str], Optional[str]]:
+ """Add decoder provenance to an already classified local-row task."""
audio_type = _local_model_audio_type(model) if task is None or task == _SPEECH_TASK else None
if task is None and audio_type is not None:
- from utils.audio_tokens import is_tts_audio_type
- if is_tts_audio_type(audio_type):
+ from utils.audio_tokens import is_output_audio_type
+ if is_output_audio_type(audio_type):
task = _SPEECH_TASK
return task, audio_type
+def _local_model_classification(model) -> tuple[Optional[str], Optional[str]]:
+ """Return picker task and decoder provenance from one local-row probe."""
+ return _local_model_classification_for_task(model, _local_model_task(model))
+
+
def _local_is_diffusers(model) -> bool:
try:
path = Path(model.path)
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index 21b5a458d9b..1a350f7e895 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -950,8 +950,6 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel
# for a response that is actually about to be served.
# Classification reads GGUF headers, so keep it off the event loop too.
try:
- # Module-qualified for the same reason as _cached_row_task: binding the bare
- # name re-points a load that resolved to routes.models before the move.
from hub.services.models import catalog_classification
models = []
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index e347509aeb7..bf6098f00e2 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -934,8 +934,8 @@ def test_local_inventory_requests_share_scan(monkeypatch, change_kind):
calls, started, releases = 0, [event(), event()], [event(), event()]
loaded, both_loaded, task_calls, epoch = 0, event(), [], [0]
epoch_reads, retried = [0], event()
- model = SimpleNamespace(id = "model")
- model.model_copy = lambda update: SimpleNamespace(id = model.id, task = update["task"])
+ model = SimpleNamespace(id = "model", path = "model")
+ model.model_copy = lambda update: SimpleNamespace(id = model.id, path = model.path, **update)
response = SimpleNamespace(models = [model])
response.model_copy = lambda update: SimpleNamespace(models = update["models"])
sources = local_inventory._local_inventory_sources()
@@ -1807,7 +1807,17 @@ def test_cached_models_scan_emits_curated_and_custom_whisper_as_stt(monkeypatch,
_SNAPSHOT_SHA = "a" * 40
-def _diffusion_scan(monkeypatch, tmp_path, repo_id: str, files: list, *, task: str):
+def _diffusion_scan(
+ monkeypatch,
+ tmp_path,
+ repo_id: str,
+ files: list,
+ *,
+ task: str | None,
+ modular_manifest: dict | None = None,
+ config_manifest: dict | None = None,
+ expect_task_classification: bool = True,
+):
"""One cached diffusion repo through _scan_cached_models, with the download-partial signal
forced off so only the pipeline-shape checks can flag the row.
@@ -1823,6 +1833,12 @@ def _diffusion_scan(monkeypatch, tmp_path, repo_id: str, files: list, *, task: s
target = snapshot / f.file_name
target.parent.mkdir(parents = True, exist_ok = True)
target.write_bytes(b"\0" * min(int(f.size_on_disk), 4096))
+ if modular_manifest is not None:
+ (snapshot / "modular_model_index.json").write_text(
+ json.dumps(modular_manifest), encoding = "utf-8"
+ )
+ if config_manifest is not None:
+ (snapshot / "config.json").write_text(json.dumps(config_manifest), encoding = "utf-8")
refs = repo_path / "refs"
refs.mkdir(parents = True, exist_ok = True)
(refs / "main").write_text(_SNAPSHOT_SHA)
@@ -1854,7 +1870,7 @@ def _diffusion_scan(monkeypatch, tmp_path, repo_id: str, files: list, *, task: s
monkeypatch.setattr(cache_inventory, "_cached_row_task", row_task)
rows = cache_inventory._scan_cached_models()
assert len(rows) == 1
- assert selected_snapshots == [snapshot]
+ assert selected_snapshots == ([snapshot] if expect_task_classification else [])
return rows[0]
@@ -1902,6 +1918,30 @@ def test_cached_models_scan_keeps_a_complete_pipeline_loadable(monkeypatch, tmp_
assert row["single_file"] is False
+def test_cached_models_scan_exposes_minimax_music3_modular_pipeline(monkeypatch, tmp_path):
+ row = _diffusion_scan(
+ monkeypatch,
+ tmp_path,
+ "MiniMaxAI/MiniMax-Music3",
+ [
+ _file("modular_model_index.json", 900),
+ _file("transformer/diffusion_pytorch_model.safetensors", 4_000_000_000),
+ ],
+ task = None,
+ modular_manifest = {
+ "_class_name": "MiniMaxMusic3ModularPipeline",
+ "_blocks_class_name": "MiniMaxMusic3Blocks",
+ },
+ expect_task_classification = False,
+ )
+
+ assert row["task"] == "text-to-speech"
+ assert row["audio_type"] == "minimax_music3"
+ assert row["capabilities"]["can_chat"] is False
+ assert row["partial"] is False
+ assert row["single_file"] is False
+
+
def test_cached_models_scan_flags_a_single_file_diffusion_checkpoint(monkeypatch, tmp_path):
"""No root model_index.json: loadable only through from_single_file + a filename. The picker
gates on this flag, and before it was carried here every hub-sourced row read as a full
@@ -1956,6 +1996,31 @@ def test_an_ordinary_repo_is_not_flagged_as_a_companion(monkeypatch, tmp_path):
assert row["capabilities"]["can_chat"] is True
+ ("repo_id", "config"),
+ [
+ ("OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano", {}),
+ ("Acme/custom-moss-codec", {"model_type": "moss-audio-tokenizer"}),
+ ("Acme/legacy-moss-codec", {"model_type": "speech_tokenizer"}),
+ ("Acme/custom-higgs-codec", {"architectures": ["HiggsAudioV2TokenizerModel"]}),
+ ],
+)
+def test_native_audio_codec_repos_are_companion_infrastructure(
+ monkeypatch, tmp_path, repo_id, config
+):
+ row = _diffusion_scan(
+ monkeypatch,
+ tmp_path,
+ repo_id,
+ [_file("config.json", 100), _file("model.safetensors", 100)],
+ task = None,
+ config_manifest = config,
+ )
+
+ assert row["companion"] is True
+ assert row["capabilities"]["can_chat"] is False
+
+
def test_the_real_companion_shape_never_reaches_a_row_at_all(monkeypatch, tmp_path):
"""Why the flag above is a latch, not a live fix.
@@ -7220,8 +7285,8 @@ def test_local_inventory_classifies_off_the_event_loop(monkeypatch):
idents: list[int] = []
loop_is_free = threading.Event()
- model = SimpleNamespace(id = "model")
- model.model_copy = lambda update: SimpleNamespace(id = model.id, task = update["task"])
+ model = SimpleNamespace(id = "model", path = "model")
+ model.model_copy = lambda update: SimpleNamespace(id = model.id, path = model.path, **update)
response = SimpleNamespace(models = [model])
response.model_copy = lambda update: SimpleNamespace(models = update["models"])
@@ -7291,8 +7356,8 @@ def test_local_inventory_classifies_a_superseded_result_off_the_event_loop(monke
idents: list[int] = []
epoch = [0]
- model = SimpleNamespace(id = "model")
- model.model_copy = lambda update: SimpleNamespace(id = model.id, task = update["task"])
+ model = SimpleNamespace(id = "model", path = "model")
+ model.model_copy = lambda update: SimpleNamespace(id = model.id, path = model.path, **update)
response = SimpleNamespace(models = [model])
response.model_copy = lambda update: SimpleNamespace(models = update["models"])
@@ -7332,8 +7397,8 @@ def test_local_inventory_retries_when_the_cache_changes_during_classification(mo
scans: list[int] = []
def _scan_response(tag: str):
- row = SimpleNamespace(id = tag)
- row.model_copy = lambda update, tag = tag: SimpleNamespace(id = tag, task = update["task"])
+ row = SimpleNamespace(id = tag, path = tag)
+ row.model_copy = lambda update, tag = tag: SimpleNamespace(id = tag, path = tag, **update)
response = SimpleNamespace(models = [row])
response.model_copy = lambda update: SimpleNamespace(models = update["models"])
return response
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index a71959f52da..7e30586ffdc 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -1596,7 +1596,7 @@ _SELECTED_DENOISER_INDEX = "diffusion_pytorch_model.safetensors.index.json"
def snapshot_has_pipeline_index(snapshot: Optional[Path]) -> bool:
- """Whether *snapshot* itself carries a ROOT ``model_index.json``.
+ """Whether *snapshot* carries a conventional or modular root pipeline index.
The snapshot-scoped twin of :func:`repo_has_pipeline_index`, for callers that already know the
ONE directory their row loads from. ``from_pretrained`` reads the manifest at the root of the
@@ -1605,13 +1605,16 @@ def snapshot_has_pipeline_index(snapshot: Optional[Path]) -> bool:
if snapshot is None:
return False
try:
- return (Path(snapshot) / "model_index.json").is_file()
+ root = Path(snapshot)
+ return (root / "model_index.json").is_file() or (
+ root / "modular_model_index.json"
+ ).is_file()
except OSError:
return False
def _manifest_denoiser_components(snapshot: Path) -> Optional[tuple[str, ...]]:
- """The denoiser subdirs this pipeline's own ``model_index.json`` declares, or None.
+ """The denoiser subdirs this pipeline's root manifest declares, or None.
Read off the manifest rather than the fixed ``_DENOISER_DIRS`` pair because multi-DiT pipelines
carry more than one (Ideogram 4 adds ``unconditional_transformer/``, Wan 2.2's A14B experts
@@ -1623,7 +1626,10 @@ def _manifest_denoiser_components(snapshot: Path) -> Optional[tuple[str, ...]]:
prove absent and the caller must not hunt for directories that layout never had.
"""
try:
- with (snapshot / "model_index.json").open("r", encoding = "utf-8") as fh:
+ manifest_path = snapshot / "model_index.json"
+ if not manifest_path.is_file():
+ manifest_path = snapshot / "modular_model_index.json"
+ with manifest_path.open("r", encoding = "utf-8") as fh:
manifest = json.load(fh)
except (OSError, ValueError, RecursionError):
# RecursionError (deeply nested json) would escape the caller's fail-open guard.
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 6575c58de82..658c851ea47 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1043,7 +1043,10 @@ class _InferenceRuntimeFields(BaseModel):
"non-diffusion models and whenever the ask and the applied split agree.",
)
is_audio: bool = Field(False, description = "Whether model is a TTS audio model")
- audio_type: Optional[str] = Field(None, description = "Audio codec type: snac, csm, bicodec, dac")
+ audio_type: Optional[str] = Field(
+ None,
+ description = "Audio codec or native generation architecture.",
+ )
has_audio_input: bool = Field(False, description = "Whether model accepts audio input (ASR)")
has_video_input: bool = Field(
False,
@@ -1934,7 +1937,12 @@ class ChatCompletionRequest(BaseModel):
parallel_tool_calls: Optional[bool] = Field(
None, description = "Whether to enable parallel function calling during tool use."
)
- seed: Optional[int] = Field(None, description = "Best-effort deterministic sampling seed.")
+ seed: Optional[int] = Field(
+ None,
+ ge = -(2**63),
+ le = 2**64 - 1,
+ description = "Best-effort deterministic sampling seed.",
+ )
stream_options: Optional[dict] = Field(
None,
description = 'Streaming options, e.g. {"include_usage": true} to emit a final usage chunk.',
@@ -1953,6 +1961,17 @@ class ChatCompletionRequest(BaseModel):
None,
description = "[x-unsloth] Base64-encoded audio (wav/mp3/ogg/flac/m4a) for audio-input models",
)
+ audio_instructions: Optional[str] = Field(
+ None,
+ description = (
+ "[x-unsloth] Scene or music-description instructions for native audio models. "
+ "MiniMax Music 3 requires this alongside lyrics."
+ ),
+ )
+ audio_language: Optional[str] = Field(
+ None,
+ description = "[x-unsloth] Target-language hint for native audio models that support it.",
+ )
video_base64: Optional[str] = Field(
None,
description = (
@@ -4162,6 +4181,27 @@ class AudioSpeechRequest(BaseModel):
"wav", description = "Output container. Only 'wav' is supported."
)
speed: Optional[float] = Field(None, description = "Speech rate (accepted, unused).")
+ instructions: Optional[str] = Field(
+ None,
+ description = "Scene or music-description instructions for compatible audio models.",
+ )
+ language: Optional[str] = Field(
+ None,
+ description = "Target-language hint for compatible audio models.",
+ )
+ seed: Optional[int] = Field(
+ None,
+ ge = -(2**63),
+ le = 2**64 - 1,
+ description = "Best-effort deterministic generation seed.",
+ )
+ max_new_tokens: Optional[int] = Field(
+ None,
+ ge = 1,
+ description = (
+ "Maximum generated audio tokens/frames; MiniMax Music 3 uses 25 frames per second."
+ ),
+ )
provider_id: Optional[str] = Field(
None,
description = "[x-unsloth] Saved connection ID. When set, synthesis is proxied to that "
diff --git a/studio/backend/models/models.py b/studio/backend/models/models.py
index 594f1c4a7dc..efd01db2d0b 100644
--- a/studio/backend/models/models.py
+++ b/studio/backend/models/models.py
@@ -253,7 +253,7 @@ class LocalModelInfo(BaseModel):
)
audio_type: Optional[str] = Field(
None,
- description = "Detected output-audio codec used to decide whether Audio can run the row",
+ description = "Detected output-audio architecture or codec used by Audio runtime policy",
)
diff --git a/studio/backend/requirements/diffusers-pin.txt b/studio/backend/requirements/diffusers-pin.txt
index fdb7ff78099..42c2f4fc05e 100644
--- a/studio/backend/requirements/diffusers-pin.txt
+++ b/studio/backend/requirements/diffusers-pin.txt
@@ -1,18 +1,17 @@
-# The Diffusers revision Unsloth is built against. THE single source of truth for it:
+# The Diffusers release Unsloth is built against. THE single source of truth for it:
# no other requirements file may name diffusers, and a test in
# tests/studio/install/test_diffusers_pin.py enforces that.
#
-# Why a git archive and not a release: MiniMax-H3 needs the modular ModularPipeline /
-# MiniMaxH3Transformer3DModel work that landed after 0.39.0 and is not in any published
-# wheel yet, so a released version makes Unsloth refuse to load H3 at all. The archive
-# reports itself as 0.40.0.dev0.
+# Diffusers 0.40.0 is the first release containing the MiniMax-H3 and MiniMax Music 3
+# modular pipelines. Keep the exact release pin so installs are reproducible without a
+# source build from GitHub.
#
# Why it is installed from its own file, in its own step: base.txt is applied near the
# start of the dependency pass. This step runs late, after every other requirements file,
# so nothing can re-resolve diffusers back to a release behind it.
#
-# python < 3.10 has no candidate: diffusers dropped 3.9 in 0.38, so pinning the archive
+# python < 3.10 has no candidate: diffusers dropped 3.9 in 0.38, so pinning 0.40.0
# outright would leave the resolver nothing at all on a 3.9 host. Those hosts get the
# newest release they can take and the H3 guard refuses the model with a clear message.
-diffusers @ https://github.com/huggingface/diffusers/archive/f53d552036a0d1bd5570782a39cd40cfabf112bc.zip ; python_version >= "3.10"
+diffusers==0.40.0 ; python_version >= "3.10"
diffusers==0.36.0 ; python_version < "3.10"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ef8283542e8..788b0370618 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -76,6 +76,8 @@ from core.inference.orchestrator import (
AUDIO_GENERATION_MAX_TOKENS,
GenStreamError,
GenStreamErrorRaised,
+ MINIMAX_MUSIC_MAX_FRAMES,
+ MOSS_TTS_MAX_FRAMES,
_summed_tool_loop_stats,
)
from core.inference.llama_admission import (
@@ -418,26 +420,48 @@ _MIN_SPEECH_OUTPUT_TOKENS = 64
# back over the context. Generous rather than exact, since the wrapper is chosen deeper
# than this and 32 tokens off a 2048 context is not worth threading it up here.
_TTS_PROMPT_FORMAT_RESERVE = 32
+_MINIMAX_MUSIC3_DEFAULT_FRAMES = 750
+# A 24 GB-class card reports slightly less than 24.0 GiB through free-VRAM
+# telemetry even when idle. Keep the admission floor below that value.
+_MINIMAX_MUSIC3_RESIDENT_GB = 23.0
+_MINIMAX_PROMPT_OVERFLOW = _re.compile(r"The assembled prompt has \d+ tokens; the maximum is \d+")
-def _tts_max_new_tokens(payload, prompt: Optional[str] = None) -> int:
+def _tts_max_new_tokens(
+ payload,
+ prompt: Optional[str] = None,
+ *,
+ audio_type: Optional[str] = None,
+ speech_api_default_max_tokens: bool = False,
+) -> int:
"""Bound TTS work consistently across llama.cpp and subprocess backends.
``prompt`` shares the loaded context with the output, so a Max tokens slider near the
ceiling plus a long prompt overflowed the context the page loaded with. Capped here so
both the Unsloth and OpenAI routes inherit it.
"""
+ moss_generation = audio_type in ("moss_tts_local", "moss_tts_nano")
+ context_length = _monitor_context_length() if moss_generation or prompt else None
+ token_ceiling = (
+ context_length or MOSS_TTS_MAX_FRAMES
+ if moss_generation
+ else (
+ MINIMAX_MUSIC_MAX_FRAMES
+ if audio_type == "minimax_music3"
+ else AUDIO_GENERATION_MAX_TOKENS
+ )
+ )
budget = min(
- AUDIO_GENERATION_MAX_TOKENS,
+ token_ceiling,
max(1, int(_effective_max_tokens(payload) or 2048)),
)
- if prompt:
- context_length = _monitor_context_length()
- if context_length:
- budget = min(
- budget,
- context_length - _prompt_token_estimate(prompt) - _TTS_PROMPT_FORMAT_RESERVE,
- )
+ if speech_api_default_max_tokens and audio_type == "minimax_music3":
+ budget = min(budget, _MINIMAX_MUSIC3_DEFAULT_FRAMES)
+ if prompt and context_length:
+ budget = min(
+ budget,
+ context_length - _prompt_token_estimate(prompt) - _TTS_PROMPT_FORMAT_RESERVE,
+ )
# A caller that reached generation with no budget left gets one token and a useless
# clip; the routes reject that case up front instead.
return max(1, budget)
@@ -464,6 +488,19 @@ def _raise_if_prompt_leaves_no_speech_budget(text: str) -> None:
)
+def _native_tts_prompt_for_budget(
+ text: str, audio_type: Optional[str], instructions: Optional[str], language: Optional[str]
+) -> str:
+ """User-controlled text fields tokenized by native TTS prompt builders."""
+ if audio_type == "higgs_tts2":
+ instructions = instructions or "Audio is recorded from a quiet room."
+ parts = [instructions]
+ if audio_type == "moss_tts_local":
+ parts.append(language)
+ parts.append(text)
+ return "\n".join(str(part) for part in parts if part)
+
+
def _prompt_token_estimate(prompt: str) -> int:
"""Tokens the prompt will occupy, from the loaded tokenizer where one is reachable.
@@ -482,14 +519,10 @@ def _prompt_token_estimate(prompt: str) -> int:
return count
except Exception: # noqa: BLE001 - an estimate must never fail the request
pass
- # llama-server holds its own tokenizer, so estimate by character class instead of a
- # flat ratio. Everything outside ASCII counts as a token: the earlier cut at U+2E7F
- # only caught CJK and emoji, so Arabic, Cyrillic, Hebrew and the Indic scripts were
- # billed at the Latin third-of-a-token rate and a long prompt in any of them passed
- # the guard, then overflowed the context during generation. Over-counting accented
- # Latin is the safe direction for a budget: it shortens the clip rather than failing.
- dense = sum(1 for ch in prompt if ord(ch) > 0x7F)
- return max(1, dense + (len(prompt) - dense) // 3)
+ # subprocess and llama-server tokenizers are not reachable here. UTF-8 bytes are a
+ # conservative upper bound for their byte-level fallbacks; under-counting can overflow
+ # the loaded context, while over-counting only shortens the requested clip.
+ return max(1, len(prompt.encode("utf-8")))
_OPENAI_COMPAT_STREAM_STALL_TIMEOUT_ENV = "UNSLOTH_OPENAI_COMPAT_STREAM_STALL_TIMEOUT"
@@ -8421,6 +8454,12 @@ async def load_model_for_preview(
def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:
+ """Effective quantization the loader will use: a LoRA adapter can flip 4-bit to
+ 16-bit via adapter_config.json, so the guard sizes this, not the raw request."""
+ from core.inference.native_audio import NATIVE_AUDIO_TYPES
+
+ if getattr(config, "audio_type", None) in NATIVE_AUDIO_TYPES:
+ return False
load_in_4bit = requested
if not getattr(config, "is_lora", False) or not getattr(config, "path", None):
return load_in_4bit
@@ -11252,6 +11291,225 @@ class _LoadPlacement(NamedTuple):
resolved_gpu_ids: Optional[List[int]]
gpu_ids_are_vulkan_ordinals: bool
diffusion_kind: Optional[bool]
+ native_required_gb: Optional[float] = None
+ native_post_handoff_free_gb: Optional[dict[int, float]] = None
+
+
+class _NativeAudioAvailability(NamedTuple):
+ effective_free_gb: dict[int, float]
+ reclaimable_gpu_gb: dict[int, float]
+ owner_snapshot: tuple[Optional[str], int] = (None, 0)
+
+
+def _native_audio_post_handoff_free_gb() -> Optional[_NativeAudioAvailability]:
+ """Free VRAM after the outgoing Studio owner is torn down, or ``None``.
+
+ Only memory attributable to a backend this CHAT handoff provably evicts is
+ credited. Training, STT, export and unknown/external processes remain in
+ the live-used figure. Missing attribution fails closed.
+ """
+ import utils.hardware as hardware
+ from core.inference.gpu_arbiter import CHAT, DIFFUSION, VIDEO, owner_snapshot
+
+ outgoing_owner = owner_snapshot()
+ owner = outgoing_owner[0]
+ live: dict[int, tuple[float, float]] = {}
+ reclaimable: dict[int, float] = {}
+
+ def _read_live() -> bool:
+ utilization = hardware.get_visible_gpu_utilization()
+ live.clear()
+ for device in utilization.get("devices", []):
+ try:
+ index = int(device["index"])
+ total = float(device["vram_total_gb"])
+ used = float(device["vram_used_gb"])
+ except (KeyError, TypeError, ValueError):
+ continue
+ live[index] = (max(total - used, 0.0), total)
+ return bool(live)
+
+ def _merge_report(reported) -> bool:
+ if not isinstance(reported, dict):
+ return False
+ try:
+ parsed = {
+ int(index): max(float(value), 0.0)
+ for index, value in reported.items()
+ if int(index) in live
+ }
+ except (TypeError, ValueError, OverflowError):
+ return False
+ if any(value >= 1_000_000 for value in parsed.values()):
+ return False
+ for index, value in parsed.items():
+ reclaimable[index] = reclaimable.get(index, 0.0) + value
+ return True
+
+ if owner == CHAT:
+ # Both standard inference and llama-server run in disposable processes.
+ # The Python worker returns its owner bytes with the system reading under
+ # one admission fence. llama-server contributes only its stable startup
+ # model-buffer floor, so changing KV/compute allocations remain charged.
+ backend = get_inference_backend()
+ worker_snapshot = None
+ if getattr(backend, "active_model_name", None):
+ worker_snapshot = getattr(backend, "post_handoff_gpu_availability_gb", lambda: None)()
+ if worker_snapshot is not None:
+ free_by_index, total_by_index, worker_reclaimable = worker_snapshot
+ live = {
+ int(index): (float(free), float(total_by_index[index]))
+ for index, free in free_by_index.items()
+ if index in total_by_index
+ }
+ if not live:
+ return None
+ _merge_report(worker_reclaimable)
+ elif not _read_live():
+ return None
+ llama_backend = get_llama_cpp_backend()
+ if getattr(llama_backend, "is_loaded", False):
+ _merge_report(getattr(llama_backend, "reclaimable_gpu_memory_gb", lambda: None)())
+ elif owner in (DIFFUSION, VIDEO):
+ # Diffusers/Video normally live in this process; native sd.cpp instead
+ # contributes a child-process startup floor below. Hold the backend's
+ # generation barrier across both readings so a denoise cannot free
+ # activations between them and make the same bytes look free and
+ # reclaimable at once.
+ if owner == DIFFUSION:
+ from core.inference.diffusion_engine_router import get_active_diffusion_engine
+ media_backend = get_active_diffusion_engine()
+ else:
+ from core.inference.video import get_video_backend
+ media_backend = get_video_backend()
+ generate_lock = getattr(media_backend, "_generate_lock", None)
+ state_lock = getattr(media_backend, "_lock", None)
+ if generate_lock is None or state_lock is None:
+ return None
+ acquired = generate_lock.acquire(blocking = False)
+ if not acquired:
+ return None
+ try:
+ with state_lock:
+ # begin_load publishes this before its background worker can
+ # replace the old state. The arbiter owner/epoch does not change
+ # again at commit, so sampling the old state here would let a
+ # smaller same-owner replacement spend bytes it no longer owns.
+ if getattr(media_backend, "_loading", None) is not None:
+ return None
+ if owner == DIFFUSION and (
+ getattr(media_backend, "_pending_server", None) is not None
+ or int(getattr(media_backend, "_stopping_servers", 0) or 0) > 0
+ ):
+ return None
+ state = getattr(media_backend, "_state", None)
+ if state is None or not _read_live():
+ return None
+ if hasattr(state, "server"):
+ # Native sd.cpp owns VRAM in a child process. Only its
+ # stable startup parameter floor is attributable; the
+ # parent torch allocator says nothing about that process.
+ server = getattr(state, "server", None)
+ if (
+ server is None
+ or getattr(media_backend, "_cpu_backend_forced", False)
+ or "--offload-to-cpu" in tuple(getattr(state, "offload_flags", ()) or ())
+ ):
+ return None
+ reported = getattr(server, "reclaimable_params_vram_gb", lambda _gpu: None)(
+ getattr(state, "physical_gpu_id", None)
+ )
+ if not _merge_report(reported):
+ return None
+ else:
+ import torch
+
+ device_type = hardware.get_device()
+ if device_type == hardware.DeviceType.CUDA:
+ device_module = torch.cuda
+ elif device_type == hardware.DeviceType.XPU:
+ device_module = torch.xpu
+ else:
+ return None
+ memory_reserved = getattr(device_module, "memory_reserved", None)
+ device_count = int(device_module.device_count())
+ if not callable(memory_reserved) or device_count <= 0:
+ return None
+ physical_ids = hardware.get_parent_visible_gpu_ids()
+ if not physical_ids:
+ physical_ids = sorted(live) if len(live) == device_count else None
+ if not physical_ids or len(physical_ids) < device_count:
+ return None
+ reclaimable = {
+ int(physical_ids[ordinal]): max(
+ int(memory_reserved(ordinal)) / float(1024**3), 0.0
+ )
+ for ordinal in range(device_count)
+ }
+ except Exception as exc:
+ logger.warning("Could not attribute resident media GPU memory: %s", exc)
+ return None
+ finally:
+ generate_lock.release()
+ else:
+ return None
+
+ # A concurrent media handoff or unload invalidates which process/state this
+ # load will tear down. Fail closed rather than crediting a former owner.
+ if owner_snapshot() != outgoing_owner:
+ return None
+ if not any(value > 0 for value in reclaimable.values()):
+ return None
+ return _NativeAudioAvailability(
+ effective_free_gb = {
+ index: min(free + reclaimable.get(index, 0.0), total)
+ for index, (free, total) in live.items()
+ },
+ reclaimable_gpu_gb = reclaimable,
+ owner_snapshot = outgoing_owner,
+ )
+
+
+def _wait_for_native_audio_gpu_free_gb(
+ gpu_index: int,
+ required_gb: float,
+ *,
+ max_wait: float = 5.0,
+ interval: float = 0.25,
+) -> bool:
+ """Wait until an evicted media backend's credited VRAM is actually free."""
+ from utils.hardware import get_visible_gpu_utilization
+
+ deadline = time.monotonic() + max(max_wait, 0.0)
+ while True:
+ try:
+ devices = get_visible_gpu_utilization().get("devices", [])
+ for device in devices:
+ if int(device["index"]) != int(gpu_index):
+ continue
+ total = float(device["vram_total_gb"])
+ used = float(device["vram_used_gb"])
+ if max(total - used, 0.0) >= required_gb:
+ return True
+ except (KeyError, TypeError, ValueError, OverflowError):
+ pass
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ time.sleep(min(interval, remaining))
+
+
+async def _unload_llama_before_standard_load(llama_backend) -> None:
+ """Tear down llama-server and wait for asynchronous driver VRAM reclaim."""
+ if not llama_backend.is_loaded:
+ return
+ logger.info("Unloading GGUF model before loading Unsloth model")
+ kill_started = time.monotonic()
+ await asyncio.to_thread(llama_backend.unload_model)
+ await asyncio.to_thread(
+ llama_backend._wait_for_vram_settle,
+ since_kill = kill_started,
+ )
def _spec_fallback_binary_changed(llama_backend) -> Optional[bool]:
@@ -11440,6 +11698,143 @@ async def _prepare_load_placement(
return _LoadPlacement(requested, resolved, is_vulkan, diffusion_kind)
+async def _preflight_native_audio_placement(
+ config: ModelConfig, request: LoadRequest | ValidateModelRequest, placement: _LoadPlacement
+) -> _LoadPlacement:
+ """Resolve native-audio placement before a resident model can be evicted."""
+ from core.inference.native_audio import NATIVE_AUDIO_TYPES
+
+ audio_type = getattr(config, "audio_type", None)
+ if audio_type not in NATIVE_AUDIO_TYPES:
+ return placement
+ if getattr(config, "is_lora", False):
+ raise HTTPException(
+ status_code = 400,
+ detail = (
+ "Native audio LoRA adapters are not supported yet. "
+ "Load a merged checkpoint instead."
+ ),
+ )
+ if audio_type in ("higgs_tts2", "higgs_tts3") and sys.version_info < (3, 10):
+ raise HTTPException(
+ status_code = 400,
+ detail = "Higgs TTS requires Python 3.10 or newer in Studio.",
+ )
+
+ automatic = not placement.requested_gpu_ids
+ availability = (
+ await asyncio.to_thread(_native_audio_post_handoff_free_gb) if automatic else None
+ )
+
+ def _resolve() -> tuple[Optional[List[int]], Optional[float], Optional[dict[int, float]]]:
+ import utils.hardware as hardware
+ from core.inference.native_audio import (
+ native_audio_kv_memory_gb,
+ native_audio_security_targets,
+ )
+
+ device = hardware.get_device()
+ if audio_type == "minimax_music3":
+ if device != hardware.DeviceType.CUDA or hardware.IS_ROCM:
+ raise ValueError(
+ "MiniMax Music 3 requires an NVIDIA CUDA GPU in its official local runtime."
+ )
+ if sys.version_info < (3, 10):
+ raise ValueError("MiniMax Music 3 requires Python 3.10 or newer in Studio.")
+ if device not in (hardware.DeviceType.CUDA, hardware.DeviceType.XPU):
+ if placement.requested_gpu_ids:
+ raise ValueError(
+ "Native audio GPU selection is only supported on CUDA and Intel XPU."
+ )
+ return None, None, None
+
+ model_source = getattr(config, "path", None) or config.identifier
+ targets = list(
+ dict.fromkeys(
+ native_audio_security_targets(
+ model_source,
+ audio_type,
+ request.hf_token,
+ )
+ )
+ )
+ # The published repo is about 67 GB, but the official BF16 modular
+ # pipeline is resident on one 24 GB CUDA device. Using repository bytes
+ # here makes auto-placement select several GPUs and the single-device
+ # native backend then rejects a model that fits one supported card.
+ required_gb = _MINIMAX_MUSIC3_RESIDENT_GB if audio_type == "minimax_music3" else None
+ if len(targets) > 1:
+ required_gb = 0.0
+ for target in targets:
+ target_required_gb, _metadata = hardware.estimate_required_model_memory_gb(
+ target,
+ hf_token = request.hf_token,
+ training_type = None,
+ load_in_4bit = False,
+ max_seq_length = request.max_seq_length,
+ )
+ if target_required_gb is None:
+ raise ValueError(
+ f"Could not estimate GPU memory for native audio component '{target}'."
+ )
+ required_gb += target_required_gb
+ required_gb += native_audio_kv_memory_gb(
+ model_source,
+ audio_type,
+ request.hf_token,
+ )
+ resolved, metadata = hardware.prepare_gpu_selection(
+ placement.requested_gpu_ids,
+ model_name = config.identifier,
+ hf_token = request.hf_token,
+ load_in_4bit = False,
+ max_seq_length = request.max_seq_length,
+ required_override_gb = required_gb,
+ )
+ post_handoff_free_gb = None
+ if required_gb is None:
+ required_gb = metadata.get("required_gb")
+ if metadata.get("selection_mode") == "fallback_all":
+ candidates = set(resolved or ())
+ fitting = sorted(
+ (
+ (index, free_gb)
+ for index, free_gb in (
+ availability.effective_free_gb if availability is not None else {}
+ ).items()
+ if index in candidates and required_gb is not None and free_gb >= required_gb
+ ),
+ key = lambda item: (-item[1], item[0]),
+ )
+ if not fitting:
+ raise ValueError(
+ "No single GPU has enough free memory for this native audio model. "
+ "Select a GPU with enough free memory and try again."
+ )
+ resolved = [fitting[0][0]]
+ if automatic and availability is not None and resolved and len(resolved) == 1:
+ selected_gpu = resolved[0]
+ reported = availability.effective_free_gb.get(selected_gpu)
+ if reported is not None:
+ post_handoff_free_gb = {selected_gpu: reported}
+ if resolved and len(resolved) > 1:
+ raise ValueError(
+ "Native audio models currently require one GPU. Select a single GPU; "
+ "multi-GPU sharding is not supported yet."
+ )
+ return resolved, required_gb, post_handoff_free_gb
+
+ try:
+ resolved, required_gb, post_handoff_free_gb = await asyncio.to_thread(_resolve)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ return placement._replace(
+ resolved_gpu_ids = resolved,
+ native_required_gb = required_gb,
+ native_post_handoff_free_gb = post_handoff_free_gb,
+ )
+
+
def _inherited_batch_flags_stripped(request) -> bool:
"""Whether inheriting the resident extras drops a -b / -ub a set field supersedes.
@@ -11571,7 +11966,7 @@ def _guard_chat_load_against_training(
placement: _LoadPlacement,
llama_extra_args: Optional[list[str]] = None,
n_parallel: int = 1,
-) -> None:
+) -> Optional[dict[str, Any]]:
"""Protect active training from automatically placed chat-model loads.
No-op when training is inactive or unknown. `load_in_4bit` must be the
@@ -11719,8 +12114,9 @@ def _guard_chat_load_against_training(
except Exception as e:
logger.warning("Could not probe llama-server slots for chat-load guard: %s", e)
- required_override_gb = (
- _estimate_gguf_required_gb(
+ required_override_gb = placement.native_required_gb
+ if is_gguf:
+ required_override_gb = _estimate_gguf_required_gb(
config,
hf_token = request.hf_token,
max_seq_length = request.max_seq_length,
@@ -11741,9 +12137,6 @@ def _guard_chat_load_against_training(
# hands this guard a bare request double that does not carry the field.
disable_vision = bool(getattr(request, "disable_vision", False)),
)
- if is_gguf
- else None
- )
# A confirmed-diffusion positive split puts only ngl/n_layers of the weights on the GPU (a
# split the loader would drop was nulled above). Unknown classification keeps the full
# estimate: its header was unreadable, so the layer count is too.
@@ -11773,6 +12166,22 @@ def _guard_chat_load_against_training(
# GGUF while training runs.
vulkan_free_vram_gb = {}
+ native_post_handoff_free_gb = placement.native_post_handoff_free_gb
+ if native_post_handoff_free_gb is not None:
+ # Revalidate as one atomic post-handoff capacity snapshot. Combining a
+ # fresh free-memory read with older owner bytes can count a reset cache
+ # twice, so the training policy consumes this value directly.
+ availability = _native_audio_post_handoff_free_gb()
+ selected = list(placement.resolved_gpu_ids or ())
+ if availability is None or len(selected) != 1:
+ native_post_handoff_free_gb = None
+ else:
+ selected_gpu = selected[0]
+ effective_free = availability.effective_free_gb.get(selected_gpu)
+ native_post_handoff_free_gb = (
+ {selected_gpu: effective_free} if effective_free is not None else None
+ )
+
ok, info = can_load_chat_during_training(
model_name = getattr(config, "identifier", request.model_path),
hf_token = request.hf_token,
@@ -11784,9 +12193,10 @@ def _guard_chat_load_against_training(
vulkan_free_vram_gb = vulkan_free_vram_gb,
required_override_gb = required_override_gb,
single_device_gpu = diffusion_gpu,
+ post_handoff_free_gpu_vram_gb = native_post_handoff_free_gb,
)
if ok:
- return
+ return info
usable = info.get("usable_gb")
needed = info.get("needed_gb")
@@ -12652,7 +13062,14 @@ async def _load_model_impl(
# Reclaim the GPU for chat (evicting a resident Images/Video pipeline) only once the load is known viable; the
# already-loaded fast paths below re-assert CHAT themselves. Deferred past validation so a doomed load evicts nothing.
- from core.inference.gpu_arbiter import acquire_for, current_owner, release, CHAT
+ from core.inference.gpu_arbiter import (
+ acquire_for,
+ current_owner,
+ release,
+ CHAT,
+ DIFFUSION,
+ VIDEO,
+ )
# ── Already-loaded check: skip reload if the exact model is active ──
backend = await asyncio.to_thread(get_inference_backend)
@@ -12930,19 +13347,24 @@ async def _load_model_impl(
"architectures)"
)
+ placement = await _preflight_native_audio_placement(config, request, placement)
+
+ async def _guard_training(guard_placement: _LoadPlacement):
+ return await asyncio.to_thread(
+ _offline_guarded,
+ (model_identifier, config.identifier, getattr(config, "base_model", None)),
+ _guard_chat_load_against_training,
+ config,
+ request,
+ load_in_4bit = effective_load_in_4bit,
+ placement = guard_placement,
+ llama_extra_args = extra_llama_args,
+ n_parallel = _n_parallel,
+ )
+
# Apply the training coexistence policy before the unload step below
# frees the resident model. Off-loop and guarded: the guard does sync HF work.
- await asyncio.to_thread(
- _offline_guarded,
- (model_identifier, config.identifier, getattr(config, "base_model", None)),
- _guard_chat_load_against_training,
- config,
- request,
- load_in_4bit = effective_load_in_4bit,
- placement = placement,
- llama_extra_args = extra_llama_args,
- n_parallel = _n_parallel,
- )
+ initial_training_info = await _guard_training(placement)
# Mark the load and refuse one the download manager already owns BEFORE the eviction below: this 409 leaves nothing
# loaded. It runs after argument inheritance, since a carried --no-mmproj changes the companion requirement.
@@ -13028,14 +13450,88 @@ async def _load_model_impl(
if _host_offload_warning:
logger.warning("Loading an oversized GGUF: %s", _host_offload_warning)
- if chat_load_needs_gpu:
- gpu_acquire_kwargs = {} if allow_gpu_owner_eviction else {"allow_evict": False}
- await asyncio.to_thread(
- acquire_for,
- CHAT,
- lambda: gguf_load_stack.enter_context(chat_load_in_flight()),
- **gpu_acquire_kwargs,
+ expected_native_owner = None
+ post_media_handoff_gpu = None
+ post_media_handoff_needed_gb = None
+ post_chat_handoff_expected_free_gb = None
+ if chat_load_needs_gpu and placement.native_post_handoff_free_gb is not None:
+ # This model was admitted using memory owned by the outgoing backend.
+ # Refresh immediately before the arbiter handoff, then bind the
+ # snapshot's epoch to the eviction so a same-owner media replacement
+ # cannot swap in a smaller model between check and teardown.
+ final_availability = await asyncio.to_thread(_native_audio_post_handoff_free_gb)
+ selected = list(placement.resolved_gpu_ids or ())
+ required = placement.native_required_gb
+ if final_availability is None or len(selected) != 1 or required is None:
+ raise HTTPException(
+ status_code = 409,
+ detail = "GPU residency changed while preparing this audio model. Retry the load.",
+ )
+ selected_gpu = selected[0]
+ effective_free = final_availability.effective_free_gb.get(selected_gpu)
+ if effective_free is None or effective_free < required:
+ raise HTTPException(
+ status_code = 409,
+ detail = "GPU residency changed and the audio model no longer fits. Retry the load.",
+ )
+ final_placement = placement._replace(
+ native_post_handoff_free_gb = {selected_gpu: effective_free}
+ )
+ final_training_info = await _guard_training(final_placement)
+ expected_native_owner = final_availability.owner_snapshot
+ post_handoff_needed_gb = float(
+ (final_training_info or initial_training_info or {}).get("needed_gb") or required
)
+ if expected_native_owner[0] in (DIFFUSION, VIDEO):
+ post_media_handoff_gpu = selected_gpu
+ post_media_handoff_needed_gb = post_handoff_needed_gb
+ elif expected_native_owner[0] == CHAT:
+ post_chat_handoff_expected_free_gb = {selected_gpu: post_handoff_needed_gb}
+
+ if chat_load_needs_gpu:
+ try:
+ handoff_kwargs = {}
+ if expected_native_owner is not None:
+ handoff_kwargs["expected_current"] = expected_native_owner
+ if not allow_gpu_owner_eviction:
+ handoff_kwargs["allow_evict"] = False
+ await asyncio.to_thread(
+ acquire_for,
+ CHAT,
+ lambda: gguf_load_stack.enter_context(chat_load_in_flight()),
+ **handoff_kwargs,
+ )
+ except Exception as exc:
+ from core.inference.gpu_arbiter import OwnerChangedError
+ if isinstance(exc, OwnerChangedError):
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+ raise
+ if post_media_handoff_gpu is not None and post_media_handoff_needed_gb is not None:
+ settled = await asyncio.to_thread(
+ _wait_for_native_audio_gpu_free_gb,
+ post_media_handoff_gpu,
+ post_media_handoff_needed_gb,
+ )
+ if not settled:
+ raise HTTPException(
+ status_code = 409,
+ detail = (
+ "GPU memory was not released after the resident media model "
+ "was stopped. Retry the audio-model load."
+ ),
+ )
+ # The outgoing media allocation is gone now. Re-run the training
+ # policy against live free VRAM only, so a concurrent training
+ # change cannot hide behind the earlier reclaimable snapshot.
+ live_placement = placement._replace(
+ # Automatic selection is already fixed at this point. Bind
+ # the live-only training recheck to that exact card, or a
+ # roomy second GPU could approve a load that still targets
+ # a now-constrained first GPU.
+ requested_gpu_ids = [post_media_handoff_gpu],
+ native_post_handoff_free_gb = None,
+ )
+ await _guard_training(live_placement)
else:
# The marker still goes up (the download-manager handshake reads it, and it keeps this load cancellable). A stale CHAT claim is dropped AFTER the load.
gguf_load_stack.enter_context(chat_load_in_flight())
@@ -13247,16 +13743,14 @@ async def _load_model_impl(
_set_preview_resident(None)
# Unload any active GGUF model first, off-loop: a 600 GB teardown measures
# 160s and on-loop would block _tunnel_safe_json's own padding.
- if llama_backend.is_loaded:
- logger.info("Unloading GGUF model before loading Unsloth model")
- try:
- await asyncio.to_thread(llama_backend.unload_model)
- except Exception:
- # This teardown runs after the marker was cleared above; if it raises with
- # the prior preview-owned GGUF still resident, restore its ownership so a
- # later preview for another checkpoint is not 503'd against it.
- _restore_marker_if_prior_preview_still_resident()
- raise
+ try:
+ await _unload_llama_before_standard_load(llama_backend)
+ except Exception:
+ # This teardown runs after the marker was cleared above; if it raises with
+ # the prior preview-owned GGUF still resident, restore its ownership so a
+ # later preview for another checkpoint is not 503'd against it.
+ _restore_marker_if_prior_preview_still_resident()
+ raise
# Shut down any export subprocess to free VRAM
try:
@@ -13291,11 +13785,16 @@ async def _load_model_impl(
hf_token = request.hf_token,
trust_remote_code = request.trust_remote_code,
approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,
- gpu_ids = placement.requested_gpu_ids,
+ gpu_ids = (
+ placement.resolved_gpu_ids
+ if placement.resolved_gpu_ids is not None
+ else placement.requested_gpu_ids
+ ),
subject = current_subject,
mlx_kv_bits = request.mlx_kv_bits,
chat_template_override = request.chat_template_override,
load_cancel_event = load_cancel_event,
+ post_handoff_expected_free_gb = post_chat_handoff_expected_free_gb,
)
except Exception:
_restore_marker_if_prior_preview_still_resident()
@@ -13768,10 +14267,15 @@ async def validate_model(
):
raise HTTPException(status_code = 400, detail = str(exc)) from exc
effective_load_in_4bit = _effective_load_in_4bit(config, request.load_in_4bit)
+ placement = await _preflight_native_audio_placement(config, request, placement)
# Both checks cover the [adapter, base] set (matching the scan route and workers):
# either repo can ship auto_map code or a poisoned pickle.
- security_targets = [config.identifier]
+ from core.inference.native_audio import native_audio_security_targets
+
+ security_targets = native_audio_security_targets(
+ config.identifier, getattr(config, "audio_type", None), request.hf_token
+ )
try:
from utils.models.model_config import get_base_model_from_lora_identifier
@@ -15576,12 +16080,29 @@ async def get_load_progress(current_subject: str = Depends(get_current_subject))
# Audio (TTS) Generation (/audio/generate)
# =====================================================================
-_TRANSFORMERS_TTS_AUDIO_TYPES = frozenset(("snac", "csm", "bicodec", "dac"))
+_TRANSFORMERS_TTS_AUDIO_TYPES = frozenset(
+ (
+ "snac",
+ "csm",
+ "bicodec",
+ "dac",
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+ )
+)
_GGUF_TTS_AUDIO_TYPES = frozenset(("snac", "bicodec", "dac"))
async def _generate_tts_wav(
- text: str, payload: ChatCompletionRequest, request: Request, current_subject: str
+ text: str,
+ payload: ChatCompletionRequest,
+ request: Request,
+ current_subject: str,
+ *,
+ speech_api_default_max_tokens: bool = False,
) -> tuple[bytes, int, str, Optional[str]]:
"""Shared core of /audio/generate and /audio/speech. Returns
(wav_bytes, sample_rate, model_name, audio_type)."""
@@ -15609,6 +16130,7 @@ async def _generate_tts_wav(
# Created before the backend pick so the GGUF lambda can close over it; the registration
# that arms it is below, once the model name is known.
_audio_cancel = threading.Event()
+ prompt_for_budget = text
# Pick backend — both return (wav_bytes, sample_rate)
llama_backend = get_llama_cpp_backend()
@@ -15629,7 +16151,12 @@ async def _generate_tts_wav(
top_p = payload.top_p,
top_k = payload.top_k,
min_p = payload.min_p,
- max_new_tokens = _tts_max_new_tokens(payload, text),
+ max_new_tokens = _tts_max_new_tokens(
+ payload,
+ prompt_for_budget,
+ audio_type = audio_type,
+ speech_api_default_max_tokens = speech_api_default_max_tokens,
+ ),
repetition_penalty = payload.repetition_penalty,
cancel_event = _audio_cancel,
)
@@ -15650,10 +16177,18 @@ async def _generate_tts_wav(
top_p = payload.top_p,
top_k = payload.top_k,
min_p = payload.min_p,
- max_new_tokens = _tts_max_new_tokens(payload, text),
+ max_new_tokens = _tts_max_new_tokens(
+ payload,
+ prompt_for_budget,
+ audio_type = audio_type,
+ speech_api_default_max_tokens = speech_api_default_max_tokens,
+ ),
repetition_penalty = payload.repetition_penalty,
use_adapter = payload.use_adapter,
cancel_event = _audio_cancel,
+ instructions = payload.audio_instructions,
+ language = payload.audio_language,
+ seed = payload.seed,
)
if audio_type not in supported_audio_types:
@@ -15661,6 +16196,19 @@ async def _generate_tts_wav(
status_code = 400,
detail = f"Active model does not support text-to-speech (audio_type={audio_type or 'unknown'}).",
)
+ if audio_type == "minimax_music3" and not str(payload.audio_instructions or "").strip():
+ raise HTTPException(
+ status_code = 400,
+ detail = "MiniMax Music 3 requires a music description in addition to lyrics.",
+ )
+ if audio_type in ("higgs_tts2", "moss_tts_local"):
+ prompt_for_budget = _native_tts_prompt_for_budget(
+ text,
+ audio_type,
+ payload.audio_instructions,
+ payload.audio_language,
+ )
+ _raise_if_prompt_leaves_no_speech_budget(prompt_for_budget)
# Audio-capable backend confirmed. The middleware claims the slot on a 2xx, so no claim
# here: claiming before the audio backend runs could strand a preview-owned checkpoint
@@ -15698,6 +16246,8 @@ async def _generate_tts_wav(
if isinstance(e, AudioBackendUnsupportedError):
logger.info("Audio generation unsupported on this backend: %s", e.detail)
raise HTTPException(status_code = 501, detail = e.message)
+ if audio_type == "minimax_music3" and _MINIMAX_PROMPT_OVERFLOW.fullmatch(str(e)):
+ raise HTTPException(status_code = 400, detail = str(e))
logger.error(f"Audio generation error: {e}", exc_info = True)
raise HTTPException(status_code = 500, detail = safe_error_detail(e))
finally:
@@ -15743,6 +16293,33 @@ def _persist_tts_clip(
return None
+@studio_router.post("/audio/download-plan", response_model = DiffusionDownloadPlanResponse)
+async def audio_download_plan(
+ request: LoadRequest, current_subject: str = Depends(get_current_subject)
+):
+ """Stage native-audio checkpoints and companion codecs through Download Manager."""
+ from core.inference.native_audio import native_audio_download_plan
+ from utils.native_path_leases import redact_native_paths
+
+ try:
+ plan = await asyncio.to_thread(
+ native_audio_download_plan,
+ request.model_path,
+ request.hf_token,
+ )
+ return DiffusionDownloadPlanResponse(**plan)
+ except (ValueError, FileNotFoundError) as exc:
+ raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc))) from exc
+ except Exception as exc: # noqa: BLE001 - Hub/API failures become a useful picker error
+ logger.warning("audio.download_plan_failed: %s", exc)
+ raise HTTPException(
+ status_code = 502,
+ detail = redact_native_paths(
+ f"Could not prepare the audio model download: {safe_error_detail(exc)}"
+ ),
+ ) from exc
+
+
@router.post("/audio/generate")
async def generate_audio(
payload: ChatCompletionRequest,
@@ -15873,6 +16450,7 @@ async def _external_tts_speech(body: AudioSpeechRequest, request: Request) -> Re
voice = external_voice,
response_format = (body.response_format or "wav").strip().lower(),
speed = body.speed,
+ instructions = body.instructions,
)
)
disconnect_watcher = asyncio.create_task(
@@ -15904,7 +16482,7 @@ async def openai_audio_speech(
"""OpenAI-compatible text-to-speech (POST /v1/audio/speech).
With ``provider_id`` the request is proxied to that connection, forwarding
- model/voice/speed. Otherwise the loaded model is used: ``model`` is informational,
+ model/voice/speed/instructions. Otherwise the loaded model is used: ``model`` is informational,
``voice``/``speed`` ignored, and only WAV exists, so another ``response_format`` is
a 400 rather than a silent container mismatch."""
if body.provider_id:
@@ -15930,9 +16508,9 @@ async def openai_audio_speech(
detail = f"Unsupported response_format '{body.response_format}'. Only 'wav' is supported.",
)
# The tts core reads its sampling knobs from a chat request shape; defaults apply here.
- # max_tokens is set explicitly because the OpenAI CreateSpeech shape has no field for it,
- # so the chat default of 2048 would silently truncate any input past ~30s of speech and
- # still return HTTP 200 with a short WAV.
+ # Keep the full speech ceiling unless a client supplies the native max_new_tokens
+ # extension. MiniMax gets its documented 750-frame default deeper in the shared core;
+ # its adapter converts that frame budget into a 30-second duration upper bound.
# Unlike the Audio page, which loads with headroom for both, this route is reachable
# after any /api/inference/load, including the default max_seq_length=0 that becomes
# 2048. Asking for the full ceiling against that context overflows or truncates, so
@@ -15940,7 +16518,10 @@ async def openai_audio_speech(
# The over-context check lives in _generate_tts_wav, so both routes share it.
payload = ChatCompletionRequest(
messages = [{"role": "user", "content": body.input}],
- max_tokens = AUDIO_GENERATION_MAX_TOKENS,
+ max_tokens = body.max_new_tokens or AUDIO_GENERATION_MAX_TOKENS,
+ audio_instructions = body.instructions,
+ audio_language = body.language,
+ seed = body.seed,
)
# model is informational and is echoed verbatim into the row, so a failure before the
# relabel below would strand the raw client string, possibly a host path, on a terminal
@@ -15952,7 +16533,11 @@ async def openai_audio_speech(
subject = current_subject,
) as monitor_id:
wav_bytes, sample_rate, model_name, audio_type = await _generate_tts_wav(
- body.input, payload, request, current_subject
+ body.input,
+ payload,
+ request,
+ current_subject,
+ speech_api_default_max_tokens = body.max_new_tokens is None,
)
api_monitor.relabel(monitor_id, model_name)
await asyncio.to_thread(
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 77941fb8967..840ace5fa30 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -1214,19 +1214,19 @@ async def _shared_compat_local_inventory_scan(
requested_sources = sources
def classify(models: List[LocalModelInfo]) -> List[LocalModelInfo]:
- # Tag each model with its task so the Images picker can filter to diffusion.
+ # Tag each model with its task and native-audio type for the model pickers.
# Inside the shared flight so overlapping callers reuse one classified result
# instead of each repeating the GGUF header reads.
classified = []
for model in models:
- task = _local_model_task(model)
+ task, audio_type = _catalog_classification._local_model_classification_for_task(
+ model, _local_model_task(model)
+ )
classified.append(
model.model_copy(
update = {
"task": task,
- "audio_type": _catalog_classification._local_model_audio_type(model)
- if task == "text-to-speech"
- else None,
+ "audio_type": audio_type,
}
)
)
@@ -2521,7 +2521,14 @@ async def scan_model_remote_code(
except Exception:
_primary_preexisting = True
requested_scan_target = scan_target
- requested_security_targets = [requested_scan_target]
+ from core.inference.native_audio import native_audio_security_targets
+
+ try:
+ requested_security_targets = native_audio_security_targets(
+ requested_scan_target, hf_token = hf_token
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
try:
from utils.models.model_config import get_base_model_from_lora_identifier
diff --git a/studio/backend/routes/training_vram.py b/studio/backend/routes/training_vram.py
index d687e92f205..879ee2fd619 100644
--- a/studio/backend/routes/training_vram.py
+++ b/studio/backend/routes/training_vram.py
@@ -244,6 +244,7 @@ def can_load_chat_during_training(
vulkan_free_vram_gb: Optional[Dict[int, float]] = None,
required_override_gb: Optional[float] = None,
single_device_gpu: Optional[str] = None,
+ post_handoff_free_gpu_vram_gb: Optional[Dict[int, float]] = None,
) -> Tuple[bool, Dict[str, Any]]:
"""Decide if a NEW chat model can load without OOMing active training (inverse
of can_keep_chat_during_training: training is already resident, so size the
@@ -275,9 +276,37 @@ def can_load_chat_during_training(
max_seq_length = max_seq_length or 2048,
)
+ # A native-audio switch may carry one atomic post-handoff capacity
+ # snapshot. It already combines live free memory with only the outgoing
+ # Studio backend, so do not re-read and add those values here.
+ if not requested_gpu_ids and not is_gguf and post_handoff_free_gpu_vram_gb is not None:
+ required_gb = required_override_gb
+ if required_gb is None:
+ required_gb, _meta = estimate_required_model_memory_gb(model_name, **est_kwargs)
+ free_vals = [
+ max(float(effective), 0.0) for effective in post_handoff_free_gpu_vram_gb.values()
+ ]
+ usable_gb = max(free_vals) if free_vals else None
+ needed_gb = (
+ round(required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB, 3)
+ if required_gb is not None
+ else None
+ )
+ fits = required_gb is not None and usable_gb is not None and usable_gb >= needed_gb
+ return fits, {
+ "mode": "native_post_handoff",
+ "required_gb": required_gb,
+ "usable_gb": usable_gb,
+ "needed_gb": needed_gb,
+ }
+
# HF auto: reuse the loader's selector; fits iff its pick clears the margin.
if not requested_gpu_ids and not is_gguf:
- _selected, meta = auto_select_gpu_ids(model_name, **est_kwargs)
+ _selected, meta = auto_select_gpu_ids(
+ model_name,
+ required_override_gb = required_override_gb,
+ **est_kwargs,
+ )
mode = meta.get("selection_mode")
required_gb = meta.get("required_gb")
usable_gb = meta.get("usable_gb")
diff --git a/studio/backend/tests/test_audio_sampling_fill.py b/studio/backend/tests/test_audio_sampling_fill.py
index 3113b6edbca..fef057f6f7a 100644
--- a/studio/backend/tests/test_audio_sampling_fill.py
+++ b/studio/backend/tests/test_audio_sampling_fill.py
@@ -100,6 +100,28 @@ def test_audio_uses_recommended_sampling_when_omitted(monkeypatch):
assert captured["top_k"] == 64
+ "model_id",
+ (
+ "OpenMOSS-Team/MOSS-TTS-Local-Transformer-v1.5",
+ "OpenMOSS-Team/MOSS-TTS-Nano-100M",
+ ),
+)
+def test_moss_uses_the_published_audio_sampling_defaults(model_id):
+ expected = {
+ "temperature": 1.7,
+ "top_p": 0.8,
+ "top_k": 25,
+ "min_p": 0.0,
+ "repetition_penalty": 1.0,
+ }
+ assert ic.get_family_inference_params(model_id) == expected
+ resolved = ic.load_inference_config(model_id)
+ assert {key: resolved[key] for key in ("temperature", "top_p", "top_k", "min_p")} == {
+ key: expected[key] for key in ("temperature", "top_p", "top_k", "min_p")
+ }
+
+
def test_audio_operator_pin_overrides_client(monkeypatch):
monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.9")
captured = _run_generate_audio(monkeypatch, recommended = {"temperature": 1.0}, temperature = 0.2)
diff --git a/studio/backend/tests/test_audio_token_detection.py b/studio/backend/tests/test_audio_token_detection.py
index 89df02ddfe2..e3402411feb 100644
--- a/studio/backend/tests/test_audio_token_detection.py
+++ b/studio/backend/tests/test_audio_token_detection.py
@@ -9,7 +9,30 @@ from __future__ import annotations
import json
from utils.audio_tokens import AUDIO_TOKEN_PATTERNS
-from utils.models.model_config import is_audio_input_type
+from utils.models.model_config import (
+ detect_audio_type_checked,
+ is_audio_input_type,
+)
+
+
+def test_curated_native_audio_repos_are_detected_without_hub_reads():
+ expected = {
+ "bosonai/higgs-tts-2-3b-base": "higgs_tts2",
+ "OpenMOSS-Team/MOSS-TTS-Local-Transformer-v1.5": "moss_tts_local",
+ "OpenMOSS-Team/MOSS-TTS-Nano-100M": "moss_tts_nano",
+ "multimodalart/higgs-audio-v3-tts-4b-transformers": "higgs_tts3",
+ "MiniMaxAI/MiniMax-Music3": "minimax_music3",
+ }
+ for repo, audio_type in expected.items():
+ assert detect_audio_type_checked(repo) == (audio_type, True)
+
+
+def test_local_native_audio_model_type_is_detected(tmp_path):
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "moss_tts_nano"}),
+ encoding = "utf-8",
+ )
+ assert detect_audio_type_checked(str(tmp_path)) == ("moss_tts_nano", True)
def _classify(tokens: list[str]) -> str | None:
diff --git a/studio/backend/tests/test_audio_tts_cancellation.py b/studio/backend/tests/test_audio_tts_cancellation.py
index 2372741ee1c..ef19f1ec313 100644
--- a/studio/backend/tests/test_audio_tts_cancellation.py
+++ b/studio/backend/tests/test_audio_tts_cancellation.py
@@ -132,6 +132,44 @@ def test_route_passes_request_cancel_event_to_transformers_backend(monkeypatch):
assert captured["cancel_event"].is_set() is False
+def test_minimax_prompt_encoder_overflow_is_a_client_error(monkeypatch):
+ class _Llama:
+ is_loaded = False
+ _is_audio = False
+
+ class _Backend:
+ active_model_name = "MiniMaxAI/MiniMax-Music3"
+ models = {
+ "MiniMaxAI/MiniMax-Music3": {
+ "is_audio": True,
+ "audio_type": "minimax_music3",
+ }
+ }
+
+ def generate_audio_response(self, **_kwargs):
+ raise RuntimeError("The assembled prompt has 5001 tokens; the maximum is 5000")
+
+ async def _noop_switch(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _noop_switch)
+ payload = ChatCompletionRequest(
+ model = "MiniMaxAI/MiniMax-Music3",
+ messages = [{"role": "user", "content": "lyrics"}],
+ audio_instructions = "long music description",
+ )
+
+ with pytest.raises(inference_route.HTTPException) as excinfo:
+ asyncio.run(
+ inference_route._generate_tts_wav("lyrics", payload, request = None, current_subject = "t")
+ )
+
+ assert excinfo.value.status_code == 400
+ assert excinfo.value.detail == "The assembled prompt has 5001 tokens; the maximum is 5000"
+
+
def test_audio_response_stopped_while_queued_is_never_sent(monkeypatch):
orchestrator = _bare_orchestrator()
monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
@@ -312,8 +350,24 @@ def test_tts_route_bounds_public_token_budget():
assert inference_route._tts_max_new_tokens(payload) == 8192
-def test_audio_worker_command_uses_the_bounded_token_budget(monkeypatch):
+def test_minimax_music_route_allows_its_official_frame_budget():
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hello"}],
+ max_tokens = 10**310,
+ )
+
+ assert inference_route._tts_max_new_tokens(payload, audio_type = "minimax_music3") == 9000
+
+
+ ("audio_type", "expected_max_tokens"),
+ ((None, 8192), ("minimax_music3", 9000)),
+)
+def test_audio_worker_command_uses_the_model_token_budget(
+ monkeypatch, audio_type, expected_max_tokens
+):
orchestrator = _bare_orchestrator()
+ orchestrator.models["model"]["audio_type"] = audio_type
monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)
sent = []
monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))
@@ -340,7 +394,7 @@ def test_audio_worker_command_uses_the_bounded_token_budget(monkeypatch):
b"RIFFfake",
24000,
)
- assert sent[0]["max_new_tokens"] == 8192
+ assert sent[0]["max_new_tokens"] == expected_max_tokens
def test_audio_response_timeout_cancels_and_drains_before_releasing(monkeypatch):
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 17066171136..3057f08cbbf 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -3590,6 +3590,11 @@ def test_hub_local_rows_are_tagged_with_their_task():
assert '"task":task' in compact
assert '"audio_type":audio_type' in compact
+ from hub.services.models import catalog_classification
+
+ classifier_src = inspect.getsource(catalog_classification._local_model_audio_type)
+ assert "native_audio_type_from_local_path" in classifier_src
+
def test_pipeline_class_guard_fires_before_any_download():
# The newer families used to die with a bare AttributeError deep in the load, after the checkpoint was fetched, on
diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.py
index 247b2e5980e..49f8827b56a 100644
--- a/studio/backend/tests/test_chat_load_during_training.py
+++ b/studio/backend/tests/test_chat_load_during_training.py
@@ -11,6 +11,7 @@ and leaves non-training/external loads untouched."""
import asyncio
import importlib.util
import sys
+import threading
import types
import unittest
from pathlib import Path
@@ -444,6 +445,10 @@ def _stub_guard_deps(
):
"""Inject the guard's two lazy imports (get_training_backend, can_load_chat_
during_training); `captured` records the can_load kwargs for assertions."""
+ # Keep the process-wide lifecycle gate in patch.dict's module snapshot so
+ # later route imports cannot create a second lock through a stale package attribute.
+ import core.inference.llama_keepwarm # noqa: F401
+
core_training = types.ModuleType("core.training")
if isinstance(training_active, Exception):
@@ -866,6 +871,161 @@ class TestEffectiveLoadIn4bit(unittest.TestCase):
cfg = SimpleNamespace(is_lora = True, path = d, base_model = "x")
self.assertTrue(self.route._effective_load_in_4bit(cfg, True)) # no crash
+ def test_native_audio_uses_full_precision_for_admission(self):
+ cfg = SimpleNamespace(
+ is_lora = False,
+ path = None,
+ base_model = None,
+ audio_type = "moss_tts_local",
+ )
+ self.assertFalse(self.route._effective_load_in_4bit(cfg, True))
+
+
+class TestNativeAudioPlacementContracts(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.route = _load_inference_route()
+
+ def _preflight(
+ self,
+ *,
+ metadata,
+ availability = None,
+ requested = None,
+ selected = None,
+ ):
+ config = SimpleNamespace(identifier = "test/native-audio", audio_type = "higgs_tts2")
+ request = SimpleNamespace(gpu_ids = requested, hf_token = None, max_seq_length = 2048)
+ placement = self.route._LoadPlacement(requested, None, False, False)
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch(
+ "core.inference.native_audio.native_audio_security_targets",
+ return_value = [config.identifier],
+ ),
+ patch(
+ "utils.hardware.prepare_gpu_selection",
+ return_value = (selected if selected is not None else [0], metadata),
+ ),
+ patch.object(
+ self.route,
+ "_native_audio_post_handoff_free_gb",
+ return_value = availability,
+ ),
+ patch.object(_hw_module, "IS_ROCM", False),
+ ):
+ return asyncio.run(
+ self.route._preflight_native_audio_placement(config, request, placement)
+ )
+
+ def test_automatic_fallback_requires_attributable_resident_memory(self):
+ metadata = {"selection_mode": "fallback_all", "required_gb": 20.0, "usable_gb": 6.0}
+ with self.assertRaisesRegex(HTTPException, "No single GPU has enough free memory"):
+ self._preflight(metadata = metadata)
+
+ availability = self.route._NativeAudioAvailability({0: 24.0}, {0: 18.0})
+ placement = self._preflight(metadata = metadata, availability = availability)
+ self.assertEqual(placement.resolved_gpu_ids, [0])
+ self.assertEqual(placement.native_required_gb, 20.0)
+ self.assertEqual(placement.native_post_handoff_free_gb, {0: 24.0})
+
+ def test_minimax_uses_a_threshold_a_24_gb_card_can_report(self):
+ config = SimpleNamespace(
+ identifier = "MiniMaxAI/MiniMax-Music3",
+ audio_type = "minimax_music3",
+ )
+ request = SimpleNamespace(gpu_ids = None, hf_token = None, max_seq_length = 2048)
+ placement = self.route._LoadPlacement(None, None, False, False)
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch.object(_hw_module, "IS_ROCM", False),
+ patch(
+ "core.inference.native_audio.native_audio_security_targets",
+ return_value = [config.identifier],
+ ),
+ patch("utils.hardware.prepare_gpu_selection", return_value = ([1], {})) as prepare,
+ ):
+ result = asyncio.run(
+ self.route._preflight_native_audio_placement(config, request, placement)
+ )
+
+ self.assertEqual(result.resolved_gpu_ids, [1])
+ self.assertEqual(result.native_required_gb, 23.0)
+ self.assertEqual(prepare.call_args.kwargs["required_override_gb"], 23.0)
+
+ def test_explicit_multi_gpu_is_rejected_before_load(self):
+ with self.assertRaisesRegex(HTTPException, "require one GPU"):
+ self._preflight(
+ metadata = {"selection_mode": "explicit"},
+ requested = [0, 1],
+ selected = [0, 1],
+ )
+
+ def test_live_training_recheck_cannot_switch_off_selected_gpu(self):
+ with (
+ patch("utils.hardware.get_device", return_value = DeviceType.CUDA),
+ patch(
+ "utils.hardware.get_visible_gpu_utilization",
+ return_value = {"devices": _devices((0, 24, 12), (1, 48, 8))},
+ ),
+ patch("utils.hardware.resolve_requested_gpu_ids", return_value = [0]),
+ patch("utils.hardware.auto_select_gpu_ids") as auto_select,
+ ):
+ ok, info = tv.can_load_chat_during_training(
+ model_name = "m",
+ hf_token = None,
+ load_in_4bit = False,
+ max_seq_length = 2048,
+ requested_gpu_ids = [0],
+ required_override_gb = 16.0,
+ )
+ self.assertFalse(ok)
+ self.assertEqual(info["usable_gb"], 12.0)
+ auto_select.assert_not_called()
+
+ def test_worker_memory_reply_is_correlated_to_its_probe(self):
+ from core.inference.orchestrator import InferenceOrchestrator
+
+ backend = InferenceOrchestrator.__new__(InferenceOrchestrator)
+ replies = iter(
+ [
+ {"type": "gpu_memory", "request_id": "old", "reclaimable_gpu_gb": {"0": 10.0}},
+ {"type": "gpu_memory", "request_id": "new", "reclaimable_gpu_gb": {"0": 4.0}},
+ ]
+ )
+ backend._read_resp = lambda **_kwargs: next(replies)
+ backend._ensure_subprocess_alive = lambda: True
+ response = backend._wait_response("gpu_memory", timeout = 1.0, expected_request_id = "new")
+ self.assertEqual(response["reclaimable_gpu_gb"], {"0": 4.0})
+
+ def test_llama_floor_uses_the_child_to_physical_gpu_map(self):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._process = SimpleNamespace(poll = lambda: None)
+ backend._gpu_ids = None
+ backend._child_gpu_physical_ids = (1,)
+ backend._stdout_lines = ["load_tensors: CUDA0 model buffer size = 10240.0 MiB"]
+ self.assertEqual(backend.reclaimable_gpu_memory_gb(), {1: 10.0})
+
+ def test_inflight_media_replacement_is_never_credited(self):
+ utilization = {"devices": [{"index": 0, "vram_total_gb": 24.0, "vram_used_gb": 18.0}]}
+ media = SimpleNamespace(
+ _generate_lock = threading.Lock(),
+ _lock = threading.Lock(),
+ _state = object(),
+ _loading = object(),
+ )
+ with (
+ patch("utils.hardware.get_visible_gpu_utilization", return_value = utilization),
+ patch("core.inference.gpu_arbiter.owner_snapshot", return_value = ("diffusion", 4)),
+ patch(
+ "core.inference.diffusion_engine_router.get_active_diffusion_engine",
+ return_value = media,
+ ),
+ ):
+ self.assertIsNone(self.route._native_audio_post_handoff_free_gb())
+
# ── validate_model integration (early refusal, real settings) ────────────────
diff --git a/studio/backend/tests/test_consent_gate.py b/studio/backend/tests/test_consent_gate.py
index 4090101f145..24c44aea11e 100644
--- a/studio/backend/tests/test_consent_gate.py
+++ b/studio/backend/tests/test_consent_gate.py
@@ -9,6 +9,7 @@ and fingerprint run for real; only the config/file fetch is stubbed.
"""
import importlib.util
+import json
import os
import sys
from pathlib import Path
@@ -656,7 +657,15 @@ class TestStructuredFindingsForDialog:
# The scan route pins one combined fingerprint over adapter + base, so adapter code is reviewed and approvable too.
assert "preflight_remote_code_consent_for_targets" in src
- def _run_scan_route(self, monkeypatch, *, adapter, base, in_cache):
+ def _run_scan_route(
+ self,
+ monkeypatch,
+ *,
+ adapter,
+ base,
+ in_cache,
+ seen_targets = None,
+ ):
"""Call scan_model_remote_code with all network/cache deps stubbed; in_cache(repo)
decides whether a repo pre-existed in cache (so it is not reported scan-created)."""
import asyncio
@@ -674,7 +683,10 @@ class TestStructuredFindingsForDialog:
monkeypatch.setattr(
security,
"preflight_remote_code_consent_for_targets",
- lambda *_a, **_k: SimpleNamespace(
+ lambda targets, **_k: (
+ seen_targets.extend(targets) if seen_targets is not None else None
+ )
+ or SimpleNamespace(
has_remote_code = False,
response_payload = lambda: {"has_remote_code": False, "approvable": True},
),
@@ -719,6 +731,52 @@ class TestStructuredFindingsForDialog:
assert payload["scan_created_repos"] == [base]
assert payload["created_by_scan"] is False
+ def test_scan_route_fingerprint_includes_native_audio_companion(self, monkeypatch):
+ model = "multimodalart/higgs-audio-v3-tts-4b-transformers"
+ companion = "bosonai/higgs-audio-v2-tokenizer"
+ targets = []
+
+ self._run_scan_route(
+ monkeypatch,
+ adapter = model,
+ base = None,
+ in_cache = lambda _n: True,
+ seen_targets = targets,
+ )
+
+ assert targets == [model, companion]
+
+ def test_scan_route_rejects_oversized_audio_metadata_as_bad_request(
+ self, monkeypatch, tmp_path
+ ):
+ import asyncio
+
+ from fastapi import HTTPException
+
+ import routes.models as models_route
+ import utils.security as security
+
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "higgs_audio_v2"}), encoding = "utf-8"
+ )
+ (tmp_path / "processor_config.json").write_text(
+ json.dumps({"padding": "x" * 1_000_000}), encoding = "utf-8"
+ )
+ monkeypatch.setattr(models_route, "is_local_path", lambda *_args: True)
+ monkeypatch.setattr(security, "load_scan_target", lambda target, subdirs: (target, subdirs))
+
+ with pytest.raises(HTTPException) as exc_info:
+ asyncio.run(
+ models_route.scan_model_remote_code(
+ model_name = str(tmp_path),
+ hf_token = None,
+ current_subject = "tester",
+ )
+ )
+
+ assert exc_info.value.status_code == 400
+ assert "security inspection limit" in str(exc_info.value.detail)
+
def test_scan_route_uses_selected_cached_snapshot(self, monkeypatch, tmp_path):
import asyncio
diff --git a/studio/backend/tests/test_control_markup_neutralize_7066.py b/studio/backend/tests/test_control_markup_neutralize_7066.py
index 94bd5fe2da5..848b638c563 100644
--- a/studio/backend/tests/test_control_markup_neutralize_7066.py
+++ b/studio/backend/tests/test_control_markup_neutralize_7066.py
@@ -2384,6 +2384,62 @@ def test_param_alias_xml_delimiters_are_neutralized(marker):
"<|im_end|>",
],
),
+ (
+ "higgs_tts2",
+ [
+ "<|start_header_id|>",
+ "<|end_header_id|>",
+ "<|scene_desc_start|>",
+ "<|scene_desc_end|>",
+ "<|eot_id|>",
+ "<|audio_out_bos|>",
+ "<|AUDIO_OUT|>",
+ "<|audio_eos|>",
+ ],
+ ),
+ (
+ "moss_tts_local",
+ [
+ "<user_inst>",
+ "</user_inst>",
+ "<|im_start|>",
+ "<|im_end|>",
+ "<|audio|>",
+ "<|audio_start|>",
+ "<|audio_end|>",
+ "<|audio_pad|>",
+ "<|vision_pad|>",
+ "<|video_pad|>",
+ ],
+ ),
+ (
+ "moss_tts_nano",
+ [
+ "<user_inst>",
+ "</user_inst>",
+ "<|im_start|>",
+ "<|im_end|>",
+ "<|audio_start|>",
+ "<|audio_end|>",
+ "<|audio_pad|>",
+ "<|vision_pad|>",
+ "<|video_pad|>",
+ ],
+ ),
+ (
+ "minimax_music3",
+ [
+ "<|im_start|>",
+ "<|im_end|>",
+ "<|caption_start|>",
+ "<|caption_end|>",
+ "<|lyrics_start|>",
+ "<|lyrics_end|>",
+ "<|audio_start|>",
+ "<|audio_end|>",
+ "<|audio_cfg|>",
+ ],
+ ),
],
)
def test_tts_breaks_the_active_codec_delimiters(codec, delimiters):
diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.py
index 3c0ddd5e1dc..2f1da841ef8 100644
--- a/studio/backend/tests/test_gpu_memory_mode.py
+++ b/studio/backend/tests/test_gpu_memory_mode.py
@@ -949,6 +949,16 @@ def test_start_diffusion_server_resets_tensor_parallel():
# ── Manual tensor split: child enumeration pinned to the picker's order ──────
+ ("parent_ids", "expected"),
+ [([], None), ([2], (2,)), ([0, 1], None)],
+)
+def test_unmasked_child_gpu_map_is_known_only_for_one_gpu(monkeypatch, parent_ids, expected):
+ import utils.hardware as hw
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: parent_ids)
+ assert LlamaCppBackend._unmasked_child_gpu_physical_ids() == expected
+
+
def _patch_split_pin_env(monkeypatch, *, inherited, reported):
"""Point the pin helper at a fake inherited mask and picker report.
``reported`` None = enumeration unavailable (falls back to ascending)."""
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index ec94d855eec..5de0655c4f2 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -1746,6 +1746,42 @@ def test_task_inventory_preserves_cached_community_tts_codec(tmp_path, monkeypat
assert rows[0]["audio_type"] == "snac"
+def test_active_cache_native_fork_loads_by_detected_snapshot(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ from core.inference.native_audio import is_native_audio_model
+ from hub.services.models import cache_inventory
+
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"moss_tts_local"}',
+ "model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": SNAPSHOT},
+ name = "models--acme--native-audio-fork",
+ )
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = tmp_path),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ rows = cache_inventory._scan_cached_models()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+
+ snapshot = repo_dir / "snapshots" / SNAPSHOT
+ assert rows[0]["repo_id"] == "acme/native-audio-fork"
+ assert rows[0]["audio_type"] == "moss_tts_local"
+ assert rows[0]["load_id"] == str(snapshot)
+ assert rows[0]["capabilities"]["can_chat"] is False
+ assert is_native_audio_model(rows[0]["load_id"])
+
+
def test_a_secondary_dangling_ref_still_judges_the_recovered_snapshot(tmp_path, monkeypatch):
"""refs/main resolves while refs/stale dangles, so recovery fires but the default-ref test does
not. The pinned snapshot is short a shard with no marker, manifest or .incomplete blob, so its
@@ -3310,6 +3346,17 @@ _CASCADE_INDEX = {
}
+def test_modular_manifest_is_parsed_before_fixed_denoiser_fallback(tmp_path):
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "modular_model_index.json").write_text(json.dumps(_CASCADE_INDEX))
+ decoder = snapshot / "decoder"
+ decoder.mkdir()
+ (decoder / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
+
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
def test_a_denoiser_missing_half_its_shards_is_not_a_present_denoiser(tmp_path):
"""Shard 1 of 2 alone is not a present denoiser, and the last shard completes it."""
snapshot = _pipeline_snapshot(
diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.py
index 5ccfe327fc1..82388b57464 100644
--- a/studio/backend/tests/test_local_model_format.py
+++ b/studio/backend/tests/test_local_model_format.py
@@ -15,6 +15,7 @@ No GPU/network: only file names and sizes are inspected.
from __future__ import annotations
+import asyncio
import json
import sys
import types
@@ -471,6 +472,60 @@ def test_local_task_none_for_plain_llm(tmp_path):
assert models_route._local_model_task(_local(d, model_id = "meta-llama/Llama-3.1-8B")) is None
+def test_local_task_tags_minimax_music3_modular_pipeline(tmp_path):
+ d = tmp_path / "music3"
+ d.mkdir()
+ (d / "modular_model_index.json").write_text(
+ json.dumps(
+ {
+ "_class_name": "MiniMaxMusic3ModularPipeline",
+ "_blocks_class_name": "MiniMaxMusic3Blocks",
+ }
+ ),
+ encoding = "utf-8",
+ )
+
+ assert models_route._local_model_task(_local(d, model_format = "safetensors")) == (
+ "text-to-speech"
+ )
+
+
+def test_compat_local_inventory_preserves_minimax_music3_audio_type(monkeypatch, tmp_path):
+ models_dir = tmp_path / "models"
+ d = models_dir / "music3"
+ d.mkdir(parents = True)
+ (d / "modular_model_index.json").write_text(
+ json.dumps(
+ {
+ "_class_name": "MiniMaxMusic3ModularPipeline",
+ "_blocks_class_name": "MiniMaxMusic3Blocks",
+ }
+ ),
+ encoding = "utf-8",
+ )
+ sources = models_route._CompatLocalInventorySources(
+ hf_cache_dir = models_dir,
+ legacy_hf = tmp_path / "legacy",
+ hf_default = tmp_path / "default",
+ lm_dirs = (),
+ known_hf_caches = (),
+ )
+
+ def scan(_models_root, *, custom_folders, sources):
+ return [_local(d, model_format = "safetensors", id = str(d))]
+
+ monkeypatch.setattr(models_route, "_compat_local_inventory_sources", lambda: sources)
+ monkeypatch.setattr(models_route, "collect_local_models", scan)
+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [])
+
+ response = asyncio.run(
+ models_route.list_local_models(models_dir = str(models_dir), current_subject = "test")
+ )
+
+ assert response.models[0].task == "text-to-speech"
+ assert response.models[0].audio_type == "minimax_music3"
+
+
def test_local_task_tags_video_pipeline_dir(tmp_path):
# A local diffusers pipeline whose id resolves to a VIDEO family must be tagged text-to-video so it surfaces in the Video On-Device picker.
d = tmp_path / "wan-local"
diff --git a/studio/backend/tests/test_native_audio.py b/studio/backend/tests/test_native_audio.py
new file mode 100644
index 00000000000..c4ccb96996f
--- /dev/null
+++ b/studio/backend/tests/test_native_audio.py
@@ -0,0 +1,711 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Compact hermetic contracts for native audio adapters."""
+
+from __future__ import annotations
+
+import json
+import sys
+import threading
+from types import SimpleNamespace
+
+import pytest
+import torch
+import torchaudio
+
+from core.inference.native_audio import (
+ HIGGS_TTS2_CODEC_REPO,
+ HIGGS_TTS3_CODEC_REPO,
+ MOSS_LOCAL_CODEC_REPO,
+ MOSS_NANO_CODEC_REPO,
+ NativeAudioBackend,
+ _moss_transformers5_config_compat,
+ _repair_moss_nano_rotary_buffers,
+ is_native_audio_model,
+ native_audio_download_plan,
+ native_audio_kv_memory_gb,
+ native_audio_security_targets,
+ native_audio_type_from_local_path,
+)
+
+
+def _backend(audio_type: str, **entry):
+ backend = NativeAudioBackend.__new__(NativeAudioBackend)
+ backend.device = "cpu"
+ backend.active_model_name = "test/model"
+ backend.models = {
+ "test/model": {
+ "audio_type": audio_type,
+ "sample_rate": entry.pop("sample_rate", 24000),
+ **entry,
+ }
+ }
+ return backend
+
+
+ ("repo", "companion"),
+ (
+ ("bosonai/higgs-tts-2-3b-base", HIGGS_TTS2_CODEC_REPO),
+ ("multimodalart/higgs-audio-v3-tts-4b-transformers", HIGGS_TTS3_CODEC_REPO),
+ ("OpenMOSS-Team/MOSS-TTS-Local-Transformer-v1.5", MOSS_LOCAL_CODEC_REPO),
+ ("OpenMOSS-Team/MOSS-TTS-Nano-100M", MOSS_NANO_CODEC_REPO),
+ ("MiniMaxAI/MiniMax-Music3", None),
+ ),
+)
+def test_curated_native_families_and_security_targets(repo, companion, monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.native_audio._read_audio_metadata", lambda *_args, **_kwargs: {}
+ )
+ assert is_native_audio_model(repo)
+ assert native_audio_security_targets(repo) == ([repo, companion] if companion else [repo])
+
+
+def test_local_minimax_detection_and_moss_companion_override(tmp_path):
+ (tmp_path / "modular_model_index.json").write_text(
+ json.dumps(
+ {
+ "_class_name": "MiniMaxMusic3ModularPipeline",
+ "_blocks_class_name": "MiniMaxMusic3Blocks",
+ }
+ ),
+ encoding = "utf-8",
+ )
+ assert native_audio_type_from_local_path(str(tmp_path)) == "minimax_music3"
+
+ (tmp_path / "modular_model_index.json").unlink()
+ (tmp_path / "processor_config.json").write_text(
+ json.dumps({"audio_tokenizer_name_or_path": "acme/custom-codec"}), encoding = "utf-8"
+ )
+ assert native_audio_security_targets(str(tmp_path), "moss_tts_local") == [
+ str(tmp_path),
+ "acme/custom-codec",
+ ]
+
+
+ ("audio_type", "metadata_file", "metadata", "codec"),
+ (
+ (
+ "higgs_tts2",
+ "processor_config.json",
+ {"audio_tokenizer": {"audio_tokenizer_name_or_path": "acme/private-higgs2-codec"}},
+ "acme/private-higgs2-codec",
+ ),
+ (
+ "higgs_tts3",
+ "config.json",
+ {
+ "model_type": "higgs_multimodal_qwen3",
+ "audio_tokenizer_id": "acme/private-higgs3-codec",
+ },
+ "acme/private-higgs3-codec",
+ ),
+ ),
+)
+def test_local_higgs_companion_metadata_drives_security_and_download_plans(
+ tmp_path, monkeypatch, audio_type, metadata_file, metadata, codec
+):
+ if metadata_file != "config.json":
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "higgs_audio_v2"}), encoding = "utf-8"
+ )
+ (tmp_path / metadata_file).write_text(json.dumps(metadata), encoding = "utf-8")
+ assert native_audio_security_targets(str(tmp_path), audio_type) == [str(tmp_path), codec]
+
+ calls = []
+ siblings = [SimpleNamespace(rfilename = "model.safetensors", size = 100)]
+
+ def model_info(repo_id, **_kwargs):
+ calls.append(repo_id)
+ return SimpleNamespace(sha = "current", siblings = siblings)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(HfApi = lambda **_kwargs: SimpleNamespace(model_info = model_info)),
+ )
+ monkeypatch.setattr(
+ "core.inference.native_audio._native_audio_file_is_cached", lambda *_args: False
+ )
+ plan = native_audio_download_plan(str(tmp_path))
+ assert calls == [codec]
+ assert [entry["repo_id"] for entry in plan["entries"]] == [codec]
+
+
+def test_higgs2_audio_tokenizer_config_takes_runtime_precedence(tmp_path):
+ (tmp_path / "processor_config.json").write_text(
+ json.dumps({"audio_tokenizer": {"audio_tokenizer_name_or_path": "acme/processor-codec"}}),
+ encoding = "utf-8",
+ )
+ (tmp_path / "audio_tokenizer_config.json").write_text(
+ json.dumps({"audio_tokenizer_name_or_path": "acme/standalone-codec"}),
+ encoding = "utf-8",
+ )
+
+ assert native_audio_security_targets(str(tmp_path), "higgs_tts2") == [
+ str(tmp_path),
+ "acme/standalone-codec",
+ ]
+
+
[email protected]("metadata_file", ("processor_config.json", "audio_tokenizer_config.json"))
+def test_oversized_higgs_companion_metadata_fails_closed(tmp_path, metadata_file):
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "higgs_audio_v2"}), encoding = "utf-8"
+ )
+ metadata = {
+ "audio_tokenizer": {"audio_tokenizer_name_or_path": "acme/unapproved-codec"},
+ "padding": "x" * 1_000_000,
+ }
+ (tmp_path / metadata_file).write_text(json.dumps(metadata), encoding = "utf-8")
+
+ with pytest.raises(ValueError, match = "security inspection limit"):
+ native_audio_security_targets(str(tmp_path), "higgs_tts2")
+ with pytest.raises(ValueError, match = "security inspection limit"):
+ native_audio_download_plan(str(tmp_path))
+
+
+def test_worker_reports_oversized_audio_metadata_as_a_load_error(tmp_path):
+ from core.inference import worker
+
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "higgs_audio_v2"}), encoding = "utf-8"
+ )
+ (tmp_path / "processor_config.json").write_text(
+ json.dumps({"padding": "x" * 1_000_000}), encoding = "utf-8"
+ )
+
+ class Queue:
+ sent = []
+
+ def put(self, message, *_args, **_kwargs):
+ self.sent.append(message)
+
+ queue = Queue()
+ targets = worker._native_audio_security_targets_or_error(str(tmp_path), None, queue)
+
+ assert targets is None
+ assert queue.sent[-1]["type"] == "error"
+ assert "security inspection limit" in queue.sent[-1]["error"]
+
+
+def test_minimax_download_plan_excludes_unreferenced_legacy_weights(monkeypatch):
+ siblings = [
+ SimpleNamespace(rfilename = "modular_model_index.json", size = 10),
+ SimpleNamespace(rfilename = "transformer/model.safetensors", size = 100),
+ SimpleNamespace(rfilename = "flowmatching_vae.pth", size = 500),
+ SimpleNamespace(rfilename = "qwen_7B/model.safetensors", size = 400),
+ ]
+ api = SimpleNamespace(
+ model_info = lambda *_args, **_kwargs: SimpleNamespace(sha = "current", siblings = siblings)
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(HfApi = lambda **_kwargs: api),
+ )
+ monkeypatch.setattr(
+ "core.inference.native_audio._native_audio_file_is_cached", lambda *_args: False
+ )
+
+ plan = native_audio_download_plan("MiniMaxAI/MiniMax-Music3")
+ assert plan["entries"][0]["files"] == [
+ "modular_model_index.json",
+ "transformer/model.safetensors",
+ ]
+ assert plan["required_bytes"] == 110
+
+
+def test_higgs_tts2_download_plan_includes_audio_tokenizer(monkeypatch):
+ calls = []
+ siblings = [SimpleNamespace(rfilename = "model.safetensors", size = 100)]
+
+ def model_info(repo_id, **_kwargs):
+ calls.append(repo_id)
+ return SimpleNamespace(sha = "current", siblings = siblings)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(HfApi = lambda **_kwargs: SimpleNamespace(model_info = model_info)),
+ )
+ monkeypatch.setattr(
+ "core.inference.native_audio._native_audio_file_is_cached", lambda *_args: False
+ )
+
+ plan = native_audio_download_plan("bosonai/higgs-tts-2-3b-base")
+ assert calls == ["bosonai/higgs-tts-2-3b-base", HIGGS_TTS2_CODEC_REPO]
+ assert [entry["repo_id"] for entry in plan["entries"]] == calls
+
+
+ ("repo", "message"),
+ (
+ ("bosonai/higgs-tts-2-3b-base", "Higgs TTS"),
+ ("multimodalart/higgs-audio-v3-tts-4b-transformers", "Higgs TTS"),
+ ("MiniMaxAI/MiniMax-Music3", "MiniMax Music 3"),
+ ),
+)
+def test_python39_refuses_unsupported_audio_before_download_planning(monkeypatch, repo, message):
+ monkeypatch.setattr("core.inference.native_audio.sys.version_info", (3, 9, 20))
+
+ with pytest.raises(ValueError, match = rf"{message} requires Python 3\.10"):
+ native_audio_download_plan(repo)
+
+
+def test_moss_kv_memory_uses_full_published_context(tmp_path):
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "gpt2_config": {
+ "n_positions": 32768,
+ "n_layer": 12,
+ "n_head": 12,
+ "n_embd": 768,
+ }
+ }
+ ),
+ encoding = "utf-8",
+ )
+ assert native_audio_kv_memory_gb(str(tmp_path), "moss_tts_nano") == pytest.approx(1.125)
+
+
+def test_transformers5_moss_compat_is_scoped(monkeypatch):
+ calls = []
+
+ class Config:
+ def __init_subclass__(cls, **_kwargs):
+ raise TypeError("non-default argument 'sampling_rate' follows default argument")
+
+ original = Config.__dict__["__init_subclass__"]
+
+ class AutoConfig:
+ @staticmethod
+ def from_pretrained(source, **kwargs):
+ calls.append((source, kwargs))
+
+ class Published(Config):
+ pass
+
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(__version__ = "5.5.0", AutoConfig = AutoConfig, PreTrainedConfig = Config),
+ )
+ _moss_transformers5_config_compat("OpenMOSS-Team/codec", {"token": "secret"})
+ assert calls == [("OpenMOSS-Team/codec", {"trust_remote_code": True, "token": "secret"})]
+ assert Config.__dict__["__init_subclass__"] is original
+
+
+ ("trust", "gpu_ids", "error"),
+ ((False, None, "trust_remote_code=True"), (True, [0, 1], "single selected GPU")),
+)
+def test_native_load_refuses_unsafe_consent_or_placement(trust, gpu_ids, error):
+ backend = NativeAudioBackend.__new__(NativeAudioBackend)
+ backend.device = "cuda"
+ backend.models = {}
+ backend.active_model_name = None
+ backend.loading_models = set()
+ backend._load_moss_local = lambda *_args: pytest.fail("loader must not run")
+ config = SimpleNamespace(
+ identifier = "OpenMOSS-Team/MOSS-TTS-Local-Transformer-v1.5",
+ path = None,
+ audio_type = "moss_tts_local",
+ )
+ with pytest.raises(RuntimeError, match = error):
+ backend.load_model(config, trust_remote_code = trust, gpu_ids = gpu_ids)
+
+
+def test_higgs_tts2_generation_contract_and_prompt_neutralization():
+ seen = {}
+
+ class Processor:
+ def apply_chat_template(self, conversation, **kwargs):
+ seen.update(conversation = conversation, template = kwargs)
+ return SimpleNamespace(to = lambda _device: {"input_ids": torch.tensor([[1]])})
+
+ def batch_decode(self, _outputs):
+ return [torch.zeros(240)]
+
+ model = SimpleNamespace(
+ device = "cpu",
+ generate = lambda **kwargs: seen.setdefault("generate", kwargs) or torch.tensor([[1, 2]]),
+ )
+ backend = _backend("higgs_tts2", model = model, processor = Processor())
+ wav, rate = backend.generate_audio_response(
+ "Hello <|eot_id|>", instructions = "Close <|scene_desc_end|>", max_new_tokens = 321
+ )
+ assert wav[:4] == b"RIFF" and rate == 24000
+ assert seen["conversation"][1]["content"][0]["text"] == "Close < |scene_desc_end|>"
+ assert seen["generate"]["max_new_tokens"] == 321
+
+
+def test_higgs_tts2_loader_moves_the_audio_tokenizer(monkeypatch):
+ codec = SimpleNamespace(to = lambda _device: None)
+ processor = SimpleNamespace(audio_tokenizer = codec)
+ model = object()
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ AutoProcessor = SimpleNamespace(from_pretrained = lambda *_args, **_kwargs: processor),
+ HiggsAudioV2ForConditionalGeneration = SimpleNamespace(
+ from_pretrained = lambda *_args, **_kwargs: model
+ ),
+ ),
+ )
+ backend = NativeAudioBackend.__new__(NativeAudioBackend)
+ backend.device = "cuda"
+ backend._dtype = lambda: torch.float16
+ moved = []
+ backend._move = lambda value: moved.append(value) or f"moved-{len(moved)}"
+
+ entry = {}
+ backend._load_higgs_tts2(entry, "bosonai/higgs-tts-2-3b-base", None)
+ assert moved == [codec, model]
+ assert processor.audio_tokenizer == "moved-1"
+ assert entry["model"] == "moved-2"
+
+
+def test_higgs_tts3_generation_contract():
+ seen = {}
+ tokenizer = object()
+ model = SimpleNamespace(
+ generate_speech = lambda text, processor, **kwargs: (
+ seen.update(text = text, processor = processor, **kwargs) or torch.zeros(240)
+ )
+ )
+ backend = _backend("higgs_tts3", model = model, processor = tokenizer)
+ wav, rate = backend.generate_audio_response("Hello v3", temperature = 0, max_new_tokens = 777)
+ assert wav[:4] == b"RIFF" and rate == 24000
+ assert (seen["text"], seen["processor"], seen["max_new_tokens"]) == (
+ "Hello v3",
+ tokenizer,
+ 777,
+ )
+
+
+def test_moss_cuda_sdpa_disables_the_broken_cudnn_backend(monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ torch.backends.cuda, "enable_flash_sdp", lambda value: calls.append(("flash", value))
+ )
+ monkeypatch.setattr(
+ torch.backends.cuda,
+ "enable_mem_efficient_sdp",
+ lambda value: calls.append(("memory", value)),
+ )
+ monkeypatch.setattr(
+ torch.backends.cuda, "enable_math_sdp", lambda value: calls.append(("math", value))
+ )
+ monkeypatch.setattr(
+ torch.backends.cuda, "enable_cudnn_sdp", lambda value: calls.append(("cudnn", value))
+ )
+ monkeypatch.setattr(torch.version, "hip", None)
+
+ NativeAudioBackend._configure_moss_cuda_sdpa()
+ assert calls == [("flash", True), ("memory", True), ("math", True), ("cudnn", False)]
+
+
+def test_moss_nano_overrides_flash_attention_on_cpu(monkeypatch):
+ seen = {}
+
+ def load_model(*_args, **kwargs):
+ seen.update(kwargs)
+ return SimpleNamespace(to = lambda _device: None, eval = lambda: None)
+
+ movable = SimpleNamespace(to = lambda _device: None, eval = lambda: None)
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ AutoModelForCausalLM = SimpleNamespace(from_pretrained = load_model),
+ AutoModel = SimpleNamespace(from_pretrained = lambda *_args, **_kwargs: movable),
+ AutoTokenizer = SimpleNamespace(from_pretrained = lambda *_args, **_kwargs: object()),
+ ),
+ )
+ monkeypatch.setattr(
+ "core.inference.native_audio._moss_transformers5_config_compat",
+ lambda *_args: None,
+ )
+ backend = NativeAudioBackend.__new__(NativeAudioBackend)
+ backend.device = "cpu"
+ backend._dtype = lambda: torch.float32
+ entry = {}
+
+ backend._load_moss_nano(entry, "OpenMOSS-Team/MOSS-TTS-Nano-100M", None, True)
+ assert seen["attn_implementation"] == "eager"
+ assert seen["local_transformer_attn_implementation"] == "eager"
+
+
+def test_moss_nano_repairs_transformers5_rotary_buffers():
+ class Rotary(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("inv_freq", torch.full((4,), float("nan")), persistent = False)
+
+ class Attention(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.rotary_emb = Rotary()
+
+ class Decoder(torch.nn.Module):
+ def __init__(self, base):
+ super().__init__()
+ self.config = SimpleNamespace(rope_base = base)
+ self.attention = Attention()
+
+ model = SimpleNamespace(transformer = Decoder(10000.0), local_transformer = Decoder(100.0))
+ _repair_moss_nano_rotary_buffers(model)
+
+ assert torch.equal(
+ model.transformer.attention.rotary_emb.inv_freq,
+ torch.tensor([1.0, 0.1, 0.01, 0.001]),
+ )
+ assert torch.allclose(
+ model.local_transformer.attention.rotary_emb.inv_freq,
+ torch.tensor([1.0, 100**-0.25, 0.1, 100**-0.75]),
+ )
+ assert "inv_freq" in model.transformer.attention.rotary_emb._non_persistent_buffers_set
+
+
+def test_moss_local_generation_contract():
+ seen = {}
+
+ class Processor:
+ def build_user_message(self, **kwargs):
+ seen["message"] = kwargs
+ return kwargs
+
+ def __call__(self, conversations, mode):
+ seen.update(conversations = conversations, mode = mode)
+ return {"input_ids": torch.tensor([[1]]), "attention_mask": torch.tensor([[1]])}
+
+ def decode(self, _outputs):
+ return [SimpleNamespace(audio_codes_list = [torch.zeros((2, 480))])]
+
+ model = SimpleNamespace(
+ generate = lambda **kwargs: seen.setdefault("generate", kwargs) or torch.tensor([[1, 2]])
+ )
+ backend = _backend("moss_tts_local", model = model, processor = Processor(), sample_rate = 48000)
+ wav, rate = backend.generate_audio_response(
+ "Bonjour <|im_end|>",
+ instructions = "Warm </user_inst>",
+ language = "<|audio|>French",
+ max_new_tokens = 400,
+ )
+ assert wav[:4] == b"RIFF" and rate == 48000
+ assert seen["message"] == {
+ "text": "Bonjour < |im_end|>",
+ "instruction": "Warm < /user_inst>",
+ "language": "< |audio|>French",
+ }
+ assert seen["mode"] == "generation" and seen["generate"]["audio_top_k"] == 50
+
+
+def test_moss_nano_generation_contract():
+ seen = {}
+
+ class Model:
+ def inference(self, **kwargs):
+ seen.update(kwargs)
+ torchaudio.save(kwargs["output_audio_path"], torch.zeros((2, 480)), 48000)
+ return {"sample_rate": 48000}
+
+ codec, tokenizer = object(), object()
+ backend = _backend(
+ "moss_tts_nano",
+ model = Model(),
+ processor = tokenizer,
+ audio_codec = codec,
+ sample_rate = 48000,
+ )
+ original_torchaudio = sys.modules[__name__].torchaudio
+ wav, rate = backend.generate_audio_response("Portable <|im_start|>speech", max_new_tokens = 375)
+ assert wav[:4] == b"RIFF" and rate == 48000
+ assert sys.modules[__name__].torchaudio is original_torchaudio
+ assert seen["text"] == "Portable < |im_start|>speech"
+ assert seen["audio_tokenizer"] is codec and seen["text_tokenizer"] is tokenizer
+ assert seen["max_new_frames"] == 375
+
+
+def test_native_speech_seed_is_reproducible_and_restores_global_rng():
+ class Model:
+ def generate_speech(self, *_args, **_kwargs):
+ return torch.rand(240)
+
+ backend = _backend("higgs_tts3", model = Model(), processor = object())
+ torch.manual_seed(91)
+ expected_next = torch.rand(8)
+ torch.manual_seed(91)
+
+ first, _ = backend.generate_audio_response("seeded", seed = 7)
+ actual_next = torch.rand(8)
+ second, _ = backend.generate_audio_response("seeded", seed = 7)
+ different, _ = backend.generate_audio_response("seeded", seed = 8)
+
+ assert torch.equal(actual_next, expected_next)
+ assert first == second
+ assert first != different
+
+
+def test_minimax_generation_and_cancellation_contract():
+ seen = {}
+ cancelled = threading.Event()
+
+ class Core:
+ hook = None
+
+ def register_forward_pre_hook(self, hook):
+ self.hook = hook
+ return SimpleNamespace(remove = lambda: seen.setdefault("removed", True))
+
+ class Pipeline:
+ language_model = SimpleNamespace(model = Core())
+ frame_rate = 25.0
+
+ def __call__(self, **kwargs):
+ seen.update(kwargs)
+ if self.language_model.model.hook:
+ self.language_model.model.hook(self.language_model.model, ())
+ if seen.get("cancel_mode"):
+ cancelled.set()
+ self.language_model.model.hook(self.language_model.model, ())
+ return [torch.zeros((2, 441))]
+
+ pipeline = Pipeline()
+ backend = _backend("minimax_music3", pipeline = pipeline, sample_rate = 44100)
+ wav, rate = backend.generate_audio_response(
+ "[verse] Morning <|lyrics_end|> <|audio_start|>",
+ instructions = "Acoustic",
+ max_new_tokens = 1500,
+ seed = 7,
+ )
+ assert wav[:4] == b"RIFF" and rate == 44100
+ assert seen["audio_duration"] == 60.0 and seen["generator"].initial_seed() == 7
+ assert seen["lyrics"] == "[verse]\nMorning < |lyrics_end|> < |audio_start|>"
+
+ backend.generate_audio_response("lyrics", instructions = "description", max_new_tokens = 1)
+ assert seen["audio_duration"] == pytest.approx(1 / 25)
+ backend.generate_audio_response("lyrics", instructions = "description", max_new_tokens = 8192)
+ assert seen["audio_duration"] == pytest.approx(8192 / 25)
+
+ seen["cancel_mode"] = True
+ with pytest.raises(RuntimeError, match = "cancelled"):
+ backend.generate_audio_response(
+ "lyrics", instructions = "description", cancel_event = cancelled
+ )
+ assert seen["removed"] is True
+
+
+def test_minimax_loader_resolves_components_from_the_selected_checkpoint(monkeypatch):
+ seen = {}
+
+ class Pipeline:
+ sampling_rate = 44100
+
+ def load_components(self, **kwargs):
+ seen["components"] = kwargs
+
+ def to(self, device):
+ seen["device"] = device
+
+ pipeline = Pipeline()
+
+ def from_pretrained(source, **_kwargs):
+ seen["source"] = source
+ return pipeline
+
+ monkeypatch.setitem(
+ sys.modules,
+ "diffusers",
+ SimpleNamespace(ModularPipeline = SimpleNamespace(from_pretrained = from_pretrained)),
+ )
+ backend = NativeAudioBackend.__new__(NativeAudioBackend)
+ backend.device = "cuda"
+ backend._dtype = lambda: torch.float16
+
+ entry = {}
+ backend._load_minimax_music3(entry, "/models/minimax-custom", None)
+ assert seen["components"]["pretrained_model_name_or_path"] == "/models/minimax-custom"
+ assert seen["device"] == "cuda"
+ assert entry["pipeline"] is pipeline
+
+
+def test_higgs_tts3_loader_uses_the_approved_codec_target_and_token(monkeypatch):
+ seen = {}
+
+ class Parameter:
+ frozen = False
+
+ def requires_grad_(self, value):
+ self.frozen = not value
+
+ class Codec:
+ parameter = Parameter()
+
+ def to(self, device):
+ seen["codec_device"] = device
+ return self
+
+ def eval(self):
+ seen["codec_eval"] = True
+ return self
+
+ def parameters(self):
+ return [self.parameter]
+
+ codec = Codec()
+
+ class Model:
+ config = SimpleNamespace(sample_rate = 24000)
+
+ def to(self, device):
+ seen["model_device"] = device
+ return self
+
+ def eval(self):
+ return self
+
+ def get_audio_codec(self):
+ raise AssertionError("the zero-argument publisher loader drops the token")
+
+ def load_codec(source, **kwargs):
+ seen["codec_load"] = (source, kwargs)
+ return codec
+
+ monkeypatch.setattr(
+ "core.inference.native_audio._higgs_tts3_codec_target",
+ lambda *_args: "acme/private-higgs3-codec",
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ AutoModel = SimpleNamespace(from_pretrained = load_codec),
+ AutoModelForCausalLM = SimpleNamespace(from_pretrained = lambda *_args, **_kwargs: Model()),
+ AutoTokenizer = SimpleNamespace(from_pretrained = lambda *_args, **_kwargs: object()),
+ ),
+ )
+ backend = NativeAudioBackend.__new__(NativeAudioBackend)
+ backend.device = "cuda"
+ backend._dtype = lambda: torch.bfloat16
+ backend._token_kwargs = lambda _token: {"token": "secret"}
+
+ entry = {}
+ backend._load_higgs_tts3(entry, "/models/higgs3", "secret", True)
+ source, kwargs = seen["codec_load"]
+ assert source == "acme/private-higgs3-codec"
+ assert kwargs["token"] == "secret" and kwargs["trust_remote_code"] is True
+ assert kwargs["dtype"] is torch.float32
+ assert entry["model"]._audio_codec is codec
+ assert codec.parameter.frozen and seen["codec_device"] == "cuda" and seen["codec_eval"]
+
+
+def test_minimax_requires_a_separate_description():
+ backend = _backend("minimax_music3", pipeline = object(), sample_rate = 44100)
+ with pytest.raises(RuntimeError, match = "music description"):
+ backend.generate_audio_response("lyrics only")
diff --git a/studio/backend/tests/test_openai_audio_speech_route.py b/studio/backend/tests/test_openai_audio_speech_route.py
index 05a27e77a9c..0bb0d725990 100644
--- a/studio/backend/tests/test_openai_audio_speech_route.py
+++ b/studio/backend/tests/test_openai_audio_speech_route.py
@@ -28,7 +28,7 @@ _WAV = b"RIFF\x24\x00\x00\x00WAVEfmt fake-payload"
def _make_client(monkeypatch, generate = None):
calls = []
- async def _fake_generate(text, payload, request, current_subject):
+ async def _fake_generate(text, payload, request, current_subject, **_kwargs):
calls.append({"text": text, "payload": payload})
if generate is not None:
return await generate(text)
@@ -291,27 +291,18 @@ def test_one_oversized_clip_is_still_returned_rather_than_pruned_immediately(mon
assert [clip["id"] for clip in gallery.list_audio()] == [saved["id"]]
-def test_non_latin_prompts_are_not_billed_at_the_latin_rate():
- """Without a Python tokenizer (GGUF TTS), the estimate is by character class. Cutting
- at U+2E7F caught CJK and emoji but billed Arabic, Cyrillic, Hebrew and the Indic
- scripts at a third of a token each, so a long prompt in any of them passed the guard
- and then overflowed the loaded context during generation."""
+def test_unreachable_subprocess_tokenizers_use_a_conservative_byte_budget():
estimate = routes_module._prompt_token_estimate
- for label, text in (
- ("arabic", "مرحبا بالعالم " * 40),
- ("cyrillic", "Привет мир " * 40),
- ("hebrew", "שלום עולם " * 40),
- ("devanagari", "नमस्ते दुनिया " * 40),
+ for text in (
+ "a " * 100,
+ "مرحبا بالعالم " * 40,
+ "Привет мир " * 40,
+ "שלום עולם " * 40,
+ "नमस्ते दुनिया " * 40,
+ "你好世界" * 50,
):
- assert estimate(text) >= len(text.replace(" ", "")), label
-
- # Latin is still counted at the cheaper rate, so ordinary English is not rejected.
- english = "the quick brown fox jumps over the lazy dog " * 40
- assert estimate(english) < len(english) // 2
-
- # And CJK, which already worked, is unchanged.
- assert estimate("你好世界" * 50) >= 200
+ assert estimate(text) == len(text.encode("utf-8"))
# ── External connection proxying (provider_id) ───────────────────
@@ -368,6 +359,7 @@ def test_provider_id_routes_to_external_endpoint(monkeypatch):
"provider_id": "conn-1",
"model": "kokoro",
"voice": "af_heart",
+ "instructions": "Speak warmly.",
},
)
assert resp.status_code == 200
@@ -379,6 +371,7 @@ def test_provider_id_routes_to_external_endpoint(monkeypatch):
assert created[0]["provider_type"] == "custom"
assert speech_calls[0]["model"] == "kokoro"
assert speech_calls[0]["voice"] == "af_heart"
+ assert speech_calls[0]["instructions"] == "Speak warmly."
rows = api_monitor.snapshot(include_details = False)
assert len(rows) == 1
assert rows[0]["endpoint"] == "/v1/audio/speech"
@@ -640,8 +633,9 @@ def test_provider_client_appends_speech_path_before_the_base_query(monkeypatch):
def raise_for_status(self):
return None
- async def _post(url, **_kwargs):
+ async def _post(url, **kwargs):
sent["url"] = url
+ sent["json"] = kwargs["json"]
return _Response()
monkeypatch.setattr(provider_module._http_client, "post", _post)
@@ -650,8 +644,9 @@ def test_provider_client_appends_speech_path_before_the_base_query(monkeypatch):
"http://127.0.0.1:8880/v1?api-version=2026-08-24",
"sk-test",
)
- asyncio.run(client.create_speech(text = "hi", model = "kokoro"))
+ asyncio.run(client.create_speech(text = "hi", model = "kokoro", instructions = "Speak warmly."))
assert sent["url"] == ("http://127.0.0.1:8880/v1/audio/speech?api-version=2026-08-24")
+ assert sent["json"]["instructions"] == "Speak warmly."
def test_external_provider_reads_do_not_block_the_event_loop(monkeypatch):
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 76f24d0f097..be3dfdf48db 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -2113,9 +2113,9 @@ def test_model_replacements_recheck_sidecar_swap_before_either_backend_is_unload
standard_wait = src.index("await _wait_for_model_switch_idle", standard_branch)
standard_sidecar_check = src.index("_raise_if_sidecar_swap_in_progress()", standard_wait)
standard_cancel = src.index("on_reload_confirmed(cancel = True)", standard_wait)
- # No parens: both teardowns are asyncio.to_thread args (on-loop a 160s one would
- # block /load's tunnel padding).
- unload_gguf = src.index("llama_backend.unload_model", standard_wait)
+ # The helper owns both the off-loop teardown and the driver-settle wait; ordering
+ # its call here still proves no destructive GGUF work precedes the final recheck.
+ unload_gguf = src.index("_unload_llama_before_standard_load", standard_wait)
assert already_loaded < gguf_wait < gguf_sidecar_check < gguf_cancel < unload_unsloth
assert standard_branch < standard_wait < standard_sidecar_check
diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.py
index 0a96dcc79d1..a964d2435aa 100644
--- a/studio/backend/tests/test_transformers_version.py
+++ b/studio/backend/tests/test_transformers_version.py
@@ -495,6 +495,26 @@ class TestCheckConfigNeeds550:
assert _check_config_needs_550(str(tmp_path)) is True
+ @pytest.mark.parametrize(
+ "cfg",
+ (
+ {"architectures": ["HiggsAudioV2ForConditionalGeneration"]},
+ {"model_type": "higgs_audio_v2"},
+ {"architectures": ["HiggsMultimodalQwen3ForConditionalGeneration"]},
+ {"model_type": "higgs_multimodal_qwen3"},
+ ),
+ ids = (
+ "higgs-tts2-architecture",
+ "higgs-tts2-model-type",
+ "higgs-tts3-architecture",
+ "higgs-tts3-model-type",
+ ),
+ )
+ def test_higgs_tts_uses_transformers_550(self, tmp_path: Path, cfg: dict):
+ (tmp_path / "config.json").write_text(json.dumps(cfg))
+
+ assert _check_config_needs_550(str(tmp_path)) is True
+
@pytest.mark.parametrize(
"cfg",
(
diff --git a/studio/backend/tests/test_tunnel_safe_long_post.py b/studio/backend/tests/test_tunnel_safe_long_post.py
index 089034ca19e..cea12c74084 100644
--- a/studio/backend/tests/test_tunnel_safe_long_post.py
+++ b/studio/backend/tests/test_tunnel_safe_long_post.py
@@ -393,6 +393,7 @@ def _stub_unsloth_load_over_a_resident_gguf(route, monkeypatch, *, teardown):
model_identifier = "org/OLD-GGUF",
layer_preserves_tensor_intent = False,
unload_model = teardown,
+ _wait_for_vram_settle = lambda **kwargs: None,
),
)
monkeypatch.setattr(
diff --git a/studio/backend/utils/audio_tokens.py b/studio/backend/utils/audio_tokens.py
index 174bdbd18f0..df907635b3d 100644
--- a/studio/backend/utils/audio_tokens.py
+++ b/studio/backend/utils/audio_tokens.py
@@ -13,10 +13,29 @@ import json
from pathlib import Path
from typing import Optional
-VALID_AUDIO_TYPES = ("snac", "csm", "bicodec", "dac", "whisper", "audio_vlm")
+NATIVE_OUTPUT_AUDIO_TYPES = frozenset(
+ {
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+ }
+)
+
+VALID_AUDIO_TYPES = (
+ "snac",
+ "csm",
+ "bicodec",
+ "dac",
+ *sorted(NATIVE_OUTPUT_AUDIO_TYPES),
+ "whisper",
+ "audio_vlm",
+)
# Emit speech; a chat turn sent to one comes back as audio, never as text.
TTS_AUDIO_TYPES = frozenset({"snac", "csm", "bicodec", "dac"})
+OUTPUT_AUDIO_TYPES = TTS_AUDIO_TYPES | NATIVE_OUTPUT_AUDIO_TYPES
def _count_prefix_exceeds(tokens, prefix: str, threshold: int) -> bool:
@@ -102,6 +121,11 @@ def is_tts_audio_type(audio_type: Optional[str]) -> bool:
return audio_type in TTS_AUDIO_TYPES
+def is_output_audio_type(audio_type: Optional[str]) -> bool:
+ """True for a model that emits audio instead of a text chat response."""
+ return audio_type in OUTPUT_AUDIO_TYPES
+
+
def detect_local_tts_audio_type(directory) -> Optional[str]:
"""The TTS codec a downloaded model directory fingerprints, or None. Local files
only. Whisper and audio_vlm answer None: both of those chat."""
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 9bcdee7f72a..d57ff38f750 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -4301,6 +4301,7 @@ def auto_select_gpu_ids(
target_modules: Optional[list] = None,
gradient_checkpointing: str = "unsloth",
optimizer: str = "adamw_8bit",
+ required_override_gb: Optional[float] = None,
) -> tuple[Optional[list[int]], Dict[str, Any]]:
metadata: Dict[str, Any] = {"selection_mode": "auto"}
@@ -4311,18 +4312,26 @@ def auto_select_gpu_ids(
metadata["selection_mode"] = "non_accelerator"
return None, metadata
- required_gb, estimate_metadata = estimate_required_model_memory_gb(
- model_name,
- hf_token = hf_token,
- training_type = training_type,
- load_in_4bit = load_in_4bit,
- batch_size = batch_size,
- max_seq_length = max_seq_length,
- lora_rank = lora_rank,
- target_modules = target_modules,
- gradient_checkpointing = gradient_checkpointing,
- optimizer = optimizer,
- )
+ if required_override_gb is None:
+ required_gb, estimate_metadata = estimate_required_model_memory_gb(
+ model_name,
+ hf_token = hf_token,
+ training_type = training_type,
+ load_in_4bit = load_in_4bit,
+ batch_size = batch_size,
+ max_seq_length = max_seq_length,
+ lora_rank = lora_rank,
+ target_modules = target_modules,
+ gradient_checkpointing = gradient_checkpointing,
+ optimizer = optimizer,
+ )
+ else:
+ required_gb = float(required_override_gb)
+ estimate_metadata = {
+ "mode": "inference" if training_type is None else "training",
+ "model_size_source": "override",
+ "required_gb": round(required_gb, 3),
+ }
metadata.update(estimate_metadata)
parent_visible_spec = _get_parent_visible_gpu_spec()
metadata["parent_cuda_visible_devices"] = parent_visible_spec["raw"]
@@ -4451,6 +4460,7 @@ def prepare_gpu_selection(
target_modules: Optional[list] = None,
gradient_checkpointing: str = "unsloth",
optimizer: str = "adamw_8bit",
+ required_override_gb: Optional[float] = None,
) -> tuple[Optional[list[int]], Dict[str, Any]]:
"""Resolve which physical GPUs to use for a model load.
@@ -4492,6 +4502,7 @@ def prepare_gpu_selection(
target_modules = target_modules,
gradient_checkpointing = gradient_checkpointing,
optimizer = optimizer,
+ required_override_gb = required_override_gb,
)
return selected_gpu_ids, metadata
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 1a5cbc432e3..c8b06de5fc8 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -1174,8 +1174,7 @@ def detect_audio_type(
"""Detect if a model is an audio model and return its type.
Works for any model via tokenizer_config.json special tokens.
- Returns an audio_type string ('snac', 'csm', 'bicodec', 'dac', 'whisper',
- 'audio_vlm') or None.
+ Returns an audio_type string from ``VALID_AUDIO_TYPES`` or None.
A None here is ambiguous: it covers both "not an audio model" and "the repo
could not be read". Callers that gate a user action on the answer want
@@ -1211,6 +1210,14 @@ def detect_audio_type_checked(
if not model_name:
return None, True
+ try:
+ from core.inference.native_audio import NATIVE_AUDIO_MODEL_IDS
+ curated_type = NATIVE_AUDIO_MODEL_IDS.get(str(model_name).strip().lower())
+ except Exception:
+ curated_type = None
+ if curated_type:
+ return curated_type, True
+
# Key on effective offline (kwarg OR env) so an offline negative can't poison a later probe.
effective_offline = bool(local_files_only or _env_offline())
# Checked on the RAW name, before the casing resolution below, because resolving a
@@ -1248,6 +1255,16 @@ def detect_audio_type_checked(
# Only definitive results are cached, so a hit is definitive by construction.
return _audio_detection_cache[cache_key], True
+ config_kwargs = {"local_files_only": effective_offline}
+ if revision is not None:
+ config_kwargs["revision"] = revision
+ result = _detect_audio_from_config(model_name, hf_token, **config_kwargs)
+ if result:
+ _audio_detection_cache[cache_key] = result
+ _audio_offline_miss_cache.pop(miss_key, None)
+ logger.info(f"Model {model_name} detected as audio model: audio_type={result}")
+ return result, True
+
tokenizer_kwargs = {"local_files_only": effective_offline}
if revision is not None:
tokenizer_kwargs["revision"] = revision
@@ -1271,6 +1288,32 @@ def detect_audio_type_checked(
return result, definitive
+def _detect_audio_from_config(
+ model_name: str,
+ hf_token: Optional[str] = None,
+ local_files_only: bool = False,
+ revision: Optional[str] = None,
+) -> Optional[str]:
+ """Detect native audio architectures whose tokenizer has no codec markers.
+
+ Curated remote IDs are handled before this helper. Here only bounded local
+ metadata is read, so capability detection never adds a Hub request or fetches
+ weights. A failed read deliberately falls through to the established tokenizer
+ detector so its definitive/transient semantics stay unchanged.
+ """
+ try:
+ del hf_token, local_files_only, revision
+ if not is_local_path(model_name):
+ return None
+ local_path = Path(normalize_path(model_name)).expanduser()
+ from core.inference.native_audio import native_audio_type_from_local_path
+
+ return native_audio_type_from_local_path(str(local_path))
+ except Exception as exc:
+ logger.debug("Could not read audio model_type for '%s': %s", model_name, exc)
+ return None
+
+
def _detect_audio_from_tokenizer(
model_name: str,
hf_token: Optional[str] = None,
@@ -3600,7 +3643,7 @@ class ModelConfig:
is_lora: bool # LoRA adapter?
is_gguf: bool = False # GGUF model?
is_audio: bool = False # TTS audio model?
- audio_type: Optional[str] = None # Audio codec type: 'snac', 'csm', 'bicodec', 'dac'
+ audio_type: Optional[str] = None # Codec or native audio generation architecture.
has_audio_input: bool = False # Accepts audio input (ASR/speech understanding)
gguf_file: Optional[str] = None # Full path to the .gguf file (local mode)
# ``(repo, variant, path, sizes)`` for a GGUF verified during config resolution;
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 9b8e12d40cf..4b3358b6fa0 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -291,6 +291,9 @@ TRANSFORMERS_550_MODEL_SUBSTRINGS: tuple[str, ...] = (
"locateanything",
"diffusion-gemma",
"diffusiongemma",
+ "higgs-tts-2",
+ "higgs-audio-v2",
+ "higgs-audio-v3-tts",
)
# Architecture classes / model_type values requiring transformers 5.10.x (via config.json).
@@ -311,12 +314,16 @@ _TRANSFORMERS_550_ARCHITECTURES: set[str] = {
"Gemma4ForConditionalGeneration",
"KimiK3ForConditionalGeneration",
"LocateAnythingForConditionalGeneration",
+ "HiggsAudioV2ForConditionalGeneration",
+ "HiggsMultimodalQwen3ForConditionalGeneration",
}
_TRANSFORMERS_550_MODEL_TYPES: set[str] = {
"diffusion_gemma",
"gemma4",
"kimi_k3",
"locateanything",
+ "higgs_audio_v2",
+ "higgs_multimodal_qwen3",
}
# Architecture classes / model_type values requiring transformers 5.3.0 (via config.json).
diff --git a/studio/frontend/src/app/routes/audio.tsx b/studio/frontend/src/app/routes/audio.tsx
index 4569ef222db..9a358be88fc 100644
--- a/studio/frontend/src/app/routes/audio.tsx
+++ b/studio/frontend/src/app/routes/audio.tsx
@@ -5,6 +5,14 @@ import { createRoute } from "@tanstack/react-router";
import { requireAuth } from "../auth-guards";
import { Route as rootRoute } from "./__root";
+const NATIVE_AUDIO_TYPES = new Set([
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+]);
+
// RootLayout renders AudioPage persistently (so an in-flight generation is not cancelled when leaving the tab); this route only owns the URL + auth gate.
export const Route = createRoute({
getParentRoute: () => rootRoute,
@@ -13,7 +21,14 @@ export const Route = createRoute({
// An audio pick made from the chat picker arrives here as ?model= (+ ?quant=, ?ggufQuant=, and task), which the page loads and then clears.
validateSearch: (
search: Record<string, unknown>,
- ): { model?: string; quant?: string; ggufQuant?: string; task?: string } => ({
+ ): {
+ model?: string;
+ quant?: string;
+ ggufQuant?: string;
+ task?: string;
+ audioType?: string;
+ loadId?: string;
+ } => ({
...(typeof search.model === "string" ? { model: search.model } : {}),
...(typeof search.quant === "string" ? { quant: search.quant } : {}),
...(typeof search.ggufQuant === "string"
@@ -23,6 +38,13 @@ export const Route = createRoute({
search.task === "text-to-speech"
? { task: search.task }
: {}),
+ ...(typeof search.audioType === "string" &&
+ NATIVE_AUDIO_TYPES.has(search.audioType)
+ ? { audioType: search.audioType }
+ : {}),
+ ...(typeof search.loadId === "string" && search.loadId.trim()
+ ? { loadId: search.loadId }
+ : {}),
}),
beforeLoad: () => requireAuth(),
component: () => null,
diff --git a/studio/frontend/src/features/audio/api.ts b/studio/frontend/src/features/audio/api.ts
index b09bf3f92b7..0920fa45294 100644
--- a/studio/frontend/src/features/audio/api.ts
+++ b/studio/frontend/src/features/audio/api.ts
@@ -27,9 +27,37 @@ export interface GenerateAudioOptions {
temperature?: number;
top_p?: number;
max_tokens?: number;
+ audio_instructions?: string;
+ audio_language?: string;
+ seed?: number;
signal?: AbortSignal;
}
+export interface AudioDownloadPlan {
+ entries: {
+ repo_id: string;
+ files: string[];
+ bytes: number;
+ gguf_filename: string | null;
+ checkpoint?: boolean;
+ }[];
+ total_bytes: number;
+ required_bytes?: number;
+ checkpoint_bytes?: number;
+}
+
+export async function getAudioDownloadPlan(
+ modelPath: string,
+ hfToken?: string,
+): Promise<AudioDownloadPlan> {
+ const response = await authFetch("/api/inference/audio/download-plan", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model_path: modelPath, hf_token: hfToken }),
+ });
+ return parseJson<AudioDownloadPlan>(response);
+}
+
export async function generateAudio(
text: string,
options: GenerateAudioOptions = {},
diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.ts
index 481164592d1..56984a3512c 100644
--- a/studio/frontend/src/features/audio/audio-page-policy.ts
+++ b/studio/frontend/src/features/audio/audio-page-policy.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { ModelSelectorChangeMeta } from "@/features/model-picker/components/model-selector/types";
+import { nativeAudioCheckpointIsLoadable } from "../model-picker/components/model-selector/audio-picker-policy.ts";
export type AudioBusy =
| "loading"
@@ -14,8 +15,88 @@ export type AudioPickTask = "tts" | "stt" | null;
export type AudioCreateMode = "speak" | "transcribe";
export type SttEngine = "transformers" | "gguf" | "mtmd";
-const TTS_AUDIO_TYPES = new Set(["snac", "csm", "bicodec", "dac"]);
+const TTS_AUDIO_TYPES = new Set([
+ "snac",
+ "csm",
+ "bicodec",
+ "dac",
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+]);
const GGUF_TTS_AUDIO_TYPES = new Set(["snac", "bicodec", "dac"]);
+const NATIVE_TTS_AUDIO_TYPES = new Set([
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+]);
+export const MOSS_TTS_FRAMES_PER_SECOND = 12.5;
+export const MOSS_TTS_DEFAULT_SECONDS = 15;
+export const MOSS_TTS_MAX_FRAMES = 32768;
+export const MOSS_TTS_MAX_SECONDS =
+ MOSS_TTS_MAX_FRAMES / MOSS_TTS_FRAMES_PER_SECOND;
+export const MINIMAX_MUSIC_FRAMES_PER_SECOND = 25;
+export const MINIMAX_MUSIC_DEFAULT_SECONDS = 30;
+export const MINIMAX_MUSIC_MAX_FRAMES = 9000;
+export const MINIMAX_MUSIC_MAX_SECONDS =
+ MINIMAX_MUSIC_MAX_FRAMES / MINIMAX_MUSIC_FRAMES_PER_SECOND;
+
+export type NativeAudioInstructionsKind = "scene" | "style" | "music";
+
+export function nativeAudioInstructionsKind(
+ audioType?: string | null,
+): NativeAudioInstructionsKind | null {
+ if (audioType === "higgs_tts2") {
+ return "scene";
+ }
+ if (audioType === "moss_tts_local") {
+ return "style";
+ }
+ if (audioType === "minimax_music3") {
+ return "music";
+ }
+ return null;
+}
+
+export function minimaxMusicFramesForSeconds(seconds: number): number {
+ const exactFrames = seconds * MINIMAX_MUSIC_FRAMES_PER_SECOND;
+ return Math.min(
+ MINIMAX_MUSIC_MAX_FRAMES,
+ Math.max(
+ 1,
+ Math.floor(
+ exactFrames + Number.EPSILON * Math.max(1, Math.abs(exactFrames)),
+ ),
+ ),
+ );
+}
+
+export function mossTtsFramesForSeconds(
+ seconds: number,
+ maxFrames = MOSS_TTS_MAX_FRAMES,
+): number {
+ return Math.min(
+ Math.max(1, Math.floor(maxFrames)),
+ Math.max(1, Math.floor(seconds * MOSS_TTS_FRAMES_PER_SECOND)),
+ );
+}
+
+export function mossTtsMaxFrames(
+ audioType?: string | null,
+ contextLength?: number | null,
+): number | null {
+ if (audioType !== "moss_tts_local" && audioType !== "moss_tts_nano") {
+ return null;
+ }
+ const detected = Math.floor(Number(contextLength));
+ return Number.isFinite(detected) && detected > 0
+ ? detected
+ : MOSS_TTS_MAX_FRAMES;
+}
export function isTtsAudioType(
audioType?: string | null,
@@ -29,6 +110,26 @@ export function isTtsAudioType(
);
}
+export function trainedTtsCheckpointIsLoadable(
+ audioType?: string | null,
+ exportType?: string | null,
+): boolean {
+ return nativeAudioCheckpointIsLoadable(audioType, exportType);
+}
+
+export function trainedTtsCheckpointIsRunnableOnMac(
+ audioType?: string | null,
+ exportType?: string | null,
+): boolean {
+ if (exportType === "gguf") return true;
+ return Boolean(
+ exportType === "merged" &&
+ audioType &&
+ NATIVE_TTS_AUDIO_TYPES.has(audioType) &&
+ audioType !== "minimax_music3",
+ );
+}
+
type SttDownloadedStatus = {
downloaded_models?: readonly string[];
transformers?: { downloaded_models?: readonly string[] };
@@ -113,18 +214,20 @@ export function exactGgufLoadSelector(
export type MacTtsPickAction = "allow" | "use-gguf-sibling" | "reject";
-/** MLX has no TTS decoder. A Mac TTS pick is runnable only when it already is
- * GGUF or its curated family publishes a GGUF sibling. */
+/** MLX has no codec TTS decoder. Curated native PyTorch audio models bypass MLX;
+ * other Mac picks still need GGUF or a family GGUF sibling. */
export function macTtsPickAction({
isMac,
isGguf,
ggufSibling,
+ nativeRuntime = false,
}: {
isMac: boolean;
isGguf: boolean;
ggufSibling: string | null;
+ nativeRuntime?: boolean;
}): MacTtsPickAction {
- if (!isMac || isGguf) return "allow";
+ if (!isMac || isGguf || nativeRuntime) return "allow";
return ggufSibling ? "use-gguf-sibling" : "reject";
}
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 5f0c36360fb..510a7476d52 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -29,6 +29,7 @@ import {
import { AdvancedDisclosure } from "@/components/advanced-disclosure";
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
import {
DropdownMenu,
DropdownMenuContent,
@@ -76,6 +77,7 @@ import type {
ModelOption,
ModelSelectorChangeMeta,
} from "@/features/model-picker/components/model-selector/types";
+import { confirmRemoteCodeIfNeeded } from "@/features/security";
import {
isTrackingSttDownload,
trackSttDownload,
@@ -83,6 +85,7 @@ import {
import { sttModelSize } from "@/features/settings/stores/stt-model-catalog";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { useScrollFades } from "@/hooks/use-scroll-fades";
+import { fetchSystemInfo } from "@/hooks/use-system";
import { BlobUrlCache } from "@/lib/blob-url-cache";
import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
import { toast } from "@/lib/toast";
@@ -94,6 +97,7 @@ import {
clearAudioGallery,
deleteAudioClip,
fetchClipObjectUrl,
+ getAudioDownloadPlan,
generateAudio,
listAudioGallery,
} from "./api";
@@ -107,24 +111,39 @@ import {
macTtsPickAction,
mergeGalleryPage,
micStreamRequestIsCurrent,
+ MOSS_TTS_DEFAULT_SECONDS,
+ MOSS_TTS_FRAMES_PER_SECOND,
+ MOSS_TTS_MAX_FRAMES,
+ MINIMAX_MUSIC_DEFAULT_SECONDS,
+ MINIMAX_MUSIC_FRAMES_PER_SECOND,
+ MINIMAX_MUSIC_MAX_SECONDS,
+ minimaxMusicFramesForSeconds,
+ mossTtsMaxFrames,
+ mossTtsFramesForSeconds,
+ nativeAudioInstructionsKind,
persistedClipForGeneration,
reconcileSttSelection,
resolveAudioPickTask,
resolveSttResidency,
selectAutoGgufVariant,
stagedTtsLoadIsOwned,
+ trainedTtsCheckpointIsLoadable,
+ trainedTtsCheckpointIsRunnableOnMac,
sttDownloadedArtifacts,
sttSelectionReady,
} from "./audio-page-policy";
import {
audioCapabilityLine,
+ audioModelRequiresRemoteCode,
audioModelsForTask,
audioTaskFor,
ggufSiblingFor,
+ isMusicGenerationModel,
macTtsCatalogChoiceIsRunnable,
sttEngineForRepoId,
sttRepoIdForSidecarKey,
sttSidecarKeyFor,
+ usesNativeAudioRuntime,
} from "./catalog";
const MODELS_BY_MODE: Record<CreateMode, ModelOption[]> = {
@@ -185,19 +204,30 @@ const galleryCache: {
};
type CreateMode = "speak" | "transcribe";
+type RemoteCodeApproval = {
+ trustRemoteCode: true;
+ approvedRemoteCodeFingerprint: string | null;
+};
function Field({
label,
hint,
+ htmlFor,
children,
}: {
label: string;
hint?: string;
+ htmlFor: string;
children: ReactNode;
}) {
return (
<div className="grid gap-1.5">
- <span className="text-ui-13 font-medium text-foreground">{label}</span>
+ <label
+ className="text-ui-13 font-medium text-foreground"
+ htmlFor={htmlFor}
+ >
+ {label}
+ </label>
{children}
{hint ? (
<p className="text-ui-11p5 leading-snug text-muted-foreground">
@@ -289,6 +319,8 @@ export function AudioPage({
// --- TTS (main inference slot) -----------------------------------------
const [status, setStatus] = useState<InferenceStatusResponse | null>(null);
const [prompt, setPrompt] = useState("");
+ const [audioInstructions, setAudioInstructions] = useState("");
+ const [audioLanguage, setAudioLanguage] = useState("");
const [temperature, setTemperature] = useState(0.6);
// Sending temperature unconditionally puts it in the request's model_fields_set, which the
// backend reads as an explicit client override and which then beats the per-model
@@ -300,6 +332,12 @@ export function AudioPage({
setTemperature(value);
}, []);
const [maxTokens, setMaxTokens] = useState(2048);
+ const [mossMaxSeconds, setMossMaxSeconds] = useState(
+ MOSS_TTS_DEFAULT_SECONDS,
+ );
+ const [minimaxMaxSeconds, setMinimaxMaxSeconds] = useState(
+ MINIMAX_MUSIC_DEFAULT_SECONDS,
+ );
const generateAbort = useRef<AbortController | null>(null);
const ttsLoadInFlight = useRef(false);
// A pick that lost the race with a load still settling. Replayed once it does.
@@ -307,6 +345,8 @@ export function AudioPage({
repoId: string;
ggufFilename?: string | null;
loadId?: string | null;
+ audioType?: string | null;
+ remoteCodeApproval?: RemoteCodeApproval;
} | null>(null);
const ttsStatusRefreshGeneration = useRef(0);
const ttsLoadGeneration = useRef(0);
@@ -387,7 +427,10 @@ export function AudioPage({
const stagedTtsGeneration = useRef(0);
const pendingStagedTtsLoad = useRef<{
repoId: string;
- ggufFilename: string;
+ ggufFilename: string | null;
+ loadId?: string | null;
+ audioType?: string | null;
+ remoteCodeApproval?: RemoteCodeApproval;
generation: number;
} | null>(null);
const stagedTtsLoadDeferred = useRef(false);
@@ -425,6 +468,23 @@ export function AudioPage({
const [srcById, setSrcById] = useState<Record<string, string>>(
galleryCache.srcById.toRecord(),
);
+ const clipSrcLoads = useRef<Map<string, Promise<void>>>(new Map());
+ const mossFrameLimit = mossTtsMaxFrames(
+ status?.audio_type,
+ status?.context_length,
+ );
+ const mossMaxSecondsLimit =
+ (mossFrameLimit ?? MOSS_TTS_MAX_FRAMES) / MOSS_TTS_FRAMES_PER_SECOND;
+
+ useEffect(() => {
+ setTemperature(mossFrameLimit !== null ? 1.7 : 0.6);
+ setTemperatureEdited(false);
+ if (mossFrameLimit !== null) {
+ setMossMaxSeconds((current) =>
+ Math.min(current, mossFrameLimit / MOSS_TTS_FRAMES_PER_SECOND),
+ );
+ }
+ }, [mossFrameLimit]);
const {
attach: attachSettingsScroll,
@@ -538,7 +598,10 @@ export function AudioPage({
const selected = selectedSttRepoRef.current;
const claim = sttLoadedByThisPage.current;
const owned =
- sttReady && selected !== null && claim !== null && claim === sttLoadedModel;
+ sttReady &&
+ selected !== null &&
+ claim !== null &&
+ claim === sttLoadedModel;
const forget = () => {
deferredSttLoad.current = null;
selectedSttRepoRef.current = null;
@@ -567,15 +630,34 @@ export function AudioPage({
galleryCache.srcById.touch(clip.id);
return;
}
+ const pending = clipSrcLoads.current.get(clip.id);
+ if (pending) return pending;
+ const load = (async () => {
+ try {
+ const fetched = await fetchClipObjectUrl(clip.url);
+ // A delete can finish while protected bytes are in flight. Do not revive its
+ // cache entry after the row is already gone.
+ if (!galleryCache.clips.some((candidate) => candidate.id === clip.id)) {
+ URL.revokeObjectURL(fetched.url);
+ return;
+ }
+ galleryCache.srcById.set(clip.id, fetched.url, fetched.bytes);
+ galleryCache.srcById.prune(
+ galleryCache.selectedId ? [galleryCache.selectedId] : [],
+ );
+ setSrcById(galleryCache.srcById.toRecord());
+ } catch {
+ // Clip may have been deleted server-side; the next gallery refresh drops it.
+ toast.error("Could not load this audio clip. Try selecting it again.");
+ }
+ })();
+ clipSrcLoads.current.set(clip.id, load);
try {
- const fetched = await fetchClipObjectUrl(clip.url);
- galleryCache.srcById.set(clip.id, fetched.url, fetched.bytes);
- galleryCache.srcById.prune(
- galleryCache.selectedId ? [galleryCache.selectedId] : [],
- );
- setSrcById(galleryCache.srcById.toRecord());
- } catch {
- // Clip may have been deleted server-side; the next gallery refresh drops it.
+ await load;
+ } finally {
+ if (clipSrcLoads.current.get(clip.id) === load) {
+ clipSrcLoads.current.delete(clip.id);
+ }
}
}, []);
@@ -628,13 +710,17 @@ export function AudioPage({
galleryCache.selectedId = merged[0].id;
setSelectedId(galleryCache.selectedId);
}
+ const selected = merged.find(
+ (clip) => clip.id === galleryCache.selectedId,
+ );
+ if (selected) void ensureClipSrc(selected);
return merged;
} catch {
// Same recoverable-poll stance as status.
return galleryCache.clips;
}
},
- [],
+ [ensureClipSrc],
);
const loadMore = useCallback(async () => {
@@ -726,11 +812,16 @@ export function AudioPage({
/** `keepFallback` is for the one case where the id is not in `clips` yet: the server
* persisted the clip but this refresh missed it, so the response audio has to stay
* mounted or the player falls through to the empty state. */
- const selectClip = useCallback((id: string, keepFallback = false) => {
- galleryCache.selectedId = id;
- setSelectedId(id);
- if (!keepFallback) setFallbackClip(null);
- }, []);
+ const selectClip = useCallback(
+ (id: string, keepFallback = false) => {
+ galleryCache.selectedId = id;
+ setSelectedId(id);
+ if (!keepFallback) setFallbackClip(null);
+ const clip = galleryCache.clips.find((candidate) => candidate.id === id);
+ if (clip) void ensureClipSrc(clip);
+ },
+ [ensureClipSrc],
+ );
// --- Model selection ----------------------------------------------------
@@ -743,12 +834,20 @@ export function AudioPage({
// display repo id instead failed offline, or re-downloaded into the active cache.
// Chat threads the same field (chat-page.tsx).
loadId?: string | null,
+ audioType?: string | null,
+ remoteCodeApproval?: RemoteCodeApproval,
) => {
// A routed pick that arrives while a previous load is still tearing down would
// otherwise be dropped here, and the route effect has already cleared ?model=, so
// nothing retries it. Remembered and replayed from the finally below instead.
- if (ttsLoadInFlight.current) {
- pendingRoutedTtsPick.current = { repoId, ggufFilename, loadId };
+ if (ttsLoadInFlight.current || busyRef.current === "generating") {
+ pendingRoutedTtsPick.current = {
+ repoId,
+ ggufFilename,
+ loadId,
+ audioType,
+ remoteCodeApproval,
+ };
return;
}
// A load stops every chat on the shared llama-server, so ask the way Chat does
@@ -781,7 +880,13 @@ export function AudioPage({
if (!activeRef.current) {
releaseLifecycle();
ttsLoadInFlight.current = false;
- pendingRoutedTtsPick.current = { repoId, ggufFilename, loadId };
+ pendingRoutedTtsPick.current = {
+ repoId,
+ ggufFilename,
+ loadId,
+ audioType,
+ remoteCodeApproval,
+ };
return;
}
const generation = ++ttsLoadGeneration.current;
@@ -807,16 +912,41 @@ export function AudioPage({
setBusy("loading");
const toastId = toast.loading(`Loading ${audioModelLabel(repoId)}…`);
try {
+ const hfToken = hfApiToken(getHfToken()) ?? null;
+ let trustRemoteCode = remoteCodeApproval?.trustRemoteCode ?? false;
+ let approvedRemoteCodeFingerprint =
+ remoteCodeApproval?.approvedRemoteCodeFingerprint ?? null;
+ if (
+ audioModelRequiresRemoteCode(repoId, audioType) &&
+ !remoteCodeApproval
+ ) {
+ const approved = await confirmRemoteCodeIfNeeded({
+ modelName: loadId || repoId,
+ hfToken,
+ requiresTrustRemoteCode: true,
+ onApprove: (fingerprint) => {
+ trustRemoteCode = true;
+ approvedRemoteCodeFingerprint = fingerprint;
+ },
+ });
+ if (!approved)
+ throw new Error(
+ "Custom code approval is required to load this model.",
+ );
+ if (controller.signal.aborted || !isCurrent()) return;
+ }
const res = await loadModel(
{
model_path: loadId || repoId,
load_request_id: loadRequestId,
force_cancel_active: stopDecision.forceCancelActive,
- hf_token: hfApiToken(getHfToken()) ?? null,
+ hf_token: hfToken,
max_seq_length: TTS_MAX_TOKENS + TTS_PROMPT_CONTEXT_RESERVE,
load_in_4bit: false,
is_lora: false,
gguf_variant: ggufFilename ?? null,
+ trust_remote_code: trustRemoteCode,
+ approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,
},
{
signal: controller.signal,
@@ -855,12 +985,12 @@ export function AudioPage({
} finally {
if (pendingTtsLoad.current?.generation === generation)
pendingTtsLoad.current = null;
+ if (activeRef.current) await refreshStatus();
ttsLoadInFlight.current = false;
// Before the replay below, which needs the gate for its own attempt.
releaseLifecycle();
busyRef.current = null;
setBusy(null);
- if (activeRef.current) void refreshStatus();
// Only while Audio is visible. Replaying unconditionally started a load with
// activeRef already false, and since the deactivation effect had run it never saw
// that attempt to cancel it, so a hidden page could replace the model Chat had
@@ -881,17 +1011,28 @@ export function AudioPage({
const queued = pendingRoutedTtsPick.current;
if (!queued) return;
pendingRoutedTtsPick.current = null;
- void loadTtsModelRef.current(queued.repoId, queued.ggufFilename, queued.loadId);
+ void loadTtsModelRef.current(
+ queued.repoId,
+ queued.ggufFilename,
+ queued.loadId,
+ queued.audioType,
+ queued.remoteCodeApproval,
+ );
}, []);
const invalidatePendingStagedTts = useCallback(() => {
stagedTtsGeneration.current += 1;
pendingStagedTtsLoad.current = null;
stagedTtsLoadDeferred.current = false;
}, []);
+ const invalidatePendingTtsSelection = useCallback(() => {
+ ttsPickGeneration.current += 1;
+ pendingRoutedTtsPick.current = null;
+ invalidatePendingStagedTts();
+ }, [invalidatePendingStagedTts]);
const transitionMode = useCallback(
(nextMode: CreateMode) => {
if (nextMode === mode) {
- if (nextMode === "transcribe") invalidatePendingStagedTts();
+ if (nextMode === "transcribe") invalidatePendingTtsSelection();
return true;
}
if (!canTransitionAudioMode(busyRef.current)) {
@@ -901,7 +1042,7 @@ export function AudioPage({
return false;
}
- if (nextMode === "transcribe") invalidatePendingStagedTts();
+ if (nextMode === "transcribe") invalidatePendingTtsSelection();
if (busyRef.current === "generating") generateAbort.current?.abort();
stopAndDiscardRecording();
setMode(nextMode);
@@ -936,7 +1077,7 @@ export function AudioPage({
return true;
},
[
- invalidatePendingStagedTts,
+ invalidatePendingTtsSelection,
mode,
releaseTranscribeSelection,
stopAndDiscardRecording,
@@ -965,7 +1106,13 @@ export function AudioPage({
return;
}
pendingStagedTtsLoad.current = null;
- void loadTtsModelRef.current(pending.repoId, pending.ggufFilename);
+ void loadTtsModelRef.current(
+ pending.repoId,
+ pending.ggufFilename,
+ pending.loadId,
+ pending.audioType,
+ pending.remoteCodeApproval,
+ );
},
});
@@ -985,23 +1132,128 @@ export function AudioPage({
return;
}
pendingStagedTtsLoad.current = null;
- void loadTtsModelRef.current(pending.repoId, pending.ggufFilename);
+ void loadTtsModelRef.current(
+ pending.repoId,
+ pending.ggufFilename,
+ pending.loadId,
+ pending.audioType,
+ pending.remoteCodeApproval,
+ );
}, [active, busy]);
const loadOrStageTtsModel = useCallback(
- (
+ async (
repoId: string,
ggufFilename: string | null,
meta: ModelSelectorChangeMeta,
) => {
+ const generation = ++stagedTtsGeneration.current;
+ pendingStagedTtsLoad.current = null;
+ stagedTtsLoadDeferred.current = false;
+ stageTtsDownload([]);
+
+ let remoteCodeApproval: RemoteCodeApproval | undefined;
+ const hfToken = hfApiToken(getHfToken()) ?? null;
+ if (
+ meta.source === "hub" &&
+ !ggufFilename &&
+ audioModelRequiresRemoteCode(repoId, meta.audioType)
+ ) {
+ try {
+ const approved = await confirmRemoteCodeIfNeeded({
+ modelName: meta.loadId || repoId,
+ hfToken,
+ requiresTrustRemoteCode: true,
+ onApprove: (fingerprint) => {
+ remoteCodeApproval = {
+ trustRemoteCode: true,
+ approvedRemoteCodeFingerprint: fingerprint,
+ };
+ },
+ });
+ if (generation !== stagedTtsGeneration.current) return;
+ if (!approved) {
+ toast.error("Custom code approval is required to load this model.");
+ return;
+ }
+ } catch (error) {
+ if (generation !== stagedTtsGeneration.current) return;
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : `Could not verify the code for ${repoId}.`,
+ );
+ return;
+ }
+ }
+
+ // Hub TTS picks use the same managed path as Chat. Native models can also
+ // depend on a second codec repository, so the selected repo's downloaded
+ // badge is not enough: the cache-aware backend plan owns every missing
+ // checkpoint, config and companion file before model loading begins.
+ if (meta.source === "hub" && !ggufFilename) {
+ let plan;
+ try {
+ plan = await getAudioDownloadPlan(
+ meta.loadId || repoId,
+ hfToken ?? undefined,
+ );
+ } catch (error) {
+ if (generation !== stagedTtsGeneration.current) return;
+ if (meta.isDownloaded === true) {
+ void loadTtsModelRef.current(
+ repoId,
+ ggufFilename,
+ meta.loadId,
+ meta.audioType,
+ remoteCodeApproval,
+ );
+ return;
+ }
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : `Could not prepare the download for ${repoId}.`,
+ );
+ return;
+ }
+ if (generation !== stagedTtsGeneration.current) return;
+ const plannedEntries = plan.entries;
+ if (plannedEntries.length > 0) {
+ pendingStagedTtsLoad.current = {
+ repoId,
+ ggufFilename,
+ loadId: meta.loadId,
+ audioType: meta.audioType,
+ remoteCodeApproval,
+ generation,
+ };
+ stageTtsDownload(
+ plannedEntries.map((entry) => ({
+ repoId: entry.repo_id,
+ files: entry.files,
+ bytes: entry.bytes,
+ ggufFilename: entry.gguf_filename,
+ checkpoint: entry.checkpoint,
+ })),
+ );
+ return;
+ }
+ }
+
if (
meta.source === "hub" &&
meta.isDownloaded === false &&
ggufFilename
) {
- const generation = ++stagedTtsGeneration.current;
- pendingStagedTtsLoad.current = { repoId, ggufFilename, generation };
- stagedTtsLoadDeferred.current = false;
+ pendingStagedTtsLoad.current = {
+ repoId,
+ ggufFilename,
+ loadId: meta.loadId,
+ audioType: meta.audioType,
+ remoteCodeApproval,
+ generation,
+ };
stageTtsDownload([
{
repoId,
@@ -1015,11 +1267,15 @@ export function AudioPage({
// A cached/local/direct pick supersedes any staged auto-load. The manager
// may keep downloading globally, but its old completion cannot load here.
- invalidatePendingStagedTts();
- stageTtsDownload([]);
- void loadTtsModelRef.current(repoId, ggufFilename, meta.loadId);
+ void loadTtsModelRef.current(
+ repoId,
+ ggufFilename,
+ meta.loadId,
+ meta.audioType,
+ remoteCodeApproval,
+ );
},
- [invalidatePendingStagedTts, stageTtsDownload],
+ [stageTtsDownload],
);
const ensureSttLoaded = useCallback(
@@ -1212,15 +1468,28 @@ export function AudioPage({
const handleModelSelect = useCallback(
async (id: string, meta: ModelSelectorChangeMeta) => {
if (busyRef.current !== null) return;
+ // Catalog first; an uncurated Hub pick falls back to its pipeline tag, or
+ // every community ASR repo would load into the TTS slot.
+ const task = resolveAudioPickTask(audioTaskFor(id), meta.pipelineTag);
+ const musicPick =
+ task !== "stt" && isMusicGenerationModel(id, meta.audioType);
+ const selectionGeneration = ++ttsPickGeneration.current;
+ if (musicPick) {
+ const system = await fetchSystemInfo();
+ if (selectionGeneration !== ttsPickGeneration.current) return;
+ if (system?.device_backend !== "cuda") {
+ toast.error(
+ `${id} requires a verified NVIDIA CUDA GPU for local generation.`,
+ { duration: 7000 },
+ );
+ return;
+ }
+ }
// Selecting a different artifact while recording is a lifecycle change
// even when it stays in Transcribe mode; never let the old capture submit
// against a sidecar that this pick is replacing.
stopAndDiscardRecording();
deferredSttLoad.current = null;
- const selectionGeneration = ++ttsPickGeneration.current;
- // Catalog first; an uncurated Hub pick falls back to its pipeline tag, or
- // every community ASR repo would load into the TTS slot.
- const task = resolveAudioPickTask(audioTaskFor(id), meta.pipelineTag);
if (task === "stt") {
// An STT pick owns Transcribe: it runs on the sidecar, not the main slot.
if (!transitionMode("transcribe")) return;
@@ -1252,10 +1521,19 @@ export function AudioPage({
id.toLowerCase().endsWith(".gguf"),
);
const ggufSibling = isGguf ? null : ggufSiblingFor(id);
- const macAction = macTtsPickAction({ isMac, isGguf, ggufSibling });
+ const nativeRuntime =
+ usesNativeAudioRuntime(id, meta.audioType) && !musicPick;
+ const macAction = macTtsPickAction({
+ isMac,
+ isGguf,
+ ggufSibling,
+ nativeRuntime,
+ });
if (macAction === "reject") {
toast.error(
- `${id} has no runnable GGUF TTS build. MLX cannot generate text-to-speech from its safetensors checkpoint on this Mac.`,
+ musicPick
+ ? `${id} currently requires an NVIDIA CUDA GPU and cannot run locally on this Mac.`
+ : `${id} has no runnable GGUF TTS build. MLX cannot generate text-to-speech from its safetensors checkpoint on this Mac.`,
{ duration: 7000 },
);
return;
@@ -1292,7 +1570,7 @@ export function AudioPage({
busyRef.current = null;
setBusy(null);
}
- loadOrStageTtsModel(ggufSibling, variant.filename, {
+ await loadOrStageTtsModel(ggufSibling, variant.filename, {
...meta,
source: "hub",
isGguf: true,
@@ -1317,7 +1595,7 @@ export function AudioPage({
}
return;
}
- loadOrStageTtsModel(id, exactGguf, meta);
+ await loadOrStageTtsModel(id, exactGguf, meta);
},
[
clearTranscript,
@@ -1336,6 +1614,8 @@ export function AudioPage({
quant?: string;
ggufQuant?: string;
task?: string;
+ audioType?: string;
+ loadId?: string;
};
const handledRouteModel = useRef<string | null>(null);
useEffect(() => {
@@ -1354,7 +1634,7 @@ export function AudioPage({
void navigateSelf({ to: "/audio", search: {}, replace: true });
return;
}
- const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}|${routeSearch.task ?? ""}`;
+ const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}|${routeSearch.task ?? ""}|${routeSearch.audioType ?? ""}|${routeSearch.loadId ?? ""}`;
if (handledRouteModel.current === key) return;
// The persistent Audio page may still be finishing hidden work. Keep the
// handoff in the URL and retry it when that work releases the lifecycle.
@@ -1365,9 +1645,15 @@ export function AudioPage({
isLora: false,
ggufFilename: routeSearch.quant ?? undefined,
ggufVariant: routeSearch.ggufQuant ?? undefined,
+ loadId: routeSearch.loadId ?? undefined,
+ audioType: routeSearch.audioType ?? undefined,
// Chat-to-Audio routing cannot preserve the inventory flag, so stage the
// exact forwarded GGUF. An already-cached job completes immediately.
- isDownloaded: routeSearch.quant ? false : undefined,
+ isDownloaded: routeSearch.loadId
+ ? true
+ : routeSearch.quant
+ ? false
+ : undefined,
pipelineTag: routeSearch.task ?? null,
});
void navigateSelf({ to: "/audio", search: {}, replace: true });
@@ -1379,6 +1665,8 @@ export function AudioPage({
routeSearch.quant,
routeSearch.ggufQuant,
routeSearch.task,
+ routeSearch.audioType,
+ routeSearch.loadId,
handleModelSelect,
navigateSelf,
transitionMode,
@@ -1390,6 +1678,13 @@ export function AudioPage({
status?.active_model &&
isTtsAudioType(status.audio_type, status.is_gguf === true),
);
+ const musicGeneration =
+ status?.audio_type === "minimax_music3" ||
+ isMusicGenerationModel(status?.active_model);
+ const mossLocalGeneration = status?.audio_type === "moss_tts_local";
+ const instructionsKind = musicGeneration
+ ? "music"
+ : nativeAudioInstructionsKind(status?.audio_type);
const handleEject = useCallback(() => {
if (busy !== null || isRecording) {
toast.info("Stop the active audio task before ejecting its model.");
@@ -1523,12 +1818,30 @@ export function AudioPage({
setMode("transcribe");
return;
}
+ const instructions = audioInstructions.trim();
+ if (musicGeneration && !instructions) {
+ busyRef.current = null;
+ setBusy(null);
+ toast.error("Add a music description for MiniMax Music 3.");
+ return;
+ }
+ const language = audioLanguage.trim();
const controller = new AbortController();
generateAbort.current = controller;
try {
const generated = await generateAudio(text, {
- ...(temperatureEdited ? { temperature } : {}),
- max_tokens: maxTokens,
+ ...(!musicGeneration && temperatureEdited ? { temperature } : {}),
+ max_tokens: musicGeneration
+ ? minimaxMusicFramesForSeconds(minimaxMaxSeconds)
+ : mossFrameLimit !== null
+ ? mossTtsFramesForSeconds(mossMaxSeconds, mossFrameLimit)
+ : maxTokens,
+ ...(instructionsKind !== null && instructions
+ ? { audio_instructions: instructions }
+ : {}),
+ ...(mossLocalGeneration && language
+ ? { audio_language: language }
+ : {}),
signal: controller.signal,
});
const refreshed = await refreshGallery();
@@ -1574,15 +1887,27 @@ export function AudioPage({
}
} finally {
generateAbort.current = null;
+ busyRef.current = null;
setBusy(null);
+ if (activeRef.current && modeRef.current === "speak")
+ replayQueuedTtsPick();
}
}, [
prompt,
+ audioInstructions,
+ audioLanguage,
+ musicGeneration,
+ mossLocalGeneration,
+ mossFrameLimit,
+ mossMaxSeconds,
+ minimaxMaxSeconds,
+ instructionsKind,
temperature,
temperatureEdited,
maxTokens,
refreshGallery,
refreshStatus,
+ replayQueuedTtsPick,
selectClip,
]);
@@ -1810,7 +2135,9 @@ export function AudioPage({
// Drop the row now, as the clear-all path does: refreshGallery swallows a failed
// GET and returns the cache without calling setClips, which left the deleted clip
// on screen against an object URL that has already been revoked.
- galleryCache.clips = galleryCache.clips.filter((clip) => clip.id !== id);
+ galleryCache.clips = galleryCache.clips.filter(
+ (clip) => clip.id !== id,
+ );
setClips(galleryCache.clips);
if (galleryCache.selectedId === id) {
galleryCache.selectedId = null;
@@ -1916,17 +2243,25 @@ export function AudioPage({
if (cancelled) return;
setTrainedTtsModels(
res.loras
- // MLX has no TTS decoder, so a trained LoRA or merged safetensors checkpoint
- // deterministically fails with "not supported on the MLX backend yet" on Mac.
- // The catalog rows are already filtered to families with a GGUF sibling; these
- // have none, so offering them only produces that error.
- .filter((lora) => !isMac || lora.export_type === "gguf")
+ // Merged native speech checkpoints bypass MLX through the portable
+ // audio worker. Other safetensors exports still need a GGUF build on Mac.
+ .filter(
+ (lora) =>
+ !isMac ||
+ trainedTtsCheckpointIsRunnableOnMac(
+ lora.audio_type,
+ lora.export_type,
+ ),
+ )
// The GGUF flag matters: GGUF_TTS_AUDIO_TYPES leaves csm out because llama.cpp has
// no CSM decoder, so a csm LoRA exported to GGUF fails at load. Without it the
// wider Transformers list answered and the row was offered anyway.
.filter((lora) =>
isTtsAudioType(lora.audio_type, lora.export_type === "gguf"),
)
+ .filter((lora) =>
+ trainedTtsCheckpointIsLoadable(lora.audio_type, lora.export_type),
+ )
.map((lora) => ({
id: lora.adapter_path,
name: audioModelLabel(lora.adapter_path),
@@ -1934,6 +2269,7 @@ export function AudioPage({
lora.export_type === "merged"
? `Fine-tuned - ${lora.base_model || "unknown base"}`
: `LoRA - ${lora.base_model || "unknown base"}`,
+ audioType: lora.audio_type ?? null,
})),
);
})
@@ -1949,6 +2285,7 @@ export function AudioPage({
// --- Render -------------------------------------------------------------
const selectedClip = clips.find((c) => c.id === selectedId) ?? null;
+ const selectedClipSrc = selectedClip ? srcById[selectedClip.id] : undefined;
const selectorModels =
mode === "speak" && isMac
? MODELS_BY_MODE.speak.filter((model) =>
@@ -2117,43 +2454,133 @@ export function AudioPage({
{mode === "speak" ? (
<>
<Field
- label="Text"
- hint="What the model should say. Generation runs on the loaded TTS model and lands in the gallery on the right."
+ label={musicGeneration ? "Lyrics" : "Text"}
+ htmlFor="audio-prompt"
+ hint={
+ musicGeneration
+ ? "Lyrics may use sections such as [verse] and [chorus]. The completed song lands in the gallery on the right."
+ : "What the model should say. Generation runs on the loaded TTS model and lands in the gallery on the right."
+ }
>
<Textarea
+ id="audio-prompt"
value={prompt}
onChange={(event) => setPrompt(event.target.value)}
- placeholder="Type the sentence to speak…"
+ placeholder={
+ musicGeneration
+ ? "[verse]\nMorning light through the pines…\n\n[chorus]\n…"
+ : "Type the sentence to speak…"
+ }
className="min-h-28"
/>
</Field>
+ {instructionsKind !== null ? (
+ <Field
+ label={
+ instructionsKind === "music"
+ ? "Music description"
+ : instructionsKind === "scene"
+ ? "Scene description"
+ : "Style instructions"
+ }
+ hint={
+ instructionsKind === "music"
+ ? "Describe genre, tempo, mood, vocals, and arrangement. MiniMax Music 3 requires this separately from the lyrics."
+ : instructionsKind === "scene"
+ ? "Optional Higgs TTS 2 scene guidance such as room acoustics, recording conditions, or background ambience."
+ : "Optional MOSS Local guidance such as speaking style, emotion, pace, or delivery."
+ }
+ htmlFor="audio-instructions"
+ >
+ <Textarea
+ id="audio-instructions"
+ value={audioInstructions}
+ onChange={(event) =>
+ setAudioInstructions(event.target.value)
+ }
+ placeholder={
+ instructionsKind === "music"
+ ? "Acoustic pop, 96 BPM, warm female lead, fingerpicked guitar and soft piano…"
+ : instructionsKind === "scene"
+ ? "Close-mic studio recording in a quiet, softly treated room…"
+ : "Warm, measured delivery with a calm conversational tone…"
+ }
+ className="min-h-24"
+ />
+ </Field>
+ ) : null}
+ {mossLocalGeneration ? (
+ <Field
+ label="Language"
+ htmlFor="audio-language"
+ hint="Optional, but MOSS Local v1.5 recommends a language tag when known (for example English, Arabic, or French)."
+ >
+ <Input
+ id="audio-language"
+ value={audioLanguage}
+ onChange={(event) => setAudioLanguage(event.target.value)}
+ placeholder="English"
+ />
+ </Field>
+ ) : null}
<AdvancedDisclosure
open={advancedOpen}
onOpenChange={setAdvancedOpen}
- description="Generation sampling. Changes apply to the next audio clip."
+ description={
+ musicGeneration
+ ? "Generation length. Changes apply to the next audio clip."
+ : "Generation sampling. Changes apply to the next audio clip."
+ }
>
- <ParamSlider
- label="Temperature"
- value={temperature}
- min={0}
- max={1.5}
- step={0.05}
- onChange={handleTemperatureChange}
- />
- <ParamSlider
- label="Max tokens"
- value={maxTokens}
- min={256}
- max={TTS_MAX_TOKENS}
- step={256}
- onChange={setMaxTokens}
- />
+ {!musicGeneration ? (
+ <ParamSlider
+ label="Temperature"
+ value={temperature}
+ min={0}
+ max={mossFrameLimit !== null ? 2 : 1.5}
+ step={0.05}
+ onChange={handleTemperatureChange}
+ />
+ ) : null}
+ {musicGeneration ? (
+ <ParamSlider
+ label="Max duration (seconds)"
+ value={minimaxMaxSeconds}
+ min={1}
+ max={MINIMAX_MUSIC_MAX_SECONDS}
+ step={1 / MINIMAX_MUSIC_FRAMES_PER_SECOND}
+ onChange={setMinimaxMaxSeconds}
+ valueSize={8}
+ info={`Starts at ${MINIMAX_MUSIC_DEFAULT_SECONDS} seconds. MiniMax Music 3 generates ${MINIMAX_MUSIC_FRAMES_PER_SECOND} frames per second, up to ${MINIMAX_MUSIC_MAX_SECONDS} seconds.`}
+ />
+ ) : mossFrameLimit !== null ? (
+ <ParamSlider
+ label="Max duration (seconds)"
+ value={mossMaxSeconds}
+ min={1}
+ max={mossMaxSecondsLimit}
+ step={1 / MOSS_TTS_FRAMES_PER_SECOND}
+ onChange={setMossMaxSeconds}
+ valueSize={8}
+ info={`Starts at ${MOSS_TTS_DEFAULT_SECONDS} seconds. This model reports ${mossFrameLimit?.toLocaleString()} frames (${mossMaxSecondsLimit.toLocaleString(undefined, { maximumFractionDigits: 2 })} seconds); the prompt uses part of that context.`}
+ />
+ ) : (
+ <ParamSlider
+ label="Max tokens"
+ value={maxTokens}
+ min={256}
+ max={TTS_MAX_TOKENS}
+ step={256}
+ onChange={setMaxTokens}
+ />
+ )}
</AdvancedDisclosure>
</>
) : (
<>
<Field
label="Microphone"
+ htmlFor="audio-record"
hint={
recordingSupported
? "Record a clip and it is transcribed when you stop."
@@ -2161,6 +2588,7 @@ export function AudioPage({
}
>
<Button
+ id="audio-record"
variant={isRecording ? "destructive" : "secondary"}
disabled={
!recordingSupported ||
@@ -2182,9 +2610,11 @@ export function AudioPage({
</Field>
<Field
label="Audio file"
+ htmlFor="audio-file"
hint="Or transcribe an existing recording (wav, mp3, m4a, webm…)."
>
<input
+ id="audio-file"
type="file"
accept="audio/*"
disabled={
@@ -2220,7 +2650,10 @@ export function AudioPage({
disabled={
busy === "generating"
? false
- : busy !== null || !ttsLoaded || !prompt.trim()
+ : busy !== null ||
+ !ttsLoaded ||
+ !prompt.trim() ||
+ (musicGeneration && !audioInstructions.trim())
}
variant={busy === "generating" ? "destructive" : "default"}
>
@@ -2301,12 +2734,24 @@ export function AudioPage({
<p className="line-clamp-2 text-ui-13 text-muted-foreground">
{selectedClip.prompt}
</p>
- {/* Auth-protected bytes, so the element plays the fetched object URL. */}
- <audio
- controls={true}
- src={srcById[selectedClip.id]}
- className="w-full"
- />
+ {/* Auth-protected bytes, so mount a fresh player only once this clip's
+ object URL exists. Reusing one media element while src is empty or
+ changing left History switches showing stale/broken controls. */}
+ {selectedClipSrc ? (
+ <audio
+ key={selectedClip.id}
+ controls={true}
+ src={selectedClipSrc}
+ className="w-full"
+ />
+ ) : (
+ <div
+ role="status"
+ className="flex h-12 w-full items-center justify-center rounded-md border border-border text-ui-12 text-muted-foreground"
+ >
+ Loading audio…
+ </div>
+ )}
<div className="flex items-center gap-2 text-ui-11p5 text-muted-foreground">
<span>{selectedClip.model}</span>
<span>·</span>
@@ -2413,6 +2858,9 @@ export function AudioPage({
<button
type="button"
onClick={() => selectClip(clip.id)}
+ aria-current={
+ clip.id === selectedId ? "true" : undefined
+ }
className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left text-ui-13"
>
<HugeiconsIcon
diff --git a/studio/frontend/src/features/audio/catalog.ts b/studio/frontend/src/features/audio/catalog.ts
index 6063d927ae6..5e48b26484a 100644
--- a/studio/frontend/src/features/audio/catalog.ts
+++ b/studio/frontend/src/features/audio/catalog.ts
@@ -24,6 +24,67 @@ export {
export type AudioTask = "tts" | "stt";
+const NATIVE_TTS_REPOS = new Set([
+ "bosonai/higgs-tts-2-3b-base",
+ "openmoss-team/moss-tts-local-transformer-v1.5",
+ "openmoss-team/moss-tts-nano-100m",
+ "multimodalart/higgs-audio-v3-tts-4b-transformers",
+ "minimaxai/minimax-music3",
+]);
+
+const REMOTE_CODE_TTS_REPOS = new Set([
+ "openmoss-team/moss-tts-local-transformer-v1.5",
+ "openmoss-team/moss-tts-nano-100m",
+ "multimodalart/higgs-audio-v3-tts-4b-transformers",
+]);
+
+const MUSIC_GENERATION_REPOS = new Set(["minimaxai/minimax-music3"]);
+const NATIVE_TTS_AUDIO_TYPES = new Set([
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+]);
+const REMOTE_CODE_TTS_AUDIO_TYPES = new Set([
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+]);
+
+const normalizedRepoId = (repoId: string): string =>
+ repoId.trim().toLowerCase();
+
+export function usesNativeAudioRuntime(
+ repoId: string,
+ audioType?: string | null,
+): boolean {
+ return (
+ NATIVE_TTS_REPOS.has(normalizedRepoId(repoId)) ||
+ Boolean(audioType && NATIVE_TTS_AUDIO_TYPES.has(audioType))
+ );
+}
+
+export function audioModelRequiresRemoteCode(
+ repoId: string,
+ audioType?: string | null,
+): boolean {
+ return (
+ REMOTE_CODE_TTS_REPOS.has(normalizedRepoId(repoId)) ||
+ Boolean(audioType && REMOTE_CODE_TTS_AUDIO_TYPES.has(audioType))
+ );
+}
+
+export function isMusicGenerationModel(
+ repoId?: string | null,
+ audioType?: string | null,
+): boolean {
+ return Boolean(
+ audioType === "minimax_music3" ||
+ (repoId && MUSIC_GENERATION_REPOS.has(normalizedRepoId(repoId))),
+ );
+}
+
export function audioTaskFor(repoId: string): AudioTask | null {
if (isKnownSttArtifactRepoId(repoId)) return "stt";
return groupForRepoId(repoId, AUDIO_CATALOG)?.task ?? null;
@@ -39,7 +100,10 @@ export function ggufSiblingFor(repoId: string): string | null {
export function macTtsCatalogChoiceIsRunnable(repoId: string): boolean {
const group = groupForRepoId(repoId, AUDIO_CATALOG);
if (!group || group.task !== "tts") return false;
- return group.artifacts.some((artifact) => artifact.format === "gguf");
+ return (
+ group.artifacts.some((artifact) => artifact.format === "gguf") ||
+ (usesNativeAudioRuntime(repoId) && !isMusicGenerationModel(repoId))
+ );
}
export const AUDIO_MODEL_OPTIONS: ModelOption[] =
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 6ea3f8064b9..3ecc86a96ed 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -602,6 +602,7 @@ export interface LocalModelInfo {
updated_at?: number | null;
// HF pipeline task inferred from the GGUF architecture, so the Images picker can filter to diffusion ("text-to-image"). Optional for older backends.
task?: string | null;
+ /** Detected output-audio architecture or codec used by Audio runtime policy. */
audio_type?: string | null;
}
@@ -638,6 +639,7 @@ export interface CachedModelRepo {
last_modified?: number;
/** HF pipeline task: "text-to-image" for a cached diffusers pipeline repo (model_index.json present), so the chat picker can hide it. Absent = chat. */
task?: string | null;
+ /** Detected output-audio architecture or codec used by Audio runtime policy. */
audio_type?: string | null;
/** True when the snapshot is incomplete (a cancelled/partial download): such a repo must not count as downloaded, or a click re-downloads the full weights. */
partial?: boolean;
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
index 737c3332f16..c353b112c76 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
@@ -4,6 +4,16 @@
import type { FormatFilter } from "./recommended-fit";
import type { ModelSelectorChangeMeta } from "./types";
+const NATIVE_AUDIO_TYPES = new Set([
+ "higgs_tts2",
+ "moss_tts_local",
+ "moss_tts_nano",
+ "higgs_tts3",
+ "minimax_music3",
+]);
+
+const TTS_CODECS = new Set(["snac", "csm", "bicodec", "dac"]);
+
export type CommunityModelPolicy = "none" | "search-only" | "recommended";
export function shouldDiscoverCommunityModels(
@@ -18,6 +28,28 @@ export function shouldRecommendCommunityModels(
return policy === "recommended";
}
+/** Maps detected audio runtime types to the media tag used by Chat routing. */
+export function audioPipelineTagFor(
+ audioType?: string | null,
+ isLocalCheckpoint = false,
+ isLora = false,
+): string | undefined {
+ if (!audioType) return undefined;
+ if (audioType === "whisper")
+ return isLocalCheckpoint ? undefined : "automatic-speech-recognition";
+ if (isLora && NATIVE_AUDIO_TYPES.has(audioType)) return undefined;
+ return TTS_CODECS.has(audioType) || NATIVE_AUDIO_TYPES.has(audioType)
+ ? "text-to-speech"
+ : undefined;
+}
+
+export function nativeAudioCheckpointIsLoadable(
+ audioType?: string | null,
+ exportType?: string | null,
+): boolean {
+ return !audioType || !NATIVE_AUDIO_TYPES.has(audioType) || exportType === "merged";
+}
+
/** Community ASR runs through the Transformers Whisper sidecar. Curated GGUF/MTMD
* artifacts are handled by the catalog before this gate, so an uncurated row must
* identify a non-GGUF Whisper checkpoint. */
@@ -53,6 +85,8 @@ export function communityAudioRowIsRunnable({
return evidence.some((value) => value.includes("whisper"));
}
+ if (audioType && NATIVE_AUDIO_TYPES.has(audioType)) return true;
+
// The main-slot TTS backend decodes only the four codec families below.
// Hub's text-to-speech tag also covers Bark, VITS, SpeechT5, and many other
// architectures that can load as language models but cannot emit a WAV here.
@@ -186,13 +220,25 @@ export function macTtsHubRowIsRunnable({
isTts,
isGguf,
hasRunnableGgufSibling,
+ audioType,
}: {
isMac: boolean;
isTts: boolean;
isGguf: boolean;
hasRunnableGgufSibling: boolean;
+ audioType?: string | null;
}): boolean {
- return !isMac || !isTts || isGguf || hasRunnableGgufSibling;
+ return (
+ !isMac ||
+ !isTts ||
+ isGguf ||
+ hasRunnableGgufSibling ||
+ Boolean(
+ audioType &&
+ NATIVE_AUDIO_TYPES.has(audioType) &&
+ audioType !== "minimax_music3",
+ )
+ );
}
export function taskCatalogFormatMatches(
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
index a310bbe789c..e165e3e8e01 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
@@ -854,6 +854,26 @@ assert.equal(groupForRepoId("unsloth/whisper-large-v3-turbo", AUDIO_CATALOG)?.ta
assert.equal(groupForRepoId("unslothai/Qwen3-ASR-0.6B-GGUF", AUDIO_CATALOG)?.task, "stt");
// A chat model stays unknown to the audio catalog.
assert.equal(groupForRepoId("unsloth/Llama-3.3-70B-GGUF", AUDIO_CATALOG), null);
+// MiniMax Music3 publishes a 67 GB repository, but its official BF16 modular loader
+// fits a 24 GB CUDA card. Download bytes must not become a false OOM badge.
+const minimaxMusic = groupForRepoId("MiniMaxAI/MiniMax-Music3", AUDIO_CATALOG);
+assert.ok(minimaxMusic);
+assert.equal(
+ curatedArtifactFitsDevice(
+ "MiniMaxAI/MiniMax-Music3",
+ AUDIO_CATALOG,
+ { gpuGb: 95, systemRamGb: 0 },
+ ),
+ true,
+);
+assert.equal(
+ curatedArtifactFitsDevice(
+ "MiniMaxAI/MiniMax-Music3",
+ AUDIO_CATALOG,
+ { gpuGb: 23, systemRamGb: 256 },
+ ),
+ false,
+);
// ── groupMatchesQuery ──────────────────────────────────────────────────────────
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
index 9fe571b37b3..c3fe7204fb2 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
@@ -455,7 +455,8 @@ export const VIDEO_CATALOG: CatalogGroup[] = [
];
// The Audio page's curated list. tts groups load into the main slot via /api/inference/load
-// (Orpheus is the only family the llama.cpp TTS path also serves as GGUF); stt groups map to
+// (Orpheus is the only family the llama.cpp TTS path also serves as GGUF); native TTS
+// families use their official Transformers/Diffusers interfaces. stt groups map to
// the dictation sidecar models in stt-model-catalog.ts, so their sizes are informational only.
export const AUDIO_CATALOG: CatalogGroup[] = [
{
@@ -496,6 +497,69 @@ export const AUDIO_CATALOG: CatalogGroup[] = [
bf16Pipeline("unsloth/Llama-OuteTTS-1.0-1B", 4, { label: "Safetensors" }),
],
},
+ {
+ canonicalId: "bosonai/higgs-tts-2-3b-base",
+ displayName: "Higgs TTS 2 3B",
+ description: "Text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("bosonai/higgs-tts-2-3b-base", 12, {
+ label: "Safetensors",
+ }),
+ ],
+ },
+ {
+ canonicalId: "OpenMOSS-Team/MOSS-TTS-Local-Transformer-v1.5",
+ displayName: "MOSS TTS Local v1.5",
+ description: "48 kHz stereo text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("OpenMOSS-Team/MOSS-TTS-Local-Transformer-v1.5", 10, {
+ label: "Safetensors",
+ }),
+ ],
+ },
+ {
+ canonicalId: "OpenMOSS-Team/MOSS-TTS-Nano-100M",
+ displayName: "MOSS TTS Nano 100M",
+ description: "CPU-friendly text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("OpenMOSS-Team/MOSS-TTS-Nano-100M", 1, {
+ label: "Safetensors",
+ }),
+ ],
+ },
+ {
+ canonicalId: "multimodalart/higgs-audio-v3-tts-4b-transformers",
+ displayName: "Higgs Audio v3 TTS 4B",
+ description: "Text-to-speech",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("multimodalart/higgs-audio-v3-tts-4b-transformers", 10, {
+ label: "Safetensors",
+ }),
+ ],
+ },
+ {
+ canonicalId: "MiniMaxAI/MiniMax-Music3",
+ displayName: "MiniMax Music 3",
+ description: "Lyrics-to-music · NVIDIA CUDA",
+ scope: "audio",
+ task: "tts",
+ artifacts: [
+ bf16Pipeline("MiniMaxAI/MiniMax-Music3", 67, {
+ label: "Diffusers",
+ // 67 GB is the repository/download footprint, not resident VRAM. The
+ // publisher's ModularPipeline path loads in BF16 on a 24 GB CUDA GPU.
+ offloadFitTiers: [{ gpuGb: 24, systemRamGb: 0 }],
+ }),
+ ],
+ },
// Llasa is deliberately absent. It speaks XCodec2 (65,536 <|s_N|> tokens), which is
// neither in _AUDIO_TOKEN_PATTERNS nor in AudioCodecManager, so a curated row here
// loaded and then failed at generation with "not a supported TTS model". Unsloth can
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index e5eac56e563..e7758f5a9d0 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -116,6 +116,7 @@ import { useChatPickerInventory } from "../../inventory/use-chat-picker-inventor
import {
type CommunityModelPolicy,
allowedHiddenModelIdMatches,
+ audioPipelineTagFor,
audioPickIsRoutable,
localAudioRowIsUndecodableGguf,
communityAudioRowIsRunnable,
@@ -123,6 +124,7 @@ import {
curatedAudioInventoryTask,
filesystemRowsSupportedForTask,
macTtsHubRowIsRunnable,
+ nativeAudioCheckpointIsLoadable,
shouldDiscoverCommunityModels,
shouldRecommendCommunityModels,
taskCatalogFormatMatches,
@@ -2111,8 +2113,6 @@ const MEDIA_PAGE_TASKS: readonly string[] = [
];
/** The page that runs this task, or null when chat should handle the pick. */
-const TTS_CODECS = new Set(["snac", "csm", "bicodec", "dac"]);
-
function mediaPageForTask(
task: string | null | undefined,
): "images" | "video" | "audio" | null {
@@ -2337,6 +2337,7 @@ function localPathTooltip(
function localModelMeta(
isGguf = false,
pipelineTag?: string | null,
+ audioType?: string | null,
): ModelSelectorChangeMeta {
return {
source: "local",
@@ -2344,6 +2345,7 @@ function localModelMeta(
isDownloaded: true,
...(isGguf ? { isGguf: true } : {}),
pipelineTag: pipelineTag ?? null,
+ audioType: audioType ?? null,
};
}
@@ -3553,6 +3555,7 @@ export function HubModelPicker({
(artifact) => artifact.format === "gguf",
),
),
+ audioType: c.audio_type,
})) ||
(catalog
? artifactForRepoId(c.repo_id, catalog) !== null
@@ -3783,6 +3786,7 @@ export function HubModelPicker({
task: pickedTask,
isGguf: Boolean(meta.isGguf || meta.ggufFilename),
isCurated: artifactForRepoId(id, AUDIO_CATALOG) !== null,
+ audioType: meta.audioType,
isLocalCheckpoint:
meta.source === "lora" ||
meta.source === "exported" ||
@@ -3812,6 +3816,8 @@ export function HubModelPicker({
: (meta.ggufVariant ?? undefined),
// pickedTask, not meta.pipelineTag: a cached row carries no tag to forward.
task: pickedTask ?? undefined,
+ audioType: meta.audioType ?? undefined,
+ loadId: meta.loadId ?? undefined,
}
: diffusionRouteSearch(id, meta),
});
@@ -3840,6 +3846,9 @@ export function HubModelPicker({
isDirectGguf: m.isDirectGguf,
}),
)
+ .filter((m) =>
+ nativeAudioCheckpointIsLoadable(m.audioType, m.exportType),
+ )
.filter((m) => {
const text = normalizeForSearch(
`${m.name} ${m.baseModel ?? ""} ${m.id}`,
@@ -5174,6 +5183,7 @@ export function HubModelPicker({
loadId: c.load_id,
isDownloaded: true,
pipelineTag: c.task ?? null,
+ audioType: c.audio_type ?? null,
})
}
vramStatus={null}
@@ -5192,6 +5202,7 @@ export function HubModelPicker({
isDownloaded: true,
isGguf: false,
pipelineTag: c.task ?? null,
+ audioType: c.audio_type ?? null,
})
}
/>
@@ -5272,6 +5283,7 @@ export function HubModelPicker({
isDownloaded: true,
isGguf: model.isGguf === true,
pipelineTag,
+ audioType: model.audioType ?? null,
})
}
vramStatus={null}
@@ -5943,7 +5955,7 @@ export function HubModelPicker({
} else {
onSelect(
m.id,
- localModelMeta(false, m.task),
+ localModelMeta(false, m.task, m.audio_type),
);
}
}}
@@ -5984,7 +5996,7 @@ export function HubModelPicker({
onConfigure={() =>
onConfigure(
m.id,
- localModelMeta(false, m.task),
+ localModelMeta(false, m.task, m.audio_type),
)
}
/>
@@ -6088,7 +6100,7 @@ export function HubModelPicker({
} else {
onSelect(
m.id,
- localModelMeta(false, m.task),
+ localModelMeta(false, m.task, m.audio_type),
);
}
}}
@@ -6129,7 +6141,7 @@ export function HubModelPicker({
onConfigure={() =>
onConfigure(
m.id,
- localModelMeta(false, m.task),
+ localModelMeta(false, m.task, m.audio_type),
)
}
/>
@@ -6220,7 +6232,7 @@ export function HubModelPicker({
} else {
onSelect(
m.id,
- localModelMeta(false, m.task),
+ localModelMeta(false, m.task, m.audio_type),
);
}
}}
@@ -6257,7 +6269,7 @@ export function HubModelPicker({
onConfigure={() =>
onConfigure(
m.id,
- localModelMeta(false, m.task),
+ localModelMeta(false, m.task, m.audio_type),
)
}
/>
@@ -6269,7 +6281,7 @@ export function HubModelPicker({
repoId={m.id}
onDevice={true}
onSelect={onSelect}
- resolveDownloadFootprint={resolveDownloadFootprint}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
parentOptionKey={optionKey}
onNavigatePastStart={() =>
@@ -6484,7 +6496,7 @@ export function HubModelPicker({
repoId={id}
pipelineTag={pipelineTagById.get(id) ?? null}
onSelect={onSelect}
- resolveDownloadFootprint={resolveDownloadFootprint}
+ resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
hfToken={hfToken || undefined}
parentOptionKey={optionKey}
@@ -6667,22 +6679,6 @@ export function HubModelPicker({
/** Fine-tuned model rows for the On Device tab's Fine-tuned section. Plugs into
* that section's roving list and shared GGUF-expand state. */
-/** Codec -> the Hub pipeline tag the media routing understands, else undefined.
- *
- * A local checkpoint never gets the ASR tag: it would route to the Audio page, which hands
- * the filesystem path to /audio/stt/load, and the sidecar's resolve_model_id takes only a
- * curated key or an `owner/model` Hub id, so the row is advertised and then 422s. TTS is
- * fine, since that loads through the main slot, which does accept a local path. */
-function audioPipelineTagFor(
- audioType?: string | null,
- isLocalCheckpoint = false,
-): string | undefined {
- if (!audioType) return undefined;
- if (audioType === "whisper")
- return isLocalCheckpoint ? undefined : "automatic-speech-recognition";
- return TTS_CODECS.has(audioType) ? "text-to-speech" : undefined;
-}
-
function FineTunedRows({
adapters,
value,
@@ -6723,6 +6719,7 @@ function FineTunedRows({
const isExported = adapter.source === "exported";
const isMerged = adapter.exportType === "merged";
const isGguf = adapter.exportType === "gguf";
+ const isLora = !isLocal && !isMerged && !isGguf;
const isExportedGguf = isExported && isGguf;
const canDelete = canDeleteLoraModel(adapter);
const isTrainingFull = isTraining && isMerged;
@@ -6737,10 +6734,11 @@ function FineTunedRows({
// The pipeline tag is what onSelect routes on, so carry the detected codec as one.
const selectionMeta: ModelSelectorChangeMeta = {
source: isLocal ? "local" : isExported ? "exported" : "lora",
- isLora: !isLocal && !isMerged && !isGguf,
+ isLora,
isDownloaded: true,
isGguf: isLocalDirectGguf,
- pipelineTag: audioPipelineTagFor(adapter.audioType, true),
+ pipelineTag: audioPipelineTagFor(adapter.audioType, true, isLora),
+ audioType: adapter.audioType ?? null,
};
const canConfigure = !(isLocalGgufDir || isExportedGguf);
const optionKey = makeModelOptionKey("lora", adapter.id);
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
index 1331bcbd749..bf6800809a6 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
@@ -18,6 +18,8 @@ export interface ModelOption {
deviceSize?: string;
deviceSizeBytes?: number;
deviceLoaded?: boolean;
+ /** Detected local audio architecture, retained by task-owned on-device rows. */
+ audioType?: string | null;
}
export interface LoraModelOption extends ModelOption {
@@ -64,6 +66,8 @@ export interface ModelSelectorChangeMeta {
/** Hub pipeline tag for an uncurated pick, so a task page can tell which task
* the repo does when it is not in the page's catalog. */
pipelineTag?: string | null;
+ /** Detected local audio architecture, used when a filesystem path has no Hub id. */
+ audioType?: string | null;
nativePathExpiresAtMs?: number | null;
}
diff --git a/studio/frontend/tests/audio-catalog-decodable.test.ts b/studio/frontend/tests/audio-catalog-decodable.test.ts
index 203381cad6b..0c773678d7c 100644
--- a/studio/frontend/tests/audio-catalog-decodable.test.ts
+++ b/studio/frontend/tests/audio-catalog-decodable.test.ts
@@ -27,7 +27,8 @@ const policy = readFileSync(
"utf8",
);
-// The four the main-slot TTS backend decodes: snac, csm, bicodec, dac.
+// The codec-backed families decoded by the legacy main-slot backend. Native
+// architecture families are checked against their dedicated backend below.
const DECODABLE = ["orpheus", "csm", "spark", "outetts"];
test("the curated audio catalog offers no model the backend cannot decode", () => {
@@ -35,11 +36,41 @@ test("the curated audio catalog offers no model the backend cannot decode", () =
const body = audio.slice(0, audio.indexOf("\n];"));
assert.doesNotMatch(body, /canonicalId: "[^"]*Llasa[^"]*"/i);
// The rows that remain are still there, so this cannot pass by emptying the catalog.
- for (const family of ["orpheus", "csm-1b", "Spark-TTS", "OuteTTS", "whisper"]) {
+ for (const family of [
+ "orpheus",
+ "csm-1b",
+ "Spark-TTS",
+ "OuteTTS",
+ "higgs-tts-2-3b-base",
+ "MOSS-TTS-Local-Transformer-v1.5",
+ "MOSS-TTS-Nano-100M",
+ "higgs-audio-v3-tts-4b-transformers",
+ "MiniMax-Music3",
+ "whisper",
+ ]) {
assert.match(body, new RegExp(family, "i"), family);
}
});
+test("the five native catalog rows are wired to native backend architectures", () => {
+ const backend = readFileSync(
+ new URL("../../backend/core/inference/native_audio.py", import.meta.url),
+ "utf8",
+ ).toLowerCase();
+ for (const repo of [
+ "bosonai/higgs-tts-2-3b-base",
+ "openmoss-team/moss-tts-local-transformer-v1.5",
+ "openmoss-team/moss-tts-nano-100m",
+ "multimodalart/higgs-audio-v3-tts-4b-transformers",
+ "minimaxai/minimax-music3",
+ ]) {
+ assert.match(
+ backend,
+ new RegExp(repo.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
+ );
+ }
+});
+
test("the community TTS family list matches what can be decoded", () => {
const match = policy.match(/\/\(\?:\^\|\[-_\.\/\]\)\(([^)]+)\)/);
assert.ok(match, "could not find the family regex");
diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.ts
index 89d2e4024c3..b1cb3194a9e 100644
--- a/studio/frontend/tests/audio-model-eject.test.ts
+++ b/studio/frontend/tests/audio-model-eject.test.ts
@@ -67,7 +67,7 @@ test("a Speak load asks the same question and forces from the answer", () => {
// The slot is claimed before the await, so a routed pick arriving mid-dialog queues.
assert.match(
source,
- /if \(ttsLoadInFlight\.current\) \{\s*pendingRoutedTtsPick\.current = \{ repoId, ggufFilename, loadId \};\s*return;\s*\}[\s\S]{0,400}?ttsLoadInFlight\.current = true;/,
+ /if \(ttsLoadInFlight\.current \|\| busyRef\.current === "generating"\) \{\s*pendingRoutedTtsPick\.current = \{\s*repoId,\s*ggufFilename,\s*loadId,\s*audioType,\s*remoteCodeApproval,\s*\};\s*return;\s*\}[\s\S]{0,400}?ttsLoadInFlight\.current = true;/,
);
// Declining releases the slot and drops the queued pick, which would else re-ask.
assert.match(
@@ -106,7 +106,7 @@ test("a model swap holds Chat's lifecycle gate across the question", () => {
// Released before the queued replay, which needs the gate for its own attempt.
assert.match(
source,
- /ttsLoadInFlight\.current = false;[\s\S]{0,120}?releaseLifecycle\(\);[\s\S]*?replayQueuedTtsPick\(\);/,
+ /if \(activeRef\.current\) await refreshStatus\(\);\s*ttsLoadInFlight\.current = false;[\s\S]{0,120}?releaseLifecycle\(\);[\s\S]*?replayQueuedTtsPick\(\);/,
);
// Eject takes it before it goes busy, so it is held across its own question too.
assert.match(
@@ -124,7 +124,7 @@ test("a load confirmed after Audio is hidden is deferred, not sent", () => {
// nothing to abort. Sending anyway let a hidden page replace the visible page's model.
assert.match(
source,
- /if \(!activeRef\.current\) \{\s*releaseLifecycle\(\);\s*ttsLoadInFlight\.current = false;\s*pendingRoutedTtsPick\.current = \{ repoId, ggufFilename, loadId \};\s*return;\s*\}/,
+ /if \(!activeRef\.current\) \{\s*releaseLifecycle\(\);\s*ttsLoadInFlight\.current = false;\s*pendingRoutedTtsPick\.current = \{\s*repoId,\s*ggufFilename,\s*loadId,\s*audioType,\s*remoteCodeApproval,\s*\};\s*return;\s*\}/,
);
// The activation effect replays exactly that queue, so the pick is not lost.
assert.match(
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index 3553064ca60..d003b6d72d2 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -11,8 +11,14 @@ import {
expectedGgufDownloadBytes,
isTtsAudioType,
macTtsPickAction,
+ MINIMAX_MUSIC_DEFAULT_SECONDS,
+ MINIMAX_MUSIC_FRAMES_PER_SECOND,
+ MINIMAX_MUSIC_MAX_FRAMES,
+ MINIMAX_MUSIC_MAX_SECONDS,
mergeGalleryPage,
micStreamRequestIsCurrent,
+ minimaxMusicFramesForSeconds,
+ nativeAudioInstructionsKind,
persistedClipForGeneration,
reconcileSttSelection,
resolveSttLoadedModel,
@@ -63,6 +69,50 @@ test("TTS load context matches the advertised generation ceiling", () => {
assert.match(audioPageSource, /label="Max tokens"[\s\S]*max=\{TTS_MAX_TOKENS\}/);
});
+test("MiniMax duration converts seconds to the official frame budget", () => {
+ assert.equal(MINIMAX_MUSIC_FRAMES_PER_SECOND, 25);
+ assert.equal(MINIMAX_MUSIC_DEFAULT_SECONDS, 30);
+ assert.equal(MINIMAX_MUSIC_MAX_FRAMES, 9000);
+ assert.equal(MINIMAX_MUSIC_MAX_SECONDS, 360);
+ assert.equal(
+ minimaxMusicFramesForSeconds(MINIMAX_MUSIC_DEFAULT_SECONDS),
+ 750,
+ );
+ assert.equal(minimaxMusicFramesForSeconds(1.99), 49);
+ assert.equal(minimaxMusicFramesForSeconds(1.16), 29);
+ assert.equal(minimaxMusicFramesForSeconds(360), 9000);
+ assert.equal(minimaxMusicFramesForSeconds(999), 9000);
+ assert.equal(minimaxMusicFramesForSeconds(0), 1);
+ for (let frames = 1; frames <= MINIMAX_MUSIC_MAX_FRAMES; frames += 1) {
+ assert.equal(
+ minimaxMusicFramesForSeconds(frames / MINIMAX_MUSIC_FRAMES_PER_SECOND),
+ frames,
+ );
+ }
+});
+
+test("native audio instruction fields match the runtime payload contract", () => {
+ assert.equal(nativeAudioInstructionsKind("higgs_tts2"), "scene");
+ assert.equal(nativeAudioInstructionsKind("moss_tts_local"), "style");
+ assert.equal(nativeAudioInstructionsKind("minimax_music3"), "music");
+ assert.equal(nativeAudioInstructionsKind("higgs_tts3"), null);
+ assert.equal(nativeAudioInstructionsKind("moss_tts_nano"), null);
+ assert.equal(nativeAudioInstructionsKind(null), null);
+});
+
+test("Audio sends model-specific duration and instruction payloads", () => {
+ assert.match(
+ audioPageSource,
+ /musicGeneration\s*\? minimaxMusicFramesForSeconds\(minimaxMaxSeconds\)/,
+ );
+ assert.match(audioPageSource, /max=\{MINIMAX_MUSIC_MAX_SECONDS\}/);
+ assert.match(
+ audioPageSource,
+ /instructionsKind !== null && instructions[\s\S]*audio_instructions: instructions/,
+ );
+ assert.match(audioPageSource, /\? "Scene description"/);
+});
+
test("Mac rejects safetensors-only TTS and redirects sibling families", () => {
assert.equal(
macTtsPickAction({ isMac: true, isGguf: false, ggufSibling: null }),
@@ -454,13 +504,10 @@ test("a recording is stopped at the sidecar's duration and size limits", () => {
assert.match(audioPageSource, /window\.clearTimeout\(durationTimer\);/);
});
-test("macOS hides trained TTS checkpoints that are not GGUF", () => {
- // MLX has no TTS decoder, so a LoRA or merged safetensors row deterministically fails
- // with "not supported on the MLX backend yet". The catalog rows are already filtered to
- // families with a GGUF sibling; these have none.
+test("the trained-model list applies the native-aware macOS policy", () => {
assert.match(
audioPageSource,
- /\.filter\(\(lora\) => !isMac \|\| lora\.export_type === "gguf"\)/,
+ /!isMac \|\|\s*trainedTtsCheckpointIsRunnableOnMac\(lora\.audio_type, lora\.export_type\)/,
);
});
diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.ts
index 8669c4ada0b..aaca8a73a69 100644
--- a/studio/frontend/tests/audio-picker-policy.test.ts
+++ b/studio/frontend/tests/audio-picker-policy.test.ts
@@ -6,6 +6,8 @@ import { readFileSync } from "node:fs";
import test from "node:test";
import {
+ audioPipelineTagFor,
+ nativeAudioCheckpointIsLoadable,
audioPickIsRoutable,
communityAudioRowIsRunnable,
curatedAudioInventoryMatches,
@@ -580,21 +582,28 @@ test("an unroutable speech pick is refused instead of loaded into chat", () => {
);
});
-test("a local Whisper checkpoint is not advertised as a routable ASR row", () => {
+test("fine-tuned audio rows receive only runnable pipeline tags", () => {
// The STT sidecar's resolve_model_id takes a curated key or an owner/model Hub id, so a
// filesystem path 422s. Routing one from the picker advertised a row that cannot load.
- const source = readFileSync(
- new URL(
- "../src/features/model-picker/components/model-selector/pickers.tsx",
- import.meta.url,
- ),
- "utf8",
+ assert.equal(audioPipelineTagFor("whisper", true), undefined);
+ assert.equal(audioPipelineTagFor("moss_tts_local", true), "text-to-speech");
+ // Native runtimes reject adapter-only checkpoints; merged exports remain runnable.
+ assert.equal(audioPipelineTagFor("moss_tts_local", true, true), undefined);
+ assert.equal(audioPipelineTagFor("moss_tts_local", true, false), "text-to-speech");
+ assert.match(
+ pickerSource,
+ /pipelineTag: audioPipelineTagFor\(adapter\.audioType, true, isLora\)/,
);
+});
+
+test("adapter-only native audio checkpoints are hidden from the runnable picker", () => {
+ assert.equal(nativeAudioCheckpointIsLoadable("moss_tts_local", "adapter"), false);
+ assert.equal(nativeAudioCheckpointIsLoadable("higgs_tts2", "merged"), true);
+ assert.equal(nativeAudioCheckpointIsLoadable("snac", "adapter"), true);
assert.match(
- source,
- /if \(audioType === "whisper"\)\s*\n?\s*return isLocalCheckpoint \? undefined : "automatic-speech-recognition";/,
+ pickerSource,
+ /fineTunedRows[\s\S]*nativeAudioCheckpointIsLoadable\(m\.audioType, m\.exportType\)/,
);
- assert.match(source, /pipelineTag: audioPipelineTagFor\(adapter\.audioType, true\)/);
});
test("an arch-tasked speech GGUF routes by detected codec", () => {
diff --git a/studio/frontend/tests/audio-tts-download-manager.test.ts b/studio/frontend/tests/audio-tts-download-manager.test.ts
index 7e3e3251633..99e76b394bb 100644
--- a/studio/frontend/tests/audio-tts-download-manager.test.ts
+++ b/studio/frontend/tests/audio-tts-download-manager.test.ts
@@ -26,12 +26,32 @@ test("uncached remote TTS GGUFs stage the exact file through the shared manager"
);
});
+test("remote code approval precedes native model staging and survives completion", () => {
+ const start = source.indexOf("const loadOrStageTtsModel");
+ const end = source.indexOf("const ensureSttLoaded", start);
+ const stagedFlow = source.slice(start, end);
+ assert.ok(start >= 0 && end > start);
+ assert.ok(
+ stagedFlow.indexOf("confirmRemoteCodeIfNeeded(") <
+ stagedFlow.indexOf("getAudioDownloadPlan("),
+ );
+ assert.match(
+ stagedFlow,
+ /pendingStagedTtsLoad\.current = \{[\s\S]*remoteCodeApproval,[\s\S]*generation/,
+ );
+ assert.match(source, /pending\.audioType,[\s\S]*pending\.remoteCodeApproval/);
+ assert.match(
+ source,
+ /audioModelRequiresRemoteCode\(repoId, audioType\) &&[\s\S]*!remoteCodeApproval/,
+ );
+});
+
test("cached and local TTS picks keep the direct load path and supersede stale staging", () => {
assert.match(
source,
// meta.loadId is the load target for a row cached in a non-active HF cache; sending
// the display repo id instead failed offline or re-downloaded into the active cache.
- /pendingStagedTtsLoad\.current = null;[\s\S]*stageTtsDownload\(\[\]\);[\s\S]*loadTtsModelRef\.current\(repoId, ggufFilename, meta\.loadId\)/,
+ /pendingStagedTtsLoad\.current = null;[\s\S]*stageTtsDownload\(\[\]\);[\s\S]*loadTtsModelRef\.current\([\s\S]*repoId,[\s\S]*ggufFilename,[\s\S]*meta\.loadId,[\s\S]*meta\.audioType/,
);
assert.match(source, /if \(busyRef\.current !== null\) return;/);
assert.match(
@@ -43,7 +63,7 @@ test("cached and local TTS picks keep the direct load path and supersede stale s
// cleared ?model=, so nothing retried it.
assert.match(
source,
- /if \(ttsLoadInFlight\.current\) \{\s*pendingRoutedTtsPick\.current = \{ repoId, ggufFilename, loadId \};\s*return;\s*\}/,
+ /if \(ttsLoadInFlight\.current \|\| busyRef\.current === "generating"\) \{\s*pendingRoutedTtsPick\.current = \{[\s\S]*repoId,[\s\S]*ggufFilename,[\s\S]*loadId,[\s\S]*audioType,[\s\S]*remoteCodeApproval,[\s\S]*\};\s*return;\s*\}/,
);
assert.match(
source,
@@ -54,6 +74,27 @@ test("cached and local TTS picks keep the direct load path and supersede stale s
);
});
+test("a preflight that loses to generation queues its load until generation ends", () => {
+ assert.match(
+ source,
+ /if \(ttsLoadInFlight\.current \|\| busyRef\.current === "generating"\) \{[\s\S]*pendingRoutedTtsPick\.current/,
+ );
+ assert.match(
+ source,
+ /generateAbort\.current = null;\s*busyRef\.current = null;\s*setBusy\(null\);\s*if \(activeRef\.current\) replayQueuedTtsPick\(\)/,
+ );
+});
+
+test("a completed load keeps controls disabled until status catches up", () => {
+ const start = source.indexOf("const loadTtsModel = useCallback");
+ const end = source.indexOf("const loadTtsModelRef", start);
+ const loadFlow = source.slice(start, end);
+ assert.match(
+ loadFlow,
+ /if \(activeRef\.current\) await refreshStatus\(\);[\s\S]*busyRef\.current = null;[\s\S]*setBusy\(null\)/,
+ );
+});
+
test("managed completion loads the exact GGUF only when Audio is active and idle", () => {
assert.match(
source,
@@ -61,7 +102,7 @@ test("managed completion loads the exact GGUF only when Audio is active and idle
);
assert.match(
source,
- /loadTtsModelRef\.current\(pending\.repoId, pending\.ggufFilename\)/,
+ /loadTtsModelRef\.current\([\s\S]*pending\.repoId,[\s\S]*pending\.ggufFilename,[\s\S]*pending\.loadId,[\s\S]*pending\.audioType/,
);
assert.match(
source,
@@ -88,7 +129,7 @@ test("switching to Transcribe invalidates a pending staged TTS auto-load", () =>
test("a GGUF forwarded from Chat enters the managed staging path", () => {
assert.match(
source,
- /ggufFilename: routeSearch\.quant \?\? undefined,[\s\S]*isDownloaded: routeSearch\.quant \? false : undefined/,
+ /ggufFilename: routeSearch\.quant \?\? undefined,[\s\S]*isDownloaded: routeSearch\.loadId[\s\S]*routeSearch\.quant[\s\S]*\? false/,
);
});
diff --git a/studio/frontend/tests/qwen-thinking-size-gate.test.ts b/studio/frontend/tests/qwen-thinking-size-gate.test.ts
index f12077783dd..82460264e3d 100644
--- a/studio/frontend/tests/qwen-thinking-size-gate.test.ts
+++ b/studio/frontend/tests/qwen-thinking-size-gate.test.ts
@@ -89,7 +89,7 @@ test("all four copies of the gate pattern stay in sync", () => {
/const sizeRe = \/(.+?)\/;/,
),
read("../../backend/core/inference/llama_cpp.py").match(
- /size_re = r"(.+?)"\n/,
+ /size_re = r"(.+?)"\r?\n/,
),
];
for (const found of patterns) assert.ok(found, "size gate pattern not found");
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index ad2ee35bb4d..c6a5b51ac46 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -5596,20 +5596,15 @@ def install_python_stack() -> int:
constrain = False,
)
- # 11b. The pinned Diffusers revision. NOT in base.txt, which is applied early: this must
+ # 11b. The pinned Diffusers release. NOT in base.txt, which is applied early: this must
# run after every other requirements file so nothing re-resolves Diffusers back to a
# release, and outside every skip_base / NO_TORCH branch so it reaches every path.
# constrain stays on: constraints.txt says nothing about diffusers today, and a
# future entry there should win rather than be silently bypassed here.
_progress("diffusers pin")
pip_install(
- "Installing the pinned Diffusers revision",
+ "Installing the pinned Diffusers release",
"--no-cache-dir",
- # The pin is a source ARCHIVE, which uv refuses to build under a user-level
- # no-build, so a hardened host failed here even once extras.txt succeeded
- # (#8530). Guarded: python < 3.10 resolves a released wheel from this file that
- # must not be forced through a source build.
- *(_sdist_only_build_args("diffusers") if sys.version_info >= (3, 10) else []),
req = REQ_ROOT / "diffusers-pin.txt",
)
diff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.py
index 53141e32a66..703db20d7eb 100644
--- a/tests/studio/install/test_diffusers_pin.py
+++ b/tests/studio/install/test_diffusers_pin.py
@@ -1,10 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""The pinned Diffusers revision has to survive a fresh install.sh, not just an update.
+"""The pinned Diffusers release has to survive a fresh install.sh, not just an update.
-MiniMax-H3 needs a Diffusers revision newer than any published release, and Unsloth
-refuses to load it otherwise. The pin originally lived in
+MiniMax-H3 and MiniMax Music 3 need Diffusers 0.40.0 or newer, and Unsloth refuses
+to load them otherwise. The pin originally lived in
studio/backend/requirements/base.txt, which did not reach fresh install.sh installs at
the time. base.txt now reaches those installs as an independent shared phase, but it
still runs too early to hold this pin safely.
@@ -41,17 +41,14 @@ def _requirements(path: pathlib.Path) -> list[str]:
return out
-def test_the_pin_file_exists_and_names_an_exact_revision():
+def test_the_pin_file_exists_and_names_the_first_supported_release():
assert PIN_FILE.is_file(), f"{PIN_FILE} is missing"
lines = _requirements(PIN_FILE)
- urls = [line for line in lines if "://" in line]
- assert len(urls) == 1, f"expected exactly one pinned URL, got {urls}"
- # A branch or tag would move under us; only a 40-char commit sha is reproducible.
- assert re.search(
- r"/archive/[0-9a-f]{40}\.zip", urls[0]
- ), f"the diffusers pin must name a full commit sha, not a moving ref: {urls[0]}"
- assert 'python_version >= "3.10"' in urls[0], (
- "diffusers dropped Python 3.9 in 0.38, so the archive needs a >= 3.10 marker or "
+ modern = [line for line in lines if 'python_version >= "3.10"' in line]
+ assert modern == ['diffusers==0.40.0 ; python_version >= "3.10"'], modern
+ assert "://" not in modern[0], "the released dependency must not require a source build"
+ assert 'python_version >= "3.10"' in modern[0], (
+ "diffusers dropped Python 3.9 in 0.38, so the release needs a >= 3.10 marker or "
"the resolver has no candidate at all on a 3.9 host"
)