Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion local-stt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ Use the HTTPS URL printed by **your** Tailscale installation, not an address cop

`GET /health` reports the model and backend. Authenticated `POST /v1/transcribe` accepts JSON `{requestId, audio, language?, vocabulary?}`. `audio` is canonical base64 of a complete 16 kHz mono PCM16 WAV, 0.25–300 seconds, at most 10 MiB. Body limit: 14 MiB. Response: `{text, requestId, model, durationMs}`.

Only one upload/inference runs at a time; overlap returns 429. Audio stays in process memory. Requests/transcripts are not persisted or logged. Language detection and vocabulary hints are supported, but hints do not guarantee spelling. Whisper may hallucinate on noise or very quiet audio; exact digital silence is rejected.
Only one upload/inference runs at a time; overlap returns 429.

The model is kept wired in memory (about 2.3 GB for this model) so macOS cannot page it out while the service is idle; otherwise the first dictation after a quiet period can wait many seconds for the model to page back in. MLX's idle buffer cache is capped at 256 MiB. Set `CLEARFLOW_KEEP_RESIDENT=0` in the service environment to give that memory back to other apps at the cost of slower first requests. The LaunchAgent runs as an `Interactive` process so launchd does not throttle it like background maintenance work. Audio stays in process memory. Requests/transcripts are not persisted or logged. Language detection and vocabulary hints are supported, but hints do not guarantee spelling. Whisper may hallucinate on noise or very quiet audio; exact digital silence is rejected.

## Troubleshooting and validation

Expand Down
6 changes: 5 additions & 1 deletion local-stt/install-agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
import subprocess
from runtime import DEFAULT_RUNTIME, LABEL, environment

# Dictation waits on this service. launchd throttles CPU and disk I/O for Background
# jobs, including paging the model back in, so it runs with app-level priority.
PROCESS_TYPE = "Interactive"

def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--runtime", type=Path, default=DEFAULT_RUNTIME)
Expand All @@ -26,7 +30,7 @@ def main():
"Label": LABEL, "ProgramArguments": [str(python), "-u", str(project / "local-stt/server.py")],
"WorkingDirectory": str(project), "EnvironmentVariables": env,
"RunAtLoad": True, "KeepAlive": True, "ThrottleInterval": 30,
"ProcessType": "Background", "Umask": 0o077,
"ProcessType": PROCESS_TYPE, "Umask": 0o077,
"StandardOutPath": str(logs / "service.stdout.log"),
"StandardErrorPath": str(logs / "service.stderr.log"),
}
Expand Down
32 changes: 29 additions & 3 deletions local-stt/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,39 @@ def do_POST(self):
server.inference_lock = threading.Lock()
return server

MIB = 1024 * 1024
CACHE_LIMIT = 256 * MIB
WIRED_HEADROOM = 256 * MIB

def wired_limit(peak, recommended):
"""Bytes to keep resident: the warm-up peak plus headroom, below the system cap.

Whisper always decodes padded 30-second windows, so a short warm-up reaches
the same working set as a real request.
"""
if peak <= 0 or recommended <= 0:
return 0
return min(peak + WIRED_HEADROOM, int(recommended * 0.9))

class WhisperEngine:
def __init__(self, model_path):
def __init__(self, model_path, keep_resident=True):
import mlx.core as mx
import numpy as np
import mlx_whisper
self.np, self.transcribe, self.model_path = np, mlx_whisper.transcribe, model_path
# Freed activation buffers otherwise stay cached and double the idle footprint.
mx.set_cache_limit(CACHE_LIMIT)
# Preload weights and tokenizer; the model remains resident between requests.
self.transcribe(np.zeros(16000, dtype=np.float32), path_or_hf_repo=model_path,
language="en", verbose=None, temperature=0.0)
self.wired = 0
if keep_resident:
# An idle model is paged out under memory pressure, and the next request
# then waits seconds for gigabytes to page back in. Wiring prevents that.
info = mx.device_info() if hasattr(mx, "device_info") else mx.metal.device_info()
self.wired = wired_limit(mx.get_peak_memory(), info.get("max_recommended_working_set_size", 0))
if self.wired:
mx.set_wired_limit(self.wired)
def __call__(self, audio, language, vocabulary):
with wave.open(io.BytesIO(audio), "rb") as f:
samples = self.np.frombuffer(f.readframes(f.getnframes()), dtype="<i2").astype(self.np.float32) / 32768.0
Expand All @@ -209,11 +233,13 @@ def main():
model_path = os.environ["CLEARFLOW_MODEL_PATH"]
# MLX work runs on one persistent thread, including initialization.
with ThreadPoolExecutor(max_workers=1) as pool:
engine = pool.submit(WhisperEngine, model_path).result()
keep_resident = os.environ.get("CLEARFLOW_KEEP_RESIDENT", "1") != "0"
engine = pool.submit(WhisperEngine, model_path, keep_resident).result()
def infer(*args):
return pool.submit(engine, *args).result()
server = make_server(token, infer, int(os.environ.get("CLEARFLOW_PORT", "8768")))
print(json.dumps({"event": "ready", "model": MODEL, "port": server.server_port}), flush=True)
print(json.dumps({"event": "ready", "model": MODEL, "port": server.server_port,
"wiredMiB": engine.wired // MIB}), flush=True)
server.serve_forever()

if __name__ == "__main__":
Expand Down
11 changes: 11 additions & 0 deletions local-stt/test_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import tempfile
import unittest
from runtime import prepare, environment
import importlib
from server import wired_limit, WIRED_HEADROOM

class RuntimeTests(unittest.TestCase):
def test_independent_runtimes_have_unique_credentials_and_private_files(self):
Expand Down Expand Up @@ -34,3 +36,12 @@ def test_invalid_port_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
for port in [0, 80, 65536]:
with self.assertRaises(ValueError): prepare(directory, port)
def test_wired_limit_covers_peak_and_stays_below_system_cap(self):
gib = 1024 ** 3
self.assertEqual(wired_limit(3 * gib, 12 * gib), 3 * gib + WIRED_HEADROOM)
self.assertEqual(wired_limit(12 * gib, 12 * gib), int(12 * gib * 0.9))
self.assertEqual(wired_limit(0, 12 * gib), 0)
self.assertEqual(wired_limit(3 * gib, 0), 0)
def test_launch_agent_is_not_throttled_as_background_work(self):
agent = importlib.import_module("install-agent")
self.assertEqual(agent.PROCESS_TYPE, "Interactive")
Loading