From ba6f22567daa37cd8af4c7f47ca52220021b6f8b Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:47 +0200 Subject: [PATCH 1/2] M12: SAM 3 mask decoder on the GPU (wgpu), and the docs for all of SAM 3 on the GPU Part 5 of 5 of #2167. The text detector's mask decoder runs on the GPU device of the image encoder: the prompt cross-attention of the memory (the DETR attention), the pixel decoder up to 288^2 (the necks' implicit-GEMM 3 x 3 convolution, a two-pass GroupNorm, ReLU), then the mask products. The instance projection is folded into the 200 mask embeddings on the CPU, and the semantic projection (#1963) is one more row, so the GPU returns the per-query masks and the semantic mask in one product. Its weights load on the first text prompt. The parity test checks the semantic mask too. docs/gpu-pipeline.md and docs/ai-masks.md describe every part, with the measured timings and accuracy, and what happens on an adapter that lacks the limits or whose device can't be created. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/examples/sam3_backbone_bench.rs | 40 ++- crates/gpu/src/sam3.rs | 48 ++- crates/gpu/src/sam3/pixel.rs | 377 +++++++++++++++++++++ crates/gpu/src/sam3/pixel/tests.rs | 165 +++++++++ crates/gpu/src/wgsl/sam3_pixel.wgsl | 161 +++++++++ crates/gpu/tests/it/main.rs | 2 + crates/gpu/tests/it/sam3_mask_decoder.rs | 287 ++++++++++++++++ docs/ai-masks.md | 96 +++++- docs/gpu-pipeline.md | 160 +++++++++ docs/hardware-parity.md | 7 +- docs/parity-checklist.md | 8 +- docs/target-app-parity.md | 6 +- 12 files changed, 1334 insertions(+), 23 deletions(-) create mode 100644 crates/gpu/src/sam3/pixel.rs create mode 100644 crates/gpu/src/sam3/pixel/tests.rs create mode 100644 crates/gpu/src/wgsl/sam3_pixel.wgsl create mode 100644 crates/gpu/tests/it/sam3_mask_decoder.rs diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs index 700c53c0a2..eec3de8314 100644 --- a/crates/gpu/examples/sam3_backbone_bench.rs +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -5,10 +5,11 @@ //! //! The model directory is `LIGHTCRAFT_SAM3_DIR`, else `~/.config/lightcraft/models/sam3`. Prints the device and //! kernel creation, the weight upload, the first and the warm forward passes, each neck's first run (which builds -//! it) and warm runs, the CPU forward pass and how far the two outputs are apart. `--app` then times what the app -//! does per photo, with the model loaded as the app loads it (GPU backbone, necks and DETR encoder, the rest in candle on the CPU): encode, -//! click features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they -//! ran on the GPU). +//! it) and warm runs, the text detector's mask decoder (first and warm, on made-up inputs), the CPU forward pass and +//! how far the two outputs are apart. `--app` then times what the app does per photo, with the model loaded as the +//! app loads it (GPU backbone, necks, DETR encoder and mask decoder, the rest in candle on the CPU): encode, click +//! features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they ran on +//! the GPU; `--cpu-masks`: with the mask decoder in candle). use std::path::PathBuf; use std::time::Instant; @@ -35,6 +36,7 @@ fn main() -> Result<(), String> { let cpu = !args.iter().any(|a| a == "--no-cpu"); let app = args.iter().any(|a| a == "--app"); let cpu_necks = args.iter().any(|a| a == "--cpu-necks"); + let cpu_masks = args.iter().any(|a| a == "--cpu-masks"); let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?; let scene = &lightcraft_scenes::demo_library()[0]; @@ -75,6 +77,23 @@ fn main() -> Result<(), String> { } } println!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6); + { + let (memory, text, valid) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256], vec![true; 32]); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + match timed(runs, || gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).map(drop)) { + Ok((first, best, mean)) => { + let (w, b) = gpu.mask_decoder_bytes().unwrap_or_default(); + println!( + "mask decoder (200 queries): first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms); {:.0} MB weights, {:.0} MB work buffers", + w as f64 / 1e6, + b as f64 / 1e6 + ); + } + Err(e) => println!("mask decoder failed on the GPU: {e}"), + } + } + if cpu { let model = Sam3::load_on(&dir, candle_core::Device::Cpu).map_err(|e| e.to_string())?; let px = candle_core::Tensor::from_vec(pixels.clone(), (1, 3, INPUT, INPUT), &candle_core::Device::Cpu).map_err(|e| e.to_string())?; @@ -96,7 +115,7 @@ fn main() -> Result<(), String> { } drop(gpu); if app { - as_the_app(&dir, &rgb, (img.width, img.height), runs, cpu_necks)?; + as_the_app(&dir, &rgb, (img.width, img.height), runs, (cpu_necks, cpu_masks))?; } // no GPU work in flight when the process ends (issue #620) lightcraft_gpu::begin_shutdown(); @@ -124,10 +143,11 @@ fn ms(t: Instant) -> String { format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3) } -/// The model's GPU accelerator with the necks left to candle (`--cpu-necks`). +/// The model's GPU accelerator with the necks (`--cpu-necks`) or the mask decoder (`--cpu-masks`) left to candle. struct Heads { gpu: Box, necks: bool, + masks: bool, } impl BackboneAccel for Heads { @@ -144,7 +164,7 @@ impl BackboneAccel for Heads { self.gpu.runs_detr_encoder() } fn runs_mask_decoder(&self) -> bool { - self.gpu.runs_mask_decoder() + self.masks && self.gpu.runs_mask_decoder() } fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { self.gpu.neck(which, backbone, n) @@ -166,9 +186,11 @@ impl BackboneAccel for Heads { } /// The model as the app loads it, timed per photo: encode, click features, a click, two Describes. -fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, cpu_necks: bool) -> Result<(), String> { +fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, (cpu_necks, cpu_masks): (bool, bool)) -> Result<(), String> { let t = Instant::now(); - let make = |r: &WeightReader| -> Result, String> { Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks })) }; + let make = |r: &WeightReader| -> Result, String> { + Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks, masks: !cpu_masks })) + }; let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, make).map_err(|e| e.to_string())?; println!("app: load {} on {}", ms(t), model.backbone_device()); let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index 2265533336..1c059268d7 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -17,8 +17,8 @@ //! per layer and reads the result back once. No subgroups or shader-f16 needed. The two necks that follow the //! backbone run on the same device, built when first asked for (`sam3/neck.rs`). //! -//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`); its weights load on the first text -//! prompt. The mask decoder stays in candle on the CPU. +//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`) and its mask decoder (`sam3/pixel.rs`); +//! their weights load on the first text prompt. //! //! The device is its own (like denoise's and faces'): it respects the same switches as GPU rendering //! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, `LIGHTCRAFT_GPU_ADAPTER`, the GPU preference), the crash sentinel @@ -35,6 +35,7 @@ use wgpu::util::DeviceExt; mod detr; mod neck; +mod pixel; #[cfg(test)] mod tests; @@ -956,6 +957,8 @@ pub struct Sam3Gpu { detr: detr::Encoder, /// The feature pyramids, built on first use. necks: neck::Necks, + /// The detector's mask decoder, loaded on the first text prompt. + masks: pixel::MaskDecoder, } /// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing, @@ -1051,7 +1054,18 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) let recorded = g.record(); let detr = detr::Encoder::new(weights.clone()); let necks = neck::Necks::new(weights.clone()); - Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision, detr, necks }) + let masks = pixel::MaskDecoder::new(weights.clone()); + Ok(Sam3Gpu { + dev, + recorded, + work: Mutex::new(Work { pixels, out: y, staging }), + weight_bytes: ld.bytes, + work_bytes, + precision, + detr, + necks, + masks, + }) } /// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). @@ -1078,6 +1092,11 @@ impl Sam3Gpu { self.detr.bytes() } + /// Bytes of device memory the mask decoder's weights and work buffers take, once a text prompt loaded them. + pub fn mask_decoder_bytes(&self) -> Option<(u64, u64)> { + self.masks.bytes() + } + fn run(&self, pixels: &[f32]) -> Result, String> { if pixels.len() != 3 * IMAGE * IMAGE { return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len())); @@ -1125,6 +1144,25 @@ impl BackboneAccel for Sam3Gpu { guarded("the SAM 3 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid)) } + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + if let Some(why) = broken_reason() { + return Err(format!("the GPU is not used any more: {why}")); + } + if let Some(why) = crate::switched_off() { + return Err(why); + } + let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) }; + guarded("the SAM 3 mask decoder", || self.masks.run(self.dev, memory, text, valid, levels, rows, bias)) + } + fn closing(&self) -> bool { crate::shutting_down() } @@ -1137,6 +1175,10 @@ impl BackboneAccel for Sam3Gpu { true } + fn runs_mask_decoder(&self) -> bool { + true + } + fn device(&self) -> String { let weights = match self.precision { Precision::F32 => "", diff --git a/crates/gpu/src/sam3/pixel.rs b/crates/gpu/src/sam3/pixel.rs new file mode 100644 index 0000000000..08d5f5b749 --- /dev/null +++ b/crates/gpu/src/sam3/pixel.rs @@ -0,0 +1,377 @@ +//! The mask decoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): the +//! DETR encoder's memory (72 × 72 tokens of 256) attends to the prompt and is added to it (`prompt_cross_attn`, after +//! its layer norm), then the pixel decoder brings it up to 288 × 288 in two stages, each a nearest 2 × up-sampling plus +//! the detector neck's level of that size (144², then 288²) → 3 × 3 convolution → GroupNorm (8 groups, eps 1e-5) → +//! ReLU; last, every row of a `[r, 256]` matrix (with its bias) is a 1 × 1 projection of the decoder's output, an image +//! `[r, 288, 288]`. The detector passes its 200 mask embeddings with the instance projection folded in, so these are the +//! per-query mask logits. ~0.9–1.4 s per prompt on the CPU through candle, most of it the 288² convolution. +//! +//! Images are pixel rows (`[pixels, channels]`), as in the necks (`sam3/neck.rs`): the convolutions are the necks' +//! implicit GEMM, the projection the backbone's matrix product (`[pixels, 256] · [r, 256]ᵀ`, then `to_chw`), the +//! prompt attention the DETR encoder's kernels (`sam3/detr.rs`). `wgsl/sam3_pixel.wgsl` adds the up-sampling, which +//! adds the channels-first neck level as uploaded, and GroupNorm + ReLU: two-pass statistics per chunk of 256 pixels, +//! merged per group (the parallel variance formula), then applied in place. +//! +//! Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, ~280 MB of work buffers. A prompt uploads +//! the memory, the prompt's tokens and padding bias, both neck levels (106 MB; they stay on the CPU with the image's +//! features, see `docs/gpu-pipeline.md`) and the rows, submits once and reads `r · 288²` numbers back. The dispatches +//! are recorded once per row count. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::detr::{self, Operand}; +use super::neck::{self, conv_weights, scoped}; +use super::{Dev, Graph, Precision, Recorded, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the decoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.mask_decoder"; +/// The memory's side (72 × 72 tokens), the width of everything, the prompt's tokens. +const GRID: usize = 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +/// The decoder's stages (each doubles the side): 144², 288². +const STAGES: usize = 2; +/// The output's side. +const SIDE: usize = GRID << STAGES; +/// GroupNorm's groups and eps (`candle_nn::group_norm(8, 256, 1e-5)`), and PyTorch's layer norm eps. +const GROUPS: usize = 8; +const EPS: f32 = 1e-5; +/// Pixels per workgroup of the GroupNorm statistics. +const CHUNK: usize = 256; + +struct Kernels { + upsample_add: wgpu::ComputePipeline, + group_stats: wgpu::ComputePipeline, + group_merge: wgpu::ComputePipeline, + group_norm_relu: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The decoder's own kernels, compiled on first use. +fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> { + KERNELS + .get_or_init(|| { + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let source = include_str!("../wgsl/sam3_pixel.wgsl"); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 pixel", source, entry); + let k = Kernels { + upsample_add: pipe("upsample_add"), + group_stats: pipe("group_stats"), + group_merge: pipe("group_merge"), + group_norm_relu: pipe("group_norm_relu"), + }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 mask decoder kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// Floats of the GroupNorm statistics of chunks for an image of `pixels`, `groups` groups. +fn partials_len(pixels: usize, groups: usize) -> usize { + pixels.div_ceil(CHUNK) * groups * 2 +} + +impl Graph { + /// Nearest up-sampling of the rows `src` (`[from², channels]`) to `to × to`, plus the channels-first image `skip` + /// (`[channels, to, to]`), into the rows `dst` (`[to², channels]`). + fn upsample_add( + &mut self, + k: &'static Kernels, + [src, skip, dst]: [&wgpu::Buffer; 3], + channels: usize, + (from, to): (usize, usize), + ) -> Result<(), String> { + if from == 0 || to < from || channels == 0 { + return Err("an up-sampling the SAM 3 kernel cannot do".into()); + } + let count = channels.checked_mul(to * to).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + let params = [u32_of(channels)?, u32_of(to)?, u32_of(from)?, 0, 0, 0, u32_of(count)?, row]; + self.push(&k.upsample_add, params, [src, skip, &self.dev.dummy, dst], g); + Ok(()) + } + + /// GroupNorm (`groups` groups of channels, eps) and ReLU in place on the rows `x` (`[pixels, channels]`, channels + /// ≤ 256), with the per-channel `gamma` and `beta`; `partials` (at least [`partials_len`] floats) and `stats` + /// (2 · groups) hold the statistics on the way. + #[allow(clippy::too_many_arguments)] + fn group_norm_relu( + &mut self, + k: &'static Kernels, + [x, gamma, beta]: [&wgpu::Buffer; 3], + [partials, stats]: [&wgpu::Buffer; 2], + (pixels, channels, groups): (usize, usize, usize), + eps: f32, + ) -> Result<(), String> { + if pixels == 0 || channels == 0 || channels > 256 || groups == 0 || !channels.is_multiple_of(groups) { + return Err("a GroupNorm the SAM 3 kernel cannot do".into()); + } + let dummy = &self.dev.dummy; + let chunks = pixels.div_ceil(CHUNK); + let (g, row) = self.flat(chunks)?; + let params = [u32_of(channels)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, 0, 0, 0, row]; + self.push(&k.group_stats, params, [x, dummy, dummy, partials], g); + let params = [u32_of(chunks)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, eps.to_bits(), u32_of(channels / groups)?, 0, 0]; + self.push(&k.group_merge, params, [partials, dummy, dummy, stats], [u32_of(groups)?, 1, 1]); + let count = pixels.checked_mul(channels).ok_or("an image too large")?; + let (g, row) = self.flat(count.div_ceil(256))?; + self.push(&k.group_norm_relu, [u32_of(channels)?, 0, 0, u32_of(groups)?, 0, 0, u32_of(count)?, row], [stats, gamma, beta, x], g); + Ok(()) + } +} + +/// The decoder's weights on the device: (weight, bias) pairs, the prompt attention's k | v concatenated, the +/// convolutions as rows `[cout, 3, 3, cin]`. +struct Weights { + ln: [wgpu::Buffer; 2], + q: [wgpu::Buffer; 2], + kv: [wgpu::Buffer; 2], + o: [wgpu::Buffer; 2], + convs: Vec<[wgpu::Buffer; 2]>, + norms: Vec<[wgpu::Buffer; 2]>, +} + +/// Reads the decoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn read(&mut self, names: &[String], shape: &[usize]) -> Result, String> { + let mut all = Vec::with_capacity(names.len() * shape.iter().product::()); + for name in names { + let full = format!("{PREFIX}.{name}"); + let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?; + if got != shape { + return Err(format!("{full}: shape {got:?}, expected {shape:?}")); + } + all.extend(data); + } + self.bytes += all.len() as u64 * 4; + Ok(all) + } + + /// A pair of `{name}.weight` (`[n, k]`, several concatenated along n) and `{name}.bias` (or a norm's scale and shift + /// with `k` 0), uploaded. + fn pair(&mut self, dev: &Dev, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> { + let w: Vec = names.iter().map(|n| format!("{n}.weight")).collect(); + let b: Vec = names.iter().map(|n| format!("{n}.bias")).collect(); + let shape: &[usize] = if k == 0 { &[n] } else { &[n, k] }; + let label = names.first().map_or("weight", String::as_str); + Ok([upload(dev, label, &self.read(&w, shape)?), upload(dev, label, &self.read(&b, &[n])?)]) + } + + fn load(&mut self, dev: &Dev) -> Result { + let a = "prompt_cross_attn"; + let proj = |ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + let mut convs = Vec::with_capacity(STAGES); + let mut norms = Vec::with_capacity(STAGES); + for i in 0..STAGES { + let name = format!("pixel_decoder.conv_layers.{i}"); + let w = self.read(&[format!("{name}.weight")], &[WIDTH, WIDTH, 3, 3])?; + let b = self.read(&[format!("{name}.bias")], &[WIDTH])?; + convs.push(conv_weights(dev, &name, &w, &b, (WIDTH, WIDTH, 3))); + norms.push(self.pair(dev, &[format!("pixel_decoder.norms.{i}")], WIDTH, 0)?); + } + Ok(Weights { + ln: self.pair(dev, &["prompt_cross_attn_norm".to_string()], WIDTH, 0)?, + q: self.pair(dev, &proj(&["q"]), WIDTH, WIDTH)?, + kv: self.pair(dev, &proj(&["k", "v"]), WIDTH, WIDTH)?, + o: self.pair(dev, &proj(&["o"]), WIDTH, WIDTH)?, + convs, + norms, + }) + } +} + +/// The buffers a prompt writes and reads, and its dispatches (recorded for one row count). +struct Work { + /// The memory in, then the memory after the prompt attention. + x: wgpu::Buffer, + text: wgpu::Buffer, + /// The prompt attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + /// The neck's levels as uploaded (`[256, 144, 144]`, `[256, 288, 288]`); the projection's channels-first result + /// ends in the second. + skip1: wgpu::Buffer, + skip0: wgpu::Buffer, + /// Two 288² images the steps alternate between (the prompt attention's smaller ones too). + a: wgpu::Buffer, + b: wgpu::Buffer, + rows: wgpu::Buffer, + row_bias: wgpu::Buffer, + partials: wgpu::Buffer, + stats: wgpu::Buffer, + staging: wgpu::Buffer, + recorded: Option<(usize, Recorded)>, +} + +impl Work { + fn new(dev: &Dev) -> Work { + let image = |label: &str| buffer(dev, label, SIDE * SIDE * WIDTH); + Work { + x: buffer(dev, "mask memory", GRID * GRID * WIDTH), + text: buffer(dev, "mask prompt", TEXT * WIDTH), + text_kv: buffer(dev, "mask prompt k|v", TEXT * 2 * WIDTH + TEXT), + skip1: buffer(dev, "mask level 1", WIDTH * (SIDE / 2) * (SIDE / 2)), + skip0: image("mask level 0"), + a: image("mask ping"), + b: image("mask pong"), + rows: buffer(dev, "mask rows", WIDTH * WIDTH), + row_bias: buffer(dev, "mask row bias", WIDTH), + partials: buffer(dev, "mask norm partials", partials_len(SIDE * SIDE, GROUPS)), + stats: buffer(dev, "mask norm stats", 2 * GROUPS), + staging: dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("mask read-back"), + size: (SIDE * SIDE * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + recorded: None, + } + } + + /// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted. + fn bytes() -> u64 { + let floats = GRID * GRID * WIDTH + + TEXT * (3 * WIDTH + 1) + + WIDTH * (SIDE / 2) * (SIDE / 2) + + 3 * SIDE * SIDE * WIDTH + + WIDTH * (WIDTH + 1) + + partials_len(SIDE * SIDE, GROUPS) + + 2 * GROUPS; + (floats * 4) as u64 + } +} + +/// The dispatches of a prompt with `r` rows: everything after the uploads, the result in `work.skip0`. +fn record(dev: &'static Dev, w: &Weights, work: &Work, r: usize) -> Result { + let (kd, kn, k) = (detr::kernels(dev)?, neck::kernels(dev)?, kernels(dev)?); + let mut g = Graph::new(dev); + let tokens = GRID * GRID; + // the memory attends to the prompt (padding masked): x += o(attention(q(ln(x)), k | v(text))) + g.layernorm_torch([&work.x, &w.ln[0], &w.ln[1], &work.a], tokens, WIDTH)?; + g.matmul([&work.a, &w.q[0], &w.q[1], &work.b], (tokens, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&work.text, &w.kv[0], &w.kv[1], &work.text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let q = Operand { buffer: &work.b, stride: WIDTH, offset: 0 }; + let (tk, tv) = + (Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(kd, [q, tk, tv], Some(TEXT * 2 * WIDTH), &work.a, (tokens, TEXT, WIDTH / HEAD_DIM))?; + g.matmul([&work.a, &w.o[0], &w.o[1], &work.x], (tokens, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // the pixel decoder: up-sample + the neck's level → 3 × 3 convolution → GroupNorm → ReLU, at 144² and at 288² + let mut cur = &work.x; + let mut side = GRID; + for (i, skip) in [&work.skip1, &work.skip0].into_iter().enumerate() { + let (Some(conv), Some(norm)) = (w.convs.get(i), w.norms.get(i)) else { return Err("a pixel decoder stage without weights".into()) }; + g.upsample_add(k, [cur, skip, &work.a], WIDTH, (side, 2 * side))?; + side *= 2; + g.conv3(kn, [&work.a, &conv[0], &conv[1], &work.b], side, (WIDTH, WIDTH))?; + g.group_norm_relu(k, [&work.b, &norm[0], &norm[1]], [&work.partials, &work.stats], (side * side, WIDTH, GROUPS), EPS)?; + cur = &work.b; + } + // each row a 1 × 1 projection of the decoder's output: [pixels, r], then channels-first into the spent level 0 + g.matmul([&work.b, &work.rows, &work.row_bias, &work.a], (side * side, r, WIDTH), 1, false, false, Precision::F32)?; + g.channels_first(&work.a, &work.skip0, r, side, side)?; + Ok(g.record()) +} + +/// The decoder with its weights on the device. +struct Built { + weights: Weights, + /// One prompt at a time (they share the work buffers). + work: Mutex, + weight_bytes: u64, +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + // every kernel compiles before anything is uploaded + detr::kernels(dev)?; + neck::kernels(dev)?; + kernels(dev)?; + scoped(dev, "the SAM 3 mask decoder", || { + let mut ld = Loader { weights, bytes: 0 }; + let w = ld.load(dev)?; + Ok(Built { weights: w, work: Mutex::new(Work::new(dev)), weight_bytes: ld.bytes }) + }) +} + +/// The mask decoder, built on first use from the checkpoint the backbone came from. +pub(super) struct MaskDecoder { + weights: WeightReader, + built: OnceLock>, +} + +impl MaskDecoder { + pub(super) fn new(weights: WeightReader) -> Self { + Self { weights, built: OnceLock::new() } + } + + /// Bytes of device memory the weights and the work buffers take, once built. + pub(super) fn bytes(&self) -> Option<(u64, u64)> { + self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, Work::bytes())) + } + + /// `[r, 288, 288]` for the encoder memory `[5184, 256]`, the prompt's tokens `[32, 256]` (`valid`: its real ones), + /// the detector neck's levels `[256, 144, 144]` and `[256, 288, 288]` (channels-first) and the rows `[r, 256]` + /// with their bias `[r]` (1 ≤ r ≤ 256). + #[allow(clippy::too_many_arguments)] + pub(super) fn run( + &self, + dev: &'static Dev, + memory: &[f32], + text: &[f32], + valid: &[bool], + [level1, level0]: [&[f32]; 2], + rows: &[f32], + row_bias: &[f32], + ) -> Result, String> { + let r = row_bias.len(); + let (l1, l0) = (WIDTH * (SIDE / 2) * (SIDE / 2), WIDTH * SIDE * SIDE); + if memory.len() != GRID * GRID * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT || level1.len() != l1 || level0.len() != l0 { + return Err(format!( + "{} memory, {} prompt values, {} prompt tokens and levels of {} and {} values, expected {GRID}² × {WIDTH}, {TEXT} × {WIDTH}, {TEXT}, {l1} and {l0}", + memory.len(), + text.len(), + valid.len(), + level1.len(), + level0.len() + )); + } + if r == 0 || r > WIDTH || rows.len() != r * WIDTH { + return Err(format!("{} row values and {r} biases, expected r × {WIDTH} and r (1 ≤ r ≤ {WIDTH})", rows.len())); + } + let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?; + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let mut work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + if work.recorded.as_ref().is_none_or(|(n, _)| *n != r) { + let recorded = scoped(dev, "the SAM 3 mask decoder", || record(dev, &b.weights, &work, r))?; + work.recorded = Some((r, recorded)); + } + let q = &dev.queue; + q.write_buffer(&work.x, 0, bytemuck::cast_slice(memory)); + q.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + q.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + q.write_buffer(&work.skip1, 0, bytemuck::cast_slice(level1)); + q.write_buffer(&work.skip0, 0, bytemuck::cast_slice(level0)); + q.write_buffer(&work.rows, 0, bytemuck::cast_slice(rows)); + q.write_buffer(&work.row_bias, 0, bytemuck::cast_slice(row_bias)); + let Some((_, recorded)) = &work.recorded else { return Err("the mask decoder was not recorded".into()) }; + let out = recorded.run("the SAM 3 mask decoder", dev, &work.skip0, &work.staging, r * SIDE * SIDE)?; + if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("the GPU mask decoder produced non-finite values".into()); + } + Ok(out) + } +} diff --git a/crates/gpu/src/sam3/pixel/tests.rs b/crates/gpu/src/sam3/pixel/tests.rs new file mode 100644 index 0000000000..ece1185c0e --- /dev/null +++ b/crates/gpu/src/sam3/pixel/tests.rs @@ -0,0 +1,165 @@ +//! The mask decoder's kernels against plain loops in f64: the up-sampling with the channels-first level added (odd +//! sides, cut-off workgroups), GroupNorm + ReLU (chunks cut off, a large mean, group sizes), and one whole pixel +//! decoder stage (up-sampling → 3 × 3 convolution at every border → GroupNorm → ReLU) on small images. The real +//! decoder against candle: `tests/it/sam3_mask_decoder.rs`. + +use super::super::neck::tests::{conv_ref, f32s, f64s}; +use super::super::tests::{gpu, read, values, worst}; +use super::*; + +fn pixel_kernels(d: &'static Dev) -> &'static Kernels { + kernels(d).unwrap() +} + +/// Nearest up-sampling of the rows `x` (`[from², c]`) to `to²`, plus the channels-first `skip` (`[c, to, to]`). +fn upsample_add_ref(x: &[f64], skip: &[f32], c: usize, (from, to): (usize, usize)) -> Vec { + let mut y = vec![0f64; to * to * c]; + for r in 0..to { + for col in 0..to { + // candle's upsample_nearest2d: floor(i · from / to) + let (sr, sc) = ((r as f64 * from as f64 / to as f64) as usize, (col as f64 * from as f64 / to as f64) as usize); + for ch in 0..c { + y[(r * to + col) * c + ch] = x[(sr * from + sc) * c + ch] + skip[ch * to * to + r * to + col] as f64; + } + } + } + y +} + +/// GroupNorm (centred two-pass variance, as candle's) and ReLU on the rows `x` (`[pixels, c]`). +fn group_norm_relu_ref(x: &[f64], c: usize, groups: usize, gamma: &[f32], beta: &[f32], eps: f64) -> Vec { + let pixels = x.len() / c; + let per = c / groups; + let mut y = x.to_vec(); + for g in 0..groups { + let at = |p: usize, i: usize| x[p * c + g * per + i]; + let n = (pixels * per) as f64; + let mean = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| at(p, i)).sum::() / n; + let var = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| (at(p, i) - mean).powi(2)).sum::() / n; + for p in 0..pixels { + for i in 0..per { + let ch = g * per + i; + let v = (x[p * c + ch] - mean) / (var + eps).sqrt() * gamma[ch] as f64 + beta[ch] as f64; + y[p * c + ch] = v.max(0.0); + } + } + } + y +} + +#[test] +fn up_sampling_adds_the_channels_first_level() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // the decoder's doublings, an odd one, and channels that leave the last workgroup part empty + for (case, (from, to, c)) in [(3usize, 6usize, 4usize), (5, 10, 12), (4, 7, 3), (1, 2, 256)].into_iter().enumerate() { + let x = values(from * from * c, 100 + case as u64, 1.0); + let skip = values(c * to * to, 110 + case as u64, 1.0); + let (bx, bs, by) = (upload(d, "x", &x), upload(d, "skip", &skip), buffer(d, "y", to * to * c)); + let mut g = Graph::new(d); + g.upsample_add(k, [&bx, &bs, &by], c, (from, to)).unwrap(); + let got = read(d, g, &by, to * to * c); + let err = worst(&got, &f32s(&upsample_add_ref(&f64s(&x), &skip, c, (from, to)))); + assert!(err < 1e-6, "case {case}: off by {err}"); + } +} + +#[test] +fn group_norm_and_relu_give_the_definition() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + // one chunk cut short; several with the last cut short; the decoder's 256 channels in 8 groups over chunks of + // 256 pixels, around a mean far from 0 (where E[x²] − E[x]² in f32 would lose the variance) + for (case, (pixels, c, groups, offset)) in + [(37usize, 16usize, 4usize, 0f32), (700, 24, 3, 0.0), (1100, 256, 8, 0.0), (600, 256, 8, 50.0), (5, 8, 1, 0.0)].into_iter().enumerate() + { + let x: Vec = values(pixels * c, 120 + case as u64, 2.0).iter().map(|v| v + offset).collect(); + let gamma = values(c, 130 + case as u64, 1.5); + let beta = values(c, 140 + case as u64, 0.5); + // normed in place, then read back: a buffer that can be copied from + let bx = buffer(d, "x", pixels * c); + d.queue.write_buffer(&bx, 0, bytemuck::cast_slice(&x)); + let (bg, bb) = (upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(pixels, groups)), buffer(d, "stats", 2 * groups)); + let mut g = Graph::new(d); + g.group_norm_relu(k, [&bx, &bg, &bb], [&partials, &stats], (pixels, c, groups), EPS).unwrap(); + let got = read(d, g, &bx, pixels * c); + let want = f32s(&group_norm_relu_ref(&f64s(&x), c, groups, &gamma, &beta, f64::from(EPS))); + let err = worst(&got, &want); + assert!(err < 2e-5, "case {case} ({pixels} pixels, {c} channels, {groups} groups): off by {err}"); + assert!(got.iter().all(|v| *v >= 0.0), "case {case}: ReLU"); + } +} + +#[test] +fn a_small_pixel_decoder_stage_gives_the_definition() { + let Some(d) = gpu() else { return }; + let (k, kn) = (pixel_kernels(d), neck::kernels(d).unwrap()); + // two stages as in the decoder (3² → 6² → 12²), 16 channels in 4 groups + let (c, groups) = (16usize, 4usize); + let x = values(3 * 3 * c, 150, 1.0); + let mut want = f64s(&x); + let mut cur = upload(d, "x", &x); + let mut g = Graph::new(d); + let mut side = 3; + for stage in 0..2u64 { + let skip = values(c * 4 * side * side, 160 + stage, 1.0); + let (w, b) = (values(c * c * 9, 170 + stage, 0.3), values(c, 180 + stage, 0.3)); + let (gamma, beta) = (values(c, 190 + stage, 1.0), values(c, 200 + stage, 0.3)); + want = upsample_add_ref(&want, &skip, c, (side, 2 * side)); + side *= 2; + want = conv_ref(&want, side, (c, c, 3), &w, &b); + want = group_norm_relu_ref(&want, c, groups, &gamma, &beta, f64::from(EPS)); + + let up = buffer(d, "up", side * side * c); + let out = buffer(d, "out", side * side * c); + let [bw, bb] = conv_weights(d, "conv", &w, &b, (c, c, 3)); + let (bs, bg, bt) = (upload(d, "skip", &skip), upload(d, "gamma", &gamma), upload(d, "beta", &beta)); + let (partials, stats) = (buffer(d, "partials", partials_len(side * side, groups)), buffer(d, "stats", 2 * groups)); + g.upsample_add(k, [&cur, &bs, &up], c, (side / 2, side)).unwrap(); + g.conv3(kn, [&up, &bw, &bb, &out], side, (c, c)).unwrap(); + g.group_norm_relu(k, [&out, &bg, &bt], [&partials, &stats], (side * side, c, groups), EPS).unwrap(); + cur = out; + } + let got = read(d, g, &cur, side * side * c); + let err = worst(&got, &f32s(&want)); + assert!(err < 1e-4, "off by {err}"); +} + +#[test] +fn the_mask_decoder_kernels_refuse_what_they_cannot_do() { + let Some(d) = gpu() else { return }; + let k = pixel_kernels(d); + let b = buffer(d, "b", 16); + let mut g = Graph::new(d); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (0, 2)).is_err(), "an empty image"); + assert!(g.upsample_add(k, [&b, &b, &b], 4, (4, 2)).is_err(), "down-sampling"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 12, 8), EPS).is_err(), "channels not a multiple of the groups"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 512, 8), EPS).is_err(), "more channels than threads"); + assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (0, 8, 8), EPS).is_err(), "no pixels"); +} + +#[test] +fn the_decoder_refuses_inputs_of_the_wrong_size() { + let Some(d) = gpu() else { return }; + // checked before the checkpoint is read: an empty reader is never touched + let dir = std::env::temp_dir().join(format!("lc-sam3-pixel-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut st = 2u64.to_le_bytes().to_vec(); + st.extend_from_slice(b"{}"); + std::fs::write(dir.join("model.safetensors"), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + let m = MaskDecoder::new(WeightReader::open(&dir).unwrap()); + let (mem, text, valid) = (vec![0f32; GRID * GRID * WIDTH], vec![0f32; TEXT * WIDTH], vec![true; TEXT]); + let (l1, l0) = (vec![0f32; WIDTH * 144 * 144], vec![0f32; WIDTH * SIDE * SIDE]); + let rows = vec![0f32; 3 * WIDTH]; + assert!(m.run(d, &mem[1..], &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l0, &l1], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 2]).is_err_and(|e| e.contains("row values"))); + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &[], &[]).is_err_and(|e| e.contains("row values"))); + // the right sizes reach the checkpoint, which has no decoder + assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("mask_decoder"))); + assert!(m.bytes().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/gpu/src/wgsl/sam3_pixel.wgsl b/crates/gpu/src/wgsl/sam3_pixel.wgsl new file mode 100644 index 0000000000..bc6b972cfd --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_pixel.wgsl @@ -0,0 +1,161 @@ +// The small steps of the text detector's pixel decoder (`sam3/pixel.rs`) around its 3 x 3 convolutions: nearest +// up-sampling plus the neck level it is added to, and GroupNorm + ReLU (statistics per chunk of pixels, merged per +// group, then applied in place). +// +// Images are pixel rows (`[pixels, channels]`, row-major); the neck levels come channels-first, as uploaded. Same +// bindings and parameter block as `sam3_ops.wgsl`; flat dispatches cover `count` items, 256 per workgroup, workgroups +// in rows of `row`. + +struct P { + a: u32, + b: u32, + c: u32, + d: u32, + e: u32, + f: u32, + count: u32, + row: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var src: array; +@group(0) @binding(2) var aux: array; +@group(0) @binding(3) var aux2: array; +@group(0) @binding(4) var dst: array; + +fn flat_id(wg: vec3, lid: u32) -> u32 { + return (wg.y * p.row + wg.x) * 256u + lid; +} + +// Nearest up-sampling of the rows `src` (a: channels, c: side) to side b, plus the channels-first image `aux` +// (`[a, b, b]`): dst[row · b + col, ch] = src[(row · c / b) · c + col · c / b, ch] + aux[ch, row, col]. (candle's +// `upsample_nearest2d` takes floor(i · c / b), the same for the decoder's exact doublings.) +@compute @workgroup_size(256) +fn upsample_add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let pixel = g / p.a; + let row = pixel / p.b; + let col = pixel % p.b; + let at = row * p.c / p.b * p.c + col * p.c / p.b; + dst[g] = src[at * p.a + ch] + aux[ch * p.b * p.b + pixel]; +} + +var red: array; + +fn reduce(lid: u32, v: f32) -> f32 { + red[lid] = v; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (lid < s) { + red[lid] += red[lid + s]; + } + workgroupBarrier(); + } + let total = red[0]; + workgroupBarrier(); + return total; +} + +// Thread `lid` holds channel lid's `v`: leaves the sum over each group's channels in red[group] (a: channels, +// d: groups). +fn group_sums(lid: u32, v: f32) { + red[lid] = v; + workgroupBarrier(); + let per = p.a / p.d; + var s = 0.0; + if (lid < p.d) { + for (var i = 0u; i < per; i++) { + s += red[lid * per + i]; + } + } + workgroupBarrier(); + if (lid < p.d) { + red[lid] = s; + } + workgroupBarrier(); +} + +// GroupNorm statistics of one chunk of pixels (a: channels ≤ 256, b: pixels, c: pixels per chunk, d: groups), one +// workgroup per chunk, thread = channel: each group's mean over the chunk and the sum of squared differences from +// it, at dst[(chunk · d + group) · 2 + 0 | 1]. Two passes over the chunk (the second from the cache), so a large mean +// costs no precision. +@compute @workgroup_size(256) +fn group_stats(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let chunk = wg.y * p.row + wg.x; + let first = chunk * p.c; + if (first >= p.b) { + return; + } + let last = min(first + p.c, p.b); + let live = lid < p.a; + let ch = min(lid, p.a - 1u); + let per = p.a / p.d; + let n = f32((last - first) * per); + var s = 0.0; + if (live) { + for (var px = first; px < last; px++) { + s += src[px * p.a + ch]; + } + } + group_sums(lid, s); + let mean = red[ch / per] / n; + let own = red[min(lid, p.d - 1u)] / n; + workgroupBarrier(); + var q = 0.0; + if (live) { + for (var px = first; px < last; px++) { + let d = src[px * p.a + ch] - mean; + q += d * d; + } + } + group_sums(lid, q); + if (lid < p.d) { + let o = (chunk * p.d + lid) * 2u; + dst[o] = own; + dst[o + 1u] = red[lid]; + } +} + +// The chunks' statistics merged, one workgroup per group (a: chunks, b: pixels, c: pixels per chunk, d: groups, +// e: eps bits, f: channels per group): dst[group · 2 + 0 | 1] = the group's mean and 1 / sqrt(variance + eps), the +// variance biased (over all of the group's numbers), as candle's GroupNorm. +@compute @workgroup_size(256) +fn group_merge(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = wg.x; + let total = f32(p.b * p.f); + var s = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + s += n * src[(i * p.d + g) * 2u]; + } + let mean = reduce(lid, s) / total; + var q = 0.0; + for (var i = lid; i < p.a; i += 256u) { + let n = f32(min(p.c, p.b - i * p.c) * p.f); + let o = (i * p.d + g) * 2u; + let d = src[o] - mean; + q += src[o + 1u] + n * d * d; + } + let variance = reduce(lid, q) / total; + if (lid == 0u) { + dst[g * 2u] = mean; + dst[g * 2u + 1u] = inverseSqrt(variance + bitcast(p.e)); + } +} + +// GroupNorm and ReLU in place on the rows `dst` (a: channels, d: groups) with the merged statistics `src`, the scale +// `aux` and the shift `aux2` (`[a]` each): dst = max((dst − mean) · rstd · aux + aux2, 0). +@compute @workgroup_size(256) +fn group_norm_relu(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let g = flat_id(wg, lid); + if (g >= p.count) { + return; + } + let ch = g % p.a; + let group = ch / (p.a / p.d); + dst[g] = max((dst[g] - src[group * 2u]) * src[group * 2u + 1u] * aux[ch] + aux2[ch], 0.0); +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 89aa46310a..cf52a4f72f 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -12,4 +12,6 @@ mod sam3_backbone; #[cfg(feature = "sam")] mod sam3_detr; #[cfg(feature = "sam")] +mod sam3_mask_decoder; +#[cfg(feature = "sam")] mod sam3_necks; diff --git a/crates/gpu/tests/it/sam3_mask_decoder.rs b/crates/gpu/tests/it/sam3_mask_decoder.rs new file mode 100644 index 0000000000..09520ebea9 --- /dev/null +++ b/crates/gpu/tests/it/sam3_mask_decoder.rs @@ -0,0 +1,287 @@ +//! The text detector's mask decoder on the GPU against the candle decoder (the reference), on one photo: the per-query +//! mask logits of all 200 queries, and the merged Describe mask, for a few prompts. Both models get the same backbone +//! output, necks and DETR encoder memory (one GPU accelerator, shared), so only the mask decoder differs. For the first +//! prompt, the instance features also against the decoder transcribed with candle's tensor ops in f64 (and in f32, to +//! show how far candle's own f32 decoder is from it). +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_mask_decoder:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by +//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts, +//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use candle_core::{Device, Tensor}; +use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu}; +use lightcraft_segment::{BackboneAccel, DetectorOutput, INPUT, NeckKind, Sam3, WeightReader}; + +fn values(t: &Tensor) -> Vec { + t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::().unwrap() +} + +/// Max |a − b|, that relative to max |b|, and mean |a − b|. +fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) { + assert_eq!(a.len(), b.len(), "{name}: length"); + let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6); + let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::() / a.len().max(1) as f64; + eprintln!(" {name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale); + (max, max / scale, mean) +} + +/// Intersection over union of two masks (logits > 0). +fn iou(a: &[f32], b: &[f32]) -> f32 { + // masks of different sizes are no match (`zip` would compare only the shorter's pixels) + assert_eq!(a.len(), b.len(), "mask sizes"); + let (mut both, mut either) = (0usize, 0usize); + for (x, y) in a.iter().zip(b) { + let (x, y) = (*x > 0.0, *y > 0.0); + both += usize::from(x && y); + either += usize::from(x || y); + } + if either == 0 { 1.0 } else { both as f32 / either as f32 } +} + +fn sigmoid(x: f32) -> f32 { + 1.0 / (1.0 + (-x).exp()) +} + +/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances +/// scoring above it), the instances, and the best-scoring query. +fn merged(out: &DetectorOutput, masks: &[f32]) -> (Vec, Vec, usize) { + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let mut merged = vec![f32::MIN; side]; + let keep: Vec = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect(); + for i in &keep { + for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) { + *m = m.max(*v); + } + } + let best = (0..out.logits.len()).max_by(|a, b| out.logits[*a].total_cmp(&out.logits[*b])).unwrap(); + (merged, keep, best) +} + +/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`. +fn photo() -> Tensor { + if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) { + let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap(); + return r.remove("pixel_values").unwrap(); + } + let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8(); + let rgb: Vec = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(); + let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap(); + Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap() +} + +/// The mask decoder transcribed with candle's tensor ops in `dtype` (f64: the arbiter between the two f32 decoders): +/// the instance features `[256, 288 · 288]` for the encoder memory `[5184, 256]`, the prompt `[32, 256]` (`valid`: its +/// real tokens) and the neck levels `[256, 144, 144]`, `[256, 288, 288]`. +fn decoder_ref(w: &WeightReader, memory: &Tensor, (text, valid): (&Tensor, &[bool]), [l1, l0]: [&Tensor; 2], dtype: candle_core::DType) -> Tensor { + let get = |name: &str| { + let (shape, data) = w.read(&format!("detector_model.mask_decoder.{name}")).unwrap(); + Tensor::from_vec(data, shape, &Device::Cpu).unwrap().to_dtype(dtype).unwrap() + }; + let lin = |x: &Tensor, name: &str| { + x.matmul(&get(&format!("{name}.weight")).t().unwrap()).unwrap().broadcast_add(&get(&format!("{name}.bias"))).unwrap() + }; + let (memory, text) = (memory.to_dtype(dtype).unwrap(), text.to_dtype(dtype).unwrap()); + // prompt attention: LN (eps 1e-5) → 8 heads of 32 over the prompt (padding masked) → output projection, added + let mean = memory.mean_keepdim(1).unwrap(); + let centred = memory.broadcast_sub(&mean).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let h = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap(); + let h = h.broadcast_mul(&get("prompt_cross_attn_norm.weight")).unwrap().broadcast_add(&get("prompt_cross_attn_norm.bias")).unwrap(); + let heads = |x: Tensor| x.reshape((x.dim(0).unwrap(), 8, 32)).unwrap().transpose(0, 1).unwrap().contiguous().unwrap(); + let q = heads(lin(&h, "prompt_cross_attn.q_proj")); + let k = heads(lin(&text, "prompt_cross_attn.k_proj")); + let v = heads(lin(&text, "prompt_cross_attn.v_proj")); + let bias: Vec = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect(); + let bias = Tensor::from_vec(bias, (1, 1, 32), &Device::Cpu).unwrap().to_dtype(dtype).unwrap(); + let s = (q.matmul(&k.t().unwrap()).unwrap() * (32f64).powf(-0.5)).unwrap().broadcast_add(&bias).unwrap(); + let e = s.broadcast_sub(&s.max_keepdim(2).unwrap()).unwrap().exp().unwrap(); + let p = e.broadcast_div(&e.sum_keepdim(2).unwrap()).unwrap(); + let o = p.matmul(&v).unwrap().transpose(0, 1).unwrap().reshape((5184, 256)).unwrap(); + let mem = (memory + lin(&o, "prompt_cross_attn.o_proj")).unwrap(); + // the pixel decoder + let mut prev = mem.t().unwrap().reshape((1, 256, 72, 72)).unwrap(); + for (i, skip) in [l1, l0].into_iter().enumerate() { + let side = skip.dim(1).unwrap(); + prev = (prev.upsample_nearest2d(side, side).unwrap() + skip.to_dtype(dtype).unwrap().unsqueeze(0).unwrap()).unwrap(); + let c = format!("pixel_decoder.conv_layers.{i}"); + prev = prev + .conv2d(&get(&format!("{c}.weight")), 1, 1, 1, 1) + .unwrap() + .broadcast_add(&get(&format!("{c}.bias")).reshape((1, 256, 1, 1)).unwrap()) + .unwrap(); + let g = prev.reshape((8, 32 * side * side)).unwrap(); + let centred = g.broadcast_sub(&g.mean_keepdim(1).unwrap()).unwrap(); + let var = centred.sqr().unwrap().mean_keepdim(1).unwrap(); + let normed = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap().reshape((1, 256, side, side)).unwrap(); + let n = format!("pixel_decoder.norms.{i}"); + let (gamma, beta) = + (get(&format!("{n}.weight")).reshape((1, 256, 1, 1)).unwrap(), get(&format!("{n}.bias")).reshape((1, 256, 1, 1)).unwrap()); + prev = normed.broadcast_mul(&gamma).unwrap().broadcast_add(&beta).unwrap().relu().unwrap(); + } + let inst = prev.conv2d(&get("instance_projection.weight"), 0, 1, 1, 1).unwrap(); + inst.broadcast_add(&get("instance_projection.bias").reshape((1, 256, 1, 1)).unwrap()).unwrap().reshape((256, 288 * 288)).unwrap() +} + +/// One GPU accelerator for both models; the mask decoder only for one of them, the other gets a result of the wrong +/// size (and then runs the candle decoder; `asked` counts the calls). +struct Shared { + gpu: Arc, + masks: bool, + asked: Arc, +} + +impl BackboneAccel for Shared { + fn forward(&self, pixels: &[f32]) -> Result, String> { + self.gpu.forward(pixels) + } + + fn device(&self) -> String { + self.gpu.device() + } + + fn runs_necks(&self) -> bool { + true + } + + fn runs_detr_encoder(&self) -> bool { + true + } + + fn runs_mask_decoder(&self) -> bool { + true + } + + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result>, String> { + self.gpu.neck(which, backbone, n) + } + + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.gpu.detr_encoder(image, pos, text, valid) + } + + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.masks { self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) } else { Ok(vec![0.0; 10]) } + } +} + +#[test] +fn the_gpu_mask_decoder_matches_the_candle_decoder() { + let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else { + lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory"); + return; + }; + let adapter = match sam3::adapter() { + Ok(a) => a, + // a kernel that doesn't compile is a failure, not a missing GPU + Err(e) if e.contains("did not compile") => panic!("{e}"), + Err(e) => { + lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})"); + return; + } + }; + let gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap()); + let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let with = |masks: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, masks, asked })) } + }; + let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap(); + let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap(); + let pixels = photo(); + let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap(); + let mut enc_acc = acc.encode_pixels(&pixels).unwrap(); + + let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into()); + let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + for (n, prompt) in prompts.iter().copied().enumerate() { + let t = Instant::now(); + let want = cpu.detect(&mut enc_cpu, prompt).unwrap(); + let cpu_time = t.elapsed(); + let t = Instant::now(); + let got = acc.detect(&mut enc_acc, prompt).unwrap(); + let gpu_time = t.elapsed(); + let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" }; + eprintln!("{prompt:?}: detector with the candle mask decoder {cpu_time:?}, with the GPU one {gpu_time:?}{first}"); + assert_eq!(acc.mask_fallback(), None, "the GPU mask decoder ran"); + assert!(cpu.mask_fallback().is_some_and(|w| w.contains("returned 10 values"))); + assert_eq!(acc.heads_device(), "CPU; the necks, the DETR encoder and the mask decoder on the GPU"); + assert_eq!(cpu.heads_device(), "CPU; the necks and the DETR encoder on the GPU"); + + if n == 0 { + // the instance features (the instance projection as the rows) against the f64 transcription, and how far + // the same transcription in f32 is from it + let reader = WeightReader::open(&dir).unwrap(); + let (_, valid) = lightcraft_segment::tokenizer::Tokenizer::load(&dir).unwrap().encode(prompt); + let levels = acc.neck_levels(NeckKind::Detector, &enc_acc).unwrap(); + let (l1, l0) = (levels[1].squeeze(0).unwrap(), levels[0].squeeze(0).unwrap()); + let (memory, text) = (got.memory.squeeze(0).unwrap(), got.text.squeeze(0).unwrap()); + let (_, rows) = reader.read("detector_model.mask_decoder.instance_projection.weight").unwrap(); + let (_, bias) = reader.read("detector_model.mask_decoder.instance_projection.bias").unwrap(); + let t = Instant::now(); + let ours = gpu.mask_decoder(&values(&memory), &values(&text), &valid, [&values(&l1), &values(&l0)], &rows, &bias).unwrap(); + eprintln!(" GPU instance features {:?}", t.elapsed()); + let t = Instant::now(); + let f64_ref: Vec = values( + &decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F64).to_dtype(candle_core::DType::F32).unwrap(), + ); + let f32_ref = values(&decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F32)); + eprintln!(" references {:?}", t.elapsed()); + let (_, rel, mean) = errors("instance features, GPU vs f64", &ours, &f64_ref); + errors("instance features, candle f32 vs f64", &f32_ref, &f64_ref); + assert!(rel < 1e-4 && mean < 1e-5, "the GPU instance features are off"); + } + + // the same memory and decoder for both: only the masks may differ, by candle's own error (its f32 decoder is + // ~400 × further from the f64 one than the GPU's, above) + let (_, logits, _) = errors("query logits", &got.logits, &want.logits); + assert!(logits < 1e-4, "the query logits moved"); + let (mg, mc) = (values(&got.masks), values(&want.masks)); + let (_, rel, mean) = errors("mask logits (200 queries), GPU vs candle", &mg, &mc); + assert!(rel < 1e-2 && mean < 0.1, "the GPU mask logits are off"); + let ((mask_g, kept_g, best_g), (mask_c, kept_c, best_c)) = (merged(&got, &mg), merged(&want, &mc)); + let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE; + let best = iou(&mg[best_g * side..(best_g + 1) * side], &mc[best_c * side..(best_c + 1) * side]); + let i = iou(&mask_g, &mask_c); + eprintln!(" instances {} vs {}, Describe mask IoU {i:.5}, best query's mask IoU {best:.5}", kept_g.len(), kept_c.len()); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99 && best > 0.99, "describe mask IoU {i}, best query {best}"); + // the semantic mask (one more row of the GPU's mask product) + let (_, rel, mean) = errors("semantic mask logits, GPU vs candle", &got.semantic, &want.semantic); + let semantic = iou(&got.semantic, &want.semantic); + eprintln!(" semantic mask IoU {semantic:.5}"); + assert!(rel < 1e-2 && mean < 0.1 && semantic > 0.99, "the GPU semantic mask is off"); + } + // an accelerator whose decoder failed once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the decoder alone (with the uploads and the read-back) + let (memory, text) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]); + let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.mask_decoder_bytes().unwrap(); + eprintln!("GPU mask decoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +} diff --git a/docs/ai-masks.md b/docs/ai-masks.md index 84e082163b..5e329ae298 100644 --- a/docs/ai-masks.md +++ b/docs/ai-masks.md @@ -2,8 +2,10 @@ LightCraft selects objects with **SAM 3** (Segment Anything with Concepts, Meta 2025), run in pure Rust by `crates/segment` on [candle](https://github.com/huggingface/candle): on the GPU -through Metal on macOS, on the CPU elsewhere (for now). If the Mac's GPU can't run it, it runs on -the CPU (see the worker below). +through Metal on macOS (if the Mac's GPU can't run it, it runs on the CPU, see the worker below); on Linux and Windows the image encoder (most of the work) runs on the GPU +through wgpu (Vulkan / DX12), with the two necks and the text detector's DETR encoder and mask +decoder, and the rest on the CPU, falling back to the CPU when there is no usable GPU +([Where it runs](#where-it-runs)). **The model is optional.** It is not part of LightCraft, and nothing requires it: without it, Object and Describe offer to download it, every other feature (and every existing mask, see @@ -34,7 +36,9 @@ In the Masking panel (M): 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 +model after launch; ~0.6 s on an RTX 5070 under Linux, of which 0.45 s is the image encoder and +0.12 s the click features, plus ~1–2 s once for loading the model onto the GPU; 32–33 s with all +of it on a 12-core Ryzen CPU). 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 @@ -46,6 +50,76 @@ The result is stored with the mask: the model's 288 × 288 mask logits over the need the model, so masks survive moving the library to a machine without it, and the web build renders them. Editing the photo's look later does not recompute a mask (click again to update). +## Where it runs + +| | Image encoder (once per photo) | Click features, clicks, descriptions | +|---|---|---| +| macOS | GPU: Metal (candle) | GPU: Metal (candle) | +| Linux, Windows | GPU: wgpu compute on Vulkan / DX12 (`lightcraft-gpu`, module `sam3`) | the two necks and the text detector's DETR encoder and mask decoder on the GPU (wgpu); the click decoder, the text encoder and the DETR decoder on the CPU (candle) | +| no usable GPU, `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off`, or the GPU failed; outside macOS also GPU rendering off | CPU (candle) | CPU (candle) | +| **CPU** chosen in Settings (any platform, macOS included) | CPU (candle) | CPU (candle) | + +Measured on Linux (AMD Ryzen 9 3900X, 12 cores / 24 threads; NVIDIA RTX 5070), release build, +the photo already rendered: + +| Step | CPU only | On the GPU | +|---|---|---| +| Image encoder (once per photo) | 30.2–31.2 s | 0.49–0.57 s (0.43–0.44 s of it on the GPU, see [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12)) | +| Loading the model (once, and again after 10 min idle) | ~1.5 s | ~1.8 s (device and kernels 0.16–1 s, weight upload ~1.1 s) | +| A photo's whole analysis before its first click | 32.3–33.4 s | 0.56–0.69 s | +| Click features (once per photo, before the first click) | 2.1–2.3 s | 0.12–0.19 s (the tracker neck on the GPU, 38 ms) | +| A click | ~0.14 s | ~0.14 s (CPU) | +| First description on a photo (detector features + text) | 6.3–6.9 s | 0.5–0.8 s (1.3 s the very first time, with the detector loading) (the detector neck, the DETR encoder and the mask decoder on the GPU) | +| A further description | 4.4–4.5 s | ~0.7 s (the DETR encoder and the mask decoder on the GPU, 24 + 33 ms; the rest on the CPU) | +| A prompt used before (on this or an earlier photo; the latest 16 are kept) | ~4.35 s | 0.45–0.46 s (no text encoder) | + +(CPU: `cargo run -p lightcraft-segment --release --example sam3_bench -- `; GPU: +`LIGHTCRAFT_SAM3_DIR= cargo run -p lightcraft-gpu --release --features sam --example +sam3_backbone_bench -- --app`, and the desktop app's log lines, `SAM 3 loaded in …` and `SAM 3 +analyzed …`. What each GPU part takes: [gpu-pipeline.md](gpu-pipeline.md#sam-3-backbone-m12).) + +**Falling back.** When the GPU can't be used (no adapter, a software one, the driver refuses the +device, not enough memory) the model loads with the image encoder on the CPU. When the GPU fails +on a photo (device lost, an output of the wrong size or with NaN), that photo is analyzed again on +the CPU and the model stays there until it loads again (except while LightCraft is closing: then +the work ends with its error, and nothing starts on the CPU). Neither is an error: the log says why +(`SAM 3 backbone accelerator unavailable (…)`, `SAM 3 backbone failed on … (…)`), and so do +Settings and `segment.model.status`. + +**Forcing the CPU.** Choose **Settings ▸ Performance ▸ AI masks ▸ Run on: CPU** +(`segment.settings {"runOn": "cpu"}`; back with `"auto"`, the default). It puts all of SAM 3 on the +CPU on every platform, macOS included (candle's CPU device instead of Metal), for a GPU that can't +run the model, and leaves GPU rendering alone. The choice is kept in +`/models/sam3-settings.json` (`{"runOn": "cpu"}`) and `segment.model.status` reports it as +`runOn`. Automatic also gives way to the switches every GPU compute in LightCraft follows (AI +Denoise, faces): `LIGHTCRAFT_GPU=0` / `LIGHTCRAFT_GPU_BACKEND=off` at start (no GPU at all for the +process) put SAM 3 on the CPU on every platform, macOS included; **Settings ▸ Performance ▸ Use the +GPU for rendering** off (`app.gpu {"enabled": false}`) does so outside macOS, where it governs the +wgpu kernels, while on macOS candle keeps Metal. When a switch changes where it runs, a model +already loaded moves at its next request (it loads again). + +**Seeing where it runs.** Settings ▸ Performance ▸ AI masks shows what the image encoder runs on +(the GPU's name, "Metal GPU" or "CPU", with the reason when it is not on the GPU) and how long the +last photo took. `segment.model.status` → `backend` says the same for agents and scripts: + +```json +"backend": { + "device": "NVIDIA GeForce RTX 5070 (Vulkan)", + "runtime": "wgpu", + "heads": "CPU; the necks, the DETR encoder and the mask decoder on the GPU", + "fallback": null, + "encodeMs": 1234, + "analyzeMs": 3456 +} +``` + +`device` is what runs the image encoder (`null` until the model first loads), `runtime` `wgpu` +(LightCraft's kernels) or `candle`, `heads` what runs the rest, `fallback` why the encoder is not on +the GPU where it could be, `encodeMs` the last image encoder run and `analyzeMs` the last photo's +analysis before its first click (encoder and click features). The log (info level) has each load +(`SAM 3 loaded in …: the backbone on the …, the rest on the CPU; the necks, the DETR encoder and the +mask decoder on the GPU`) and each photo (`SAM 3 analyzed W×H in …: backbone … on the …, click features … on the …`). + ## Remote Metal inference Native builds with `sam` can keep the editor, RAW files, library, and exports local while @@ -64,7 +138,9 @@ ssh -N -T -o ExitOnForwardFailure=yes -L 127.0.0.1:8793:127.0.0.1:8793 user@your LIGHTCRAFT_SAM3_REMOTE=127.0.0.1:8793 lightcraft ``` -Object clicks, Describe prompts, and detail refinement use the remote worker. Only the +Object clicks, Describe prompts, and detail refinement use the remote worker. **Run on** (Settings +▸ Performance ▸ AI masks, `segment.settings`) only places local inference: the remote worker +always runs on the Mac's Metal device, whatever is chosen here. Only the rendered model input (long edge at most 1008 pixels) and prompts cross the tunnel. The worker caches the current photo; detail crops do not replace that cache. Returned masks stay in the local library, so later adjustments and exports work without the connection. @@ -190,11 +266,14 @@ Therefore: | `mask.objectPoint` | `{x, y, exclude?: bool, id?}` | one click on the selected mask's Object selection (≤ 64 clicks) | | `mask.refineDetail` | `{id?, component?}` | the zoomed-in detail pass → `{started}` | | `segment.prepare` | `{}` | load the model and analyze the active photo → `{busy}` | -| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.model.status` | `{}` | `{available, installed, remote, dir, loaded, busy, analyzing, runOn, backend, sizeBytes, license, licenseUrl, mirrors, download}` | +| `segment.settings` | `{runOn?: "auto" \| "cpu"}` | where SAM 3 runs ([Where it runs](#where-it-runs)) → `{runOn}` | | `segment.model.download` | `{acknowledged: true}` | start the download in the background → `{started}` | | `segment.model.cancel` | `{}` | stop it (it resumes next time) → `{cancelled}` | `remote` reports the configured endpoint, not its health. `installed` describes local weights only. +`backend` is where the model runs and how long the last photo took ([Where it runs](#where-it-runs)); `null` in a +build without AI masks. `download` is `{running, done, total, file, error, cancelled, finished}`: `cancelled` is true when the last download was cancelled (its `error` says so in words; decide on the flag). An AI mask command refused because the model is not installed (or still downloading) fails with an error that starts with "The SAM 3 model is @@ -225,6 +304,13 @@ wait and return the result (when built with the `sam` feature; the default CLI h memory map: `unsafe` stays in `lightcraft-sysmem`), only the tensors a path needs, and every tensor's byte range is checked against the file's length when it is opened (a truncated or damaged file is an error, never a crash). +- The image encoder can run outside candle: `lightcraft_segment::BackboneAccel` (pixels in, the + backbone's `[1024, 72, 72]` features out), built from the checkpoint through `WeightReader` and + given to `Sam3::load_accelerated`. `lightcraft-gpu` (feature `sam`, on with the engine's `sam`) + implements it in WGSL. `Sam3` checks every result (size, finite values) and drops the + accelerator for the candle backbone on the first failure; `Sam3::backbone_device` / + `accelerated` / `backbone_fallback` report it. The engine's worker picks the placement + (`Placement` in `worker.rs`). - The engine (`crates/engine/src/segment/`) owns one worker thread with the model and the last encoded photo; the session sends it jobs and receives results over channels, never holding a lock the model holds. Each job runs under `catch_unwind`: a panic inside candle becomes an diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index c55e12965e..af3bf7088c 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -328,6 +328,166 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source - Result (M4 Pro, 14 raws, loupe, 12 steps): peak RSS 1.9–2.3 GB → 0.83–0.99 GB, peak footprint 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). +## SAM 3 backbone (M12) +AI masks (Object, Subject, Describe) spend almost all of their time in SAM 3's vision backbone, a 32-layer ViT +(`crates/segment/src/vit.rs`, ~4.6 TFLOP plus attention per photo): ~37–40 s on the CPU through candle. With the +`sam` feature, `lightcraft_gpu::sam3::backbone(&WeightReader)` runs it with wgpu compute kernels instead and returns +a `lightcraft_segment::BackboneAccel` for `Sam3::load_accelerated`; the heads stay on candle (the necks: below). It has a +device of its own (like denoise and faces) with the same switches, crash sentinel, shutdown gate and +stop-after-a-device-error handling; any failure is an `Err` and the candle backbone runs instead. +- Same math as `vit.rs`: patch embedding (im2col + matrix product, 24 × 24 position table tiled), `ln_pre`, then per + layer LN → one q|k|v product (the three weights concatenated) → 2-D RoPE (`rope_tables`, recomputed bit for bit) + → attention over 24 × 24 windows, or all 5184 tokens in layers 7/15/23/31 → output projection + residual → LN → + MLP 1024 → 4736 → 1024 with GELU (erf form; A&S 7.1.26, |error| < 1.5e-7) + residual. +- Tokens stay in *window order* (window-major, row-major inside a window) from the patch embedding to the last + layer: a window is a contiguous range of keys, the position table repeats per window (a bias table indexed by + row % 576), and global attention does not depend on order (its RoPE table is stored in window order). The last + kernel writes the `[1024, 72, 72]` channels-first output. +- Kernels (`wgsl/sam3_*.wgsl`): `sam3_matmul` (Y = X · Wᵀ with the checkpoint's `[N, K]` weights as they are, + 64 × 64 tiles, 4 × 4 per thread, k in steps of 16 through padded workgroup memory, bias/GELU/residual in the + epilogue; written out per tile size with one variable per accumulator), `sam3_attention` (flash style: one query + per thread, keys and values 32 at a time through workgroup memory, online softmax; the 16 × 5184² scores of a + global layer never exist; also written out, since arrays indexed in loops spilled to local memory and ran 3.5 × + slower), `sam3_ops` (layer norm, RoPE in place with the 1/8 scale folded into q, im2col, the final reorder). No + subgroups and no shader-f16 needed. +- All 228 dispatches, their parameters (one uniform buffer) and bind groups are recorded once with the weights; a + forward pass writes the pixels, submits one command buffer per layer and reads the result back once. +- Limits requested: WebGPU downlevel defaults plus 98 MB storage bindings / buffers (the MLP's activations, + 5184 × 4736 floats) and 16 KB of workgroup memory. Device memory: 1.8 GB of f32 weights + 0.2 GB of work + buffers. When the f32 weights don't fit (out-of-memory while uploading), it retries with f16 weights (pairs + packed in u32, unpacked with `unpack2x16float`, products still in f32): 0.9 GB, but ~20 × the error (below). + An adapter short of a limit gets no device (`short_limits`, e.g. "max_storage_buffer_binding_size 67108864 < + 98205696"), nor does one whose device creation fails or panics (the crash sentinel keeps a driver crash from + repeating on the next start); SAM 3 then runs in candle on the CPU, and `segment.model.status` → `backend.fallback` + and Settings ▸ Performance ▸ AI masks say why. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`): device + kernel compile 0.16–0.3 s (≈1 s with a + cold driver shader cache), weight upload 1.1 s, first forward 0.43–0.47 s, warm forward 0.43–0.44 s; candle on + the CPU 36–40 s. Matrix products ~13.5 TFLOP/s (~80 % of the time), attention ~12 TFLOP/s. f16 weights: 0.47 s + (no faster: the products are compute-bound), upload 2.9 s. +- Accuracy (`tests/it/sam3_backbone.rs`, a photo with a Hugging Face reference from `tools/sam3_reference.py`): GPU vs + CPU backbone max abs 5.3e-2 at a scale of 223 (max rel 2.4e-4), mean abs 2.2e-5; against Hugging Face the GPU is + as close as the CPU port (max rel 1.4e-4 vs 2.0e-4). Click masks and a Describe mask ("person") from either + backbone: IoU 1.0. With f16 weights: max rel 3.8e-3, mean abs 5.4e-4, mask IoU ≥ 0.9997. +- Tests: kernel unit tests against plain loops (`src/sam3/tests.rs`: cut-off tiles, K not a multiple of the tile, + windowed and global attention, LN, RoPE, im2col/reorder, f16 rounding), skipped without a GPU; the end-to-end + test runs with `LIGHTCRAFT_SAM3_DIR` set. Tested on NVIDIA (RTX 5070, Vulkan) and Apple silicon (M4 Pro, Metal + through wgpu: first forward 3.1 s, CPU 17.2 s; max rel 4.9e-5, masks IoU ≥ 0.99992). AMD, Intel and DX12 are untested. + +### SAM 3 necks +After the backbone, the click decoder needs the tracker neck (`tracker_neck`) and Describe the detector's +(`detector_model.vision_encoder.neck`): the same `Sam3VisionNeck` (`crates/segment/src/neck.rs`) with other weights, +three levels each (288², 144² and 72², 256 channels; the 36² level is used by neither head). In candle on the CPU +they took ~2.3 and ~2.6 s per photo, more than the GPU backbone. `BackboneAccel::neck` runs them with the backbone's +device (`crates/gpu/src/sam3/neck.rs`); `Sam3` turns the levels into candle tensors on its device, checks their +sizes and values, and on any `Err` warns once and runs that neck in candle from then on (the other neck and the +backbone stay on the GPU). +- Images are pixel rows (`[pixels, channels]`), so every step is the backbone's matrix kernel. A 2 × 2 stride-2 + transposed convolution is one product per input pixel, `[pixels, cin] · [cin, 4 · cout]` (PyTorch's + `[cin, cout, 2, 2]` weight laid out as `[(ky, kx, cout), cin]` on upload, the bias repeated 4 ×), GELU (erf) + between level 0's two in the epilogue. Its output rows hold each pixel's four outputs one after the other; `proj1` + (1 × 1) doesn't care about pixel order, so one reorder (`unshuffle` in `wgsl/sam3_neck.wgsl`) after it puts the + pixels of one or two up-samplings in row-major order. +- `proj2` (3 × 3, padding 1) is an implicit GEMM: the matrix kernel with another A-tile loader + (`wgsl/sam3_conv.wgsl`, spliced in place of the dense one between `// #if dense` marks of `sam3_matmul.wgsl`) that + reads the 9 · 256 numbers of a pixel's neighbourhood straight from the image (K ordered tap-major, so each vec4 is + four channels of one pixel; zero outside). The im2col matrix (764 MB at 288²) never exists. The weights go to + `[cout, ky, kx, cin]` on upload. The last step is `to_chw` with one window over the whole image. +- Built on first use, not with the backbone: the three kernels compile (≈0.2 s with a cold driver cache, a few ms + warm), the work buffers are made (pixel rows of the backbone, 21 MB, and two 85 MB buffers the steps alternate + between, shared by both necks), and the neck's weights (~27 MB) are read, laid out and uploaded (~0.1 s). Each + level is recorded once and is one submission with its own read-back (85 / 21 / 5 MB), so no buffer exceeds the + backbone's 98 MB limits and no limit is raised. Device memory: ~245 MB with both necks built. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`; `--app` times the app's per-photo steps, + `--cpu-necks` the same with candle's necks): a neck 38 ms warm (level 0: 13 ms of products at ~12 TFLOP/s, the + rest mostly the 85 MB read-back), first use 0.08–0.12 s (0.4 s with a cold driver shader cache); candle 2.3–3.5 s. + Per photo in the app's order: click features (the tracker neck plus the tracker's two 1 × 1 convolutions, still + candle) 0.11–0.19 s instead of 2.0–2.3 s, so encode + click features 0.56–0.69 s instead of 2.4–2.9 s; the first + Describe 5.1–5.8 s instead of 7.0–7.4 s (the rest of it is the DETR encoder and decoder in candle). +- Accuracy (`tests/it/sam3_necks.rs`, both models fed the same GPU backbone output): every level of both necks within + max rel 2.1e-6, mean abs ≤ 7.7e-7 of candle; click and Describe masks IoU 1.0. +- Tests: kernel unit tests against plain f64 loops (`src/sam3/neck/tests.rs`: transposed convolutions + reorder + with odd sides, the 3 × 3 convolution at every border, single-pixel and odd sizes, cut-off tiles, the weight + layouts, a whole small neck against a transcription of `Neck::forward`); `crates/segment` tests the fallback + (wrong sizes, NaN) with a fake accelerator. + +### SAM 3 DETR encoder +Each text prompt (Describe; Subject's "person") runs the text detector (`crates/segment/src/detector.rs`), whose +DETR encoder fuses the prompt into the 72 × 72 image tokens: ~4–5 s of the ~5–7 s a prompt took on the CPU. The +same accelerator runs it (`BackboneAccel::detr_encoder`, `src/sam3/detr.rs`); `Detector::predict` uses its result +as the encoder memory and runs the rest in candle. Any failure (no such accelerator, out of memory, a wrong-sized +or non-finite result) is logged once and noted (`Sam3::detr_fallback`), and from then on candle runs the encoder +for that model. +- Same math as `detector.rs`, six layers over 5184 tokens of 256: LN (eps 1e-5, PyTorch's default) → self-attention + (8 heads of 32; q and k from the normed tokens plus their sine position encoding, v from the normed tokens; q | k + one product with the weights concatenated) → output projection + residual → LN → cross-attention to the prompt's + 32 tokens (k | v one product) with the key-padding bias → output projection + residual → LN → MLP 256 → 2048 → + 256 with ReLU + residual. +- Kernels: the backbone's matrix product (ReLU as a third epilogue activation) and layer norm (with eps 1e-5), and + `wgsl/sam3_detr.wgsl`: attention for heads of 32 (flash style, written out like the backbone's) whose q, k and v + come from separate buffers with their own strides and offsets, with an optional per-key bias stored after the + prompt's k | v (0 or f32::MIN, as candle's `padding_bias`; the running maximum starts at f32::MIN, so a padded key + weighs exactly nothing and an all-padding prompt averages, as candle's softmax does); and a sum (tokens + position). +- Loaded on the first prompt, not with the backbone: kernels, 38 MB of f32 weights, 80 MB of work buffers (model + load time and memory before the first Describe are unchanged). 84 dispatches, recorded once; a prompt writes the + tokens, their position encoding, the prompt's tokens and its padding bias, submits one command buffer per layer + and reads the memory back. +- Measured (RTX 5070, Vulkan; CPU busy with parallel builds, load ~7–10): the encoder 23–25 ms with uploads and + read-back (self-attention 2.2 ms a layer at 12 TFLOP/s, products 10–12 TFLOP/s), candle 4.6–5.7 s (3.9–4.4 s on + an idle CPU). A Describe on a photo already analyzed (second prompt) 6.6 s → 2.0 s. What remains, per prompt: + CLIP text encoder 0.27–0.46 s, DETR decoder 0.75–1.3 s (of it the box relative-position bias ~75 ms a layer), + mask head ~0.9–1.4 s (pixel decoder 3 × 3 convs at 144² and 288² ~0.75–1.2 s, 1 × 1 instance projection 0.12 s, + mask products 25 ms; now on the GPU, below). +- Accuracy (`tests/it/sam3_detr.rs`, the photo of `tools/sam3_reference.py`, prompts "person", "sky", "the red car"; + both models share one GPU backbone, so only the encoder differs): memory max rel 1.7e-6–4.2e-6, mean abs + 2.3e-6–7.7e-6; query logits max abs ≤ 2.5e-4; presence logits ≤ 2.3e-5 apart; boxes ≤ 1.2e-4; the same instances + and Describe mask IoU 1.0. Kernel unit tests (`src/sam3/detr/tests.rs`): self-attention with 8 × 32 heads and a + part-empty last workgroup, cross-attention to 32 keys with 0, 1, 5 and 32 real tokens, ReLU, the sum, the eps. + +### SAM 3 mask head +A prompt's masks come from the detector's mask decoder (`mask_decoder` in the checkpoint): the encoder memory attends +to the prompt (`prompt_cross_attn`, after its layer norm) and is added to it; the pixel decoder brings it from 72² to +288² in two stages, each nearest 2 × up-sampling + the detector neck's level of that size → 3 × 3 convolution → +GroupNorm (8 groups, eps 1e-5) → ReLU; the 1 × 1 instance projection follows, and each query's mask embedding (the +`mask_embedder` MLP on the decoder's queries) times that is its mask logits. ~0.7–1.4 s per prompt in candle on the +CPU, most of it the 288² convolution. `BackboneAccel::mask_decoder` runs it on the accelerator (`src/sam3/pixel.rs`); +any failure (out of memory, a wrong-sized or non-finite result) is logged once and noted (`Sam3::mask_fallback`), and +candle runs the decoder for that model from then on. +- Interface: the encoder memory, the prompt's tokens and which are real, both neck levels (channels-first, as + `Features` holds them) and `rows` `[r, 256]` with a bias `[r]` (r ≤ 256), each row a 1 × 1 projection of the pixel + decoder's output; it returns `[r, 288, 288]`. The detector folds the instance projection into its 200 mask + embeddings on the CPU (e · (W x + b) = (e W) x + e b: 13 MFLOP instead of the projection's 11 GFLOP), so one + product `[82944, 256] · [200, 256]ᵀ` on the GPU gives the masks and the CPU fallback stays the candle code as it was. + SAM 3's semantic segmentation head (the semantic mask Describe and Subject share out to their instances, #1963) is + another 1 × 1 read-out of the same output, so it is one more row: 201 rows, the last one the semantic mask. +- Kernels: the prompt attention is the DETR encoder's (torch-eps layer norm, products, attention with the padding + bias); the convolutions are the necks' implicit GEMM; `wgsl/sam3_pixel.wgsl` adds the up-sampling, which adds the + neck level as uploaded (channels-first, so no separate reorder), and GroupNorm + ReLU: two-pass statistics per + chunk of 256 pixels (thread = channel, so the loads are contiguous), merged per group with the parallel variance + formula, then normalized in place. The projection's `[pixels, r]` goes channels-first with `to_chw`. +- Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, 282 MB of work buffers (and an 85 MB + read-back buffer in host memory). 17 dispatches, recorded once per row count; a prompt uploads the memory (5 MB), + the prompt, both neck levels (106 MB) and the rows, submits once and reads `r · 288²` numbers back (66 MB). + Keeping the levels on the device after `BackboneAccel::neck` would save the 106 MB upload (a few ms) but needs an + image identity in the interface and another 106 MB of device memory per photo; not done. +- Measured (RTX 5070, Vulkan, `examples/sam3_backbone_bench.rs`, quiet machine): the decoder 33 ms warm with the + uploads and the read-back (by FLOP count about a third of it kernels, the 288² convolution ~8 ms at ~12 TFLOP/s; + the rest transfers), first use 0.09–0.17 s. Per prompt in the app (`--app`, against `--cpu-masks`): a Describe on a + photo already analyzed 1.9–2.2 s → 1.04–1.06 s, the first on a photo 2.0–2.1 s → 1.11–1.12 s (2.5 s → 1.65 s with + the first load); under load (~15, parallel builds) 1.9 s → 1.1–1.2 s. With the CPU-side text cache and one-pass box + bias as well: a new prompt on an analyzed photo ~0.7 s, a prompt used before 0.45–0.46 s. What remains is in candle + on the CPU: the DETR decoder (~0.4 s) and, for a new prompt, the CLIP text encoder (~0.25 s). +- Accuracy (`tests/it/sam3_mask_decoder.rs`; both models share one GPU accelerator, so only the mask decoder differs): + against the decoder transcribed with candle's tensor ops in f64, the GPU's instance features are within max rel + 4.2e-6, mean abs 1.7e-7; candle's own f32 decoder is 1.1e-3–1.5e-3 / 2e-4 from it, all of that from its GroupNorm's + f32 sums over 2.6 M numbers per group (with those in f64 the f32 transcription is within 1.1e-6). So GPU vs candle, + all 200 queries' mask logits: max rel 1.0e-3–1.7e-3; the same instances, Describe mask IoU 1.0 ("person", "sky", + "the red car" on the photo of `tools/sam3_reference.py`). Kernel unit tests (`src/sam3/pixel/tests.rs`): the + up-sampling + level (odd sizes), GroupNorm + ReLU (cut-off chunks, a mean of 50, 1–8 groups), a two-stage small + decoder (up-sampling → convolution at every border → GroupNorm) against f64 loops, and the size checks. +- Not done: masks only for the queries above the threshold (`merge` keeps sigmoid(logit) · sigmoid(presence) > 0.5). + `Sam3::detect` returns all 200 and the reference test (`crates/segment/tests/reference.rs`) checks the + best-scoring query's mask, which need not pass the threshold; with `rows` it is a matter of passing fewer of them. + ## Open items - Keep the loupe texture on the GPU (render into an `egui-wgpu` texture on eframe's device instead of reading back); share the device with eframe. diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index a6c63b816a..5aca6898e7 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (pen pressure for brush masks; monitor profile from colord on Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (SAM 3's mask decoder on the GPU through wgpu on Windows and Linux); previously major (created from the code, gpu-pipeline.md and the parity checklist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 What Lightroom does with the machine's hardware, per platform, and what LightCraft does. Sources: [gpu-pipeline.md](gpu-pipeline.md), [display-profiles.md](display-profiles.md), [denoise.md](denoise.md), @@ -10,7 +10,7 @@ What Lightroom does with the machine's hardware, per platform, and what LightCra |---|---|---|---|---|---|---| | GPU for display and editing | Metal / DX12, "Use GPU for display / image processing / export" | wgpu Metal: geometry, resize, blur, WB, NR, guided filter, dehaze, masks, finish; CPU fallback per render | DX12 only (Vulkan opt-in, #136) | Vulkan (CPU ↔ GPU equivalence verified on an AMD Radeon 8060S, RADV) | CPU only (no WebGPU yet) | 🟡 defringe, spot removal, heuristic masks, long brushes and high-bit exports stay on CPU | | GPU export | ✅ | ✅ (6000 × 4000 in ~0.3 s vs ~1.2 s CPU) | ✅ | ✅ | — | ✅ (black-export fix on an Intel iGPU, #78) | -| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on CPU | CPU / GPU denoise | CPU / GPU denoise | — | 🟡 no Core ML / Neural Engine / DirectML | +| AI on GPU / neural engine | Metal / DirectML / Core ML, model per feature | AI denoise on GPU or CPU (setting); SAM 3 on Metal via candle; faces on GPU when faster (CPU-only setting) | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, DX12), the rest of the heads on CPU (untested on DX12 so far); faces GPU / CPU | CPU / GPU denoise; SAM 3 image encoder, necks, DETR encoder and mask decoder on the GPU (wgpu, Vulkan), the rest of the heads on CPU (a photo's analysis ~0.6 s on an RTX 5070 vs ~33 s on a Ryzen 9 3900X, a description ~0.5–0.7 s vs ~4.5 s); faces GPU / CPU | — | 🟡 no Core ML / Neural Engine / DirectML; SAM 3's click decoder, text encoder and DETR decoder on CPU outside macOS | | HDR (EDR) display | ✅ (macOS EDR, Windows HDR) | ⬜ | ⬜ | ⬜ | ⬜ | ⬜ (LR-VIEW-HDR-DISPLAY) | | Monitor profile | automatic per display, follows the window | ✅ the screen's profile, followed across screens | 🟡 picked by hand (WCS needs FFI) | 🟡 colord's profile (one display, or all sharing one); no follow across monitors | — | 🟡 Windows OS profile not read; Linux per-monitor follow missing | | Second window / second monitor | ✅ (Classic) | ✅ (⌘F11) | ✅ | ✅ | — | ✅ (Classic secondary-window keys missing) | @@ -49,6 +49,9 @@ NVIDIA, Intel and Windows DX12 still rely on user reports. | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | AI on GPU: SAM 3's text detector mask decoder also runs on the GPU through wgpu on Windows and Linux (a description ~0.5–0.7 s with the text cache and box bias of the same change) | +| 2026-10-17 | minor | AI on GPU: SAM 3's necks and DETR encoder also run on the GPU through wgpu on Windows and Linux | +| 2026-10-17 | minor | AI on GPU: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback; follows the GPU switches); faces run on the GPU when faster | | 2026-10-12 | minor | Monitor profile: Linux reads the display profile from colord; macOS row reflects #787 | | 2026-10-12 | minor | CPU ↔ GPU equivalence suite run on an AMD Radeon 8060S (Vulkan, RADV, Linux): 16 tests / 135 cases pass, max 2 LSB, mean ≤ 0.0003; first GPU verified outside Apple | | 2026-10-12 | minor | Pen pressure: strokes record per-point pressure from egui touch force, scaling dab size and flow; per-platform status | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 21140ae26e..163ebc5e8b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-21 · **Change:** minor (LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (LR-MASK-OBJECTS: SAM 3's image encoder, necks, DETR encoder and mask decoder on the GPU through wgpu outside macOS) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -293,7 +293,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-MASK-SUBJECT | Select subject | P2 | 🟡 | `cmd:mask.add` (`subject`), `crates/pipeline/src/masks.rs` | saliency heuristic, no segmentation model; a photo that carries person mattes (DNG semantic masks: iPhone ProRAW portrait / skin / hair / teeth / glasses mattes) uses them instead (synthetic files only: no corpus file carries person mattes) | | LR-MASK-SKY | Select sky | P2 | 🟡 | `cmd:mask.add` (`sky`), `crates/pipeline/src/masks.rs` (`Mattes`), `crates/raw/src/semantic.rs` | heuristic; a photo that carries a sky matte (DNG semantic mask, e.g. iPhone ProRAW) uses it instead, through orientation / crop / lens corrections, preview = export (checked on one CC0 iPhone 12 Pro ProRAW and synthetic files) | | LR-MASK-BACKGROUND | Select background | P2 | 🟡 | `cmd:mask.add` (`background`) | inverse of the subject mask (heuristic, or the photo's person mattes) | -| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment/mod.rs` | SAM 3 in pure Rust (candle; Metal on macOS, CPU elsewhere): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, much longer on CPU) | +| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment/mod.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) | | LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic | | LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty | | LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt | @@ -818,6 +818,10 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | | 2026-10-12 | minor | LR-IMP-FORMATS: folder discovery includes SR2/SRF; MCP and CLI reuse the engine extension list. DSC-F828 remains preview-only; decoder support and row status unchanged | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's text detector mask decoder runs on the GPU through wgpu too (with the cached prompt features and the one-pass box bias: a description ~2 s → ~0.5–0.7 s with an RTX 5070); status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's two necks and the text detector's DETR encoder also run on the GPU (wgpu) outside macOS: a photo's analysis ~0.6 s, a description ~2 s on an RTX 5070; status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: Run on: Automatic / CPU for AI masks (`segment.settings`), CPU on every platform incl. macOS; status unchanged (🟡) | +| 2026-10-17 | minor | LR-MASK-OBJECTS: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback, the GPU switches), where it runs shows in Settings and `segment.model.status`; status unchanged (🟡) | | 2026-10-12 | minor | LR-EDIT-OPTICS-PROFILE: Sony ARW shading, CA and distortion tables decoded with settings and provenance (raw IFD, `SR2SubIFD` fallback); applied corrections unchanged (ILCE-7RM4A and ILCE-7RM6 distortion); status unchanged (🟡) | | 2026-10-14 | minor | LR-IMP-CAMERA-COVERAGE: Camera-coverage sweep (#1327): 30 models verified on 40 CC0 files (coverage.py 515 → 545 verified); sensor verification does not establish colour parity (#1277); status unchanged (🟡) | | 2026-10-13 | minor | LR-MERGE-PANO: a panorama's DNG takes its `AsShotNeutral` from the median of its frames' vendor white-balance multipliers (CR2, NEF, ARW…) instead of the first frame's tags, and frames now carry the multipliers (issue #1144); status unchanged (✅) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a7091a05a..7febd8cd7d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: LightCraft vs Adobe Lightroom -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; Platforms: the Windows x64 installer verified on Windows 11) · **Target:** Adobe Lightroom Classic 15.5 (August 2026) and Lightroom 9.6 (desktop) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Object / Describe masks: SAM 3 on the GPU through wgpu outside macOS) · **Target:** Adobe Lightroom Classic 15.5 (August 2026) and Lightroom 9.6 (desktop) The authoritative assessment of how close LightCraft is to Lightroom. The row-by-row checklist is [parity-checklist.md](parity-checklist.md); the ranked work list is [gaps.md](gaps.md); deep areas @@ -94,7 +94,7 @@ search embeddings; generative remove runs in Adobe's cloud. | 2026-10-12 | minor | Epson ERF decoded (raw-parity.md): 240 models verified, 229 preview-only; shares and rounded numbers unchanged | | Subject / Sky / Background masks | classical heuristics; the file's own DNG semantic mattes | 🟡 | | People (faces, body, hair, skin…) and Landscape masks | — | ⬜ | -| Object / Describe masks | SAM 3 in pure Rust (Metal / CPU); opt-in 3.4 GB download, no mirror configured | 🟡 | +| Object / Describe masks | SAM 3 in pure Rust (Metal on macOS; elsewhere the image encoder, necks and text detector's DETR encoder and mask decoder on the GPU through wgpu, the rest of the heads on the CPU, CPU fallback); opt-in 3.4 GB download, no mirror configured | 🟡 | | Depth range mask, Lens Blur | — | ⬜ | | AI Denoise | Bayer only, pure-Rust CPU / GPU, user-installed weights | 🟡 | | Raw Details, Super Resolution | — | ⬜ | @@ -302,6 +302,8 @@ P2 items 12–25 h; look tuning, performance, packaging, hardening 25–45 h. |---|---|---| | 2026-10-19 | minor | Localization ~55% → ~64% (mean of the 12 key languages): Indonesian (`id`) catalog, every message but What's New; full target 61.2% → 61.5% (still ~61%) | | 2026-10-19 | patch | Platforms: the Windows installer is no longer listed as unverified (the 0.9.1 x64 MSI is tested on Windows 11; a confirmation after uninstalling from Settings → Apps, #892, remains); #790 noted as fixed in 0.9.1; percentages and hours unchanged | +| 2026-10-17 | minor | Object / Describe masks: SAM 3's necks and text detector's encoder also on the GPU outside macOS; status unchanged | +| 2026-10-17 | minor | Object / Describe masks: SAM 3's image encoder runs on the GPU through wgpu on Windows and Linux (CPU fallback); status and numbers unchanged | | 2026-10-14 | minor | Localization ~52% → ~55% (mean of the 12 key languages): de, es, fr, ja and uk catalogs filled | | 2026-10-12 | minor | UI/UX remaining 34–58 h → 32–54 h (canvas tools by keyboard); headline numbers unchanged | | 2026-10-14 | minor | Merge and HDR: merge 100% → 88% (LR-MERGE-HDR ✅ → 🟡 after testing on real 67 MP brackets; gap 29); area percentages unchanged | From f7ca0511861f21a5db6f6942a23404037f0b279a Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:26:53 +0100 Subject: [PATCH 2/2] docs(gpu): SAM 3 tested on an RX 7900 XTX; device memory of all parts The backbone notes list the AMD RX 7900 XTX run on Windows 11 (DX12 and Vulkan, all four sam3_ tests) next to the RTX 5070 and the M4 Pro. A short section adds up the device memory of the backbone, necks, DETR encoder and mask decoder, and says what happens when a part runs out of it. Co-Authored-By: Claude Opus 5.5 --- docs/gpu-pipeline.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index ca5406b880..326a2ab0dd 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -401,8 +401,10 @@ stop-after-a-device-error handling; any failure is an `Err` and the candle backb backbone: IoU 1.0. With f16 weights: max rel 3.8e-3, mean abs 5.4e-4, mask IoU ≥ 0.9997. - Tests: kernel unit tests against plain loops (`src/sam3/tests.rs`: cut-off tiles, K not a multiple of the tile, windowed and global attention, LN, RoPE, im2col/reorder, f16 rounding), skipped without a GPU; the end-to-end - test runs with `LIGHTCRAFT_SAM3_DIR` set. Tested on NVIDIA (RTX 5070, Vulkan) and Apple silicon (M4 Pro, Metal - through wgpu: first forward 3.1 s, CPU 17.2 s; max rel 4.9e-5, masks IoU ≥ 0.99992). AMD, Intel and DX12 are untested. + test runs with `LIGHTCRAFT_SAM3_DIR` set. Tested on NVIDIA (RTX 5070, Vulkan), Apple silicon (M4 Pro, Metal + through wgpu: first forward 3.1 s, CPU 17.2 s; max rel 4.9e-5, masks IoU ≥ 0.99992) and AMD (RX 7900 XTX on + Windows 11, DX12 and Vulkan, all four `sam3_` tests: backbone 0.46 s on DX12 and 0.51 s on Vulkan against 26 s in + candle on the CPU, max rel 4.3e-5 / 5.1e-5; on DX12 Describe, semantic and click masks IoU ≥ 0.9993). Intel is untested. ### SAM 3 necks After the backbone, the click decoder needs the tracker neck (`tracker_neck`) and Describe the detector's @@ -519,6 +521,14 @@ candle runs the decoder for that model from then on. `Sam3::detect` returns all 200 and the reference test (`crates/segment/tests/reference.rs`) checks the best-scoring query's mask, which need not pass the threshold; with `rows` it is a matter of passing fewer of them. +### SAM 3 on the GPU: device memory in all +With every part on the GPU (after a photo's analysis and a first Describe): the backbone's 1.8 GB of f32 weights and +0.2 GB of work buffers, both necks ~245 MB, the DETR encoder 38 MB of weights and 80 MB of work buffers, the mask +decoder 6 MB and 282 MB: ~2.7 GB of device memory, ~1.8 GB when the backbone falls back to f16 weights. The parts +after the backbone load on first use, each on its own; one that runs out of memory (or fails otherwise) stays in +candle on the CPU from then on (`Sam3::detr_fallback`, `Sam3::mask_fallback`, the necks per kind) and the others stay +on the GPU. Settings ▸ Performance ▸ AI masks ▸ Run on: CPU keeps all of it off the GPU. + ## Open items - Keep the loupe texture on the GPU (render into an `egui-wgpu` texture on eframe's device instead of reading back); share the device with eframe.