diff --git a/local-stt/README.md b/local-stt/README.md index 7628abc..75c98af 100644 --- a/local-stt/README.md +++ b/local-stt/README.md @@ -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 diff --git a/local-stt/install-agent.py b/local-stt/install-agent.py index 0e1ef40..1b08361 100644 --- a/local-stt/install-agent.py +++ b/local-stt/install-agent.py @@ -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) @@ -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"), } diff --git a/local-stt/server.py b/local-stt/server.py index 797ccc8..5db0499 100644 --- a/local-stt/server.py +++ b/local-stt/server.py @@ -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="