From 48a002e73af31fe837a21358ce3290e36e0fda37 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:38 +0200 Subject: [PATCH 1/3] M12: SAM 3 accelerator plumbing: backend choice, CPU fallback and the AI masks setting Part 1 of 5 of #2167. lightcraft-segment gets a BackboneAccel trait (backbone, plus optional necks, DETR encoder and mask decoder, asked only when runs_heads()), WeightReader and Sam3::load_accelerated. Whatever an accelerator returns is checked (length, finite values); an error, a wrong size or a NaN falls back to candle, logged once, with the reason kept for the status. The engine worker places the model (Metal on macOS, the CPU elsewhere, or the CPU when chosen or switched off), reloads it when a GPU switch or the setting changes, and reports where it ran in segment.model.status. Settings > Performance > AI masks gets Run on: Automatic / CPU. #2067's retry is kept: a job that fails on candle's GPU (Metal) runs once more on the CPU, which then serves the session (now a placement with the reason); LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off keep the model on the CPU on macOS too. #1963's semantic mask comes from the mask decoder as before (on an accelerator: one more row of its mask product). This build has no GPU backbone (GPU_BACKBONE is None), so the GPU path is off: outside macOS candle runs everything on the CPU, as on main. Also on the CPU: the text features of the last 16 prompts are cached per model, and the detector's box relative-position bias is one pass, with the decoder MLPs' bias and ReLU fused (bit-identical outputs). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/engine/src/cmd/masks.rs | 20 +- crates/engine/src/config.rs | 7 +- crates/engine/src/segment/mod.rs | 99 ++- crates/engine/src/segment/worker.rs | 685 ++++++++++++++++---- crates/engine/src/tests_segment.rs | 45 ++ crates/gpu/src/lib.rs | 7 +- crates/segment/Cargo.toml | 2 + crates/segment/examples/sam3_bench.rs | 56 +- crates/segment/src/cpu.rs | 147 +++++ crates/segment/src/detector.rs | 293 ++++++++- crates/segment/src/lib.rs | 633 ++++++++++++++++-- crates/segment/src/nn.rs | 48 +- crates/segment/tests/it/accel.rs | 58 ++ crates/segment/tests/it/main.rs | 2 + crates/segment/tests/it/prompts.rs | 63 ++ crates/ui-egui/locales/cs-formats.json | 3 +- crates/ui-egui/locales/cs.json | 10 +- crates/ui-egui/locales/de-formats.json | 3 +- crates/ui-egui/locales/de.json | 10 +- crates/ui-egui/locales/es-formats.json | 3 +- crates/ui-egui/locales/es.json | 10 +- crates/ui-egui/locales/fi-formats.json | 3 +- crates/ui-egui/locales/fi.json | 10 +- crates/ui-egui/locales/fr-formats.json | 3 +- crates/ui-egui/locales/fr.json | 10 +- crates/ui-egui/locales/id-formats.json | 3 +- crates/ui-egui/locales/id.json | 10 +- crates/ui-egui/locales/it-formats.json | 3 +- crates/ui-egui/locales/it.json | 11 +- crates/ui-egui/locales/ja-formats.json | 3 +- crates/ui-egui/locales/ja.json | 10 +- crates/ui-egui/locales/ka-formats.json | 3 +- crates/ui-egui/locales/ka.json | 10 + crates/ui-egui/locales/pl-formats.json | 3 +- crates/ui-egui/locales/pl.json | 12 +- crates/ui-egui/locales/pt-br-formats.json | 3 +- crates/ui-egui/locales/pt-br.json | 10 +- crates/ui-egui/locales/ru-formats.json | 3 +- crates/ui-egui/locales/ru.json | 10 +- crates/ui-egui/locales/sv-formats.json | 3 +- crates/ui-egui/locales/sv.json | 10 +- crates/ui-egui/locales/uk-formats.json | 3 +- crates/ui-egui/locales/uk.json | 10 +- crates/ui-egui/locales/vi-formats.json | 3 +- crates/ui-egui/locales/vi.json | 10 +- crates/ui-egui/locales/zh-hans-formats.json | 3 +- crates/ui-egui/locales/zh-hans.json | 10 +- crates/ui-egui/locales/zh-hant-formats.json | 3 +- crates/ui-egui/locales/zh-hant.json | 10 +- crates/ui-egui/src/panels/settings.rs | 57 +- crates/ui-egui/src/tests_dialog_fit.rs | 37 ++ 52 files changed, 2219 insertions(+), 265 deletions(-) create mode 100644 crates/segment/src/cpu.rs create mode 100644 crates/segment/tests/it/accel.rs create mode 100644 crates/segment/tests/it/prompts.rs diff --git a/Cargo.lock b/Cargo.lock index 8b3985fc09..8c29f11536 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3485,6 +3485,7 @@ dependencies = [ "lightcraft-fetch", "lightcraft-testkit", "log", + "rayon", "serde", "serde_json", "thiserror 2.0.21", diff --git a/crates/engine/src/cmd/masks.rs b/crates/engine/src/cmd/masks.rs index dc403df9b1..9c7c8bca8f 100644 --- a/crates/engine/src/cmd/masks.rs +++ b/crates/engine/src/cmd/masks.rs @@ -533,7 +533,7 @@ pub fn specs() -> Vec { "AI Mask Model Status", [], None, - "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, and the download's progress → {available, installed, dir, loaded, busy, analyzing, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", + "{} — whether this build has AI masks, whether the SAM 3 model is installed (and where), loaded, busy, where it runs and how long the last photo took, and the download's progress → {available, installed, dir, loaded, busy, analyzing, runOn (auto | cpu: segment.settings), backend: {device (what runs the backbone: a GPU's name, Metal GPU or CPU; null until loaded), runtime (wgpu|candle), heads (CPU|Metal GPU, and which of the parts after the backbone the GPU accelerator runs, e.g. `CPU; the necks on the GPU`), fallback (why the backbone is not on the GPU), encodeMs (last backbone run), analyzeMs (last photo's analysis before the first click)}, sizeBytes, license, licenseUrl, mirrors, download: {running, done, total, file, error, finished}}", super::always, |s, _| { let g = &s.segmenter; @@ -545,6 +545,8 @@ pub fn specs() -> Vec { "loaded": g.loaded(), "busy": g.busy(), "analyzing": g.analyzing(), + "runOn": g.run_on().name(), + "backend": g.backend(), "sizeBytes": crate::segment::MODEL_BYTES, "license": crate::segment::LICENSE_NAME, "licenseUrl": crate::segment::LICENSE_URL, @@ -553,6 +555,22 @@ pub fn specs() -> Vec { })) } ), + cmd!( + query "segment.settings", + "AI Mask Settings", + [], + None, + "{runOn?: auto | cpu} → {runOn} — where SAM 3 runs (Settings ▸ Performance ▸ AI masks): `auto` (the default) the GPU when there is one (Metal on macOS; elsewhere candle on the CPU: this build has no wgpu kernels for SAM 3 yet), `cpu` all of it on the CPU on every platform (for a GPU that can't run it). Local inference only: a remote worker (`LIGHTCRAFT_SAM3_REMOTE`) runs on its Mac's Metal device either way. Kept with the app's settings; a loaded model moves at its next request", + super::always, + |s, p| { + let c = "segment.settings"; + if let Some(v) = p.get("runOn") { + let run_on = v.as_str().and_then(crate::segment::RunOn::parse).ok_or_else(|| bad(c, "`runOn` must be auto or cpu"))?; + s.segmenter.set_run_on(run_on).map_err(ai_err)?; + } + Ok(json!({"runOn": s.segmenter.run_on().name()})) + } + ), cmd!( query "segment.model.download", "Download AI Mask Model", diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index b3ded1fbd7..839836b274 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -132,11 +132,14 @@ fn sam3_dir(var: Option, config: Option) -> Option< } impl Session { - /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), and for the user's - /// download mirrors in `/models/sam3-mirrors.txt`. + /// Look for the SAM 3 model in the shared default folder ([`default_sam3_dir`]), for the user's + /// download mirrors in `/models/sam3-mirrors.txt` and for where it runs in + /// `/models/sam3-settings.json`. pub fn with_default_sam3_model(mut self) -> Self { self.segmenter.dir = default_sam3_dir(); self.segmenter.mirrors_file = config_dir().map(|d| d.join("models").join("sam3-mirrors.txt")); + self.segmenter.settings_file = config_dir().map(|d| d.join("models").join("sam3-settings.json")); + self.segmenter.load_settings(); self } diff --git a/crates/engine/src/segment/mod.rs b/crates/engine/src/segment/mod.rs index b69a6dca27..b4302d77f7 100644 --- a/crates/engine/src/segment/mod.rs +++ b/crates/engine/src/segment/mod.rs @@ -117,12 +117,57 @@ pub struct DownloadStatus { pub finished: bool, } +/// Where SAM 3 runs (Settings ▸ Performance ▸ AI masks; `segment.settings {runOn}`, kept in +/// [`Segmenter::settings_file`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum RunOn { + /// The GPU when there is one: Metal on macOS, elsewhere the image encoder through wgpu unless + /// the GPU is switched off ("Use the GPU for rendering", `LIGHTCRAFT_GPU=0`, …). + #[default] + Auto, + /// The CPU for all of it, on every platform (on macOS candle's CPU device instead of Metal). + Cpu, +} + +impl RunOn { + pub fn parse(name: &str) -> Option { + match name { + "auto" => Some(RunOn::Auto), + "cpu" => Some(RunOn::Cpu), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + RunOn::Auto => "auto", + RunOn::Cpu => "cpu", + } + } +} + +/// Why the model runs on the CPU when [`RunOn::Cpu`] is chosen (`segment.model.status` → +/// `backend.fallback`). +pub const CPU_CHOSEN: &str = "the CPU is chosen in Settings (AI masks)"; + +/// The settings file's contents (`sam3-settings.json`). +#[derive(Default, serde::Serialize, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct Settings { + /// `auto` or `cpu` (`None` or anything else: `auto`). + run_on: Option, +} + /// The model (on its worker thread), the download, and AI mask requests in flight. pub struct Segmenter { /// Where the `facebook/sam3` files live (set by the app; `None`: no AI masks). pub dir: Option, /// The user's list of download mirrors (one base URL per line), if any. pub mirrors_file: Option, + /// Where [`Segmenter::run_on`] is kept (`/models/sam3-settings.json` in the app; `None`: + /// only for this session). + pub settings_file: Option, + run_on: RunOn, /// Run requests in the background and apply them in [`Session::segment_poll`] (the /// desktop app); otherwise commands wait for their result (CLI, MCP, tests). pub background: bool, @@ -143,6 +188,8 @@ impl Default for Segmenter { Segmenter { dir: None, mirrors_file: None, + settings_file: None, + run_on: RunOn::Auto, background: false, pending: None, messages: Vec::new(), @@ -160,6 +207,33 @@ impl Segmenter { /// Whether this build can compute AI masks at all. pub const AVAILABLE: bool = cfg!(feature = "sam"); + /// Where SAM 3 runs: the user's choice. + pub fn run_on(&self) -> RunOn { + self.run_on + } + + /// Read the choice of where SAM 3 runs from [`Segmenter::settings_file`] (a missing or damaged + /// file is [`RunOn::Auto`]). + pub fn load_settings(&mut self) { + let read = self.settings_file.as_deref().and_then(|f| crate::denoise::read_capped(f, 4096)); + let st: Settings = read.and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + self.run_on = st.run_on.as_deref().and_then(RunOn::parse).unwrap_or_default(); + } + + /// Choose where SAM 3 runs, and keep the choice in [`Segmenter::settings_file`]. A loaded model + /// moves at its next request (it loads again). + pub fn set_run_on(&mut self, run_on: RunOn) -> Result<(), String> { + if let Some(f) = &self.settings_file { + if let Some(parent) = f.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("could not create {}: {e}", parent.display()))?; + } + let st = Settings { run_on: Some(run_on.name().to_string()) }; + crate::denoise::write_atomic(f, &serde_json::to_vec_pretty(&st).map_err(|e| e.to_string())?)?; + } + self.run_on = run_on; + Ok(()) + } + pub fn remote_endpoint(&self) -> Option { #[cfg(feature = "sam")] return lightcraft_segment::remote::configured(); @@ -192,6 +266,28 @@ impl Segmenter { false } + /// Where the model runs and how long the last photo took (`segment.model.status` → `backend`): + /// `{device, runtime, heads, fallback, encodeMs, analyzeMs}` (see `worker::Backend`; `device` + /// is `null` until the model first loads, and `fallback` then says whether the GPU is switched + /// off), or `null` in a build without AI masks. + pub fn backend(&self) -> serde_json::Value { + #[cfg(feature = "sam")] + { + let mut b = self.worker.backend(); + if b.device.is_none() { + b.fallback = match self.run_on { + RunOn::Cpu => Some(CPU_CHOSEN.into()), + // macOS: Metal, unless the environment switches the GPU off (the preference is wgpu's) + RunOn::Auto if cfg!(target_os = "macos") => lightcraft_gpu::env_off_reason().map(Into::into), + RunOn::Auto => lightcraft_gpu::switched_off(), + }; + } + serde_json::to_value(b).unwrap_or_default() + } + #[cfg(not(feature = "sam"))] + serde_json::Value::Null + } + /// Whether a zoomed-in detail pass is queued or running. pub fn detail_busy(&self) -> bool { #[cfg(feature = "sam")] @@ -431,7 +527,8 @@ impl Session { job } }; - Ok(worker::Job { dir, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) + let cpu = self.segmenter.run_on == RunOn::Cpu; + Ok(worker::Job { dir, cpu, key: if region.is_some() { 0 } else { key }, render: Some(render), missing, kind, tag, reply }) } /// Send a request and wait for its result (CLI, MCP, tests; or when not in background mode). diff --git a/crates/engine/src/segment/worker.rs b/crates/engine/src/segment/worker.rs index efbb1c21c4..6bae968924 100644 --- a/crates/engine/src/segment/worker.rs +++ b/crates/engine/src/segment/worker.rs @@ -8,24 +8,33 @@ //! counters are decremented by drop guards, so they can't stay stuck. The model is unloaded //! after [`IDLE_UNLOAD`] without requests (it holds several GB). //! -//! Where the model can run on the GPU (Metal on macOS), a job that fails there (a panic or an -//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the -//! model and runs once more on the CPU. When that works, the model stays on the CPU for the rest -//! of the session and the job's outcome says so; when it fails too, the GPU wasn't the cause and -//! the next job uses it again. `LIGHTCRAFT_GPU=0` or `LIGHTCRAFT_GPU_BACKEND=off` keep the model on -//! the CPU from the start. +//! Where the model runs ([`Placement`]): on macOS candle runs all of it on the GPU through Metal. +//! Elsewhere candle runs on the CPU, and the backbone (most of the work) can run on the GPU through an +//! accelerator ([`GPU_BACKBONE`]: none in this build yet, so it runs in candle as before), unless the GPU is switched off (`LIGHTCRAFT_GPU=0`, +//! `LIGHTCRAFT_GPU_BACKEND=off`, or Settings ▸ Performance ▸ Use the GPU for rendering, as for AI +//! Denoise and faces); a GPU that can't be used or fails on a photo leaves the backbone to the CPU. +//! Settings ▸ Performance ▸ AI masks ▸ CPU ([`Job::cpu`]) puts all of it on the CPU, on every +//! platform, and so do `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` (macOS included, as +//! for AI Denoise and the face models). +//! +//! Where candle runs the model on the GPU (Metal on macOS), a job that fails there (a panic or an +//! error from candle, e.g. a kernel the GPU's compiler can't build, issue #1974) frees the model +//! and runs once more on the CPU. When that works, the model stays on the CPU for the rest of the +//! session and the job's outcome says so; when it fails too, the GPU wasn't the cause and the next +//! job uses it again. (The wgpu backbone elsewhere falls back to candle by itself, part by part.) +//! [`Backend`] tells the session where it ran and how long the last photo took. use std::collections::VecDeque; use std::panic::AssertUnwindSafe; -use std::path::PathBuf; -use std::sync::Arc; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use lightcraft_develop::SegMask; use lightcraft_segment::{ - Encoded, Sam3, + BackboneAccel, Device, Encoded, Sam3, WeightReader, remote::{self, Operation, Request, text_logits}, }; @@ -62,6 +71,8 @@ pub enum Kind { pub struct Job { /// The model folder. pub dir: PathBuf, + /// The user chose the CPU for SAM 3 (Settings ▸ Performance ▸ AI masks). + pub cpu: bool, /// Which photo and look the request is about (the encode cache's key). pub key: u64, /// Renders the model input when the cache doesn't hold `key` (always for a detail pass). @@ -87,29 +98,6 @@ pub struct Outcome { pub const GPU_FAILED: &str = "The GPU couldn't run the AI mask model, so it runs on the CPU until LightCraft restarts (slower). Details are in the log."; -/// Where the model is loaded. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Placement { - /// On the GPU when there is one (Metal on macOS); a job that fails there is retried on the CPU. - Gpu, - /// On the CPU: this build has no GPU path, the environment switches the GPU off, or the model - /// failed on it. - Cpu, -} - -impl Placement { - fn initial() -> Self { - if !lightcraft_segment::GPU_BUILD { - return Placement::Cpu; - } - if let Some(why) = lightcraft_gpu::env_off_reason() { - log::info!("SAM 3 runs on the CPU ({why})"); - return Placement::Cpu; - } - Placement::Gpu - } -} - /// Why a job failed. #[derive(Debug)] enum Failure { @@ -156,6 +144,154 @@ pub struct Shared { pub loaded: AtomicBool, /// Loading the model or encoding a photo right now (the slow parts). pub encoding: AtomicBool, + /// Where the model runs and how long the last photo took. + pub backend: Mutex, +} + +/// Where the model runs, and how long the last photo took (`segment.model.status` → `backend`, +/// Settings ▸ Performance ▸ AI masks). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Backend { + /// What the backbone (the 32-layer ViT, most of the work) runs on: a GPU's name ("NVIDIA + /// GeForce RTX 5070 (Vulkan)"), "Metal GPU" or "CPU". `None` until the model first loads. + pub device: Option, + /// What runs the backbone: "wgpu" (LightCraft's GPU kernels) or "candle". + pub runtime: Option, + /// What runs the rest (the necks and the click and text heads): "CPU" or "Metal GPU", with the parts the GPU + /// accelerator runs ("CPU; the necks on the GPU"). + pub heads: Option, + /// Why the backbone runs on the CPU where it could use the GPU: the GPU is switched off, there + /// is no usable one, or it failed on a photo. + pub fallback: Option, + /// The last photo's backbone run, in milliseconds. + pub encode_ms: Option, + /// The last photo's whole analysis before the first click (backbone and click features), in + /// milliseconds. + pub analyze_ms: Option, +} + +/// Where the model runs on this machine. +#[derive(Clone, Debug, PartialEq)] +enum Placement { + /// All of it in candle on its best device (Metal on macOS). + Best, + /// The backbone on the GPU (wgpu), the rest in candle on the CPU. + GpuBackbone, + /// All of it in candle on the CPU: the CPU is chosen, or the GPU is switched off (why). + Cpu(String), +} + +/// Where the model runs, for candle's best device being the CPU (`best_is_cpu`), the GPU switched +/// off (`switched_off`: why) or not, and the CPU chosen in Settings (`cpu`) or not. The choice wins +/// on every platform; the GPU switches only govern the wgpu backbone (macOS keeps Metal). +fn placement(best_is_cpu: bool, switched_off: Option, cpu: bool) -> Placement { + match (cpu, best_is_cpu, switched_off) { + (true, _, _) => Placement::Cpu(super::CPU_CHOSEN.into()), + (false, false, _) => Placement::Best, + (false, true, None) => Placement::GpuBackbone, + (false, true, Some(why)) => Placement::Cpu(why), + } +} + +/// Where the model is to run now: [`placement`], unless candle's GPU failed on it this session (`failed`: why; +/// the CPU until LightCraft restarts) or the environment switches the GPU off (`LIGHTCRAFT_GPU=0`, +/// `LIGHTCRAFT_GPU_BACKEND=off`), which keeps it off Metal too. +fn wanted(best_is_cpu: bool, cpu: bool, failed: Option<&str>) -> Placement { + if cpu { + return placement(best_is_cpu, None, true); + } + if let Some(why) = failed { + return Placement::Cpu(why.into()); + } + if let Some(why) = lightcraft_gpu::env_off_reason() { + return Placement::Cpu(why.into()); + } + match placement(best_is_cpu, lightcraft_gpu::switched_off(), false) { + // without a GPU backbone in this build, candle's best device runs it all + Placement::GpuBackbone if GPU_BACKBONE.is_none() => Placement::Best, + p => p, + } +} + +/// Whether a model loaded for `loaded` runs somewhere else than `wanted` (it must load again), candle's best device +/// being the CPU or not (`best_is_cpu`). Two reasons for the CPU are the same place, and so is candle's best device +/// when that is the CPU. +fn moves(loaded: &Placement, wanted: &Placement, best_is_cpu: bool) -> bool { + #[derive(PartialEq)] + enum Runs { + Cpu, + Metal, + Wgpu, + } + let runs = |p: &Placement| match p { + Placement::Best if best_is_cpu => Runs::Cpu, + Placement::Best => Runs::Metal, + Placement::GpuBackbone => Runs::Wgpu, + Placement::Cpu(_) => Runs::Cpu, + }; + runs(loaded) != runs(wanted) +} + +/// Builds the GPU backbone from the checkpoint (tests use fakes). +type MakeAccel = fn(&WeightReader) -> Result, String>; + +/// The GPU backbone of this build: none yet (its wgpu kernels come separately), so where candle has no GPU the +/// model runs in candle on the CPU, as before. +const GPU_BACKBONE: Option = None; + +fn no_accelerator(_: &WeightReader) -> Result, String> { + Err("this build has no GPU backbone".into()) +} + +/// Load the model in `dir` as `placement` says, on `best` (candle's best device). +fn load(dir: &Path, best: Device, placement: &Placement, make: MakeAccel) -> lightcraft_segment::Result { + match placement { + Placement::Best => Sam3::load_on(dir, best), + Placement::Cpu(_) => Sam3::load_on(dir, Device::Cpu), + Placement::GpuBackbone => Sam3::load_accelerated(dir, Device::Cpu, make), + } +} + +/// Note where the model `m`, just loaded for `placement`, runs. +fn note_loaded(shared: &Shared, m: &Sam3, placement: &Placement) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + *b = Backend { + device: Some(m.backbone_device()), + runtime: Some(if m.accelerated() { "wgpu" } else { "candle" }.into()), + heads: Some(m.heads_device()), + fallback: match placement { + Placement::Cpu(why) => Some(why.clone()), + _ => m.backbone_fallback(), + }, + encode_ms: None, + analyze_ms: None, + }; +} + +/// Note where the backbone ran a photo (it may have moved to the CPU on the way) and, when it +/// succeeded, how long it took (`encode`). +fn note_run(shared: &Shared, m: &Sam3, encode: Option) { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + b.device = Some(m.backbone_device()); + b.runtime = Some(if m.accelerated() { "wgpu" } else { "candle" }.into()); + b.heads = Some(m.heads_device()); + if let Some(why) = m.backbone_fallback() { + b.fallback = Some(why); + } + if let Some(d) = encode { + b.encode_ms = Some(millis(d)); + } +} + +/// Note where the backbone ran a detail pass (a zoomed-in region): not how long it took, since the last photo's +/// times are its whole analysis and the backbone run in it. +fn note_detail(shared: &Shared, m: &Sam3) { + note_run(shared, m, None); +} + +fn millis(d: Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// Decrements a counter when dropped (also when unwinding). @@ -218,6 +354,11 @@ impl Worker { !self.dead() && self.shared.loaded.load(Ordering::SeqCst) } + /// Where the model runs (ran, once unloaded) and how long the last photo took. + pub fn backend(&self) -> Backend { + self.shared.backend.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + /// Queue `job`; returns at once. pub fn submit(&mut self, job: Job) -> Result<(), String> { if self.dead() { @@ -237,7 +378,7 @@ impl Worker { // (re)start the thread let (tx, rx) = mpsc::channel(); let shared = self.shared.clone(); - match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, Placement::initial())) { + match std::thread::Builder::new().name("sam3".into()).spawn(move || run(&rx, &shared, IDLE_UNLOAD, lightcraft_segment::GPU_BUILD)) { Ok(t) => { self.thread = Some(t); self.tx = Some(tx.clone()); @@ -255,6 +396,8 @@ impl Worker { #[derive(Default)] struct State { model: Option<(PathBuf, Sam3)>, + /// Where the model was loaded to run, and whether candle's best device was the CPU then. + placement: Option<(Placement, bool)>, cache: Option<(u64, Encoded)>, remote: Option, } @@ -269,8 +412,12 @@ fn supersedes(later: &Job, job: &Job) -> bool { } } -fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: Placement) { +/// The worker's loop. `metal`: candle may run the model on a GPU here (macOS), so a job that fails is retried on +/// the CPU. +fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, metal: bool) { let mut state = State::default(); + // why the model runs on the CPU for the rest of the session: it failed on the GPU and works on the CPU + let mut gpu_failed: Option = None; let mut queue: VecDeque = VecDeque::new(); loop { if queue.is_empty() { @@ -300,24 +447,26 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: let _ = job.reply.send(Outcome { tag: job.tag, result: Ok(None), superseded: true, notice: None }); continue; } - // what a retry on the CPU needs (running the job takes them) - let retry = (placement == Placement::Gpu && remote::configured().is_none()).then(|| (job.kind.clone(), job.render.clone())); - let mut result = attempt(&mut state, shared, &mut job, placement); + // on candle's GPU: what a retry on the CPU needs (running the job takes them) + let on_gpu = metal && gpu_failed.is_none() && !job.cpu && lightcraft_gpu::env_off_reason().is_none() && remote::configured().is_none(); + let retry = on_gpu.then(|| (job.kind.clone(), job.render.clone())); + let mut result = attempt(&mut state, shared, &mut job, gpu_failed.as_deref()); let mut notice = None; - let gpu_failed = match &result { + let failed_why = match &result { Err(Failure::Model(why)) => Some(why.clone()), _ => None, }; - if let (Some(why), Some((kind, render))) = (gpu_failed, retry) { + if let (Some(why), Some((kind, render))) = (failed_why, retry) { // the GPU may be the cause (e.g. a kernel its compiler can't build, issue #1974): free // the model there and try once on the CPU log::warn!("SAM 3 failed on the GPU ({why}); trying the CPU"); state = State::default(); (job.kind, job.render) = (kind, render); - match attempt(&mut state, shared, &mut job, Placement::Cpu) { + let reason = format!("the GPU couldn't run it ({why}); the CPU until LightCraft restarts"); + match attempt(&mut state, shared, &mut job, Some(&reason)) { Ok(r) => { log::warn!("SAM 3 runs on the CPU from now on: it failed on the GPU and works on the CPU"); - placement = Placement::Cpu; + gpu_failed = Some(reason); notice = Some(GPU_FAILED.to_string()); result = Ok(r); } @@ -338,10 +487,10 @@ fn run(rx: &mpsc::Receiver, shared: &Shared, idle: Duration, mut placement: } } -/// Run `job` with the model on `placement`. A panic is a [`Failure::Model`] and drops what the -/// model kept. -fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { - match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, placement))) { +/// Run `job`, on the CPU when `failed` says the GPU failed this session. A panic is a [`Failure::Model`] and drops +/// what the model kept. +fn attempt(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { + match std::panic::catch_unwind(AssertUnwindSafe(|| run_job(state, shared, job, failed))) { Ok(r) => r, Err(p) => { let why = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); @@ -353,19 +502,38 @@ fn attempt(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme } } -/// The model for `dir`, loading it on `placement` when needed. -fn model<'a>(state: &'a mut State, shared: &Shared, dir: &std::path::Path, placement: Placement) -> Result<&'a mut Sam3, Failure> { - if state.model.as_ref().is_none_or(|(d, _)| d != dir) { +/// The model for `dir`, loading it when needed (and again when the GPU was switched on or off, or +/// the CPU chosen or not: `cpu`; `failed`: the GPU failed this session, see [`wanted`]). +fn model<'a>(state: &'a mut State, shared: &Shared, dir: &Path, cpu: bool, failed: Option<&str>) -> Result<&'a mut Sam3, Failure> { + let now = state.placement.as_ref().map(|(_, best_is_cpu)| wanted(*best_is_cpu, cpu, failed)); + let stale = state.placement.as_ref().zip(now.as_ref()).is_some_and(|((p, best_is_cpu), now)| moves(p, now, *best_is_cpu)); + if let (false, Some((p, _)), Some(now)) = (stale, state.placement.as_mut(), now) { + // the same device for another reason (the choice, a GPU switch): the model stays, the reason it shows changes + if *p != now { + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).fallback = match &now { + Placement::Cpu(why) => Some(why.clone()), + _ => None, + }; + *p = now; + } + } + if stale || state.model.as_ref().is_none_or(|(d, _)| d != dir) { state.model = None; + state.placement = None; state.cache = None; let _busy = Flag::raise(&shared.encoding); let t = web_time::Instant::now(); - let m = match placement { - Placement::Gpu => Sam3::load(dir)?, - Placement::Cpu => Sam3::load_cpu(dir)?, - }; - log::info!("SAM 3 loaded in {:?} ({})", t.elapsed(), if m.device().is_cpu() { "CPU" } else { "GPU" }); + // with the CPU chosen (or forced) candle's best device isn't asked for (on macOS that sets up Metal): + // it counts as Metal on macOS and the CPU elsewhere when the choice changes back + let skip = cpu || failed.is_some() || lightcraft_gpu::env_off_reason().is_some(); + let best = if skip { Device::Cpu } else { lightcraft_segment::best_device() }; + let best_is_cpu = if skip { !cfg!(target_os = "macos") } else { best.is_cpu() }; + let placement = wanted(best_is_cpu, cpu, failed); + let m = load(dir, best, &placement, GPU_BACKBONE.unwrap_or(no_accelerator))?; + log::info!("SAM 3 loaded in {:?}: the backbone on the {}, the rest on the {}", t.elapsed(), m.backbone_device(), m.heads_device()); + note_loaded(shared, &m, &placement); state.model = Some((dir.to_path_buf(), m)); + state.placement = Some((placement, best_is_cpu)); shared.loaded.store(true, Ordering::SeqCst); } state.model.as_mut().map(|(_, m)| m).ok_or_else(|| "the model did not load".into()) @@ -390,17 +558,33 @@ fn render(job: &mut Job) -> Result { } /// The model and the encoded photo `job.key` (rendering and encoding it when needed). -fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { - model(state, shared, &job.dir, placement)?; +fn encoded<'a>(state: &'a mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result<(&'a mut Sam3, &'a mut Encoded), Failure> { + model(state, shared, &job.dir, job.cpu, failed)?; if state.cache.as_ref().is_none_or(|(k, _)| *k != job.key) { state.cache = None; let input = render(job)?; let _busy = Flag::raise(&shared.encoding); let m = state.model.as_mut().map(|(_, m)| m).ok_or("the model did not load")?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + let encode = t.elapsed(); + note_run(shared, m, None); + let mut enc = enc?; m.prepare_clicks(&mut enc)?; - log::info!("SAM 3 encoded {}×{} in {:?}", input.w, input.h, t.elapsed()); + let analyze = t.elapsed(); + // both times together, once the whole analysis worked: never one photo's encoder with another's total + { + let mut b = shared.backend.lock().unwrap_or_else(PoisonError::into_inner); + (b.encode_ms, b.analyze_ms) = (Some(millis(encode)), Some(millis(analyze))); + } + log::info!( + "SAM 3 analyzed {}×{} in {analyze:?}: backbone {encode:?} on the {}, click features {:?} on the {}", + input.w, + input.h, + m.backbone_device(), + analyze.saturating_sub(encode), + m.heads_device() + ); state.cache = Some((job.key, enc)); } let State { model, cache, .. } = state; @@ -457,7 +641,7 @@ fn remote_job(state: &mut State, shared: &Shared, job: &mut Job, endpoint: &str) })) } -fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placement) -> Result, Failure> { +fn run_job(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result, Failure> { if let Some(endpoint) = remote::configured() { let result = remote_job(state, shared, job, &endpoint); if result.is_err() { @@ -468,33 +652,38 @@ fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme let side = lightcraft_segment::MASK_SIDE; match std::mem::replace(&mut job.kind, Kind::Prepare) { Kind::Prepare => { - encoded(state, shared, job, placement)?; + encoded(state, shared, job, failed)?; Ok(None) } Kind::Clicks(clicks) => { - let (m, enc) = encoded(state, shared, job, placement)?; + let (m, enc) = encoded(state, shared, job, failed)?; let p = m.segment_clicks(enc, &clicks)?; Ok(Some(SegMask::from_logits(side, &p.logits))) } Kind::Text(text) => { - let (m, enc) = encoded(state, shared, job, placement)?; - Ok(text_logits(m, enc, &text)?.map(|l| SegMask::from_logits(side, &l))) + let (m, enc) = encoded(state, shared, job, failed)?; + let logits = text_logits(m, enc, &text)?; + // the text heads may have moved to the CPU on the way (a failure on the GPU) + shared.backend.lock().unwrap_or_else(PoisonError::into_inner).heads = Some(m.heads_device()); + Ok(logits.map(|l| SegMask::from_logits(side, &l))) } #[cfg(test)] #[allow(clippy::panic)] Kind::Panic => panic!("a test panic"), #[cfg(test)] #[allow(clippy::panic)] - Kind::FailOnGpu { panic } => match placement { - Placement::Gpu if panic => panic!("a test panic on the GPU"), - Placement::Gpu => Err(Failure::Model("a test error on the GPU".into())), - Placement::Cpu => Ok(None), + Kind::FailOnGpu { panic } => match failed.is_some() || job.cpu { + false if panic => panic!("a test panic on the GPU"), + false => Err(Failure::Model("a test error on the GPU".into())), + true => Ok(None), }, Kind::Detail { prompt, region } => { let input = render(job)?; - let m = model(state, shared, &job.dir, placement)?; + let m = model(state, shared, &job.dir, job.cpu, failed)?; let t = web_time::Instant::now(); - let mut enc = m.encode(&input.rgb, input.w, input.h)?; + let enc = m.encode(&input.rgb, input.w, input.h); + note_detail(shared, m); + let mut enc = enc?; let (rw, rh) = (region[2] - region[0], region[3] - region[1]); if !(rw > 0.0 && rh > 0.0) { return Ok(None); @@ -527,7 +716,7 @@ mod tests { fn job(tag: Tag, reply: &mpsc::Sender) -> Job { // an empty folder: loading fails with an error (no model files) let dir = std::env::temp_dir().join(format!("lc-sam3-worker-none-{}", std::process::id())); - Job { dir, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } + Job { dir, cpu: false, key: 1, render: None, missing: None, kind: Kind::Prepare, tag, reply: reply.clone() } } #[test] @@ -560,7 +749,7 @@ mod tests { jtx.send(job(Tag::Wait, &tx)).unwrap(); shared.pending.store(2, Ordering::SeqCst); drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let first = rx.recv().unwrap(); assert!(first.result.unwrap_err().contains("failed unexpectedly")); let second = rx.recv().unwrap(); @@ -569,72 +758,6 @@ mod tests { assert!(!shared.encoding.load(Ordering::SeqCst)); } - /// Run `kinds` in turn on a worker that starts on `placement`; their outcomes. - fn run_kinds(placement: Placement, kinds: Vec) -> Vec { - let (tx, rx) = mpsc::channel(); - let (jtx, jrx) = mpsc::channel(); - let shared = Shared::default(); - shared.pending.store(kinds.len(), Ordering::SeqCst); - for kind in kinds { - let mut j = job(Tag::Wait, &tx); - j.kind = kind; - jtx.send(j).unwrap(); - } - drop(jtx); - run(&jrx, &shared, Duration::from_secs(60), placement); - assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); - assert!(!shared.encoding.load(Ordering::SeqCst)); - rx.try_iter().collect() - } - - #[test] - fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { - // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); - assert_eq!(out.len(), 2); - assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); - assert_eq!(out[1].notice, None, "said once"); - } - - #[test] - fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { - let out = run_kinds(Placement::Gpu, vec![Kind::FailOnGpu { panic: false }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); - assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly")); - assert_eq!(out[0].notice, None); - // not the GPU's fault: the next job tries the GPU first again - assert!(matches!(out[1].result, Ok(None))); - assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); - } - - #[test] - fn a_worker_on_the_cpu_never_tries_the_gpu() { - // no GPU in this build, or LIGHTCRAFT_GPU=0 / LIGHTCRAFT_GPU_BACKEND=off - let out = run_kinds(Placement::Cpu, vec![Kind::FailOnGpu { panic: true }]); - assert!(matches!(out[0].result, Ok(None))); - assert_eq!(out[0].notice, None); - if !lightcraft_segment::GPU_BUILD { - assert_eq!(Placement::initial(), Placement::Cpu); - } - } - - #[test] - fn missing_model_files_are_not_retried_on_the_cpu() { - let out = run_kinds(Placement::Gpu, vec![Kind::Prepare]); - assert!(out[0].result.as_ref().unwrap_err().contains("not found")); - assert_eq!(out[0].notice, None); - let missing = lightcraft_segment::Error::Missing(PathBuf::from("models")); - assert!(matches!(Failure::from(missing), Failure::Other(_))); - } - #[test] fn a_newer_request_for_the_same_selection_supersedes_a_queued_one() { let (tx, rx) = mpsc::channel(); @@ -652,10 +775,298 @@ mod tests { drop(jtx); let shared = Shared::default(); shared.pending.store(3, Ordering::SeqCst); - run(&jrx, &shared, Duration::from_secs(60), Placement::Cpu); + run(&jrx, &shared, Duration::from_secs(60), false); let out: Vec = rx.try_iter().collect(); assert_eq!(out.len(), 3); assert!(out[0].superseded && out[1].superseded && !out[2].superseded); assert_eq!(shared.pending.load(Ordering::SeqCst), 0); } + + /// A model folder whose checkpoint holds no tensors: it loads with an accelerator, never in candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-worker-{name}-{}", 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(lightcraft_segment::WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// A GPU backbone that answers with zeros, or fails on every photo. + struct FakeGpu(bool); + + impl BackboneAccel for FakeGpu { + fn forward(&self, _: &[f32]) -> Result, String> { + if self.0 { Err("device lost".into()) } else { Ok(vec![0.0; 1024 * 72 * 72]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + fn fake_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(false))) + } + + fn failing_gpu(_: &WeightReader) -> Result, String> { + Ok(Box::new(FakeGpu(true))) + } + + fn no_gpu(_: &WeightReader) -> Result, String> { + Err("no GPU adapter".into()) + } + + #[allow(clippy::panic)] + fn never(_: &WeightReader) -> Result, String> { + panic!("the GPU backbone was built") + } + + #[allow(clippy::unwrap_used)] + fn backend(shared: &Shared) -> Backend { + shared.backend.lock().unwrap().clone() + } + + #[test] + fn the_backbone_goes_to_the_gpu_only_where_candle_has_none_and_the_gpu_is_on() { + // macOS: candle runs everything on Metal, as before (the GPU switches are wgpu's) + assert_eq!(placement(false, None, false), Placement::Best); + assert_eq!(placement(false, Some("disabled by LIGHTCRAFT_GPU=0".into()), false), Placement::Best); + // elsewhere: the backbone on the GPU unless it is switched off + assert_eq!(placement(true, None, false), Placement::GpuBackbone); + let off = "disabled by the GPU rendering preference (app.gpu)"; + assert_eq!(placement(true, Some(off.into()), false), Placement::Cpu(off.into())); + } + + #[test] + fn the_cpu_chosen_in_settings_wins_on_every_platform() { + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // macOS (Metal) and elsewhere, the GPU on or off + for best_is_cpu in [false, true] { + for off in [None, Some("disabled by LIGHTCRAFT_GPU=0".to_string())] { + assert_eq!(placement(best_is_cpu, off.clone(), true), chosen, "{best_is_cpu} {off:?}"); + } + } + assert_eq!(super::super::CPU_CHOSEN, "the CPU is chosen in Settings (AI masks)"); + } + + #[test] + fn switching_the_gpu_or_the_choice_reloads_only_a_model_it_moves() { + let cpu = |why: &str| Placement::Cpu(why.into()); + let chosen = || placement(true, None, true); + // the GPU switch: Metal stays; the wgpu backbone goes to the CPU and back + assert!(!moves(&Placement::Best, &placement(false, Some("off".into()), false), false)); + assert!(moves(&Placement::GpuBackbone, &placement(true, Some("off".into()), false), true)); + assert!(moves(&cpu("off"), &placement(true, None, false), true)); + // without a GPU backbone candle's best device is the CPU: the GPU switch moves nothing + assert!(!moves(&Placement::Best, &cpu("off"), true)); + assert!(!moves(&cpu("off"), &Placement::Best, true)); + // the choice: Metal (macOS) or the GPU backbone to the CPU and back + assert!(moves(&Placement::Best, &placement(false, None, true), false)); + assert!(moves(&placement(false, None, true), &placement(false, None, false), false)); + assert!(moves(&Placement::GpuBackbone, &chosen(), true)); + // the CPU for one reason or the other: it stays loaded + assert!(!moves(&cpu("disabled by LIGHTCRAFT_GPU=0"), &chosen(), true)); + assert!(!moves(&chosen(), &cpu("disabled by LIGHTCRAFT_GPU=0"), false)); + assert!(!moves(&Placement::GpuBackbone, &placement(true, None, false), true)); + } + + #[test] + fn with_the_cpu_chosen_the_gpu_backbone_is_never_built() { + let dir = empty_model("chosen"); + // candle loads on the CPU (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &placement(true, None, true), never).is_err()); + assert!(load(&dir, Device::Cpu, &placement(false, None, true), never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_gpu_backbone_loads_and_reports_where_it_runs() { + let dir = empty_model("gpu"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, fake_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + let b = backend(&shared); + assert_eq!( + (b.device.as_deref(), b.runtime.as_deref(), b.heads.as_deref(), b.fallback.as_deref()), + (Some("Fake GPU (Vulkan)"), Some("wgpu"), Some("CPU"), None) + ); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(812))); + assert_eq!(backend(&shared).encode_ms, Some(812)); + let json = serde_json::to_value(backend(&shared)).unwrap(); + assert_eq!(json["device"], "Fake GPU (Vulkan)"); + assert_eq!(json["encodeMs"], 812); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn with_the_gpu_switched_off_the_gpu_backbone_is_never_built() { + let dir = empty_model("off"); + let off = Placement::Cpu("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()); + // candle loads (and fails: the checkpoint is empty), without touching the GPU + assert!(load(&dir, Device::Cpu, &off, never).is_err()); + assert!(load(&dir, Device::Cpu, &Placement::Best, never).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_gpu_that_cannot_be_used_leaves_the_backbone_to_the_cpu() { + let dir = empty_model("nogpu"); + // without an adapter candle loads the backbone (failing here only for the empty checkpoint) + let e = load(&dir, Device::Cpu, &Placement::GpuBackbone, no_gpu).err().unwrap(); + assert!(!e.to_string().contains("no GPU adapter"), "{e}"); + // a GPU that fails on a photo: the CPU takes over, and the status says why + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + assert_eq!(backend(&shared).runtime.as_deref(), Some("wgpu")); + let enc = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_run(&shared, &m, enc.is_ok().then_some(Duration::from_millis(1))); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_environment_switches_and_a_failed_gpu_keep_the_model_on_the_cpu_also_on_macos() { + // candle's GPU failed this session: the CPU, with the reason, wherever candle has a GPU or not + for best_is_cpu in [false, true] { + assert_eq!(wanted(best_is_cpu, false, Some("the GPU couldn't run it")), Placement::Cpu("the GPU couldn't run it".into())); + } + // the CPU chosen in Settings still says so + assert_eq!(wanted(false, true, Some("x")), Placement::Cpu(super::super::CPU_CHOSEN.into())); + // otherwise as `placement`, with the environment switches deciding for Metal too + let want = match lightcraft_gpu::env_off_reason() { + Some(why) => Placement::Cpu(why.into()), + None => Placement::Best, + }; + assert_eq!(wanted(false, false, None), want); + } + + /// Run `kinds` in turn on a worker where candle has a GPU (`metal`) or not, the CPU chosen or not; their outcomes. + fn run_kinds(metal: bool, cpu: bool, kinds: Vec) -> Vec { + let (tx, rx) = mpsc::channel(); + let (jtx, jrx) = mpsc::channel(); + let shared = Shared::default(); + shared.pending.store(kinds.len(), Ordering::SeqCst); + for kind in kinds { + let mut j = job(Tag::Wait, &tx); + j.kind = kind; + j.cpu = cpu; + jtx.send(j).unwrap(); + } + drop(jtx); + run(&jrx, &shared, Duration::from_secs(60), metal); + assert_eq!(shared.pending.load(Ordering::SeqCst), 0, "counters reset"); + assert!(!shared.encoding.load(Ordering::SeqCst)); + rx.try_iter().collect() + } + + /// The tests of the CPU fallback assume the GPU isn't switched off in the environment (it never is tried then). + fn gpu_allowed() -> bool { + let ok = lightcraft_gpu::env_off_reason().is_none(); + if !ok { + lightcraft_testkit::skip!(Gpu, "the GPU is switched off in the environment"); + } + ok + } + + #[test] + fn a_job_that_panics_on_the_gpu_runs_on_the_cpu_and_so_do_the_next_ones() { + if !gpu_allowed() { + return; + } + // issue #1974: candle panics compiling a Metal kernel the GPU's compiler can't build + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: true }, Kind::FailOnGpu { panic: true }]); + assert_eq!(out.len(), 2); + assert!(matches!(out[0].result, Ok(None)), "retried on the CPU: {:?}", out[0].result.as_ref().err()); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + assert!(matches!(out[1].result, Ok(None)), "the next job starts on the CPU"); + assert_eq!(out[1].notice, None, "said once"); + } + + #[test] + fn a_model_error_on_the_gpu_is_retried_on_the_cpu_too() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn a_job_that_fails_on_the_cpu_too_keeps_the_gpu() { + if !gpu_allowed() { + return; + } + let out = run_kinds(true, false, vec![Kind::Panic, Kind::FailOnGpu { panic: true }]); + assert!(out[0].result.as_ref().unwrap_err().contains("failed unexpectedly"), "reported as before"); + assert_eq!(out[0].notice, None); + // the next job still starts on the GPU, fails there and works on the CPU + assert!(matches!(out[1].result, Ok(None))); + assert_eq!(out[1].notice.as_deref(), Some(GPU_FAILED)); + } + + #[test] + fn missing_model_files_are_not_retried_on_the_cpu() { + let out = run_kinds(true, false, vec![Kind::Prepare]); + assert!(out[0].result.as_ref().unwrap_err().contains("not found")); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_worker_on_the_cpu_never_tries_the_gpu() { + // the CPU chosen in Settings, and a build where candle has no GPU + for (metal, cpu) in [(true, true), (false, true)] { + let out = run_kinds(metal, cpu, vec![Kind::FailOnGpu { panic: true }]); + assert!(matches!(out[0].result, Ok(None))); + assert_eq!(out[0].notice, None); + } + // no GPU path (not macOS): a failure is reported, not retried + let out = run_kinds(false, false, vec![Kind::FailOnGpu { panic: false }]); + assert!(out[0].result.is_err()); + assert_eq!(out[0].notice, None); + } + + #[test] + fn a_cpu_model_kept_for_another_reason_shows_that_reason() { + let dir = empty_model("reason"); + let shared = Shared::default(); + let mut state = State::default(); + let chosen = Placement::Cpu(super::super::CPU_CHOSEN.into()); + // loaded with the CPU chosen (put there by hand: the empty checkpoint doesn't load) + state.placement = Some((chosen.clone(), true)); + shared.backend.lock().unwrap().fallback = Some(super::super::CPU_CHOSEN.into()); + // the choice goes back to Automatic while the CPU stays for another reason: the new reason shows (the reload + // that follows here is only because no model was in memory) + let why = "the GPU couldn't run it"; + let _ = model(&mut state, &shared, &dir, false, Some(why)); + assert_eq!(backend(&shared).fallback.as_deref(), Some(why)); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_detail_pass_leaves_the_last_photos_times_alone() { + let dir = empty_model("detail"); + let m = load(&dir, Device::Cpu, &Placement::GpuBackbone, failing_gpu).unwrap(); + let shared = Shared::default(); + note_loaded(&shared, &m, &Placement::GpuBackbone); + { + let mut b = shared.backend.lock().unwrap(); + (b.encode_ms, b.analyze_ms) = (Some(812), Some(900)); + } + // the zoomed-in region: the GPU fails on it, and the status says where the backbone runs now + let _ = m.encode(&[0; 8 * 8 * 3], 8, 8); + note_detail(&shared, &m); + let b = backend(&shared); + assert_eq!((b.device.as_deref(), b.runtime.as_deref()), (Some("CPU"), Some("candle"))); + assert!(b.fallback.as_deref().is_some_and(|f| f.contains("device lost")), "{b:?}"); + assert_eq!((b.encode_ms, b.analyze_ms), (Some(812), Some(900)), "the last photo's times"); + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/crates/engine/src/tests_segment.rs b/crates/engine/src/tests_segment.rs index f4b9f4f484..f317ef8fd4 100644 --- a/crates/engine/src/tests_segment.rs +++ b/crates/engine/src/tests_segment.rs @@ -50,6 +50,17 @@ fn status_and_model_commands_without_the_model() { assert_eq!(st["installed"], false); assert_eq!(st["download"]["running"], false); assert!(st["license"].as_str().unwrap().contains("SAM License")); + // where it runs: nowhere yet (no model loaded), and nothing timed + if Segmenter::AVAILABLE { + let b = &st["backend"]; + assert!(b["device"].is_null() && b["encodeMs"].is_null() && b["analyzeMs"].is_null(), "{b}"); + // the GPU switches show before the model loads (macOS: Metal, which only the environment switches govern) + let off = if cfg!(target_os = "macos") { lightcraft_gpu::env_off_reason().map(str::to_string) } else { lightcraft_gpu::switched_off() }; + assert_eq!(b["fallback"].as_str(), off.as_deref(), "{b}"); + } else { + assert!(st["backend"].is_null()); + } + assert_eq!(st["runOn"], "auto"); // downloading needs the user's consent, and names the size and the licence let e = s.execute("segment.model.download", &json!({})).unwrap_err().to_string(); assert!(e.contains("acknowledged") && e.contains("SAM License") && e.contains("GB"), "{e}"); @@ -305,3 +316,37 @@ fn a_missing_model_is_model_missing_by_kind() { } } } + +/// Where SAM 3 runs is the user's choice (`segment.settings`), shown by `segment.model.status`, kept in the settings +/// file and read back by the next session; a bad value is refused and changes nothing. +#[test] +fn the_choice_of_where_ai_masks_run_is_kept() { + let dir = tmp("runon"); + let file = dir.join("models").join("sam3-settings.json"); + let mut s = Session::with_demo(); + s.segmenter.settings_file = Some(file.clone()); + assert_eq!(s.execute("segment.settings", &json!({})).unwrap()["runOn"], "auto"); + assert_eq!(s.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let st = s.execute("segment.model.status", &json!({})).unwrap(); + assert_eq!(st["runOn"], "cpu"); + if Segmenter::AVAILABLE { + assert_eq!(st["backend"]["fallback"], crate::segment::CPU_CHOSEN, "{st}"); + } + let e = s.execute("segment.settings", &json!({"runOn": "gpu"})).unwrap_err().to_string(); + assert!(e.contains("auto or cpu"), "{e}"); + assert_eq!(s.segmenter.run_on(), crate::segment::RunOn::Cpu); + let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(saved["runOn"], "cpu"); + // the next session reads it; a damaged file is Automatic + let mut again = Session::with_demo(); + again.segmenter.settings_file = Some(file.clone()); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Cpu); + std::fs::write(&file, b"{not json").unwrap(); + again.segmenter.load_settings(); + assert_eq!(again.segmenter.run_on(), crate::segment::RunOn::Auto); + // without a settings file the choice holds for the session + let mut memory = Session::with_demo(); + assert_eq!(memory.execute("segment.settings", &json!({"runOn": "cpu"})).unwrap()["runOn"], "cpu"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7efae6a576..ec644df6e7 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -237,10 +237,11 @@ pub fn wait_idle(timeout: std::time::Duration) -> bool { } } -/// Why GPU compute that has a device of its own (denoise, faces) is switched off by the user's settings, or `None`: the -/// environment switches and the rendering preference, but not a render-device failure (the devices are separate). +/// Why GPU compute that has a device of its own (denoise, faces, SAM 3) is switched off by the user's settings, or +/// `None`: the environment switches and the rendering preference, but not a render-device failure (the devices are +/// separate). #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn switched_off() -> Option { +pub fn switched_off() -> Option { if let Some(why) = env_off_reason() { return Some(why.into()); } diff --git a/crates/segment/Cargo.toml b/crates/segment/Cargo.toml index b4614a81d8..77f6353524 100644 --- a/crates/segment/Cargo.toml +++ b/crates/segment/Cargo.toml @@ -19,6 +19,8 @@ log = { workspace = true } candle-core = { workspace = true } candle-nn = { workspace = true } lightcraft-fetch = { workspace = true } +# the CPU kernels share candle's thread pool +rayon = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] candle-core = { workspace = true, features = ["metal"] } diff --git a/crates/segment/examples/sam3_bench.rs b/crates/segment/examples/sam3_bench.rs index 982f482e96..a00ae556dd 100644 --- a/crates/segment/examples/sam3_bench.rs +++ b/crates/segment/examples/sam3_bench.rs @@ -1,25 +1,57 @@ //! Times SAM 3 on this machine (a synthetic gradient image; the first run includes compiling -//! the GPU kernels): `cargo run -p lightcraft-segment --release --example sam3_bench -- `. +//! the GPU kernels and loading the heads): `cargo run -p lightcraft-segment --release --example +//! sam3_bench -- `. Each run times the backbone, the click features (tracker neck), +//! a first and a further click, and a first and a second description of the same image (the +//! first one computes the detector's features). + +use std::time::{Duration, Instant}; + +fn ms(d: Duration) -> String { + format!("{:.0} ms", d.as_secs_f64() * 1e3) +} fn main() -> Result<(), Box> { let mut args = std::env::args().skip(1); - let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench ")?); - let t = std::time::Instant::now(); + let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench [runs]")?); + let runs: usize = args.next().map(|s| s.parse()).transpose()?.unwrap_or(3); + let t = Instant::now(); let mut model = lightcraft_segment::Sam3::load(&dir)?; - eprintln!("load: {:?} on {:?}", t.elapsed(), model.device()); + eprintln!("load: {} on {}", ms(t.elapsed()), model.backbone_device()); let (w, h) = (1200, 800); let rgb: Vec = (0..w * h * 3).map(|i| ((i / 3 % w) * 255 / w) as u8).collect(); - for run in 0..3 { - let t = std::time::Instant::now(); + let click = |x, y| lightcraft_segment::Click { x, y, positive: true }; + for run in 0..runs { + let t = Instant::now(); let mut enc = model.encode(&rgb, w, h)?; lightcraft_segment::sync(&model)?; - let e = t.elapsed(); - let t = std::time::Instant::now(); - let p = model.segment_clicks(&mut enc, &[lightcraft_segment::Click { x: 0.5, y: 0.5, positive: true }])?; - let c = t.elapsed(); - let t = std::time::Instant::now(); + let encode = t.elapsed(); + let t = Instant::now(); + model.prepare_clicks(&mut enc)?; + lightcraft_segment::sync(&model)?; + let features = t.elapsed(); + let t = Instant::now(); + let p = model.segment_clicks(&mut enc, &[click(0.5, 0.5)])?; + let click1 = t.elapsed(); + let t = Instant::now(); + model.segment_clicks(&mut enc, &[click(0.5, 0.5), click(0.3, 0.6)])?; + let click2 = t.elapsed(); + let t = Instant::now(); let d = model.segment_text(&mut enc, "sky", 0.5)?; - eprintln!("run {run}: encode {e:?}, click {c:?} (score {:.2}), text {:?} ({})", p.score, t.elapsed(), d.is_some()); + let text1 = t.elapsed(); + let t = Instant::now(); + model.segment_text(&mut enc, "the red car", 0.5)?; + let text2 = t.elapsed(); + eprintln!( + "run {run}: encode {}, click features {}, click {} (score {:.2}), further click {}, first describe {} ({}), second describe {}", + ms(encode), + ms(features), + ms(click1), + p.score, + ms(click2), + ms(text1), + d.is_some(), + ms(text2) + ); } Ok(()) } diff --git a/crates/segment/src/cpu.rs b/crates/segment/src/cpu.rs new file mode 100644 index 0000000000..64827840ce --- /dev/null +++ b/crates/segment/src/cpu.rs @@ -0,0 +1,147 @@ +//! Fused CPU kernels for the model's elementwise work. +//! +//! On the CPU, candle runs bias adds, activations, broadcasts and layout copies one element at a +//! time on one thread. The kernels do the same arithmetic in the same order (bit-identical +//! results), fused into fewer passes over memory and spread over the rayon pool that candle's +//! matrix products use. + +use std::f32::consts::FRAC_1_SQRT_2; + +use candle_core::cpu::erf::erf_f32; +use candle_core::{CpuStorage, CustomOp2, D, Layout, Shape, Tensor, bail}; +use candle_nn::Linear; +use rayon::prelude::*; + +use crate::{Error, Result}; + +/// The contiguous `f32` values of a CPU tensor. +fn values<'a>(s: &'a CpuStorage, l: &Layout) -> candle_core::Result<&'a [f32]> { + match (s, l.contiguous_offsets()) { + (CpuStorage::F32(v), Some((start, end))) => match v.get(start..end) { + Some(v) => Ok(v), + None => bail!("layout outside its storage"), + }, + _ => bail!("fused kernels take contiguous f32 tensors"), + } +} + +/// `x · Wᵀ` over the rows of `x` (`[…, K]`) as `[rows, N]`: `Linear::forward` without the bias. +fn product(x: &Tensor, l: &Linear) -> Result { + let k = x.dim(D::Minus1)?; + Ok(x.reshape(((), k))?.matmul(&l.weight().t()?)?) +} + +fn bias(l: &Linear) -> Result<&Tensor> { + l.bias().ok_or_else(|| Error::Model("fused linear without a bias".into())) +} + +/// `gelu_erf(x · Wᵀ + b)` (`gelu`) or `relu(x · Wᵀ + b)`: `[rows, N]`. +pub fn linear_act(x: &Tensor, l: &Linear, gelu: bool) -> Result { + Ok(product(x, l)?.apply_op2_no_bwd(bias(l)?, &BiasAct { gelu })?) +} + +/// The detector's box relative-position bias `[1, heads, 1 + queries, side²]` from its row and +/// column terms `ey`, `ex` (`[queries, side, heads]`): `ey[q, y, h] + ex[q, x, h]` at `y·side + x`, +/// after a row of zeros (the presence token). +pub fn box_bias(ey: &Tensor, ex: &Tensor) -> Result { + Ok(ey.contiguous()?.apply_op2_no_bwd(&ex.contiguous()?, &BoxBias)?) +} + +/// Rows of `x` (`[rows, N]`) with a bias `[N]`. +fn rows(x: &[f32], b: &[f32]) -> candle_core::Result { + if b.is_empty() || !x.len().is_multiple_of(b.len()) { + bail!("bias of {} for {} values", b.len(), x.len()); + } + Ok(b.len()) +} + +struct BiasAct { + gelu: bool, +} + +impl CustomOp2 for BiasAct { + fn name(&self) -> &'static str { + if self.gelu { "bias-gelu-erf" } else { "bias-relu" } + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (x, b) = (values(s1, l1)?, values(s2, l2)?); + let n = rows(x, b)?; + let mut out = vec![0f32; x.len()]; + out.par_chunks_mut(n).zip(x.par_chunks(n)).for_each(|(o, x)| { + for ((o, x), b) in o.iter_mut().zip(x).zip(b) { + let v = x + b; + // candle's `gelu_erf` and `relu` + *o = if self.gelu { (erf_f32(v * FRAC_1_SQRT_2) + 1.) * 0.5 * v } else { v.max(0f32) }; + } + }); + Ok((CpuStorage::F32(out), l1.shape().clone())) + } +} + +struct BoxBias; + +impl CustomOp2 for BoxBias { + fn name(&self) -> &'static str { + "box-relative-position-bias" + } + + fn cpu_fwd(&self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { + let (ey, ex) = (values(s1, l1)?, values(s2, l2)?); + let (q, side, heads) = l1.shape().dims3()?; + if l2.shape() != l1.shape() { + bail!("box bias terms {:?} and {:?}", l1.shape(), l2.shape()); + } + let n = side * side; + let mut out = vec![0f32; heads * (q + 1) * n]; + // row 0 of each head (the presence token) stays zero + out.par_chunks_mut(n).enumerate().filter(|(i, _)| i % (q + 1) != 0).for_each(|(i, o)| { + let (h, q) = (i / (q + 1), i % (q + 1) - 1); + for (y, o) in o.chunks_exact_mut(side).enumerate() { + let ey = ey[(q * side + y) * heads + h]; + for (x, o) in o.iter_mut().enumerate() { + *o = ey + ex[(q * side + x) * heads + h]; + } + } + }); + Ok((CpuStorage::F32(out), Shape::from((1, heads, q + 1, n)))) + } +} + +#[cfg(test)] +mod tests { + use candle_core::Device; + use candle_nn::Module; + + use super::*; + + fn randn(shape: &[usize]) -> Tensor { + Tensor::randn(0f32, 1.0, shape, &Device::Cpu).unwrap() + } + + #[test] + fn linear_act_matches_the_tensor_ops() { + let x = randn(&[2, 7, 5]); + let l = Linear::new(randn(&[6, 5]), Some(randn(&[6]))); + for gelu in [false, true] { + let want = l.forward(&x).unwrap(); + let want = if gelu { want.gelu_erf() } else { want.relu() }.unwrap().reshape((14, 6)).unwrap(); + let got = linear_act(&x, &l, gelu).unwrap(); + assert_eq!(got.dims(), want.dims()); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } + assert!(linear_act(&x, &Linear::new(randn(&[6, 5]), None), false).is_err()); + } + + #[test] + fn box_bias_matches_the_tensor_ops() { + let (ey, ex) = (randn(&[4, 5, 3]), randn(&[4, 5, 3])); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((4, 25, 3)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap().unsqueeze(0).unwrap(); + let got = box_bias(&ey, &ex).unwrap(); + assert_eq!(got.dims(), want.dims()); + // the same additions: bit-identical + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + assert!(box_bias(&ey, &randn(&[4, 6, 3])).is_err()); + } +} diff --git a/crates/segment/src/detector.rs b/crates/segment/src/detector.rs index c302aafe76..edb8557dff 100644 --- a/crates/segment/src/detector.rs +++ b/crates/segment/src/detector.rs @@ -6,18 +6,24 @@ //! the Python/PyTorch SAM 3 code of Hugging Face Transformers (`models/sam3/modeling_sam3.py`), Copyright The HuggingFace //! Team and Meta Platforms, Inc.; translated to Rust on candle and restructured. See NOTICE. +use std::collections::VecDeque; +use std::sync::{Mutex, OnceLock, PoisonError}; + use candle_core::{D, Device, IndexOp, Module, Tensor}; use candle_nn::{Conv2d, Conv2dConfig, GroupNorm, LayerNorm, Linear, VarBuilder}; use crate::clip::TextEncoder; use crate::neck::{FPN, Neck}; use crate::nn::{Attention, DecoderMlp, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec}; -use crate::{Error, Prediction, Result}; +use crate::{BackboneAccel, Error, Prediction, Result, cpu}; const HIDDEN: usize = FPN; const HEADS: usize = 8; const QUERIES: usize = 200; const LAYERS: usize = 6; +/// Prompts whose text features are kept: they don't depend on the image, and the same few come back (Subject's +/// "person" on every photo). 32 KB each. +const TEXT_CACHE: usize = 16; /// Detector image features, computed once per image. pub struct Features { @@ -44,6 +50,17 @@ pub struct Output { /// Semantic logits `[288, 288]` flattened: everything the prompt names, one mask without /// boundaries between instances. pub semantic: Vec, + /// The DETR encoder's memory `[1, 5184, 256]` (tests). + pub memory: Tensor, +} + +/// Where the DETR encoder and the mask decoder may run outside candle: the model's accelerator (if it still has one), +/// and why the encoder (`failed`) or the mask decoder (`masks_failed`) stopped running there (set on its first failure; +/// from then on candle runs it). +pub struct EncoderAccel<'a> { + pub accel: &'a Mutex>>, + pub failed: &'a OnceLock, + pub masks_failed: &'a OnceLock, } struct EncoderLayer { @@ -71,6 +88,8 @@ pub struct Detector { neck: Neck, text: TextEncoder, text_proj: Linear, + /// The latest prompts' token ids and valid marks with their features `[1, 32, 256]`, most recent last. + texts: Mutex, Vec, Tensor)>>, encoder: Vec, decoder: Vec, out_ln: LayerNorm, @@ -138,6 +157,7 @@ impl Detector { neck: Neck::new(vb.pp("vision_encoder.neck"))?, text: TextEncoder::new(vb.pp("text_encoder.text_model"))?, text_proj: linear(1024, HIDDEN, vb.pp("text_projection"))?, + texts: Mutex::new(VecDeque::with_capacity(TEXT_CACHE)), encoder, decoder, out_ln: ln(HIDDEN, TORCH_LN_EPS, d.pp("output_layer_norm"))?, @@ -164,9 +184,13 @@ impl Detector { }) } - /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`. - pub fn features(&self, backbone: &Tensor) -> Result { - let levels = self.neck.forward(backbone, 3)?; + /// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`, or from its neck's three + /// levels when they were computed elsewhere (an accelerator). + pub fn features(&self, backbone: &Tensor, levels: Option>) -> Result { + let levels = match levels { + Some(levels) => levels, + None => self.neck.forward(backbone, 3)?, + }; let last = levels.last().ok_or_else(|| Error::Model("detector neck".into()))?; let (_, _, side, _) = last.dims4()?; let flat = last.flatten_from(2)?.transpose(1, 2)?.contiguous()?; @@ -174,6 +198,23 @@ impl Detector { Ok(Features { levels, flat, pos, side }) } + /// The prompt's features `[1, 32, 256]`: the CLIP text encoder and its projection, or the same tensor again + /// when the prompt was among the last [`TEXT_CACHE`]. + fn text_features(&self, ids: &[u32], valid: &[bool]) -> Result { + let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(seen) = texts.iter().position(|(i, v, _)| i == ids && v == valid).and_then(|at| texts.remove(at)) { + let text = seen.2.clone(); + texts.push_back(seen); + return Ok(text); + } + let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; + if texts.len() >= TEXT_CACHE { + texts.pop_front(); + } + texts.push_back((ids.to_vec(), valid.to_vec(), text.clone())); + Ok(text) + } + /// Box relative-position bias `[1, heads, 1 + 200, side²]` for reference boxes (cx, cy, w, h). fn rpb(&self, boxes: &Tensor, side: usize) -> Result { let xyxy = cxcywh_to_xyxy(boxes)?.squeeze(0)?; // [200, 4] @@ -188,6 +229,9 @@ impl Detector { let dx = log_scale(coords.broadcast_sub(&pick(0, 2)?)?)?; let ey = self.rpb_y.forward(&dy)?; // [200, side, heads] let ex = self.rpb_x.forward(&dx)?; + if self.device.is_cpu() { + return cpu::box_bias(&ey, &ex); + } let m = ey.unsqueeze(2)?.broadcast_add(&ex.unsqueeze(1)?)?; // [200, side, side, heads] let m = m.reshape((QUERIES, side * side, HEADS))?.permute((2, 0, 1))?; // [heads, 200, side²] let m = m.pad_with_zeros(1, 1, 0)?; // the presence token attends everywhere @@ -208,23 +252,143 @@ impl Detector { Ok(Tensor::cat(&[one(1)?, one(0)?, one(2)?, one(3)?], D::Minus1)?) } - /// Run the detector for one tokenized prompt. - pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool]) -> Result { - let text = self.text_proj.forward(&self.text.forward(ids, valid)?)?; // [1, 32, 256] - let text_bias = padding_bias(valid, &self.device)?; - - // DETR encoder: image tokens attend to themselves and to the prompt + /// The DETR encoder: image tokens attend to themselves and to the prompt. Returns the memory `[1, 5184, 256]`. + fn encode(&self, f: &Features, text: &Tensor, text_bias: &Tensor) -> Result { let mut x = f.flat.clone(); for l in &self.encoder { let h = l.ln1.forward(&x)?; let hp = (&h + &f.pos)?; x = (&x + l.self_attn.forward(&hp, &hp, &h, None)?)?; let h = l.ln2.forward(&x)?; - x = (&x + l.cross_attn.forward(&h, &text, &text, Some(&text_bias))?)?; + x = (&x + l.cross_attn.forward(&h, text, text, Some(text_bias))?)?; let h = l.ln3.forward(&x)?; x = (&x + l.mlp.forward(&h)?)?; } - let memory = x; + Ok(x) + } + + /// [`Detector::encode`] on the accelerator; `None` when there is none, or it doesn't run the encoder or fails (the + /// first failure is logged and noted in `accel.failed`, and the accelerator isn't asked again). `Err` when the app is + /// closing. + fn encode_accelerated(&self, f: &Features, text: &Tensor, valid: &[bool], accel: &EncoderAccel) -> Result> { + if accel.failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_detr_encoder()) else { return Ok(None) }; + let image = to_vec(&f.flat)?; + let want = image.len(); + // what the decoder can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.detr_encoder(&image, &to_vec(&f.pos)?, &to_vec(text)?, valid).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => Ok(Some(Tensor::from_vec(out, f.flat.dims(), &self.device)?)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 DETR encoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// The mask decoder in candle: the per-query mask logits `[200, 288, 288]` for the encoder memory and the mask + /// embeddings `e` `[1, 200, 256]`. + fn masks(&self, f: &Features, memory: &Tensor, text: &Tensor, text_bias: &Tensor, e: &Tensor) -> Result<(Tensor, Vec)> { + // the encoder memory attends to the prompt, then a pixel decoder up to 288² + let mem = (memory + self.prompt_attn.forward(&self.prompt_ln.forward(memory)?, text, text, Some(text_bias))?)?; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; + for (i, skip) in [l1, l0].into_iter().enumerate() { + let (_, _, sh, sw) = skip.dims4()?; + prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; + let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { + return Err(Error::Model("pixel decoder".into())); + }; + prev = norm.forward(&conv.forward(&prev)?)?.relu()?; + } + let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] + let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; + let (_, c, mh, mw) = inst.dims4()?; + Ok((e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?, semantic)) + } + + /// [`Detector::masks`] on the accelerator (the semantic mask as one more row of the same product); `None` when there + /// is none, or it doesn't run the mask decoder or fails + /// (the first failure is logged and noted in `accel.masks_failed`, and the accelerator isn't asked again). `Err` when + /// the app is closing. + fn masks_accelerated( + &self, + f: &Features, + memory: &Tensor, + (text, valid): (&Tensor, &[bool]), + e: &Tensor, + accel: &EncoderAccel, + ) -> Result)>> { + if accel.masks_failed.get().is_some() { + return Ok(None); + } + let guard = accel.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: candle runs this, and that is no failure + let Some(a) = guard.as_ref().filter(|a| a.runs_mask_decoder()) else { return Ok(None) }; + let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; + let (_, _, mh, mw) = l0.dims4()?; + // the instance projection folded into the embeddings: e · (W x + b) = (e W) x + e b, one product per pixel + let e = e.squeeze(0)?; // [200, 256] + let rows = e.matmul(&self.instance_proj.weight().reshape((HIDDEN, HIDDEN))?)?; + let mut bias = match self.instance_proj.bias() { + Some(b) => to_vec(&e.matmul(&b.unsqueeze(1)?)?)?, + None => vec![0.0; QUERIES], + }; + // the semantic projection (1 × 1, 256 → 1) is one more row: the last mask is the semantic one + let rows = Tensor::cat(&[rows, self.semantic_proj.weight().reshape((1, HIDDEN))?], 0)?; + bias.push(match self.semantic_proj.bias() { + Some(b) => to_vec(b)?.first().copied().unwrap_or(0.0), + None => 0.0, + }); + let want = (QUERIES + 1) * mh * mw; + // what the masks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let checked = a.mask_decoder(&to_vec(memory)?, &to_vec(text)?, valid, [&to_vec(l1)?, &to_vec(l0)?], &to_vec(&rows)?, &bias).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if !out.iter().fold(true, |ok, v| ok & v.is_finite()) { + // without short-cutting, so that it vectorizes (17 M values) + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(mut out) => { + let semantic = out.split_off(QUERIES * mh * mw); + Ok(Some((Tensor::from_vec(out, (QUERIES, mh, mw), &self.device)?, semantic))) + } + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 mask decoder not run on {} ({e}); using the {} for it from now on", a.device(), crate::device_name(&self.device)); + let _ = accel.masks_failed.set(format!("{}: {e}", a.device())); + Ok(None) + } + } + } + + /// Run the detector for one tokenized prompt, the DETR encoder and the mask decoder on `accel` when it runs them. + pub fn predict(&self, f: &Features, ids: &[u32], valid: &[bool], accel: &EncoderAccel) -> Result { + let text = self.text_features(ids, valid)?; + let text_bias = padding_bias(valid, &self.device)?; + + let memory = match self.encode_accelerated(f, &text, valid, accel)? { + Some(memory) => memory, + None => self.encode(f, &text, &text_bias)?, + }; // DETR decoder: presence token + 200 queries with iterative box refinement let mut boxes = candle_nn::ops::sigmoid(&self.reference_points)?; @@ -260,21 +424,7 @@ impl Detector { let pq = self.score_query_proj.forward(&queries)?; // [1, 200, 256] let logits = (pq.matmul(&pt.unsqueeze(2)?)? / (HIDDEN as f64).sqrt())?.clamp(-12f32, 12f32)?; - // masks: the encoder memory attends to the prompt, then a pixel decoder up to 288² - let mem = (&memory + self.prompt_attn.forward(&self.prompt_ln.forward(&memory)?, &text, &text, Some(&text_bias))?)?; - let [l0, l1, _] = &f.levels[..] else { return Err(Error::Model("detector levels".into())) }; - let mut prev = mem.transpose(1, 2)?.reshape((1, HIDDEN, f.side, f.side))?; - for (i, skip) in [l1, l0].into_iter().enumerate() { - let (_, _, sh, sw) = skip.dims4()?; - prev = (prev.upsample_nearest2d(sh, sw)? + skip)?; - let (Some(conv), Some(norm)) = (self.pixel_convs.get(i), self.pixel_norms.get(i)) else { - return Err(Error::Model("pixel decoder".into())); - }; - prev = norm.forward(&conv.forward(&prev)?)?.relu()?; - } - let inst = self.instance_proj.forward(&prev)?; // [1, 256, 288, 288] - let semantic = to_vec(&self.semantic_proj.forward(&prev)?)?; - let (_, c, mh, mw) = inst.dims4()?; + // masks: each query's mask embedding against the mask decoder's per-pixel output let mut e = queries.clone(); for (i, l) in self.mask_embedder.iter().enumerate() { e = l.forward(&e)?; @@ -282,7 +432,10 @@ impl Detector { e = e.relu()?; } } - let masks = e.matmul(&inst.reshape((1, c, mh * mw))?)?.reshape((QUERIES, mh, mw))?; + let (masks, semantic) = match self.masks_accelerated(f, &memory, (&text, valid), &e, accel)? { + Some(masks) => masks, + None => self.masks(f, &memory, &text, &text_bias, &e)?, + }; let boxes = cxcywh_to_xyxy(&boxes)?; let bv = to_vec(&boxes)?; Ok(Output { @@ -292,6 +445,7 @@ impl Detector { boxes: bv.as_chunks::<4>().0.to_vec(), text, semantic, + memory, }) } } @@ -335,7 +489,89 @@ pub fn merge(out: &Output, threshold: f32) -> Option { #[cfg(test)] mod tests { + use std::path::PathBuf; + use super::*; + use crate::Sam3; + + /// The real checkpoint in `$LIGHTCRAFT_SAM3_DIR` (as the GPU tests), or `None` (the test skips) without it or when it + /// doesn't load. + fn model() -> Option { + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + if !crate::is_model_dir(&dir) { + return None; + } + match Sam3::load_on(&dir, Device::Cpu) { + Ok(m) => Some(m), + Err(e) => { + eprintln!("the model in {} doesn't load: {e}", dir.display()); + None + } + } + } + + fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() + } + + #[test] + fn the_box_bias_matches_the_tensor_ops_on_random_boxes() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, _, _) = m.detector_parts().unwrap(); + let side = 72; + for _ in 0..3 { + let centres = Tensor::rand(0f32, 1.0, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let sizes = Tensor::rand(0.01f32, 0.6, (1, QUERIES, 2), &Device::Cpu).unwrap(); + let boxes = Tensor::cat(&[centres, sizes], 2).unwrap(); + let got = det.rpb(&boxes, side).unwrap(); + // what the other devices run, from the same row and column terms + let xyxy = cxcywh_to_xyxy(&boxes).unwrap().squeeze(0).unwrap(); + let coords = Tensor::arange(0u32, side as u32, &Device::Cpu).unwrap().to_dtype(candle_core::DType::F32).unwrap(); + let coords = coords.affine(1.0 / side as f64, 0.0).unwrap().reshape((1, side, 1)).unwrap(); + let term = |mlp: &DecoderMlp, a: usize, b: usize| { + let pick = Tensor::cat(&[xyxy.narrow(1, a, 1).unwrap(), xyxy.narrow(1, b, 1).unwrap()], 1).unwrap().unsqueeze(1).unwrap(); + let d = (coords.broadcast_sub(&pick).unwrap() * 8.0).unwrap(); + let d = d.sign().unwrap().mul(&((d.abs().unwrap() + 1.0).unwrap().log().unwrap() / 8f64.ln()).unwrap()).unwrap(); + mlp.forward(&d).unwrap() + }; + let (ey, ex) = (term(&det.rpb_y, 1, 3), term(&det.rpb_x, 0, 2)); + let want = ey.unsqueeze(2).unwrap().broadcast_add(&ex.unsqueeze(1).unwrap()).unwrap(); + let want = want.reshape((QUERIES, side * side, HEADS)).unwrap().permute((2, 0, 1)).unwrap().pad_with_zeros(1, 1, 0).unwrap(); + assert_eq!(got.dims(), [1, HEADS, 1 + QUERIES, side * side]); + assert_eq!(values(&got), values(&want)); + } + } + + #[test] + fn prompt_features_are_kept_for_the_latest_prompts() { + let Some(mut m) = model() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let (det, tok, _) = m.detector_parts().unwrap(); + let prompts: Vec<(Vec, Vec)> = (0..=TEXT_CACHE).map(|i| tok.encode(&format!("{i} people"))).collect(); + let features = |i: usize| det.text_features(&prompts[i].0, &prompts[i].1).unwrap(); + let first = features(0); + let fresh = det.text_proj.forward(&det.text.forward(&prompts[0].0, &prompts[0].1).unwrap()).unwrap(); + assert_eq!(values(&first), values(&fresh)); + // the same tensor again, also after other prompts + assert_eq!(features(0).id(), first.id()); + let second = features(1); + for i in 2..TEXT_CACHE { + features(i); + } + assert_eq!(features(0).id(), first.id(), "prompt 0 is the latest one now"); + // one more prompt drops the least recently used, prompt 1, which is computed again + features(TEXT_CACHE); + assert_eq!(det.texts.lock().unwrap().len(), TEXT_CACHE); + assert_eq!(features(0).id(), first.id()); + let again = features(1); + assert_ne!(again.id(), second.id()); + assert_eq!(values(&again), values(&second)); + } /// Two people side by side on a row of cells, each only weakly sure of themself and both fading where /// they touch; the semantic mask is sure of both and runs across. Each takes the semantic logits where @@ -376,6 +612,7 @@ mod tests { boxes: vec![[0.0; 4]; 3], text: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), semantic: semantic.to_vec(), + memory: Tensor::zeros(1, candle_core::DType::F32, &Device::Cpu).unwrap(), }; let semantic = [5.0, 6.0, 4.0, 6.0, 5.0]; let merged = merge(&output([4.0, 4.0, -6.0], &semantic), 0.5).unwrap(); diff --git a/crates/segment/src/lib.rs b/crates/segment/src/lib.rs index 6c24d0836f..959232edf4 100644 --- a/crates/segment/src/lib.rs +++ b/crates/segment/src/lib.rs @@ -8,9 +8,14 @@ //! The expensive part, the 32-layer ViT over the 1008 × 1008 input, runs once per image //! ([`Sam3::encode`]); each click or prompt then reuses the [`Encoded`] features. //! -//! On macOS the model runs on the GPU through Metal; elsewhere (for now) on the CPU. The -//! weights are not part of LightCraft: they are the `facebook/sam3` checkpoint (SAM License), -//! read from a directory the user downloads them to ([`Sam3::load`]). +//! On macOS the model runs on the GPU through Metal ([`Sam3::load`]). Elsewhere candle runs on +//! the CPU, and the backbone, most of the work, can run outside candle on an accelerator, with +//! the two necks after it ([`BackboneAccel`]: `lightcraft-gpu`'s wgpu kernels on Vulkan / DX12, loaded with +//! [`Sam3::load_accelerated`]); when that can't be built or fails on a photo, the candle backbone +//! takes over ([`Sam3::backbone_fallback`] says why; not while the app is closing: [`BackboneAccel::closing`]). +//! The accelerator can also run the text detector's DETR encoder (else, or once it fails, candle does: +//! [`Sam3::detr_fallback`]). The weights are not part of LightCraft: they are the `facebook/sam3` checkpoint +//! (SAM License), read from a directory the user downloads them to. //! //! Ported from the Hugging Face `transformers` implementation (Apache-2.0); see `NOTICE`. //! This crate is therefore licensed under the Apache License 2.0 only (not the MIT option of @@ -29,6 +34,8 @@ #[cfg(not(target_arch = "wasm32"))] mod clip; #[cfg(not(target_arch = "wasm32"))] +mod cpu; +#[cfg(not(target_arch = "wasm32"))] mod detector; #[cfg(not(target_arch = "wasm32"))] pub mod fetch; @@ -49,13 +56,15 @@ mod weights; use std::path::{Path, PathBuf}; #[cfg(not(target_arch = "wasm32"))] -use std::sync::Arc; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; #[cfg(not(target_arch = "wasm32"))] -use candle_core::{DType, Device, Tensor}; +use candle_core::{DType, Tensor}; #[cfg(not(target_arch = "wasm32"))] use candle_nn::VarBuilder; +#[cfg(not(target_arch = "wasm32"))] +pub use candle_core::Device; #[cfg(not(target_arch = "wasm32"))] pub use tracker::Click; @@ -103,12 +112,135 @@ pub fn best_device() -> Device { } #[cfg(not(target_arch = "wasm32"))] -/// A loaded model. The vision backbone loads with it; the point and text heads load on first use. +/// Where the backbone's weights are in the checkpoint. +pub const BACKBONE_PREFIX: &str = "detector_model.vision_encoder.backbone"; + +#[cfg(not(target_arch = "wasm32"))] +/// The vision backbone run outside candle (the wgpu compute kernels of `lightcraft-gpu` on +/// Vulkan / DX12 / Metal). It computes what the candle ViT computes, so everything after the +/// backbone (necks, heads) stays as it is. +pub trait BackboneAccel: Send + Sync { + /// `pixels`: `[3, 1008, 1008]` (CHW, normalized to −1..1). Returns the backbone output + /// `[1024, 72, 72]` (CHW), as the candle ViT's `[1, 1024, 72, 72]` without the batch. + fn forward(&self, pixels: &[f32]) -> std::result::Result, String>; + /// What it runs on, for logs and Settings (e.g. "NVIDIA GeForce RTX 5070 (Vulkan)"). + fn device(&self) -> String; + + /// Whether the app is closing, so that an `Err` from it is no failure of the accelerator: it stays in use, and the + /// work ends with that error instead of running in candle (no CPU inference while the app quits). + fn closing(&self) -> bool { + false + } + + /// Whether it runs the necks ([`BackboneAccel::neck`]); when not, they are never asked for and run in candle. + fn runs_necks(&self) -> bool { + false + } + + /// Whether it runs the text detector's DETR encoder ([`BackboneAccel::detr_encoder`]); when not, candle does. + fn runs_detr_encoder(&self) -> bool { + false + } + + /// Whether it runs the text detector's mask decoder ([`BackboneAccel::mask_decoder`]); when not, candle does. + fn runs_mask_decoder(&self) -> bool { + false + } + + /// The feature pyramid of the `which` neck for a backbone output `[1024, 72, 72]` (CHW): the + /// `n` finest levels, each `[256, s, s]` (CHW; s = 288, 144, 72, 36), as the candle `Neck::forward`. + /// `Err` when this accelerator doesn't run it (the candle neck runs instead). + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + let _ = (which, backbone, n); + Err("no neck on this accelerator".into()) + } + + /// The detector's DETR encoder (6 layers): the image tokens `[5184, 256]` with their sine + /// position encoding `pos` `[5184, 256]` attend to themselves and to the prompt `text` + /// `[32, 256]` (`valid` marks its real tokens). Returns the encoder memory `[5184, 256]`. + /// `Err` when this accelerator doesn't run it (the candle encoder runs instead). + fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> std::result::Result, String> { + let _ = (image, pos, text, valid); + Err("no DETR encoder on this accelerator".into()) + } + + /// The detector's mask decoder: the encoder memory `[5184, 256]` attends to the prompt `text` `[32, 256]` (`valid` + /// marks its real tokens) and is added to it, the pixel decoder brings that up to 288² with the detector neck's + /// `levels` `[256, 144, 144]` and `[256, 288, 288]` (CHW), and each of the `rows` `[r, 256]` (1 ≤ r ≤ 256, with + /// `bias` `[r]`) is a 1 × 1 projection of its output. Returns `[r, 288, 288]` (the detector passes its mask + /// embeddings with the instance projection folded in: the per-query mask logits). `Err` when this accelerator + /// doesn't run it (the candle decoder runs instead). + fn mask_decoder( + &self, + memory: &[f32], + text: &[f32], + valid: &[bool], + levels: [&[f32]; 2], + rows: &[f32], + bias: &[f32], + ) -> std::result::Result, String> { + let _ = (memory, text, valid, levels, rows, bias); + Err("no mask decoder on this accelerator".into()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// The two feature pyramids of the checkpoint. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NeckKind { + /// `tracker_neck`: the click decoder's (3 levels). + Tracker, + /// `detector_model.vision_encoder.neck`: the text detector's (3 levels). + Detector, +} + +#[cfg(not(target_arch = "wasm32"))] +/// Read access to a checkpoint's tensors (for accelerators that upload weights themselves; +/// cloning shares the open file, so an accelerator can keep one and load more layers later). +#[derive(Clone)] +pub struct WeightReader(Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl WeightReader { + /// The checkpoint in a model directory (see [`is_model_dir`]). + pub fn open(dir: &Path) -> Result { + if !is_model_dir(dir) { + return Err(Error::Missing(dir.to_path_buf())); + } + Ok(Self(weights::Weights::open(&dir.join(WEIGHTS_FILE))?)) + } + + /// The stored shape of `name`, without reading its data. + pub fn shape(&self, name: &str) -> Option> { + self.0.shape(name).map(<[usize]>::to_vec) + } + + /// Tensor `name`: its shape and its values (f32, row-major). + pub fn read(&self, name: &str) -> Result<(Vec, Vec)> { + let t = self.0.read(name)?; + Ok((t.dims().to_vec(), t.flatten_all()?.to_vec1::()?)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// A loaded model. The vision backbone loads with it (unless an accelerator runs it); the point +/// and text heads load on first use. pub struct Sam3 { dir: PathBuf, device: Device, weights: Arc, - backbone: vit::Vit, + /// The candle backbone: loaded with the model, or only when an accelerator fails. + backbone: OnceLock, + accel: Mutex>>, + /// Why the accelerator `load_accelerated` was given is not (or no longer) used. + fallback: Mutex>, + /// Why the DETR encoder runs in candle although there is an accelerator (it failed there once). + detr_fallback: OnceLock, + /// The same for the text detector's mask decoder. + mask_fallback: OnceLock, + /// The necks the accelerator failed on: candle runs them from then on. + necks_off: Mutex>, + /// The candle tracker neck: loaded on first use, unless the accelerator runs it. tracker_neck: Option, tracker: Option, detector: Option, @@ -149,8 +281,123 @@ impl Sam3 { return Err(Error::Missing(dir.to_path_buf())); } let weights = weights::Weights::open(&dir.join(WEIGHTS_FILE))?; - let backbone = vit::Vit::new(Self::vb(&weights, &device).pp("detector_model.vision_encoder.backbone"))?; - Ok(Self { dir: dir.to_path_buf(), device, weights, backbone, tracker_neck: None, tracker: None, detector: None, tokenizer: None }) + let model = Self::unloaded(dir, device, weights, None); + model.candle_backbone()?; + Ok(model) + } + + /// Load with the backbone on an accelerator `make` builds from the checkpoint, and the rest + /// on `device`. When `make` fails the candle backbone loads instead, and when the + /// accelerator fails later, [`Sam3::encode`] falls back to it (logged, not an error), unless the app is closing. + pub fn load_accelerated( + dir: &Path, + device: Device, + make: impl FnOnce(&WeightReader) -> std::result::Result, String>, + ) -> Result { + let reader = WeightReader::open(dir)?; + match make(&reader) { + Ok(accel) => { + log::info!("SAM 3 backbone on {}", accel.device()); + Ok(Self::unloaded(dir, device, reader.0, Some(accel))) + } + Err(e) => { + log::warn!("SAM 3 backbone accelerator unavailable ({e}); using the {}", device_name(&device)); + let model = Self::unloaded(dir, device, reader.0, None); + *model.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(e); + model.candle_backbone()?; + Ok(model) + } + } + } + + fn unloaded(dir: &Path, device: Device, weights: Arc, accel: Option>) -> Self { + Self { + dir: dir.to_path_buf(), + device, + weights, + backbone: OnceLock::new(), + accel: Mutex::new(accel), + fallback: Mutex::new(None), + detr_fallback: OnceLock::new(), + mask_fallback: OnceLock::new(), + necks_off: Mutex::new(Vec::new()), + tracker_neck: None, + tracker: None, + detector: None, + tokenizer: None, + } + } + + /// The candle backbone, loading it on first use. + fn candle_backbone(&self) -> Result<&vit::Vit> { + if let Some(b) = self.backbone.get() { + return Ok(b); + } + let b = vit::Vit::new(Self::vb(&self.weights, &self.device).pp(BACKBONE_PREFIX))?; + Ok(self.backbone.get_or_init(|| b)) + } + + /// What the backbone runs on: the accelerator's device, else the candle device ("CPU", "Metal GPU"). + pub fn backbone_device(&self) -> String { + match &*self.accel.lock().unwrap_or_else(PoisonError::into_inner) { + Some(a) => a.device(), + None => device_name(&self.device), + } + } + + /// Whether the backbone runs on the accelerator (rather than in candle). + pub fn accelerated(&self) -> bool { + self.accel.lock().unwrap_or_else(PoisonError::into_inner).is_some() + } + + /// Why the backbone runs in candle although an accelerator was offered: it could not be built, or it failed on + /// a photo (from then on the model stays in candle). `None` when there is no such reason. + pub fn backbone_fallback(&self) -> Option { + self.fallback.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + /// Why the text detector's DETR encoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn detr_fallback(&self) -> Option { + self.detr_fallback.get().cloned() + } + + /// Why the text detector's mask decoder runs in candle although the backbone runs on an accelerator: the + /// accelerator doesn't run it or failed on it (then it isn't asked again). `None` when there is no such reason. + pub fn mask_fallback(&self) -> Option { + self.mask_fallback.get().cloned() + } + + /// What runs everything after the backbone: the model's device, and which of those parts the accelerator runs + /// (e.g. "CPU; the necks, the DETR encoder and the mask decoder on the GPU"). + pub fn heads_device(&self) -> String { + let base = device_name(&self.device); + // what the accelerator runs (none: there is none any more), less what failed on it + let (necks, detr, masks) = match self.accel.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { + Some(a) => (a.runs_necks(), a.runs_detr_encoder(), a.runs_mask_decoder()), + None => (false, false, false), + }; + let mut gpu = Vec::new(); + if necks { + let off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + match (off.contains(&NeckKind::Tracker), off.contains(&NeckKind::Detector)) { + (false, false) => gpu.push("the necks"), + (false, true) => gpu.push("the click neck"), + (true, false) => gpu.push("the text neck"), + (true, true) => {} + } + } + if detr && self.detr_fallback.get().is_none() { + gpu.push("the DETR encoder"); + } + if masks && self.mask_fallback.get().is_none() { + gpu.push("the mask decoder"); + } + match gpu.split_last() { + None => base, + Some((last, [])) => format!("{base}; {last} on the GPU"), + Some((last, rest)) => format!("{base}; {} and {last} on the GPU", rest.join(", ")), + } } fn vb<'a>(w: &Arc, device: &Device) -> VarBuilder<'a> { @@ -171,30 +418,133 @@ impl Sam3 { /// Run the backbone on preprocessed pixels `[1, 3, 1008, 1008]` (−1..1). pub fn encode_pixels(&self, pixels: &Tensor) -> Result { - Ok(Encoded { backbone: self.backbone.forward(&pixels.to_device(&self.device)?)?, tracker: None, detector: None }) + let side = vit::GRID; + { + let mut accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(a) = accel.as_ref() { + let px = pixels.to_device(&Device::Cpu)?.flatten_all()?.to_vec1::()?; + // what the necks can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let want = vit::HIDDEN * side * side; + let checked = a.forward(&px).and_then(|out| { + if out.len() != want { + Err(format!("it returned {} values instead of {want}", out.len())) + } else if out.iter().any(|v| !v.is_finite()) { + Err("it returned values that are not numbers".into()) + } else { + Ok(out) + } + }); + match checked { + Ok(out) => { + let backbone = Tensor::from_vec(out, (1, vit::HIDDEN, side, side), &self.device)?; + return Ok(Encoded { backbone, tracker: None, detector: None }); + } + Err(e) if a.closing() => return Err(Error::Model(e)), + Err(e) => { + log::warn!("SAM 3 backbone failed on {} ({e}); using the {} from now on", a.device(), device_name(&self.device)); + *self.fallback.lock().unwrap_or_else(PoisonError::into_inner) = Some(format!("{} failed: {e}", a.device())); + *accel = None; + } + } + } + } + let backbone = self.candle_backbone()?.forward(&pixels.to_device(&self.device)?)?; + Ok(Encoded { backbone, tracker: None, detector: None }) } - fn tracker_parts(&mut self) -> Result<(&neck::Neck, &tracker::Tracker)> { - if self.tracker_neck.is_none() { - self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + /// The `n` finest levels of the `which` neck for `backbone`, computed by the accelerator and put on the model's + /// device; `None` when there is no accelerator, it doesn't run this neck or failed on it (logged once; candle + /// runs that neck from then on). `Err` when the app is closing. + fn accel_neck(&self, which: NeckKind, backbone: &Tensor, n: usize) -> Result>> { + let accel = self.accel.lock().unwrap_or_else(PoisonError::into_inner); + // an accelerator for the backbone only: the necks run in candle, and that is no failure + let Some(a) = accel.as_ref().filter(|a| a.runs_necks()) else { return Ok(None) }; + let mut off = self.necks_off.lock().unwrap_or_else(PoisonError::into_inner); + if off.contains(&which) { + return Ok(None); } + let run = || -> std::result::Result, String> { + let x = backbone.to_device(&Device::Cpu).and_then(|t| t.flatten_all()).and_then(|t| t.to_vec1::()).map_err(|e| e.to_string())?; + let levels = a.neck(which, &x, n)?; + if levels.len() != n { + return Err(format!("it returned {} levels instead of {n}", levels.len())); + } + levels + .into_iter() + .enumerate() + .map(|(i, l)| { + // what the heads can't use is a failure too: a wrong size, or NaN / ∞ from a broken kernel + let side = tracker::LOW_RES >> i; + if l.len() != neck::FPN * side * side { + return Err(format!("it returned {} values for level {i} instead of {}", l.len(), neck::FPN * side * side)); + } + // without short-cutting, so that it vectorizes (28 M values) + if !l.iter().fold(true, |ok, v| ok & v.is_finite()) { + return Err("it returned values that are not numbers".into()); + } + Tensor::from_vec(l, (1, neck::FPN, side, side), &self.device).map_err(|e| e.to_string()) + }) + .collect() + }; + match run() { + Ok(levels) => Ok(Some(levels)), + Err(e) if a.closing() => Err(Error::Model(e)), + Err(e) => { + let name = match which { + NeckKind::Tracker => "tracker", + NeckKind::Detector => "detector", + }; + log::warn!("SAM 3 {name} neck failed on {} ({e}); using the {} for it from now on", a.device(), device_name(&self.device)); + off.push(which); + Ok(None) + } + } + } + + fn tracker(&mut self) -> Result<&tracker::Tracker> { if self.tracker.is_none() { self.tracker = Some(tracker::Tracker::new(Self::vb(&self.weights, &self.device).pp("tracker_model"))?); } - match (&self.tracker_neck, &self.tracker) { - (Some(n), Some(t)) => Ok((n, t)), - _ => Err(Error::Model("tracker failed to load".into())), + self.tracker.as_ref().ok_or_else(|| Error::Model("tracker failed to load".into())) + } + + /// The click decoder's features for `enc`, once: the tracker neck on the accelerator when it runs it, else in + /// candle. + fn tracker_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.tracker.is_some() { + return Ok(()); } + let levels = match self.accel_neck(NeckKind::Tracker, &enc.backbone, 3)? { + Some(levels) => levels, + None => { + if self.tracker_neck.is_none() { + self.tracker_neck = Some(neck::Neck::new(Self::vb(&self.weights, &self.device).pp("tracker_neck"))?); + } + let neck = self.tracker_neck.as_ref().ok_or_else(|| Error::Model("tracker neck failed to load".into()))?; + neck.forward(&enc.backbone, 3)? + } + }; + enc.tracker = Some(self.tracker()?.features(&levels)?); + Ok(()) + } + + /// The `which` neck's three finest levels for `enc`, each `[1, 256, s, s]` (tests and tools): on the + /// accelerator when it runs it, else in candle. + pub fn neck_levels(&self, which: NeckKind, enc: &Encoded) -> Result> { + if let Some(levels) = self.accel_neck(which, &enc.backbone, 3)? { + return Ok(levels); + } + let prefix = match which { + NeckKind::Tracker => "tracker_neck", + NeckKind::Detector => "detector_model.vision_encoder.neck", + }; + neck::Neck::new(Self::vb(&self.weights, &self.device).pp(prefix))?.forward(&enc.backbone, 3) } /// Compute the click decoder's features for `enc` now (so the first click is fast). pub fn prepare_clicks(&mut self, enc: &mut Encoded) -> Result<()> { - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } - Ok(()) + self.tracker()?; + self.tracker_features(enc) } /// Segment one object from clicks (positions normalized to the image, 0..1). @@ -202,18 +552,15 @@ impl Sam3 { if clicks.is_empty() { return Err(Error::Model("no clicks".into())); } - let (neck, tracker) = self.tracker_parts()?; - if enc.tracker.is_none() { - let levels = neck.forward(&enc.backbone, 3)?; - enc.tracker = Some(tracker.features(&levels)?); - } + self.tracker_features(enc)?; + let tracker = self.tracker()?; let f = enc.tracker.as_ref().ok_or_else(|| Error::Model("tracker features".into()))?; // one click: SAM's three alternatives, best by predicted IoU; more: the single mask let p = tracker.predict(f, clicks, clicks.len() == 1)?; Ok(Prediction { logits: p.logits, score: p.iou * sigmoid(p.object_score) }) } - fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer)> { + fn detector_parts(&mut self) -> Result<(&detector::Detector, &tokenizer::Tokenizer, detector::EncoderAccel<'_>)> { if self.detector.is_none() { self.detector = Some(detector::Detector::new(Self::vb(&self.weights, &self.device).pp("detector_model"))?); } @@ -221,34 +568,42 @@ impl Sam3 { self.tokenizer = Some(tokenizer::Tokenizer::load(&self.dir)?); } match (&self.detector, &self.tokenizer) { - (Some(d), Some(t)) => Ok((d, t)), + (Some(d), Some(t)) => { + Ok((d, t, detector::EncoderAccel { accel: &self.accel, failed: &self.detr_fallback, masks_failed: &self.mask_fallback })) + } _ => Err(Error::Model("detector failed to load".into())), } } + /// The detector's features for `enc`, once: its neck on the accelerator when it runs it, else in candle. + fn detector_features(&mut self, enc: &mut Encoded) -> Result<()> { + if enc.detector.is_none() { + let levels = self.accel_neck(NeckKind::Detector, &enc.backbone, 3)?; + let (det, _, _) = self.detector_parts()?; + enc.detector = Some(det.features(&enc.backbone, levels)?); + } + Ok(()) + } + /// Segment every instance of the concept `text` names. Instances scoring above /// `threshold` (0..1, 0.5 is the reference default) are merged into one mask; `None` when /// nothing matches. pub fn segment_text(&mut self, enc: &mut Encoded, text: &str, threshold: f32) -> Result> { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - let out = det.predict(f, &ids, &valid)?; + let out = det.predict(f, &ids, &valid, &accel)?; Ok(detector::merge(&out, threshold)) } /// Raw detector outputs for `text` (tests and tools). pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result { - let (det, tok) = self.detector_parts()?; - if enc.detector.is_none() { - enc.detector = Some(det.features(&enc.backbone)?); - } + self.detector_features(enc)?; + let (det, tok, accel) = self.detector_parts()?; let f = enc.detector.as_ref().ok_or_else(|| Error::Model("detector features".into()))?; let (ids, valid) = tok.encode(text); - det.predict(f, &ids, &valid) + det.predict(f, &ids, &valid, &accel) } } @@ -260,6 +615,16 @@ impl Encoded { } } +#[cfg(not(target_arch = "wasm32"))] +/// A candle device as people call it ("CPU", "Metal GPU"). +pub fn device_name(device: &Device) -> String { + match device { + Device::Cpu => "CPU".into(), + Device::Metal(_) => "Metal GPU".into(), + Device::Cuda(_) => "CUDA GPU".into(), + } +} + #[cfg(not(target_arch = "wasm32"))] fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) @@ -273,3 +638,193 @@ pub use detector::Output as DetectorOutput; pub fn sync(model: &Sam3) -> Result<()> { Ok(model.device.synchronize()?) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// A model folder whose checkpoint holds no tensors: enough to load with an accelerator, never to run candle. + #[allow(clippy::unwrap_used)] + fn empty_model(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-sam3-{name}-{}", 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(WEIGHTS_FILE), st).unwrap(); + std::fs::write(dir.join("vocab.json"), "{}").unwrap(); + std::fs::write(dir.join("merges.txt"), "").unwrap(); + dir + } + + /// Answers with `values` backbone values, all `fill`, or fails. + struct Fake { + values: usize, + fill: f32, + fail: bool, + } + + impl BackboneAccel for Fake { + fn forward(&self, pixels: &[f32]) -> std::result::Result, String> { + assert_eq!(pixels.len(), 3 * INPUT * INPUT); + if self.fail { Err("device lost".into()) } else { Ok(vec![self.fill; self.values]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + } + + const FULL: usize = vit::HIDDEN * vit::GRID * vit::GRID; + + fn with(fake: Fake) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(fake)) + } + + #[test] + fn the_backbone_runs_on_the_accelerator_without_loading_candle() { + let dir = empty_model("accel"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(Fake { values: FULL, fill: 0.25, fail: false })).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Fake GPU (Vulkan)"); + assert_eq!(m.backbone_fallback(), None); + // an accelerator for the backbone only: the rest is candle's + assert_eq!(m.heads_device(), "CPU"); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(enc.backbone().dims(), [1, vit::HIDDEN, vit::GRID, vit::GRID]); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn an_accelerator_that_cannot_be_built_leaves_the_backbone_to_candle() { + let dir = empty_model("nomake"); + // the empty checkpoint has no candle backbone: the load fails, but only after trying it + let r = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no adapter".into())); + assert!(r.is_err_and(|e| !e.to_string().contains("no adapter"))); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// A backbone of `fill`, and neck levels of the right sizes (filled with their index) for the tracker; for the + /// detector the third level is cut short (`short`) or holds a NaN. + struct NeckFake { + calls: Arc, + short: bool, + } + + impl BackboneAccel for NeckFake { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + Ok(vec![0.5; FULL]) + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> std::result::Result>, String> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!((backbone.len(), backbone[0]), (FULL, 0.5)); + let mut levels: Vec> = (0..n).map(|i| vec![i as f32; neck::FPN * (tracker::LOW_RES >> i).pow(2)]).collect(); + if which == NeckKind::Detector { + if self.short { + levels[2].pop(); + } else { + levels[2][7] = f32::NAN; + } + } + Ok(levels) + } + } + + #[test] + fn neck_levels_come_from_the_accelerator_and_a_failing_neck_is_left_to_candle() { + for short in [true, false] { + let dir = empty_model(&format!("neck-{short}")); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let fake = NeckFake { calls: calls.clone(), short }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, move |_| Ok(Box::new(fake))).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + let levels = m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().unwrap(); + for (i, (l, side)) in levels.iter().zip([288, 144, 72]).enumerate() { + assert_eq!(l.dims(), [1, neck::FPN, side, side]); + assert_eq!(l.flatten_all().unwrap().max(0).unwrap().to_scalar::().unwrap(), i as f32); + } + // a wrong level: candle's neck from then on, without asking again + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert!(m.accel_neck(NeckKind::Detector, enc.backbone(), 3).unwrap().is_none()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(m.heads_device(), "CPU; the click neck on the GPU"); + // the other neck and the backbone stay on the accelerator + assert!(m.accel_neck(NeckKind::Tracker, enc.backbone(), 3).unwrap().is_some()); + assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 3); + assert!(m.accelerated()); + std::fs::remove_dir_all(dir).unwrap(); + } + } + + /// Fails as the GPU does once the app is closing (the backbone or, with a backbone of zeros, a neck). + struct Closing { + backbone: bool, + } + + impl BackboneAccel for Closing { + fn forward(&self, _: &[f32]) -> std::result::Result, String> { + if self.backbone { Err("LightCraft is closing".into()) } else { Ok(vec![0.0; FULL]) } + } + fn device(&self) -> String { + "Fake GPU (Vulkan)".into() + } + fn closing(&self) -> bool { + true + } + fn runs_necks(&self) -> bool { + true + } + fn neck(&self, _: NeckKind, _: &[f32], _: usize) -> std::result::Result>, String> { + Err("LightCraft is closing".into()) + } + } + + #[test] + fn closing_is_no_accelerator_failure_and_nothing_runs_in_candle() { + let dir = empty_model("closing"); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(true)).unwrap(); + let e = m.encode(&[128; 4 * 3 * 3], 4, 3).err().unwrap(); + assert!(e.to_string().contains("LightCraft is closing"), "{e}"); + assert!(m.backbone.get().is_none(), "the candle backbone was never loaded"); + assert!(m.accelerated()); + assert_eq!((m.backbone_device().as_str(), m.backbone_fallback()), ("Fake GPU (Vulkan)", None)); + // a neck: the error, not candle's neck, and the accelerator keeps it + let m = Sam3::load_accelerated(&dir, Device::Cpu, with_closing(false)).unwrap(); + let enc = m.encode(&[128; 4 * 3 * 3], 4, 3).unwrap(); + for which in [NeckKind::Tracker, NeckKind::Detector] { + assert!(m.accel_neck(which, enc.backbone(), 3).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + assert!(m.neck_levels(which, &enc).is_err_and(|e| e.to_string().contains("closing")), "{which:?}"); + } + assert_eq!(m.heads_device(), "CPU; the necks on the GPU"); + std::fs::remove_dir_all(dir).unwrap(); + } + + fn with_closing(backbone: bool) -> impl FnOnce(&WeightReader) -> std::result::Result, String> { + move |_| Ok(Box::new(Closing { backbone })) + } + + #[test] + fn a_failing_or_wrong_accelerator_is_dropped_for_candle() { + for (name, fake, why) in [ + ("fail", Fake { values: FULL, fill: 0.0, fail: true }, "device lost"), + ("short", Fake { values: 10, fill: 0.0, fail: false }, "returned 10 values"), + ("nan", Fake { values: FULL, fill: f32::NAN, fail: false }, "not numbers"), + ] { + let dir = empty_model(name); + let m = Sam3::load_accelerated(&dir, Device::Cpu, with(fake)).unwrap(); + // the candle backbone takes over (and fails here: the checkpoint is empty) + assert!(m.encode(&[128; 4 * 3 * 3], 4, 3).is_err(), "{name}"); + assert!(!m.accelerated(), "{name}"); + assert_eq!(m.backbone_device(), "CPU", "{name}"); + let fallback = m.backbone_fallback().unwrap(); + assert!(fallback.starts_with("Fake GPU (Vulkan) failed: ") && fallback.contains(why), "{name}: {fallback}"); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} diff --git a/crates/segment/src/nn.rs b/crates/segment/src/nn.rs index 540196e5d8..3666d8c411 100644 --- a/crates/segment/src/nn.rs +++ b/crates/segment/src/nn.rs @@ -7,7 +7,7 @@ use candle_core::{D, DType, Device, Module, Tensor}; use candle_nn::{LayerNorm, Linear, VarBuilder}; -use crate::Result; +use crate::{Result, cpu}; /// `nn.LayerNorm(d)` (PyTorch's default eps). pub const TORCH_LN_EPS: f64 = 1e-5; @@ -149,15 +149,25 @@ impl DecoderMlp { Ok(Self { layers }) } + /// On the CPU the hidden layers' bias add and ReLU are fused ([`cpu::linear_act`]: the box bias's MLPs have + /// 200 · 72 rows of 256). pub fn forward(&self, x: &Tensor) -> Result { + let mut dims = x.dims().to_vec(); let mut x = x.clone(); for (i, l) in self.layers.iter().enumerate() { - x = l.forward(&x)?; - if i + 1 < self.layers.len() { - x = x.relu()?; - } + x = if i + 1 == self.layers.len() { + l.forward(&x)? + } else if x.device().is_cpu() { + cpu::linear_act(&x, l, false)? + } else { + l.forward(&x)?.relu()? + }; } - Ok(x) + // the fused layers return rows + if let Some(last) = dims.last_mut() { + *last = x.dim(D::Minus1)?; + } + Ok(x.reshape(dims)?) } } @@ -240,3 +250,29 @@ pub fn cxcywh_to_xyxy(b: &Tensor) -> Result { pub fn to_vec(t: &Tensor) -> Result> { Ok(t.to_dtype(DType::F32)?.flatten_all()?.to_vec1::()?) } + +#[cfg(test)] +mod tests { + use candle_core::{DType, Device}; + use candle_nn::VarMap; + + use super::*; + + #[test] + fn a_decoder_mlp_over_rows_matches_linear_per_batch() { + let vars = VarMap::new(); + let vb = VarBuilder::from_varmap(&vars, DType::F32, &Device::Cpu); + let mlp = DecoderMlp::new(2, 256, 8, 2, vb).unwrap(); + let x = Tensor::randn(0f32, 1.0, (200, 72, 2), &Device::Cpu).unwrap(); + let mut want = x.clone(); + for (i, l) in mlp.layers.iter().enumerate() { + want = l.forward(&want).unwrap(); + if i + 1 < mlp.layers.len() { + want = want.relu().unwrap(); + } + } + let got = mlp.forward(&x).unwrap(); + assert_eq!(got.dims(), [200, 72, 8]); + assert_eq!(got.flatten_all().unwrap().to_vec1::().unwrap(), want.flatten_all().unwrap().to_vec1::().unwrap()); + } +} diff --git a/crates/segment/tests/it/accel.rs b/crates/segment/tests/it/accel.rs new file mode 100644 index 0000000000..ad8dad3c11 --- /dev/null +++ b/crates/segment/tests/it/accel.rs @@ -0,0 +1,58 @@ +//! A backbone accelerator that fails leaves the work to candle, with the real checkpoint. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. Runs the candle backbone once on the CPU (about half a minute in release). + +use std::path::PathBuf; + +use lightcraft_segment::{BackboneAccel, Device, Sam3, WeightReader}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// Fails on every photo, as a GPU that lost its device would. +struct Lost; + +impl BackboneAccel for Lost { + fn forward(&self, _: &[f32]) -> Result, String> { + Err("device lost".into()) + } + fn device(&self) -> String { + "Lost GPU (Vulkan)".into() + } +} + +#[test] +fn an_accelerator_failing_on_a_photo_falls_back_to_candle() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_: &WeightReader| Ok(Box::new(Lost) as Box)).unwrap(); + assert!(m.accelerated()); + assert_eq!(m.backbone_device(), "Lost GPU (Vulkan)"); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let enc = m.encode(&rgb, w, h).unwrap(); + assert_eq!(enc.backbone().dims(), [1, 1024, 72, 72]); + let v = enc.backbone().flatten_all().unwrap().to_vec1::().unwrap(); + assert!(v.iter().all(|x| x.is_finite()) && v.iter().any(|x| *x != 0.0), "candle computed the features"); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("Lost GPU (Vulkan) failed: device lost")); +} + +#[test] +fn an_accelerator_that_cannot_be_built_loads_candles_backbone() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Err("no GPU adapter".into())).unwrap(); + assert!(!m.accelerated()); + assert_eq!(m.backbone_device(), "CPU"); + assert_eq!(m.backbone_fallback().as_deref(), Some("no GPU adapter")); +} diff --git a/crates/segment/tests/it/main.rs b/crates/segment/tests/it/main.rs index 4dcb685916..629ae5f085 100644 --- a/crates/segment/tests/it/main.rs +++ b/crates/segment/tests/it/main.rs @@ -1,4 +1,6 @@ //! The integration tests, one module per file, linked into one test binary. +mod accel; +mod prompts; mod reference; mod remote; diff --git a/crates/segment/tests/it/prompts.rs b/crates/segment/tests/it/prompts.rs new file mode 100644 index 0000000000..1ff14679e8 --- /dev/null +++ b/crates/segment/tests/it/prompts.rs @@ -0,0 +1,63 @@ +//! A text prompt seen before reuses its features, with the same detector output as the first time. +//! +//! Needs the model: `$LIGHTCRAFT_SAM3_DIR`, else the desktop app's folder (`~/.config/lightcraft/models/sam3` on +//! Linux). Skipped when it is missing. The backbone output is made up (no ViT run); the necks, the text encoder +//! and the detector are candle's on the CPU. + +use std::path::PathBuf; + +use candle_core::Tensor; +use lightcraft_segment::{BackboneAccel, DetectorOutput, Device, Sam3}; + +fn model_dir() -> Option { + // only `$LIGHTCRAFT_SAM3_DIR`, as the GPU tests: never whatever is in the user's model folder + let dir = std::env::var_os("LIGHTCRAFT_SAM3_DIR").filter(|v| !v.is_empty()).map(PathBuf::from)?; + lightcraft_segment::is_model_dir(&dir).then_some(dir) +} + +/// A backbone output `[1024, 72, 72]` that varies over the channels and the grid. +struct Waves; + +impl BackboneAccel for Waves { + fn forward(&self, _: &[f32]) -> Result, String> { + Ok((0..1024 * 72 * 72).map(|i| (i as f32 * 0.37).sin() * 0.5).collect()) + } + fn device(&self) -> String { + "Waves (test)".into() + } +} + +fn values(t: &Tensor) -> Vec { + t.flatten_all().unwrap().to_vec1().unwrap() +} + +fn assert_same(a: &DetectorOutput, b: &DetectorOutput) { + assert_eq!(a.logits, b.logits); + assert_eq!(a.presence, b.presence); + assert_eq!(a.boxes, b.boxes); + assert_eq!(values(&a.text), values(&b.text)); + assert_eq!(values(&a.memory), values(&b.memory)); + assert_eq!(values(&a.masks), values(&b.masks)); +} + +#[test] +fn a_repeated_prompt_gives_the_same_output() { + let Some(dir) = model_dir() else { + lightcraft_testkit::skip!(Model, "SAM 3 not installed (set LIGHTCRAFT_SAM3_DIR)"); + return; + }; + let mut m = Sam3::load_accelerated(&dir, Device::Cpu, |_| Ok(Box::new(Waves) as Box)).unwrap(); + let (w, h) = (64, 48); + let rgb: Vec = (0..w * h * 3).map(|i| (i % 251) as u8).collect(); + let mut enc = m.encode(&rgb, w, h).unwrap(); + let fresh = m.detect(&mut enc, "person").unwrap(); + m.detect(&mut enc, "sky").unwrap(); + let cached = m.detect(&mut enc, "person").unwrap(); + assert_eq!(cached.text.id(), fresh.text.id(), "the prompt's features were reused"); + assert_same(&cached, &fresh); + // and on the next photo + let mut next = m.encode(&rgb, w, h).unwrap(); + let again = m.detect(&mut next, "person").unwrap(); + assert_eq!(again.text.id(), fresh.text.id()); + assert_same(&again, &fresh); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 8a50d38f10..822688011d 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Procházení složek – složky: {folders}, soubory: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kodér obrazu {encoder:.1} s" } diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index e3a98569fd..84a3efb7b2 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2394,5 +2394,13 @@ "End Slideshow": "Ukončit prezentaci", "Save Current Settings as New Effect Preset…": "Uložit aktuální nastavení jako nové přednastavení efektu…", "Manage Effect Presets…": "Spravovat přednastavení efektů…", - "Export Effect Presets…": "Exportovat přednastavení efektů…" + "Export Effect Presets…": "Exportovat přednastavení efektů…", + "AI masks": "AI masky", + "Device": "Zařízení", + "Last photo": "Poslední fotka", + "Remote worker": "Vzdálený proces", + "Run on": "Spouštět na", + "Automatic (GPU when available)": "Automaticky (GPU, je-li k dispozici)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masky Objekt a Popsat analyzují každou fotku jednou, na grafické kartě, pokud není zvoleno CPU nebo vypnuto „Použít GPU pro vykreslování“. Na procesoru to trvá mnohem déle.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaticky spouští model na grafické kartě Macu. Pokud tam AI masky selhávají, zvolte CPU; na procesoru trvají mnohem déle." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index af29f7134e..109126c4de 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben", "Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?", "Listing folders — folders: {folders}, files: {files}": "Ordner werden aufgelistet – Ordner: {folders}, Dateien: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, Bildencoder {encoder:.1} s" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 67a305ddf5..4184b529f5 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3422,5 +3422,13 @@ "favourites across restarts (issue #328).": "über Neustarts hinweg Favoriten (Issue #328).", "Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Optionales entferntes SAM 3: Der native Editor bleibt lokal, und Objekt-, Beschreibungs- und Detail-", "inference on a Mac through SSH. Saved masks still render and export offline.": "Inferenz laufen über SSH auf einem Mac. Gespeicherte Masken werden weiterhin offline gerendert und exportiert.", - "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference)." + "See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference).", + "AI masks": "KI-Masken", + "Device": "Gerät", + "Last photo": "Letztes Foto", + "Remote worker": "Entfernter Worker", + "Run on": "Ausführen auf", + "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wählen Sie CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index fd15401693..55ac68506e 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”", "Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?", "Listing folders — folders: {folders}, files: {files}": "Listando carpetas — carpetas: {folders}, archivos: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagen {encoder:.1} s" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 46965c7782..9a6ae2b299 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2342,5 +2342,13 @@ "Checking the GPU…": "Comprobando la GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modelo de caras usa la GPU solo cuando una comprobación muestra que da los mismos resultados más rápido.", - "Checking the GPU for faces": "Comprobando la GPU para las caras" + "Checking the GPU for faces": "Comprobando la GPU para las caras", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Proceso remoto", + "Run on": "Ejecutar en", + "Automatic (GPU when available)": "Automático (GPU si la hay)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Las máscaras Objeto y Describir analizan cada foto una sola vez, en la tarjeta gráfica salvo que se elija CPU o «Usar la GPU para renderizar» esté desactivado. En el procesador tarda mucho más.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático ejecuta el modelo en la tarjeta gráfica del Mac. Elige CPU si las máscaras de IA fallan allí; en el procesador tardan mucho más." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 698080e10d..78025df6b5 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "”{to}” on jo henkilö. Yhdistäminen tekee kahdesta yhden henkilön; Kumoa erottaa ne uudelleen.", "• {assumption}": "• {assumption}", "… and {more} more": "… ja {more} lisää", - "…and {more} more": "…ja {more} lisää" + "…and {more} more": "…ja {more} lisää", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kuvakooderi {encoder:.1} s" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index ff1707ac7a..aadff2f442 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2311,5 +2311,13 @@ "− harder border · + softer border": "− terävämpi reuna · + pehmeämpi reuna", "≤ at most": "≤ enintään", "≥ at least": "≥ vähintään", - "★ Favorites": "★ Suosikit" + "★ Favorites": "★ Suosikit", + "AI masks": "Tekoälymaskit", + "Device": "Laite", + "Last photo": "Viimeisin kuva", + "Remote worker": "Etätyöskentelijä", + "Run on": "Suorita", + "Automatic (GPU when available)": "Automaattinen (GPU, jos saatavilla)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Kohde- ja Kuvaile-maskit analysoivat jokaisen kuvan kerran, näytönohjaimella, ellei Suoritin ole valittuna tai ”Käytä GPU:ta renderöintiin” ole pois päältä. Suorittimella se kestää paljon kauemmin.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automaattinen suorittaa mallin Macin näytönohjaimella. Valitse Suoritin, jos tekoälymaskit epäonnistuvat siellä; suorittimella ne kestävät paljon kauemmin." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index ae2b778725..566a24c37b 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »", "Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?", "Listing folders — folders: {folders}, files: {files}": "Liste des dossiers — dossiers : {folders}, fichiers : {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{} déplacée(s) vers « {} ». Modifier → Annuler les remet en place.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, encodeur d’image {encoder:.1} s" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 2f22a70c1c..47f2f6025f 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2340,5 +2340,13 @@ "Checking the GPU…": "Vérification du GPU…", "CPU": "Processeur", "A face model uses the GPU only when a check shows it gives the same results faster.": "Un modèle de visages n’utilise le GPU que si une vérification montre qu’il donne les mêmes résultats plus vite.", - "Checking the GPU for faces": "Vérification du GPU pour les visages" + "Checking the GPU for faces": "Vérification du GPU pour les visages", + "AI masks": "Masques IA", + "Device": "Appareil", + "Last photo": "Dernière photo", + "Remote worker": "Processus distant", + "Run on": "Exécuter sur", + "Automatic (GPU when available)": "Automatique (GPU si disponible)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Les masques Objet et Décrire analysent chaque photo une fois, sur la carte graphique sauf si Processeur est choisi ou si « Utiliser le GPU pour le rendu » est désactivé. Sur le processeur, c’est beaucoup plus long.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatique exécute le modèle sur la carte graphique du Mac. Choisissez Processeur si les masques IA y échouent ; sur le processeur, ils sont beaucoup plus longs." } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index b3887f9174..0072148c1f 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -297,5 +297,6 @@ "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}: resolusi penuhnya ({full}) memerlukan memori melebihi kapasitas komputer ini", "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Hasil penggabungan {what} ditambahkan dengan resolusi {mp}, resolusi maksimum untuk panorama (resolusi penuhnya {full})", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} dtk, penyandi gambar {encoder:.1} dtk" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index aefe04417a..17d698afab 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2325,5 +2325,13 @@ "≤ at most": "≤ maksimal", "≥ at least": "≥ minimal", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "Masker AI", + "Device": "Perangkat", + "Last photo": "Foto terakhir", + "Remote worker": "Worker jarak jauh", + "Run on": "Jalankan di", + "Automatic (GPU when available)": "Otomatis (GPU jika tersedia)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Masker Objek dan Deskripsikan menganalisis setiap foto sekali, di kartu grafis kecuali CPU dipilih atau “Gunakan GPU untuk rendering” dimatikan. Di prosesor hal itu jauh lebih lama.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Otomatis menjalankan model di kartu grafis Mac. Pilih CPU jika masker AI gagal di sana; di prosesor prosesnya jauh lebih lama." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index ccd01e6a71..778c4568c9 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}", "Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Foto spostate in “{1}”: {n}{0:.0}. Modifica → Annulla le riporta indietro.", - "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}" + "Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificatore d’immagine {encoder:.1} s" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index a638c14820..00035165d4 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2344,7 +2344,14 @@ "Loupe Info 1": "Info lente 1", "Loupe Info 2": "Info lente 2", "Use Defaults": "Usa predefiniti", - "Dimensions": "Dimensioni", "Camera & Lens": "Fotocamera e obiettivo", - "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2." + "View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.", + "AI masks": "Maschere IA", + "Device": "Dispositivo", + "Last photo": "Ultima foto", + "Remote worker": "Processo remoto", + "Run on": "Esegui su", + "Automatic (GPU when available)": "Automatico (GPU se disponibile)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Le maschere Oggetto e Descrivi analizzano ogni foto una volta, sulla scheda grafica a meno che sia scelta la CPU o «Usa la GPU per il rendering» sia disattivato. Sul processore richiede molto più tempo.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatico esegue il modello sulla scheda grafica del Mac. Scegli CPU se lì le maschere IA non funzionano; sul processore richiedono molto più tempo." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index ce56500b5e..5f2e86b59b 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」はすでに別の人物です。まとめると1人になり、元に戻すと再び分かれます。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}合成を{mp}で追加しました:フルサイズ({full})にはこのコンピューターのメモリが足りません", "Listing folders — folders: {folders}, files: {files}": "フォルダーを一覧中 — フォルダー:{folders}、ファイル:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}合成を{mp}で追加しました。パノラマの最大サイズです(フルサイズ:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒(画像エンコーダー {encoder:.1} 秒)" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 4c55ee4947..794cc0539e 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2342,5 +2342,13 @@ "Checking the GPU…": "GPU を確認中…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "顔モデルが GPU を使うのは、同じ結果をより速く出せると確認できた場合だけです。", - "Checking the GPU for faces": "顔用の GPU を確認中" + "Checking the GPU for faces": "顔用の GPU を確認中", + "AI masks": "AIマスク", + "Device": "デバイス", + "Last photo": "直前の写真", + "Remote worker": "リモートワーカー", + "Run on": "実行先", + "Automatic (GPU when available)": "自動(GPUがあれば使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "オブジェクトと説明で選択のマスクは、写真ごとに一度だけ解析します。CPUを選んだ場合や「描画にGPUを使用」がオフの場合を除き、グラフィックカードで行います。処理装置ではかなり時間がかかります。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "自動ではMacのグラフィックカードでモデルを実行します。そこでAIマスクが失敗する場合はCPUを選んでください。処理装置ではかなり時間がかかります。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index c3b48ef626..5c6ea7c16a 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”", "Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?", "Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} წმ, გამოსახულების ენკოდერი {encoder:.1} წმ" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 066f2ecd25..190df90630 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -86,6 +86,7 @@ "AI Denoise needs a model. Install one in Settings.": "AI ხმაურის მოცილებას მოდელი სჭირდება. დააინსტალირეთ პარამეტრებში.", "AI Mask Model Status": "AI ნიღბების მოდელის მდგომარეობა", "AI RAW denoise": "RAW-ის AI ხმაურის მოცილება", + "AI masks": "AI ნიღბები", "AI masks with SAM 3 (Object and Describe in the Masking panel): click an object to select it (⌥-click leaves a": "AI ნიღბები SAM 3-ით (ობიექტი და აღწერა ნიღბვის პანელში): დაწკაპეთ ობიექტზე მის მოსანიშნად (⌥-დაწკაპუნება ტოვებს", "ARW) gives the merged DNG the colour each photo has when opened alone (issue #965). An HDR merge of CR2s used to come": "ARW) ფოტოების გაერთიანება გაერთიანებულ DNG-ს აძლევს იმ ფერს, რომელიც თითო ფოტოს ცალკე გახსნისას აქვს (ხარვეზი #965). CR2-ების HDR გაერთიანება ადრე", "About": "პროგრამის შესახებ", @@ -229,7 +230,9 @@ "Auto-Tag from Tracklog: GPS locations for your photos from a GPX track log, matched by capture time.": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან: GPS მდებარეობები თქვენი ფოტოებისთვის GPX მარშრუტის ჟურნალიდან, გადაღების დროის მიხედვით.", "Auto-Tag from Tracklog…": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან…", "Automatic": "ავტომატური", + "Automatic (GPU when available)": "ავტომატური (GPU, თუ არის)", "Automatic renders the Detail view at the size it is shown, up to the photo's own pixels. Choose a size to cap it: smaller is faster.": "ავტომატური რეჟიმი დეტალურ ხედს ასახავს იმ ზომით, რომლითაც ის ჩანს, ფოტოს საკუთარ პიქსელებამდე. ზღვრისთვის აირჩიეთ ზომა: პატარა უფრო სწრაფია.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "ავტომატური რეჟიმი მოდელს Mac-ის ვიდეობარათზე უშვებს. აირჩიეთ CPU, თუ AI ნიღბები იქ ვერ მუშაობს; პროცესორზე ისინი გაცილებით დიდხანს გრძელდება.", "Automatic uses the graphics card where it is faster than the processor: both are timed on this computer the first time a photo is made.": "ავტომატური რეჟიმი იყენებს ვიდეობარათს, როცა ის პროცესორზე სწრაფია: ორივეს დრო ამ კომპიუტერზე იზომება, როცა ფოტო პირველად მზადდება.", "Automatically Write Changes into XMP": "ცვლილებების XMP-ში ავტომატურად ჩაწერა", "Automatically write changes into XMP sidecars": "ცვლილებების XMP თანმხლებ ფაილებში ავტომატურად ჩაწერა", @@ -296,6 +299,7 @@ "By day (YYYY/YYYY-MM-DD)": "დღის მიხედვით (YYYY/YYYY-MM-DD)", "By month (YYYY/YYYY-MM)": "თვის მიხედვით (YYYY/YYYY-MM)", "C-RAWs imported earlier, Photo ▸ Reload from Disk picks up the raw data.": "R7 C-RAW-ებისთვის ფოტო → დისკიდან ხელახლა ჩატვირთვა RAW მონაცემებს წაიკითხავს.", + "CPU": "CPU", "CPU threads": "CPU ნაკადები", "Cache": "ქეში", "Calibration": "კალიბრაცია", @@ -597,6 +601,7 @@ "Detect Faces": "სახეების ამოცნობა", "Detect Faces (Photo menu) needs it: a small one-time download.": "სახეების ამოცნობას (მენიუ „ფოტო“) ეს სჭირდება: მცირე, ერთჯერადი ჩამოტვირთვა.", "Develop": "დამუშავება", + "Device": "მოწყობილობა", "Diagonal": "დიაგონალური", "Dialogs": "დიალოგები", "Dialogs fit the window": "დიალოგები ფანჯარაში ეტევა", @@ -1085,6 +1090,7 @@ "Last GPU fallback": "GPU-დან ბოლო გადართვა", "Last commit": "ბოლო კომიტი", "Last loupe render": "ლუპის ბოლო რენდერი", + "Last photo": "ბოლო ფოტო", "Last view": "ბოლო ხედი", "Lateral Chromatic Aberration": "განივი ქრომატული აბერაცია", "Layer": "შრე", @@ -1368,6 +1374,7 @@ "None": "არცერთი", "None (the display is treated as sRGB)": "არცერთი (ეკრანი sRGB-ად ითვლება)", "Not Now": "ახლა არა", + "Not loaded yet": "ჯერ არ ჩატვირთულა", "Not saved": "არ არის შენახული", "Nothing already edited changes: a Custom white balance set on the old relative scale renders pixel for pixel as": "არაფერი უკვე დამუშავებული არ იცვლება: ძველ ფარდობით შკალაზე დაყენებული მორგებული თეთრის ბალანსი პიქსელ-პიქსელ ისევე რენდერდება, როგორც", "Nothing is fetched until you accept. The model is kept on this computer only; LightCraft never uploads or shares it.": "თქვენს თანხმობამდე არაფერი ჩამოიტვირთება. მოდელი მხოლოდ ამ კომპიუტერზე ინახება; LightCraft მას არასოდეს ატვირთავს და არავის უზიარებს.", @@ -1378,6 +1385,7 @@ "ONNX model": "ONNX მოდელი", "Object": "ობიექტი", "Object Mask": "ობიექტის ნიღაბი", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "ობიექტისა და აღწერის ნიღბები თითო ფოტოს ერთხელ აანალიზებს, ვიდეობარათზე, თუ CPU არ არის არჩეული და „რენდერირებისთვის GPU-ის გამოყენება“ გამორთული არ არის. პროცესორზე ეს გაცილებით დიდხანს გრძელდება.", "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.": "ნიღბები „ობიექტი“ და „აღწერა“ იყენებს SAM 3-ს, Meta-ს სეგმენტაციის მოდელს. ის LightCraft-ის ნაწილი არ არის და ყველაფერი დანარჩენი მის გარეშეც მუშაობს.", "October 2026": "ოქტომბერი 2026", "Off": "გამორთული", @@ -1663,6 +1671,7 @@ "Relinked": "ხელახლა დაკავშირებულია", "Reload Changed Files": "შეცვლილი ფაილების ხელახლა ჩატვირთვა", "Reload from Disk": "დისკიდან ხელახლა ჩატვირთვა", + "Remote worker": "დისტანციური დამმუშავებელი", "Remove": "მოშორება", "Remove (H)": "მოშორება (H)", "Remove CA": "ქრომატული აბერაციის მოცილება", @@ -1766,6 +1775,7 @@ "Rule problems are shown in your language and name the field the way the menu does (\"Title: needs something to look": "წესების პრობლემები ნაჩვენებია თქვენს ენაზე და ველს ისე ასახელებს, როგორც მენიუ („დასახელება: საჭიროა საძიებო", "Rule values are checked: a rating of 9, a date like 2026-13 or \"banana\", a \"between\" whose dates are the wrong": "წესების მნიშვნელობები მოწმდება: შეფასება 9, თარიღი, როგორიცაა 2026-13 ან „banana“, „შორის“, რომლის თარიღებიც არასწორი", "Rules": "წესები", + "Run on": "გაშვება", "SAM 3 download stopped: it resumes where it left off next time.": "SAM 3-ის ჩამოტვირთვა შეწყდა: შემდეგ ჯერზე იქიდან გაგრძელდება, სადაც შეჩერდა.", "SDR": "SDR", "SDR Brightness": "SDR სიკაშკაშე", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index e3ce316a0d..7791c4f840 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Przeglądanie folderów — foldery: {folders}, pliki: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, koder obrazu {encoder:.1} s" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index aba88ef445..dad3624832 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2269,5 +2269,15 @@ "SDR Shadows": "Cienie SDR", "SDR Whites": "Biele SDR", "SDR Clarity": "Przejrzystość SDR", - "Face Models on the GPU": "Modele twarzy przetwarzane na GPU" + "Face Models on the GPU": "Modele twarzy przetwarzane na GPU", + "AI masks": "Maski AI", + "Device": "Urządzenie", + "Last photo": "Ostatnie zdjęcie", + "Remote worker": "Zdalny proces", + "Not loaded yet": "Jeszcze nie wczytano", + "Run on": "Uruchamiaj na", + "Automatic (GPU when available)": "Automatycznie (GPU, gdy jest)", + "CPU": "CPU", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Maski Obiekt i Opisz analizują każde zdjęcie raz, na karcie graficznej, chyba że wybrano CPU albo opcja „Użyj procesora graficznego do renderowania” jest wyłączona. Na procesorze trwa to znacznie dłużej.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatycznie uruchamia model na karcie graficznej Maca. Wybierz CPU, jeśli maski AI tam zawodzą; na procesorze trwa to znacznie dłużej." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index bab81a3688..facb052cb1 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” já é uma pessoa. Combiná-las deixa uma só; Desfazer as separa de novo.", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} mesclagem adicionada em {mp}: o tamanho completo, {full}, precisa de mais memória do que este computador tem", "Listing folders — folders: {folders}, files: {files}": "Listando pastas — pastas: {folders}, arquivos: {files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} mesclagem adicionada em {mp}, o maior tamanho possível para um panorama (tamanho completo: {full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagem {encoder:.1} s" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 5b4ae44096..e6e41243ac 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2188,5 +2188,13 @@ "Color Overlay on B&W": "Sobreposição de cor em P&B", "Image on Black": "Imagem sobre preto", "Image on White": "Imagem sobre branco", - "White on Black": "Branco sobre preto" + "White on Black": "Branco sobre preto", + "AI masks": "Máscaras de IA", + "Device": "Dispositivo", + "Last photo": "Última foto", + "Remote worker": "Processo remoto", + "Run on": "Executar em", + "Automatic (GPU when available)": "Automático (GPU quando houver)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "As máscaras Objeto e Descrever analisam cada foto uma vez, na placa de vídeo, a menos que CPU esteja escolhida ou “Usar a GPU para renderização” esteja desligado. No processador isso demora muito mais.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automático executa o modelo na placa de vídeo do Mac. Escolha CPU se as máscaras de IA falharem nela; no processador elas demoram muito mais." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 1efc30268e..2299b498ad 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Просмотр папок — папок: {folders}, файлов: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодировщик изображения {encoder:.1} с" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index bf191bb515..744bc0ce55 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2335,5 +2335,13 @@ "Checking the GPU…": "Проверка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель лиц использует ГП, только если проверка показала, что он даёт те же результаты быстрее.", - "Checking the GPU for faces": "Проверка ГП для лиц" + "Checking the GPU for faces": "Проверка ГП для лиц", + "AI masks": "ИИ-маски", + "Device": "Устройство", + "Last photo": "Последнее фото", + "Remote worker": "Удалённый обработчик", + "Run on": "Выполнять на", + "Automatic (GPU when available)": "Автоматически (GPU, если есть)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Объект» и «Описать» анализируют каждое фото один раз — на видеокарте, если не выбран ЦП и не выключено «Использовать GPU для рендеринга». На процессоре это намного дольше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматически» запускает модель на видеокарте Mac. Если ИИ-маски там не работают, выберите ЦП; на процессоре они намного дольше." } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 50e3fa4be0..ca8350cc57 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -297,5 +297,6 @@ "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.", "{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.", - "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}" + "Listing folders — folders: {folders}, files: {files}": "Listing folders — folders: {folders}, files: {files}", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, bildkodare {encoder:.1} s" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 76f08c2d38..00bcb9f599 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2414,5 +2414,13 @@ "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", "★ Favorites": "★ Favoriter", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "AI-masker", + "Device": "Enhet", + "Last photo": "Senaste foto", + "Remote worker": "Fjärrarbetare", + "Run on": "Kör på", + "Automatic (GPU when available)": "Automatisk (GPU när den finns)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- och Beskriv-masker analyserar varje foto en gång, på grafikkortet om inte CPU är vald eller ”Använd GPU:n för rendering” är av. På processorn tar det mycket längre tid.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisk kör modellen på Macens grafikkort. Välj CPU om AI-masker misslyckas där; på processorn tar de mycket längre tid." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 0ada44e080..f960122d27 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -297,5 +297,6 @@ "Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}", "Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?", "Listing folders — folders: {folders}, files: {files}": "Перегляд тек — тек: {folders}, файлів: {files}", - "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх." + "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх.", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодувальник зображення {encoder:.1} с" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 4dff39f784..0628803bcd 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2340,5 +2340,13 @@ "Checking the GPU…": "Перевірка ГП…", "CPU": "ЦП", "A face model uses the GPU only when a check shows it gives the same results faster.": "Модель облич використовує ГП, лише якщо перевірка показала, що він дає ті самі результати швидше.", - "Checking the GPU for faces": "Перевірка ГП для облич" + "Checking the GPU for faces": "Перевірка ГП для облич", + "AI masks": "ШІ-маски", + "Device": "Пристрій", + "Last photo": "Останнє фото", + "Remote worker": "Віддалений обробник", + "Run on": "Виконувати на", + "Automatic (GPU when available)": "Автоматично (ГП, якщо є)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Маски «Об’єкт» і «Описати» аналізують кожне фото один раз — на відеокарті, якщо не вибрано ЦП і не вимкнено «Використовувати ГП для рендерингу». На процесорі це значно довше.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "«Автоматично» запускає модель на відеокарті Mac. Якщо ШІ-маски там не працюють, виберіть ЦП; на процесорі вони значно довші." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index 9ff8ed6b99..c627d80df2 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}” is already a person. Combining them makes one person; Undo separates them again.", "• {assumption}": "• {assumption}", "… and {more} more": "… và {more} nữa", - "…and {more} more": "…and {more} more" + "…and {more} more": "…và {more} nữa", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} giây, bộ mã hóa ảnh {encoder:.1} giây" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index 6908be70e1..d752190a82 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2220,5 +2220,13 @@ "≥ at least": "≥ tối thiểu", "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.", "日本語": "日本語", - "繁體中文(台灣)": "繁體中文(台灣)" + "繁體中文(台灣)": "繁體中文(台灣)", + "AI masks": "Mặt nạ AI", + "Device": "Thiết bị", + "Last photo": "Ảnh gần nhất", + "Remote worker": "Worker từ xa", + "Run on": "Chạy trên", + "Automatic (GPU when available)": "Tự động (GPU nếu có)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Mặt nạ Đối tượng và Mô tả phân tích mỗi ảnh một lần, trên card đồ họa trừ khi chọn CPU hoặc tắt “Dùng GPU để kết xuất”. Trên bộ xử lý việc này lâu hơn nhiều.", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Tự động chạy mô hình trên card đồ họa của máy Mac. Hãy chọn CPU nếu mặt nạ AI bị lỗi ở đó; trên bộ xử lý chúng chạy lâu hơn nhiều." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index a28b07d2c8..e6688a8fb7 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "“{to}”已经是另一个人。合并后成为一个人;撤销会再把他们分开。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已添加 {what} 合并({mp}):完整尺寸({full})所需的内存超出了这台电脑的内存", "Listing folders — folders: {folders}, files: {files}": "正在列出文件夹 — 文件夹:{folders},文件:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已添加 {what} 合并({mp}),这是全景图的最大尺寸(完整尺寸:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,图像编码器 {encoder:.1} 秒" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 4a2ebaa7b1..633147d336 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2186,5 +2186,13 @@ "Suggests who is in a photo from the faces you have named. Everything stays on your computer.": "根据你已命名的人脸,推测照片中的人物。所有数据仅保存在本机。", "This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。", "Detect Faces (Photo menu) needs it: a small one-time download.": "“检测人脸”(照片菜单)依赖它:一次性小文件下载。", - "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)" + "This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)", + "AI masks": "AI 蒙版", + "Device": "设备", + "Last photo": "上一张照片", + "Remote worker": "远程工作进程", + "Run on": "运行位置", + "Automatic (GPU when available)": "自动(有 GPU 时使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "“对象”和“描述”蒙版对每张照片只分析一次;除非选择了 CPU 或关闭了“使用 GPU 渲染”,否则在显卡上进行。在处理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "“自动”会在 Mac 的显卡上运行模型。如果 AI 蒙版在那里失败,请选择 CPU;在处理器上会慢得多。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 1192722251..7eca03bbd6 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -297,5 +297,6 @@ "“{to}” is already a person. Combining them makes one person; Undo separates them again.": "「{to}」已經是另一個人。合併後成為一個人;還原會再把他們分開。", "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "已新增{what}合併照片({mp}):完整尺寸({full})所需的記憶體超過這台電腦的記憶體", "Listing folders — folders: {folders}, files: {files}": "正在列出資料夾 — 資料夾:{folders},檔案:{files}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})" + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "已新增{what}合併照片({mp}),這是全景圖的最大尺寸(完整尺寸:{full})", + "{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,影像編碼器 {encoder:.1} 秒" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 78d8851285..961d83505e 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2143,5 +2143,13 @@ "Checking the GPU…": "正在檢查 GPU…", "CPU": "CPU", "A face model uses the GPU only when a check shows it gives the same results faster.": "只有在檢查顯示 GPU 能更快得出相同結果時,臉孔模型才會使用 GPU。", - "Checking the GPU for faces": "正在檢查用於臉孔的 GPU" + "Checking the GPU for faces": "正在檢查用於臉孔的 GPU", + "AI masks": "AI 遮色片", + "Device": "裝置", + "Last photo": "上一張照片", + "Remote worker": "遠端工作程序", + "Run on": "執行位置", + "Automatic (GPU when available)": "自動(有 GPU 時使用)", + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "「物件」和「描述」遮色片對每張照片只分析一次;除非選擇了 CPU 或關閉了「使用 GPU 算繪」,否則在顯示卡上進行。在處理器上分析要慢得多。", + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "「自動」會在 Mac 的顯示卡上執行模型。如果 AI 遮色片在那裡失敗,請選擇 CPU;在處理器上會慢得多。" } diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index 2f844f4ae9..66df3e719b 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -1,5 +1,5 @@ -//! The Settings dialog (⌘,): General, Import, Performance, Display, Interface, Slideshow, Faces, -//! AI Denoise. +//! The Settings dialog (⌘,): General, Import, Performance (incl. where AI masks run), Display, +//! Interface, Slideshow, Faces, AI Denoise. //! //! Changes apply immediately (no OK/Cancel). Where they are stored: //! - **app settings** ([`crate::state::AppSettings`]: startup view, delete confirmation, GPU, @@ -485,6 +485,59 @@ fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ); #[cfg(not(target_arch = "wasm32"))] smart_previews(app, ui, t); + ai_masks(app, ui, t); +} + +/// Where AI masks (SAM 3) run: the choice (`segment.settings {runOn}`), what they run on, why not on +/// the GPU, and how long the last photo took (`segment.model.status` → `backend`), as Settings ▸ +/// Faces shows its models' processor. The same lines whatever the state, so nothing moves when the +/// model loads. +fn ai_masks(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + return; + } + heading(ui, t, crate::i18n::tr("AI masks")); + let current = app.session.segmenter.run_on().name(); + let mut run_on = current; + if row(ui, t, "Run on", |ui| choices(ui, "settingsAiMasksRunOn", &[("auto", "Automatic (GPU when available)"), ("cpu", "CPU")], &mut run_on)) + && let Err(e) = app.run("segment.settings", json!({"runOn": run_on})) + { + app.toast(ui.ctx(), e); + } + let g = &app.session.segmenter; + let b = g.backend(); + let device = if g.remote_endpoint().is_some() { + crate::i18n::tr("Remote worker").to_string() + } else { + b["device"].as_str().map_or_else(|| crate::i18n::tr("Not loaded yet").to_string(), str::to_string) + }; + let text = match b["fallback"].as_str() { + Some(why) if g.remote_endpoint().is_none() => format!("{device} ({why})"), + _ => device, + }; + row(ui, t, "Device", |ui| { + let r = ui.add(egui::Label::new(RichText::new(text.clone()).color(t.text)).truncate()).on_hover_text(text); + register(ui.ctx(), "settings:aiMasksDevice", r.rect); + }); + let took = match (b["analyzeMs"].as_u64().or(b["encodeMs"].as_u64()), b["encodeMs"].as_u64()) { + (Some(all), Some(encoder)) => { + crate::i18n::tr_format!("{all:.1} s, image encoder {encoder:.1} s", all = all as f64 / 1000.0, encoder = encoder as f64 / 1000.0) + } + _ => "—".to_string(), + }; + row(ui, t, "Last photo", |ui| { + let r = ui.label(RichText::new(took).color(t.text)); + register(ui.ctx(), "settings:aiMasksTime", r.rect); + }); + hint( + ui, + t, + crate::i18n::tr(if cfg!(target_os = "macos") { + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer." + } else { + "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer." + }), + ); } /// Where this library keeps its smart previews (the offline-editing proxies, which can be large): diff --git a/crates/ui-egui/src/tests_dialog_fit.rs b/crates/ui-egui/src/tests_dialog_fit.rs index 52d4128294..3d11c260fa 100644 --- a/crates/ui-egui/src/tests_dialog_fit.rs +++ b/crates/ui-egui/src/tests_dialog_fit.rs @@ -158,3 +158,40 @@ fn gpu_status_never_moves_the_performance_controls() { let first = seen[0].1; assert!(seen.iter().all(|(_, r, _)| *r == first), "the memory buttons moved: {seen:?}"); } + +/// Settings ▸ Performance says where AI masks run and how long the last photo took (issue #932): before the model +/// loads, its two lines are there all the same, at the end of the tab, so nothing above them moves when it loads. +#[test] +fn performance_tab_shows_where_ai_masks_run() { + let mut h = demo([1300.0, 820.0]); + let r = h.request("ui.key", json!({"key": ",", "cmd": true}), T); + assert_eq!(r["ok"], true, "{r}"); + let r = h.request("ui.clickWidget", json!({"id": "button:settingsTab-performance"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let has = |h: &Headless, id: &str| h.app.widgets.iter().any(|(w, _)| w == id); + if !lightcraft_engine::segment::Segmenter::AVAILABLE { + assert!(!has(&h, "settings:aiMasksDevice"), "a build without AI masks says nothing about them"); + return; + } + let (device, time) = (rect(&h, "settings:aiMasksDevice"), rect(&h, "settings:aiMasksTime")); + assert!(device.bottom() <= time.top() + 1.0, "the device line comes first: {device:?} {time:?}"); + let choice = rect(&h, "button:settingsAiMasksRunOn-1"); + assert!(choice.bottom() <= device.top() + 1.0, "the choice of where they run comes first: {choice:?} {device:?}"); + assert!(rect(&h, "button:settingsMemory-2").bottom() < choice.top(), "after the other performance settings"); + let b = h.app.session.segmenter.backend(); + assert!(b["device"].is_null() && b["encodeMs"].is_null(), "nothing loaded or timed yet: {b}"); + // CPU, then Automatic again: the choice applies at once, and nothing moves + use lightcraft_engine::segment::{CPU_CHOSEN, RunOn}; + for (button, want) in [("button:settingsAiMasksRunOn-1", RunOn::Cpu), ("button:settingsAiMasksRunOn-0", RunOn::Auto)] { + let r = h.request("ui.clickWidget", json!({"id": button}), T); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + h.step(); + assert_eq!(h.app.session.segmenter.run_on(), want); + let fallback = h.app.session.segmenter.backend()["fallback"].clone(); + assert_eq!(fallback == CPU_CHOSEN, want == RunOn::Cpu, "{fallback}"); + // (its text says why it runs on the CPU now, so only its width changes) + assert_eq!(rect(&h, "settings:aiMasksDevice").min, device.min, "the device line stays put"); + } +} From dbb754fe187d04effec94ffb36788e5f48d497a6 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:08:51 +0200 Subject: [PATCH 2/3] i18n(de): the GPU hint for AI masks uses du, like the rest of the German UI Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/de.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 529cebe691..5599c06131 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3445,5 +3445,5 @@ "Run on": "Ausführen auf", "Automatic (GPU when available)": "Automatisch (GPU, wenn vorhanden)", "Object and Describe masks analyze each photo once, on the graphics card unless CPU is chosen or “Use the GPU for rendering” is off. On the processor that takes much longer.": "Objekt- und Beschreiben-Masken analysieren jedes Foto einmal, auf der Grafikkarte, außer CPU ist gewählt oder „GPU zum Rendern verwenden“ ist aus. Auf dem Prozessor dauert das deutlich länger.", - "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wählen Sie CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." + "Automatic runs the model on the Mac's graphics card. Choose CPU if AI masks fail there; on the processor they take much longer.": "Automatisch führt das Modell auf der Grafikkarte des Mac aus. Wähle CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger." } From 1cc33aff329244de803ba33ee9680f32f312cde1 Mon Sep 17 00:00:00 2001 From: helgehelge123 <117832631+helgehelge123@users.noreply.github.com> Date: Mon, 9 Nov 2026 03:57:05 +0100 Subject: [PATCH 3/3] =?UTF-8?q?M12:=20the=20AI=20masks=20settings=20test?= =?UTF-8?q?=20scrolls=20to=20the=20foot=20of=20Settings=20=E2=96=B8=20Perf?= =?UTF-8?q?ormance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main's new rows on the tab (hot pixel limit, preview cache hints, Prepare photos in the background) push the AI masks lines below the dialog's scroll room at 1300×820, so the click on "CPU" was refused as not visible. The test now scrolls the page to its foot, as a user would, and checks the lines are in view before clicking. It only runs with the engine's `sam` feature, which the workspace build (CI) turns on but `cargo test -p lightcraft-ui-egui` alone does not. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tests/dialog_fit.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/ui-egui/src/tests/dialog_fit.rs b/crates/ui-egui/src/tests/dialog_fit.rs index 6a534797fc..1301705514 100644 --- a/crates/ui-egui/src/tests/dialog_fit.rs +++ b/crates/ui-egui/src/tests/dialog_fit.rs @@ -161,6 +161,8 @@ fn gpu_status_never_moves_the_performance_controls() { /// Settings ▸ Performance says where AI masks run and how long the last photo took (issue #932): before the model /// loads, its two lines are there all the same, at the end of the tab, so nothing above them moves when it loads. +/// The tab is taller than the dialog, so the test scrolls to its foot first, as a user would, and clicks the +/// choice there (a press on a row scrolled out of view is refused, not delivered). #[test] fn performance_tab_shows_where_ai_masks_run() { let mut h = demo([1300.0, 820.0]); @@ -174,7 +176,16 @@ fn performance_tab_shows_where_ai_masks_run() { assert!(!has(&h, "settings:aiMasksDevice"), "a build without AI masks says nothing about them"); return; } + // (the AI masks lines end the page, below the room for it: scrolled to its foot) + let r = h.request("ui.hoverWidget", json!({"id": "settings:pageRoom"}), T); + assert_eq!(r["ok"], true, "{r}"); + h.request("ui.scroll", json!({"dy": -5000.0}), T); + h.settle(T); + let room = rect(&h, "settings:pageRoom"); let (device, time) = (rect(&h, "settings:aiMasksDevice"), rect(&h, "settings:aiMasksTime")); + for (what, r) in [("the choice", rect(&h, "button:settingsAiMasksRunOn-1")), ("the device line", device), ("the time line", time)] { + assert!(room.contains_rect(r), "{what} {r:?} is in view in {room:?}"); + } assert!(device.bottom() <= time.top() + 1.0, "the device line comes first: {device:?} {time:?}"); let choice = rect(&h, "button:settingsAiMasksRunOn-1"); assert!(choice.bottom() <= device.top() + 1.0, "the choice of where they run comes first: {choice:?} {device:?}");