diff --git a/crates/gpu/examples/sam3_backbone_bench.rs b/crates/gpu/examples/sam3_backbone_bench.rs index 9f6c8ebe11..700c53c0a2 100644 --- a/crates/gpu/examples/sam3_backbone_bench.rs +++ b/crates/gpu/examples/sam3_backbone_bench.rs @@ -6,7 +6,7 @@ //! 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 and necks, the rest in candle on the CPU): encode, +//! 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). diff --git a/crates/gpu/src/sam3.rs b/crates/gpu/src/sam3.rs index 263599d373..2265533336 100644 --- a/crates/gpu/src/sam3.rs +++ b/crates/gpu/src/sam3.rs @@ -15,8 +15,10 @@ //! `wgsl/sam3_ops.wgsl` (layer norm, RoPE, im2col, the final reorder). All of the dispatches, with their parameters //! and bind groups, are built once with the weights; a forward pass uploads the pixels, submits one command buffer //! 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 text detector's heads stay in -//! candle on the CPU. +//! 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 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 @@ -31,6 +33,7 @@ use bytemuck::Pod; use lightcraft_segment::{BACKBONE_PREFIX, BackboneAccel, NeckKind, WeightReader}; use wgpu::util::DeviceExt; +mod detr; mod neck; #[cfg(test)] mod tests; @@ -949,6 +952,8 @@ pub struct Sam3Gpu { /// Bytes of work buffers on the device. work_bytes: u64, precision: Precision, + /// The detector's DETR encoder, loaded on the first text prompt. + detr: detr::Encoder, /// The feature pyramids, built on first use. necks: neck::Necks, } @@ -1044,8 +1049,9 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision) } g.channels_first(&x, &y, HIDDEN, GRID, WINDOW)?; 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, necks }) + Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision, detr, necks }) } /// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name). @@ -1067,6 +1073,11 @@ impl Sam3Gpu { self.work_bytes + (TOKENS * HIDDEN * 4) as u64 } + /// Bytes of device memory the DETR encoder's weights and work buffers take, once a text prompt loaded them. + pub fn detr_bytes(&self) -> Option<(u64, u64)> { + self.detr.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())); @@ -1103,6 +1114,17 @@ impl BackboneAccel for Sam3Gpu { guarded("a SAM 3 neck", || self.necks.run(self.dev, which, backbone, n)) } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> 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 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid)) + } + fn closing(&self) -> bool { crate::shutting_down() } @@ -1111,6 +1133,10 @@ impl BackboneAccel for Sam3Gpu { true } + fn runs_detr_encoder(&self) -> bool { + true + } + fn device(&self) -> String { let weights = match self.precision { Precision::F32 => "", diff --git a/crates/gpu/src/sam3/detr.rs b/crates/gpu/src/sam3/detr.rs new file mode 100644 index 0000000000..a3e28c25cb --- /dev/null +++ b/crates/gpu/src/sam3/detr.rs @@ -0,0 +1,356 @@ +//! The DETR encoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): six +//! layers over the 72 × 72 image tokens of 256, each self-attention (q and k from the normed tokens plus their sine +//! position encoding, v from the normed tokens) → cross-attention to the prompt's 32 tokens (with the key-padding bias) +//! → MLP 256 → 2048 → 256 with ReLU, each after a layer norm (eps 1e-5) and added to the tokens. ~4 s per prompt on +//! the CPU through candle. +//! +//! Kernels: the backbone's matrix product (ReLU in its epilogue) and layer norm, and `wgsl/sam3_detr.wgsl`: attention +//! with heads of 32 whose q, k and v come from separate buffers (the cross-attention's k and v from the prompt), with +//! an optional per-key bias, and a sum. The weights (38 MB) and the kernels load on the first prompt, not with the +//! backbone; then every dispatch is recorded once, and 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. + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use lightcraft_segment::WeightReader; + +use super::{Dev, Graph, Precision, Recorded, TIMEOUT, buffer, pipeline, u32_of, upload}; + +#[cfg(test)] +mod tests; + +/// Where the encoder's weights are in the checkpoint. +const PREFIX: &str = "detector_model.detr_encoder"; +/// Image tokens (72 × 72), their width, the prompt's tokens. +const TOKENS: usize = 72 * 72; +const WIDTH: usize = 256; +const TEXT: usize = 32; +const HEAD_DIM: usize = 32; +const MLP: usize = 2048; +const LAYERS: usize = 6; +/// PyTorch's `nn.LayerNorm` default (`TORCH_LN_EPS`). +const EPS: f32 = 1e-5; +/// Keys per step of the attention kernel (the prompt's 32 tokens are one step). +const KEYS: u32 = 32; +/// `p.gelu` of the matrix product: ReLU. +const RELU: u32 = 2; +/// No bias in the attention kernel. +const NONE: u32 = u32::MAX; + +pub(super) struct Kernels { + attention: wgpu::ComputePipeline, + add: wgpu::ComputePipeline, +} + +static KERNELS: OnceLock> = OnceLock::new(); + +/// The encoder's kernels, compiled on first use (the mask decoder's prompt attention uses them too). +pub(super) 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 = attention_source(KEYS); + let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 detr", &source, entry); + let k = Kernels { attention: pipe("attention"), add: pipe("add") }; + match pollster::block_on(validation.pop()) { + Some(e) => Err(format!("{}: the SAM 3 DETR kernels did not compile ({e})", dev.info.name)), + None => Ok(k), + } + }) + .as_ref() + .map_err(Clone::clone) +} + +/// The attention kernel for `keys` keys per step, written out from `wgsl/sam3_detr.wgsl` (as the backbone's). +fn attention_source(keys: u32) -> String { + use std::fmt::Write; + let d4 = (HEAD_DIM / 4) as u32; + let (mut decl, mut scores, mut rescale, mut acc, mut store) = (String::new(), String::new(), String::new(), String::new(), String::new()); + // writing into a String cannot fail + for c in 0..d4 { + let _ = writeln!(decl, " let q{c} = qs[qa + {c}u];\n var o{c} = vec4(0.0);"); + let _ = writeln!(rescale, " o{c} *= fix;"); + let _ = writeln!(store, " out[oa + {c}u] = o{c} * r;"); + } + for j in 0..keys { + let terms: Vec = (0..d4).map(|c| format!("q{c} * Ks[{}u]", j * d4 + c)).collect(); + let _ = writeln!( + scores, + " let d{j} = {};\n let s{j} = (d{j}.x + d{j}.y + d{j}.z + d{j}.w) * SCALE + Bs[{j}u];\n top = max(top, s{j});", + terms.join(" + ") + ); + let _ = writeln!(acc, " {{\n let w = exp(s{j} - top);\n l += w;"); + for c in 0..d4 { + let _ = writeln!(acc, " o{c} = fma(vec4(w), Vs[{}u], o{c});", j * d4 + c); + } + let _ = writeln!(acc, " }}"); + } + include_str!("../wgsl/sam3_detr.wgsl") + .replace("{{KB}}", &keys.to_string()) + .replace("{{DECL}}", &decl) + .replace("{{SCORES}}", &scores) + .replace("{{RESCALE}}", &rescale) + .replace("{{ACCUMULATE}}", &acc) + .replace("{{STORE}}", &store) +} + +/// Where an attention's q, k and v are: a buffer, its row stride and the column of head 0 (in floats). +pub(super) struct Operand<'a> { + pub(super) buffer: &'a wgpu::Buffer, + pub(super) stride: usize, + pub(super) offset: usize, +} + +impl Graph { + /// Layer norm with PyTorch's eps (the backbone's is 1e-6). + pub(super) fn layernorm_torch(&mut self, [x, gamma, beta, y]: [&wgpu::Buffer; 4], rows: usize, c: usize) -> Result<(), String> { + let (g, row) = self.flat(rows)?; + self.push(&self.dev.k.layernorm, [u32_of(rows)?, u32_of(c)?, 0, 0, EPS.to_bits(), 0, u32_of(rows)?, row], [x, gamma, beta, y], g); + Ok(()) + } + + /// `y = relu(x · wᵀ + bias)`. + fn matmul_relu(&mut self, buffers: [&wgpu::Buffer; 4], dims: (usize, usize, usize)) -> Result<(), String> { + self.matmul(buffers, dims, 1, false, false, Precision::F32)?; + if let Some(step) = self.steps.last_mut() { + step.params[4] = RELU; + } + Ok(()) + } + + /// `out = a + b`, `len` floats (a multiple of 4). + fn add(&mut self, k: &'static Kernels, [a, b, out]: [&wgpu::Buffer; 3], len: usize) -> Result<(), String> { + if !len.is_multiple_of(4) { + return Err("a sum the SAM 3 kernel cannot do".into()); + } + let (g, row) = self.flat((len / 4).div_ceil(256))?; + self.push(&k.add, [u32_of(len / 4)?, row, 0, 0, 0, 0, 0, 0], [a, b, &self.dev.dummy, out], g); + Ok(()) + } + + /// Attention of `queries` queries over `keys` keys, `heads` heads of 32, into `out` (`[queries, heads · 32]`); + /// with `bias`, key j's scores get `k.buffer[bias + j]` added. + #[allow(clippy::too_many_arguments)] + pub(super) fn attention_detr( + &mut self, + kernels: &'static Kernels, + [q, k, v]: [Operand; 3], + bias: Option, + out: &wgpu::Buffer, + (queries, keys, heads): (usize, usize, usize), + ) -> Result<(), String> { + let aligned = [q.stride, q.offset, k.stride, k.offset, v.stride, v.offset].iter().all(|n| n.is_multiple_of(4)); + if keys == 0 || !keys.is_multiple_of(KEYS as usize) || !aligned || q.offset != 0 { + return Err("an attention the SAM 3 DETR kernel cannot do".into()); + } + let bias = match bias { + Some(b) => u32_of(b)?, + None => NONE, + }; + let params = + [u32_of(queries)?, u32_of(keys)?, u32_of(q.stride)?, u32_of(k.stride)?, u32_of(v.stride)?, u32_of(k.offset)?, u32_of(v.offset)?, bias]; + let groups = [u32_of(queries.div_ceil(64))?, u32_of(heads)?, 1]; + if groups[0] > self.dev.limits.max_compute_workgroups_per_dimension { + return Err("too many queries for the SAM 3 DETR attention kernel".into()); + } + self.push(&kernels.attention, params, [q.buffer, k.buffer, v.buffer, out], groups); + Ok(()) + } +} + +/// One layer's weights on the device: (weight, bias) pairs, the q | k and k | v ones concatenated. +struct Layer { + ln1: [wgpu::Buffer; 2], + self_qk: [wgpu::Buffer; 2], + self_v: [wgpu::Buffer; 2], + self_o: [wgpu::Buffer; 2], + ln2: [wgpu::Buffer; 2], + cross_q: [wgpu::Buffer; 2], + cross_kv: [wgpu::Buffer; 2], + cross_o: [wgpu::Buffer; 2], + ln3: [wgpu::Buffer; 2], + fc1: [wgpu::Buffer; 2], + fc2: [wgpu::Buffer; 2], +} + +/// Reads the encoder's tensors, checking their shapes. +struct Loader<'a> { + weights: &'a WeightReader, + dev: &'static Dev, + bytes: u64, +} + +impl Loader<'_> { + /// The tensors `names` (each of `shape`) concatenated along the first axis. + fn upload(&mut self, names: &[String], shape: &[usize]) -> Result { + 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(upload(self.dev, names.first().map_or("weight", String::as_str), &all)) + } + + /// A linear layer (or several along n): `[n, k]` weights and their bias. + fn linear(&mut self, 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(); + Ok([self.upload(&w, &[n, k])?, self.upload(&b, &[n])?]) + } + + fn norm(&mut self, name: &str) -> Result<[wgpu::Buffer; 2], String> { + Ok([self.upload(&[format!("{name}.weight")], &[WIDTH])?, self.upload(&[format!("{name}.bias")], &[WIDTH])?]) + } + + fn layer(&mut self, i: usize) -> Result { + let l = format!("layers.{i}"); + let (s, c) = (format!("{l}.self_attn"), format!("{l}.cross_attn")); + let proj = |a: &str, ps: &[&str]| -> Vec { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() }; + Ok(Layer { + ln1: self.norm(&format!("{l}.layer_norm1"))?, + self_qk: self.linear(&proj(&s, &["q", "k"]), WIDTH, WIDTH)?, + self_v: self.linear(&proj(&s, &["v"]), WIDTH, WIDTH)?, + self_o: self.linear(&proj(&s, &["o"]), WIDTH, WIDTH)?, + ln2: self.norm(&format!("{l}.layer_norm2"))?, + cross_q: self.linear(&proj(&c, &["q"]), WIDTH, WIDTH)?, + cross_kv: self.linear(&proj(&c, &["k", "v"]), WIDTH, WIDTH)?, + cross_o: self.linear(&proj(&c, &["o"]), WIDTH, WIDTH)?, + ln3: self.norm(&format!("{l}.layer_norm3"))?, + fc1: self.linear(&[format!("{l}.mlp.fc1")], MLP, WIDTH)?, + fc2: self.linear(&[format!("{l}.mlp.fc2")], WIDTH, MLP)?, + }) + } +} + +/// The buffers a prompt writes and reads. +struct Work { + /// The image tokens in, the memory out (the layers add to it in place). + x: wgpu::Buffer, + pos: wgpu::Buffer, + text: wgpu::Buffer, + /// The cross-attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats). + text_kv: wgpu::Buffer, + staging: wgpu::Buffer, +} + +/// The encoder with its weights on the device and its dispatches recorded. +struct Built { + recorded: Recorded, + /// One prompt at a time (they share the work buffers). + work: Mutex, + /// Bytes of device memory: weights, work buffers. + weight_bytes: u64, + work_bytes: u64, +} + +/// The DETR encoder, built on first use from the checkpoint the backbone came from. +pub(super) struct Encoder { + weights: WeightReader, + built: OnceLock>, +} + +impl Encoder { + 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, b.work_bytes)) + } + + /// The memory `[5184, 256]` for the image tokens and their position encoding (`[5184, 256]` each) and the prompt's + /// tokens `[32, 256]` (`valid`: its real ones). + pub(super) fn run(&self, dev: &'static Dev, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + if image.len() != TOKENS * WIDTH || pos.len() != TOKENS * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT { + return Err(format!( + "{} image, {} position, {} prompt values and {} prompt tokens, expected {TOKENS} × {WIDTH}, {TOKENS} × {WIDTH}, {TEXT} × {WIDTH} and {TEXT}", + image.len(), + pos.len(), + text.len(), + valid.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 work = b.work.lock().unwrap_or_else(PoisonError::into_inner); + dev.queue.write_buffer(&work.x, 0, bytemuck::cast_slice(image)); + dev.queue.write_buffer(&work.pos, 0, bytemuck::cast_slice(pos)); + dev.queue.write_buffer(&work.text, 0, bytemuck::cast_slice(text)); + dev.queue.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias)); + let out = b.recorded.run("the SAM 3 DETR encoder", dev, &work.x, &work.staging, TOKENS * WIDTH)?; + if out.iter().any(|v| !v.is_finite()) { + return Err("the GPU DETR encoder produced non-finite values".into()); + } + Ok(out) + } +} + +fn build(dev: &'static Dev, weights: &WeightReader) -> Result { + let k = kernels(dev)?; + let oom = dev.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation); + let made = build_inner(dev, k, weights); + // let the uploads land before the scopes close + let _ = dev.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(TIMEOUT) }); + let (validation, oom) = (pollster::block_on(validation.pop()), pollster::block_on(oom.pop())); + if let Some(e) = oom { + return Err(format!("not enough GPU memory for the SAM 3 DETR encoder: {e}")); + } + if let Some(e) = validation { + return Err(format!("the GPU rejected the SAM 3 DETR encoder: {e}")); + } + made +} + +fn build_inner(dev: &'static Dev, k: &'static Kernels, weights: &WeightReader) -> Result { + let mut ld = Loader { weights, dev, bytes: 0 }; + let layers = (0..LAYERS).map(|i| ld.layer(i)).collect::, _>>()?; + + let tokens = |label: &str| buffer(dev, label, TOKENS * WIDTH); + let (x, y, hp, v, att, pos) = + (tokens("detr hidden"), tokens("detr normed"), tokens("detr normed + pos"), tokens("detr v"), tokens("detr attention"), tokens("detr pos")); + // the self-attention's q | k, then the MLP's hidden activations + let wide = buffer(dev, "detr wide", TOKENS * MLP.max(2 * WIDTH)); + let text = buffer(dev, "detr prompt", TEXT * WIDTH); + let text_kv = buffer(dev, "detr prompt k|v", TEXT * 2 * WIDTH + TEXT); + let staging = dev.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("detr read-back"), + size: (TOKENS * WIDTH * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let work_bytes = ((7 * TOKENS * WIDTH + TOKENS * MLP + TEXT * (3 * WIDTH + 1)) * 4) as u64; + + let mut g = Graph::new(dev); + let heads = WIDTH / HEAD_DIM; + for l in &layers { + // self-attention: q and k from the normed tokens plus their position, v from the normed tokens + g.layernorm_torch([&x, &l.ln1[0], &l.ln1[1], &y], TOKENS, WIDTH)?; + g.add(k, [&y, &pos, &hp], TOKENS * WIDTH)?; + g.matmul([&hp, &l.self_qk[0], &l.self_qk[1], &wide], (TOKENS, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&y, &l.self_v[0], &l.self_v[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (q, kk) = (Operand { buffer: &wide, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &wide, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [q, kk, Operand { buffer: &v, stride: WIDTH, offset: 0 }], None, &att, (TOKENS, TOKENS, heads))?; + g.matmul([&att, &l.self_o[0], &l.self_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // cross-attention to the prompt, its padding masked + g.layernorm_torch([&x, &l.ln2[0], &l.ln2[1], &y], TOKENS, WIDTH)?; + g.matmul([&y, &l.cross_q[0], &l.cross_q[1], &v], (TOKENS, WIDTH, WIDTH), 1, false, false, Precision::F32)?; + g.matmul([&text, &l.cross_kv[0], &l.cross_kv[1], &text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?; + let (tk, tv) = (Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &text_kv, stride: 2 * WIDTH, offset: WIDTH }); + g.attention_detr(k, [Operand { buffer: &v, stride: WIDTH, offset: 0 }, tk, tv], Some(TEXT * 2 * WIDTH), &att, (TOKENS, TEXT, heads))?; + g.matmul([&att, &l.cross_o[0], &l.cross_o[1], &x], (TOKENS, WIDTH, WIDTH), 1, false, true, Precision::F32)?; + // MLP + g.layernorm_torch([&x, &l.ln3[0], &l.ln3[1], &y], TOKENS, WIDTH)?; + g.matmul_relu([&y, &l.fc1[0], &l.fc1[1], &wide], (TOKENS, MLP, WIDTH))?; + g.matmul([&wide, &l.fc2[0], &l.fc2[1], &x], (TOKENS, WIDTH, MLP), 1, false, true, Precision::F32)?; + g.cut(); + } + let recorded = g.record(); + Ok(Built { recorded, work: Mutex::new(Work { x, pos, text, text_kv, staging }), weight_bytes: ld.bytes, work_bytes }) +} diff --git a/crates/gpu/src/sam3/detr/tests.rs b/crates/gpu/src/sam3/detr/tests.rs new file mode 100644 index 0000000000..95884facab --- /dev/null +++ b/crates/gpu/src/sam3/detr/tests.rs @@ -0,0 +1,267 @@ +//! The DETR encoder's kernels against plain loops: attention with heads of 32 (self- and cross-attention, the padding +//! bias, queries not filling the last workgroup), the sum, ReLU and the layer norm's eps. The whole encoder against +//! candle: `tests/it/sam3_detr.rs`. + +use super::super::dev; +use super::*; + +fn gpu() -> Option<(&'static Dev, &'static Kernels)> { + let d = match dev() { + Ok(d) => d, + // 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 None; + } + }; + Some((d, kernels(d).unwrap())) +} + +/// Deterministic values in −scale..scale. +fn values(n: usize, seed: u64, scale: f32) -> Vec { + let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() +} + +fn read(d: &'static Dev, g: Graph, out: &wgpu::Buffer, len: usize) -> Vec { + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (len * 4) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + g.record().run("a test", d, out, &staging, len).unwrap() +} + +fn worst(got: &[f32], want: &[f32]) -> f32 { + assert_eq!(got.len(), want.len()); + got.iter().zip(want).fold(0f32, |m, (a, b)| m.max((a - b).abs())) +} + +/// Where a test attention's operand is in its buffer. +struct At<'a> { + data: &'a [f32], + stride: usize, + offset: usize, +} + +/// Softmax attention of every query over all keys, `heads` heads of 32, as candle computes it: the scores +/// `q · k / sqrt(32) + bias` in f32 (so f32::MIN swallows a padded key's score), the rest in f64. +fn attention_ref(q: At, k: At, v: At, bias: Option<&[f32]>, (queries, keys, heads): (usize, usize, usize)) -> Vec { + let scale = (HEAD_DIM as f32).powf(-0.5); + let mut out = vec![0f32; queries * heads * HEAD_DIM]; + for t in 0..queries { + for h in 0..heads { + let at = |o: &At, row: usize, c: usize| o.data[row * o.stride + o.offset + h * HEAD_DIM + c]; + let scores: Vec = (0..keys) + .map(|j| { + let dot = (0..HEAD_DIM).map(|c| f64::from(at(&q, t, c)) * f64::from(at(&k, j, c))).sum::() as f32; + dot * scale + bias.map_or(0.0, |b| b[j]) + }) + .collect(); + let top = scores.iter().fold(f32::MIN, |m, s| m.max(*s)); + let w: Vec = scores.iter().map(|s| f64::from(s - top).exp()).collect(); + let sum: f64 = w.iter().sum(); + for c in 0..HEAD_DIM { + let o = (0..keys).map(|j| w[j] * f64::from(at(&v, j, c))).sum::() / sum; + out[(t * heads + h) * HEAD_DIM + c] = o as f32; + } + } + } + out +} + +#[test] +fn the_kernel_source_is_written_out() { + let src = attention_source(KEYS); + assert!(!src.contains("{{"), "a mark is left"); + assert!(src.contains("let s31 = ") && !src.contains("let s32 = ")); + assert!(src.contains("let q7 = ") && !src.contains("let q8 = ")); +} + +#[test] +fn self_attention_over_8_heads_of_32_gives_the_softmax_of_the_definition() { + let Some((d, k)) = gpu() else { return }; + let heads = 8; + let w = heads * HEAD_DIM; + // q | k in one buffer (k at column 256), v in another; 200 queries leave the last workgroup part empty + for (queries, keys) in [(200, 96), (64, 32), (130, 320)] { + let rows = queries.max(keys); + let qk = values(rows * 2 * w, queries as u64, 2.0); + let v = values(keys * w, 7 + keys as u64, 1.0); + let (bqk, bv) = (upload(d, "qk", &qk), upload(d, "v", &v)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bqk, stride: 2 * w, offset: 0 }, + Operand { buffer: &bqk, stride: 2 * w, offset: w }, + Operand { buffer: &bv, stride: w, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &out, (queries, keys, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &qk, stride: 2 * w, offset: 0 }, + At { data: &qk, stride: 2 * w, offset: w }, + At { data: &v, stride: w, offset: 0 }, + None, + (queries, keys, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{queries} queries × {keys} keys: off by {err}"); + } +} + +#[test] +fn cross_attention_to_32_prompt_tokens_leaves_out_the_padding() { + let Some((d, k)) = gpu() else { return }; + let (heads, queries) = (8, 130); + let w = heads * HEAD_DIM; + let q = values(queries * w, 1, 2.0); + // the prompt's k | v ([32, 512]), then its bias: 0 for the real tokens, f32::MIN for padding + for real in [5, 32, 1, 0] { + let mut kv = values(TEXT * 2 * w, 2 + real as u64, 2.0); + let bias: Vec = (0..TEXT).map(|j| if j < real { 0.0 } else { f32::MIN }).collect(); + kv.extend(&bias); + let (bq, bkv) = (upload(d, "q", &q), upload(d, "kv", &kv)); + let out = buffer(d, "out", queries * w); + let mut g = Graph::new(d); + let ops = [ + Operand { buffer: &bq, stride: w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: 0 }, + Operand { buffer: &bkv, stride: 2 * w, offset: w }, + ]; + g.attention_detr(k, ops, Some(TEXT * 2 * w), &out, (queries, TEXT, heads)).unwrap(); + let got = read(d, g, &out, queries * w); + let want = attention_ref( + At { data: &q, stride: w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: 0 }, + At { data: &kv, stride: 2 * w, offset: w }, + Some(&bias), + (queries, TEXT, heads), + ); + let err = worst(&got, &want); + assert!(err < 2e-5, "{real} real tokens: off by {err}"); + if real == 1 { + // one real token: every query gets its v + let first = &kv[w..2 * w]; + assert!(worst(&got[..w], first) < 1e-6); + } + } +} + +#[test] +fn attention_the_kernel_cannot_do_is_an_error() { + let Some((d, k)) = gpu() else { return }; + let b = buffer(d, "b", 64 * 256); + let op = |stride, offset| Operand { buffer: &b, stride, offset }; + // keys not a multiple of 32, a stride not a multiple of 4, q not at column 0 + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(256, 0), op(256, 0)], None, &b, (64, 40, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 0), op(258, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).attention_detr(k, [op(256, 4), op(256, 0), op(256, 0)], None, &b, (64, 32, 8)).is_err()); + assert!(Graph::new(d).add(k, [&b, &b, &b], 6).is_err()); +} + +#[test] +fn sum_relu_and_torch_layer_norm_give_what_the_definitions_give() { + let Some((d, k)) = gpu() else { return }; + // the sum, over more than one row of workgroups' worth + let n = 4 * 256 * 70 + 12; + let (a, b) = (values(n, 1, 1.0), values(n, 2, 1.0)); + let (ba, bb, out) = (upload(d, "a", &a), upload(d, "b", &b), buffer(d, "out", n)); + let mut g = Graph::new(d); + g.add(k, [&ba, &bb, &out], n).unwrap(); + let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); + assert_eq!(read(d, g, &out, n), want); + + // ReLU in the product's epilogue + let (m, nn, kk) = (70, 90, 64); + let (x, w, bias) = (values(m * kk, 3, 1.0), values(nn * kk, 4, 0.3), values(nn, 5, 0.5)); + let (bx, bw, bbias, by) = (upload(d, "x", &x), upload(d, "w", &w), upload(d, "bias", &bias), buffer(d, "y", m * nn)); + let mut g = Graph::new(d); + g.matmul_relu([&bx, &bw, &bbias, &by], (m, nn, kk)).unwrap(); + let got = read(d, g, &by, m * nn); + let want: Vec = (0..m * nn) + .map(|o| { + let (i, j) = (o / nn, o % nn); + let v = f64::from(bias[j]) + (0..kk).map(|t| f64::from(x[i * kk + t]) * f64::from(w[j * kk + t])).sum::(); + v.max(0.0) as f32 + }) + .collect(); + assert!(worst(&got, &want) < 1e-5); + assert!(got.contains(&0.0) && got.iter().any(|v| *v > 0.0)); + + // rows of small spread, where eps 1e-5 and 1e-6 differ + let (rows, c) = (5, WIDTH); + let x = values(rows * c, 6, 3e-3); + let (gamma, beta) = (values(c, 7, 1.0), values(c, 8, 0.1)); + let (bx, bg, bb, by) = (upload(d, "x", &x), upload(d, "g", &gamma), upload(d, "b", &beta), buffer(d, "y", rows * c)); + let mut g = Graph::new(d); + g.layernorm_torch([&bx, &bg, &bb, &by], rows, c).unwrap(); + let got = read(d, g, &by, rows * c); + let mut want = vec![0f32; rows * c]; + for r in 0..rows { + let row = &x[r * c..(r + 1) * c]; + let mean = row.iter().map(|v| f64::from(*v)).sum::() / c as f64; + let var = row.iter().map(|v| (f64::from(*v) - mean).powi(2)).sum::() / c as f64; + for i in 0..c { + want[r * c + i] = ((f64::from(row[i]) - mean) / (var + f64::from(EPS)).sqrt() * f64::from(gamma[i]) + f64::from(beta[i])) as f32; + } + } + let err = worst(&got, &want); + assert!(err < 1e-4, "layer norm off by {err}"); +} + +/// The encoder's steps at its shapes: +/// `cargo test --release -p lightcraft-gpu --features sam --lib sam3::detr::tests::timings -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: needs a GPU"] +fn timings() { + let Some((d, k)) = gpu() else { return }; + let reps = 20; + let time = |name: &str, flops: f64, build: &dyn Fn(&mut Graph)| { + let out = buffer(d, "out", 4); + let staging = d.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut g = Graph::new(d); + for _ in 0..reps { + build(&mut g); + } + let rec = g.record(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let t = std::time::Instant::now(); + rec.run("a test", d, &out, &staging, 4).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3 / reps as f64; + eprintln!("{name:>34}: {ms:7.3} ms {:6.2} TFLOP/s", flops / ms / 1e9); + }; + let x = buffer(d, "x", TOKENS * MLP); + let y = buffer(d, "y", TOKENS * MLP); + let w = buffer(d, "w", MLP * WIDTH); + let b = buffer(d, "b", MLP); + for (n, kk) in [(2 * WIDTH, WIDTH), (WIDTH, WIDTH), (MLP, WIDTH), (WIDTH, MLP)] { + let flops = 2.0 * (TOKENS * n * kk) as f64; + time(&format!("matmul {TOKENS}x{n}x{kk}"), flops, &|g| g.matmul([&x, &w, &b, &y], (TOKENS, n, kk), 1, false, false, Precision::F32).unwrap()); + } + for keys in [TOKENS, TEXT] { + let flops = 4.0 * (TOKENS * keys * WIDTH) as f64; + time(&format!("attention {keys} keys"), flops, &|g| { + let ops = [ + Operand { buffer: &x, stride: 2 * WIDTH, offset: 0 }, + Operand { buffer: &x, stride: 2 * WIDTH, offset: WIDTH }, + Operand { buffer: &x, stride: WIDTH, offset: 0 }, + ]; + g.attention_detr(k, ops, None, &y, (TOKENS, keys, WIDTH / HEAD_DIM)).unwrap() + }); + } + time("layernorm", 0.0, &|g| g.layernorm_torch([&x, &b, &b, &y], TOKENS, WIDTH).unwrap()); + time("add", 0.0, &|g| g.add(k, [&x, &x, &y], TOKENS * WIDTH).unwrap()); +} diff --git a/crates/gpu/src/wgsl/sam3_detr.wgsl b/crates/gpu/src/wgsl/sam3_detr.wgsl new file mode 100644 index 0000000000..2ed63db145 --- /dev/null +++ b/crates/gpu/src/wgsl/sam3_detr.wgsl @@ -0,0 +1,105 @@ +// The DETR encoder of SAM 3's text detector (`sam3/detr.rs`): attention with heads of 32 (8 of them over 256 numbers), +// for the image tokens over themselves (self-attention) and over the prompt's tokens (cross-attention, with a +// key-padding bias), and the sum of two arrays (the position encoding added to the normed tokens). +// +// q [queries, q_stride]: head h's q at h · 32 (binding 1) +// k [keys, k_stride] from k_off (binding 2), v [keys, v_stride] from v_off (binding 3); 2 and 3 may be one buffer +// bias `keys` floats in binding 2 from `bias` (NONE: no bias), added to every score of its key: 0 for a real +// token, f32::MIN for padding, as candle's `padding_bias` +// out [queries, heads · 32] +// +// Strides and offsets count floats (multiples of 4); keys is a multiple of KB. Flash style like +// `sam3_attention.wgsl`: one query per thread with its q and partial output in registers, keys and values KB at a +// time through workgroup memory, online softmax. The running maximum starts at f32::MIN rather than below it: a padded +// key's score is then exactly f32::MIN (as in candle, where s + f32::MIN rounds to f32::MIN) and weighs nothing next +// to a real one, and a query whose keys are all padding averages them, as candle's softmax over equal scores does. +// The host writes out the per-thread work with one variable per vector and score (the DECL, SCORES, RESCALE, +// ACCUMULATE and STORE marks). + +struct P { + queries: u32, + keys: u32, + q_stride: u32, + k_stride: u32, + v_stride: u32, + k_off: u32, + v_off: u32, + bias: u32, +} + +@group(0) @binding(0) var p: P; +@group(0) @binding(1) var qs: array>; +@group(0) @binding(2) var ks: array>; +@group(0) @binding(3) var vs: array>; +@group(0) @binding(4) var out: array>; + +// head_dim / 4, keys per step, 1 / sqrt(head_dim) +const D4: u32 = 8u; +const KB: u32 = {{KB}}u; +const SCALE: f32 = 0.17677669529663687; +const NONE: u32 = 0xffffffffu; +const LOWEST: f32 = -3.4028234663852886e38; + +var Ks: array, KB * D4>; +var Vs: array, KB * D4>; +var Bs: array; + +@compute @workgroup_size(64) +fn attention(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) groups: vec3, @builtin(local_invocation_index) lid: u32) { + let head = wg.y; + let tq = wg.x * 64u + lid; + // threads past the last query compute on query 0 (the barriers below stay uniform) and store nothing + let live = tq < p.queries; + let qa = select(0u, tq, live) * (p.q_stride / 4u) + head * D4; + let k4 = p.k_stride / 4u; + let v4 = p.v_stride / 4u; + let ka = p.k_off / 4u + head * D4; + let va = p.v_off / 4u + head * D4; + +{{DECL}} + var m = LOWEST; + var l = 0.0; + + for (var k0 = 0u; k0 < p.keys; k0 += KB) { + for (var e = lid; e < KB * D4; e += 64u) { + let t = k0 + e / D4; + Ks[e] = ks[t * k4 + ka + e % D4]; + Vs[e] = vs[t * v4 + va + e % D4]; + } + if (lid < KB) { + var b = 0.0; + if (p.bias != NONE) { + let i = p.bias + k0 + lid; + b = ks[i / 4u][i % 4u]; + } + Bs[lid] = b; + } + workgroupBarrier(); + + var top = m; +{{SCORES}} + // rescale what was summed under the old maximum + let fix = exp(m - top); + l *= fix; +{{RESCALE}} +{{ACCUMULATE}} + m = top; + workgroupBarrier(); + } + + if (live) { + let r = 1.0 / l; + let oa = tq * groups.y * D4 + head * D4; +{{STORE}} + } +} + +// out = qs + ks, `queries` vectors (keys: workgroups per row of the dispatch). +@compute @workgroup_size(256) +fn add(@builtin(workgroup_id) wg: vec3, @builtin(local_invocation_index) lid: u32) { + let i = (wg.y * p.keys + wg.x) * 256u + lid; + if (i >= p.queries) { + return; + } + out[i] = qs[i] + ks[i]; +} diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index 6f7c7c9168..be8e9ca964 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -11,5 +11,7 @@ mod gpu_probe; #[cfg(feature = "sam")] mod sam3_backbone; #[cfg(feature = "sam")] +mod sam3_detr; +#[cfg(feature = "sam")] mod sam3_necks; mod thumbs_bench; diff --git a/crates/gpu/tests/it/sam3_detr.rs b/crates/gpu/tests/it/sam3_detr.rs new file mode 100644 index 0000000000..69e2355626 --- /dev/null +++ b/crates/gpu/tests/it/sam3_detr.rs @@ -0,0 +1,182 @@ +//! The text detector's DETR encoder on the GPU against the candle encoder (the reference), on one photo: the encoder +//! memory, and what the difference does to the detector's outputs (per-query logits, presence, boxes and the merged +//! Describe mask) for a few prompts. Both models get the same backbone output (one GPU backbone, shared), so only the +//! encoder differs. +//! +//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR= cargo test --release -p lightcraft-gpu --features sam +//! --test it sam3_detr:: -- --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, 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), and how many instances that is. +fn merged(out: &DetectorOutput) -> (Vec, usize) { + let masks = values(&out.masks); + 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); + } + } + (merged, keep.len()) +} + +/// 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() +} + +/// One GPU backbone for both models; the DETR encoder only for one of them (`asked` counts the calls). +struct Shared { + gpu: Arc, + detr: 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_detr_encoder(&self) -> bool { + true + } + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result, String> { + self.asked.fetch_add(1, Ordering::Relaxed); + if self.detr { self.gpu.detr_encoder(image, pos, text, valid) } else { Err("left to candle for the comparison".into()) } + } +} + +#[test] +fn the_gpu_detr_encoder_matches_the_candle_encoder() { + 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 = |detr: bool, asked: &Arc| { + let (gpu, asked) = (gpu.clone(), asked.clone()); + move |_: &WeightReader| -> Result, String> { Ok(Box::new(Shared { gpu, detr, 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(); + assert_eq!(values(enc_cpu.backbone()), values(enc_acc.backbone()), "the same backbone output for both"); + + 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 encoder {cpu_time:?}, with the GPU encoder {gpu_time:?}{first}"); + assert_eq!(acc.detr_fallback(), None, "the GPU encoder ran"); + assert!(cpu.detr_fallback().is_some_and(|w| w.contains("left to candle"))); + + let (_, rel, mean) = errors("memory", &values(&got.memory), &values(&want.memory)); + assert!(rel < 1e-3 && mean < 1e-4, "the GPU encoder memory is off"); + let (logits, _, _) = errors("query logits", &got.logits, &want.logits); + let presence = (got.presence - want.presence).abs(); + let boxes = got.boxes.iter().flatten().zip(want.boxes.iter().flatten()).fold(0f32, |m, (a, b)| m.max((a - b).abs())); + let ((mask_g, kept_g), (mask_c, kept_c)) = (merged(&got), merged(&want)); + let i = iou(&mask_g, &mask_c); + eprintln!( + " presence {:.4} vs {:.4} (logit diff {presence:.2e}), boxes max diff {boxes:.2e}, instances {kept_g} vs {kept_c}, mask IoU {i:.5}", + sigmoid(got.presence), + sigmoid(want.presence) + ); + // every query's mask, not only the merged ones: the largest |Δ| of the logits and of the masks (sigmoid, 0..1) + let (dl, dm) = values(&got.masks) + .iter() + .zip(&values(&want.masks)) + .fold((0f32, 0f32), |(l, m), (a, b)| (l.max((a - b).abs()), m.max((sigmoid(*a) - sigmoid(*b)).abs()))); + eprintln!(" masks of all {} queries: max |Δ| logits {dl:.2e}, mask {dm:.2e}", got.logits.len()); + assert!(logits < 0.05 && presence < 0.05 && boxes < 1e-2, "the detector outputs moved"); + assert_eq!(kept_g, kept_c, "the same instances"); + assert!(i > 0.99, "describe mask IoU {i}"); + } + // an accelerator that failed on the encoder once isn't asked again + assert_eq!(asked_cpu.load(Ordering::Relaxed), 1); + assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len()); + + // the encoder alone (with the uploads and the read-back) + let (image, pos, text) = (vec![0.1f32; 5184 * 256], vec![0.2f32; 5184 * 256], vec![0.3f32; 32 * 256]); + let valid: Vec = (0..32).map(|i| i < 4).collect(); + let mut best = f64::MAX; + for _ in 0..5 { + let t = Instant::now(); + gpu.detr_encoder(&image, &pos, &text, &valid).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + } + let (w, b) = gpu.detr_bytes().unwrap(); + eprintln!("GPU DETR encoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6); +}