use std::path::Path; use std::time::Instant; use anyhow::{anyhow, Result}; use ndarray::{Array2, Array4}; use ort::session::builder::GraphOptimizationLevel; use ort::session::Session; use ort::value::Tensor; use serde::{Deserialize, Serialize}; use tokenizers::Tokenizer; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EngineKind { DistilBert, IndicBert, ModernBert, } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct QueryItem { pub text: String, pub max_classes: usize, // Explicitly declared cardinality, zero regex guessing } #[derive(Debug, Clone, Deserialize)] pub struct DecisionRequest { pub state_prefix: String, pub queries: Vec, #[serde(default = "default_temperature")] pub temperature: f32, } fn default_temperature() -> f32 { 1.0 } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DecisionOutput { pub slot: usize, pub query: String, pub predicted_class: usize, pub confidence: f32, pub probabilities: Vec, pub raw_logits: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TelemetryBreakdown { pub engine: String, pub tokenize_ms: f32, pub mask_build_ms: f32, pub inference_ms: f32, pub postprocess_ms: f32, pub total_pipeline_ms: f32, pub context_tokens: usize, pub total_sequence_tokens: usize, } pub struct UnifiedFalcoEngine { session: Session, tokenizer: Tokenizer, cls_id: u32, sep_id: u32, has_position_ids: bool, max_sequence_length: usize, pub kind: EngineKind, pub name: &'static str, } impl UnifiedFalcoEngine { pub fn new>( model_path: P, tokenizer_path: P, kind: EngineKind, intra_threads: usize, ) -> Result { let tokenizer = Tokenizer::from_file(&tokenizer_path) .map_err(|e| anyhow!("Failed to load tokenizer from {:?}: {e}", tokenizer_path.as_ref()))?; let (cls_id, sep_id, max_tokens, name) = match kind { EngineKind::DistilBert => ( tokenizer.token_to_id("[CLS]").unwrap_or(101), tokenizer.token_to_id("[SEP]").unwrap_or(102), 512, "Falco Express (DistilBERT English)", ), EngineKind::IndicBert => ( tokenizer.token_to_id("[CLS]").unwrap_or(1), tokenizer.token_to_id("[SEP]").unwrap_or(2), 512, "Falco Vernacular (IndicBERT-v2 22 Scripts)", ), EngineKind::ModernBert => ( tokenizer.token_to_id("[CLS]").unwrap_or(50281), tokenizer.token_to_id("[SEP]").unwrap_or(50282), 4096, "Falco Document (ModernBERT-base INT8 RoPE)", ), }; // Initialize ONNX Runtime session with optimized multi-threaded CPU execution let session = Session::builder() .map_err(|e| anyhow!("{e}"))? .with_optimization_level(GraphOptimizationLevel::Level3) .map_err(|e| anyhow!("{e}"))? .with_intra_threads(intra_threads) .map_err(|e| anyhow!("{e}"))? .with_execution_providers([ ort::ep::CPU::default().build(), ]) .map_err(|e| anyhow!("{e}"))? .commit_from_file(&model_path)?; let has_position_ids = session.inputs().iter().any(|inp| inp.name() == "position_ids"); Ok(Self { session, tokenizer, cls_id, sep_id, has_position_ids, max_sequence_length: max_tokens, kind, name, }) } pub fn evaluate( &mut self, state: &str, queries: &[QueryItem], temperature: f32, ) -> Result<(Vec, TelemetryBreakdown)> { let t_start = Instant::now(); if queries.is_empty() { return Err(anyhow!("Verification Failure: Query collection cannot be empty.")); } if state.trim().is_empty() { return Err(anyhow!("Verification Failure: State prefix cannot be empty string payload.")); } // --- SECTOR 2: HIGH-EFFICIENCY PACKING CONTRACT --- let t0 = Instant::now(); let state_encoding = self.tokenizer.encode(state, false) .map_err(|e| anyhow!("State tokenization failure: {e}"))?; let state_ids = state_encoding.get_ids(); let state_len = state_ids.len() + 1; let mut packed_ids = Vec::with_capacity(self.max_sequence_length.min(1024)); packed_ids.push(self.cls_id); packed_ids.extend_from_slice(state_ids); let mut ranges = Vec::with_capacity(queries.len()); let mut query_offsets = Vec::with_capacity(queries.len()); let mut curr = packed_ids.len(); for q in queries { if q.text.trim().is_empty() { return Err(anyhow!("Contract Failure: Embedded empty queries are structurally illegal.")); } let enc = self.tokenizer.encode(q.text.as_str(), false) .map_err(|e| anyhow!("Query tokenization failure: {e}"))?; let q_ids = enc.get_ids(); let start = curr; packed_ids.extend_from_slice(q_ids); packed_ids.push(self.sep_id); let end = packed_ids.len(); if end > self.max_sequence_length { return Err(anyhow!( "Sequence Overflow: Target total token allocation breaches {} boundaries.", self.max_sequence_length )); } ranges.push((start, end)); query_offsets.push((end - 1) as i64); curr = end; } let tokenize_ms = t0.elapsed().as_secs_f32() * 1000.0; // --- SECTOR 3: COORDINATE BLOCK-SPARSE ATTENTION MAP --- let t1 = Instant::now(); let total_len = packed_ids.len(); let mut mask = Array2::::zeros((total_len, total_len)); for i in 0..state_len { for j in 0..state_len { mask[[i, j]] = 1.0; } } for &(s, e) in &ranges { for i in s..e { for j in 0..state_len { mask[[i, j]] = 1.0; } for j in s..e { mask[[i, j]] = 1.0; } } } let additive_mask = (1.0 - mask) * -10000.0; let mask_4d: Array4 = additive_mask.insert_axis(ndarray::Axis(0)).insert_axis(ndarray::Axis(0)); // Fixed type mapping explicitly to i64 for input_ids let input_ids_tensor = Tensor::from_array(Array2::from_shape_vec( (1, total_len), packed_ids.into_iter().map(|id| id as i64).collect(), )?)?; let attention_mask_tensor = Tensor::from_array(mask_4d)?; // Fix: Wrap query_offsets into a 2D Array2 shape (1, num_queries) to match rank 2 let num_queries = query_offsets.len(); let query_indices_tensor = Tensor::from_array(Array2::from_shape_vec( (1, num_queries), query_offsets, )?)?; let position_ids_tensor = if self.has_position_ids { let mut pos_ids: Vec = Vec::with_capacity(total_len); for i in 0..state_len { pos_ids.push(i as i64); } for &(s, e) in &ranges { for i in s..e { pos_ids.push((state_len + (i - s)) as i64); } } Some(Tensor::from_array(Array2::from_shape_vec((1, total_len), pos_ids)?)?) } else { None }; let mask_build_ms = t1.elapsed().as_secs_f32() * 1000.0; // --- SECTOR 4: EXECUTION GRAPH INVOCATION --- let t2 = Instant::now(); let outputs = match &position_ids_tensor { Some(pos) => self.session.run(ort::inputs![ "input_ids" => &input_ids_tensor, "attention_mask" => &attention_mask_tensor, "position_ids" => pos, "query_indices" => &query_indices_tensor, ]), None => self.session.run(ort::inputs![ "input_ids" => &input_ids_tensor, "attention_mask" => &attention_mask_tensor, "query_indices" => &query_indices_tensor, ]), }.map_err(|e| anyhow!("Inference Execution Crash: {e}"))?; let inference_ms = t2.elapsed().as_secs_f32() * 1000.0; // --- SECTOR 5: STABLE TEMPERATURE LAYER DECODING --- let t3 = Instant::now(); let (_output_shape, data_slice) = outputs[0] .try_extract_tensor::() .map_err(|e| anyhow!("Tensor Alignment Extract Failure: {e}"))?; let data: Vec = data_slice.to_vec(); let num_queries = queries.len(); let total_elements = data.len(); if total_elements == 0 || total_elements % num_queries != 0 { return Err(anyhow!("ABI Violation: Model shape mismatch. Received {} values for {} queries.", total_elements, num_queries)); } let max_classes = total_elements / num_queries; let temp = if temperature <= 0.0 || !temperature.is_finite() { 1.0 } else { temperature }; let mut decisions = Vec::with_capacity(num_queries); for (idx, q) in queries.iter().enumerate() { let row_start = idx * max_classes; let raw_row = &data[row_start..row_start + max_classes]; let k = q.max_classes.min(max_classes); let valid_logits = &raw_row[0..k]; if valid_logits.is_empty() { return Err(anyhow!("Execution Error: Extracted zero valid logits for query index {}", idx)); } let max_val = valid_logits.iter().copied().fold(f32::NEG_INFINITY, f32::max); if !max_val.is_finite() { return Err(anyhow!("Numerical Fault: Non-finite maximum logit detected.")); } let exps: Vec = valid_logits.iter().map(|&x| ((x - max_val) / temp).exp()).collect(); let sum_exps: f32 = exps.iter().sum(); let probs: Vec = if sum_exps > 0.0 && sum_exps.is_finite() { exps.iter().map(|&x| x / sum_exps).collect() } else { vec![1.0 / (k as f32); k] }; let (top_id, &top_prob) = probs.iter().enumerate() .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal)) .unwrap_or((0, &0.0)); decisions.push(DecisionOutput { slot: idx + 1, query: q.text.clone(), predicted_class: top_id, confidence: top_prob, probabilities: probs, raw_logits: valid_logits.to_vec(), }); } let postprocess_ms = t3.elapsed().as_secs_f32() * 1000.0; Ok((decisions, TelemetryBreakdown { engine: self.name.to_string(), tokenize_ms, mask_build_ms, inference_ms, postprocess_ms, total_pipeline_ms: t_start.elapsed().as_secs_f32() * 1000.0, context_tokens: state_len, total_sequence_tokens: total_len, })) } }