Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
TokenSynth on an NVIDIA GPU (docs/cloud-render.feature CR25): run.py --device cpu|cuda (the DAC decoder and the model on the device, sampling still on the CPU from the seed), raea's asset store passes it from RAEA_TOKENSYNTH_DEVICE (the device is in the cache key, so a GPU's note is its own sample), and an install from before --device says to run setup.sh again. sdk/cloud/deploy/modal/tokensynth.py installs it into raea-models (built at its own path on the container's disk: uv's temporary files fail on the volume, and the venv names its path) and measures it. On a Modal A10, 2.5 s a note with the model loaded against 50.6 s on 4 CPU cores; a process a note, 15.5 s on a T4 against 103 s. CLAP audio embeddings: 4 of 6 GPU notes are as close to the CPU's as two CPU seeds are.
shinyobjectzc53a2cfd47df
diff --git a/apps/tools/src/sound.rs b/apps/tools/src/sound.rsindex 502339ec..4671e1f5 100644--- a/apps/tools/src/sound.rs+++ b/apps/tools/src/sound.rs@@ -186,11 +186,17 @@ pub fn tokensynth(args: &[String]) -> R<String> {if !raea_io_assets::TOKENSYNTH_PRECISIONS.contains(&precision.as_str()) {return Err(format!("--precision is one of {}", raea_io_assets::TOKENSYNTH_PRECISIONS.join(", ")));}+ // RAEA_TOKENSYNTH_DEVICE=cuda: an NVIDIA GPU (raea's cloud farm sets it); it's in the params, so a GPU's note is+ // its own sample in the store, never taken for the CPU's+ let device = std::env::var("RAEA_TOKENSYNTH_DEVICE").unwrap_or_else(|_| "cpu".into());+ if device != "cpu" && device != "cuda" {+ return Err(format!("RAEA_TOKENSYNTH_DEVICE is cpu or cuda, got {device}"));+ }let s = store(args);let out = flag(args, "-o").map(PathBuf::from);let mut lines = Vec::new();for (name, midi) in ¬es {- let params = json!({"seconds": seconds, "midi": midi, "velocity": velocity, "seed": seed, "device": "cpu", "precision": precision});+ let params = json!({"seconds": seconds, "midi": midi, "velocity": velocity, "seed": seed, "device": device, "precision": precision});let cached = s.made("tokensynth", &timbre, seed, ¶ms)?.is_some_and(|a| s.path(&a).exists());let t0 = std::time::Instant::now();let a = s.make("tokensynth", &timbre, seed, ¶ms)?;diff --git a/io/assets/src/local.rs b/io/assets/src/local.rsindex 24a73841..5226feb3 100644--- a/io/assets/src/local.rs+++ b/io/assets/src/local.rs@@ -33,14 +33,17 @@ pub(crate) fn sao(prompt: &str, seed: u64, params: &J, part: &Path) -> Result<Ve/// TokenSynth (local; tools/tokensynth/setup.sh installs it in $RAEA_TOKENSYNTH, else ~/.cache/raea-tokensynth, on first/// use): one note of the instrument the prompt describes, {midi, velocity, seconds} in the params, normalised to -1-/// dBFS. The device is in the params (CPU and MPS give different samples from the same seed), so the cache key holds it;+/// dBFS. The device is in the params (cpu or cuda: each gives its own sample from the same seed), so the cache key holds it;/// so is `precision` (fp32, fp16, bf16, int8 or coreml: run.py --precision), since each precision samples differently/// from the same seed. Absent, it's fp16, run.py's default and what TSX's tokensynth() and the CLI always write out./// (Until 2026-10-19 an absent precision meant fp32 here; nothing has written a note without one since precisions/// existed, so no cached key changes meaning in practice.)pub(crate) fn tokensynth(prompt: &str, seed: u64, params: &J, part: &Path) -> Result<Vec<u8>, String> {- if params["device"].as_str().unwrap_or("cpu") != "cpu" {- return Err("tokensynth: only the CPU renders (MPS can't run DAC's decoder on long clips)".into());+ // the CPU everywhere, or an NVIDIA GPU (cuda: Linux, Windows, raea's cloud farm); MPS can't run DAC's decoder on+ // long clips+ let device = params["device"].as_str().unwrap_or("cpu");+ if device != "cpu" && device != "cuda" {+ return Err(format!("tokensynth: device `{device}`: cpu or cuda (MPS can't run DAC's decoder on long clips)"));}let precision = params["precision"].as_str().unwrap_or(TOKENSYNTH_PRECISION);if !TOKENSYNTH_PRECISIONS.contains(&precision) {@@ -60,12 +63,18 @@ pub(crate) fn tokensynth(prompt: &str, seed: u64, params: &J, part: &Path) -> Re.arg(dir.join("weights")).arg("--wav").arg(&wav)+ // only a GPU asks: an install set up before --device existed still renders CPU notes+ .args(if device == "cuda" { vec!["--device", "cuda"] } else { vec![] }).output().map_err(|e| format!("tokensynth: {}: {e}", dir.display()))?;let bytes = std::fs::read(&wav);let _ = std::fs::remove_file(&wav);if !out.status.success() {- return Err(format!("tokensynth: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("failed")));+ let err = String::from_utf8_lossy(&out.stderr);+ if device == "cuda" && err.contains("unrecognized arguments: --device") {+ return Err(format!("tokensynth: the install in {} is from before cuda: run tools/tokensynth/setup.sh again", dir.display()));+ }+ return Err(format!("tokensynth: {}", err.lines().last().unwrap_or("failed")));}bytes.map_err(|e| format!("tokensynth: {}: {e}", wav.display()))}diff --git a/sdk/cloud/deploy/modal/tokensynth.py b/sdk/cloud/deploy/modal/tokensynth.pynew file mode 100644index 00000000..d99b5176--- /dev/null+++ b/sdk/cloud/deploy/modal/tokensynth.py@@ -0,0 +1,153 @@+# TokenSynth on raea's Modal GPUs (docs/cloud-render.feature CR25): tools/tokensynth installed once into the volume+# raea-models (/models/tokensynth, what the farm mounts as RAEA_TOKENSYNTH), then its notes on an NVIDIA GPU+# (run.py --device cuda) measured against the CPU's in the same container. From sdk/cloud:+#+# MODAL_PROFILE=raea modal run deploy/modal/tokensynth.py --setup-only # the install (CPU, once)+# MODAL_PROFILE=raea modal run deploy/modal/tokensynth.py [--gpu L4] [--warm-only] --out DIR # the check: times, CLAP, the wavs+#+# A note runs as raea runs one (a process each, the model loaded each time) and warm (one process, the runtime loaded+# once, as a batch would). The GPU's notes are their own samples (its logits round differently), so they're judged as+# a new seed is: CLAP's text-audio match to the timbre, against the CPU's, and the GPU take's distance from the CPU take+# against a second CPU take's (another seed). The venv lives on the volume, its Python in the image (/opt/uv-python),+# so every container of this image runs it.++import json+import os+import subprocess+import threading+import time++import modal++HERE = os.path.dirname(os.path.abspath(__file__))+TOOL = os.path.normpath(os.path.join(HERE, "..", "..", "..", "..", "tools", "tokensynth"))+DIR = "/models/tokensynth"+models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2)+image = (+ modal.Image.from_registry("debian:trixie-slim", add_python="3.12")+ .apt_install("ca-certificates", "curl", "git", "ffmpeg")+ .pip_install("uv==0.8.0")+ .env({"UV_PYTHON_INSTALL_DIR": "/opt/uv-python", "UV_PYTHON_PREFERENCE": "only-managed", "UV_CACHE_DIR": "/tmp/uv-cache", "HF_HOME": "/tmp/hf"})+ .run_commands("uv python install 3.11")+ .add_local_dir(TOOL, "/tools/tokensynth", ignore=["__pycache__", ".venv"])+)+app = modal.App("raea-tokensynth", image=image)++NOTES = [("grand piano", 48), ("grand piano", 72), ("nylon string guitar", 55), ("warm analog synth pad", 60), ("muted trumpet", 65), ("plucked cello", 43)]+SECONDS, SEED = 2.0, 1234++WARM = r"""+import json, sys, time+sys.path.insert(0, sys.argv[1])+import run, soundfile as sf, numpy as np, torch+notes, device, seed, out = json.loads(sys.argv[2]), sys.argv[3], int(sys.argv[4]), sys.argv[5]+t = time.time(); rt = run.Runtime("fp16", sys.argv[1] + "/weights", device); load = time.time() - t+times = []+for timbre, midi in notes:+ t = time.time(); (audio, _), _ = rt.render(timbre, midi, 100, 2.0, seed)+ if device == "cuda": torch.cuda.synchronize()+ times.append(time.time() - t)+ sf.write(f"{out}/{device}-s{seed}-{midi}-{timbre.replace(' ', '_')}.wav", np.stack([audio, audio], 1), run.SR, subtype="FLOAT")+print(json.dumps({"load": load, "times": times}))+"""++CLAP = r"""+import json, sys, glob, os+import numpy as np, soundfile as sf, torch, laion_clap+from scipy.signal import resample_poly+m = laion_clap.CLAP_Module(enable_fusion=False, amodel="HTSAT-base", device="cuda" if torch.cuda.is_available() else "cpu")+m.load_ckpt(sys.argv[1], verbose=False)+unit = lambda v: v / np.linalg.norm(v)+out = {}+for f in sorted(glob.glob(sys.argv[2] + "/*.wav")):+ a, sr = sf.read(f, dtype="float32")+ a = resample_poly(a.mean(1) if a.ndim > 1 else a, 160, 147).astype(np.float32) # 44.1 to 48 kHz, CLAP's rate+ timbre = os.path.basename(f)[:-4].split("-", 3)[3].replace("_", " ")+ e = unit(m.get_audio_embedding_from_data(x=a[None], use_tensor=False)[0])+ t = unit(m.get_text_embedding([timbre, timbre])[0])+ out[os.path.basename(f)] = {"text": float(e @ t), "emb": e.tolist()}+print(json.dumps(out))+"""+++def beat(label, path, done):+ while not done.wait(30):+ n = sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk(path) for f in fs) if os.path.isdir(path) else 0+ print(f"{label}: {n / 1e9:.2f} GB in {path} so far", flush=True)++[email protected](volumes={"/vol": models}, cpu=8, memory=16384, timeout=3600)+def setup() -> dict:+ """tools/tokensynth/setup.sh, then the install onto the volume: the repo, the venv, the weights and convert.py's fp16+ runtime (its Core ML half fails here and is skipped, as on any machine that isn't a Mac). It's built at DIR on the+ container's own disk, the volume mounted beside it at /vol, then copied in: uv's temporary files in a venv on the+ volume fail (11-17), and the venv names its own path (the editable repo), so it's built where bench() finds it."""+ done = threading.Event()+ threading.Thread(target=beat, args=("tokensynth setup", DIR, done), daemon=True).start()+ t = time.time()+ r = subprocess.run(["sh", "/tools/tokensynth/setup.sh"], env={**os.environ, "RAEA_TOKENSYNTH": DIR, "RAEA_TOKENSYNTH_FROM": "/nonexistent"}, capture_output=True, text=True)+ built = round(time.time() - t)+ if r.returncode == 0:+ subprocess.run(["rm", "-rf", "/vol/tokensynth"], check=True)+ subprocess.run(["cp", "-a", DIR, "/vol/tokensynth"], check=True)+ models.commit()+ done.set()+ return {"code": r.returncode, "s": built, "copied_s": round(time.time() - t) - built, "tail": (r.stdout + r.stderr)[-1500:]}+++# a list is Modal's fallback order, whichever is free first (11-17: no T4 for 10 minutes, then a T4 taken back mid-run); --gpu names one[email protected](volumes={"/models": models}, gpu=["T4", "L4", "A10G"], cpu=4, memory=16384, timeout=3600)+def bench(notes: list, process: bool = True) -> dict:+ py = f"{DIR}/.venv/bin/python"+ out = "/tmp/notes"+ os.makedirs(out, exist_ok=True)+ gpu = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip()+ print(f"bench: on {gpu}", flush=True)+ res = {"gpu": gpu, "process": [], "warm": {}}+ # a process a note, as raea's asset store runs one (the model loads each time); the CPU on the first two only (11-17:+ # it's 103-105 s a note every time, and all six with the warm runs ran past a 30-minute limit)+ for i, (timbre, midi) in enumerate(notes if process else []):+ row = {"timbre": timbre, "midi": midi}+ for dev in ("cpu", "cuda") if i < 2 else ("cuda",):+ wav = f"/tmp/{dev}-{midi}.wav"+ t = time.time()+ r = subprocess.run([py, "-I", f"{DIR}/run.py", "--timbre", timbre, "--midi", str(midi), "--seconds", str(SECONDS), "--seed", str(SEED),+ "--weights", f"{DIR}/weights", "--wav", wav] + (["--device", "cuda"] if dev == "cuda" else []), capture_output=True, text=True)+ row[dev] = round(time.time() - t, 2) if r.returncode == 0 else f"failed: {r.stderr.strip().splitlines()[-1:]}"+ print(f"bench: {timbre} {midi} on {dev}: {row[dev]}", flush=True)+ res["process"].append(row)+ # warm: one process, the runtime loaded once; the CPU twice (a second seed: how far two CPU takes are apart)+ for dev, seed in (("cuda", SEED), ("cpu", SEED), ("cpu", SEED + 1)):+ # -I: Modal puts this file, tokensynth.py, in the working folder, and `-c` would import it as the package (11-17)+ r = subprocess.run([py, "-I", "-c", WARM, DIR, json.dumps(notes), dev, str(seed), out], capture_output=True, text=True)+ res["warm"][f"{dev}-s{seed}"] = json.loads(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else r.stderr[-800:]+ print(f"bench: warm {dev} seed {seed}: {json.dumps(res['warm'][f'{dev}-s{seed}'])[:600]}", flush=True)+ r = subprocess.run([py, "-I", "-c", CLAP, f"{DIR}/weights/clap_music_audioset_epoch_15_esc_90.14.pt", out], capture_output=True, text=True)+ res["clap"] = json.loads(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else r.stderr[-800:]+ if isinstance(res["clap"], dict):+ for f, v in res["clap"].items():+ print(f"bench: clap {f}: text {v['text']:.3f}", flush=True)+ else:+ print(f"bench: clap failed: {res['clap']}", flush=True)+ res["wavs"] = {f: open(os.path.join(out, f), "rb").read() for f in sorted(os.listdir(out))}+ return res++[email protected]_entrypoint()+def main(gpu: str = "", out: str = "", setup_only: bool = False, setup_first: bool = False, warm_only: bool = False):+ if setup_only or setup_first:+ s = setup.remote()+ print(f"setup: exit {s['code']} in {s['s']} s\n{s['tail']}")+ if setup_only or s["code"] != 0:+ return+ r = (bench.with_options(gpu=gpu) if gpu else bench).remote(NOTES, not warm_only)+ wavs = r.pop("wavs")+ if out:+ os.makedirs(out, exist_ok=True)+ for f, b in wavs.items():+ open(os.path.join(out, f), "wb").write(b)+ json.dump(r, open(os.path.join(out, "bench.json"), "w"), indent=1)+ clap = r.get("clap") if isinstance(r.get("clap"), dict) else {}+ print(json.dumps({k: v for k, v in r.items() if k != "clap"}, indent=1))+ for f, v in clap.items():+ print(f"clap {f}: text {v['text']:.3f}")diff --git a/tools/tokensynth/run.py b/tools/tokensynth/run.pyindex 88980cdd..70357e8a 100644--- a/tools/tokensynth/run.py+++ b/tools/tokensynth/run.py@@ -3,7 +3,10 @@and keeps the bytes under their hash (sdk/react/docs/audio-stack.md, "Generated sources"). TokenSynth reads notes that endbefore 5.0 s; `seconds` is the note's held length, and the release rings on up to 1.5 s after it.run.py --timbre TEXT --midi N [--velocity 100] [--seconds 2] [--seed 1234] --wav OUT.wav [--weights DIR]- [--precision fp32|fp16|bf16|int8|coreml]+ [--precision fp32|fp16|bf16|int8|coreml] [--device cpu|cuda]+--device cuda runs the transformers and DAC's decoder on an NVIDIA GPU (Linux, Windows) with fp16, bf16 or fp32; the+sampling stays on the CPU from the seed. A GPU's logits round differently from the CPU's, so its notes are their own+samples, as each precision's are.--precision picks the runtime; all but fp32 read what convert.py made beside DIR (weights-fp16/, coreml/), skiplaion_clap's audio tower and CLAP's 2.35 GB file, and stop generating once the frames cover the note and its release(TokenSynth otherwise runs its 450-step cap; the audio is the same, CLAP cosine 1.000 on the same tokens):@@ -218,7 +221,10 @@ class Runtime:def __init__(self, precision, weights, device="cpu"):self.precision, self.W = precision, Path(weights)self.F, self.C = self.W.parent / "weights-fp16", self.W.parent / "coreml"- dev = torch.device(device)+ dev = self.dev = torch.device(device)+ # int8 is PyTorch's dynamic quantization (CPU kernels only) and coreml is the Mac's: neither runs on a GPU+ if dev.type != "cpu" and precision in ("int8", "coreml"):+ raise SystemExit(f"tokensynth: {precision} runs on the CPU only; fp16, bf16 or fp32 on {dev.type}")if precision != "fp32":_bare_package("tokensynth")from tokensynth import utils as ts_utils@@ -262,7 +268,8 @@ class Runtime:if precision == "coreml":self.dac = ct.models.CompiledMLModel(str(self.C / "dac_decoder.mlmodelc"), compute_units=cu)else:- self.dac = load_dac(self.F)+ # on a GPU the decoder goes there too: it's most of a note's time on the CPU+ self.dac = load_dac(self.F).to(dev)def text(self, timbre):with torch.no_grad():@@ -297,7 +304,7 @@ class Runtime:pad[:, :, :min(n, frames)] = codes[:, :, :frames].numpy()audio = self.dac.predict({"codes": pad})["audio"].reshape(-1)return audio[: n * 512].astype(np.float32)- return self.dac(codes).float().numpy()+ return self.dac(codes.to(self.dev)).float().cpu().numpy()def render(self, timbre, midi, velocity=100, seconds=2.0, seed=1234):held = max(0.05, min(seconds, 3.4))@@ -327,12 +334,15 @@ def main():ap.add_argument("--wav", required=True)ap.add_argument("--weights", default=str(Path(__file__).resolve().parent / "weights"))ap.add_argument("--precision", choices=PRECISIONS, default=DEFAULT)+ # cuda: the transformer and the decoder on an NVIDIA GPU (Linux, Windows), the sampling still on the CPU from the+ # seed, so a note's draws match the CPU's while their logits do; mps stays refused by raea (DAC on long clips)+ ap.add_argument("--device", choices=("cpu", "cuda", "mps"), default="cpu")args = ap.parse_args()import soundfile as sf- rt = Runtime(args.precision, args.weights)+ rt = Runtime(args.precision, args.weights, args.device)(audio, peak), _ = rt.render(args.timbre, args.midi, args.velocity, args.seconds, args.seed)sf.write(args.wav, np.stack([audio, audio], axis=1), SR, subtype="FLOAT")- print(f"tokensynth: midi {args.midi}, {len(audio) / SR:.2f} s, peak was {peak:.2f}, {args.precision}", file=sys.stderr)+ print(f"tokensynth: midi {args.midi}, {len(audio) / SR:.2f} s, peak was {peak:.2f}, {args.precision} on {args.device}", file=sys.stderr)if __name__ == "__main__":