cadence/tests/test_whisper_unload.py
pedro-bento 1f9a9b4e77 fix(cuda): offload cached aligner before loading the next ASR model
On a 6 GB GPU the Wav2Vec2 aligner kept in `align_cache` across inputs was
still resident when the next input loaded Whisper large-v3, so CUDA init
failed with out-of-memory and silently fell back to CPU (catastrophic for
long recordings).

`load_or_transcribe` now offloads cached aligner weights to CPU (freeing
their VRAM) right before the ASR model loads; `_align_with_whisperx` moves
them back to the align device before aligning, since whisperx.align never
moves the model itself. Entries that cannot be moved are evicted so they
reload from scratch.
2026-10-06 20:51:15 +01:00

175 lines
5.6 KiB
Python

"""The Whisper <-> CTC-aligner VRAM handoff.
Whisper large-v3 (~4.5 GB) and the Wav2Vec2 aligner cannot both fit on a 6 GB
GPU, which made alignment fail with ``CUBLAS_STATUS_ALLOC_FAILED``. The ASR
model must therefore be dropped and its memory released *before* alignment, and
a cached aligner from an earlier input must be offloaded before the next ASR
model is loaded.
"""
import sys
import types
import cadence
class _FakeAlignModel:
"""Minimal stand-in for a torch ``nn.Module`` aligner."""
def __init__(self, fail: bool = False):
self.device = "cuda"
self.fail = fail
self.calls: list[str] = []
def to(self, device):
self.calls.append(device)
if self.fail:
raise RuntimeError("cannot move")
self.device = device
return self
def test_release_cuda_memory_is_safe_without_gpu():
# Must never raise when torch is absent or no CUDA device exists: it only
# nudges the GC and (when available) torch's CUDA cache.
assert cadence._release_cuda_memory() is None
def test_transcribe_releases_vram_before_aligning(monkeypatch, tmp_path):
events = []
def fake_transcribe(*args, **kwargs):
events.append("transcribe")
return [], [{"start": 0.0, "end": 1.0}]
def fake_release():
events.append("release")
def fake_align(**kwargs):
events.append("align")
return []
monkeypatch.setattr(cadence, "_cache_path", lambda *a, **k: tmp_path / "c.json")
monkeypatch.setattr(cadence, "_transcribe_faster_whisper", fake_transcribe)
monkeypatch.setattr(cadence, "_release_cuda_memory", fake_release)
monkeypatch.setattr(cadence, "_align_with_whisperx", fake_align)
monkeypatch.setattr(cadence, "_write_cache", lambda *a, **k: None)
cadence.load_or_transcribe(
video=tmp_path / "v.mp4",
wav_16k=tmp_path / "a.wav",
model="large-v3",
language="en",
track_idx=0,
no_cache=True,
backend="whisper",
)
# The model is gone and its memory released before the aligner is loaded.
assert events == ["transcribe", "release", "align"]
def test_offload_align_cache_moves_models_to_cpu(monkeypatch):
released = []
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: released.append(True))
model = _FakeAlignModel()
cache = {"en": (model, {"language": "en", "type": "huggingface"})}
cadence._offload_align_cache(cache)
assert model.calls == ["cpu"]
# The entry stays cached so the weights need not be reloaded from disk.
assert "en" in cache
assert released == [True]
def test_offload_align_cache_is_noop_without_entries(monkeypatch):
released = []
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: released.append(True))
cadence._offload_align_cache(None)
cadence._offload_align_cache({})
assert released == []
def test_offload_align_cache_drops_unmovable_entries(monkeypatch):
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
cache = {"en": (_FakeAlignModel(fail=True), {})}
cadence._offload_align_cache(cache)
# A model that cannot be offloaded must be evicted so it reloads later.
assert cache == {}
def test_load_or_transcribe_offloads_aligner_before_transcribing(monkeypatch, tmp_path):
events = []
def fake_offload(cache):
events.append("offload")
def fake_transcribe(*args, **kwargs):
events.append("transcribe")
return [], [{"start": 0.0, "end": 1.0}]
def fake_release():
events.append("release")
def fake_align(**kwargs):
events.append("align")
return []
monkeypatch.setattr(cadence, "_cache_path", lambda *a, **k: tmp_path / "c.json")
monkeypatch.setattr(cadence, "_offload_align_cache", fake_offload)
monkeypatch.setattr(cadence, "_transcribe_faster_whisper", fake_transcribe)
monkeypatch.setattr(cadence, "_release_cuda_memory", fake_release)
monkeypatch.setattr(cadence, "_align_with_whisperx", fake_align)
monkeypatch.setattr(cadence, "_write_cache", lambda *a, **k: None)
cadence.load_or_transcribe(
video=tmp_path / "v.mp4",
wav_16k=tmp_path / "a.wav",
model="large-v3",
language="en",
track_idx=0,
no_cache=True,
backend="whisper",
align_cache={"en": (_FakeAlignModel(), {})},
)
# An earlier input's aligner is returned to CPU before this input's ASR load.
assert events == ["offload", "transcribe", "release", "align"]
def test_align_moves_cached_model_back_to_device(monkeypatch, tmp_path):
model = _FakeAlignModel()
def fake_align(raw_segments, align_model, align_meta, audio_data, device, **kwargs):
# whisperx.align never moves the model itself.
assert align_model is model
assert align_model.device == "cuda"
return {"word_segments": []}
fake_torch = types.SimpleNamespace(
cuda=types.SimpleNamespace(is_available=lambda: True),
backends=types.SimpleNamespace(mps=types.SimpleNamespace(is_available=lambda: False)),
)
fake_whisperx = types.SimpleNamespace(
load_audio=lambda path: "audio",
load_align_model=lambda **kwargs: (_ for _ in ()).throw(AssertionError("reload")),
align=fake_align,
)
monkeypatch.setitem(sys.modules, "torch", fake_torch)
monkeypatch.setitem(sys.modules, "whisperx", fake_whisperx)
words = cadence._align_with_whisperx(
raw_segments=[{"start": 0.0, "end": 1.0}],
wav_16k=tmp_path / "a.wav",
language="en",
align_cache={"en": (model, {"language": "en"})},
)
assert model.calls == ["cuda"]
assert words == []