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.

perf(ai): length-aware batching for the neural embedder (#366) (#897)

xerj-org70713d04f1a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 19ca6d7cd..cb64a2463 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Performance
+
+- **`--embed-mode neural`: a long passage no longer pads a whole batch up to
+ its own length** ([#366](https://github.com/xerj-org/xerj/issues/366)). The
+ built-in Candle encoder tokenized every call with `PaddingStrategy::
+ BatchLongest` and ran one rectangular forward pass over it, so a window that
+ held one 512-character chunk beside sixty short lines cost `61 × long`
+ instead of `long + 60 × short` — the model did the work, the attention
+ tensors were allocated, and the padding contributed nothing. The encoder now
+ sorts a call's passages by token length and cuts batches at 64 rows or a 4096
+ `rows × padded_sequence_length` budget (`xerj-ai/src/microbatch.rs`, shared
+ with the experimental ONNX backend), pads each batch to its own longest row,
+ and restores input order. This affects the opt-in neural backend only; the
+ default embedder is unchanged lexical feature-hashing.
+
+ Measured on this repo's 32-core x86_64 box with MiniLM-L6 (median of three
+ interleaved runs each, box shared with other builds — the spread is wide, so
+ the medians are quoted, not the best runs):
+
+ | shape | before | after |
+ |---|---|---|
+ | one 210 KB source file (504 chunks, one call) | 46.2–57.8 s, 8.97 GB peak RSS | 19.9 s, 0.42 GB peak RSS |
+ | 45 files of `apache/lucene`, chunked as ingest chunks them (1214 passages) | 8.9 passages/s | 12.1 passages/s |
+ | synthetic window of 4 long chunks + 60 short lines | 40.2 passages/s | 145.7 passages/s |
+ | uniform short documents, window of 64 | 171.0 passages/s | 175.6 passages/s |
+ | one passage per call | 68.9 passages/s | 72.8 passages/s |
+
+ Padding waste (`rows × padded_sequence_length` ÷ real tokens) on the Lucene
+ corpus fell from 1.50 to 1.13, and on the synthetic mixed window from 2.66 to
+ 1.00.
+
+ The first row is the other half of #366 — "each of those two files held the
+ run for 30+ seconds" on 200 KB C++ headers. `semantic_embedding_window_end`
+ always admits a whole document even past the scheduling window, so every
+ chunk of a large field reached the model as one forward pass whose attention
+ tensors scaled with the document: 8.97 GB of resident memory for a single
+ 210 KB file, which is an OOM on a laptop rather than a slowdown. The row cap
+ bounds it.
+
+ **What this does not fix, stated plainly:** #366 reported ~15 documents/s on
+ short uniform strings and read it as per-document inference. That reading
+ does not hold — HTTP `_bulk` already batches (`bulk.rs` collects the whole
+ request, `index.rs` windows 64 passages across documents), and the last two
+ rows above show that shape is unchanged by this work. On uniform short
+ documents ~15 docs/s is the cost of CPU transformer inference, and moving it
+ needs quantization, a GPU provider or a smaller model. What was genuinely
+ broken was mixed-length work, which is what pointing `autoindex` at a real
+ folder produces. Binary-protocol `_bulk` still embeds one document per
+ inference call (`xerj-api/src/binary_protocol.rs`); the HTTP path this
+ release measures does not.
+
### Fixed
- **The exclusion sweep can no longer delete a sibling corpus's catalog
diff --git a/docs/EXPERIMENTAL_ONNX.md b/docs/EXPERIMENTAL_ONNX.md
index 4b8cdf9ee..81eb64109 100644
--- a/docs/EXPERIMENTAL_ONNX.md
+++ b/docs/EXPERIMENTAL_ONNX.md
@@ -202,6 +202,13 @@ These controls do not select a smaller or quantized model. Model choice remains
the operator's responsibility through the explicit ONNX assets (or another
embedding backend).
+The built-in Candle backend (`--embed-mode neural`) shares the same
+length-aware batching rule, but its limits are compiled-in constants — 64 rows
+and a 4096 `rows × padded_sequence_length` budget — not settings.
+`onnx_max_batch` and `onnx_padded_token_budget` apply to the ONNX backend only,
+so there is no operator lever for the neural backend's batch size.
+`onnx_scheduling_window` does bound the caller-side window for either encoder.
+
## Admission and errors
One bounded ONNX Runtime session pool is shared per complete model
diff --git a/engine/crates/xerj-ai/Cargo.toml b/engine/crates/xerj-ai/Cargo.toml
index e46c00452..541d0ae08 100644
--- a/engine/crates/xerj-ai/Cargo.toml
+++ b/engine/crates/xerj-ai/Cargo.toml
@@ -49,3 +49,9 @@ tokio = { version = "1", features = ["full"] }
[[example]]
name = "onnx_experimental"
required-features = ["onnx-experimental"]
+
+# Throughput harness for the Candle neural embedder (issue #366). Downloads
+# MiniLM on first run; not built unless `neural` is on.
+[[example]]
+name = "neural_throughput"
+required-features = ["neural"]
diff --git a/engine/crates/xerj-ai/examples/neural_throughput.rs b/engine/crates/xerj-ai/examples/neural_throughput.rs
new file mode 100644
index 000000000..aa3d6189d
--- /dev/null
+++ b/engine/crates/xerj-ai/examples/neural_throughput.rs
@@ -0,0 +1,245 @@
+//! Throughput harness for the built-in Candle neural embedder (issue #366).
+//!
+//! Measures passages/second through [`xerj_ai::neural::NeuralEmbedder`] under
+//! the shapes the ingest path actually produces, so the cost of
+//! `--embed-mode neural` can be quoted from a run rather than guessed:
+//!
+//! * `single` — one passage per `embed_blocking` call. This is what the
+//! per-document ingest paths do (single-doc `PUT`, binary-protocol bulk).
+//! * `uniform` — one window of equal-length short passages, the shape the
+//! HTTP `_bulk` path produces for the short documents in #366.
+//! * `mixed` — one window mixing a few long chunks with many short ones,
+//! the shape `autoindex` produces over a real folder. Padding every row to
+//! the longest member of the window is what this arm exposes.
+//! * `one big document` — every chunk of one large field in a SINGLE call.
+//! `semantic_embedding_window_end` always admits a whole document even past
+//! the scheduling window, so this really does happen; without a row cap the
+//! forward pass and its attention tensors scale with the document.
+//!
+//! `padded/real` is the padding waste: `rows × padded_sequence_length` summed
+//! over the forward passes, divided by the tokens the input actually held. 1.00
+//! means the model did no work on padding.
+//!
+//! Run (downloads ~90 MB of MiniLM weights on first use):
+//!
+//! ```sh
+//! cargo run --release -p xerj-ai --features neural --example neural_throughput
+//! ```
+//!
+//! `XERJ_NEURAL_LOCAL_DIR=/path/to/model` loads air-gapped weights instead.
+//! `XERJ_NEURAL_CORPUS=/path/to/folder` adds an arm over real files, chunked
+//! the way ingest chunks a `semantic_text` field. `XERJ_NEURAL_BIGDOC=/path/to/
+//! file` replaces the synthesized big document with a real one.
+//!
+//! This measures the encoder in isolation. The end-to-end server measurement
+//! (ingest a corpus over HTTP with `--embed-mode neural`) lives in
+//! `demo/playbooks/neural-embedder-verification/`.
+
+use std::time::Instant;
+
+use xerj_ai::neural::{BatchStats, NeuralConfig, NeuralEmbedder};
+use xerj_ai::TextChunker;
+
+/// One ~120-character line, the document shape measured in issue #366.
+fn short_passage(i: usize) -> String {
+ format!(
+ "method selectAndLinkDiverse{i} in HnswGraphBuilder.java. Select neighbors to add and \
+ return a mask of the ones kept."
+ )
+}
+
+/// One ~512-character chunk, what `TextChunker` emits for a long field.
+fn long_passage(i: usize) -> String {
+ let mut s = format!("chunk {i}: ");
+ while s.len() < 512 {
+ s.push_str(
+ "the graph builder links each new node to its diverse neighbors and prunes the \
+ candidate list before the next level is entered. ",
+ );
+ }
+ s.truncate(512);
+ s
+}
+
+/// Embed `texts` in windows of `window` passages and report the arm.
+///
+/// `padded/real` is what this build actually ran. `rect/real` is what the same
+/// windows cost as ONE rectangular forward pass each — the pre-#366 behaviour —
+/// priced from the same token lengths, so any corpus can be scored for how much
+/// length-aware batching is worth on it without keeping an old binary around.
+fn arm(
+ embedder: &NeuralEmbedder,
+ label: &str,
+ texts: &[String],
+ window: usize,
+) -> anyhow::Result<()> {
+ let mut total = BatchStats::default();
+ let mut rectangular = 0usize;
+ for chunk in texts.chunks(window) {
+ let lengths = embedder.token_lengths(chunk)?;
+ rectangular += lengths.len() * lengths.iter().copied().max().unwrap_or(0);
+ }
+ let started = Instant::now();
+ for chunk in texts.chunks(window) {
+ let (_, stats) = embedder.embed_blocking_stats(chunk)?;
+ total.inference_calls += stats.inference_calls;
+ total.padded_token_slots += stats.padded_token_slots;
+ total.real_tokens += stats.real_tokens;
+ }
+ let secs = started.elapsed().as_secs_f64();
+ let real = total.real_tokens.max(1) as f64;
+ println!(
+ "{label:<28} passages={:<5} forwards={:<4} wall={secs:>7.2}s {:>7.1} passages/s \
+ padded/real={:.2} rect/real={:.2}",
+ texts.len(),
+ total.inference_calls,
+ texts.len() as f64 / secs,
+ total.padded_token_slots as f64 / real,
+ rectangular as f64 / real,
+ );
+ Ok(())
+}
+
+/// Every readable file under `dir`, as one passage list: each file's text is
+/// chunked exactly the way the ingest path chunks a `semantic_text` field
+/// (`SEMANTIC_CHUNK_SIZE` 512 / overlap 64 in `xerj-engine`), so the passage
+/// length distribution is the one a real `autoindex` run produces.
+fn corpus_passages(dir: &std::path::Path, max_files: usize) -> anyhow::Result<Vec<String>> {
+ let chunker = TextChunker::new(512, 64);
+ let mut passages = Vec::new();
+ let mut stack = vec![dir.to_path_buf()];
+ let mut files = 0;
+ while let Some(path) = stack.pop() {
+ if files >= max_files {
+ break;
+ }
+ let Ok(entries) = std::fs::read_dir(&path) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ } else if let Ok(text) = std::fs::read_to_string(&path) {
+ if text.trim().is_empty() {
+ continue;
+ }
+ passages.extend(chunker.chunk(&text, None).into_iter().map(|c| c.text));
+ files += 1;
+ if files >= max_files {
+ break;
+ }
+ }
+ }
+ }
+ println!(
+ "corpus {}: {files} files, {} passages",
+ dir.display(),
+ passages.len()
+ );
+ Ok(passages)
+}
+
+fn main() -> anyhow::Result<()> {
+ let cfg = NeuralConfig {
+ local_dir: std::env::var("XERJ_NEURAL_LOCAL_DIR").ok().map(Into::into),
+ ..Default::default()
+ };
+ let t = Instant::now();
+ let embedder = NeuralEmbedder::load(&cfg)?;
+ println!(
+ "loaded model dims={} in {:.2}s on {} cores\n",
+ embedder.dims(),
+ t.elapsed().as_secs_f64(),
+ std::thread::available_parallelism().map_or(0, |n| n.get())
+ );
+
+ // Warm up: the first call pays lazy allocation inside candle.
+ embedder.embed_blocking(&[short_passage(0)])?;
+
+ let short: Vec<String> = (0..320).map(short_passage).collect();
+ arm(&embedder, "single (1 passage/call)", &short[..128], 1)?;
+ arm(&embedder, "uniform short (window 64)", &short, 64)?;
+
+ // Each window of 64 holds 4 long chunks and 60 short lines — one window
+ // per 64 consecutive entries.
+ let mut mixed = Vec::new();
+ for w in 0..5 {
+ mixed.extend((0..4).map(|i| long_passage(w * 4 + i)));
+ mixed.extend((0..60).map(|i| short_passage(w * 60 + i)));
+ }
+ arm(&embedder, "mixed 4 long + 60 short", &mixed, 64)?;
+
+ // Batch-size sweep on uniform short passages: where does batching stop
+ // paying?
+ let sweep: Vec<String> = (0..512).map(short_passage).collect();
+ for window in [1usize, 8, 16, 32, 64, 128, 256] {
+ arm(
+ &embedder,
+ &format!("sweep short batch={window}"),
+ &sweep,
+ window,
+ )?;
+ }
+
+ // All-long control: nothing short to pad up, so length grouping has
+ // nothing to win and only the token budget applies.
+ let long: Vec<String> = (0..64).map(long_passage).collect();
+ arm(&embedder, "all long (control)", &long, 64)?;
+
+ // One large document, every chunk in a single call — what a 200 KB header
+ // does to the ingest path. Run it last: pre-fix this arm peaks at multiple
+ // GB of resident memory.
+ //
+ // The synthesized default is prose (~4.7 characters per token), which shows
+ // the row cap but understates the memory. Point `XERJ_NEURAL_BIGDOC` at a
+ // real source file for the honest number: dense code tokenizes near 1.2
+ // characters per token, so its chunks are ~4x longer and BERT's attention
+ // tensor is quadratic in that.
+ let document = match std::env::var("XERJ_NEURAL_BIGDOC") {
+ Ok(path) => {
+ let mut text = std::fs::read_to_string(&path)?;
+ let cut = text
+ .char_indices()
+ .map(|(i, _)| i)
+ .find(|i| *i >= 210_000)
+ .unwrap_or(text.len());
+ text.truncate(cut);
+ println!("big document: {path} ({} bytes)", text.len());
+ text
+ }
+ Err(_) => {
+ let mut text = String::new();
+ while text.len() < 210_000 {
+ text.push_str(&long_passage(text.len()));
+ text.push(' ');
+ }
+ text
+ }
+ };
+ let chunks: Vec<String> = TextChunker::new(512, 64)
+ .chunk(&document, None)
+ .into_iter()
+ .map(|c| c.text)
+ .collect();
+ arm(
+ &embedder,
+ "one 210 KB document",
+ &chunks,
+ chunks.len().max(1),
+ )?;
+
+ // Optional: a real folder, chunked the way ingest chunks it.
+ if let Ok(dir) = std::env::var("XERJ_NEURAL_CORPUS") {
+ let max_files = std::env::var("XERJ_NEURAL_CORPUS_FILES")
+ .ok()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(60);
+ let passages = corpus_passages(std::path::Path::new(&dir), max_files)?;
+ if !passages.is_empty() {
+ arm(&embedder, "real corpus (window 64)", &passages, 64)?;
+ }
+ }
+
+ Ok(())
+}
diff --git a/engine/crates/xerj-ai/src/lib.rs b/engine/crates/xerj-ai/src/lib.rs
index fa4b0f91c..38632096a 100644
--- a/engine/crates/xerj-ai/src/lib.rs
+++ b/engine/crates/xerj-ai/src/lib.rs
@@ -8,6 +8,8 @@
//! - [`embed`] — Embedding proxy: async HTTP client for OpenAI-compatible embedding APIs
//! - [`local`] — Built-in zero-config deterministic text embedder (feature hashing)
//! - [`neural`] — Built-in neural BERT sentence embedder via candle (feature `neural`)
+//! - `microbatch` — Length-aware batching shared by the two in-process
+//! encoders, so one long passage cannot pad a whole window up to its length
//! - `onnx` — Experimental MiniLM-compatible FP32 ONNX backend
//! (feature `onnx-experimental`; server feature + explicit runtime selection required)
//! - [`chunker`] — Text chunking with sentence-aware splitting and overlap
@@ -22,6 +24,8 @@ pub mod chunker;
pub mod embed;
pub mod embedder;
pub mod local;
+#[cfg(any(feature = "neural", feature = "onnx-experimental"))]
+pub mod microbatch;
#[cfg(feature = "neural")]
pub mod neural;
#[cfg(feature = "onnx-experimental")]
diff --git a/engine/crates/xerj-ai/src/microbatch.rs b/engine/crates/xerj-ai/src/microbatch.rs
new file mode 100644
index 000000000..8fde865fc
--- /dev/null
+++ b/engine/crates/xerj-ai/src/microbatch.rs
@@ -0,0 +1,153 @@
+//! Length-aware batching for transformer inference.
+//!
+//! Both in-process encoder backends (Candle [`crate::neural`] and the
+//! experimental [`crate::onnx`] one) run a *rectangular* tensor: every row in
+//! one call is padded to the longest row in that call, and the model pays for
+//! the padding exactly as if it were real text. A window that mixes one long
+//! chunk with sixty short lines therefore costs `61 × long`, not
+//! `long + 60 × short`.
+//!
+//! [`group_by_padded_cost`] is the shared cure: sort the rows by token length,
+//! then cut a batch as soon as adding the next row would break either the row
+//! cap or the `rows × padded_sequence_length` budget. Rows of similar length
+//! end up together, so padding waste is bounded rather than set by the single
+//! longest member of the window, and the token budget bounds the activation
+//! memory one call can allocate.
+//!
+//! The returned groups hold *positions into the input*, so callers must map
+//! results back into input order — neither backend may reorder its output.
+
+/// Group row positions into inference batches.
+///
+/// `token_lengths[i]` is the tokenized length of row `i`. A batch is cut when
+/// it already holds `max_rows` rows, or when admitting the next row would push
+/// `rows × longest_row` past `padded_token_budget`.
+///
+/// A single row longer than the whole budget is still emitted, alone: the
+/// caller's model has its own truncation limit and refusing the row here would
+/// turn an expensive document into a failed one. Callers that want an error
+/// instead check the lengths before calling (see [`crate::onnx`]).
+///
+/// The sort is stable, so equal-length rows keep input order and the plan is
+/// deterministic for a given input.
+pub fn group_by_padded_cost(
+ token_lengths: &[usize],
+ max_rows: usize,
+ padded_token_budget: usize,
+) -> Vec<Vec<usize>> {
+ debug_assert!(max_rows > 0 && padded_token_budget > 0);
+ let max_rows = max_rows.max(1);
+ let padded_token_budget = padded_token_budget.max(1);
+
+ let mut order = (0..token_lengths.len()).collect::<Vec<_>>();
+ order.sort_by_key(|&i| token_lengths[i]);
+
+ let mut batches: Vec<Vec<usize>> = Vec::new();
+ let mut batch: Vec<usize> = Vec::new();
+ let mut longest = 0usize;
+ for i in order {
+ let length = token_lengths[i];
+ let next_longest = longest.max(length);
+ if !batch.is_empty()
+ && (batch.len() >= max_rows
+ || next_longest.saturating_mul(batch.len() + 1) > padded_token_budget)
+ {
+ batches.push(std::mem::take(&mut batch));
+ longest = 0;
+ }
+ longest = longest.max(length);
+ batch.push(i);
+ }
+ if !batch.is_empty() {
+ batches.push(batch);
+ }
+ batches
+}
+
+/// Total `rows × longest_row` slots a plan pushes through the model.
+///
+/// This is the quantity the padding waste lives in: it equals the sum of the
+/// real token lengths only when every batch is length-homogeneous.
+pub fn padded_token_slots(token_lengths: &[usize], batches: &[Vec<usize>]) -> usize {
+ batches
+ .iter()
+ .map(|batch| {
+ let longest = batch
+ .iter()
+ .map(|&i| token_lengths[i])
+ .max()
+ .unwrap_or_default();
+ longest * batch.len()
+ })
+ .sum()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_position_appears_exactly_once() {
+ let lengths = [512, 14, 200, 16, 400, 15, 90, 300];
+ let batches = group_by_padded_cost(&lengths, 3, 600);
+ let mut positions = batches.iter().flatten().copied().collect::<Vec<_>>();
+ positions.sort_unstable();
+ assert_eq!(positions, (0..lengths.len()).collect::<Vec<_>>());
+ }
+
+ #[test]
+ fn batches_respect_the_row_cap_and_the_token_budget() {
+ let lengths = [512, 14, 200, 16, 400, 15, 90, 300];
+ let batches = group_by_padded_cost(&lengths, 3, 600);
+ for batch in &batches {
+ assert!(batch.len() <= 3, "row cap");
+ let longest = batch.iter().map(|&i| lengths[i]).max().unwrap();
+ assert!(
+ longest * batch.len() <= 600 || batch.len() == 1,
+ "token budget: {longest} × {}",
+ batch.len()
+ );
+ }
+ }
+
+ /// The defect this module exists for: one long row in a window of short
+ /// ones must not drag the short ones up to its length.
+ #[test]
+ fn one_long_row_does_not_pad_the_short_rows_up_to_it() {
+ let mut lengths = vec![128];
+ lengths.resize(64, 30);
+ let real: usize = lengths.iter().sum();
+
+ // What a single rectangular call costs: 64 rows × the longest row.
+ let unbatched = padded_token_slots(&lengths, &[(0..lengths.len()).collect()]);
+ assert_eq!(unbatched, 64 * 128);
+
+ let planned = padded_token_slots(&lengths, &group_by_padded_cost(&lengths, 64, 4096));
+ assert_eq!(planned, real, "length-homogeneous groups pad nothing");
+ assert!(
+ planned * 3 < unbatched,
+ "planned={planned} must be far below the rectangular cost {unbatched}"
+ );
+ }
+
+ #[test]
+ fn a_row_longer_than_the_budget_is_emitted_alone() {
+ let batches = group_by_padded_cost(&[8, 9_000, 8], 64, 4_096);
+ let oversized = batches
+ .iter()
+ .find(|batch| batch.contains(&1))
+ .expect("the oversized row is still planned");
+ assert_eq!(oversized.as_slice(), &[1]);
+ }
+
+ #[test]
+ fn empty_input_plans_nothing() {
+ assert!(group_by_padded_cost(&[], 64, 4_096).is_empty());
+ }
+
+ #[test]
+ fn equal_lengths_keep_input_order() {
+ let batches = group_by_padded_cost(&[10, 10, 10, 10], 2, 4_096);
+ assert_eq!(batches, vec![vec![0, 1], vec![2, 3]]);
+ }
+}
diff --git a/engine/crates/xerj-ai/src/neural.rs b/engine/crates/xerj-ai/src/neural.rs
index fbd230387..21c6ea9ba 100644
--- a/engine/crates/xerj-ai/src/neural.rs
+++ b/engine/crates/xerj-ai/src/neural.rs
@@ -22,7 +22,9 @@ use candle_core::{DType, Device, Tensor};
use candle_nn::VarBuilder;
use candle_transformers::models::bert::{BertModel, Config, DTYPE};
use std::path::{Path, PathBuf};
-use tokenizers::{PaddingParams, PaddingStrategy, Tokenizer, TruncationParams};
+use tokenizers::{Encoding, Tokenizer, TruncationParams};
+
+use crate::microbatch::group_by_padded_cost;
/// Default sentence encoder: 6-layer MiniLM, 384-dim, ~90 MB.
pub const DEFAULT_MODEL_ID: &str = "sentence-transformers/all-MiniLM-L6-v2";
@@ -31,6 +33,44 @@ pub const DEFAULT_MODEL_ID: &str = "sentence-transformers/all-MiniLM-L6-v2";
/// already chunked upstream, so this is a safety clamp, not the usual path.
const MAX_TOKENS: usize = 512;
+/// Rows in one forward pass. Measured on CPU with MiniLM
+/// (`examples/neural_throughput.rs`): throughput climbs steeply to 64 rows and
+/// then flattens and falls back. Two runs of that sweep on this shared box
+/// disagree on absolute throughput — 32/64/128/256 rows read 139/155/151/132
+/// passages/s in one and 179.1/199.9/198.7/166.2 in the other (the second is
+/// the run published with this change) — but agree on where the knee is. 64 is
+/// also what the ONNX backend uses.
+const MAX_BATCH_ROWS: usize = 64;
+
+/// Ceiling on `rows × padded_sequence_length` for one forward pass. Bounds the
+/// activation memory a single call can allocate (BERT's attention tensor grows
+/// with `rows × heads × seq²`) and stops a long passage from being batched with
+/// many others at its own length. 4096 leaves a full 64-row batch of ~64-token
+/// passages intact; on real ingest chunks (512 *characters*, so roughly
+/// 110–130 tokens of prose and up to ~400 for dense code) it is usually the
+/// budget rather than the row cap that binds — about 32 rows for prose, ~9 for
+/// code.
+const PADDED_TOKEN_BUDGET: usize = 4_096;
+
+/// BERT's `[PAD]` id. Padded positions carry attention-mask 0, so the id only
+/// has to be a valid embedding-table index; 0 is what the tokenizer's own
+/// `PaddingParams::default()` used before batches were planned here.
+const PAD_TOKEN_ID: u32 = 0;
+
+/// What one [`NeuralEmbedder::embed_blocking_stats`] call actually pushed
+/// through the model. `padded_token_slots` equals `real_tokens` exactly when
+/// every batch is length-homogeneous; the ratio between them is the padding
+/// waste, which is what length-aware batching exists to keep near 1.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct BatchStats {
+ /// Forward passes run for this call.
+ pub inference_calls: usize,
+ /// `rows × padded_sequence_length`, summed over those forward passes.
+ pub padded_token_slots: usize,
+ /// Tokens the input actually contained, after truncation.
+ pub real_tokens: usize,
+}
+
/// How to obtain the model weights.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NeuralConfig {
@@ -86,12 +126,14 @@ impl NeuralEmbedder {
let mut tokenizer = Tokenizer::from_file(&tokenizer_path)
.map_err(|e| anyhow!("load tokenizer {}: {e}", tokenizer_path.display()))?;
- // Pad each batch to its longest member so we can stack into one tensor,
- // and clamp over-long passages to the model's positional limit.
- tokenizer.with_padding(Some(PaddingParams {
- strategy: PaddingStrategy::BatchLongest,
- ..Default::default()
- }));
+ // Tokenize WITHOUT padding. Padding to the longest member of whatever
+ // the caller handed us is exactly the cost this backend used to pay:
+ // one long chunk in a window of short lines charged every short line
+ // the long chunk's length. `embed_blocking` groups rows by length and
+ // pads each group to its own longest row instead (see
+ // [`crate::microbatch`]), so padding is applied here, per batch.
+ tokenizer.with_padding(None);
+ // Clamp over-long passages to the model's positional limit.
tokenizer
.with_truncation(Some(TruncationParams {
max_length: MAX_TOKENS,
@@ -119,28 +161,90 @@ impl NeuralEmbedder {
/// Embed a batch of passages into L2-normalized sentence vectors using
/// attention-masked mean pooling (the sentence-transformers convention).
/// **Blocking / CPU-bound** — call via `spawn_blocking`.
+ ///
+ /// Output order matches input order regardless of how the passages were
+ /// grouped internally.
pub fn embed_blocking(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
+ self.embed_blocking_stats(texts).map(|(vectors, _)| vectors)
+ }
+
+ /// Tokenized length of each passage, after truncation to [`MAX_TOKENS`].
+ ///
+ /// The cost of one forward pass is `rows × padded_sequence_length`, so
+ /// these lengths are what any batching decision has to be made on; the
+ /// throughput harness uses them to price a plan without running it.
+ pub fn token_lengths(&self, texts: &[String]) -> Result<Vec<usize>> {
+ Ok(self
+ .tokenizer
+ .encode_batch(texts.to_vec(), true)
+ .map_err(|e| anyhow!("tokenize batch: {e}"))?
+ .iter()
+ .map(|enc| enc.get_ids().len().min(MAX_TOKENS))
+ .collect())
+ }
+
+ /// [`Self::embed_blocking`], additionally reporting how much work the call
+ /// actually pushed through the model. Used by the throughput harness and
+ /// by the padding regression test; behaviour is otherwise identical.
+ pub fn embed_blocking_stats(&self, texts: &[String]) -> Result<(Vec<Vec<f32>>, BatchStats)> {
if texts.is_empty() {
- return Ok(vec![]);
+ return Ok((vec![], BatchStats::default()));
}
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 {
- // All-empty input — return zero vectors of the right width.
- return Ok(vec![vec![0.0; self.dims]; batch]);
+ // The tokenizer truncates at MAX_TOKENS and no longer pads, so these
+ // are the real per-passage lengths.
+ let lengths = encodings
+ .iter()
+ .map(|enc| enc.get_ids().len().min(MAX_TOKENS))
+ .collect::<Vec<_>>();
+
+ let mut stats = BatchStats {
+ real_tokens: lengths.iter().sum(),
+ ..BatchStats::default()
+ };
+ let mut ordered = vec![Vec::new(); texts.len()];
+ for rows in group_by_padded_cost(&lengths, MAX_BATCH_ROWS, PADDED_TOKEN_BUDGET) {
+ let seq_len = rows.iter().map(|&i| lengths[i]).max().unwrap_or(0);
+ if seq_len == 0 {
+ // All-empty group — zero vectors of the right width.
+ for i in rows {
+ ordered[i] = vec![0.0; self.dims];
+ }
+ continue;
+ }
+ stats.inference_calls += 1;
+ stats.padded_token_slots += rows.len() * seq_len;
+ let vectors = self.forward_padded(&encodings, &rows, &lengths, seq_len)?;
+ for (i, vector) in rows.into_iter().zip(vectors) {
+ ordered[i] = vector;
+ }
}
+ Ok((ordered, stats))
+ }
+ /// Run one rectangular forward pass over `rows`, right-padding each row to
+ /// `seq_len` with [`PAD_TOKEN_ID`] and attention-mask 0. Returns vectors in
+ /// `rows` order.
+ fn forward_padded(
+ &self,
+ encodings: &[Encoding],
+ rows: &[usize],
+ lengths: &[usize],
+ seq_len: usize,
+ ) -> Result<Vec<Vec<f32>>> {
+ let batch = rows.len();
let mut ids: Vec<u32> = Vec::with_capacity(batch * seq_len);
let mut mask: Vec<u32> = Vec::with_capacity(batch * seq_len);
- for enc in &encodings {
- ids.extend_from_slice(enc.get_ids());
- mask.extend_from_slice(enc.get_attention_mask());
+ for &row in rows {
+ let len = lengths[row];
+ ids.extend_from_slice(&encodings[row].get_ids()[..len]);
+ ids.resize(ids.len() + (seq_len - len), PAD_TOKEN_ID);
+ mask.extend_from_slice(&encodings[row].get_attention_mask()[..len]);
+ mask.resize(mask.len() + (seq_len - len), 0);
}
let input_ids = Tensor::from_vec(ids, (batch, seq_len), &self.device)
@@ -317,4 +421,93 @@ mod tests {
sentence (got paraphrase={sim_paraphrase:.3}, unrelated={sim_unrelated:.3})"
);
}
+
+ /// The ~512-character chunk `TextChunker` emits for a long field.
+ fn long_passage() -> String {
+ let mut s = String::new();
+ while s.len() < 512 {
+ s.push_str(
+ "the graph builder links each new node to its diverse neighbors and prunes the \
+ candidate list before the next level is entered. ",
+ );
+ }
+ s.truncate(512);
+ s
+ }
+
+ /// ~120 characters, the document shape measured in issue #366.
+ fn short_passage(i: usize) -> String {
+ format!(
+ "method selectAndLinkDiverse{i} in HnswGraphBuilder.java. Select neighbors and \
+ return a mask of the ones kept."
+ )
+ }
+
+ /// Regression for #366. A window that mixes one long chunk with many short
+ /// lines must not charge the short lines the long chunk's length.
+ ///
+ /// Before length-aware batching this ran as ONE rectangular forward pass of
+ /// 64 rows padded to the long chunk, i.e. `padded_token_slots` ≈ 3× the
+ /// tokens the input actually held; measured wall time on the same box went
+ /// 40 → 146 passages/s when this bound started holding.
+ ///
+ /// Live test (needs the MiniLM weights), so `#[ignore]`d:
+ /// cargo test -p xerj-ai --features neural -- --ignored --nocapture
+ #[test]
+ #[ignore]
+ fn mixed_length_window_does_not_pad_short_passages_up_to_the_long_one() {
+ let emb = NeuralEmbedder::load(&NeuralConfig::default()).expect("load MiniLM");
+
+ let mut texts = vec![long_passage()];
+ texts.extend((0..63).map(short_passage));
+ let (vectors, stats) = emb.embed_blocking_stats(&texts).expect("embed");
+
+ assert_eq!(vectors.len(), texts.len());
+ eprintln!(
+ "forwards={} padded_slots={} real_tokens={} ratio={:.2}",
+ stats.inference_calls,
+ stats.padded_token_slots,
+ stats.real_tokens,
+ stats.padded_token_slots as f64 / stats.real_tokens as f64
+ );
+ assert!(
+ stats.padded_token_slots * 2 <= stats.real_tokens * 3,
+ "padding waste must stay under 1.5×: {} padded slots for {} real tokens \
+ ({} forward passes)",
+ stats.padded_token_slots,
+ stats.real_tokens,
+ stats.inference_calls
+ );
+ }
+
+ /// Grouping reorders rows internally; the vectors that come back must still
+ /// line up with the inputs, and must match what each passage gets on its
+ /// own. Live test, so `#[ignore]`d.
+ #[test]
+ #[ignore]
+ fn grouping_preserves_input_order() {
+ let emb = NeuralEmbedder::load(&NeuralConfig::default()).expect("load MiniLM");
+
+ // Deliberately interleaved lengths so the length sort has to reorder.
+ let texts = vec![
+ long_passage(),
+ short_passage(1),
+ "a".to_string(),
+ long_passage(),
+ short_passage(2),
+ ];
+ let batched = emb.embed_blocking(&texts).expect("embed batch");
+ assert_eq!(batched.len(), texts.len());
+ for (i, text) in texts.iter().enumerate() {
+ let alone = emb
+ .embed_blocking(std::slice::from_ref(text))
+ .expect("embed alone");
+ let sim = cosine(&batched[i], &alone[0]);
+ assert!(
+ sim > 0.999,
+ "row {i} came back out of order or altered: cosine {sim:.4} against the \
+ same passage embedded alone"
+ );
+ }
+ }
}
diff --git a/engine/crates/xerj-ai/src/onnx.rs b/engine/crates/xerj-ai/src/onnx.rs
index 231ae46e9..92f2eb974 100644
--- a/engine/crates/xerj-ai/src/onnx.rs
+++ b/engine/crates/xerj-ai/src/onnx.rs
@@ -350,6 +350,11 @@ impl OnnxEmbedder {
/// 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,
@@ -362,35 +367,27 @@ pub fn plan_microbatches(
config.max_pending
));
}
- let mut order = (0..token_lengths.len()).collect::<Vec<_>>();
- order.sort_by_key(|&i| token_lengths[i].min(MAX_TOKENS));
- let mut batches = Vec::new();
- let mut batch = Vec::new();
- let mut longest = 0;
- for i in order {
- let length = token_lengths[i].min(MAX_TOKENS);
- if length > config.padded_token_budget {
- return Err(anyhow!(
- "padded_token_budget={} cannot fit one {}-token input",
- config.padded_token_budget,
- length
- ));
- }
- let next_longest = longest.max(length);
- if !batch.is_empty()
- && (batch.len() == config.max_batch
- || next_longest * (batch.len() + 1) > config.padded_token_budget)
- {
- batches.push(std::mem::take(&mut batch));
- longest = 0;
- }
- longest = longest.max(length);
- batch.push(i);
- }
- if !batch.is_empty() {
- batches.push(batch);
+ 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(batches)
+ Ok(crate::microbatch::group_by_padded_cost(
+ &clamped,
+ config.max_batch,
+ config.padded_token_budget,
+ ))
}
#[cfg(test)]