Compare commits

...
Author SHA1 Message Date
shinyobjectz f897fc2e19 The farm draws a video on up to 32 containers, kept warm a minute, and says where a slow job's end went
A 35 s 1080x1920 cut: 80 s from the box's call to its file, from 104-160. At 8 containers its parts ran two after another on each; at 2 s idle every render's containers started cold.
2026-12-01 18:05:20 -08:00
shinyobjectz 30f06bd73c The farm reads a cut's scene frames on containers of their own, side by side
They went through the API's one core one after another inside its event loop: 70 frames of a 35 s ad took 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow). A whole goal check on a 35 s cut: 34 s, from 77-98.
2026-12-01 17:46:18 -08:00
+77 -33
View File
@@ -32,6 +32,7 @@ import re
import resource
import shutil
import subprocess
import threading
import time
import uuid
@@ -81,8 +82,10 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
# workspace limit holds these back as it does GPUs
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
# 32 since 12-01: at 8, a 34 s ad's 16 parts ran two after another on each container, 53 s of a 104 s render, and
# at 16 a 35 s one still drew for 73 s beside another job; the containers' seconds, and so the bill, are the same
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "32"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "128"))
ROOT = "/farm"
JOBS = f"{ROOT}/jobs"
@@ -168,6 +171,8 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
# the scene reader's models, loaded once a container (/v1/scene)
SCENE = None
# one reading at a time a container: the models aren't safe to run from two threads
SCENE_LOCK = threading.Lock()
# when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time()
@@ -228,6 +233,10 @@ class Log:
# a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed
# about five times their GPUs' working seconds
SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
CPU_SCALEDOWN = 60
def on(gpus, job):
@@ -291,7 +300,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=CPU_SCALEDOWN)
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
@@ -434,7 +443,9 @@ def coordinate(id: str, args: list[str], opts: dict):
except Exception as e: # the job's own failure, said in its log; the farm goes on
log(f"raea farm: {e!r}", err=True)
code = 1
t_end = [time.time()]
vol.commit()
t_end.append(time.time())
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
@@ -448,7 +459,9 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
else:
time.sleep(pause)
t_end.append(time.time())
after = snapshot(work)
t_end.append(time.time())
changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"):
# the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out
@@ -460,10 +473,66 @@ def coordinate(id: str, args: list[str], opts: dict):
with open(f"{JOBS}/{id}/changed.txt", "w") as f:
f.write("".join(p + "\n" for p in changed))
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
t_end.append(time.time())
vol.commit()
t_end.append(time.time())
# where a job's end goes, said when it's slow (12-01: 17-60 s between the join and the box hearing it's done)
if t_end[-1] - t_end[0] > 5:
d = [b - a for a, b in zip(t_end, t_end[1:])]
log(f"raea farm: the job's end took {sum(d):.0f} s: saving {d[0]:.1f} s, reloading {d[1]:.1f} s, listing what changed {d[2]:.1f} s, clearing its frames {d[3]:.1f} s, saving again {d[4]:.1f} s")
log.end(code)
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
def read_scenes(frames):
"""Each base64 JPEG's scene (farm_scene.Scene.read and its seams), None for one that isn't a picture"""
import base64
import cv2
import numpy as np
import farm_scene
global SCENE
with SCENE_LOCK:
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return out
# A cut's frames went through the API's one core one after another, inside its event loop: 70 frames of a 35 s ad took
# 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow; 12-01).
# More than SCENE_HERE frames are shared out to these, SCENE_PART each; fewer are read in the API on a thread.
SCENE_HERE = 4
SCENE_PART = 6
@app.function(cpu=2, memory=4096, timeout=600, max_containers=CPUS, scaledown_window=60)
def scene_run(frames: list[str]) -> list:
return read_scenes(frames)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
@modal.concurrent(max_inputs=32)
@modal.asgi_app()
@@ -548,19 +617,6 @@ def api():
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
@web.post("/v1/scene")
async def scene(req: Request):
@@ -569,11 +625,6 @@ def api():
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
@@ -581,18 +632,11 @@ def api():
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
global SCENE
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
if len(frames) <= SCENE_HERE:
out = await asyncio.to_thread(read_scenes, frames)
else:
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)]
out = [r async for part in scene_run.map.aio(parts) for r in part]
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words")