From ea5fc2e5efbecfbc04113121ac3dd6c94b2c5b42 Mon Sep 17 00:00:00 2001 From: shinyobjectz Date: Tue, 10 Nov 2026 22:59:25 -0800 Subject: [PATCH] MX1, MX2: raea-sys-mlx, MLX on Apple silicon's GPU beside raea-sys-ml's ONNX Runtime (docs/mlx.feature) On mlx-rs =0.34.0 (MIT OR Apache-2.0), which builds MLX v0.32.2 from source with cmake at build time. The dependency is macOS-only, so the crate is empty on Linux and Windows. A model's MLX path is plain functions over its safetensors, read by the checkpoint's own tensor names (weights.rs), with f32 tensors in and out (tensor.rs) and layers that do PyTorch's maths (nn.rs): a Linear runs in its weight's dtype; LayerNorm, GELU and SiLU run in f32; attention is MLX's fused kernel. Tests check each layer against the same maths in plain Rust on the CPU. f32 matmuls run in TF32 on the GPU by default (within 3e-3; 1e-5 with MLX_ENABLE_TF32=0). use_metallib points MLX at a fetched metallib (MX4). No model uses it yet: IDOL, which was to be first, is held. --- Cargo.lock | 140 ++++++++++++++++++++++++++++++++-- Cargo.toml | 1 + docs/mlx.feature | 60 +++++++++++++++ systems/mlx/Cargo.toml | 15 ++++ systems/mlx/src/lib.rs | 32 ++++++++ systems/mlx/src/nn.rs | 54 +++++++++++++ systems/mlx/src/tensor.rs | 37 +++++++++ systems/mlx/src/tests.rs | 151 +++++++++++++++++++++++++++++++++++++ systems/mlx/src/weights.rs | 57 ++++++++++++++ tools/layers.toml | 3 + 10 files changed, 543 insertions(+), 7 deletions(-) create mode 100644 docs/mlx.feature create mode 100644 systems/mlx/Cargo.toml create mode 100644 systems/mlx/src/lib.rs create mode 100644 systems/mlx/src/nn.rs create mode 100644 systems/mlx/src/tensor.rs create mode 100644 systems/mlx/src/tests.rs create mode 100644 systems/mlx/src/weights.rs diff --git a/Cargo.lock b/Cargo.lock index 5adc6b30..c688332a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4165,6 +4165,8 @@ dependencies = [ "cexpr", "clang-sys", "itertools 0.13.0", + "log", + "prettyplease", "proc-macro2", "quote", "regex", @@ -5677,8 +5679,18 @@ version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] @@ -5695,17 +5707,41 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim 0.11.1", + "syn 3.0.9", +] + [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core", + "darling_core 0.20.11", "quote", "syn 2.0.119", ] +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.9", +] + [[package]] name = "dary_heap" version = "0.3.9" @@ -5858,7 +5894,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0df63c21a4383f94bd5388564829423f35c316aed85dc4f8427aded372c7c0d" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.119", @@ -6171,7 +6207,7 @@ version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.119", @@ -10117,6 +10153,15 @@ version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619" +[[package]] +name = "mach-sys" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48460c2e82a3a0de197152fdf8d2c2d5e43adc501501553e439bf2156e6f87c7" +dependencies = [ + "fastrand", +] + [[package]] name = "mach2" version = "0.4.3" @@ -10415,6 +10460,66 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "mlx-internal-macros" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f11a82b6a4730c2c3778469d186cc3ee9585a5b27a8ffcdfd3c96179b76a895d" +dependencies = [ + "darling 0.24.1", + "itertools 0.15.0", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "mlx-macros" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32fc73395b87b961f5556e10104e7c08ed72c500765f44d38e320a6ac83977ed" +dependencies = [ + "darling 0.24.1", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "mlx-rs" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0d7721525b23f77bc38d7757e6c17ea7c925cd2b2889ce86965a17b5e85e86" +dependencies = [ + "dyn-clone", + "half", + "itertools 0.15.0", + "libc", + "mach-sys", + "mlx-internal-macros", + "mlx-macros", + "mlx-sys", + "num-complex", + "num-traits", + "num_enum", + "parking_lot", + "paste", + "smallvec", + "strum 0.28.0", + "thiserror 2.0.21", +] + +[[package]] +name = "mlx-sys" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da965f83ce211b80f9b681d9bbd6fa625fe6bb2e659ba7bc55dd95eea8d3b028" +dependencies = [ + "bindgen", + "cc", + "cmake", +] + [[package]] name = "mock_instant" version = "0.6.1" @@ -13214,6 +13319,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + [[package]] name = "primal-check" version = "0.3.4" @@ -15740,6 +15855,14 @@ dependencies = [ "ureq 2.12.1", ] +[[package]] +name = "raea-sys-mlx" +version = "0.1.0" +dependencies = [ + "anyhow", + "mlx-rs", +] + [[package]] name = "raea-sys-page" version = "0.1.0" @@ -18683,6 +18806,9 @@ name = "strum" version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros 0.28.0", +] [[package]] name = "strum_macros" @@ -18792,7 +18918,7 @@ version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ee5c550c2e00a0b3c046bef84a9ee217e04e7c014142eeb96f9e48781c5cfd3" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.119", @@ -19979,7 +20105,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f8e91a023810fd2019648410d00eea13a71f21d849e71d6d9ed936fb8061174" dependencies = [ - "darling", + "darling 0.20.11", "proc-macro2", "quote", "syn 2.0.119", diff --git a/Cargo.toml b/Cargo.toml index 52010003..9caae175 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,6 +78,7 @@ members = [ "systems/tone", "systems/mix", "systems/ml", + "systems/mlx", "systems/speech", "systems/layout", "systems/vision", diff --git a/docs/mlx.feature b/docs/mlx.feature new file mode 100644 index 00000000..b6668e5a --- /dev/null +++ b/docs/mlx.feature @@ -0,0 +1,60 @@ +@spec +Feature: MLX: local models on Apple silicon's GPU (systems/mlx, raea-sys-mlx) + Shane, 2026-11-10, told IDOL could run on MLX: "we should just do mlx anyway makes no sense not to support mlx + generally going forward". Then, holding IDOL: "just have mlx support". On this M5 Pro Mac, ort's CPU kernels are the + fastest ONNX path and too slow for big models. ort's Core ML provider has been slower still, and Core ML's GPU + computes some models wrong (SigLIP: cosine 0.855 against the CPU's 0.98). MLX runs on the GPU directly. + + So raea-sys-mlx sits beside raea-sys-ml's ONNX Runtime: + - Each model gets an MLX path on the Mac. + - ONNX stays the path on Windows and Linux, and the cross-platform reference. + - The facility reaches users only once a model and a verb use it. + + Background: + Given mlx-rs =0.34.0 (crates.io, MIT OR Apache-2.0, maintained), which builds MLX v0.32.2 from source at build + time. Its cmake clones MLX from GitHub, and Xcode's Metal toolchain compiles the kernels. + And a model's MLX path is plain functions over its safetensors, keyed by the checkpoint's own tensor names, so it + reads the same files as its PyTorch and ONNX paths + + Rule: the facility builds where MLX runs, and nowhere else + @done + Scenario: MX1. raea-sys-mlx links MLX on the Mac and is empty on Linux and Windows + Then on macOS the crate links MLX and runs on the GPU (`on_gpu`) + And on Linux and Windows it compiles to nothing and brings no MLX in: the dependency is macOS-only + And 11-10, measured on the M5 Pro with renders sharing the GPU: a 4096^3 matmul runs at 9.2 TFLOPS in f32 and + 11.5 TFLOPS in f16 + + Rule: its layers do PyTorch's maths, so a model's numbers can be matched + @done + Scenario: MX2. Each layer matches the same maths written out on the CPU + Then linear, layer norm, attention, GELU (tanh) and SiLU agree with plain Rust on the CPU + (systems/mlx/src/tests.rs) + And the tolerance is 1e-5, or 3e-3 for an f32 matmul or attention, which MLX runs in TF32 on the GPU unless + MLX_ENABLE_TF32=0 (with it set, all of them agree to 1e-5) + And a Linear runs in its weight's dtype and a LayerNorm in f32, as PyTorch's do, so a model's mixed precision + can be mirrored + And weights load from safetensors by name, and a missing name is an error that names it + + Scenario: MX3. A model's MLX path is checked against its reference before it becomes the Mac default + Given a model with a PyTorch or ONNX path + Then each of its networks is compared with the reference on the same inputs (cosine and max error), against a bar + written in the model's own feature file + And the end-to-end output is compared the same way + And the Mac default is picked by parity first, then speed, with both times stated + + Rule: the metallib reaches the user's Mac + Scenario: MX4. A Mac without Xcode runs an MLX op from the signed raea + Given MLX loads mlx.metallib (184 MB, 59 MB gzipped) at run time. It looks, in order: the path set by + `use_metallib`, beside the binary, Resources/, then the build machine's path (~/.mlx/lib/) + Then with the first model, the metallib either: + - arrives with that model's files on first use, sha256-pinned and from a models release, then `use_metallib` + - or ships beside raea in the Mac tarball and the app + And release.yml's Mac job builds the crate + + Rule: models use it + Scenario: MX5. The first model runs on MLX on the Mac + # IDOL (one image to a 3D Gaussian splat) was to be the first. It was held 11-10 (docs/handoff/idol.md, "Parked + # 11-10"), with its six-network seam agreed. + # Next candidates: + # - SigLIP (perception's embeddings), which Core ML's GPU computes wrong on this Mac + # - any local model whose ONNX run on the Mac's CPU is too slow to use diff --git a/systems/mlx/Cargo.toml b/systems/mlx/Cargo.toml new file mode 100644 index 00000000..0b2dba90 --- /dev/null +++ b/systems/mlx/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "raea-sys-mlx" +version = "0.1.0" +edition = "2024" +publish = false +description = "raea's MLX facility: models run on Apple silicon's GPU through MLX (mlx-rs), beside raea-sys-ml's ONNX Runtime" +license = "FSL-1.1-ALv2" + +[dependencies] +anyhow = "1" + +# MLX is Apple silicon's: on other systems the crate is empty and pulls nothing in +[target.'cfg(target_os = "macos")'.dependencies] +mlx-rs = "=0.34.0" + diff --git a/systems/mlx/src/lib.rs b/systems/mlx/src/lib.rs new file mode 100644 index 00000000..e0f57b86 --- /dev/null +++ b/systems/mlx/src/lib.rs @@ -0,0 +1,32 @@ +//! raea's MLX facility (docs/mlx.feature): models run on Apple silicon's GPU through MLX (mlx-rs, MIT OR Apache-2.0), +//! beside raea-sys-ml's ONNX Runtime, which stays the path on Windows and Linux and the cross-platform reference. +//! +//! A model's MLX path is written as plain functions over a [`weights::Weights`] map keyed by the checkpoint's own +//! tensor names, so it reads the same safetensors files its PyTorch and ONNX paths do, with the layers in [`nn`] +//! matching PyTorch's numerics. No model uses it yet (IDOL, its first, is held: docs/handoff/idol.md). +//! +//! Precision: MLX runs f32 matmuls (and attention) on the GPU in TF32 unless MLX_ENABLE_TF32=0 is in the environment +//! when the process makes its first matmul, process-wide (like PyTorch's `allow_tf32`; about 1e-3 relative). A model +//! whose parity bar needs exact f32 says so; most run in f16 or bf16 anyway. +//! +//! The crate is empty on every OS but macOS. +#![cfg(target_os = "macos")] + +pub mod nn; +pub mod tensor; +pub mod weights; + +#[cfg(test)] +mod tests; + +/// Points MLX at the metallib to load, ahead of one next to the binary and the path baked in at build time (raea is +/// to fetch it with a model's files on first use, docs/mlx.feature MX4). Call before the first MLX operation. +pub fn use_metallib(path: &std::path::Path) -> anyhow::Result<()> { + mlx_rs::metal::set_metallib_path(path.to_string_lossy()) + .map_err(|e| anyhow::anyhow!("mlx: can't use metallib {}: {e}", path.display())) +} + +/// Whether MLX runs on the GPU here (it falls back to the CPU only where Metal is missing). +pub fn on_gpu() -> bool { + mlx_rs::Device::default() == mlx_rs::Device::gpu() +} diff --git a/systems/mlx/src/nn.rs b/systems/mlx/src/nn.rs new file mode 100644 index 00000000..653e1523 --- /dev/null +++ b/systems/mlx/src/nn.rs @@ -0,0 +1,54 @@ +//! Layers shared by the networks, written to match PyTorch's numerics where they differ from MLX's defaults: a Linear +//! runs in its weight's dtype, a LayerNorm in f32, GELU and SiLU in f32 (PyTorch's opmath on half tensors). + +use anyhow::Result; +use mlx_rs::{Array, Dtype, fast, ops}; + +use crate::weights::Weights; + +pub fn cast(x: &Array, dtype: Dtype) -> Result { + Ok(if x.dtype() == dtype { x.clone() } else { x.as_dtype(dtype)? }) +} + +pub fn f32(x: &Array) -> Result { + cast(x, Dtype::Float32) +} + +/// `nn.Linear` at `prefix`: y = x W^T + b, in W's dtype (the input is cast to it, as IDOL's `.type()` calls do). +pub fn linear(w: &Weights, prefix: &str, x: &Array) -> Result { + let weight = w.get(&format!("{prefix}.weight"))?; + let x = cast(x, weight.dtype())?; + let y = x.matmul(&weight.transpose()?)?; + Ok(match w.opt(&format!("{prefix}.bias")) { + Some(b) => ops::add(&y, &cast(b, weight.dtype())?)?, + None => y, + }) +} + +/// LayerNorm over the last axis, computed in f32 and returned in x's dtype (IDOL's LayerNorm32, F.layer_norm). +pub fn layer_norm(x: &Array, weight: Option<&Array>, bias: Option<&Array>, eps: f32) -> Result { + let y = fast::layer_norm(f32(x)?, weight, bias, eps)?; + cast(&y, x.dtype()) +} + +/// `nn.LayerNorm` at `prefix` with its affine parameters, in f32. +pub fn layer_norm_at(w: &Weights, prefix: &str, x: &Array, eps: f32) -> Result { + let weight = w.opt(&format!("{prefix}.weight")); + let bias = w.opt(&format!("{prefix}.bias")); + layer_norm(x, weight, bias, eps) +} + +/// An elementwise op (an activation) computed in f32 and returned in x's dtype, as PyTorch computes one on a half +/// tensor: `in_f32(&x, mlx_rs::nn::gelu_approximate)` is GELU (tanh), with mlx_rs::nn's gelu and silu alike. +pub fn in_f32(x: &Array, op: impl Fn(Array) -> mlx_rs::error::Result) -> Result { + cast(&op(f32(x)?)?, x.dtype()) +} + +/// Attention over [B, L, H, D] queries and [B, S, H, D] keys and values -> [B, L, H, D], scaled by 1/sqrt(D) with no +/// mask (PyTorch's F.scaled_dot_product_attention defaults). MLX's fused kernel never forms the L x S matrix. +pub fn attention(q: &Array, k: &Array, v: &Array) -> Result { + let d = *q.shape().last().unwrap() as f32; + let (q, k, v) = (q.swap_axes(1, 2)?, k.swap_axes(1, 2)?, v.swap_axes(1, 2)?); + let o = fast::scaled_dot_product_attention(&q, &k, &v, 1.0 / d.sqrt(), None, None)?; + Ok(o.swap_axes(1, 2)?) +} diff --git a/systems/mlx/src/tensor.rs b/systems/mlx/src/tensor.rs new file mode 100644 index 00000000..8a1fd3fb --- /dev/null +++ b/systems/mlx/src/tensor.rs @@ -0,0 +1,37 @@ +//! Plain f32 tensors in and out of MLX, the form a backend seam passes (raea-sys-ml's model traits). + +use anyhow::{Result, anyhow}; +use mlx_rs::{Array, Dtype}; + +#[derive(Clone, Debug, PartialEq)] +pub struct Tensor { + pub shape: Vec, + pub data: Vec, +} + +impl Tensor { + pub fn new(shape: Vec, data: Vec) -> Result { + let n: usize = shape.iter().product(); + if n != data.len() { + return Err(anyhow!("tensor: shape {shape:?} holds {n} values, given {}", data.len())); + } + Ok(Self { shape, data }) + } + + pub fn zeros(shape: Vec) -> Self { + let n = shape.iter().product(); + Self { shape, data: vec![0.0; n] } + } + + pub fn to_array(&self) -> Array { + let shape: Vec = self.shape.iter().map(|&d| d as i32).collect(); + Array::from_slice(&self.data, &shape) + } + + pub fn from_array(a: &Array) -> Result { + // a strided view (a transpose, a slice) is copied to row-major first + let a = if a.dtype() == Dtype::Float32 { a.clone() } else { a.as_dtype(Dtype::Float32)? }.contiguous()?; + a.eval()?; + Ok(Self { shape: a.shape().iter().map(|&d| d as usize).collect(), data: a.as_slice::().to_vec() }) + } +} diff --git a/systems/mlx/src/tests.rs b/systems/mlx/src/tests.rs new file mode 100644 index 00000000..38db2604 --- /dev/null +++ b/systems/mlx/src/tests.rs @@ -0,0 +1,151 @@ +//! Each layer on the GPU against the same maths written out on the CPU in plain Rust (docs/mlx.feature MX2). + +use mlx_rs::{Array, Dtype}; + +use crate::nn; +use crate::tensor::Tensor; +use crate::weights::Weights; + +/// The bound on an f32 matmul's error for values near 1. MLX runs f32 matmuls in TF32 on the GPU by default +/// (MLX_ENABLE_TF32=1): about 1e-3 off here (11-10: 1.2e-3 on the linear test). With MLX_ENABLE_TF32=0 all of these +/// pass at 1e-5. A wrong transpose or axis is off by order 1, so the bound still catches the bugs it's for. +const MATMUL_F32: f32 = 3e-3; + +/// Deterministic values in -1..1 (no rand dependency). +fn values(n: usize, seed: u64) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 + }) + .collect() +} + +fn read(a: &Array) -> Vec { + Tensor::from_array(a).unwrap().data +} + +fn max_err(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) +} + +fn linear_weights(o: usize, i: usize, dtype: Dtype) -> (Weights, Vec, Vec) { + let (w, b) = (values(o * i, 1), values(o, 2)); + let mut weights: Weights = + [("fc.weight", Array::from_slice(&w, &[o as i32, i as i32])), ("fc.bias", Array::from_slice(&b, &[o as i32]))] + .into_iter() + .collect(); + weights.cast_where(dtype, |_| true).unwrap(); + (weights, w, b) +} + +#[test] +fn runs_on_the_gpu() { + assert!(crate::on_gpu(), "MLX's default device on this Mac should be the GPU"); +} + +#[test] +fn linear_matches_the_cpu() { + let (n, i, o) = (6, 8, 5); + let (weights, w, b) = linear_weights(o, i, Dtype::Float32); + let x = values(n * i, 3); + let y = nn::linear(&weights, "fc", &Array::from_slice(&x, &[2, 3, i as i32])).unwrap(); + assert_eq!(y.shape(), &[2, 3, o as i32]); + let want: Vec = (0..n) + .flat_map(|r| (0..o).map(move |c| (r, c))) + .map(|(r, c)| b[c] + (0..i).map(|k| x[r * i + k] * w[c * i + k]).sum::()) + .collect(); + let got = read(&y); + let err = max_err(&got, &want); + assert!(err < MATMUL_F32, "max error {err}: got {:?}, want {:?}", &got[..5], &want[..5]); +} + +#[test] +fn a_half_linear_runs_in_half_and_stays_close() { + let (weights, _, _) = linear_weights(5, 8, Dtype::Float16); + let (full, _, _) = linear_weights(5, 8, Dtype::Float32); + let x = Array::from_slice(&values(24, 3), &[3, 8]); + let half = nn::linear(&weights, "fc", &x).unwrap(); + assert_eq!(half.dtype(), Dtype::Float16, "an f16 Linear casts its input and answers in f16, as PyTorch's does"); + assert!(max_err(&read(&half), &read(&nn::linear(&full, "fc", &x).unwrap())) < 1e-2); +} + +#[test] +fn layer_norm_matches_the_cpu_and_keeps_the_input_dtype() { + let (rows, d) = (4, 16); + let x = values(rows * d, 4); + let y = nn::layer_norm(&Array::from_slice(&x, &[rows as i32, d as i32]), None, None, 1e-6).unwrap(); + let want: Vec = x + .chunks(d) + .flat_map(|r| { + let mean = r.iter().sum::() / d as f32; + let var = r.iter().map(|v| (v - mean).powi(2)).sum::() / d as f32; + r.iter().map(move |v| (v - mean) / (var + 1e-6).sqrt()).collect::>() + }) + .collect(); + assert!(max_err(&read(&y), &want) < 1e-5); + let half = Array::from_slice(&x, &[rows as i32, d as i32]).as_dtype(Dtype::Float16).unwrap(); + assert_eq!(nn::layer_norm(&half, None, None, 1e-6).unwrap().dtype(), Dtype::Float16); +} + +#[test] +fn attention_matches_the_cpu() { + let (l, s, h, d) = (5, 7, 2, 4); + let (q, k, v) = (values(l * h * d, 5), values(s * h * d, 6), values(s * h * d, 7)); + let arr = |x: &[f32], n: usize| Array::from_slice(x, &[1, n as i32, h as i32, d as i32]); + let o = nn::attention(&arr(&q, l), &arr(&k, s), &arr(&v, s)).unwrap(); + assert_eq!(o.shape(), &[1, l as i32, h as i32, d as i32]); + let at = |x: &[f32], t: usize, head: usize, c: usize| x[(t * h + head) * d + c]; + let mut want = vec![0.0; l * h * d]; + for head in 0..h { + for t in 0..l { + let scores: Vec = (0..s) + .map(|u| (0..d).map(|c| at(&q, t, head, c) * at(&k, u, head, c)).sum::() / (d as f32).sqrt()) + .collect(); + let top = scores.iter().cloned().fold(f32::MIN, f32::max); + let e: Vec = scores.iter().map(|x| (x - top).exp()).collect(); + let z: f32 = e.iter().sum(); + for c in 0..d { + want[(t * h + head) * d + c] = (0..s).map(|u| e[u] / z * at(&v, u, head, c)).sum(); + } + } + } + assert!(max_err(&read(&o), &want) < MATMUL_F32); +} + +#[test] +fn activations_match_their_formulas() { + let x = values(32, 8); + let a = Array::from_slice(&x, &[32]); + let tanh_gelu: Vec = x + .iter() + .map(|v| 0.5 * v * (1.0 + ((2.0 / std::f32::consts::PI).sqrt() * (v + 0.044715 * v.powi(3))).tanh())) + .collect(); + assert!(max_err(&read(&nn::in_f32(&a, mlx_rs::nn::gelu_approximate).unwrap()), &tanh_gelu) < 1e-5); + let silu: Vec = x.iter().map(|v| v / (1.0 + (-v).exp())).collect(); + assert!(max_err(&read(&nn::in_f32(&a, mlx_rs::nn::silu).unwrap()), &silu) < 1e-6); +} + +#[test] +fn weights_load_from_safetensors_by_name() { + let dir = std::env::temp_dir().join(format!("raea-sys-mlx-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("w.safetensors"); + let w = Array::from_slice(&values(6, 9), &[2, 3]); + Array::save_safetensors([("block.0.fc.weight", &w)], None, &path).unwrap(); + let loaded = Weights::load(&path); + std::fs::remove_dir_all(&dir).unwrap(); + let loaded = loaded.unwrap(); + assert_eq!(loaded.count(), 6); + assert_eq!(read(loaded.get("block.0.fc.weight").unwrap()), read(&w)); + assert!(loaded.get("block.1.fc.weight").unwrap_err().to_string().contains("block.1.fc.weight")); +} + +#[test] +fn tensors_round_trip() { + let t = Tensor::new(vec![2, 3], values(6, 10)).unwrap(); + assert_eq!(Tensor::from_array(&t.to_array()).unwrap(), t); + assert!(Tensor::new(vec![2, 2], vec![0.0; 3]).is_err()); +} diff --git a/systems/mlx/src/weights.rs b/systems/mlx/src/weights.rs new file mode 100644 index 00000000..df56e78f --- /dev/null +++ b/systems/mlx/src/weights.rs @@ -0,0 +1,57 @@ +//! A model's tensors by their checkpoint names, loaded from safetensors. + +use std::collections::HashMap; +use std::path::Path; + +use anyhow::{Context, Result, anyhow}; +use mlx_rs::{Array, Dtype}; + +pub struct Weights { + map: HashMap, +} + +impl Weights { + pub fn load(path: &Path) -> Result { + let map = Array::load_safetensors(path).map_err(|e| anyhow!("weights: can't read {}: {e:?}", path.display()))?; + Ok(Self { map }) + } + + /// The tensor named `key`; its absence is an error that names it. + pub fn get(&self, key: &str) -> Result<&Array> { + self.opt(key).with_context(|| format!("weights: no tensor {key}")) + } + + pub fn opt(&self, key: &str) -> Option<&Array> { + self.map.get(key) + } + + /// Casts every tensor whose name `pick` accepts to `dtype`, as PyTorch's `module.half()` on part of a model does. + pub fn cast_where(&mut self, dtype: Dtype, pick: impl Fn(&str) -> bool) -> Result<()> { + for (key, value) in self.map.iter_mut() { + if pick(key) && value.dtype() != dtype { + *value = value.as_dtype(dtype)?; + } + } + Ok(()) + } + + /// Evaluates every tensor (loads them onto the device now rather than on first use). + pub fn eval(&self) -> Result<()> { + for value in self.map.values() { + value.eval()?; + } + Ok(()) + } + + /// The number of parameters. + pub fn count(&self) -> usize { + self.map.values().map(|a| a.size()).sum() + } +} + +/// Tensors made in code (a converted checkpoint, a test's), by name. +impl> FromIterator<(K, Array)> for Weights { + fn from_iter>(tensors: I) -> Self { + Self { map: tensors.into_iter().map(|(k, a)| (k.into(), a)).collect() } + } +} diff --git a/tools/layers.toml b/tools/layers.toml index 2395e1ad..d9a19f68 100644 --- a/tools/layers.toml +++ b/tools/layers.toml @@ -52,6 +52,8 @@ raea-sys-mix = "systems" raea-sys-tone = "systems" 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" raea-sys-speech = "systems" raea-sys-layout = "systems" raea-sys-vision = "systems" @@ -227,6 +229,7 @@ raea-sys-rt = true raea-sys-mix = true raea-sys-tone = true raea-sys-ml = true +raea-sys-mlx = true raea-sys-layout = true raea-sys-vision = true # a file's encoder columns (Fingerprint's heads read them)