Skip to content

armgit / raea

Public Imported from GitHub
0

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.

CH15c: Kimodo on this Mac. raea-sys-kimodo runs Kimodo-SOMA-RP-v1 and its LLM2Vec text encoder (Llama 3 8B Instruct in 8 bits) on MLX in Rust, with no Python and no cloud GPU; `raea motion "LINE" [--keys KEYS.json]` writes the clip sdk/body/tools/fromkimodo.ts reads

shinyobjectzb5425278b3f2
diff --git a/Cargo.lock b/Cargo.lock
index 1e6eee57..9d2ec048 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13975,6 +13975,7 @@ dependencies = [
"raea-io-media",
"raea-runtime-bundle",
"raea-runtime-export",
+ "raea-sys-kimodo",
"serde_json",
]
@@ -15866,6 +15867,18 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "raea-sys-kimodo"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "mlx-rs",
+ "raea-sys-ml",
+ "raea-sys-mlx",
+ "serde_json",
+ "tokenizers",
+]
+
[[package]]
name = "raea-sys-layers"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 8279b020..9b35f5a1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -81,6 +81,7 @@ members = [
"systems/mix",
"systems/ml",
"systems/mlx",
+ "systems/kimodo",
"systems/speech",
"systems/layout",
"systems/vision",
diff --git a/LICENSES/dyn-clone-1.0.20/LICENSE-APACHE b/LICENSES/dyn-clone-1.0.20/LICENSE-APACHE
deleted file mode 100644
index 1b5ec8b7..00000000
--- a/LICENSES/dyn-clone-1.0.20/LICENSE-APACHE
+++ /dev/null
@@ -1,176 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
diff --git a/LICENSES/dyn-clone-1.0.20/LICENSE-MIT b/LICENSES/dyn-clone-1.0.20/LICENSE-MIT
deleted file mode 100644
index 31aa7938..00000000
--- a/LICENSES/dyn-clone-1.0.20/LICENSE-MIT
+++ /dev/null
@@ -1,23 +0,0 @@
-Permission is hereby granted, free of charge, to any
-person obtaining a copy of this software and associated
-documentation files (the "Software"), to deal in the
-Software without restriction, including without
-limitation the rights to use, copy, modify, merge,
-publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software
-is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice
-shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
-ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
-TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
-IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
diff --git a/NOTICE b/NOTICE
index 8368c222..8dc43e59 100644
--- a/NOTICE
+++ b/NOTICE
@@ -175,7 +175,6 @@ LICENSES/<crate>-<version>/.
deterministic-hash 1.0.2: MIT
disjoint-sets 0.4.2: MIT/Apache-2.0
dot_vox 5.2.0: MIT
- dyn-clone 1.0.20: MIT OR Apache-2.0
dyn-eq 0.1.3: MPL-2.0
dyn-hash 1.0.0: MIT OR Apache-2.0
earcut 0.4.5: ISC
diff --git a/apps/tools/Cargo.toml b/apps/tools/Cargo.toml
index 9b998b3b..edce548b 100644
--- a/apps/tools/Cargo.toml
+++ b/apps/tools/Cargo.toml
@@ -16,3 +16,7 @@ serde_json = "1"
# the verbs' flags read as a render reads its own
raea-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-sys-kimodo = { path = "../../systems/kimodo" }
diff --git a/apps/tools/src/lib.rs b/apps/tools/src/lib.rs
index 280caf4b..a8a18b64 100644
--- a/apps/tools/src/lib.rs
+++ b/apps/tools/src/lib.rs
@@ -4,6 +4,8 @@
//! 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)
+pub mod motion;
pub mod song;
pub mod sound;
pub mod splat;
diff --git a/apps/tools/src/motion.rs b/apps/tools/src/motion.rs
new file mode 100644
index 00000000..6c8d0b67
--- /dev/null
+++ b/apps/tools/src/motion.rs
@@ -0,0 +1,117 @@
+//! `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).
+
+use std::path::PathBuf;
+
+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";
+
+fn number(args: &[String], name: &str, default: f64) -> R<f64> {
+ match flag(args, name) {
+ None => Ok(default),
+ Some(v) => v.parse::<f64>().ok().filter(|n| n.is_finite() && *n >= 0.0).ok_or(format!("{name} takes a number, got `{v}`")),
+ }
+}
+
+fn line(args: &[String]) -> String {
+ const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
+ let mut out = Vec::new();
+ let mut i = 1;
+ while i < args.len() {
+ if WITH_VALUE.contains(&args[i].as_str()) {
+ i += 2;
+ continue;
+ }
+ if !args[i].starts_with("--") {
+ out.push(args[i].as_str());
+ }
+ i += 1;
+ }
+ out.join(" ")
+}
+
+/// what a call asks for, read from its words and flags
+struct Ask {
+ words: String,
+ keys: Option<String>,
+ constraints: Option<serde_json::Value>,
+ frames: usize,
+ seed: u64,
+ steps: usize,
+ out: Option<String>,
+}
+
+pub fn motion(args: &[String]) -> R<String> {
+ let words = line(args);
+ let keys = flag(args, "--keys");
+ if words.trim().is_empty() && keys.is_none() {
+ return Err(format!("{USAGE}\n ({ABOUT})"));
+ }
+ let frames = match flag(args, "--frames") {
+ Some(_) => number(args, "--frames", 150.0)? as usize,
+ None => (number(args, "--seconds", 5.0)? * 30.0).round() as usize,
+ };
+ if !(2..=600).contains(&frames) {
+ return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
+ }
+ let constraints = match &keys {
+ Some(p) => Some(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?),
+ None => None,
+ };
+ let (seed, steps) = (number(args, "--seed", 1.0)? as u64, (number(args, "--steps", 100.0)? as usize).max(2));
+ make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
+}
+
+#[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))
+}
+
+#[cfg(target_os = "macos")]
+fn make(ask: Ask) -> R<String> {
+ // float32 as checked against PyTorch: MLX's TF32 matmuls off, before the first one
+ if std::env::var_os("MLX_ENABLE_TF32").is_none() {
+ 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 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();
+ let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
+ let t1 = std::time::Instant::now();
+ 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() })
+ }));
+ 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)",
+ clean,
+ if ask.keys.is_some() { " with keys" } else { "" },
+ ask.frames,
+ ask.frames as f64 / 30.0,
+ ask.seed,
+ ask.steps,
+ out.display()
+ ))
+}
diff --git a/docs/character.feature b/docs/character.feature
index f932c8ff..0c7ed6ac 100644
--- a/docs/character.feature
+++ b/docs/character.feature
@@ -274,7 +274,7 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
# `mps` device), so the earlier line that it does not run on a Mac is untested, not true.
Then a stage `do` line gets a clip made from its words, checked, and kept in the project
- Scenario: CH15c. Kimodo on the user's own machine, in MLX (planned)
+ Scenario: CH15c. Kimodo on the user's own machine, in MLX
# The user, 11-15: "lets plan that if kimodo works well we port it mlx weights or go find some". Gated on
# an eval first: about ten lines (wave, point, shrug, clap, nod, bow, look at a watch, cross the arms,
# scratch the head, stretch), each with a check of its own (which hand rises, where the head turns) and a look
@@ -286,6 +286,25 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
# model (a small diffusion transformer): its weights converted and run in MLX, checked against the PyTorch
# motion for the same line, constraints, seed and noise. Before anything ships to users: the licences of
# converted weights (NVIDIA's Open Model License for Kimodo, Meta's Llama 3 licence for the encoder).
+ # 11-16. Done in Rust, no Python: raea-sys-kimodo runs Kimodo-SOMA-RP-v1's denoiser and LLM2Vec on MLX from
+ # the checkpoints' own files (nothing converted: mlx-community's 8-bit Llama 3 8B Instruct, McGill-NLP's two
+ # adapters run beside it unmerged), and `raea motion "LINE" [--keys KEYS.json]` writes the clip fromkimodo.ts
+ # reads. Against PyTorch: the denoiser within 2e-3; a whole 100-step generation from the same noise and text
+ # within 0.002 cm on every joint; constraints become the same conditions. The stated tolerance is the 8-bit
+ # encoder's: cosine 0.99993 to float32, which moves the joints 0.01 to 0.74 cm on average and 1.44 cm at
+ # worst over eight lines (4-bit moved them 8 cm and is not used). A seed's noise is not torch's, so a seed is
+ # not the cloud's motion for that seed; measured by what it does, the local wave falls in the cloud's three
+ # (a hand above the shoulder 54 to 67 of 120 frames against 48 to 59, the hips within 3 cm). Cost: the
+ # motion model 1.1 GB and the encoder 8.8 GB once, then 5 s to load and read a new line (a line's numbers
+ # are kept, so a line is read once) and about 8 s a 4 s clip on an M5 Pro, against the cloud's 130 s
+ # loading. The eval (sdk/body tools/doeval.ts, each line's check measured on the joints; clips by
+ # tools/makedo.ts, three seeds a line between standing keys): every clip passes the bar of the captures that
+ # end standing; the seed kept is the one whose upper body moves most (a do line fails by standing through
+ # it: one seed of three stood still through "scratch the head"), and the kept ten all do what they say
+ # (seed 1 alone 7 of 10, seed 2 8, seed 3 7). Film: sheet3d out/do-eval-v1.mp4, posted for the user's look
+ # (i-show-mwj21c0d-1). Open: that look; the user's word on shipping the downloads (Kimodo under NVIDIA's
+ # Open Model License; Meta Llama 3 under its Community License, fetched from mlx-community's ungated 8-bit
+ # copy; the adapters MIT); Kimodo's own post-processing (its C++ foot-skate clean-up) is not ported.
Given the eval's lines pass
Then a do line's clip is made on a Mac with no GPU in the cloud, matching the cloud's within a stated
tolerance
diff --git a/docs/manual/reference/cli/blender.md b/docs/manual/reference/cli/blender.md
index 26c33f6c..a32f1730 100644
--- a/docs/manual/reference/cli/blender.md
+++ b/docs/manual/reference/cli/blender.md
@@ -1,7 +1,7 @@
---
title: "raea blender"
summary: "Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth."
-order: 105
+order: 106
sources: ["apps/tools/src/blender.rs", "apps/engines/src/blender_ts.rs"]
---
diff --git a/docs/manual/reference/cli/godot.md b/docs/manual/reference/cli/godot.md
index 53407548..5d499a47 100644
--- a/docs/manual/reference/cli/godot.md
+++ b/docs/manual/reference/cli/godot.md
@@ -1,7 +1,7 @@
---
title: "raea godot"
summary: "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."
-order: 106
+order: 107
sources: ["apps/engines/src/godot.rs", "apps/engines/src/godot_run.rs"]
---
diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.md
index 043cdb94..f2e00bd3 100644
--- a/docs/manual/reference/cli/index.md
+++ b/docs/manual/reference/cli/index.md
@@ -104,13 +104,14 @@ Music read, foley and instruments made on this machine.
## Generate and 3D tools
-Generated media, physics bakes, clothes for SOMA's body, Blender and Godot.
+Generated media, physics bakes, clothes and motion for SOMA's body, Blender and Godot.
| Verb | What it does |
| --- | --- |
| [`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 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.md
new file mode 100644
index 00000000..d1876636
--- /dev/null
+++ b/docs/manual/reference/cli/motion.md
@@ -0,0 +1,45 @@
+---
+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."
+order: 105
+sources: ["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.
+
+<!-- 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)
+```
+
+Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
+
+## Flags
+
+| Flag | Takes | What it does |
+| --- | --- | --- |
+| `--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). |
+| `--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. |
+
+<!-- generated:end -->
+
+## Example
+
+A stage's `do` line made into a clip: the body stands at the start and the end, and the motion between comes from the
+words.
+
+```sh
+bun sdk/body/tools/between.ts skeleton.json LIBDIR aMale2_A1_Stand:0 aMale2_A1_Stand:0 stand.json 4 0,0 0
+raea motion "A person waves at the camera with their right hand" --keys stand.json --seconds 4 --seed 2 -o wave.clip.json
+```
+
+A 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 the
+project's made clips.
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 1fb8fe6a..e29d0e48 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -136,6 +136,8 @@ 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.ts
let 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] | 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
+ let usage = format!("{usage}\n {} ({})", tools::motion::USAGE, tools::motion::ABOUT);
// 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 (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
@@ -253,6 +255,8 @@ 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)
+ 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)
Some("gen") => return raea_app_tools::generate::generate(args),
diff --git a/systems/kimodo/Cargo.toml b/systems/kimodo/Cargo.toml
new file mode 100644
index 00000000..438111db
--- /dev/null
+++ b/systems/kimodo/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "raea-sys-kimodo"
+version = "0.1.0"
+edition = "2024"
+publish = false
+description = "Kimodo (nv-tlabs/kimodo) on raea's MLX facility: SOMA body motion from a line of text and constraints, made on this Mac"
+license = "FSL-1.1-ALv2"
+
+[dependencies]
+anyhow = "1"
+serde_json = "1"
+
+# the networks run on MLX, Apple silicon's: elsewhere the crate is its plain-Rust parts (the skeleton, the constraints,
+# features to joints, the clip file)
+[target.'cfg(target_os = "macos")'.dependencies]
+raea-sys-mlx = { path = "../mlx" }
+raea-sys-ml = { path = "../ml" }
+mlx-rs = "=0.34.0"
+tokenizers = { version = "0.23", default-features = false, features = ["onig"] }
diff --git a/systems/kimodo/src/constraints.rs b/systems/kimodo/src/constraints.rs
new file mode 100644
index 00000000..ae0ee5f5
--- /dev/null
+++ b/systems/kimodo/src/constraints.rs
@@ -0,0 +1,178 @@
+//! A Kimodo constraints file (full-body keyframes, hand and foot targets, a root path: what sdk/body/tools/between.ts
+//! writes) turned into the denoiser's conditions: the observed features (normalised) and which of them are given.
+//! kimodo/constraints.py with KimodoMotionRep.create_conditions; where two constraints give one number, the last wins.
+
+use std::collections::BTreeMap;
+
+use anyhow::{Context, Result, bail};
+use serde_json::Value;
+
+use crate::decode::{DIM, J};
+use crate::skeleton::{M3, Skeleton, fk, floats as nums};
+use crate::stats::Stats;
+
+/// Each of the frames' 369 numbers: what is asked (normalised) and whether it is asked (1) or free (0).
+pub struct Conditions {
+ pub obs: Vec<f32>,
+ pub mask: Vec<f32>,
+}
+
+fn axis_angle(a: [f32; 3]) -> M3 {
+ let angle = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt();
+ let (x, y, z) = (a[0] / (angle + 1e-6), a[1] / (angle + 1e-6), a[2] / (angle + 1e-6));
+ let k = [[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]];
+ let kk = crate::skeleton::mul(&k, &k);
+ let (s, c) = (angle.sin(), 1.0 - angle.cos());
+ let mut m = crate::skeleton::EYE;
+ for i in 0..3 {
+ for j in 0..3 {
+ m[i][j] += s * k[i][j] + c * kk[i][j];
+ }
+ }
+ m
+}
+
+fn end_effector(class: &str) -> Option<&'static [&'static str]> {
+ Some(match class {
+ "left-hand" => &["LeftHand"],
+ "right-hand" => &["RightHand"],
+ "left-foot" => &["LeftFoot"],
+ "right-foot" => &["RightFoot"],
+ _ => return None,
+ })
+}
+
+/// the joints whose places pin an end effector (the first is the one whose turn is pinned too)
+fn ee_places(base: &str) -> Result<&'static [&'static str]> {
+ Ok(match base {
+ "LeftFoot" => &["LeftFoot", "LeftToeBase"],
+ "RightFoot" => &["RightFoot", "RightToeBase"],
+ "LeftHand" => &["LeftHand", "LeftHandMiddleEnd"],
+ "RightHand" => &["RightHand", "RightHandMiddleEnd"],
+ "Hips" => &["Hips"],
+ _ => bail!("kimodo: no end effector {base}"),
+ })
+}
+
+pub fn conditions(saved: &Value, frames: usize, st: &Stats, sk: &Skeleton) -> Result<Conditions> {
+ let list = saved.as_array().context("kimodo: a constraints file is a list")?;
+ let idx: BTreeMap<&str, usize> = sk.names30.iter().enumerate().map(|(i, n)| (n.as_str(), i)).collect();
+ let [r_hip, l_hip] = sk.hips30;
+ // (frame, joint or 0) -> values, the last given winning
+ let mut smooth: BTreeMap<usize, [f32; 2]> = BTreeMap::new();
+ let mut root_y: BTreeMap<usize, f32> = BTreeMap::new();
+ let mut heading: BTreeMap<usize, [f32; 2]> = BTreeMap::new();
+ let mut rots: BTreeMap<(usize, usize), M3> = BTreeMap::new();
+ let mut places: BTreeMap<(usize, usize), [f32; 3]> = BTreeMap::new();
+ for el in list {
+ let fi: Vec<usize> = el["frame_indices"].as_array().context("kimodo: a constraint without frame_indices")?.iter().filter_map(|v| v.as_u64()).map(|v| v as usize).collect();
+ let kind = el["type"].as_str().unwrap_or("");
+ let given_smooth = |k: usize| -> Option<[f32; 2]> {
+ let s = nums(&el["smooth_root_2d"]);
+ let per = s.len() / fi.len().max(1);
+ (per >= 2).then(|| [s[k * per], s[k * per + 1]])
+ };
+ if kind == "root2d" {
+ let h = nums(&el["global_root_heading"]);
+ for (k, &f) in fi.iter().enumerate() {
+ if let Some(s) = given_smooth(k) {
+ smooth.insert(f, s);
+ }
+ if h.len() >= 2 * fi.len() {
+ heading.insert(f, [h[2 * k], h[2 * k + 1]]);
+ }
+ }
+ continue;
+ }
+ let aa = nums(&el["local_joints_rot"]);
+ let per = aa.len() / 3 / fi.len().max(1);
+ anyhow::ensure!(per == 30 || per == 77, "kimodo: local_joints_rot has {per} joints a frame, not 30 or 77");
+ let local: Vec<Vec<M3>> = (0..fi.len())
+ .map(|k| {
+ let all: Vec<M3> = (0..per).map(|j| axis_angle([aa[(k * per + j) * 3], aa[(k * per + j) * 3 + 1], aa[(k * per + j) * 3 + 2]])).collect();
+ if per == 77 { sk.slice30in77.iter().map(|&i| all[i]).collect() } else { all }
+ })
+ .collect();
+ let rp = nums(&el["root_positions"]);
+ let root: Vec<[f32; 3]> = rp.chunks_exact(3).take(fi.len()).map(|c| [c[0], c[1], c[2]]).collect();
+ let (g, pos) = fk(&local, &root, &sk.parents30, &sk.neutral30);
+ let (pj, rj): (Vec<usize>, Vec<usize>) = if kind == "fullbody" {
+ ((0..J).collect(), vec![])
+ } else {
+ let base: Vec<String> = match end_effector(kind) {
+ Some(b) => b.iter().map(|s| s.to_string()).collect(),
+ None => el["joint_names"].as_array().context("kimodo: an end-effector constraint without joint_names")?.iter().filter_map(|v| v.as_str().map(String::from)).collect(),
+ };
+ let mut pj = vec![];
+ let mut rj = vec![];
+ for b in &base {
+ let names = ee_places(b)?;
+ for n in names {
+ pj.push(*idx.get(n).with_context(|| format!("kimodo: no joint {n}"))?);
+ }
+ rj.push(idx[names[0]]);
+ }
+ (pj, rj)
+ };
+ for (k, &f) in fi.iter().enumerate() {
+ for &j in &pj {
+ places.insert((f, j), pos[k][j]);
+ }
+ for &j in &rj {
+ rots.insert((f, j), g[k][j]);
+ }
+ let d = [0, 1, 2].map(|c| pos[k][r_hip][c] - pos[k][l_hip][c]);
+ let ang = d[2].atan2(-d[0]);
+ smooth.insert(f, given_smooth(k).unwrap_or([pos[k][0][0], pos[k][0][2]]));
+ root_y.insert(f, pos[k][0][1]);
+ heading.insert(f, [ang.cos(), ang.sin()]);
+ }
+ }
+ let mut obs = vec![0.0f32; frames * DIM];
+ let mut mask = vec![0.0f32; frames * DIM];
+ fn put(obs: &mut [f32], mask: &mut [f32], frames: usize, f: usize, c: usize, v: f32) {
+ if f < frames {
+ obs[f * DIM + c] = v;
+ mask[f * DIM + c] = 1.0;
+ }
+ }
+ macro_rules! set {
+ ($f:expr, $c:expr, $v:expr) => {
+ put(&mut obs, &mut mask, frames, $f, $c, $v)
+ };
+ }
+ for (&f, s) in &smooth {
+ set!(f, 0, s[0]);
+ set!(f, 2, s[1]);
+ }
+ for (&f, &y) in &root_y {
+ set!(f, 1, y);
+ }
+ for (&f, h) in &heading {
+ set!(f, 3, h[0]);
+ set!(f, 4, h[1]);
+ }
+ for (&(f, j), r) in &rots {
+ for k in 0..3 {
+ set!(f, 95 + j * 6 + k, r[k][0]);
+ set!(f, 95 + j * 6 + 3 + k, r[k][1]);
+ }
+ }
+ for (&(f, j), p) in &places {
+ if f >= frames {
+ continue;
+ }
+ anyhow::ensure!(
+ mask[f * DIM] > 0.0 && mask[f * DIM + 2] > 0.0,
+ "kimodo: to pin joint places the smooth root must be pinned on those frames too (frame {f})"
+ );
+ let (rx, rz) = (obs[f * DIM], obs[f * DIM + 2]);
+ set!(f, 5 + j * 3, p[0] - rx);
+ set!(f, 5 + j * 3 + 1, p[1]);
+ set!(f, 5 + j * 3 + 2, p[2] - rz);
+ }
+ for i in 0..frames * DIM {
+ obs[i] = (obs[i] - st.mean[i % DIM]) / st.std[i % DIM];
+ }
+ Ok(Conditions { obs, mask })
+}
diff --git a/systems/kimodo/src/decode.rs b/systems/kimodo/src/decode.rs
new file mode 100644
index 00000000..c5a79095
--- /dev/null
+++ b/systems/kimodo/src/decode.rs
@@ -0,0 +1,104 @@
+//! Features to joints: KimodoMotionRep.inverse, then SOMASkeleton30.output_to_SOMASkeleton77. Each frame's 369
+//! numbers (normalised) are: smooth root place 3, heading cos and sin 2, the 30 joints' places from the smooth root
+//! 90, their world turns as two matrix columns 180, their speeds 90, foot contacts 4.
+
+use crate::skeleton::{M3, Skeleton, fk, mul, transpose};
+use crate::stats::Stats;
+
+pub const DIM: usize = 369;
+pub const J: usize = 30;
+
+pub struct Motion {
+ pub local77: Vec<Vec<M3>>,
+ pub global77: Vec<Vec<M3>>,
+ pub joints77: Vec<Vec<[f32; 3]>>,
+ pub root: Vec<[f32; 3]>,
+ pub smooth_root: Vec<[f32; 3]>,
+ pub heading: Vec<[f32; 2]>,
+ /// left heel, left toe, left toe end, right heel, right toe, right toe end
+ pub contacts: Vec<[bool; 6]>,
+}
+
+fn norm(v: [f32; 3]) -> [f32; 3] {
+ let n = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
+ [v[0] / n, v[1] / n, v[2] / n]
+}
+
+fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
+ std::array::from_fn(|i| a[(i + 1) % 3] * b[(i + 2) % 3] - a[(i + 2) % 3] * b[(i + 1) % 3])
+}
+
+/// Two columns of a turn (6 numbers) -> the turn: Gram-Schmidt, columns x, z cross x, z
+pub fn cont6d(c: &[f32]) -> M3 {
+ let x = norm([c[0], c[1], c[2]]);
+ let z = norm(cross(x, [c[3], c[4], c[5]]));
+ let y = cross(z, x);
+ [[x[0], y[0], z[0]], [x[1], y[1], z[1]], [x[2], y[2], z[2]]]
+}
+
+/// One clip's features [T * 369], normalised, to the 77 joints.
+pub fn decode(features: &[f32], st: &Stats, sk: &Skeleton) -> Motion {
+ let t_n = features.len() / DIM;
+ let f: Vec<f32> = features.iter().enumerate().map(|(i, v)| v * st.std[i % DIM] + st.mean[i % DIM]).collect();
+ let (mut local77, mut root, mut smooth, mut heading, mut contacts) = (vec![], vec![], vec![], vec![], vec![]);
+ for t in 0..t_n {
+ let r = &f[t * DIM..(t + 1) * DIM];
+ let g30: Vec<M3> = (0..J).map(|j| cont6d(&r[95 + j * 6..95 + j * 6 + 6])).collect();
+ let mut loc = sk.relaxed77.clone();
+ for j in 0..J {
+ let p = sk.parents30[j];
+ let parent = if p < 0 || j == 0 { crate::skeleton::EYE } else { g30[p as usize] };
+ loc[sk.slice30in77[j]] = mul(&transpose(&parent), &g30[j]);
+ }
+ local77.push(loc);
+ let s = [r[0], r[1], r[2]];
+ root.push([r[5] + s[0], r[6], r[7] + s[2]]);
+ smooth.push(s);
+ heading.push([r[3], r[4]]);
+ let c = [r[365] > 0.5, r[366] > 0.5, r[367] > 0.5, r[368] > 0.5];
+ contacts.push([c[0], c[1], c[1], c[2], c[3], c[3]]);
+ }
+ let (global77, joints77) = fk(&local77, &root, &sk.parents77, &sk.neutral77);
+ Motion { local77, global77, joints77, root, smooth_root: smooth, heading, contacts }
+}
+
+/// A turn as a quaternion x y z w, as the cloud runner writes them (kimodo_constraints.py `quat`).
+pub fn quat(m: &M3) -> [f64; 4] {
+ let m = m.map(|r| r.map(|v| v as f64));
+ let w = (1.0 + m[0][0] + m[1][1] + m[2][2]).max(1e-12).sqrt() / 2.0;
+ let x = (1.0 + m[0][0] - m[1][1] - m[2][2]).max(0.0).sqrt() / 2.0;
+ let y = (1.0 - m[0][0] + m[1][1] - m[2][2]).max(0.0).sqrt() / 2.0;
+ let z = (1.0 - m[0][0] - m[1][1] + m[2][2]).max(0.0).sqrt() / 2.0;
+ let (x, y, z) = (x.copysign(m[2][1] - m[1][2]), y.copysign(m[0][2] - m[2][0]), z.copysign(m[1][0] - m[0][1]));
+ let n = (x * x + y * y + z * z + w * w).sqrt();
+ [x / n, y / n, z / n, w / n]
+}
+
+/// to `places` decimals, as the cloud runner wrote them
+fn round(v: f64, places: i32) -> f64 {
+ format!("{v:.*}", places as usize).parse().unwrap_or(v)
+}
+
+/// 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 {
+ let source = format!(
+ "Kimodo-SOMA-RP-v1 (nv-tlabs/kimodo), NVIDIA Open Model License, on this Mac (raea-sys-kimodo, MLX); {}",
+ match (prompt.trim().is_empty(), constrained) {
+ (false, true) => format!("text: {prompt:?}, and constraints"),
+ (false, false) => format!("text: {prompt:?}"),
+ (true, _) => "constraints only, no text".into(),
+ }
+ );
+ serde_json::json!({
+ "fps": 30,
+ "names": sk.names77,
+ "root": m.joints77.iter().map(|f| f[0].map(|v| round(v as f64, 5))).collect::<Vec<_>>(),
+ "turns": m.global77.iter().map(|f| f.iter().map(|g| quat(g).map(|v| round(v, 6))).collect::<Vec<_>>()).collect::<Vec<_>>(),
+ "contacts": m.contacts.iter().map(|c| c.map(|b| b as u8)).collect::<Vec<_>>(),
+ "seed": seed,
+ "steps": steps,
+ "source": source,
+ "prompt": prompt,
+ })
+}
diff --git a/systems/kimodo/src/lib.rs b/systems/kimodo/src/lib.rs
new file mode 100644
index 00000000..00781649
--- /dev/null
+++ b/systems/kimodo/src/lib.rs
@@ -0,0 +1,173 @@
+//! Kimodo on this Mac (docs/character.feature CH15c): SOMA body motion from a line of text and constraints, made by
+//! Kimodo-SOMA-RP-v1 (nv-tlabs/kimodo: code Apache-2.0; weights under NVIDIA's Open Model License, commercial use
+//! allowed) on raea's MLX facility, with its text encoder (LLM2Vec, McGill-NLP, MIT adapters, on Llama 3 8B Instruct
+//! in 8 bits: Meta's Llama 3 Community License) on MLX too. No GPU in the cloud and no Python.
+//!
+//! The networks are plain functions over the checkpoints' own safetensors (net.rs, text.rs), checked against the
+//! PyTorch reference: the denoiser to 1e-4 on its features, a whole 100-step generation to hundredths of a millimetre
+//! on the joints (tests.rs). Kimodo's post-processing (foot-skate cleanup and constraint enforcement, a C++ extension)
+//! 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.
+
+pub mod constraints;
+pub mod decode;
+pub mod skeleton;
+pub mod stats;
+
+#[cfg(target_os = "macos")]
+pub mod net;
+#[cfg(target_os = "macos")]
+pub mod sample;
+#[cfg(target_os = "macos")]
+pub mod text;
+
+#[cfg(all(test, target_os = "macos"))]
+mod tests;
+
+#[cfg(target_os = "macos")]
+pub use model::*;
+
+#[cfg(target_os = "macos")]
+mod model {
+ use std::path::{Path, PathBuf};
+
+ use anyhow::Result;
+ use raea_sys_ml::models::{Spec, ensure};
+
+ use crate::constraints::{Conditions, conditions};
+ use crate::decode::{DIM, Motion, decode};
+ use crate::net::Net;
+ use crate::skeleton::Skeleton;
+ use crate::stats::Stats;
+
+ /// The motion model: 1.13 GB.
+ pub const MOTION: Spec = Spec {
+ name: "kimodo",
+ files: &[
+ ("nvidia/Kimodo-SOMA-RP-v1", "model.safetensors", "model.safetensors"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "stats/motion/global_root/mean.npy", "stats/motion/global_root/mean.npy"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "stats/motion/global_root/std.npy", "stats/motion/global_root/std.npy"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "stats/motion/local_root/mean.npy", "stats/motion/local_root/mean.npy"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "stats/motion/local_root/std.npy", "stats/motion/local_root/std.npy"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "stats/motion/body/mean.npy", "stats/motion/body/mean.npy"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "stats/motion/body/std.npy", "stats/motion/body/std.npy"),
+ ("nvidia/Kimodo-SOMA-RP-v1", "LICENSE", "LICENSE"),
+ ],
+ };
+
+ /// The text encoder: 8.5 GB of 8-bit Llama 3 and 336 MB of adapters. Fetched only when a line has words that
+ /// haven't been read before.
+ pub const TEXT: Spec = Spec {
+ name: "kimodo-text",
+ files: &[
+ ("mlx-community/Meta-Llama-3-8B-Instruct-8bit", "config.json", "config.json"),
+ ("mlx-community/Meta-Llama-3-8B-Instruct-8bit", "model-00001-of-00002.safetensors", "model-00001-of-00002.safetensors"),
+ ("mlx-community/Meta-Llama-3-8B-Instruct-8bit", "model-00002-of-00002.safetensors", "model-00002-of-00002.safetensors"),
+ ("McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp", "adapter_model.safetensors", "llm2vec/mntp.safetensors"),
+ ("McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp-supervised", "adapter_model.safetensors", "llm2vec/supervised.safetensors"),
+ ("McGill-NLP/LLM2Vec-Meta-Llama-3-8B-Instruct-mntp", "tokenizer.json", "llm2vec/tokenizer.json"),
+ ],
+ };
+
+ /// What a clip is made from.
+ pub struct Ask<'a> {
+ pub line: &'a str,
+ pub frames: usize,
+ pub seed: u64,
+ pub steps: usize,
+ /// a Kimodo constraints file's list (keyframes, end effectors, a root path), or none
+ pub constraints: Option<&'a serde_json::Value>,
+ /// guidance for the text and for the constraints (Kimodo's default 2 and 2)
+ pub cfg: (f32, f32),
+ }
+
+ pub struct Made {
+ pub motion: Motion,
+ pub features: Vec<f32>,
+ /// the line as the encoder read it (sanitised)
+ pub line: String,
+ }
+
+ pub struct Kimodo {
+ pub net: Net,
+ pub stats: Stats,
+ pub skeleton: Skeleton,
+ text_dir: Option<PathBuf>,
+ text: Option<crate::text::Encoder>,
+ /// where each line's numbers are kept once read (CH15c: the encoder runs once a line), and whether the
+ /// encoder may be fetched into the models folder when a line is new
+ lines: Option<PathBuf>,
+ fetch_text: bool,
+ }
+
+ /// what a line's numbers are kept under: FNV-1a over the encoder's name and the line as it reads it
+ fn line_key(clean: &str) -> String {
+ let h = "llm2vec-llama3-8b-instruct-q8\n".bytes().chain(clean.bytes()).fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3));
+ format!("{h:016x}.f32")
+ }
+
+ impl Kimodo {
+ /// From folders already on disk: the motion checkpoint, and the text encoder's (read on the first line with words).
+ pub fn open(motion_dir: &Path, text_dir: Option<&Path>) -> Result<Self> {
+ let stats = Stats::load(motion_dir)?;
+ Ok(Kimodo { net: Net::load(motion_dir, &stats)?, stats, skeleton: Skeleton::soma()?, text_dir: text_dir.map(Path::to_path_buf), text: None, lines: None, fetch_text: false })
+ }
+
+ /// From raea's models folder, fetching the motion model if it's missing; the text encoder is fetched by the
+ /// first line it hasn't read, and each line's numbers are kept beside the motion model.
+ pub fn fetch(progress: &mut dyn FnMut(&str, u64)) -> Result<Self> {
+ let m = ensure(&MOTION, progress)?;
+ let mut k = Self::open(&m, None)?;
+ k.lines = Some(m.join("lines"));
+ k.fetch_text = true;
+ Ok(k)
+ }
+
+ /// A line's 4096 numbers, or none for an empty line.
+ pub fn encode(&mut self, line: &str) -> Result<(String, Option<Vec<f32>>)> {
+ let clean = crate::text::sanitize(line);
+ if clean.is_empty() {
+ return Ok((clean, None));
+ }
+ let kept = self.lines.as_ref().map(|d| d.join(line_key(&clean)));
+ if let Some(b) = kept.as_ref().and_then(|p| std::fs::read(p).ok()).filter(|b| b.len() == 4 * crate::net::TEXT_DIM as usize) {
+ return Ok((clean, Some(b.chunks(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())));
+ }
+ if self.text.is_none() {
+ let dir = match (&self.text_dir, self.fetch_text) {
+ (Some(d), _) => d.clone(),
+ (None, true) => ensure(&TEXT, &mut |f, n| if n % (1 << 30) < (1 << 16) { eprintln!("kimodo: fetching the text encoder's {f}: {} MB", n >> 20) })?,
+ (None, false) => anyhow::bail!("kimodo: a line with words needs the text encoder's folder"),
+ };
+ self.text = Some(crate::text::Encoder::load(&dir)?);
+ }
+ let (t, e) = self.text.as_ref().unwrap().encode(line)?;
+ if let Some(p) = kept {
+ let b: Vec<u8> = e.iter().flat_map(|v| v.to_le_bytes()).collect();
+ let _ = std::fs::create_dir_all(p.parent().unwrap()).and_then(|_| std::fs::write(&p, b));
+ }
+ Ok((t, Some(e)))
+ }
+
+ pub fn conditions(&self, c: &serde_json::Value, frames: usize) -> Result<Conditions> {
+ conditions(c, frames, &self.stats, &self.skeleton)
+ }
+
+ /// One clip. `text` is the line's embedding (from `encode`), or none.
+ pub fn make(&self, ask: &Ask, text: Option<&[f32]>, noise: Option<&[f32]>) -> Result<Made> {
+ let cond = ask.constraints.map(|c| self.conditions(c, ask.frames)).transpose()?;
+ let own;
+ let noise = match noise {
+ Some(n) => n,
+ None => {
+ own = crate::sample::noise(ask.seed, ask.frames * DIM);
+ &own
+ }
+ };
+ let features = crate::sample::sample(&self.net, noise, ask.frames, ask.steps, text, cond.as_ref().map(|c| (c.obs.as_slice(), c.mask.as_slice())), ask.cfg)?;
+ Ok(Made { motion: decode(&features, &self.stats, &self.skeleton), features, line: crate::text::sanitize(ask.line) })
+ }
+ }
+}
diff --git a/systems/kimodo/src/net.rs b/systems/kimodo/src/net.rs
new file mode 100644
index 00000000..3beb052a
--- /dev/null
+++ b/systems/kimodo/src/net.rs
@@ -0,0 +1,185 @@
+//! Kimodo's two-stage denoiser on MLX (kimodo/model/twostage_denoiser.py, backbone.py): two torch
+//! TransformerEncoders of the same shape (16 layers, width 1024, 8 heads, feed-forward 2048, GELU, norm after each
+//! sublayer, no final norm). The root stage predicts the 5 global root numbers; they become 4 local root speeds; the
+//! body stage predicts the other 364. Each stage sees [50 text tokens, the timestep, the first heading, the frames]
+//! plus a fixed sin/cos table over the whole sequence. Weights by the checkpoint's own names.
+
+use std::path::Path;
+
+use anyhow::Result;
+use mlx_rs::{Array, Dtype, fast, ops};
+use raea_sys_mlx::nn::linear;
+use raea_sys_mlx::weights::Weights;
+
+use crate::decode::DIM;
+use crate::stats::Stats;
+
+pub const LATENT: i32 = 1024;
+pub const HEADS: i32 = 8;
+pub const LAYERS: usize = 16;
+pub const TEXT_TOKENS: i32 = 50;
+pub const TEXT_DIM: i32 = 4096;
+pub const FPS: f32 = 30.0;
+const ROOT_DIM: i32 = 5;
+const P: &str = "denoiser.backbone.";
+
+pub struct Net {
+ pub w: Weights,
+ pe: Array,
+ mean_g: Array,
+ std_g: Array,
+ mean_l: Array,
+ std_l: Array,
+}
+
+/// Kimodo's fixed sin/cos table, in f32 as PyTorch computes it.
+fn pe_table(n: usize, d: usize) -> Vec<f32> {
+ let mut pe = vec![0.0f32; n * d];
+ let div: Vec<f32> = (0..d / 2).map(|k| 10000f32.powf(-((2 * k) as f32) / d as f32)).collect();
+ for p in 0..n {
+ for (k, dv) in div.iter().enumerate() {
+ let a = p as f32 * dv;
+ pe[p * d + 2 * k] = a.sin();
+ pe[p * d + 2 * k + 1] = a.cos();
+ }
+ }
+ pe
+}
+
+fn arr(v: &[f32]) -> Array {
+ Array::from_slice(v, &[v.len() as i32])
+}
+
+/// frames start..end along `axis`
+pub fn slice(a: &Array, axis: i32, start: i32, end: i32) -> Result<Array> {
+ let idx: Vec<i32> = (start..end).collect();
+ Ok(ops::indexing::take_axis(a, Array::from_slice(&idx, &[idx.len() as i32]), axis)?)
+}
+
+impl Net {
+ pub fn load(ckpt: &Path, st: &Stats) -> Result<Self> {
+ let w = Weights::load(&ckpt.join("model.safetensors"))?;
+ w.eval()?;
+ Ok(Net {
+ w,
+ pe: Array::from_slice(&pe_table(5000, LATENT as usize), &[5000, LATENT]),
+ mean_g: arr(&st.mean_global_root),
+ std_g: arr(&st.std_global_root),
+ mean_l: arr(&st.mean_local_root),
+ std_l: arr(&st.std_local_root),
+ })
+ }
+
+ fn w(&self, k: &str) -> Result<&Array> {
+ self.w.get(k)
+ }
+
+ /// torch.nn.TransformerEncoderLayer: norm after (norm_first false), GELU (erf), no dropout
+ fn layer(&self, p: &str, x: &Array, mask: &Array) -> Result<Array> {
+ let s = x.shape();
+ let (b, l, d) = (s[0], s[1], s[2]);
+ let qkv = ops::add(&x.matmul(&self.w(&format!("{p}.self_attn.in_proj_weight"))?.transpose()?)?, self.w(&format!("{p}.self_attn.in_proj_bias"))?)?;
+ let parts = ops::split_equal(&qkv, 3, -1)?;
+ let heads = |a: &Array| -> Result<Array> { Ok(a.reshape(&[b, l, HEADS, d / HEADS])?.transpose_axes(&[0, 2, 1, 3])?) };
+ let (q, k, v) = (heads(&parts[0])?, heads(&parts[1])?, heads(&parts[2])?);
+ let a = fast::scaled_dot_product_attention(&q, &k, &v, 1.0 / ((d / HEADS) as f32).sqrt(), mask, None)?;
+ let a = linear(&self.w, &format!("{p}.self_attn.out_proj"), &a.transpose_axes(&[0, 2, 1, 3])?.reshape(&[b, l, d])?)?;
+ let x = fast::layer_norm(&ops::add(x, &a)?, Some(self.w(&format!("{p}.norm1.weight"))?), Some(self.w(&format!("{p}.norm1.bias"))?), 1e-5)?;
+ let f = linear(&self.w, &format!("{p}.linear2"), &mlx_rs::nn::gelu(linear(&self.w, &format!("{p}.linear1"), &x)?)?)?;
+ Ok(fast::layer_norm(&ops::add(&x, &f)?, Some(self.w(&format!("{p}.norm2.weight"))?), Some(self.w(&format!("{p}.norm2.bias"))?), 1e-5)?)
+ }
+
+ /// kimodo.model.backbone.TransformerEncoderBlock. `keep` [B, T] is 1 on a clip's frames, 0 past its end;
+ /// `t` [B] the timesteps; `heading` [B] the first frame's heading. All 50 text slots are attended (the checkpoint's
+ /// use_text_mask is false), zero-padded past the text's own tokens.
+ fn block(&self, p: &str, x: &Array, keep: &Array, text: &Array, t: &Array, heading: &Array) -> Result<Array> {
+ let s = x.shape();
+ let (b, tn) = (s[0], s[1]);
+ let x = linear(&self.w, &format!("{p}.input_linear"), x)?;
+ let n = text.shape()[1].min(TEXT_TOKENS);
+ let text = slice(text, 1, 0, n)?;
+ let text = if n < TEXT_TOKENS { ops::concatenate(&[text, ops::zeros::<f32>(&[b, TEXT_TOKENS - n, TEXT_DIM])?], 1)? } else { text };
+ let e_text = linear(&self.w, &format!("{p}.embed_text"), &text)?;
+ let pe_t = ops::indexing::take_axis(&self.pe, t, 0)?;
+ let e_time = linear(&self.w, &format!("{p}.embed_timestep.time_embed.2"), &mlx_rs::nn::silu(linear(&self.w, &format!("{p}.embed_timestep.time_embed.0"), &pe_t)?)?)?;
+ let e_head = linear(&self.w, &format!("{p}.linear_first_heading_angle"), &ops::stack(&[ops::cos(heading)?, ops::sin(heading)?], -1)?)?;
+ let seq = ops::concatenate(&[e_text, e_time.expand_dims(1)?, e_head.expand_dims(1)?, x], 1)?;
+ let len = seq.shape()[1];
+ let pre = len - tn;
+ let seq = ops::add(&seq, &slice(&self.pe, 0, 0, len)?.expand_dims(0)?)?;
+ let keep_all = ops::concatenate(&[ops::ones::<f32>(&[b, pre])?, keep.clone()], 1)?;
+ // additive: 0 where a key is kept, -1e9 past a clip's end
+ let mask = ops::multiply(&ops::subtract(&keep_all, &Array::from_f32(1.0))?, &Array::from_f32(1e9))?.reshape(&[b, 1, 1, len])?;
+ let mut seq = seq;
+ for i in 0..LAYERS {
+ seq = self.layer(&format!("{p}.seqTransEncoder.layers.{i}"), &seq, &mask)?;
+ }
+ linear(&self.w, &format!("{p}.output_linear"), &slice(&seq, 1, pre, len)?)
+ }
+
+ /// normalised [smooth root x y z, heading cos, sin] -> normalised [turn speed, x speed, z speed, height]; the speeds
+ /// are differences times 30 with a zero appended, the last valid frame taking the one before it
+ fn local_root(&self, root: &Array, lengths: &[i32]) -> Result<Array> {
+ let root = ops::add(&ops::multiply(root, &self.std_g)?, &self.mean_g)?;
+ let tn = root.shape()[1];
+ let b = root.shape()[0];
+ let pos = slice(&root, 2, 0, 3)?;
+ let ang = ops::atan2(&slice(&root, 2, 4, 5)?, &slice(&root, 2, 3, 4)?)?;
+ let (c, s) = (ops::cos(&ang)?, ops::sin(&ang)?);
+ let (c1, c0, s1, s0) = (slice(&c, 1, 1, tn)?, slice(&c, 1, 0, tn - 1)?, slice(&s, 1, 1, tn)?, slice(&s, 1, 0, tn - 1)?);
+ let d = ops::multiply(
+ &ops::atan2(&ops::subtract(&ops::multiply(&s1, &c0)?, &ops::multiply(&c1, &s0)?)?, &ops::add(&ops::multiply(&c1, &c0)?, &ops::multiply(&s1, &s0)?)?)?,
+ &Array::from_f32(FPS),
+ )?;
+ let vel = ops::multiply(&ops::subtract(&slice(&pos, 1, 1, tn)?, &slice(&pos, 1, 0, tn - 1)?)?, &Array::from_f32(FPS))?;
+ let pad = |a: &Array| -> Result<Array> {
+ let z = ops::zeros::<f32>(&[b, 1, a.shape()[2]])?;
+ let a = ops::concatenate(&[a.clone(), z.clone()], 1)?;
+ let prev = ops::concatenate(&[z, slice(&a, 1, 0, tn - 1)?], 1)?;
+ // the last valid frame of each clip takes the frame before it
+ let mut last = vec![0.0f32; (b * tn) as usize];
+ for (i, &l) in lengths.iter().enumerate() {
+ last[i * tn as usize + (l - 1) as usize] = 1.0;
+ }
+ let last = Array::from_slice(&last, &[b, tn, 1]);
+ Ok(ops::add(&ops::multiply(&last, &prev)?, &ops::multiply(&ops::subtract(&Array::from_f32(1.0), &last)?, &a)?)?)
+ };
+ let (rot, vel) = (pad(&d)?, pad(&vel)?);
+ let local = ops::concatenate(&[rot, slice(&vel, 2, 0, 1)?, slice(&vel, 2, 2, 3)?, slice(&pos, 2, 1, 2)?], 2)?;
+ Ok(ops::divide(&ops::subtract(&local, &self.mean_l)?, &self.std_l)?)
+ }
+
+ /// The denoiser's clean-motion prediction for x [B, T, 369] at timesteps t, with conditions (mask, obs) or none.
+ pub fn denoise(&self, x: &Array, lengths: &[i32], text: &Array, t: &Array, heading: &Array, cond: Option<(&Array, &Array)>) -> Result<Array> {
+ let s = x.shape();
+ let (b, tn) = (s[0], s[1]);
+ let zeros;
+ let (mask, obs) = match cond {
+ Some(c) => c,
+ None => {
+ zeros = ops::zeros::<f32>(&[b, tn, DIM as i32])?;
+ (&zeros, &zeros)
+ }
+ };
+ let x = ops::add(&ops::multiply(x, &ops::subtract(&Array::from_f32(1.0), mask)?)?, &ops::multiply(obs, mask)?)?;
+ let mut keep = vec![0.0f32; (b * tn) as usize];
+ for (i, &l) in lengths.iter().enumerate() {
+ for f in 0..l as usize {
+ keep[i * tn as usize + f] = 1.0;
+ }
+ }
+ let keep = Array::from_slice(&keep, &[b, tn]);
+ let root = self.block(&format!("{P}root_model"), &ops::concatenate(&[x.clone(), mask.clone()], -1)?, &keep, text, t, heading)?;
+ let local = self.local_root(&root, lengths)?;
+ let body_in = ops::concatenate(&[local, slice(&x, 2, ROOT_DIM, DIM as i32)?, mask.clone()], -1)?;
+ let body = self.block(&format!("{P}body_model"), &body_in, &keep, text, t, heading)?;
+ Ok(ops::concatenate(&[root, body], -1)?)
+ }
+}
+
+pub fn f32_array(a: &Array) -> Result<Vec<f32>> {
+ let a = if a.dtype() == Dtype::Float32 { a.clone() } else { a.as_dtype(Dtype::Float32)? };
+ let a = a.contiguous()?;
+ a.eval()?;
+ Ok(a.as_slice::<f32>().to_vec())
+}
diff --git a/systems/kimodo/src/sample.rs b/systems/kimodo/src/sample.rs
new file mode 100644
index 00000000..f8a9c5cc
--- /dev/null
+++ b/systems/kimodo/src/sample.rs
@@ -0,0 +1,125 @@
+//! Kimodo's sampler (kimodo/model/kimodo_model.py, diffusion.py, cfg.py): a cosine schedule on 1000 base steps
+//! respaced to N, deterministic DDIM (eta 0) on the model's clean-motion prediction, and separated guidance:
+//! uncond + w_text (text - uncond) + w_constraint (constrained - uncond). Kimodo always runs the three passes as one
+//! batch; a pass whose inputs equal the unconditional one's (no text, or no constraints) is run once here.
+
+use anyhow::Result;
+use mlx_rs::{Array, ops};
+
+use crate::decode::DIM;
+use crate::net::{Net, TEXT_DIM};
+
+pub const BASE_STEPS: usize = 1000;
+
+pub struct Schedule {
+ pub use_t: Vec<i32>,
+ pub recip: Vec<f32>,
+ pub recipm1: Vec<f32>,
+ pub prev: Vec<f32>,
+}
+
+/// In f32 as PyTorch (and the MLX reference) compute it.
+pub fn schedule(steps: usize) -> Schedule {
+ let ab = |t: f64| ((t + 0.008) / 1.008 * std::f64::consts::PI / 2.0).cos().powi(2);
+ let betas: Vec<f32> = (0..BASE_STEPS).map(|i| (1.0 - ab((i + 1) as f64 / BASE_STEPS as f64) / ab(i as f64 / BASE_STEPS as f64)).min(0.999) as f32).collect();
+ let mut base = Vec::with_capacity(BASE_STEPS);
+ let mut acc = 1.0f32;
+ for b in &betas {
+ acc *= 1.0 - b;
+ base.push(acc);
+ }
+ // (numpy: the fraction divided in f64 and cast, the products rounded half to even)
+ let frac = ((BASE_STEPS - 1) as f64 / (steps.max(2) - 1) as f64) as f32;
+ let use_t: Vec<i32> = (0..steps).map(|i| ((i as f32 * frac).round_ties_even() as i32).min(BASE_STEPS as i32 - 1)).collect();
+ let ac: Vec<f32> = use_t.iter().map(|&u| base[u as usize]).collect();
+ let mut acp = Vec::with_capacity(steps);
+ let mut acc = 1.0f32;
+ for (i, a) in ac.iter().enumerate() {
+ let before = if i == 0 { 1.0 } else { ac[i - 1] };
+ let b = 1.0 - a / before;
+ acc *= 1.0 - b;
+ acp.push(acc.max(1e-9));
+ }
+ let prev: Vec<f32> = (0..steps).map(|i| if i == 0 { 1.0 } else { acp[i - 1] }).collect();
+ Schedule {
+ use_t,
+ recip: acp.iter().map(|a| 1.0 / a.sqrt()).collect(),
+ recipm1: acp.iter().map(|a| 1.0 / (a / (1.0 - a)).sqrt()).collect(),
+ prev,
+ }
+}
+
+/// One clip [frames, 369] from `noise` (normalised features), a text embedding (4096 numbers, or none) and conditions.
+pub fn sample(net: &Net, noise: &[f32], frames: usize, steps: usize, text: Option<&[f32]>, cond: Option<(&[f32], &[f32])>, cfg: (f32, f32)) -> Result<Vec<f32>> {
+ let t_n = frames as i32;
+ let mut x = Array::from_slice(noise, &[1, t_n, DIM as i32]);
+ let zt = ops::zeros::<f32>(&[1, 1, TEXT_DIM])?;
+ let text = text.map(|t| Array::from_slice(t, &[1, 1, TEXT_DIM]));
+ let cond_in = cond;
+ let cond = cond.map(|(obs, mask)| (Array::from_slice(mask, &[1, t_n, DIM as i32]), Array::from_slice(obs, &[1, t_n, DIM as i32])));
+ let has_text = text.is_some();
+ let any_con = cond_in.is_some_and(|(_, m)| m.iter().any(|&v| v > 0.0));
+ let has_con = any_con;
+ // the passes: unconditional; text and no constraints; constraints and no text
+ let zm = ops::zeros::<f32>(&[1, t_n, DIM as i32])?;
+ let mut texts = vec![zt.clone()];
+ let mut masks = vec![zm.clone()];
+ if let Some(t) = &text {
+ texts.push(t.clone());
+ masks.push(zm.clone());
+ }
+ if has_con {
+ texts.push(zt.clone());
+ masks.push(cond.as_ref().unwrap().0.clone());
+ }
+ let n = texts.len() as i32;
+ let text_b = ops::concatenate(&texts, 0)?;
+ let mask_b = ops::concatenate(&masks, 0)?;
+ let obs_b = match &cond {
+ Some((_, o)) => ops::concatenate(&vec![o.clone(); n as usize], 0)?,
+ None => ops::zeros::<f32>(&[n, t_n, DIM as i32])?,
+ };
+ let lengths = vec![t_n; n as usize];
+ let heading = ops::zeros::<f32>(&[n])?;
+ let s = schedule(steps);
+ for i in (0..steps).rev() {
+ let xb = ops::concatenate(&vec![x.clone(); n as usize], 0)?;
+ let t = Array::from_slice(&vec![s.use_t[i]; n as usize], &[n]);
+ let out = net.denoise(&xb, &lengths, &text_b, &t, &heading, Some((&mask_b, &obs_b)))?;
+ let parts = ops::split_equal(&out, n, 0)?;
+ let unc = &parts[0];
+ let mut pred = unc.clone();
+ if has_text {
+ pred = ops::add(&pred, &ops::multiply(&ops::subtract(&parts[1], unc)?, &Array::from_f32(cfg.0))?)?;
+ }
+ if has_con {
+ pred = ops::add(&pred, &ops::multiply(&ops::subtract(&parts[n as usize - 1], unc)?, &Array::from_f32(cfg.1))?)?;
+ }
+ let eps = ops::divide(&ops::subtract(&ops::multiply(&x, &Array::from_f32(s.recip[i]))?, &pred)?, &Array::from_f32(s.recipm1[i]))?;
+ let (a, b) = ((s.prev[i] as f64).sqrt() as f32, (1.0 - s.prev[i] as f64).sqrt() as f32);
+ x = ops::add(&ops::multiply(&pred, &Array::from_f32(a))?, &ops::multiply(&eps, &Array::from_f32(b))?)?;
+ x.eval()?;
+ }
+ crate::net::f32_array(&x)
+}
+
+/// Starting noise from a seed: Box-Muller over a PCG32 stream. Not numpy's or torch's: a seed here is not the same
+/// motion as that seed in the cloud.
+pub fn noise(seed: u64, n: usize) -> Vec<f32> {
+ let mut state = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let mut next = || {
+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let x = (((state >> 18) ^ state) >> 27) as u32;
+ let rot = (state >> 59) as u32;
+ (x.rotate_right(rot) as f64 + 0.5) / 4294967296.0
+ };
+ let mut out = Vec::with_capacity(n + 1);
+ while out.len() < n {
+ let (u, v) = (next(), next());
+ let r = (-2.0 * u.ln()).sqrt();
+ out.push((r * (2.0 * std::f64::consts::PI * v).cos()) as f32);
+ out.push((r * (2.0 * std::f64::consts::PI * v).sin()) as f32);
+ }
+ out.truncate(n);
+ out
+}
diff --git a/systems/kimodo/src/skeleton.rs b/systems/kimodo/src/skeleton.rs
new file mode 100644
index 00000000..21349eda
--- /dev/null
+++ b/systems/kimodo/src/skeleton.rs
@@ -0,0 +1,119 @@
+//! SOMA's 77-joint skeleton and the 30 joints Kimodo's features hold, as Kimodo's code builds them (soma77.json:
+//! parents, rest places, the relaxed hands' local turns, which of the 77 the 30 are).
+
+use anyhow::{Context, Result};
+use serde_json::Value;
+
+pub type M3 = [[f32; 3]; 3];
+
+pub struct Skeleton {
+ pub names30: Vec<String>,
+ pub names77: Vec<String>,
+ pub parents30: Vec<i32>,
+ pub parents77: Vec<i32>,
+ pub neutral30: Vec<[f32; 3]>,
+ pub neutral77: Vec<[f32; 3]>,
+ /// each of the 77's local turn in the relaxed-hands rest pose; the 30 Kimodo makes are written over it
+ pub relaxed77: Vec<M3>,
+ /// where each of the 30 sits in the 77
+ pub slice30in77: Vec<usize>,
+ /// the right and the left hip among the 30
+ pub hips30: [usize; 2],
+}
+
+fn ints(v: &Value, k: &str) -> Result<Vec<i64>> {
+ v[k].as_array().with_context(|| format!("soma77.json: no {k}"))?.iter().map(|x| x.as_i64().context("not an integer")).collect()
+}
+
+/// every number in a JSON value, nested arrays flattened
+pub(crate) fn floats(v: &Value) -> Vec<f32> {
+ match v {
+ Value::Array(a) => a.iter().flat_map(floats).collect(),
+ Value::Number(n) => vec![n.as_f64().unwrap_or(0.0) as f32],
+ _ => vec![],
+ }
+}
+
+fn v3(v: &Value, k: &str) -> Vec<[f32; 3]> {
+ floats(&v[k]).chunks(3).map(|c| [c[0], c[1], c[2]]).collect()
+}
+
+fn names(v: &Value, k: &str) -> Vec<String> {
+ v[k].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default()
+}
+
+impl Skeleton {
+ pub fn soma() -> Result<Self> {
+ let v: Value = serde_json::from_str(include_str!("soma77.json"))?;
+ let hips = ints(&v, "hips30")?;
+ let sk = Skeleton {
+ names30: names(&v, "names30"),
+ names77: names(&v, "names77"),
+ parents30: ints(&v, "parents30")?.into_iter().map(|p| p as i32).collect(),
+ parents77: ints(&v, "parents77")?.into_iter().map(|p| p as i32).collect(),
+ neutral30: v3(&v, "neutral30"),
+ neutral77: v3(&v, "neutral77"),
+ relaxed77: floats(&v["relaxed77"]).chunks(9).map(|c| [[c[0], c[1], c[2]], [c[3], c[4], c[5]], [c[6], c[7], c[8]]]).collect(),
+ slice30in77: ints(&v, "slice30in77")?.into_iter().map(|i| i as usize).collect(),
+ hips30: [hips[0] as usize, hips[1] as usize],
+ };
+ anyhow::ensure!(
+ sk.names30.len() == 30 && sk.names77.len() == 77 && sk.relaxed77.len() == 77 && sk.neutral77.len() == 77 && sk.slice30in77.len() == 30,
+ "soma77.json: a table has the wrong length"
+ );
+ Ok(sk)
+ }
+}
+
+pub fn mul(a: &M3, b: &M3) -> M3 {
+ let mut o = [[0.0; 3]; 3];
+ for i in 0..3 {
+ for j in 0..3 {
+ o[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
+ }
+ }
+ o
+}
+
+pub fn apply(a: &M3, v: [f32; 3]) -> [f32; 3] {
+ [0, 1, 2].map(|i| a[i][0] * v[0] + a[i][1] * v[1] + a[i][2] * v[2])
+}
+
+pub fn transpose(a: &M3) -> M3 {
+ [0, 1, 2].map(|i| [a[0][i], a[1][i], a[2][i]])
+}
+
+pub const EYE: M3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
+
+/// Forward kinematics: local turns and the root's place per frame -> each joint's world turn and place. `neutral` is
+/// the rest pose's joint places (only their offsets from the parent matter).
+pub fn fk(local: &[Vec<M3>], root: &[[f32; 3]], parents: &[i32], neutral: &[[f32; 3]]) -> (Vec<Vec<M3>>, Vec<Vec<[f32; 3]>>) {
+ let n = parents.len();
+ let mut g_all = Vec::with_capacity(local.len());
+ let mut p_all = Vec::with_capacity(local.len());
+ for (t, loc) in local.iter().enumerate() {
+ let mut g = vec![EYE; n];
+ let mut p = vec![[0.0f32; 3]; n];
+ for j in 0..n {
+ let par = parents[j];
+ if par < 0 {
+ g[j] = loc[j];
+ continue;
+ }
+ let par = par as usize;
+ debug_assert!(par < j);
+ g[j] = mul(&g[par], &loc[j]);
+ let off = [0, 1, 2].map(|k| neutral[j][k] - neutral[par][k]);
+ let r = apply(&g[par], off);
+ p[j] = [0, 1, 2].map(|k| p[par][k] + r[k]);
+ }
+ for q in p.iter_mut() {
+ for k in 0..3 {
+ q[k] += root[t][k];
+ }
+ }
+ g_all.push(g);
+ p_all.push(p);
+ }
+ (g_all, p_all)
+}
diff --git a/systems/kimodo/src/soma77.json b/systems/kimodo/src/soma77.json
new file mode 100644
index 00000000..351cca9b
--- /dev/null
+++ b/systems/kimodo/src/soma77.json
@@ -0,0 +1 @@
+{"parents30":[-1,0,1,2,3,4,5,6,6,6,3,10,11,12,13,13,3,16,17,18,19,19,0,22,23,24,0,26,27,28],"neutral30":[[0.0,0.0,0.0],[-0.0001372700062347576,0.050037626177072525,-0.0005372666637413204],[-0.00013727186887990683,0.12129063904285431,-0.0008355152094736695],[-0.00013727761688642204,0.19679127633571625,-0.008995224721729755],[-0.0019540428183972836,0.4599042236804962,-0.014528708532452583],[-0.0019540712237358093,0.5369982123374939,0.008497146889567375],[-0.001954117324203253,0.5982873439788818,0.028034232556819916],[-0.0019277484389021993,0.603043258190155,0.058983638882637024],[0.030109690502285957,0.6520894169807434,0.10390306264162064],[-0.03417851775884628,0.6519060134887695,0.10361656546592712],[0.016079239547252655,0.4291629195213318,0.04213890805840492],[0.16527768969535828,0.4291629195213318,-0.0128843504935503],[0.45267078280448914,0.4291629493236542,-0.012910229153931141],[0.7236105799674988,0.4291629195213318,-0.012884139083325863],[0.8462968468666077,0.39696118235588074,0.03544654697179794],[0.9137302041053772,0.426034152507782,-0.013223709538578987],[-0.013938459567725658,0.42859435081481934,0.04314635321497917],[-0.16431042551994324,0.4285944700241089,-0.01230969000607729],[-0.4516768157482147,0.4285944998264313,-0.012335660867393017],[-0.7230129837989807,0.4285944998264313,-0.012309534475207329],[-0.8456555008888245,0.39647993445396423,0.03573085740208626],[-0.9130189418792725,0.425528347492218,-0.012625268660485744],[0.1004321426153183,-0.0843452662229538,0.025956546887755394],[0.1004321277141571,-0.516562819480896,0.017927419394254684],[0.1004321426153183,-0.9381137490272522,-0.016887810081243515],[0.1004321426153183,-0.98870849609375,0.11542748659849167],[-0.10047277808189392,-0.0829525962471962,0.02620317041873932],[-0.10047277063131332,-0.5165746808052063,0.018147611990571022],[-0.10047274827957153,-0.9377486109733582,-0.01663636788725853],[-0.10047275573015213,-0.9885447025299072,0.11620558798313141]],"hips30":[26,22],"names30":["Hips","Spine1","Spine2","Chest","Neck1","Neck2","Head","Jaw","LeftEye","RightEye","LeftShoulder","LeftArm","LeftForeArm","LeftHand","LeftHandThumbEnd","LeftHandMiddleEnd","RightShoulder","RightArm","RightForeArm","RightHand","RightHandThumbEnd","RightHandMiddleEnd","LeftLeg","LeftShin","LeftFoot","LeftToeBase","RightLeg","RightShin","RightFoot","RightToeBase"],"parents77":[-1,0,1,2,3,4,5,6,6,6,6,3,11,12,13,14,15,16,17,14,19,20,21,22,14,24,25,26,27,14,29,30,31,32,14,34,35,36,37,3,39,40,41,42,43,44,45,42,47,48,49,50,42,52,53,54,55,42,57,58,59,60,42,62,63,64,65,0,67,68,69,70,0,72,73,74,75],"neutral77":[[0.0,0.0,0.0],[-0.0001372700062347576,0.050037626177072525,-0.0005372666637413204],[-0.00013727186887990683,0.12129063904285431,-0.0008355152094736695],[-0.00013727761688642204,0.19679127633571625,-0.008995224721729755],[-0.0019540428183972836,0.4599042236804962,-0.014528708532452583],[-0.0019540712237358093,0.5369982123374939,0.008497146889567375],[-0.001954117324203253,0.5982873439788818,0.028034232556819916],[-0.0019181378884240985,0.7589413523674011,0.009680439718067646],[-0.0019277484389021993,0.603043258190155,0.058983638882637024],[0.030109690502285957,0.6520894169807434,0.10390306264162064],[-0.03417851775884628,0.6519060134887695,0.10361656546592712],[0.016079239547252655,0.4291629195213318,0.04213890805840492],[0.16527768969535828,0.4291629195213318,-0.0128843504935503],[0.45267078280448914,0.4291629493236542,-0.012910229153931141],[0.7236105799674988,0.4291629195213318,-0.012884139083325863],[0.7463753819465637,0.415242463350296,0.01902998983860016],[0.786503791809082,0.3969612121582031,0.03544653579592705],[0.81448894739151,0.3969612121582031,0.03544650599360466],[0.8462968468666077,0.39696118235588074,0.03544654697179794],[0.7560861110687256,0.4238429367542267,0.010077552869915962],[0.8197318911552429,0.4239635467529297,0.011863548308610916],[0.8563555479049683,0.4239635467529297,0.01186355110257864],[0.879647970199585,0.4239635765552521,0.011863592080771923],[0.9072441458702087,0.42215821146965027,0.010733352042734623],[0.755245566368103,0.43157273530960083,-0.00288081681355834],[0.8171533346176147,0.4289799630641937,-0.012906298041343689],[0.8607185482978821,0.42897990345954895,-0.012906305491924286],[0.8906872868537903,0.4289798438549042,-0.012906303629279137],[0.9137302041053772,0.426034152507782,-0.013223709538578987],[0.7524369955062866,0.4286264181137085,-0.016109570860862732],[0.8109824061393738,0.4237643778324127,-0.029847977682948112],[0.8544881939888,0.4237643778324127,-0.029847946017980576],[0.8810014128684998,0.4237644672393799,-0.029847923666238785],[0.900362491607666,0.42454132437705994,-0.029848629608750343],[0.7522655725479126,0.4260628819465637,-0.0288879182189703],[0.803144097328186,0.4127514660358429,-0.04660021886229515],[0.8338538408279419,0.4127514958381653,-0.04660021513700485],[0.8493505120277405,0.4127514958381653,-0.04660020396113396],[0.8687994480133057,0.4111734926700592,-0.046028021723032],[-0.013938459567725658,0.42859435081481934,0.04314635321497917],[-0.16431042551994324,0.4285944700241089,-0.01230969000607729],[-0.4516768157482147,0.4285944998264313,-0.012335660867393017],[-0.7230129837989807,0.4285944998264313,-0.012309534475207329],[-0.7457533478736877,0.41475459933280945,0.019321737810969353],[-0.7858676314353943,0.39647993445396423,0.03573087975382805],[-0.8138169646263123,0.39647990465164185,0.03573084995150566],[-0.8456555008888245,0.39647993445396423,0.03573085740208626],[-0.7555456757545471,0.4233939051628113,0.010519127361476421],[-0.8189648389816284,0.4235186278820038,0.012301784940063953],[-0.8555135726928711,0.4235185384750366,0.012301783077418804],[-0.8787894248962402,0.4235185384750366,0.01230179239064455],[-0.9064072966575623,0.4217119812965393,0.011171014048159122],[-0.7546940445899963,0.43106043338775635,-0.002299230545759201],[-0.8165023326873779,0.4284720718860626,-0.012308182194828987],[-0.8599913716316223,0.4284720718860626,-0.012308184057474136],[-0.8899937868118286,0.42847204208374023,-0.012308205477893353],[-0.9130189418792725,0.425528347492218,-0.012625268660485744],[-0.7518699169158936,0.42791497707366943,-0.015398116782307625],[-0.8104118704795837,0.42305365204811096,-0.02913542650640011],[-0.8537999987602234,0.4230536222457886,-0.029135428369045258],[-0.8803490400314331,0.4230535924434662,-0.029135389253497124],[-0.899684727191925,0.4238288402557373,-0.029135914519429207],[-0.7516772747039795,0.425166517496109,-0.028150983154773712],[-0.8025909662246704,0.41184598207473755,-0.04587482661008835],[-0.8332176208496094,0.4118459224700928,-0.04587481915950775],[-0.8486828804016113,0.41184598207473755,-0.04587484151124954],[-0.868134081363678,0.41026878356933594,-0.045302730053663254],[0.1004321426153183,-0.0843452662229538,0.025956546887755394],[0.1004321277141571,-0.516562819480896,0.017927419394254684],[0.1004321426153183,-0.9381137490272522,-0.016887810081243515],[0.1004321426153183,-0.98870849609375,0.11542748659849167],[0.10033607482910156,-1.0051846504211426,0.18055765330791473],[-0.10047277808189392,-0.0829525962471962,0.02620317041873932],[-0.10047277063131332,-0.5165746808052063,0.018147611990571022],[-0.10047274827957153,-0.9377486109733582,-0.01663636788725853],[-0.10047275573015213,-0.9885447025299072,0.11620558798313141],[-0.10037743300199509,-1.0048885345458984,0.18081149458885193]],"relaxed77":[[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,-1.3427583098746254e-06,-3.9264031670427357e-07],[1.3427583098746254e-06,1.000000238418579,-1.6478944075970503e-07],[3.9264048723453016e-07,4.464928693437287e-08,1.000000238418579]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[0.980038046836853,0.10456321388483047,0.16909213364124298],[-0.10096757858991623,0.9944452047348022,-0.02974773570895195],[-0.17126333713531494,0.012080984190106392,0.985151469707489]],[[0.9818174839019775,0.18747958540916443,-0.029765967279672623],[-0.18972326815128326,0.974337637424469,-0.12112738192081451],[0.006293131969869137,0.12457224726676941,0.9921908378601074]],[[0.9882956147193909,1.1954236356359615e-07,0.15255138278007507],[1.2170265506483702e-07,1.0000003576278687,1.1255096854512203e-09],[-0.15255147218704224,-6.156434473325589e-09,0.9882957935333252]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[0.9985320568084717,0.030242079868912697,0.04493670165538788],[-0.03214818984270096,0.9985869526863098,0.04232209548354149],[-0.043593283742666245,-0.043704744428396225,0.9980931878089905]],[[0.9810277223587036,0.18235456943511963,0.06581452488899231],[-0.1758711338043213,0.979948878288269,-0.09364926069974899],[-0.08157219737768173,0.08029749989509583,0.9934277534484863]],[[0.9337304830551147,0.35797688364982605,-2.539580989946444e-08],[-0.3579767346382141,0.9337307810783386,-8.669996987009654e-08],[1.5877981596190693e-08,-4.312953549856502e-08,1.000000238418579]],[[0.9313047528266907,0.3588401675224304,0.06249217316508293],[-0.3617202639579773,0.9312959313392639,0.04297603294253349],[-0.04277715086936951,-0.0626286044716835,0.9971199631690979]],[[1.0,7.989044803480283e-08,-1.0939109529317648e-07],[8.867302625503726e-08,1.0000003576278687,-6.046956002592196e-08],[9.944098167125048e-08,-7.377190769375375e-08,1.000000238418579]],[[0.9989528059959412,0.02326994203031063,0.03939470648765564],[-0.023762758821249008,0.9996448159217834,0.012091930024325848],[-0.039099305868148804,-0.013015532866120338,0.999150812625885]],[[0.9314213991165161,0.3638163208961487,-0.009597794152796268],[-0.3637995421886444,0.929991602897644,-0.05259339511394501],[-0.010208404622972012,0.05247814953327179,0.9985701441764832]],[[0.9710460305213928,0.23889276385307312,-6.942111774321802e-09],[-0.23889261484146118,0.9710462689399719,-8.680182617126775e-08],[3.955703675728728e-08,-5.6245866630888486e-08,1.000000238418579]],[[0.9143363833427429,0.4049510657787323,0.0019584561232477427],[-0.40493232011795044,0.9142212867736816,0.015156357549130917],[0.004347181413322687,-0.014651183970272541,0.9998834729194641]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[0.9995572566986084,0.005557473283261061,0.029233748093247414],[-0.005129389464855194,0.9998792409896851,-0.01469280943274498],[-0.029311854392290115,0.014536227099597454,0.9994648098945618]],[[0.9693662524223328,0.2455878108739853,-0.003998155239969492],[-0.24561482667922974,0.9691089391708374,-0.022401701658964157],[-0.0016269013285636902,0.02269735187292099,0.99974125623703]],[[0.8269525766372681,0.5621064901351929,-0.013640386052429676],[-0.562249481678009,0.8268929719924927,-0.01113723125308752],[0.005018884781748056,0.016879167407751083,0.9998450875282288]],[[0.9393614530563354,0.34282228350639343,0.00856061838567257],[-0.34251558780670166,0.9391621947288513,-0.025651078671216965],[-0.01683351956307888,0.02116338536143303,0.9996344447135925]],[[1.0000001192092896,7.095973586501714e-08,1.34568995946438e-08],[7.095973586501714e-08,1.0000003576278687,-5.411286352341449e-08],[1.34568995946438e-08,-5.411286352341449e-08,1.0000001192092896]],[[0.9981033802032471,0.06012800335884094,0.013206100091338158],[-0.060004234313964844,0.9981526136398315,-0.009565235115587711],[-0.013756813481450081,0.00875452347099781,0.99986732006073]],[[0.960137665271759,0.27127575874328613,-0.06741887331008911],[-0.2740127742290497,0.9610827565193176,-0.03517961874604225],[0.055251795798540115,0.05225076898932457,0.9971046447753906]],[[0.993886411190033,0.1104077696800232,2.7541052105561903e-08],[-0.11040759831666946,0.9938867092132568,-7.914825062016462e-08],[4.094326300219109e-08,-5.936898617164843e-08,1.0000003576278687]],[[0.9484628438949585,0.3047541081905365,0.08685233443975449],[-0.3104344606399536,0.948600172996521,0.06155230477452278],[-0.06362971663475037,-0.0853421539068222,0.9943181872367859]],[[1.0000001192092896,1.60153916795025e-07,3.714115592856615e-08],[1.860044918089443e-08,1.000000238418579,-3.587032182394978e-08],[3.5881356552636134e-08,-1.0167633490709704e-07,1.0000003576278687]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[0.9950336217880249,-0.03400981053709984,-0.09354962408542633],[0.03898259624838829,0.9978938698768616,0.05185317248106003],[0.09158914536237717,-0.05524258688092232,0.9942634701728821]],[[0.9689887166023254,-0.2465875893831253,0.01598574034869671],[0.246683731675148,0.9615330696105957,-0.12083777785301208],[0.014426319859921932,0.12103372812271118,0.992543637752533]],[[0.9755706787109375,-6.032398136568418e-09,-0.21968600153923035],[-1.4764328426508655e-08,1.000000238418579,-5.104336864292236e-08],[0.21968604624271393,-7.599813045544579e-08,0.9755706787109375]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[0.9989951848983765,-0.027317475527524948,-0.03553270548582077],[0.029050273820757866,0.9983665943145752,0.04920250177383423],[0.03413066640496254,-0.05018545687198639,0.9981566667556763]],[[0.9939585328102112,-0.0884183943271637,-0.06502870470285416],[0.08220367133617401,0.9922928810119629,-0.09272538870573044],[0.07272621244192123,0.08681940287351608,0.99356609582901]],[[0.9815588593482971,-0.1911604106426239,6.040594513478936e-08],[0.19116035103797913,0.9815590977668762,-7.543771829432444e-08],[3.969322648345042e-08,-9.051092320078169e-08,1.000000238418579]],[[0.975672721862793,-0.20632407069206238,-0.07411642372608185],[0.20932693779468536,0.9772104024887085,0.0352504663169384],[0.06515438854694366,-0.049907661974430084,0.9966265559196472]],[[1.0,-3.128822712028523e-08,5.321204454844519e-08],[-3.128822712028523e-08,1.000000238418579,-8.74741346024166e-08],[5.321204454844519e-08,-8.74741346024166e-08,1.0000001192092896]],[[0.9991795420646667,-0.021660208702087402,-0.03422252833843231],[0.02253466658294201,0.999424159526825,0.025378331542015076],[0.03365320712327957,-0.026128867641091347,0.9990921020507812]],[[0.9667755365371704,-0.25422102212905884,0.026775022968649864],[0.25543513894081116,0.9647941589355469,-0.06265555322170258],[-0.009903957135975361,0.06741295754909515,0.9976761341094971]],[[0.9689971804618835,-0.2417343407869339,-0.05107900872826576],[0.2459598183631897,0.9633893966674805,0.10670134425163269],[0.023415658622980118,-0.1159568503499031,0.9929783940315247]],[[0.941867470741272,-0.3359818756580353,-0.0014353847363963723],[0.3359754681587219,0.9418008327484131,0.011499876156449318],[-0.0025118428748100996,-0.0113137885928154,0.9999330043792725]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[0.9996333122253418,-0.0061468142084777355,-0.02637435868382454],[0.00615928927436471,0.9999812841415405,0.0003948818484786898],[0.026371527463197708,-0.0005573396338149905,0.9996522068977356]],[[0.9364164471626282,-0.34295132756233215,0.07422114908695221],[0.3449566662311554,0.9384870529174805,-0.015735777094960213],[-0.06425891071557999,0.04033815488219261,0.997117817401886]],[[0.9467210173606873,-0.32205501198768616,4.636428840854023e-08],[0.322054922580719,0.9467213153839111,-6.129761942474943e-08],[9.372781661909357e-09,-8.999508338547457e-08,1.000000238418579]],[[0.982410728931427,-0.1866968870162964,-0.003674674779176712],[0.18654502928256989,0.9821150302886963,-0.025529347360134125],[0.008375243283808231,0.024394650012254715,0.9996675252914429]],[[1.0,-5.399165914354853e-08,3.024080186264655e-08],[-5.399165914354853e-08,1.0000003576278687,-7.882910324497061e-08],[3.024080186264655e-08,-7.882910324497061e-08,1.000000238418579]],[[0.9983538389205933,-0.057158663868904114,0.004752615001052618],[0.05710673704743385,0.9983140826225281,0.010412987321615219],[-0.005339713301509619,-0.01012459397315979,0.9999346137046814]],[[0.9107372164726257,-0.35845717787742615,0.2051009088754654],[0.35850635170936584,0.9327439665794373,0.038242265582084656],[-0.20501473546028137,0.03870117664337158,0.9779936075210571]],[[0.9898684024810791,-0.1419883370399475,5.918328582765753e-08],[0.14198823273181915,0.9898686408996582,-6.623200476951752e-08],[4.9272500746155856e-08,-7.999228301969197e-08,1.0000001192092896]],[[0.9467962980270386,-0.30904620885849,-0.08981873095035553],[0.3149397373199463,0.9471571445465088,0.060884833335876465],[0.06625629216432571,-0.08593318611383438,0.994095504283905]],[[1.0000001192092896,-9.611500217943103e-08,5.342175413147743e-08],[9.53837098194299e-09,1.0000003576278687,-6.045292622047782e-08],[5.2956131924020156e-08,-9.241933440762296e-08,1.0000001192092896]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,-9.346368123885895e-11,2.1470714095528365e-11],[8.58312379503623e-12,1.0000004768371582,-1.1385103704242283e-07],[2.1471657785099296e-11,-4.4665963372381157e-08,1.0000004768371582]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]],[[1.0,1.1998419618963752e-11,2.0857204852120503e-12],[6.382799150328466e-11,1.0000001192092896,-2.5707786122097787e-08],[2.0864421301780567e-12,-6.083076442564561e-08,1.0000001192092896]]],"names77":["Hips","Spine1","Spine2","Chest","Neck1","Neck2","Head","HeadEnd","Jaw","LeftEye","RightEye","LeftShoulder","LeftArm","LeftForeArm","LeftHand","LeftHandThumb1","LeftHandThumb2","LeftHandThumb3","LeftHandThumbEnd","LeftHandIndex1","LeftHandIndex2","LeftHandIndex3","LeftHandIndex4","LeftHandIndexEnd","LeftHandMiddle1","LeftHandMiddle2","LeftHandMiddle3","LeftHandMiddle4","LeftHandMiddleEnd","LeftHandRing1","LeftHandRing2","LeftHandRing3","LeftHandRing4","LeftHandRingEnd","LeftHandPinky1","LeftHandPinky2","LeftHandPinky3","LeftHandPinky4","LeftHandPinkyEnd","RightShoulder","RightArm","RightForeArm","RightHand","RightHandThumb1","RightHandThumb2","RightHandThumb3","RightHandThumbEnd","RightHandIndex1","RightHandIndex2","RightHandIndex3","RightHandIndex4","RightHandIndexEnd","RightHandMiddle1","RightHandMiddle2","RightHandMiddle3","RightHandMiddle4","RightHandMiddleEnd","RightHandRing1","RightHandRing2","RightHandRing3","RightHandRing4","RightHandRingEnd","RightHandPinky1","RightHandPinky2","RightHandPinky3","RightHandPinky4","RightHandPinkyEnd","LeftLeg","LeftShin","LeftFoot","LeftToeBase","LeftToeEnd","RightLeg","RightShin","RightFoot","RightToeBase","RightToeEnd"],"slice30in77":[0,1,2,3,4,5,6,8,9,10,11,12,13,14,18,28,39,40,41,42,46,56,67,68,69,70,72,73,74,75],"source":"SOMA's 77-joint skeleton and Kimodo's 30-joint subset, from nv-tlabs/kimodo (Apache-2.0) kimodo/skeleton and SOMA (NVlabs/SOMA-X, Apache-2.0)"}
\ No newline at end of file
diff --git a/systems/kimodo/src/stats.rs b/systems/kimodo/src/stats.rs
new file mode 100644
index 00000000..46b1b5b2
--- /dev/null
+++ b/systems/kimodo/src/stats.rs
@@ -0,0 +1,68 @@
+//! The checkpoint's feature statistics (stats/motion/{global_root,local_root,body}/{mean,std}.npy, float64), each
+//! number normalised as (x - mean) / sqrt(std^2 + 1e-5) in f32, as Kimodo does.
+
+use std::path::Path;
+
+use anyhow::{Context, Result, bail};
+
+pub const EPS: f32 = 1e-5;
+
+pub struct Stats {
+ /// the 369 feature numbers: the global root's 5, then the body's 364
+ pub mean: Vec<f32>,
+ pub std: Vec<f32>,
+ pub mean_global_root: Vec<f32>,
+ pub std_global_root: Vec<f32>,
+ pub mean_local_root: Vec<f32>,
+ pub std_local_root: Vec<f32>,
+}
+
+/// A 1-D little-endian float64 or float32 .npy file (format 1.0 or 2.0) as f32s.
+pub fn npy(path: &Path) -> Result<Vec<f32>> {
+ let b = std::fs::read(path).with_context(|| format!("can't read {}", path.display()))?;
+ if b.len() < 10 || &b[..6] != b"\x93NUMPY" {
+ bail!("{}: not a .npy file", path.display());
+ }
+ let (hlen, start) = if b[6] == 1 { (u16::from_le_bytes([b[8], b[9]]) as usize, 10) } else { (u32::from_le_bytes([b[8], b[9], b[10], b[11]]) as usize, 12) };
+ let header = std::str::from_utf8(&b[start..start + hlen])?;
+ let data = &b[start + hlen..];
+ if header.contains("'fortran_order': True") {
+ bail!("{}: Fortran order", path.display());
+ }
+ Ok(if header.contains("'<f8'") {
+ words::<8>(data).map(f64::from_le_bytes).map(|v| v as f32).collect()
+ } else if header.contains("'<f4'") {
+ words::<4>(data).map(f32::from_le_bytes).collect()
+ } else {
+ bail!("{}: not little-endian float32 or float64 ({header})", path.display())
+ })
+}
+
+impl Stats {
+ /// From the checkpoint folder (its stats/motion/...).
+ pub fn load(ckpt: &Path) -> Result<Self> {
+ let part = |p: &str| -> Result<(Vec<f32>, Vec<f32>)> {
+ let d = ckpt.join("stats/motion").join(p);
+ let mean = npy(&d.join("mean.npy"))?;
+ let std = npy(&d.join("std.npy"))?.into_iter().map(|s| (s * s + EPS).sqrt()).collect();
+ Ok((mean, std))
+ };
+ let (mg, sg) = part("global_root")?;
+ let (ml, sl) = part("local_root")?;
+ let (mb, sb) = part("body")?;
+ anyhow::ensure!(mg.len() == 5 && ml.len() == 4 && mb.len() == 364, "kimodo: the feature statistics have the wrong sizes");
+ Ok(Stats {
+ mean: mg.iter().chain(&mb).copied().collect(),
+ std: sg.iter().chain(&sb).copied().collect(),
+ mean_global_root: mg,
+ std_global_root: sg,
+ mean_local_root: ml,
+ std_local_root: sl,
+ })
+ }
+}
+
+/// little-endian words of N bytes
+fn words<const N: usize>(data: &[u8]) -> impl Iterator<Item = [u8; N]> + '_ {
+ data.chunks_exact(N).map(|c| <[u8; N]>::try_from(c).unwrap())
+}
diff --git a/systems/kimodo/src/tests.rs b/systems/kimodo/src/tests.rs
new file mode 100644
index 00000000..14aca21d
--- /dev/null
+++ b/systems/kimodo/src/tests.rs
@@ -0,0 +1,157 @@
+//! Against the PyTorch reference (nv-tlabs/kimodo on the CPU, float32) and the float32 text encoder: fixtures made by
+//! ~/.cache/raea-kimodo/mlx (ref_torch.py, then converted to safetensors in ref/rust), the weights from the models
+//! folder or RAEA_KIMODO_DIR / RAEA_KIMODO_TEXT_DIR. A test whose files are absent says so and passes.
+//! Run one at a time (`-- --test-threads=1`): the text encoder holds 9 GB.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Once;
+
+use mlx_rs::Array;
+
+use crate::decode::DIM;
+use crate::net::f32_array;
+
+static TF32_OFF: Once = Once::new();
+
+/// float32 parity needs MLX's TF32 matmuls off, process-wide, before the first matmul
+fn exact() {
+ TF32_OFF.call_once(|| unsafe { std::env::set_var("MLX_ENABLE_TF32", "0") });
+}
+
+fn cache() -> PathBuf {
+ PathBuf::from(std::env::var("HOME").unwrap()).join(".cache/raea-kimodo/mlx")
+}
+
+fn fixture(name: &str) -> Option<HashMap<String, Array>> {
+ let p = std::env::var("RAEA_KIMODO_REF").map(PathBuf::from).unwrap_or_else(|_| cache().join("ref/rust")).join(name);
+ if !p.exists() {
+ eprintln!("skipped: no fixture {}", p.display());
+ return None;
+ }
+ Some(Array::load_safetensors(&p).unwrap())
+}
+
+fn motion_dir() -> Option<PathBuf> {
+ let d = std::env::var("RAEA_KIMODO_DIR").map(PathBuf::from).unwrap_or_else(|_| cache().join("weights/Kimodo-SOMA-RP-v1"));
+ if d.join("model.safetensors").exists() { Some(d) } else { eprintln!("skipped: no Kimodo checkpoint at {}", d.display()); None }
+}
+
+fn text_dir() -> Option<PathBuf> {
+ let d = std::env::var("RAEA_KIMODO_TEXT_DIR").map(PathBuf::from).unwrap_or_else(|_| cache().join("weights/llama3-8b-instruct-8bit"));
+ if d.join("llm2vec/mntp.safetensors").exists() { Some(d) } else { eprintln!("skipped: no text encoder at {}", d.display()); None }
+}
+
+fn v(m: &HashMap<String, Array>, k: &str) -> Vec<f32> {
+ f32_array(&m[k]).unwrap()
+}
+
+fn max_abs(a: &[f32], b: &[f32]) -> f32 {
+ assert_eq!(a.len(), b.len());
+ a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
+}
+
+#[test]
+fn sanitising_a_line_matches_kimodo() {
+ use crate::text::sanitize;
+ assert_eq!(sanitize(" a person walks forward and stops "), "A person walks forward and stops.");
+ assert_eq!(sanitize("wave at the camera"), "Wave at the camera.");
+ assert_eq!(sanitize("A drunk man staggers. then he SITS down!"), "A drunk man staggers. Then he sits down!");
+ assert_eq!(sanitize(" "), "");
+}
+
+#[test]
+fn the_denoiser_matches_pytorch() {
+ exact();
+ let (Some(r), Some(dir)) = (fixture("denoiser.safetensors"), motion_dir()) else { return };
+ let st = crate::stats::Stats::load(&dir).unwrap();
+ let net = crate::net::Net::load(&dir, &st).unwrap();
+ // A: zero text, no constraints, t = 500, 150 frames
+ let t = Array::from_slice(&[v(&r, "A_t")[0] as i32], &[1]);
+ let y = net.denoise(&r["A_x"], &[150], &mlx_rs::ops::zeros::<f32>(&[1, 1, 4096]).unwrap(), &t, &mlx_rs::ops::zeros::<f32>(&[1]).unwrap(), None).unwrap();
+ let err = max_abs(&f32_array(&y).unwrap(), &v(&r, "A_y"));
+ assert!(err < 2e-3, "A: max abs difference {err}");
+ // B: two clips of different lengths, 12 text tokens, constraints, headings; compared on each clip's own frames
+ let pad = v(&r, "B_pad");
+ let lengths: Vec<i32> = pad.chunks(120).map(|c| c.iter().filter(|&&p| p > 0.5).count() as i32).collect();
+ let tb: Vec<i32> = v(&r, "B_t").iter().map(|&x| x as i32).collect();
+ let y = net
+ .denoise(&r["B_x"], &lengths, &r["B_text"], &Array::from_slice(&tb, &[2]), &r["B_head"], Some((&r["B_mask"], &r["B_obs"])))
+ .unwrap();
+ let (got, want) = (f32_array(&y).unwrap(), v(&r, "B_y"));
+ let mut err = 0f32;
+ for (c, &l) in lengths.iter().enumerate() {
+ let s = c * 120 * DIM;
+ err = err.max(max_abs(&got[s..s + l as usize * DIM], &want[s..s + l as usize * DIM]));
+ }
+ assert!(err < 2e-3, "B: max abs difference {err} (lengths {lengths:?})");
+}
+
+#[test]
+fn a_whole_generation_matches_pytorch() {
+ exact();
+ let (Some(r), Some(dir)) = (fixture("gen_text_walk_stop.safetensors"), motion_dir()) else { return };
+ let k = crate::Kimodo::open(&dir, None).unwrap();
+ let ask = crate::Ask { line: "A person walks forward and stops.", frames: 150, seed: 0, steps: 100, constraints: None, cfg: (2.0, 2.0) };
+ let made = k.make(&ask, Some(&v(&r, "text")), Some(&v(&r, "noise"))).unwrap();
+ let want = v(&r, "posed_joints");
+ let got: Vec<f32> = made.motion.joints77.iter().flatten().flatten().copied().collect();
+ let cm: Vec<f32> = got.chunks(3).zip(want.chunks(3)).map(|(a, b)| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt() * 100.0).collect();
+ let (worst, mean) = (cm.iter().cloned().fold(0.0, f32::max), cm.iter().sum::<f32>() / cm.len() as f32);
+ eprintln!("whole generation against PyTorch: joints {mean:.4} cm mean, {worst:.4} cm worst");
+ assert!(worst < 0.05, "joints {worst} cm off at worst ({mean} mean)");
+ let contacts = v(&r, "foot_contacts");
+ let differ = made.motion.contacts.iter().flatten().zip(&contacts).filter(|(a, b)| **a != (**b > 0.5)).count();
+ assert!(differ <= 2, "{differ} foot contacts differ");
+}
+
+#[test]
+fn constraints_become_pytorchs_conditions() {
+ let (Some(r), Some(dir)) = (fixture("cond_03.safetensors"), motion_dir()) else { return };
+ let path = std::env::var("RAEA_KIMODO_REF").map(PathBuf::from).unwrap_or_else(|_| cache().join("ref/rust")).join("cond_03_constraints.json");
+ let c: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
+ let st = crate::stats::Stats::load(&dir).unwrap();
+ let sk = crate::skeleton::Skeleton::soma().unwrap();
+ let got = crate::constraints::conditions(&c, 150, &st, &sk).unwrap();
+ let (mask, obs) = (v(&r, "mask"), v(&r, "obs"));
+ assert_eq!(got.mask, mask, "the same numbers are constrained");
+ let err = got.obs.iter().zip(&got.mask).zip(obs.iter().zip(&mask)).map(|((a, m), (b, n))| (a * m - b * n).abs()).fold(0.0, f32::max);
+ assert!(err < 1e-4, "observed values {err} off (normalised units)");
+}
+
+/// `raea motion`'s chain through raea's models folder: RAEA_KIMODO_LINE (and RAEA_KIMODO_KEYS, a constraints file) to
+/// the clip file sdk/body/tools/fromkimodo.ts reads, at RAEA_KIMODO_CLIP. Skipped unless RAEA_KIMODO_CLIP is set.
+#[test]
+fn a_line_becomes_a_clip_file() {
+ let Ok(out) = std::env::var("RAEA_KIMODO_CLIP") else { return eprintln!("skipped: RAEA_KIMODO_CLIP unset") };
+ exact();
+ let line = std::env::var("RAEA_KIMODO_LINE").unwrap_or_else(|_| "a person walks forward and waves".into());
+ let keys: Option<serde_json::Value> = std::env::var("RAEA_KIMODO_KEYS").ok().map(|p| serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap());
+ let frames = std::env::var("RAEA_KIMODO_FRAMES").map(|f| f.parse().unwrap()).unwrap_or(150);
+ let t0 = std::time::Instant::now();
+ let mut k = crate::Kimodo::fetch(&mut |f, n| eprintln!("fetching {f}: {} MB", n >> 20)).unwrap();
+ let (clean, emb) = k.encode(&line).unwrap();
+ let loaded = t0.elapsed().as_secs_f64();
+ let ask = crate::Ask { line: &line, frames, seed: 1, steps: 100, constraints: keys.as_ref(), cfg: (2.0, 2.0) };
+ let made = k.make(&ask, emb.as_deref(), None).unwrap();
+ let clip = crate::decode::clip_json(&made.motion, &k.skeleton, 1, 100, &clean, keys.is_some());
+ std::fs::write(&out, clip.to_string()).unwrap();
+ eprintln!("{clean:?}: {frames} frames in {:.1} s after {loaded:.1} s loading and encoding -> {out}", t0.elapsed().as_secs_f64() - loaded);
+}
+
+#[test]
+fn the_8bit_text_encoder_matches_the_reference() {
+ exact();
+ let (Some(r), Some(dir)) = (fixture("text_walk_stop.safetensors"), text_dir()) else { return };
+ let enc = crate::text::Encoder::load(&dir).unwrap();
+ let (line, e) = enc.encode("a person walks forward and stops").unwrap();
+ assert_eq!(line, "A person walks forward and stops.");
+ let cos = |a: &[f32], b: &[f32]| {
+ let (d, na, nb) = a.iter().zip(b).fold((0f64, 0f64, 0f64), |(d, na, nb), (x, y)| (d + (*x as f64) * (*y as f64), na + (*x as f64).powi(2), nb + (*y as f64).powi(2)));
+ d / (na.sqrt() * nb.sqrt())
+ };
+ let (c8, c32) = (cos(&e, &v(&r, "q8_local")), cos(&e, &v(&r, "f32")));
+ eprintln!("8-bit encoder: cosine {c8:.6} to the Python MLX 8-bit, {c32:.6} to float32");
+ assert!(c8 > 0.99995, "cosine {c8} to the Python MLX 8-bit run");
+ assert!(c32 > 0.9998, "cosine {c32} to the float32 encoder");
+}
diff --git a/systems/kimodo/src/text.rs b/systems/kimodo/src/text.rs
new file mode 100644
index 00000000..c99f5445
--- /dev/null
+++ b/systems/kimodo/src/text.rs
@@ -0,0 +1,171 @@
+//! Kimodo's text encoder on MLX: LLM2Vec (McGill-NLP) on Llama 3 8B Instruct, 8-bit (mlx-community's, group 64), its
+//! two LoRA adapters (mntp, then supervised; rank 16, alpha 32, on every projection) run beside the quantised base in
+//! f32. Every token sees every token (LLM2Vec's bidirectional attention); the final norm's outputs are averaged over
+//! the text's own tokens and <|eot_id|>. 4096 numbers a line.
+//!
+//! Measured 11-16 against the float32 encoder on eight lines: cosine 0.99989 to 0.99993; with the same noise the
+//! motion's joints move 0.01 to 0.74 cm on average (1.44 cm at worst, a run and leap) over 5 s. 4-bit moved them 8 cm.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use anyhow::{Context, Result, anyhow};
+use mlx_rs::{Array, Dtype, fast, ops};
+use mlx_rs::ops::{QuantizedMatmulOptions, quantized_matmul};
+use raea_sys_mlx::weights::Weights;
+
+const LAYERS: usize = 32;
+const HEADS: i32 = 32;
+const KV_HEADS: i32 = 8;
+const HEAD_DIM: i32 = 128;
+const THETA: f32 = 500000.0;
+const EPS: f32 = 1e-5;
+const LORA_SCALE: f32 = 32.0 / 16.0;
+const PROJ: [&str; 7] = ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"];
+
+pub struct Encoder {
+ w: Weights,
+ /// per (layer, projection): each adapter's A [16, in] and B [out, 16]
+ lora: HashMap<(usize, &'static str), Vec<(Array, Array)>>,
+ tok: tokenizers::Tokenizer,
+ group: i32,
+ bits: i32,
+}
+
+/// kimodo.sanitize.sanitize_text (paragraph=True): one space between words, from the first letter or digit, the
+/// first letter capitalised and the rest lowered, ended with a full stop, each sentence capitalised.
+pub fn sanitize(text: &str) -> String {
+ let t = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ if t.is_empty() {
+ return t;
+ }
+ let chars: Vec<char> = t.chars().collect();
+ let start = chars.iter().position(|c| c.is_alphanumeric()).unwrap_or(chars.len() - 1);
+ let rest: String = chars[start..].iter().collect();
+ let mut it = rest.chars();
+ let mut t: String = match it.next() {
+ Some(f) => f.to_uppercase().chain(it.as_str().to_lowercase().chars()).collect(),
+ None => String::new(),
+ };
+ let chars: Vec<char> = t.chars().collect();
+ if let Some(end) = chars.iter().rposition(|c| c.is_alphanumeric() || matches!(c, '.' | '!' | '?' | '"' | ']' | ')' | '\'')) {
+ t = chars[..=end].iter().collect();
+ }
+ if !t.ends_with(['.', '!', '?']) {
+ t.push('.');
+ }
+ for brk in ['.', '!', '?'] {
+ let parts: Vec<String> = t
+ .split(brk)
+ .map(|x| {
+ let y = x.trim();
+ let mut c = y.chars();
+ match c.next() {
+ Some(f) => f.to_uppercase().chain(c).collect(),
+ None => String::new(),
+ }
+ })
+ .collect();
+ t = parts.join(&format!("{brk} ")).trim().to_string();
+ }
+ t
+}
+
+fn rms(x: &Array, w: &Array) -> Result<Array> {
+ Ok(fast::rms_norm(x, Some(&w.as_dtype(Dtype::Float32)?), EPS)?)
+}
+
+impl Encoder {
+ /// From the model folder: the 8-bit Llama's config.json and model*.safetensors, llm2vec/{mntp,supervised}.safetensors
+ /// and llm2vec/tokenizer.json.
+ pub fn load(dir: &Path) -> Result<Self> {
+ let q: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join("config.json")).context("kimodo text: no config.json")?)?;
+ let (group, bits) = (q["quantization"]["group_size"].as_i64().unwrap_or(64) as i32, q["quantization"]["bits"].as_i64().unwrap_or(8) as i32);
+ let mut shards: Vec<_> = std::fs::read_dir(dir)?.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| {
+ let n = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ n.starts_with("model") && n.ends_with(".safetensors")
+ }).collect();
+ shards.sort();
+ anyhow::ensure!(!shards.is_empty(), "kimodo text: no model*.safetensors in {}", dir.display());
+ let mut all = Vec::new();
+ for s in &shards {
+ let m = Array::load_safetensors(s).map_err(|e| anyhow!("kimodo text: can't read {}: {e:?}", s.display()))?;
+ all.extend(m.into_iter().filter(|(k, _)| !k.starts_with("lm_head")));
+ }
+ let w: Weights = all.into_iter().collect();
+ let mut lora: HashMap<(usize, &'static str), Vec<(Array, Array)>> = HashMap::new();
+ for f in ["mntp", "supervised"] {
+ let a = Weights::load(&dir.join("llm2vec").join(format!("{f}.safetensors")))?;
+ for i in 0..LAYERS {
+ for p in PROJ {
+ let k = format!("base_model.model.layers.{i}.{p}");
+ let (la, lb) = (a.get(&format!("{k}.lora_A.weight"))?.as_dtype(Dtype::Float32)?, a.get(&format!("{k}.lora_B.weight"))?.as_dtype(Dtype::Float32)?);
+ lora.entry((i, p)).or_default().push((la.transpose()?, lb.transpose()?));
+ }
+ }
+ }
+ let tok = tokenizers::Tokenizer::from_file(dir.join("llm2vec/tokenizer.json")).map_err(|e| anyhow!("kimodo text: tokenizer: {e}"))?;
+ Ok(Encoder { w, lora, tok, group, bits })
+ }
+
+ fn lin(&self, i: usize, p: &'static str, h: &Array) -> Result<Array> {
+ let k = format!("model.layers.{i}.{p}");
+ let (scales, biases) = (self.w.get(&format!("{k}.scales"))?.as_dtype(Dtype::Float32)?, self.w.get(&format!("{k}.biases"))?.as_dtype(Dtype::Float32)?);
+ let opts = QuantizedMatmulOptions { transpose: true, group_size: Some(self.group), bits: Some(self.bits), ..Default::default() };
+ let mut y = quantized_matmul(h, self.w.get(&format!("{k}.weight"))?, &scales, &biases, opts).map_err(|e| anyhow!("kimodo text: {e:?}"))?;
+ for (a, b) in &self.lora[&(i, p)] {
+ y = ops::add(&y, &ops::multiply(&h.matmul(a)?.matmul(b)?, &Array::from_f32(LORA_SCALE))?)?;
+ }
+ Ok(y)
+ }
+
+ /// A line's 4096 numbers (and the line as sanitised). An empty line is all zeros, as Kimodo's is.
+ pub fn encode(&self, line: &str) -> Result<(String, Vec<f32>)> {
+ let t = sanitize(line);
+ if t.is_empty() {
+ return Ok((t, vec![0.0; 4096]));
+ }
+ let ids = self.tok.encode(format!("<|start_header_id|>user<|end_header_id|>\n\n{t}<|eot_id|>"), true).map_err(|e| anyhow!("{e}"))?.get_ids().to_vec();
+ let n = self.tok.encode(format!("{t}<|eot_id|>"), false).map_err(|e| anyhow!("{e}"))?.get_ids().len() as i32;
+ let l = ids.len() as i32;
+ let idx = Array::from_slice(&ids.iter().map(|&i| i as i32).collect::<Vec<_>>(), &[l]);
+ let mut x = ops::indexing::take_axis(self.w.get("model.embed_tokens.weight")?, &idx, 0)?.as_dtype(Dtype::Float32)?.expand_dims(0)?;
+ // rotary tables as the reference computes them: f32, the two halves alike
+ let inv: Vec<f32> = (0..HEAD_DIM / 2).map(|k| 1.0 / THETA.powf((2 * k) as f32 / HEAD_DIM as f32)).collect();
+ let mut f = vec![0.0f32; (l * HEAD_DIM) as usize];
+ for p in 0..l as usize {
+ for k in 0..(HEAD_DIM / 2) as usize {
+ let a = p as f32 * inv[k];
+ f[p * HEAD_DIM as usize + k] = a;
+ f[p * HEAD_DIM as usize + k + (HEAD_DIM / 2) as usize] = a;
+ }
+ }
+ let cos = Array::from_slice(&f.iter().map(|a| a.cos()).collect::<Vec<_>>(), &[1, 1, l, HEAD_DIM]);
+ let sin = Array::from_slice(&f.iter().map(|a| a.sin()).collect::<Vec<_>>(), &[1, 1, l, HEAD_DIM]);
+ let rope = |a: &Array| -> Result<Array> {
+ let half = HEAD_DIM / 2;
+ let (a1, a2) = (crate::net::slice(a, 3, 0, half)?, crate::net::slice(a, 3, half, HEAD_DIM)?);
+ let rot = ops::concatenate(&[ops::negative(&a2)?, a1], 3)?;
+ Ok(ops::add(&ops::multiply(a, &cos)?, &ops::multiply(&rot, &sin)?)?)
+ };
+ for i in 0..LAYERS {
+ let h = rms(&x, self.w.get(&format!("model.layers.{i}.input_layernorm.weight"))?)?;
+ let heads = |a: Array, n: i32| -> Result<Array> { Ok(a.reshape(&[1, l, n, HEAD_DIM])?.transpose_axes(&[0, 2, 1, 3])?) };
+ let q = rope(&heads(self.lin(i, "self_attn.q_proj", &h)?, HEADS)?)?;
+ let k = rope(&heads(self.lin(i, "self_attn.k_proj", &h)?, KV_HEADS)?)?;
+ let v = heads(self.lin(i, "self_attn.v_proj", &h)?, KV_HEADS)?;
+ // no mask: every token sees every token; MLX's kernel shares each key head among four query heads
+ let a = fast::scaled_dot_product_attention(&q, &k, &v, 1.0 / (HEAD_DIM as f32).sqrt(), None, None)?;
+ let a = a.transpose_axes(&[0, 2, 1, 3])?.reshape(&[1, l, HEADS * HEAD_DIM])?;
+ x = ops::add(&x, &self.lin(i, "self_attn.o_proj", &a)?)?;
+ let h = rms(&x, self.w.get(&format!("model.layers.{i}.post_attention_layernorm.weight"))?)?;
+ let g = self.lin(i, "mlp.gate_proj", &h)?;
+ let up = self.lin(i, "mlp.up_proj", &h)?;
+ x = ops::add(&x, &self.lin(i, "mlp.down_proj", &ops::multiply(&mlx_rs::nn::silu(&g)?, &up)?)?)?;
+ x.eval()?;
+ }
+ let x = rms(&x, self.w.get("model.norm.weight")?)?;
+ let mean = crate::net::slice(&x, 1, l - n, l)?.mean_axis(1, false)?;
+ Ok((t, crate::net::f32_array(&mean)?))
+ }
+}
diff --git a/tools/layers.toml b/tools/layers.toml
index c265d08a..09fb0a33 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -55,6 +55,8 @@ raea-seedling = "systems"
raea-sys-ml = "systems"
# MLX on Apple silicon, beside raea-sys-ml's ONNX Runtime (empty on other systems)
raea-sys-mlx = "systems"
+# Kimodo's text to SOMA motion on MLX (raea motion; docs/character.feature CH15c)
+raea-sys-kimodo = "systems"
raea-sys-speech = "systems"
raea-sys-layout = "systems"
raea-sys-vision = "systems"
diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.ts
index 7be0e507..e5e3fb99 100644
--- a/tools/manual-ref/cli.ts
+++ b/tools/manual-ref/cli.ts
@@ -30,7 +30,7 @@ const GROUPS: [string, string, string[]][] = [
["Check", "What's wrong before anyone watches it.", ["check", "judge", "fingerprint", "findings", "scene", "world", "solid", "next", "doctor", "hook", "traces"]],
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio"]],
- ["Generate and 3D tools", "Generated media, physics bakes, clothes for SOMA's body, Blender and Godot.", ["gen", "physics", "clothes", "blender", "godot"]],
+ ["Generate and 3D tools", "Generated media, physics bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "clothes", "motion", "blender", "godot"]],
["Agents and setup", "What an agent reads and shows the person, and the tools raea installs.", ["guide", "context", "notes", "show", "skill", "skills", "setup"]],
]
/** A verb's page: VERB.md, but index.md is this section's own page, so raea index's is indexer.md */