M13.36: face tracking trained model — MediaPipe Face Landmarker on a pure-Rust TFLite interpreter

- effectcraft-segment: a FaceModel interface (find a face in a region, follow it; a Topology
  maps the model's points to the tracker's landmarks and outline), a TensorFlow Lite reader and
  interpreter (float ops, float16 weights folded; matches ai-edge-litert to ~1e-6), and
  MediaPipe Face Landmarker (Google, Apache-2.0: BlazeFace + Face Mesh V2, 3.8 MB, pinned
  SHA-256). The registry gains a task and authors per model; installed weights get a NOTICE.
- effectcraft-track: FaceTracker::new_with uses the model, falls back to the classical fitter
  when it finds no face; chin and jaw come from the outline either way so measurements agree.
- Engine: roto_models becomes models (both tasks); face.models / face.model.* commands,
  Settings ▸ Face Tracking, `wait` on select/install/download for scripts; track.mask reports
  faceModel.
- Credits: ATTRIBUTION.md lists the optional models and the Apache-2.0 specs the code follows.
- Docs: README, ROADMAP (G7), gaps, parity (TRK-3 score unchanged pending G1), agents,
  preferences, architecture, segment README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatastic
2026-10-05 20:39:45 +07:00
co-authored by Claude Opus 5.5
parent 4624c00308
commit e43bf66775
33 changed files with 2298 additions and 485 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "effectcraft-segment"
description = "Swappable trained segmentation models for Roto Brush: the MaskModel interface, a registry of open-licensed models, a PyTorch checkpoint reader and a pure-Rust MobileSAM (TinyViT + SAM prompt encoder and mask decoder)"
description = "Swappable trained models for Roto Brush and face tracking: the MaskModel and FaceModel interfaces, a registry of open-licensed models, PyTorch checkpoint and TensorFlow Lite readers, a pure-Rust MobileSAM and MediaPipe Face Landmarker"
version.workspace = true
edition.workspace = true
license.workspace = true
+45 -19
View File
@@ -1,38 +1,64 @@
# effectcraft-segment
Trained segmentation models for Roto Brush, behind one swappable interface.
Trained models for Roto Brush and face tracking, each kind behind one swappable interface.
- **`MaskModel`**: what Roto Brush asks of a model: given a frame and prompts (foreground /
background points, a box, a prior mask), the foreground probability of every pixel. Roto Brush
(`effectcraft-track`) only talks to this trait, so models can be added or swapped without
touching it. The classical graph-cut segmenter stays built in as the fallback.
- **`face::FaceModel`**: what face tracking asks of a model: find a face in a region of a frame,
then follow it from frame to frame. A model reports its own points plus a `Topology` naming
which are the tracker's landmarks and which trace the face outline, so the tracker never
depends on one model's layout. The classical face tracker stays built in as the fallback.
- **`MODELS`**: the registry. Every entry must be open source under a licence compatible with
EffectCraft's MIT OR Apache-2.0 (`ALLOWED_LICENCES`), with its homepage, licence URL, the
official weights URL, size and SHA-256. `load` refuses anything else.
EffectCraft's MIT OR Apache-2.0 (`ALLOWED_LICENCES`), with its task, authors, homepage, licence
URL, the official weights URL, size and SHA-256. `load` refuses anything else.
- **Weights are never bundled.** They are downloaded on demand (or installed from a file) by the
engine (`roto.model.*`, Settings ▸ Roto Brush) and verified against the registry's SHA-256
(`sha256`, dependency-free).
engine (`roto.model.*` / `face.model.*`, Settings ▸ Roto Brush / Face Tracking), verified
against the registry's SHA-256 (`sha256`, dependency-free) and kept with a notice naming their
authors, licence and source (`notice`).
- **`pt`**: reads PyTorch checkpoints (`torch.save` zip archives and the pickle subset state dicts
use), so official weights load exactly as published.
- **`tflite`**: reads TensorFlow Lite models (the FlatBuffer laid out by TensorFlow Lite's
`schema.fbs`) and runs the float operators small vision models use (convolutions, depthwise
convolutions, pooling, PReLU, padding, concatenation; float16 weights dequantised at load).
- **`mobilesam`**: MobileSAM in plain Rust: the TinyViT-5M image encoder and Segment Anything's
prompt encoder and two-way-transformer mask decoder, on `nn` kernels (rayon, and ndarray's safe
`general_mat_mul`, which picks AVX/FMA kernels at run time). No ML framework, no unsafe code.
prompt encoder and two-way-transformer mask decoder.
- **`mediapipe`**: MediaPipe Face Landmarker: the BlazeFace short-range detector (SSD anchors,
weighted non-maximum suppression) and Face Mesh V2 (478 points), with the rotated crops
MediaPipe's face landmarker graph uses.
All of it runs on `nn` kernels (rayon, and ndarray's safe `general_mat_mul`, which picks AVX/FMA
kernels at run time). No ML framework, no unsafe code.
## Models
| id | Model | Licence | Weights | Size |
|---|---|---|---|---|
| `mobilesam` | [MobileSAM](https://github.com/ChaoningZhang/MobileSAM) (C. Zhang et al., 2023): Segment Anything with a 5M-parameter TinyViT encoder | Apache-2.0 | `mobile_sam.pt` from the official repository | 40.7 MB |
| id | Task | Model | Authors | Licence | File | Size |
|---|---|---|---|---|---|---|
| `mobilesam` | Roto Brush | [MobileSAM](https://github.com/ChaoningZhang/MobileSAM): Segment Anything with a 5M-parameter TinyViT encoder | Chaoning Zhang et al., building on Meta AI's Segment Anything and Microsoft's TinyViT | Apache-2.0 | `mobile_sam.pt` from the official repository | 40.7 MB |
| `mediapipe-face` | Face tracking | [MediaPipe Face Landmarker](https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker): BlazeFace detector and Face Mesh V2 | Google LLC | Apache-2.0 ([model card](https://storage.googleapis.com/mediapipe-assets/Model%20Card%20MediaPipe%20Face%20Mesh%20V2.pdf)) | `face_landmarker.task` (float16, version 1) from Google's model storage | 3.8 MB |
The implementation follows the published architectures (MobileSAM, TinyViT and Segment Anything
papers and their Apache-2.0 reference code); its output was checked against an independent
implementation (Hugging Face candle's, MIT/Apache-2.0) on the same weights: embeddings within 0.3%
RMS (exact vs. tanh GELU) and 99.9% of mask pixels equal.
How they were checked:
- **MobileSAM**: the implementation follows the published architectures (MobileSAM, TinyViT and
Segment Anything papers and their Apache-2.0 reference code). Its output was checked against an
independent implementation (Hugging Face candle's, MIT/Apache-2.0) on the same weights:
embeddings within 0.3% RMS (exact vs. tanh GELU) and 99.9% of mask pixels equal.
- **MediaPipe Face Landmarker**: the interpreter's outputs match TensorFlow Lite's own
(`ai-edge-litert` 2.2.0) on both models to about one part in a million (a test pins them). The
whole pipeline's 478 points on a test portrait are 0.85 px from MediaPipe's own Python pipeline
on average (2.2 px at worst). Finding a face takes about 45 ms; following it, about 20 ms a
frame (32-thread CPU).
Tests that need the weights run when `EFFECTCRAFT_MOBILESAM` / `EFFECTCRAFT_FACE_LANDMARKER`
point at the files, and are skipped otherwise.
## Adding a model
1. Pick a model whose code **and** weights are open source under an allowed licence.
2. Add a `ModelInfo` to `MODELS` (pin the official file's SHA-256 and size).
3. Implement `MaskModel` for it and add its loader to `load`.
4. Test it against a reference implementation; Roto Brush, Settings and the `roto.model.*`
commands pick it up from the registry.
1. Pick a model whose code **and** weights are open source under an allowed licence. Check the
weights' own terms: many models with MIT code ship weights trained on research-only data.
2. Add a `ModelInfo` to `MODELS` (its task and authors; pin the official file's SHA-256 and size),
and credit it in the root `ATTRIBUTION.md`.
3. Implement `MaskModel` or `FaceModel` for it and add its loader to `load`.
4. Test it against a reference implementation; Settings, the `roto.model.*` / `face.model.*`
commands and the tools pick it up from the registry.
+115
View File
@@ -0,0 +1,115 @@
//! Trained face models for face tracking, behind one swappable interface.
//!
//! - [`FaceModel`]: what the face tracker (`effectcraft-track`) asks of a model: find a face in a
//! region of a frame, then follow it from frame to frame. A model reports its own points (a
//! mesh, for MediaPipe) plus a [`Topology`] saying which of them are the tracker's named
//! landmarks and which trace the face outline, so the tracker never depends on one model's
//! layout. The classical tracker stays built in as the fallback when no model is chosen.
//! - [`Roi`] and [`crop`]: the rotated square crops face models look at.
use crate::{ModelInfo, Result};
/// Which of a model's points are the tracker's landmarks and its face outline.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Topology {
/// The points tracing the face outline, in order around the face.
pub outline: &'static [usize],
/// (landmark id, as the tracker names them, e.g. `leftEyeInner`; point index). "Left" is
/// image-left. Chin and jaw come from the outline.
pub landmarks: &'static [(&'static str, usize)],
}
/// A face in a frame: the model's points (frame pixels) and its confidence (0–1).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Face {
pub points: Vec<[f32; 2]>,
pub score: f32,
}
/// A trained face model (swappable: the face tracker only uses this interface). Frames are
/// straight RGB 0–1, row-major `w×h`, coordinates frame pixels.
pub trait FaceModel: Send + Sync {
fn info(&self) -> &'static ModelInfo;
fn topology(&self) -> &'static Topology;
/// The most confident face whose centre lies in `region` (`[x0, y0, x1, y1]`).
fn find(&self, rgb: &[[f32; 3]], w: usize, h: usize, region: [f32; 4]) -> Result<Option<Face>>;
/// The face `prev` was in the previous frame, in this one; `None` when it is lost.
fn follow(&self, rgb: &[[f32; 3]], w: usize, h: usize, prev: &Face) -> Result<Option<Face>>;
}
/// A rotated square region of a frame: centre, side and angle (radians, the direction of the
/// square's x axis in the frame, y down).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Roi {
pub center: [f32; 2],
pub size: f32,
pub angle: f32,
}
impl Roi {
/// Frame position of the normalised square position `(u, v)` (0–1).
pub fn to_frame(&self, u: f32, v: f32) -> [f32; 2] {
let (s, c) = self.angle.sin_cos();
let (x, y) = ((u - 0.5) * self.size, (v - 0.5) * self.size);
[self.center[0] + c * x - s * y, self.center[1] + s * x + c * y]
}
}
/// Sample `roi` into an `n×n` RGB tensor (bilinear; zero outside the frame), each channel mapped
/// from 0–1 to `lo`–`hi`.
pub fn crop(rgb: &[[f32; 3]], w: usize, h: usize, roi: &Roi, n: usize, [lo, hi]: [f32; 2]) -> Vec<f32> {
let mut out = vec![0.0f32; n * n * 3];
if rgb.len() < w * h || n == 0 {
return out;
}
let px = |x: i64, y: i64| -> [f32; 3] {
if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 { [0.0; 3] } else { rgb.get(y as usize * w + x as usize).copied().unwrap_or([0.0; 3]) }
};
for j in 0..n {
for i in 0..n {
let p = roi.to_frame((i as f32 + 0.5) / n as f32, (j as f32 + 0.5) / n as f32);
let (x, y) = (p[0] - 0.5, p[1] - 0.5);
let (x0, y0) = (x.floor(), y.floor());
let (fx, fy) = (x - x0, y - y0);
let (x0, y0) = (x0 as i64, y0 as i64);
let (a, b, c, d) = (px(x0, y0), px(x0 + 1, y0), px(x0, y0 + 1), px(x0 + 1, y0 + 1));
for k in 0..3 {
let v = (a[k] * (1.0 - fx) + b[k] * fx) * (1.0 - fy) + (c[k] * (1.0 - fx) + d[k] * fx) * fy;
out[(j * n + i) * 3 + k] = lo + v * (hi - lo);
}
}
}
out
}
pub(crate) fn sigmoid(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roi_maps_corners_and_rotates() {
let r = Roi { center: [10.0, 20.0], size: 4.0, angle: 0.0 };
assert_eq!(r.to_frame(0.0, 0.0), [8.0, 18.0]);
assert_eq!(r.to_frame(1.0, 1.0), [12.0, 22.0]);
// A quarter turn: the square's x axis points down the frame.
let q = Roi { angle: std::f32::consts::FRAC_PI_2, ..r };
let p = q.to_frame(1.0, 0.5);
assert!((p[0] - 10.0).abs() < 1e-5 && (p[1] - 22.0).abs() < 1e-5);
}
#[test]
fn crop_samples_pixel_centres() {
// A 4×4 ramp cropped 1:1 reproduces it; outside the frame is zero.
let rgb: Vec<[f32; 3]> = (0..16).map(|i| [i as f32 / 16.0, 0.0, 1.0]).collect();
let c = crop(&rgb, 4, 4, &Roi { center: [2.0, 2.0], size: 4.0, angle: 0.0 }, 4, [0.0, 1.0]);
for i in 0..16 {
assert!((c[i * 3] - i as f32 / 16.0).abs() < 1e-6);
}
let c = crop(&rgb, 4, 4, &Roi { center: [-10.0, -10.0], size: 4.0, angle: 0.0 }, 2, [-1.0, 1.0]);
assert!(c.iter().all(|v| *v == -1.0));
}
}
+74 -13
View File
@@ -1,21 +1,28 @@
//! Trained segmentation models for Roto Brush, behind one swappable interface.
//! Trained models for Roto Brush and face tracking, each kind behind one swappable interface.
//!
//! - [`MaskModel`]: what Roto Brush asks of a model, the foreground probability of each pixel of a
//! frame given prompts (foreground / background points from the strokes, a box, a prior mask).
//! Anything implementing it can be plugged in; the classical graph-cut segmenter in
//! `effectcraft-track` stays the built-in fallback when no model is chosen.
//! - [`face::FaceModel`]: what face tracking asks of a model: find a face in a region, follow it
//! from frame to frame. The classical face tracker stays the built-in fallback.
//! - [`MODELS`]: the registry. Every entry is open source under a licence compatible with
//! EffectCraft's (MIT OR Apache-2.0), with its source, size and SHA-256. Weights are never
//! bundled: they are fetched on demand (or installed from a file), verified ([`sha256`]) and
//! loaded by [`load`].
//! - [`pt`]: a PyTorch checkpoint reader, so official weights load as published.
//! - [`mobilesam`]: MobileSAM (Apache-2.0) in plain Rust ([`nn`] kernels on rayon).
//! EffectCraft's (MIT OR Apache-2.0), with its authors, source, size and SHA-256. Weights are
//! never bundled: they are fetched on demand (or installed from a file), verified ([`sha256`])
//! and loaded by [`load`].
//! - [`pt`]: a PyTorch checkpoint reader; [`tflite`]: a TensorFlow Lite reader and interpreter;
//! so official weights load as published.
//! - [`mobilesam`]: MobileSAM (Apache-2.0) and [`mediapipe`]: MediaPipe Face Landmarker
//! (Apache-2.0), in plain Rust ([`nn`] kernels on rayon).
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::todo, clippy::unreachable)]
pub mod face;
pub mod mediapipe;
pub mod mobilesam;
pub mod nn;
pub mod pt;
pub mod tflite;
use std::sync::Arc;
@@ -40,12 +47,24 @@ pub trait MaskModel: Send + Sync {
fn segment(&self, rgb: &[[f32; 3]], w: usize, h: usize, prompt: &Prompt) -> Result<Vec<f32>>;
}
/// A model in the registry: what it is, its licence and where its weights come from.
/// What a model is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Task {
/// Roto Brush ([`MaskModel`]).
Mask,
/// Face tracking ([`face::FaceModel`]).
Face,
}
/// A model in the registry: what it is, who made it, its licence and where its weights come from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ModelInfo {
pub id: &'static str,
pub task: Task,
pub name: &'static str,
pub description: &'static str,
/// Who made it (shown with the model, and in ATTRIBUTION.md).
pub authors: &'static str,
/// SPDX licence of the weights and the architecture.
pub licence: &'static str,
pub licence_url: &'static str,
@@ -64,8 +83,10 @@ pub const ALLOWED_LICENCES: &[&str] = &["MIT", "Apache-2.0", "BSD-2-Clause", "BS
pub const MOBILE_SAM: ModelInfo = ModelInfo {
id: "mobilesam",
task: Task::Mask,
name: "MobileSAM",
description: "Segment Anything distilled to a 5M-parameter TinyViT encoder (C. Zhang et al., 2023). Turns your strokes into a clean matte and tidies every propagated frame.",
authors: "Chaoning Zhang et al. (MobileSAM), building on Meta AI's Segment Anything and Microsoft's TinyViT",
licence: "Apache-2.0",
licence_url: "https://github.com/ChaoningZhang/MobileSAM/blob/master/LICENSE",
homepage: "https://github.com/ChaoningZhang/MobileSAM",
@@ -75,18 +96,46 @@ pub const MOBILE_SAM: ModelInfo = ModelInfo {
sha256: "6dbb90523a35330fedd7f1d3dfc66f995213d81b29a5ca8108dbcdd4e37d6c2f",
};
/// The models Roto Brush can use besides the built-in classical segmenter.
pub const MODELS: &[ModelInfo] = &[MOBILE_SAM];
pub const FACE_LANDMARKER: ModelInfo = ModelInfo {
id: "mediapipe-face",
task: Task::Face,
name: "MediaPipe Face Landmarker",
description: "Google's BlazeFace detector and 478-point Face Mesh V2. Follows faces turned to the side, partly covered or in difficult light, where the classic tracker loses them.",
authors: "Google LLC (MediaPipe)",
licence: "Apache-2.0",
licence_url: "https://storage.googleapis.com/mediapipe-assets/Model%20Card%20MediaPipe%20Face%20Mesh%20V2.pdf",
homepage: "https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker",
url: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",
file_name: "face_landmarker.task",
size: 3_758_596,
sha256: "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff",
};
/// The id of the built-in classical (graph cut) segmenter: no weights, always available.
/// The trained models, besides the built-in classical engines.
pub const MODELS: &[ModelInfo] = &[MOBILE_SAM, FACE_LANDMARKER];
/// The id of the built-in classical engines (graph cut segmenter, shape-model face tracker): no
/// weights, always available.
pub const CLASSICAL: &str = "classical";
pub fn info(id: &str) -> Option<&'static ModelInfo> {
MODELS.iter().find(|m| m.id == id)
}
/// The models for `task`.
pub fn models(task: Task) -> impl Iterator<Item = &'static ModelInfo> {
MODELS.iter().filter(move |m| m.task == task)
}
/// A loaded model.
#[derive(Clone)]
pub enum Loaded {
Mask(Arc<dyn MaskModel>),
Face(Arc<dyn face::FaceModel>),
}
/// Check a weights file against the registry and build the model.
pub fn load(id: &str, bytes: &[u8]) -> Result<Arc<dyn MaskModel>> {
pub fn load(id: &str, bytes: &[u8]) -> Result<Loaded> {
let info = info(id).ok_or_else(|| format!("unknown model `{id}`"))?;
if !ALLOWED_LICENCES.contains(&info.licence) {
return Err(format!("{}: licence {} is not allowed", info.name, info.licence));
@@ -98,12 +147,21 @@ pub fn load(id: &str, bytes: &[u8]) -> Result<Arc<dyn MaskModel>> {
match id {
"mobilesam" => {
let w = pt::read(bytes)?;
Ok(Arc::new(Sam { net: mobilesam::MobileSam::from_weights(&w)? }))
Ok(Loaded::Mask(Arc::new(Sam { net: mobilesam::MobileSam::from_weights(&w)? })))
}
"mediapipe-face" => Ok(Loaded::Face(Arc::new(mediapipe::FaceLandmarker::from_task(bytes)?))),
_ => Err(format!("no loader for `{id}`")),
}
}
/// The notice kept next to installed weights: what they are, who made them, their licence.
pub fn notice(m: &ModelInfo) -> String {
format!(
"{}\n\nAuthors: {}\nLicence: {} (full text: https://spdx.org/licenses/{}.html; as stated by the authors: {})\nSource: {}\nProject: {}\n\nDownloaded unmodified from the source above. EffectCraft runs it with its own implementation\nand is not affiliated with or endorsed by its authors.\n",
m.name, m.authors, m.licence, m.licence, m.licence_url, m.url, m.homepage
)
}
struct Sam {
net: mobilesam::MobileSam,
}
@@ -202,8 +260,11 @@ mod tests {
for m in MODELS {
assert!(ALLOWED_LICENCES.contains(&m.licence), "{}", m.id);
assert_eq!(m.sha256.len(), 64);
assert!(m.url.starts_with("https://"));
assert!(m.url.starts_with("https://") && m.licence_url.starts_with("https://") && m.homepage.starts_with("https://"));
assert!(!m.authors.is_empty() && notice(m).contains(m.authors));
}
assert_eq!(models(Task::Face).map(|m| m.id).collect::<Vec<_>>(), ["mediapipe-face"]);
assert!(load("mediapipe-face", b"nope").err().is_some_and(|e| e.contains("does not match")));
// A file that isn't the published one is refused before anything is parsed.
assert!(load("mobilesam", b"not the weights").err().is_some_and(|e| e.contains("does not match")));
assert!(load("nope", b"").is_err());
+312
View File
@@ -0,0 +1,312 @@
//! MediaPipe Face Landmarker (Google LLC, Apache-2.0) in plain Rust: the official
//! `face_landmarker.task` bundle's BlazeFace short-range detector and Face Mesh V2 (478 points)
//! run on the [`tflite`](crate::tflite) interpreter.
//!
//! The pipeline follows MediaPipe's published face landmarker graph (Apache-2.0): the detector
//! sees a 128×128 crop scaled to −1…1 and decodes 896 SSD anchors (strides 8, 16, 16, 16; two
//! anchors per cell per layer) with weighted non-maximum suppression; the mesh sees a 256×256
//! crop (0…1) of a square 1.5× the face, rotated so the eyes are level (detector keypoints 0 → 1,
//! then mesh points 33 → 263), and reports a presence score. The landmark indices in
//! [`TOPOLOGY`] are points of MediaPipe's canonical face mesh.
use crate::face::{Face, FaceModel, Roi, Topology, crop, sigmoid};
use crate::tflite::Model;
use crate::{FACE_LANDMARKER, ModelInfo, Result};
pub const DETECTOR: &str = "face_detector.tflite";
pub const MESH: &str = "face_landmarks_detector.tflite";
const DET_SIZE: usize = 128;
const MESH_SIZE: usize = 256;
const MESH_POINTS: usize = 478;
/// Detection and presence thresholds (MediaPipe's defaults).
const MIN_SCORE: f32 = 0.5;
const NMS_IOU: f32 = 0.3;
/// Crops are this much larger than the face.
const ROI_SCALE: f32 = 1.5;
/// Mesh points whose direction levels the crop: the outer eye corners.
const EYE_LINE: [usize; 2] = [33, 263];
/// MediaPipe's face mesh: the face oval (`FACEMESH_FACE_OVAL`, in order) and the points the
/// tracker's landmarks are (inner lips for the mouth, iris centres for the pupils).
pub const TOPOLOGY: Topology = Topology {
outline: &[
10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162,
21, 54, 103, 67, 109,
],
landmarks: &[
("leftEyebrowInner", 107),
("leftEyebrowMiddle", 105),
("leftEyebrowOuter", 70),
("rightEyebrowInner", 336),
("rightEyebrowMiddle", 334),
("rightEyebrowOuter", 300),
("leftEyeInner", 133),
("leftEyeOuter", 33),
("leftEyeTop", 159),
("leftEyeBottom", 145),
("leftPupil", 468),
("rightEyeInner", 362),
("rightEyeOuter", 263),
("rightEyeTop", 386),
("rightEyeBottom", 374),
("rightPupil", 473),
("noseTip", 1),
("leftNostril", 79),
("rightNostril", 309),
("mouthLeft", 61),
("mouthRight", 291),
("mouthTop", 13),
("mouthBottom", 14),
],
};
/// A detected face: box `[x0, y0, x1, y1]`, six keypoints (eyes, nose tip, mouth, ears; image
/// left first) and score, in frame pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Detection {
pub bbox: [f32; 4],
pub keypoints: [[f32; 2]; 6],
pub score: f32,
}
pub struct FaceLandmarker {
detector: Model,
mesh: Model,
/// Anchor centres (normalised).
anchors: Vec<[f32; 2]>,
}
/// SSD anchor centres: per stride group, `fm×fm` cells with two anchors per layer each.
fn anchors() -> Vec<[f32; 2]> {
let mut out = vec![];
for (stride, layers) in [(8usize, 1usize), (16, 3)] {
let fm = DET_SIZE.div_ceil(stride);
for y in 0..fm {
for x in 0..fm {
for _ in 0..2 * layers {
out.push([(x as f32 + 0.5) / fm as f32, (y as f32 + 0.5) / fm as f32]);
}
}
}
}
out
}
fn iou(a: &[f32; 4], b: &[f32; 4]) -> f32 {
let iw = (a[2].min(b[2]) - a[0].max(b[0])).max(0.0);
let ih = (a[3].min(b[3]) - a[1].max(b[1])).max(0.0);
let inter = iw * ih;
let union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter;
if union > 0.0 { inter / union } else { 0.0 }
}
/// Weighted non-maximum suppression: each cluster of overlapping detections becomes their
/// score-weighted average, with the best score.
fn weighted_nms(mut dets: Vec<Detection>) -> Vec<Detection> {
dets.sort_by(|a, b| b.score.total_cmp(&a.score));
let mut out = vec![];
while let Some(top) = dets.first().copied() {
let (cluster, rest): (Vec<Detection>, Vec<Detection>) = dets.into_iter().partition(|d| iou(&d.bbox, &top.bbox) > NMS_IOU);
dets = rest;
let total: f32 = cluster.iter().map(|d| d.score).sum();
if total <= 0.0 {
out.push(top);
continue;
}
let mut avg = Detection { bbox: [0.0; 4], keypoints: [[0.0; 2]; 6], score: top.score };
for d in &cluster {
let k = d.score / total;
for i in 0..4 {
avg.bbox[i] += d.bbox[i] * k;
}
for (a, p) in avg.keypoints.iter_mut().zip(&d.keypoints) {
a[0] += p[0] * k;
a[1] += p[1] * k;
}
}
out.push(avg);
}
out
}
/// The crop a face's mesh is computed in: `bbox` grown to a square 1.5× its long side, turned so
/// `from → to` is level.
fn roi_of(bbox: [f32; 4], from: [f32; 2], to: [f32; 2]) -> Roi {
Roi {
center: [(bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0],
size: (bbox[2] - bbox[0]).max(bbox[3] - bbox[1]) * ROI_SCALE,
angle: (to[1] - from[1]).atan2(to[0] - from[0]),
}
}
fn bounds(points: &[[f32; 2]]) -> [f32; 4] {
points
.iter()
.fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])
}
impl FaceLandmarker {
/// From the official `face_landmarker.task` bundle (a zip archive of `.tflite` models).
pub fn from_task(bytes: &[u8]) -> Result<FaceLandmarker> {
let detector = Model::read(&crate::pt::zip_file(bytes, DETECTOR)?)?;
let mesh = Model::read(&crate::pt::zip_file(bytes, MESH)?)?;
let anchors = anchors();
if detector.input_shape(0) != Some(&[1, DET_SIZE, DET_SIZE, 3]) || detector.output(0).map(|o| o.0) != Some(&[1, anchors.len(), 16]) {
return Err("unexpected face detector".into());
}
if mesh.input_shape(0) != Some(&[1, MESH_SIZE, MESH_SIZE, 3]) || mesh.output(0).map(|o| o.0.iter().product::<usize>()) != Some(MESH_POINTS * 3) {
return Err("unexpected face mesh".into());
}
Ok(FaceLandmarker { detector, mesh, anchors })
}
/// Faces in the square `roi` of a frame (frame pixels), best first.
pub fn detect(&self, rgb: &[[f32; 3]], w: usize, h: usize, roi: &Roi) -> Result<Vec<Detection>> {
let x = crop(rgb, w, h, roi, DET_SIZE, [-1.0, 1.0]);
let out = self.detector.run(&[&x])?;
let (Some(reg), Some(cls)) = (out.first(), out.get(1)) else { return Err("face detector: missing outputs".into()) };
let s = DET_SIZE as f32;
let mut dets = vec![];
for (i, a) in self.anchors.iter().enumerate() {
let (Some(r), Some(&c)) = (reg.get(i * 16..i * 16 + 16), cls.get(i)) else { break };
let score = sigmoid(c.clamp(-100.0, 100.0));
if score < MIN_SCORE {
continue;
}
let (cx, cy, bw, bh) = (r[0] / s + a[0], r[1] / s + a[1], r[2] / s, r[3] / s);
let to = |u: f32, v: f32| roi.to_frame(u, v);
let corners =
[to(cx - bw / 2.0, cy - bh / 2.0), to(cx + bw / 2.0, cy - bh / 2.0), to(cx - bw / 2.0, cy + bh / 2.0), to(cx + bw / 2.0, cy + bh / 2.0)];
let mut keypoints = [[0.0f32; 2]; 6];
for (k, p) in keypoints.iter_mut().enumerate() {
*p = to(r[4 + 2 * k] / s + a[0], r[5 + 2 * k] / s + a[1]);
}
dets.push(Detection { bbox: bounds(&corners), keypoints, score });
}
Ok(weighted_nms(dets))
}
/// The face mesh in `roi`: 478 points (frame pixels) and the presence score.
pub fn mesh(&self, rgb: &[[f32; 3]], w: usize, h: usize, roi: &Roi) -> Result<Face> {
let x = crop(rgb, w, h, roi, MESH_SIZE, [0.0, 1.0]);
let out = self.mesh.run(&[&x])?;
let (Some(pts), Some(flag)) = (out.first(), out.get(1).and_then(|f| f.first())) else { return Err("face mesh: missing outputs".into()) };
let s = MESH_SIZE as f32;
let points = pts.chunks_exact(3).take(MESH_POINTS).map(|p| roi.to_frame(p[0] / s, p[1] / s)).collect();
Ok(Face { points, score: sigmoid(*flag) })
}
/// The crop that frames a face found earlier.
fn roi_of_face(face: &Face) -> Option<Roi> {
let (a, b) = (face.points.get(EYE_LINE[0])?, face.points.get(EYE_LINE[1])?);
Some(roi_of(bounds(&face.points), *a, *b))
}
/// The mesh from `roi`, refined once from its own points (a detector box is coarse).
fn mesh_refined(&self, rgb: &[[f32; 3]], w: usize, h: usize, roi: &Roi) -> Result<Option<Face>> {
let first = self.mesh(rgb, w, h, roi)?;
if first.score < MIN_SCORE {
return Ok(None);
}
let Some(r) = Self::roi_of_face(&first) else { return Ok(None) };
let refined = self.mesh(rgb, w, h, &r)?;
Ok(Some(if refined.score >= MIN_SCORE { refined } else { first }))
}
}
impl FaceModel for FaceLandmarker {
fn info(&self) -> &'static ModelInfo {
&FACE_LANDMARKER
}
fn topology(&self) -> &'static Topology {
&TOPOLOGY
}
fn find(&self, rgb: &[[f32; 3]], w: usize, h: usize, region: [f32; 4]) -> Result<Option<Face>> {
let inside = |d: &Detection| {
let c = [(d.bbox[0] + d.bbox[2]) / 2.0, (d.bbox[1] + d.bbox[3]) / 2.0];
c[0] >= region[0] && c[0] <= region[2] && c[1] >= region[1] && c[1] <= region[3]
};
// Around the region first (a face filling the mask), then the whole frame (a small face).
let side = (region[2] - region[0]).max(region[3] - region[1]);
let around = Roi { center: [(region[0] + region[2]) / 2.0, (region[1] + region[3]) / 2.0], size: side * ROI_SCALE, angle: 0.0 };
let whole = Roi { center: [w as f32 / 2.0, h as f32 / 2.0], size: w.max(h) as f32, angle: 0.0 };
for roi in [around, whole] {
if !roi.size.is_finite() || roi.size <= 4.0 {
continue;
}
if let Some(d) = self.detect(rgb, w, h, &roi)?.into_iter().find(inside) {
return self.mesh_refined(rgb, w, h, &roi_of(d.bbox, d.keypoints[0], d.keypoints[1]));
}
}
Ok(None)
}
fn follow(&self, rgb: &[[f32; 3]], w: usize, h: usize, prev: &Face) -> Result<Option<Face>> {
let Some(roi) = Self::roi_of_face(prev) else { return Ok(None) };
let face = self.mesh(rgb, w, h, &roi)?;
if face.score >= MIN_SCORE {
return Ok(Some(face));
}
// Lost by the mesh (a fast move): look for it again near where it was.
let b = bounds(&prev.points);
let (gw, gh) = ((b[2] - b[0]) * 0.5, (b[3] - b[1]) * 0.5);
self.find(rgb, w, h, [b[0] - gw, b[1] - gh, b[2] + gw, b[3] + gh])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn anchors_match_the_detector_layout() {
let a = anchors();
assert_eq!(a.len(), 896);
// Stride 8: 16×16 cells, two anchors each; then stride 16: 8×8 cells, six each.
assert_eq!(a[0], [0.5 / 16.0, 0.5 / 16.0]);
assert_eq!(a[1], a[0]);
assert_eq!(a[2], [1.5 / 16.0, 0.5 / 16.0]);
assert_eq!(a[512], [0.5 / 8.0, 0.5 / 8.0]);
assert_eq!(a[517], a[512]);
assert_eq!(a[518], [1.5 / 8.0, 0.5 / 8.0]);
}
#[test]
fn nms_averages_overlapping_detections() {
let d = |x: f32, s: f32| Detection { bbox: [x, 0.0, x + 10.0, 10.0], keypoints: [[x, 0.0]; 6], score: s };
let out = weighted_nms(vec![d(0.0, 0.9), d(1.0, 0.9), d(50.0, 0.6)]);
assert_eq!(out.len(), 2);
assert!((out[0].bbox[0] - 0.5).abs() < 1e-5 && out[0].score == 0.9);
assert_eq!(out[1].bbox[0], 50.0);
}
/// The official bundle (`EFFECTCRAFT_FACE_LANDMARKER` = path to `face_landmarker.task`) on a
/// fixed input matches TensorFlow Lite's own interpreter (`ai-edge-litert` 2.2.0, run once
/// to record these sums).
#[test]
fn matches_tensorflow_lite_on_the_official_weights() {
let Some(path) = std::env::var_os("EFFECTCRAFT_FACE_LANDMARKER") else { return };
let bytes = std::fs::read(path).unwrap();
let m = FaceLandmarker::from_task(&bytes).unwrap();
let input = |n: usize| -> Vec<f32> { (0..n).map(|i| ((i as f32) * 0.013).sin() * 0.5).collect() };
let close = |got: &[f32], want: f64| {
let s: f64 = got.iter().map(|v| *v as f64).sum();
assert!((s - want).abs() <= 1e-5 * want.abs().max(1.0), "{s} vs {want}");
};
let d = m.detector.run(&[&input(DET_SIZE * DET_SIZE * 3)]).unwrap();
close(&d[0], 54_202.040_273);
close(&d[1], -3_061.866_384);
let y = m.mesh.run(&[&input(MESH_SIZE * MESH_SIZE * 3)]).unwrap();
close(&y[0], 119_864.749_257);
close(&y[1], -19.777_233);
}
#[test]
fn topology_indices_are_mesh_points() {
assert!(TOPOLOGY.outline.iter().chain(TOPOLOGY.landmarks.iter().map(|l| &l.1)).all(|&i| i < MESH_POINTS));
assert_eq!(TOPOLOGY.outline.len(), 36);
}
}
+29 -16
View File
@@ -101,22 +101,28 @@ impl Conv {
pub fn forward(&self, x: &[f32], h: usize, w: usize) -> (Vec<f32>, usize, usize) {
let (oh, ow) = (self.out_size(h), self.out_size(w));
(self.forward_sized(x, h, w, oh, ow, [self.pad; 2]), oh, ow)
}
/// An `oh×ow` output with `pad` (top, left) zero rows and columns before the input; what
/// falls past the input's far edges is zero too (so asymmetric "same" padding works).
pub fn forward_sized(&self, x: &[f32], h: usize, w: usize, oh: usize, ow: usize, pad: [usize; 2]) -> Vec<f32> {
let kk = self.ks * self.ks * self.inp;
let mut y: Vec<f32> = (0..oh * ow).flat_map(|_| self.b.iter().copied()).collect();
if x.len() < h * w * self.inp {
return (y, oh, ow);
if x.len() < h * w * self.inp || self.wt.len() < kk * self.out {
return y;
}
y.par_chunks_mut(ow * self.out).enumerate().for_each(|(oy, row)| {
// This output row's patches.
let mut patch = vec![0.0f32; ow * kk];
for ox in 0..ow {
for ky in 0..self.ks {
let iy = (oy * self.stride + ky) as isize - self.pad as isize;
let iy = (oy * self.stride + ky) as isize - pad[0] as isize;
if iy < 0 || iy >= h as isize {
continue;
}
for kx in 0..self.ks {
let ix = (ox * self.stride + kx) as isize - self.pad as isize;
let ix = (ox * self.stride + kx) as isize - pad[1] as isize;
if ix < 0 || ix >= w as isize {
continue;
}
@@ -134,17 +140,18 @@ impl Conv {
general_mat_mul(1.0, &av, &bv, 1.0, &mut cv);
}
});
(y, oh, ow)
y
}
}
/// A depthwise 3×3 convolution (padding 1, stride 1 or 2) on `h×w×c`.
/// A depthwise `ks×ks` convolution (one filter per channel) on `h×w×c`.
#[derive(Clone, Debug, Default)]
pub struct Depthwise {
/// `[tap × c]`.
pub w: Vec<f32>,
pub b: Vec<f32>,
pub c: usize,
pub ks: usize,
pub stride: usize,
}
@@ -160,32 +167,38 @@ impl Depthwise {
wt[t * c + ch] = w[ch * 9 + t];
}
}
Some(Depthwise { w: wt, b: b.map_or_else(|| vec![0.0; c], <[f32]>::to_vec), c, stride })
Some(Depthwise { w: wt, b: b.map_or_else(|| vec![0.0; c], <[f32]>::to_vec), c, ks: 3, stride })
}
/// 3×3 with padding 1.
pub fn forward(&self, x: &[f32], h: usize, w: usize) -> (Vec<f32>, usize, usize) {
let c = self.c;
let (oh, ow) = ((h + 2 - 3) / self.stride + 1, (w + 2 - 3) / self.stride + 1);
(self.forward_sized(x, h, w, oh, ow, [1, 1]), oh, ow)
}
/// An `oh×ow` output with `pad` (top, left) before the input, as [`Conv::forward_sized`].
pub fn forward_sized(&self, x: &[f32], h: usize, w: usize, oh: usize, ow: usize, pad: [usize; 2]) -> Vec<f32> {
let (c, ks) = (self.c, self.ks);
let mut y = vec![0.0f32; oh * ow * c];
if x.len() < h * w * c {
return (y, oh, ow);
if x.len() < h * w * c || self.w.len() < ks * ks * c || self.b.len() < c {
return y;
}
y.par_chunks_mut(ow * c).enumerate().for_each(|(oy, row)| {
for ox in 0..ow {
let out = &mut row[ox * c..(ox + 1) * c];
out.copy_from_slice(&self.b);
for ky in 0..3 {
let iy = (oy * self.stride + ky) as isize - 1;
for ky in 0..ks {
let iy = (oy * self.stride + ky) as isize - pad[0] as isize;
if iy < 0 || iy >= h as isize {
continue;
}
for kx in 0..3 {
let ix = (ox * self.stride + kx) as isize - 1;
for kx in 0..ks {
let ix = (ox * self.stride + kx) as isize - pad[1] as isize;
if ix < 0 || ix >= w as isize {
continue;
}
let src = &x[(iy as usize * w + ix as usize) * c..][..c];
let tap = &self.w[(ky * 3 + kx) * c..][..c];
let tap = &self.w[(ky * ks + kx) * c..][..c];
for ((o, s), k) in out.iter_mut().zip(src).zip(tap) {
*o += s * k;
}
@@ -193,7 +206,7 @@ impl Depthwise {
}
}
});
(y, oh, ow)
y
}
}
+7 -1
View File
@@ -102,6 +102,12 @@ fn read_entry<'a>(b: &'a [u8], e: &Entry) -> Result<std::borrow::Cow<'a, [u8]>>
}
}
/// The bytes of the archive entry `name` (model bundles are zip archives too).
pub(crate) fn zip_file<'a>(b: &'a [u8], name: &str) -> Result<std::borrow::Cow<'a, [u8]>> {
let entries = zip_entries(b)?;
read_entry(b, entries.get(name).ok_or_else(|| format!("{name} is missing from the archive"))?)
}
/// Pickle values (what state dicts use).
#[derive(Clone, Debug)]
enum Obj {
@@ -341,7 +347,7 @@ fn to_f32(dtype: &str, bytes: &[u8]) -> Option<Vec<f32>> {
}
}
fn half_to_f32(h: u16) -> f32 {
pub(crate) fn half_to_f32(h: u16) -> f32 {
let (s, e, m) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as u32, (h & 0x3ff) as u32);
let bits = match (e, m) {
(0, 0) => s << 31,
+660
View File
@@ -0,0 +1,660 @@
//! Running TensorFlow Lite models without TensorFlow: a reader for the `.tflite` FlatBuffer
//! (fields as numbered in TensorFlow Lite's published `schema.fbs`, Apache-2.0) and an
//! interpreter for the float operators small vision models use: `CONV_2D`, `DEPTHWISE_CONV_2D`,
//! `MAX_POOL_2D`, `ADD`, `PAD`, `CONCATENATION`, `RESHAPE`, `RELU`, `RELU6`, `PRELU`, `LOGISTIC`
//! and `DEQUANTIZE` of float16 weights (folded at load). Weights are re-laid out once at load for
//! the [`nn`](crate::nn) kernels. Anything else (other operators, quantised tensors, dilation) is a
//! load error, never a panic: models are pinned by SHA-256, so what loads once always loads.
use crate::nn::{Conv, Depthwise, Linear};
use crate::pt::half_to_f32;
type Result<T> = std::result::Result<T, String>;
// ---------------------------------------------------------------- FlatBuffers
/// A FlatBuffer: bounds-checked little-endian reads.
#[derive(Clone, Copy)]
struct Fb<'a>(&'a [u8]);
/// A table: its position in the buffer.
#[derive(Clone, Copy)]
struct Table(usize);
impl<'a> Fb<'a> {
fn bytes<const N: usize>(&self, at: usize) -> Result<[u8; N]> {
self.0.get(at..at.checked_add(N).ok_or("bad offset")?).and_then(|s| s.try_into().ok()).ok_or_else(|| "truncated model".to_string())
}
fn u8(&self, at: usize) -> Result<u8> {
Ok(self.bytes::<1>(at)?[0])
}
fn u16(&self, at: usize) -> Result<u16> {
Ok(u16::from_le_bytes(self.bytes(at)?))
}
fn u32(&self, at: usize) -> Result<u32> {
Ok(u32::from_le_bytes(self.bytes(at)?))
}
fn i32(&self, at: usize) -> Result<i32> {
Ok(i32::from_le_bytes(self.bytes(at)?))
}
fn u64(&self, at: usize) -> Result<u64> {
Ok(u64::from_le_bytes(self.bytes(at)?))
}
/// Follow the offset stored at `at`.
fn deref(&self, at: usize) -> Result<usize> {
at.checked_add(self.u32(at)? as usize).ok_or_else(|| "bad offset".to_string())
}
fn root(&self) -> Result<Table> {
Ok(Table(self.deref(0)?))
}
/// Where field `id` of `t` is stored (absent fields have their default).
fn field(&self, t: Table, id: usize) -> Result<Option<usize>> {
let vt = (t.0 as i64 - self.i32(t.0)? as i64).try_into().map_err(|_| "bad vtable")?;
let vt_len = self.u16(vt)? as usize;
let slot = 4 + 2 * id;
if slot + 2 > vt_len {
return Ok(None);
}
let off = self.u16(vt + slot)? as usize;
Ok((off != 0).then_some(t.0 + off))
}
fn int(&self, t: Table, id: usize, default: i32) -> Result<i32> {
self.field(t, id)?.map_or(Ok(default), |p| self.i32(p))
}
fn byte(&self, t: Table, id: usize, default: u8) -> Result<u8> {
self.field(t, id)?.map_or(Ok(default), |p| self.u8(p))
}
fn table(&self, t: Table, id: usize) -> Result<Option<Table>> {
self.field(t, id)?.map(|p| self.deref(p).map(Table)).transpose()
}
/// A vector field: (start of its elements, length).
fn vector(&self, t: Table, id: usize) -> Result<(usize, usize)> {
let Some(p) = self.field(t, id)? else { return Ok((0, 0)) };
let v = self.deref(p)?;
let n = self.u32(v)? as usize;
if v.saturating_add(4).saturating_add(n) > self.0.len() {
return Err("truncated model".into());
}
Ok((v + 4, n))
}
fn tables(&self, t: Table, id: usize) -> Result<Vec<Table>> {
let (at, n) = self.vector(t, id)?;
(0..n).map(|i| self.deref(at + 4 * i).map(Table)).collect()
}
fn ints(&self, t: Table, id: usize) -> Result<Vec<i32>> {
let (at, n) = self.vector(t, id)?;
(0..n).map(|i| self.i32(at + 4 * i)).collect()
}
fn string(&self, t: Table, id: usize) -> Result<String> {
let (at, n) = self.vector(t, id)?;
Ok(String::from_utf8_lossy(self.0.get(at..at + n).ok_or("truncated model")?).into_owned())
}
}
// ---------------------------------------------------------------- the model
/// Operator codes (`BuiltinOperator`).
mod op {
pub const ADD: i32 = 0;
pub const CONCATENATION: i32 = 2;
pub const CONV_2D: i32 = 3;
pub const DEPTHWISE_CONV_2D: i32 = 4;
pub const DEQUANTIZE: i32 = 6;
pub const LOGISTIC: i32 = 14;
pub const MAX_POOL_2D: i32 = 17;
pub const RELU: i32 = 19;
pub const RELU6: i32 = 21;
pub const RESHAPE: i32 = 22;
pub const PAD: i32 = 34;
pub const PRELU: i32 = 54;
}
/// The most values a tensor may hold.
const MAX_TENSOR: usize = 1 << 28;
/// Tensor types (`TensorType`).
const FLOAT32: u8 = 0;
const FLOAT16: u8 = 1;
const INT32: u8 = 2;
/// A fused activation (`ActivationFunctionType`).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Act {
None,
Relu,
ReluN1To1,
Relu6,
Tanh,
}
impl Act {
fn from(code: u8) -> Result<Act> {
Ok(match code {
0 => Act::None,
1 => Act::Relu,
2 => Act::ReluN1To1,
3 => Act::Relu6,
4 => Act::Tanh,
c => return Err(format!("unsupported fused activation {c}")),
})
}
fn apply(self, x: &mut [f32]) {
let f: fn(f32) -> f32 = match self {
Act::None => return,
Act::Relu => |v| v.max(0.0),
Act::ReluN1To1 => |v| v.clamp(-1.0, 1.0),
Act::Relu6 => |v| v.clamp(0.0, 6.0),
Act::Tanh => f32::tanh,
};
for v in x {
*v = f(*v);
}
}
}
/// One operator, its weights laid out for the kernels.
#[derive(Clone, Debug)]
enum Op {
/// A 1×1, stride-1 convolution: a dense layer over the pixels.
Pointwise(Linear, Act),
Conv(Conv, [usize; 2], Act),
Depthwise(Depthwise, [usize; 2], Act),
/// Kernel, stride, padding before (top, left).
MaxPool {
k: [usize; 2],
stride: [usize; 2],
pad: [usize; 2],
act: Act,
},
Add(Act),
/// Constant padding (zeros), per dimension (before, after).
Pad(Vec<[usize; 2]>),
Concat {
axis: usize,
act: Act,
},
Reshape,
Act(Act),
Prelu(Vec<f32>),
Logistic,
}
#[derive(Clone, Debug)]
struct Step {
op: Op,
/// Runtime inputs (tensor ids).
inputs: Vec<usize>,
output: usize,
}
/// A loaded model, ready to run (batch of one, static shapes).
#[derive(Clone, Debug)]
pub struct Model {
shapes: Vec<Vec<usize>>,
names: Vec<String>,
/// Constant float tensors (weights folded into the steps are not kept).
consts: Vec<Option<Vec<f32>>>,
steps: Vec<Step>,
inputs: Vec<usize>,
outputs: Vec<usize>,
/// After which step each tensor is last needed (to free memory as the model runs).
last_use: Vec<usize>,
}
fn index(i: i32, n: usize) -> Result<usize> {
usize::try_from(i).ok().filter(|&i| i < n).ok_or_else(|| format!("bad tensor index {i}"))
}
/// "Same" padding: output size and padding before.
fn same(input: usize, k: usize, stride: usize) -> (usize, usize) {
let out = input.div_ceil(stride);
let total = ((out.saturating_sub(1)) * stride + k).saturating_sub(input);
(out, total / 2)
}
/// Output size and padding before, for `padding` (0 same, 1 valid).
fn window(padding: u8, input: usize, k: usize, stride: usize) -> Result<(usize, usize)> {
match padding {
0 => Ok(same(input, k, stride)),
1 if input >= k => Ok(((input - k) / stride + 1, 0)),
_ => Err("bad window".into()),
}
}
impl Model {
/// Read a `.tflite` file.
pub fn read(bytes: &[u8]) -> Result<Model> {
let fb = Fb(bytes);
let root = fb.root()?;
let codes: Vec<i32> = fb.tables(root, 1)?.into_iter().map(|c| Ok(fb.int(c, 3, 0)?.max(fb.byte(c, 0, 0)? as i8 as i32))).collect::<Result<_>>()?;
let buffers = fb.tables(root, 4)?;
let graphs = fb.tables(root, 2)?;
let g = *graphs.first().ok_or("the model has no graph")?;
let tensors = fb.tables(g, 0)?;
let n = tensors.len();
let mut shapes = Vec::with_capacity(n);
let mut names = Vec::with_capacity(n);
// Constant data: float tensors as f32, int tensors (pads, shapes) as i32.
let mut floats: Vec<Option<Vec<f32>>> = vec![None; n];
let mut ints: Vec<Option<Vec<i32>>> = vec![None; n];
for (i, t) in tensors.iter().enumerate() {
let shape: Vec<usize> = fb
.ints(*t, 0)?
.into_iter()
.map(|d| usize::try_from(d).map_err(|_| "dynamic shapes are not supported"))
.collect::<std::result::Result<_, _>>()?;
let ty = fb.byte(*t, 1, FLOAT32)?;
let buf = fb.int(*t, 2, 0)? as u32 as usize;
names.push(fb.string(*t, 3)?);
// Every size computed from shapes later stays in range.
let count = shape.iter().try_fold(1usize, |a, &d| a.checked_mul(d)).filter(|&c| c <= MAX_TENSOR).ok_or("a tensor is too large")?;
if fb.field(*t, 4)?.is_some() && fb.table(*t, 4)?.is_some_and(|q| fb.vector(q, 2).is_ok_and(|v| v.1 > 0)) {
return Err(format!("{}: quantised tensors are not supported", names[i]));
}
if buf > 0 {
let b = *buffers.get(buf).ok_or("bad buffer index")?;
let (mut at, mut len) = fb.vector(b, 0)?;
if len == 0 {
// Large models keep data after the FlatBuffer: offset and size from its start.
let (o, s) = (fb.field(b, 1)?.map(|p| fb.u64(p)).transpose()?.unwrap_or(0), fb.field(b, 2)?.map(|p| fb.u64(p)).transpose()?.unwrap_or(0));
(at, len) = (o as usize, s as usize);
}
if len > 0 {
let data = bytes.get(at..at.checked_add(len).ok_or("bad buffer")?).ok_or("truncated model")?;
match ty {
FLOAT32 if data.len() == 4 * count => {
floats[i] = Some(data.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
}
FLOAT16 if data.len() == 2 * count => {
floats[i] = Some(data.chunks_exact(2).map(|c| half_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect())
}
INT32 if data.len() == 4 * count => {
ints[i] = Some(data.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
}
_ => return Err(format!("{}: unsupported tensor data", names[i])),
}
}
}
shapes.push(shape);
}
let inputs = fb.ints(g, 1)?.into_iter().map(|i| index(i, n)).collect::<Result<Vec<_>>>()?;
let outputs = fb.ints(g, 2)?.into_iter().map(|i| index(i, n)).collect::<Result<Vec<_>>>()?;
let mut steps = vec![];
for o in fb.tables(g, 3)? {
let code = *codes.get(fb.int(o, 0, 0)? as u32 as usize).ok_or("bad operator code")?;
// Optional inputs are -1.
let ins: Vec<Option<usize>> = fb.ints(o, 1)?.into_iter().map(|i| if i < 0 { Ok(None) } else { index(i, n).map(Some) }).collect::<Result<_>>()?;
let outs = fb.ints(o, 2)?;
let output = index(*outs.first().ok_or("an operator has no output")?, n)?;
// Float16 weights: fold their DEQUANTIZE.
if code == op::DEQUANTIZE
&& let Some(f) = ins.first().copied().flatten().and_then(|i| floats[i].clone())
{
floats[output] = Some(f);
continue;
}
let opts = fb.table(o, 4)?;
let opt_int = |id: usize, default: i32| opts.map_or(Ok(default), |t| fb.int(t, id, default));
let opt_byte = |id: usize, default: u8| opts.map_or(Ok(default), |t| fb.byte(t, id, default));
let input = |k: usize| ins.get(k).copied().flatten().ok_or_else(|| format!("{}: missing input {k}", names[output]));
let weights = |k: usize| -> Result<Vec<f32>> {
let id = input(k)?;
floats[id].clone().ok_or_else(|| format!("{}: input {k} is not constant", names[output]))
};
let bias = |count: usize| -> Result<Vec<f32>> {
match ins.get(2).copied().flatten() {
Some(id) => floats[id].clone().filter(|b| b.len() == count).ok_or_else(|| format!("{}: bad bias", names[output])),
None => Ok(vec![0.0; count]),
}
};
let in_shape = |k: usize| -> Result<Vec<usize>> { Ok(shapes[input(k)?].clone()) };
let out_shape = shapes[output].clone();
let stride = |w: usize, h: usize| -> Result<[usize; 2]> {
let s = [opt_int(h, 1)?, opt_int(w, 1)?];
if s.iter().any(|v| *v < 1) {
return Err("bad stride".into());
}
Ok(s.map(|v| v as usize))
};
let mut runtime = vec![input(0)?];
let op = match code {
op::DEQUANTIZE => Op::Reshape,
op::CONV_2D | op::DEPTHWISE_CONV_2D => {
let depthwise = code == op::DEPTHWISE_CONV_2D;
let (padding, s) = (opt_byte(0, 0)?, stride(1, 2)?);
let act_id = if depthwise { 4 } else { 3 };
let dil = if depthwise { [opt_int(6, 1)?, opt_int(5, 1)?] } else { [opt_int(5, 1)?, opt_int(4, 1)?] };
if dil != [1, 1] {
return Err(format!("{}: dilated convolutions are not supported", names[output]));
}
let act = Act::from(opt_byte(act_id, 0)?)?;
let (x, f) = (in_shape(0)?, shapes[input(1)?].clone());
let (&[1, h, w, cin], &[fo, kh, kw, fi], &[1, oh, ow, cout]) = (&x[..], &f[..], &out_shape[..]) else {
return Err(format!("{}: unexpected convolution shapes", names[output]));
};
if kh != kw || s[0] != s[1] {
return Err(format!("{}: only square kernels and strides are supported", names[output]));
}
let (ey, py) = window(padding, h, kh, s[0])?;
let (ex, px) = window(padding, w, kw, s[1])?;
if (ey, ex) != (oh, ow) {
return Err(format!("{}: output size disagrees with the padding", names[output]));
}
let wt = weights(1)?;
let b = bias(cout)?;
if depthwise {
if fo != 1 || fi != cout || cin != cout {
return Err(format!("{}: depth multipliers are not supported", names[output]));
}
Op::Depthwise(Depthwise { w: wt, b, c: cout, ks: kh, stride: s[0] }, [py, px], act)
} else {
if fo != cout || fi != cin {
return Err(format!("{}: unexpected filter shape", names[output]));
}
// OHWI → [(ky·ks + kx)·inp + ci] × out.
let kk = kh * kw * cin;
let mut t = vec![0.0f32; kk * cout];
for o in 0..cout {
for p in 0..kk {
t[p * cout + o] = *wt.get(o * kk + p).ok_or("bad filter")?;
}
}
if kh == 1 && s[0] == 1 {
Op::Pointwise(Linear { wt: t, b, inp: cin, out: cout }, act)
} else {
Op::Conv(Conv { wt: t, b, inp: cin, out: cout, ks: kh, stride: s[0], pad: 0 }, [py, px], act)
}
}
}
op::MAX_POOL_2D => {
let (padding, s) = (opt_byte(0, 0)?, stride(1, 2)?);
let k = [opt_int(4, 1)?, opt_int(3, 1)?];
if k.iter().any(|v| *v < 1) {
return Err("bad pool size".into());
}
let k = k.map(|v| v as usize);
let x = in_shape(0)?;
let (&[1, h, w, _], &[1, oh, ow, _]) = (&x[..], &out_shape[..]) else { return Err("unexpected pool shapes".into()) };
let (ey, py) = window(padding, h, k[0], s[0])?;
let (ex, px) = window(padding, w, k[1], s[1])?;
if (ey, ex) != (oh, ow) {
return Err(format!("{}: output size disagrees with the padding", names[output]));
}
Op::MaxPool { k, stride: s, pad: [py, px], act: Act::from(opt_byte(5, 0)?)? }
}
op::ADD => {
runtime.push(input(1)?);
Op::Add(Act::from(opt_byte(0, 0)?)?)
}
op::PAD => {
let p = ints[input(1)?].clone().ok_or("PAD: paddings must be constant")?;
let pads = p
.chunks_exact(2)
.map(|c| Ok([usize::try_from(c[0]).map_err(|_| "bad pad")?, usize::try_from(c[1]).map_err(|_| "bad pad")?]))
.collect::<Result<Vec<_>>>()?;
Op::Pad(pads)
}
op::CONCATENATION => {
runtime = (0..ins.len()).map(input).collect::<Result<_>>()?;
let rank = out_shape.len() as i32;
let a = opt_int(0, 0)?;
let axis = if a < 0 { a + rank } else { a };
Op::Concat { axis: index(axis, out_shape.len())?, act: Act::from(opt_byte(1, 0)?)? }
}
op::RESHAPE => Op::Reshape,
op::RELU => Op::Act(Act::Relu),
op::RELU6 => Op::Act(Act::Relu6),
op::LOGISTIC => Op::Logistic,
op::PRELU => {
let alpha = weights(1)?;
let c = *out_shape.last().ok_or("PRELU: bad shape")?;
if alpha.len() != c {
return Err(format!("{}: only per-channel PReLU is supported", names[output]));
}
Op::Prelu(alpha)
}
c => return Err(format!("operator {c} is not supported")),
};
steps.push(Step { op, inputs: runtime, output });
}
let mut last_use = vec![usize::MAX; n];
for (k, s) in steps.iter().enumerate() {
for &i in &s.inputs {
last_use[i] = k;
}
}
for &o in &outputs {
last_use[o] = usize::MAX;
}
Ok(Model { shapes, names, consts: floats, steps, inputs, outputs, last_use })
}
/// The shape of input `k`.
pub fn input_shape(&self, k: usize) -> Option<&[usize]> {
self.inputs.get(k).and_then(|&i| self.shapes.get(i)).map(Vec::as_slice)
}
/// The shape and name of output `k`.
pub fn output(&self, k: usize) -> Option<(&[usize], &str)> {
let &i = self.outputs.get(k)?;
Some((self.shapes.get(i)?.as_slice(), self.names.get(i)?.as_str()))
}
/// Run the model on its inputs (row-major, NHWC); returns its outputs.
pub fn run(&self, inputs: &[&[f32]]) -> Result<Vec<Vec<f32>>> {
let mut vals: Vec<Option<Vec<f32>>> = vec![None; self.shapes.len()];
for (k, &id) in self.inputs.iter().enumerate() {
let x = inputs.get(k).ok_or("missing model input")?;
if x.len() != self.shapes[id].iter().product::<usize>() {
return Err(format!("input {k}: expected {:?}", self.shapes[id]));
}
vals[id] = Some(x.to_vec());
}
for (k, s) in self.steps.iter().enumerate() {
let y = {
let get = |i: usize| -> Result<&[f32]> {
vals.get(i)
.and_then(Option::as_deref)
.or_else(|| self.consts.get(i).and_then(Option::as_deref))
.ok_or_else(|| format!("{}: input not computed", self.names[s.output]))
};
let x = get(s.inputs[0])?;
let xs = &self.shapes[s.inputs[0]];
let ys = &self.shapes[s.output];
let (h, w) = (xs.get(1).copied().unwrap_or(1), xs.get(2).copied().unwrap_or(1));
let (oh, ow) = (ys.get(1).copied().unwrap_or(1), ys.get(2).copied().unwrap_or(1));
let y = match &s.op {
Op::Pointwise(l, a) => {
let mut y = l.forward(x, h * w);
a.apply(&mut y);
y
}
Op::Conv(c, pad, a) => {
let mut y = c.forward_sized(x, h, w, oh, ow, *pad);
a.apply(&mut y);
y
}
Op::Depthwise(d, pad, a) => {
let mut y = d.forward_sized(x, h, w, oh, ow, *pad);
a.apply(&mut y);
y
}
Op::MaxPool { k, stride, pad, act } => {
let mut y = max_pool(x, [h, w], *xs.last().unwrap_or(&1), [oh, ow], *k, *stride, *pad);
act.apply(&mut y);
y
}
Op::Add(a) => {
let b = get(s.inputs[1])?;
if b.len() != x.len() {
return Err(format!("{}: broadcasting ADD is not supported", self.names[s.output]));
}
let mut y: Vec<f32> = x.iter().zip(b).map(|(p, q)| p + q).collect();
a.apply(&mut y);
y
}
Op::Pad(p) => pad(x, xs, p)?,
Op::Concat { axis, act } => {
let parts = s.inputs.iter().map(|&i| Ok((get(i)?, &self.shapes[i]))).collect::<Result<Vec<_>>>()?;
let mut y = concat(&parts, *axis)?;
act.apply(&mut y);
y
}
Op::Reshape => x.to_vec(),
Op::Act(a) => {
let mut y = x.to_vec();
a.apply(&mut y);
y
}
Op::Prelu(alpha) => {
let c = alpha.len().max(1);
x.iter().enumerate().map(|(i, &v)| if v >= 0.0 { v } else { v * alpha[i % c] }).collect()
}
Op::Logistic => x.iter().map(|v| 1.0 / (1.0 + (-v).exp())).collect(),
};
if y.len() != ys.iter().product::<usize>() {
return Err(format!("{}: computed {} values for shape {ys:?}", self.names[s.output], y.len()));
}
y
};
vals[s.output] = Some(y);
for &i in &s.inputs {
if self.last_use[i] == k {
vals[i] = None;
}
}
}
self.outputs.iter().map(|&o| vals[o].take().or_else(|| self.consts[o].clone()).ok_or_else(|| "an output was not computed".to_string())).collect()
}
}
/// Max pooling over `k` windows; window cells outside the input are ignored.
fn max_pool(x: &[f32], [h, w]: [usize; 2], c: usize, [oh, ow]: [usize; 2], k: [usize; 2], s: [usize; 2], pad: [usize; 2]) -> Vec<f32> {
let mut y = vec![f32::NEG_INFINITY; oh * ow * c];
for oy in 0..oh {
for ox in 0..ow {
let out = &mut y[(oy * ow + ox) * c..][..c];
for ky in 0..k[0] {
let Some(iy) = (oy * s[0] + ky).checked_sub(pad[0]).filter(|&v| v < h) else { continue };
for kx in 0..k[1] {
let Some(ix) = (ox * s[1] + kx).checked_sub(pad[1]).filter(|&v| v < w) else { continue };
let Some(src) = x.get((iy * w + ix) * c..(iy * w + ix + 1) * c) else { continue };
for (o, v) in out.iter_mut().zip(src) {
*o = o.max(*v);
}
}
}
}
}
y
}
/// Zero padding of a row-major tensor of shape `shape`.
fn pad(x: &[f32], shape: &[usize], pads: &[[usize; 2]]) -> Result<Vec<f32>> {
if pads.len() != shape.len() {
return Err("PAD: rank mismatch".into());
}
let out: Vec<usize> = shape.iter().zip(pads).map(|(d, p)| d + p[0] + p[1]).collect();
let mut y = vec![0.0f32; out.iter().product()];
let rank = shape.len();
let inner = *shape.last().unwrap_or(&1);
let rows = x.len() / inner.max(1);
// Copy each innermost row to its padded place.
let mut idx = vec![0usize; rank.saturating_sub(1)];
for r in 0..rows {
let mut at = 0usize;
for d in 0..rank {
let i = if d + 1 == rank { pads[d][0] } else { idx[d] + pads[d][0] };
at = at * out[d] + i;
}
if let (Some(dst), Some(src)) = (y.get_mut(at..at + inner), x.get(r * inner..(r + 1) * inner)) {
dst.copy_from_slice(src);
}
for d in (0..idx.len()).rev() {
idx[d] += 1;
if idx[d] < shape[d] {
break;
}
idx[d] = 0;
}
}
Ok(y)
}
/// Concatenate along `axis`.
fn concat(parts: &[(&[f32], &Vec<usize>)], axis: usize) -> Result<Vec<f32>> {
let Some((_, s0)) = parts.first() else { return Ok(vec![]) };
let outer: usize = s0.get(..axis).ok_or("CONCATENATION: bad axis")?.iter().product();
let mut y = Vec::with_capacity(parts.iter().map(|p| p.0.len()).sum());
for o in 0..outer {
for (x, s) in parts {
let chunk: usize = s.get(axis..).ok_or("CONCATENATION: bad axis")?.iter().product();
y.extend_from_slice(x.get(o * chunk..(o + 1) * chunk).ok_or("CONCATENATION: bad input")?);
}
}
Ok(y)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn same_padding_matches_tensorflow() {
// TensorFlow pads the extra row after: 128 → 64 with a 3×3 stride-2 window pads 0 before.
assert_eq!(same(128, 3, 2), (64, 0));
assert_eq!(same(128, 5, 2), (64, 1));
assert_eq!(same(16, 3, 1), (16, 1));
assert_eq!(same(7, 2, 2), (4, 0));
assert_eq!(window(1, 4, 2, 2), Ok((2, 0)));
assert!(window(1, 1, 2, 2).is_err());
}
#[test]
fn asymmetric_conv_padding() {
// A 3×3 stride-2 "same" conv on 4×4: pads nothing before, one after.
let x: Vec<f32> = (0..16).map(|v| v as f32).collect();
let ones = vec![1.0f32; 9];
let c = Conv { wt: ones.clone(), b: vec![0.0], inp: 1, out: 1, ks: 3, stride: 2, pad: 0 };
let y = c.forward_sized(&x, 4, 4, 2, 2, [0, 0]);
// Top-left window rows 0–2, cols 0–2; the bottom-right one is cut by the edge.
assert_eq!(y, vec![45.0, 39.0, 66.0, 50.0]);
let d = Depthwise { w: ones, b: vec![0.0], c: 1, ks: 3, stride: 2 };
assert_eq!(d.forward_sized(&x, 4, 4, 2, 2, [0, 0]), y);
}
#[test]
fn pool_pad_and_concat() {
let x: Vec<f32> = (0..16).map(|v| v as f32).collect();
assert_eq!(max_pool(&x, [4, 4], 1, [2, 2], [2, 2], [2, 2], [0, 0]), vec![5.0, 7.0, 13.0, 15.0]);
// Same padding on 3×3 → 2×2: the last window is cut by the edge.
let x3: Vec<f32> = (0..9).map(|v| v as f32).collect();
assert_eq!(max_pool(&x3, [3, 3], 1, [2, 2], [2, 2], [2, 2], [0, 0]), vec![4.0, 5.0, 7.0, 8.0]);
// Channel padding (residual connections widen the channels with zeros).
let p = pad(&[1.0, 2.0, 3.0, 4.0], &[1, 1, 2, 2], &[[0, 0], [0, 0], [0, 0], [0, 1]]).unwrap();
assert_eq!(p, vec![1.0, 2.0, 0.0, 3.0, 4.0, 0.0]);
let p = pad(&[1.0, 2.0], &[1, 2], &[[0, 0], [1, 0]]).unwrap();
assert_eq!(p, vec![0.0, 1.0, 2.0]);
let a = [1.0, 2.0, 3.0, 4.0];
let b = [5.0, 6.0];
let (sa, sb) = (vec![1, 2, 2], vec![1, 1, 2]);
assert_eq!(concat(&[(&a, &sa), (&b, &sb)], 1).unwrap(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let (sa, sb) = (vec![2, 2], vec![2, 1]);
assert_eq!(concat(&[(&a, &sa), (&b, &sb)], 1).unwrap(), vec![1.0, 2.0, 5.0, 3.0, 4.0, 6.0]);
}
#[test]
fn damaged_files_are_errors_not_panics() {
assert!(Model::read(b"").is_err());
assert!(Model::read(&[0xff; 64]).is_err());
// Every prefix and a few corruptions of a hand-made buffer.
let mut fb = vec![12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 0, 0, 0, 0];
for n in 0..fb.len() {
let _ = Model::read(&fb[..n]);
}
for i in 0..fb.len() {
fb[i] ^= 0x5a;
let _ = Model::read(&fb);
}
}
}