M13.35: Roto Brush trained model — swappable segment module, MobileSAM in pure Rust

- New L1 crate effectcraft-segment: the MaskModel interface (prompts → foreground probability),
  a registry of open-licensed models (licence must be MIT/Apache/BSD/…; URL, size, SHA-256),
  a PyTorch checkpoint reader (zip + pickle subset), dependency-free SHA-256, and MobileSAM
  (TinyViT-5M + SAM prompt encoder / two-way transformer / mask decoder) on rayon and ndarray's
  safe GEMM. Loads the official mobile_sam.pt as published; checked against candle
  (embedding 0.3% RMS, 99.9% equal mask pixels); ~0.7 s/frame encoder at 32 threads, cached
  per frame, ~0.1 s decoder.
- track::roto: segment_with / propagate_with prompt a model with the strokes or the flow-warped
  matte (box, core points, mask); its probability is a strong, unblurred prior for the same
  graph cut (strokes stay hard constraints); a failing model or one disagreeing with the flow
  (IoU < 0.5) is ignored. Prior gets a weight.
- effects::roto: Version 2.0 / 3.0 use the model chosen in Settings (set_model / model_for);
  the model id is part of the chain seed.
- engine: roto_models (roto.models, roto.model.select / install / download / remove), weights in
  the models folder (host::config_dir()/models, shared by the app, CLI and MCP), background
  loading, downloads through the system curl, verified; Settings ▸ Roto Brush page (prefs
  roto.model). host::config_dir moved from the desktop app.
- Tests: segment (kernels vs direct sums, checkpoint reader, SHA-256 vectors, registry), track
  (fake model: prior shapes the cut, failing / disagreeing models ignored; real weights with
  EFFECTCRAFT_MOBILESAM: base IoU 0.989, propagated ≥ 0.980 vs classic 0.973), engine (registry,
  verification, selection; real install + load), MCP.
- Docs: README, ROADMAP, parity (MSK-4 done: 90/2/0), preferences, agents, architecture,
  crates/segment/README.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatastic
2026-10-05 17:55:02 +07:00
co-authored by Claude Opus 5.5
parent 11d4885764
commit 7579de21c6
32 changed files with 2774 additions and 53 deletions
+211
View File
@@ -0,0 +1,211 @@
//! Trained segmentation models for Roto Brush, behind one swappable interface.
//!
//! - [`MaskModel`]: what Roto Brush asks of a model, the foreground probability of each pixel of a
//! frame given prompts (foreground / background points from the strokes, a box, a prior mask).
//! Anything implementing it can be plugged in; the classical graph-cut segmenter in
//! `effectcraft-track` stays the built-in fallback when no model is chosen.
//! - [`MODELS`]: the registry. Every entry is open source under a licence compatible with
//! EffectCraft's (MIT OR Apache-2.0), with its source, size and SHA-256. Weights are never
//! bundled: they are fetched on demand (or installed from a file), verified ([`sha256`]) and
//! loaded by [`load`].
//! - [`pt`]: a PyTorch checkpoint reader, so official weights load as published.
//! - [`mobilesam`]: MobileSAM (Apache-2.0) in plain Rust ([`nn`] kernels on rayon).
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::todo, clippy::unreachable)]
pub mod mobilesam;
pub mod nn;
pub mod pt;
use std::sync::Arc;
pub type Result<T> = std::result::Result<T, String>;
/// What a model is asked: coordinates in frame pixels.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Prompt {
/// Points and whether each is foreground (`true`) or background.
pub points: Vec<([f32; 2], bool)>,
/// A box around the object: `[x0, y0, x1, y1]`.
pub bbox: Option<[f32; 4]>,
/// A prior: the foreground probability of every pixel (`w×h`), e.g. the previous frame's
/// matte carried forward.
pub mask: Option<Vec<f32>>,
}
/// A trained segmentation model (swappable: Roto Brush only uses this interface).
pub trait MaskModel: Send + Sync {
fn info(&self) -> &'static ModelInfo;
/// Foreground probability (0–1) of each pixel of a frame (straight RGB 0–1, row-major `w×h`).
fn segment(&self, rgb: &[[f32; 3]], w: usize, h: usize, prompt: &Prompt) -> Result<Vec<f32>>;
}
/// A model in the registry: what it is, its licence and where its weights come from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ModelInfo {
pub id: &'static str,
pub name: &'static str,
pub description: &'static str,
/// SPDX licence of the weights and the architecture.
pub licence: &'static str,
pub licence_url: &'static str,
/// The project's page.
pub homepage: &'static str,
/// The official weights file.
pub url: &'static str,
pub file_name: &'static str,
pub size: u64,
/// SHA-256 of the weights file (lower-case hex).
pub sha256: &'static str,
}
/// Licences a model may have to be listed (open source, compatible with MIT OR Apache-2.0).
pub const ALLOWED_LICENCES: &[&str] = &["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Zlib", "CC0-1.0"];
pub const MOBILE_SAM: ModelInfo = ModelInfo {
id: "mobilesam",
name: "MobileSAM",
description: "Segment Anything distilled to a 5M-parameter TinyViT encoder (C. Zhang et al., 2023). Turns your strokes into a clean matte and tidies every propagated frame.",
licence: "Apache-2.0",
licence_url: "https://github.com/ChaoningZhang/MobileSAM/blob/master/LICENSE",
homepage: "https://github.com/ChaoningZhang/MobileSAM",
url: "https://raw.githubusercontent.com/ChaoningZhang/MobileSAM/master/weights/mobile_sam.pt",
file_name: "mobile_sam.pt",
size: 40_728_226,
sha256: "6dbb90523a35330fedd7f1d3dfc66f995213d81b29a5ca8108dbcdd4e37d6c2f",
};
/// The models Roto Brush can use besides the built-in classical segmenter.
pub const MODELS: &[ModelInfo] = &[MOBILE_SAM];
/// The id of the built-in classical (graph cut) segmenter: no weights, always available.
pub const CLASSICAL: &str = "classical";
pub fn info(id: &str) -> Option<&'static ModelInfo> {
MODELS.iter().find(|m| m.id == id)
}
/// Check a weights file against the registry and build the model.
pub fn load(id: &str, bytes: &[u8]) -> Result<Arc<dyn MaskModel>> {
let info = info(id).ok_or_else(|| format!("unknown model `{id}`"))?;
if !ALLOWED_LICENCES.contains(&info.licence) {
return Err(format!("{}: licence {} is not allowed", info.name, info.licence));
}
let got = sha256::hex(bytes);
if got != info.sha256 {
return Err(format!("{}: the file does not match (SHA-256 {got}, expected {})", info.name, info.sha256));
}
match id {
"mobilesam" => {
let w = pt::read(bytes)?;
Ok(Arc::new(Sam { net: mobilesam::MobileSam::from_weights(&w)? }))
}
_ => Err(format!("no loader for `{id}`")),
}
}
struct Sam {
net: mobilesam::MobileSam,
}
impl MaskModel for Sam {
fn info(&self) -> &'static ModelInfo {
&MOBILE_SAM
}
fn segment(&self, rgb: &[[f32; 3]], w: usize, h: usize, prompt: &Prompt) -> Result<Vec<f32>> {
let e = self.net.embed(rgb, w, h)?;
Ok(self.net.predict(&e, prompt).0)
}
}
/// SHA-256 (FIPS 180-4), to verify downloaded weights without another dependency.
pub mod sha256 {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
pub fn digest(data: &[u8]) -> [u8; 32] {
let mut h: [u32; 8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
let bits = (data.len() as u64).wrapping_mul(8);
let mut tail = data[data.len() - data.len() % 64..].to_vec();
tail.push(0x80);
while tail.len() % 64 != 56 {
tail.push(0);
}
tail.extend_from_slice(&bits.to_be_bytes());
for block in data[..data.len() - data.len() % 64].chunks_exact(64).chain(tail.chunks_exact(64)) {
let mut w = [0u32; 64];
for (i, c) in block.chunks_exact(4).enumerate() {
w[i] = u32::from_be_bytes([c[0], c[1], c[2], c[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ (!e & g);
let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
for (x, y) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
*x = x.wrapping_add(y);
}
}
let mut out = [0u8; 32];
for (i, v) in h.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&v.to_be_bytes());
}
out
}
pub fn hex(data: &[u8]) -> String {
digest(data).iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod tests {
#[test]
fn known_vectors() {
assert_eq!(super::hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
assert_eq!(super::hex(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
let long = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
assert_eq!(super::hex(long), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
assert_eq!(super::hex(&vec![b'a'; 1_000_000]), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_is_open_source_and_verifies_files() {
for m in MODELS {
assert!(ALLOWED_LICENCES.contains(&m.licence), "{}", m.id);
assert_eq!(m.sha256.len(), 64);
assert!(m.url.starts_with("https://"));
}
// A file that isn't the published one is refused before anything is parsed.
assert!(load("mobilesam", b"not the weights").err().is_some_and(|e| e.contains("does not match")));
assert!(load("nope", b"").is_err());
}
}
+677
View File
@@ -0,0 +1,677 @@
//! MobileSAM (C. Zhang et al., "Faster Segment Anything: Towards Lightweight SAM for Mobile
//! Applications", 2023; Apache-2.0) in plain Rust: the TinyViT-5M image encoder (Wu et al.,
//! "TinyViT", ECCV 2022) feeding Segment Anything's prompt encoder and two-way-transformer mask
//! decoder (Kirillov et al., "Segment Anything", ICCV 2023), loaded straight from the official
//! `mobile_sam.pt` checkpoint. The image goes in at 1024 pixels on its long side; the encoder
//! gives a 64×64×256 embedding, cached per image so that new prompts on the same frame only run
//! the (fast) decoder.
use std::f32::consts::PI;
use std::sync::Mutex;
use rayon::prelude::*;
use crate::nn::{self, Conv, Depthwise, Linear, Norm, Upconv};
use crate::pt::Weights;
use crate::{Prompt, Result};
const IMG: usize = 1024;
const EMB: usize = 64;
const DIM: usize = 256;
const LOW: usize = 256;
const MEAN: [f32; 3] = [123.675, 116.28, 103.53];
const STD: [f32; 3] = [58.395, 57.12, 57.375];
/// Weight lookup by name with the expected element count.
struct W<'a>(&'a Weights);
impl W<'_> {
fn get(&self, name: &str, n: usize) -> Result<&[f32]> {
let t = self.0.get(name).ok_or_else(|| format!("checkpoint is missing {name}"))?;
if t.data.len() != n {
return Err(format!("{name}: expected {n} values, found {}", t.data.len()));
}
Ok(&t.data)
}
fn linear(&self, p: &str, out: usize, inp: usize, bias: bool) -> Result<Linear> {
let w = self.get(&format!("{p}.weight"), out * inp)?;
let b = if bias { Some(self.get(&format!("{p}.bias"), out)?) } else { None };
Linear::new(w, b, out, inp).ok_or_else(|| format!("{p}: bad shape"))
}
fn norm(&self, p: &str, c: usize, eps: f32) -> Result<Norm> {
Ok(Norm { w: self.get(&format!("{p}.weight"), c)?.to_vec(), b: self.get(&format!("{p}.bias"), c)?.to_vec(), eps })
}
/// A conv + batch norm (eval) folded into one weight and bias: `[out × inp/groups × k × k]`.
fn conv_bn(&self, p: &str, out: usize, per: usize) -> Result<(Vec<f32>, Vec<f32>)> {
let w = self.get(&format!("{p}.c.weight"), out * per)?;
let g = self.get(&format!("{p}.bn.weight"), out)?;
let b = self.get(&format!("{p}.bn.bias"), out)?;
let m = self.get(&format!("{p}.bn.running_mean"), out)?;
let v = self.get(&format!("{p}.bn.running_var"), out)?;
let mut wf = w.to_vec();
let mut bf = vec![0.0; out];
for o in 0..out {
let s = g[o] / (v[o] + 1e-5).sqrt();
wf[o * per..(o + 1) * per].iter_mut().for_each(|x| *x *= s);
bf[o] = b[o] - m[o] * s;
}
Ok((wf, bf))
}
fn pointwise_bn(&self, p: &str, out: usize, inp: usize) -> Result<Linear> {
let (w, b) = self.conv_bn(p, out, inp)?;
Linear::new(&w, Some(&b), out, inp).ok_or_else(|| format!("{p}: bad shape"))
}
fn depthwise_bn(&self, p: &str, c: usize, stride: usize) -> Result<Depthwise> {
let (w, b) = self.conv_bn(p, c, 9)?;
Depthwise::new(&w, Some(&b), c, stride).ok_or_else(|| format!("{p}: bad shape"))
}
fn conv3_bn(&self, p: &str, out: usize, inp: usize, stride: usize) -> Result<Conv> {
let (w, b) = self.conv_bn(p, out, inp * 9)?;
Conv::new(&w, Some(&b), out, inp, 3, stride, 1).ok_or_else(|| format!("{p}: bad shape"))
}
}
/// MBConv: 1×1 expand, depthwise 3×3, 1×1 project, residual.
struct MbConv {
c1: Linear,
c2: Depthwise,
c3: Linear,
}
impl MbConv {
fn forward(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let mut t = self.c1.forward(x, h * w);
nn::gelu(&mut t);
let (mut t, _, _) = self.c2.forward(&t, h, w);
nn::gelu(&mut t);
let mut t = self.c3.forward(&t, h * w);
nn::add(&mut t, x);
nn::gelu(&mut t);
t
}
}
/// Patch merging between stages: 1×1, depthwise 3×3 (stride 2, or 1 into the last stage), 1×1.
struct Merge {
c1: Linear,
c2: Depthwise,
c3: Linear,
}
impl Merge {
fn forward(&self, x: &[f32], h: usize, w: usize) -> (Vec<f32>, usize, usize) {
let mut t = self.c1.forward(x, h * w);
nn::gelu(&mut t);
let (mut t, oh, ow) = self.c2.forward(&t, h, w);
nn::gelu(&mut t);
(self.c3.forward(&t, oh * ow), oh, ow)
}
}
/// A TinyViT block: windowed attention (with learned relative-position biases), a depthwise
/// "local conv", then an MLP.
struct Block {
norm: Norm,
qkv: Linear,
proj: Linear,
/// `[heads × n × n]` for the `ws × ws` window.
bias: Vec<f32>,
heads: usize,
ws: usize,
local: Depthwise,
mlp_norm: Norm,
fc1: Linear,
fc2: Linear,
}
impl Block {
fn new(w: &W, p: &str, dim: usize, heads: usize, ws: usize) -> Result<Block> {
let n = ws * ws;
// Offsets between window positions, numbered in first-seen order (as TinyViT does).
let points: Vec<(i64, i64)> = (0..ws as i64).flat_map(|r| (0..ws as i64).map(move |c| (r, c))).collect();
let mut offsets: Vec<(i64, i64)> = vec![];
let mut idx = Vec::with_capacity(n * n);
for a in &points {
for b in &points {
let o = ((a.0 - b.0).abs(), (a.1 - b.1).abs());
let i = match offsets.iter().position(|x| *x == o) {
Some(i) => i,
None => {
offsets.push(o);
offsets.len() - 1
}
};
idx.push(i);
}
}
let table = w.get(&format!("{p}.attn.attention_biases"), heads * offsets.len())?;
let no = offsets.len();
let bias = (0..heads).flat_map(|h| idx.iter().map(move |i| table[h * no + i])).collect::<Vec<f32>>();
Ok(Block {
norm: w.norm(&format!("{p}.attn.norm"), dim, 1e-5)?,
qkv: w.linear(&format!("{p}.attn.qkv"), 3 * dim, dim, true)?,
proj: w.linear(&format!("{p}.attn.proj"), dim, dim, true)?,
bias,
heads,
ws,
local: w.depthwise_bn(&format!("{p}.local_conv"), dim, 1)?,
mlp_norm: w.norm(&format!("{p}.mlp.norm"), dim, 1e-5)?,
fc1: w.linear(&format!("{p}.mlp.fc1"), 4 * dim, dim, true)?,
fc2: w.linear(&format!("{p}.mlp.fc2"), dim, 4 * dim, true)?,
})
}
fn forward(&self, x: &mut Vec<f32>, h: usize, w: usize) {
let dim = self.proj.out;
let (ws, heads) = (self.ws, self.heads);
let hd = dim / heads;
// Pad the grid to whole windows (zeros, as TinyViT does), then norm + qkv once.
let (ph, pw) = (h.div_ceil(ws) * ws, w.div_ceil(ws) * ws);
let mut pad = vec![0.0f32; ph * pw * dim];
for y in 0..h {
pad[y * pw * dim..(y * pw + w) * dim].copy_from_slice(&x[y * w * dim..(y + 1) * w * dim]);
}
self.norm.forward(&mut pad);
let qkv = self.qkv.forward(&pad, ph * pw);
// Per window: gather q, k, v (each head's qkv is [q | k | v]), attend.
let (nwy, nwx) = (ph / ws, pw / ws);
let n = ws * ws;
let outs: Vec<Vec<f32>> = (0..nwy * nwx)
.into_par_iter()
.map(|win| {
let (wy, wx) = (win / nwx, win % nwx);
let (mut q, mut k, mut v) = (vec![0.0f32; n * dim], vec![0.0f32; n * dim], vec![0.0f32; n * dim]);
for t in 0..n {
let (ty, tx) = (wy * ws + t / ws, wx * ws + t % ws);
let src = &qkv[(ty * pw + tx) * 3 * dim..][..3 * dim];
for hh in 0..heads {
let s = &src[hh * 3 * hd..][..3 * hd];
q[t * dim + hh * hd..][..hd].copy_from_slice(&s[..hd]);
k[t * dim + hh * hd..][..hd].copy_from_slice(&s[hd..2 * hd]);
v[t * dim + hh * hd..][..hd].copy_from_slice(&s[2 * hd..]);
}
}
nn::attention(&q, &k, &v, n, n, heads, hd, Some(&self.bias))
})
.collect();
// Un-window into the real grid, project, residual.
let mut a = vec![0.0f32; h * w * dim];
for (win, o) in outs.iter().enumerate() {
let (wy, wx) = (win / nwx, win % nwx);
for t in 0..n {
let (ty, tx) = (wy * ws + t / ws, wx * ws + t % ws);
if ty < h && tx < w {
a[(ty * w + tx) * dim..][..dim].copy_from_slice(&o[t * dim..][..dim]);
}
}
}
let a = self.proj.forward(&a, h * w);
nn::add(x, &a);
// Local depthwise conv (no residual), then the MLP with its residual.
let (lc, _, _) = self.local.forward(x, h, w);
*x = lc;
let mut m = x.clone();
self.mlp_norm.forward(&mut m);
let mut m = self.fc1.forward(&m, h * w);
nn::gelu(&mut m);
let m = self.fc2.forward(&m, h * w);
nn::add(x, &m);
}
}
/// The TinyViT-5M encoder with SAM's neck.
struct Encoder {
pe1: Conv,
pe2: Conv,
stage0: Vec<MbConv>,
merges: Vec<Merge>,
stages: Vec<Vec<Block>>,
neck1: Linear,
neck_ln1: Norm,
neck2: Conv,
neck_ln2: Norm,
}
const DIMS: [usize; 4] = [64, 128, 160, 320];
const DEPTHS: [usize; 4] = [2, 2, 6, 2];
const HEADS: [usize; 4] = [2, 4, 5, 10];
const WINDOWS: [usize; 4] = [7, 7, 14, 7];
impl Encoder {
fn new(w: &W) -> Result<Encoder> {
let p = "image_encoder";
let stage0 = (0..DEPTHS[0])
.map(|i| {
let b = format!("{p}.layers.0.blocks.{i}");
Ok(MbConv {
c1: w.pointwise_bn(&format!("{b}.conv1"), DIMS[0] * 4, DIMS[0])?,
c2: w.depthwise_bn(&format!("{b}.conv2"), DIMS[0] * 4, 1)?,
c3: w.pointwise_bn(&format!("{b}.conv3"), DIMS[0], DIMS[0] * 4)?,
})
})
.collect::<Result<Vec<_>>>()?;
let mut merges = vec![];
let mut stages = vec![];
for l in 0..3 {
let (inp, out) = (DIMS[l], DIMS[l + 1]);
let d = format!("{p}.layers.{l}.downsample");
merges.push(Merge {
c1: w.pointwise_bn(&format!("{d}.conv1"), out, inp)?,
c2: w.depthwise_bn(&format!("{d}.conv2"), out, if out == 320 { 1 } else { 2 })?,
c3: w.pointwise_bn(&format!("{d}.conv3"), out, out)?,
});
let s = l + 1;
stages
.push((0..DEPTHS[s]).map(|i| Block::new(w, &format!("{p}.layers.{s}.blocks.{i}"), DIMS[s], HEADS[s], WINDOWS[s])).collect::<Result<Vec<_>>>()?);
}
let n2 = w.get(&format!("{p}.neck.2.weight"), DIM * DIM * 9)?;
Ok(Encoder {
pe1: w.conv3_bn(&format!("{p}.patch_embed.seq.0"), DIMS[0] / 2, 3, 2)?,
pe2: w.conv3_bn(&format!("{p}.patch_embed.seq.2"), DIMS[0], DIMS[0] / 2, 2)?,
stage0,
merges,
stages,
neck1: w.linear(&format!("{p}.neck.0"), DIM, DIMS[3], false)?,
neck_ln1: w.norm(&format!("{p}.neck.1"), DIM, 1e-6)?,
neck2: Conv::new(n2, None, DIM, DIM, 3, 1, 1).ok_or("neck: bad shape")?,
neck_ln2: w.norm(&format!("{p}.neck.3"), DIM, 1e-6)?,
})
}
/// `IMG×IMG×3` normalised pixels → `EMB×EMB×DIM`.
fn forward(&self, x: &[f32]) -> Vec<f32> {
let (mut t, h, w) = self.pe1.forward(x, IMG, IMG);
nn::gelu(&mut t);
let (mut t, mut h, mut w) = {
let (t2, h2, w2) = self.pe2.forward(&t, h, w);
(t2, h2, w2)
};
for b in &self.stage0 {
t = b.forward(&t, h, w);
}
for (m, blocks) in self.merges.iter().zip(&self.stages) {
let (t2, h2, w2) = m.forward(&t, h, w);
(t, h, w) = (t2, h2, w2);
for b in blocks {
b.forward(&mut t, h, w);
}
}
let mut t = self.neck1.forward(&t, h * w);
self.neck_ln1.forward(&mut t);
let (mut t, _, _) = self.neck2.forward(&t, h, w);
self.neck_ln2.forward(&mut t);
t
}
}
/// SAM's attention with optional down-projection (`internal = DIM / rate`).
struct Attn {
q: Linear,
k: Linear,
v: Linear,
out: Linear,
}
impl Attn {
fn new(w: &W, p: &str, rate: usize) -> Result<Attn> {
let i = DIM / rate;
Ok(Attn {
q: w.linear(&format!("{p}.q_proj"), i, DIM, true)?,
k: w.linear(&format!("{p}.k_proj"), i, DIM, true)?,
v: w.linear(&format!("{p}.v_proj"), i, DIM, true)?,
out: w.linear(&format!("{p}.out_proj"), DIM, i, true)?,
})
}
fn forward(&self, q: &[f32], nq: usize, k: &[f32], v: &[f32], nk: usize) -> Vec<f32> {
let (q, k, v) = (self.q.forward(q, nq), self.k.forward(k, nk), self.v.forward(v, nk));
let heads = 8;
let o = nn::attention(&q, &k, &v, nq, nk, heads, self.q.out / heads, None);
self.out.forward(&o, nq)
}
}
fn plus(a: &[f32], b: &[f32]) -> Vec<f32> {
a.iter().zip(b).map(|(x, y)| x + y).collect()
}
struct TwoWayBlock {
self_attn: Attn,
norm1: Norm,
t2i: Attn,
norm2: Norm,
lin1: Linear,
lin2: Linear,
norm3: Norm,
i2t: Attn,
norm4: Norm,
skip_pe: bool,
}
/// The decoder: prompt encoder, two-way transformer, mask head.
struct Decoder {
gauss: Vec<f32>,
/// `EMB×EMB×DIM` positional encoding of the embedding grid.
dense_pe: Vec<f32>,
point_embed: [Vec<f32>; 4],
not_a_point: Vec<f32>,
no_mask: Vec<f32>,
md1: Conv,
md_ln1: Norm,
md2: Conv,
md_ln2: Norm,
md3: Linear,
blocks: Vec<TwoWayBlock>,
final_attn: Attn,
norm_final: Norm,
iou_token: Vec<f32>,
mask_tokens: Vec<f32>,
up1: Upconv,
up_ln: Norm,
up2: Upconv,
hyper: Vec<[Linear; 3]>,
iou_head: [Linear; 3],
}
impl Decoder {
fn new(w: &W) -> Result<Decoder> {
let pe = "prompt_encoder";
let md = "mask_decoder";
let gauss = w.get(&format!("{pe}.pe_layer.positional_encoding_gaussian_matrix"), 2 * DIM / 2)?.to_vec();
let pt = |i: usize| w.get(&format!("{pe}.point_embeddings.{i}.weight"), DIM).map(<[f32]>::to_vec);
let conv = |p: &str, out: usize, inp: usize, ks: usize| -> Result<Conv> {
let wt = w.get(&format!("{p}.weight"), out * inp * ks * ks)?;
let b = w.get(&format!("{p}.bias"), out)?;
Conv::new(wt, Some(b), out, inp, ks, 2, 0).ok_or_else(|| format!("{p}: bad shape"))
};
let blocks = (0..2)
.map(|i| {
let p = format!("{md}.transformer.layers.{i}");
Ok(TwoWayBlock {
self_attn: Attn::new(w, &format!("{p}.self_attn"), 1)?,
norm1: w.norm(&format!("{p}.norm1"), DIM, 1e-5)?,
t2i: Attn::new(w, &format!("{p}.cross_attn_token_to_image"), 2)?,
norm2: w.norm(&format!("{p}.norm2"), DIM, 1e-5)?,
lin1: w.linear(&format!("{p}.mlp.lin1"), 2048, DIM, true)?,
lin2: w.linear(&format!("{p}.mlp.lin2"), DIM, 2048, true)?,
norm3: w.norm(&format!("{p}.norm3"), DIM, 1e-5)?,
i2t: Attn::new(w, &format!("{p}.cross_attn_image_to_token"), 2)?,
norm4: w.norm(&format!("{p}.norm4"), DIM, 1e-5)?,
skip_pe: i == 0,
})
})
.collect::<Result<Vec<_>>>()?;
let upconv = |p: &str, inp: usize, out: usize| -> Result<Upconv> {
Upconv::new(w.get(&format!("{p}.weight"), inp * out * 4)?, w.get(&format!("{p}.bias"), out)?, inp, out).ok_or_else(|| format!("{p}: bad shape"))
};
let mlp3 = |p: &str, out: usize| -> Result<[Linear; 3]> {
Ok([
w.linear(&format!("{p}.layers.0"), DIM, DIM, true)?,
w.linear(&format!("{p}.layers.1"), DIM, DIM, true)?,
w.linear(&format!("{p}.layers.2"), out, DIM, true)?,
])
};
let mut d = Decoder {
gauss,
dense_pe: vec![],
point_embed: [pt(0)?, pt(1)?, pt(2)?, pt(3)?],
not_a_point: w.get(&format!("{pe}.not_a_point_embed.weight"), DIM)?.to_vec(),
no_mask: w.get(&format!("{pe}.no_mask_embed.weight"), DIM)?.to_vec(),
md1: conv(&format!("{pe}.mask_downscaling.0"), 4, 1, 2)?,
md_ln1: w.norm(&format!("{pe}.mask_downscaling.1"), 4, 1e-6)?,
md2: conv(&format!("{pe}.mask_downscaling.3"), 16, 4, 2)?,
md_ln2: w.norm(&format!("{pe}.mask_downscaling.4"), 16, 1e-6)?,
md3: w.linear(&format!("{pe}.mask_downscaling.6"), DIM, 16, true)?,
blocks,
final_attn: Attn::new(w, &format!("{md}.transformer.final_attn_token_to_image"), 2)?,
norm_final: w.norm(&format!("{md}.transformer.norm_final_attn"), DIM, 1e-5)?,
iou_token: w.get(&format!("{md}.iou_token.weight"), DIM)?.to_vec(),
mask_tokens: w.get(&format!("{md}.mask_tokens.weight"), 4 * DIM)?.to_vec(),
up1: upconv(&format!("{md}.output_upscaling.0"), DIM, DIM / 4)?,
up_ln: w.norm(&format!("{md}.output_upscaling.1"), DIM / 4, 1e-6)?,
up2: upconv(&format!("{md}.output_upscaling.3"), DIM / 4, DIM / 8)?,
hyper: (0..4).map(|i| mlp3(&format!("{md}.output_hypernetworks_mlps.{i}"), DIM / 8)).collect::<Result<Vec<_>>>()?,
iou_head: mlp3(&format!("{md}.iou_prediction_head"), 4)?,
};
d.dense_pe = (0..EMB * EMB).flat_map(|i| d.pe(((i % EMB) as f32 + 0.5) / EMB as f32, ((i / EMB) as f32 + 0.5) / EMB as f32)).collect();
Ok(d)
}
/// Random Fourier positional encoding of a point in [0, 1]².
fn pe(&self, x: f32, y: f32) -> Vec<f32> {
let half = DIM / 2;
let (cx, cy) = (2.0 * x - 1.0, 2.0 * y - 1.0);
let a: Vec<f32> = (0..half).map(|j| 2.0 * PI * (cx * self.gauss[j] + cy * self.gauss[half + j])).collect();
a.iter().map(|v| v.sin()).chain(a.iter().map(|v| v.cos())).collect()
}
fn mlp3(layers: &[Linear; 3], x: &[f32]) -> Vec<f32> {
let mut t = layers[0].forward(x, 1);
nn::relu(&mut t);
let mut t = layers[1].forward(&t, 1);
nn::relu(&mut t);
layers[2].forward(&t, 1)
}
/// Mask logits (`LOW×LOW`, in the padded `IMG` square) and their predicted IoU for the
/// prompt (coordinates already in `IMG` space).
fn forward(&self, emb: &[f32], points: &[([f32; 2], bool)], bbox: Option<[f32; 4]>, mask: Option<&[f32]>, multimask: bool) -> (Vec<f32>, f32) {
// Sparse prompt tokens.
let mut sparse: Vec<f32> = vec![];
for (p, fg) in points {
let mut e = self.pe((p[0] + 0.5) / IMG as f32, (p[1] + 0.5) / IMG as f32);
let add = &self.point_embed[usize::from(*fg)];
e.iter_mut().zip(add).for_each(|(a, b)| *a += b);
sparse.extend(e);
}
match bbox {
Some(b) => {
for (i, (x, y)) in [(b[0], b[1]), (b[2], b[3])].into_iter().enumerate() {
let mut e = self.pe((x + 0.5) / IMG as f32, (y + 0.5) / IMG as f32);
e.iter_mut().zip(&self.point_embed[2 + i]).for_each(|(a, b)| *a += b);
sparse.extend(e);
}
}
// Points without a box get a padding "not a point".
None if !points.is_empty() => sparse.extend(&self.not_a_point),
None => {}
}
// Dense prompt: the mask input, or "no mask".
let dense: Vec<f32> = match mask {
Some(m) if m.len() == LOW * LOW => {
let (mut t, h, w) = self.md1.forward(m, LOW, LOW);
self.md_ln1.forward(&mut t);
nn::gelu(&mut t);
let (mut t, h, w) = self.md2.forward(&t, h, w);
self.md_ln2.forward(&mut t);
nn::gelu(&mut t);
self.md3.forward(&t, h * w)
}
_ => (0..EMB * EMB).flat_map(|_| self.no_mask.iter().copied()).collect(),
};
// Tokens: IoU, four mask tokens, prompts.
let mut tokens: Vec<f32> = self.iou_token.clone();
tokens.extend(&self.mask_tokens);
tokens.extend(&sparse);
let nt = tokens.len() / DIM;
let nk = EMB * EMB;
let mut keys = plus(emb, &dense);
let pe = &self.dense_pe;
let qpe = tokens.clone();
let mut queries = tokens;
for b in &self.blocks {
// Self attention.
queries = if b.skip_pe {
b.self_attn.forward(&queries, nt, &queries, &queries, nt)
} else {
let q = plus(&queries, &qpe);
plus(&queries, &b.self_attn.forward(&q, nt, &q, &queries, nt))
};
b.norm1.forward(&mut queries);
// Tokens to image.
let q = plus(&queries, &qpe);
let k = plus(&keys, pe);
queries = plus(&queries, &b.t2i.forward(&q, nt, &k, &keys, nk));
b.norm2.forward(&mut queries);
// MLP.
let mut m = b.lin1.forward(&queries, nt);
nn::relu(&mut m);
queries = plus(&queries, &b.lin2.forward(&m, nt));
b.norm3.forward(&mut queries);
// Image to tokens.
let q = plus(&queries, &qpe);
let k = plus(&keys, pe);
keys = plus(&keys, &b.i2t.forward(&k, nk, &q, &queries, nt));
b.norm4.forward(&mut keys);
}
let q = plus(&queries, &qpe);
let k = plus(&keys, pe);
queries = plus(&queries, &self.final_attn.forward(&q, nt, &k, &keys, nk));
self.norm_final.forward(&mut queries);
// Upscale the image tokens 4× and dot them with each mask token's hypernetwork output.
let mut up = self.up1.forward(&keys, EMB, EMB);
self.up_ln.forward(&mut up);
nn::gelu(&mut up);
let mut up = self.up2.forward(&up, 2 * EMB, 2 * EMB);
nn::gelu(&mut up);
let c = DIM / 8;
let iou = Self::mlp3(&self.iou_head, &queries[..DIM]);
let pick = if multimask { (1..4).max_by(|a, b| iou[*a].total_cmp(&iou[*b])).unwrap_or(0) } else { 0 };
let hyper = Self::mlp3(&self.hyper[pick], &queries[(1 + pick) * DIM..][..DIM]);
let logits: Vec<f32> = up.par_chunks(c).map(|px| px.iter().zip(&hyper).map(|(a, b)| a * b).sum()).collect();
(logits, iou.get(pick).copied().unwrap_or(0.0))
}
}
/// An image's embedding and how it was fitted into the model's square.
#[derive(Clone)]
pub struct Embedding {
pub data: Vec<f32>,
pub w: usize,
pub h: usize,
/// Image pixels → model pixels.
pub scale: f32,
}
pub struct MobileSam {
enc: Encoder,
dec: Decoder,
/// The last image embedded (by content hash): new prompts on the same frame reuse it.
cache: Mutex<Option<(u64, Embedding)>>,
}
fn hash_rgb(rgb: &[[f32; 3]], w: usize, h: usize) -> u64 {
let mut s: u64 = 0xcbf2_9ce4_8422_2325 ^ ((w as u64) << 32 | h as u64);
for p in rgb.iter().step_by(7) {
for v in p {
s = (s ^ v.to_bits() as u64).wrapping_mul(0x0100_0000_01b3);
}
}
s
}
impl MobileSam {
pub fn from_weights(w: &Weights) -> Result<MobileSam> {
let w = W(w);
Ok(MobileSam { enc: Encoder::new(&w)?, dec: Decoder::new(&w)?, cache: Mutex::new(None) })
}
/// Embed an image (straight RGB 0–1, row-major `w×h`), or reuse the last embedding.
pub fn embed(&self, rgb: &[[f32; 3]], w: usize, h: usize) -> Result<Embedding> {
if w == 0 || h == 0 || rgb.len() != w * h {
return Err("empty image".into());
}
let key = hash_rgb(rgb, w, h);
if let Ok(c) = self.cache.lock()
&& let Some((k, e)) = c.as_ref()
&& *k == key
{
return Ok(e.clone());
}
let scale = IMG as f32 / w.max(h) as f32;
let (rw, rh) = (((w as f32 * scale).round() as usize).clamp(1, IMG), ((h as f32 * scale).round() as usize).clamp(1, IMG));
// Resize (box filter when shrinking, bilinear when growing), normalise, pad.
let mut x = vec![0.0f32; IMG * IMG * 3];
x.par_chunks_mut(IMG * 3).enumerate().take(rh).for_each(|(y, row)| {
for xo in 0..rw {
let px = sample(rgb, w, h, (xo as f32 + 0.5) / scale, (y as f32 + 0.5) / scale, 1.0 / scale);
for c in 0..3 {
row[xo * 3 + c] = (px[c] * 255.0 - MEAN[c]) / STD[c];
}
}
});
let e = Embedding { data: self.enc.forward(&x), w, h, scale };
if let Ok(mut c) = self.cache.lock() {
*c = Some((key, e.clone()));
}
Ok(e)
}
/// Foreground probability (`w×h`) for a prompt on an embedded image, and the predicted IoU.
pub fn predict(&self, e: &Embedding, prompt: &Prompt) -> (Vec<f32>, f32) {
let s = e.scale;
let points: Vec<([f32; 2], bool)> = prompt.points.iter().map(|(p, fg)| ([p[0] * s, p[1] * s], *fg)).collect();
let bbox = prompt.bbox.map(|b| b.map(|v| v * s));
// A prior mask (probabilities at image size) → logits on the low-res grid.
let mask: Option<Vec<f32>> = prompt.mask.as_ref().filter(|m| m.len() == e.w * e.h).map(|m| {
(0..LOW * LOW)
.map(|i| {
let (gx, gy) = (((i % LOW) as f32 + 0.5) * 4.0 / s, ((i / LOW) as f32 + 0.5) * 4.0 / s);
if gx >= e.w as f32 || gy >= e.h as f32 {
return -20.0;
}
let p = m[(gy as usize).min(e.h - 1) * e.w + (gx as usize).min(e.w - 1)];
((p - 0.5) * 40.0).clamp(-20.0, 20.0)
})
.collect()
});
let multimask = points.len() == 1 && bbox.is_none() && mask.is_none();
let (logits, iou) = self.dec.forward(&e.data, &points, bbox, mask.as_deref(), multimask);
// Low-res logits (the padded square) → image pixels, bilinear, then sigmoid.
let prob: Vec<f32> = (0..e.w * e.h)
.into_par_iter()
.map(|i| {
let (x, y) = ((i % e.w) as f32 + 0.5, (i / e.w) as f32 + 0.5);
let (u, v) = (x * s / 4.0 - 0.5, y * s / 4.0 - 0.5);
let l = bilinear(&logits, LOW, LOW, u, v);
1.0 / (1.0 + (-l).exp())
})
.collect();
(prob, iou)
}
}
fn bilinear(g: &[f32], w: usize, h: usize, u: f32, v: f32) -> f32 {
let (u, v) = (u.clamp(0.0, (w - 1) as f32), v.clamp(0.0, (h - 1) as f32));
let (x0, y0) = (u.floor() as usize, v.floor() as usize);
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
let (fx, fy) = (u - x0 as f32, v - y0 as f32);
let at = |x: usize, y: usize| g.get(y * w + x).copied().unwrap_or(0.0);
(at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx) * (1.0 - fy) + (at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx) * fy
}
/// The image's colour around `(x, y)`: a `foot`-pixel box average when shrinking, else bilinear.
fn sample(rgb: &[[f32; 3]], w: usize, h: usize, x: f32, y: f32, foot: f32) -> [f32; 3] {
if foot <= 1.0 {
let (u, v) = ((x - 0.5).clamp(0.0, (w - 1) as f32), (y - 0.5).clamp(0.0, (h - 1) as f32));
let (x0, y0) = (u.floor() as usize, v.floor() as usize);
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
let (fx, fy) = (u - x0 as f32, v - y0 as f32);
let p = |x: usize, y: usize| rgb[y * w + x];
return [0, 1, 2].map(|c| (p(x0, y0)[c] * (1.0 - fx) + p(x1, y0)[c] * fx) * (1.0 - fy) + (p(x0, y1)[c] * (1.0 - fx) + p(x1, y1)[c] * fx) * fy);
}
let r = foot / 2.0;
let (xa, xb) = (((x - r).floor().max(0.0)) as usize, ((x + r).ceil() as usize).min(w));
let (ya, yb) = (((y - r).floor().max(0.0)) as usize, ((y + r).ceil() as usize).min(h));
let mut s = [0.0f32; 3];
let mut n = 0.0;
for yy in ya..yb.max(ya + 1).min(h) {
for xx in xa..xb.max(xa + 1).min(w) {
let p = rgb[yy * w + xx];
for c in 0..3 {
s[c] += p[c];
}
n += 1.0;
}
}
s.map(|v| v / f32::max(n, 1.0))
}
+432
View File
@@ -0,0 +1,432 @@
//! The few neural-network kernels MobileSAM needs, on token-major feature maps (`[pixels, channels]`
//! row-major, i.e. NHWC with a batch of one): dense layers on a parallel GEMM (ndarray's safe
//! `general_mat_mul`, which picks AVX/FMA kernels at run time), convolutions as patch matrices
//! times weights, depthwise and transposed convolutions, layer norm, exact GELU and softmax.
//! Weights are re-laid out once at load so every inner loop runs over contiguous channels.
use ndarray::linalg::general_mat_mul;
use ndarray::{ArrayView2, ArrayViewMut2};
use rayon::prelude::*;
/// Rows of the left matrix per parallel task.
const ROW_BLOCK: usize = 64;
/// `out[m×n] += a[m×k] · b[k×n]` (row-major), rows split across threads.
pub fn gemm(a: &[f32], m: usize, k: usize, b: &[f32], n: usize, out: &mut [f32]) {
if m == 0 || n == 0 || a.len() < m * k || b.len() < k * n || out.len() < m * n {
return;
}
let Ok(bv) = ArrayView2::from_shape((k, n), &b[..k * n]) else { return };
let block = |r0: usize, oc: &mut [f32]| {
let rows = oc.len() / n;
if let (Ok(av), Ok(mut cv)) = (ArrayView2::from_shape((rows, k), &a[r0 * k..(r0 + rows) * k]), ArrayViewMut2::from_shape((rows, n), oc)) {
general_mat_mul(1.0, &av, &bv, 1.0, &mut cv);
}
};
if m <= ROW_BLOCK {
block(0, &mut out[..m * n]);
} else {
out[..m * n].par_chunks_mut(ROW_BLOCK * n).enumerate().for_each(|(i, oc)| block(i * ROW_BLOCK, oc));
}
}
/// A dense layer (also a 1×1 convolution): `y = x·Wᵀ + b`, with `W` stored transposed.
#[derive(Clone, Debug, Default)]
pub struct Linear {
/// `[inp × out]`.
pub wt: Vec<f32>,
pub b: Vec<f32>,
pub inp: usize,
pub out: usize,
}
impl Linear {
/// From PyTorch's `[out × inp]` weight (a 1×1 conv's `[out × inp × 1 × 1]` too).
pub fn new(w: &[f32], b: Option<&[f32]>, out: usize, inp: usize) -> Option<Linear> {
if w.len() != out * inp || b.is_some_and(|b| b.len() != out) {
return None;
}
let mut wt = vec![0.0; inp * out];
for o in 0..out {
for i in 0..inp {
wt[i * out + o] = w[o * inp + i];
}
}
Some(Linear { wt, b: b.map_or_else(|| vec![0.0; out], <[f32]>::to_vec), inp, out })
}
/// `rows` tokens of `inp` channels → `rows × out`.
pub fn forward(&self, x: &[f32], rows: usize) -> Vec<f32> {
let mut y: Vec<f32> = (0..rows).flat_map(|_| self.b.iter().copied()).collect();
gemm(x, rows, self.inp, &self.wt, self.out, &mut y);
y
}
}
/// A `ks×ks` convolution (any stride and padding, one group) on `h×w×inp` → `oh×ow×out`, as a
/// patch matrix times the weights, built a block of output rows at a time.
#[derive(Clone, Debug, Default)]
pub struct Conv {
/// `[(ky·ks + kx)·inp + ci] × out`.
pub wt: Vec<f32>,
pub b: Vec<f32>,
pub inp: usize,
pub out: usize,
pub ks: usize,
pub stride: usize,
pub pad: usize,
}
impl Conv {
/// From PyTorch's `[out × inp × ks × ks]`.
pub fn new(w: &[f32], b: Option<&[f32]>, out: usize, inp: usize, ks: usize, stride: usize, pad: usize) -> Option<Conv> {
if w.len() != out * inp * ks * ks || b.is_some_and(|b| b.len() != out) || stride == 0 {
return None;
}
let kk = ks * ks * inp;
let mut wt = vec![0.0; kk * out];
for o in 0..out {
for ci in 0..inp {
for t in 0..ks * ks {
wt[(t * inp + ci) * out + o] = w[(o * inp + ci) * ks * ks + t];
}
}
}
Some(Conv { wt, b: b.map_or_else(|| vec![0.0; out], <[f32]>::to_vec), inp, out, ks, stride, pad })
}
pub fn out_size(&self, n: usize) -> usize {
(n + 2 * self.pad).saturating_sub(self.ks) / self.stride + 1
}
pub fn forward(&self, x: &[f32], h: usize, w: usize) -> (Vec<f32>, usize, usize) {
let (oh, ow) = (self.out_size(h), self.out_size(w));
let kk = self.ks * self.ks * self.inp;
let mut y: Vec<f32> = (0..oh * ow).flat_map(|_| self.b.iter().copied()).collect();
if x.len() < h * w * self.inp {
return (y, oh, ow);
}
y.par_chunks_mut(ow * self.out).enumerate().for_each(|(oy, row)| {
// This output row's patches.
let mut patch = vec![0.0f32; ow * kk];
for ox in 0..ow {
for ky in 0..self.ks {
let iy = (oy * self.stride + ky) as isize - self.pad as isize;
if iy < 0 || iy >= h as isize {
continue;
}
for kx in 0..self.ks {
let ix = (ox * self.stride + kx) as isize - self.pad as isize;
if ix < 0 || ix >= w as isize {
continue;
}
let src = (iy as usize * w + ix as usize) * self.inp;
let dst = ox * kk + (ky * self.ks + kx) * self.inp;
patch[dst..dst + self.inp].copy_from_slice(&x[src..src + self.inp]);
}
}
}
if let (Ok(av), Ok(bv), Ok(mut cv)) = (
ArrayView2::from_shape((ow, kk), &patch[..]),
ArrayView2::from_shape((kk, self.out), &self.wt[..]),
ArrayViewMut2::from_shape((ow, self.out), row),
) {
general_mat_mul(1.0, &av, &bv, 1.0, &mut cv);
}
});
(y, oh, ow)
}
}
/// A depthwise 3×3 convolution (padding 1, stride 1 or 2) on `h×w×c`.
#[derive(Clone, Debug, Default)]
pub struct Depthwise {
/// `[tap × c]`.
pub w: Vec<f32>,
pub b: Vec<f32>,
pub c: usize,
pub stride: usize,
}
impl Depthwise {
/// From PyTorch's `[c × 1 × 3 × 3]`.
pub fn new(w: &[f32], b: Option<&[f32]>, c: usize, stride: usize) -> Option<Depthwise> {
if w.len() != c * 9 || b.is_some_and(|b| b.len() != c) || stride == 0 {
return None;
}
let mut wt = vec![0.0; 9 * c];
for ch in 0..c {
for t in 0..9 {
wt[t * c + ch] = w[ch * 9 + t];
}
}
Some(Depthwise { w: wt, b: b.map_or_else(|| vec![0.0; c], <[f32]>::to_vec), c, stride })
}
pub fn forward(&self, x: &[f32], h: usize, w: usize) -> (Vec<f32>, usize, usize) {
let c = self.c;
let (oh, ow) = ((h + 2 - 3) / self.stride + 1, (w + 2 - 3) / self.stride + 1);
let mut y = vec![0.0f32; oh * ow * c];
if x.len() < h * w * c {
return (y, oh, ow);
}
y.par_chunks_mut(ow * c).enumerate().for_each(|(oy, row)| {
for ox in 0..ow {
let out = &mut row[ox * c..(ox + 1) * c];
out.copy_from_slice(&self.b);
for ky in 0..3 {
let iy = (oy * self.stride + ky) as isize - 1;
if iy < 0 || iy >= h as isize {
continue;
}
for kx in 0..3 {
let ix = (ox * self.stride + kx) as isize - 1;
if ix < 0 || ix >= w as isize {
continue;
}
let src = &x[(iy as usize * w + ix as usize) * c..][..c];
let tap = &self.w[(ky * 3 + kx) * c..][..c];
for ((o, s), k) in out.iter_mut().zip(src).zip(tap) {
*o += s * k;
}
}
}
}
});
(y, oh, ow)
}
}
/// A 2×2, stride-2 transposed convolution (each input pixel paints a 2×2 block):
/// `h×w×inp` → `2h×2w×out`.
#[derive(Clone, Debug, Default)]
pub struct Upconv {
/// One dense layer per output tap (dy, dx).
pub taps: Vec<Linear>,
pub out: usize,
}
impl Upconv {
/// From PyTorch's ConvTranspose2d `[inp × out × 2 × 2]`.
pub fn new(w: &[f32], b: &[f32], inp: usize, out: usize) -> Option<Upconv> {
if w.len() != inp * out * 4 || b.len() != out {
return None;
}
let taps = (0..4)
.map(|t| {
let mut wt = vec![0.0; inp * out];
for i in 0..inp {
for o in 0..out {
wt[i * out + o] = w[(i * out + o) * 4 + t];
}
}
Linear { wt, b: b.to_vec(), inp, out }
})
.collect();
Some(Upconv { taps, out })
}
pub fn forward(&self, x: &[f32], h: usize, w: usize) -> Vec<f32> {
let (ow, c) = (2 * w, self.out);
let mut y = vec![0.0f32; 4 * h * w * c];
for (t, lin) in self.taps.iter().enumerate() {
let (dy, dx) = (t / 2, t % 2);
let part = lin.forward(x, h * w);
for p in 0..h * w {
let (py, px) = (p / w, p % w);
let dst = ((2 * py + dy) * ow + 2 * px + dx) * c;
if let (Some(d), Some(s)) = (y.get_mut(dst..dst + c), part.get(p * c..(p + 1) * c)) {
d.copy_from_slice(s);
}
}
}
y
}
}
/// Layer norm over the channels of each token.
#[derive(Clone, Debug, Default)]
pub struct Norm {
pub w: Vec<f32>,
pub b: Vec<f32>,
pub eps: f32,
}
impl Norm {
pub fn forward(&self, x: &mut [f32]) {
let c = self.w.len();
if c == 0 {
return;
}
x.par_chunks_mut(c).for_each(|t| {
let mean = t.iter().sum::<f32>() / c as f32;
let var = t.iter().map(|v| (v - mean) * (v - mean)).sum::<f32>() / c as f32;
let inv = 1.0 / (var + self.eps).sqrt();
for ((v, w), b) in t.iter_mut().zip(&self.w).zip(&self.b) {
*v = (*v - mean) * inv * w + b;
}
});
}
}
/// The error function (Abramowitz & Stegun 7.1.26 refined: |error| < 1.5e-7).
fn erf(x: f32) -> f32 {
let s = x.signum();
let x = x.abs() as f64;
let t = 1.0 / (1.0 + 0.327_591_1 * x);
let y = 1.0 - (((((1.061_405_429 * t - 1.453_152_027) * t) + 1.421_413_741) * t - 0.284_496_736) * t + 0.254_829_592) * t * (-x * x).exp();
s * y as f32
}
/// GELU (the exact, erf form, as PyTorch's `nn.GELU`), in place.
pub fn gelu(x: &mut [f32]) {
x.par_chunks_mut(4096).for_each(|c| {
for v in c {
*v = 0.5 * *v * (1.0 + erf(*v * std::f32::consts::FRAC_1_SQRT_2));
}
});
}
pub fn relu(x: &mut [f32]) {
for v in x {
*v = v.max(0.0);
}
}
/// `a += b`.
pub fn add(a: &mut [f32], b: &[f32]) {
a.par_chunks_mut(4096).zip(b.par_chunks(4096)).for_each(|(a, b)| {
for (x, y) in a.iter_mut().zip(b) {
*x += y;
}
});
}
/// Softmax of each row of `n` values, in place.
pub fn softmax_rows(x: &mut [f32], n: usize) {
if n == 0 {
return;
}
for row in x.chunks_mut(n) {
let m = row.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let mut s = 0.0;
for v in row.iter_mut() {
*v = (*v - m).exp();
s += *v;
}
let inv = 1.0 / s.max(1e-30);
for v in row.iter_mut() {
*v *= inv;
}
}
}
/// Multi-head scaled dot-product attention of `nq` queries over `nk` keys/values, each `heads ×
/// hd` wide (token-major, heads side by side), plus an optional per-head bias `[heads × nq × nk]`.
pub fn attention(q: &[f32], k: &[f32], v: &[f32], nq: usize, nk: usize, heads: usize, hd: usize, bias: Option<&[f32]>) -> Vec<f32> {
let dim = heads * hd;
let mut out = vec![0.0f32; nq * dim];
if q.len() < nq * dim || k.len() < nk * dim || v.len() < nk * dim {
return out;
}
let scale = 1.0 / (hd as f32).sqrt();
for h in 0..heads {
// This head's q, kᵀ and v as contiguous matrices.
let qh: Vec<f32> = (0..nq).flat_map(|i| q[i * dim + h * hd..][..hd].iter().map(|x| x * scale)).collect();
let mut kt = vec![0.0f32; hd * nk];
for j in 0..nk {
for d in 0..hd {
kt[d * nk + j] = k[j * dim + h * hd + d];
}
}
let vh: Vec<f32> = (0..nk).flat_map(|j| v[j * dim + h * hd..][..hd].iter().copied()).collect();
let mut s = match bias.and_then(|b| b.get(h * nq * nk..(h + 1) * nq * nk)) {
Some(b) => b.to_vec(),
None => vec![0.0; nq * nk],
};
gemm(&qh, nq, hd, &kt, nk, &mut s);
softmax_rows(&mut s, nk);
let mut oh = vec![0.0f32; nq * hd];
gemm(&s, nq, nk, &vh, hd, &mut oh);
for i in 0..nq {
out[i * dim + h * hd..][..hd].copy_from_slice(&oh[i * hd..][..hd]);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gemm_matches_naive() {
let (m, k, n) = (130, 17, 9);
let a: Vec<f32> = (0..m * k).map(|i| ((i * 7) % 13) as f32 - 6.0).collect();
let b: Vec<f32> = (0..k * n).map(|i| ((i * 5) % 11) as f32 - 5.0).collect();
let mut c = vec![1.0f32; m * n];
gemm(&a, m, k, &b, n, &mut c);
for i in 0..m {
for j in 0..n {
let want: f32 = 1.0 + (0..k).map(|p| a[i * k + p] * b[p * n + j]).sum::<f32>();
assert_eq!(c[i * n + j], want);
}
}
}
#[test]
fn convolutions_match_direct_sums() {
// 3×3 stride-2 conv on a 5×4×2 input vs. the definition.
let (h, w, inp, out) = (5, 4, 2, 3);
let x: Vec<f32> = (0..h * w * inp).map(|i| (i % 7) as f32 * 0.5).collect();
let wt: Vec<f32> = (0..out * inp * 9).map(|i| ((i % 5) as f32 - 2.0) * 0.25).collect();
let b = [0.1, -0.2, 0.3];
let conv = Conv::new(&wt, Some(&b), out, inp, 3, 2, 1).unwrap();
let (y, oh, ow) = conv.forward(&x, h, w);
assert_eq!((oh, ow), (3, 2));
for oy in 0..oh {
for ox in 0..ow {
for o in 0..out {
let mut s = b[o];
for ci in 0..inp {
for ky in 0..3 {
for kx in 0..3 {
let (iy, ix) = ((oy * 2 + ky) as isize - 1, (ox * 2 + kx) as isize - 1);
if iy >= 0 && ix >= 0 && iy < h as isize && ix < w as isize {
s += x[(iy as usize * w + ix as usize) * inp + ci] * wt[((o * inp + ci) * 3 + ky) * 3 + kx];
}
}
}
}
assert!((y[(oy * ow + ox) * out + o] - s).abs() < 1e-5);
}
}
}
// Depthwise == a grouped conv: compare with Conv on each channel alone.
let dw_w: Vec<f32> = (0..inp * 9).map(|i| (i as f32 - 8.0) * 0.1).collect();
let dw = Depthwise::new(&dw_w, None, inp, 1).unwrap();
let (yd, _, _) = dw.forward(&x, h, w);
for ci in 0..inp {
let xc: Vec<f32> = (0..h * w).map(|p| x[p * inp + ci]).collect();
let single = Conv::new(&dw_w[ci * 9..ci * 9 + 9], None, 1, 1, 3, 1, 1).unwrap();
let (yc, _, _) = single.forward(&xc, h, w);
for p in 0..h * w {
assert!((yd[p * inp + ci] - yc[p]).abs() < 1e-5);
}
}
}
#[test]
fn gelu_and_softmax() {
let mut x = [-3.0f32, -1.0, 0.0, 1.0, 3.0];
gelu(&mut x);
// PyTorch's exact GELU values.
let want = [-0.004_049_7, -0.158_655_3, 0.0, 0.841_344_7, 2.995_950_3];
for (a, b) in x.iter().zip(want) {
assert!((a - b).abs() < 1e-5, "{a} {b}");
}
let mut s = [1.0f32, 2.0, 3.0];
softmax_rows(&mut s, 3);
assert!((s.iter().sum::<f32>() - 1.0).abs() < 1e-6 && s[2] > s[1]);
}
}
+499
View File
@@ -0,0 +1,499 @@
//! Reading PyTorch checkpoints (`torch.save` of a state dict) without PyTorch: the file is a zip
//! archive (stored or deflated entries, zip64 sizes) holding `data.pkl`, a pickle (protocol 2–4)
//! whose tensors are `torch._utils._rebuild_tensor_v2(storage, offset, size, stride, …)` calls
//! with storages as persistent ids pointing at `data/<key>` entries. Only what state dicts use is
//! understood; anything else is an error, never a panic.
use std::collections::HashMap;
/// A tensor read from a checkpoint: its shape and its values as f32 (row-major, contiguous).
#[derive(Clone, Debug, PartialEq)]
pub struct Tensor {
pub shape: Vec<usize>,
pub data: Vec<f32>,
}
/// A checkpoint's tensors by name (non-float tensors such as batch-norm counters are skipped).
pub type Weights = HashMap<String, Tensor>;
type Result<T> = std::result::Result<T, String>;
fn u16_at(b: &[u8], o: usize) -> Result<usize> {
b.get(o..o + 2).map(|s| u16::from_le_bytes([s[0], s[1]]) as usize).ok_or_else(|| "truncated zip".to_string())
}
fn u32_at(b: &[u8], o: usize) -> Result<u64> {
b.get(o..o + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64).ok_or_else(|| "truncated zip".to_string())
}
fn u64_at(b: &[u8], o: usize) -> Result<u64> {
b.get(o..o + 8).and_then(|s| s.try_into().ok()).map(u64::from_le_bytes).ok_or_else(|| "truncated zip".to_string())
}
/// One archive entry: where its data starts, its sizes and compression.
struct Entry {
data: usize,
size: usize,
stored: usize,
method: usize,
}
/// The entries of a zip archive by name.
fn zip_entries(b: &[u8]) -> Result<HashMap<String, Entry>> {
// End of central directory: the last `PK\x05\x06` (a comment may follow it).
let eocd =
(0..b.len().saturating_sub(21)).rev().find(|&i| b.get(i..i + 4) == Some(b"PK\x05\x06")).ok_or("not a zip archive (no end of central directory)")?;
let mut count = u16_at(b, eocd + 10)? as u64;
let mut cd = u32_at(b, eocd + 16)?;
// Zip64: the locator precedes the record.
if (count == 0xffff || cd == 0xffff_ffff) && eocd >= 20 && b.get(eocd - 20..eocd - 16) == Some(b"PK\x06\x07") {
let rec = u64_at(b, eocd - 12)? as usize;
if b.get(rec..rec + 4) == Some(b"PK\x06\x06") {
count = u64_at(b, rec + 32)?;
cd = u64_at(b, rec + 48)?;
}
}
let mut out = HashMap::new();
let mut p = cd as usize;
for _ in 0..count.min(1 << 20) {
if b.get(p..p + 4) != Some(b"PK\x01\x02") {
return Err("damaged zip central directory".into());
}
let method = u16_at(b, p + 10)?;
let mut stored = u32_at(b, p + 20)?;
let mut size = u32_at(b, p + 24)?;
let (nl, xl, cl) = (u16_at(b, p + 28)?, u16_at(b, p + 30)?, u16_at(b, p + 32)?);
let mut local = u32_at(b, p + 42)?;
let name = String::from_utf8_lossy(b.get(p + 46..p + 46 + nl).ok_or("truncated zip")?).to_string();
// Zip64 extended information: the 0xffffffff fields, in order.
let mut x = p + 46 + nl;
let xend = x + xl;
while x + 4 <= xend {
let (id, len) = (u16_at(b, x)?, u16_at(b, x + 2)?);
if id == 1 {
let mut f = x + 4;
for v in [&mut size, &mut stored, &mut local] {
if *v == 0xffff_ffff {
*v = u64_at(b, f)?;
f += 8;
}
}
}
x += 4 + len;
}
let l = local as usize;
if b.get(l..l + 4) != Some(b"PK\x03\x04") {
return Err(format!("damaged zip entry {name}"));
}
let data = l + 30 + u16_at(b, l + 26)? + u16_at(b, l + 28)?;
out.insert(name, Entry { data, size: size as usize, stored: stored as usize, method });
p += 46 + nl + xl + cl;
}
Ok(out)
}
/// An entry's bytes (stored, or raw-deflated).
fn read_entry<'a>(b: &'a [u8], e: &Entry) -> Result<std::borrow::Cow<'a, [u8]>> {
let raw = b.get(e.data..e.data + e.stored).ok_or("truncated zip entry")?;
match e.method {
0 => Ok(std::borrow::Cow::Borrowed(raw)),
8 => {
miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1)).map(std::borrow::Cow::Owned).map_err(|e| format!("bad deflate data: {e:?}"))
}
m => Err(format!("unsupported zip compression {m}")),
}
}
/// Pickle values (what state dicts use).
#[derive(Clone, Debug)]
enum Obj {
None,
Bool,
Int(i64),
Float,
Str(String),
Tuple(Vec<Obj>),
List(Vec<Obj>),
Dict(Vec<(Obj, Obj)>),
Global(String, String),
/// A storage: (dtype class name, entry key).
Storage(String, String),
/// `_rebuild_tensor_v2`: storage, element offset, size, stride.
Tensor {
dtype: String,
key: String,
offset: usize,
size: Vec<usize>,
stride: Vec<usize>,
},
/// A call we don't interpret.
Other,
Mark,
}
fn int_list(o: &Obj) -> Option<Vec<usize>> {
match o {
Obj::Tuple(v) | Obj::List(v) => v.iter().map(|x| if let Obj::Int(i) = x { usize::try_from(*i).ok() } else { None }).collect(),
_ => None,
}
}
/// Run the pickle program and return its result.
fn unpickle(p: &[u8]) -> Result<Obj> {
let mut stack: Vec<Obj> = Vec::new();
let mut memo: HashMap<u64, Obj> = HashMap::new();
let mut i = 0usize;
let take = |i: &mut usize, n: usize| -> Result<&[u8]> {
let s = p.get(*i..*i + n).ok_or("truncated pickle")?;
*i += n;
Ok(s)
};
let pop = |stack: &mut Vec<Obj>| stack.pop().ok_or_else(|| "pickle stack underflow".to_string());
let pop_mark = |stack: &mut Vec<Obj>| -> Result<Vec<Obj>> {
let m = stack.iter().rposition(|o| matches!(o, Obj::Mark)).ok_or("pickle: no mark")?;
let items = stack.split_off(m + 1);
stack.pop();
Ok(items)
};
let line = |i: &mut usize| -> Result<String> {
let rest = p.get(*i..).ok_or("truncated pickle")?;
let n = rest.iter().position(|c| *c == b'\n').ok_or("truncated pickle")?;
let s = String::from_utf8_lossy(&rest[..n]).to_string();
*i += n + 1;
Ok(s)
};
loop {
let op = *p.get(i).ok_or("truncated pickle")?;
i += 1;
match op {
0x80 => {
take(&mut i, 1)?;
}
0x95 => {
take(&mut i, 8)?;
}
b'}' => stack.push(Obj::Dict(vec![])),
b']' => stack.push(Obj::List(vec![])),
b')' => stack.push(Obj::Tuple(vec![])),
b'(' => stack.push(Obj::Mark),
b'N' => stack.push(Obj::None),
0x88 | 0x89 => stack.push(Obj::Bool),
b'K' => stack.push(Obj::Int(take(&mut i, 1)?[0] as i64)),
b'M' => {
let s = take(&mut i, 2)?;
stack.push(Obj::Int(u16::from_le_bytes([s[0], s[1]]) as i64));
}
b'J' => {
let s = take(&mut i, 4)?;
stack.push(Obj::Int(i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as i64));
}
0x8a => {
let n = take(&mut i, 1)?[0] as usize;
let s = take(&mut i, n)?;
let mut v: i64 = 0;
for (k, byte) in s.iter().take(8).enumerate() {
v |= (*byte as i64) << (8 * k);
}
if n > 0 && n < 8 && s[n - 1] & 0x80 != 0 {
v -= 1i64 << (8 * n);
}
stack.push(Obj::Int(v));
}
b'G' => {
take(&mut i, 8)?;
stack.push(Obj::Float);
}
b'X' => {
let s = take(&mut i, 4)?;
let n = u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as usize;
stack.push(Obj::Str(String::from_utf8_lossy(take(&mut i, n)?).to_string()));
}
0x8c => {
let n = take(&mut i, 1)?[0] as usize;
stack.push(Obj::Str(String::from_utf8_lossy(take(&mut i, n)?).to_string()));
}
b'C' => {
let n = take(&mut i, 1)?[0] as usize;
take(&mut i, n)?;
stack.push(Obj::Other);
}
b'B' => {
let s = take(&mut i, 4)?;
let n = u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as usize;
take(&mut i, n)?;
stack.push(Obj::Other);
}
b'c' => {
let (m, n) = (line(&mut i)?, line(&mut i)?);
stack.push(Obj::Global(m, n));
}
0x93 => {
let n = pop(&mut stack)?;
let m = pop(&mut stack)?;
match (m, n) {
(Obj::Str(m), Obj::Str(n)) => stack.push(Obj::Global(m, n)),
_ => return Err("pickle: bad STACK_GLOBAL".into()),
}
}
b'q' => {
let k = take(&mut i, 1)?[0] as u64;
memo.insert(k, stack.last().cloned().ok_or("pickle stack underflow")?);
}
b'r' => {
let s = take(&mut i, 4)?;
memo.insert(u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64, stack.last().cloned().ok_or("pickle stack underflow")?);
}
0x94 => {
let k = memo.len() as u64;
memo.insert(k, stack.last().cloned().ok_or("pickle stack underflow")?);
}
b'h' => {
let k = take(&mut i, 1)?[0] as u64;
stack.push(memo.get(&k).cloned().ok_or("pickle: bad memo")?);
}
b'j' => {
let s = take(&mut i, 4)?;
stack.push(memo.get(&(u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64)).cloned().ok_or("pickle: bad memo")?);
}
b't' => {
let items = pop_mark(&mut stack)?;
stack.push(Obj::Tuple(items));
}
0x85..=0x87 => {
let n = (op - 0x84) as usize;
if stack.len() < n {
return Err("pickle stack underflow".into());
}
let items = stack.split_off(stack.len() - n);
stack.push(Obj::Tuple(items));
}
b'Q' => {
// Persistent id: ('storage', dtype class, key, location, numel).
let pid = pop(&mut stack)?;
let Obj::Tuple(t) = pid else { return Err("pickle: bad persistent id".into()) };
match (t.get(1), t.get(2)) {
(Some(Obj::Global(_, dtype)), Some(Obj::Str(key))) => stack.push(Obj::Storage(dtype.clone(), key.clone())),
_ => stack.push(Obj::Other),
}
}
b'R' | 0x81 => {
let args = pop(&mut stack)?;
let f = pop(&mut stack)?;
let args = match args {
Obj::Tuple(a) => a,
_ => vec![],
};
stack.push(match f {
Obj::Global(m, n) if m == "torch._utils" && n == "_rebuild_tensor_v2" => {
match (args.first(), args.get(1), args.get(2).and_then(int_list), args.get(3).and_then(int_list)) {
(Some(Obj::Storage(dtype, key)), Some(Obj::Int(off)), Some(size), Some(stride)) => {
Obj::Tensor { dtype: dtype.clone(), key: key.clone(), offset: usize::try_from(*off).unwrap_or(0), size, stride }
}
_ => Obj::Other,
}
}
Obj::Global(m, n) if m == "collections" && n == "OrderedDict" => Obj::Dict(vec![]),
_ => Obj::Other,
});
}
b'b' => {
pop(&mut stack)?;
}
b's' => {
let v = pop(&mut stack)?;
let k = pop(&mut stack)?;
if let Some(Obj::Dict(d)) = stack.last_mut() {
d.push((k, v));
}
}
b'u' => {
let items = pop_mark(&mut stack)?;
if let Some(Obj::Dict(d)) = stack.last_mut() {
let mut it = items.into_iter();
while let (Some(k), Some(v)) = (it.next(), it.next()) {
d.push((k, v));
}
}
}
b'a' => {
let v = pop(&mut stack)?;
if let Some(Obj::List(l)) = stack.last_mut() {
l.push(v);
}
}
b'e' => {
let items = pop_mark(&mut stack)?;
if let Some(Obj::List(l)) = stack.last_mut() {
l.extend(items);
}
}
b'.' => return pop(&mut stack),
other => return Err(format!("pickle: unsupported opcode 0x{other:02x}")),
}
}
}
/// Element bytes and conversion of a storage dtype.
fn to_f32(dtype: &str, bytes: &[u8]) -> Option<Vec<f32>> {
match dtype {
"FloatStorage" => Some(bytes.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()),
"HalfStorage" => Some(bytes.chunks_exact(2).map(|c| half_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect()),
"BFloat16Storage" => Some(bytes.chunks_exact(2).map(|c| f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16)).collect()),
_ => None,
}
}
fn half_to_f32(h: u16) -> f32 {
let (s, e, m) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as u32, (h & 0x3ff) as u32);
let bits = match (e, m) {
(0, 0) => s << 31,
(0, m) => {
// Subnormal: normalise.
let mut e = 127 - 15 + 1;
let mut m = m;
while m & 0x400 == 0 {
m <<= 1;
e -= 1;
}
(s << 31) | (e << 23) | ((m & 0x3ff) << 13)
}
(0x1f, m) => (s << 31) | (0xff << 23) | (m << 13),
(e, m) => (s << 31) | ((e + 127 - 15) << 23) | (m << 13),
};
f32::from_bits(bits)
}
/// Read a PyTorch checkpoint's float tensors. A dict holding the state dict under `model` or
/// `state_dict` is unwrapped.
pub fn read(bytes: &[u8]) -> Result<Weights> {
let entries = zip_entries(bytes)?;
let (pkl_name, pkl) = entries.iter().find(|(n, _)| n.ends_with("data.pkl")).ok_or("not a PyTorch checkpoint (no data.pkl)")?;
let prefix = pkl_name.trim_end_matches("data.pkl").to_string();
let root = unpickle(&read_entry(bytes, pkl)?)?;
let dict = match root {
Obj::Dict(d) => d,
_ => return Err("the checkpoint is not a state dict".into()),
};
let dict = match dict.iter().find(|(k, _)| matches!(k, Obj::Str(s) if s == "model" || s == "state_dict")) {
Some((_, Obj::Dict(inner))) => inner.clone(),
_ => dict,
};
let mut storages: HashMap<String, std::borrow::Cow<[u8]>> = HashMap::new();
let mut out = Weights::new();
for (k, v) in dict {
let (Obj::Str(name), Obj::Tensor { dtype, key, offset, size, stride }) = (k, v) else { continue };
if !storages.contains_key(&key) {
let e = entries.get(&format!("{prefix}data/{key}")).ok_or_else(|| format!("missing storage {key}"))?;
storages.insert(key.clone(), read_entry(bytes, e)?);
}
let Some(values) = storages.get(&key).and_then(|b| to_f32(&dtype, b)) else { continue };
let n: usize = size.iter().product();
// Gather (any strides) into a contiguous row-major tensor.
let mut data = Vec::with_capacity(n);
let mut idx = vec![0usize; size.len()];
for _ in 0..n {
let at = offset + idx.iter().zip(&stride).map(|(i, s)| i * s).sum::<usize>();
data.push(*values.get(at).ok_or_else(|| format!("{name}: data out of range"))?);
for d in (0..idx.len()).rev() {
idx[d] += 1;
if idx[d] < size[d] {
break;
}
idx[d] = 0;
}
}
out.insert(name, Tensor { shape: size, data });
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
/// A zip archive with stored entries (what `torch.save` writes).
fn zip(files: &[(&str, &[u8])]) -> Vec<u8> {
let mut out = vec![];
let mut central = vec![];
for (name, data) in files {
let off = out.len() as u32;
out.extend_from_slice(b"PK\x03\x04");
out.extend_from_slice(&[20, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
out.extend_from_slice(&[0; 4]); // crc (unchecked)
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(data);
central.extend_from_slice(b"PK\x01\x02");
central.extend_from_slice(&[20, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
central.extend_from_slice(&[0; 4]);
central.extend_from_slice(&(data.len() as u32).to_le_bytes());
central.extend_from_slice(&(data.len() as u32).to_le_bytes());
central.extend_from_slice(&(name.len() as u16).to_le_bytes());
central.extend_from_slice(&[0; 12]);
central.extend_from_slice(&off.to_le_bytes());
central.extend_from_slice(name.as_bytes());
}
let cd = out.len() as u32;
out.extend_from_slice(&central);
out.extend_from_slice(b"PK\x05\x06");
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&(files.len() as u16).to_le_bytes());
out.extend_from_slice(&(files.len() as u16).to_le_bytes());
out.extend_from_slice(&(central.len() as u32).to_le_bytes());
out.extend_from_slice(&cd.to_le_bytes());
out.extend_from_slice(&[0, 0]);
out
}
/// The pickle `torch.save({'w': t.t()})` writes for a 2×3 tensor stored transposed (strides
/// (1, 2)), plus an int64 counter that is skipped.
fn pickle() -> Vec<u8> {
let mut p = vec![0x80, 2, b'}', b'q', 0, b'('];
let s = |p: &mut Vec<u8>, t: &str| {
p.push(b'X');
p.extend_from_slice(&(t.len() as u32).to_le_bytes());
p.extend_from_slice(t.as_bytes());
};
for (name, dtype, key, size, stride) in [("w", "FloatStorage", "0", [2u8, 3], [1u8, 2]), ("n", "LongStorage", "1", [1, 1], [1, 1])] {
s(&mut p, name);
// The call's argument mark, then the persistent id tuple's.
p.extend_from_slice(b"ctorch._utils\n_rebuild_tensor_v2\n((");
s(&mut p, "storage");
p.extend_from_slice(format!("ctorch\n{dtype}\n").as_bytes());
s(&mut p, key);
s(&mut p, "cpu");
p.extend_from_slice(&[b'K', 6, b't', b'Q', b'K', 0]);
p.extend_from_slice(&[b'K', size[0], b'K', size[1], 0x86, b'K', stride[0], b'K', stride[1], 0x86]);
p.extend_from_slice(&[0x89, b'c']);
p.extend_from_slice(b"collections\nOrderedDict\n");
p.extend_from_slice(b")RtR");
}
p.extend_from_slice(b"u.");
p
}
#[test]
fn reads_a_state_dict_with_strides() {
let storage: Vec<u8> = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0].iter().flat_map(|v| v.to_le_bytes()).collect();
let pkl = pickle();
let file = zip(&[("ckpt/data.pkl", &pkl), ("ckpt/data/0", &storage), ("ckpt/data/1", &7i64.to_le_bytes())]);
let w = read(&file).unwrap();
// Strides (1, 2) over [1..6]: rows are [1, 3, 5] and [2, 4, 6].
assert_eq!(w.get("w"), Some(&Tensor { shape: vec![2, 3], data: vec![1.0, 3.0, 5.0, 2.0, 4.0, 6.0] }));
assert!(!w.contains_key("n"), "integer tensors are skipped");
}
#[test]
fn damaged_files_are_errors() {
assert!(read(b"not a zip").is_err());
let pkl = pickle();
let file = zip(&[("ckpt/data.pkl", &pkl[..pkl.len() - 5])]);
assert!(read(&file).is_err());
// Truncate the storage: the tensor reads out of range.
let file = zip(&[("ckpt/data.pkl", &pkl), ("ckpt/data/0", &[0u8; 8]), ("ckpt/data/1", &[0u8; 8])]);
assert!(read(&file).is_err());
assert_eq!(half_to_f32(0x3c00), 1.0);
assert_eq!(half_to_f32(0xc000), -2.0);
}
}