Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

17.8 KB
Raw Blame
//! Experimental FP32 ONNX Runtime MiniLM backend.
//!
//! This backend is available end-to-end only in builds with the
//! `onnx-experimental` feature and must be explicitly selected with local
//! model/tokenizer paths. It is deliberately not a generic ONNX interface: the
//! graph must be an FP32 all-MiniLM-L6-v2-compatible encoder with int64 inputs
//! named `input_ids`, `attention_mask`, and `token_type_ids`, and a rank-3,
//! width-384 output named `last_hidden_state` or `token_embeddings`. The
//! tokenizer.json must come from the same model/export. XERJ attention-mask
//! mean-pools and L2-normalizes the token output.
//!
//! The safe `ort` API requires mutable session access, so one
//! session is serialized behind a mutex and aggregate throughput comes from
//! bounded, length-aware microbatches rather than unsafe concurrent `Run`.

use anyhow::{anyhow, Context, Result};
use ort::session::{builder::GraphOptimizationLevel, Session};
use ort::value::Tensor;
use std::path::Path;
use std::sync::{Arc, Condvar, Mutex};
use tokenizers::{PaddingParams, PaddingStrategy, Tokenizer, TruncationParams};

pub const MAX_TOKENS: usize = 512;
pub const DIMS: usize = 384;

/// Bounds for one offline scheduling window.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct MicrobatchConfig {
    /// Maximum inputs accepted in one call. Larger calls receive a clear
    /// backpressure error instead of allocating an unbounded queue.
    pub max_pending: usize,
    /// Maximum documents sent to one inference call.
    pub max_batch: usize,
    /// Maximum `batch_size × longest_sequence` token slots.
    pub padded_token_budget: usize,
}

impl Default for MicrobatchConfig {
    fn default() -> Self {
        Self {
            max_pending: 4_096,
            max_batch: 64,
            padded_token_budget: 4_096,
        }
    }
}

impl MicrobatchConfig {
    fn validate(self) -> Result<Self> {
        if self.max_pending == 0 || self.max_batch == 0 || self.padded_token_budget == 0 {
            return Err(anyhow!(
                "ONNX microbatch limits must be non-zero (max_pending={}, max_batch={}, padded_token_budget={})",
                self.max_pending,
                self.max_batch,
                self.padded_token_budget
            ));
        }
        Ok(self)
    }
}

pub struct OnnxEmbedder {
    session: Mutex<Session>,
    tokenizer: Tokenizer,
}

/// A fixed-width pool of independent ONNX Runtime sessions.
///
/// Construction is atomic: callers either receive the requested number of
/// sessions or an error, never a partially initialized pool.
pub(crate) struct OnnxPool {
    size: usize,
    sessions: Mutex<Vec<Arc<OnnxEmbedder>>>,
    available: Condvar,
}

struct SessionLease<'a> {
    pool: &'a OnnxPool,
    session: Option<Arc<OnnxEmbedder>>,
}

impl OnnxPool {
    pub(crate) fn load_bytes(
        model_bytes: &[u8],
        tokenizer_bytes: &[u8],
        intra_threads: usize,
        pool_size: usize,
    ) -> Result<Self> {
        if pool_size == 0 {
            return Err(anyhow!("ONNX session pool size must be non-zero"));
        }
        let sessions = build_exact_pool(pool_size, |ordinal| {
            OnnxEmbedder::load_bytes(model_bytes, tokenizer_bytes, intra_threads).with_context(
                || {
                    format!(
                        "construct ONNX session {} of {}; no partial pool was published",
                        ordinal + 1,
                        pool_size
                    )
                },
            )
        })?
        .into_iter()
        .map(Arc::new)
        .collect();
        Ok(Self {
            size: pool_size,
            sessions: Mutex::new(sessions),
            available: Condvar::new(),
        })
    }

    pub(crate) fn len(&self) -> usize {
        self.size
    }

    fn lease(&self) -> Result<SessionLease<'_>> {
        let mut sessions = self
            .sessions
            .lock()
            .map_err(|_| anyhow!("ONNX session pool mutex poisoned"))?;
        while sessions.is_empty() {
            sessions = self
                .available
                .wait(sessions)
                .map_err(|_| anyhow!("ONNX session pool mutex poisoned"))?;
        }
        let session = sessions.pop().expect("non-empty pool checked");
        Ok(SessionLease {
            pool: self,
            session: Some(session),
        })
    }

    pub(crate) fn embed_scheduled_blocking(
        &self,
        texts: &[String],
        config: MicrobatchConfig,
    ) -> Result<Vec<Vec<f32>>> {
        let lease = self.lease()?;
        lease
            .session
            .as_ref()
            .expect("leased session present")
            .embed_scheduled_blocking(texts, config)
    }
}

fn build_exact_pool<T>(
    pool_size: usize,
    mut construct: impl FnMut(usize) -> Result<T>,
) -> Result<Vec<T>> {
    let mut values = Vec::with_capacity(pool_size);
    for ordinal in 0..pool_size {
        values.push(construct(ordinal)?);
    }
    Ok(values)
}

impl Drop for SessionLease<'_> {
    fn drop(&mut self) {
        if let Some(session) = self.session.take() {
            let mut sessions = self
                .pool
                .sessions
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            sessions.push(session);
            self.pool.available.notify_one();
        }
    }
}

impl OnnxEmbedder {
    pub fn load(model_path: &Path, tokenizer_path: &Path, intra_threads: usize) -> Result<Self> {
        let model = std::fs::read(model_path)
            .with_context(|| format!("read ONNX model {}", model_path.display()))?;
        let tokenizer = std::fs::read(tokenizer_path)
            .with_context(|| format!("read tokenizer {}", tokenizer_path.display()))?;
        Self::load_bytes(&model, &tokenizer, intra_threads)
    }

    pub(crate) fn load_bytes(
        model_bytes: &[u8],
        tokenizer_bytes: &[u8],
        intra_threads: usize,
    ) -> Result<Self> {
        let mut tokenizer = Tokenizer::from_bytes(tokenizer_bytes)
            .map_err(|e| anyhow!("load tokenizer.json bytes: {e}"))?;
        tokenizer.with_padding(Some(PaddingParams {
            strategy: PaddingStrategy::BatchLongest,
            ..Default::default()
        }));
        tokenizer
            .with_truncation(Some(TruncationParams {
                max_length: MAX_TOKENS,
                ..Default::default()
            }))
            .map_err(|e| anyhow!("configure tokenizer truncation: {e}"))?;

        let ort_log_level = match std::env::var("XERJ_ONNX_LOG")
            .unwrap_or_default()
            .to_ascii_lowercase()
            .as_str()
        {
            "verbose" | "trace" => ort::logging::LogLevel::Verbose,
            "info" | "debug" => ort::logging::LogLevel::Info,
            "error" => ort::logging::LogLevel::Error,
            "fatal" => ort::logging::LogLevel::Fatal,
            _ => ort::logging::LogLevel::Warning,
        };
        let session = Session::builder()
            .map_err(|e| anyhow!("create ONNX Runtime session builder: {e}"))?
            .with_log_level(ort_log_level)
            .map_err(|e| anyhow!("configure ONNX Runtime log level: {e}"))?
            .with_optimization_level(GraphOptimizationLevel::Level3)
            .map_err(|e| anyhow!("configure ONNX graph optimizations: {e}"))?
            .with_config_entry("session.intra_op.allow_spinning", "0")
            .map_err(|e| anyhow!("disable ONNX intra-op spinning: {e}"))?
            .with_intra_threads(intra_threads.max(1))
            .map_err(|e| anyhow!("configure ONNX intra-op threads: {e}"))?
            .commit_from_memory(model_bytes)
            .context("load ONNX model bytes")?;
        Ok(Self {
            session: Mutex::new(session),
            tokenizer,
        })
    }

    /// Embed a bounded scheduling window, grouping similar lengths and
    /// restoring vectors to exact input order.
    pub fn embed_scheduled_blocking(
        &self,
        texts: &[String],
        config: MicrobatchConfig,
    ) -> Result<Vec<Vec<f32>>> {
        let config = config.validate()?;
        if texts.len() > config.max_pending {
            return Err(anyhow!(
                "ONNX embedding queue is full: received {} texts, max_pending={}; split the request or retry after draining",
                texts.len(),
                config.max_pending
            ));
        }
        let lengths = texts
            .iter()
            .map(|text| self.token_len(text))
            .collect::<Result<Vec<_>>>()?;
        let batches = plan_microbatches(&lengths, config)?;
        let mut ordered = vec![Vec::new(); texts.len()];
        for batch in batches {
            let input = batch.iter().map(|&i| texts[i].clone()).collect::<Vec<_>>();
            let vectors = self.embed_blocking(&input)?;
            for (position, vector) in batch.into_iter().zip(vectors) {
                ordered[position] = vector;
            }
        }
        Ok(ordered)
    }

    pub fn token_len(&self, text: &str) -> Result<usize> {
        self.tokenizer
            .encode(text, true)
            .map(|encoding| encoding.len())
            .map_err(|e| anyhow!("tokenize for ONNX scheduling: {e}"))
    }

    pub fn embed_blocking(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        if texts.is_empty() {
            return Ok(vec![]);
        }
        let encodings = self
            .tokenizer
            .encode_batch(texts.to_vec(), true)
            .map_err(|e| anyhow!("tokenize batch: {e}"))?;
        let batch = encodings.len();
        let seq_len = encodings.first().map(|e| e.get_ids().len()).unwrap_or(0);
        if seq_len == 0 {
            return Ok(vec![vec![0.0; DIMS]; batch]);
        }

        let mut ids = Vec::with_capacity(batch * seq_len);
        let mut mask = Vec::with_capacity(batch * seq_len);
        for encoding in &encodings {
            ids.extend(encoding.get_ids().iter().map(|&v| i64::from(v)));
            mask.extend(encoding.get_attention_mask().iter().map(|&v| i64::from(v)));
        }
        let token_types = vec![0_i64; ids.len()];
        let shape = [batch, seq_len];
        let input_ids = Tensor::from_array((shape, ids)).context("build input_ids")?;
        let attention_mask =
            Tensor::from_array((shape, mask.clone())).context("build attention_mask")?;
        let token_type_ids =
            Tensor::from_array((shape, token_types)).context("build token_type_ids")?;

        let mut session = self
            .session
            .lock()
            .map_err(|_| anyhow!("ONNX session mutex poisoned"))?;
        let outputs = session
            .run(ort::inputs! {
                "input_ids" => input_ids,
                "attention_mask" => attention_mask,
                "token_type_ids" => token_type_ids,
            })
            .context("ONNX MiniLM inference")?;
        let output = outputs
            .get("last_hidden_state")
            .or_else(|| outputs.get("token_embeddings"))
            .ok_or_else(|| anyhow!("ONNX model did not return token embeddings"))?;
        let (output_shape, hidden) = output
            .try_extract_tensor::<f32>()
            .context("extract ONNX token embeddings")?;
        let shape_dims = output_shape.iter().copied().collect::<Vec<_>>();
        if shape_dims != [batch as i64, seq_len as i64, DIMS as i64] {
            return Err(anyhow!(
                "unexpected ONNX output shape {shape_dims:?}, expected [{batch}, {seq_len}, {DIMS}]"
            ));
        }

        let mut vectors = Vec::with_capacity(batch);
        for row in 0..batch {
            let mut pooled = vec![0.0_f32; DIMS];
            let mut count = 0.0_f32;
            for token in 0..seq_len {
                let weight = mask[row * seq_len + token] as f32;
                count += weight;
                let base = (row * seq_len + token) * DIMS;
                for dim in 0..DIMS {
                    pooled[dim] += hidden[base + dim] * weight;
                }
            }
            for value in &mut pooled {
                *value /= count.max(1e-9);
            }
            let norm = pooled
                .iter()
                .map(|value| value * value)
                .sum::<f32>()
                .sqrt()
                .max(1e-12);
            for value in &mut pooled {
                *value /= norm;
            }
            vectors.push(pooled);
        }
        Ok(vectors)
    }
}

/// Plan length-aware microbatches. Indices are sorted for inference efficiency;
/// callers must use them to restore original order.
///
/// The grouping itself is [`crate::microbatch::group_by_padded_cost`], shared
/// with the Candle backend. What stays here is the ONNX-specific contract:
/// backpressure past `max_pending`, and refusing a single input the budget
/// cannot fit rather than silently running it alone.
pub fn plan_microbatches(
    token_lengths: &[usize],
    config: MicrobatchConfig,
) -> Result<Vec<Vec<usize>>> {
    let config = config.validate()?;
    if token_lengths.len() > config.max_pending {
        return Err(anyhow!(
            "ONNX embedding queue is full: received {} texts, max_pending={}",
            token_lengths.len(),
            config.max_pending
        ));
    }
    let clamped = token_lengths
        .iter()
        .map(|length| (*length).min(MAX_TOKENS))
        .collect::<Vec<_>>();
    if let Some(length) = clamped
        .iter()
        .copied()
        .filter(|length| *length > config.padded_token_budget)
        .min()
    {
        return Err(anyhow!(
            "padded_token_budget={} cannot fit one {}-token input",
            config.padded_token_budget,
            length
        ));
    }
    Ok(crate::microbatch::group_by_padded_cost(
        &clamped,
        config.max_batch,
        config.padded_token_budget,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pool_initialization_discards_partial_members_on_failure() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        #[derive(Debug)]
        struct Member<'a>(&'a AtomicUsize);
        impl Drop for Member<'_> {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        let dropped = AtomicUsize::new(0);
        let error = build_exact_pool(3, |ordinal| {
            if ordinal == 1 {
                Err(anyhow!("synthetic second-session failure"))
            } else {
                Ok(Member(&dropped))
            }
        })
        .expect_err("a member failure must reject the whole pool")
        .to_string();
        assert!(error.contains("second-session failure"), "{error}");
        assert_eq!(dropped.load(Ordering::Relaxed), 1);
    }

    /// Run with explicit matching assets:
    ///
    /// `XERJ_ONNX_TEST_MODEL=/abs/model.onnx
    ///  XERJ_ONNX_TEST_TOKENIZER=/abs/tokenizer.json
    ///  cargo test -p xerj-ai --features onnx-experimental
    ///  independent_pool_sessions_are_bit_identical -- --ignored`
    #[test]
    #[ignore = "requires explicit matching ONNX model and tokenizer assets"]
    fn independent_pool_sessions_are_bit_identical() {
        let model = std::fs::read(
            std::env::var_os("XERJ_ONNX_TEST_MODEL").expect("XERJ_ONNX_TEST_MODEL is required"),
        )
        .unwrap();
        let tokenizer = std::fs::read(
            std::env::var_os("XERJ_ONNX_TEST_TOKENIZER")
                .expect("XERJ_ONNX_TEST_TOKENIZER is required"),
        )
        .unwrap();
        let texts = vec![
            "quarterly revenue increased year over year".to_string(),
            "operating margin declined in the fourth quarter".to_string(),
        ];
        let config = MicrobatchConfig::default();
        let expected = OnnxEmbedder::load_bytes(&model, &tokenizer, 2)
            .unwrap()
            .embed_scheduled_blocking(&texts, config)
            .unwrap();
        let expected_bits = expected
            .iter()
            .flatten()
            .map(|value| value.to_bits())
            .collect::<Vec<_>>();
        let pool = OnnxPool::load_bytes(&model, &tokenizer, 2, 2).unwrap();
        let sessions = pool.sessions.lock().unwrap();
        assert_eq!(sessions.len(), 2);
        for session in sessions.iter() {
            let actual = session.embed_scheduled_blocking(&texts, config).unwrap();
            assert_eq!(
                actual
                    .iter()
                    .flatten()
                    .map(|value| value.to_bits())
                    .collect::<Vec<_>>(),
                expected_bits
            );
        }
    }

    #[test]
    fn planner_bounds_every_batch_and_preserves_all_positions() {
        let lengths = [512, 14, 200, 16, 400, 15, 90, 300];
        let config = MicrobatchConfig {
            max_pending: 8,
            max_batch: 3,
            padded_token_budget: 600,
        };
        let batches = plan_microbatches(&lengths, config).unwrap();
        let mut positions = batches.iter().flatten().copied().collect::<Vec<_>>();
        positions.sort_unstable();
        assert_eq!(positions, (0..lengths.len()).collect::<Vec<_>>());
        for batch in batches {
            assert!(batch.len() <= config.max_batch);
            let longest = batch.iter().map(|&i| lengths[i]).max().unwrap();
            assert!(longest * batch.len() <= config.padded_token_budget);
        }
    }

    #[test]
    fn planner_applies_backpressure() {
        let error = plan_microbatches(
            &[10, 20, 30],
            MicrobatchConfig {
                max_pending: 2,
                ..MicrobatchConfig::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("queue is full"));
        assert!(error.contains("max_pending=2"));
    }

    #[test]
    fn planner_rejects_impossible_budget() {
        let error = plan_microbatches(
            &[512],
            MicrobatchConfig {
                padded_token_budget: 128,
                ..MicrobatchConfig::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("cannot fit"));
    }
}