Skip to content

SOTA-Class TTS at Compact Scale

Python

Fix SGLang Omni memory leak and make streaming optional

linux295650-ux89c286480941
diff --git a/README.md b/README.md
index 2f1162e..93f3104 100644
--- a/README.md
+++ b/README.md
@@ -304,6 +304,13 @@ of decoder context and a one-frame boundary guard. Override these values with
`AUDIO8_TTS_STREAM_CHUNK_FRAMES`, `AUDIO8_TTS_STREAM_CONTEXT_FRAMES`, and
`AUDIO8_TTS_STREAM_GUARD_FRAMES`.
+Streaming is a server-side opt-in. Start the service with
+`AUDIO8_TTS_STREAM_ENABLED=1` to enable SSE streaming; the default is off, and
+requests are answered with the complete audio after generation finishes
+(a request-level `"stream": true` is then ignored). Non-streaming remains the
+default for maximum throughput and stable memory usage. `response_format` of
+`codes`/`codec`/`npy` always returns codec codes without streaming.
+
Run the smoke test to verify a deployment:
```bash
diff --git a/README_zh.md b/README_zh.md
index 61a3a1e..640f301 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -283,6 +283,11 @@ curl -sS --fail-with-body \
guard。可通过 `AUDIO8_TTS_STREAM_CHUNK_FRAMES`、
`AUDIO8_TTS_STREAM_CONTEXT_FRAMES` 和 `AUDIO8_TTS_STREAM_GUARD_FRAMES` 调整。
+流式输出是服务端可选项:启动服务时设置 `AUDIO8_TTS_STREAM_ENABLED=1` 才会启用 SSE
+流式;默认关闭,请求会在生成完成后一次性返回完整音频(请求中的 `"stream": true`
+此时会被忽略)。默认非流式以获得更高的吞吐和稳定的显存占用。
+`response_format` 为 `codes`/`codec`/`npy` 时始终非流式,直接返回 codec codes。
+
运行以下 smoke test 可以验证部署:
```bash
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/config.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/config.py
index 20e20fe..003ade6 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/config.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/config.py
@@ -1,7 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
-from typing import ClassVar
+import os
+from typing import Any, ClassVar
from sglang_omni.config import (
ExecutorConfig,
@@ -50,5 +51,12 @@ class Audio8TTSPipelineConfig(PipelineConfig):
),
]
+ def model_post_init(self, __context: Any = None) -> None:
+ super().model_post_init(__context)
+ if os.getenv("AUDIO8_TTS_STREAM_ENABLED", "0") != "1":
+ # Default to non-streaming: do not wire per-step vocoder queues.
+ for stage in self.stages:
+ stage.stream_to = []
+
EntryClass = Audio8TTSPipelineConfig
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 a2e8b87..5e0a0bf 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/factory.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/factory.py
@@ -86,7 +86,7 @@ def create_audio8_engine(
def stream_adapter(request: Any, output: Any) -> Any:
if output.data is None:
return None
- codes = output.data.codes.clone()
+ codes = output.data.codes
if stream_fn is not None:
stream_fn(request.request_id, codes)
return codes
@@ -115,14 +115,22 @@ def create_audio8_engine(
def make_server_args(model_path: str) -> Any:
from sglang.srt.server_args import ServerArgs
+ max_running_requests = int(
+ os.getenv("AUDIO8_TTS_MAX_RUNNING_REQUESTS", "32")
+ )
+ max_total_tokens_env = os.getenv("AUDIO8_TTS_MAX_TOTAL_NUM_TOKENS")
+ max_total_tokens = (
+ int(max_total_tokens_env) if max_total_tokens_env is not None else None
+ )
server_args = ServerArgs(
model_path=model_path,
tp_size=1,
dtype="bfloat16",
trust_remote_code=True,
mem_fraction_static=float(os.getenv("AUDIO8_TTS_MEM_FRACTION_STATIC", "0.2")),
- chunked_prefill_size=int(os.getenv("AUDIO8_TTS_CHUNKED_PREFILL_SIZE", "2048")),
- max_running_requests=int(os.getenv("AUDIO8_TTS_MAX_RUNNING_REQUESTS", "32")),
+ max_total_tokens=max_total_tokens,
+ chunked_prefill_size=int(os.getenv("AUDIO8_TTS_CHUNKED_PREFILL_SIZE", "8192")),
+ max_running_requests=max_running_requests,
disable_radix_cache=os.getenv("AUDIO8_TTS_DISABLE_RADIX_CACHE", "1") == "1",
)
setattr(
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/io.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/io.py
index 0b3a5e6..e9d6de3 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/io.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/io.py
@@ -24,6 +24,7 @@ class Audio8TTSState:
completion_tokens: int = 0
audio_samples: Any | None = None
sample_rate: int = 44100
+ response_format: str = "wav"
@staticmethod
def _to_list(value: Any) -> Any:
@@ -50,6 +51,7 @@ class Audio8TTSState:
"completion_tokens": self.completion_tokens,
"audio_samples": self._to_list(self.audio_samples),
"sample_rate": self.sample_rate,
+ "response_format": self.response_format,
}
return {key: value for key, value in data.items() if value is not None}
@@ -79,4 +81,5 @@ class Audio8TTSState:
completion_tokens=int(data.get("completion_tokens", 0)),
audio_samples=data.get("audio_samples"),
sample_rate=int(data.get("sample_rate", 44100)),
+ response_format=str(data.get("response_format", "wav")),
)
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/engine_io.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/engine_io.py
index 704c780..5fa0516 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/engine_io.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/engine_io.py
@@ -59,6 +59,7 @@ def apply_tts_result(state: Audio8TTSState, result: Audio8SGLangRequestData) ->
all_codes = torch.cat(result.output_codes, dim=1)
state.output_codes = all_codes[1:]
state.completion_tokens = int(all_codes.shape[1])
+ result.output_codes.clear()
else:
state.output_codes = None
state.prompt_tokens = len(result.input_ids) if result.input_ids is not None else 0
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/next_stage.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/next_stage.py
index 3ce60c0..aab37ce 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/next_stage.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/next_stage.py
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
from typing import Any
+from sglang_omni.models.audio8_tts.pipeline.state_io import load_state
+
def preprocessing_next(request_id: str, output: Any) -> str:
del request_id, output
@@ -8,7 +10,10 @@ def preprocessing_next(request_id: str, output: Any) -> str:
def tts_engine_next(request_id: str, output: Any) -> str:
- del request_id, output
+ del request_id
+ state = load_state(output)
+ if state.response_format in {"codes", "codec", "npy"}:
+ return None
return "vocoder"
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 dcb7551..1393e07 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
@@ -146,6 +146,8 @@ def create_preprocessing_executor(
def preprocess(payload: StagePayload) -> StagePayload:
inputs = payload.request.inputs or {}
params = payload.request.params or {}
+ metadata = payload.request.metadata or {}
+ tts_params = metadata.get("tts_params") or {}
if isinstance(inputs, str):
inputs = {"text": inputs}
references: list[Reference] | None = None
@@ -178,6 +180,7 @@ def create_preprocessing_executor(
top_k=int(params.get("top_k", 50)),
do_sample=float(params.get("temperature", 0.8)) > 0,
sample_rate=config.codec_sample_rate,
+ response_format=str(tts_params.get("response_format", "wav")).lower(),
)
return store_state(payload, state)
@@ -200,11 +203,19 @@ def create_sglang_tts_engine_executor(
server_args = make_server_args(model_path)
gpu_id = int(device.split(":")[-1]) if ":" in device else 0
enqueue_fn_holder: dict[str, Any] = {}
+ codes_only_ids: set[str] = set()
+ stream_enabled = os.getenv("AUDIO8_TTS_STREAM_ENABLED", "0") == "1"
def enqueue_stream(request_id: str, codes: torch.Tensor) -> None:
+ if not stream_enabled:
+ return
+ if request_id in codes_only_ids:
+ return
enqueue_fn = enqueue_fn_holder.get("fn")
if enqueue_fn is not None:
- enqueue_fn(request_id, codes, target_stage="vocoder")
+ # The model overwrites its persistent output buffer on the next
+ # decode step, so the vocoder must receive its own copy.
+ enqueue_fn(request_id, codes.clone(), target_stage="vocoder")
engine = create_audio8_engine(
server_args,
@@ -215,17 +226,22 @@ def create_sglang_tts_engine_executor(
)
def request_builder(payload: StagePayload):
- return build_tts_request(load_state(payload), tokenizer, payload.request_id)
+ state = load_state(payload)
+ if state.response_format in {"codes", "codec", "npy"}:
+ codes_only_ids.add(payload.request_id)
+ return build_tts_request(state, tokenizer, payload.request_id)
def result_builder(payload: StagePayload, result: Any) -> StagePayload:
state = load_state(payload)
apply_tts_result(state, result)
+ codes_only_ids.discard(payload.request_id)
return store_state(payload, state)
executor = EngineExecutor(
engine=engine,
request_builder=request_builder,
result_builder=result_builder,
+ stream_enabled=stream_enabled,
)
def set_stream_fn(stream_fn: Any) -> None:
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/streaming_vocoder.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/streaming_vocoder.py
index e6cf7f1..82a4935 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/streaming_vocoder.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/pipeline/streaming_vocoder.py
@@ -8,7 +8,7 @@ import numpy as np
import torch
from sglang_omni.executors import Executor
-from sglang_omni.models.audio8_tts.pipeline.state_io import load_state
+from sglang_omni.models.audio8_tts.pipeline.state_io import load_state, store_state
from sglang_omni.proto import StagePayload
@@ -46,10 +46,40 @@ class Audio8StreamingVocoderExecutor(Executor):
if request_id in self._aborted:
return
self._output_queues[request_id] = asyncio.Queue()
- task = asyncio.create_task(self._run_request(payload))
+ if self._stream_queue is None:
+ task = asyncio.create_task(self._run_batch(payload))
+ else:
+ task = asyncio.create_task(self._run_request(payload))
self._tasks[request_id] = task
task.add_done_callback(lambda _task: self._done.put_nowait(request_id))
+ async def _run_batch(self, payload: StagePayload) -> StagePayload:
+ """Non-streaming decode: decode the complete output_codes at once."""
+ state = load_state(payload)
+ codes = state.output_codes
+ if codes is None:
+ raise ValueError("Audio8 generation produced no codec frames")
+ codes = torch.as_tensor(codes, device=self._device, dtype=torch.long)
+ if codes.ndim != 2 or codes.shape[0] != self._num_codebooks or codes.shape[1] == 0:
+ raise ValueError(
+ f"unexpected Audio8 codes shape {tuple(codes.shape)}, "
+ f"expected [{self._num_codebooks}, T>0]"
+ )
+ with torch.inference_mode():
+ audio = self._codec.decode(codes.unsqueeze(0))[0, 0]
+ arr = audio.detach().float().cpu().numpy().astype(np.float32, copy=False)
+ self._output_queues.pop(payload.request_id, None)
+ payload.data.update(
+ {
+ "audio_waveform": arr.tobytes(),
+ "audio_waveform_shape": list(arr.shape),
+ "audio_waveform_dtype": "float32",
+ "sample_rate": self._sample_rate,
+ "modality": "audio",
+ }
+ )
+ return payload
+
async def get_result(self) -> StagePayload:
while True:
request_id = await self._done.get()
@@ -123,7 +153,8 @@ class Audio8StreamingVocoderExecutor(Executor):
await output_queue.put(self._audio_payload(chunk))
if not frames:
- raise ValueError("Audio8 generation produced no codec frames")
+ await output_queue.put(None)
+ return store_state(payload, state)
tail, absolute_start = await self._decode_stream_window(frames)
begin = max(0, emitted_samples - absolute_start)
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 a6e036d..35d432d 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
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
+import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
@@ -22,6 +23,8 @@ from sglang_omni.engines.omni.types import (
if TYPE_CHECKING:
from sglang_omni.engines.ar.sglang_backend.model_worker import ModelWorker
+logger = logging.getLogger(__name__)
+
@dataclass
class Audio8StepOutput:
@@ -73,6 +76,8 @@ class Audio8IterationController:
data: Audio8SGLangRequestData = request.data
if data.req.is_chunked > 0:
return False
+ if output.data is None:
+ return False
semantic = int(output.data.codes[0, -1].item())
if semantic == self.eos_token_id:
return True
@@ -100,9 +105,9 @@ class Audio8ModelRunner:
if data.vq_mask_tokens is not None and data.vq_parts:
mask = data.vq_mask_tokens.to(device=device, dtype=torch.bool).flatten()
expected_length = prefix_length + request_length
- if mask.numel() != expected_length:
+ if expected_length > mask.numel():
raise ValueError(
- f"Audio8 reference mask length {mask.numel()} != request length {expected_length}"
+ f"Audio8 reference mask length {mask.numel()} < request span {expected_length}"
)
mask_slice = mask[prefix_length : prefix_length + request_length]
parts = [part.to(device=device, dtype=torch.long).T for part in data.vq_parts]
@@ -167,6 +172,16 @@ class Audio8ModelRunner:
and bool(model._vq_mask[index].item())
):
model._vq_codes[index].copy_(data._last_codebook_values)
+ elif (
+ not is_prefill
+ and data._last_codebook_values is None
+ and bool(model._vq_mask[index].item())
+ ):
+ logger.warning(
+ "AUDIO8-STALE-VQ index=%d rid=%s mask=True last_codebook=None",
+ index,
+ data.req.rid,
+ )
def _build_outputs(self, scheduler_output: SchedulerOutput) -> dict[str, RequestOutput]:
model = self.model_worker.model_runner.model
@@ -190,6 +205,14 @@ class Audio8ModelRunner:
schedule_batch = scheduler_output.batch_data
worker_batch = schedule_batch.get_model_worker_batch()
is_prefill = schedule_batch.forward_mode.is_extend()
+ if len(scheduler_output.requests) != len(schedule_batch.reqs):
+ logger.warning(
+ "AUDIO8-ALIGN requests=%d batch_reqs=%d batch_rows=%s mode=%s",
+ len(scheduler_output.requests),
+ len(schedule_batch.reqs),
+ tuple(worker_batch.input_ids.shape),
+ schedule_batch.forward_mode,
+ )
self._update_runtime_buffers(
worker_batch,
scheduler_output,
@@ -219,8 +242,24 @@ class Audio8ModelRunner:
class Audio8ResourceManager(SGLangResourceManager):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._freed_since_compact = 0
+
def free(self, request: SchedulerRequest) -> None:
data: Audio8SGLangRequestData = request.data
+ self._freed_since_compact += 1
release_kv_cache(data.req, self.tree_cache)
data._previous_semantic_tokens.clear()
data._last_codebook_values = None
+ if self._freed_since_compact >= 64:
+ self._freed_since_compact = 0
+ if torch.cuda.is_available():
+ allocated = torch.cuda.memory_allocated()
+ reserved = torch.cuda.memory_reserved()
+ logger.info(
+ "Audio8 memory: allocated=%.2f GB reserved=%.2f GB",
+ allocated / 1024**3,
+ reserved / 1024**3,
+ )
+ torch.cuda.empty_cache()
diff --git a/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model.py b/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model.py
index 502d0e9..4df4f7c 100644
--- a/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model.py
+++ b/sglang_omni/adapter/sglang_omni/models/audio8_tts/sglang_model.py
@@ -722,6 +722,7 @@ class Audio8SGLangModel(nn.Module):
self._output_codes[:batch, position + 1] = current
self._output_semantic_ids[:batch] = semantic
+ @torch.inference_mode()
def forward(
self,
input_ids: Tensor,