perf(pipeline): halve a job's CPU with byte-identical clips
Reverts 1d3d20c (NVDEC decode + quarter-size blur): it changed the
delivered pixels (SSIM 0.998-0.9997, not identical), and clips must not
change. Replaces it with two fixes that leave every clip byte-identical.
- Parakeet's onnxruntime pool threads no longer spin
(transcribe_backends.parakeet_session_options). While the GPU did the
work they burned ~160 CPU-s per 9 min of audio, the biggest CPU cost of
a job. The VAD keeps load_vad's defaults: any options there make
onnx_asr drop its default providers and a word changes.
- analyze_scenes_strategy and split_layout read their sampled frames in
one forward pass (frame_sampler.read_at) instead of a seek per sample,
which re-decoded the GOP every time: 89 -> 6 CPU-s for one clip's
samples, same frames.
Bench on balrog, 3 Carlos Gracia videos (2.5/9/17 min, 15 clips), Gemini
decisions recorded once and replayed: every clip identical to the old
code (decoded-frame MD5s + audio). Serial stage profile of the 9 min
video: 629 -> 273 CPU-s per job; Python side 332 -> 57 CPU-s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
cbf0eb37f3
commit
a4c92cac2c
14 changed files with 251 additions and 129 deletions
29
CLAUDE.md
29
CLAUDE.md
|
|
@ -508,18 +508,23 @@ 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 first, then check the CPU.
|
||||
|
||||
The CPU is the other ceiling. NVENC only takes the encode: decoding and
|
||||
every filter (scale, blur, overlay, captions) run on the host's 20 threads,
|
||||
and at peak (8 jobs x `CLIP_WORKERS`=3) balrog sat at load ~100 with the
|
||||
card's decoder at 0% (22 and 25-sep-2026), starving the Coolify builds and
|
||||
everything else on the box. Two fixes in `ffmpeg_utils`, and new render code
|
||||
should use both:
|
||||
- `video_decode_args()` before a video's `-i`: NVDEC decode (`-hwaccel cuda`)
|
||||
whenever the encode is on nvenc; `FFMPEG_HWDECODE=0` switches it off.
|
||||
- `blurred_backdrop()` for any blurred fill: gblur at quarter size, then
|
||||
scaled up. The full-size gblur on 1080x1920 was most of a GENERAL segment's
|
||||
cost. Together, a GENERAL segment dropped from ~16 s to ~6 s of CPU per 10 s
|
||||
of clip (measured in prod, SSIM 0.994 against the old output).
|
||||
The CPU is the other ceiling (balrog: 20 threads, load ~100 at peak on
|
||||
22 and 25-sep-2026). Two costs were pure waste and are gone, with the
|
||||
delivered clips byte-identical (decoded-frame MD5s + audio, 15 clips of 3
|
||||
real videos, bench of 25-sep-2026):
|
||||
- **onnxruntime threads spinning** during Parakeet: ~160 CPU-s per 9 min of
|
||||
audio while the GPU did the work. `parakeet_session_options()` turns
|
||||
spinning off for the ASR session only; the VAD must keep `load_vad`'s
|
||||
defaults (see the docstring for why).
|
||||
- **A seek per sampled frame** in `analyze_scenes_strategy` and
|
||||
`split_layout`: each seek re-decoded the GOP. `frame_sampler.read_at`
|
||||
reads forward once and returns the same frames.
|
||||
Net: a job's CPU roughly halves (Python side -65-80%). What is left is
|
||||
ffmpeg decode/filter/encode per pass; any change there (NVDEC decode, a
|
||||
cheaper blur, fusing the watermark/hook/caption passes) changes the output
|
||||
pixels, so it needs a decision, not just a benchmark. `NVDEC` + a
|
||||
quarter-size blur were shipped and reverted on 25-sep-2026 for that reason
|
||||
(SSIM 0.998, not identical).
|
||||
|
||||
Three guards keep the card from filling (22-sep-2026: 30-60% of jobs failing
|
||||
per hour at peak with `MAX_CONCURRENT_JOBS=8`):
|
||||
|
|
|
|||
|
|
@ -259,7 +259,6 @@ WHISPER_MODEL=large-v3-turbo
|
|||
WHISPER_DEVICE=cuda
|
||||
WHISPER_COMPUTE=float16
|
||||
FFMPEG_ENCODER=auto # probes h264_nvenc at startup, falls back to x264
|
||||
FFMPEG_HWDECODE=1 # default: decode on the GPU (NVDEC) whenever the encode is on nvenc
|
||||
TRANSCRIBE_BACKEND=parakeet # optional: ~2x faster than whisper, 25 European languages, auto-falls back to whisper
|
||||
ASR_GPU_CONCURRENCY=1
|
||||
```
|
||||
|
|
|
|||
|
|
@ -20,8 +20,6 @@ them with margin.
|
|||
"""
|
||||
import os
|
||||
|
||||
from ffmpeg_utils import blurred_backdrop
|
||||
|
||||
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
|
||||
# frame) still counts as anchored to it
|
||||
|
||||
|
|
@ -283,7 +281,8 @@ def inset_filtergraph(orig_w, orig_h, out_w, out_h, box, camera_ratio=None):
|
|||
# Blurred backdrop so the leftover strip is not a black bar. Scaled by
|
||||
# HEIGHT: scaling a 16:9 source to 1080 wide gives 608 tall, and there
|
||||
# is no 1920-tall crop to take out of that.
|
||||
f"[bga]{blurred_backdrop(out_w, out_h, 14)}[bg];"
|
||||
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h},"
|
||||
f"scale={out_w}:{out_h},gblur=sigma=14[bg];"
|
||||
f"[sa]scale={out_w}:{screen_h}[screen];"
|
||||
f"[ca]crop=w={w}:h={h}:x={x}:y={y},scale={out_w}:{cam_h}[cam];"
|
||||
f"[bg][screen]overlay=x=0:y={filler_h // 2}[withscreen];"
|
||||
|
|
|
|||
|
|
@ -206,42 +206,6 @@ def video_encode_args(tier=QUALITY):
|
|||
return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier])
|
||||
|
||||
|
||||
def video_decode_args():
|
||||
"""Input args that decode the video on the GPU (NVDEC), or [] for software.
|
||||
|
||||
Spliced in right before the video's ``-i``. Only on when the encode runs
|
||||
on nvenc too: a card that encodes can decode. The frames come back to
|
||||
system memory, so every CPU filter downstream sees the same pixels, and a
|
||||
codec NVDEC cannot take falls back to software decode on its own.
|
||||
|
||||
Until 25-sep-2026 only the encode was on the GPU: the card's decoder sat at
|
||||
0% while 8 jobs x 3 clips decoded 1080p on the 20-thread CPU and saturated
|
||||
the host. FFMPEG_HWDECODE=0 turns it off.
|
||||
"""
|
||||
if os.environ.get("FFMPEG_HWDECODE", "1").strip() == "0":
|
||||
return []
|
||||
mode = os.environ.get("FFMPEG_ENCODER", "x264").strip().lower()
|
||||
if mode in ("nvenc", "auto") and nvenc_available():
|
||||
return ["-hwaccel", "cuda"]
|
||||
return []
|
||||
|
||||
|
||||
def blurred_backdrop(out_w, out_h, sigma):
|
||||
"""Filter chain (no labels) filling out_w x out_h with a blurred copy.
|
||||
|
||||
The blur runs at a quarter of the output size and is scaled up afterwards:
|
||||
a blurred picture carries no detail to lose, and the result is visually
|
||||
the same (SSIM 0.994 against the full-size gblur on a prod clip) for ~45%
|
||||
less CPU on the whole segment encode. ``sigma`` is the full-size one.
|
||||
"""
|
||||
small_w = max(2, out_w // 4 - (out_w // 4) % 2)
|
||||
small_h = max(2, out_h // 4 - (out_h // 4) % 2)
|
||||
return (
|
||||
f"scale=-2:{small_h},crop=w=min(iw\\,{small_w}):h={small_h},"
|
||||
f"gblur=sigma={sigma / 4:g},scale={out_w}:{out_h}"
|
||||
)
|
||||
|
||||
|
||||
def escape_filter_value(value):
|
||||
r"""Escape a path/value for use inside a quoted FFmpeg filter argument.
|
||||
|
||||
|
|
@ -299,7 +263,6 @@ def cut_clip(input_video, clip_temp_path, start, end, clip_number):
|
|||
'ffmpeg', '-y',
|
||||
'-ss', str(start),
|
||||
'-to', str(end),
|
||||
*video_decode_args(),
|
||||
'-i', input_video,
|
||||
*encode_args,
|
||||
*audio_encode_args(),
|
||||
|
|
|
|||
48
frame_sampler.py
Normal file
48
frame_sampler.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"""Read sampled frames without a seek per sample.
|
||||
|
||||
The scene classifiers sample a handful of frames per scene with
|
||||
``cap.set(CAP_PROP_POS_FRAMES, i); cap.read()``. On H.264 every such seek
|
||||
decodes again from the previous keyframe, so a clip's ~100 samples decoded
|
||||
the same GOPs over and over: 89 CPU-s for one 20 s clip, against 6 CPU-s for
|
||||
a single forward pass that keeps the frames asked for (prod bench,
|
||||
25-sep-2026). The frames are byte-identical either way (checked on 217
|
||||
samples of NVENC-cut clips), so every downstream decision stays the same.
|
||||
"""
|
||||
import cv2
|
||||
|
||||
# Past this many frames ahead, one seek is cheaper than decoding forward to
|
||||
# the target (an NVENC cut's GOP is ~250 frames).
|
||||
MAX_FORWARD = 300
|
||||
|
||||
|
||||
def read_at(cap, indices, max_forward=MAX_FORWARD):
|
||||
"""Yield ``cap.read()``'s frame for each index in ``indices``, in order,
|
||||
or None where a seek + read would have failed (past the last frame).
|
||||
|
||||
``cap`` must be freshly opened (positioned at frame 0). Indices should be
|
||||
non-decreasing to get the forward-pass saving; a step backwards or a jump
|
||||
past ``max_forward`` seeks exactly like the callers used to. A repeated
|
||||
index yields the same frame object again: treat frames as read-only.
|
||||
"""
|
||||
pos = 0 # index of the frame the next grab() decodes
|
||||
last = (None, None)
|
||||
for idx in indices:
|
||||
idx = int(idx)
|
||||
if idx == last[0]:
|
||||
yield last[1]
|
||||
continue
|
||||
if idx < pos or idx - pos > max_forward:
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
|
||||
pos = idx
|
||||
frame = None
|
||||
while pos < idx:
|
||||
if not cap.grab():
|
||||
break
|
||||
pos += 1
|
||||
if pos == idx:
|
||||
ok, frame = cap.read()
|
||||
pos += 1
|
||||
if not ok:
|
||||
frame = None
|
||||
last = (idx, frame)
|
||||
yield frame
|
||||
3
hooks.py
3
hooks.py
|
|
@ -6,7 +6,7 @@ import urllib.request
|
|||
import uuid
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
from ffmpeg_utils import video_encode_args, video_decode_args, QUALITY, METADATA_SCRUB
|
||||
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||
|
||||
|
||||
def _truncate_bytes(text, max_bytes):
|
||||
|
|
@ -426,7 +426,6 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
|
|||
|
||||
ffmpeg_cmd = [
|
||||
'ffmpeg', '-y',
|
||||
*video_decode_args(),
|
||||
'-i', video_path,
|
||||
'-i', img_path,
|
||||
'-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}"
|
||||
|
|
|
|||
27
main.py
27
main.py
|
|
@ -22,6 +22,7 @@ import mediapipe as mp
|
|||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
import frame_sampler
|
||||
import gemini_worker
|
||||
import hook_grounding
|
||||
import layout_picker
|
||||
|
|
@ -30,8 +31,8 @@ from clip_selection import (build_transcript_windows, clip_count_targets,
|
|||
clip_duration_bounds, dedupe_overlapping,
|
||||
score_batches, shortlist_target,
|
||||
snap_clip_to_words, trim_to_best)
|
||||
from ffmpeg_utils import (video_encode_args, video_decode_args, audio_encode_args,
|
||||
cut_clip, QUALITY, QUALITY_FAST, METADATA_SCRUB)
|
||||
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
|
||||
QUALITY_FAST, METADATA_SCRUB)
|
||||
from dotenv import load_dotenv
|
||||
import json
|
||||
|
||||
|
|
@ -569,7 +570,10 @@ def analyze_scenes_strategy(video_path, scenes):
|
|||
|
||||
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
||||
|
||||
for start, end in tqdm(scenes, desc=" Analyzing Scenes"):
|
||||
# Every scene's samples first, then one forward pass over the clip
|
||||
# (frame_sampler): same frames, same detector calls in the same order.
|
||||
plan = []
|
||||
for si, (start, end) in enumerate(scenes):
|
||||
s_f, e_f = start.get_frames(), end.get_frames()
|
||||
# Sample 5 frames spread across the scene, clamped inside it (the old
|
||||
# start+5/end-5 samples landed outside scenes shorter than ~10 frames).
|
||||
|
|
@ -577,12 +581,14 @@ def analyze_scenes_strategy(video_path, scenes):
|
|||
frames_to_check = sorted(set(
|
||||
int(round(f)) for f in np.linspace(s_f + margin, e_f - 1 - margin, 5)
|
||||
))
|
||||
plan.extend((si, f_idx) for f_idx in frames_to_check)
|
||||
|
||||
face_counts = []
|
||||
for f_idx in frames_to_check:
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, f_idx)
|
||||
ret, frame = cap.read()
|
||||
if not ret: continue
|
||||
counts_per_scene = [[] for _ in scenes]
|
||||
frames = frame_sampler.read_at(cap, [f_idx for _si, f_idx in plan])
|
||||
for (si, _f_idx), frame in tqdm(zip(plan, frames), total=len(plan),
|
||||
desc=" Analyzing Scenes"):
|
||||
if frame is None:
|
||||
continue
|
||||
|
||||
# Near-black frames (fades, cut-to-black) carry no faces and used
|
||||
# to drag single-person scenes into GENERAL. Skip them.
|
||||
|
|
@ -591,8 +597,9 @@ def analyze_scenes_strategy(video_path, scenes):
|
|||
|
||||
# Detect faces
|
||||
candidates = detect_face_candidates(frame)
|
||||
face_counts.append(len(candidates))
|
||||
counts_per_scene[si].append(len(candidates))
|
||||
|
||||
for face_counts in counts_per_scene:
|
||||
# Decision Logic
|
||||
if not face_counts:
|
||||
avg_faces = 0
|
||||
|
|
@ -1253,7 +1260,7 @@ def apply_watermark(video_path):
|
|||
f"[0:v][wm]overlay=x={x}:y={y}"
|
||||
)
|
||||
tmp_path = video_path + ".wm.mp4"
|
||||
cmd = ["ffmpeg", "-y", *video_decode_args(), "-i", video_path, "-i", logo_path,
|
||||
cmd = ["ffmpeg", "-y", "-i", video_path, "-i", logo_path,
|
||||
"-filter_complex", filt,
|
||||
*video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB,
|
||||
"-movflags", "+faststart", tmp_path]
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ import punch_in
|
|||
import screencast_layout
|
||||
import layout_ranges
|
||||
import split_layout
|
||||
from ffmpeg_utils import (video_encode_args, video_decode_args, blurred_backdrop,
|
||||
escape_filter_value, QUALITY_FAST, METADATA_SCRUB)
|
||||
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY_FAST,
|
||||
METADATA_SCRUB)
|
||||
|
||||
ANALYSIS_MAX_WIDTH = 640
|
||||
|
||||
|
|
@ -157,7 +157,8 @@ def general_filtergraph(out_w, out_h, content_h=None, orig_w=None, orig_h=None):
|
|||
fg_h += fg_h % 2
|
||||
return (
|
||||
f"[0:v]split=2[bga][fga];"
|
||||
f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];"
|
||||
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h},"
|
||||
f"scale={out_w}:{out_h},gblur=sigma=12[bg];"
|
||||
# Scale by HEIGHT, then trim any overflow to the output width. crop
|
||||
# centres by default, and min() makes it a no-op when the scaled source
|
||||
# is already narrower than the frame (portrait/square sources).
|
||||
|
|
@ -576,8 +577,7 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
|
||||
_run([
|
||||
"ffmpeg", "-y", "-loglevel", "error",
|
||||
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}",
|
||||
*video_decode_args(), "-i", input_video,
|
||||
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", "-i", input_video,
|
||||
"-filter_complex", graph, "-map", "[v]",
|
||||
*video_encode_args(QUALITY_FAST), "-an", seg_path,
|
||||
])
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ import os
|
|||
|
||||
import numpy as np
|
||||
|
||||
import frame_sampler
|
||||
|
||||
ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1"
|
||||
|
||||
# Fraction of sampled frames that must show BOTH faces at once.
|
||||
|
|
@ -236,6 +238,7 @@ def detect_split_scenes(video_path, scenes, strategies, samples=None):
|
|||
# presence bar: measured 4 of 12 samples lost on a 22s scene.
|
||||
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
|
||||
found = {}
|
||||
plan = []
|
||||
|
||||
try:
|
||||
for i, (start, end) in enumerate(scenes):
|
||||
|
|
@ -255,11 +258,17 @@ def detect_split_scenes(video_path, scenes, strategies, samples=None):
|
|||
if last_f < s_f:
|
||||
continue
|
||||
|
||||
plan.append((i, n, [int(round(f)) for f in np.linspace(s_f, last_f, n)]))
|
||||
|
||||
# One forward pass for every scene's samples (frame_sampler): the same
|
||||
# frames, detected in the same order as a seek per sample.
|
||||
flat = [f_idx for _i, _n, idxs in plan for f_idx in idxs]
|
||||
frames = frame_sampler.read_at(cap, flat)
|
||||
for i, n, idxs in plan:
|
||||
sampled = []
|
||||
for f_idx in np.linspace(s_f, last_f, n):
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(f_idx)))
|
||||
ok, frame = cap.read()
|
||||
if not ok:
|
||||
for _f_idx in idxs:
|
||||
frame = next(frames)
|
||||
if frame is None:
|
||||
continue
|
||||
if frame.mean() < 16: # fade to black, same as the classifier
|
||||
continue
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ import re
|
|||
import subprocess
|
||||
import sys
|
||||
|
||||
from ffmpeg_utils import (video_encode_args, video_decode_args, escape_filter_value,
|
||||
QUALITY, METADATA_SCRUB)
|
||||
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY,
|
||||
METADATA_SCRUB)
|
||||
|
||||
|
||||
_STDIO_CONFIGURED = False
|
||||
|
|
@ -563,7 +563,6 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
|
|||
|
||||
cmd = [
|
||||
'ffmpeg', '-y',
|
||||
*video_decode_args(),
|
||||
'-i', video_path,
|
||||
'-vf', vf,
|
||||
'-c:a', 'copy',
|
||||
|
|
|
|||
|
|
@ -9,10 +9,8 @@ from ffmpeg_utils import (
|
|||
METADATA_SCRUB,
|
||||
QUALITY,
|
||||
QUALITY_FAST,
|
||||
blurred_backdrop,
|
||||
mark_ai_generated,
|
||||
reset_encoder_cache,
|
||||
video_decode_args,
|
||||
video_encode_args,
|
||||
)
|
||||
|
||||
|
|
@ -20,7 +18,6 @@ from ffmpeg_utils import (
|
|||
@pytest.fixture(autouse=True)
|
||||
def _clean_encoder_state(monkeypatch):
|
||||
monkeypatch.delenv("FFMPEG_ENCODER", raising=False)
|
||||
monkeypatch.delenv("FFMPEG_HWDECODE", raising=False)
|
||||
reset_encoder_cache()
|
||||
yield
|
||||
reset_encoder_cache()
|
||||
|
|
@ -87,42 +84,6 @@ def test_returns_a_fresh_list_each_call():
|
|||
assert "-mutated" not in video_encode_args(QUALITY)
|
||||
|
||||
|
||||
def test_decode_stays_on_the_cpu_under_x264():
|
||||
assert video_decode_args() == []
|
||||
|
||||
|
||||
def test_decode_moves_to_the_gpu_with_the_encode(monkeypatch):
|
||||
monkeypatch.setenv("FFMPEG_ENCODER", "auto")
|
||||
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True)
|
||||
assert video_decode_args() == ["-hwaccel", "cuda"]
|
||||
|
||||
|
||||
def test_decode_stays_on_the_cpu_when_nvenc_is_unusable(monkeypatch):
|
||||
monkeypatch.setenv("FFMPEG_ENCODER", "auto")
|
||||
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: False)
|
||||
assert video_decode_args() == []
|
||||
|
||||
|
||||
def test_hwdecode_can_be_switched_off_on_a_gpu(monkeypatch):
|
||||
monkeypatch.setenv("FFMPEG_ENCODER", "nvenc")
|
||||
monkeypatch.setenv("FFMPEG_HWDECODE", "0")
|
||||
monkeypatch.setattr(ffmpeg_utils, "_probe_nvenc", lambda: True)
|
||||
assert video_decode_args() == []
|
||||
|
||||
|
||||
def test_backdrop_blurs_at_quarter_size_and_fills_the_frame():
|
||||
chain = blurred_backdrop(1080, 1920, 12)
|
||||
assert "scale=-2:480,crop=w=min(iw\\,270):h=480" in chain
|
||||
assert "gblur=sigma=3," in chain
|
||||
assert chain.endswith("scale=1080:1920")
|
||||
|
||||
|
||||
def test_backdrop_keeps_the_small_size_even():
|
||||
chain = blurred_backdrop(1080, 1350, 14)
|
||||
assert "scale=-2:336" in chain and "min(iw\\,270)" in chain
|
||||
assert "gblur=sigma=3.5," in chain
|
||||
|
||||
|
||||
def test_metadata_scrub_covers_global_and_per_stream():
|
||||
# Global -map_metadata -1 alone leaves the audio handler_name intact on a
|
||||
# stream copy — the per-stream specifiers are what strip YouTube's
|
||||
|
|
@ -225,12 +186,6 @@ def test_successful_cut_runs_once(_cut):
|
|||
assert "h264_nvenc" in fake.commands[0]
|
||||
|
||||
|
||||
def test_cut_decodes_the_source_on_the_gpu(_cut):
|
||||
cmd = _cut([(0, 5_000_000, "")]).commands[0]
|
||||
assert cmd.index("-hwaccel") < cmd.index("-i")
|
||||
assert cmd[cmd.index("-hwaccel") + 1] == "cuda"
|
||||
|
||||
|
||||
def test_retry_stays_on_the_gpu_after_a_wait(_cut):
|
||||
"""No libx264 fallback: the GPU failure is transient, so wait and ask again."""
|
||||
fake = _cut([(1, 0, "OpenEncodeSessionEx failed: out of memory"),
|
||||
|
|
|
|||
78
tests/test_frame_sampler.py
Normal file
78
tests/test_frame_sampler.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import cv2
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import frame_sampler
|
||||
|
||||
N_FRAMES = 60
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def video(tmp_path_factory):
|
||||
"""A short clip whose frames all differ, with keyframes far apart."""
|
||||
path = str(tmp_path_factory.mktemp("fs") / "clip.avi")
|
||||
writer = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"MJPG"), 30, (64, 48))
|
||||
if not writer.isOpened():
|
||||
pytest.skip("no video writer in this OpenCV build")
|
||||
rng = np.random.default_rng(1)
|
||||
for i in range(N_FRAMES):
|
||||
frame = rng.integers(0, 255, (48, 64, 3), dtype=np.uint8)
|
||||
cv2.putText(frame, str(i), (4, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
|
||||
writer.write(frame)
|
||||
writer.release()
|
||||
return path
|
||||
|
||||
|
||||
def _seek_read(path, indices):
|
||||
"""What the classifiers did before: one seek + read per sample."""
|
||||
cap = cv2.VideoCapture(path)
|
||||
out = []
|
||||
for i in indices:
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i))
|
||||
ok, frame = cap.read()
|
||||
out.append(frame if ok else None)
|
||||
cap.release()
|
||||
return out
|
||||
|
||||
|
||||
def _forward(path, indices, **kw):
|
||||
cap = cv2.VideoCapture(path)
|
||||
out = list(frame_sampler.read_at(cap, indices, **kw))
|
||||
cap.release()
|
||||
return out
|
||||
|
||||
|
||||
def _same(a, b):
|
||||
assert len(a) == len(b)
|
||||
for x, y in zip(a, b):
|
||||
assert (x is None) == (y is None)
|
||||
if x is not None:
|
||||
assert np.array_equal(x, y)
|
||||
|
||||
|
||||
def test_forward_pass_returns_the_frames_a_seek_returns(video):
|
||||
idx = [0, 3, 4, 10, 11, 12, 30, 45, 59]
|
||||
_same(_forward(video, idx), _seek_read(video, idx))
|
||||
|
||||
|
||||
def test_repeated_index_yields_the_same_frame_again(video):
|
||||
idx = [5, 5, 5, 6]
|
||||
got = _forward(video, idx)
|
||||
_same(got, _seek_read(video, idx))
|
||||
assert got[0] is got[1] is got[2]
|
||||
|
||||
|
||||
def test_past_the_end_is_none_like_a_failed_read(video):
|
||||
idx = [58, 59, 60, 75]
|
||||
got = _forward(video, idx)
|
||||
assert got[2] is None and got[3] is None
|
||||
_same(got, _seek_read(video, idx))
|
||||
|
||||
|
||||
def test_long_jumps_and_steps_back_seek_instead(video):
|
||||
idx = [2, 50, 20, 21, 57]
|
||||
_same(_forward(video, idx, max_forward=10), _seek_read(video, idx))
|
||||
|
||||
|
||||
def test_empty_request_reads_nothing(video):
|
||||
assert _forward(video, []) == []
|
||||
|
|
@ -346,3 +346,43 @@ class TestParakeetMemorySettings:
|
|||
assert name == "CUDAExecutionProvider" and cpu == "CPUExecutionProvider"
|
||||
assert opts["arena_extend_strategy"] == "kSameAsRequested"
|
||||
assert opts["cudnn_conv_use_max_workspace"] == "0"
|
||||
|
||||
|
||||
def test_parakeet_threads_sleep_but_the_vad_keeps_its_defaults(monkeypatch):
|
||||
"""Spinning ORT threads were most of a job's CPU; the VAD must stay on
|
||||
load_vad's defaults (any options there change the transcript)."""
|
||||
class FakeOptions:
|
||||
def __init__(self):
|
||||
self.entries = {}
|
||||
|
||||
def add_session_config_entry(self, key, value):
|
||||
self.entries[key] = value
|
||||
|
||||
calls = {}
|
||||
|
||||
class FakeModel:
|
||||
def with_vad(self, vad, batch_size):
|
||||
return self
|
||||
|
||||
def with_timestamps(self):
|
||||
return self
|
||||
|
||||
def load_model(model_id, **kw):
|
||||
calls["model"] = kw
|
||||
return FakeModel()
|
||||
|
||||
def load_vad(*a, **kw):
|
||||
calls["vad"] = (a, kw)
|
||||
return object()
|
||||
|
||||
monkeypatch.setitem(sys.modules, "onnxruntime", SimpleNamespace(SessionOptions=FakeOptions))
|
||||
monkeypatch.setitem(sys.modules, "onnx_asr",
|
||||
SimpleNamespace(load_model=load_model, load_vad=load_vad))
|
||||
monkeypatch.setattr(tb, "_parakeet_model", None)
|
||||
|
||||
tb._get_parakeet_model()
|
||||
|
||||
entries = calls["model"]["sess_options"].entries
|
||||
assert entries == {"session.intra_op.allow_spinning": "0",
|
||||
"session.inter_op.allow_spinning": "0"}
|
||||
assert calls["vad"] == (("silero",), {})
|
||||
|
|
|
|||
|
|
@ -279,12 +279,33 @@ def parakeet_providers():
|
|||
return [("CUDAExecutionProvider", cuda_opts), "CPUExecutionProvider"]
|
||||
|
||||
|
||||
def parakeet_session_options():
|
||||
"""onnxruntime SessionOptions for Parakeet: pool threads sleep, never spin.
|
||||
|
||||
By default every ORT pool thread busy-waits for its next op. On the CUDA
|
||||
path the CPU has almost nothing to do, so that spinning was the work:
|
||||
~160 CPU-s for a 9-minute video, the biggest CPU cost of a whole job
|
||||
(prod bench 25-sep-2026). Without it: ~35 CPU-s, and the transcript is
|
||||
byte-identical (text and every word timestamp, 3 real videos).
|
||||
|
||||
Parakeet only: the VAD must keep ``load_vad``'s defaults. Passing it any
|
||||
options, even an empty SessionOptions, makes onnx_asr drop its default
|
||||
providers, the VAD falls to the CPU, and a word and 16 timestamps change.
|
||||
"""
|
||||
import onnxruntime as rt
|
||||
opts = rt.SessionOptions()
|
||||
opts.add_session_config_entry("session.intra_op.allow_spinning", "0")
|
||||
opts.add_session_config_entry("session.inter_op.allow_spinning", "0")
|
||||
return opts
|
||||
|
||||
|
||||
def _get_parakeet_model():
|
||||
global _parakeet_model
|
||||
with _parakeet_lock:
|
||||
if _parakeet_model is None:
|
||||
import onnx_asr
|
||||
model = onnx_asr.load_model(PARAKEET_MODEL_ID, providers=parakeet_providers())
|
||||
model = onnx_asr.load_model(PARAKEET_MODEL_ID, providers=parakeet_providers(),
|
||||
sess_options=parakeet_session_options())
|
||||
vad = onnx_asr.load_vad("silero")
|
||||
_parakeet_model = model.with_vad(
|
||||
vad, batch_size=PARAKEET_VAD_BATCH).with_timestamps()
|
||||
|
|
|
|||
Loading…
Reference in a new issue