Merge pull request #2533 from helgehelge123/sam3-gpu-1-plumbing

M12: SAM 3 accelerator plumbing (1/5 of #2167): backend choice, CPU fallback and the AI masks setting
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 13:56:34 +01:00
commit 46ab3c1387
50 files changed
+2040 -232

No files matched your search

+19 -1
View File
@@ -581,7 +581,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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;
@@ -593,6 +593,8 @@ pub fn specs() -> Vec<CommandSpec> {
"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,
@@ -601,6 +603,22 @@ pub fn specs() -> Vec<CommandSpec> {
}))
}
),
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",
+5 -2
View File
@@ -164,11 +164,14 @@ fn sam3_dir(var: Option<std::ffi::OsString>, config: Option<PathBuf>) -> 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 `<config>/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 `<config>/models/sam3-mirrors.txt` and for where it runs in
/// `<config>/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
}
+98 -1
View File
@@ -120,12 +120,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<RunOn> {
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<String>,
}
/// 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<PathBuf>,
/// The user's list of download mirrors (one base URL per line), if any.
pub mirrors_file: Option<PathBuf>,
/// Where [`Segmenter::run_on`] is kept (`<config>/models/sam3-settings.json` in the app; `None`:
/// only for this session).
pub settings_file: Option<PathBuf>,
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,
@@ -146,6 +191,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(),
@@ -163,6 +210,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<String> {
#[cfg(feature = "sam")]
return lightcraft_segment::remote::configured();
@@ -195,6 +269,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")]
@@ -452,7 +548,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).
+553 -139
View File
@@ -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},
};
@@ -68,6 +77,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).
@@ -93,29 +104,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 {
@@ -162,6 +150,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<Backend>,
}
/// 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<String>,
/// What runs the backbone: "wgpu" (LightCraft's GPU kernels) or "candle".
pub runtime: Option<String>,
/// 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<String>,
/// 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<String>,
/// The last photo's backbone run, in milliseconds.
pub encode_ms: Option<u64>,
/// The last photo's whole analysis before the first click (backbone and click features), in
/// milliseconds.
pub analyze_ms: Option<u64>,
}
/// 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<String>, 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<Box<dyn BackboneAccel>, 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<MakeAccel> = None;
fn no_accelerator(_: &WeightReader) -> Result<Box<dyn BackboneAccel>, 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<Sam3> {
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<Duration>) {
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).
@@ -224,6 +360,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() {
@@ -243,7 +384,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());
@@ -261,6 +402,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<remote::Client>,
}
@@ -275,8 +418,12 @@ fn supersedes(later: &Job, job: &Job) -> bool {
}
}
fn run(rx: &mpsc::Receiver<Job>, 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<Job>, 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<String> = None;
let mut queue: VecDeque<Job> = VecDeque::new();
loop {
if queue.is_empty() {
@@ -306,24 +453,26 @@ fn run(rx: &mpsc::Receiver<Job>, 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);
}
@@ -344,10 +493,10 @@ fn run(rx: &mpsc::Receiver<Job>, 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<Option<SegMask>, 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<Option<SegMask>, 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::<String>().cloned()).unwrap_or_default();
@@ -359,19 +508,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())
@@ -396,17 +564,33 @@ fn render(job: &mut Job) -> Result<Input, String> {
}
/// 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;
@@ -464,7 +648,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<Option<SegMask>, Failure> {
fn run_job(state: &mut State, shared: &Shared, job: &mut Job, failed: Option<&str>) -> Result<Option<SegMask>, Failure> {
if let Some(endpoint) = remote::configured() {
let result = remote_job(state, shared, job, &endpoint);
if result.is_err() {
@@ -475,38 +659,46 @@ 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)))
}
Kind::Subject { focus } => {
let (m, enc) = encoded(state, shared, job, placement)?;
let (m, enc) = encoded(state, shared, job, failed)?;
// (the reference score threshold, as Describe uses)
Ok(m.segment_subject(enc, focus, 0.5)?.map(|p| SegMask::from_logits(side, &p.logits)))
let subject = m.segment_subject(enc, focus, 0.5)?;
// the text heads may have moved to the CPU on the way (a failure on the GPU), as for Describe
shared.backend.lock().unwrap_or_else(PoisonError::into_inner).heads = Some(m.heads_device());
Ok(subject.map(|p| SegMask::from_logits(side, &p.logits)))
}
#[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);
@@ -539,7 +731,7 @@ mod tests {
fn job(tag: Tag, reply: &mpsc::Sender<Outcome>) -> 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]
@@ -572,7 +764,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();
@@ -581,72 +773,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<Kind>) -> Vec<Outcome> {
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();
@@ -664,10 +790,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<Outcome> = 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<Vec<f32>, 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<Box<dyn BackboneAccel>, String> {
Ok(Box::new(FakeGpu(false)))
}
fn failing_gpu(_: &WeightReader) -> Result<Box<dyn BackboneAccel>, String> {
Ok(Box::new(FakeGpu(true)))
}
fn no_gpu(_: &WeightReader) -> Result<Box<dyn BackboneAccel>, String> {
Err("no GPU adapter".into())
}
#[allow(clippy::panic)]
fn never(_: &WeightReader) -> Result<Box<dyn BackboneAccel>, 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<Kind>) -> Vec<Outcome> {
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();
}
}
+45
View File
@@ -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}");
@@ -332,3 +343,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);
}
+4 -3
View File
@@ -250,10 +250,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<String> {
pub fn switched_off() -> Option<String> {
if let Some(why) = env_off_reason() {
return Some(why.into());
}
+44 -12
View File
@@ -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 -- <model dir>`.
//! the GPU kernels and loading the heads): `cargo run -p lightcraft-segment --release --example
//! sam3_bench -- <model dir>`. 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<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench <model dir>")?);
let t = std::time::Instant::now();
let dir = std::path::PathBuf::from(args.next().ok_or("usage: sam3_bench <model dir> [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<u8> = (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(())
}
+262 -28
View File
@@ -6,6 +6,9 @@
//! 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, LayerNorm, Linear, VarBuilder};
@@ -14,12 +17,15 @@ use crate::neck::{FPN, Neck};
use crate::nn::{
Attention, DecoderMlp, GroupNormRelu, Mlp, TORCH_LN_EPS, cxcywh_to_xyxy, inverse_sigmoid, linear, ln, padding_bias, sine_grid, to_vec,
};
use crate::{Error, Prediction, Result, cpu};
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 {
@@ -46,6 +52,17 @@ pub struct Output {
/// Semantic logits `[288, 288]` flattened: everything the prompt names, one mask without
/// boundaries between instances.
pub semantic: Vec<f32>,
/// 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<Option<Box<dyn BackboneAccel>>>,
pub failed: &'a OnceLock<String>,
pub masks_failed: &'a OnceLock<String>,
}
struct EncoderLayer {
@@ -73,6 +90,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<VecDeque<(Vec<u32>, Vec<bool>, Tensor)>>,
encoder: Vec<EncoderLayer>,
decoder: Vec<DecoderLayer>,
out_ln: LayerNorm,
@@ -140,6 +159,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"))?,
@@ -166,9 +186,13 @@ impl Detector {
})
}
/// The detector's feature pyramid for the backbone output `[1, 1024, 72, 72]`.
pub fn features(&self, backbone: &Tensor) -> Result<Features> {
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<Vec<Tensor>>) -> Result<Features> {
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()?;
@@ -176,6 +200,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<Tensor> {
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<Tensor> {
let xyxy = cxcywh_to_xyxy(boxes)?.squeeze(0)?; // [200, 4]
@@ -213,23 +254,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<Output> {
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<Tensor> {
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 = l.mlp.forward_add(&h, &x)?;
}
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<Option<Tensor>> {
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<f32>)> {
// 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)?)?;
}
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<Option<(Tensor, Vec<f32>)>> {
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<Output> {
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)?;
@@ -265,21 +426,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)?)?;
}
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)?;
@@ -287,7 +434,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 {
@@ -297,6 +447,7 @@ impl Detector {
boxes: bv.as_chunks::<4>().0.to_vec(),
text,
semantic,
memory,
})
}
}
@@ -423,7 +574,89 @@ pub fn subject(outs: &[Output], threshold: f32, focus: Option<(f32, f32)>) -> Op
#[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<Sam3> {
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<f32> {
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<u32>, Vec<bool>)> = (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));
}
/// A group in front is kept, the crowd behind isn't; the camera's focus decides: on a person,
/// that person and the others as large; on nobody, nothing (the object there is the subject).
@@ -488,6 +721,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();
+588 -39
View File
@@ -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
@@ -51,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;
@@ -111,12 +118,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<Vec<f32>, 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<Vec<Vec<f32>>, 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<Vec<f32>, 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<Vec<f32>, 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<weights::Weights>);
#[cfg(not(target_arch = "wasm32"))]
impl WeightReader {
/// The checkpoint in a model directory (see [`is_model_dir`]).
pub fn open(dir: &Path) -> Result<Self> {
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<Vec<usize>> {
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<usize>, Vec<f32>)> {
let t = self.0.read(name)?;
Ok((t.dims().to_vec(), t.flatten_all()?.to_vec1::<f32>()?))
}
}
#[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<weights::Weights>,
backbone: vit::Vit,
/// The candle backbone: loaded with the model, or only when an accelerator fails.
backbone: OnceLock<vit::Vit>,
accel: Mutex<Option<Box<dyn BackboneAccel>>>,
/// Why the accelerator `load_accelerated` was given is not (or no longer) used.
fallback: Mutex<Option<String>>,
/// Why the DETR encoder runs in candle although there is an accelerator (it failed there once).
detr_fallback: OnceLock<String>,
/// The same for the text detector's mask decoder.
mask_fallback: OnceLock<String>,
/// The necks the accelerator failed on: candle runs them from then on.
necks_off: Mutex<Vec<NeckKind>>,
/// The candle tracker neck: loaded on first use, unless the accelerator runs it.
tracker_neck: Option<neck::Neck>,
tracker: Option<tracker::Tracker>,
detector: Option<detector::Detector>,
@@ -158,8 +288,124 @@ impl Sam3 {
}
let weights = weights::Weights::open(&dir.join(WEIGHTS_FILE))?;
hugging_face_format(&weights)?;
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<Box<dyn BackboneAccel>, String>,
) -> Result<Self> {
let reader = WeightReader::open(dir)?;
hugging_face_format(&reader.0)?;
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<weights::Weights>, accel: Option<Box<dyn BackboneAccel>>) -> 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<String> {
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<String> {
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<String> {
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<weights::Weights>, device: &Device) -> VarBuilder<'a> {
@@ -180,30 +426,133 @@ impl Sam3 {
/// Run the backbone on preprocessed pixels `[1, 3, 1008, 1008]` (−1..1).
pub fn encode_pixels(&self, pixels: &Tensor) -> Result<Encoded> {
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::<f32>()?;
// 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<Option<Vec<Tensor>>> {
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<Vec<Tensor>, String> {
let x = backbone.to_device(&Device::Cpu).and_then(|t| t.flatten_all()).and_then(|t| t.to_vec1::<f32>()).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<Vec<Tensor>> {
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).
@@ -215,18 +564,15 @@ impl Sam3 {
if clicks.len() > MAX_CLICKS {
return Err(Error::Model(format!("at most {MAX_CLICKS} clicks, not {}", clicks.len())));
}
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"))?);
}
@@ -234,22 +580,32 @@ 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<Option<Prediction>> {
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))
}
@@ -264,13 +620,11 @@ impl Sam3 {
/// Raw detector outputs for `text` (tests and tools).
pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result<detector::Output> {
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)
}
}
@@ -282,6 +636,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"))]
/// Meta's original checkpoint (`sam3.pt`, or a `sam3.safetensors` conversion of it as on community
/// mirrors) names its tensors differently: say so, rather than name the first tensor it lacks (#3378).
@@ -314,6 +678,191 @@ pub fn sync(model: &Sam3) -> Result<()> {
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<Vec<f32>, 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<Box<dyn BackboneAccel>, 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<std::sync::atomic::AtomicUsize>,
short: bool,
}
impl BackboneAccel for NeckFake {
fn forward(&self, _: &[f32]) -> std::result::Result<Vec<f32>, 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<Vec<Vec<f32>>, String> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
assert_eq!((backbone.len(), backbone[0]), (FULL, 0.5));
let mut levels: Vec<Vec<f32>> = (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::<f32>().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<Vec<f32>, 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<Vec<Vec<f32>>, 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<Box<dyn BackboneAccel>, 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();
}
}
#[test]
fn meta_original_checkpoint_is_named_as_such() {
// #3378: a community mirror's `sam3.safetensors` (Meta's key names, C64 RoPE tables) saved as model.safetensors
+41 -5
View File
@@ -171,15 +171,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<Tensor> {
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)?)
}
}
@@ -286,3 +296,29 @@ pub fn cxcywh_to_xyxy(b: &Tensor) -> Result<Tensor> {
pub fn to_vec(t: &Tensor) -> Result<Vec<f32>> {
Ok(t.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?)
}
#[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::<f32>().unwrap(), want.flatten_all().unwrap().to_vec1::<f32>().unwrap());
}
}
+58
View File
@@ -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<PathBuf> {
// 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<Vec<f32>, 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<dyn BackboneAccel>)).unwrap();
assert!(m.accelerated());
assert_eq!(m.backbone_device(), "Lost GPU (Vulkan)");
let (w, h) = (64, 48);
let rgb: Vec<u8> = (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::<f32>().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"));
}
+2
View File
@@ -1,4 +1,6 @@
//! The integration tests, one module per file, linked into one test binary.
mod accel;
mod prompts;
mod reference;
mod remote;
+63
View File
@@ -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<PathBuf> {
// 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<Vec<f32>, 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<f32> {
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<dyn BackboneAccel>)).unwrap();
let (w, h) = (64, 48);
let rgb: Vec<u8> = (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);
}
+1
View File
@@ -322,6 +322,7 @@
"Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}",
"{name} is installed": "{name} je nainstalován",
"{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kodér obrazu {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Fotografie importujete přes Soubor › Importovat fotografie… ({keys}).",
"View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).",
"File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).",
+8
View File
@@ -2481,6 +2481,14 @@
"Top bar": "Horní lišta",
"Tool strip": "Pruh nástrojů",
"Bottom bar": "Dolní lišta",
"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.",
"User Templates": "Uživatelské šablony",
"Delete Folder": "Odstranit složku",
"Folder name": "Název složky",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}",
"{name} is installed": "{name} ist installiert",
"{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, Bildencoder {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.",
"View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).",
"File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).",
+8
View File
@@ -3540,6 +3540,14 @@
"Tool strip": "Werkzeugleiste",
"Bottom bar": "Untere Leiste",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)",
"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ähle CPU, wenn KI-Masken dort scheitern; auf dem Prozessor dauern sie deutlich länger.",
"User Templates": "Benutzervorlagen",
"Delete Folder": "Ordner löschen",
"Folder name": "Ordnername",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}",
"{name} is installed": "{name} está instalado",
"{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagen {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).",
"View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).",
"File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).",
+8
View File
@@ -2436,6 +2436,14 @@
"Tool strip": "Barra de herramientas",
"Bottom bar": "Barra inferior",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)",
"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.",
"User Templates": "Plantillas del usuario",
"Delete Folder": "Eliminar carpeta",
"Folder name": "Nombre de la carpeta",
+1
View File
@@ -319,6 +319,7 @@
"Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}",
"{name} is installed": "{name} on asennettu",
"{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, kuvakooderi {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia… ({keys}).",
"View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).",
"File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).",
+8
View File
@@ -2413,6 +2413,14 @@
"Top bar": "Yläpalkki",
"Tool strip": "Työkalupalkki",
"Bottom bar": "Alapalkki",
"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.",
"User Templates": "Käyttäjän mallipohjat",
"Delete Folder": "Poista kansio",
"Folder name": "Kansion nimi",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "Le déplacement du panneau n'a pas été appliqué : {error}",
"{name} is installed": "{name} est installé",
"{name} is installed and in use: face recognition is on": "{name} est installé et utilisé : la reconnaissance des visages est activée",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, encodeur d’image {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).",
"View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).",
"File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).",
+8
View File
@@ -3619,6 +3619,14 @@
"Tool strip": "Barre d’outils",
"Bottom bar": "Barre inférieure",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Empêcher le scintillement G-SYNC/FreeSync (au prochain démarrage)",
"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.",
"User Templates": "Modèles utilisateur",
"Delete Folder": "Supprimer le dossier",
"Folder name": "Nom du dossier",
+1
View File
@@ -322,6 +322,7 @@
"Creates {stacks} stack{} from {photos} of {scope}": "Membuat {stacks} tumpukan dari {photos} foto ({scope}){:.0}",
"{n} selected photo{} · {pages} page{}": "{n} foto dipilih · {pages} halaman{:.0}{:.0}",
"{n} photo{} in view · {slides} slide{} · {time}": "{n} foto di tampilan · {slides} slide · {time}{:.0}{:.0}",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} dtk, penyandi gambar {encoder:.1} dtk",
"Bring photos in with File › Import Photos… ({keys}).": "Masukkan foto melalui File › Impor foto… ({keys}).",
"View › Detail View ({keys}).": "Tampilan › Tampilan Detail ({keys}).",
"File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).",
+8
View File
@@ -2427,6 +2427,14 @@
"Top bar": "Bilah atas",
"Tool strip": "Bilah alat",
"Bottom bar": "Bilah bawah",
"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.",
"User Templates": "Templat pengguna",
"Delete Folder": "Hapus folder",
"Folder name": "Nama folder",
+1
View File
@@ -322,6 +322,7 @@
"Panel move was not applied: {error}": "Lo spostamento del pannello non è stato applicato: {error}",
"{name} is installed": "{name} è installato",
"{name} is installed and in use: face recognition is on": "{name} è installato e in uso: il riconoscimento dei volti è attivo",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificatore d’immagine {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Importa le foto con File › Importa foto… ({keys}).",
"View › Detail View ({keys}).": "Visualizza › Vista dettaglio ({keys}).",
"File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).",
+8
View File
@@ -2599,6 +2599,14 @@
"Top bar": "Barra superiore",
"Tool strip": "Barra degli strumenti",
"Bottom bar": "Barra inferiore",
"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.",
"User Templates": "Modelli utente",
"Delete Folder": "Elimina cartella",
"Folder name": "Nome della cartella",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "パネルの移動は適用されませんでした:{error}",
"{name} is installed": "{name} をインストールしました",
"{name} is installed and in use: face recognition is on": "{name} をインストールして使用中です:顔認識はオンです",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒(画像エンコーダー {encoder:.1} 秒)",
"Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。",
"View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。",
"File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。",
+8
View File
@@ -2434,6 +2434,14 @@
"Tool strip": "ツールバー",
"Bottom bar": "下部バー",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC/FreeSyncのちらつきを防ぐ(次回起動時に適用)",
"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を選んでください。処理装置ではかなり時間がかかります。",
"User Templates": "ユーザーテンプレート",
"Delete Folder": "フォルダを削除",
"Folder name": "フォルダ名",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "პანელის გადატანა არ შესრულდა: {error}",
"{name} is installed": "{name} დაინსტალირებულია",
"{name} is installed and in use: face recognition is on": "{name} დაინსტალირებულია და გამოიყენება: სახეების ამოცნობა ჩართულია",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} წმ, გამოსახულების ენკოდერი {encoder:.1} წმ",
"Bring photos in with File › Import Photos… ({keys}).": "ფოტოების შემოსატანად გამოიყენეთ ფაილი › ფოტოების იმპორტი… ({keys}).",
"View › Detail View ({keys}).": "ხედი › დეტალური ხედი ({keys}).",
"File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).",
+8
View File
@@ -87,6 +87,7 @@
"AI Denoise and Find Missing Photos. Each row has the task's name, a progress bar, the count and what it is working": "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": "პროგრამის შესახებ",
@@ -232,7 +233,9 @@
"Auto-Tag from Tracklog…": "მდებარეობის მინიჭება მარშრუტის ჟურნალიდან…",
"Add Locations": "მდებარეობების დამატება",
"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 თანმხლებ ფაილებში ავტომატურად ჩაწერა",
@@ -601,6 +604,7 @@
"Detect Faces": "სახეების ამოცნობა",
"Detect Faces (Photo menu) needs it: a small one-time download.": "სახეების ამოცნობას (მენიუ „ფოტო“) ეს სჭირდება: მცირე, ერთჯერადი ჩამოტვირთვა.",
"Develop": "დამუშავება",
"Device": "მოწყობილობა",
"Develop a photo": "ფოტოს დამუშავება",
"Diagonal": "დიაგონალური",
"Dialogs": "დიალოგები",
@@ -1101,6 +1105,7 @@
"Last GPU fallback": "GPU-დან ბოლო გადართვა",
"Last commit": "ბოლო კომიტი",
"Last loupe render": "ლუპის ბოლო რენდერი",
"Last photo": "ბოლო ფოტო",
"Last view": "ბოლო ხედი",
"Lateral Chromatic Aberration": "განივი ქრომატული აბერაცია",
"Layer": "შრე",
@@ -1399,6 +1404,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": "გამორთული",
@@ -1690,6 +1696,7 @@
"Relinked": "ხელახლა დაკავშირებულია",
"Reload Changed Files": "შეცვლილი ფაილების ხელახლა ჩატვირთვა",
"Reload from Disk": "დისკიდან ხელახლა ჩატვირთვა",
"Remote worker": "დისტანციური დამმუშავებელი",
"Remove": "მოშორება",
"Remove (H)": "მოშორება (H)",
"Remove CA": "ქრომატული აბერაციის მოცილება",
@@ -1793,6 +1800,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 სიკაშკაშე",
+1
View File
@@ -322,6 +322,7 @@
"Panel move was not applied: {error}": "Przeniesienie panelu nie zostało zastosowane: {error}",
"{name} is installed": "{name} jest zainstalowany",
"{name} is installed and in use: face recognition is on": "{name} jest zainstalowany i używany: rozpoznawanie twarzy jest włączone",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, koder obrazu {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Zdjęcia importujesz przez Plik › Importuj zdjęcia… ({keys}).",
"View › Detail View ({keys}).": "Widok › Widok szczegółów ({keys}).",
"File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).",
+10
View File
@@ -2358,6 +2358,16 @@
"Top bar": "Górny pasek",
"Tool strip": "Pasek narzędzi",
"Bottom bar": "Dolny pasek",
"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.",
"User Templates": "Szablony użytkownika",
"Delete Folder": "Usuń folder",
"Folder name": "Nazwa folderu",
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "A movimentação do painel não foi aplicada: {error}",
"{name} is installed": "{name} está instalado",
"{name} is installed and in use: face recognition is on": "{name} está instalado e em uso: o reconhecimento facial está ativado",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, codificador de imagem {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).",
"View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).",
"File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).",
+8
View File
@@ -2280,6 +2280,14 @@
"Tool strip": "Barra de ferramentas",
"Bottom bar": "Barra inferior",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar cintilação de G-SYNC/FreeSync (no próximo início)",
"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.",
"User Templates": "Modelos do usuário",
"Delete Folder": "Excluir pasta",
"Folder name": "Nome da pasta",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "Перемещение панели не применено: {error}",
"{name} is installed": "Модель {name} установлена",
"{name} is installed and in use: face recognition is on": "Модель {name} установлена и используется: распознавание лиц включено",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодировщик изображения {encoder:.1} с",
"Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).",
"View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).",
"File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).",
+8
View File
@@ -2642,6 +2642,14 @@
"Tool strip": "Панель инструментов",
"Bottom bar": "Нижняя панель",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Предотвращать мерцание G-SYNC/FreeSync (после перезапуска)",
"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. Если ИИ-маски там не работают, выберите ЦП; на процессоре они намного дольше.",
"User Templates": "Пользовательские шаблоны",
"Delete Folder": "Удалить папку",
"Folder name": "Название папки",
+1
View File
@@ -322,6 +322,7 @@
"Creates {stacks} stack{} from {photos} of {scope}": "Skapar staplar: {stacks} · foton: {photos} av {scope}{:.0}",
"{n} selected photo{} · {pages} page{}": "Markerade foton: {n} · sidor: {pages}{:.0}{:.0}",
"{n} photo{} in view · {slides} slide{} · {time}": "Foton i vyn: {n} · bilder: {slides} · {time}{:.0}{:.0}",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} s, bildkodare {encoder:.1} s",
"Bring photos in with File › Import Photos… ({keys}).": "Importera foton via Fil › Importera foton… ({keys}).",
"View › Detail View ({keys}).": "Visa › Detaljvy ({keys}).",
"File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).",
+8
View File
@@ -2517,6 +2517,14 @@
"Top bar": "Övre fältet",
"Tool strip": "Verktygsfält",
"Bottom bar": "Nedre fältet",
"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.",
"User Templates": "Användarmallar",
"Delete Folder": "Radera mapp",
"Folder name": "Mappnamn",
+1
View File
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "Переміщення панелі не застосовано: {error}",
"{name} is installed": "{name} установлено",
"{name} is installed and in use: face recognition is on": "{name} установлено й використовується: розпізнавання облич увімкнено",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} с, кодувальник зображення {encoder:.1} с",
"Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).",
"View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).",
"File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).",
+8
View File
@@ -2432,6 +2432,14 @@
"Tool strip": "Панель інструментів",
"Bottom bar": "Нижня панель",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Запобігати мерехтінню G-SYNC/FreeSync (після перезапуску)",
"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. Якщо ШІ-маски там не працюють, виберіть ЦП; на процесорі вони значно довші.",
"User Templates": "Власні шаблони",
"Delete Folder": "Видалити теку",
"Folder name": "Назва теки",
+1
View File
@@ -319,6 +319,7 @@
"Panel move was not applied: {error}": "Việc di chuyển bảng chưa được áp dụng: {error}",
"{name} is installed": "{name} đã được cài đặt",
"{name} is installed and in use: face recognition is on": "{name} đã được cài đặt và đang dùng: nhận diện khuôn mặt đã bật",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} giây, bộ mã hóa ảnh {encoder:.1} giây",
"Bring photos in with File › Import Photos… ({keys}).": "Đưa ảnh vào bằng Tệp › Nhập ảnh… ({keys}).",
"View › Detail View ({keys}).": "Xem › Chế độ xem chi tiết ({keys}).",
"File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).",
+8
View File
@@ -2741,6 +2741,14 @@
"Top bar": "Thanh trên cùng",
"Tool strip": "Thanh công cụ",
"Bottom bar": "Thanh dưới cùng",
"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.",
"User Templates": "Mẫu người dùng",
"Delete Folder": "Xóa thư mục",
"Folder name": "Tên thư mục",
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "面板移动未应用:{error}",
"{name} is installed": "{name} 已安装",
"{name} is installed and in use: face recognition is on": "{name} 已安装并在使用:人脸识别已开启",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,图像编码器 {encoder:.1} 秒",
"Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。",
"View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。",
"File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。",
+8
View File
@@ -2435,6 +2435,14 @@
"Top bar": "顶部栏",
"Tool strip": "工具栏",
"Bottom bar": "底部栏",
"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;在处理器上会慢得多。",
"User Templates": "用户模板",
"Delete Folder": "删除文件夹",
"Folder name": "文件夹名称",
@@ -325,6 +325,7 @@
"Panel move was not applied: {error}": "面板移動未套用:{error}",
"{name} is installed": "{name} 已安裝",
"{name} is installed and in use: face recognition is on": "{name} 已安裝並在使用中:臉部辨識已開啟",
"{all:.1} s, image encoder {encoder:.1} s": "{all:.1} 秒,影像編碼器 {encoder:.1} 秒",
"Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。",
"View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。",
"File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。",
+8
View File
@@ -2436,6 +2436,14 @@
"Tool strip": "工具列",
"Bottom bar": "底部列",
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "防止 G-SYNC/FreeSync 閃爍(下次啟動時生效)",
"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;在處理器上會慢得多。",
"User Templates": "使用者範本",
"Delete Folder": "刪除資料夾",
"Folder name": "資料夾名稱",
+2 -2
View File
@@ -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,
@@ -120,6 +120,59 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To
);
#[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, "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, "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."
}),
);
}
/// Settings ▸ Performance ▸ Prepare photos in the background (notes 47 and 48): per mode, what
+48
View File
@@ -158,3 +158,51 @@ 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.
/// 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]);
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;
}
// (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:?}");
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");
}
}