Spaces:
Build error
Build error
Download src/inference/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 31.6 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/inference/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/inference/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/inference/mod.rs
31.6 kB
| //! ONNX inference module for IntentForge v2 | |
| //! | |
| //! Handles batch inference for text embeddings and scoring using | |
| //! all-MiniLM-L6-v2 model with 384-dimensional output vectors. | |
| use anyhow::{Context, Result}; | |
| use lru::LruCache; | |
| use std::num::NonZeroUsize; | |
| use std::path::Path; | |
| use std::sync::{Arc, Mutex}; | |
| /// Tokenizer for text preprocessing | |
| pub struct Tokenizer { | |
| max_seq_length: usize, | |
| vocab: std::collections::HashMap<String, i64>, | |
| } | |
| /// Tokenized batch as raw Vec data with shape info | |
| pub struct TokenizedBatch { | |
| pub input_ids: Vec<i64>, | |
| pub attention_mask: Vec<i64>, | |
| pub token_type_ids: Vec<i64>, | |
| pub shape: Vec<i64>, | |
| } | |
| impl Tokenizer { | |
| pub fn new(max_seq_length: usize) -> Self { | |
| let mut vocab = std::collections::HashMap::new(); | |
| // Attempt to load BERT vocab if it exists in models/vocab.txt | |
| if let Ok(content) = std::fs::read_to_string("models/vocab.txt") { | |
| for (i, line) in content.lines().enumerate() { | |
| vocab.insert(line.to_string(), i as i64); | |
| } | |
| tracing::info!("Loaded {} tokens into Tokenizer vocab", vocab.len()); | |
| } else { | |
| tracing::warn!("models/vocab.txt not found. Tokenizer will use fallback hashing."); | |
| } | |
| Self { | |
| max_seq_length, | |
| vocab, | |
| } | |
| } | |
| /// Tokenize a batch of texts into flat vectors with shape [batch, seq_len] | |
| pub fn tokenize_batch(&self, texts: &[String]) -> TokenizedBatch { | |
| let batch_size = texts.len(); | |
| let seq_len = self.max_seq_length; | |
| let total = batch_size * seq_len; | |
| let mut input_ids = vec![0i64; total]; | |
| let mut attention_mask = vec![0i64; total]; | |
| let token_type_ids = vec![0i64; total]; | |
| for (i, text) in texts.iter().enumerate() { | |
| let tokens = self.tokenize_text(text); | |
| for (j, &token_id) in tokens.iter().enumerate().take(seq_len) { | |
| let idx = i * seq_len + j; | |
| input_ids[idx] = token_id; | |
| attention_mask[idx] = 1; | |
| } | |
| } | |
| TokenizedBatch { | |
| input_ids, | |
| attention_mask, | |
| token_type_ids, | |
| shape: vec![batch_size as i64, seq_len as i64], | |
| } | |
| } | |
| /// Tokenize pairs of texts (e.g., query + document) for Cross-Encoders | |
| pub fn tokenize_pairs(&self, pairs: &[(String, String)]) -> TokenizedBatch { | |
| let batch_size = pairs.len(); | |
| let seq_len = self.max_seq_length; | |
| let total = batch_size * seq_len; | |
| let mut input_ids = vec![0i64; total]; | |
| let mut attention_mask = vec![0i64; total]; | |
| let mut token_type_ids = vec![0i64; total]; | |
| for (i, (text_a, text_b)) in pairs.iter().enumerate() { | |
| let tokens_a = self.tokenize_text_raw(text_a); | |
| let tokens_b = self.tokenize_text_raw(text_b); | |
| // BERT-style: [CLS] text_a [SEP] text_b [SEP] | |
| let mut combined = vec![101i64]; // [CLS] | |
| // Limit text_a and text_b to fit in seq_len | |
| let max_a = (seq_len - 3) / 2; | |
| let max_b = seq_len - 3 - tokens_a.len().min(max_a); | |
| for &t in tokens_a.iter().take(max_a) { | |
| combined.push(t); | |
| } | |
| combined.push(102i64); // [SEP] | |
| let sep_idx = combined.len(); | |
| for &t in tokens_b.iter().take(max_b) { | |
| combined.push(t); | |
| } | |
| combined.push(102i64); // [SEP] | |
| for (j, &token_id) in combined.iter().enumerate().take(seq_len) { | |
| let idx = i * seq_len + j; | |
| input_ids[idx] = token_id; | |
| attention_mask[idx] = 1; | |
| if j >= sep_idx { | |
| token_type_ids[idx] = 1; | |
| } | |
| } | |
| } | |
| TokenizedBatch { | |
| input_ids, | |
| attention_mask, | |
| token_type_ids, | |
| shape: vec![batch_size as i64, seq_len as i64], | |
| } | |
| } | |
| fn tokenize_text(&self, text: &str) -> Vec<i64> { | |
| let mut tokens = vec![101i64]; // [CLS] | |
| for word in text.split_whitespace().take(self.max_seq_length - 2) { | |
| tokens.push(self.hash_to_token_id(word)); | |
| } | |
| tokens.push(102i64); // [SEP] | |
| tokens | |
| } | |
| fn tokenize_text_raw(&self, text: &str) -> Vec<i64> { | |
| text.split_whitespace() | |
| .map(|word| self.hash_to_token_id(word)) | |
| .collect() | |
| } | |
| fn hash_to_token_id(&self, word: &str) -> i64 { | |
| use std::collections::hash_map::DefaultHasher; | |
| use std::hash::{Hash, Hasher}; | |
| let lower = word.to_lowercase(); | |
| if let Some(&id) = self.vocab.get(&lower) { | |
| return id; | |
| } | |
| let mut hasher = DefaultHasher::new(); | |
| lower.hash(&mut hasher); | |
| let hash = hasher.finish(); | |
| 1000 + (hash % 29522) as i64 | |
| } | |
| } | |
| /// Scoring rules and heuristics for content quality | |
| pub struct QualityScorer { | |
| min_length: usize, | |
| max_length: usize, | |
| stop_words: std::collections::HashSet<String>, | |
| high_signal_words: std::collections::HashSet<String>, | |
| } | |
| impl QualityScorer { | |
| pub fn new() -> Self { | |
| let mut high_signal = std::collections::HashSet::new(); | |
| for word in &[ | |
| "tutorial", | |
| "guide", | |
| "how-to", | |
| "comparison", | |
| "benchmark", | |
| "analysis", | |
| "framework", | |
| "library", | |
| "release", | |
| "announcement", | |
| "research", | |
| "paper", | |
| ] { | |
| high_signal.insert(word.to_string()); | |
| } | |
| let mut stop_words = std::collections::HashSet::new(); | |
| for word in &[ | |
| "a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", | |
| "by", "from", "is", "it", "that", "this", "was", "are", "be", "has", "had", "have", | |
| "do", "does", "did", "will", "would", "could", "should", "may", "might", "can", "not", | |
| "no", "so", "if", "as", "its", "into", "about", "up", "out", "then", "than", "them", | |
| "they", "their", "there", "here", "when", "where", "which", "who", "whom", "what", | |
| "how", "all", "each", "every", "both", "few", "more", "most", "other", "some", "such", | |
| "only", "own", "same", "just", "also", "very", "too", "now", "i", "me", "my", "we", | |
| "us", "our", "you", "your", "he", "him", "his", "she", "her", "it", "its", "been", | |
| "being", "were", "am", "s", "t", "re", "ve", "ll", "d", | |
| ] { | |
| stop_words.insert(word.to_string()); | |
| } | |
| Self { | |
| min_length: 100, | |
| max_length: 50000, | |
| stop_words, | |
| high_signal_words: high_signal, | |
| } | |
| } | |
| /// Calculate a rule-based score [0, 1] | |
| pub fn calculate_rule_score(&self, text: &str) -> f32 { | |
| let len = text.len(); | |
| if len < self.min_length { | |
| return 0.1; | |
| } | |
| let words: Vec<&str> = text.split_whitespace().collect(); | |
| if words.is_empty() { | |
| return 0.0; | |
| } | |
| // Length bonus/penalty (prefer medium-long content) | |
| let length_score = if len > 5000 { | |
| 0.8 // Very long, potentially redundant | |
| } else if len > 1000 { | |
| 1.0 // Ideal length | |
| } else { | |
| 0.5 // Short but okay | |
| }; | |
| // Signal word density | |
| let mut signal_count = 0; | |
| let mut content_words = Vec::new(); | |
| for word in &words { | |
| let lower = word.to_lowercase(); | |
| if self.high_signal_words.contains(&lower) { | |
| signal_count += 1; | |
| } | |
| if !self.stop_words.contains(&lower) { | |
| content_words.push(lower); | |
| } | |
| } | |
| let signal_score = (signal_count as f32 / 10.0).min(1.0); | |
| // Content word diversity (excluding stop words) | |
| let unique_ratio = if content_words.is_empty() { | |
| 0.0 | |
| } else { | |
| let unique: std::collections::HashSet<_> = content_words.iter().collect(); | |
| unique.len() as f32 / content_words.len() as f32 | |
| }; | |
| (length_score * 0.4 + signal_score * 0.4 + unique_ratio * 0.2).min(1.0) | |
| } | |
| /// Calculate quality score with domain boost | |
| pub fn calculate_boosted_score(&self, text: &str, url: &str) -> f32 { | |
| let base_score = self.calculate_rule_score(text); | |
| let mut boost = 1.0f32; | |
| let url_lower = url.to_lowercase(); | |
| if url_lower.contains("arxiv.org") | |
| || url_lower.contains("github.com") | |
| || url_lower.contains("docs.") | |
| || url_lower.contains(".edu") | |
| || url_lower.contains("rust-lang.org") | |
| { | |
| boost = 1.3; | |
| } else if url_lower.contains("techcrunch.com") | |
| || url_lower.contains("news.") | |
| || url_lower.contains("blog.") | |
| { | |
| boost = 0.9; | |
| } | |
| (base_score * boost).clamp(0.0, 1.0) | |
| } | |
| } | |
| /// Lightweight keyword-based intent scorer for pre-fetch filtering | |
| pub struct FastIntentScorer { | |
| weights: std::collections::HashMap<String, f32>, | |
| threshold: f32, | |
| } | |
| impl FastIntentScorer { | |
| pub fn new(threshold: f32) -> Self { | |
| let mut weights = std::collections::HashMap::new(); | |
| // High-signal intent keywords | |
| let high_signal = [ | |
| ("tutorial", 0.5), | |
| ("guide", 0.4), | |
| ("how-to", 0.5), | |
| ("benchmark", 0.4), | |
| ("analysis", 0.3), | |
| ("framework", 0.3), | |
| ("library", 0.3), | |
| ("release", 0.2), | |
| ("announcement", 0.2), | |
| ("research", 0.4), | |
| ("paper", 0.4), | |
| ("github", 0.3), | |
| ("arxiv", 0.4), | |
| ("medium", 0.1), | |
| ("dev.to", 0.2), | |
| ("documentation", 0.4), | |
| ("api", 0.3), | |
| ("rust", 0.2), | |
| ("python", 0.1), | |
| ("ai", 0.2), | |
| ("ml", 0.2), | |
| ("deeplearning", 0.3), | |
| ("opensource", 0.3), | |
| ]; | |
| for (word, weight) in high_signal { | |
| weights.insert(word.to_string(), weight); | |
| } | |
| Self { weights, threshold } | |
| } | |
| /// Calculate a fast intent score [0, 1] based on URL and Title tokens | |
| pub fn score(&self, text: &str) -> f32 { | |
| let normalized = text.to_lowercase(); | |
| let mut score = 0.1f32; // Baseline | |
| for (word, weight) in &self.weights { | |
| if normalized.contains(word) { | |
| score += weight; | |
| } | |
| } | |
| score.min(1.0) | |
| } | |
| /// Check if the text passes the intent threshold | |
| pub fn passes(&self, text: &str) -> bool { | |
| self.score(text) >= self.threshold | |
| } | |
| pub fn threshold(&self) -> f32 { | |
| self.threshold | |
| } | |
| } | |
| /// ONNX embedding model for batch inference | |
| pub struct EmbeddingModel { | |
| session: Option<Arc<Mutex<ort::session::Session>>>, | |
| rerank_session: Option<Arc<Mutex<ort::session::Session>>>, | |
| tokenizer: Tokenizer, | |
| scorer: QualityScorer, | |
| pub fast_scorer: FastIntentScorer, | |
| embedding_dim: usize, | |
| batch_size: usize, | |
| embedding_cache: Arc<Mutex<LruCache<String, Vec<f32>>>>, | |
| } | |
| impl EmbeddingModel { | |
| pub fn new( | |
| model_path: &str, | |
| embedding_dim: usize, | |
| max_seq_length: usize, | |
| batch_size: usize, | |
| fast_intent_threshold: f32, | |
| ) -> Result<Self> { | |
| let tokenizer = Tokenizer::new(max_seq_length); | |
| let scorer = QualityScorer::new(); | |
| let fast_scorer = FastIntentScorer::new(fast_intent_threshold); | |
| let session = if Path::new(model_path).exists() { | |
| tracing::info!("Loading ONNX embedding model from '{}'...", model_path); | |
| let session = ort::session::Session::builder() | |
| .with_context(|| "Failed to create ONNX session builder")? | |
| .commit_from_file(model_path) | |
| .with_context(|| format!("Failed to load ONNX model from {}", model_path))?; | |
| Some(Arc::new(Mutex::new(session))) | |
| } else { | |
| tracing::warn!( | |
| "ONNX embedding model not found at '{}', using fallback hash embeddings", | |
| model_path | |
| ); | |
| None | |
| }; | |
| // Try to load rerank model if it exists (usually cross-encoder/ms-marco-MiniLM-L6-v2) | |
| let rerank_path = model_path.replace("all-MiniLM-L6-v2", "rerank-MiniLM-L6-v2"); | |
| let rerank_session = if Path::new(&rerank_path).exists() { | |
| tracing::info!("Loading ONNX rerank model from '{}'...", rerank_path); | |
| let session = ort::session::Session::builder() | |
| .with_context(|| "Failed to create ONNX rerank session builder")? | |
| .commit_from_file(&rerank_path) | |
| .with_context(|| { | |
| format!("Failed to load ONNX rerank model from {}", rerank_path) | |
| })?; | |
| Some(Arc::new(Mutex::new(session))) | |
| } else { | |
| tracing::warn!( | |
| "ONNX rerank model not found at '{}', reranking will use fallback", | |
| rerank_path | |
| ); | |
| None | |
| }; | |
| Ok(Self { | |
| session, | |
| rerank_session, | |
| tokenizer, | |
| scorer, | |
| fast_scorer, | |
| embedding_dim, | |
| batch_size, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(1000).unwrap()))), | |
| }) | |
| } | |
| pub fn is_loaded(&self) -> bool { | |
| self.session.is_some() | |
| } | |
| pub fn is_rerank_loaded(&self) -> bool { | |
| self.rerank_session.is_some() | |
| } | |
| /// Calculate quality score for text with domain boost | |
| pub fn calculate_quality_score(&self, text: &str, url: &str) -> f32 { | |
| self.scorer.calculate_boosted_score(text, url) | |
| } | |
| /// Get embedding dimension | |
| pub fn embedding_dim(&self) -> usize { | |
| self.embedding_dim | |
| } | |
| /// Generate embeddings for a batch of texts with LRU caching | |
| pub fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> { | |
| if texts.is_empty() { | |
| return Ok(Vec::new()); | |
| } | |
| // Check cache for each text, separate into cached vs missing | |
| let mut results = Vec::with_capacity(texts.len()); | |
| let mut missing_indices = Vec::new(); | |
| { | |
| let mut cache = self | |
| .embedding_cache | |
| .lock() | |
| .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?; | |
| for (i, text) in texts.iter().enumerate() { | |
| if let Some(embedding) = cache.get(text) { | |
| results.push((i, embedding.clone())); | |
| } else { | |
| missing_indices.push(i); | |
| } | |
| } | |
| } | |
| // Compute embeddings for missing texts | |
| if !missing_indices.is_empty() { | |
| let missing_texts: Vec<String> = | |
| missing_indices.iter().map(|&i| texts[i].clone()).collect(); | |
| let computed = if self.session.is_some() { | |
| self.embed_with_model(&missing_texts)? | |
| } else { | |
| self.embed_fallback(&missing_texts) | |
| }; | |
| // Store in cache and results | |
| let mut cache = self | |
| .embedding_cache | |
| .lock() | |
| .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?; | |
| for (idx, embedding) in missing_indices.into_iter().zip(computed.into_iter()) { | |
| cache.put(texts[idx].clone(), embedding.clone()); | |
| results.push((idx, embedding)); | |
| } | |
| } | |
| // Sort by original index | |
| results.sort_by_key(|(i, _)| *i); | |
| Ok(results.into_iter().map(|(_, emb)| emb).collect()) | |
| } | |
| fn embed_with_model(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> { | |
| let session_lock = self.session.as_ref().unwrap(); | |
| let mut session = session_lock | |
| .lock() | |
| .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?; | |
| let mut all_embeddings = Vec::with_capacity(texts.len()); | |
| for chunk in texts.chunks(self.batch_size) { | |
| let batch = self.tokenizer.tokenize_batch(chunk); | |
| let input_ids_tensor = | |
| ort::value::Tensor::from_array((batch.shape.clone(), batch.input_ids)) | |
| .with_context(|| "Failed to create input_ids tensor")?; | |
| let attention_mask_tensor = | |
| ort::value::Tensor::from_array((batch.shape.clone(), batch.attention_mask.clone())) | |
| .with_context(|| "Failed to create attention_mask tensor")?; | |
| let token_type_ids_tensor = | |
| ort::value::Tensor::from_array((batch.shape, batch.token_type_ids)) | |
| .with_context(|| "Failed to create token_type_ids tensor")?; | |
| let outputs = session | |
| .run(ort::inputs![ | |
| "input_ids" => input_ids_tensor, | |
| "attention_mask" => attention_mask_tensor, | |
| "token_type_ids" => token_type_ids_tensor | |
| ]) | |
| .with_context(|| "ONNX inference failed")?; | |
| let output_value = &outputs["last_hidden_state"]; | |
| let (shape, data) = output_value.try_extract_tensor::<f32>()?; | |
| let batch_size_actual = chunk.len(); | |
| let seq_len = shape[1] as usize; | |
| let hidden_dim = shape[2] as usize; | |
| for i in 0..batch_size_actual { | |
| let mut embedding = vec![0.0f32; self.embedding_dim]; | |
| let mut count = 0usize; | |
| for j in 0..seq_len { | |
| let mask_idx = i * seq_len + j; | |
| if batch.attention_mask[mask_idx] == 1 { | |
| for (k, val) in embedding | |
| .iter_mut() | |
| .enumerate() | |
| .take(hidden_dim.min(self.embedding_dim)) | |
| { | |
| let idx = i * seq_len * hidden_dim + j * hidden_dim + k; | |
| *val += data[idx]; | |
| } | |
| count += 1; | |
| } | |
| } | |
| if count > 0 { | |
| for val in embedding.iter_mut() { | |
| *val /= count as f32; | |
| } | |
| } | |
| let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt(); | |
| if norm > 0.0 { | |
| for val in embedding.iter_mut() { | |
| *val /= norm; | |
| } | |
| } | |
| all_embeddings.push(embedding); | |
| } | |
| } | |
| Ok(all_embeddings) | |
| } | |
| /// Rerank query-document pairs using Cross-Encoder | |
| pub fn rerank(&self, query: &str, documents: &[String]) -> Result<Vec<f32>> { | |
| if documents.is_empty() { | |
| return Ok(Vec::new()); | |
| } | |
| if let Some(rerank_lock) = &self.rerank_session { | |
| let mut session = rerank_lock | |
| .lock() | |
| .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?; | |
| let mut all_scores = Vec::with_capacity(documents.len()); | |
| for chunk in documents.chunks(self.batch_size) { | |
| let pairs: Vec<(String, String)> = chunk | |
| .iter() | |
| .map(|doc| (query.to_string(), doc.clone())) | |
| .collect(); | |
| let batch = self.tokenizer.tokenize_pairs(&pairs); | |
| let input_ids_tensor = | |
| ort::value::Tensor::from_array((batch.shape.clone(), batch.input_ids)) | |
| .with_context(|| "Failed to create input_ids tensor")?; | |
| let attention_mask_tensor = | |
| ort::value::Tensor::from_array((batch.shape.clone(), batch.attention_mask)) | |
| .with_context(|| "Failed to create attention_mask tensor")?; | |
| let token_type_ids_tensor = | |
| ort::value::Tensor::from_array((batch.shape, batch.token_type_ids)) | |
| .with_context(|| "Failed to create token_type_ids tensor")?; | |
| let outputs = session | |
| .run(ort::inputs![ | |
| "input_ids" => input_ids_tensor, | |
| "attention_mask" => attention_mask_tensor, | |
| "token_type_ids" => token_type_ids_tensor | |
| ]) | |
| .with_context(|| "ONNX rerank inference failed")?; | |
| // Cross-encoders usually output a single score per pair | |
| // The output name might vary, but "logits" or "output_0" are common | |
| let output_value = outputs | |
| .get("logits") | |
| .or_else(|| outputs.get("output_0")) | |
| .context("Failed to find output tensor in rerank model")?; | |
| let (_, data) = output_value.try_extract_tensor::<f32>()?; | |
| for &score in data.iter() { | |
| // Sigmoid for probability if needed, or just raw logits | |
| let prob = 1.0 / (1.0 + (-score).exp()); | |
| all_scores.push(prob); | |
| } | |
| } | |
| Ok(all_scores) | |
| } else { | |
| // Fallback: use cosine similarity of embeddings | |
| let query_emb = self | |
| .embed_batch(&[query.to_string()])? | |
| .into_iter() | |
| .next() | |
| .unwrap(); | |
| let doc_embs = self.embed_batch(documents.to_vec().as_slice())?; | |
| let scores = doc_embs | |
| .iter() | |
| .map(|doc_emb| crate::utils::cosine_similarity(&query_emb, doc_emb).clamp(0.0, 1.0)) | |
| .collect(); | |
| Ok(scores) | |
| } | |
| } | |
| pub fn embed_fallback(&self, texts: &[String]) -> Vec<Vec<f32>> { | |
| texts.iter().map(|text| self.hash_embedding(text)).collect() | |
| } | |
| fn hash_embedding(&self, text: &str) -> Vec<f32> { | |
| use std::collections::hash_map::DefaultHasher; | |
| use std::hash::{Hash, Hasher}; | |
| let mut embedding = vec![0.0f32; self.embedding_dim]; | |
| for (i, word) in text.split_whitespace().enumerate() { | |
| let mut hasher = DefaultHasher::new(); | |
| word.to_lowercase().hash(&mut hasher); | |
| let hash = hasher.finish(); | |
| for (j, val) in embedding.iter_mut().enumerate().take(self.embedding_dim) { | |
| let seed = (i * self.embedding_dim + j) as u64; | |
| let mut h = DefaultHasher::new(); | |
| (hash ^ seed).hash(&mut h); | |
| let noise = (h.finish() as f64 / u64::MAX as f64) as f32; | |
| *val += noise; | |
| } | |
| } | |
| let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt(); | |
| if norm > 0.0 { | |
| for val in embedding.iter_mut() { | |
| *val /= norm; | |
| } | |
| } | |
| embedding | |
| } | |
| /// Score documents using hybrid rule-based and embedding diversity metrics | |
| pub fn score_batch(&self, texts: &[String]) -> Result<Vec<f32>> { | |
| if texts.is_empty() { | |
| return Ok(Vec::new()); | |
| } | |
| let embeddings = self.embed_batch(texts)?; | |
| let mut scores = Vec::with_capacity(texts.len()); | |
| for (i, text) in texts.iter().enumerate() { | |
| let emb = &embeddings[i]; | |
| // Embedding diversity score | |
| let mean = emb.iter().sum::<f32>() / emb.len() as f32; | |
| let diversity = emb.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / emb.len() as f32; | |
| let embedding_score = (diversity.sqrt() * 10.0).clamp(0.0, 1.0); | |
| // Rule-based score | |
| let rule_score = self.scorer.calculate_rule_score(text); | |
| // Weighted average | |
| let final_score = (embedding_score * 0.4 + rule_score * 0.6).clamp(0.0, 1.0); | |
| scores.push(final_score); | |
| } | |
| Ok(scores) | |
| } | |
| pub fn batch_size(&self) -> usize { | |
| self.batch_size | |
| } | |
| } | |
| mod tests { | |
| use super::*; | |
| fn test_tokenizer_basic() { | |
| let tokenizer = Tokenizer::new(128); | |
| let texts = vec!["hello world test".to_string()]; | |
| let batch = tokenizer.tokenize_batch(&texts); | |
| assert_eq!(batch.shape, vec![1, 128]); | |
| // CLS token | |
| assert_eq!(batch.input_ids[0], 101); | |
| // SEP token (3 words + CLS + SEP = 5 tokens) | |
| assert_eq!(batch.input_ids[4], 102); | |
| // Attention mask should be 1 for first 5 positions | |
| assert_eq!(batch.attention_mask[0], 1); | |
| assert_eq!(batch.attention_mask[4], 1); | |
| assert_eq!(batch.attention_mask[5], 0); | |
| } | |
| fn test_tokenizer_batch() { | |
| let tokenizer = Tokenizer::new(64); | |
| let texts = vec![ | |
| "first document".to_string(), | |
| "second document with more words".to_string(), | |
| ]; | |
| let batch = tokenizer.tokenize_batch(&texts); | |
| assert_eq!(batch.shape, vec![2, 64]); | |
| // Both should have CLS | |
| assert_eq!(batch.input_ids[0], 101); | |
| assert_eq!(batch.input_ids[64], 101); | |
| } | |
| fn test_fallback_embedding() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let texts = vec!["hello world".to_string()]; | |
| let embeddings = model.embed_fallback(&texts); | |
| assert_eq!(embeddings.len(), 1); | |
| assert_eq!(embeddings[0].len(), 384); | |
| let norm: f32 = embeddings[0].iter().map(|x| x * x).sum::<f32>().sqrt(); | |
| assert!((norm - 1.0).abs() < 1e-5); | |
| } | |
| fn test_fallback_embedding_deterministic() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let texts = vec!["test input".to_string()]; | |
| let emb1 = model.embed_fallback(&texts); | |
| let emb2 = model.embed_fallback(&texts); | |
| assert_eq!(emb1, emb2); | |
| } | |
| fn test_fallback_embedding_different_inputs() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let emb1 = model.embed_fallback(&["hello world".to_string()]); | |
| let emb2 = model.embed_fallback(&["goodbye universe".to_string()]); | |
| assert_ne!(emb1[0], emb2[0]); | |
| } | |
| fn test_fallback_batch_embedding() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let texts = vec![ | |
| "first document".to_string(), | |
| "second document".to_string(), | |
| "third document".to_string(), | |
| ]; | |
| let embeddings = model.embed_fallback(&texts); | |
| assert_eq!(embeddings.len(), 3); | |
| for emb in &embeddings { | |
| assert_eq!(emb.len(), 384); | |
| let norm: f32 = emb.iter().map(|x| x * x).sum::<f32>().sqrt(); | |
| assert!((norm - 1.0).abs() < 1e-5); | |
| } | |
| } | |
| fn test_embed_batch_fallback() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let model = model; | |
| let texts = vec!["hello world".to_string()]; | |
| let embeddings = model.embed_batch(&texts).unwrap(); | |
| assert_eq!(embeddings.len(), 1); | |
| assert_eq!(embeddings[0].len(), 384); | |
| } | |
| fn test_empty_batch() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let embeddings = model.embed_batch(&[]).unwrap(); | |
| assert!(embeddings.is_empty()); | |
| let scores = model.score_batch(&[]).unwrap(); | |
| assert!(scores.is_empty()); | |
| } | |
| fn test_score_batch() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let texts = vec![ | |
| "short".to_string(), | |
| "a much longer document with many more words and details".to_string(), | |
| ]; | |
| let scores = model.score_batch(&texts).unwrap(); | |
| assert_eq!(scores.len(), 2); | |
| for score in &scores { | |
| assert!(*score >= 0.0 && *score <= 1.0); | |
| } | |
| } | |
| fn test_hash_embedding_distribution() { | |
| let model = EmbeddingModel { | |
| session: None, | |
| rerank_session: None, | |
| tokenizer: Tokenizer::new(128), | |
| scorer: QualityScorer::new(), | |
| fast_scorer: FastIntentScorer::new(0.4), | |
| embedding_dim: 384, | |
| batch_size: 32, | |
| embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))), | |
| }; | |
| let embedding = model.hash_embedding("test embedding distribution"); | |
| let mean = embedding.iter().sum::<f32>() / embedding.len() as f32; | |
| let variance = | |
| embedding.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / embedding.len() as f32; | |
| assert!(variance > 0.0, "Embedding should have non-zero variance"); | |
| } | |
| fn test_model_not_loaded_without_file() { | |
| let model = EmbeddingModel::new("nonexistent_model.onnx", 384, 128, 32, 0.4).unwrap(); | |
| assert!(!model.is_loaded()); | |
| } | |
| } | |