From d17b62d103420c671e4cabc09773bbd5e5845421 Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 20:37:16 +0100 Subject: [PATCH] Desktop: use the GPU, Neural Engine and CPU together for face recognition. The boxes stay on the CPU interpreter. The recogniser uses every accelerator when a startup check still matches that interpreter, so the names stay the same. --- apps/app/src/i18n.ts | 4 + apps/app/src/library/CardScan.tsx | 15 +- apps/desktop/package.json | 2 +- apps/desktop/src-tauri/.gitignore | 1 + apps/desktop/src-tauri/Cargo.toml | 6 +- apps/desktop/src-tauri/onnx/.gitkeep | 0 apps/desktop/src-tauri/src/accel.rs | 549 +++++++++++++++++++++++++ apps/desktop/src-tauri/src/faces.rs | 36 +- apps/desktop/src-tauri/src/lib.rs | 1 + apps/desktop/src-tauri/tauri.conf.json | 6 +- infra/desktop/bundle-onnx.sh | 81 ++++ workers/faces/src/lib.rs | 81 +++- 12 files changed, 759 insertions(+), 23 deletions(-) create mode 100644 apps/desktop/src-tauri/onnx/.gitkeep create mode 100644 apps/desktop/src-tauri/src/accel.rs create mode 100755 infra/desktop/bundle-onnx.sh diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 2346339..1f18bd2 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -621,6 +621,10 @@ export const t = { title: "Procurar numa pasta", help: "Escolhe uma pasta. As fotos ficam onde estão. Só entram no jogo as que selecionares.", local: "A ler neste computador. As fotos não são enviadas. O que já foi lido fica guardado.", + accelAll: "A usar a gráfica, o Neural Engine e o processador.", + accelGpu: "A usar a gráfica e o processador.", + accelAne: "A usar o Neural Engine e o processador.", + accelCpu: "O reconhecimento nesta máquina está a correr no processador.", preparing: "A preparar o reconhecimento neste computador. Da primeira vez demora um pouco.", game: "Jogo", roster: (n: number) => diff --git a/apps/app/src/library/CardScan.tsx b/apps/app/src/library/CardScan.tsx index 5fbe157..6b78cbf 100644 --- a/apps/app/src/library/CardScan.tsx +++ b/apps/app/src/library/CardScan.tsx @@ -128,6 +128,7 @@ export function CardScan({ const [gameId, setGameId] = useState(eventId); const [roster, setRoster] = useState(undefined); const [localMode, setLocalMode] = useState(false); + const [accelerators, setAccelerators] = useState(null); const folderRef = useRef(""); const gameRef = useRef(gameId); gameRef.current = gameId; @@ -231,6 +232,7 @@ export function CardScan({ stop.current = false; folderRef.current = folder; setLocalMode(true); + setAccelerators(null); setNote(t.cardScan.preparing); setSent(null); setSelected(new Set()); @@ -273,7 +275,10 @@ export function CardScan({ let unlisten = () => {}; try { const { listen } = await import("@tauri-apps/api/event"); - unlisten = await listen("faces-photo", (e) => { + const stopAccel = await listen<{ accelerators: string }>("faces-accel", (e) => { + if (e.payload.accelerators) setAccelerators(e.payload.accelerators); + }); + const stopPhoto = await listen("faces-photo", (e) => { const ev = e.payload; if (stop.current) return; setTotal(ev.total); @@ -296,6 +301,10 @@ export function CardScan({ } setItems(next.slice()); }); + unlisten = () => { + stopAccel(); + stopPhoto(); + }; const token = await api.realtimeToken(); await desktopInvoke("faces_scan", { folder, orgId, eventId: gameRef.current, api: api.baseUrl, token }); if (pending.length) { @@ -395,6 +404,10 @@ export function CardScan({

{localMode ? t.cardScan.local : t.cardScan.help} {t.cardScan.jpeg} + {localMode && accelerators === "all" && {t.cardScan.accelAll}} + {localMode && accelerators === "gpu" && {t.cardScan.accelGpu}} + {localMode && accelerators === "ane" && {t.cardScan.accelAne}} + {localMode && accelerators === "cpu" && {t.cardScan.accelCpu}} {roster === null && {t.cardScan.rosterOpen}} {roster === 0 && {t.cardScan.rosterNone}} {typeof roster === "number" && roster > 0 && {t.cardScan.roster(roster)}} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4efd03d..c6994f5 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.13", + "version": "0.3.14", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/.gitignore b/apps/desktop/src-tauri/.gitignore index 267627c..06edd64 100644 --- a/apps/desktop/src-tauri/.gitignore +++ b/apps/desktop/src-tauri/.gitignore @@ -1,4 +1,5 @@ target/ gen/ +onnx/*.dylib # Generated by `pnpm --filter @photoreport/desktop icons` (scripts/make-icon.py) icons/ diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index fa95255..ce1344a 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photoreport-desktop" -version = "0.3.13" +version = "0.3.14" edition = "2024" publish = false description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." @@ -36,6 +36,10 @@ tauri-plugin-updater = "2" # New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates. reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"] } rustls = { version = "0.23", default-features = false, features = ["ring"] } +# Apple Silicon only: the published ONNX Runtime build with Core ML exists for that chip. +# It is linked into the app, so Intel Macs simply keep the CPU interpreter. +[target.'cfg(all(target_os = "macos", target_arch = "aarch64"))'.dependencies] +ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "download-binaries", "copy-dylibs", "api-31", "tls-native", "coreml"] } # Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells # a disassembler what machine code does, not what the functions were called. diff --git a/apps/desktop/src-tauri/onnx/.gitkeep b/apps/desktop/src-tauri/onnx/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/desktop/src-tauri/src/accel.rs b/apps/desktop/src-tauri/src/accel.rs new file mode 100644 index 0000000..74ae653 --- /dev/null +++ b/apps/desktop/src-tauri/src/accel.rs @@ -0,0 +1,549 @@ +//! The face recogniser on every chip this computer will actually use. +//! +//! YuNet stays on the checked CPU interpreter, so the boxes stay the ones the server named people with. +//! AuraFace is the heavy net. On Apple Silicon it runs through ONNX Runtime on the GPU, the Neural Engine +//! and the CPU together (`ComputeUnits::All`). A startup check compares that embedding with the CPU +//! interpreter on two fixed faces. If they are not close, the scan keeps the interpreter and the names stay +//! the same. Intel Macs and other systems keep the CPU interpreter: there is no published accelerator build +//! for them. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::Duration; + +use photoreport_faces::Engine; + +const SIDE: usize = 112; +const MEAN: f32 = 127.5; +const STD: f32 = 127.5; +/// Cosine below this is a different face for a close call (the server matches at 0.40). +const MIN_COSINE: f32 = 0.995; +const REVISION: &str = "1"; + +/// One shared recogniser. Sessions are handed out one photo at a time; CoreML is not safe to run +/// concurrently on the same session. +pub struct Accel { + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + inner: MacAccel, +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +struct MacAccel { + sessions: Mutex>, + waiting: Condvar, + input_name: String, + output_name: String, + copies: usize, + label: &'static str, +} + +impl Accel { + pub fn embed(&self, rgb: &[u8]) -> Result, String> { + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + { + return self.inner.embed(rgb); + } + #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] + { + let _ = rgb; + Err("no accelerator".into()) + } + } + + /// True while every accelerator session is already running a face. + /// The scan uses this so it does not start more CPU copies that would only wait. + pub fn is_saturated(&self) -> bool { + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + { + return self + .inner + .sessions + .lock() + .map(|guard| guard.is_empty()) + .unwrap_or(false); + } + #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] + { + false + } + } + + /// RAM to leave free for the compiled accelerator copies, in gigabytes. + pub fn reserved_gb(&self) -> f64 { + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + { + return 1.2 * self.inner.copies as f64; + } + #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] + { + 0.0 + } + } + + /// `all` (GPU + Neural Engine + CPU), `gpu`, `ane`, for the folder-search banner. + pub fn label(&self) -> &'static str { + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + { + return self.inner.label; + } + #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] + { + "cpu" + } + } +} + +/// Load the accelerator when this machine has one and it still matches the CPU recogniser. +pub fn open(models: &Path) -> Option> { + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + { + return open_mac(models).map(|inner| Arc::new(Accel { inner })); + } + #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] + { + let _ = models; + None + } +} + +/// ArcFace preprocessing: RGB, `(x − 127.5) / 127.5`, NCHW. The CPU interpreter does the same. +fn nchw(rgb: &[u8]) -> Result, String> { + let plane = SIDE * SIDE; + if rgb.len() != plane * 3 { + return Err("the face picture is not 112×112".into()); + } + let mut data = vec![0.0f32; 3 * plane]; + for (i, px) in rgb.chunks_exact(3).enumerate() { + for channel in 0..3 { + data[channel * plane + i] = (f32::from(px[channel]) - MEAN) / STD; + } + } + Ok(data) +} + +fn unit(values: &[f32]) -> Result, String> { + if values.iter().any(|value| !value.is_finite()) { + return Err("the accelerator gave a non-finite face".into()); + } + let norm = values + .iter() + .map(|value| f64::from(*value) * f64::from(*value)) + .sum::() + .sqrt(); + if !norm.is_finite() || norm < 1e-9 { + return Err("the accelerator gave an empty face".into()); + } + Ok(values + .iter() + .map(|value| (f64::from(*value) / norm) as f32) + .collect()) +} + +fn cosine(left: &[f32], right: &[f32]) -> f32 { + if left.len() != right.len() || left.is_empty() { + return 0.0; + } + left.iter().zip(right).map(|(a, b)| a * b).sum() +} + +fn pattern(seed: u32) -> Vec { + let mut state = seed; + (0..SIDE * SIDE * 3) + .map(|_| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + (state >> 8) as u8 + }) + .collect() +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn open_mac(models: &Path) -> Option { + use ort::ep::coreml::ComputeUnits; + + let env = match shared_env() { + Ok(env) => env, + Err(err) => { + eprintln!("faces: ONNX Runtime did not start ({err}), using the CPU"); + return None; + } + }; + let model = models.join("glintr100.onnx"); + if !model.is_file() { + return None; + } + let engine = match Engine::load(models, "auraface", 0.6) { + Ok(engine) => engine, + Err(err) => { + eprintln!("faces: {err}"); + return None; + } + }; + + let mut order = [ + ComputeUnits::All, + ComputeUnits::CPUAndGPU, + ComputeUnits::CPUAndNeuralEngine, + ]; + if let Some(first) = preferred(models) { + if let Some(pos) = order.iter().position(|units| *units == first) { + order.swap(0, pos); + } + } + + for units in order { + let session = match session_for(&env, &model, models, units) { + Ok(session) => session, + Err(err) => { + eprintln!( + "faces: accelerator {} did not load: {err}", + unit_name(units) + ); + continue; + } + }; + let (input_name, output_name) = match io_names(&session) { + Ok(names) => names, + Err(err) => { + eprintln!( + "faces: accelerator {} has no face tensor: {err}", + unit_name(units) + ); + continue; + } + }; + let trial = MacAccel { + sessions: Mutex::new(vec![session]), + waiting: Condvar::new(), + input_name, + output_name, + copies: 1, + label: label_of(units), + }; + match closest(&trial, &engine) { + Some(score) if score >= MIN_COSINE => { + eprintln!( + "faces: recogniser on {} (cosine {score:.4})", + unit_name(units) + ); + drop(engine); + let ready = more_copies(trial, &env, &model, models, units); + remember(models, units); + return Some(ready); + } + Some(score) => { + eprintln!( + "faces: accelerator {} cosine {score:.4} is too far from the CPU recogniser", + unit_name(units) + ); + if score < 0.90 { + break; + } + } + None => eprintln!( + "faces: accelerator {} did not finish the check", + unit_name(units) + ), + } + } + eprintln!("faces: recogniser staying on the CPU"); + None +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn more_copies( + accel: MacAccel, + env: &ort::environment::Environment, + model: &Path, + models: &Path, + units: ort::ep::coreml::ComputeUnits, +) -> MacAccel { + let want = session_copies(); + let mut accel = accel; + for _ in 1..want { + match session_for(env, model, models, units) { + Ok(session) => { + if let Ok(mut guard) = accel.sessions.lock() { + guard.push(session); + accel.copies += 1; + } + } + Err(err) => { + eprintln!("faces: extra accelerator copy skipped: {err}"); + break; + } + } + } + accel +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn session_copies() -> usize { + let gb = memory_gb(); + if gb >= 24.0 { + 3 + } else if gb >= 12.0 { + 2 + } else { + 1 + } +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn session_for( + env: &ort::environment::Environment, + model: &Path, + models: &Path, + units: ort::ep::coreml::ComputeUnits, +) -> Result { + use ort::ep::coreml::{CoreML, ModelFormat, SpecializationStrategy}; + use ort::session::Session; + use ort::session::builder::GraphOptimizationLevel; + + let cache = cache_dir(models, units); + std::fs::create_dir_all(&cache).map_err(|e| e.to_string())?; + // Level 1 keeps the graph close to the file the CPU interpreter runs. CoreML then places the + // ops on whatever of the GPU, Neural Engine and CPU this setting allows. + Session::builder(env) + .map_err(|e| e.to_string())? + .with_execution_providers([CoreML::default() + .with_compute_units(units) + .with_model_format(ModelFormat::MLProgram) + .with_specialization_strategy(SpecializationStrategy::FastPrediction) + .with_static_input_shapes(true) + .with_low_precision_accumulation_on_gpu(false) + .with_model_cache_dir(cache.display().to_string()) + .build()]) + .map_err(|e| e.to_string())? + .with_optimization_level(GraphOptimizationLevel::Level1) + .map_err(|e| e.to_string())? + .with_intra_threads(1) + .map_err(|e| e.to_string())? + .commit_from_file(model) + .map_err(|e| e.to_string()) +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn io_names(session: &ort::session::Session) -> Result<(String, String), String> { + let input = session + .inputs() + .first() + .ok_or("the recogniser has no input")?; + let output = session + .outputs() + .first() + .ok_or("the recogniser has no output")?; + Ok((input.name().to_string(), output.name().to_string())) +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn closest(accel: &MacAccel, cpu: &Engine) -> Option { + let mut worst = 1.0f32; + for seed in [0x2545_f491u32, 0x1234_5678u32] { + let rgb = pattern(seed); + let left = cpu.embed_aligned(&rgb).ok()?; + let right = accel.embed(&rgb).ok()?; + worst = worst.min(cosine(&left, &right)); + } + Some(worst) +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +impl MacAccel { + fn embed(&self, rgb: &[u8]) -> Result, String> { + let data = nchw(rgb)?; + let input = self.input_name.clone(); + let output = self.output_name.clone(); + let mut session = self.checkout()?; + let result = infer(&mut session, &input, &output, data); + self.checkin(session); + result + } + + fn checkout(&self) -> Result { + let mut guard = self.sessions.lock().map_err(|e| e.to_string())?; + let started = std::time::Instant::now(); + loop { + if let Some(session) = guard.pop() { + return Ok(session); + } + if started.elapsed() > Duration::from_secs(120) { + return Err("the accelerator stayed busy".into()); + } + let (next, timeout) = self + .waiting + .wait_timeout(guard, Duration::from_millis(200)) + .map_err(|e| e.to_string())?; + guard = next; + if timeout.timed_out() + && guard.is_empty() + && started.elapsed() > Duration::from_secs(120) + { + return Err("the accelerator stayed busy".into()); + } + } + } + + fn checkin(&self, session: ort::session::Session) { + if let Ok(mut guard) = self.sessions.lock() { + guard.push(session); + self.waiting.notify_one(); + } + } +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn infer( + session: &mut ort::session::Session, + input: &str, + output: &str, + data: Vec, +) -> Result, String> { + use ort::value::Tensor; + + let tensor = Tensor::from_array(([1usize, 3, SIDE, SIDE], data.into_boxed_slice())) + .map_err(|e| e.to_string())?; + let outputs = session + .run(ort::inputs![input => tensor]) + .map_err(|e| e.to_string())?; + let (_shape, values) = outputs[output] + .try_extract_tensor::() + .map_err(|e| e.to_string())?; + unit(values) +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn shared_env() -> Result<&'static ort::environment::Environment, String> { + static CELL: OnceLock = OnceLock::new(); + if CELL.get().is_some() { + return Ok(CELL.get().expect("accelerator environment")); + } + let env = ort::init().build().map_err(|e| e.to_string())?; + Ok(CELL.get_or_init(|| env)) +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn cache_dir(models: &Path, units: ort::ep::coreml::ComputeUnits) -> PathBuf { + models + .parent() + .unwrap_or(models) + .join(format!("coreml-{}", unit_name(units))) +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn preference_path(models: &Path) -> PathBuf { + models.parent().unwrap_or(models).join("accel-device") +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn preferred(models: &Path) -> Option { + use ort::ep::coreml::ComputeUnits; + let text = std::fs::read_to_string(preference_path(models)).ok()?; + let mut parts = text.split_whitespace(); + if parts.next() != Some(REVISION) { + return None; + } + match parts.next() { + Some("all") => Some(ComputeUnits::All), + Some("gpu") => Some(ComputeUnits::CPUAndGPU), + Some("ane") => Some(ComputeUnits::CPUAndNeuralEngine), + _ => None, + } +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn remember(models: &Path, units: ort::ep::coreml::ComputeUnits) { + let _ = std::fs::write( + preference_path(models), + format!("{REVISION} {}\n", label_of(units)), + ); +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn label_of(units: ort::ep::coreml::ComputeUnits) -> &'static str { + use ort::ep::coreml::ComputeUnits; + match units { + ComputeUnits::All => "all", + ComputeUnits::CPUAndNeuralEngine => "ane", + ComputeUnits::CPUAndGPU => "gpu", + ComputeUnits::CPUOnly => "cpu", + } +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn unit_name(units: ort::ep::coreml::ComputeUnits) -> &'static str { + use ort::ep::coreml::ComputeUnits; + match units { + ComputeUnits::All => "GPU + Neural Engine + CPU", + ComputeUnits::CPUAndGPU => "GPU + CPU", + ComputeUnits::CPUAndNeuralEngine => "Neural Engine + CPU", + ComputeUnits::CPUOnly => "CPU", + } +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +fn memory_gb() -> f64 { + let pages = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) }; + let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + if pages <= 0 || size <= 0 { + return 8.0; + } + (pages as f64) * (size as f64) / 1e9 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recogniser_input_uses_arcface_normalisation() { + let mut rgb = vec![0u8; SIDE * SIDE * 3]; + rgb[0] = 255; + rgb[2] = 0; + let data = nchw(&rgb).unwrap(); + let plane = SIDE * SIDE; + assert_eq!(data.len(), plane * 3); + assert!((data[0] - 1.0).abs() < 1e-6); + assert!((data[2 * plane] - (-1.0)).abs() < 1e-6); + assert!(nchw(&[0u8; 3]).is_err()); + } + + #[test] + fn cosine_of_the_same_face_is_one() { + let face = vec![0.0f32, 0.6, 0.8]; + assert!((cosine(&face, &face) - 1.0).abs() < 1e-5); + assert_eq!(cosine(&face, &[1.0, 0.0]), 0.0); + let empty: Vec = Vec::new(); + assert_eq!(cosine(&empty, &empty), 0.0); + } + + /// Opt-in: `PHOTOREPORT_FACE_MODELS= cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --lib accelerator_matches -- --ignored --nocapture` + #[test] + #[ignore = "needs the ONNX models and a Mac accelerator"] + fn accelerator_matches_the_cpu_recogniser() { + let dir = std::env::var("PHOTOREPORT_FACE_MODELS").expect("PHOTOREPORT_FACE_MODELS"); + let models = Path::new(&dir); + let accel = open(models).expect("accelerator"); + assert!( + matches!(accel.label(), "all" | "gpu" | "ane"), + "{}", + accel.label() + ); + let rgb = pattern(0x2545_f491); + let engine = Engine::load(models, "auraface", 0.6).unwrap(); + let cpu = engine.embed_aligned(&rgb).unwrap(); + let gpu = accel.embed(&rgb).unwrap(); + let score = cosine(&cpu, &gpu); + assert!(score >= MIN_COSINE, "cosine {score}"); + } + + #[test] + fn unit_length_is_one() { + let vector = unit(&[0.0, 3.0, 4.0]).unwrap(); + let length = vector.iter().map(|value| value * value).sum::().sqrt(); + assert!((length - 1.0).abs() < 1e-5); + assert!(unit(&[0.0, 0.0]).is_err()); + assert!(unit(&[f32::NAN]).is_err()); + } +} diff --git a/apps/desktop/src-tauri/src/faces.rs b/apps/desktop/src-tauri/src/faces.rs index 8d8bd64..3cd08ce 100644 --- a/apps/desktop/src-tauri/src/faces.rs +++ b/apps/desktop/src-tauri/src/faces.rs @@ -1,5 +1,8 @@ -//! Read a folder for faces on this computer. Photos are not uploaded: the engine runs here, one copy per -//! core, and only a face that is not already named is sent to the server as its embedding. +//! Read a folder for faces on this computer. Photos are not uploaded. +//! +//! Detection runs on the CPU interpreter, one copy per core, so the boxes match the server. The recogniser +//! uses the GPU, the Neural Engine and the CPU together when those embeddings still match that interpreter +//! (`accel`). Only a face that is not already named is sent to the server as its embedding. //! //! Results stay on disk (the face, and the name for this game) so opening the same folder again does not //! read the photos a second time. @@ -15,6 +18,8 @@ use tauri::{AppHandle, Emitter}; use photoreport_faces::{Engine, FoundFace}; +use crate::accel::Accel; + const CPU_TARGET: f64 = 0.97; const MODEL_FILES: [&str; 2] = ["face_detection_yunet_2023mar.onnx", "glintr100.onnx"]; @@ -83,6 +88,11 @@ struct Progress { faces: Vec, } +#[derive(Clone, Serialize)] +struct AccelStatus { + accelerators: &'static str, +} + struct Job { path: PathBuf, key: String, @@ -213,9 +223,11 @@ fn memory_gb() -> f64 { } /// One engine per core, and only as many as memory can hold (each copy of the model is large). -fn engine_cap() -> usize { +/// `extra_gb` is RAM already taken by the accelerator, so the CPU copies leave room for it. +fn engine_cap(extra_gb: f64) -> usize { let cpus = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2); - let by_mem = ((memory_gb() - 2.0) / 0.7).floor().max(1.0) as usize; + let spare = (memory_gb() - 2.0 - extra_gb).max(0.7); + let by_mem = (spare / 0.7).floor().max(1.0) as usize; cpus.max(1).min(by_mem.max(1)) } @@ -317,7 +329,7 @@ async fn ensure_models(api: &str, token: &str, org_id: &str) -> Result>>, cancel: Arc, app: AppHandle, done: Arc, total: usize) { +fn run_jobs(dir: PathBuf, jobs: Arc>>, cancel: Arc, app: AppHandle, done: Arc, total: usize, accel: Option>) { let engine = match Engine::load(&dir, "auraface", 0.6) { Ok(engine) => engine, Err(err) => { @@ -337,7 +349,7 @@ fn run_jobs(dir: PathBuf, jobs: Arc>>, cancel: Arc, a emit_one(&app, &done, total, &job.path, true, true, false, None, &thumb, faces); continue; } - match engine.analyse(&job.path) { + match engine.analyse_with(&job.path, &mut |rgb| accel.as_ref().and_then(|device| device.embed(rgb).ok())) { Ok(read) => { let _ = write_json(&engine_file(&job.key), &EngineCache { faces: read.faces.clone() }); let thumb = thumb_jpeg(&job.path); @@ -375,7 +387,11 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String, return Ok(()); } let jobs = Arc::new(Mutex::new(pending)); - let cap = engine_cap(); + let accel = crate::accel::open(&models); + let accelerators = accel.as_ref().map(|item| item.label()).unwrap_or("cpu"); + let _ = app.emit("faces-accel", AccelStatus { accelerators }); + let extra = accel.as_ref().map(|item| item.reserved_gb()).unwrap_or(0.0); + let cap = engine_cap(extra); let mut handles: Vec> = Vec::new(); let mut sample = None; let _ = cpu_used(&mut sample); @@ -392,7 +408,8 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String, } break; } - if left > 0 && handles.len() < cap { + let gpu_full = accel.as_ref().is_some_and(|item| item.is_saturated()); + if left > 0 && handles.len() < cap && !gpu_full { let used = cpu_used(&mut sample).unwrap_or(0.0); let busy = handles.is_empty() || used < CPU_TARGET; if busy { @@ -403,7 +420,8 @@ fn scan_folder(app: AppHandle, folder: String, org_id: String, event_id: String, let app = app.clone(); let done = done.clone(); let dir = models.clone(); - handles.push(std::thread::spawn(move || run_jobs(dir, jobs, cancel, app, done, total))); + let accel = accel.clone(); + handles.push(std::thread::spawn(move || run_jobs(dir, jobs, cancel, app, done, total, accel))); } } } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index a0681d0..e9206ef 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -5,6 +5,7 @@ //! indexes the photographer's own folders for it; `deliver` saves deliveries to folders here and imports upload //! destinations from Photo Mechanic and FileZilla; `updater` keeps the shell itself current. +mod accel; mod card; mod catalog; mod faces; diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 96c746f..719a5ee 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,13 +1,14 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PhotoReport", - "version": "0.3.13", + "version": "0.3.14", "identifier": "pt.photoreport.desktop", "build": { "devUrl": "http://localhost:5173", "frontendDist": "../../app/dist", "beforeDevCommand": "pnpm --filter @photoreport/app dev", - "beforeBuildCommand": "pnpm --filter @photoreport/app build" + "beforeBuildCommand": "pnpm --filter @photoreport/app build", + "beforeBundleCommand": "bash ../../../infra/desktop/bundle-onnx.sh" }, "app": { "windows": [ @@ -28,6 +29,7 @@ }, "bundle": { "active": true, + "resources": ["onnx/"], "targets": "all", "category": "Photography", "shortDescription": "PhotoReport desktop", diff --git a/infra/desktop/bundle-onnx.sh b/infra/desktop/bundle-onnx.sh new file mode 100755 index 0000000..6ec9e75 --- /dev/null +++ b/infra/desktop/bundle-onnx.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Copies ONNX Runtime next to the desktop app so face recognition can use the GPU. +# A universal Mac build joins the Apple Silicon and Intel libraries. Linux has no GPU library +# in this build; the app still reads faces on the CPU. +set -euo pipefail + +if [[ "$(uname)" != Darwin ]]; then + exit 0 +fi + +root="$(cd "$(dirname "$0")/../.." && pwd)" +tauri="$root/apps/desktop/src-tauri" +dest="$tauri/onnx" +mkdir -p "$dest" + +files=() +while IFS= read -r found; do + files+=("$found") +done < <(find "$tauri/target" -name 'libonnxruntime*.dylib' \( -type f -o -type l \) 2>/dev/null || true) + +# Apple Silicon links ONNX Runtime into the app. A separate library is only copied when the build produced one. +if [[ ${#files[@]} -eq 0 ]]; then + echo "ONNX Runtime is linked into the app." + exit 0 +fi + +names="$(printf '%s\n' "${files[@]}" | xargs -n1 basename | sort -u)" +while IFS= read -r name; do + [[ -n "$name" ]] || continue + arm="" + x64="" + other="" + for candidate in "${files[@]}"; do + [[ "$(basename "$candidate")" == "$name" ]] || continue + info="$(lipo -info "$candidate" 2>/dev/null || true)" + if [[ "$info" == *arm64* && "$info" == *x86_64* ]]; then + other="$candidate" + elif [[ "$info" == *arm64* && -z "$arm" ]]; then + arm="$candidate" + elif [[ "$info" == *x86_64* && -z "$x64" ]]; then + x64="$candidate" + elif [[ -z "$other" ]]; then + other="$candidate" + fi + done + out="$dest/$name" + if [[ -n "$arm" && -n "$x64" ]]; then + lipo -create "$arm" "$x64" -output "$out" + elif [[ -n "$other" ]]; then + cp -fL "$other" "$out" + elif [[ -n "$arm" ]]; then + cp -fL "$arm" "$out" + else + cp -fL "$x64" "$out" + fi +done <<< "$names" + +if [[ ! -e "$dest/libonnxruntime.dylib" ]]; then + first="$(find "$dest" -name 'libonnxruntime*.dylib' -type f | head -1 || true)" + if [[ -n "${first}" ]]; then + cp -f "$first" "$dest/libonnxruntime.dylib" + fi +fi + +shopt -s nullglob +for lib in "$dest"/*.dylib; do + base="$(basename "$lib")" + install_name_tool -id "@rpath/${base}" "$lib" || true + install_name_tool -add_rpath @loader_path "$lib" 2>/dev/null || true + while IFS= read -r dep; do + [[ -n "$dep" ]] || continue + dep_base="$(basename "$dep")" + if [[ -f "$dest/$dep_base" && "$dep" != "@rpath/$dep_base" && "$dep" != "@loader_path/$dep_base" ]]; then + install_name_tool -change "$dep" "@loader_path/$dep_base" "$lib" || true + fi + done < <(otool -L "$lib" | awk 'NR>1 { print $1 }') + codesign --force --sign - "$lib" >/dev/null 2>&1 || true +done + +count="$(find "$dest" -name 'libonnxruntime*.dylib' -type f | wc -l | tr -d ' ')" +echo "bundled ${count} ONNX Runtime libraries" diff --git a/workers/faces/src/lib.rs b/workers/faces/src/lib.rs index 3ce4e79..2176b66 100644 --- a/workers/faces/src/lib.rs +++ b/workers/faces/src/lib.rs @@ -51,7 +51,10 @@ fn load(dir: &Path, embedder: &str) -> Result { let det_path = dir.join("face_detection_yunet_2023mar.onnx"); let det_bytes = std::fs::read(&det_path).map_err(|e| format!("{}: {e}", det_path.display()))?; if Some(sha256(&det_bytes).as_str()) != yunet.sha256.as_deref() { - return Err(format!("{} does not match the published YuNet file", det_path.display())); + return Err(format!( + "{} does not match the published YuNet file", + det_path.display() + )); } let detector = Detector::new(&det_bytes).map_err(|e| e.to_string())?; @@ -62,7 +65,11 @@ fn load(dir: &Path, embedder: &str) -> Result { let emb_path: PathBuf = dir.join(file); let emb_bytes = std::fs::read(&emb_path).map_err(|e| format!("{}: {e}", emb_path.display()))?; if Some(sha256(&emb_bytes).as_str()) != manifest.sha256.as_deref() { - return Err(format!("{} does not match the published {} file", emb_path.display(), manifest.name)); + return Err(format!( + "{} does not match the published {} file", + emb_path.display(), + manifest.name + )); } drop(emb_bytes); let embedder = Embedder::load(&emb_path, &manifest).map_err(|e| e.to_string())?; @@ -82,7 +89,11 @@ fn sharpness(rgb: &[u8], w: usize, h: usize) -> f32 { let (mut n, mut sum, mut sq) = (0f64, 0f64, 0f64); for y in (h / 4).max(1)..(h * 3 / 4).min(h - 1) { for x in (w / 4).max(1)..(w * 3 / 4).min(w - 1) { - let l = 4.0 * grey(x, y) - grey(x - 1, y) - grey(x + 1, y) - grey(x, y - 1) - grey(x, y + 1); + let l = 4.0 * grey(x, y) + - grey(x - 1, y) + - grey(x + 1, y) + - grey(x, y - 1) + - grey(x, y + 1); n += 1.0; sum += f64::from(l); sq += f64::from(l) * f64::from(l); @@ -98,7 +109,10 @@ fn sharpness(rgb: &[u8], w: usize, h: usize) -> f32 { impl Engine { /// Loads YuNet and the recognition model (`auraface` or `sface`). Checks each file against its published SHA-256. pub fn load(dir: &Path, embedder: &str, min_score: f32) -> Result { - Ok(Engine { models: load(dir, embedder)?, min_score }) + Ok(Engine { + models: load(dir, embedder)?, + min_score, + }) } pub fn dim(&self) -> u64 { @@ -108,14 +122,32 @@ impl Engine { } } + /// The unit-length embedding of one already aligned face. Same picture the recogniser inside `analyse` sees. + pub fn embed_aligned(&self, rgb: &[u8]) -> Result, String> { + self.models.embedder.embed(rgb).map_err(|e| e.to_string()) + } + /// Faces in one upright JPEG (EXIF orientation applied), with an embedding when the face can be aligned. pub fn analyse(&self, path: &Path) -> Result { + self.analyse_with(path, &mut |_| None) + } + + /// Like `analyse`. `embed` may replace the CPU recogniser for an aligned face. + /// + /// `None`, or a vector that is the wrong length, keeps the CPU recogniser. Callers use that to try a + /// faster device and still name the face when the device is missing or disagrees. + pub fn analyse_with( + &self, + path: &Path, + embed: &mut dyn FnMut(&[u8]) -> Option>, + ) -> Result { let mut decoder = image::ImageReader::open(path) .and_then(|r| r.with_guessed_format()) .map_err(|e| e.to_string())? .into_decoder() .map_err(|e| e.to_string())?; - let orientation = image::ImageDecoder::orientation(&mut decoder).unwrap_or(image::metadata::Orientation::NoTransforms); + let orientation = image::ImageDecoder::orientation(&mut decoder) + .unwrap_or(image::metadata::Orientation::NoTransforms); let mut dynamic = image::DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?; dynamic.apply_orientation(orientation); let img = dynamic.into_rgb8(); @@ -124,17 +156,30 @@ impl Engine { let faces = self .models .detector - .detect(&rgb, w, h, &Options { score: self.min_score, ..Options::default() }) + .detect( + &rgb, + w, + h, + &Options { + score: self.min_score, + ..Options::default() + }, + ) .map_err(|e| e.to_string())?; - let pic = Rgb { data: &rgb, width: w, height: h }; + let pic = Rgb { + data: &rgb, + width: w, + height: h, + }; let (iw, ih) = self.models.embedder.input_size(); + let want = usize::try_from(self.dim()).unwrap_or(0); let out = faces .iter() .map(|f| { let px = f.landmarks.map(|(x, y)| (x * w as f32, y * h as f32)); let crop = align_to_template(&pic, &px, iw, ih); let sharpness = crop.as_deref().map(|c| sharpness(c, iw, ih)); - let embedding = crop.and_then(|c| self.models.embedder.embed(&c).ok()); + let embedding = crop.and_then(|c| self.embedding_of(&c, want, embed)); FoundFace { x0: f.x0.clamp(0.0, 1.0), y0: f.y0.clamp(0.0, 1.0), @@ -147,6 +192,24 @@ impl Engine { } }) .collect(); - Ok(Analysed { width: w, height: h, faces: out }) + Ok(Analysed { + width: w, + height: h, + faces: out, + }) + } + + fn embedding_of( + &self, + crop: &[u8], + want: usize, + embed: &mut dyn FnMut(&[u8]) -> Option>, + ) -> Option> { + if let Some(vector) = embed(crop) { + if vector.len() == want && vector.iter().all(|value| value.is_finite()) { + return Some(vector); + } + } + self.models.embedder.embed(crop).ok() } } -- 2.47.3