Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(stt): stop losing the GPU to a CUDA library sitting off the search path

Ruben Lütkeeedd199ace1f
diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.py
index 5ba4652e2a..54c2411793 100644
--- a/jarvis/plugins/stt/fwhisper.py
+++ b/jarvis/plugins/stt/fwhisper.py
@@ -11,10 +11,12 @@ from __future__ import annotations
import contextlib
import logging
+import os
import sys
import threading
from collections.abc import AsyncIterator, Iterator
-from typing import Any
+from pathlib import Path
+from typing import Any, Final
import numpy as np
@@ -190,6 +192,119 @@ def _cpu_safe_compute_type(compute_type: str) -> str:
return compute_type
+#: Package directories that ship the CUDA runtime DLLs ctranslate2 links
+#: against, relative to a site-packages root. ``torch`` carries a complete set
+#: (``cublas64_12.dll``, ``cudnn64_9.dll``, ...) and the standalone
+#: ``nvidia-*-cu12`` wheels carry them one subdirectory deeper, so a host with
+#: either is covered without depending on either.
+_CUDA_DLL_PACKAGE_DIRS: Final[tuple[tuple[str, ...], ...]] = (
+ ("torch", "lib"),
+ ("nvidia", "cublas", "bin"),
+ ("nvidia", "cudnn", "bin"),
+)
+
+#: Loaded explicitly, in dependency order, once a directory holding them is
+#: found. Adding that directory to the search path is NOT enough on its own —
+#: measured: ctranslate2 still raised "Library cublas64_12.dll is not found or
+#: cannot be loaded" with the directory added, and succeeded once these were
+#: loaded by name. cuDNN is optional here (only some compute types reach it), so
+#: a miss on it never blocks the rest.
+_CUDA_DLL_PRELOAD: Final[tuple[str, ...]] = (
+ "cublasLt64_12.dll", # cublas depends on it — must come first
+ "cublas64_12.dll",
+ "cudnn64_9.dll",
+)
+
+#: Set once the libraries are actually in the process, so repeated model builds
+#: do not re-walk site-packages.
+_cuda_dll_path_prepared = False
+
+
+def ensure_cuda_libraries_findable() -> None:
+ """Load the CUDA runtime DLLs ctranslate2 needs, on Windows. No-op elsewhere.
+
+ This does NOT decide, promise, or probe whether the GPU is usable (AP-25) —
+ it only removes a way for the question to be answered wrongly. The existing
+ ``cuda -> cpu`` self-heal in :meth:`FasterWhisperProvider._ensure_model`
+ remains the verdict, and a machine where this changes nothing lands there
+ exactly as before.
+
+ Why it is needed at all: on Windows ``cublas64_12.dll`` is resolved through
+ the DLL search path, and a pip-installed ``torch`` keeps its copy inside its
+ OWN package directory, which is not on that path. ctranslate2 then fails
+ with ``Library cublas64_12.dll is not found or cannot be loaded`` on a
+ machine that demonstrably has a working CUDA stack — measured on an RTX 5070
+ Ti with the same runtime reporting CUDA available. The configured GPU device
+ fell back to the CPU on every load: honest behaviour, wrong outcome. The
+ local recogniser ran at ~1.1x realtime, an 8 s dictation segment taking a
+ full 8 s, where the same model on the GPU runs at ~7.9x and that segment
+ takes 1.05 s (measured 2026-07-30, large-v3/int8_float16).
+
+ Both halves are load-bearing and were separated by measurement:
+ ``add_dll_directory`` alone did NOT fix it (the failure reproduced with the
+ directory added), and loading the libraries by name did — the directory
+ entry is what then lets their own dependencies resolve.
+
+ Deliberately does NOT import torch: only the spec's location is needed.
+ Importing it would cost seconds on a lazy path and collide with
+ :func:`inference_only_import_shield`, which stubs that exact module while
+ ctranslate2 loads.
+
+ Never raises. Every failure mode — not Windows, no such package, no DLLs in
+ it — is an ordinary state on some install and leaves the process untouched.
+ """
+ global _cuda_dll_path_prepared
+ if _cuda_dll_path_prepared:
+ return
+ add_dll_directory = getattr(os, "add_dll_directory", None)
+ if add_dll_directory is None:
+ # POSIX resolves shared libraries through the loader's own search path,
+ # where a pip-installed CUDA runtime already lands. Nothing to do.
+ _cuda_dll_path_prepared = True
+ return
+ import ctypes
+ import importlib.util
+
+ for parts in _CUDA_DLL_PACKAGE_DIRS:
+ try:
+ spec = importlib.util.find_spec(parts[0])
+ except (ImportError, ValueError):
+ # ValueError is what find_spec raises for a module stubbed as None
+ # in sys.modules — exactly what the import shield does to torch.
+ # Leaving the flag unset means a later build tries again.
+ continue
+ origin = getattr(spec, "origin", None) if spec is not None else None
+ if not origin:
+ continue
+ directory = Path(origin).parent.joinpath(*parts[1:])
+ if not directory.is_dir() or not any(directory.glob("cublas64_*.dll")):
+ continue
+ with contextlib.suppress(OSError):
+ # Lets the loaded libraries find their own dependencies by name.
+ add_dll_directory(str(directory))
+ loaded = []
+ for name in _CUDA_DLL_PRELOAD:
+ library = directory / name
+ if not library.is_file():
+ continue
+ try:
+ ctypes.WinDLL(str(library))
+ except OSError as exc:
+ log.debug("could not load %s: %s", library, exc)
+ continue
+ loaded.append(name)
+ if not any(name.startswith("cublas64") for name in loaded):
+ continue # the one that actually blocks ctranslate2 is still missing
+ log.info(
+ "CUDA runtime libraries loaded from %s (%s) — the GPU device is now "
+ "reachable. Whether it works is still decided by the model build.",
+ directory,
+ ", ".join(loaded),
+ )
+ _cuda_dll_path_prepared = True
+ return
+
+
def _new_whisper_model(
model_name: str, device: str, compute_type: str, cpu_threads: int = 0
) -> Any:
@@ -211,6 +326,10 @@ def _new_whisper_model(
internal cross-thread contention. Only the wake model sets this (it coexists
with torch on the always-on loop); the utterance STT keeps auto threads.
"""
+ if device != "cpu":
+ # Before the engine loads, not after it failed: the load is where the
+ # DLL is resolved, and a miss there costs the GPU for the whole session.
+ ensure_cuda_libraries_findable()
with inference_only_import_shield():
from faster_whisper import WhisperModel
diff --git a/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.py b/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.py
new file mode 100644
index 0000000000..2e6a1bf3a4
--- /dev/null
+++ b/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.py
@@ -0,0 +1,211 @@
+"""The GPU device must not be lost to a CUDA library sitting off the search path.
+
+A pip-installed torch keeps ``cublas64_12.dll`` inside its own package
+directory, which is not on Windows' DLL search path. ctranslate2 then fails with
+``Library cublas64_12.dll is not found or cannot be loaded`` on a machine whose
+CUDA stack demonstrably works, and the provider's ``cuda -> cpu`` self-heal
+quietly takes the local recogniser from ~7.9x realtime down to ~1.1x — an 8 s
+dictation segment going from 1.05 s to a full 8 s.
+
+These tests pin the CONTRACT, not the platform: the helper must be a silent
+no-op wherever it cannot help, must never raise, and must not import torch.
+"""
+
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+from jarvis.plugins.stt import fwhisper
+
+
[email protected](autouse=True)
+def _reset_module_flag(monkeypatch):
+ """Each test starts with the helper un-run."""
+ monkeypatch.setattr(fwhisper, "_cuda_dll_path_prepared", False)
+
+
+class TestItNeverCostsAnything:
+ def test_it_is_a_no_op_where_there_is_no_dll_search_path(self, monkeypatch):
+ """POSIX has no ``os.add_dll_directory`` — and needs none."""
+ monkeypatch.delattr(fwhisper.os, "add_dll_directory", raising=False)
+
+ fwhisper.ensure_cuda_libraries_findable()
+
+ assert fwhisper._cuda_dll_path_prepared is True, (
+ "the no-op still counts as done, so it is not retried per model build"
+ )
+
+ def test_a_missing_package_is_an_ordinary_state(self, monkeypatch):
+ """A base install has neither torch nor the nvidia wheels."""
+ monkeypatch.setattr(
+ fwhisper.os, "add_dll_directory", lambda _p: None, raising=False
+ )
+ monkeypatch.setattr(
+ "importlib.util.find_spec", lambda _name: None
+ )
+
+ fwhisper.ensure_cuda_libraries_findable() # must not raise
+
+ assert fwhisper._cuda_dll_path_prepared is False, (
+ "nothing was loaded, so a later build must be free to try again"
+ )
+
+ def test_a_stubbed_module_does_not_end_the_search(self, monkeypatch):
+ """``inference_only_import_shield`` stubs torch as None in sys.modules.
+
+ ``find_spec`` raises ValueError for that, which must be survivable —
+ otherwise the one helper that repairs the GPU path is defeated by the
+ one shield that runs right next to it.
+ """
+ monkeypatch.setattr(
+ fwhisper.os, "add_dll_directory", lambda _p: None, raising=False
+ )
+
+ def _raise(name: str):
+ raise ValueError(f"{name}.__spec__ is None")
+
+ monkeypatch.setattr("importlib.util.find_spec", _raise)
+
+ fwhisper.ensure_cuda_libraries_findable() # must not raise
+
+ assert fwhisper._cuda_dll_path_prepared is False
+
+ def test_it_does_not_import_torch(self, monkeypatch):
+ """Importing torch here would cost seconds and fight the import shield."""
+ monkeypatch.setattr(
+ fwhisper.os, "add_dll_directory", lambda _p: None, raising=False
+ )
+ monkeypatch.setattr("importlib.util.find_spec", lambda _name: None)
+ had_torch = "torch" in sys.modules
+
+ fwhisper.ensure_cuda_libraries_findable()
+
+ if not had_torch:
+ assert "torch" not in sys.modules
+
+
+class TestItOnlyClaimsSuccessWhenItLoadedTheOne:
+ def test_a_directory_without_cublas_is_skipped(self, tmp_path, monkeypatch):
+ """cuDNN alone does not unblock ctranslate2 — cublas is the blocker."""
+ package = tmp_path / "torch"
+ (package / "lib").mkdir(parents=True)
+ (package / "lib" / "cudnn64_9.dll").write_bytes(b"")
+ (package / "__init__.py").write_text("")
+
+ added: list[str] = []
+ monkeypatch.setattr(
+ fwhisper.os, "add_dll_directory", added.append, raising=False
+ )
+ monkeypatch.setattr(
+ "importlib.util.find_spec",
+ lambda name: (
+ type("S", (), {"origin": str(package / "__init__.py")})()
+ if name == "torch"
+ else None
+ ),
+ )
+
+ fwhisper.ensure_cuda_libraries_findable()
+
+ assert fwhisper._cuda_dll_path_prepared is False
+ assert added == [], "a directory with no cublas is not worth adding"
+
+ def test_the_search_path_entry_accompanies_the_load(self, tmp_path, monkeypatch):
+ """Both halves are load-bearing, and measurement is why.
+
+ ``add_dll_directory`` ALONE did not fix the failure — it reproduced with
+ the directory added. Loading by name did. The directory entry is what
+ then lets the loaded libraries resolve their own dependencies, so a
+ version that keeps only one of the two is a regression either way.
+ """
+ package = tmp_path / "torch"
+ lib = package / "lib"
+ lib.mkdir(parents=True)
+ for name in ("cublasLt64_12.dll", "cublas64_12.dll"):
+ (lib / name).write_bytes(b"")
+ (package / "__init__.py").write_text("")
+
+ added: list[str] = []
+ loaded: list[str] = []
+ monkeypatch.setattr(
+ fwhisper.os, "add_dll_directory", added.append, raising=False
+ )
+ monkeypatch.setattr(
+ "importlib.util.find_spec",
+ lambda name: (
+ type("S", (), {"origin": str(package / "__init__.py")})()
+ if name == "torch"
+ else None
+ ),
+ )
+ # ctypes.WinDLL does not exist off Windows, so it is injected rather
+ # than patched — the test states the contract on every platform.
+ fake_ctypes = type(
+ "C", (), {"WinDLL": staticmethod(lambda path: loaded.append(path))}
+ )
+ monkeypatch.setitem(sys.modules, "ctypes", fake_ctypes)
+
+ fwhisper.ensure_cuda_libraries_findable()
+
+ assert added == [str(lib)], "the directory must be on the search path"
+ assert [p.rsplit("\\", 1)[-1].rsplit("/", 1)[-1] for p in loaded] == [
+ "cublasLt64_12.dll",
+ "cublas64_12.dll",
+ ], "cublasLt must load before the cublas that depends on it"
+ assert fwhisper._cuda_dll_path_prepared is True
+
+ def test_a_library_that_will_not_load_is_survived(self, tmp_path, monkeypatch):
+ """A present-but-broken DLL falls through to the cuda->cpu self-heal."""
+ package = tmp_path / "torch"
+ lib = package / "lib"
+ lib.mkdir(parents=True)
+ (lib / "cublas64_12.dll").write_bytes(b"")
+ (package / "__init__.py").write_text("")
+
+ monkeypatch.setattr(
+ fwhisper.os, "add_dll_directory", lambda _p: None, raising=False
+ )
+ monkeypatch.setattr(
+ "importlib.util.find_spec",
+ lambda name: (
+ type("S", (), {"origin": str(package / "__init__.py")})()
+ if name == "torch"
+ else None
+ ),
+ )
+
+ def _boom(_path):
+ raise OSError("not a valid Win32 application")
+
+ monkeypatch.setitem(
+ sys.modules, "ctypes", type("C", (), {"WinDLL": staticmethod(_boom)})
+ )
+
+ fwhisper.ensure_cuda_libraries_findable() # must not raise
+
+ assert fwhisper._cuda_dll_path_prepared is False
+
+
+def test_the_cpu_device_never_pays_for_this(monkeypatch):
+ """A CPU-only host must not walk site-packages on every model build."""
+ calls: list[int] = []
+ monkeypatch.setattr(
+ fwhisper, "ensure_cuda_libraries_findable", lambda: calls.append(1)
+ )
+ monkeypatch.setattr(
+ fwhisper, "inference_only_import_shield", lambda: __import__(
+ "contextlib"
+ ).nullcontext()
+ )
+ fake = type("M", (), {})
+ monkeypatch.setitem(
+ sys.modules,
+ "faster_whisper",
+ type("FW", (), {"WhisperModel": staticmethod(lambda *a, **k: fake)}),
+ )
+
+ fwhisper._new_whisper_model("tiny", "cpu", "int8")
+
+ assert calls == [], "the CUDA repair is for GPU devices only"