From 357b16b8d81b69bff6677b85860947177f4ab679 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:03:03 +0200 Subject: [PATCH] M12: SAM 3 on the CPU ~3x faster: encode ~37 -> ~11 s, a description ~6 -> ~2 s On the CPU, candle runs elementwise ops and layout copies on one thread, batched matmuls one batch element after another (each spread over all threads) and transposed convolutions one output channel at a time. In the 32-layer ViT that was more than half of the ~37 s encode on a 12-core Ryzen 9 3900X; a text prompt spent most of its ~6 s in the DETR encoder's attention over 5184 tokens. crates/segment/src/cpu.rs, used on the CPU only (Metal keeps the tensor ops): - fused parallel kernels for the bias adds with GELU / ReLU / residual add, the ViT's window partition + head split + RoPE (with the 1/8 score scale moved to q, exact for a power of two) and head merge, the detector's box relative-position bias and the pixel decoder's GroupNorm + ReLU: the same float operations in the same order, bit-identical results; - sdpa as one rayon task per (batch, head, block of query rows), with 256 KB score blocks that stay in the core's cache (4 MB blocks were 3x slower for the detector's 8 heads of 32); - the necks' 2x2 stride-2 transposed convolutions as one matmul plus a reordering. The last two change how gemm blocks its sums, so results move by float rounding only, as between two CPUs (gemm picks its blocking from the cache sizes). Against the unchanged code on a real photo: backbone 1.1e-5 relative, click mask 1e-5 with no pixel changing side, text masks <= 7e-4 with at most 6 of 16.6M pixels changing side, the same kept instances. Ryzen 9 3900X, 24 threads: encode ~37 -> ~11 s, preparing clicks ~2.3 -> ~0.9 s, a description ~6 -> ~2.1 s (the first one on a photo also builds the detector's features: ~8.8 -> ~2.9 s). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/segment/Cargo.toml | 2 + crates/segment/src/clip.rs | 2 +- crates/segment/src/cpu.rs | 551 +++++++++++++++++++++++++++++++++ crates/segment/src/detector.rs | 21 +- crates/segment/src/lib.rs | 2 + crates/segment/src/neck.rs | 5 +- crates/segment/src/nn.rs | 50 ++- crates/segment/src/vit.rs | 113 ++++++- docs/ai-masks.md | 26 +- 10 files changed, 741 insertions(+), 32 deletions(-) create mode 100644 crates/segment/src/cpu.rs diff --git a/Cargo.lock b/Cargo.lock index 4b6d54289f..f94a68a2ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3465,6 +3465,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/src/clip.rs b/crates/segment/src/clip.rs index b69c148a4f..18a82b3dd0 100644 --- a/crates/segment/src/clip.rs +++ b/crates/segment/src/clip.rs @@ -74,7 +74,7 @@ impl TextEncoder { let h = l.ln1.forward(&x)?; x = (&x + l.attn.forward(&h, &h, &h, Some(&bias))?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } Ok(self.final_ln.forward(&x)?) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..ffbd0bde6c --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,551 @@ +//! Fused CPU kernels for the model's elementwise work, attention and upsampling. +//! +//! On the CPU, candle runs bias adds, activations, the rotary encoding and layout copies (window +//! partitioning, splitting and merging heads) one element at a time on one thread, batched matrix +//! products one pair at a time and transposed convolutions one output channel at a time: in the +//! 32-layer ViT that was more than half of the encode time on a 12-core CPU, and most of a text +//! prompt went to attention over 5184 tokens. The elementwise kernels do the same arithmetic in +//! the same order (bit-identical results), fused into fewer passes over memory and spread over +//! the rayon pool that candle's matrix products use. Attention in cache-sized blocks and the +//! transposed convolutions as one product change how gemm blocks its sums: those results move +//! by float rounding (as they do between two CPUs, gemm picking its blocking from the caches). + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp1, CustomOp2, CustomOp3, D, IndexOp, Layout, Shape, Tensor, bail}; +use candle_nn::{ConvTranspose2d, Linear}; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// A `b × h × w` token grid (row-major, `heads × head_dim` channels) attended in non-overlapping +/// `win × win` windows, or as a whole when `win` is 0. +#[derive(Clone, Copy, Debug)] +pub struct Grid { + pub b: usize, + pub h: usize, + pub w: usize, + pub win: usize, + pub heads: usize, + pub head_dim: usize, +} + +impl Grid { + /// Window height and width. + fn window(&self) -> (usize, usize) { + if self.win == 0 { (self.h, self.w) } else { (self.win, self.win) } + } + + /// Windows per image (down, across). + fn per_image(&self) -> (usize, usize) { + let (wh, ww) = self.window(); + (self.h / wh, self.w / ww) + } + + fn windows(&self) -> usize { + let (nh, nw) = self.per_image(); + self.b * nh * nw + } + + fn tokens(&self) -> usize { + let (wh, ww) = self.window(); + wh * ww + } + + fn channels(&self) -> usize { + self.heads * self.head_dim + } + + fn check(&self) -> candle_core::Result<()> { + let (wh, ww) = self.window(); + if wh == 0 || ww == 0 || !self.h.is_multiple_of(wh) || !self.w.is_multiple_of(ww) || !self.head_dim.is_multiple_of(2) { + bail!("grid {self:?}: windows must tile the grid"); + } + Ok(()) + } + + /// The grid row (token index in row-major order) of token `t` of window `win`. + fn row(&self, win: usize, t: usize) -> usize { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (win / (nh * nw), win % (nh * nw)); + let (y, x) = (i / nw * wh + t / ww, i % nw * ww + t % ww); + (b * self.h + y) * self.w + x + } + + /// The window and the token within it of grid row `row`. + fn window_of(&self, row: usize) -> (usize, usize) { + let (wh, ww) = self.window(); + let (nh, nw) = self.per_image(); + let (b, i) = (row / (self.h * self.w), row % (self.h * self.w)); + let (y, x) = (i / self.w, i % self.w); + ((b * nh + y / wh) * nw + x / ww, y % wh * ww + x % ww) + } +} + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// `residual + (x · Wᵀ + b)`, shaped like `residual`. +pub fn linear_add(x: &Tensor, l: &Linear, residual: &Tensor) -> Result { + Ok(product(x, l)?.apply_op3_no_bwd(bias(l)?, &residual.contiguous()?, &BiasAdd)?) +} + +/// The projection `x · Wᵀ + b` of the grid's tokens (`x`: `[b, h, w, C]`), split into heads per +/// window: `[windows, heads, tokens, head_dim]`, with the rotary encoding (`cos`, `sin`: +/// `[tokens, head_dim]`) applied when given, then multiplied by `scale`. +pub fn heads(x: &Tensor, l: &Linear, grid: Grid, rope: Option<(&[f32], &[f32])>, scale: f32) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &Heads { grid, rope, scale })?) +} + +/// Attention scores computed per task (elements): a block of query rows against all keys, +/// small enough (256 KB) to stay in a core's L2 cache between the two products and the softmax. +/// 4 MB blocks were 3× slower for the detector's 5184-token attention (8 heads of 32). +const SCORE_TILE: usize = 1 << 16; + +/// `nn::sdpa` on `[B, H, L, d]` tensors (`bias` `[B or 1, H or 1, Lq or 1, Lk]`): the same +/// operations (scores × `scale` unless it is 1, plus the bias, softmax, × v), but candle +/// multiplies batched matrices one pair after another, each spread over all threads, which is +/// slow for 9 windows × 16 heads of 576 tokens or 8 heads of 5184; here every (batch, head, +/// block of query rows) is a task of its own. +pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + let (b, h, lq, _) = q.dims4()?; + let (lk, dv) = (k.dim(2)?, v.dim(3)?); + let bias = match bias { + Some(t) => Some((t, t.dims4()?)), + None => None, + }; + let rows = (SCORE_TILE / lk.max(1)).clamp(1, lq.max(1)); + let tasks: Vec<(usize, usize, usize)> = (0..b * h).flat_map(|i| (0..lq).step_by(rows).map(move |r| (i / h, i % h, r))).collect(); + let out = tasks + .par_iter() + .map(|&(bi, hi, r)| -> Result { + let n = rows.min(lq - r); + let mut att = q.i((bi, hi))?.narrow(0, r, n)?.matmul(&k.i((bi, hi))?.t()?)?; + if scale != 1.0 { + att = (att * scale)?; + } + if let Some((t, (tb, th, tq, _))) = bias { + let t = t.i((if tb == 1 { 0 } else { bi }, if th == 1 { 0 } else { hi }))?; + att = att.broadcast_add(&if tq == 1 { t } else { t.narrow(0, r, n)? })?; + } + Ok(candle_nn::ops::softmax_last_dim(&att)?.matmul(&v.i((bi, hi))?)?) + }) + .collect::>>()?; + Ok(Tensor::cat(&out, 0)?.reshape((b, h, lq, dv))?) +} + +/// Attention over `q`, `k`, `v` from [`heads`] (`q` already scaled), merged back to the grid: +/// `[b, h, w, C]`. +pub fn attention(q: &Tensor, k: &Tensor, v: &Tensor, grid: Grid) -> Result { + Ok(sdpa(q, k, v, None, 1.0)?.apply_op1_no_bwd(&Merge { grid })?) +} + +/// `ConvTranspose2d` with a 2 × 2 kernel and stride 2 (the neck's upsampling) on `x` +/// `[1, Cin, H, W]`, then GELU when `gelu`: `[1, Cout, 2H, 2W]`. The kernel windows don't overlap, +/// so this is one product `[H·W, Cin] × [Cin, Cout·4]` and a reordering with the bias; candle +/// computes it one output channel at a time (~50 GFLOP/s here). +pub fn upsample2(x: &Tensor, ct: &ConvTranspose2d, gelu: bool) -> Result { + let (b, cin, h, w) = x.dims4()?; + let (wi, cout, kh, kw) = ct.weight().dims4()?; + let c = ct.config(); + if b != 1 || wi != cin || (kh, kw, c.stride, c.padding, c.output_padding, c.dilation) != (2, 2, 2, 0, 0, 1) { + return Err(Error::Model(format!("upsample2: {:?} with a {:?} kernel", x.dims(), ct.weight().dims()))); + } + let y = x.reshape((cin, h * w))?.t()?.matmul(&ct.weight().reshape((cin, cout * 4))?)?; + let bias = match ct.bias() { + Some(b) => b.clone(), + None => Tensor::zeros(cout, candle_core::DType::F32, x.device())?, + }; + Ok(y.apply_op2_no_bwd(&bias, &Unpatch { h, w, gelu })?) +} + +/// `relu(group_norm(x))` over `[B, C, …]` with `groups` groups and per-channel `weight`, `bias`. +/// candle's `GroupNorm` makes eight single-threaded passes over the 288² pixel decoder maps. +pub fn group_norm_relu(x: &Tensor, weight: &Tensor, bias: &Tensor, groups: usize, eps: f64) -> Result { + Ok(x.contiguous()?.apply_op3_no_bwd(weight, bias, &GroupNormRelu { groups, eps })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BiasAdd; + +impl CustomOp3 for BiasAdd { + fn name(&self) -> &'static str { + "bias-residual-add" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b, r) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let n = rows(x, b)?; + if r.len() != x.len() { + bail!("residual of {} for {} values", r.len(), x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).zip(r.par_chunks(n)).for_each(|((o, x), r)| { + for (((o, x), b), r) in o.iter_mut().zip(x).zip(b).zip(r) { + *o = r + (x + b); + } + }); + Ok((CpuStorage::F32(out), l3.shape().clone())) + } +} + +struct Heads<'a> { + grid: Grid, + rope: Option<(&'a [f32], &'a [f32])>, + scale: f32, +} + +impl CustomOp2 for Heads<'_> { + fn name(&self) -> &'static str { + "split-heads-rope" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let (x, bias) = (values(s1, l1)?, values(s2, l2)?); + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if bias.len() != c || x.len() != g.b * g.h * g.w * c { + bail!("heads: {} values with a bias of {} for {g:?}", x.len(), bias.len()); + } + if let Some((cos, sin)) = self.rope + && (cos.len() != n * d || sin.len() != n * d) + { + bail!("rotary tables of {} and {} for {n} tokens", cos.len(), sin.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n * d).enumerate().for_each(|(i, o)| { + let (win, head) = (i / g.heads, i % g.heads); + let bias = &bias[head * d..][..d]; + for (t, o) in o.chunks_exact_mut(d).enumerate() { + let x = &x[g.row(win, t) * c + head * d..][..d]; + for ((o, x), b) in o.iter_mut().zip(x).zip(bias) { + *o = x + b; + } + if let Some((cos, sin)) = self.rope { + // x·cos + rotate_pairwise(x)·sin, rotate_pairwise mapping (a, b) to (−b, a) + let (cos, sin) = (&cos[t * d..][..d], &sin[t * d..][..d]); + for ((o, cos), sin) in o.as_chunks_mut::<2>().0.iter_mut().zip(cos.as_chunks::<2>().0).zip(sin.as_chunks::<2>().0) { + let [a, b] = *o; + *o = [a * cos[0] + -b * sin[0], b * cos[1] + a * sin[1]]; + } + } + for o in o.iter_mut() { + *o *= self.scale; + } + } + }); + let shape = Shape::from((g.windows(), g.heads, n, d)); + Ok((CpuStorage::F32(out), shape)) + } +} + +struct GroupNormRelu { + groups: usize, + eps: f64, +} + +impl CustomOp3 for GroupNormRelu { + fn name(&self) -> &'static str { + "group-norm-relu" + } + + fn cpu_fwd( + &self, + s1: &CpuStorage, + l1: &Layout, + s2: &CpuStorage, + l2: &Layout, + s3: &CpuStorage, + l3: &Layout, + ) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, w, b) = (values(s1, l1)?, values(s2, l2)?, values(s3, l3)?); + let dims = l1.shape().dims(); + let (batch, c) = match dims { + [batch, c, _, ..] => (*batch, *c), + _ => bail!("group norm of {dims:?}"), + }; + if c == 0 || self.groups == 0 || !c.is_multiple_of(self.groups) || w.len() != c || b.len() != c || x.is_empty() { + bail!("group norm: {dims:?} in {} groups, {} weights", self.groups, w.len()); + } + let hw = x.len() / (batch * c); + let per = c / self.groups * hw; + // mean and σ per (image, group), as candle computes them (f32 sums in order) + let n = (1.0 / per as f64) as f32; + let stats: Vec<(f32, f32)> = x + .par_chunks(per) + .map(|g| { + let mean = g.iter().fold(0f32, |s, v| s + v) * n; + let var = g.iter().fold(0f32, |s, v| s + (v - mean) * (v - mean)) * n; + (mean, (var + self.eps as f32).sqrt()) + }) + .collect(); + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(hw).zip(x.par_chunks(hw)).enumerate().for_each(|(row, (o, x))| { + let ch = row % c; + let (mean, sd) = stats[row / c * self.groups + ch / (c / self.groups)]; + for (o, x) in o.iter_mut().zip(x) { + *o = ((x - mean) / sd * w[ch] + b[ch]).max(0f32); + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +/// `[H·W, Cout·2·2]` patches (+ bias, then GELU) to `[1, Cout, 2H, 2W]`. +struct Unpatch { + h: usize, + w: usize, + gelu: bool, +} + +impl CustomOp2 for Unpatch { + fn name(&self) -> &'static str { + "unpatch-2x2" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (y, bias) = (values(s1, l1)?, values(s2, l2)?); + let (h, w, cout) = (self.h, self.w, bias.len()); + if y.len() != h * w * cout * 4 { + bail!("unpatch: {} values for {h} × {w} × {cout} × 4", y.len()); + } + let mut out = vec![0f32; y.len()]; + // one output row (channel c, row 2·r + i) at a time + out.par_chunks_mut(2 * w).enumerate().for_each(|(row, o)| { + let (c, r, i) = (row / (2 * h), row % (2 * h) / 2, row % 2); + for (x, o) in o.as_chunks_mut::<2>().0.iter_mut().enumerate() { + let p = &y[(r * w + x) * cout * 4 + c * 4 + i * 2..][..2]; + for (o, p) in o.iter_mut().zip(p) { + let v = p + bias[c]; + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v }; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, cout, 2 * h, 2 * w)))) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +struct Merge { + grid: Grid, +} + +impl CustomOp1 for Merge { + fn name(&self) -> &'static str { + "merge-heads" + } + + fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let g = self.grid; + g.check()?; + let x = values(s, l)?; + let (c, d, n) = (g.channels(), g.head_dim, g.tokens()); + if x.len() != g.windows() * g.heads * n * d { + bail!("merge: {} values for {g:?}", x.len()); + } + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(c).enumerate().for_each(|(row, o)| { + let (win, t) = g.window_of(row); + for (head, o) in o.chunks_exact_mut(d).enumerate() { + o.copy_from_slice(&x[((win * g.heads + head) * n + t) * d..][..d]); + } + }); + Ok((CpuStorage::F32(out), Shape::from((g.b, g.h, g.w, c)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::{ConvTranspose2dConfig, Module}; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + /// The kernels against candle's tensor operations: equal up to float rounding (on x86-64 most + /// are bit-identical; the matrix products may block differently). + fn close(name: &str, got: &Tensor, want: &Tensor) { + assert_eq!(got.dims(), want.dims(), "{name}: shape"); + let (got, want): (Vec, Vec) = (got.flatten_all().unwrap().to_vec1().unwrap(), want.flatten_all().unwrap().to_vec1().unwrap()); + let scale = want.iter().fold(1e-6f32, |m, v| m.max(v.abs())); + let err = got.iter().zip(&want).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(err <= 1e-5 * scale, "{name}: max error {err} (scale {scale})"); + } + + #[test] + fn sdpa_matches_the_tensor_ops() { + // 1000 keys: blocks of 65 query rows, the last one short + let (q, k, v) = (randn(&[2, 3, 150, 8]), randn(&[2, 3, 1000, 8]), randn(&[2, 3, 1000, 5])); + let biases = + [None, Some(randn(&[1, 1, 1, 1000])), Some(randn(&[1, 3, 150, 1000])), Some(randn(&[2, 1, 150, 1000])), Some(randn(&[2, 3, 1, 1000]))]; + for (i, bias) in biases.iter().enumerate() { + for scale in [0.35, 1.0] { + let got = sdpa(&q, &k, &v, bias.as_ref(), scale).unwrap(); + let want = crate::nn::sdpa_tensors(&q, &k, &v, bias.as_ref(), scale).unwrap(); + close(&format!("bias {i}, scale {scale}"), &got, &want); + } + } + } + + #[test] + fn fused_linears_match_the_tensor_ops() { + let x = randn(&[3, 5, 7]); + let l = Linear::new(randn(&[6, 7]), Some(randn(&[6]))); + let y = l.forward(&x).unwrap().reshape((15, 6)).unwrap(); + close("gelu", &linear_act(&x, &l, true).unwrap(), &y.gelu_erf().unwrap()); + close("relu", &linear_act(&x, &l, false).unwrap(), &y.relu().unwrap()); + let r = randn(&[3, 5, 6]); + close("residual", &linear_add(&x, &l, &r).unwrap(), &(&r + l.forward(&x).unwrap()).unwrap()); + assert!(linear_act(&x, &Linear::new(randn(&[6, 7]), None), true).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + close("box bias", &box_bias(&ey, &ex).unwrap(), &want); + } + + #[test] + fn upsampling_matches_the_transposed_convolution() { + let x = randn(&[1, 6, 3, 4]); + let cfg = ConvTranspose2dConfig { stride: 2, ..Default::default() }; + let ct = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), Some(randn(&[5])), cfg); + let want = ct.forward(&x).unwrap(); + close("upsample", &upsample2(&x, &ct, false).unwrap(), &want); + close("upsample + gelu", &upsample2(&x, &ct, true).unwrap(), &want.gelu_erf().unwrap()); + let other = ConvTranspose2d::new(randn(&[6, 5, 2, 2]), None, ConvTranspose2dConfig::default()); + assert!(upsample2(&x, &other, false).is_err()); + } + + #[test] + fn group_norm_matches_candle() { + let x = randn(&[2, 6, 4, 5]); + let (w, b) = (randn(&[6]), randn(&[6])); + let want = candle_nn::GroupNorm::new(w.clone(), b.clone(), 6, 3, 1e-5).unwrap().forward(&x).unwrap().relu().unwrap(); + close("group norm", &group_norm_relu(&x, &w, &b, 3, 1e-5).unwrap(), &want); + assert!(group_norm_relu(&x, &w, &b, 4, 1e-5).is_err()); + } + + #[test] + fn window_indexing_round_trips() { + for win in [0, 3] { + let g = Grid { b: 2, h: 6, w: 9, win, heads: 1, head_dim: 2 }; + g.check().unwrap(); + let mut seen = vec![false; g.b * g.h * g.w]; + for w in 0..g.windows() { + for t in 0..g.tokens() { + let row = g.row(w, t); + assert_eq!(g.window_of(row), (w, t)); + seen[row] = true; + } + } + assert!(seen.iter().all(|s| *s)); + } + assert!(Grid { b: 1, h: 6, w: 9, win: 4, heads: 1, head_dim: 2 }.check().is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index 7c4eccbd33..70c623570b 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -7,12 +7,14 @@ //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. use candle_core::{D, Device, IndexOp, Module, Tensor}; -use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; +use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; -use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::nn::{ + Attention, DecoderMlp, GroupNormRelu, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec, +}; +use crate::{Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; @@ -89,7 +91,7 @@ pub struct Detector { prompt_attn: Attention, prompt_ln: LayerNorm, pixel_convs: Vec, - pixel_norms: Vec, + pixel_norms: Vec, instance_proj: Conv2d, mask_embedder: Vec, } @@ -153,7 +155,7 @@ impl Detector { prompt_attn: Attention::new(HIDDEN, HIDDEN, HEADS, m.pp("prompt_cross_attn"))?, prompt_ln: ln(HIDDEN, TORCH_LN_EPS, m.pp("prompt_cross_attn_norm"))?, pixel_convs: (0..3).map(|i| Ok(candle_nn::conv2d(HIDDEN, HIDDEN, 3, conv3, p.pp(format!("conv_layers.{i}")))?)).collect::>()?, - pixel_norms: (0..3).map(|i| Ok(candle_nn::group_norm(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))?)).collect::>()?, + pixel_norms: (0..3).map(|i| GroupNormRelu::new(8, HIDDEN, 1e-5, p.pp(format!("norms.{i}")))).collect::>()?, instance_proj: candle_nn::conv2d(HIDDEN, HIDDEN, 1, Conv2dConfig::default(), m.pp("instance_projection"))?, mask_embedder: (0..3).map(|i| linear(HIDDEN, HIDDEN, m.pp(format!("mask_embedder.layers.{i}")))).collect::>()?, }) @@ -183,6 +185,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -217,7 +222,7 @@ impl Detector { let h = l.ln2.forward(&x)?; x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; let h = l.ln3.forward(&x)?; - x = (&x + l.mlp.forward(&h)?)?; + x = l.mlp.forward_add(&h, &x)?; } let memory = x; @@ -236,7 +241,7 @@ impl Detector { h = l.text_ln.forward(&(&h + l.text_attn.forward(&q, &text, &text, Some(&text_bias))?)?)?; let q = (&h + &qpos)?; h = l.vision_ln.forward(&(&h + l.vision_attn.forward(&q, &key_pos, &memory, Some(&bias))?)?)?; - h = l.mlp_ln.forward(&(&h + l.mlp.forward(&h)?)?)?; + h = l.mlp_ln.forward(&l.mlp.forward_add(&h, &h)?)?; let qh = self.out_ln.forward(&h.narrow(1, 1, QUERIES)?)?; boxes = candle_nn::ops::sigmoid(&(self.box_head.forward(&qh)? + inverse_sigmoid(&boxes)?)?)?; let p = self.presence_head.forward(&self.presence_ln.forward(&h.narrow(1, 0, 1)?)?)?; @@ -265,7 +270,7 @@ impl Detector { let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { return Err(Error::Model("pixel decoder".into())); }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + prev = norm.forward(&conv.forward(&prev)?)?; } let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] let (_, c, mh, mw) = inst.dims4()?; diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6d488a919a..61cac2e63b 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -29,6 +29,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; diff --git a/crates/segment/src/neck.rs b/crates/segment/src/neck.rs index c4f716dd6f..46cbebf1e5 100644 --- a/crates/segment/src/neck.rs +++ b/crates/segment/src/neck.rs @@ -8,8 +8,8 @@ use candle_core::{Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, ConvTranspose2d, ConvTranspose2dConfig, VarBuilder}; -use crate::Result; use crate::vit::HIDDEN; +use crate::{Result, cpu}; pub const FPN: usize = 256; @@ -64,8 +64,11 @@ impl Neck { pub fn forward(&self, x: &Tensor, n: usize) -> Result> { let mut out = Vec::with_capacity(n); for l in self.levels.iter().take(n) { + let cpu = x.device().is_cpu(); let y = match &l.scale { + Scale::Up4(a, b) if cpu => cpu::upsample2(&cpu::upsample2(x, a, true)?, b, false)?, Scale::Up4(a, b) => b.forward(&a.forward(x)?.gelu_erf()?)?, + Scale::Up2(a) if cpu => cpu::upsample2(x, a, false)?, Scale::Up2(a) => a.forward(x)?, Scale::Same => x.clone(), Scale::Down2 => x.max_pool2d(2)?, diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..0749d9c72a 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -25,8 +25,17 @@ pub fn linear(i: usize, o: usize, vb: VarBuilder) -> Result { const SCORE_BLOCK: usize = 64 << 20; /// Scaled dot-product attention on `[B, H, L, d]` tensors, with an optional additive bias -/// broadcastable to `[B, H, Lq, Lk]`. Heads are processed in groups to bound memory. +/// broadcastable to `[B, H, Lq, Lk]` (on the CPU: [`cpu::sdpa`]). pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { + if q.device().is_cpu() && bias.is_none_or(|t| t.rank() == 4) { + return cpu::sdpa(q, k, v, bias, scale); + } + sdpa_tensors(q, k, v, bias, scale) +} + +/// [`sdpa`] with candle's tensor operations (any device). Heads are processed in groups to bound +/// memory. +pub fn sdpa_tensors(q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>, scale: f64) -> Result { let (b, h, lq, _) = q.dims4()?; let lk = k.dim(2)?; let per_head = b.saturating_mul(lq).saturating_mul(lk).max(1); @@ -97,6 +106,11 @@ impl Attention { Ok(self.o.forward(x)?) } + /// The q, k, v and output projections. + pub fn projections(&self) -> [&Linear; 4] { + [&self.q, &self.k, &self.v, &self.o] + } + /// `q`, `k`, `v`: `[B, L, hidden]`; `bias` broadcastable to `[B, heads, Lq, Lk]`. pub fn forward(&self, q: &Tensor, k: &Tensor, v: &Tensor, bias: Option<&Tensor>) -> Result { let (b, lq, _) = q.dims3()?; @@ -132,6 +146,14 @@ impl Mlp { let x = if self.gelu { x.gelu_erf()? } else { x.relu()? }; Ok(self.fc2.forward(&x)?) } + + /// `residual + forward(x)`; on the CPU with the bias adds, activation and residual add fused. + pub fn forward_add(&self, x: &Tensor, residual: &Tensor) -> Result { + if !x.device().is_cpu() { + return Ok((residual + self.forward(x)?)?); + } + cpu::linear_add(&cpu::linear_act(x, &self.fc1, self.gelu)?, &self.fc2, residual) + } } /// `Sam3DecoderMLP`: `layer1 … layerN` with ReLU between (2 or 3 layers). @@ -188,6 +210,30 @@ impl FeedForward { } } +/// `nn.GroupNorm` followed by ReLU (the pixel decoder's), fused on the CPU. +pub struct GroupNormRelu { + norm: candle_nn::GroupNorm, + weight: Tensor, + bias: Tensor, + groups: usize, + eps: f64, +} + +impl GroupNormRelu { + pub fn new(groups: usize, channels: usize, eps: f64, vb: VarBuilder) -> Result { + let (weight, bias) = (vb.get(channels, "weight")?, vb.get(channels, "bias")?); + let norm = candle_nn::GroupNorm::new(weight.clone(), bias.clone(), channels, groups, eps)?; + Ok(Self { norm, weight, bias, groups, eps }) + } + + pub fn forward(&self, x: &Tensor) -> Result { + if x.device().is_cpu() { + return cpu::group_norm_relu(x, &self.weight, &self.bias, self.groups, self.eps); + } + Ok(self.norm.forward(x)?.relu()?) + } +} + /// Layer norm over the channel axis of an NCHW tensor (`Sam3TrackerLayerNorm`, channels_first). pub fn ln_channels(x: &Tensor, norm: &LayerNorm) -> Result { let x = x.permute((0, 2, 3, 1))?; diff --git a/crates/segment/src/vit.rs b/crates/segment/src/vit.rs index 16b09a729b..1f356ad547 100644 --- a/crates/segment/src/vit.rs +++ b/crates/segment/src/vit.rs @@ -8,8 +8,8 @@ use candle_core::{D, Device, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, LayerNorm, VarBuilder}; -use crate::nn::{Attention, Mlp, ln, sdpa}; -use crate::{Error, Result}; +use crate::nn::{Attention, Mlp, ln, sdpa_tensors}; +use crate::{Error, Result, cpu}; pub const IMAGE: usize = 1008; pub const PATCH: usize = 14; @@ -19,14 +19,26 @@ pub const HIDDEN: usize = 1024; const HEADS: usize = 16; const HEAD_DIM: usize = HIDDEN / HEADS; const LAYERS: usize = 32; +const INTERMEDIATE: usize = 4736; const WINDOW: usize = 24; const GLOBAL: [usize; 4] = [7, 15, 23, 31]; const PRETRAIN_GRID: usize = 336 / PATCH; const EPS: f64 = 1e-6; +/// The attention score scale, `HEAD_DIM^-0.5`. A power of two, so scaling the queries instead +/// of the scores (on the CPU) gives the same scores, bit for bit. +const SCALE: f32 = 0.125; +const _: () = assert!(HEAD_DIM == 64); + +/// Cosine and sine tables `[N, head_dim]`, also as plain values for the CPU kernels. +struct Rope { + cos: Tensor, + sin: Tensor, + values: (Vec, Vec), +} /// Cosine and sine tables `[N, head_dim]` for a `side × side` grid whose coordinates are scaled /// by `scale` (`Sam3ViTRotaryEmbedding`: x frequencies then y, each duplicated pairwise). -fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tensor)> { +fn rope_tables(side: usize, scale: f64, device: &Device) -> Result { let spatial = HEAD_DIM / 2; let inv: Vec = (0..spatial).step_by(2).map(|i| 1.0 / 10000f64.powf(i as f64 / spatial as f64)).collect(); let n = side * side; @@ -44,7 +56,7 @@ fn rope_tables(side: usize, scale: f64, device: &Device) -> Result<(Tensor, Tens } } } - Ok((Tensor::from_vec(cos, (n, HEAD_DIM), device)?, Tensor::from_vec(sin, (n, HEAD_DIM), device)?)) + Ok(Rope { cos: Tensor::from_slice(&cos, (n, HEAD_DIM), device)?, sin: Tensor::from_slice(&sin, (n, HEAD_DIM), device)?, values: (cos, sin) }) } /// `x·cos + rotate_pairwise(x)·sin`, where rotate_pairwise maps (a, b) pairs to (−b, a). @@ -71,7 +83,12 @@ struct Layer { impl Layer { /// `x`: `[B, H, W, C]`. - fn forward(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn forward(&self, x: &Tensor, rope: &Rope) -> Result { + if x.device().is_cpu() { self.forward_cpu(x, rope) } else { self.forward_tensors(x, rope) } + } + + /// With candle's tensor operations (any device). + fn forward_tensors(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let y = self.ln1.forward(x)?; let y = match (h.checked_div(self.window), w.checked_div(self.window)) { @@ -90,21 +107,37 @@ impl Layer { Ok((x + y)?) } + /// [`Self::forward`] on the CPU: the same arithmetic, with the window partitioning, head + /// split, rotary encoding, bias adds, GELU and residual adds in fused parallel kernels. + fn forward_cpu(&self, x: &Tensor, rope: &Rope) -> Result { + let (b, h, w, _) = x.dims4()?; + let grid = cpu::Grid { b, h, w, win: self.window, heads: HEADS, head_dim: HEAD_DIM }; + let y = self.ln1.forward(x)?; + let [q, k, v, o] = self.attn.projections(); + let table = Some((rope.values.0.as_slice(), rope.values.1.as_slice())); + let q = cpu::heads(&y, q, grid, table, SCALE)?; + let k = cpu::heads(&y, k, grid, table, 1.0)?; + let v = cpu::heads(&y, v, grid, None, 1.0)?; + let att = cpu::attention(&q, &k, &v, grid)?; + let x = cpu::linear_add(&att, o, x)?; + self.mlp.forward_add(&self.ln2.forward(&x)?, &x) + } + /// RoPE self-attention over `[B, H, W, C]`. - fn attend(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attend(&self, x: &Tensor, rope: &Rope) -> Result { let (b, h, w, c) = x.dims4()?; let seq = x.reshape((b, h * w, c))?; Ok(self.attn_rope(&seq, rope)?.reshape((b, h, w, c))?) } - fn attn_rope(&self, x: &Tensor, rope: &(Tensor, Tensor)) -> Result { + fn attn_rope(&self, x: &Tensor, rope: &Rope) -> Result { let (b, n, _) = x.dims3()?; let split = |t: Tensor| -> Result { Ok(t.reshape((b, n, HEADS, HEAD_DIM))?.transpose(1, 2)?.contiguous()?) }; let (q, k, v) = self.attn.qkv(x)?; - let q = apply_rope(&split(q)?, &rope.0, &rope.1)?; - let k = apply_rope(&split(k)?, &rope.0, &rope.1)?; + let q = apply_rope(&split(q)?, &rope.cos, &rope.sin)?; + let k = apply_rope(&split(k)?, &rope.cos, &rope.sin)?; let v = split(v)?; - let o = sdpa(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; + let o = sdpa_tensors(&q, &k, &v, None, (HEAD_DIM as f64).powf(-0.5))?; let o = o.transpose(1, 2)?.reshape((b, n, HIDDEN))?; self.attn.out(&o) } @@ -115,8 +148,8 @@ pub struct Vit { pos: Tensor, ln_pre: LayerNorm, layers: Vec, - rope_window: (Tensor, Tensor), - rope_global: (Tensor, Tensor), + rope_window: Rope, + rope_global: Rope, } impl Vit { @@ -141,7 +174,7 @@ impl Vit { ln1: ln(HIDDEN, EPS, l.pp("layer_norm1"))?, attn: Attention::new(HIDDEN, HIDDEN, HEADS, l.pp("attention"))?, ln2: ln(HIDDEN, EPS, l.pp("layer_norm2"))?, - mlp: Mlp::new(HIDDEN, 4736, true, l.pp("mlp"))?, + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, l.pp("mlp"))?, window: if GLOBAL.contains(&i) { 0 } else { WINDOW }, }); } @@ -168,3 +201,57 @@ impl Vit { Ok(x.permute((0, 3, 1, 2))?.contiguous()?) } } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use candle_core::DType; + + use super::*; + + /// A layer with random weights. + fn layer(window: usize) -> Layer { + let d = Device::Cpu; + let mut t = HashMap::new(); + let mut add = |name: String, shape: &[usize], mean: f32| { + t.insert(name, Tensor::randn(mean, 0.05f32, shape, &d).unwrap()); + }; + for n in ["layer_norm1", "layer_norm2"] { + add(format!("{n}.weight"), &[HIDDEN], 1.0); + add(format!("{n}.bias"), &[HIDDEN], 0.0); + } + for n in ["q_proj", "k_proj", "v_proj", "o_proj"] { + add(format!("attention.{n}.weight"), &[HIDDEN, HIDDEN], 0.0); + add(format!("attention.{n}.bias"), &[HIDDEN], 0.0); + } + add("mlp.fc1.weight".into(), &[INTERMEDIATE, HIDDEN], 0.0); + add("mlp.fc1.bias".into(), &[INTERMEDIATE], 0.0); + add("mlp.fc2.weight".into(), &[HIDDEN, INTERMEDIATE], 0.0); + add("mlp.fc2.bias".into(), &[HIDDEN], 0.0); + let vb = VarBuilder::from_tensors(t, DType::F32, &d); + Layer { + ln1: ln(HIDDEN, EPS, vb.pp("layer_norm1")).unwrap(), + attn: Attention::new(HIDDEN, HIDDEN, HEADS, vb.pp("attention")).unwrap(), + ln2: ln(HIDDEN, EPS, vb.pp("layer_norm2")).unwrap(), + mlp: Mlp::new(HIDDEN, INTERMEDIATE, true, vb.pp("mlp")).unwrap(), + window, + } + } + + #[test] + fn cpu_kernels_match_the_tensor_ops() { + // two images each: 12 × 24 tokens in 6 × 6 windows, and 12 × 12 with global attention + for (window, (h, w), side, scale) in [(6, (12, 24), 6, 1.0), (0, (12, 12), 12, 0.5)] { + let x = Tensor::randn(0f32, 1.0, (2, h, w, HIDDEN), &Device::Cpu).unwrap(); + let (l, rope) = (layer(window), rope_tables(side, scale, &Device::Cpu).unwrap()); + let want = l.forward_tensors(&x, &rope).unwrap().flatten_all().unwrap().to_vec1::().unwrap(); + let got = l.forward_cpu(&x, &rope).unwrap(); + assert_eq!(got.dims(), x.dims()); + let got = got.flatten_all().unwrap().to_vec1::().unwrap(); + let err = want.iter().zip(&got).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + // the same arithmetic (one attention block per window here): equal on x86-64 + assert!(err <= 1e-5, "window {window}: max error {err}"); + } + } +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index b02912abc1..37cd9c1639 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -29,13 +29,13 @@ In the Masking panel (M): so small objects get 5–10× finer edges than one pass over the whole photo gives. The first Object or Describe on a photo analyzes it (the image encoder runs once per photo and -look: ~3 s on an Apple M4 Pro, plus a one-time ~6 s for compiling GPU kernels and loading the -model after launch). That starts in the background as soon as you pick Object; after it, each -click takes ~35 ms and each description ~0.6 s. Everything the model does runs on its own worker -thread: the window stays responsive, a click shows its dot at once and the selection follows -when it's computed ("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is -unloaded after 10 minutes without use (it takes several GB of memory) and loaded again when -needed. +look: ~3 s on an Apple M4 Pro, ~11 s on the CPU of a 12-core Ryzen 9 3900X, plus a one-time ~6 s +for compiling GPU kernels and loading the model after launch). That starts in the background as +soon as you pick Object; after it, each click takes ~35 ms and each description ~0.6 s (~0.15 s +and ~2 s on that CPU). Everything the model does runs on its own worker thread: the window stays +responsive, a click shows its dot at once and the selection follows when it's computed +("Selecting…" / "Analyzing the photo…" under the mask tiles). The model is unloaded after 10 +minutes without use (it takes several GB of memory) and loaded again when needed. The result is stored with the mask: the model's 288 × 288 mask logits over the uncropped photo (quantized, compressed, ~10–30 KB). Renders and exports sample them at any resolution and never @@ -230,6 +230,18 @@ wait and return the result (when built with the `sam` feature; the default CLI h - Accuracy: `crates/segment/tests/reference.rs` compares every stage against the Python reference (`tools/sam3_reference.py`); on Metal the backbone matches to 7e-5 relative error and masks to ~5e-5. f16 was tried and rejected (overflow, ~7 % faster). +- Speed on the CPU: candle runs elementwise operations and layout copies on one thread, batched + matrix products one pair after another and transposed convolutions one output channel at a + time. `cpu.rs` fuses the bias adds, activations, rotary encoding, window partitioning, head + split/merge, the detector's box bias and the pixel decoder's GroupNorm into parallel kernels + (the same operations in the same order: bit-identical), runs attention as one task per batch, + head and block of query rows (256 KB of scores, so they stay in the core's cache), and the + necks' 2 × 2 transposed convolutions as one matrix product each. Those two change how gemm + blocks its sums, so results move by float rounding only, as they do between two CPUs (gemm + picks its blocking from the cache sizes): against the tensor operations the backbone differs + by 1e-5 relative and the masks by at most 7e-4, and fewer than 4e-7 of the mask pixels change + side. On a 12-core Ryzen 9 3900X: encode ~37 → ~11 s, a description ~6 → ~2 s, getting ready + for clicks ~2.3 → ~0.8 s. - The engine feature `sam` (on in the desktop app, off for web and CLI) gates the model; without it the commands report that the build has no AI masks.