Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: run the Transformers dictation engine in a spawn child (#8668)

Daniel Han62b12f006573
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index c66e23ec07a..db558ced681 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -1534,10 +1534,11 @@ class InferenceOrchestrator:
return True
# --- Dictation models -------------------------------------------------
- # These run in the STT sidecars (whisper-server, llama-server, Transformers
- # in process), not the chat worker. Their lifecycle goes through here all
- # the same, so one object knows everything that is resident and Voice
- # settings and Model Hub cannot report different things about one model.
+ # These run in the STT sidecars (whisper-server, llama-server, and the
+ # Transformers spawn child), not the chat worker. Their lifecycle goes
+ # through here all the same, so one object knows everything that is
+ # resident and Voice settings and Model Hub cannot report different things
+ # about one model.
def load_stt_model(
self,
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
index f6f0deab682..eeec72c8b3c 100644
--- a/studio/backend/core/inference/stt_registry.py
+++ b/studio/backend/core/inference/stt_registry.py
@@ -4,10 +4,10 @@
"""One place that knows which dictation models are resident, and loads them.
The sidecars still own their processes: whisper.cpp serves GGML through
-whisper-server, llama.cpp serves mtmd models, and Transformers loads in
-process. What lives here is the lifecycle above them, so the orchestrator has a
-single view of dictation the way it has one of chat, and Voice settings and
-Model Hub cannot report different things about the same model.
+whisper-server, llama.cpp serves mtmd models, and Transformers loads in a spawn
+child of its own. What lives here is the lifecycle above them, so the
+orchestrator has a single view of dictation the way it has one of chat, and
+Voice settings and Model Hub cannot report different things about the same model.
"""
from __future__ import annotations
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index 878f527c7d4..89d9d7c704a 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -4,11 +4,17 @@
"""
Standalone speech-to-text (STT) sidecar for dictation.
-Loads a Whisper model (via Transformers) in the backend process, separate from
-the chat model's inference subprocess, so dictation works with any chat model
-without evicting it. Curated defaults plus any Transformers-compatible Whisper
-repo; weights come through Studio's Model Hub and stay warm briefly between
-dictations. CUDA runs float16; MPS and CPU run float32.
+Loads a Whisper model (via Transformers) in a spawn child of its own, separate
+from the chat model's inference subprocess, so dictation works with any chat
+model without evicting it. Curated defaults plus any Transformers-compatible
+Whisper repo; weights come through Studio's Model Hub and stay warm briefly
+between dictations. CUDA runs float16; MPS and CPU run float32.
+
+Everything except the model itself stays here: device choice, the Hub cache,
+audio decoding, windowing and the idle timer. Only the load and the generate
+happen in core/inference/stt_transformers_worker.py, because an accelerator
+context is never returned while the process holding it lives and the backend
+must not be the process that takes one.
"""
from __future__ import annotations
@@ -190,7 +196,7 @@ class SttModelNotDownloadedError(RuntimeError):
class SttModelBusyError(RuntimeError):
- """A switch was asked for while the current model is mid-transcription."""
+ """The current model cannot make way yet, so the switch has to be retried."""
class SttModelIdError(ValueError):
@@ -988,6 +994,69 @@ def _pick_device():
return "cpu", torch.float32
+def _dtype_name(dtype) -> str:
+ """Name a dtype for the worker command: torch.float16 becomes float16.
+
+ Takes the plain strings tests use as readily as a real torch dtype, so the
+ command carries no torch object across the process boundary.
+ """
+ return str(dtype).rsplit(".", 1)[-1]
+
+
+def _engine_is_alive(engine) -> bool:
+ """False only for a worker whose process is confirmed dead.
+
+ Anything without a liveness check counts as live, so a caller holding a
+ plain object (tests, or a future in-process engine) is unaffected. So does
+ a probe that cannot answer: absence of liveness evidence is not evidence
+ that the accelerator context was released, and reporting nothing resident
+ is what lets training be admitted against memory that is not free.
+ """
+ is_alive = getattr(engine, "is_alive", None)
+ if is_alive is None:
+ return True
+ try:
+ return bool(is_alive())
+ except Exception as exc: # noqa: BLE001 - an unanswerable probe must not fail a status read
+ logger.warning("Could not check whether the STT worker is alive: %s", exc)
+ return True
+
+
+def _engine_survived_kill(engine) -> bool:
+ """Whether a handle says its own child outlived terminate and kill.
+
+ close() reports that to its caller, but a cancelled or timed-out command
+ closes the worker from inside the handle and raises over the answer, so the
+ only record that reaches here is the one the handle keeps on itself.
+ """
+ return bool(getattr(engine, "survived_kill", False))
+
+
+def _close_engine(engine) -> bool:
+ """End the worker behind an engine handle, if it has one.
+
+ Ending the worker is what returns its accelerator context; dropping the
+ handle and emptying the cache cannot. A plain object (tests, or a future
+ in-process engine) has no close and needs none.
+
+ False when the engine says so itself, which WhisperWorker does for a child
+ that outlived terminate and kill and is therefore still holding the memory
+ this call was made to release, and False when close() raises out of a
+ process operation: nothing was confirmed dead, so the handle has to be kept
+ rather than the memory advertised as free. A close that raised over a child
+ already gone still counts as released, so bookkeeping that failed after the
+ death cannot wedge every later load.
+ """
+ close = getattr(engine, "close", None)
+ if close is None:
+ return True
+ try:
+ return close() is not False
+ except Exception as exc: # noqa: BLE001 - a stuck worker must not block the unload
+ logger.warning("Could not stop the STT worker: %s", exc)
+ return not _engine_is_alive(engine)
+
+
def _decode_audio_bounded(audio: bytes, cancel_event = None):
"""Decode to 16 kHz mono PCM without buffering unbounded audio.
@@ -1085,9 +1154,20 @@ class WhisperSttSidecar:
self._keep_alive_seconds = max(0.0, keep_alive_seconds)
self._idle_timer: Optional[threading.Timer] = None
self._idle_generation = 0
+ # Held only to keep its memory accounted: a worker that outlived its own
+ # kill answers nothing, so a later dictation cannot be handed it.
+ self._survivor = False
+ # A child that outlived the kill start() gave it, handed from _build_model
+ # to the load that called it. Written and read under _lock.
+ self._start_survivor = None
@property
def loaded_model(self) -> Optional[str]:
+ # A worker that died holds nothing, so reporting its model would make
+ # training admission reserve memory for a model that is not there.
+ engine = self._engine
+ if engine is not None and not _engine_is_alive(engine):
+ return None
return self._model_id
@property
@@ -1180,56 +1260,155 @@ class WhisperSttSidecar:
logger.info("Unloading idle STT model %s", self._model_id)
self._release_engine_locked()
- def _release_engine_locked(self) -> None:
+ def _release_engine_locked(self) -> bool:
+ """Release the resident engine. False if its child outlived the kill.
+
+ Such a child still holds its accelerator memory, so forgetting it here
+ would report the model unloaded and let training be admitted against
+ memory that is not free. Keep it resident instead and rearm the idle
+ timer, so the release is tried again rather than stranded.
+
+ The fields are cleared only once the worker is confirmed dead. close()
+ can take the full shutdown wait, and loaded_model reads the fields
+ without this lock, so clearing them first would report nothing resident
+ for that whole window.
+
+ A worker kept this way is flagged a survivor: it was asked to shut down,
+ terminated and killed, so it is held for its memory and not for its
+ answers, and a later dictation must load one of its own rather than be
+ handed this one and wait out the command timeout on it.
+ """
self._cancel_idle_unload_locked()
engine = self._engine
device = self._device
- self._engine = None
- self._model_id = None
- self._device = None
+ released = _close_engine(engine)
+ if released:
+ self._engine = None
+ self._model_id = None
+ self._device = None
+ self._survivor = False
+ else:
+ self._survivor = True
del engine
_clear_device_cache(device)
+ if not released:
+ self._schedule_idle_unload_locked()
+ return released
- def _build_model(self, snapshot_path: str, device: str, dtype, cancel_event: threading.Event):
- """Load a Whisper model + processor from the local Hub cache.
+ def _keep_survivor_locked(
+ self,
+ engine,
+ model_id: str,
+ device: Optional[str] = None,
+ ) -> None:
+ """Hold an engine whose child outlived its close, so it stays accounted.
- local_files_only keeps the Model Hub the only download path; a cache
- miss raises so the caller can surface SttModelNotDownloadedError.
+ Its device is the one the child reports, which after a CPU retry is not
+ the one this load started on; a child that never finished its load
+ reports none, so the device the attempt was made on stands in. The idle
+ timer is rearmed, so the release is tried again rather than the survivor
+ being stranded here.
+
+ Held for its memory, not for its answers: it is flagged so a later
+ dictation loads a worker of its own instead of being handed one that is
+ wedged, which would cost the caller the whole command timeout.
"""
- import torch
- from transformers import WhisperForConditionalGeneration, WhisperProcessor
+ self._engine = engine
+ self._model_id = model_id
+ self._survivor = True
+ self._device = getattr(engine, "device", None) or device
+ logger.error(
+ "The dictation worker for %s outlived the kill and still holds its memory; "
+ "keeping it resident so it is not reported unloaded",
+ model_id,
+ )
+ self._schedule_idle_unload_locked()
+
+ def _is_survivor_locked(self) -> bool:
+ """Whether the resident engine is held for its memory, not its answers.
+
+ Folds in the flag the handle raised on itself: a command that was
+ cancelled or timed out closes the worker from inside the handle, so
+ close()'s False never reaches the sidecar and this is the only way it
+ learns the child outlived both signals. Handing such a worker to the
+ next dictation would spend the whole command timeout on it under the
+ model lock; refusing lets the idle timer retry the kill instead.
+ """
+ if self._survivor:
+ return True
+ if self._engine is not None and _engine_survived_kill(self._engine):
+ self._survivor = True
+ return True
+ return False
+
+ def _release_dead_engine_locked(self) -> None:
+ """Drop a worker whose process is gone, so the next use loads a fresh one."""
+ if self._engine is not None and not _engine_is_alive(self._engine):
+ logger.warning("STT worker for %s exited; it will be reloaded", self._model_id)
+ self._release_engine_locked()
- processor = None
- model = None
+ def _build_model(self, snapshot_path: str, device: str, dtype, cancel_event: threading.Event):
+ """Start a worker process holding this model and return its handle.
+
+ Out of process because an accelerator context is never given back while
+ the process holding it lives, so an in-process load made the backend
+ permanently heavier even after unload.
+
+ A host that cannot create a child at all (a sandbox, or a frozen POSIX
+ build) falls back to loading here instead, on the CPU: this move may
+ take work out of the backend, never take dictation away from someone
+ who had it. The fallback waits for the CPU attempt, so a spawn failure
+ on an accelerator still goes through the caller's own CPU retry rather
+ than downgrading the user here.
+
+ A child that outlived start()'s own kill is left in ``_start_survivor``
+ for the caller. start() ends its child on every failure, so a handle
+ still reporting a live process is one holding memory that nothing else
+ knows about: dropping it here is what would let this failed load read as
+ nothing resident.
+ """
+ from core.inference.stt_transformers_worker import (
+ InProcessWhisperEngine,
+ SttWorkerSpawnError,
+ WhisperWorker,
+ )
+
+ worker = WhisperWorker()
try:
- processor = WhisperProcessor.from_pretrained(snapshot_path, local_files_only = True)
- self._raise_if_load_cancelled(cancel_event)
- # use_safetensors forces the pickle-free load path even if a
- # pytorch_model.bin somehow reached the cache; the selector and the
- # completeness check already exclude pickle weights upstream.
- model = WhisperForConditionalGeneration.from_pretrained(
- snapshot_path, torch_dtype = dtype, local_files_only = True, use_safetensors = True
+ # start() kills its own child on any failure, including cancellation.
+ worker.start(str(snapshot_path), device, _dtype_name(dtype), cancel_event)
+ except SttWorkerSpawnError as exc:
+ if device != "cpu":
+ raise
+ logger.warning(
+ "No dictation worker process could be started (%s); "
+ "loading the model in the backend on the CPU instead",
+ exc,
)
- self._raise_if_load_cancelled(cancel_event)
- model.to(torch.device(device))
- self._raise_if_load_cancelled(cancel_event)
- model.eval()
- return model, processor
- except SttLoadCancelledError:
- model = None
- processor = None
- _clear_device_cache(device)
+ engine = InProcessWhisperEngine()
+ engine.start(str(snapshot_path), "cpu", _dtype_name(dtype), cancel_event)
+ return engine
+ except BaseException:
+ if _engine_is_alive(worker):
+ self._start_survivor = worker
raise
+ return worker
def _ensure_model_downloaded(self, model_id: str) -> _CachedSttSnapshot:
"""Validate the local snapshot before decode or model replacement.
Returns the checkpoint's multilingual flag when local metadata provides
it. Curated defaults are known multilingual.
+
+ A survivor is held for its memory alone, so it does not answer for the
+ model the way a resident one does: the snapshot is looked up on disk, or
+ the load it precedes would be turned away as a checkpoint that is not
+ downloaded.
"""
model_id = resolve_model_id(model_id)
with self._lock:
- if self._engine is not None and self._model_id == model_id:
+ reusable = self._engine is not None and self._model_id == model_id
+ if reusable and not self._is_survivor_locked():
resident_model = (
self._engine[0] if isinstance(self._engine, (tuple, list)) else self._engine
)
@@ -1277,7 +1456,9 @@ class WhisperSttSidecar:
if request_cancel_event is not None and request_cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
ensure_stt_available()
- if self._engine is not None and self._model_id == model_id:
+ self._release_dead_engine_locked()
+ reusable = self._engine is not None and self._model_id == model_id
+ if reusable and not self._is_survivor_locked():
self._schedule_idle_unload_locked()
return self._engine
import torch
@@ -1286,6 +1467,7 @@ class WhisperSttSidecar:
candidate = None
device: Optional[str] = None
resident_released = False
+ self._start_survivor = None
try:
self._raise_if_load_cancelled(cancel_event)
cached = self._ensure_model_downloaded(model_id)
@@ -1297,7 +1479,13 @@ class WhisperSttSidecar:
)
self._raise_if_load_cancelled(cancel_event)
device, dtype = _pick_device()
- self._release_engine_locked()
+ if not self._release_engine_locked():
+ # Starting a second child over one that never exited doubles
+ # the memory this release was meant to give back.
+ raise SttModelBusyError(
+ "The previous dictation worker did not exit and still holds its "
+ "memory. Try again shortly."
+ )
resident_released = True
logger.info("Loading STT model %s (%s) on %s", model_id, snapshot_path, device)
@@ -1314,10 +1502,23 @@ class WhisperSttSidecar:
except SttLoadCancelledError:
raise
except Exception as exc:
- if _is_missing_local_model_error(exc):
+ # The worker classifies a cache miss; the exception cannot cross processes.
+ if isinstance(exc, SttModelNotDownloadedError) or _is_missing_local_model_error(
+ exc
+ ):
raise not_downloaded(exc) from exc
if device == "cpu":
raise
+ if self._start_survivor is not None:
+ # The attempt left a child that outlived its own kill and still
+ # holds the device. A second child would sit beside it, and
+ # installing that one would forget this one, which is what lets
+ # training be admitted against memory that is not free. Refuse as
+ # a release that could not kill its worker does; the timer retries.
+ raise SttModelBusyError(
+ "The previous dictation worker did not exit and still holds its "
+ "memory. Try again shortly."
+ ) from exc
logger.warning("STT load on %s failed (%s); retrying on CPU", device, exc)
retry_on_cpu = True
if retry_on_cpu:
@@ -1336,7 +1537,9 @@ class WhisperSttSidecar:
except SttLoadCancelledError:
raise
except Exception as cpu_exc:
- if _is_missing_local_model_error(cpu_exc):
+ if isinstance(
+ cpu_exc, SttModelNotDownloadedError
+ ) or _is_missing_local_model_error(cpu_exc):
raise not_downloaded(cpu_exc) from cpu_exc
raise
device = "cpu"
@@ -1345,6 +1548,7 @@ class WhisperSttSidecar:
self._engine = candidate
self._model_id = model_id
self._device = device
+ self._survivor = False
self._load_cancel_event = None
self._load_owner_cancel_event = None
self._loading = False
@@ -1352,6 +1556,29 @@ class WhisperSttSidecar:
logger.info("STT model %s ready on %s", model_id, device)
return self._engine
except SttLoadCancelledError:
+ # cancel_pending_load() does not wait for the model lock, so the cancel
+ # can land after start() came back with a live child. Nothing installed
+ # the candidate, and dropping the handle does not end the process holding
+ # the context training is waiting for, so close it here.
+ if self._start_survivor is not None:
+ # start() ends its own child, so this one outlived terminate and kill
+ # inside it and never became a candidate. It holds its memory all the
+ # same and this is the only handle on the process, so keep it rather
+ # than let the cancel report the memory given back; the timer retries.
+ self._keep_survivor_locked(self._start_survivor, model_id, device)
+ _clear_device_cache(device)
+ raise
+ if not _close_engine(candidate):
+ # It outlived terminate and kill, so it still holds the memory this
+ # cancel was made to free. Keep it, for the same reason
+ # _release_engine_locked keeps its own survivor: reporting nothing
+ # resident is what lets training be admitted against memory that is
+ # not free. Nothing is installed over, since a candidate exists only
+ # after the resident was released.
+ self._keep_survivor_locked(candidate, model_id)
+ candidate = None
+ _clear_device_cache(device)
+ raise
candidate = None
if resident_released:
# _release_engine_locked already collected, and the candidate was dropped
@@ -1363,7 +1590,16 @@ class WhisperSttSidecar:
else:
_clear_device_cache(device)
raise
+ except BaseException:
+ # Same reasoning for any other failed load: this is the only handle on a
+ # child that outlived start()'s own kill and still holds its memory, and
+ # reporting nothing resident lets training be admitted against it.
+ if self._start_survivor is not None and self._engine is None:
+ self._keep_survivor_locked(self._start_survivor, model_id, device)
+ _clear_device_cache(device)
+ raise
finally:
+ self._start_survivor = None
self._end_load(cancel_event)
def _transcribe_decoded(
@@ -1375,57 +1611,38 @@ class WhisperSttSidecar:
) -> str:
"""Run Whisper on already-decoded 16 kHz mono PCM and return text.
- Feeds a pre-decoded array so nothing here touches the Transformers audio
- path (torchcodec/ffmpeg). Splits into 30s windows (Whisper's receptive
- field); short clips take one pass.
+ Splits into 30s windows (Whisper's receptive field) and sends one window
+ at a time to the worker; short clips take one pass. Windowing stays here
+ so a cancelled dictation stops between windows even while the worker is
+ busy, and so no single message carries more than 30 seconds of audio.
"""
- import torch
+ import numpy as np
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
if cancel_event is None:
- model, processor = self.load(model_id)
+ engine = self.load(model_id)
else:
- model, processor = self.load(model_id, request_cancel_event = cancel_event)
+ engine = self.load(model_id, request_cancel_event = cancel_event)
effective_generate_kwargs = dict(generate_kwargs)
- if cancel_event is not None:
- from transformers import StoppingCriteriaList
- class _CancelCriteria:
- def __call__(self, *_args, **_kwargs):
- return cancel_event.is_set()
-
- effective_generate_kwargs["stopping_criteria"] = StoppingCriteriaList(
- [_CancelCriteria()]
- )
- generation_config = getattr(model, "generation_config", None)
+ generation_config = getattr(engine, "generation_config", None)
if getattr(generation_config, "is_multilingual", None) is False:
# English-only checkpoints fix language and task in their generation
# config, and Transformers rejects passing them here.
effective_generate_kwargs.pop("task", None)
effective_generate_kwargs.pop("language", None)
window = 30 * _TARGET_SAMPLE_RATE
- target_dtype = getattr(model, "dtype", None)
parts: list[str] = []
- with torch.no_grad():
- for start in range(0, max(len(decoded_audio), 1), window):
- if cancel_event is not None and cancel_event.is_set():
- raise SttTranscriptionCancelledError("Transcription cancelled.")
- segment = decoded_audio[start : start + window]
- if segment.size == 0:
- continue
- inputs = processor(
- segment,
- sampling_rate = _TARGET_SAMPLE_RATE,
- return_tensors = "pt",
- )
- features = inputs.input_features.to(model.device)
- if target_dtype is not None:
- features = features.to(target_dtype)
- generated = model.generate(features, **effective_generate_kwargs)
- if cancel_event is not None and cancel_event.is_set():
- raise SttTranscriptionCancelledError("Transcription cancelled.")
- text = processor.batch_decode(generated, skip_special_tokens = True)
- parts.append(text[0] if text else "")
+ for start in range(0, max(len(decoded_audio), 1), window):
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ segment = decoded_audio[start : start + window]
+ if segment.size == 0:
+ continue
+ pcm = np.ascontiguousarray(segment, dtype = np.float32).tobytes()
+ parts.append(engine.transcribe_window(pcm, effective_generate_kwargs, cancel_event))
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
return " ".join(part.strip() for part in parts if part.strip()).strip()
def transcribe(
@@ -1499,7 +1716,12 @@ class WhisperSttSidecar:
}
def cancel_transcription(self, cancel_event: threading.Event) -> bool:
- """Ask this request's Transformers generation or load to stop."""
+ """Ask this request's Transformers generation or load to stop.
+
+ Only this request's own event is set. The thread waiting on the worker
+ mirrors it into the child within a poll, so a cancel never reaches a
+ window belonging to a different request.
+ """
already_cancelled = cancel_event.is_set()
cancel_event.set()
return self._cancel_owned_load(cancel_event) or not already_cancelled
diff --git a/studio/backend/core/inference/stt_transformers_worker.py b/studio/backend/core/inference/stt_transformers_worker.py
new file mode 100644
index 00000000000..136821c93b9
--- /dev/null
+++ b/studio/backend/core/inference/stt_transformers_worker.py
@@ -0,0 +1,684 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Whisper (Transformers) dictation in a spawn child, and the handle for it.
+
+A CUDA context costs ~700 MiB on a current card and is never returned while the
+process that created it lives, so an in-process load left the backend that much
+heavier for good: unloading the model frees the weights and nothing else (the
+rule is written down in core/inference/gpu_arbiter.py). whisper.cpp and
+llama.cpp dictation already serve from their own processes; this puts the
+Transformers engine on the same footing, so an idle unload ends a process and
+the context goes with it.
+
+Both sides live here: ``run_stt_worker`` is the child entrypoint (imported by
+name in the child, so it must stay at module scope for Windows spawn), and
+``WhisperWorker`` is the parent-side handle the sidecar holds instead of a
+model object.
+"""
+
+from __future__ import annotations
+
+import multiprocessing as mp
+import queue as _queue
+import sys
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# Spawn, never fork: a forked CUDA context is unusable, and Windows/macOS have no fork.
+_CTX = mp.get_context("spawn")
+
+_BACKEND_PATH = str(Path(__file__).resolve().parent.parent.parent)
+
+# Both bounds only break a hang: a cold-disk large-v3 load and a 30 minute
+# transcription are both legitimately slow.
+_LOAD_TIMEOUT_SECONDS = 600.0
+_TRANSCRIBE_TIMEOUT_SECONDS = 600.0
+# How long a cancelled command gets before the child is killed. Generation stops
+# within a token, but a load inside from_pretrained never sees the cancel, and
+# training is waiting for that memory.
+_CANCEL_GRACE_SECONDS = 10.0
+_SHUTDOWN_TIMEOUT_SECONDS = 10.0
+_POLL_SECONDS = 0.1
+
+# Errors the child may report that the parent must re-raise as themselves; any
+# other failure crosses as a RuntimeError carrying the child's message.
+_FORWARDED_ERRORS = (
+ "SttLoadCancelledError",
+ "SttTranscriptionCancelledError",
+ "SttModelNotDownloadedError",
+ "SttModelCompatibilityError",
+ "SttUnavailableError",
+)
+
+
+class SttWorkerError(RuntimeError):
+ """The dictation worker crashed, hung, or could not be reached."""
+
+
+class SttWorkerSpawnError(SttWorkerError):
+ """No child could be created at all: this host forbids or cannot spawn.
+
+ Distinct because it says nothing about the model or the device, so the
+ caller answers it by loading in process rather than by giving up.
+ """
+
+
+# ---------------------------------------------------------------------------
+# Child process
+# ---------------------------------------------------------------------------
+
+
+def _ensure_backend_on_path() -> None:
+ if _BACKEND_PATH not in sys.path:
+ sys.path.insert(0, _BACKEND_PATH)
+
+
+class _CancelCriteria:
+ """Stops generation as soon as the parent sets the shared cancel event."""
+
+ def __init__(self, cancel_event) -> None:
+ self._cancel_event = cancel_event
+
+ def __call__(self, *_args, **_kwargs) -> bool:
+ return self._cancel_event.is_set()
+
+
+def _raise_if_cancelled(cancel_event) -> None:
+ from core.inference.stt_sidecar import SttLoadCancelledError
+ if cancel_event is not None and cancel_event.is_set():
+ raise SttLoadCancelledError("STT model loading was cancelled so training could start.")
+
+
+def load_whisper(
+ snapshot_path: str,
+ device: str,
+ dtype_name: str,
+ cancel_event = None,
+) -> tuple:
+ """Load a Whisper model + processor from the local Hub cache. Child side.
+
+ local_files_only keeps the Model Hub the only download path; a cache miss
+ raises so the parent can surface SttModelNotDownloadedError.
+ """
+ import torch
+ from transformers import WhisperForConditionalGeneration, WhisperProcessor
+
+ dtype = getattr(torch, dtype_name, None) or torch.float32
+ processor = WhisperProcessor.from_pretrained(snapshot_path, local_files_only = True)
+ _raise_if_cancelled(cancel_event)
+ # use_safetensors forces the pickle-free load path even if a pytorch_model.bin
+ # reached the cache; the selector and completeness check exclude them upstream.
+ model = WhisperForConditionalGeneration.from_pretrained(
+ snapshot_path, torch_dtype = dtype, local_files_only = True, use_safetensors = True
+ )
+ _raise_if_cancelled(cancel_event)
+ model.to(torch.device(device))
+ _raise_if_cancelled(cancel_event)
+ model.eval()
+ return model, processor
+
+
+def transcribe_window(
+ model,
+ processor,
+ pcm: bytes,
+ generate_kwargs: dict,
+ cancel_event = None,
+):
+ """Run Whisper over one window of 16 kHz mono float32 PCM. Child side.
+
+ Feeds a pre-decoded array so nothing here touches the Transformers audio
+ path (torchcodec/ffmpeg); the parent decodes and windows.
+ """
+ import numpy as np
+ import torch
+
+ segment = np.frombuffer(pcm, dtype = np.float32)
+ kwargs = dict(generate_kwargs)
+ if cancel_event is not None:
+ from transformers import StoppingCriteriaList
+ kwargs["stopping_criteria"] = StoppingCriteriaList([_CancelCriteria(cancel_event)])
+ from core.inference.stt_sidecar import _TARGET_SAMPLE_RATE
+
+ inputs = processor(segment, sampling_rate = _TARGET_SAMPLE_RATE, return_tensors = "pt")
+ features = inputs.input_features.to(model.device)
+ target_dtype = getattr(model, "dtype", None)
+ if target_dtype is not None:
+ features = features.to(target_dtype)
+ with torch.no_grad():
+ generated = model.generate(features, **kwargs)
+ text = processor.batch_decode(generated, skip_special_tokens = True)
+ return text[0] if text else ""
+
+
+def _error_response(exc: BaseException) -> dict:
+ """Describe a failure so the parent can re-raise the same class.
+
+ The exception itself is not sent: an arbitrary Transformers or torch error
+ may not pickle, and a queue that fails to serialise costs the caller its
+ whole timeout instead of an error.
+ """
+ from core.inference.stt_sidecar import _is_missing_local_model_error
+
+ kind = type(exc).__name__
+ message = str(exc) or kind
+ if kind not in _FORWARDED_ERRORS and _is_missing_local_model_error(exc):
+ # A local-cache miss means the model is not downloaded, not a broken runtime.
+ kind = "SttModelNotDownloadedError"
+ message = "The dictation model is not downloaded."
+ return {"type": "error", "kind": kind, "error": message}
+
+
+def _send(resp_queue, response: dict) -> None:
+ try:
+ resp_queue.put(response)
+ except (OSError, ValueError) as exc:
+ logger.error("STT worker could not answer the backend: %s", exc)
+
+
+def run_stt_worker(
+ *,
+ cmd_queue,
+ resp_queue,
+ cancel_event,
+ ready_event = None,
+ config: Optional[dict] = None,
+) -> None:
+ """Child entrypoint: hold one Whisper model and answer transcription commands.
+
+ Returning ends the process, which is the only way to give the CUDA context
+ back, so a failed load and an unload both exit rather than idle.
+
+ Sets ready_event before touching a command, which is what tells the parent a
+ fresh interpreter came up here.
+ """
+ import os
+
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
+ _ensure_backend_on_path()
+ try:
+ from loggers.config import LogConfig
+ LogConfig.setup_logging(
+ service_name = "unsloth-studio-stt-worker",
+ env = os.getenv("ENVIRONMENT_TYPE", "production"),
+ )
+ except Exception as exc: # noqa: BLE001 - logging setup must not fail dictation
+ logger.debug("STT worker logging setup failed: %s", exc)
+
+ # Say this interpreter is up before any model work. Without it the parent has
+ # only the exit code, and Windows has no signals: a native crash inside the model
+ # load ends the child with a positive status there exactly as a child that never
+ # bootstrapped does, and reading that crash as a host that cannot spawn moves the
+ # same crashing load into the backend, which the backend does not survive.
+ #
+ # An Event, not a queue message: Queue.put only hands the object to a feeder
+ # thread, so a child that faults before that thread drains the buffer never
+ # delivers it (measured here, the queued word was lost in 17 of 20 runs). An
+ # Event is shared memory, set the moment it returns, and was lost in none.
+ if ready_event is not None:
+ ready_event.set()
+
+ engine = None
+ while True:
+ try:
+ command = cmd_queue.get(timeout = 1.0)
+ except _queue.Empty:
+ continue
+ except (EOFError, OSError):
+ return
+ if not isinstance(command, dict):
+ continue
+ kind = command.get("type")
+ try:
+ if kind == "load":
+ model, processor = load_whisper(
+ command["snapshot_path"],
+ command["device"],
+ command["dtype"],
+ cancel_event,
+ )
+ engine = (model, processor)
+ generation_config = getattr(model, "generation_config", None)
+ is_multilingual = getattr(generation_config, "is_multilingual", None)
+ _send(
+ resp_queue,
+ {
+ "type": "loaded",
+ "device": command["device"],
+ "is_multilingual": (
+ is_multilingual if isinstance(is_multilingual, bool) else None
+ ),
+ },
+ )
+ elif kind == "transcribe":
+ if engine is None:
+ raise SttWorkerError("The dictation worker has no model loaded.")
+ cancellable = bool(command.get("cancellable"))
+ text = transcribe_window(
+ engine[0],
+ engine[1],
+ command["audio"],
+ command.get("generate_kwargs") or {},
+ cancel_event if cancellable else None,
+ )
+ if cancellable and cancel_event.is_set():
+ from core.inference.stt_sidecar import SttTranscriptionCancelledError
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ _send(resp_queue, {"type": "text", "text": text})
+ elif kind == "shutdown":
+ _send(resp_queue, {"type": "shutdown_ack"})
+ return
+ else:
+ _send(
+ resp_queue,
+ {
+ "type": "error",
+ "kind": "SttWorkerError",
+ "error": f"Unknown command '{kind}'.",
+ },
+ )
+ except BaseException as exc: # noqa: BLE001 - every failure is reported, then handled
+ _send(resp_queue, _error_response(exc))
+ if kind == "load":
+ # Nothing is resident after a failed load, and the attempt may
+ # already have taken a context; exiting returns it.
+ return
+
+
+# ---------------------------------------------------------------------------
+# Parent process
+# ---------------------------------------------------------------------------
+
+
+def _raise_worker_error(response: dict) -> None:
+ from core.inference import stt_sidecar
+
+ kind = response.get("kind")
+ message = response.get("error") or "The dictation worker failed."
+ error_type = getattr(stt_sidecar, kind, None) if kind in _FORWARDED_ERRORS else None
+ raise (error_type or SttWorkerError)(message)
+
+
+class WhisperWorker:
+ """Parent-side handle for one Whisper model living in one child process.
+
+ Stands in for the ``(model, processor)`` pair the sidecar used to hold, so
+ the sidecar keeps its lifecycle, its lock and its idle timer unchanged.
+ Not thread-safe by itself: the sidecar serialises every call under its
+ model lock, exactly as it did for in-process inference.
+ """
+
+ def __init__(self) -> None:
+ self._process = None
+ self._cmd_queue = None
+ self._resp_queue = None
+ self._cancel_event = None
+ # Set by the child before any model work, so this separates a host that
+ # cannot bring a child up from a child that failed at something.
+ self._ready_event = None
+ self._answered = False
+ # Set once close() found a child that outlived terminate and kill. The handle
+ # is kept so its memory stays accounted, but a child that answered neither
+ # signal answers no later command either, and its terminate left the queues
+ # liable to corruption, so it must never be handed to a later dictation.
+ self.survived_kill = False
+ self.device: Optional[str] = None
+ # Read by the sidecar the way it read the model's, so an English-only
+ # checkpoint still drops the task/language kwargs it rejects.
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+
+ def start(
+ self,
+ snapshot_path: str,
+ device: str,
+ dtype_name: str,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> None:
+ """Spawn the child and load the model, or raise having killed it."""
+ from utils.hf_cache_settings import child_environment_for_spawn, get_hf_cache_paths
+ from utils.native_path_leases import (
+ native_path_secret_removed_for_child_start,
+ run_without_native_path_secret,
+ )
+ from utils.process_lifetime import adopt_pid
+
+ cache_env = get_hf_cache_paths().child_env({})
+ try:
+ with (
+ child_environment_for_spawn(cache_env),
+ native_path_secret_removed_for_child_start(),
+ ):
+ self._cmd_queue = _CTX.Queue()
+ self._resp_queue = _CTX.Queue()
+ self._cancel_event = _CTX.Event()
+ self._ready_event = _CTX.Event()
+ self._process = _CTX.Process(
+ # The shared shim binds the child to this process's lifetime and
+ # applies the Hub cache environment before any import.
+ target = run_without_native_path_secret,
+ args = ("core.inference.stt_transformers_worker", "run_stt_worker", cache_env),
+ kwargs = {
+ "cmd_queue": self._cmd_queue,
+ "resp_queue": self._resp_queue,
+ "cancel_event": self._cancel_event,
+ "ready_event": self._ready_event,
+ "config": {},
+ },
+ daemon = True,
+ )
+ self._process.start()
+ except Exception as exc: # noqa: BLE001 - any refusal to spawn reads the same
+ # Nothing was started, so nothing to kill; raise a class the caller can act on.
+ self._process = None
+ self._close_queues()
+ raise SttWorkerSpawnError(
+ f"Could not start the dictation worker process: {exc}"
+ ) from exc
+ adopt_pid(self._process.pid) # terminate_all backstop for graceful exits
+ logger.info(
+ "STT worker started (pid=%s) for %s on %s", self._process.pid, snapshot_path, device
+ )
+ try:
+ self._send(
+ {
+ "type": "load",
+ "snapshot_path": str(snapshot_path),
+ "device": device,
+ "dtype": dtype_name,
+ }
+ )
+ response = self._await("loaded", _LOAD_TIMEOUT_SECONDS, cancel_event, "load")
+ except BaseException as exc:
+ # Classify before close(), which reaps the child and drops the handle.
+ stillborn = self._never_bootstrapped(exc)
+ self.close()
+ if stillborn:
+ raise SttWorkerSpawnError(
+ f"The dictation worker process could not start: {exc}"
+ ) from exc
+ raise
+ self.device = response.get("device") or device
+ self.generation_config = SimpleNamespace(is_multilingual = response.get("is_multilingual"))
+
+ def transcribe_window(
+ self,
+ pcm: bytes,
+ generate_kwargs: dict,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> str:
+ """Transcribe one decoded window and return its text."""
+ if self._cancel_event is not None:
+ self._cancel_event.clear()
+ self._send(
+ {
+ "type": "transcribe",
+ "audio": pcm,
+ "generate_kwargs": dict(generate_kwargs),
+ "cancellable": cancel_event is not None,
+ }
+ )
+ response = self._await("text", _TRANSCRIBE_TIMEOUT_SECONDS, cancel_event, "transcribe")
+ text = response.get("text")
+ return text if isinstance(text, str) else ""
+
+ def is_alive(self) -> bool:
+ process = self._process
+ return process is not None and process.is_alive()
+
+ def _never_bootstrapped(self, exc: BaseException) -> bool:
+ """Whether the child died without its fresh interpreter ever coming up.
+
+ start() returning says only that the exec worked: a frozen POSIX build
+ re-runs its own binary instead of an interpreter, so the child is gone
+ before it can read the load command. That is a host that cannot spawn,
+ which the caller answers by loading in process, not by trying the same
+ thing again on another device.
+
+ The child sets ready_event before it touches a command, so a positive
+ exitcode with the event never set is a child that never got that far.
+ The handshake is what makes this safe on Windows, where there are no
+ signals and a native fault surfaces as a positive status
+ (STATUS_ACCESS_VIOLATION reads as 3221225477) rather than the negative
+ exitcode POSIX reports one with: a crash inside the model load would
+ otherwise read as a host that cannot spawn, and be answered by running
+ that same load in the backend. A signal death (the box under memory
+ pressure, a driver fault) and any child that did answer keep their own
+ error.
+ """
+ if self._answered or not isinstance(exc, SttWorkerError):
+ return False
+ ready = self._ready_event
+ if ready is not None and ready.is_set():
+ return False
+ process = self._process
+ if process is None or process.is_alive():
+ return False
+ exitcode = getattr(process, "exitcode", None)
+ return isinstance(exitcode, int) and exitcode > 0
+
+ def cancel(self) -> None:
+ """Ask the child to stop the command it is running."""
+ if self._cancel_event is not None:
+ self._cancel_event.set()
+
+ def close(self, graceful_timeout: float = _SHUTDOWN_TIMEOUT_SECONDS) -> bool:
+ """Stop the child, which is what actually returns its accelerator memory.
+
+ graceful_timeout is how long the child gets to consume the queued
+ shutdown and exit by itself. Zero means that wait has already been
+ spent elsewhere -- the cancel grace in _await -- so go straight to
+ terminate rather than restart the clock on a caller that is already
+ out of patience.
+
+ Returns True only once the child is confirmed dead. A child that
+ survives terminate and kill (wedged in a driver call that outlives
+ SIGKILL) still holds its memory, so its handle and its adoption record
+ are KEPT: forgetting the pid would leave terminate_all and the next
+ startup sweep nothing to find it by.
+ """
+ process = self._process
+ self.cancel() # unblock a generation before asking the loop to exit
+ if process is not None:
+ try:
+ if graceful_timeout > 0 and process.is_alive() and self._cmd_queue is not None:
+ self._cmd_queue.put({"type": "shutdown"})
+ except (OSError, ValueError):
+ pass
+ if graceful_timeout > 0:
+ process.join(graceful_timeout)
+ if process.is_alive():
+ logger.warning("STT worker %s did not exit; terminating", process.pid)
+ process.terminate()
+ process.join(5)
+ if process.is_alive():
+ process.kill()
+ process.join(3)
+ if process.is_alive():
+ logger.error(
+ "STT worker %s survived terminate and kill; keeping its handle and its "
+ "pid record so the sweep can still reach it",
+ process.pid,
+ )
+ # Recorded on the handle, not just returned: a cancelled or timed-out
+ # command closes the worker from inside _await and raises over this
+ # answer, so the sidecar would keep offering the wedged child otherwise.
+ self.survived_kill = True
+ return False
+ try:
+ from utils.process_lifetime import forget_pid
+ forget_pid(process.pid)
+ except Exception as exc: # noqa: BLE001 - bookkeeping must not fail an unload
+ logger.debug("Could not forget STT worker pid %s: %s", process.pid, exc)
+ self._process = None
+ self._close_queues()
+ return True
+
+ def _close_queues(self) -> None:
+ for handle in (self._cmd_queue, self._resp_queue):
+ try:
+ if handle is not None:
+ # The feeder thread must not outlive the queue it feeds.
+ handle.cancel_join_thread()
+ handle.close()
+ except Exception: # noqa: BLE001 - a closed queue is best effort
+ pass
+ self._cmd_queue = None
+ self._resp_queue = None
+
+ def _send(self, command: dict) -> None:
+ if self._cmd_queue is None:
+ raise SttWorkerError("The dictation worker is not running.")
+ try:
+ self._cmd_queue.put(command)
+ except (OSError, ValueError) as exc:
+ raise SttWorkerError(f"Could not reach the dictation worker: {exc}") from exc
+
+ def _await(
+ self, expected: str, timeout: float, cancel_event: Optional[threading.Event], phase: str
+ ) -> dict:
+ """Wait for one response, mirroring cancellation and watching for death."""
+ deadline = time.monotonic() + timeout
+ cancel_deadline: Optional[float] = None
+ while True:
+ if cancel_event is not None and cancel_event.is_set():
+ self.cancel()
+ if cancel_deadline is None:
+ cancel_deadline = time.monotonic() + _CANCEL_GRACE_SECONDS
+ elif time.monotonic() >= cancel_deadline:
+ # A load inside from_pretrained never sees the event and the memory
+ # is wanted now, so end the process. The grace WAS the graceful
+ # shutdown, and a child too busy to read the cancel will not read a
+ # shutdown, so terminate rather than wait _SHUTDOWN_TIMEOUT_SECONDS more.
+ self.close(graceful_timeout = 0.0)
+ self._raise_cancelled(phase)
+ try:
+ response = self._resp_queue.get(timeout = _POLL_SECONDS)
+ except _queue.Empty:
+ if not self.is_alive():
+ raise SttWorkerError(self._crash_message(phase))
+ if time.monotonic() >= deadline:
+ if cancel_deadline is not None:
+ # A cancel landing near the end of the timeout is still a cancel:
+ # the caller is owed the phase's own error (409 load, 499
+ # transcription), and a child that ignored it ignores a shutdown.
+ self.close(graceful_timeout = 0.0)
+ self._raise_cancelled(phase)
+ self.close()
+ raise SttWorkerError(
+ "The dictation worker stopped responding; try recording again."
+ )
+ continue
+ except (EOFError, OSError, ValueError) as exc:
+ raise SttWorkerError(f"Lost contact with the dictation worker: {exc}") from exc
+ if not isinstance(response, dict):
+ continue
+ self._answered = True
+ if response.get("type") == "error":
+ _raise_worker_error(response)
+ if response.get("type") == expected:
+ return response
+
+ @staticmethod
+ def _raise_cancelled(phase: str) -> None:
+ from core.inference.stt_sidecar import (
+ SttLoadCancelledError,
+ SttTranscriptionCancelledError,
+ )
+ if phase == "load":
+ raise SttLoadCancelledError("STT model loading was cancelled so training could start.")
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+
+ def _crash_message(self, phase: str) -> str:
+ process = self._process
+ exitcode = getattr(process, "exitcode", None)
+ detail = f"exitcode={exitcode}"
+ if isinstance(exitcode, int) and exitcode < 0:
+ import signal
+
+ try:
+ name = signal.Signals(-exitcode).name
+ except ValueError:
+ name = f"SIG{-exitcode}"
+ detail = f"signal={name}"
+ if name == "SIGKILL":
+ # The usual cause on a busy box, and the one the user can act on.
+ detail += "; the system may have killed it under memory pressure"
+ what = "loading the dictation model" if phase == "load" else "transcribing"
+ return f"The dictation worker stopped while {what} ({detail})."
+
+
+class InProcessWhisperEngine:
+ """The pre-spawn engine, kept for hosts where no child can be created.
+
+ A sandboxed deployment or a frozen POSIX build may refuse spawn outright,
+ and dictation worked there before this module existed, so it still has to.
+ Presents the same surface as WhisperWorker, so the sidecar cannot tell the
+ two apart.
+
+ CPU only, and deliberately so: the reason the model moved out of process is
+ that an accelerator context is never given back while the process holding
+ it lives. A CPU load in the backend takes no context, so this fallback
+ costs the backend nothing permanent.
+ """
+
+ def __init__(self) -> None:
+ self._model = None
+ self._processor = None
+ self.device: Optional[str] = None
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+
+ def start(
+ self,
+ snapshot_path: str,
+ device: str,
+ dtype_name: str,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> None:
+ if device != "cpu":
+ raise SttWorkerError("The in-process dictation fallback runs on the CPU only.")
+ model, processor = load_whisper(str(snapshot_path), "cpu", dtype_name, cancel_event)
+ self._model = model
+ self._processor = processor
+ self.device = "cpu"
+ generation_config = getattr(model, "generation_config", None)
+ is_multilingual = getattr(generation_config, "is_multilingual", None)
+ self.generation_config = SimpleNamespace(
+ is_multilingual = is_multilingual if isinstance(is_multilingual, bool) else None
+ )
+ logger.info("STT model loaded in process on the CPU from %s", snapshot_path)
+
+ def transcribe_window(
+ self,
+ pcm: bytes,
+ generate_kwargs: dict,
+ cancel_event: Optional[threading.Event] = None,
+ ) -> str:
+ if self._model is None:
+ raise SttWorkerError("The dictation worker has no model loaded.")
+ text = transcribe_window(
+ self._model, self._processor, pcm, dict(generate_kwargs), cancel_event
+ )
+ if cancel_event is not None and cancel_event.is_set():
+ from core.inference.stt_sidecar import SttTranscriptionCancelledError
+ raise SttTranscriptionCancelledError("Transcription cancelled.")
+ return text
+
+ def is_alive(self) -> bool:
+ return self._model is not None
+
+ def cancel(self) -> None:
+ """Nothing to signal: the caller's own event stops the generation."""
+
+ def close(self, graceful_timeout: float = _SHUTDOWN_TIMEOUT_SECONDS) -> bool:
+ self._model = None
+ self._processor = None
+ self.device = None
+ return True
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
index cb07246d528..704037fc40e 100644
--- a/studio/backend/tests/test_stt_sidecar.py
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -23,6 +23,7 @@ from core.inference.stt_sidecar import (
SttAudioTooLongError,
SttLanguageError,
SttLoadCancelledError,
+ SttModelBusyError,
SttModelCompatibilityError,
SttModelIdError,
SttModelNotDownloadedError,
@@ -311,36 +312,20 @@ def test_english_only_model_rejects_non_english_before_decode(monkeypatch, tmp_p
def test_english_only_model_omits_forbidden_generation_controls(monkeypatch):
calls = []
- class FakeTensor:
- def to(self, *_args):
- return self
-
- class FakeProcessor:
- def __call__(self, *_args, **_kwargs):
- return SimpleNamespace(input_features = FakeTensor())
-
- def batch_decode(self, *_args, **_kwargs):
- return ["hello"]
-
- class FakeModel:
- dtype = None
- device = "cpu"
+ class FakeWorker:
generation_config = SimpleNamespace(is_multilingual = False)
- def generate(self, _features, **kwargs):
- calls.append(kwargs)
- return [[1]]
-
- class NoGrad:
- def __enter__(self):
- return None
-
- def __exit__(self, *_args):
- return False
+ def transcribe_window(
+ self,
+ _pcm,
+ generate_kwargs,
+ _cancel_event = None,
+ ):
+ calls.append(generate_kwargs)
+ return "hello"
- monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(no_grad = NoGrad))
sidecar = WhisperSttSidecar()
- monkeypatch.setattr(sidecar, "load", lambda _model: (FakeModel(), FakeProcessor()))
+ monkeypatch.setattr(sidecar, "load", lambda _model: FakeWorker())
text = sidecar._transcribe_decoded(
"owner/whisper-small.en",
@@ -453,45 +438,622 @@ def _install_fake_torch(monkeypatch):
return fake_torch
-def test_load_uses_model_hub_cache_without_implicit_download(monkeypatch):
- calls = []
+def _install_fake_worker(monkeypatch, start = None):
+ """Replace the spawn child with a handle that records how it was started."""
+ started = []
+
+ class FakeWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ self.device = None
+ self.closed = False
+ self.alive = True
+
+ def start(
+ self,
+ snapshot_path,
+ device,
+ dtype_name,
+ cancel_event = None,
+ ):
+ started.append((snapshot_path, device, dtype_name))
+ if start is not None:
+ start(snapshot_path, device, dtype_name, cancel_event)
+ self.device = device
+
+ def is_alive(self):
+ return self.alive
+
+ def close(self):
+ self.closed = True
+ self.alive = False
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker", FakeWorker, raising = True
+ )
+ return started
+
+
+def test_load_hands_the_cached_snapshot_to_the_worker_process(monkeypatch):
+ # The model never enters this process: an accelerator context taken here is
+ # never given back, which is the whole reason the engine is out of process.
_install_fake_torch(monkeypatch)
+ started = _install_fake_worker(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
- class FakeWhisperForConditionalGeneration:
- @classmethod
- def from_pretrained(cls, repo, **kwargs):
- calls.append(("model", repo, kwargs))
- return _FakeModel()
+ # str(Path(...)), so the separator is the platform's.
+ assert started == [(str(Path("/cached/model")), "cpu", "float32")]
+ assert sidecar.loaded_model == "small"
- class FakeWhisperProcessor:
- @classmethod
- def from_pretrained(cls, repo, **kwargs):
- calls.append(("processor", repo, kwargs))
- return object()
- monkeypatch.setitem(
- sys.modules,
- "transformers",
- SimpleNamespace(
- WhisperForConditionalGeneration = FakeWhisperForConditionalGeneration,
- WhisperProcessor = FakeWhisperProcessor,
- ),
+def test_load_sends_the_dtype_by_name_so_torch_stays_out_of_the_command(monkeypatch):
+ fake_torch = _install_fake_torch(monkeypatch)
+ fake_torch.float16 = "torch.float16"
+ started = _install_fake_worker(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cuda", fake_torch.float16))
+
+ WhisperSttSidecar(keep_alive_seconds = 0).load("small")
+
+ assert started == [(str(Path("/cached/model")), "cuda", "float16")]
+
+
+def test_a_worker_that_died_is_not_resident_and_is_replaced_on_the_next_load(monkeypatch):
+ _install_fake_torch(monkeypatch)
+ started = _install_fake_worker(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ worker = sidecar.load("small")
+ worker.alive = False
+
+ assert sidecar.loaded_model is None
+
+ replacement = sidecar.load("small")
+
+ assert replacement is not worker
+ assert len(started) == 2
+ assert sidecar.loaded_model == "small"
+
+
+def test_unload_stops_the_worker_process(monkeypatch):
+ # empty_cache cannot return the context; ending the process is what does.
+ _install_fake_torch(monkeypatch)
+ _install_fake_worker(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ worker = sidecar.load("small")
+ sidecar.unload()
+
+ assert worker.closed is True
+ assert sidecar.loaded_model is None
+
+
+def test_a_worker_rejected_by_a_late_cancel_is_stopped_rather_than_leaked(monkeypatch):
+ # cancel_pending_load() does not wait for the model lock, so it can land after
+ # start() came back with a live child. Nothing installed that child, and dropping
+ # the handle does not end the process holding the context training waits for.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ workers = []
+
+ class LateCancelWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ self.device = None
+ self.closed = False
+ workers.append(self)
+
+ def start(
+ self,
+ _snapshot_path,
+ device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ # The load succeeded; the cancel arrives a moment later.
+ self.device = device
+ assert sidecar.cancel_pending_load() is True
+
+ def is_alive(self):
+ return not self.closed
+
+ def close(self):
+ self.closed = True
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker", LateCancelWorker, raising = True
)
+
+ with pytest.raises(SttLoadCancelledError):
+ sidecar.load("small")
+
+ assert len(workers) == 1
+ assert workers[0].closed is True
+ assert sidecar.loaded_model is None
+ assert sidecar.is_loading() is False
+
+
+def test_a_late_cancelled_worker_that_outlived_the_kill_stays_resident(monkeypatch):
+ # The same late cancel, against a child that answers False: it survived terminate
+ # and kill and still holds its accelerator memory, so reporting nothing resident
+ # would let training be admitted against memory that is not free.
+ _install_fake_torch(monkeypatch)
monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ workers = []
+
+ class UnkillableLateCancelWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ self.device = None
+ self.closes = 0
+ workers.append(self)
+
+ def start(
+ self,
+ _snapshot_path,
+ device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ self.device = device
+ assert sidecar.cancel_pending_load() is True
+
+ def is_alive(self):
+ return True
+
+ def close(self):
+ self.closes += 1
+ return False
- WhisperSttSidecar(keep_alive_seconds = 0).load("small")
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker",
+ UnkillableLateCancelWorker,
+ raising = True,
+ )
+
+ with pytest.raises(SttLoadCancelledError):
+ sidecar.load("small")
+
+ assert len(workers) == 1
+ # Once. A second terminate-and-kill round on the way out would only spend
+ # another wait on a child that just proved it does not answer them.
+ assert workers[0].closes == 1
+ assert sidecar.loaded_model == "small"
+ assert sidecar.device == "cpu"
+ assert sidecar.is_loading() is False
+
+
+def _install_unkillable_worker(monkeypatch):
+ """A worker whose child outlived terminate and kill, so close() answers False."""
+ workers = []
+
+ class UnkillableWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ self.device = None
+ self.closes = 0
+ workers.append(self)
+
+ def start(
+ self,
+ _snapshot_path,
+ device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ self.device = device
+
+ def is_alive(self):
+ return True
+
+ def close(self):
+ self.closes += 1
+ return False
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker", UnkillableWorker, raising = True
+ )
+ return workers
+
+
+def test_a_worker_that_outlived_the_kill_stays_resident_rather_than_reported_unloaded(monkeypatch):
+ # close() answers False for a child wedged in a driver call that outlives SIGKILL. It
+ # still holds its memory, so reporting the model unloaded would let training be
+ # admitted against memory that is not free.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ workers = _install_unkillable_worker(monkeypatch)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+ sidecar.unload()
+
+ assert workers[0].closes == 1
+ assert sidecar.loaded_model == "small"
+ assert sidecar.device == "cpu"
+
+
+def test_a_new_load_is_refused_while_the_previous_worker_still_holds_its_memory(monkeypatch):
+ # Starting a second child over one that never exited doubles the memory the
+ # first was unloaded to release, so refuse and let the caller retry.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ workers = _install_unkillable_worker(monkeypatch)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+
+ with pytest.raises(SttModelBusyError, match = "did not exit"):
+ sidecar.load("base")
+
+ assert len(workers) == 1
+ assert sidecar.loaded_model == "small"
+ assert sidecar.is_loading() is False
+
+
+def test_a_surviving_worker_is_not_handed_to_the_next_dictation(monkeypatch):
+ # It is held for its memory, not for its answers: it already had its shutdown, a
+ # terminate and a kill, so handing it to a transcription costs the caller the whole
+ # command timeout under the model lock. Refuse, and let the retry kill it again.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ workers = _install_unkillable_worker(monkeypatch)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+ sidecar.unload()
+
+ with pytest.raises(SttModelBusyError, match = "did not exit"):
+ sidecar.load("small")
+
+ assert len(workers) == 1
+ assert sidecar.loaded_model == "small"
+
+
+def test_a_worker_wedged_by_a_cancelled_transcription_is_not_handed_to_the_next_dictation(
+ monkeypatch,
+):
+ # A cancel that outruns the grace closes the worker from inside the handle, so
+ # close() answers False to nobody and the sidecar never learns the child outlived
+ # both signals. Handing it on spends the whole command timeout under the model lock.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ workers = []
+
+ class WedgedByCancelWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ self.device = None
+ self.survived_kill = False
+ workers.append(self)
+
+ def start(
+ self,
+ _snapshot_path,
+ device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ self.device = device
+
+ def is_alive(self):
+ return True
+
+ def transcribe_window(
+ self,
+ _pcm,
+ _generate_kwargs,
+ _cancel_event = None,
+ ):
+ # What _await does once the cancel grace expires: close() terminates and
+ # kills, the child answers neither, and the cancel is raised over its False.
+ self.survived_kill = True
+ raise stt_sidecar_module.SttTranscriptionCancelledError("Transcription cancelled.")
+
+ def close(self):
+ return False
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker",
+ WedgedByCancelWorker,
+ raising = True,
+ )
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ cancel_event = threading.Event()
+ with pytest.raises(stt_sidecar_module.SttTranscriptionCancelledError):
+ sidecar.transcribe(b"audio", "small", cancel_event = cancel_event)
+
+ with pytest.raises(SttModelBusyError, match = "did not exit"):
+ sidecar.load("small")
+
+ assert len(workers) == 1
+ # Still accounted for: it holds its memory until the kill finally takes.
+ assert sidecar.loaded_model == "small"
+
+
+def _install_worker_that_survives_its_own_start(monkeypatch, error):
+ """A worker whose start() fails over a child that outlived its own kill.
+
+ start() ends its child on every failure, so a handle still reporting a live
+ process is one holding memory nothing else knows about.
+ """
+ workers = []
+
+ class SurvivingStartWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ # start() never got as far as naming the device it loaded on.
+ self.device = None
+ workers.append(self)
+
+ def start(
+ self,
+ _snapshot_path,
+ _device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ raise error
+
+ def is_alive(self):
+ return True
+
+ def close(self):
+ return False
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker",
+ SurvivingStartWorker,
+ raising = True,
+ )
+ return workers
+
+
+def test_a_child_that_outlived_the_kill_inside_start_stays_accounted(monkeypatch):
+ # The cancel lands while the child is inside from_pretrained, which never reads it,
+ # so the load kills the child on the way out and the child outlives it. Nothing
+ # installed that handle and it is the only one on the process: dropping it reports
+ # nothing resident while the context is taken, admitting training against it.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ workers = _install_worker_that_survives_its_own_start(
+ monkeypatch, SttLoadCancelledError("STT model loading was cancelled so training can start.")
+ )
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ with pytest.raises(SttLoadCancelledError):
+ sidecar.load("small")
+
+ assert len(workers) == 1
+ assert sidecar.loaded_model == "small"
+ # The child never named a device, so the one the attempt was made on stands in.
+ assert sidecar.device == "cpu"
+ assert sidecar.is_loading() is False
+
+
+def test_a_load_whose_child_outlived_the_kill_is_not_retried_onto_a_second_child(monkeypatch):
+ # The accelerator attempt failed leaving a live child, so the CPU retry would
+ # put a second child beside it and, installing that one, forget the first.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cuda", "float16"))
+ workers = _install_worker_that_survives_its_own_start(
+ monkeypatch, RuntimeError("the dictation worker stopped responding")
+ )
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ with pytest.raises(SttModelBusyError, match = "did not exit"):
+ sidecar.load("small")
+
+ assert len(workers) == 1
+ assert sidecar.loaded_model == "small"
+ assert sidecar.device == "cuda"
+ assert sidecar.is_loading() is False
+
+
+def test_an_idle_unload_retries_a_worker_that_outlived_the_kill(monkeypatch):
+ # Keeping the survivor resident must not strand it: the idle timer is rearmed
+ # so the release is tried again once the child finally goes.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ monkeypatch.setattr(stt_sidecar_module.threading, "Timer", _FakeTimer)
+ workers = _install_unkillable_worker(monkeypatch)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 60)
+ sidecar.load("small")
+ sidecar._idle_timer.fire()
+
+ assert workers[0].closes == 1
+ assert sidecar.loaded_model == "small"
+ assert sidecar._idle_timer.started is True
+
+
+def _install_worker(monkeypatch, *, is_alive, close):
+ """Install a worker handle whose liveness and close behaviour a test chooses."""
+ workers = []
+
+ class _ScriptedWorker:
+ def __init__(self) -> None:
+ self.generation_config = SimpleNamespace(is_multilingual = None)
+ self.device = None
+ self.closes = 0
+ self.alive = True
+ workers.append(self)
+
+ def start(
+ self,
+ _snapshot_path,
+ device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ self.device = device
+
+ def is_alive(self):
+ return is_alive(self)
+
+ def close(self):
+ self.closes += 1
+ return close(self)
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker", _ScriptedWorker, raising = True
+ )
+ return workers
+
+
+def _closed(worker):
+ worker.alive = False
+ return True
+
+
+def test_a_worker_whose_liveness_cannot_be_read_stays_resident(monkeypatch):
+ # An unanswerable probe is not evidence that the context was released, so reporting
+ # nothing resident would let training be admitted against memory still held.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ def unreadable(_worker):
+ raise OSError("the process handle cannot be inspected")
+
+ workers = _install_worker(monkeypatch, is_alive = unreadable, close = _closed)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+
+ assert stt_sidecar_module._engine_is_alive(workers[0]) is True
+ assert sidecar.loaded_model == "small"
+ assert workers[0].closes == 0
+
+
+def test_a_close_that_raises_is_a_failed_release(monkeypatch):
+ # close() raising out of join/terminate/kill confirms nothing dead, so discarding
+ # the only handle would advertise memory the child is still holding as free.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ def raising(_worker):
+ raise OSError("the worker could not be joined")
+
+ workers = _install_worker(monkeypatch, is_alive = lambda worker: True, close = raising)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+ sidecar.unload()
+
+ assert workers[0].closes == 1
+ assert sidecar.loaded_model == "small"
+ assert sidecar.device == "cpu"
+
+
+def test_a_close_that_raises_over_a_child_already_gone_still_releases(monkeypatch):
+ # The other direction: bookkeeping that raised over a confirmed dead child
+ # holds no memory, and keeping it would refuse every later load.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+
+ def raising_after_death(worker):
+ worker.alive = False
+ raise OSError("the worker pid could not be forgotten")
+
+ workers = _install_worker(
+ monkeypatch, is_alive = lambda worker: worker.alive, close = raising_after_death
+ )
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+ sidecar.unload()
+
+ assert workers[0].closes == 1
+ assert sidecar.loaded_model is None
+ assert sidecar.device is None
- # str(Path(...)), so the separator is the platform's.
- cached = str(Path("/cached/model"))
- assert {(kind, repo) for kind, repo, _ in calls} == {
- ("processor", cached),
- ("model", cached),
- }
- # Never fetch weights implicitly; the Model Hub owns downloads.
- assert all(kwargs.get("local_files_only") is True for _, _, kwargs in calls)
- # The weight load forces safetensors so a pickle checkpoint cannot execute.
- model_kwargs = next(kwargs for kind, _, kwargs in calls if kind == "model")
- assert model_kwargs.get("use_safetensors") is True
+
+def test_a_worker_being_reaped_stays_visible_to_training_admission(monkeypatch):
+ # loaded_model and summarize_resident_stt() read the fields without the model
+ # lock, so clearing them before the reap would report nothing resident for the
+ # whole close, and training would start into the child's accelerator memory.
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
+ release = threading.Event()
+
+ def slow_close(worker):
+ release.wait(timeout = 10)
+ worker.alive = False
+ return True
+
+ _install_worker(monkeypatch, is_alive = lambda worker: worker.alive, close = slow_close)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ sidecar.load("small")
+
+ seen = {}
+ unloading = threading.Thread(target = sidecar.unload, daemon = True)
+ unloading.start()
+ try:
+ time.sleep(0.2) # inside the close
+ seen["model"] = sidecar.loaded_model
+ seen["device"] = sidecar.device
+ finally:
+ release.set()
+ unloading.join(timeout = 10)
+
+ assert seen["model"] == "small", "the reaping worker read as gone; training would miss its VRAM"
+ assert seen["device"] == "cpu"
+ # Only once the child is confirmed dead does it read as unloaded.
+ assert sidecar.loaded_model is None
+ assert sidecar.device is None
+
+
+def test_a_host_that_cannot_spawn_keeps_dictation_in_process_on_cpu(monkeypatch):
+ # Moving the engine out of process may not take dictation away from a host that
+ # cannot create a child. The accelerator attempt goes through the usual CPU retry
+ # first, so nobody is downgraded before that has run.
+ import core.inference.stt_transformers_worker as worker_module
+
+ _install_fake_torch(monkeypatch)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cuda", "float16"))
+ spawned = []
+ loaded = []
+
+ class RefusedWorker:
+ def start(
+ self,
+ _snapshot_path,
+ device,
+ _dtype_name,
+ _cancel_event = None,
+ ):
+ spawned.append(device)
+ raise worker_module.SttWorkerSpawnError("spawn is not permitted here")
+
+ monkeypatch.setattr(
+ "core.inference.stt_transformers_worker.WhisperWorker", RefusedWorker, raising = True
+ )
+ monkeypatch.setattr(
+ worker_module,
+ "load_whisper",
+ lambda path, device, dtype, _cancel = None: (
+ loaded.append((path, device, dtype)) or (_FakeModel(), object())
+ ),
+ )
+ monkeypatch.setattr(worker_module, "transcribe_window", lambda *_args, **_kwargs: "hello")
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ engine = sidecar.load("small")
+
+ assert spawned == ["cuda", "cpu"]
+ # In process only after both spawns failed, and only ever on the CPU.
+ assert loaded == [(str(Path("/cached/model")), "cpu", "float32")]
+ assert sidecar.device == "cpu"
+ assert sidecar.loaded_model == "small"
+ assert engine.transcribe_window(b"", {}) == "hello"
def test_model_cache_preflight_uses_shared_offline_resolver(monkeypatch):
@@ -517,25 +1079,14 @@ def test_model_cache_preflight_reports_missing_snapshot(monkeypatch):
def test_load_reports_model_hub_cache_miss(monkeypatch):
_install_fake_torch(monkeypatch)
- class LocalEntryNotFoundError(RuntimeError):
- pass
-
- class MissingWhisperProcessor:
- @classmethod
- def from_pretrained(cls, *_args, **_kwargs):
- raise LocalEntryNotFoundError("not cached")
+ def missing(*_args, **_kwargs):
+ # What the worker reports for a cache miss it hit inside from_pretrained.
+ raise SttModelNotDownloadedError("The dictation model is not downloaded.")
- monkeypatch.setitem(
- sys.modules,
- "transformers",
- SimpleNamespace(
- WhisperForConditionalGeneration = object,
- WhisperProcessor = MissingWhisperProcessor,
- ),
- )
+ _install_fake_worker(monkeypatch, start = missing)
monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda: ("cpu", "float32"))
- with pytest.raises(SttModelNotDownloadedError, match = "not downloaded"):
+ with pytest.raises(SttModelNotDownloadedError, match = "large-v3"):
WhisperSttSidecar(keep_alive_seconds = 0).load("large-v3")
diff --git a/studio/backend/tests/test_stt_transformers_worker.py b/studio/backend/tests/test_stt_transformers_worker.py
new file mode 100644
index 00000000000..f404403e3e7
--- /dev/null
+++ b/studio/backend/tests/test_stt_transformers_worker.py
@@ -0,0 +1,1049 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The out-of-process Transformers dictation engine.
+
+The engine moved into a spawn child because an accelerator context is never
+returned while the process holding it lives, so the backend must not be the
+process that takes one. These cover both halves: what the child does with a
+command, and what the parent-side handle does with a child that answers late,
+dies, or is cancelled.
+"""
+
+import queue
+import signal
+import threading
+import time
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+
+import core.inference.stt_transformers_worker as worker_module
+from core.inference.stt_sidecar import (
+ SttLoadCancelledError,
+ SttModelNotDownloadedError,
+ SttTranscriptionCancelledError,
+)
+from core.inference.stt_transformers_worker import SttWorkerError, WhisperWorker
+
+# signal.Signals is populated per platform, so Windows reads a -9 exitcode back as its
+# number; it cannot produce one either (multiprocessing maps TerminateProcess to
+# -SIGTERM, and kill() is terminate() there). This only shapes the assertion below.
+_SIGKILL_TEXT = "SIGKILL" if hasattr(signal, "SIGKILL") else "SIG9"
+
+
+# ---------------------------------------------------------------------------
+# Fakes
+# ---------------------------------------------------------------------------
+
+
+class _FakeTensor:
+ def __init__(self, dtype = None) -> None:
+ self.dtype = dtype
+ self.moved_to = []
+
+ def to(self, value):
+ self.moved_to.append(value)
+ return self
+
+
+class _FakeProcessor:
+ def __init__(self) -> None:
+ self.seen_audio = None
+ self.seen_rate = None
+ self.features = _FakeTensor()
+
+ def __call__(
+ self,
+ audio,
+ sampling_rate = None,
+ return_tensors = None,
+ ):
+ self.seen_audio = audio
+ self.seen_rate = sampling_rate
+ return SimpleNamespace(input_features = self.features)
+
+ def batch_decode(self, _generated, **_kwargs):
+ return ["hello"]
+
+
+class _FakeModel:
+ def __init__(self, dtype = "float16") -> None:
+ self.dtype = dtype
+ self.device = "cuda"
+ self.generation_config = SimpleNamespace(is_multilingual = True)
+ self.generate_kwargs = None
+ self.moved_to = None
+ self.evaluated = False
+
+ def to(self, device):
+ self.moved_to = device
+ return self
+
+ def eval(self):
+ self.evaluated = True
+ return self
+
+ def generate(self, _features, **kwargs):
+ self.generate_kwargs = kwargs
+ return [[1]]
+
+
+class _FakeProcess:
+ """Stands in for mp.Process; alive until something ends it."""
+
+ def __init__(
+ self,
+ pid = 4242,
+ alive = True,
+ ) -> None:
+ self.pid = pid
+ self._alive = alive
+ self.exitcode = None
+ self.terminated = False
+ self.killed = False
+
+ def is_alive(self):
+ return self._alive
+
+ def join(self, _timeout = None):
+ return None
+
+ def terminate(self):
+ self.terminated = True
+ self._alive = False
+ self.exitcode = -15
+
+ def kill(self):
+ self.killed = True
+ self._alive = False
+ self.exitcode = -9
+
+
+def _wired_worker(process = None):
+ """A handle wired to in-process queues, so no child is ever spawned."""
+ handle = WhisperWorker()
+ handle._process = process if process is not None else _FakeProcess()
+ handle._cmd_queue = queue.Queue()
+ handle._resp_queue = queue.Queue()
+ handle._cancel_event = threading.Event()
+ return handle
+
+
+def _install_fake_transformers(
+ monkeypatch,
+ model = None,
+ processor = None,
+):
+ fake_model = model if model is not None else _FakeModel()
+ fake_processor = processor if processor is not None else _FakeProcessor()
+ calls = []
+
+ class FakeWhisperForConditionalGeneration:
+ @classmethod
+ def from_pretrained(cls, path, **kwargs):
+ calls.append(("model", path, kwargs))
+ return fake_model
+
+ class FakeWhisperProcessor:
+ @classmethod
+ def from_pretrained(cls, path, **kwargs):
+ calls.append(("processor", path, kwargs))
+ return fake_processor
+
+ class _NoGrad:
+ def __enter__(self):
+ return None
+
+ def __exit__(self, *_args):
+ return False
+
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "transformers",
+ SimpleNamespace(
+ WhisperForConditionalGeneration = FakeWhisperForConditionalGeneration,
+ WhisperProcessor = FakeWhisperProcessor,
+ StoppingCriteriaList = list,
+ ),
+ )
+ monkeypatch.setitem(
+ __import__("sys").modules,
+ "torch",
+ SimpleNamespace(
+ float16 = "float16",
+ float32 = "float32",
+ device = lambda value: value,
+ no_grad = _NoGrad,
+ ),
+ )
+ return calls, fake_model, fake_processor
+
+
+# ---------------------------------------------------------------------------
+# Child: loading
+# ---------------------------------------------------------------------------
+
+
+def test_child_loads_from_the_model_hub_cache_without_an_implicit_download(monkeypatch):
+ calls, model, _processor = _install_fake_transformers(monkeypatch)
+
+ worker_module.load_whisper("/cached/model", "cuda", "float16")
+
+ assert {(kind, path) for kind, path, _ in calls} == {
+ ("processor", "/cached/model"),
+ ("model", "/cached/model"),
+ }
+ # Never fetch weights implicitly; the Model Hub owns downloads.
+ assert all(kwargs.get("local_files_only") is True for _, _, kwargs in calls)
+ # The weight load forces safetensors so a pickle checkpoint cannot execute.
+ model_kwargs = next(kwargs for kind, _, kwargs in calls if kind == "model")
+ assert model_kwargs.get("use_safetensors") is True
+ assert model_kwargs.get("torch_dtype") == "float16"
+ assert model.moved_to == "cuda"
+ assert model.evaluated is True
+
+
+def test_child_load_stops_at_the_first_checkpoint_after_a_cancel(monkeypatch):
+ _calls, model, _processor = _install_fake_transformers(monkeypatch)
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ with pytest.raises(SttLoadCancelledError):
+ worker_module.load_whisper("/cached/model", "cuda", "float16", cancel_event)
+
+ # Cancelled before the weights could reach the accelerator.
+ assert model.moved_to is None
+
+
+def test_child_falls_back_to_float32_for_an_unknown_dtype_name(monkeypatch):
+ calls, _model, _processor = _install_fake_transformers(monkeypatch)
+
+ worker_module.load_whisper("/cached/model", "cpu", "bfloat9")
+
+ model_kwargs = next(kwargs for kind, _, kwargs in calls if kind == "model")
+ assert model_kwargs.get("torch_dtype") == "float32"
+
+
+# ---------------------------------------------------------------------------
+# Child: transcription
+# ---------------------------------------------------------------------------
+
+
+def test_child_feeds_decoded_pcm_and_matches_the_model_dtype(monkeypatch):
+ _calls, model, processor = _install_fake_transformers(monkeypatch)
+ pcm = np.arange(4, dtype = np.float32).tobytes()
+
+ text = worker_module.transcribe_window(
+ model, processor, pcm, {"task": "transcribe", "num_beams": 5}
+ )
+
+ assert text == "hello"
+ assert processor.seen_rate == 16000
+ assert np.array_equal(processor.seen_audio, np.arange(4, dtype = np.float32))
+ # to(device) then to(dtype): features must match the weights they meet.
+ assert processor.features.moved_to == ["cuda", "float16"]
+ assert model.generate_kwargs == {"task": "transcribe", "num_beams": 5}
+
+
+def test_child_only_installs_stopping_criteria_for_a_cancellable_request(monkeypatch):
+ _calls, model, processor = _install_fake_transformers(monkeypatch)
+ cancel_event = threading.Event()
+ pcm = np.zeros(4, dtype = np.float32).tobytes()
+
+ worker_module.transcribe_window(model, processor, pcm, {}, cancel_event)
+ criteria = model.generate_kwargs["stopping_criteria"]
+
+ assert criteria[0]() is False
+ cancel_event.set()
+ assert criteria[0]() is True
+
+ worker_module.transcribe_window(model, processor, pcm, {})
+ assert "stopping_criteria" not in model.generate_kwargs
+
+
+# ---------------------------------------------------------------------------
+# Child: command loop
+# ---------------------------------------------------------------------------
+
+
+def _run_child(
+ monkeypatch,
+ commands,
+ *,
+ load = None,
+ transcribe = None,
+):
+ """Drive run_stt_worker over in-process queues and collect its responses.
+
+ The bootstrap handshake is asserted here and dropped, so each test reads the
+ answers to its own commands.
+ """
+ cmd_queue: queue.Queue = queue.Queue()
+ resp_queue: queue.Queue = queue.Queue()
+ cancel_event = threading.Event()
+ if load is not None:
+ monkeypatch.setattr(worker_module, "load_whisper", load)
+ if transcribe is not None:
+ monkeypatch.setattr(worker_module, "transcribe_window", transcribe)
+ for command in commands:
+ cmd_queue.put(command)
+ ready_event = threading.Event()
+ thread = threading.Thread(
+ target = worker_module.run_stt_worker,
+ kwargs = {
+ "cmd_queue": cmd_queue,
+ "resp_queue": resp_queue,
+ "cancel_event": cancel_event,
+ "ready_event": ready_event,
+ "config": {},
+ },
+ daemon = True,
+ )
+ thread.start()
+ thread.join(timeout = 10)
+ assert thread.is_alive() is False
+ assert ready_event.is_set() is True
+ responses = []
+ while not resp_queue.empty():
+ responses.append(resp_queue.get_nowait())
+ return responses, cancel_event
+
+
+def test_child_reports_the_loaded_model_then_transcribes_then_exits(monkeypatch):
+ model = _FakeModel()
+ model.generation_config = SimpleNamespace(is_multilingual = False)
+ responses, _cancel = _run_child(
+ monkeypatch,
+ [
+ {
+ "type": "load",
+ "snapshot_path": "/cached/model",
+ "device": "cuda",
+ "dtype": "float16",
+ },
+ {"type": "transcribe", "audio": b"", "generate_kwargs": {}, "cancellable": False},
+ {"type": "shutdown"},
+ ],
+ load = lambda *_args, **_kwargs: (model, _FakeProcessor()),
+ transcribe = lambda *_args, **_kwargs: "hello",
+ )
+
+ assert responses == [
+ {"type": "loaded", "device": "cuda", "is_multilingual": False},
+ {"type": "text", "text": "hello"},
+ {"type": "shutdown_ack"},
+ ]
+
+
+def test_child_exits_after_a_failed_load_so_a_half_taken_context_goes_with_it(monkeypatch):
+ def boom(*_args, **_kwargs):
+ raise RuntimeError("out of memory")
+
+ responses, _cancel = _run_child(
+ monkeypatch,
+ # The transcribe would be answered if the child stayed in its loop.
+ [
+ {
+ "type": "load",
+ "snapshot_path": "/cached/model",
+ "device": "cuda",
+ "dtype": "float16",
+ },
+ {"type": "transcribe", "audio": b"", "generate_kwargs": {}, "cancellable": False},
+ ],
+ load = boom,
+ )
+
+ assert responses == [{"type": "error", "kind": "RuntimeError", "error": "out of memory"}]
+
+
+def test_child_survives_a_failed_transcription_and_keeps_the_model(monkeypatch):
+ def boom(*_args, **_kwargs):
+ raise ValueError("bad audio")
+
+ responses, _cancel = _run_child(
+ monkeypatch,
+ [
+ {"type": "load", "snapshot_path": "/cached/model", "device": "cpu", "dtype": "float32"},
+ {"type": "transcribe", "audio": b"", "generate_kwargs": {}, "cancellable": False},
+ {"type": "shutdown"},
+ ],
+ load = lambda *_args, **_kwargs: (_FakeModel(), _FakeProcessor()),
+ transcribe = boom,
+ )
+
+ assert [response["type"] for response in responses] == ["loaded", "error", "shutdown_ack"]
+ assert responses[1]["error"] == "bad audio"
+
+
+def test_child_reports_a_cancelled_generation_rather_than_partial_text(monkeypatch):
+ def stop_early(
+ _model,
+ _processor,
+ _pcm,
+ _kwargs,
+ cancel_event = None,
+ ):
+ cancel_event.set() # what StoppingCriteria does to a running generate
+ return "half a sen"
+
+ responses, _cancel = _run_child(
+ monkeypatch,
+ [
+ {"type": "load", "snapshot_path": "/cached/model", "device": "cpu", "dtype": "float32"},
+ {"type": "transcribe", "audio": b"", "generate_kwargs": {}, "cancellable": True},
+ {"type": "shutdown"},
+ ],
+ load = lambda *_args, **_kwargs: (_FakeModel(), _FakeProcessor()),
+ transcribe = stop_early,
+ )
+
+ assert responses[1]["kind"] == "SttTranscriptionCancelledError"
+
+
+def test_child_answers_an_unknown_command_instead_of_dropping_it(monkeypatch):
+ responses, _cancel = _run_child(
+ monkeypatch,
+ [{"type": "explode"}, {"type": "shutdown"}],
+ )
+
+ assert responses[0]["type"] == "error"
+ assert "explode" in responses[0]["error"]
+
+
+# ---------------------------------------------------------------------------
+# Error transport
+# ---------------------------------------------------------------------------
+
+
+def test_a_local_cache_miss_crosses_as_a_not_downloaded_error():
+ class LocalEntryNotFoundError(RuntimeError):
+ pass
+
+ response = worker_module._error_response(LocalEntryNotFoundError("not cached"))
+
+ assert response["kind"] == "SttModelNotDownloadedError"
+ with pytest.raises(SttModelNotDownloadedError):
+ worker_module._raise_worker_error(response)
+
+
+def test_cancellation_keeps_its_class_across_the_process_boundary():
+ response = worker_module._error_response(
+ SttTranscriptionCancelledError("Transcription cancelled.")
+ )
+
+ with pytest.raises(SttTranscriptionCancelledError, match = "cancelled"):
+ worker_module._raise_worker_error(response)
+
+
+def test_an_unknown_failure_arrives_as_a_worker_error_carrying_its_message():
+ # The exception object is never sent: a torch error that will not pickle
+ # would cost the caller its whole timeout instead of an error.
+ response = worker_module._error_response(TypeError("weird"))
+
+ assert response == {"type": "error", "kind": "TypeError", "error": "weird"}
+ with pytest.raises(SttWorkerError, match = "weird"):
+ worker_module._raise_worker_error(response)
+
+
+# ---------------------------------------------------------------------------
+# Parent handle
+# ---------------------------------------------------------------------------
+
+
+def test_handle_sends_one_window_and_returns_its_text():
+ handle = _wired_worker()
+ handle._resp_queue.put({"type": "text", "text": "hello"})
+
+ text = handle.transcribe_window(b"\x00\x00\x00\x00", {"num_beams": 1})
+
+ assert text == "hello"
+ command = handle._cmd_queue.get_nowait()
+ assert command["type"] == "transcribe"
+ assert command["generate_kwargs"] == {"num_beams": 1}
+ assert command["cancellable"] is False
+
+
+def test_handle_reports_a_dead_child_instead_of_waiting_out_its_timeout():
+ process = _FakeProcess(alive = False)
+ process.exitcode = -9
+ handle = _wired_worker(process)
+
+ with pytest.raises(SttWorkerError, match = _SIGKILL_TEXT):
+ handle.transcribe_window(b"", {})
+
+
+def test_handle_kills_a_child_that_stops_answering():
+ process = _FakeProcess()
+ handle = _wired_worker(process)
+
+ with pytest.raises(SttWorkerError, match = "stopped responding"):
+ handle._await("text", 0.0, None, "transcribe")
+
+ assert process.killed or process.terminated
+
+
+def test_handle_mirrors_a_request_cancel_into_the_child():
+ handle = _wired_worker()
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ def answer_once():
+ # The child sees the shared event and reports the cancellation itself.
+ time.sleep(0.2)
+ handle._resp_queue.put(
+ {
+ "type": "error",
+ "kind": "SttTranscriptionCancelledError",
+ "error": "Transcription cancelled.",
+ }
+ )
+
+ thread = threading.Thread(target = answer_once, daemon = True)
+ thread.start()
+ with pytest.raises(SttTranscriptionCancelledError):
+ handle._await("text", 30.0, cancel_event, "transcribe")
+ thread.join(timeout = 5)
+
+ assert handle._cancel_event.is_set()
+
+
+def test_a_cancelled_load_that_never_answers_is_killed_rather_than_waited_on(monkeypatch):
+ # from_pretrained reaches no checkpoint, and training is waiting for the memory.
+ monkeypatch.setattr(worker_module, "_CANCEL_GRACE_SECONDS", 0.0)
+ process = _FakeProcess()
+ handle = _wired_worker(process)
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ with pytest.raises(SttLoadCancelledError):
+ handle._await("loaded", 30.0, cancel_event, "load")
+
+ assert handle.is_alive() is False
+
+
+def test_the_cancel_grace_is_not_followed_by_a_second_shutdown_wait(monkeypatch):
+ # The grace IS the graceful shutdown: a child too busy inside from_pretrained to
+ # read the cancel event will not read a shutdown command either, and another
+ # _SHUTDOWN_TIMEOUT_SECONDS would block the waiting training run for twice the 10s.
+ monkeypatch.setattr(worker_module, "_CANCEL_GRACE_SECONDS", 0.0)
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda _pid: None)
+
+ class _Recording(_FakeProcess):
+ def __init__(self) -> None:
+ super().__init__()
+ self.joins = []
+
+ def join(self, timeout = None):
+ self.joins.append(timeout)
+
+ process = _Recording()
+ handle = _wired_worker(process)
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ with pytest.raises(SttLoadCancelledError):
+ handle._await("loaded", 30.0, cancel_event, "load")
+
+ # No graceful join, no shutdown command queued for a child that cannot read it.
+ assert worker_module._SHUTDOWN_TIMEOUT_SECONDS not in process.joins
+ assert process.terminated is True
+ assert handle.is_alive() is False
+
+
+ ("phase", "expected"),
+ [("load", SttLoadCancelledError), ("transcribe", SttTranscriptionCancelledError)],
+)
+def test_a_cancel_that_lands_near_the_command_timeout_keeps_its_cancellation(
+ monkeypatch, phase, expected
+):
+ # A cancel arriving in the last seconds of the timeout is still a cancellation: the
+ # caller is owed the 409 or the 499, not a 500 for a worker that "stopped
+ # responding", and not another full shutdown wait.
+ monkeypatch.setattr(worker_module, "_CANCEL_GRACE_SECONDS", 30.0)
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda _pid: None)
+
+ class _Recording(_FakeProcess):
+ def __init__(self) -> None:
+ super().__init__()
+ self.joins = []
+
+ def join(self, timeout = None):
+ self.joins.append(timeout)
+
+ process = _Recording()
+ handle = _wired_worker(process)
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ with pytest.raises(expected):
+ handle._await("text" if phase == "transcribe" else "loaded", 0.0, cancel_event, phase)
+
+ assert worker_module._SHUTDOWN_TIMEOUT_SECONDS not in process.joins
+ assert handle.is_alive() is False
+
+
+def test_closing_a_handle_normally_still_asks_the_child_to_exit_first(monkeypatch):
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda _pid: None)
+
+ class _Recording(_FakeProcess):
+ def __init__(self) -> None:
+ super().__init__()
+ self.joins = []
+
+ def join(self, timeout = None):
+ self.joins.append(timeout)
+ self._alive = False # an idle child consumes the shutdown and exits
+
+ process = _Recording()
+ handle = _wired_worker(process)
+ cmd_queue = handle._cmd_queue
+
+ handle.close()
+
+ assert cmd_queue.get_nowait() == {"type": "shutdown"}
+ assert process.joins[0] == worker_module._SHUTDOWN_TIMEOUT_SECONDS
+ assert process.terminated is False
+
+
+def test_closing_the_handle_ends_the_child_and_drops_its_pid(monkeypatch):
+ forgotten = []
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda pid: forgotten.append(pid))
+ process = _FakeProcess()
+ handle = _wired_worker(process)
+
+ handle.close()
+
+ assert forgotten == [4242]
+ assert handle.is_alive() is False
+ assert handle._cmd_queue is None
+
+
+def test_a_child_that_survives_terminate_and_kill_keeps_its_pid_and_handle(monkeypatch):
+ # A child wedged in a driver call outlives SIGKILL and still holds its accelerator
+ # memory; forgetting its pid leaves terminate_all and the sweep nothing to find it by.
+ forgotten = []
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda pid: forgotten.append(pid))
+
+ class _Unkillable(_FakeProcess):
+ def terminate(self):
+ self.terminated = True # neither signal reaches it
+
+ def kill(self):
+ self.killed = True
+
+ process = _Unkillable()
+ handle = _wired_worker(process)
+
+ closed = handle.close()
+
+ assert forgotten == []
+ assert closed is False
+ assert handle._process is process
+ assert handle.is_alive() is True
+ assert handle._cmd_queue is not None
+
+
+def test_a_child_that_outlived_a_cancelled_command_marks_its_handle_unusable(monkeypatch):
+ # The cancel grace expires and close() terminates and kills a child that answers
+ # neither, so the handle is kept for its memory. It answers no later command either,
+ # and its terminate leaves the queues liable to corruption, so the handle has to say
+ # it is spent: the cancel is raised over close(), so its False reaches nobody.
+ monkeypatch.setattr(worker_module, "_CANCEL_GRACE_SECONDS", 0.0)
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda _pid: None)
+
+ class _Unkillable(_FakeProcess):
+ def terminate(self):
+ self.terminated = True # neither signal reaches it
+
+ def kill(self):
+ self.killed = True
+
+ handle = _wired_worker(_Unkillable())
+ assert handle.survived_kill is False
+ cancel_event = threading.Event()
+ cancel_event.set()
+
+ with pytest.raises(SttTranscriptionCancelledError):
+ handle._await("text", 30.0, cancel_event, "transcribe")
+
+ assert handle.is_alive() is True
+ assert handle.survived_kill is True
+
+
+def test_a_handle_whose_child_did_exit_is_still_usable(monkeypatch):
+ # The flag is only for a child that outlived both signals; an ordinary
+ # close must not retire a handle that gave its memory back.
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda _pid: None)
+
+ handle = _wired_worker()
+
+ assert handle.close() is True
+ assert handle.survived_kill is False
+
+
+def test_closing_a_handle_that_ignores_shutdown_escalates_to_a_kill(monkeypatch):
+ monkeypatch.setattr("utils.process_lifetime.forget_pid", lambda _pid: None)
+
+ class _Stubborn(_FakeProcess):
+ def terminate(self):
+ self.terminated = True # ignores it, unlike _FakeProcess
+
+ process = _Stubborn()
+ handle = _wired_worker(process)
+
+ handle.close()
+
+ assert process.terminated is True
+ assert process.killed is True
+
+
+# ---------------------------------------------------------------------------
+# Hosts that cannot spawn
+# ---------------------------------------------------------------------------
+
+
+class _RefusingProcess:
+ """A child that cannot be created: a sandbox, or a frozen POSIX build."""
+
+ def __init__(self, error) -> None:
+ self.pid = None
+ self.exitcode = None
+ self._error = error
+
+ def is_alive(self):
+ return False
+
+ def start(self):
+ raise self._error
+
+ def join(self, _timeout = None):
+ return None
+
+
+class _RefusingContext:
+ def __init__(self, error = None) -> None:
+ self.error = error or PermissionError("spawn is not permitted here")
+
+ def Queue(self):
+ return queue.Queue()
+
+ def Event(self):
+ return threading.Event()
+
+ def Process(self, **_kwargs):
+ return _RefusingProcess(self.error)
+
+
+def test_dictation_still_loads_and_transcribes_when_no_child_can_be_started(monkeypatch):
+ # This may only move work out of the backend, never remove a working
+ # configuration: a host that forbids spawn had dictation before.
+ from core.inference.stt_sidecar import WhisperSttSidecar
+
+ monkeypatch.setattr(worker_module, "_CTX", _RefusingContext())
+ _calls, _model, _processor = _install_fake_transformers(monkeypatch)
+
+ engine = WhisperSttSidecar(keep_alive_seconds = 0)._build_model(
+ "/cached/model", "cpu", "float32", threading.Event()
+ )
+
+ assert isinstance(engine, worker_module.InProcessWhisperEngine)
+ assert engine.device == "cpu"
+ assert engine.is_alive() is True
+ assert engine.transcribe_window(np.zeros(4, dtype = np.float32).tobytes(), {}) == "hello"
+
+
+def test_a_spawn_failure_on_an_accelerator_leaves_the_cpu_retry_to_the_sidecar(monkeypatch):
+ # An in-process load takes the context this module exists to avoid, so the fallback
+ # is CPU only; the accelerator attempt must reach the sidecar's own CPU retry first.
+ from core.inference.stt_sidecar import WhisperSttSidecar
+
+ monkeypatch.setattr(worker_module, "_CTX", _RefusingContext())
+ monkeypatch.setattr(
+ worker_module,
+ "load_whisper",
+ lambda *_args, **_kwargs: pytest.fail("no in-process load on an accelerator"),
+ )
+
+ with pytest.raises(worker_module.SttWorkerSpawnError, match = "not permitted"):
+ WhisperSttSidecar(keep_alive_seconds = 0)._build_model(
+ "/cached/model", "cuda", "float16", threading.Event()
+ )
+
+
+class _StillbornProcess:
+ """A child that starts but whose fresh interpreter never comes up.
+
+ A frozen POSIX build re-runs its own binary rather than an interpreter, so
+ start() returns and the child is gone before it can read a command.
+ """
+
+ def __init__(self, exitcode = 1) -> None:
+ self.pid = 4243
+ self.exitcode = None
+ self._exitcode = exitcode
+
+ def start(self):
+ self.exitcode = self._exitcode
+
+ def is_alive(self):
+ return False
+
+ def join(self, _timeout = None):
+ return None
+
+ def terminate(self):
+ pass
+
+ def kill(self):
+ pass
+
+
+class _StillbornContext:
+ def __init__(self, exitcode = 1) -> None:
+ self.exitcode = exitcode
+
+ def Queue(self):
+ return queue.Queue()
+
+ def Event(self):
+ return threading.Event()
+
+ def Process(self, **_kwargs):
+ return _StillbornProcess(self.exitcode)
+
+
+def test_a_child_that_never_bootstraps_reads_as_a_host_that_cannot_spawn(monkeypatch):
+ # start() succeeding says only that the exec worked. A child that dies before
+ # answering took no device, so it must reach the fallback, not a second child.
+ from core.inference.stt_sidecar import WhisperSttSidecar
+
+ monkeypatch.setattr(worker_module, "_CTX", _StillbornContext())
+ _calls, _model, _processor = _install_fake_transformers(monkeypatch)
+
+ engine = WhisperSttSidecar(keep_alive_seconds = 0)._build_model(
+ "/cached/model", "cpu", "float32", threading.Event()
+ )
+
+ assert isinstance(engine, worker_module.InProcessWhisperEngine)
+ assert engine.device == "cpu"
+
+
+def test_a_child_killed_by_a_signal_keeps_its_crash_instead_of_falling_back(monkeypatch):
+ # A child the box killed under memory pressure bootstrapped fine, so spawn
+ # works here; loading the same model in the backend would only repeat it.
+ monkeypatch.setattr(worker_module, "_CTX", _StillbornContext(exitcode = -9))
+ monkeypatch.setattr(
+ worker_module,
+ "load_whisper",
+ lambda *_args, **_kwargs: pytest.fail("no in-process load after a real crash"),
+ )
+
+ handle = WhisperWorker()
+ with pytest.raises(SttWorkerError, match = _SIGKILL_TEXT) as caught:
+ handle.start("/cached/model", "cpu", "float32")
+
+ assert isinstance(caught.value, worker_module.SttWorkerSpawnError) is False
+
+
+class _NativeCrashProcess:
+ """A child that bootstraps and then dies inside the native model load.
+
+ Runs the real child entrypoint, whose load neither returns nor reports
+ anything, exactly as a fault in native code does not; the process is then
+ simply gone. Its exit code is positive because Windows has no signals to
+ report a fault with (0xC0000005 reads as 3221225477), which is what a child
+ that never bootstrapped looks like from the exit code alone.
+ """
+
+ def __init__(self, kwargs, faulted: threading.Event) -> None:
+ self.pid = 4244
+ self.exitcode = None
+ self._kwargs = kwargs
+ self._faulted = faulted
+
+ def start(self):
+ thread = threading.Thread(
+ target = worker_module.run_stt_worker,
+ kwargs = self._kwargs,
+ daemon = True,
+ )
+ thread.start()
+
+ def is_alive(self):
+ if self._faulted.is_set():
+ self.exitcode = 3221225477 # 0xC0000005, STATUS_ACCESS_VIOLATION
+ return False
+ return True
+
+ def join(self, _timeout = None):
+ return None
+
+ def terminate(self):
+ pass
+
+ def kill(self):
+ pass
+
+
+class _NativeCrashContext:
+ """Spawns a child that comes up and then faults in the model load."""
+
+ def __init__(self, faulted: threading.Event) -> None:
+ self._faulted = faulted
+ self._queues: list = []
+
+ def Queue(self):
+ made: queue.Queue = queue.Queue()
+ self._queues.append(made)
+ return made
+
+ def Event(self):
+ return threading.Event()
+
+ def Process(self, **kwargs):
+ # Forward what start() actually passed, ready_event included: rebuilding the
+ # kwargs would drop it, and readiness is the whole signal this test turns on.
+ process = _NativeCrashProcess(dict(kwargs.get("kwargs") or {}), self._faulted)
+ self._process = process
+ return process
+
+
+def _fault_in_the_native_load(monkeypatch, faulted: threading.Event, forever: threading.Event):
+ def _fault(*_args, **_kwargs):
+ # A fault in native code reports nothing and never comes back.
+ faulted.set()
+ forever.wait(30)
+ raise AssertionError("the crashed child was resumed")
+
+ monkeypatch.setattr(worker_module, "load_whisper", _fault)
+
+
+def test_a_child_that_crashed_in_the_load_is_not_read_as_a_host_that_cannot_spawn(monkeypatch):
+ # A native crash under the load kills the child with a positive exit code on Windows,
+ # where there are no signals. That child bootstrapped, so spawn works here: reading
+ # it as a host that cannot spawn would repeat the native load inside the backend.
+ faulted = threading.Event()
+ forever = threading.Event()
+ monkeypatch.setattr(worker_module, "_CTX", _NativeCrashContext(faulted))
+ _fault_in_the_native_load(monkeypatch, faulted, forever)
+
+ handle = WhisperWorker()
+ try:
+ with pytest.raises(SttWorkerError) as caught:
+ handle.start("/cached/model", "cpu", "float32")
+ finally:
+ forever.set()
+
+ assert faulted.is_set()
+ assert isinstance(caught.value, worker_module.SttWorkerSpawnError) is False
+
+
+def test_a_crash_in_the_child_load_is_never_repeated_inside_the_backend(monkeypatch):
+ # The fallback exists for a host that cannot bring a child up. A load that crashes
+ # the child crashes the backend too, and the backend is what the user talks to.
+ from core.inference.stt_sidecar import WhisperSttSidecar
+
+ faulted = threading.Event()
+ forever = threading.Event()
+ monkeypatch.setattr(worker_module, "_CTX", _NativeCrashContext(faulted))
+ _fault_in_the_native_load(monkeypatch, faulted, forever)
+ monkeypatch.setattr(
+ worker_module.InProcessWhisperEngine,
+ "start",
+ lambda *_args, **_kwargs: pytest.fail("no in-process load after a crash in the child"),
+ )
+
+ try:
+ with pytest.raises(SttWorkerError):
+ WhisperSttSidecar(keep_alive_seconds = 0)._build_model(
+ "/cached/model", "cpu", "float32", threading.Event()
+ )
+ finally:
+ forever.set()
+
+
+def test_the_child_says_it_is_ready_before_it_touches_a_command(monkeypatch):
+ # The handshake is what separates a host that cannot spawn from a child that
+ # failed at something, so it has to precede even a load that fails.
+ cmd_queue: queue.Queue = queue.Queue()
+ resp_queue: queue.Queue = queue.Queue()
+
+ def boom(*_args, **_kwargs):
+ raise RuntimeError("kaboom")
+
+ monkeypatch.setattr(worker_module, "load_whisper", boom)
+ cmd_queue.put(
+ {"type": "load", "snapshot_path": "/cached/model", "device": "cpu", "dtype": "float32"}
+ )
+ ready_event = threading.Event()
+ worker_module.run_stt_worker(
+ cmd_queue = cmd_queue,
+ resp_queue = resp_queue,
+ cancel_event = threading.Event(),
+ ready_event = ready_event,
+ config = {},
+ )
+
+ assert ready_event.is_set() is True
+ assert resp_queue.get_nowait()["kind"] == "RuntimeError"
+
+
+def test_the_in_process_fallback_reports_the_checkpoint_language_support(monkeypatch):
+ _calls, model, _processor = _install_fake_transformers(monkeypatch)
+ model.generation_config = SimpleNamespace(is_multilingual = False)
+
+ engine = worker_module.InProcessWhisperEngine()
+ engine.start("/cached/model", "cpu", "float32")
+
+ # The sidecar reads this to drop the kwargs an English-only model rejects.
+ assert engine.generation_config.is_multilingual is False
+ engine.close()
+ assert engine.is_alive() is False
+
+
+class _LosesTheReadyMessage(queue.Queue):
+ """A response queue that drops the ready word, as a real one does.
+
+ multiprocessing.Queue.put only hands the object to a feeder thread. A child
+ that faults before that thread drains the buffer delivers nothing, and the
+ load command is already queued when the child reaches get(), so it faults
+ almost immediately: measured at 17 losses in 20 runs, against 0 for an
+ Event. A thread queue.Queue delivers in the caller, which is why a queued
+ handshake looks sound in tests and is not.
+ """
+
+ def put(self, item, *args, **kwargs):
+ if isinstance(item, dict) and item.get("type") == "ready":
+ return
+ return super().put(item, *args, **kwargs)
+
+
+class _LossyNativeCrashContext(_NativeCrashContext):
+ def Queue(self):
+ made = _LosesTheReadyMessage()
+ self._queues.append(made)
+ return made
+
+
+def test_a_crashed_child_whose_ready_word_was_lost_is_still_not_read_as_a_bad_host(monkeypatch):
+ # The child came up and faulted in the native load, but its queued ready
+ # never reached the backend. Classifying that as a host that cannot spawn
+ # sends the same crashing load into the backend, which does not survive it.
+ faulted = threading.Event()
+ forever = threading.Event()
+ monkeypatch.setattr(worker_module, "_CTX", _LossyNativeCrashContext(faulted))
+ _fault_in_the_native_load(monkeypatch, faulted, forever)
+
+ handle = WhisperWorker()
+ try:
+ with pytest.raises(SttWorkerError) as caught:
+ handle.start("/cached/model", "cpu", "float32")
+ finally:
+ forever.set()
+
+ assert faulted.is_set()
+ assert isinstance(caught.value, worker_module.SttWorkerSpawnError) is False