capsule_core/ml/runner.rs
1//! The inference seam — a [`ModelRunner`] trait the orchestrator consumes, plus a deterministic
2//! [`FixtureRunner`] for tests (SSoT: [AI/ML Integrations]).
3//!
4//! Real per-platform runners (ONNX Runtime / CoreML / NNAPI) implement this trait behind the
5//! **default-off, weight-fetching `inference` feature** (the real CLIP runner is a feature-gated
6//! follow-up — it downloads weights at runtime, so it is never part of the default gate). Until
7//! then [`FixtureRunner`] stands in — exactly as
8//! [`ReferenceAuthority`](crate::crypto::authority::ReferenceAuthority) stands in for live MLS
9//! behind [`AlbumAuthority`](crate::crypto::authority::AlbumAuthority). The fixture maps an input's
10//! bytes to a reproducible L2-normalized vector by expanding SHA-256, so identical content embeds
11//! identically and semantic matches are testable without any model weights.
12//!
13//! The runner works over **decoded pixels** conceptually (a real runner decodes + resizes the
14//! frame bytes and runs the model); the fixture hashes the bytes. Two embedding tasks produce
15//! stored vectors ([`SemanticSearch`](TaskKind::SemanticSearch),
16//! [`FaceRecognition`](TaskKind::FaceRecognition)); the two detection tasks
17//! ([`ObjectDetection`](TaskKind::ObjectDetection), [`FaceDetection`](TaskKind::FaceDetection))
18//! produce boxes/landmarks that feed downstream stages.
19//!
20//! [AI/ML Integrations]: https://docs/design/ai/
21
22use thiserror::Error;
23
24use crate::crypto::hash;
25use crate::ml::{ModelId, ModelVersion, Registry, TaskKind};
26
27/// An embedding vector (L2-normalized by convention, so cosine ranks like the inner product).
28pub type Embedding = Vec<f32>;
29
30/// One image (or video keyframe) handed to a runner. The offline core passes the asset's bytes; a
31/// real runner decodes + runs the model, the fixture hashes them.
32#[derive(Debug, Clone, Copy)]
33pub struct Frame<'a> {
34 /// The image bytes.
35 pub bytes: &'a [u8],
36}
37
38impl<'a> Frame<'a> {
39 /// A frame over `bytes`.
40 pub fn new(bytes: &'a [u8]) -> Self {
41 Self { bytes }
42 }
43}
44
45/// A normalized bounding box (coordinates in `[0, 1]`).
46#[derive(Debug, Clone, Copy, PartialEq)]
47pub struct BBox {
48 /// Left.
49 pub x: f32,
50 /// Top.
51 pub y: f32,
52 /// Width.
53 pub w: f32,
54 /// Height.
55 pub h: f32,
56}
57
58/// A detection from a detection task (object box, face box + landmarks downstream).
59#[derive(Debug, Clone, PartialEq)]
60pub struct Detection {
61 /// Where.
62 pub bbox: BBox,
63 /// Optional class label.
64 pub label: Option<String>,
65 /// Confidence in `[0, 1]`.
66 pub score: f32,
67}
68
69/// Errors a runner can return.
70#[derive(Debug, Error, PartialEq, Eq)]
71pub enum RunnerError {
72 /// The runner cannot serve this task (e.g. an embedding call on a detection task).
73 #[error("runner does not support task {0:?}")]
74 Unsupported(TaskKind),
75 /// Inference failed.
76 #[error("inference failed: {0}")]
77 Inference(String),
78}
79
80/// The inference seam every consumer routes through. Implemented by real per-platform runners
81/// (behind the `inference` feature) and by [`FixtureRunner`] for tests.
82pub trait ModelRunner {
83 /// The platform partition tag for this runner's outputs (incomparable across platforms).
84 fn platform(&self) -> &str;
85
86 /// The `(model_id, model_version)` this runner produces for `task`, if it serves it. Must equal
87 /// the registry's canonical row for the output to be accepted by the index.
88 fn model(&self, task: TaskKind) -> Option<(ModelId, ModelVersion)>;
89
90 /// Embed images for an embedding task (`SemanticSearch`, `FaceRecognition`). One vector per
91 /// frame, in order.
92 fn embed_image(
93 &self,
94 task: TaskKind,
95 frames: &[Frame<'_>],
96 ) -> Result<Vec<Embedding>, RunnerError>;
97
98 /// Embed text into the semantic-search space — for natural-language queries and the zero-shot
99 /// tagging that reuses the semantic embedder.
100 fn embed_text(&self, texts: &[&str]) -> Result<Vec<Embedding>, RunnerError>;
101
102 /// Detect objects / faces for a detection task (`ObjectDetection`, `FaceDetection`). One list
103 /// per frame, in order.
104 fn detect(
105 &self,
106 task: TaskKind,
107 frames: &[Frame<'_>],
108 ) -> Result<Vec<Vec<Detection>>, RunnerError>;
109}
110
111/// Expand SHA-256 of `(model, bytes)` into a deterministic, L2-normalized `dim`-vector.
112///
113/// `model` is the `(model_id, model_version)` the caller declares, folded into the digest so the
114/// fixture models the one property a real model swap has: **a version bump changes the output for
115/// unchanged pixels**. Without the fold a "v2" fixture would reproduce v1's vectors byte-for-byte
116/// and a regeneration could not be distinguished from copying the stale vector forward — which is
117/// exactly what E2E case 10 (the index is in `capsule-e2e`) has to tell apart.
118/// Within one version the fixture keeps its contract: identical bytes produce an identical vector,
119/// distinct bytes produce near-orthogonal ones, and image bytes embed identically to the same text
120/// (both fold the same semantic-search pair).
121fn deterministic_embedding(model: &str, bytes: &[u8], dim: usize) -> Embedding {
122 let mut out: Embedding = Vec::with_capacity(dim);
123 let mut counter: u32 = 0;
124 while out.len() < dim {
125 let mut input = Vec::with_capacity(model.len() + bytes.len() + 5);
126 input.extend_from_slice(model.as_bytes());
127 // A byte that cannot occur in the UTF-8 `model` tag, so `(model, bytes)` is unambiguous.
128 input.push(0xFF);
129 input.extend_from_slice(bytes);
130 input.extend_from_slice(&counter.to_le_bytes());
131 let digest = hash::hash_bytes(&input);
132 for pair in digest.0.chunks_exact(2) {
133 if out.len() == dim {
134 break;
135 }
136 // Map two bytes to roughly [-1, 1).
137 let v = i16::from_le_bytes([pair[0], pair[1]]) as f32 / 32768.0;
138 out.push(v);
139 }
140 counter += 1;
141 }
142 l2_normalize(&mut out);
143 out
144}
145
146fn l2_normalize(v: &mut [f32]) {
147 let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
148 if norm > 0.0 {
149 for x in v.iter_mut() {
150 *x /= norm;
151 }
152 }
153}
154
155/// A deterministic, weightless runner for tests. Declares the canonical model versions from a
156/// [`Registry`] (so its outputs satisfy the embedding-provenance invariant) and embeds by hashing
157/// input bytes — content equality ⇒ vector equality, which makes semantic matches reproducible.
158#[derive(Debug, Clone)]
159pub struct FixtureRunner {
160 platform: String,
161 registry: Registry,
162}
163
164impl FixtureRunner {
165 /// A fixture on `platform` declaring the canonical inventory's model versions.
166 pub fn new(platform: &str) -> Self {
167 Self {
168 platform: platform.to_string(),
169 registry: Registry::canonical(),
170 }
171 }
172
173 /// A fixture whose declared model versions come from `registry` — for simulating a model swap
174 /// (a runner that produces the *new* canonical version after a bump).
175 pub fn with_registry(platform: &str, registry: Registry) -> Self {
176 Self {
177 platform: platform.to_string(),
178 registry,
179 }
180 }
181
182 fn dim(&self, task: TaskKind) -> Result<usize, RunnerError> {
183 self.registry
184 .dim_for(task)
185 .map(crate::ml::EmbeddingDim::get)
186 .ok_or(RunnerError::Unsupported(task))
187 }
188
189 /// The digest-domain tag for `task`'s canonical pair — what makes the fixture's output
190 /// version-sensitive (see [`deterministic_embedding`]).
191 fn model_tag(&self, task: TaskKind) -> Result<String, RunnerError> {
192 let row = self
193 .registry
194 .canonical_for(task)
195 .ok_or(RunnerError::Unsupported(task))?;
196 Ok(format!("{}@{}", row.model_id, row.canonical_version))
197 }
198}
199
200impl ModelRunner for FixtureRunner {
201 fn platform(&self) -> &str {
202 &self.platform
203 }
204
205 fn model(&self, task: TaskKind) -> Option<(ModelId, ModelVersion)> {
206 self.registry
207 .canonical_for(task)
208 .map(|r| (r.model_id.clone(), r.canonical_version.clone()))
209 }
210
211 fn embed_image(
212 &self,
213 task: TaskKind,
214 frames: &[Frame<'_>],
215 ) -> Result<Vec<Embedding>, RunnerError> {
216 let dim = self.dim(task)?;
217 let model = self.model_tag(task)?;
218 Ok(frames
219 .iter()
220 .map(|f| deterministic_embedding(&model, f.bytes, dim))
221 .collect())
222 }
223
224 fn embed_text(&self, texts: &[&str]) -> Result<Vec<Embedding>, RunnerError> {
225 // Text shares the semantic-search space — same model tag, so identical content still
226 // embeds identically across the image and text sides.
227 let dim = self.dim(TaskKind::SemanticSearch)?;
228 let model = self.model_tag(TaskKind::SemanticSearch)?;
229 Ok(texts
230 .iter()
231 .map(|t| deterministic_embedding(&model, t.as_bytes(), dim))
232 .collect())
233 }
234
235 fn detect(
236 &self,
237 task: TaskKind,
238 frames: &[Frame<'_>],
239 ) -> Result<Vec<Vec<Detection>>, RunnerError> {
240 match task {
241 TaskKind::ObjectDetection | TaskKind::FaceDetection => {
242 // The fixture has no real detector; it reports no detections deterministically.
243 Ok(frames.iter().map(|_| Vec::new()).collect())
244 }
245 other => Err(RunnerError::Unsupported(other)),
246 }
247 }
248}
249
250#[cfg(test)]
251mod tests;