Skip to content

SOTA-Class TTS at Compact Scale

Python

Add SGLang Omni support for Audio8-TTS-0.1B (Falcon-H1 hybrid slow backbone)

linyubupab1e2c9da5532
diff --git a/README.md b/README.md
index af84787..ea981c7 100644
--- a/README.md
+++ b/README.md
@@ -169,6 +169,34 @@ revision instead of the latest `main` branch.
| Transformers | `4.57.1` |
| Precision | BF16 |
+### Audio8-TTS-0.1B (Falcon-H1 hybrid slow backbone)
+
+`Audio8-TTS-Preview-0.1b` replaces the pure-attention slow AR backbone with a
+Falcon-H1 hybrid (Mamba 2 SSM + attention). The adapter detects this
+automatically from `config.json` (`slow_backbone: falcon_h1` or a `mamba_d_ssm`
+field) and switches to the eager hybrid path: the slow backbone runs with one
+`FalconHybridMambaAttentionDynamicCache` per request, while the fast codebook
+AR, semantic sampling and vocoder are shared with the 0.6B path. The 0.6B
+path is unchanged.
+
+```bash
+export MODEL=/models/Audio8-TTS-Preview-0.1b
+export CONFIG=./sglang_omni/configs/audio8_tts_0_1b.yaml
+export MODEL_NAME=audio8/tts-0.1b
+
+CUDA_VISIBLE_DEVICES=0 \
+SGLANG_OMNI_ROOT="${SGLANG_OMNI_ROOT}" \
+MODEL="${MODEL}" \
+CONFIG="${CONFIG}" \
+MODEL_NAME="${MODEL_NAME}" \
+./sglang_omni/scripts/run_server.sh
+```
+
+Because the Mamba backbone keeps its own hybrid caches and does not consume
+SGLang KV pages, the adapter disables CUDA graphs and caps the static memory
+fraction for this model. The slow backbone is bit-exact with the Transformers
+Falcon-H1 implementation for both prefill and cached decode.
+
### Performance
Warm single-stream latency was measured on one NVIDIA H20 with BF16 weights,
diff --git a/README_zh.md b/README_zh.md
index 640f301..9c6086d 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -149,6 +149,31 @@ paged attention、动态 batching、Fast AR 固定 KV cache、参考音频编码
| Transformers | `4.57.1` |
| 精度 | BF16 |
+### Audio8-TTS-0.1B(Falcon-H1 混合慢速主干)
+
+`Audio8-TTS-Preview-0.1b` 将纯注意力的慢速 AR 主干替换为 Falcon-H1 混合结构
+(Mamba 2 SSM + 注意力)。适配器会自动从 `config.json` 检测(`slow_backbone:
+falcon_h1` 或存在 `mamba_d_ssm` 字段)并切换到 eager 混合路径:慢速主干为每个
+请求维护一个 `FalconHybridMambaAttentionDynamicCache`,而快速码本 AR、语义采样
+与声码器与 0.6B 路径完全共用,0.6B 路径不受影响。
+
+```bash
+export MODEL=/models/Audio8-TTS-Preview-0.1b
+export CONFIG=./sglang_omni/configs/audio8_tts_0_1b.yaml
+export MODEL_NAME=audio8/tts-0.1b
+
+CUDA_VISIBLE_DEVICES=0 \
+SGLANG_OMNI_ROOT="${SGLANG_OMNI_ROOT}" \
+MODEL="${MODEL}" \
+CONFIG="${CONFIG}" \
+MODEL_NAME="${MODEL_NAME}" \
+./sglang_omni/scripts/run_server.sh
+```
+
+由于 Mamba 主干自行维护混合缓存、不占用 SGLang KV 页,适配器会为该模型关闭
+CUDA Graph 并限制静态显存比例。慢速主干在 prefill 与增量 decode 上与
+Transformers 的 Falcon-H1 实现逐位一致。
+
### 性能
单流 warm latency 在单张 NVIDIA H20 上测试,使用 BF16、CUDA Graph、greedy decoding,
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/factory.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/factory.py
index 5e0a0bf..4b0075a 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/factory.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/factory.py
@@ -1,8 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
+import json
import os
from collections.abc import Callable
+from pathlib import Path
from typing import Any
from sglang_omni.engines.omni.engine import OmniEngine
@@ -19,6 +21,20 @@ from sglang_omni.models.audio8_tts.runtime.audio8_sglang_ar import (
)
+def uses_hybrid_slow_backbone(model_path: str) -> bool:
+ """True when the checkpoint's slow AR is the Falcon-H1 Mamba hybrid.
+
+ The 0.1B preview uses ``slow_backbone: falcon_h1`` and carries the mamba_*
+ config fields; the 0.6B preview is pure attention and has neither.
+ """
+ try:
+ with open(Path(model_path) / "config.json", encoding="utf-8") as handle:
+ config = json.load(handle)
+ except OSError:
+ return False
+ return config.get("slow_backbone") == "falcon_h1" or "mamba_d_ssm" in config
+
+
def create_audio8_engine(
server_args: Any,
*,
@@ -39,9 +55,29 @@ def create_audio8_engine(
from sglang_omni.engines.omni.runtime.sglang_ar import SGLangBatchPlanner
from sglang_omni.models.audio8_tts.sglang_model import Audio8SGLangModel
+ hybrid = uses_hybrid_slow_backbone(server_args.model_path)
+ if hybrid:
+ from sglang_omni.models.audio8_tts.sglang_model_hybrid import (
+ Audio8HybridSGLangModel,
+ )
+
+ model_cls = Audio8HybridSGLangModel
+ # The eager Falcon-H1 slow backbone (Mamba + attention) is not CUDA
+ # graph capturable, and it does not consume the SGLang KV pages, so
+ # keep the scheduler's static KV fraction small.
+ setattr(server_args, "disable_" + "cuda_graph", True)
+ server_args.mem_fraction_static = min(
+ float(server_args.mem_fraction_static), 0.05
+ )
+ server_args.chunked_prefill_size = max(
+ int(server_args.chunked_prefill_size), 65536
+ )
+ else:
+ model_cls = Audio8SGLangModel
+
# Register lazily in the worker process so the adapter does not require a
# patch to SGLang-Omni's hard-coded model registry bootstrap.
- ModelRegistry.models["ArkttsModel"] = Audio8SGLangModel
+ ModelRegistry.models["ArkttsModel"] = model_cls
if server_args.attention_backend is None:
server_args.attention_backend = "fa3"
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/stages.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/stages.py
index 1393e07..1047657 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/stages.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/stages.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import base64
import importlib.util
+import inspect
import json
import logging
import os
@@ -237,11 +238,14 @@ def create_sglang_tts_engine_executor(
codes_only_ids.discard(payload.request_id)
return store_state(payload, state)
+ executor_kwargs: dict[str, Any] = {}
+ if "stream_enabled" in inspect.signature(EngineExecutor.__init__).parameters:
+ executor_kwargs["stream_enabled"] = stream_enabled
executor = EngineExecutor(
engine=engine,
request_builder=request_builder,
result_builder=result_builder,
- stream_enabled=stream_enabled,
+ **executor_kwargs,
)
def set_stream_fn(stream_fn: Any) -> None:
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/runtime/audio8_sglang_ar.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/runtime/audio8_sglang_ar.py
index 35d432d..9f1e6f3 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/runtime/audio8_sglang_ar.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/runtime/audio8_sglang_ar.py
@@ -45,6 +45,9 @@ class Audio8SGLangRequestData(SGLangARRequestData):
do_sample: bool = True
_previous_semantic_tokens: list[int] = field(default_factory=list)
_last_codebook_values: torch.Tensor | None = None
+ # Falcon-H1 hybrid slow cache (Mamba states + attention KV) used by the
+ # 0.1B path. Created at prefill, carried through decode, freed at the end.
+ _slow_cache: Any | None = None
class Audio8IterationController:
@@ -183,6 +186,13 @@ class Audio8ModelRunner:
data.req.rid,
)
+ # Hand the per-request Falcon-H1 hybrid caches to the model (0.1B path
+ # only; Audio8SGLangModel has no ``_batch_slow_caches`` attribute).
+ if hasattr(model, "_batch_slow_caches"):
+ model._batch_slow_caches = [
+ scheduled.data._slow_cache for scheduled in scheduler_output.requests
+ ]
+
def _build_outputs(self, scheduler_output: SchedulerOutput) -> dict[str, RequestOutput]:
model = self.model_worker.model_runner.model
outputs: dict[str, RequestOutput] = {}
@@ -205,6 +215,7 @@ class Audio8ModelRunner:
schedule_batch = scheduler_output.batch_data
worker_batch = schedule_batch.get_model_worker_batch()
is_prefill = schedule_batch.forward_mode.is_extend()
+ model = self.model_worker.model_runner.model
if len(scheduler_output.requests) != len(schedule_batch.reqs):
logger.warning(
"AUDIO8-ALIGN requests=%d batch_reqs=%d batch_rows=%s mode=%s",
@@ -222,6 +233,11 @@ class Audio8ModelRunner:
self._inject_reference_embeds(worker_batch, scheduler_output)
forward_batch = ForwardBatch.init_new(worker_batch, self.model_worker.model_runner)
batch_result = self.model_worker.forward_batch_generation(forward_batch)
+ if hasattr(model, "_batch_slow_caches"):
+ # Prefill seeds / decode advances each request's Falcon-H1 hybrid
+ # cache; persist it back onto the request data for the next step.
+ for index, scheduled in enumerate(scheduler_output.requests):
+ scheduled.data._slow_cache = model._batch_slow_caches[index]
if schedule_batch.is_prefill_only:
batch_result.next_token_ids = torch.zeros(
len(worker_batch.seq_lens),
@@ -230,7 +246,6 @@ class Audio8ModelRunner:
)
self.batch_planner.record_last_batch(schedule_batch)
outputs = self._build_outputs(scheduler_output)
- model = self.model_worker.model_runner.model
batch = len(scheduler_output.requests)
schedule_batch.output_ids = model._output_semantic_ids[:batch].clone()
request_ids = [request.request_id for request in scheduler_output.requests]
@@ -252,6 +267,7 @@ class Audio8ResourceManager(SGLangResourceManager):
release_kv_cache(data.req, self.tree_cache)
data._previous_semantic_tokens.clear()
data._last_codebook_values = None
+ data._slow_cache = None
if self._freed_since_compact >= 64:
self._freed_since_compact = 0
if torch.cuda.is_available():
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model_hybrid.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model_hybrid.py
new file mode 100644
index 0000000..2eb1d2a
--- /dev/null
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model_hybrid.py
@@ -0,0 +1,544 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Audio8 0.1B (Falcon-H1 hybrid) slow AR on the SGLang-Omni engine.
+
+The 0.1B preview swaps the pure-attention slow backbone for a Falcon-H1
+``Mamba + attention`` hybrid. SGLang's paged attention cannot cache Mamba
+state, so this model runs the slow backbone eagerly with a per-request
+``FalconHybridMambaAttentionDynamicCache`` (attention KV + Mamba conv/SSM
+states). The fast codebook head, semantic sampling and the vocoder path are
+shared with the 0.6B adapter.
+
+The AR runtime keeps one hybrid cache on each request
+(``Audio8SGLangRequestData._slow_cache``) and hands the current batch's caches
+to the model through ``_batch_slow_caches`` before every forward, aligned with
+the scheduler request order. Prefill runs the full prompt through the eager
+Falcon-H1 backbone and seeds the cache; each decode step runs a single token
+through the cache. No SGLang KV pages are consumed, so CUDA graphs are disabled
+for this path (see ``factory.create_audio8_engine``).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from typing import Any, Iterable, Optional, Tuple
+
+import torch
+import torch.nn.functional as F
+from sglang.srt.layers.logits_processor import LogitsProcessorOutput
+from torch import Tensor, nn
+
+from sglang_omni.vendor.sglang.core import ForwardBatch
+
+from sglang_omni.models.audio8_tts.sglang_model import (
+ FastDecoderLayer,
+ FastRMSNorm,
+ _default_weight_loader,
+ _rope,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _build_falcon_config(config: Any) -> Any:
+ """Translate an ArkttsConfig into the Falcon-H1 config used by the model.
+
+ Mirrors ``ArkttsModel._build_falcon_config`` in the 0.1B checkpoint's
+ ``modeling_arktts.py``.
+ """
+ from transformers.models.falcon_h1.configuration_falcon_h1 import FalconH1Config
+
+ return FalconH1Config(
+ vocab_size=config.vocab_size,
+ hidden_size=config.dim,
+ intermediate_size=config.intermediate_size,
+ num_hidden_layers=config.n_layer,
+ num_attention_heads=config.n_head,
+ num_key_value_heads=config.n_local_heads,
+ head_dim=config.head_dim,
+ hidden_act=config.hidden_act,
+ rms_norm_eps=config.norm_eps,
+ rope_theta=config.rope_base,
+ max_position_embeddings=config.max_seq_len,
+ attention_bias=config.attention_bias,
+ attention_dropout=config.attention_dropout,
+ attention_in_multiplier=config.attention_in_multiplier,
+ attention_out_multiplier=config.attention_out_multiplier,
+ key_multiplier=config.key_multiplier,
+ embedding_multiplier=config.embedding_multiplier,
+ lm_head_multiplier=config.lm_head_multiplier,
+ expansion_factor=config.expansion_factor,
+ mlp_bias=config.mlp_bias,
+ mlp_multipliers=config.mlp_multipliers,
+ mamba_chunk_size=config.mamba_chunk_size,
+ mamba_conv_bias=config.mamba_conv_bias,
+ mamba_d_conv=config.mamba_d_conv,
+ mamba_d_head=config.mamba_d_head,
+ mamba_d_ssm=config.mamba_d_ssm,
+ mamba_d_state=config.mamba_d_state,
+ mamba_expand=config.mamba_expand,
+ mamba_n_groups=config.mamba_n_groups,
+ mamba_n_heads=config.mamba_n_heads,
+ mamba_norm_before_gate=config.mamba_norm_before_gate,
+ mamba_proj_bias=config.mamba_proj_bias,
+ mamba_rms_norm=config.mamba_rms_norm,
+ mamba_use_mlp=config.mamba_use_mlp,
+ projectors_bias=config.projectors_bias,
+ ssm_in_multiplier=config.ssm_in_multiplier,
+ ssm_multipliers=config.ssm_multipliers,
+ ssm_out_multiplier=config.ssm_out_multiplier,
+ time_step_floor=config.time_step_floor,
+ time_step_max=config.time_step_max,
+ time_step_min=config.time_step_min,
+ time_step_rank=config.time_step_rank,
+ initializer_range=config.initializer_range,
+ use_cache=config.use_cache,
+ tie_word_embeddings=config.tie_word_embeddings,
+ pad_token_id=config.pad_token_id,
+ eos_token_id=config.eos_token_id,
+ bos_token_id=config.bos_token_id,
+ )
+
+
+class Audio8HybridSGLangModel(nn.Module):
+ """Eager Falcon-H1 slow backbone plus Audio8's fixed-length fast head.
+
+ The slow backbone is the checkpoint's ``FalconH1Model`` (Mamba + attention)
+ run eagerly with one ``FalconHybridMambaAttentionDynamicCache`` per request.
+ The fast AR branch, semantic sampling and codebook embeddings mirror the
+ existing ``Audio8SGLangModel``.
+ """
+
+ def __init__(self, config: Any, quant_config: Any = None) -> None:
+ super().__init__()
+ del quant_config
+ self.config = config
+ self.vocab_size = int(config.vocab_size)
+ self.hidden_size = int(config.dim)
+ self.num_layers = int(config.n_layer)
+ self.tie_word_embeddings = bool(config.tie_word_embeddings)
+
+ from transformers.models.falcon_h1.modeling_falcon_h1 import FalconH1Model
+
+ self.slow = FalconH1Model(_build_falcon_config(config))
+ self.slow.eval()
+
+ self.codebook_embeddings = nn.Embedding(
+ config.codebook_size * config.num_codebooks,
+ config.dim,
+ )
+ self.fast_project_in = (
+ nn.Linear(config.dim, config.fast_dim)
+ if config.fast_dim != config.dim
+ else nn.Identity()
+ )
+ self.fast_embeddings = nn.Embedding(config.codebook_size, config.fast_dim)
+ self.fast_layers = nn.ModuleList(
+ [FastDecoderLayer(config) for _ in range(config.n_fast_layer)]
+ )
+ self.fast_norm = FastRMSNorm(config.fast_dim, config.norm_eps)
+ self.fast_output = nn.Linear(config.fast_dim, config.codebook_size, bias=False)
+ # Compact slow-AR head: 4096 semantic tokens + 1 EOS, matching the
+ # checkpoint's ``semantic_output`` layout (index codebook_size = EOS).
+ self.semantic_output = nn.Linear(
+ config.dim, config.codebook_size + 1, bias=False
+ )
+ self._decode_ready = False
+ # Per-request Falcon-H1 hybrid caches; set by the AR runtime before
+ # every forward (aligned with the scheduler request order).
+ self._batch_slow_caches: list[Any] = []
+
+ @property
+ def embed_tokens(self) -> nn.Module:
+ return self.slow.embed_tokens
+
+ def get_embed_tokens(self) -> nn.Module:
+ return self.slow.embed_tokens
+
+ # ------------------------------------------------------------------
+ # Decode buffers (shared layout with Audio8SGLangModel.setup_audio8_decode)
+ # ------------------------------------------------------------------
+
+ def setup_audio8_decode(self, max_batch_size: int) -> None:
+ device = self.slow.embed_tokens.weight.device
+ config = self.config
+ self.register_buffer(
+ "_codebook_offsets",
+ torch.arange(config.num_codebooks, device=device, dtype=torch.long)
+ * config.codebook_size,
+ persistent=False,
+ )
+ self.register_buffer(
+ "_vq_codes",
+ torch.zeros(
+ max_batch_size, config.num_codebooks, device=device, dtype=torch.long
+ ),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_vq_mask",
+ torch.zeros(max_batch_size, device=device, dtype=torch.bool),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_output_codes",
+ torch.zeros(
+ max_batch_size,
+ config.num_codebooks + 1,
+ device=device,
+ dtype=torch.long,
+ ),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_output_semantic_ids",
+ torch.zeros(max_batch_size, device=device, dtype=torch.long),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_temperature",
+ torch.full((max_batch_size,), 0.8, device=device),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_top_p",
+ torch.full((max_batch_size,), 0.95, device=device),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_top_k",
+ torch.full((max_batch_size,), 50, device=device, dtype=torch.long),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_do_sample",
+ torch.ones(max_batch_size, device=device, dtype=torch.bool),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_previous_semantic",
+ torch.zeros(
+ max_batch_size,
+ config.ras_window_size,
+ device=device,
+ dtype=torch.long,
+ ),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_previous_valid",
+ torch.zeros(
+ max_batch_size,
+ config.ras_window_size,
+ device=device,
+ dtype=torch.bool,
+ ),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_fast_rope",
+ _rope(
+ config.num_codebooks,
+ config.fast_head_dim,
+ config.rope_base,
+ device,
+ ),
+ persistent=False,
+ )
+ self.register_buffer(
+ "_audio8_fast_position",
+ torch.zeros(1, device=device, dtype=torch.long),
+ persistent=False,
+ )
+ for layer in self.fast_layers:
+ layer.feed_forward.fuse_gate_up()
+ layer.attention.setup_audio8_cache(
+ max_batch_size,
+ config.num_codebooks + 1,
+ device=device,
+ dtype=self.slow.embed_tokens.weight.dtype,
+ )
+ self._decode_ready = True
+
+ # ------------------------------------------------------------------
+ # Fast AR (shared with Audio8SGLangModel)
+ # ------------------------------------------------------------------
+
+ def _embed_decode(self, input_ids: Tensor) -> Tensor:
+ hidden = self.slow.embed_tokens(input_ids)
+ batch = hidden.shape[0]
+ codes = self._vq_codes[:batch] + self._codebook_offsets[None]
+ codebook_sum = self.codebook_embeddings(codes).sum(dim=1).to(hidden.dtype)
+ return torch.where(
+ self._vq_mask[:batch, None],
+ hidden + codebook_sum,
+ hidden,
+ )
+
+ @staticmethod
+ def _sample(
+ scores: Tensor,
+ temperature: Tensor,
+ top_p: Tensor,
+ top_k: Tensor,
+ do_sample: Tensor,
+ ) -> Tensor:
+ if os.getenv("AUDIO8_TTS_GREEDY_FASTPATH", "0") == "1":
+ return scores.argmax(dim=-1)
+ sorted_scores, sorted_indices = torch.sort(scores, descending=True, dim=-1)
+ cumulative = torch.softmax(sorted_scores, dim=-1).cumsum(dim=-1)
+ positions = torch.arange(scores.shape[-1], device=scores.device)[None]
+ remove_sorted = (cumulative > top_p[:, None]) | (positions >= top_k[:, None])
+ remove_sorted[:, 0] = False
+ remove = torch.zeros_like(remove_sorted).scatter(1, sorted_indices, remove_sorted)
+ filtered = scores.masked_fill(remove, -float("inf"))
+ filtered = filtered / temperature[:, None].clamp_min(1e-5)
+ greedy = filtered.argmax(dim=-1)
+ probabilities = torch.softmax(filtered, dim=-1)
+ random = torch.rand_like(probabilities).clamp_min(torch.finfo(probabilities.dtype).tiny)
+ sampled = torch.argmax(probabilities / (-torch.log(random)), dim=-1)
+ return torch.where(do_sample, sampled, greedy)
+
+ def _sample_semantic(self, logits: Tensor) -> Tensor:
+ """Sample compact semantic logits in the checkpoint's layout.
+
+ ``semantic_output`` emits ``[codebook_size + 1]`` logits where indices
+ ``0..codebook_size-1`` are semantic tokens (offset by
+ ``semantic_begin_id``) and index ``codebook_size`` is the EOS token.
+ """
+ batch = logits.shape[0]
+ scores = logits.float()
+ normal_index = self._sample(
+ scores,
+ self._temperature[:batch],
+ self._top_p[:batch],
+ self._top_k[:batch],
+ self._do_sample[:batch],
+ )
+ ras_temperature = torch.full_like(
+ self._temperature[:batch], self.config.ras_temperature
+ )
+ ras_top_p = torch.full_like(self._top_p[:batch], self.config.ras_top_p)
+ high_index = self._sample(
+ scores,
+ ras_temperature,
+ ras_top_p,
+ self._top_k[:batch],
+ self._do_sample[:batch],
+ )
+ eos_idx = self.config.codebook_size
+ begin = self.config.semantic_begin_id
+ normal = torch.where(
+ normal_index == eos_idx,
+ self.config.eos_token_id,
+ begin + normal_index,
+ )
+ high = torch.where(
+ high_index == eos_idx,
+ self.config.eos_token_id,
+ begin + high_index,
+ )
+ repeated = (
+ (self._previous_semantic[:batch] == normal[:, None])
+ & self._previous_valid[:batch]
+ ).any(dim=1)
+ is_semantic = (normal >= begin) & (normal <= self.config.semantic_end_id)
+ return torch.where(repeated & is_semantic, high, normal)
+
+ def _semantic_logits(self, hidden_states: Tensor) -> Tensor:
+ return self.semantic_output(hidden_states)
+
+ def _clear_audio8_fast_caches(self) -> None:
+ for layer in self.fast_layers:
+ layer.attention.clear_audio8_cache()
+
+ def _run_audio8_fast_position(self, hidden: Tensor, position: int) -> Tensor:
+ batch = hidden.shape[0]
+ self._audio8_fast_position.fill_(position)
+ rope_values = self._fast_rope[self._audio8_fast_position]
+ cache_positions = self._audio8_fast_position.expand(batch).to(torch.int32)
+ for layer in self.fast_layers:
+ hidden = layer.forward_audio8_cached(
+ hidden,
+ rope_values,
+ cache_positions,
+ )
+ return self.fast_output(self.fast_norm(hidden))[:, -1]
+
+ @torch.no_grad()
+ def _decode_codebooks(self, logits: Tensor, slow_hidden: Tensor) -> None:
+ batch = logits.shape[0]
+ semantic = self._sample_semantic(logits)
+ current = (semantic - self.config.semantic_begin_id).clamp(
+ 0, self.config.codebook_size - 1
+ )
+ self._output_codes[:batch, 0] = semantic
+ self._output_codes[:batch, 1] = current
+ self._clear_audio8_fast_caches()
+ fast_hidden = self.fast_project_in(slow_hidden).unsqueeze(1)
+ self._run_audio8_fast_position(fast_hidden, 0)
+ for position in range(1, self.config.num_codebooks):
+ fast_hidden = self.fast_embeddings(current).unsqueeze(1)
+ scores = self._run_audio8_fast_position(fast_hidden, position).float()
+ current = self._sample(
+ scores,
+ self._temperature[:batch],
+ self._top_p[:batch],
+ self._top_k[:batch],
+ self._do_sample[:batch],
+ )
+ self._output_codes[:batch, position + 1] = current
+ self._output_semantic_ids[:batch] = semantic
+
+ # ------------------------------------------------------------------
+ # Slow AR (eager Falcon-H1 hybrid)
+ # ------------------------------------------------------------------
+
+ def _new_slow_cache(self, device: torch.device, dtype: torch.dtype) -> Any:
+ from transformers.models.falcon_h1.modeling_falcon_h1 import (
+ FalconHybridMambaAttentionDynamicCache,
+ )
+
+ falcon_config = _build_falcon_config(self.config)
+ return FalconHybridMambaAttentionDynamicCache(
+ falcon_config,
+ 1,
+ dtype,
+ devices=[
+ self.slow.layers[i].mamba.conv1d.weight.device
+ for i in range(falcon_config.num_hidden_layers)
+ ],
+ )
+
+ def _slow_prefill(
+ self,
+ input_ids: Tensor,
+ input_embeds: Optional[Tensor],
+ forward_batch: ForwardBatch,
+ ) -> Tensor:
+ """Run the full prompt through Falcon-H1 and seed per-request caches."""
+ seq_lens = forward_batch.extend_seq_lens
+ batch = len(self._batch_slow_caches)
+ starts = torch.cumsum(
+ torch.cat(
+ (
+ torch.zeros(1, dtype=torch.long, device=seq_lens.device),
+ seq_lens[:-1],
+ )
+ ),
+ dim=0,
+ )
+ multiplier = self.slow.embedding_multiplier
+ hidden_list: list[Tensor] = []
+ for index in range(batch):
+ length = int(seq_lens[index])
+ start = int(starts[index])
+ cache = self._batch_slow_caches[index]
+ if cache is None:
+ cache = self._new_slow_cache(
+ self.slow.embed_tokens.weight.device,
+ self.slow.embed_tokens.weight.dtype,
+ )
+ positions = torch.arange(length, device=input_ids.device)
+ attention_mask = torch.ones(
+ 1, length, device=input_ids.device, dtype=torch.long
+ )
+ if input_embeds is not None:
+ # ``_inject_reference_embeds`` provides embeddings without the
+ # Falcon-H1 embedding multiplier, so apply it here.
+ embeds = input_embeds[start : start + length].unsqueeze(0) * multiplier
+ outputs = self.slow(
+ inputs_embeds=embeds,
+ attention_mask=attention_mask,
+ position_ids=positions.unsqueeze(0),
+ past_key_values=cache,
+ use_cache=True,
+ cache_position=positions,
+ )
+ else:
+ tokens = input_ids[start : start + length].unsqueeze(0)
+ outputs = self.slow(
+ input_ids=tokens,
+ attention_mask=attention_mask,
+ position_ids=positions.unsqueeze(0),
+ past_key_values=cache,
+ use_cache=True,
+ cache_position=positions,
+ )
+ self._batch_slow_caches[index] = outputs.past_key_values
+ hidden_list.append(outputs.last_hidden_state[:, -1])
+ return torch.cat(hidden_list, dim=0)
+
+ def _slow_decode(self, input_ids: Tensor, forward_batch: ForwardBatch) -> Tensor:
+ """Run one cached token per request through Falcon-H1."""
+ del forward_batch
+ embeds = self._embed_decode(input_ids)
+ embeds = embeds * self.slow.embedding_multiplier
+ hidden_list: list[Tensor] = []
+ batch = len(self._batch_slow_caches)
+ for index in range(batch):
+ cache = self._batch_slow_caches[index]
+ if cache is None:
+ raise RuntimeError(
+ "Audio8 hybrid slow cache is missing for a decode request"
+ )
+ position = cache.get_seq_length()
+ position_t = torch.tensor(
+ [position], device=input_ids.device, dtype=torch.long
+ )
+ attention_mask = torch.ones(
+ 1, position + 1, device=input_ids.device, dtype=torch.long
+ )
+ outputs = self.slow(
+ inputs_embeds=embeds[index : index + 1].unsqueeze(1),
+ attention_mask=attention_mask,
+ position_ids=position_t.unsqueeze(0),
+ past_key_values=cache,
+ use_cache=True,
+ cache_position=position_t,
+ )
+ self._batch_slow_caches[index] = outputs.past_key_values
+ hidden_list.append(outputs.last_hidden_state[:, -1])
+ return torch.cat(hidden_list, dim=0)
+
+ # ------------------------------------------------------------------
+ # SGLang model interface
+ # ------------------------------------------------------------------
+
+ @torch.inference_mode()
+ def forward(
+ self,
+ input_ids: Tensor,
+ positions: Tensor,
+ forward_batch: ForwardBatch,
+ input_embeds: Optional[Tensor] = None,
+ ) -> LogitsProcessorOutput:
+ del positions
+ if input_embeds is None and forward_batch.input_embeds is not None:
+ input_embeds = forward_batch.input_embeds
+ if forward_batch.forward_mode.is_extend():
+ hidden_states = self._slow_prefill(input_ids, input_embeds, forward_batch)
+ else:
+ hidden_states = self._slow_decode(input_ids, forward_batch)
+ logits = self._semantic_logits(hidden_states)
+ if self._decode_ready:
+ self._decode_codebooks(logits, hidden_states)
+ return LogitsProcessorOutput(
+ next_token_logits=logits,
+ hidden_states=hidden_states,
+ )
+
+ def load_weights(self, weights: Iterable[Tuple[str, Tensor]]) -> None:
+ params = dict(self.named_parameters())
+ for name, loaded_weight in weights:
+ if name in {"freqs_cis", "fast_freqs_cis"}:
+ continue
+ target = params.get(name)
+ if target is None:
+ logger.debug("Skipping Audio8 hybrid weight: %s", name)
+ continue
+ loader = getattr(target, "weight_loader", _default_weight_loader)
+ loader(target, loaded_weight)
+
+
+EntryClass = Audio8HybridSGLangModel
diff --git a/sglang_omni/configs/audio8_tts_0_1b.yaml b/sglang_omni/configs/audio8_tts_0_1b.yaml
new file mode 100644
index 0000000..22c4129
--- /dev/null
+++ b/sglang_omni/configs/audio8_tts_0_1b.yaml
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: Apache-2.0
+config_cls: Audio8TTSPipelineConfig
+name: audio8-tts-0.1b
+model_path: /models/Audio8-TTS-Preview-0.1b
+relay_backend: shm
+entry_stage: preprocessing
+stages:
+ - name: preprocessing
+ num_workers: 1
+ executor:
+ factory: sglang_omni.models.audio8_tts.pipeline.stages.create_preprocessing_executor
+ args:
+ device: cuda:0
+ get_next: sglang_omni.models.audio8_tts.pipeline.next_stage.preprocessing_next
+ relay:
+ device: cpu
+ - name: tts_engine
+ num_workers: 1
+ executor:
+ factory: sglang_omni.models.audio8_tts.pipeline.stages.create_sglang_tts_engine_executor
+ args:
+ device: cuda:0
+ max_new_tokens: 1024
+ get_next: sglang_omni.models.audio8_tts.pipeline.next_stage.tts_engine_next
+ relay:
+ device: cuda
+ stream_to:
+ - to_stage: vocoder
+ - name: vocoder
+ num_workers: 1
+ executor:
+ factory: sglang_omni.models.audio8_tts.pipeline.stages.create_vocoder_executor
+ args:
+ device: cuda:0
+ get_next: sglang_omni.models.audio8_tts.pipeline.next_stage.vocoder_next
+ relay:
+ device: cpu