diff --git a/README.md b/README.md index 2e28d2c..02d1376 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,10 @@ tts = Stackvox(voice="af_bella") tts.speak("First line") tts.speak("Faster", speed=1.2) +# Cap ONNX Runtime's thread pools — it otherwise sizes them from the host's core +# count, which oversubscribes inside a container with a smaller CPU quota. +tts = Stackvox(threads=4) + # Non-blocking playback. tts.speak("async", blocking=False) tts.stop() diff --git a/pyproject.toml b/pyproject.toml index 9a9162a..d5c33df 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,7 @@ classifiers = [ ] dependencies = [ "kokoro-onnx>=0.4.0", + "onnxruntime>=1.20.1", "soundfile>=0.12.1", "sounddevice>=0.4.6", "numpy>=1.24", @@ -124,7 +125,7 @@ disallow_untyped_defs = true [[tool.mypy.overrides]] # Third-party deps without inline type stubs (or, for `tomli`, a 3.10-only # fallback that's not installed on the typechecker's Python). -module = ["kokoro_onnx", "sounddevice", "soundfile", "tomli"] +module = ["kokoro_onnx", "onnxruntime", "sounddevice", "soundfile", "tomli"] ignore_missing_imports = true [[tool.mypy.overrides]] diff --git a/stackvox/engine.py b/stackvox/engine.py index cc15433..295727c 100644 --- a/stackvox/engine.py +++ b/stackvox/engine.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import os import queue import re import sys @@ -12,6 +13,7 @@ from pathlib import Path import numpy as np +import onnxruntime as ort import sounddevice as sd from kokoro_onnx import Kokoro @@ -79,6 +81,50 @@ def _ensure_models(cache_dir: Path) -> tuple[Path, Path]: return model_path, voices_path +def _onnx_providers() -> list[str]: + """Pick execution providers the way ``Kokoro.__init__`` would. + + ``Kokoro.from_session`` takes the session exactly as handed to it, so a + session we build ourselves has to make the provider choice that constructing + ``Kokoro`` directly would have made. Otherwise asking for a thread cap would + also silently change which provider runs the model. kokoro-onnx additionally + probes for its GPU extra, but it does so with ``find_spec("onnxruntime-gpu")`` + — a distribution name, not an importable module — so that branch never fires + and there is nothing to mirror. ``ONNX_PROVIDER`` is the knob that works. + """ + env_provider = os.getenv("ONNX_PROVIDER") + return [env_provider] if env_provider else ["CPUExecutionProvider"] + + +def _load_kokoro( + model_path: Path, + voices_path: Path, + threads: int | None, + session_options: ort.SessionOptions | None, +) -> Kokoro: + """Build the Kokoro engine, taking over session construction only when asked. + + Left alone, ONNX Runtime sizes its thread pools from the host's core count. + Inside a container whose CPU quota is smaller than the machine that means + more threads contending for less CPU than the default assumed, which costs + throughput rather than buying it. ``threads`` caps the pools; passing + ``session_options`` instead hands over everything else ORT exposes. + """ + if threads is not None and session_options is not None: + raise ValueError("pass threads or session_options, not both") + if threads is not None: + session_options = ort.SessionOptions() + session_options.intra_op_num_threads = threads + session_options.inter_op_num_threads = threads + if session_options is None: + return Kokoro(str(model_path), str(voices_path)) + session = ort.InferenceSession(str(model_path), sess_options=session_options, providers=_onnx_providers()) + # from_session carries no return annotation upstream, so bind it through a + # typed name rather than returning Any straight out of a typed function. + kokoro: Kokoro = Kokoro.from_session(session, str(voices_path)) + return kokoro + + # Split after ., !, or ? that is followed by whitespace, and on newlines. The # whitespace requirement leaves decimals ("0.95") and mid-token dots # ("file.ts") intact, which is good enough for speech chunking. @@ -111,6 +157,11 @@ class Stackvox: and defaults to the built-in ones. A mix's own lang and speed beat the ``lang`` and ``speed`` given here, which act as defaults; pass them per call to override a mix. + + ``threads`` caps the ONNX Runtime thread pools, which otherwise size + themselves from the host's core count and oversubscribe inside a container + with a CPU quota. ``session_options`` replaces it when some other ORT + setting is wanted; the two are mutually exclusive. """ def __init__( @@ -120,6 +171,8 @@ def __init__( lang: str = DEFAULT_LANG, cache_dir: Path | None = None, custom_voices: Mapping[str, VoiceMix] | None = None, + threads: int | None = None, + session_options: ort.SessionOptions | None = None, ) -> None: self.voice = voice self.speed = speed @@ -127,7 +180,7 @@ def __init__( self.custom_voices = dict(BUILTIN_VOICES if custom_voices is None else custom_voices) self._blends: dict[str, np.ndarray] = {} model_path, voices_path = _ensure_models(cache_dir or _default_cache_dir()) - self._kokoro = Kokoro(str(model_path), str(voices_path)) + self._kokoro = _load_kokoro(model_path, voices_path, threads, session_options) self._stop_event = threading.Event() self._play_thread: threading.Thread | None = None self._stream: sd.OutputStream | None = None diff --git a/tests/test_engine.py b/tests/test_engine.py index c1625f1..0e93164 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -34,6 +34,12 @@ def fake_kokoro(mocker, fake_ensure_models): return mocker.patch.object(engine, "Kokoro") +@pytest.fixture +def fake_ort(mocker): + """Mock onnxruntime so a session can be built without loading a real model.""" + return mocker.patch.object(engine, "ort") + + @pytest.fixture def fake_audio(mocker): """Mock the sounddevice surface used by Stackvox (streaming + speak_sequence).""" @@ -70,6 +76,61 @@ def test_falls_back_to_default_cache_dir(self, fake_kokoro, fake_ensure_models, fake_ensure_models.assert_called_once_with(default) +class TestSessionOptions: + def test_default_construction_leaves_the_session_to_kokoro(self, fake_kokoro, fake_ort): + tts = engine.Stackvox() + + fake_kokoro.assert_called_once() + fake_ort.InferenceSession.assert_not_called() + assert tts._kokoro is fake_kokoro.return_value + + def test_threads_caps_both_onnx_thread_pools(self, fake_kokoro, fake_ort, fake_ensure_models): + model_path, voices_path = fake_ensure_models.return_value + + tts = engine.Stackvox(threads=4) + + options = fake_ort.SessionOptions.return_value + assert options.intra_op_num_threads == 4 + assert options.inter_op_num_threads == 4 + assert fake_ort.InferenceSession.call_args.args == (str(model_path),) + assert fake_ort.InferenceSession.call_args.kwargs["sess_options"] is options + # from_session, not the plain constructor, is what honours our session. + fake_kokoro.assert_not_called() + fake_kokoro.from_session.assert_called_once_with( + fake_ort.InferenceSession.return_value, str(voices_path) + ) + assert tts._kokoro is fake_kokoro.from_session.return_value + + def test_session_options_are_passed_through_untouched(self, fake_kokoro, fake_ort, mocker): + options = mocker.Mock() + + engine.Stackvox(session_options=options) + + assert fake_ort.InferenceSession.call_args.kwargs["sess_options"] is options + fake_ort.SessionOptions.assert_not_called() + + def test_threads_and_session_options_together_is_rejected(self, fake_kokoro, fake_ort, mocker): + with pytest.raises(ValueError, match="not both"): + engine.Stackvox(threads=4, session_options=mocker.Mock()) + + def test_session_defaults_to_the_cpu_provider(self, fake_kokoro, fake_ort, monkeypatch): + # Building the session ourselves means making the provider choice + # Kokoro.__init__ would have made, or a thread cap silently moves the + # model onto a different provider. + monkeypatch.delenv("ONNX_PROVIDER", raising=False) + + engine.Stackvox(threads=2) + + assert fake_ort.InferenceSession.call_args.kwargs["providers"] == ["CPUExecutionProvider"] + + def test_session_follows_the_onnx_provider_env_var(self, fake_kokoro, fake_ort, monkeypatch): + monkeypatch.setenv("ONNX_PROVIDER", "CUDAExecutionProvider") + + engine.Stackvox(threads=2) + + assert fake_ort.InferenceSession.call_args.kwargs["providers"] == ["CUDAExecutionProvider"] + + class TestSynthesize: def test_passes_engine_defaults_to_kokoro(self, fake_kokoro): samples = np.zeros(10, dtype=np.float32)