diff --git a/.github/workflows/memory-bench.yml b/.github/workflows/memory-bench.yml new file mode 100644 index 0000000..31d6d87 --- /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 --example bench_memory + 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: | + target/release/examples/bench_memory \ + --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/Cargo.lock b/Cargo.lock index 6d7ee3d..503ff6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -589,6 +589,7 @@ dependencies = [ "fastembed", "futures", "hf-hub", + "ort", "serde", "serde_json", "sysinfo", @@ -597,6 +598,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "ureq", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b95d91c..02efe4d 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" @@ -18,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/src/embedding.rs b/src/embedding.rs index 87fde29..33d5278 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,22 @@ mod tests { assert_eq!(cfg.cache_dir.as_deref(), Some("/tmp/embedding-cache")); } + #[test] + fn cpu_sessions_disable_the_memory_arena() { + let _g = isolate_env(); + let providers = execution_providers(&EmbeddingConfig::from_env()); + assert_eq!(providers.len(), 1); + 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!( + cpu.contains("use_arena: false"), + "expected the CPU memory arena to be disabled, got {cpu}" + ); + } + #[test] fn from_env_parses_pool_size() { let _g = isolate_env();