Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat: add ONNX text embedder with tract — model downloaded on init
FABIOTESS1f9a6e97a87f
diff --git a/src/embed.rs b/src/embed.rsnew file mode 100644index 00000000..24687bb3--- /dev/null+++ b/src/embed.rs@@ -0,0 +1,134 @@+//! ONNX-based text embedding using tract.+//! Loads a sentence-transformer model exported to ONNX format.++use anyhow::{Context, Result};+use std::path::Path;+use tokenizers::Tokenizer;+use tract_onnx::prelude::*;++use crate::poincare::l2_normalize;++/// Model download URLs for bge-small-en-v1.5+pub const BGE_SMALL_ONNX_URL: &str =+ "https://huggingface.co/BAAI/bge-small-en-v1.5/resolve/main/onnx/model.onnx";+pub const BGE_SMALL_TOKENIZER_URL: &str =+ "https://huggingface.co/BAAI/bge-small-en-v1.5/resolve/main/tokenizer.json";++pub struct TextEmbedder {+ model: SimplePlan<TypedFact, Box<dyn TypedOp>, Graph<TypedFact, Box<dyn TypedOp>>>,+ tokenizer: Tokenizer,+ dim: usize,+}++impl TextEmbedder {+ /// Load an ONNX model and tokenizer from disk.+ pub fn load(model_path: &Path, tokenizer_path: &Path) -> Result<Self> {+ let model = tract_onnx::onnx()+ .model_for_path(model_path)+ .context("Failed to load ONNX model")?+ .into_optimized()+ .context("Failed to optimize model")?+ .into_runnable()+ .context("Failed to create runnable model")?;++ let tokenizer = Tokenizer::from_file(tokenizer_path)+ .map_err(|e| anyhow::anyhow!("Failed to load tokenizer: {e}"))?;++ // Detect output dimension from model+ let output_fact = model.model().output_fact(0)?;+ let dim = output_fact+ .shape+ .as_concrete()+ .and_then(|s| s.last().copied())+ .unwrap_or(384);++ Ok(Self {+ model,+ tokenizer,+ dim,+ })+ }++ /// Embed a single text string. Returns L2-normalized vector.+ pub fn embed(&self, text: &str) -> Result<Vec<f32>> {+ let encoding = self+ .tokenizer+ .encode(text, true)+ .map_err(|e| anyhow::anyhow!("Tokenization failed: {e}"))?;++ let input_ids: Vec<i64> = encoding.get_ids().iter().map(|&id| id as i64).collect();+ let attention_mask: Vec<i64> = encoding+ .get_attention_mask()+ .iter()+ .map(|&m| m as i64)+ .collect();+ let token_type_ids: Vec<i64> =+ encoding.get_type_ids().iter().map(|&t| t as i64).collect();+ let seq_len = input_ids.len();++ let input_ids_tensor =+ tract_ndarray::Array2::from_shape_vec((1, seq_len), input_ids)?;+ let attention_tensor =+ tract_ndarray::Array2::from_shape_vec((1, seq_len), attention_mask.clone())?;+ let type_ids_tensor =+ tract_ndarray::Array2::from_shape_vec((1, seq_len), token_type_ids)?;++ let outputs = self.model.run(tvec![+ input_ids_tensor.into_tensor().into(),+ attention_tensor.into_tensor().into(),+ type_ids_tensor.into_tensor().into(),+ ])?;++ // Get the last hidden state (first output), shape [1, seq_len, dim]+ let output = outputs[0].to_array_view::<f32>()?;++ // Mean pooling with attention mask+ let mut pooled = vec![0.0f32; self.dim];+ let mut mask_sum = 0.0f32;+ for (i, &mask) in attention_mask.iter().enumerate() {+ if mask > 0 {+ let mask_f = mask as f32;+ for j in 0..self.dim {+ pooled[j] += output[[0, i, j]] * mask_f;+ }+ mask_sum += mask_f;+ }+ }+ if mask_sum > 0.0 {+ for v in &mut pooled {+ *v /= mask_sum;+ }+ }++ Ok(l2_normalize(&pooled))+ }++ /// Embed multiple texts. Returns Vec of L2-normalized vectors.+ pub fn embed_batch(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {+ texts.iter().map(|t| self.embed(t)).collect()+ }++ /// Output dimension of the model.+ pub fn dim(&self) -> usize {+ self.dim+ }+}++/// Download a file from URL to a local path.+pub async fn download_model_file(url: &str, dest: &Path) -> Result<()> {+ let client = reqwest::Client::new();+ let resp = client+ .get(url)+ .send()+ .await+ .context("Failed to download model")?;++ if !resp.status().is_success() {+ anyhow::bail!("Download failed with status: {}", resp.status());+ }++ let bytes = resp.bytes().await?;+ std::fs::write(dest, &bytes).context("Failed to write model file")?;++ Ok(())+}diff --git a/src/lib.rs b/src/lib.rsindex 5da34b1b..41ee1072 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -21,3 +21,7 @@ pub mod tableaux;pub mod poincare;#[cfg(feature = "embeddings")]pub mod vecstore;+#[cfg(feature = "embeddings")]+pub mod embed;+#[cfg(feature = "embeddings")]+pub mod structembed;diff --git a/tests/embed_test.rs b/tests/embed_test.rsnew file mode 100644index 00000000..331883c7--- /dev/null+++ b/tests/embed_test.rs@@ -0,0 +1,65 @@+#[cfg(feature = "embeddings")]+mod tests {+ use open_ontologies::embed::TextEmbedder;+ use std::path::Path;++ #[test]+ fn test_model_not_found_error() {+ let result = TextEmbedder::load(+ Path::new("/nonexistent/model.onnx"),+ Path::new("/nonexistent/tokenizer.json"),+ );+ assert!(result.is_err(), "Should error when model file doesn't exist");+ }++ #[test]+ fn test_embed_text_if_model_exists() {+ let model_dir = dirs::home_dir().unwrap().join(".open-ontologies/models");+ let model_path = model_dir.join("bge-small-en-v1.5.onnx");+ let tokenizer_path = model_dir.join("tokenizer.json");++ if !model_path.exists() {+ eprintln!("Skipping: model not downloaded. Run `open-ontologies init` first.");+ return;+ }++ let embedder = TextEmbedder::load(&model_path, &tokenizer_path).unwrap();+ let vec = embedder.embed("Dog").unwrap();+ assert_eq!(+ vec.len(),+ 384,+ "bge-small-en-v1.5 should produce 384-dim vectors"+ );++ let norm: f32 = vec.iter().map(|x| x * x).sum::<f32>().sqrt();+ assert!(+ (norm - 1.0).abs() < 0.01,+ "Should be L2-normalized, got norm={norm}"+ );+ }++ #[test]+ fn test_similar_terms_closer() {+ let model_dir = dirs::home_dir().unwrap().join(".open-ontologies/models");+ let model_path = model_dir.join("bge-small-en-v1.5.onnx");+ let tokenizer_path = model_dir.join("tokenizer.json");++ if !model_path.exists() {+ eprintln!("Skipping: model not downloaded.");+ return;+ }++ let embedder = TextEmbedder::load(&model_path, &tokenizer_path).unwrap();+ let dog = embedder.embed("Dog").unwrap();+ let cat = embedder.embed("Cat").unwrap();+ let car = embedder.embed("Automobile").unwrap();++ let dog_cat: f32 = dog.iter().zip(cat.iter()).map(|(a, b)| a * b).sum();+ let dog_car: f32 = dog.iter().zip(car.iter()).map(|(a, b)| a * b).sum();++ assert!(+ dog_cat > dog_car,+ "Dog-Cat similarity ({dog_cat}) should be > Dog-Car ({dog_car})"+ );+ }+}