fix(whisper): survive CUDA OOM with a memory-lean fallback ladder
All checks were successful
CI / lint-and-test (pull_request) Successful in 11s
Version bump / version-bump (pull_request) Successful in 6s

large-v3 in float16 (~4.5 GB) left a 6 GB card no headroom for CTranslate2
decoder spikes, so long transcriptions died partway through with
"CUDA failed with error out of memory".

- default to int8_float16 on CUDA and pin CT2_CUDA_ALLOCATOR=cub_caching
- on a CUDA OOM, drop and release the model and retry a smaller-footprint
  config (int8 + greedy decoding, then CPU int8) instead of aborting
This commit is contained in:
pedro-bento 2026-10-17 20:57:22 +01:00
parent 1718b95261
commit 7949903c89
3 changed files with 246 additions and 18 deletions

View file

@ -70,6 +70,15 @@ to also write the `.kdenlive` project.
Presets: `super-relaxed`, `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.
## GPU notes (Linux / NVIDIA)
Transcription is memory-lean and degrades instead of crashing: cadence starts
with `int8_float16` and, if CTranslate2 still runs out of VRAM partway through a
long file (common with `large-v3` on a 6 GB card), it drops and releases the
model and retries with `int8` + greedy decoding before finally falling back to
CPU. When unset, `CT2_CUDA_ALLOCATOR=cub_caching` is selected for a more robust
allocator.
## Development
Run the linter and tests locally:

View file

@ -118,6 +118,16 @@ VERBATIM_PROMPT = (
"Verbatim transcription with all hesitations, stutters, and verbal fillers like um, uh, er."
)
# faster-whisper / CTranslate2 GPU configs tried in order when transcription
# runs out of VRAM. large-v3 in float16 needs ~4.5 GB, which leaves a 6 GB card
# no headroom for decoder spikes, so we start memory-lean and step down on OOM.
# Each tuple is (device, compute_type, beam_size).
FASTER_WHISPER_FALLBACKS: tuple[tuple[str, str, int], ...] = (
("cuda", "int8_float16", 5),
("cuda", "int8", 1),
("cpu", "int8", 1),
)
@dataclass(frozen=True, slots=True)
class Word:
@ -403,18 +413,42 @@ def _transcribe_mlx(
return words, raw_segments
def _load_faster_whisper_model(model_size: str):
def _configure_ct2_cuda_allocator() -> None:
"""Prefer CTranslate2's caching CUDA allocator.
CTranslate2's default ``cuda_malloc_async`` allocator can surface spurious
"CUDA failed with error out of memory" errors under fragmentation or memory
pressure (OpenNMT/CTranslate2#690); ``cub_caching`` reuses freed blocks and
is more robust across a long transcription. Must be set before
``ctranslate2``/``faster_whisper`` is imported.
"""
if platform.system() == "Linux":
os.environ.setdefault("CT2_CUDA_ALLOCATOR", "cub_caching")
def _load_faster_whisper_model(
model_size: str,
device: str | None = None,
compute_type: str | None = None,
):
_configure_ct2_cuda_allocator()
preload_nvidia_libs()
from faster_whisper import WhisperModel
target_device = "cuda" if platform.system() == "Linux" else "cpu"
target_compute = "float16" if target_device == "cuda" else "int8"
if device is None:
# Default path keeps the historical CPU fallback when GPU init fails.
device = "cuda" if platform.system() == "Linux" else "cpu"
compute_type = compute_type or ("int8_float16" if device == "cuda" else "int8")
try:
return WhisperModel(model_size, device=device, compute_type=compute_type)
except Exception as e:
if device == "cpu":
raise
logger.info(f"[*] {device.upper()} init failed ({e}), falling back to CPU.")
return WhisperModel(model_size, device="cpu", compute_type="int8")
try:
return WhisperModel(model_size, device=target_device, compute_type=target_compute)
except Exception as e:
logger.info(f"[*] {target_device.upper()} init failed ({e}), falling back to CPU.")
return WhisperModel(model_size, device="cpu", compute_type="int8")
# Explicit device/compute_type (fallback ladder): honour it strictly.
return WhisperModel(model_size, device=device, compute_type=compute_type or "int8")
def _release_cuda_memory() -> None:
@ -460,23 +494,26 @@ def _offload_align_cache(align_cache: dict | None) -> None:
_release_cuda_memory()
def _transcribe_faster_whisper(
wav: Path,
model_size: str,
language: str = "en",
model=None,
) -> tuple[list[Word], list[dict]]:
from tqdm import tqdm
def _is_cuda_oom(exc: BaseException) -> bool:
"""True for CTranslate2's CUDA allocation failures (not torch OOM)."""
return "out of memory" in str(exc).lower()
if model is None:
model = _load_faster_whisper_model(model_size)
def _run_faster_whisper(
wav: Path,
model,
language: str,
beam_size: int,
) -> tuple[list[Word], list[dict]]:
"""Consume one WhisperModel's segment generator into words + raw segments."""
from tqdm import tqdm
segments, meta = model.transcribe(
str(wav),
language=language,
word_timestamps=True,
vad_filter=False,
beam_size=5,
beam_size=beam_size,
condition_on_previous_text=False,
initial_prompt=VERBATIM_PROMPT,
)
@ -507,6 +544,53 @@ def _transcribe_faster_whisper(
return words, raw_segments
def _transcribe_faster_whisper(
wav: Path,
model_size: str,
language: str = "en",
model=None,
) -> tuple[list[Word], list[dict]]:
"""Transcribe with faster-whisper, stepping down VRAM usage on CUDA OOM.
When ``model`` is supplied it is used as-is (dependency injection/tests).
Otherwise the ``FASTER_WHISPER_FALLBACKS`` ladder is walked: on a CUDA out-of-
memory error the current model is dropped, its memory released, and the next,
smaller-footprint config is tried from scratch. The last error is re-raised
only after every fallback has failed.
"""
if model is not None:
return _run_faster_whisper(wav, model, language, beam_size=5)
last_exc: BaseException | None = None
for device, compute_type, beam_size in FASTER_WHISPER_FALLBACKS:
try:
attempt_model = _load_faster_whisper_model(
model_size, device=device, compute_type=compute_type
)
except Exception as e:
last_exc = e
logger.warning(f"[!] faster-whisper init failed on {device}/{compute_type}: {e}")
continue
try:
return _run_faster_whisper(wav, attempt_model, language, beam_size=beam_size)
except RuntimeError as e:
if not _is_cuda_oom(e):
raise
last_exc = e
logger.warning(
f"[!] Out of VRAM transcribing with {device}/{compute_type} "
f"(beam_size={beam_size}); retrying with a smaller footprint..."
)
finally:
del attempt_model
_release_cuda_memory()
raise RuntimeError(
f"Transcription failed on every fallback for {wav.name}: {last_exc}"
)
def _cache_key(model: str, backend: str, language: str) -> str:
return hashlib.sha256(
json.dumps([backend, language, model]).encode()

View file

@ -0,0 +1,135 @@
"""CUDA OOM fallback for faster-whisper transcription.
faster-whisper large-v3 in float16 needs ~4.5 GB, leaving a 6 GB card no
headroom for CTranslate2 decoder spikes, so a long transcription can die
partway through with ``CUDA failed with error out of memory``. The loader must
start memory-lean and ``_transcribe_faster_whisper`` must step down a fallback
ladder (dropping and releasing each model) instead of aborting.
"""
import os
import sys
import types
from pathlib import Path
import cadence
def test_is_cuda_oom_classifies_allocation_failures():
assert cadence._is_cuda_oom(RuntimeError("CUDA failed with error out of memory"))
assert cadence._is_cuda_oom(RuntimeError("out of memory"))
assert not cadence._is_cuda_oom(RuntimeError("boom"))
def test_load_model_defaults_to_memory_lean_cuda(monkeypatch):
monkeypatch.delenv("CT2_CUDA_ALLOCATOR", raising=False)
monkeypatch.setattr(cadence.platform, "system", lambda: "Linux")
calls: list[tuple[str, dict]] = []
class _FakeWhisperModel:
def __init__(self, model_size, **kwargs):
calls.append((model_size, kwargs))
fake_module = types.SimpleNamespace(WhisperModel=_FakeWhisperModel)
monkeypatch.setitem(sys.modules, "faster_whisper", fake_module)
cadence._load_faster_whisper_model("large-v3")
assert calls == [("large-v3", {"device": "cuda", "compute_type": "int8_float16"})]
assert os.environ["CT2_CUDA_ALLOCATOR"] == "cub_caching"
def test_load_model_honours_explicit_device(monkeypatch):
monkeypatch.setattr(cadence.platform, "system", lambda: "Linux")
calls: list[tuple[str, dict]] = []
class _FakeWhisperModel:
def __init__(self, model_size, **kwargs):
calls.append((model_size, kwargs))
fake_module = types.SimpleNamespace(WhisperModel=_FakeWhisperModel)
monkeypatch.setitem(sys.modules, "faster_whisper", fake_module)
cadence._load_faster_whisper_model("large-v3", device="cpu", compute_type="int8")
# No silent substitution: the explicit config is passed straight through.
assert calls == [("large-v3", {"device": "cpu", "compute_type": "int8"})]
def test_transcribe_steps_down_ladder_on_cuda_oom(monkeypatch):
attempts: list[tuple[str, str]] = []
runs = {"n": 0}
def fake_load(model_size, device=None, compute_type=None):
attempts.append((device, compute_type))
return object()
def fake_run(wav, model, language, beam_size):
runs["n"] += 1
if runs["n"] == 1:
raise RuntimeError("CUDA failed with error out of memory")
return (
[cadence.Word("hi", 0.0, 1.0)],
[{"start": 0.0, "end": 1.0, "text": "hi"}],
)
monkeypatch.setattr(cadence, "_load_faster_whisper_model", fake_load)
monkeypatch.setattr(cadence, "_run_faster_whisper", fake_run)
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
words, raw_segments = cadence._transcribe_faster_whisper(Path("a.wav"), "large-v3")
assert words == [cadence.Word("hi", 0.0, 1.0)]
assert raw_segments == [{"start": 0.0, "end": 1.0, "text": "hi"}]
assert attempts == [("cuda", "int8_float16"), ("cuda", "int8")]
def test_transcribe_propagates_non_oom_errors(monkeypatch):
attempts: list[tuple[str, str]] = []
def fake_load(model_size, device=None, compute_type=None):
attempts.append((device, compute_type))
return object()
def fake_run(wav, model, language, beam_size):
raise RuntimeError("unrelated")
monkeypatch.setattr(cadence, "_load_faster_whisper_model", fake_load)
monkeypatch.setattr(cadence, "_run_faster_whisper", fake_run)
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
try:
cadence._transcribe_faster_whisper(Path("a.wav"), "large-v3")
except RuntimeError as e:
assert "unrelated" in str(e)
else:
raise AssertionError("expected RuntimeError")
# A non-OOM error must not be swallowed into a second attempt.
assert len(attempts) == 1
def test_transcribe_raises_after_every_fallback_fails(monkeypatch):
attempts: list[tuple[str, str]] = []
def fake_load(model_size, device=None, compute_type=None):
attempts.append((device, compute_type))
return object()
def fake_run(wav, model, language, beam_size):
raise RuntimeError("CUDA failed with error out of memory")
monkeypatch.setattr(cadence, "_load_faster_whisper_model", fake_load)
monkeypatch.setattr(cadence, "_run_faster_whisper", fake_run)
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
try:
cadence._transcribe_faster_whisper(Path("a.wav"), "large-v3")
except RuntimeError as e:
assert "fallback" in str(e)
else:
raise AssertionError("expected RuntimeError")
assert len(attempts) == len(cadence.FASTER_WHISPER_FALLBACKS)