Skip to main content

ffai_models/
lib.rs

1//! # ffai-models
2//!
3//! Weight management for `FFai`. Core principle: **weights are data, not
4//! code** — the repo holds only TOML *manifests* describing each model (files,
5//! source, checksums, and crucially its *license*, which is often different
6//! from `FFai`'s). Weights are fetched into a local cache, never vendored.
7//!
8//! Phase 0 ships manifests + cache resolution; the downloader (Hugging Face
9//! hub, resumable, checksum-verified) lands in Phase 1.
10
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13
14use ffai_core::error::{Error, Result};
15use serde::Deserialize;
16use sha2::{Digest, Sha256};
17
18/// A model whose files are all present locally, with their resolved paths.
19#[derive(Debug, Clone)]
20pub struct ResolvedModel {
21    pub name: String,
22    /// The WEIGHTS' license — may be more restrictive than `FFai`'s own.
23    pub license: String,
24    /// Filename → local path.
25    pub files: BTreeMap<String, PathBuf>,
26}
27
28impl ResolvedModel {
29    /// Path of a required file, or a clear error naming what's missing.
30    pub fn file(&self, name: &str) -> Result<&Path> {
31        self.files
32            .get(name)
33            .map(PathBuf::as_path)
34            .ok_or_else(|| Error::Model(format!("model `{}` has no file `{name}`", self.name)))
35    }
36}
37
38/// Resolve one file from the shared Hugging Face cache, downloading it when
39/// `cache_only` is false. Uses the same cache as `transformers` and
40/// `faster-whisper`, so a model either side already has is not fetched twice.
41#[cfg(feature = "fetch")]
42fn hub_download(repo: &str, filename: &str, cache_only: bool) -> Result<PathBuf> {
43    let (owner, name) = repo
44        .split_once('/')
45        .ok_or_else(|| Error::Model(format!("hf_repo `{repo}` is not in `owner/name` form")))?;
46    let client = hf_hub::HFClientSync::new()
47        .map_err(|e| Error::Model(format!("hugging face client init failed: {e}")))?;
48    client
49        .model(owner, name)
50        .download_file()
51        .filename(filename)
52        .local_files_only(cache_only)
53        .send()
54        .map_err(|e| Error::Model(format!("{repo}/{filename}: {e}")))
55}
56
57/// Without `fetch`, nothing is downloaded — and the error says which file to
58/// supply rather than failing as a missing symbol.
59#[cfg(not(feature = "fetch"))]
60fn hub_download(repo: &str, filename: &str, _cache_only: bool) -> Result<PathBuf> {
61    Err(Error::Model(format!(
62        "{repo}/{filename} is not present locally and this build has the          `fetch` feature disabled — place the file in the model directory, or          enable `ffai-models/fetch` to download it"
63    )))
64}
65
66/// Verify a downloaded file against its manifest checksum, when one is
67/// declared. A mismatch is an error, never a warning: silently running on
68/// unexpected weights would invalidate every measurement taken with them.
69fn verify_checksum(path: &Path, file: &ModelFile) -> Result<()> {
70    let Some(expected) = &file.sha256 else {
71        return Ok(());
72    };
73    let bytes = std::fs::read(path)?;
74    let actual: String = Sha256::digest(&bytes)
75        .iter()
76        .map(|b| format!("{b:02x}"))
77        .collect();
78    if actual != expected.to_ascii_lowercase() {
79        return Err(Error::Model(format!(
80            "checksum mismatch for {}: manifest says {expected}, file is {actual}",
81            path.display()
82        )));
83    }
84    Ok(())
85}
86
87/// One weight/config file belonging to a model.
88#[derive(Debug, Clone, Deserialize)]
89pub struct ModelFile {
90    /// Filename within the model's cache directory (and its HF repo).
91    pub name: String,
92    /// Hex SHA-256, verified after download when present.
93    pub sha256: Option<String>,
94}
95
96/// A model manifest (`models/*.toml`).
97#[derive(Debug, Clone, Deserialize)]
98pub struct ModelManifest {
99    pub name: String,
100    /// Task tag: "asr", "tts", "ocr", "vlm".
101    pub task: String,
102    pub description: Option<String>,
103    /// The WEIGHTS' license — surfaced to users because it may be more
104    /// restrictive than `FFai`'s MIT/Apache code license.
105    pub license: String,
106    /// Hugging Face repo id, e.g. "openai/whisper-tiny".
107    pub hf_repo: Option<String>,
108    #[serde(default)]
109    pub files: Vec<ModelFile>,
110}
111
112impl ModelManifest {
113    pub fn from_toml(text: &str) -> Result<Self> {
114        toml::from_str(text).map_err(|e| Error::Model(format!("bad manifest: {e}")))
115    }
116
117    pub fn load(path: &Path) -> Result<Self> {
118        let text = std::fs::read_to_string(path)?;
119        Self::from_toml(&text)
120    }
121
122    /// Directory this model's files live in when placed manually.
123    #[must_use]
124    pub fn cache_path(&self) -> PathBuf {
125        cache_dir().join("models").join(&self.name)
126    }
127
128    /// True when every listed file already resolves locally — no network.
129    #[must_use]
130    pub fn is_cached(&self) -> bool {
131        !self.files.is_empty()
132            && self
133                .files
134                .iter()
135                .all(|f| self.local_path(&f.name).is_some())
136    }
137
138    /// Resolve one file without touching the network: a manual placement
139    /// under [`Self::cache_path`] wins, otherwise the shared Hugging Face
140    /// cache (the same one `transformers`/`faster-whisper` use, so a model
141    /// downloaded by either side is not downloaded twice).
142    #[must_use]
143    pub fn local_path(&self, name: &str) -> Option<PathBuf> {
144        let manual = self.cache_path().join(name);
145        if manual.exists() {
146            return Some(manual);
147        }
148        hub_download(self.hf_repo.as_ref()?, name, true).ok()
149    }
150
151    /// Resolve every file, downloading from the Hugging Face hub as needed.
152    ///
153    /// Downloads are cached, so this is cheap on repeat calls — but it is
154    /// still network I/O the first time, which is why benchmarks warm the
155    /// cache outside any timed region (see docs/benchmarking.md).
156    pub fn fetch(&self) -> Result<ResolvedModel> {
157        let mut files = BTreeMap::new();
158        for file in &self.files {
159            if let Some(path) = self.local_path(&file.name) {
160                verify_checksum(&path, file)?;
161                files.insert(file.name.clone(), path);
162                continue;
163            }
164            let repo = self.hf_repo.as_ref().ok_or_else(|| {
165                Error::Model(format!(
166                    "model `{}` declares no hf_repo and `{}` is not present under {}",
167                    self.name,
168                    file.name,
169                    self.cache_path().display()
170                ))
171            })?;
172            let path = hub_download(repo, &file.name, false)?;
173            verify_checksum(&path, file)?;
174            files.insert(file.name.clone(), path);
175        }
176        Ok(ResolvedModel {
177            name: self.name.clone(),
178            license: self.license.clone(),
179            files,
180        })
181    }
182
183    /// Resolve every file from `root/<model name>/<file>` and nowhere else —
184    /// **no cache lookup, no network, ever.**
185    ///
186    /// This is the production form for a scheduled or offline job: the caller
187    /// states where weights live, a missing file is an error naming the exact
188    /// path that was expected, and nothing is fetched mid-job
189    /// (docs/plans/commercial-gaps.md, gap 7). Checksums are verified exactly
190    /// as [`Self::fetch`] verifies them.
191    pub fn resolve_in(&self, root: &Path) -> Result<ResolvedModel> {
192        let all: Vec<&str> = self.files.iter().map(|f| f.name.as_str()).collect();
193        self.resolve_only_in(root, &all)
194    }
195
196    /// [`Self::resolve_in`], for just the named files.
197    ///
198    /// A manifest documents provenance as well as runtime needs, so it can list
199    /// files no engine loads. `ppocrv5-mobile-det`, for example, lists its
200    /// training checkpoint, the source of the fused weights. An offline
201    /// deployment must not be made to ship those, so a loader asks for what it
202    /// will open. A name the manifest does not declare is an error, because it
203    /// has no checksum to verify against.
204    pub fn resolve_only_in(&self, root: &Path, needed: &[&str]) -> Result<ResolvedModel> {
205        let dir = root.join(&self.name);
206        let mut files = BTreeMap::new();
207        for name in needed {
208            if !self.files.iter().any(|f| f.name == *name) {
209                return Err(Error::Model(format!(
210                    "model `{}` declares no file `{name}` — it has no checksum to verify against",
211                    self.name
212                )));
213            }
214        }
215        for file in self
216            .files
217            .iter()
218            .filter(|f| needed.contains(&f.name.as_str()))
219        {
220            let path = dir.join(&file.name);
221            if !path.is_file() {
222                return Err(Error::Model(format!(
223                    "model `{}` needs `{}`, expected at {} — not present (offline resolution \
224                     never downloads)",
225                    self.name,
226                    file.name,
227                    path.display()
228                )));
229            }
230            verify_checksum(&path, file)?;
231            files.insert(file.name.clone(), path);
232        }
233        Ok(ResolvedModel {
234            name: self.name.clone(),
235            license: self.license.clone(),
236            files,
237        })
238    }
239
240    /// Check that every file is already present locally and matches its
241    /// checksum, **without downloading anything** — the `verify` half of
242    /// `prefetch`/`verify`. Resolves exactly where [`Self::fetch`] would look.
243    pub fn verify(&self) -> Result<ResolvedModel> {
244        let mut files = BTreeMap::new();
245        for file in &self.files {
246            let path = self.local_path(&file.name).ok_or_else(|| {
247                Error::Model(format!(
248                    "model `{}` is missing `{}` (looked under {}{})",
249                    self.name,
250                    file.name,
251                    self.cache_path().display(),
252                    if self.hf_repo.is_some() {
253                        " and the Hugging Face cache"
254                    } else {
255                        ""
256                    }
257                ))
258            })?;
259            verify_checksum(&path, file)?;
260            files.insert(file.name.clone(), path);
261        }
262        Ok(ResolvedModel {
263            name: self.name.clone(),
264            license: self.license.clone(),
265            files,
266        })
267    }
268}
269
270/// Load every `*.toml` manifest in a directory (typically `models/`).
271///
272/// A missing directory is an error that NAMES the directory. The bare i/o
273/// error ("The system cannot find the path specified") is what a crates.io
274/// user got when `models/` did not exist relative to their working directory,
275/// and it reads like missing weights rather than a missing manifest folder.
276pub fn load_dir(dir: &Path) -> Result<Vec<ModelManifest>> {
277    let mut out = Vec::new();
278    let entries = std::fs::read_dir(dir).map_err(|e| {
279        Error::Model(format!(
280            "cannot read model manifest directory {}: {e}",
281            dir.display()
282        ))
283    })?;
284    for entry in entries {
285        let path = entry?.path();
286        if path.extension().and_then(|e| e.to_str()) == Some("toml") {
287            out.push(
288                ModelManifest::load(&path)
289                    .map_err(|e| Error::Model(format!("{}: {e}", path.display())))?,
290            );
291        }
292    }
293    out.sort_by(|a, b| a.task.cmp(&b.task).then_with(|| a.name.cmp(&b.name)));
294    Ok(out)
295}
296
297/// The `FFai` model cache root: `$FFAI_CACHE` or `<os cache dir>/ffai`.
298pub fn cache_dir() -> PathBuf {
299    if let Ok(dir) = std::env::var("FFAI_CACHE") {
300        return PathBuf::from(dir);
301    }
302    dirs::cache_dir()
303        .unwrap_or_else(std::env::temp_dir)
304        .join("ffai")
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn manifest_parses_and_surfaces_license() {
313        let m = ModelManifest::from_toml(
314            r#"
315            name = "whisper-tiny"
316            task = "asr"
317            license = "Apache-2.0"
318            hf_repo = "openai/whisper-tiny"
319
320            [[files]]
321            name = "model.safetensors"
322            "#,
323        )
324        .unwrap();
325        assert_eq!(m.name, "whisper-tiny");
326        assert_eq!(m.license, "Apache-2.0");
327        assert_eq!(m.files.len(), 1);
328        assert!(!m.is_cached());
329    }
330
331    fn scratch(tag: &str) -> PathBuf {
332        let d = std::env::temp_dir().join(format!("ffai-models-{tag}-{}", std::process::id()));
333        let _ = std::fs::remove_dir_all(&d);
334        std::fs::create_dir_all(&d).unwrap();
335        d
336    }
337
338    fn manifest_for(sha: &str) -> ModelManifest {
339        ModelManifest::from_toml(&format!(
340            r#"
341            name = "tiny-test"
342            task = "ocr"
343            license = "MIT"
344
345            [[files]]
346            name = "w.bin"
347            sha256 = "{sha}"
348            "#
349        ))
350        .unwrap()
351    }
352
353    /// sha256("abc")
354    const ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
355
356    #[test]
357    fn resolve_in_names_the_exact_missing_path_and_never_fetches() {
358        let root = scratch("missing");
359        let err = manifest_for(ABC).resolve_in(&root).unwrap_err().to_string();
360        let want = root.join("tiny-test").join("w.bin");
361        assert!(
362            err.contains(&want.display().to_string()),
363            "error must name {}: {err}",
364            want.display()
365        );
366        assert!(err.contains("never downloads"), "{err}");
367        let _ = std::fs::remove_dir_all(&root);
368    }
369
370    #[test]
371    fn resolve_in_finds_and_checksums_a_placed_file() {
372        let root = scratch("present");
373        std::fs::create_dir_all(root.join("tiny-test")).unwrap();
374        std::fs::write(root.join("tiny-test").join("w.bin"), b"abc").unwrap();
375        let r = manifest_for(ABC).resolve_in(&root).unwrap();
376        assert_eq!(
377            r.file("w.bin").unwrap(),
378            root.join("tiny-test").join("w.bin")
379        );
380
381        // Same bytes, wrong declared checksum: an error, not a warning.
382        let bad = manifest_for(&"0".repeat(64))
383            .resolve_in(&root)
384            .unwrap_err()
385            .to_string();
386        assert!(bad.contains("checksum mismatch"), "{bad}");
387        let _ = std::fs::remove_dir_all(&root);
388    }
389
390    #[test]
391    fn load_dir_names_a_missing_directory() {
392        let missing = std::env::temp_dir().join("ffai-models-definitely-absent-dir");
393        let err = load_dir(&missing).unwrap_err().to_string();
394        assert!(err.contains(&missing.display().to_string()), "{err}");
395    }
396
397    /// Only the named files are required, so a provenance-only file (a
398    /// training checkpoint) need not be shipped; but an undeclared name is
399    /// refused, because there is no checksum to verify it against.
400    #[test]
401    fn resolve_only_in_needs_just_the_named_files_and_refuses_undeclared_ones() {
402        let root = scratch("subset");
403        std::fs::create_dir_all(root.join("tiny-test")).unwrap();
404        std::fs::write(root.join("tiny-test").join("w.bin"), b"abc").unwrap();
405        let m = ModelManifest::from_toml(&format!(
406            r#"
407            name = "tiny-test"
408            task = "ocr"
409            license = "MIT"
410
411            [[files]]
412            name = "w.bin"
413            sha256 = "{ABC}"
414
415            [[files]]
416            name = "train-only.bin"
417            "#
418        ))
419        .unwrap();
420        assert!(
421            m.resolve_in(&root).is_err(),
422            "the full set includes an absent file"
423        );
424        let r = m.resolve_only_in(&root, &["w.bin"]).unwrap();
425        assert_eq!(r.files.len(), 1);
426        let err = m
427            .resolve_only_in(&root, &["nope.bin"])
428            .unwrap_err()
429            .to_string();
430        assert!(err.contains("declares no file `nope.bin`"), "{err}");
431        let _ = std::fs::remove_dir_all(&root);
432    }
433}