Files
raea/systems/mlx/src/tensor.rs
shinyobjectz ea5fc2e5ef 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.
2026-11-12 21:28:48 -08:00

38 lines
1.2 KiB
Rust

//! 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<usize>,
pub data: Vec<f32>,
}
impl Tensor {
pub fn new(shape: Vec<usize>, data: Vec<f32>) -> Result<Self> {
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<usize>) -> Self {
let n = shape.iter().product();
Self { shape, data: vec![0.0; n] }
}
pub fn to_array(&self) -> Array {
let shape: Vec<i32> = self.shape.iter().map(|&d| d as i32).collect();
Array::from_slice(&self.data, &shape)
}
pub fn from_array(a: &Array) -> Result<Self> {
// 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::<f32>().to_vec() })
}
}