From f07302b944e36cb8488b61bfbd2f7d55ec49c9d8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 15 Oct 2026 00:48:48 +0200 Subject: [PATCH] feat: admit GPU prefills by free memory; the worker falls back to the CPU for that prompt (STRA-219) PrefillAccelerator::admit lets an accelerator refuse a prompt without being disabled. The GPU prefill estimates its footprint (two layers of weights, scratch, hidden states, caches, 1 GiB headroom; 1.6 GiB estimated vs 2.0 GiB peak private bytes measured for 1024 tokens before the headroom was raised) and compares it with a probe; the worker's probe is the OS's available memory (sysinfo). admission_check exercises both outcomes on the real model. 1024-token prefill with the vec4 attention: 15.9 s (64.5 tok/s), single unpaired run. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + .../gptoss-igpu/examples/admission_check.rs | 52 ++++++++++++++ crates/gptoss-igpu/examples/gpu_prefill.rs | 10 ++- crates/gptoss-igpu/src/lib.rs | 67 +++++++++++++++++++ crates/gptoss/src/lib.rs | 8 ++- crates/igpu-worker/Cargo.toml | 1 + crates/igpu-worker/src/main.rs | 12 +++- docs/igpu-prefill.md | 11 ++- 8 files changed, 156 insertions(+), 6 deletions(-) create mode 100644 crates/gptoss-igpu/examples/admission_check.rs diff --git a/Cargo.lock b/Cargo.lock index 12fc04b8..d1ce0954 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1326,6 +1326,7 @@ version = "0.1.0" dependencies = [ "leleka-cpu-worker", "leleka-gptoss-igpu", + "sysinfo", ] [[package]] diff --git a/crates/gptoss-igpu/examples/admission_check.rs b/crates/gptoss-igpu/examples/admission_check.rs new file mode 100644 index 00000000..2556f0b0 --- /dev/null +++ b/crates/gptoss-igpu/examples/admission_check.rs @@ -0,0 +1,52 @@ +//! The memory admission of the GPU prefill: with a probe that reports too little memory the prompt must go +//! down the CPU path (no GPU timings, one refusal counted); with plenty it must use the GPU. +//! +//! Run: `cargo run --release -p leleka-gptoss-igpu --example admission_check -- ` + +use leleka_cpu_kernels::Dispatch; +use leleka_cpu_sys::mapping::Mapping; +use leleka_gguf::Gguf; +use leleka_gptoss::{Model, PrefillAccelerator, State}; +use leleka_gptoss_igpu::GpuPrefill; +use std::fs::File; +use std::io::BufReader; +use std::path::Path; + +fn main() { + let path = std::env::args().nth(1).expect("model path"); + let path = Path::new(&path); + let size = std::fs::metadata(path).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(path).expect("open")), + size, + ) + .expect("valid GGUF"); + let model = Model::load( + std::sync::Arc::new(Mapping::open(path).expect("map model")), + &gguf, + Dispatch::from_env().expect("kernel level"), + 4, + ) + .expect("load model"); + let prompt: Vec = (0..40u32).map(|i| 1000 + i * 37).collect(); + for (label, available) in [ + ("too little (100 MiB)", 100u64 << 20), + ("plenty (64 GiB)", 64 << 30), + ] { + let mut accel = GpuPrefill::new() + .expect("a GPU") + .with_memory_probe(Box::new(move || Some(available))); + let admitted = accel.admit(&model, prompt.len()); + let mut state = State::new(&model.config, 64); + let reuse = model + .prefill_reuse_accelerated(&mut state, &prompt, &mut accel, 1, &mut |_, _| true) + .expect("prefill") + .expect("not cancelled"); + println!( + "{label}: admitted {admitted}, refused so far {}, GPU tokens {}, next token {}", + accel.refused(), + accel.timings().tokens, + reuse.next + ); + } +} diff --git a/crates/gptoss-igpu/examples/gpu_prefill.rs b/crates/gptoss-igpu/examples/gpu_prefill.rs index db5b7537..3315a269 100644 --- a/crates/gptoss-igpu/examples/gpu_prefill.rs +++ b/crates/gptoss-igpu/examples/gpu_prefill.rs @@ -68,6 +68,10 @@ fn main() { if std::env::var_os("LELEKA_SKIP_CPU").is_some() { // GPU timing only (long prompts, where the CPU run would take minutes) let mut accel = GpuPrefill::new().expect("a GPU").with_batch(batch); + println!( + "estimated memory for this prompt: {} MiB", + accel.estimate_bytes(&model, prompt.len()) >> 20 + ); let mut state = State::new(&model.config, capacity); let t = Instant::now(); let reuse = model @@ -101,7 +105,11 @@ fn main() { // GPU let mut accel = GpuPrefill::new().expect("a GPU").with_batch(batch); - println!("gpu: {}, batch {batch}", accel.adapter_name()); + println!( + "gpu: {}, batch {batch}, estimated memory for this prompt {} MiB", + accel.adapter_name(), + accel.estimate_bytes(&model, prompt.len()) >> 20 + ); let mut gpu_state = State::new(&model.config, capacity); let t = Instant::now(); let gpu_reuse = model diff --git a/crates/gptoss-igpu/src/lib.rs b/crates/gptoss-igpu/src/lib.rs index e6de40ca..b140c1d1 100644 --- a/crates/gptoss-igpu/src/lib.rs +++ b/crates/gptoss-igpu/src/lib.rs @@ -58,8 +58,14 @@ pub struct GpuPrefill { gpu: Gpu, batch: usize, timings: Timings, + /// Free memory in bytes, when the caller can tell (see [`GpuPrefill::with_memory_probe`]). + memory_probe: Option, + refused: usize, } +/// Reports the memory that can be used without paging (the OS's "available" figure). +pub type MemoryProbe = Box Option + Send>; + fn gpu_error(e: GpuError) -> ModelError { ModelError::Invalid(format!("GPU: {e}")) } @@ -146,6 +152,8 @@ impl GpuPrefill { gpu: Gpu::new()?, batch: DEFAULT_BATCH, timings: Timings::default(), + memory_probe: None, + refused: 0, }) } @@ -156,6 +164,46 @@ impl GpuPrefill { self } + /// Admit a GPU prefill only while `probe` reports enough free memory for it (see + /// [`GpuPrefill::estimate_bytes`]); otherwise the request is left to the CPU path. The GPU's memory is the + /// system's memory, so an unrestricted prefill could push the model's pages out. + pub fn with_memory_probe(mut self, probe: MemoryProbe) -> Self { + self.memory_probe = Some(probe); + self + } + + /// Prefills refused for lack of memory so far. + pub fn refused(&self) -> usize { + self.refused + } + + /// A conservative estimate of the memory a prefill of `tokens` tokens uses: two layers of weights (one in + /// use, one being built) plus the largest matrix while it is repacked, the batch scratch buffers, the + /// hidden states, the key and value caches of one layer, and 512 MiB of headroom. + pub fn estimate_bytes(&self, model: &Model, tokens: usize) -> u64 { + let c = &model.config; + let layer = model.layer_view(0); + let matrices = [ + &layer.wq, + &layer.wk, + &layer.wv, + &layer.wo, + &layer.gate, + &layer.up, + &layer.down, + ]; + let layer_bytes: usize = matrices.iter().map(|m| m.data.len()).sum(); + let largest = matrices.iter().map(|m| m.data.len()).max().unwrap_or(0); + let batch = self.batch.min(tokens); + let entries = batch * c.n_expert_used; + let scratch = 4 + * (batch * (2 * c.n_embd + 3 * c.q_width() + 2 * c.kv_width()) + + entries * (2 * c.n_ff + c.n_embd)); + let hidden = tokens * c.n_embd * 4; + let caches = tokens * c.kv_width() * 2 * 2; + (2 * layer_bytes + largest + scratch + hidden + caches + (1024 << 20)) as u64 + } + pub fn adapter_name(&self) -> String { self.gpu.adapter_name() } @@ -218,6 +266,25 @@ impl PrefillAccelerator for GpuPrefill { ) -> Result>, ModelError> { self.run(model, state, tokens, pos0, progress, false) } + fn admit(&mut self, model: &Model, tokens: usize) -> bool { + let Some(probe) = self.memory_probe.as_ref() else { + return true; + }; + let Some(available) = probe() else { + return true; // the probe cannot tell: do not block the GPU on that + }; + let needed = self.estimate_bytes(model, tokens); + let admitted = available >= needed; + if !admitted { + self.refused += 1; + eprintln!( + "leleka-gptoss-igpu: GPU prefill of {tokens} tokens needs about {} MiB and {} MiB are available; using the CPU for this prompt", + needed >> 20, + available >> 20 + ); + } + admitted + } } impl GpuPrefill { diff --git a/crates/gptoss/src/lib.rs b/crates/gptoss/src/lib.rs index 395f0392..0c4dc40d 100644 --- a/crates/gptoss/src/lib.rs +++ b/crates/gptoss/src/lib.rs @@ -655,6 +655,12 @@ pub trait PrefillAccelerator { pos0: usize, progress: &mut dyn FnMut(f64) -> bool, ) -> Result>, ModelError>; + + /// Whether a prefill of `tokens` tokens can start now (enough free memory, say). When it cannot, this + /// request takes the CPU path and the accelerator stays in use for later ones. + fn admit(&mut self, _model: &Model, _tokens: usize) -> bool { + true + } } /// What [`Model::prefill_reuse`] did. @@ -926,7 +932,7 @@ impl Model { .take_while(|(a, b)| a == b) .count(); let reused = common.min(prompt.len() - 1); - if prompt.len() - reused < min_tokens { + if prompt.len() - reused < min_tokens || !accelerator.admit(self, prompt.len() - reused) { return self.prefill_reuse_with(state, prompt, progress); } state.truncate(reused); diff --git a/crates/igpu-worker/Cargo.toml b/crates/igpu-worker/Cargo.toml index 1f355522..16337f1b 100644 --- a/crates/igpu-worker/Cargo.toml +++ b/crates/igpu-worker/Cargo.toml @@ -13,6 +13,7 @@ path = "src/main.rs" [dependencies] leleka-cpu-worker = { path = "../cpu-worker" } leleka-gptoss-igpu = { path = "../gptoss-igpu" } +sysinfo = { version = "0.39.6", default-features = false, features = ["system"] } [lints] workspace = true diff --git a/crates/igpu-worker/src/main.rs b/crates/igpu-worker/src/main.rs index bf867f31..768145cc 100644 --- a/crates/igpu-worker/src/main.rs +++ b/crates/igpu-worker/src/main.rs @@ -107,7 +107,10 @@ fn main() -> ExitCode { args.gpu_batch ); engine.set_accelerator( - Box::new(gpu.with_batch(args.gpu_batch)), + Box::new( + gpu.with_batch(args.gpu_batch) + .with_memory_probe(Box::new(available_memory)), + ), args.gpu_min_tokens, ); } @@ -128,3 +131,10 @@ fn main() -> ExitCode { } } } + +/// Memory the OS can hand out without paging (free plus reclaimable cache), in bytes. +fn available_memory() -> Option { + let mut system = sysinfo::System::new(); + system.refresh_memory(); + Some(system.available_memory()).filter(|bytes| *bytes > 0) +} diff --git a/docs/igpu-prefill.md b/docs/igpu-prefill.md index eb06386b..d563ebfe 100644 --- a/docs/igpu-prefill.md +++ b/docs/igpu-prefill.md @@ -89,6 +89,11 @@ ones and all decoding run on the CPU. With no usable GPU it says so on standard a GPU prefill fails the request is redone on the CPU and the GPU is not used again in that session. The control plane starts it like any worker (set the worker executable to this binary). -Not done yet: admission by free RAM (the GPU path needs about 2 GB of device memory beside the model mapping at -batch 512, and the repacking thread competes with the GPU for memory bandwidth), and an A/B run of a full agent -workload through the control plane. +Memory admission: the GPU's memory is the system's memory, so before each GPU prefill the worker compares the +OS's "available" figure with an estimate (two layers of weights, batch scratch, hidden states, caches, 1 GiB +headroom: about 2 GiB for a 40-token prompt, 1.6 GiB + headroom for 1024 tokens measured against 2.0 GiB peak +private bytes) and sends the request down the CPU path, with a line on standard error, when it does not fit; the +GPU stays in use for later requests (`PrefillAccelerator::admit`, `examples/admission_check.rs`). + +Not done yet: an A/B run of a full agent workload through the control plane at the charter's required +measurement detail.