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
raea motion on PyTorch off the Mac, raea setup motion, and shaded meshes that spawn after a load
shinyobjectz10a18eb33292
diff --git a/apps/tools/Cargo.toml b/apps/tools/Cargo.tomlindex 6376c96b..3a516779 100644--- a/apps/tools/Cargo.toml+++ b/apps/tools/Cargo.toml@@ -17,7 +17,6 @@ serde_json = "1"# the verbs' flags read as a render reads its ownraea-runtime-bundle = { path = "../../runtime/bundle" }raea-runtime-export = { path = "../../runtime/export" }--# `raea motion`: Kimodo on MLX, Apple silicon's-[target.'cfg(target_os = "macos")'.dependencies]+# `raea motion` and `raea setup motion`: Kimodo on MLX on a Mac, on PyTorch elsewhere (raea-sys-kimodo's torch.rs, plain+# Rust that runs the environment it makes)raea-sys-kimodo = { path = "../../systems/kimodo" }diff --git a/apps/tools/src/lib.rs b/apps/tools/src/lib.rsindex a8a18b64..643eed89 100644--- a/apps/tools/src/lib.rs+++ b/apps/tools/src/lib.rs@@ -4,7 +4,7 @@//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs).pub mod generate;-/// `raea motion`: body motion made on this Mac by Kimodo on MLX (raea-sys-kimodo)+/// `raea motion` and `raea setup motion`: body motion made by Kimodo, on MLX on a Mac, on PyTorch elsewhere (raea-sys-kimodo)pub mod motion;pub mod song;pub mod sound;diff --git a/apps/tools/src/motion.rs b/apps/tools/src/motion.rsindex 6c8d0b67..a74925d8 100644--- a/apps/tools/src/motion.rs+++ b/apps/tools/src/motion.rs@@ -1,7 +1,11 @@-//! `raea motion "LINE" [--keys KEYS.json] ...`: body motion made on this Mac by Kimodo (raea-sys-kimodo, on MLX): a-//! SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a-//! root path: what sdk/body/tools/between.ts writes). The clip is the file sdk/body/tools/fromkimodo.ts reads, the-//! same one the cloud runner wrote (docs/character.feature CH15b, CH15c).+//! `raea motion "LINE" [--keys KEYS.json] ...`: body motion made on this machine by Kimodo (raea-sys-kimodo): a SOMA clip+//! from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path:+//! what sdk/body/tools/between.ts writes). The clip is the file sdk/body/tools/fromkimodo.ts reads, the same one the+//! cloud runner wrote (docs/character.feature CH15b, CH15c).+//!+//! Which backend makes it is the machine's: MLX on a Mac (Apple silicon), PyTorch elsewhere (Linux, Windows), in the+//! environment `raea setup motion` makes (raea-sys-kimodo torch.rs). Both hand decode.rs the sampler's features, so+//! both write one file; their noise differs, so a seed is a different take on each.use std::path::PathBuf;@@ -10,7 +14,10 @@ use raea_runtime_bundle::flag;type R<T> = Result<T, String>;pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json]";-pub const ABOUT: &str = "body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads; the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters); a line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT";+pub const ABOUT: &str = "body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0";++pub const SETUP_USAGE: &str = "raea setup motion [--check]";+pub const SETUP_ABOUT: &str = "what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU";fn number(args: &[String], name: &str, default: f64) -> R<f64> {match flag(args, name) {@@ -68,9 +75,72 @@ pub fn motion(args: &[String]) -> R<String> {make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })}+/// -o, else a file named by the line's words in the working folder+fn out_path(out: Option<String>, clean: &str) -> PathBuf {+ PathBuf::from(out.unwrap_or_else(|| {+ let slug = clean.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_lowercase).collect::<Vec<_>>().join("-");+ format!("{}.clip.json", if slug.is_empty() { "keys".to_string() } else { slug.chars().take(60).collect() })+ }))+}++/// how far the hips end from where they start, on the ground+fn travel(m: &raea_sys_kimodo::decode::Motion) -> f32 {+ let r = &m.root;+ let (a, b) = (r[0], r[r.len() - 1]);+ ((b[0] - a[0]).powi(2) + (b[2] - a[2]).powi(2)).sqrt()+}++/// Kimodo's PyTorch environment: raea's models folder's kimodo-torch+#[cfg(not(target_os = "macos"))]+fn torch_env() -> raea_sys_kimodo::torch::Torch {+ raea_sys_kimodo::torch::Torch::at(raea_io_home::models().join("kimodo-torch"))+}+#[cfg(not(target_os = "macos"))]fn make(ask: Ask) -> R<String> {- Err(format!("raea motion runs Kimodo on MLX, on Apple silicon's GPU: {:?} can be made on a Mac", ask.words))+ use raea_sys_kimodo::{decode, skeleton::Skeleton, stats::Stats, torch};+ let t = torch_env();+ let missing = t.missing();+ if !missing.is_empty() {+ return Err(format!(+ "raea motion runs Kimodo on PyTorch on this machine (MLX is Apple silicon's), and its {} isn't set up in {} yet: raea setup motion makes it (uv, then about 26 GB: PyTorch, Kimodo's code and weights, Llama 3 8B Instruct for the text encoder)",+ missing.join(", the "),+ t.dir.display()+ ));+ }+ let keys = ask.keys.as_ref().map(std::path::Path::new);+ let job = torch::Job { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, keys, cfg: (2.0, 2.0) };+ let made = t.make(&job).map_err(|e| format!("raea motion: {e}"))?;+ let (stats, sk) = (Stats::load(&t.checkpoint()).map_err(|e| format!("raea motion: {e}"))?, Skeleton::soma().map_err(|e| format!("raea motion: {e}"))?);+ let motion = decode::decode(&made.features, &stats, &sk);+ let info = &made.info;+ let clean = info["line"].as_str().unwrap_or(&ask.words).to_string();+ let (dev, text_dev) = (info["motion"].as_str().unwrap_or("?"), info["text"].as_str().unwrap_or("?"));+ let on = match info["gpu"].as_str().filter(|_| dev == "cuda") {+ Some(g) => format!("on PyTorch {} with CUDA ({g}; the text encoder on {text_dev}), upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),+ None => format!("on PyTorch {} on the CPU, upstream nv-tlabs/kimodo {}", info["torch"].as_str().unwrap_or("?"), &torch::KIMODO[..7]),+ };+ let clip = decode::clip_json_on(&motion, &sk, ask.seed, ask.steps, &clean, ask.constraints.is_some(), &on);+ let out = out_path(ask.out, &clean);+ std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;+ // the hips as PyTorch decoded them against decode.rs's: the features were read as Kimodo wrote them+ let ours: Vec<[f32; 3]> = motion.joints77.iter().map(|f| f[0]).collect();+ let gap = torch::root_gap(&info["root"], &ours).map(|g| format!(", decoded here within {:.3} mm of PyTorch's own", g * 1000.0)).unwrap_or_default();+ let f = |k: &str| info[k].as_f64().unwrap_or(0.0);+ let read = if f("read_s") > 0.0 { format!(", reading the line {:.1} s after {:.1} s loading its encoder", f("read_s"), f("text_load_s")) } else { String::new() };+ Ok(format!(+ "APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made {on} in {:.1} s after {:.1} s loading{read}; the hips end {:.2} m from where they start{gap})",+ clean,+ if ask.keys.is_some() { " with keys" } else { "" },+ ask.frames,+ ask.frames as f64 / 30.0,+ ask.seed,+ ask.steps,+ out.display(),+ f("gen_s"),+ f("load_s"),+ travel(&motion),+ ))}#[cfg(target_os = "macos")]@@ -80,13 +150,7 @@ fn make(ask: Ask) -> R<String> {unsafe { std::env::set_var("MLX_ENABLE_TF32", "0") };}let t0 = std::time::Instant::now();- // a line every 512 MB of each file fetched- let mut shown = std::collections::HashMap::<String, u64>::new();- let mut progress = |file: &str, n: u64| {- if shown.insert(file.to_string(), n >> 29) != Some(n >> 29) {- eprintln!("raea motion: fetching {file}: {} MB", n >> 20);- }- };+ let mut progress = fetching();let mut k = raea_sys_kimodo::Kimodo::fetch(&mut progress).map_err(|e| format!("raea motion: {e}"))?;let (clean, emb) = k.encode(&ask.words).map_err(|e| format!("raea motion: {e}"))?;let load_s = t0.elapsed().as_secs_f64();@@ -95,23 +159,112 @@ fn make(ask: Ask) -> R<String> {let made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;let gen_s = t1.elapsed().as_secs_f64();let clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());- // without -o, the line's words name the file- let out = PathBuf::from(ask.out.unwrap_or_else(|| {- let slug = clean.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_lowercase).collect::<Vec<_>>().join("-");- format!("{}.clip.json", if slug.is_empty() { "keys".to_string() } else { slug.chars().take(60).collect() })- }));+ let out = out_path(ask.out, &clean);std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;- let r = &made.motion.root;- let (a, b) = (r[0], r[r.len() - 1]);- let travel = ((b[0] - a[0]).powi(2) + (b[2] - a[2]).powi(2)).sqrt();Ok(format!(- "APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {travel:.2} m from where they start)",+ "APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {:.2} m from where they start)",clean,if ask.keys.is_some() { " with keys" } else { "" },ask.frames,ask.frames as f64 / 30.0,ask.seed,ask.steps,- out.display()+ out.display(),+ travel(&made.motion)))}++/// a line every 512 MB of each file fetched+#[cfg(target_os = "macos")]+fn fetching() -> impl FnMut(&str, u64) {+ let mut shown = std::collections::HashMap::<String, u64>::new();+ move |file: &str, n: u64| {+ if shown.insert(file.to_string(), n >> 29) != Some(n >> 29) {+ eprintln!("raea motion: fetching {file}: {} MB", n >> 20);+ }+ }+}++/// What a folder takes on disk, as du says it (through a link: the Mac's model folders can be links to their files)+fn disk(dir: &std::path::Path) -> String {+ std::process::Command::new("du").arg("-shL").arg(dir).output().ok()+ .and_then(|o| String::from_utf8_lossy(&o.stdout).split_whitespace().next().map(str::to_string))+ .unwrap_or_else(|| "?".into())+}++/// `raea setup motion [--check]`: what raea motion runs on here, made where missing (--check only says), and where it is.+pub fn setup(args: &[String]) -> R<String> {+ let check = args.iter().any(|a| a == "--check");+ if let Some(a) = args.iter().find(|a| *a != "--check") {+ return Err(format!("{SETUP_USAGE}: no `{a}`"));+ }+ setup_here(check)+}++#[cfg(target_os = "macos")]+fn setup_here(check: bool) -> R<String> {+ let was = raea_sys_kimodo::installed();+ if !check && was.iter().any(|m| !m.2) {+ raea_io_home::offline("raea setup motion's models").map_err(|e| format!("raea setup motion: {e}"))?;+ let mut progress = fetching();+ raea_sys_kimodo::fetch_all(&mut progress).map_err(|e| format!("raea setup motion: {e}"))?;+ }+ let now = raea_sys_kimodo::installed();+ let mut lines = vec![" backend MLX, on this Mac's GPU (raea-sys-kimodo, no Python)".to_string()];+ for ((name, dir, had), (_, _, has)) in was.iter().zip(&now) {+ let what = if *name == "kimodo" { "the motion model: Kimodo-SOMA-RP-v1, 1.1 GB, NVIDIA Open Model License" } else { "the text encoder: Llama 3 8B Instruct in 8 bits (Meta Llama 3 Community License) with LLM2Vec's adapters (MIT), 8.8 GB" };+ let state = match (had, has) {+ (true, _) => "installed",+ (false, true) => "installed now",+ (false, false) => "not installed: raea setup motion fetches it (raea motion does too, the first time it needs it)",+ };+ lines.push(format!(" {name:<12} {state}; {what}\n {} ({})", dir.display(), if *has { disk(dir) } else { "-".into() }));+ }+ let ready = now.iter().all(|m| m.2);+ let head = match (check, ready) {+ (true, true) => "CHECKED raea motion's models",+ (true, false) => "CHECKED raea motion's models (some missing)",+ _ => "APPLIED raea motion's models ready",+ };+ Ok(format!("{head}\n{}", lines.join("\n")))+}++#[cfg(not(target_os = "macos"))]+fn setup_here(check: bool) -> R<String> {+ let t = torch_env();+ let was = t.missing();+ let mut made = Vec::new();+ if !check && !was.is_empty() {+ raea_io_home::offline("raea setup motion's environment and weights").map_err(|e| format!("raea setup motion: {e}"))?;+ made = t.setup(&mut |s| eprintln!("raea setup motion: {s}")).map_err(|e| format!("raea setup motion: {e}"))?;+ }+ let now = t.missing();+ let mut lines: Vec<String> = made.iter().map(|m| format!(" {m}")).collect();+ lines.push(format!(" folder {} ({})", t.dir.display(), if t.dir.exists() { disk(&t.dir) } else { "-".into() }));+ if now.is_empty() {+ match t.probe() {+ Ok(p) => {+ let gb = |k: &str| p[k].as_f64().map(|v| format!("{v:.0} GB")).unwrap_or_else(|| "?".into());+ let gpu = match p["gpu"].as_str() {+ Some(g) => format!("{g}, {} (CUDA {})", gb("vram_gb"), p["cuda"].as_str().unwrap_or("?")),+ None => "none that PyTorch sees (no NVIDIA GPU, or its driver)".into(),+ };+ lines.push(format!(" backend PyTorch {}, upstream Kimodo {}", p["torch"].as_str().unwrap_or("?"), &raea_sys_kimodo::torch::KIMODO[..7]));+ lines.push(format!(" machine GPU: {gpu}; memory {}; {} CPU threads", gb("ram_gb"), p["threads"]));+ lines.push(format!(" runs on the denoiser: {}; the text encoder (a new line only): {}", p["motion"].as_str().unwrap_or("?"), p["text"].as_str().unwrap_or("?")));+ if p["text"] == "cpu" && p["ram_gb"].as_f64().is_some_and(|r| r < 18.0) {+ lines.push(format!(" warning a new line's encoder needs about 18 GB of memory on the CPU, and this machine has {}: lines already read still work", gb("ram_gb")));+ }+ }+ Err(e) => lines.push(format!(" backend the environment didn't answer: {e}")),+ }+ } else {+ lines.push(format!(" missing the {}: raea setup motion makes it (needs uv: https://docs.astral.sh/uv)", now.join(", the ")));+ }+ let head = match (check, now.is_empty()) {+ (true, true) => "CHECKED raea motion's PyTorch environment",+ (true, false) => "CHECKED raea motion's PyTorch environment (not set up)",+ _ => "APPLIED raea motion's PyTorch environment ready",+ };+ Ok(format!("{head}\n{}", lines.join("\n")))+}diff --git a/docs/character.feature b/docs/character.featureindex 45825602..67ded6a4 100644--- a/docs/character.feature+++ b/docs/character.feature@@ -314,6 +314,24 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generatedtoleranceAnd its cost is a one-off download and seconds a line+ Scenario: CH15d. Kimodo on every machine raea ships to: MLX on a Mac, PyTorch elsewhere+ # Shane, 11-17: `raea motion` picks its backend by the machine, so it is part of the system, not a Mac feature.+ # On Linux and Windows it runs upstream Kimodo (nv-tlabs/kimodo at e1c219c, the commit the MLX port was checked+ # against) on PyTorch, in an environment `raea setup motion [--check]` makes in raea's models folder+ # (kimodo-torch): Python 3.11 by uv, PyTorch as uv picks it for the machine's driver, upstream's own pins for the+ # rest; then the same Kimodo-SOMA-RP-v1 checkpoint, LLM2Vec's two adapters, and Llama 3 8B Instruct in bf16 from+ # NousResearch's ungated copy, whose four weight files have Meta's SHA-256 (read with the account's access, 11-17)+ # and are checked against it. The runner (systems/kimodo/torch/run.py, kept in the binary) calls Kimodo as its+ # generate script does (post_processing=False) and hands back the sampler's features; decode.rs makes the clip,+ # so both backends write one file. The denoiser runs on CUDA with an NVIDIA GPU, else the CPU; the text encoder+ # beside it on a GPU of 18 GB or more, else the CPU (about 18 GB of memory, refused below 17). 11-17: the Rust+ # half checked on MLX's own features through a stand-in runner (every field of the clip equal to MLX's but+ # its source; fromkimodo.ts keeps both), and the code checked for Linux and Windows. Not yet run on a machine:+ # the CUDA box's link fell to 1.5 MB/s mid-install, so the environment, the weights and a clip there are open.+ Then `raea motion` makes a clip on Linux and Windows with the same line and seed options as on a Mac, after+ `raea setup motion`, and says what is missing and that command when it isn't set up+ And the clip is the file fromkimodo.ts reads, in the format the MLX path writes+Scenario: CH16. Staging: a performance is a list of steps# Built on the old rig: matching.ts `perform(lib, {at, facing, steps})` with walk, face, wait; course.ts;# the take (docs/hands.feature). This is the one vocabulary for all of them.diff --git a/docs/first-person.feature b/docs/first-person.featurenew file mode 100644index 00000000..94efe21c--- /dev/null+++ b/docs/first-person.feature@@ -0,0 +1,131 @@+Feature: First person: his own body's hands, what they do with the world, and cutscenes, at AA quality+ Set by the user 2026-11-17, on the Gambit trailer's previz: "the ones in the previz look hella broken we will for+ sure want super relaistic hands and fps system for procedural hand animaitons + whatver e can do in kimodo. or+ sequences liek iopening a swere grate and climbging in, or steppign through a drill hol in the wall, or pulling up+ a map to view etc", then: "we need like AA level quality hands and fps interaction and cutscene sytem id honeslty+ work on that before the trailer". So the trailer waits on this.++ What raea already has, and this builds on rather than redoes:+ - raea/character's hands (docs/hands.feature, HG0 to HG19): the arm's reach that leans, fingers closed on a thing's+ distance field in a grip chosen for its shape (graspThing), take and fetch (a thing taken from where the body+ stands, or walked up to first), interact/plan/hold (beats of reach, grab, lift, carry, put, throw), hand shapes+ from SOMA-X's prior, and HG14's measured bar (tools/hands-audit) that the hands are held to.+ - raea motion: Kimodo on MLX on this Mac (a PyTorch backend for other machines is being built), whole-body motion+ from words with keys (full-body poses, hand and foot targets, a root path).+ - Games: useInput and useGameState, a pure step per frame, played live by raea play.+ Where the code lives: in the Gambit project's components/fp/ while it is made (so no uncommitted file of this+ sits in sdk/character and holds up the character lane's landings), moved into raea/character as `raea/character/fp`+ once it passes FP7 and commits are agreed.++ What's missing: a first-person view of that body; the layers a first-person game puts on its hands; hands on the+ world's fixed things (a grate, a ladder, a door, a hole's rim) rather than things carried; and sequences that take+ the camera from play into a scripted move and back.++ What "AA" means here, as qualities to measure (the user's bar; no other game's code or art is used): hands that+ read as real hands in a close-up (skin, nails, creases, gloves that crease), that touch what they touch (no skin+ in a thing, pads on it), that never pop, that lag and settle as a body's do when the view turns, walks or fires,+ and moves into and out of scripted sequences with no seam a player sees.++ Rule: The rig++ Scenario: FP1. True first person: the camera is his body's eyes+ # A first-person body, not floating arms: the dressed body posed by its stance, a clip or the walk, its eyes at+ # the camera, its head turned the way the camera looks. Gambit's probe: components/trailer/fp-body.tsx.+ Given a body posed standing, sitting, kneeling or from a clip+ Then the camera is at its eyes' landmark within 1 mm and looks where its head faces+ And the head's motion reaches the camera stabilised: roll within 1 degree, and no shake above 4 Hz larger than+ 0.3 degrees (a person's eyes hold the world still as the head bobs)+ And no skin or cloth of his own is nearer the camera than its near plane, in any frame of FP7's set+ And his body casts its shadow and is seen when he looks down (feet, knees, chest)++ Scenario: FP2. His hands are framed+ # True first person at a film's lens puts the hands low or out of frame; a game's hands are framed. Hands are+ # pulled in toward the view's centre by the least that frames them, along the arm (shoulder and elbow follow),+ # never moved off what they hold.+ Then in every beat of FP7 that needs them the hands are within the frame's safe area+ And his sleeves and elbows never fill more than a quarter of the frame+ And a hand on a thing stays on it (FP5) while it is pulled in++ Scenario: FP3. The layers on the hands and the view, as functions of time+ # Frame-pure: each layer is read from the camera's path, the body's clip and the game's state, never integrated+ # frame by frame in a composition. A game feeds the same layer from useGameState.+ Then these are layers with a weight each, off at 0:+ | layer | what moves |+ | breath | chest, shoulders and the held thing rise and fall, 12 to 20 a minute by exertion |+ | idle | a slow drift of the hands and view, under 5 mm and 0.3 degrees |+ | sway | the hands lag the view's turn and settle (a critically damped spring on its path) |+ | bob | the view and hands follow the walk's foot contacts, not a sine |+ | kick | a shot's recoil back and up, and its recovery, by the weapon's weight |+ | tremor | the hands' shake under stress or cold, by a heart rate |+ And each is measured: its amplitude and frequency in a test, and a still frame of each is unchanged at weight 0++ Rule: Hands, AA++ Scenario: FP4. The surface holds up in a close-up+ # Owner: the character lane (HG18, a surface: skin, clothes, hair). Shown at 4K, hands filling the frame.+ Then the hand is SOMA's at full detail with nails, knuckle creases and skin with light under it+ And period gloves are garments on the hand's joints that crease at the knuckles and leave no skin through them+ And a sleeve's cuff covers the wrist through the arm's whole range, with no gap and no cuff inside the forearm+ And a men's civilian winter coat of 1917 Berlin exists for him (the probe tints the British jacket: a stand-in)++ Scenario: FP5. Contact, in first person+ Given every interaction in FP7, measured by tools/hands-audit's measures on the body's own skin+ Then no skin of the hand is in a thing beyond a pad's give (2 mm), none in the scene or his own body+ And every finger meant to hold has its pad on the thing+ And no joint's speed changes by more than 300 degrees a second in a frame, fingers included+ And no hand pops between beats: a goal that changes is blended by inertialization, not cut++ Rule: Interactions with the world++ Scenario: FP6. An interactable is data+ Then an interactable names:+ | field | what |+ | solid | its shape, as a distance field and a mesh |+ | guides | where hands go: bars, rungs, edges, handles, rims, each a raea/character guide |+ | parts | what moves: a lid that lifts and slides, a door on its hinge, a lever, with mass |+ | beats | approach, align, reach, grip, act (along a path or about an axis, with its weight), release |+ | camera | free look within limits, guided toward a point, or locked to the body |+ | body | optionally a whole-body move: Kimodo with keys taken from the guides and a traversal path |+ And running it gives, for any time, his pose, the camera and every part's place++ Scenario: FP7. The set, each in first person, in motion, passing FP1 to FP5+ Then these are made and shown:+ | id | what he does |+ | grate | lifts a sewer lid with a hook, slides it aside, sits on the rim, climbs down the rungs |+ | hole | steps through a hole drilled in a wall: a hand on the rim, ducks, one leg then the other |+ | map | takes a folded map from his coat, unfolds it and holds it up to read |+ | ledge | lights a cigarette with a match at an open window, then sits up on the ledge |+ | rifle | shoulders a bolt-action rifle, aims, fires, works the bolt, loads a charger clip |+ | door | opens a door by its handle and goes through |+ | lantern | picks up a lantern by its bail and carries it, lighting the way |+ And each passes FP1 to FP5, with the numbers printed++ Rule: Cutscenes++ Scenario: FP8. A cutscene is tracks of time+ Then a cutscene has cameras (shots, cuts, blends), actors (clips captured, from Kimodo or procedural, with+ their contacts held by IK), props (parts moving), and events (sounds, effects, the score's cues)+ And the same file plays in a game (raea play) and renders (a trailer's shot)++ Scenario: FP9. Into and out of play with no seam+ Then play goes into a cutscene by a camera blend from his eyes, or a match on motion, and comes back to his+ eyes where the cutscene leaves his body+ And his pose is inertialized at each seam (FP5's 300 degrees a second holds across it)+ And where the cutscene allows, the player keeps look within limits (an interactive cutscene)++ Scenario: FP10. A playable test level+ Then a Berlin courtyard (a manhole, a door, a window's ledge) and a cellar with a drilled hole are played live+ with keyboard and mouse at 60 frames a second on this Mac+ And FP7's moves are rendered from the same files as trailer shots++ Rule: Order, and who+ Scenario: FP11. The order+ Then:+ | step | what | who |+ | 1 | FP1 to FP3 on the probe (bakery counter, manhole, map) | the trailer overseer |+ | 2 | FP6's data and runner, and grate, hole and map from FP7 | the trailer overseer |+ | 3 | FP4, the surface, and the coat | the character lane |+ | 4 | FP5's measures on FP7 (tools/hands-audit in first person) | both |+ | 5 | FP8 and FP9 | the trailer overseer |+ | 6 | FP10, with the interiors and map lanes' sets | the trailer overseer |+ And the trailer resumes when FP7's set passes and Shane has watched it in motiondiff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.mdindex 8ee1ebf0..def379f1 100644--- a/docs/manual/reference/cli/index.md+++ b/docs/manual/reference/cli/index.md@@ -111,7 +111,7 @@ Generated media, physics bakes, clothes and motion for SOMA's body, Blender and| [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. || [`raea physics`](physics.md) | Make the bakes <Physics> and <Goo> play: rigid bodies, soft goo, and parts cut out of a .glb. || [`raea clothes`](clothes.md) | Clothes for SOMA's body from words: make sews a garment from a sewing pattern (GarmentCode, MIT), cut to SOMA's measurements and draped by raea's own cloth, as assets/clothes/NAME.json and its .glb; cover lays one on the skin by procedure; wear puts garments on a body. |-| [`raea motion`](motion.md) | Body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. |+| [`raea motion`](motion.md) | Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTorch on Linux and Windows: a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. || [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. || [`raea godot`](godot.md) | Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project. |diff --git a/docs/manual/reference/cli/motion.md b/docs/manual/reference/cli/motion.mdindex d1876636..ba1b2925 100644--- a/docs/manual/reference/cli/motion.md+++ b/docs/manual/reference/cli/motion.md@@ -1,18 +1,18 @@---title: "raea motion"-summary: "Body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads."+summary: "Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTorch on Linux and Windows: a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads."order: 105sources: ["engine/cli/src/cli.rs"]----Body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads.+Body motion made on this machine by Kimodo (NVIDIA), on MLX on a Mac and on PyTorch on Linux and Windows: a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads.<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->## Usage```sh-raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json] (body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads; the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters); a line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT)+raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json] (body motion made on this machine by Kimodo (NVIDIA): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. On a Mac it runs on MLX (Apple silicon's GPU): the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters). On Linux and Windows it runs upstream Kimodo on PyTorch, set up once by raea setup motion: on an NVIDIA GPU with CUDA (the text encoder, 16 GB in bf16, on the CPU unless the card has 18 GB or more), else on the CPU alone; reading a new line on the CPU takes about 18 GB of memory. A line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT, Kimodo's code Apache-2.0)```Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.@@ -24,7 +24,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b| `--frames` | `N` | The clip's length in frames at 30 a second, 2 to 600. Instead of `--seconds`. || `--keys` | `KEYS.json` | Kimodo constraints the motion must meet: full-body keyframes, a hand or foot at a place on a frame, a path for the hips. `bun sdk/body/tools/between.ts` writes them between two poses of the body library. || `--seconds` | `5` | The clip's length in seconds (5 unless said). |-| `--seed` | `1` | Which of the motions the line could be: another seed is another take of the same line. A seed here is not that seed on Kimodo's PyTorch code (the noise is drawn differently). |+| `--seed` | `1` | Which of the motions the line could be: another seed is another take of the same line. A seed on MLX is not that seed on PyTorch (the noise is drawn differently), so the same seed is a different take on a Mac and on Linux or Windows. || `--steps` | `100` | Denoising steps (Kimodo's 100). Fewer is faster and rougher. || `-o` | `CLIP.json` | Where the clip goes: `{fps, names, root, turns, contacts, ...}`, Kimodo's 77 SOMA joints as each one's turn in the world from the T-pose. Without it, the line's words name the file in the working folder. |@@ -43,3 +43,19 @@ raea motion "A person waves at the camera with their right hand" --keys stand.jsA clip takes about 8 seconds on an M5 Pro. `bun sdk/body/tools/makedo.ts` does the whole of it for a stage's lines:three seeds a line, each checked against the captures the body hands on to, and the one that does the most kept in theproject's made clips.++## Where it runs++On a Mac, Kimodo runs on MLX, on the GPU, with no Python. The first use fetches the motion model (1.1 GB), and the first+new line the text encoder (8.8 GB).++On Linux and Windows it runs upstream Kimodo (nv-tlabs/kimodo) on PyTorch. Run `raea setup motion` once first: it needs+[uv](https://docs.astral.sh/uv) on PATH, makes a Python environment in raea's models folder, and fetches the weights,+about 26 GB in all. With an NVIDIA GPU the motion runs on CUDA, and the text encoder (Llama 3 8B Instruct, 16 GB in+bf16) joins it on a GPU of 18 GB or more. On a smaller card the encoder runs on the CPU and needs about 18 GB of memory.+With no NVIDIA GPU everything runs on the CPU. `raea setup motion --check` says what is set up and where each part runs.++Both backends write the same clip file. A line's words are read once and kept, so the encoder loads once a line.++Licences: Kimodo's code is Apache-2.0 and its weights are under NVIDIA's Open Model License. The text encoder is Meta+Llama 3 8B Instruct (Meta Llama 3 Community License) with LLM2Vec's adapters (MIT).diff --git a/docs/manual/reference/cli/setup.md b/docs/manual/reference/cli/setup.mdindex e0ea34fb..c8520b71 100644--- a/docs/manual/reference/cli/setup.md+++ b/docs/manual/reference/cli/setup.md@@ -19,6 +19,7 @@ raea setup blender```shraea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install raea's add-on and the MCP add-on)+raea setup motion [--check] (what raea motion runs on, made where missing (--check only says): on a Mac the MLX models in raea's models folder (the motion model 1.1 GB, the text encoder 8.8 GB); on Linux and Windows, in raea's models folder's kimodo-torch, a Python 3.11 environment made by uv (which it needs on PATH: https://docs.astral.sh/uv) with PyTorch (its CUDA build where there is an NVIDIA driver, about 8 GB, else CPU only, about 2 GB) and upstream Kimodo (nv-tlabs/kimodo at e1c219c, Apache-2.0), then the weights: Kimodo-SOMA-RP-v1 (1.1 GB, NVIDIA Open Model License), LLM2Vec's two adapters (0.3 GB, MIT) and Meta Llama 3 8B Instruct in bf16 (16 GB, Meta Llama 3 Community License, from NousResearch's ungated copy, checked file by file against Meta's SHA-256); about 26 GB in all. It says what this machine has and where each network runs: the denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more, else the CPU)raea setup godot [--check] (download Godot 4.6.1 with GodotJS, its TypeScript bindings (MIT), into ~/.raea/tools/godot: JavaScriptCore on the Mac, QuickJS on Windows and Linux; raea's own build (the Mac's notarized), else GodotJS's, each checked against its pinned sha256)```diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 0ab75b9b..3ed05852 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -136,12 +136,13 @@ pub fn run(args: &[String]) -> R<String> {let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.tslet usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");- // body motion made on this Mac by Kimodo on MLX (docs/character.feature CH15c): apps/tools/src/motion.rs+ // body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):+ // apps/tools/src/motion.rs; `raea setup motion` is listed with the other setups, after blender'slet usage = format!("{usage}\n {} ({})", tools::motion::USAGE, tools::motion::ABOUT);// an agent's report of a bug in raea itself, to raea's server (engine/cli/src/bug.ts; Shane 11-16)let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");// a workspace's files and specs (docs/projects.feature), listed under render's usage like library- let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);+ let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));@@ -190,6 +191,11 @@ pub fn run(args: &[String]) -> R<String> {if args[0] == "doctor" {return skill::doctor(&args[1..]);}+ // `setup motion [--check]`: what `raea motion` runs on here, made or checked: MLX's models on a Mac, the PyTorch+ // environment and its weights elsewhere (apps/tools motion.rs)+ if args[0] == "setup" && args.get(1).map(String::as_str) == Some("motion") {+ return tools::motion::setup(&args[2..]);+ }// `setup blender|godot`, `blender ...` and `godot ...`: Blender and Godot scripted (SK11, apps/engines)if let Some(done) = raea_app_engines::cli(args) {return done;@@ -257,7 +263,7 @@ pub fn run(args: &[String]) -> R<String> {Some("song") => return tools::song::song(args),// `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for <Matchmove> (motion/track.rs)Some("track") => return motion::track::track(args),- // `motion "LINE" [--keys KEYS.json]`: body motion made on this Mac by Kimodo on MLX (apps/tools motion.rs, raea-sys-kimodo)+ // `motion "LINE" [--keys KEYS.json]`: body motion made by Kimodo, on MLX on a Mac, on PyTorch elsewhere (apps/tools motion.rs, raea-sys-kimodo)Some("motion") => return tools::motion::motion(args),// `gen …`: generation flows on made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, and ComfyUI workflows read// and written (raea-io-gen, through apps/tools generate.rs for the local models)diff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rsindex 90a7ca9c..7c1668af 100644--- a/engine/render/src/engine/spawn.rs+++ b/engine/render/src/engine/spawn.rs@@ -128,6 +128,9 @@ pub fn apply_rows(world: &mut World, dir: &Path, rows: &[Tup]) -> Result<bool, S}// a <BevyComponent> or <BevyResource> whose value a live frame changed (or a new one): set on its partplugins::apply_live_rows(world, &reflected)?;+ // a mesh spawned here with a shader over its surface: put on now that this frame's rows are in (scene3d's+ // shade_meshes), not only when a model came with it+ scene3d::shade_meshes(world)?;Ok(spawned)}diff --git a/runtime/scene3d/src/shaded.rs b/runtime/scene3d/src/shaded.rsindex 798ee5fb..ace336ca 100644--- a/runtime/scene3d/src/shaded.rs+++ b/runtime/scene3d/src/shaded.rs@@ -31,14 +31,26 @@ pub fn shade_rows(world: &mut World, inserted: &[Tup]) -> Result<(), String> {let ext = shader_ext::build(world, &v, plugins::image).map_err(|e| format!("SurfaceShader: {e}"))?;world.insert_resource(SceneShader(ext));}+ shade_meshes(world)?;+ pass_rows(world, inserted)?;+ compute_rows(world, inserted)+}++/// Each mesh row waiting for its shader (MeshShader) given it. A load runs it with the rest of shade_rows; apply_rows+/// runs it after a live frame's or a fed render's rows, so a shaded mesh that first appears after the load gets its+/// shader too. (It ran only when a model spawned, so a shaded part with no model beside it drew its bare standard+/// surface: gambit's gate set after a shot of plain meshes, its street in its own vertex colours, 11-17.)+pub fn shade_meshes(world: &mut World) -> Result<(), String> {let todo: Vec<Entity> = world.query_filtered::<Entity, With<MeshShader>>().iter(world).collect();+ if todo.is_empty() {+ return Ok(());+ }let mut made = Made::new();for e in todo {let Some(s) = world.entity_mut(e).take::<MeshShader>() else { continue };shader_ext::put(world, e, &s.spec, plugins::image, &mut made).map_err(|err| format!("mesh {}: shader: {err}", s.id))?;}- pass_rows(world, inserted)?;- compute_rows(world, inserted)+ Ok(())}/// Rows of `kind` in the order written (`kind`0 first).diff --git a/sdk/guides/craft/bevy/characters.md b/sdk/guides/craft/bevy/characters.mdindex 62ca1e16..ecc14544 100644--- a/sdk/guides/craft/bevy/characters.md+++ b/sdk/guides/craft/bevy/characters.md@@ -98,17 +98,28 @@ its hands, feet, gaze and seat on the scene's real things, said in the scene's c- `raea clothes wear assets/characters/dressed trousers tee --body assets/characters/NAME --head HEAD_DIR` writesa dressed body folder. Register that folder with `registerBody`, and give each garment's glb to `<Character>`as one of its `parts`.-- An act no capture holds (wave at the camera, shrug, look at a watch) is made from its words on this Mac with- `raea motion`, Kimodo on MLX (no cloud GPU):+- An act no capture holds (wave at the camera, shrug, look at a watch) is made from its words with `raea motion`:+ Kimodo, run on the machine itself (no cloud GPU). On a Mac it runs on MLX. On Linux and Windows it runs upstream+ Kimodo on PyTorch. Both write the same clip file.- `raea motion "A person waves at the camera" --keys stand.json --seconds 4 --seed 2 -o wave.clip.json` takes about- 8 seconds. Say who moves ("A person ..."), as Kimodo's captions do. `--keys` holds the body to poses or places- on given frames: `bun sdk/body/tools/between.ts` writes standing keys at both ends, so the act starts and ends- where the walks around it can join it.+ 8 seconds on a Mac. Say who moves ("A person ..."), as Kimodo's captions do. `--keys` holds the body to poses or+ places on given frames: `bun sdk/body/tools/between.ts` writes standing keys at both ends, so the act starts and+ ends where the walks around it can join it.- Each seed is another take, and a take can stand still through its line. `bun sdk/body/tools/makedo.ts SKELETONLIBDIR OUTDIR "wave at the camera" ...` makes a stage's `do` lines with three seeds each, and keeps the take- that passes the body's checks and moves most.- - The first use fetches the motion model (1.1 GB), and the first new line the text encoder (8.8 GB). A line's- words are read once and kept.+ that passes the body's checks and moves most. A seed is a different take on MLX and on PyTorch, because their+ noise is drawn differently.+ - On a Mac, the first use fetches the motion model (1.1 GB), and the first new line the text encoder (8.8 GB).+ - On Linux and Windows, run `raea setup motion` once first. It needs uv (https://docs.astral.sh/uv) on PATH. It+ makes a Python environment in raea's models folder with PyTorch and upstream Kimodo, then fetches the weights,+ about 26 GB in all. With an NVIDIA GPU the motion runs on CUDA. The text encoder (16 GB in bf16) joins it on a+ GPU of 18 GB or more; on a smaller card it runs on the CPU and needs about 18 GB of memory. Without an NVIDIA GPU+ everything runs on the CPU, which is slower. `raea setup motion --check` says what is set up and where each part+ runs.+ - A line's words are read once and kept, so the text encoder loads once a line.+ - Licences: Kimodo's code is Apache-2.0 and its weights are under NVIDIA's Open Model License (commercial use+ allowed). The text encoder is Meta Llama 3 8B Instruct (Meta Llama 3 Community License) with LLM2Vec's adapters+ (MIT).```tsxconst perf = perform(lib, { at: [0.4, 0, 2], facing: Math.PI / 2, frames: 450, steps: [diff --git a/skills b/skillsindex fbebab5f..135f399e 160000--- a/skills+++ b/skills@@ -1 +1 @@-Subproject commit fbebab5f640b17047731cac3eaa60a69dc19e37d+Subproject commit 135f399ecb8a59874a4875d61d43e7e81eb25e69diff --git a/systems/kimodo/src/decode.rs b/systems/kimodo/src/decode.rsindex c5a79095..7556b1b2 100644--- a/systems/kimodo/src/decode.rs+++ b/systems/kimodo/src/decode.rs@@ -82,8 +82,14 @@ fn round(v: f64, places: i32) -> f64 {/// The clip file sdk/body/tools/fromkimodo.ts reads: {fps, names (the 77), root (the hips' place a frame), turns (each/// joint's world turn from SOMA's T-pose, x y z w), contacts, seed, steps, source, prompt}.pub fn clip_json(m: &Motion, sk: &Skeleton, seed: u64, steps: usize, prompt: &str, constrained: bool) -> serde_json::Value {+ clip_json_on(m, sk, seed, steps, prompt, constrained, "on this Mac (raea-sys-kimodo, MLX)")+}++/// clip_json, its source saying where it was made (`made_on`: "on this Mac (raea-sys-kimodo, MLX)", or PyTorch's+/// device), for one file whichever backend made the clip.+pub fn clip_json_on(m: &Motion, sk: &Skeleton, seed: u64, steps: usize, prompt: &str, constrained: bool, made_on: &str) -> serde_json::Value {let source = format!(- "Kimodo-SOMA-RP-v1 (nv-tlabs/kimodo), NVIDIA Open Model License, on this Mac (raea-sys-kimodo, MLX); {}",+ "Kimodo-SOMA-RP-v1 (nv-tlabs/kimodo), NVIDIA Open Model License, {made_on}; {}",match (prompt.trim().is_empty(), constrained) {(false, true) => format!("text: {prompt:?}, and constraints"),(false, false) => format!("text: {prompt:?}"),diff --git a/systems/kimodo/src/lib.rs b/systems/kimodo/src/lib.rsindex 00781649..763a70e4 100644--- a/systems/kimodo/src/lib.rs+++ b/systems/kimodo/src/lib.rs@@ -9,12 +9,14 @@//! is not here: clips are post_processing=False, and raea's own foot planting runs on them downstream.//!//! The skeleton, the constraints, features to joints and the clip file are plain Rust and build everywhere; the-//! networks only on macOS.+//! networks only on macOS. Elsewhere (Linux, Windows) torch.rs runs upstream Kimodo on PyTorch in an environment raea+//! makes, and decode.rs turns its features into the same clip.pub mod constraints;pub mod decode;pub mod skeleton;pub mod stats;+pub mod torch;#[cfg(target_os = "macos")]pub mod net;@@ -71,6 +73,20 @@ mod model {],};+ /// Each model's folder in the models folder, and whether every file it needs is there (`raea setup motion --check`).+ pub fn installed() -> [(&'static str, PathBuf, bool); 2] {+ [&MOTION, &TEXT].map(|s| {+ let d = raea_sys_ml::models::root().join(s.name);+ let all = s.files.iter().all(|f| d.join(f.2).exists());+ (s.name, d, all)+ })+ }++ /// Both models fetched where missing (`raea setup motion`): the motion model, then the text encoder.+ pub fn fetch_all(progress: &mut dyn FnMut(&str, u64)) -> Result<[PathBuf; 2]> {+ Ok([ensure(&MOTION, progress)?, ensure(&TEXT, progress)?])+ }+/// What a clip is made from.pub struct Ask<'a> {pub line: &'a str,diff --git a/systems/kimodo/src/torch.rs b/systems/kimodo/src/torch.rsnew file mode 100644index 00000000..bb014363--- /dev/null+++ b/systems/kimodo/src/torch.rs@@ -0,0 +1,225 @@+//! Kimodo on PyTorch, for the machines MLX doesn't run on (Linux and Windows): upstream nv-tlabs/kimodo at the commit+//! the MLX port was checked against, in a Python environment raea makes in its models folder (`raea setup motion`),+//! with the same Kimodo-SOMA-RP-v1 checkpoint and LLM2Vec on Llama 3 8B Instruct (in bf16 here, 8 bits on MLX). The+//! runner (torch/run.py, kept in this binary) hands back the sampler's features, and decode.rs turns them into the+//! clip the MLX path writes, so the two backends write one file. Where the networks run is the runner's call: the+//! denoiser on CUDA when there is an NVIDIA GPU, else the CPU; the text encoder beside it on a GPU of 18 GB or more,+//! else the CPU.+//!+//! Plain Rust (it runs a program), so it builds everywhere; `raea motion` uses it where the networks aren't on MLX.++use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++use anyhow::{Context, Result, bail};++/// upstream Kimodo, at the commit the MLX port was checked against (tests.rs)+pub const KIMODO: &str = "e1c219c99b4b94ba48be1fb6a1cbc64ecee4c954";+/// what the environment's Python runs: written beside the environment before each use, so it is always this binary's+pub const RUNNER: &str = include_str!("../torch/run.py");+/// The environment's packages: what generation imports, at upstream's own pins (docker_requirements.txt at KIMODO,+/// compiled by uv; the cloud runner installed that list on 11-15), and Kimodo at KIMODO with what it brings. PyTorch is+/// left to uv's pick for the machine (--torch-backend auto: its CUDA build for the NVIDIA driver there, else CPU only),+/// as upstream leaves it to its container. Not yet installed by `raea setup motion` on a machine (11-17: the CUDA box's+/// link fell to 1.5 MB/s mid-install), so this list is untested as a whole.+pub const PACKAGES: &[&str] = &[+ "torch>=2.6,<3",+ "transformers==5.1.0",+ "peft==0.18.1",+ "huggingface-hub==1.6.0",+ "safetensors==0.7.0",+ "tokenizers==0.22.2",+ "numpy==1.26.4",+ "scipy==1.15.3",+ "hydra-core==1.3.2",+ "omegaconf==2.3.0",+ "einops==0.8.2",+ "kimodo @ git+https://github.com/nv-tlabs/kimodo@e1c219c99b4b94ba48be1fb6a1cbc64ecee4c954",+];++/// A file the environment needs, and what it is (for saying what's missing).+const NEEDS: &[(&str, &str)] = &[+ ("checkpoints/Kimodo-SOMA-RP-v1/model.safetensors", "the motion model"),+ ("checkpoints/Kimodo-SOMA-RP-v1/config.yaml", "the motion model"),+ ("checkpoints/Kimodo-SOMA-RP-v1/stats/motion/body/std.npy", "the motion model"),+ ("text/McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp/adapter_model.safetensors", "the text encoder"),+ ("text/McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp-supervised/adapter_model.safetensors", "the text encoder"),+ ("text/meta-llama/Meta-Llama-3-8B-Instruct/.sha256-checked", "the text encoder"),+];++/// Kimodo's PyTorch environment in a folder (raea's models folder's kimodo-torch).+pub struct Torch {+ pub dir: PathBuf,+}++/// One clip asked of PyTorch.+pub struct Job<'a> {+ pub line: &'a str,+ pub frames: usize,+ pub seed: u64,+ pub steps: usize,+ /// a Kimodo constraints file (keyframes, end effectors, a root path), or none+ pub keys: Option<&'a Path>,+ pub cfg: (f32, f32),+}++pub struct Made {+ /// frames x 369, normalised, as the sampler leaves them (decode.rs reads them)+ pub features: Vec<f32>,+ /// the runner's account: the line as Kimodo read it, where each network ran, the seconds, PyTorch's own root+ pub info: serde_json::Value,+}++impl Torch {+ pub fn at(dir: PathBuf) -> Self {+ Torch { dir }+ }++ pub fn venv(&self) -> PathBuf {+ self.dir.join("venv")+ }++ pub fn python(&self) -> PathBuf {+ if cfg!(windows) { self.venv().join("Scripts").join("python.exe") } else { self.venv().join("bin").join("python") }+ }++ /// the motion checkpoint's folder (its stats are decode.rs's too)+ pub fn checkpoint(&self) -> PathBuf {+ self.dir.join("checkpoints").join("Kimodo-SOMA-RP-v1")+ }++ /// the environment's record of what it was made from: a different list makes it again+ fn made_from(&self) -> PathBuf {+ self.venv().join("raea-packages.txt")+ }++ fn packages() -> String {+ PACKAGES.join("\n")+ }++ /// Whether the Python environment is made from this binary's package list.+ pub fn has_env(&self) -> bool {+ self.python().exists() && std::fs::read_to_string(self.made_from()).is_ok_and(|s| s == Self::packages())+ }++ /// What isn't there yet, by name: the Python environment, the motion model, the text encoder. Empty when it's all set up.+ pub fn missing(&self) -> Vec<&'static str> {+ let mut out = Vec::new();+ if !self.has_env() {+ out.push("Python environment");+ }+ for (f, what) in NEEDS {+ if !self.dir.join(f).exists() && !out.contains(what) {+ out.push(what);+ }+ }+ out+ }++ /// The runner, written beside the environment when it differs from this binary's.+ fn runner(&self) -> Result<PathBuf> {+ let p = self.dir.join("run.py");+ if std::fs::read_to_string(&p).ok().as_deref() != Some(RUNNER) {+ std::fs::create_dir_all(&self.dir)?;+ std::fs::write(&p, RUNNER).with_context(|| format!("can't write {}", p.display()))?;+ }+ Ok(p)+ }++ /// The Python environment (made by uv: Python 3.11, PyTorch with CUDA where there is an NVIDIA driver, Kimodo),+ /// then the weights; each step only when it's missing. `say` gets a line a step; what was made is returned.+ pub fn setup(&self, say: &mut dyn FnMut(&str)) -> Result<Vec<String>> {+ let mut made = Vec::new();+ std::fs::create_dir_all(&self.dir).with_context(|| format!("can't make {}", self.dir.display()))?;+ if !self.has_env() {+ let uv = Command::new("uv").arg("--version").output();+ if uv.as_ref().map_or(true, |o| !o.status.success()) {+ bail!(+ "raea setup motion makes its Python environment with uv, which isn't on PATH: install it (https://docs.astral.sh/uv; Linux and macOS: curl -LsSf https://astral.sh/uv/install.sh | sh; Windows: winget install astral-sh.uv), then run raea setup motion again"+ );+ }+ let venv = self.venv();+ let _ = std::fs::remove_dir_all(&venv);+ say(&format!("making the Python environment (Python 3.11 by uv) in {}", venv.display()));+ run(Command::new("uv").args(["venv", "--quiet", "--python", "3.11"]).arg(&venv), "uv venv")?;+ say("installing PyTorch (CUDA where there is an NVIDIA driver, else CPU only) and Kimodo: a few GB the first time");+ let mut pip = Command::new("uv");+ pip.args(["pip", "install", "--python"]).arg(self.python()).args(["--torch-backend", "auto"]).args(PACKAGES);+ // Kimodo's own post-processing (a C++ extension built with CMake) isn't used: clips are post_processing=False+ pip.env("SKIP_MOTION_CORRECTION_IN_SETUP", "1");+ if let Err(e) = run(&mut pip, "uv pip install") {+ let _ = std::fs::remove_dir_all(&venv);+ return Err(e);+ }+ std::fs::write(self.made_from(), Self::packages())?;+ made.push(format!("made the Python environment (Python 3.11, PyTorch, Kimodo at {}): {}", &KIMODO[..7], venv.display()));+ }+ if self.missing().iter().any(|m| *m != "Python environment") {+ say("fetching the weights: Kimodo-SOMA-RP-v1 (1.1 GB), LLM2Vec's adapters (0.3 GB) and Llama 3 8B Instruct in bf16 (16 GB)");+ let runner = self.runner()?;+ run(Command::new(self.python()).arg("-I").arg(&runner).arg("fetch").arg(&self.dir), "fetching the weights")?;+ made.push(format!("fetched the weights: {}", self.dir.display()));+ }+ Ok(made)+ }++ /// What this machine has and where each network would run (the runner's probe: torch, cuda, gpu, vram_gb, ram_gb,+ /// motion, text, threads).+ pub fn probe(&self) -> Result<serde_json::Value> {+ let runner = self.runner()?;+ let o = Command::new(self.python()).arg("-I").arg(&runner).arg("probe").arg(&self.dir).stderr(Stdio::inherit()).output().context("can't run the environment's Python")?;+ if !o.status.success() {+ bail!("the environment's probe failed ({})", o.status);+ }+ last_json(&o.stdout)+ }++ /// One clip's features from PyTorch. The runner's progress goes to stderr as it comes.+ pub fn make(&self, job: &Job) -> Result<Made> {+ let runner = self.runner()?;+ let tmp = std::env::temp_dir().join(format!("raea-motion-{}", std::process::id()));+ std::fs::create_dir_all(&tmp)?;+ let (ask, out) = (tmp.join("ask.json"), tmp.join("features.f32"));+ let keys = job.keys.map(|k| std::fs::canonicalize(k).unwrap_or_else(|_| k.to_path_buf()));+ let a = serde_json::json!({"line": job.line, "frames": job.frames, "seed": job.seed, "steps": job.steps, "keys": keys, "cfg": [job.cfg.0, job.cfg.1]});+ std::fs::write(&ask, a.to_string())?;+ let o = Command::new(self.python()).arg("-I").arg(&runner).arg("make").arg(&self.dir).arg(&ask).arg(&out).stderr(Stdio::inherit()).output().context("can't run the environment's Python");+ let read = std::fs::read(&out);+ let _ = std::fs::remove_dir_all(&tmp);+ let o = o?;+ if !o.status.success() {+ bail!("Kimodo on PyTorch failed ({}); what it said is above", o.status);+ }+ let b = read.context("Kimodo on PyTorch wrote no features")?;+ let features: Vec<f32> = b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();+ if features.len() != job.frames * crate::decode::DIM {+ bail!("Kimodo on PyTorch gave {} numbers, not {} frames of {}", features.len(), job.frames, crate::decode::DIM);+ }+ Ok(Made { features, info: last_json(&o.stdout)? })+ }+}++/// A program run with its output going to the person as it comes; an error names it.+fn run(c: &mut Command, what: &str) -> Result<()> {+ let s = c.stdin(Stdio::null()).status().with_context(|| format!("can't run {what}"))?;+ if !s.success() {+ bail!("{what} failed ({s}); what it said is above");+ }+ Ok(())+}++/// the last line of a program's output that is a JSON object+fn last_json(out: &[u8]) -> Result<serde_json::Value> {+ String::from_utf8_lossy(out).lines().rev().find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok().filter(|v| v.is_object())).context("the runner's answer had no JSON line")+}++/// The largest distance, in metres, between PyTorch's own decoded root and decode.rs's, frame by frame: a check that+/// the features were read as Kimodo wrote them.+pub fn root_gap(torch_root: &serde_json::Value, ours: &[[f32; 3]]) -> Option<f64> {+ let r = torch_root.as_array()?;+ (r.len() == ours.len()).then_some(())?;+ r.iter().zip(ours).map(|(a, b)| {+ let a: Vec<f64> = a.as_array().map(|v| v.iter().filter_map(serde_json::Value::as_f64).collect()).unwrap_or_default();+ (0..3).map(|i| (a.get(i).copied().unwrap_or(f64::NAN) - b[i] as f64).powi(2)).sum::<f64>().sqrt()+ }).try_fold(0.0f64, |m, d| d.is_finite().then_some(m.max(d)))+}diff --git a/systems/kimodo/torch/run.py b/systems/kimodo/torch/run.pynew file mode 100644index 00000000..235f9e62--- /dev/null+++ b/systems/kimodo/torch/run.py@@ -0,0 +1,244 @@+"""raea motion on PyTorch, for the machines MLX doesn't run on (Linux, Windows): upstream Kimodo (nv-tlabs/kimodo, code+Apache-2.0) in the Python environment `raea setup motion` makes in raea's models folder (kimodo-torch), run by raea+(systems/kimodo/src/torch.rs), which keeps this file in its binary and writes it beside the environment before each use.++ python -I run.py fetch DIR the weights into DIR, each repository at a fixed revision: Kimodo-SOMA-RP-v1+ (NVIDIA Open Model License), LLM2Vec's two adapters (MIT) and Meta Llama 3 8B+ Instruct in bf16 (Meta Llama 3 Community License) from NousResearch's ungated+ copy, whose four weight files are checked by SHA-256 against Meta's own+ python -I run.py probe DIR what this machine has and where each network would run, as one JSON line+ python -I run.py make DIR ASK.json OUT one clip: ASK is {line, frames, seed, steps, keys (a constraints file or null),+ cfg}; OUT gets the denoised features (frames x 369 float32, normalised, as+ Kimodo's sampler leaves them), which raea decodes into the same clip the MLX+ path writes; stdout's last line is JSON about the run++The networks are upstream's own, called as its generate script calls them (post_processing=False, as on MLX). Where+they run: the denoiser on CUDA when there is an NVIDIA GPU, else on the CPU; LLM2Vec (16 GB in bf16) beside it on a GPU+of 18 GB or more, else on the CPU. RAEA_MOTION_DEVICE=cpu|cuda and RAEA_MOTION_TEXT_DEVICE=cpu|cuda say otherwise. A+line's 4096 numbers are kept in DIR/lines once read, so the encoder loads once a line, as on MLX.+"""+import hashlib+import json+import os+import pathlib+import sys+import time++MODEL = "Kimodo-SOMA-RP-v1"+MNTP = "McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp"+SUPERVISED = "McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp-supervised"+# the adapters name Meta's repository as their base; its bytes are fetched from an ungated copy into a folder of that+# name under DIR/text, which is where the encoder is loaded from (relative to it: see Text.load)+BASE = "meta-llama/Meta-Llama-3-8B-Instruct"+SHARDS = [f"model-0000{i}-of-00004.safetensors" for i in range(1, 5)]+# (repository, revision, files, folder under DIR)+FILES = [+ ("nvidia/Kimodo-SOMA-RP-v1", "defbe1f34f5fd031eb0ccfe19f3f92a9880c287b",+ ["config.yaml", "model.safetensors", "LICENSE"] + [f"stats/motion/{p}/{s}.npy" for p in ("global_root", "local_root", "body") for s in ("mean", "std")],+ f"checkpoints/{MODEL}"),+ (MNTP, "31474e395ada192e8ed1586db6be79fb3b70c9c0",+ ["adapter_config.json", "adapter_model.safetensors", "config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"],+ f"text/{MNTP}"),+ (SUPERVISED, "baa8ebf04a1c2500e61288e7dad65e8ae42601a7", ["adapter_config.json", "adapter_model.safetensors"], f"text/{SUPERVISED}"),+ ("NousResearch/Meta-Llama-3-8B-Instruct", "53346005fb0ef11d3b6a83b12c895cca40156b6c",+ ["config.json", "generation_config.json", "model.safetensors.index.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "LICENSE", "USE_POLICY.md"] + SHARDS,+ f"text/{BASE}"),+]+# meta-llama/Meta-Llama-3-8B-Instruct's own weight files (Hugging Face's LFS SHA-256, read 11-17), which the copy matches+META_SHA256 = {+ "model-00001-of-00004.safetensors": "d8cf9c4d0dd972e1a2131bfe656235ee98221679711a3beef6d46dadf0f20b5c",+ "model-00002-of-00004.safetensors": "8d4782b4a69ef03845159ce1a15e272aadaaf134dc138d68f616098e8531729c",+ "model-00003-of-00004.safetensors": "3acdd690e65c24f42a24581b8467af98bd3ca357444580f8012aacd2bd607921",+ "model-00004-of-00004.safetensors": "67e9ad31c8c32abf3a55ee7fc7217b3ecb35fd3c74d98a5bd233e0e4d6964f46",+}+TEXT_DIM = 4096+# the encoder's name in a kept line's key: bf16 here, so not the MLX path's 8-bit numbers+ENCODER = "llm2vec-llama3-8b-instruct-bf16"+# a GPU this big holds LLM2Vec in bf16 beside the denoiser (about 17 GB together)+TEXT_ON_GPU_BYTES = 18 << 30+# memory LLM2Vec needs on the CPU in bf16: its 16 GB and Python's own (a little under 18 GB, so a machine sold as 18 GB passes)+TEXT_ON_CPU_BYTES = 17 << 30+++def say(*a):+ print("raea motion:", *a, file=sys.stderr, flush=True)+++def sha256(p):+ h = hashlib.sha256()+ with open(p, "rb") as f:+ for b in iter(lambda: f.read(1 << 24), b""):+ h.update(b)+ return h.hexdigest()+++def fetch(d):+ from huggingface_hub import hf_hub_download++ for repo, rev, files, sub in FILES:+ dest = d / sub+ for f in files:+ if (dest / f).exists():+ continue+ say(f"fetching {repo} {f}")+ hf_hub_download(repo, f, revision=rev, local_dir=str(dest))+ base = d / "text" / BASE+ checked = base / ".sha256-checked"+ if not checked.exists():+ for f, want in META_SHA256.items():+ say(f"checking {f} against Meta's SHA-256")+ got = sha256(base / f)+ if got != want:+ (base / f).unlink()+ raise SystemExit(f"{base / f}: SHA-256 {got} isn't Meta's {want}; removed, so the next setup fetches it again")+ checked.write_text(json.dumps(META_SHA256, indent=1))+ print(json.dumps({"fetched": str(d)}))+++def ram_bytes():+ try:+ return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")+ except (AttributeError, ValueError, OSError):+ pass+ try:+ import ctypes++ class Status(ctypes.Structure):+ _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong)] + [(n, ctypes.c_ulonglong) for n in ("a", "b", "c", "d", "e", "f")]++ s = Status()+ s.dwLength = ctypes.sizeof(Status)+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(s))+ return int(s.ullTotalPhys)+ except Exception:+ return None+++def plan():+ import torch++ cuda = torch.cuda.is_available()+ p = {"torch": torch.__version__, "cuda": torch.version.cuda if cuda else None, "gpu": None, "vram_gb": None, "ram_gb": None}+ if cuda:+ g = torch.cuda.get_device_properties(0)+ p["gpu"], p["vram_gb"] = g.name, round(g.total_memory / 2**30, 1)+ r = ram_bytes()+ p["ram_gb"] = round(r / 2**30, 1) if r else None+ motion = os.environ.get("RAEA_MOTION_DEVICE") or ("cuda" if cuda else "cpu")+ text = os.environ.get("RAEA_MOTION_TEXT_DEVICE") or ("cuda" if motion == "cuda" and cuda and torch.cuda.get_device_properties(0).total_memory >= TEXT_ON_GPU_BYTES else "cpu")+ p["motion"], p["text"] = motion, text+ p["threads"] = torch.get_num_threads()+ return p+++class Text:+ """Kimodo's text encoder, as Kimodo calls it: LLM2Vec (on Llama 3 8B Instruct, bf16), loaded only when a line hasn't+ been read before; a line's 4096 numbers are kept in DIR/lines, and an empty line is zeros (Kimodo zeroes it)."""++ def __init__(self, d, device):+ self.d, self.device, self.enc, self.read, self.load_s = d, device, None, [], 0.0++ def to(self, *a, **k):+ return self++ def eval(self):+ return self++ def kept(self, line):+ return self.d / "lines" / (hashlib.sha256(f"{ENCODER}\n{line}".encode()).hexdigest()[:16] + ".f32")++ def load(self):+ from kimodo.model.llm2vec import LLM2VecEncoder++ ram = ram_bytes()+ if self.device == "cpu" and ram and ram < TEXT_ON_CPU_BYTES:+ raise SystemExit(f"reading a new line runs the text encoder (Llama 3 8B Instruct, 16 GB in bf16) on the CPU, which needs about 18 GB of memory, and this machine has {ram / 2**30:.0f} GB: "+ "a line already read still works, and a GPU of 18 GB or more holds the encoder instead")+ t = self.d / "text"+ # the adapters' base is named by its repository; from DIR/text that name is the local folder of its bytes, so+ # nothing is fetched (HF_HUB_OFFLINE) and the gated repository is never asked for+ os.chdir(t)+ os.environ["TEXT_ENCODERS_DIR"] = str(t)+ say(f"loading the text encoder (LLM2Vec on Llama 3 8B Instruct, 16 GB in bf16) on {self.device}")+ t0 = time.time()+ self.enc = LLM2VecEncoder(base_model_name_or_path=MNTP, peft_model_name_or_path=SUPERVISED, dtype="bfloat16", llm_dim=TEXT_DIM, device=self.device)+ self.load_s = round(time.time() - t0, 2)+ say(f"text encoder loaded in {self.load_s:.1f} s")++ def one(self, line):+ import numpy as np+ import torch++ if not line.strip():+ return torch.zeros(TEXT_DIM)+ p = self.kept(line)+ if p.exists() and p.stat().st_size == 4 * TEXT_DIM:+ return torch.from_numpy(np.fromfile(p, dtype="<f4").copy())+ if self.enc is None:+ self.load()+ t0 = time.time()+ e, _ = self.enc([line])+ e = e.reshape(-1, TEXT_DIM)[0].float().cpu()+ self.read.append(round(time.time() - t0, 2))+ p.parent.mkdir(parents=True, exist_ok=True)+ e.numpy().astype("<f4").tofile(p)+ return e++ def __call__(self, texts):+ import torch++ texts = [texts] if isinstance(texts, str) else list(texts)+ return torch.stack([self.one(t) for t in texts])[:, None], [1] * len(texts)+++def make(d, ask_path, out_path):+ ask = json.loads(pathlib.Path(ask_path).read_text())+ os.environ["HF_HUB_OFFLINE"] = "1"+ os.environ["TRANSFORMERS_OFFLINE"] = "1"+ os.environ["CHECKPOINT_DIR"] = str(d / "checkpoints")+ t0 = time.time()+ import torch+ from kimodo.constraints import load_constraints_lst+ from kimodo.model.load_model import load_model+ from kimodo.sanitize import sanitize_texts++ p = plan()+ clean = sanitize_texts([ask["line"]])[0]+ text = Text(d, p["text"])+ model = load_model(MODEL, device=p["motion"], text_encoder=text)+ cons = load_constraints_lst(str(pathlib.Path(ask["keys"]).resolve()), model.skeleton) if ask.get("keys") else None+ load_s = time.time() - t0+ # the features the sampler leaves, taken where Kimodo decodes them+ grab = {}+ inverse = model.motion_rep.inverse++ def keep(motion, *a, **k):+ grab["features"] = motion+ return inverse(motion, *a, **k)++ model.motion_rep.inverse = keep+ torch.manual_seed(int(ask["seed"]))+ t1 = time.time()+ out = model([ask["line"]], int(ask["frames"]), num_denoising_steps=int(ask["steps"]), constraint_lst=[cons] if cons else [],+ cfg_weight=[float(c) for c in ask.get("cfg", [2.0, 2.0])], num_samples=1, post_processing=False, progress_bar=lambda x, **k: x)+ gen_s = time.time() - t1 - sum(text.read) - text.load_s+ f = grab["features"].reshape(-1, int(ask["frames"]), grab["features"].shape[-1])[0].float().cpu().numpy()+ if f.shape[1] != 369:+ raise SystemExit(f"Kimodo's features are {f.shape[1]} a frame, not 369")+ f.astype("<f4").tofile(out_path)+ pj = out["posed_joints"]+ root = pj.reshape(-1, *pj.shape[-3:])[0, :, 0].float().cpu().tolist()+ print(json.dumps({"line": clean, "motion": p["motion"], "text": p["text"], "gpu": p["gpu"], "torch": p["torch"], "load_s": round(load_s, 2),+ "text_load_s": text.load_s, "read_s": sum(text.read), "gen_s": round(gen_s, 2), "frames": f.shape[0], "root": [[round(v, 5) for v in r] for r in root]}))+++if __name__ == "__main__":+ verb, d = sys.argv[1], pathlib.Path(sys.argv[2]).resolve()+ if verb == "fetch":+ fetch(d)+ elif verb == "probe":+ print(json.dumps(plan()))+ elif verb == "make":+ make(d, sys.argv[3], sys.argv[4])+ else:+ raise SystemExit(f"run.py fetch|probe|make DIR ...: no verb {verb!r}")