mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
694231f8c1 |
No files matched your search
@@ -76,9 +76,6 @@ BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
|
||||
RAEA_GPUS = os.environ.get("RAEA_FARM_RAEA_GPUS", "T4,A10,L4").split(",")
|
||||
BLENDER_GPUS = os.environ.get("RAEA_FARM_BLENDER_GPUS", "L40S,RTX-PRO-6000,L4").split(",")
|
||||
GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit; Team's is 50
|
||||
# one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in
|
||||
# the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once
|
||||
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
|
||||
ROOT = "/farm"
|
||||
JOBS = f"{ROOT}/jobs"
|
||||
|
||||
@@ -128,11 +125,7 @@ image = (
|
||||
# the job at once instead of installing it on a GPU's clock
|
||||
"RAEA_TOKENSYNTH": "/models/tokensynth", "RAEA_TOKENSYNTH_DEVICE": "cuda", "RAEA_AUDIO_AUTOSETUP": "0",
|
||||
# Stable Audio Open small on ONNX Runtime with CUDA, as deploy/modal/sao.py installs it (CR25)
|
||||
"RAEA_SAO": "/models/sao",
|
||||
# a video's runs encoded by the ffmpeg CLI's libx264 at the quality's CRF (master 11), not openh264 at a
|
||||
# bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching
|
||||
# failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30)
|
||||
"RAEA_MEDIA": "ffmpeg"})
|
||||
"RAEA_SAO": "/models/sao"})
|
||||
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
|
||||
)
|
||||
|
||||
@@ -580,7 +573,7 @@ def api():
|
||||
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
|
||||
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
|
||||
q = req.query_params
|
||||
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
id = str(uuid.uuid4())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
async with gate.use():
|
||||
|
||||
@@ -44,34 +44,6 @@ def splittable(args):
|
||||
return out is not None and (out.endswith(VIDEO) or not os.path.splitext(out)[1]) and any(COMPOSITION.search(a) for a in rest[1:])
|
||||
|
||||
|
||||
# how often a job's log says it's still waiting on a GPU run: from outside, a run queued behind the workspace's GPU
|
||||
# limit and one still drawing look the same, and a silent wait read as a stall (11-30: StreetTalk's agents said "stalled
|
||||
# before frame 0" while another app held all 10 of the workspace's GPUs)
|
||||
WAIT_SAY_S = 30
|
||||
|
||||
|
||||
def waited(fn, log, *a, **kw):
|
||||
"""fn.remote(*a, **kw), saying in the log every WAIT_SAY_S that it has no answer yet."""
|
||||
if not hasattr(fn, "spawn"):
|
||||
return fn.remote(*a, **kw)
|
||||
try:
|
||||
import modal.exception as me
|
||||
timeouts = (TimeoutError, me.TimeoutError)
|
||||
except Exception:
|
||||
timeouts = (TimeoutError,)
|
||||
call = fn.spawn(*a, **kw)
|
||||
t = time.time()
|
||||
while True:
|
||||
try:
|
||||
return call.get(timeout=WAIT_SAY_S)
|
||||
except timeouts as e:
|
||||
# Modal's FunctionTimeoutError is a TimeoutError too: the run itself ran out of time, so it goes up as
|
||||
# .remote() raised it, not waited on again (it would answer the same at once, forever)
|
||||
if type(e).__name__ == "FunctionTimeoutError":
|
||||
raise
|
||||
log(f"raea farm: waiting {time.time() - t:.0f} s for a GPU run to answer (queued while the workspace's GPUs are busy, or still drawing)")
|
||||
|
||||
|
||||
def gpus_for(frames, frame_s, start_s, most):
|
||||
"""The GPUs worth starting for `frames` frames of `frame_s` each, when each one first spends `start_s`: the most that
|
||||
keep each one's start at most SHARE of its time, never more than `most`."""
|
||||
@@ -218,7 +190,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
if out.endswith(VIDEO):
|
||||
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
|
||||
t.start()
|
||||
p = bill.add(waited(render, log, id, rest, probe=True))
|
||||
p = bill.add(render.remote(id, rest, probe=True))
|
||||
if p["code"] or not p["length"]:
|
||||
log(p["out"], err=True)
|
||||
if not p["code"]:
|
||||
@@ -228,7 +200,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
|
||||
video = out.endswith(VIDEO)
|
||||
n0 = min(length, FIRST)
|
||||
r0 = bill.add(waited(render, log, id, rest, list(range(n0)), 0, video=video))
|
||||
r0 = bill.add(render.remote(id, rest, list(range(n0)), 0, video=video))
|
||||
if r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
@@ -349,7 +321,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
|
||||
if video:
|
||||
o |= {"video": True, "fps": info["fps"]}
|
||||
log(f"raea farm: {blend}, frames {first}-{last} ({info['engine']}), at {info['fps']:g} fps")
|
||||
r0 = bill.add(waited(render, log, id, blend, first, first, o))
|
||||
r0 = bill.add(render.remote(id, blend, first, first, o))
|
||||
if r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
@@ -394,7 +366,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
|
||||
if splittable(args):
|
||||
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill)
|
||||
else:
|
||||
r = bill.add(waited(render, log, opts["id"], args))
|
||||
r = bill.add(render.remote(opts["id"], args))
|
||||
log(r["out"], err=bool(r["code"]))
|
||||
code = r["code"]
|
||||
log(bill.line())
|
||||
|
||||
@@ -158,35 +158,4 @@ b.add({"code": 1, "out": "no task id"})
|
||||
assert "2 GPU containers up 35 s" in b.line(), b.line()
|
||||
ok("the bill: each container from its boot or the job's start to its last run, plus its boot and idle seconds")
|
||||
|
||||
# a GPU run with no answer yet is said in the log, not waited on in silence; its answer still comes back
|
||||
class SlowCall:
|
||||
def __init__(self, waits): self.waits = waits
|
||||
def get(self, timeout=None):
|
||||
if self.waits:
|
||||
self.waits -= 1
|
||||
raise TimeoutError
|
||||
return {"code": 0, "out": "drawn"}
|
||||
class SlowGpu:
|
||||
def spawn(self, *a, **kw): return SlowCall(2)
|
||||
lines.clear()
|
||||
fp.WAIT_SAY_S = 0.01
|
||||
assert fp.waited(SlowGpu(), log, "j4", ["render"]) == {"code": 0, "out": "drawn"}
|
||||
assert sum("waiting" in l and "GPU run" in l for l in lines) == 2, lines
|
||||
ok("a GPU run that hasn't answered is said in the log every WAIT_SAY_S until it does")
|
||||
|
||||
# a GPU run that ran out of its own time fails the job, as .remote() did, instead of being waited on forever
|
||||
class FunctionTimeoutError(TimeoutError): pass
|
||||
class TimedOutCall:
|
||||
def get(self, timeout=None): raise FunctionTimeoutError("Function timeout")
|
||||
class TimedOutGpu:
|
||||
def spawn(self, *a, **kw): return TimedOutCall()
|
||||
lines.clear()
|
||||
try:
|
||||
fp.waited(TimedOutGpu(), log, "j5", ["render"])
|
||||
raise AssertionError("waited() swallowed a function timeout")
|
||||
except FunctionTimeoutError:
|
||||
pass
|
||||
assert not any("waiting" in l for l in lines), lines
|
||||
ok("a GPU run that timed out fails the job instead of being waited on forever")
|
||||
|
||||
shutil.rmtree(root)
|
||||
@@ -8,6 +8,7 @@ import { createRoot } from "react-dom/client";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { Input } from "@raea/playable/host/input";
|
||||
import { Collector, UNDER3D_CSS, clearUnder3d } from "./collect";
|
||||
import { patchShaderModules } from "./wgsl";
|
||||
|
||||
/** raea-web's engine, as wasm-bindgen exports it (engine/web: `import init, { Raea } from "./raea_web.js"`). */
|
||||
export interface RaeaEngine {
|
||||
@@ -31,6 +32,8 @@ const loaded = new WeakMap<() => Promise<RaeaWebModule>, Promise<RaeaWebModule>>
|
||||
export function loadRaea(load: () => Promise<RaeaWebModule>): Promise<RaeaWebModule> {
|
||||
let p = loaded.get(load);
|
||||
if (!p) {
|
||||
// Safari reads WGSL to the letter: Bevy's shaders are made to its rules first (wgsl.ts)
|
||||
patchShaderModules();
|
||||
p = load().then(async (m) => (await m.default(), m));
|
||||
loaded.set(load, p);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Safari's WGSL (WebKit) holds to the spec: a `let` can't hold a texture or a sampler (they aren't constructible
|
||||
// types), while Chrome's Tint lets it through. Bevy's PBR shaders do it (bevy_pbr pbr_fragment.wesl,
|
||||
// `let texture = pbr_bindings::base_color_texture;`), in every mesh with UVs, so raea-web drew nothing in Safari
|
||||
// ("Fragment module is invalid", 12-02). Each such `let` is inlined here before the module is made: its name is replaced
|
||||
// by what it held (a global binding, or an index into a binding array) through the rest of its block.
|
||||
|
||||
/** the global bindings of handle types (textures, samplers, arrays of either) a shader declares */
|
||||
function handles(code: string): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const m of code.matchAll(/\bvar\s+(\w+)\s*:\s*(?:texture_|sampler|binding_array\s*<\s*(?:texture_|sampler))/g)) out.add(m[1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** where the block holding `at` closes (the index of its `}`), or the end */
|
||||
function blockEnd(code: string, at: number): number {
|
||||
let depth = 0;
|
||||
for (let i = at; i < code.length; i++) {
|
||||
const c = code[i];
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
if (depth === 0) return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return code.length;
|
||||
}
|
||||
|
||||
/** The shader with every `let` that holds a texture or sampler inlined; the same text when there's none. */
|
||||
export function inlineHandleLets(code: string): string {
|
||||
const globals = handles(code);
|
||||
if (!globals.size) return code;
|
||||
const decl = /\blet\s+(\w+)\s*(?::\s*[^=]+)?=\s*([^;]+);/g;
|
||||
for (let guard = 0; guard < 10_000; guard++) {
|
||||
decl.lastIndex = 0;
|
||||
let m: RegExpExecArray | null, found: RegExpExecArray | null = null;
|
||||
while ((m = decl.exec(code))) {
|
||||
const root = /^\s*(?:\w+::)*(\w+)/.exec(m[2])?.[1];
|
||||
if (root && globals.has(root)) { found = m; break; }
|
||||
}
|
||||
if (!found) return code;
|
||||
const [whole, name, held] = found;
|
||||
const from = found.index + whole.length;
|
||||
const end = blockEnd(code, from);
|
||||
const value = held.trim().replace(/\s+/g, " ");
|
||||
const rest = code.slice(from, end).replace(new RegExp(`\\b${name}\\b`, "g"), () => value);
|
||||
code = code.slice(0, found.index) + rest + code.slice(end);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
let patched = false;
|
||||
/** Makes every WebGPU shader module from its inlined text (once per page; nothing where there's no WebGPU). */
|
||||
export function patchShaderModules() {
|
||||
const G = (globalThis as { GPUDevice?: { prototype: { createShaderModule(d: { code: string }): unknown } } }).GPUDevice;
|
||||
if (patched || !G) return;
|
||||
patched = true;
|
||||
const make = G.prototype.createShaderModule;
|
||||
G.prototype.createShaderModule = function (d: { code: string }) {
|
||||
return make.call(this, typeof d?.code === "string" ? { ...d, code: inlineHandleLets(d.code) } : d);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// wgsl.ts: a `let` holding a texture or sampler is inlined for Safari; everything else is left as it was
|
||||
import { expect, test } from "bun:test";
|
||||
import { inlineHandleLets } from "../../src/wgsl";
|
||||
|
||||
const head = `@group(2) @binding(1) var base_color_texture: texture_2d<f32>;
|
||||
@group(2) @binding(2) var base_color_sampler: sampler;
|
||||
@group(2) @binding(3) var bindless_textures_2d: binding_array<texture_2d<f32>, 16>;
|
||||
`;
|
||||
|
||||
test("a texture and a sampler held by lets are used directly, in their block only", () => {
|
||||
const code = `${head}fn f(uv: vec2<f32>) -> vec4<f32> {
|
||||
var c = vec4(1.0);
|
||||
if (true) {
|
||||
let texture = base_color_texture;
|
||||
let sampler_ = base_color_sampler;
|
||||
let coords = uv;
|
||||
c *= textureSampleBias(texture, sampler_, coords, 0.0);
|
||||
}
|
||||
let texture_scale = 2.0;
|
||||
return c * texture_scale;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).not.toContain("let texture =");
|
||||
expect(out).not.toContain("let sampler_ =");
|
||||
expect(out).toContain("textureSampleBias(base_color_texture, base_color_sampler, coords, 0.0)");
|
||||
expect(out).toContain("let coords = uv;");
|
||||
expect(out).toContain("let texture_scale = 2.0;");
|
||||
expect(out).toContain("return c * texture_scale;");
|
||||
});
|
||||
|
||||
test("a binding array's element, over lines, and the same name again in the next block", () => {
|
||||
const code = `${head}fn g(i: u32, uv: vec2<f32>) -> f32 {
|
||||
var a = 0.0;
|
||||
{
|
||||
let texture = bindless_textures_2d[
|
||||
i
|
||||
];
|
||||
a += textureSample(texture, base_color_sampler, uv).r;
|
||||
}
|
||||
{
|
||||
let texture = base_color_texture;
|
||||
a += textureSample(texture, base_color_sampler, uv).g;
|
||||
}
|
||||
return a;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).toContain("textureSample(bindless_textures_2d[ i ], base_color_sampler, uv).r");
|
||||
expect(out).toContain("textureSample(base_color_texture, base_color_sampler, uv).g");
|
||||
expect(out).not.toMatch(/let texture\b/);
|
||||
});
|
||||
|
||||
test("a module path (naga_oil's pbr_bindings::) is a binding all the same; a shader with no handles is untouched", () => {
|
||||
expect(inlineHandleLets(`${head}fn h() { let t = pbr_bindings::base_color_texture; textureDimensions(t); }`)).toContain("textureDimensions(pbr_bindings::base_color_texture)");
|
||||
const plain = "fn k() -> f32 { let x = 1.0; return x; }";
|
||||
expect(inlineHandleLets(plain)).toBe(plain);
|
||||
});
|
||||
Reference in new issue
Block a user