Compare commits
No commits in common. "70198e0a750264e68f677786bc6ea8acbfb757bf" and "5032f48eeeebaa010a05da21c467419754365973" have entirely different histories.
70198e0a75
...
5032f48eee
3 changed files with 17 additions and 245 deletions
|
|
@ -70,15 +70,6 @@ to also write the `.kdenlive` project.
|
||||||
|
|
||||||
Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.
|
Presets: `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
|
## Development
|
||||||
|
|
||||||
Run the linter and tests locally:
|
Run the linter and tests locally:
|
||||||
|
|
|
||||||
118
cadence.py
118
cadence.py
|
|
@ -56,7 +56,7 @@ from typing import Literal
|
||||||
|
|
||||||
logger = logging.getLogger("cadence")
|
logger = logging.getLogger("cadence")
|
||||||
|
|
||||||
__version__ = "0.3.2"
|
__version__ = "0.3.0"
|
||||||
|
|
||||||
# Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc.
|
# Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc.
|
||||||
HESITATION_REGEX = re.compile(
|
HESITATION_REGEX = re.compile(
|
||||||
|
|
@ -112,16 +112,6 @@ VERBATIM_PROMPT = (
|
||||||
"Verbatim transcription with all hesitations, stutters, and verbal fillers like um, uh, er."
|
"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)
|
@dataclass(frozen=True, slots=True)
|
||||||
class Word:
|
class Word:
|
||||||
|
|
@ -407,42 +397,18 @@ def _transcribe_mlx(
|
||||||
return words, raw_segments
|
return words, raw_segments
|
||||||
|
|
||||||
|
|
||||||
def _configure_ct2_cuda_allocator() -> None:
|
def _load_faster_whisper_model(model_size: str):
|
||||||
"""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()
|
preload_nvidia_libs()
|
||||||
from faster_whisper import WhisperModel
|
from faster_whisper import WhisperModel
|
||||||
|
|
||||||
if device is None:
|
target_device = "cuda" if platform.system() == "Linux" else "cpu"
|
||||||
# Default path keeps the historical CPU fallback when GPU init fails.
|
target_compute = "float16" if target_device == "cuda" else "int8"
|
||||||
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")
|
|
||||||
|
|
||||||
# Explicit device/compute_type (fallback ladder): honour it strictly.
|
try:
|
||||||
return WhisperModel(model_size, device=device, compute_type=compute_type or "int8")
|
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")
|
||||||
|
|
||||||
|
|
||||||
def _release_cuda_memory() -> None:
|
def _release_cuda_memory() -> None:
|
||||||
|
|
@ -488,26 +454,23 @@ def _offload_align_cache(align_cache: dict | None) -> None:
|
||||||
_release_cuda_memory()
|
_release_cuda_memory()
|
||||||
|
|
||||||
|
|
||||||
def _is_cuda_oom(exc: BaseException) -> bool:
|
def _transcribe_faster_whisper(
|
||||||
"""True for CTranslate2's CUDA allocation failures (not torch OOM)."""
|
|
||||||
return "out of memory" in str(exc).lower()
|
|
||||||
|
|
||||||
|
|
||||||
def _run_faster_whisper(
|
|
||||||
wav: Path,
|
wav: Path,
|
||||||
model,
|
model_size: str,
|
||||||
language: str,
|
language: str = "en",
|
||||||
beam_size: int,
|
model=None,
|
||||||
) -> tuple[list[Word], list[dict]]:
|
) -> tuple[list[Word], list[dict]]:
|
||||||
"""Consume one WhisperModel's segment generator into words + raw segments."""
|
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
if model is None:
|
||||||
|
model = _load_faster_whisper_model(model_size)
|
||||||
|
|
||||||
segments, meta = model.transcribe(
|
segments, meta = model.transcribe(
|
||||||
str(wav),
|
str(wav),
|
||||||
language=language,
|
language=language,
|
||||||
word_timestamps=True,
|
word_timestamps=True,
|
||||||
vad_filter=False,
|
vad_filter=False,
|
||||||
beam_size=beam_size,
|
beam_size=5,
|
||||||
condition_on_previous_text=False,
|
condition_on_previous_text=False,
|
||||||
initial_prompt=VERBATIM_PROMPT,
|
initial_prompt=VERBATIM_PROMPT,
|
||||||
)
|
)
|
||||||
|
|
@ -538,53 +501,6 @@ def _run_faster_whisper(
|
||||||
return words, raw_segments
|
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:
|
def _cache_key(model: str, backend: str, language: str) -> str:
|
||||||
return hashlib.sha256(
|
return hashlib.sha256(
|
||||||
json.dumps([backend, language, model]).encode()
|
json.dumps([backend, language, model]).encode()
|
||||||
|
|
|
||||||
|
|
@ -1,135 +0,0 @@
|
||||||
"""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)
|
|
||||||
Loading…
Reference in a new issue