Files
helgehelge123andClaude Opus 5.5 357b16b8d8 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 <noreply@anthropic.com>
2026-10-16 00:05:42 +02:00

32 lines
975 B
TOML

[package]
name = "lightcraft-segment"
version.workspace = true
edition.workspace = true
license = "Apache-2.0"
description = "LightCraft segmentation: SAM 3 (Segment Anything with Concepts) inference in pure Rust (L3)"
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# the model runs natively only (the web build has no AI masks)
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
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"] }
candle-nn = { workspace = true, features = ["metal"] }
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }