From b384777cdacd04be0ab169a79a9b455044b2355b Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 5 Nov 2026 10:03:46 +0530 Subject: [PATCH 1/4] fix(embedding): disable the onnx memory arena on cpu sessions ONNX Runtime's default CPU arena keeps the high-water mark of every input shape for the life of the session, so a loaded nomic session holds its peak after each batch of long texts. CPU sessions now register the CPU provider with the arena disabled. GPU providers are unchanged. ort is pinned to the version fastembed uses so the provider type matches. --- Cargo.lock | 1 + Cargo.toml | 2 ++ src/embedding.rs | 34 ++++++++++++++++++++++++++-------- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6d7ee3d..7c3f0a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -589,6 +589,7 @@ dependencies = [ "fastembed", "futures", "hf-hub", + "ort", "serde", "serde_json", "sysinfo", diff --git a/Cargo.toml b/Cargo.toml index b95d91c..75d42f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,8 @@ axum = "0.8.7" fastembed = "5.15.0" futures = "0.3.32" hf-hub = "0.5.0" +# Pinned to the ort fastembed uses so the CPU provider type matches. +ort = { version = "=2.0.0-rc.13", default-features = false, features = ["std"] } serde = { version = "1.0.219", features = ["derive"] } serde_json = "1.0.145" sysinfo = "0.39.2" diff --git a/src/embedding.rs b/src/embedding.rs index 87fde29..967fcd7 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -47,6 +47,16 @@ fn default_pool_size() -> usize { 1 } +/// The configured GPU providers, or the CPU provider with ONNX Runtime's +/// memory arena disabled. The arena keeps the high-water mark of every input +/// shape for the life of the session, so long texts pin gigabytes. +fn execution_providers(config: &EmbeddingConfig) -> Vec { + if !config.execution_providers.is_empty() { + return config.execution_providers.clone(); + } + vec![ort::ep::CPU::default().with_arena_allocator(false).build()] +} + fn default_intra_threads() -> usize { available_cpus() } @@ -450,10 +460,9 @@ impl EmbeddingClient { let per_instance_loaded = mem_before_loading_model.saturating_sub(memory_after_loading_model); - // ONNX Runtime uses arena allocation that grows with - // batch_size × sequence_length² (attention matrices) and is never - // released. The warmup above only allocates a minimal arena for a - // single short text. Apply a 3× multiplier to account for realistic + // Inference memory grows with batch_size × sequence_length² + // (attention matrices). The warmup above only covers a single + // short text. Apply a 3× multiplier to account for realistic // inference workloads (batch=8-32 texts of 1000-2000 tokens each). let per_instance_bytes = per_instance_loaded.saturating_mul(3); @@ -585,10 +594,7 @@ impl EmbeddingClient { init_options = init_options.with_cache_dir(cache_dir.into()); } - if !config.execution_providers.is_empty() { - init_options = - init_options.with_execution_providers(config.execution_providers.clone()); - } + init_options = init_options.with_execution_providers(execution_providers(config)); TextEmbedding::try_new(init_options) .map_err(|e| format!("Failed to initialize embedding model: {}", e)) @@ -882,6 +888,18 @@ mod tests { assert_eq!(cfg.cache_dir.as_deref(), Some("/tmp/embedding-cache")); } + #[test] + fn cpu_sessions_register_the_cpu_provider() { + let _g = isolate_env(); + let providers = execution_providers(&EmbeddingConfig::from_env()); + assert_eq!(providers.len(), 1); + let provider = format!("{:?}", providers[0]); + assert!( + provider.starts_with("CPUExecutionProvider"), + "expected the CPU provider that disables the memory arena, got {provider}" + ); + } + #[test] fn from_env_parses_pool_size() { let _g = isolate_env(); From 1bf604f0068f70ca685dd6bb46dfd6ef36950d70 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 5 Nov 2026 10:03:46 +0530 Subject: [PATCH 2/4] ci: compare base and head memory on pull requests Builds the PR's base and head, runs the same long-text workload against each, and posts peak and retained RSS as a single updated PR comment. --- .github/workflows/memory-bench.yml | 90 +++++++++++++ scripts/bench_memory.py | 195 +++++++++++++++++++++++++++++ 2 files changed, 285 insertions(+) create mode 100644 .github/workflows/memory-bench.yml create mode 100644 scripts/bench_memory.py diff --git a/.github/workflows/memory-bench.yml b/.github/workflows/memory-bench.yml new file mode 100644 index 0000000..bc0a7cf --- /dev/null +++ b/.github/workflows/memory-bench.yml @@ -0,0 +1,90 @@ +name: Memory benchmark + +on: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: write + +env: + CARGO_TERM_COLOR: always + +jobs: + bench: + name: memory before vs after + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Check out base + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: base + + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable + + - uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + with: + key: memory-bench + + - name: Cache models + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: models + key: fastembed-models-nomic-v1 + + # Both builds share one target dir so dependencies compile once. + - name: Build base and head + run: | + mkdir -p bin + cargo build --release --manifest-path base/Cargo.toml --target-dir target --bin embedding + cp target/release/embedding bin/base + cargo build --release --bins + cp target/release/embedding bin/head + + - name: Download model + run: target/release/warmup + env: + EMBEDDING_MODELS: nomic + EMBEDDING_CACHE_DIR: ${{ github.workspace }}/models + + - name: Run benchmark + run: | + python3 scripts/bench_memory.py \ + --base bin/base --head bin/head \ + --cache-dir "$GITHUB_WORKSPACE/models" \ + --out bench.md + { + echo "" + echo "### Memory benchmark" + echo + echo "Base \`${BASE_SHA:0:7}\` vs head \`${HEAD_SHA:0:7}\` on \`ubuntu-latest\`." + echo + cat bench.md + } > comment.md + cat comment.md >> "$GITHUB_STEP_SUMMARY" + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + + # Fork PRs get a read-only token, so they only get the job summary. + - name: Comment on PR + if: github.event.pull_request.head.repo.full_name == github.repository + run: | + id=$(gh api "repos/$REPO/issues/$PR/comments" --paginate \ + -q '.[] | select(.body | startswith("")) | .id' | head -n1) + if [ -n "$id" ]; then + gh api -X PATCH "repos/$REPO/issues/comments/$id" -F body=@comment.md > /dev/null + else + gh pr comment "$PR" --repo "$REPO" --body-file comment.md + fi + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} diff --git a/scripts/bench_memory.py b/scripts/bench_memory.py new file mode 100644 index 0000000..778edd2 --- /dev/null +++ b/scripts/bench_memory.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Compare the memory of two embedding server binaries under the same load. + +Starts each binary, sends batches of long texts of varying length to /embed, +samples RSS, and prints a markdown table of peak and retained RSS. + + python3 scripts/bench_memory.py --base target/base --head target/head \ + --cache-dir models --out bench.md +""" + +import argparse +import json +import os +import random +import socket +import statistics +import subprocess +import sys +import threading +import time +import urllib.request + +WORDS = ( + "function return class public private static array string value index " + "query request response database" +).split() + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def rss_bytes(pid): + out = subprocess.run( + ["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True + ).stdout.strip() + return int(out) * 1024 if out else 0 + + +def workload(seed, batches, batch_size): + # Varying lengths so ONNX Runtime sees many input shapes. + rng = random.Random(seed) + return [ + [" ".join(rng.choices(WORDS, k=rng.randint(100, 1800))) for _ in range(batch_size)] + for _ in range(batches) + ] + + +def run(binary, args, concurrency): + port = free_port() + env = dict( + os.environ, + EMBEDDING_PORT=str(port), + EMBEDDING_MODELS=args.model, + EMBEDDING_POOL_SIZE=str(args.pool_size), + EMBEDDING_IDLE_UNLOAD_SECS="0", + EMBEDDING_CACHE_DIR=args.cache_dir, + RUST_LOG="warn", + ) + proc = subprocess.Popen([binary], env=env, stdout=subprocess.DEVNULL) + url = f"http://127.0.0.1:{port}" + peak = 0 + stop = threading.Event() + + def sample(): + nonlocal peak + while not stop.is_set(): + peak = max(peak, rss_bytes(proc.pid)) + time.sleep(0.1) + + def post(texts): + body = json.dumps({"model": args.model, "texts": texts}).encode() + req = urllib.request.Request( + url + "/embed", body, {"content-type": "application/json"} + ) + with urllib.request.urlopen(req, timeout=900) as resp: + json.load(resp) + + try: + for _ in range(300): + try: + urllib.request.urlopen(url + "/health", timeout=1).close() + break + except Exception: + if proc.poll() is not None: + sys.exit(f"{binary} exited with {proc.returncode}") + time.sleep(0.1) + else: + sys.exit(f"{binary} never became healthy") + + sampler = threading.Thread(target=sample, daemon=True) + sampler.start() + errors = [] + + def guarded(texts): + try: + post(texts) + except Exception as e: + errors.append(e) + + batches = workload(args.seed, args.batches, args.batch_size) + started = time.monotonic() + for i in range(0, len(batches), concurrency): + threads = [ + threading.Thread(target=guarded, args=(b,)) + for b in batches[i : i + concurrency] + ] + for t in threads: + t.start() + for t in threads: + t.join() + elapsed = time.monotonic() - started + if errors: + sys.exit(f"{binary}: /embed failed: {errors[0]}") + + time.sleep(args.settle) + retained = rss_bytes(proc.pid) + stop.set() + sampler.join() + return peak, retained, elapsed + finally: + stop.set() + proc.terminate() + proc.wait() + + +def mb(value): + return f"{value / 2**20:,.0f} MB" + + +def delta(base, head): + if base == 0: + return "n/a" + return f"{(head - base) / base * 100:+.0f}%" + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--base", required=True, help="baseline server binary") + p.add_argument("--head", required=True, help="candidate server binary") + p.add_argument("--cache-dir", required=True) + p.add_argument("--model", default="nomic") + p.add_argument("--pool-size", type=int, default=1) + p.add_argument("--concurrency", default="1,4", help="comma-separated scenarios") + p.add_argument("--reps", type=int, default=2) + p.add_argument("--batches", type=int, default=12) + p.add_argument("--batch-size", type=int, default=16) + p.add_argument("--settle", type=float, default=3.0) + p.add_argument("--seed", type=int, default=42) + p.add_argument("--out", help="also write the markdown table here") + args = p.parse_args() + + rows = [] + for conc in [int(c) for c in args.concurrency.split(",")]: + results = {} + for label, binary in (("base", args.base), ("head", args.head)): + reps = [] + for rep in range(args.reps): + peak, retained, elapsed = run(binary, args, conc) + print( + f"{label} conc={conc} rep={rep + 1}: peak={mb(peak)} " + f"retained={mb(retained)} time={elapsed:.1f}s", + file=sys.stderr, + ) + reps.append((peak, retained, elapsed)) + results[label] = [statistics.median(col) for col in zip(*reps)] + b, h = results["base"], results["head"] + rows.append( + f"| {conc} | {mb(b[0])} | {mb(h[0])} | {delta(b[0], h[0])} " + f"| {mb(b[1])} | {mb(h[1])} | {delta(b[1], h[1])} " + f"| {b[2]:.1f}s | {h[2]:.1f}s |" + ) + + table = "\n".join( + [ + f"Model `{args.model}`, `EMBEDDING_POOL_SIZE={args.pool_size}`, " + f"{args.batches} requests of {args.batch_size} texts (100 to 1,800 words), " + f"median of {args.reps} runs. Retained is RSS {args.settle:g}s after the last request.", + "", + "| Concurrent requests | Peak (base) | Peak (head) | Δ | Retained (base) " + "| Retained (head) | Δ | Time (base) | Time (head) |", + "|---|---|---|---|---|---|---|---|---|", + *rows, + ] + ) + print(table) + if args.out: + with open(args.out, "w") as f: + f.write(table + "\n") + + +if __name__ == "__main__": + main() From e27ddcab038df22aeb29eb3ad2b81ce45dac05ff Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 5 Nov 2026 10:09:00 +0530 Subject: [PATCH 3/4] ci: measure memory with a rust example instead of python The benchmark is now examples/bench_memory.rs, using sysinfo for RSS and ureq (dev-only, already in the tree via hf-hub) for HTTP, so CI needs no Python and the server binary gains no dependencies. --- .github/workflows/memory-bench.yml | 4 +- Cargo.lock | 1 + Cargo.toml | 4 + examples/bench_memory.rs | 303 +++++++++++++++++++++++++++++ scripts/bench_memory.py | 195 ------------------- 5 files changed, 310 insertions(+), 197 deletions(-) create mode 100644 examples/bench_memory.rs delete mode 100644 scripts/bench_memory.py diff --git a/.github/workflows/memory-bench.yml b/.github/workflows/memory-bench.yml index bc0a7cf..31d6d87 100644 --- a/.github/workflows/memory-bench.yml +++ b/.github/workflows/memory-bench.yml @@ -45,7 +45,7 @@ jobs: mkdir -p bin cargo build --release --manifest-path base/Cargo.toml --target-dir target --bin embedding cp target/release/embedding bin/base - cargo build --release --bins + cargo build --release --bins --example bench_memory cp target/release/embedding bin/head - name: Download model @@ -56,7 +56,7 @@ jobs: - name: Run benchmark run: | - python3 scripts/bench_memory.py \ + target/release/examples/bench_memory \ --base bin/base --head bin/head \ --cache-dir "$GITHUB_WORKSPACE/models" \ --out bench.md diff --git a/Cargo.lock b/Cargo.lock index 7c3f0a6..503ff6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -598,6 +598,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "ureq", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 75d42f2..02efe4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,3 +20,7 @@ tracing-subscriber = { version = "0.3.20", features = ["env-filter"] } [target.'cfg(not(target_env = "msvc"))'.dependencies] tikv-jemallocator = { version = "0.6", features = ["override_allocator_on_supported_platforms"] } + +[dev-dependencies] +# HTTP client for examples/bench_memory.rs; already in the tree via hf-hub. +ureq = { version = "3.3.0", default-features = false } diff --git a/examples/bench_memory.rs b/examples/bench_memory.rs new file mode 100644 index 0000000..5856e43 --- /dev/null +++ b/examples/bench_memory.rs @@ -0,0 +1,303 @@ +//! Compare the memory of two embedding server binaries under the same load. +//! +//! Starts each binary, sends batches of long texts of varying length to +//! /embed, samples RSS, and prints a markdown table of peak and retained RSS. +//! +//! cargo run --release --example bench_memory -- \ +//! --base bin/base --head bin/head --cache-dir models --out bench.md + +use std::net::TcpListener; +use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::thread; +use std::time::{Duration, Instant}; + +use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System}; + +const WORDS: &[&str] = &[ + "function", "return", "class", "public", "private", "static", "array", "string", "value", + "index", "query", "request", "response", "database", +]; + +struct Args { + base: String, + head: String, + cache_dir: String, + model: String, + pool_size: usize, + concurrency: Vec, + reps: usize, + batches: usize, + batch_size: usize, + settle_secs: u64, + seed: u64, + out: Option, +} + +impl Args { + fn parse() -> Result { + let mut args = Args { + base: String::new(), + head: String::new(), + cache_dir: String::new(), + model: "nomic".into(), + pool_size: 1, + concurrency: vec![1, 4], + reps: 2, + batches: 12, + batch_size: 16, + settle_secs: 3, + seed: 42, + out: None, + }; + let mut it = std::env::args().skip(1); + while let Some(flag) = it.next() { + let value = it.next().ok_or(format!("{flag} needs a value"))?; + let num = |v: &str| v.parse::().map_err(|e| format!("{flag}: {e}")); + match flag.as_str() { + "--base" => args.base = value, + "--head" => args.head = value, + "--cache-dir" => args.cache_dir = value, + "--model" => args.model = value, + "--pool-size" => args.pool_size = num(&value)? as usize, + "--concurrency" => { + args.concurrency = value + .split(',') + .map(|c| num(c.trim()).map(|n| n.max(1) as usize)) + .collect::>()? + } + "--reps" => args.reps = num(&value)?.max(1) as usize, + "--batches" => args.batches = num(&value)? as usize, + "--batch-size" => args.batch_size = num(&value)? as usize, + "--settle" => args.settle_secs = num(&value)?, + "--seed" => args.seed = num(&value)?, + "--out" => args.out = Some(value), + _ => return Err(format!("unknown flag {flag}")), + } + } + if args.base.is_empty() || args.head.is_empty() || args.cache_dir.is_empty() { + return Err("--base, --head and --cache-dir are required".into()); + } + Ok(args) + } +} + +struct Sample { + peak: u64, + retained: u64, + elapsed: Duration, +} + +/// xorshift64 so the workload is identical for base and head without a rand dependency. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn range(&mut self, lo: usize, hi: usize) -> usize { + lo + (self.next() % (hi - lo + 1) as u64) as usize + } +} + +// Varying lengths so ONNX Runtime sees many input shapes. +fn workload(args: &Args) -> Vec> { + let mut rng = Rng(args.seed.max(1)); + (0..args.batches) + .map(|_| { + (0..args.batch_size) + .map(|_| { + let len = rng.range(100, 1800); + (0..len) + .map(|_| WORDS[rng.range(0, WORDS.len() - 1)]) + .collect::>() + .join(" ") + }) + .collect() + }) + .collect() +} + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .and_then(|l| l.local_addr()) + .map(|a| a.port()) + .expect("bind a free port") +} + +fn rss(sys: &mut System, pid: Pid) -> u64 { + sys.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid]), + true, + ProcessRefreshKind::nothing().with_memory(), + ); + sys.process(pid).map(|p| p.memory()).unwrap_or(0) +} + +struct Server(Child); + +impl Drop for Server { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +fn run(binary: &str, args: &Args, batches: &[Vec], concurrency: usize) -> Sample { + let port = free_port(); + let mut server = Server( + Command::new(binary) + .env("EMBEDDING_PORT", port.to_string()) + .env("EMBEDDING_MODELS", &args.model) + .env("EMBEDDING_POOL_SIZE", args.pool_size.to_string()) + .env("EMBEDDING_IDLE_UNLOAD_SECS", "0") + .env("EMBEDDING_CACHE_DIR", &args.cache_dir) + .env("RUST_LOG", "warn") + .stdout(Stdio::null()) + .spawn() + .unwrap_or_else(|e| panic!("start {binary}: {e}")), + ); + let pid = Pid::from_u32(server.0.id()); + let url = format!("http://127.0.0.1:{port}"); + + let deadline = Instant::now() + Duration::from_secs(30); + while ureq::get(format!("{url}/health")).call().is_err() { + if let Ok(Some(status)) = server.0.try_wait() { + panic!("{binary} exited with {status}"); + } + assert!(Instant::now() < deadline, "{binary} never became healthy"); + thread::sleep(Duration::from_millis(100)); + } + + let peak = AtomicU64::new(0); + let done = AtomicBool::new(false); + let errors = Mutex::new(Vec::new()); + let mut elapsed = Duration::ZERO; + + thread::scope(|s| { + s.spawn(|| { + let mut sys = System::new(); + while !done.load(Ordering::Relaxed) { + peak.fetch_max(rss(&mut sys, pid), Ordering::Relaxed); + thread::sleep(Duration::from_millis(100)); + } + }); + + let started = Instant::now(); + let (url, errors) = (&url, &errors); + for chunk in batches.chunks(concurrency) { + thread::scope(|inner| { + for texts in chunk { + inner.spawn(move || { + let body = serde_json::json!({ "model": args.model, "texts": texts }); + let result = ureq::post(format!("{url}/embed")) + .header("content-type", "application/json") + .send(body.to_string()) + .and_then(|mut r| r.body_mut().read_to_string()); + if let Err(e) = result { + errors.lock().unwrap().push(e.to_string()); + } + }); + } + }); + } + elapsed = started.elapsed(); + done.store(true, Ordering::Relaxed); + }); + + if let Some(e) = errors.lock().unwrap().first() { + panic!("{binary}: /embed failed: {e}"); + } + + thread::sleep(Duration::from_secs(args.settle_secs)); + let retained = rss(&mut System::new(), pid); + Sample { + peak: peak.into_inner().max(retained), + retained, + elapsed, + } +} + +fn median(mut values: Vec) -> T { + values.sort_by(|a, b| a.partial_cmp(b).unwrap()); + values[values.len() / 2] +} + +fn mb(bytes: u64) -> String { + format!("{} MB", bytes / (1024 * 1024)) +} + +fn delta(base: u64, head: u64) -> String { + if base == 0 { + return "n/a".into(); + } + format!("{:+.0}%", (head as f64 - base as f64) / base as f64 * 100.0) +} + +fn main() { + let args = Args::parse().unwrap_or_else(|e| { + eprintln!("bench_memory: {e}"); + std::process::exit(2); + }); + let batches = workload(&args); + + let mut rows = Vec::new(); + for &concurrency in &args.concurrency { + let mut medians = Vec::new(); + for (label, binary) in [("base", &args.base), ("head", &args.head)] { + let samples: Vec = (1..=args.reps) + .map(|rep| { + let s = run(binary, &args, &batches, concurrency); + eprintln!( + "{label} concurrency={concurrency} rep={rep}: peak={} retained={} time={:.1}s", + mb(s.peak), + mb(s.retained), + s.elapsed.as_secs_f64() + ); + s + }) + .collect(); + medians.push(( + median(samples.iter().map(|s| s.peak).collect()), + median(samples.iter().map(|s| s.retained).collect()), + median(samples.iter().map(|s| s.elapsed.as_secs_f64()).collect()), + )); + } + let (b, h) = (medians[0], medians[1]); + rows.push(format!( + "| {concurrency} | {} | {} | {} | {} | {} | {} | {:.1}s | {:.1}s |", + mb(b.0), + mb(h.0), + delta(b.0, h.0), + mb(b.1), + mb(h.1), + delta(b.1, h.1), + b.2, + h.2 + )); + } + + let table = format!( + "Model `{}`, `EMBEDDING_POOL_SIZE={}`, {} requests of {} texts (100 to 1,800 words), \ + median of {} runs. Retained is RSS {}s after the last request.\n\n\ + | Concurrent requests | Peak (base) | Peak (head) | Δ | Retained (base) \ + | Retained (head) | Δ | Time (base) | Time (head) |\n\ + |---|---|---|---|---|---|---|---|---|\n{}\n", + args.model, + args.pool_size, + args.batches, + args.batch_size, + args.reps, + args.settle_secs, + rows.join("\n") + ); + print!("{table}"); + if let Some(out) = &args.out { + std::fs::write(out, &table).unwrap_or_else(|e| panic!("write {out}: {e}")); + } +} diff --git a/scripts/bench_memory.py b/scripts/bench_memory.py deleted file mode 100644 index 778edd2..0000000 --- a/scripts/bench_memory.py +++ /dev/null @@ -1,195 +0,0 @@ -#!/usr/bin/env python3 -"""Compare the memory of two embedding server binaries under the same load. - -Starts each binary, sends batches of long texts of varying length to /embed, -samples RSS, and prints a markdown table of peak and retained RSS. - - python3 scripts/bench_memory.py --base target/base --head target/head \ - --cache-dir models --out bench.md -""" - -import argparse -import json -import os -import random -import socket -import statistics -import subprocess -import sys -import threading -import time -import urllib.request - -WORDS = ( - "function return class public private static array string value index " - "query request response database" -).split() - - -def free_port(): - with socket.socket() as s: - s.bind(("127.0.0.1", 0)) - return s.getsockname()[1] - - -def rss_bytes(pid): - out = subprocess.run( - ["ps", "-o", "rss=", "-p", str(pid)], capture_output=True, text=True - ).stdout.strip() - return int(out) * 1024 if out else 0 - - -def workload(seed, batches, batch_size): - # Varying lengths so ONNX Runtime sees many input shapes. - rng = random.Random(seed) - return [ - [" ".join(rng.choices(WORDS, k=rng.randint(100, 1800))) for _ in range(batch_size)] - for _ in range(batches) - ] - - -def run(binary, args, concurrency): - port = free_port() - env = dict( - os.environ, - EMBEDDING_PORT=str(port), - EMBEDDING_MODELS=args.model, - EMBEDDING_POOL_SIZE=str(args.pool_size), - EMBEDDING_IDLE_UNLOAD_SECS="0", - EMBEDDING_CACHE_DIR=args.cache_dir, - RUST_LOG="warn", - ) - proc = subprocess.Popen([binary], env=env, stdout=subprocess.DEVNULL) - url = f"http://127.0.0.1:{port}" - peak = 0 - stop = threading.Event() - - def sample(): - nonlocal peak - while not stop.is_set(): - peak = max(peak, rss_bytes(proc.pid)) - time.sleep(0.1) - - def post(texts): - body = json.dumps({"model": args.model, "texts": texts}).encode() - req = urllib.request.Request( - url + "/embed", body, {"content-type": "application/json"} - ) - with urllib.request.urlopen(req, timeout=900) as resp: - json.load(resp) - - try: - for _ in range(300): - try: - urllib.request.urlopen(url + "/health", timeout=1).close() - break - except Exception: - if proc.poll() is not None: - sys.exit(f"{binary} exited with {proc.returncode}") - time.sleep(0.1) - else: - sys.exit(f"{binary} never became healthy") - - sampler = threading.Thread(target=sample, daemon=True) - sampler.start() - errors = [] - - def guarded(texts): - try: - post(texts) - except Exception as e: - errors.append(e) - - batches = workload(args.seed, args.batches, args.batch_size) - started = time.monotonic() - for i in range(0, len(batches), concurrency): - threads = [ - threading.Thread(target=guarded, args=(b,)) - for b in batches[i : i + concurrency] - ] - for t in threads: - t.start() - for t in threads: - t.join() - elapsed = time.monotonic() - started - if errors: - sys.exit(f"{binary}: /embed failed: {errors[0]}") - - time.sleep(args.settle) - retained = rss_bytes(proc.pid) - stop.set() - sampler.join() - return peak, retained, elapsed - finally: - stop.set() - proc.terminate() - proc.wait() - - -def mb(value): - return f"{value / 2**20:,.0f} MB" - - -def delta(base, head): - if base == 0: - return "n/a" - return f"{(head - base) / base * 100:+.0f}%" - - -def main(): - p = argparse.ArgumentParser() - p.add_argument("--base", required=True, help="baseline server binary") - p.add_argument("--head", required=True, help="candidate server binary") - p.add_argument("--cache-dir", required=True) - p.add_argument("--model", default="nomic") - p.add_argument("--pool-size", type=int, default=1) - p.add_argument("--concurrency", default="1,4", help="comma-separated scenarios") - p.add_argument("--reps", type=int, default=2) - p.add_argument("--batches", type=int, default=12) - p.add_argument("--batch-size", type=int, default=16) - p.add_argument("--settle", type=float, default=3.0) - p.add_argument("--seed", type=int, default=42) - p.add_argument("--out", help="also write the markdown table here") - args = p.parse_args() - - rows = [] - for conc in [int(c) for c in args.concurrency.split(",")]: - results = {} - for label, binary in (("base", args.base), ("head", args.head)): - reps = [] - for rep in range(args.reps): - peak, retained, elapsed = run(binary, args, conc) - print( - f"{label} conc={conc} rep={rep + 1}: peak={mb(peak)} " - f"retained={mb(retained)} time={elapsed:.1f}s", - file=sys.stderr, - ) - reps.append((peak, retained, elapsed)) - results[label] = [statistics.median(col) for col in zip(*reps)] - b, h = results["base"], results["head"] - rows.append( - f"| {conc} | {mb(b[0])} | {mb(h[0])} | {delta(b[0], h[0])} " - f"| {mb(b[1])} | {mb(h[1])} | {delta(b[1], h[1])} " - f"| {b[2]:.1f}s | {h[2]:.1f}s |" - ) - - table = "\n".join( - [ - f"Model `{args.model}`, `EMBEDDING_POOL_SIZE={args.pool_size}`, " - f"{args.batches} requests of {args.batch_size} texts (100 to 1,800 words), " - f"median of {args.reps} runs. Retained is RSS {args.settle:g}s after the last request.", - "", - "| Concurrent requests | Peak (base) | Peak (head) | Δ | Retained (base) " - "| Retained (head) | Δ | Time (base) | Time (head) |", - "|---|---|---|---|---|---|---|---|---|", - *rows, - ] - ) - print(table) - if args.out: - with open(args.out, "w") as f: - f.write(table + "\n") - - -if __name__ == "__main__": - main() From fb7466c677203c0f581f1a0aa02d379b43f22140 Mon Sep 17 00:00:00 2001 From: ArnabChatterjee20k Date: Thu, 5 Nov 2026 18:25:52 +0530 Subject: [PATCH 4/4] test(embedding): assert the cpu provider disables the memory arena The previous assertion only checked the provider name, which the dispatch Debug output exposes, so it passed even with the arena enabled. Downcast to ort::ep::CPU and check use_arena instead. Co-Authored-By: Claude Opus 5.5 --- src/embedding.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/embedding.rs b/src/embedding.rs index 967fcd7..33d5278 100644 --- a/src/embedding.rs +++ b/src/embedding.rs @@ -889,14 +889,18 @@ mod tests { } #[test] - fn cpu_sessions_register_the_cpu_provider() { + fn cpu_sessions_disable_the_memory_arena() { let _g = isolate_env(); let providers = execution_providers(&EmbeddingConfig::from_env()); assert_eq!(providers.len(), 1); - let provider = format!("{:?}", providers[0]); + let cpu = providers[0] + .downcast_ref::() + .expect("expected the CPU execution provider"); + // `use_arena` is private, so read it through the derived Debug output. + let cpu = format!("{cpu:?}"); assert!( - provider.starts_with("CPUExecutionProvider"), - "expected the CPU provider that disables the memory arena, got {provider}" + cpu.contains("use_arena: false"), + "expected the CPU memory arena to be disabled, got {cpu}" ); }