fix(gpu): stop jobs from filling the card (CUDA OOM at peak)

On 22-sep-2026 30-60% of jobs failed per hour at peak with 8 concurrent
jobs on a 20 GB GPU: a job three clips into its render still held 5.9 GB.

- main.py releases the ASR models right after transcribing (Parakeet's
  onnxruntime CUDA arena lived until the process exited); TransNetV2
  empties torch's cache after each pass.
- Host-wide cap on GPU transcriptions (flock slots on the shared output
  volume, ASR_HOST_SLOTS=2), across job processes and deploy containers.
- The queue only starts a job when nvidia-smi reports GPU_MIN_FREE_MB free
  (an idle card always starts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-22 22:42:52 +02:00
parent faf633ed43
commit fed9395022
7 changed files with 211 additions and 9 deletions

View file

@ -445,6 +445,20 @@ in-process and the ASR singletons then lived in uvicorn for good, so both
now call `transcribe_backends.release_models()` when they are done. Size
`MAX_CONCURRENT_JOBS` against the free VRAM, not the core count.
Three guards keep the card from filling (22-sep-2026: 30-60% of jobs failing
per hour at peak with `MAX_CONCURRENT_JOBS=8`):
- **Job processes release the ASR model after transcribing**
(`main.transcribe_video` → `release_models()`). Before, a job kept Parakeet's
onnxruntime CUDA arena (~4-6 GB) for its whole render; TransNetV2 also
`empty_cache()`s after each pass.
- **Host-wide transcription slots** (`transcribe_backends.host_asr_slot`,
`ASR_HOST_SLOTS`, default 2): flock files `output/.asr-gpu-N.lock`, shared by
every job process and by both containers of a deploy.
- **Queue admission** (`app._wait_for_shared_gpu`): a job starts only when
running-here + running-on-the-draining-instance < `MAX_CONCURRENT_JOBS` and
`nvidia-smi` reports at least `GPU_MIN_FREE_MB` (4500) free; an idle card
always starts, and the wait is bounded by the drain timeout.
### Paid proxy accounting (`cloud/proxy_ledger.py`)
Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB),

60
app.py
View file

@ -827,22 +827,68 @@ def _jobs_busy_elsewhere(now=None) -> int:
SHARED_GPU_WAIT_SECONDS = 5
SHARED_GPU_MAX_WAIT = DRAIN_TIMEOUT_SECONDS + 120
# Free VRAM a new job needs before it starts. A job peaks at ~4-6 GB while it
# transcribes; starting one on a nearly full card is what made NVENC and
# TransNetV2 of the jobs already running fail with CUDA OOM. 0 disables.
GPU_MIN_FREE_MB = int(os.environ.get("GPU_MIN_FREE_MB", "4500"))
_gpu_free_cache = {"at": 0.0, "mb": None}
def _gpu_free_mb():
"""Free memory on GPU 0 in MiB, or None when there is no nvidia-smi (CPU
host, self-host without a GPU): then only the job count limits."""
now = time.monotonic()
if now - _gpu_free_cache["at"] < 2:
return _gpu_free_cache["mb"]
mb = None
try:
out = subprocess.run(
["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits",
"-i", "0"], capture_output=True, text=True, timeout=5)
if out.returncode == 0 and out.stdout.strip():
mb = int(float(out.stdout.strip().splitlines()[0]))
except Exception:
mb = None
_gpu_free_cache.update(at=now, mb=mb)
return mb
def gpu_has_room(running_here: int, busy_elsewhere: int, free_mb) -> bool:
"""Whether a new job may start now.
The job count covers both instances during a deploy handover. The free
VRAM check covers what the count cannot see: jobs differ by an order of
magnitude in memory. With nothing running anywhere the job always starts,
so a card held by something outside our control can never stall the queue.
"""
total = running_here + busy_elsewhere
if total >= MAX_CONCURRENT_JOBS:
return False
if total == 0 or GPU_MIN_FREE_MB <= 0 or free_mb is None:
return True
return free_mb >= GPU_MIN_FREE_MB
async def _wait_for_shared_gpu():
"""Hold a new job while this instance's jobs plus the ones another
instance is still draining already fill MAX_CONCURRENT_JOBS. Bounded: a
killed instance stops heartbeating within HEARTBEAT_STALE_AFTER anyway,
and the drain itself cannot outlive DRAIN_TIMEOUT_SECONDS."""
"""Hold a new job until the GPU has room for it: this instance's jobs
plus the ones another instance is still draining must fit
MAX_CONCURRENT_JOBS, and the card must have GPU_MIN_FREE_MB free.
Bounded: a killed instance stops heartbeating within
HEARTBEAT_STALE_AFTER, a drain cannot outlive DRAIN_TIMEOUT_SECONDS, and
past SHARED_GPU_MAX_WAIT the job starts anyway rather than wait forever."""
waited = 0.0
logged = False
loop = asyncio.get_event_loop()
while waited < SHARED_GPU_MAX_WAIT:
elsewhere = _jobs_busy_elsewhere()
if len(_running_jobs) + elsewhere < MAX_CONCURRENT_JOBS:
free_mb = await loop.run_in_executor(None, _gpu_free_mb)
if gpu_has_room(len(_running_jobs), elsewhere, free_mb):
return
if not logged:
print(f"⏳ GPU shared with a draining instance ({elsewhere} job(s) there, "
f"{len(_running_jobs)} here): holding the next job.")
print(f"⏳ Holding the next job: {len(_running_jobs)} running here, "
f"{elsewhere} on a draining instance, "
f"{free_mb if free_mb is not None else '?'} MiB GPU free "
f"(needs {GPU_MIN_FREE_MB}).")
logged = True
await asyncio.sleep(SHARED_GPU_WAIT_SECONDS)
waited += SHARED_GPU_WAIT_SECONDS

16
main.py
View file

@ -1534,9 +1534,23 @@ def clear_transcript_checkpoint(output_dir):
def transcribe_video(video_path):
print("🎙️ Transcribing video...")
from transcribe_backends import transcribe_media
from transcribe_backends import transcribe_media, release_models, host_asr_slot
# At most ASR_HOST_SLOTS jobs transcribe on the GPU at once, host-wide.
# Inside the slot, the model's VRAM is handed back before the long render
# phase: a job process used to keep Parakeet (onnxruntime CUDA arena)
# resident until it exited. Measured in prod on 22-sep-2026, a job three
# clips into its render still held 5.9 GB of the 20 GB card; eight such
# jobs filled it and NVENC / TransNetV2 failed with CUDA OOM (30-60% of
# jobs failing per hour at peak). Nothing after this point transcribes.
with host_asr_slot():
try:
transcript = transcribe_media(video_path)
finally:
try:
release_models()
except Exception as e:
print(f"⚠️ [ASR] could not release models ({type(e).__name__}: {e})")
print(f" Detected language '{transcript['language']}', "
f"{len(transcript['segments'])} segments")

View file

@ -108,6 +108,12 @@ def _detect_transnetv2(video_path):
with _TN2_LOCK, torch.no_grad():
tensor = torch.from_numpy(np.ascontiguousarray(frames)).to(model.device)
single_frame_pred, _ = model.predict_frames(tensor, quiet=True)
single_frame_pred = single_frame_pred.cpu()
del tensor
# torch's caching allocator keeps the peak of this pass reserved for
# the rest of the process; eight jobs doing that filled a 20 GB card.
if torch.cuda.is_available():
torch.cuda.empty_cache()
# predictions_to_scenes returns [[start, end], ...] with INCLUSIVE ends;
# downstream expects PySceneDetect's exclusive ends.

View file

@ -256,6 +256,7 @@ class TestSharedGpu:
monkeypatch.setattr(app_module, "SHARED_GPU_WAIT_SECONDS", 0.01)
busy = {"n": 3}
monkeypatch.setattr(app_module, "_jobs_busy_elsewhere", lambda now=None: busy["n"])
monkeypatch.setattr(app_module, "_gpu_free_mb", lambda: None)
calls = {"n": 0}
real_sleep = asyncio.sleep
@ -272,8 +273,29 @@ class TestSharedGpu:
monkeypatch.setattr(app_module, "MAX_CONCURRENT_JOBS", 3)
monkeypatch.setattr(app_module, "_running_jobs", {"x", "y"})
monkeypatch.setattr(app_module, "_jobs_busy_elsewhere", lambda now=None: 0)
monkeypatch.setattr(app_module, "_gpu_free_mb", lambda: 20000)
async def boom(sec):
raise AssertionError("should not wait")
monkeypatch.setattr(app_module.asyncio, "sleep", boom)
asyncio.run(app_module._wait_for_shared_gpu())
class TestGpuHasRoom:
def test_count_limit(self, out, monkeypatch):
monkeypatch.setattr(app_module, "MAX_CONCURRENT_JOBS", 8)
assert not app_module.gpu_has_room(5, 3, 20000)
def test_needs_free_vram_when_something_runs(self, out, monkeypatch):
monkeypatch.setattr(app_module, "MAX_CONCURRENT_JOBS", 8)
monkeypatch.setattr(app_module, "GPU_MIN_FREE_MB", 4500)
assert not app_module.gpu_has_room(3, 0, 1200)
assert app_module.gpu_has_room(3, 0, 6000)
def test_idle_card_always_starts(self, out, monkeypatch):
monkeypatch.setattr(app_module, "GPU_MIN_FREE_MB", 4500)
assert app_module.gpu_has_room(0, 0, 100)
def test_no_nvidia_smi_falls_back_to_count(self, out, monkeypatch):
monkeypatch.setattr(app_module, "MAX_CONCURRENT_JOBS", 8)
assert app_module.gpu_has_room(4, 0, None)

View file

@ -295,3 +295,41 @@ def test_release_models_drops_the_transnetv2_singleton_too(monkeypatch):
tb.release_models()
assert fake._tn2_model is None
class TestHostAsrSlot:
"""Cross-process cap on GPU transcriptions (flock slots on the shared disk)."""
def test_slots_are_exclusive_and_released(self, tmp_path):
import transcribe_backends as tb
a = tb.host_asr_slot(slots=2, lock_dir=str(tmp_path), poll=0.01)
b = tb.host_asr_slot(slots=2, lock_dir=str(tmp_path), poll=0.01)
with a, b:
assert a._fh is not None and b._fh is not None
assert a._fh.name != b._fh.name
assert a._fh is None and b._fh is None
def test_third_waits_until_one_frees(self, tmp_path):
import threading, time
import transcribe_backends as tb
first = tb.host_asr_slot(slots=1, lock_dir=str(tmp_path), poll=0.01)
first.__enter__()
got = []
def worker():
with tb.host_asr_slot(slots=1, lock_dir=str(tmp_path), poll=0.01):
got.append(time.monotonic())
t = threading.Thread(target=worker)
t.start()
time.sleep(0.1)
assert got == [] # still blocked behind the first holder
released = time.monotonic()
first.__exit__(None, None, None)
t.join(2)
assert got and got[0] >= released
def test_disabled_is_a_noop(self, tmp_path):
import transcribe_backends as tb
with tb.host_asr_slot(slots=0, lock_dir=str(tmp_path)) as s:
assert s._fh is None

View file

@ -54,6 +54,68 @@ _ASR_SLOTS = int(os.environ.get("ASR_GPU_CONCURRENCY", "1"))
_ASR_GATE = threading.Semaphore(_ASR_SLOTS)
# Host-wide cap on GPU transcriptions, across job processes AND across the two
# containers of a deploy handover (the lock files live on the shared output/
# volume). _ASR_GATE above only serialises threads inside one process; every
# main.py job is its own process, so eight jobs could all load Parakeet at
# once. Peak per transcription is ~4-6 GB on a 20 GB card (prod, 22-sep-2026).
ASR_HOST_SLOTS = int(os.environ.get("ASR_HOST_SLOTS", "2"))
ASR_LOCK_DIR = os.environ.get("ASR_LOCK_DIR", "output")
class host_asr_slot:
"""``with host_asr_slot():`` holds one of ASR_HOST_SLOTS flock slots.
Blocks (polling once a second) until a slot is free. A crashed holder
releases its lock with its file descriptor, so a slot can never leak.
Degrades to a no-op where flock or the directory is unavailable.
"""
def __init__(self, slots=None, lock_dir=None, poll=1.0):
self.slots = ASR_HOST_SLOTS if slots is None else slots
self.lock_dir = lock_dir or ASR_LOCK_DIR
self.poll = poll
self._fh = None
def __enter__(self):
if self.slots <= 0:
return self
try:
import fcntl
os.makedirs(self.lock_dir, exist_ok=True)
except Exception:
return self
announced = False
while True:
for i in range(self.slots):
path = os.path.join(self.lock_dir, f".asr-gpu-{i}.lock")
try:
fh = open(path, "a+")
except OSError:
return self
try:
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
self._fh = fh
return self
except OSError:
fh.close()
if not announced:
print("🎙️ Waiting for a free transcription slot…", flush=True)
announced = True
time.sleep(self.poll)
def __exit__(self, *exc):
if self._fh is not None:
try:
import fcntl
fcntl.flock(self._fh, fcntl.LOCK_UN)
except Exception:
pass
self._fh.close()
self._fh = None
return False
class _NullGate:
def __enter__(self):
return self