Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

IX13: raea-sys-index in tools/layers.toml (systems); its copies folded: the models folder and the index home through raea-io-home's env_path, the Core ML cache judged by the package's Manifest.json (no walk of the package), the text tower loaded from SigLIP 2's folder

shinyobjectz86cf4fe12e87
diff --git a/Cargo.lock b/Cargo.lock
index a2f7fb30..8577dd51 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15799,6 +15799,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"objc2-image-io",
"ort",
+ "raea-io-home",
"raea-sys-ml",
"rayon",
"rusqlite",
diff --git a/systems/index/Cargo.toml b/systems/index/Cargo.toml
index 55903fba..698fbd2e 100644
--- a/systems/index/Cargo.toml
+++ b/systems/index/Cargo.toml
@@ -15,6 +15,8 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
# the text tower: ONNX on ONNX Runtime's CPU kernels, as raea's other encoders
raea-sys-ml = { path = "../ml" }
+# the models folder and the index home, as raea names them
+raea-io-home = { path = "../../io/home" }
ort = { version = "=2.0.0-rc.13", features = ["half"] }
tokenizers = { version = "0.23", default-features = false, features = ["onig"] }
walkdir = "2"
diff --git a/systems/index/examples/fast.rs b/systems/index/examples/fast.rs
index e13d3f0d..bf5e61a4 100644
--- a/systems/index/examples/fast.rs
+++ b/systems/index/examples/fast.rs
@@ -1,6 +1,5 @@
//! `raea index` without building all of raea, to measure the fast pass (docs/index.feature IX1, IX14):
//! fast add FOLDER | fast search WORDS... | fast status | fast remove ID | fast serve (cli.rs USAGE)
fn main() {
- let args: Vec<String> = std::env::args().skip(1).collect();
- std::process::exit(raea_sys_index::cli::cli(&args));
+ std::process::exit(raea_sys_index::cli::cli(&std::env::args().skip(1).collect::<Vec<_>>()));
}
diff --git a/systems/index/src/apple.rs b/systems/index/src/apple.rs
index ad1292a6..3a0769fb 100644
--- a/systems/index/src/apple.rs
+++ b/systems/index/src/apple.rs
@@ -119,20 +119,14 @@ pub fn write_jpeg(img: &CGImage, to: &Path) -> Result<(), String> {
pub struct Model(Retained<MLModel>);
unsafe impl Send for Model {}
-fn modified(p: &Path) -> std::time::SystemTime {
- fn walk(p: &Path, best: &mut std::time::SystemTime) {
- if let Ok(m) = std::fs::metadata(p).and_then(|m| m.modified()) {
- *best = (*best).max(m);
- }
- if let Ok(rd) = std::fs::read_dir(p) {
- for e in rd.flatten() {
- walk(&e.path(), best);
- }
- }
+/// Whether the compiled copy is older than the package: a package's Manifest.json is written whenever it is saved or
+/// copied in, and the compiled folder when it was compiled. No compiled copy, or no time to read, compiles again.
+fn stale(compiled: &Path, package: &Path) -> bool {
+ let (Ok(c), Ok(p)) = (std::fs::metadata(compiled), std::fs::metadata(package.join("Manifest.json"))) else { return true };
+ match (c.modified(), p.modified()) {
+ (Ok(c), Ok(p)) => c < p,
+ _ => true,
}
- let mut best = std::time::UNIX_EPOCH;
- walk(p, &mut best);
- best
}
impl Model {
@@ -145,7 +139,7 @@ impl Model {
std::fs::create_dir_all(&caches).map_err(|e| e.to_string())?;
let name = package.file_stem().and_then(|s| s.to_str()).unwrap_or("model");
let compiled = caches.join(format!("{name}.mlmodelc"));
- if !compiled.exists() || modified(&compiled) < modified(package) {
+ if stale(&compiled, package) {
let url = NSURL::from_directory_path(package).ok_or("bad package path")?;
#[allow(deprecated)]
let fresh = unsafe { MLModel::compileModelAtURL_error(&url) }.map_err(|e| format!("compiling {name}: {}", e.localizedDescription()))?;
diff --git a/systems/index/src/cli.rs b/systems/index/src/cli.rs
index f10f50a8..59ef7c8b 100644
--- a/systems/index/src/cli.rs
+++ b/systems/index/src/cli.rs
@@ -11,14 +11,11 @@ use std::sync::atomic::AtomicBool;
pub const USAGE: &str = "raea index add FOLDER... [--json] | raea index search WORDS... [--k N] [--source ID|FOLDER] [--json] | raea index status [--json] | raea index remove ID|FOLDER | raea index serve [--home DIR] (every picture on a folder or a drive made searchable by words on this Mac, fast: add lists it and embeds each picture's small copy with SigLIP 2 on the Neural Engine, a counter as it goes, JSON lines with --json; search gives the best for the words; status lists the sources and what each holds; remove takes one out; serve keeps the index open for the raea app, one JSON ask a line on stdin; the index lives in ~/.raea/library/fast, or --home / RAEA_INDEX_HOME)";
+/// The exit code: 0, or 1 with the reason said
pub fn cli(args: &[String]) -> i32 {
- match run(args) {
- Ok(()) => 0,
- Err(e) => {
- eprintln!("raea index: {e:#}");
- 1
- }
- }
+ let Err(e) = run(args) else { return 0 };
+ eprintln!("raea index: {e:#}");
+ 1
}
struct Flags {
@@ -127,8 +124,7 @@ fn find(f: &Flags, home: &std::path::Path) -> Result<()> {
}
None => None,
};
- let (m, tok) = crate::text_files();
- let mut text = Text::load(&m, &tok)?;
+ let mut text = Text::load(&crate::siglip_dir())?;
let rows = Rows::load(&store, MODEL)?;
let q = text.embed(&words)?;
let hits = search::search(&store, &rows, &q, f.k, source.as_deref())?;
diff --git a/systems/index/src/lib.rs b/systems/index/src/lib.rs
index 16c159b2..1d47a081 100644
--- a/systems/index/src/lib.rs
+++ b/systems/index/src/lib.rs
@@ -55,18 +55,14 @@ pub fn normalise(v: &mut [f32]) {
v.iter_mut().for_each(|x| *x /= n);
}
-/// Where SigLIP 2 B/16-256's files are: $RAEA_MODELS, else ~/.local/share/raea-models
-pub fn models_dir() -> PathBuf {
- std::env::var_os("RAEA_MODELS").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".local/share/raea-models"))
+/// SigLIP 2 B/16-256's folder in the models folder ($RAEA_MODELS, else ~/.local/share/raea-models, as perception's):
+/// the image tower's Core ML package, the text tower's ONNX and the tokenizer
+pub fn siglip_dir() -> PathBuf {
+ raea_io_home::env_path("RAEA_MODELS", ".local/share/raea-models").join("siglip2-base-p16-256")
}
pub fn image_package() -> PathBuf {
- models_dir().join("siglip2-base-p16-256/SigLIP2Image.mlpackage")
-}
-
-pub fn text_files() -> (PathBuf, PathBuf) {
- let d = models_dir().join("siglip2-base-p16-256");
- (d.join("onnx/text_model.onnx"), d.join("tokenizer.json"))
+ siglip_dir().join("SigLIP2Image.mlpackage")
}
/// What listing a source found
@@ -141,8 +137,8 @@ pub fn embed_pictures(store: &mut Store, model: &apple::Model, source: &str, sto
}
let pxs: Vec<&objc2_core_video::CVPixelBuffer> = batch.iter().map(|r| &*r.px).collect();
let vs = model.embed(&pxs).map_err(|e| anyhow::anyhow!(e))?;
- let rows: Vec<(i64, f64, Vec<f32>)> = batch.iter().zip(vs).map(|(r, v)| (r.item, r.t, v)).collect();
- let dims: Vec<(i64, u32, u32)> = batch.iter().map(|r| (r.item, r.w, r.h)).collect();
+ // each picture's row and its size, in one pass
+ let (rows, dims): (Vec<(i64, f64, Vec<f32>)>, Vec<(i64, u32, u32)>) = batch.iter().zip(vs).map(|(r, v)| ((r.item, r.t, v), (r.item, r.w, r.h))).unzip();
store.append(MODEL, &rows, &dims)?;
prog.done += batch.len() as u64;
prog.newest.extend(batch.iter().map(|r| r.item));
diff --git a/systems/index/src/serve.rs b/systems/index/src/serve.rs
index a031665d..6e3ed641 100644
--- a/systems/index/src/serve.rs
+++ b/systems/index/src/serve.rs
@@ -109,7 +109,7 @@ pub fn serve(dir: &Path) -> Result<()> {
}
fn answer(sh: &Shared, store: &mut Store, jobs: &mpsc::Sender<PathBuf>, finds: &mpsc::Sender<Find>, ask: &Value, id: Value) -> Result<Option<Value>> {
- let s = |k: &str| ask.get(k).and_then(Value::as_str).map(str::to_string);
+ let s = |k: &str| ask[k].as_str().map(String::from);
let k = ask.get("k").and_then(Value::as_u64).unwrap_or(60).clamp(1, 2000) as usize;
match ask.get("op").and_then(Value::as_str).unwrap_or("") {
"add" => {
@@ -226,8 +226,7 @@ fn find(sh: &Shared, dir: &Path, finds: mpsc::Receiver<Find>) {
return Ok(0.0);
}
let t = Instant::now();
- let (m, tok) = crate::text_files();
- *text = Some(Text::load(&m, &tok)?);
+ *text = Some(Text::load(&crate::siglip_dir())?);
Ok(t.elapsed().as_secs_f64() * 1e3)
};
for f in finds {
diff --git a/systems/index/src/store.rs b/systems/index/src/store.rs
index e7e21426..3ab33c86 100644
--- a/systems/index/src/store.rs
+++ b/systems/index/src/store.rs
@@ -72,8 +72,9 @@ impl Store {
Ok(Store { dir: dir.to_path_buf(), db })
}
+ /// $RAEA_INDEX_HOME, else ~/.raea/library/fast
pub fn default_dir() -> PathBuf {
- std::env::var_os("RAEA_INDEX_HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".raea/library/fast"))
+ raea_io_home::env_path("RAEA_INDEX_HOME", ".raea/library/fast")
}
pub fn vectors(&self, model: &str) -> PathBuf {
diff --git a/systems/index/src/text.rs b/systems/index/src/text.rs
index 9394d940..69cb2233 100644
--- a/systems/index/src/text.rs
+++ b/systems/index/src/text.rs
@@ -15,10 +15,11 @@ pub struct Text {
}
impl Text {
- pub fn load(model: &Path, tokenizer: &Path) -> Result<Text> {
- let tok = tokenizers::Tokenizer::from_file(tokenizer).map_err(|e| anyhow!("SigLIP 2's tokenizer: {e}"))?;
- let pad = tok.token_to_id("<pad>").unwrap_or(0) as i64;
- Ok(Text { s: raea_sys_ml::session(model).context("SigLIP 2's text tower")?, tok, pad })
+ /// From SigLIP 2's folder: onnx/text_model.onnx and tokenizer.json
+ pub fn load(dir: &Path) -> Result<Text> {
+ let s = raea_sys_ml::session(&dir.join("onnx/text_model.onnx")).context("SigLIP 2's text tower")?;
+ let tok = tokenizers::Tokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| anyhow!("SigLIP 2's tokenizer: {e}"))?;
+ Ok(Text { pad: tok.token_to_id("<pad>").map_or(0, i64::from), s, tok })
}
/// The words' vector, L2-normalised
diff --git a/tools/layers.toml b/tools/layers.toml
index d5bf6042..cd216222 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -58,6 +58,8 @@ raea-sys-mlx = "systems"
raea-sys-speech = "systems"
raea-sys-layout = "systems"
raea-sys-vision = "systems"
+# Index's fast pass (docs/index.feature): pictures embedded on the Neural Engine, searched by words
+raea-sys-index = "systems"
# Fingerprint (docs/fingerprint.feature): the columns its heads read, and the heads
raea-sys-columns = "systems"
raea-sys-fingerprint = "systems"