From c9713c8bc1d7137319c77f1f03aa1bf02d54f4a4 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 20:02:33 +0100 Subject: [PATCH] [HIP][LD][GW] Bound VRAM across requests: unpooled KV + FP16 serve KV + bucketed flash scratch Federico saw VRAM grow ~7 GiB per agent step (44.9/48 GiB, near OOM). Root cause: the KV cache scales with max_seq=prompt+max_new (varies per request) and the exact-size DeviceBuf pool retained every distinct KV size, so a multi-turn chat accumulated KV without bound. The full-attn flash scores scratch (n_win grows per token) leaked similarly. - DeviceBuf gains a 'pooled' flag + alloc_unpooled(): always hipFree on drop, never pooled. KV (k_cache/v_cache) uses it -> freed at request end, no accumulation. Per-token fixed-size intermediates stay pooled (decode speed). - flash_scores_scratch buckets the allocation to a power of two so the pool reuses it as cur_pos grows (kernel still strides by actual n_win <= bucket). - KV dtype: FP16 for the resident serve (exact strata KvDtype::FP16 default, parity-verified EXACT, half the VRAM of F32). Safe process-wide switch set_kv_f16(); InklingEngine::new opts in. The ld CPU-oracle parity tests keep the F32 default (VETTA_F32_KV=1 also forces F32). Measured (new binary, 3 requests of 200/400/600 prompt tokens): VRAM 7.66 -> 8.07 -> 8.33 GiB (small bounded expert lazy-load growth, NOT +7 GiB/step); clean release to 0.34 GiB on QUIT. Parity EXACT (16 tok); 18 ld + 18 hip + 5 gw GPU green; workspace -D warnings green; 5 Lean 0 sorryAx. --- crates/vetta-infer-gw/src/serve.rs | 4 ++ crates/vetta-infer-hip/src/lib.rs | 62 +++++++++++++++++++++--------- crates/vetta-infer-ld/src/layer.rs | 24 ++++++++++-- 3 files changed, 68 insertions(+), 22 deletions(-) diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index 1c5a3dc..20a40ae 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -63,6 +63,10 @@ pub struct InklingEngine { impl InklingEngine { /// Load the archive + `config.json` and derive the forward dimensions. pub fn new(dir: &str) -> Result { + // Production KV dtype: FP16 (exact strata default, parity-verified EXACT, + // half the VRAM of the F32 CPU-oracle baseline). The ld parity tests keep + // the F32 default; the resident serve opts in here. + vetta_infer_ld::layer::set_kv_f16(true); let ar = SafetensorsArchive::open(dir)?; let cfg_path = ar.dir.join("config.json"); let raw = std::fs::read_to_string(&cfg_path) diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 01b001c..1afdbed 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -136,6 +136,10 @@ pub fn query_device(dev_id: i32) -> Option { pub struct DeviceBuf { pub ptr: *mut std::os::raw::c_void, pub bytes: usize, + /// Whether drop returns this buffer to the size-bucketed pool. Large + /// per-request buffers whose size varies (KV cache) are unpooled so they are + /// truly freed instead of accumulating every distinct size in the pool. + pooled: bool, } // Size-bucketed free list of device buffers. The layer forward allocates and @@ -171,29 +175,46 @@ fn pool_enabled() -> bool { && std::env::var("VETTA_NO_BUF_POOL").is_err() } +/// Set the blocking host-wait schedule once, before the first hipMalloc creates +/// the device context, so GPU waits sleep instead of spinning at 100% CPU (exact +/// strata --hip-sync blocking). Escape hatch VETTA_NO_BLOCKING_SYNC=1 keeps the +/// ROCm default spin schedule (for A/B CPU measurement). +#[cfg(feature = "hip")] +fn ensure_sync_init() { + static SYNC_INIT: std::sync::Once = std::sync::Once::new(); + SYNC_INIT.call_once(|| unsafe { + if std::env::var("VETTA_NO_BLOCKING_SYNC").is_err() { + ffi::vetta_hip_init_blocking_sync(); + } + }); +} + +#[cfg(feature = "hip")] +fn raw_alloc(bytes: usize) -> Result<*mut std::os::raw::c_void, String> { + let mut ptr: *mut std::os::raw::c_void = std::ptr::null_mut(); + let rc = unsafe { ffi::vetta_buf_alloc(&mut ptr, bytes) }; + if rc != 0 || ptr.is_null() { return Err(format!("hipMalloc({bytes}) failed")); } + Ok(ptr) +} + #[cfg(feature = "hip")] impl DeviceBuf { pub fn alloc(bytes: usize) -> Result { - // Set the blocking host-wait schedule once, before the first hipMalloc - // creates the device context, so GPU waits sleep instead of spinning at - // 100% CPU (exact strata --hip-sync blocking). - static SYNC_INIT: std::sync::Once = std::sync::Once::new(); - SYNC_INIT.call_once(|| unsafe { - // Escape hatch VETTA_NO_BLOCKING_SYNC=1 keeps the ROCm default spin - // schedule (for A/B CPU measurement). - if std::env::var("VETTA_NO_BLOCKING_SYNC").is_err() { - ffi::vetta_hip_init_blocking_sync(); - } - }); + ensure_sync_init(); if pool_enabled() { if let Some(ptr) = BUF_POOL.with(|p| p.borrow_mut().get_mut(&bytes).and_then(|v| v.pop())) { - return Ok(Self { ptr, bytes }); + return Ok(Self { ptr, bytes, pooled: true }); } } - let mut ptr: *mut std::os::raw::c_void = std::ptr::null_mut(); - let rc = unsafe { ffi::vetta_buf_alloc(&mut ptr, bytes) }; - if rc != 0 || ptr.is_null() { return Err(format!("hipMalloc({bytes}) failed")); } - Ok(Self { ptr, bytes }) + Ok(Self { ptr: raw_alloc(bytes)?, bytes, pooled: true }) + } + /// Allocate a buffer that is ALWAYS `hipFree`'d on drop (never pooled). For + /// large per-request buffers whose size varies between requests (the KV + /// cache scales with prompt+max_new): the exact-size pool would retain every + /// distinct size and grow VRAM without bound across a multi-turn chat. + pub fn alloc_unpooled(bytes: usize) -> Result { + ensure_sync_init(); + Ok(Self { ptr: raw_alloc(bytes)?, bytes, pooled: false }) } pub fn h2d(&self, src: &[f32]) -> Result<(), String> { let bytes = src.len() * 4; @@ -226,7 +247,7 @@ impl DeviceBuf { #[cfg(feature = "hip")] impl Drop for DeviceBuf { fn drop(&mut self) { - if pool_enabled() && !self.ptr.is_null() { + if self.pooled && pool_enabled() && !self.ptr.is_null() { BUF_POOL.with(|p| p.borrow_mut().entry(self.bytes).or_default().push(self.ptr)); } else { unsafe { ffi::vetta_buf_free(self.ptr); } @@ -292,7 +313,12 @@ pub fn flash_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &Devic fn flash_scores_scratch(n_head: i32, swa_window: i32, cur_pos: i32) -> Result { let k_start = if swa_window > 0 && cur_pos >= swa_window { cur_pos - swa_window + 1 } else { 0 }; let n_win = (cur_pos - k_start + 1).max(1) as usize; - DeviceBuf::alloc(n_head as usize * n_win * 4) + // Bucket the allocation to a power of two so the pool reuses it as cur_pos + // grows (full-attn n_win increases every token); otherwise every distinct + // size is retained and VRAM creeps up over a long generation. The kernel + // still strides by the actual n_win (<= bucket), so the extra slack is safe. + let cap = n_win.next_power_of_two(); + DeviceBuf::alloc(n_head as usize * cap * 4) } /// Launch k_flash_swa_gqa_decode: Inkling SWA window + relpos + sink + gate. diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index c56487a..636d656 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -185,11 +185,14 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result Result { if f16_kv() { - let b = DeviceBuf::alloc(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b) + let b = DeviceBuf::alloc_unpooled(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b) } else { - let b = DeviceBuf::alloc(kv_n * 4)?; b.h2d(&vec![0f32; kv_n])?; Ok(b) + let b = DeviceBuf::alloc_unpooled(kv_n * 4)?; b.h2d(&vec![0f32; kv_n])?; Ok(b) } }; let kv_vec = || -> Result, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() }; @@ -204,8 +207,21 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result bool { std::env::var("VETTA_F16_KV").is_ok() } +/// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer +/// tests) use F32; the resident serve opts into FP16 — the exact strata default +/// (KvDtype::FP16, "default lossless FP16"), parity-verified EXACT (16/40 greedy +/// tokens) and half the VRAM. Attention math stays f32; only stored K/V round to +/// FP16. Process-wide safe switch (no env mutation); serve calls set_kv_f16(true). +static KV_F16: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Select FP16 KV (true) or the F32 baseline (false). The resident serve sets +/// true at startup; tests keep the F32 default for CPU-oracle parity. +pub fn set_kv_f16(on: bool) { KV_F16.store(on, std::sync::atomic::Ordering::Relaxed); } + +fn f16_kv() -> bool { + if std::env::var("VETTA_F32_KV").is_ok() { return false; } + KV_F16.load(std::sync::atomic::Ordering::Relaxed) || std::env::var("VETTA_F16_KV").is_ok() +} /// Run one SWA layer step on `cur` (in place), appending a depth-block snapshot /// to `blocks` when `ip % block_size == 0`. `pos` is the decode position.