diff --git a/cadence.py b/cadence.py index ed74f68..7499b22 100755 --- a/cadence.py +++ b/cadence.py @@ -324,6 +324,16 @@ def _align_with_whisperx( logger.info(f"[*] Running CTC forced alignment ({align_device})...") if isinstance(align_cache, dict) and language in align_cache: align_model, align_meta = align_cache[language] + # The cached aligner may have been offloaded to CPU to free VRAM + # for the ASR model; whisperx.align does not move it itself. + try: + align_model.to(align_device) + except Exception: + align_model, align_meta = whisperx.load_align_model( + language_code=language, device=align_device + ) + if isinstance(align_cache, dict): + align_cache[language] = (align_model, align_meta) else: align_model, align_meta = whisperx.load_align_model( language_code=language, device=align_device @@ -421,6 +431,29 @@ def _release_cuda_memory() -> None: pass +def _offload_align_cache(align_cache: dict | None) -> None: + """Return GPU memory held by cached CTC aligners before the next ASR load. + + The aligner is deliberately kept in ``align_cache`` between inputs so its + weights need not be reloaded from disk. But Whisper large-v3 and the + Wav2Vec2 aligner cannot coexist on a 6 GB card: with an earlier input's + aligner still resident, the next input's Whisper init fails with CUDA OOM + and silently drops to CPU. Moving the cached weights back to CPU keeps the + cache warm while returning VRAM to the driver; ``_align_with_whisperx`` + moves them to the align device again when alignment starts. Entries that + cannot be moved are dropped so they reload from scratch. + """ + if not isinstance(align_cache, dict) or not align_cache: + return + for language, entry in list(align_cache.items()): + model = entry[0] if isinstance(entry, tuple) else entry + try: + model.to("cpu") + except Exception: + align_cache.pop(language, None) + _release_cuda_memory() + + def _transcribe_faster_whisper( wav: Path, model_size: str, @@ -531,6 +564,11 @@ def load_or_transcribe( if extract is not None: extract() + # An earlier input's aligner may still be resident on the GPU; return its + # VRAM before the ASR model loads, or Whisper init OOMs and silently falls + # back to CPU (catastrophic for long recordings). + _offload_align_cache(align_cache) + logger.info(f"[*] Transcribing ({backend}) | Model: {model} | File: {video.name}") if backend == "mlx": diff --git a/tests/test_whisper_unload.py b/tests/test_whisper_unload.py index d76a17c..21337db 100644 --- a/tests/test_whisper_unload.py +++ b/tests/test_whisper_unload.py @@ -1,13 +1,34 @@ -"""The Whisper -> CTC-aligner VRAM handoff. +"""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. +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. @@ -46,3 +67,109 @@ def test_transcribe_releases_vram_before_aligning(monkeypatch, tmp_path): # 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 == []