From 9b076cc296b6f584ac303f32f66bef48cdcf215a Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 11:53:48 +0530 Subject: [PATCH 1/7] feat(model): add the context length of each model --- src/model.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/model.rs b/src/model.rs index 0fc3267..fcbcf4d 100644 --- a/src/model.rs +++ b/src/model.rs @@ -23,6 +23,16 @@ pub fn dimension(model: &EmbeddingModel) -> usize { } } +/// Longest input, in tokens, the model was trained to embed. +pub fn context_length(model: &EmbeddingModel) -> usize { + match model { + EmbeddingModel::NomicEmbedTextV15 | EmbeddingModel::NomicEmbedTextV1 => 8192, + EmbeddingModel::EmbeddingGemma300M => 2048, + EmbeddingModel::AllMiniLML6V2 => 256, + _ => 512, + } +} + #[cfg(test)] mod tests { use super::*; @@ -46,4 +56,11 @@ mod tests { assert_eq!(dimension(&EmbeddingModel::BGELargeENV15), 1024); assert_eq!(dimension(&EmbeddingModel::EmbeddingGemma300M), 768); } + #[test] + fn context_length_known_models() { + assert_eq!(context_length(&EmbeddingModel::NomicEmbedTextV15), 8192); + assert_eq!(context_length(&EmbeddingModel::EmbeddingGemma300M), 2048); + assert_eq!(context_length(&EmbeddingModel::BGESmallENV15), 512); + assert_eq!(context_length(&EmbeddingModel::AllMiniLML6V2), 256); + } } From 739848b6a11b987536b4d339d9a1592f0cdbe551 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 11:53:48 +0530 Subject: [PATCH 2/7] fix(embedding): embed up to the model context and count those tokens --- src/embedding.rs | 54 +++++++++++++++++++++++++++++++++++++++++++--- tests/embed_e2e.rs | 2 ++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/embedding.rs b/src/embedding.rs index 33d5278..4c6e80f 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -9,7 +9,7 @@ use std::sync::{ atomic::{AtomicU64, AtomicUsize, Ordering}, }; use std::time::{Duration, Instant}; -use tokenizers::Tokenizer; +use tokenizers::{Tokenizer, TruncationParams}; /// Unload a model this many seconds after last use. `0` disables unloading. pub const DEFAULT_IDLE_UNLOAD_SECS: u64 = 300; @@ -17,6 +17,11 @@ pub const DEFAULT_IDLE_UNLOAD_SECS: u64 = 300; /// After a failed load, skip another download/init for this long. const LOAD_RETRY_SECS: u64 = 30; +/// Upper bound on tokens embedded per text, whatever the model supports. +/// One text at 4096 tokens peaks near 3 GB and memory grows with the square of +/// the length, so nomic's full 8192 cannot run in a typical container. +pub const DEFAULT_MAX_TOKENS: usize = 2048; + #[derive(Debug, Clone)] pub struct EmbeddingResult { pub model: String, @@ -35,6 +40,7 @@ pub struct EmbeddingConfig { pub sub_batch_size: usize, pub intra_threads: usize, pub idle_unload_secs: u64, + pub max_tokens: usize, } fn available_cpus() -> usize { @@ -156,6 +162,10 @@ impl EmbeddingConfig { .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_IDLE_UNLOAD_SECS); + let max_tokens = parse_usize_env("EMBEDDING_MAX_TOKENS") + .filter(|&n| n >= 1) + .unwrap_or(DEFAULT_MAX_TOKENS); + Self { models, show_download_progress: true, @@ -165,8 +175,14 @@ impl EmbeddingConfig { sub_batch_size: 0, intra_threads, idle_unload_secs, + max_tokens, } } + + /// Tokens embedded per text for `model`. + fn max_length(&self, model: &EmbeddingModel) -> usize { + model::context_length(model).min(self.max_tokens) + } } pub struct EmbeddingClient { @@ -183,6 +199,7 @@ struct LoadedModel { load: Mutex<()>, inner: Mutex, dimension: usize, + max_length: usize, last_access: AtomicU64, in_flight: AtomicUsize, last_failure: Mutex>, @@ -233,6 +250,7 @@ impl EmbeddingClient { tokenizer: None, }), dimension: model::dimension(model), + max_length: config.max_length(model), last_access: AtomicU64::new(0), in_flight: AtomicUsize::new(0), last_failure: Mutex::new(None), @@ -578,7 +596,18 @@ impl EmbeddingClient { let path = repo .get("tokenizer.json") .map_err(|e| format!("fetch tokenizer.json: {}", e))?; - Tokenizer::from_file(&path).map_err(|e| format!("parse tokenizer.json: {}", e)) + let mut tokenizer = + Tokenizer::from_file(&path).map_err(|e| format!("parse tokenizer.json: {}", e))?; + // Count what the model embeds: cut where it cuts, and leave out the + // padding some tokenizer.json files turn on. + tokenizer + .with_truncation(Some(TruncationParams { + max_length: config.max_length(model), + ..Default::default() + })) + .map_err(|e| format!("truncate tokenizer: {}", e))?; + tokenizer.with_padding(None); + Ok(tokenizer) } fn init_model( @@ -587,6 +616,7 @@ impl EmbeddingClient { intra_threads: usize, ) -> Result { let mut init_options = InitOptions::new(model.clone()) + .with_max_length(config.max_length(model)) .with_show_download_progress(config.show_download_progress) .with_intra_threads(intra_threads); @@ -736,12 +766,13 @@ mod tests { static ENV_LOCK: Mutex<()> = Mutex::new(()); - const ENV_KEYS: [&str; 5] = [ + const ENV_KEYS: [&str; 6] = [ "EMBEDDING_MODELS", "EMBEDDING_CACHE_DIR", "EMBEDDING_POOL_SIZE", "EMBEDDING_INTRA_THREADS", "EMBEDDING_IDLE_UNLOAD_SECS", + "EMBEDDING_MAX_TOKENS", ]; /// Holds the env mutex and restores the original values on drop. Tests that @@ -947,6 +978,23 @@ mod tests { assert_eq!(cfg.idle_unload_secs, 60); } + #[test] + fn max_length_is_the_context_length_capped_by_max_tokens() { + let _g = isolate_env(); + let config = EmbeddingConfig::from_env(); + assert_eq!(config.max_tokens, DEFAULT_MAX_TOKENS); + assert_eq!(config.max_length(&EmbeddingModel::NomicEmbedTextV15), 2048); + assert_eq!(config.max_length(&EmbeddingModel::AllMiniLML6V2), 256); + + set("EMBEDDING_MAX_TOKENS", "8192"); + let config = EmbeddingConfig::from_env(); + assert_eq!(config.max_length(&EmbeddingModel::NomicEmbedTextV15), 8192); + assert_eq!(config.max_length(&EmbeddingModel::EmbeddingGemma300M), 2048); + + set("EMBEDDING_MAX_TOKENS", "0"); + assert_eq!(EmbeddingConfig::from_env().max_tokens, DEFAULT_MAX_TOKENS); + } + #[test] fn should_unload_requires_prior_use_and_timeout() { assert!(!should_unload(0, 1_000, 300)); diff --git a/tests/embed_e2e.rs b/tests/embed_e2e.rs index 741af35..4a31395 100644 --- a/tests/embed_e2e.rs +++ b/tests/embed_e2e.rs @@ -12,6 +12,7 @@ fn small_model_config(pool_size: usize) -> EmbeddingConfig { sub_batch_size: 0, intra_threads: 1, idle_unload_secs: 0, + max_tokens: 2048, } } @@ -25,6 +26,7 @@ fn nomic_config() -> EmbeddingConfig { sub_batch_size: 0, intra_threads: 1, idle_unload_secs: 0, + max_tokens: 2048, } } From 3242a5afce4c8155a9b5e727beb994d9b4d788d9 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 12:00:03 +0530 Subject: [PATCH 3/7] fix(embedding): size sub-batches by the configured max length --- src/embedding.rs | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/embedding.rs b/src/embedding.rs index 4c6e80f..69fbb66 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -198,7 +198,6 @@ struct LoadedModel { next: AtomicUsize, load: Mutex<()>, inner: Mutex, - dimension: usize, max_length: usize, last_access: AtomicU64, in_flight: AtomicUsize, @@ -249,7 +248,6 @@ impl EmbeddingClient { pool: None, tokenizer: None, }), - dimension: model::dimension(model), max_length: config.max_length(model), last_access: AtomicU64::new(0), in_flight: AtomicUsize::new(0), @@ -691,7 +689,7 @@ impl EmbeddingClient { sys.available_memory(), sys.cgroup_limits().map(|limits| limits.free_memory), ) / (1024 * 1024); - Self::compute_sub_batch(available_mb, loaded.dimension, self.gpu) + Self::compute_sub_batch(available_mb, loaded.max_length, self.gpu) }; // Each chunk runs in spawn_blocking so ORT inference does not occupy @@ -746,13 +744,12 @@ impl EmbeddingClient { /// When GPU is enabled, the upper clamp is raised to 256 (GPU VRAM can /// handle much larger batches than CPU). /// TODO: add here the config batch size - fn compute_sub_batch(available_mb: u64, dimension: usize, gpu: bool) -> usize { - // Per-text memory estimate for ONNX inference. Attention matrices - // dominate: heads × seq² × 4 bytes. For 768-dim BERT-like models - // (12 heads) processing ~1000-2000 token code chunks, attention alone - // is 50-200 MB per text. The estimate below is conservative so the - // sub-batch stays small enough to prevent arena over-allocation. - let mb_per_text: u64 = if dimension >= 768 { 100 } else { 40 }; + fn compute_sub_batch(available_mb: u64, max_length: usize, gpu: bool) -> usize { + // Peak memory per text for ONNX inference. Attention matrices dominate + // and grow with seq². Fitted just above nomic on CPU: 86 MB at 512 + // tokens, 206 MB at 1024, 591 MB at 2048 and 2.4 GB at 4096. + let max_length = max_length as u64; + let mb_per_text = 50 + max_length * max_length / 6_500; let budget_mb = available_mb / 2; let max_batch = if gpu { 256 } else { 16 }; (budget_mb / mb_per_text).clamp(1, max_batch) as usize @@ -1005,19 +1002,26 @@ mod tests { #[test] fn compute_sub_batch_shrinks_to_fit_small_budgets() { - assert_eq!(EmbeddingClient::compute_sub_batch(0, 768, false), 1); - // 200 MiB free -> 100 MiB budget -> one 100 MiB text, not four. - assert_eq!(EmbeddingClient::compute_sub_batch(200, 768, false), 1); + assert_eq!(EmbeddingClient::compute_sub_batch(0, 2048, false), 1); + // 200 MiB free -> 100 MiB budget -> never less than one text. + assert_eq!(EmbeddingClient::compute_sub_batch(200, 2048, false), 1); assert_eq!( - EmbeddingClient::compute_sub_batch(64 * 1024, 768, false), + EmbeddingClient::compute_sub_batch(64 * 1024, 512, false), 16 ); assert_eq!( - EmbeddingClient::compute_sub_batch(64 * 1024, 768, true), + EmbeddingClient::compute_sub_batch(64 * 1024, 512, true), 256 ); } + #[test] + fn compute_sub_batch_shrinks_as_max_length_grows() { + assert_eq!(EmbeddingClient::compute_sub_batch(4096, 512, false), 16); + assert_eq!(EmbeddingClient::compute_sub_batch(4096, 2048, false), 2); + assert_eq!(EmbeddingClient::compute_sub_batch(4096, 8192, false), 1); + } + #[test] fn next_index_round_robins_through_pool() { let counter = AtomicUsize::new(0); From 14ece645a36b0218d16019cf55dba992a81c6c43 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 12:00:03 +0530 Subject: [PATCH 4/7] test(embedding): cover long input and embedded token counts --- tests/embed_e2e.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tests/embed_e2e.rs b/tests/embed_e2e.rs index 4a31395..0cc33ad 100644 --- a/tests/embed_e2e.rs +++ b/tests/embed_e2e.rs @@ -189,3 +189,54 @@ async fn nomic_embed_is_768d_and_ranks_similar_text_higher() { "related sentences should rank above an unrelated one: similar={similar} dissimilar={dissimilar}" ); } + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "downloads the NomicEmbedTextV15 ONNX model on first run"] +async fn nomic_embeds_text_past_512_tokens() { + let client = EmbeddingClient::new(nomic_config()).expect("client init"); + let prefix = "fox ".repeat(600); + let cats = format!("{prefix}cats cats cats cats"); + let quantum = format!("{prefix}quantum quantum quantum quantum"); + let result = client + .embed("nomic", &[cats.as_str(), quantum.as_str()]) + .await + .expect("nomic embed should succeed"); + + assert_ne!(result.embeddings[0], result.embeddings[1]); +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "downloads the NomicEmbedTextV15 ONNX model on first run"] +async fn nomic_tokens_stop_at_max_length() { + let mut cfg = nomic_config(); + cfg.max_tokens = 64; + let client = EmbeddingClient::new(cfg).expect("client init"); + let long = "word ".repeat(20_000); + let result = client + .embed("nomic", &[long.as_str(), long.as_str()]) + .await + .expect("nomic embed should succeed"); + + assert_eq!(result.tokens, 2 * 64); +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "downloads the AllMiniLML6V2 ONNX model on first run"] +async fn tokens_leave_out_padding() { + let client = EmbeddingClient::new(small_model_config(1)).expect("client init"); + let alone = client + .embed("minilm", &["hi"]) + .await + .expect("embed should succeed"); + let long = "word ".repeat(100); + let long_alone = client + .embed("minilm", &[long.as_str()]) + .await + .expect("embed should succeed"); + let batch = client + .embed("minilm", &["hi", long.as_str()]) + .await + .expect("embed should succeed"); + + assert_eq!(batch.tokens, alone.tokens + long_alone.tokens); +} From e860c9c26c1fe21a4874146c8d1487f63af99178 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 12:00:03 +0530 Subject: [PATCH 5/7] docs: document EMBEDDING_MAX_TOKENS --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 2413639..5842dcd 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ Configured via environment variables (set them in `.env`): | `EMBEDDING_POOL_SIZE` | `1` | Number of ONNX sessions per model while it is loaded, then capped by available RAM. Concurrent `/embed` calls round-robin across sessions. Raise this for parallel HTTP throughput; each extra session keeps another copy of the weights resident until idle unload. | | `EMBEDDING_INTRA_THREADS` | CPU count | ONNX Runtime intra-op threads per session. The default uses the whole machine on the single default session. When `EMBEDDING_POOL_SIZE` is greater than one, threads are split across sessions (`nproc / pool_size`, still capped by this value) so concurrent embeds do not oversubscribe the host. | | `EMBEDDING_IDLE_UNLOAD_SECS` | `300` | Drop a model's sessions this many seconds after last use (`0` disables). The next `/embed` reloads the same checkpoint from `EMBEDDING_CACHE_DIR`. | +| `EMBEDDING_MAX_TOKENS` | `2048` | Most tokens embedded per text; longer input is truncated. Each model also stops at its own context: `nomic` 8192, `embedding-gemma` 2048, `bge-small` 512, `all-minilm` 256. Memory grows with the square of this value: one nomic text peaks near 1.2 GB at 2048 and 3 GB at 4096, and 8192 did not fit in 5 GB. | ## API @@ -51,6 +52,8 @@ Response: } ``` +`tokens` is the number of tokens embedded, after truncation. + Errors: - `400 Bad Request` — `texts` is empty or the model alias is not in `EMBEDDING_MODELS`. From 945aa68e9c5558a7663c8e7d04b36d35b80366fa Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 15:03:17 +0530 Subject: [PATCH 6/7] fix(embedding): reject text over the token limit instead of truncating --- src/embedding.rs | 61 +++++++++++++++++++++++++++++++--------------- src/error.rs | 5 +++- src/main.rs | 4 ++- tests/embed_e2e.rs | 27 ++++++++++++++------ 4 files changed, 68 insertions(+), 29 deletions(-) diff --git a/src/embedding.rs b/src/embedding.rs index 69fbb66..4217405 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -9,7 +9,7 @@ use std::sync::{ atomic::{AtomicU64, AtomicUsize, Ordering}, }; use std::time::{Duration, Instant}; -use tokenizers::{Tokenizer, TruncationParams}; +use tokenizers::Tokenizer; /// Unload a model this many seconds after last use. `0` disables unloading. pub const DEFAULT_IDLE_UNLOAD_SECS: u64 = 300; @@ -17,7 +17,8 @@ pub const DEFAULT_IDLE_UNLOAD_SECS: u64 = 300; /// After a failed load, skip another download/init for this long. const LOAD_RETRY_SECS: u64 = 30; -/// Upper bound on tokens embedded per text, whatever the model supports. +/// Upper bound on tokens per text, whatever the model supports. Longer texts +/// are rejected. /// One text at 4096 tokens peaks near 3 GB and memory grows with the square of /// the length, so nomic's full 8192 cannot run in a typical container. pub const DEFAULT_MAX_TOKENS: usize = 2048; @@ -125,6 +126,15 @@ pub(crate) fn should_unload(last_access: u64, now: u64, idle_unload_secs: u64) - && now.saturating_sub(last_access) >= idle_unload_secs.saturating_mul(1000) } +/// Index and token count of the first text longer than `max_length`. +fn first_over_limit(counts: &[usize], max_length: usize) -> Option<(usize, usize)> { + counts + .iter() + .copied() + .enumerate() + .find(|&(_, count)| count > max_length) +} + fn parse_usize_env(key: &str) -> Option { std::env::var(key) .ok() @@ -596,14 +606,11 @@ impl EmbeddingClient { .map_err(|e| format!("fetch tokenizer.json: {}", e))?; let mut tokenizer = Tokenizer::from_file(&path).map_err(|e| format!("parse tokenizer.json: {}", e))?; - // Count what the model embeds: cut where it cuts, and leave out the - // padding some tokenizer.json files turn on. + // Count every input token: some tokenizer.json files turn on truncation + // and padding, which would hide input over the limit. tokenizer - .with_truncation(Some(TruncationParams { - max_length: config.max_length(model), - ..Default::default() - })) - .map_err(|e| format!("truncate tokenizer: {}", e))?; + .with_truncation(None) + .map_err(|e| format!("configure tokenizer: {}", e))?; tokenizer.with_padding(None); Ok(tokenizer) } @@ -680,6 +687,25 @@ impl EmbeddingClient { counter: &loaded.in_flight, }; + let tokenizer = self.tokenizer(loaded).await?; + let owned_texts: Vec = texts.iter().map(|t| t.to_string()).collect(); + let counts = tokio::task::spawn_blocking(move || -> Result, String> { + let encodings = tokenizer + .encode_batch(owned_texts, true) + .map_err(|e| format!("tokenize: {}", e))?; + Ok(encodings.iter().map(|e| e.get_ids().len()).collect()) + }) + .await + .map_err(|e| format!("Failed to join tokenizer task: {}", e))??; + + if let Some((index, count)) = first_over_limit(&counts, loaded.max_length) { + return Err(EmbedError::TooLong(format!( + "text at index {} has {} tokens, the limit for {} is {}", + index, count, model_name, loaded.max_length + ))); + } + let tokens = counts.iter().sum(); + let sub_batch = if self.sub_batch_override > 0 { self.sub_batch_override } else { @@ -717,17 +743,6 @@ impl EmbeddingClient { embeddings.append(&mut batch_result); } - let tokenizer = self.tokenizer(loaded).await?; - let owned_texts: Vec = texts.iter().map(|t| t.to_string()).collect(); - let tokens = tokio::task::spawn_blocking(move || -> Result { - let encodings = tokenizer - .encode_batch(owned_texts, true) - .map_err(|e| format!("tokenize: {}", e))?; - Ok(encodings.iter().map(|e| e.get_ids().len()).sum()) - }) - .await - .map_err(|e| format!("Failed to join tokenizer task: {}", e))??; - touch_access(loaded); Ok(EmbeddingResult { @@ -1015,6 +1030,12 @@ mod tests { ); } + #[test] + fn first_over_limit_allows_text_at_the_limit() { + assert_eq!(first_over_limit(&[10, 64], 64), None); + assert_eq!(first_over_limit(&[10, 65, 70], 64), Some((1, 65))); + } + #[test] fn compute_sub_batch_shrinks_as_max_length_grows() { assert_eq!(EmbeddingClient::compute_sub_batch(4096, 512, false), 16); diff --git a/src/error.rs b/src/error.rs index f5fbdb5..b228177 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,13 +1,16 @@ #[derive(Debug)] pub enum EmbedError { UnknownModel(String), + TooLong(String), Internal(String), } impl std::fmt::Display for EmbedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - EmbedError::UnknownModel(m) | EmbedError::Internal(m) => write!(f, "{}", m), + EmbedError::UnknownModel(m) | EmbedError::TooLong(m) | EmbedError::Internal(m) => { + write!(f, "{}", m) + } } } } diff --git a/src/main.rs b/src/main.rs index 15b7c4f..db3323b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -67,7 +67,9 @@ async fn embed( .embed(&req.model, &refs) .await .map_err(|e| match e { - EmbedError::UnknownModel(msg) => AppError(StatusCode::BAD_REQUEST, msg), + EmbedError::UnknownModel(msg) | EmbedError::TooLong(msg) => { + AppError(StatusCode::BAD_REQUEST, msg) + } EmbedError::Internal(msg) => AppError(StatusCode::INTERNAL_SERVER_ERROR, msg), })?; diff --git a/tests/embed_e2e.rs b/tests/embed_e2e.rs index 0cc33ad..6249ff3 100644 --- a/tests/embed_e2e.rs +++ b/tests/embed_e2e.rs @@ -1,4 +1,4 @@ -use embedding::{EmbeddingClient, EmbeddingConfig, EmbeddingModel}; +use embedding::{EmbedError, EmbeddingClient, EmbeddingConfig, EmbeddingModel}; use std::sync::Arc; use std::time::Duration; @@ -207,17 +207,30 @@ async fn nomic_embeds_text_past_512_tokens() { #[tokio::test(flavor = "multi_thread")] #[ignore = "downloads the NomicEmbedTextV15 ONNX model on first run"] -async fn nomic_tokens_stop_at_max_length() { +async fn nomic_rejects_text_over_max_length() { let mut cfg = nomic_config(); cfg.max_tokens = 64; let client = EmbeddingClient::new(cfg).expect("client init"); - let long = "word ".repeat(20_000); - let result = client - .embed("nomic", &[long.as_str(), long.as_str()]) + let long = "word ".repeat(100); + let err = client + .embed("nomic", &["short", long.as_str()]) .await - .expect("nomic embed should succeed"); + .expect_err("text over the limit should be rejected"); + + assert!(matches!(err, EmbedError::TooLong(_))); +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "downloads the AllMiniLML6V2 ONNX model on first run"] +async fn minilm_rejects_text_over_its_context() { + let client = EmbeddingClient::new(small_model_config(1)).expect("client init"); + let long = "word ".repeat(300); + let err = client + .embed("minilm", &[long.as_str()]) + .await + .expect_err("text over the model context should be rejected"); - assert_eq!(result.tokens, 2 * 64); + assert!(matches!(err, EmbedError::TooLong(_))); } #[tokio::test(flavor = "multi_thread")] From a96bc8fca3b8cf34a4f29ce25c72f6b948dd60a1 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 18 Nov 2026 15:03:17 +0530 Subject: [PATCH 7/7] docs: document the token limit error --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5842dcd..05f23f0 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Configured via environment variables (set them in `.env`): | `EMBEDDING_POOL_SIZE` | `1` | Number of ONNX sessions per model while it is loaded, then capped by available RAM. Concurrent `/embed` calls round-robin across sessions. Raise this for parallel HTTP throughput; each extra session keeps another copy of the weights resident until idle unload. | | `EMBEDDING_INTRA_THREADS` | CPU count | ONNX Runtime intra-op threads per session. The default uses the whole machine on the single default session. When `EMBEDDING_POOL_SIZE` is greater than one, threads are split across sessions (`nproc / pool_size`, still capped by this value) so concurrent embeds do not oversubscribe the host. | | `EMBEDDING_IDLE_UNLOAD_SECS` | `300` | Drop a model's sessions this many seconds after last use (`0` disables). The next `/embed` reloads the same checkpoint from `EMBEDDING_CACHE_DIR`. | -| `EMBEDDING_MAX_TOKENS` | `2048` | Most tokens embedded per text; longer input is truncated. Each model also stops at its own context: `nomic` 8192, `embedding-gemma` 2048, `bge-small` 512, `all-minilm` 256. Memory grows with the square of this value: one nomic text peaks near 1.2 GB at 2048 and 3 GB at 4096, and 8192 did not fit in 5 GB. | +| `EMBEDDING_MAX_TOKENS` | `2048` | Most tokens allowed per text; longer input is rejected with `400`. Each model also has its own limit: `nomic` 8192, `embedding-gemma` 2048, `bge-small` 512, `all-minilm` 256. Memory grows with the square of this value: one nomic text peaks near 1.2 GB at 2048 and 3 GB at 4096, and 8192 did not fit in 5 GB. | ## API @@ -52,10 +52,8 @@ Response: } ``` -`tokens` is the number of tokens embedded, after truncation. - Errors: -- `400 Bad Request` — `texts` is empty or the model alias is not in `EMBEDDING_MODELS`. +- `400 Bad Request` — `texts` is empty, the model alias is not in `EMBEDDING_MODELS`, or a text is over the token limit. Split long input before sending it. - `500 Internal Server Error` — embedding or tokenizer failure (message in `error` field). - `503 Service Unavailable` — `GET /health` for 30 seconds after a model load has failed (message in `error` field).