Files
raea/sdk/cloud/bench/encode.py
shaneandshinyobjectz dea4d75c8a The farm draws a video with no 3D without a GPU, keeps its runs by their frames' keys, reads clips at the size they're drawn, and joins every frame (#283)
- A video whose frame 0 has no 3D is drawn on containers with no GPU (cpus, 8 by default; 0 keeps it on GPUs); a run
  that fails there or draws 3D is drawn again on a GPU.
- A run's frame is timed by raea's own clocks over the whole frame, a part's start planned at 5 s at least, 2 parts
  at most a container with no GPU.
- With render --keys, a video's runs are kept under their frames' keys in a store named for the raea, the arguments
  and the job's files; a job draws only the frames no kept run holds, and a sound-only change draws none and joins
  the kept pictures to the new sound. A 30 s ad drawn again unchanged: 46 s and $0.000; one caption word changed:
  148 frames, $0.011.
- A clip much larger than it's drawn is read from a copy at its drawn size (lanczos, CRF 12, sound, frame times and
  face track kept), made on containers with no GPU and kept by hash. The ad as a half-size draft: frames in 30-37 s
  from copies against 48-65 s. A master that needs its clips whole gets no copies.
- A piece with 3D asks its GPU runs for NVENC and NVDEC (RAEA_NV=1; needs raea with engine-render-cost, older raea
  ignores it).
- The join reads only the runs' video tracks and cuts at the piece's length: each run's AAC track moved the joined
  video 21 ms after the sound and -shortest then ended it 2 frames early (892 of 894 frames on every split render).
- deploy/modal/build.py builds a Linux raea from a source folder into the volume; a test farm deployed with
  RAEA_FARM_BUILD=NAME runs it. bench/job.ts times one job, bench/encode.py the encoders.
- An unknown GPU name is a GPU, not a CPU, in the bill; A10G is an A10.

Without --keys (raea 0.1.13 and older) a job runs as before, on GPUs or CPUs by its probe, with nothing kept.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 18:36:22 -08:00

250 lines
15 KiB
Python

# Where a farm run's seconds go, and what each encoder costs and keeps (docs/cloud-render.feature CR27, CR31): the same
# frames of one project rendered on a GPU container sized as the farm's (farm_plan.RESERVED), once to PNGs (no video
# encoder: the picture every encode is scored against) and once through each encoder, timed. From sdk/cloud:
#
# MODAL_PROFILE=raea modal run bench/encode.py --dir ../../bench/rerender --args "render film.tsx --composition cut" --frames 0-299
# ... --encoders x264,soft,nvenc --out bench/results/encode-film.json
# ... --gpu none --cpu 8 --gib 8 the same on a container with no GPU (lavapipe), sized as said: what a piece
# with no 3D costs where nothing waits on a graphics card
#
# Each encoder's row: s (the run's wall time), ms a frame over the run, cores busy on average, the file's MB, SSIM and
# PSNR against the PNGs (all frames, and the darkest tenth of them alone, where an encoder's blocks show), what
# `raea check` says of its picture (the blotching line), raea's own RAEA_TIMES line, and the ffmpeg command raea ran.
# png raea's frames as PNGs: the reference, and a run with no video encoder
# x264 RAEA_MEDIA=ffmpeg: libx264 medium at the quality's CRF on the container's cores (the farm today)
# soft raea's own portable encoder (openh264 at a bitrate): the farm before 11-30
# nvenc RAEA_MEDIA=ffmpeg with h264_nvenc in libx264's place (constant QP at the CRF's number), on the run's own GPU
# An ephemeral app: it never touches the deployed farm.
import json
import os
import sys
import modal
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "deploy", "modal"))
import farm # noqa: E402 the farm's image, so the bench measures what the farm runs
import farm_plan # noqa: E402
app = modal.App("raea-farm-encode-bench", image=farm.image.add_local_python_source("farm"))
CPU, GIB = farm_plan.RESERVED["raea"]
# ffmpeg in the encoder's place: raea's ffmpeg backend names libx264 itself (io/ffmpeg), so the bench swaps the encoder
# where raea calls it. RAEA_BENCH_ENCODER holds the arguments that replace "-c:v libx264 -preset medium -crf N" ({q} is N)
WRAP = r"""#!/usr/bin/env python3
import json, os, sys
a = sys.argv[1:]
said = os.environ.get("RAEA_BENCH_SAID", "/dev/null")
with open(said, "a") as f:
f.write(" ".join(a) + "\n")
enc = json.loads(os.environ.get("RAEA_BENCH_ENCODER") or "null")
if enc and "libx264" in a and "rawvideo" in a:
i = a.index("-c:v")
if "-crf" in a:
j = a.index("-crf") + 2
new = enc["crf"].format(q=a[j - 1])
else:
j = a.index("-bufsize") + 2
new = enc["rate"].format(b=a[a.index("-b:v") + 1], m=a[a.index("-maxrate") + 1], u=a[j - 1])
a = a[:i] + new.split() + a[j:]
with open(said, "a") as f:
f.write("-> " + " ".join(a) + "\n")
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *a])
"""
# what replaces "-c:v libx264 -preset medium" and its rate arguments where raea calls ffmpeg: "crf" when the render
# names a quality ({q} the CRF), "rate" when it doesn't ({b}, {m}, {u}: the bitrate, its ceiling and the buffer)
NV = "-c:v h264_nvenc -preset {p} -tune hq -bf 2 -g 60 -spatial-aq 1 -temporal-aq 1"
ENCODERS = {
"x264": {"RAEA_MEDIA": "ffmpeg"},
"soft": {"RAEA_MEDIA": "soft"},
"nvenc": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p5") + " -rc constqp -qp {q}", "rate": NV.format(p="p5") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"nvenc-p7": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p7") + " -rc constqp -qp {q}", "rate": NV.format(p="p7") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"x264-fast": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": "-c:v libx264 -preset veryfast -crf {q}", "rate": "-c:v libx264 -preset veryfast -b:v {b} -maxrate {m} -bufsize {u}"})},
}
def _sample(stop, rows):
"""What the container's processes are doing while a render runs: every 2 s, each process's name and CPU seconds so
far (ps), so a run's cores can be put to raea's threads or to the ffmpeg children it starts."""
import subprocess
import time
while not stop.is_set():
o = subprocess.run(["ps", "-eLo", "pid,comm,time,args", "--no-headers"], capture_output=True, text=True).stdout
rows.append((time.time(), o))
stop.wait(2)
def _run(cmd, cwd, env, timeout=3600):
import resource
import subprocess
import time
for d in (farm.CACHES["__GL_SHADER_DISK_CACHE_PATH"], farm.CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0, t = resource.getrusage(resource.RUSAGE_CHILDREN), time.time()
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **farm.CACHES, **env}, timeout=timeout)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
return r.returncode, r.stdout + r.stderr, s, round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2)
def _score(video, pngs, first, fps, dark):
"""SSIM and PSNR of `video` against the PNGs: over every frame, and over the darkest tenth (`dark`: frame indexes)."""
import re
import subprocess
def one(select):
vf = f"[0:v]{select}format=yuv420p[a];[1:v]{select}format=yuv420p[b];[a][b]ssim;[0:v]{select}format=yuv420p[c];[1:v]{select}format=yuv420p[d];[c][d]psnr"
r = subprocess.run(["ffmpeg", "-hide_banner", "-i", video, "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-lavfi", vf, "-f", "null", "-"], capture_output=True, text=True)
s, p = re.search(r"SSIM .*All:([\d.]+)", r.stderr), re.search(r"PSNR .*average:([\d.inf]+)", r.stderr)
return (float(s.group(1)) if s else None, float(p.group(1)) if p and p.group(1) != "inf" else None)
out = dict(zip(("ssim", "psnr"), one("")))
if dark:
sel = "select='" + "+".join(f"eq(n\\,{i})" for i in dark) + "',"
out |= dict(zip(("ssim_dark", "psnr_dark"), one(sel)))
return out
@app.function(gpu="T4", cpu=CPU, memory=GIB * 1024, volumes={farm.ROOT: farm.vol, "/models": farm.models}, timeout=3600)
def measure(folder: bytes, args: list[str], first: int, last: int, encoders: list[str], check: bool = True, media: list | None = None, cpu_only: bool = False, size: tuple = (CPU, GIB), extra: dict | None = None, png: bool = True) -> dict:
import re
import shutil
import subprocess
import tarfile
import io
import farm_media
say = lambda *a: print(*a, flush=True)
# the job's folder on the volume, where the farm's own jobs are: a media link into the cache resolves there
work = f"{farm.JOBS}/bench-{os.environ.get('MODAL_TASK_ID', 'x')}/work"
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
tarfile.open(fileobj=io.BytesIO(folder)).extractall(work)
if media:
with open(f"{work}/{farm_media.MANIFEST}", "w") as f:
json.dump({"objects": media}, f)
farm_media.fetch(work, f"{farm.ROOT}/blobs", say)
base = dict(farm.CPU_ENV) if cpu_only else {}
extra = extra or {}
os.makedirs("/tmp/bin", exist_ok=True)
with open("/tmp/bin/ffmpeg", "w") as f:
f.write(WRAP)
os.chmod("/tmp/bin/ffmpeg", 0o755)
path = "/tmp/bin:" + os.environ["PATH"]
at = ",".join(map(str, range(first, last + 1)))
n = last - first + 1
res = {"gpu": "" if cpu_only else farm.kind(), "cores": size[0], "gib": size[1], "raea": farm.RAEA, "frames": n, "args": args,
"has": subprocess.run("ffmpeg -hide_banner -encoders 2>/dev/null | grep -E '264|hevc|av1' | awk '{print $2}'", shell=True, capture_output=True, text=True).stdout.split(),
"nvidia": subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip(), "rows": {}}
# a first run nobody times: the shader caches, the models, the page's fonts
code, out, s, _ = _run(["raea", *args, "--at", f"{first},{first + 1}", "-o", "/tmp/warm"], work, {**base, "PATH": path})
say(f"warm-up: exit {code} in {s:.1f} s", out[-300:] if code else "")
pngs = "/tmp/png"
shutil.rmtree(pngs, ignore_errors=True)
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", pngs], work, {**base, "PATH": path, "RAEA_TIMES": "1"}) if png else (0, "", 0.0, 0.0)
say(f"png: exit {code}, {n} frames in {s:.1f} s, {cores} cores busy")
made = sorted(x for x in os.listdir(pngs) if x.endswith(".png")) if os.path.isdir(pngs) else []
for i, name in enumerate(made): # named by their frame, as the encodes' frames are counted
os.rename(f"{pngs}/{name}", f"{pngs}/t-{first + i:05d}.png")
for i in range(len(made)):
os.rename(f"{pngs}/t-{first + i:05d}.png", f"{pngs}/frame-{first + i:05d}.png")
fps = 30
m = re.search(r"(\d+(?:\.\d+)?) fps", out)
if made:
# each frame's pixels as a hash, and a few frames whole, to hold one container's picture against another's
md5 = subprocess.run(["ffmpeg", "-v", "error", "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-pix_fmt", "rgba", "-f", "framemd5", "-"], capture_output=True, text=True).stdout
res["frame_md5"] = [l.split(",")[-1].strip() for l in md5.splitlines() if l and not l.startswith("#")]
res["frame_png"] = {str(first + i): open(f"{pngs}/frame-{first + i:05d}.png", "rb").read() for i in sorted({0, len(made) // 2, len(made) - 1})} if extra.get("BENCH_KEEP") else {}
res["rows"]["png"] = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "frames": len(made), "times": [l for l in out.splitlines() if " ms" in l][-12:], "out": out[-600:] if code else ""}
# the darkest tenth of the frames, by mean luma
dark = []
if made:
import cv2
lum = [(float(cv2.imread(f"{pngs}/frame-{first + i:05d}.png", cv2.IMREAD_GRAYSCALE)[::8, ::8].mean()), i) for i in range(len(made))]
dark = sorted(i for _, i in sorted(lum)[: max(1, len(lum) // 10)])
res["dark_luma"] = round(sorted(lum)[len(dark) - 1][0], 1)
for name in encoders:
env = {**base, "PATH": path, "RAEA_TIMES": "1", "RAEA_STARTUP_TRACE": "1", **extra, "RAEA_BENCH_SAID": f"/tmp/{name}.said", **ENCODERS[name]}
video = f"/tmp/{name}.mp4"
for p in (video, env["RAEA_BENCH_SAID"]):
if os.path.exists(p):
os.remove(p)
import threading
stop, snaps = threading.Event(), []
th = threading.Thread(target=_sample, args=(stop, snaps), daemon=True)
if extra.get("BENCH_DIAG"):
th.start()
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", video], work, env)
stop.set()
row = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "said_ms": (re.search(r"([\d.]+) ms a frame", out) or [None, None])[1],
"times": [l for l in out.splitlines() if " ms" in l or "raea startup" in l][-40:], "out": out[-800:] if code else ""}
if os.path.exists(env["RAEA_BENCH_SAID"]):
calls = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if not l.startswith("->")]
row["ffmpeg"] = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if "rawvideo" in l][-2:]
row["ffmpeg_calls"] = len(calls)
row["ffmpeg_decodes"] = len([l for l in calls if " -ss " in f" {l} "])
row["ffmpeg_decode_sample"] = [l[:260] for l in calls if " -ss " in f" {l} "][:6]
if snaps:
# the middle snapshot's processes, and how many distinct ffmpeg pids were seen over the run
pids = {l.split()[0] for _, o in snaps for l in o.splitlines() if " ffmpeg" in l[:40]}
mid = snaps[len(snaps) // 2][1].splitlines()
row["ps_ffmpeg_pids"] = len(pids)
row["ps_mid"] = sorted({" ".join(l.split()[1:3]) + " " + " ".join(l.split()[3:])[:120] for l in mid if l.split()[2] != "00:00:00"})[:40]
if os.path.exists(video):
row["mb"] = round(os.path.getsize(video) / 1e6, 2)
pr = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,codec_name,profile,r_frame_rate", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip()
row["probe"] = pr
if made:
row |= _score(video, pngs, first, fps, dark)
if check:
c, o, cs, _ = _run(["raea", "check", video], work, {"PATH": os.environ["PATH"]})
row["check"] = {"code": c, "s": round(cs, 1), "lines": [l.strip() for l in o.splitlines() if re.search(r"blotch|flash|freez|FAIL|PASS|passed|failed", l)][:12]}
res["rows"][name] = row
say(f"{name}: exit {code}, {s:.1f} s, {cores} cores busy, {row.get('mb')} MB, ssim {row.get('ssim')} dark {row.get('ssim_dark')}")
shutil.rmtree(os.path.dirname(work), ignore_errors=True)
return res
@app.local_entrypoint()
def main(dir: str, args: str, frames: str = "0-299", encoders: str = "x264,soft,nvenc", out: str = "", check: bool = True, gpu: str = "T4", cpu: int = CPU, gib: int = GIB, env: str = "", png: bool = True):
import hashlib
import io
import tarfile
a, _, b = frames.partition("-")
# files of 4 MB and more go by hash from the farm's cache, where a box's render put them (server/media.ts
# farmInputs); one the farm doesn't hold fails the run, which says so
media = []
def keep(i):
if i.name.startswith(("./out", "./.git", "./ios")):
return None
if i.isfile() and i.size >= 4 << 20:
h = hashlib.sha256()
with open(os.path.join(dir, i.name), "rb") as f:
for blk in iter(lambda: f.read(1 << 20), b""):
h.update(blk)
media.append({"path": i.name[2:], "oid": h.hexdigest(), "size": i.size})
return None
return i
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as t:
t.add(dir, arcname=".", filter=keep)
fn = measure.with_options(gpu=None if gpu == "none" else gpu, cpu=cpu, memory=gib * 1024)
r = fn.remote(buf.getvalue(), args.split(), int(a), int(b or a), [e for e in encoders.split(",") if e], check, media, gpu == "none", (cpu, gib), dict(kv.split("=", 1) for kv in env.split(",") if kv), png)
for n, b in (r.pop("frame_png", None) or {}).items():
if out:
with open(f"{os.path.splitext(out)[0]}-{int(n):05d}.png", "wb") as f:
f.write(b)
print(json.dumps({**r, "frame_md5": len(r.get("frame_md5") or [])}, indent=2))
if out:
with open(out, "w") as f:
json.dump(r, f, indent=2)