Compare commits

..
3 Commits
Author SHA1 Message Date
adm a6ca73105c [Proto] Fix prefix-cache turn-3 regression: LRU-on-restore + monotonic grid
best_match/restore never refreshed ck.lru, so the grid checkpoint just used
at turn 2 kept its turn-1 tick and was evicted by turn 2 prompt-boundary +
full-sequence saves; turn 3 fell back to the pinned 1024 anchor (~1min again).
Fix (audit §1): restore takes &mut self and bumps lru on hit; eviction prefers
non-grid entries (is_grid) so stable 512-grid prefixes survive; replace
pos%512==0 with a monotonic next_grid threshold that splits a chunk exactly on
each 512 boundary regardless of start. Cap 8. Verified 4-turn probe: restored
advances 1536->1686->1778 (no fallback), turn2+ prefill ~1-3.5s vs ~30s cold.
2026-12-02 02:28:53 +01:00
adm 844d9e68ee [Core] Cache static msg_queries in WeightCache; async KV zero-fill
load_msg_queries rebuilt the stacked cross-pass queries [4,hidden] on EVERY
core visit: 2 sync D2H + 1 sync H2D of STATIC model weights = 72 PCIe stalls
per prefill chunk (720/prompt) and 24 per decode token (audit §3.1). Memoize
the 12 device buffers once in WeightCache.msg_queries => zero host round-trips
on the hot path. Measured prefill 2048tok 40.9 -> 38.5s.

new_state zeroed ~3.75GB KV via host vec![0u8] + blocking h2d_bytes every
request (system-RAM alloc + CPU zero + sync PCIe copy, ~0.5-1.5s stall, even
on a prefix-cache hit). Replace with async device hipMemsetAsync (zero_async,
~7.5ms GPU): removes the blocking copy while keeping the cache deterministic
for the full-byte parity tests (causal attention only reads [0..=pos]).
2026-12-02 02:28:53 +01:00
adm ac1b55425c [HIP] Bound BUF_POOL with a 512MiB cap + LRU hipFree; guard moe_scatter_buckets
The exact-size thread-local BUF_POOL never called hipFree: every distinct
batched tail size (bu = suffix % chunk, varies per turn) parked ~100-160MiB
forever => unbounded multi-turn VRAM leak (audit 2026-12-02 §2.1). Track
POOL_BYTES and hipFree a dropped buffer once the pool exceeds MAX_POOL_BYTES
(512MiB); hot fixed-size intermediates still recycle. Also add the symmetric
e<0||e>=128 guard to k_moe_scatter_buckets (count_buckets had it) so a corrupt
router id cannot write exp_cur out of bounds.
2026-12-02 02:28:45 +01:00
4 changed files with 82 additions and 21 deletions

No files matched your search

+34 -13
View File
@@ -56,8 +56,12 @@ const MAX_CONTEXT: usize = 32768;
/// so a new request whose prompt extends a cached prefix restores it and prefills
/// only the NEW tokens (restore_equiv: exact). Pinned anchors {512,1024} are never
/// evicted (I3); otherwise LRU eviction at the cap.
const PREFIX_CACHE_CAP: usize = 6;
const PREFIX_CACHE_CAP: usize = 8;
fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 }
/// Grid checkpoints (multiples of 512) are the STABLE prefixes that survive the
/// turn-tag tail divergence; boundary/full-sequence checkpoints rarely hit again.
/// Eviction prefers dropping non-grid entries so the useful grid is protected.
fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
struct Checkpoint {
tokens: Vec<i32>,
@@ -92,7 +96,11 @@ impl PrefixCache {
}
/// Allocate + restore every checkpointed layer into `states` at `max_seq`.
fn restore(&self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a
/// just-restored grid checkpoint keeps its old tick and gets evicted by the
/// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor.
fn restore(&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
{
let ck = &self.pool[idx];
// A usable checkpoint must cover EVERY layer: a partially-restored state
// would cold-start the missing layers and break prefix equivalence.
@@ -106,7 +114,10 @@ impl PrefixCache {
states[ip] = Some(st);
}
}
Ok(ck.tokens.len())
}
self.tick += 1;
self.pool[idx].lru = self.tick;
Ok(self.pool[idx].tokens.len())
}
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
@@ -129,7 +140,7 @@ impl PrefixCache {
}
let victim = self.pool.iter().enumerate()
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
.min_by_key(|(_, c)| c.lru).map(|(i, _)| i);
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
if let Some(i) = victim {
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
}
@@ -284,8 +295,9 @@ pub fn serve_gen(
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
let mut start = 0usize;
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
if let Some((idx, _l)) = eng.prefix.borrow().best_match(&g.ids) {
match eng.prefix.borrow().restore(idx, &mut states, &eng.d, max_seq) {
let matched = eng.prefix.borrow().best_match(&g.ids);
if let Some((idx, _l)) = matched {
match eng.prefix.borrow_mut().restore(idx, &mut states, &eng.d, max_seq) {
Ok(n) => start = n,
Err(_) => {
// Incomplete/failed restore: fall back to a clean cold prefill.
@@ -326,6 +338,10 @@ pub fn serve_gen(
let chunk = prefill_chunk_size();
let suffix = &g.ids[start..];
let mut done = 0usize;
// Monotonic 512-grid threshold: split a chunk exactly on the next grid boundary
// so a checkpoint always lands on every multiple of 512 regardless of `start`
// (pos % 512 == 0 would miss boundaries when start/suffix aren't aligned).
let mut next_grid = ((start / 512) + 1) * 512;
while done < suffix.len() {
if stop.load(Ordering::Relaxed) {
sess.on_stop();
@@ -334,7 +350,11 @@ pub fn serve_gen(
stop.store(false, Ordering::Relaxed);
return;
}
let take = chunk.min(suffix.len() - done);
let mut take = chunk.min(suffix.len() - done);
let pos_now = start + done;
if pos_now < next_grid && pos_now + take > next_grid {
take = next_grid - pos_now;
}
let toks = &suffix[done..done + take];
let lg = if take == 1 {
eng.forward(toks[0], pos, max_seq, &mut states)
@@ -353,16 +373,17 @@ pub fn serve_gen(
pos += take as i32;
done += take;
// Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate
// checkpoint every 512 tokens so the next turn can restore a stable prefix
// even when the prompt's trailing turn-tag tokens re-render differently
// (strata-ctl serializes the turn boundary differently once turn 1 becomes
// history). best_match then picks the longest 512-grid checkpoint that is a
// full prefix, instead of discarding everything over a 2-token tail mismatch.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 && pos % 512 == 0 {
// checkpoint on every 512 boundary so the next turn can restore a stable
// prefix even when the prompt's trailing turn-tag tokens re-render
// differently. best_match picks the longest grid checkpoint that is a full
// prefix; grid entries are protected from eviction (is_grid) and refreshed
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid {
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] grid save seq={pos}");
}
next_grid += 512;
}
let ms = t0.elapsed().as_secs_f64() * 1000.0;
if let Ok(pp) = sess.on_prefill_chunk((start + done) as u32, n_prompt as u32, ms) {
+23
View File
@@ -198,8 +198,19 @@ pub struct DeviceBuf {
thread_local! {
static BUF_POOL: std::cell::RefCell<std::collections::HashMap<usize, Vec<*mut std::os::raw::c_void>>> =
std::cell::RefCell::new(std::collections::HashMap::new());
// Total bytes currently retained (free) in the pool. Capped so the exact-size
// pool cannot accumulate every distinct batched-tail size (bu = suffix % chunk
// varies per turn) forever: beyond MAX_POOL_BYTES a dropped buffer is hipFree'd
// instead of pooled, bounding the multi-turn VRAM leak (audit 2026-12-02 §2.1).
static POOL_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Upper bound on bytes retained in the thread-local buffer pool. Hot fixed-size
/// intermediates (chunk=256 batched + M=1 decode) fit well under this; excess
/// distinct sizes are freed rather than retained without bound.
#[cfg(feature = "hip")]
const MAX_POOL_BYTES: usize = 512 * 1024 * 1024;
#[cfg(feature = "hip")]
static POOL_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
@@ -264,6 +275,7 @@ impl DeviceBuf {
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())) {
POOL_BYTES.with(|c| c.set(c.get().saturating_sub(bytes)));
return Ok(Self { ptr, bytes, pooled: true });
}
}
@@ -331,10 +343,21 @@ impl DeviceBuf {
impl Drop for DeviceBuf {
fn drop(&mut self) {
if self.pooled && pool_enabled() && !self.ptr.is_null() {
// Retain only while under the global pool budget; otherwise hipFree so
// distinct one-off sizes (batched tail chunks) cannot leak unbounded.
let keep = POOL_BYTES.with(|c| {
if c.get().saturating_add(self.bytes) <= MAX_POOL_BYTES {
c.set(c.get() + self.bytes); true
} else { false }
});
if keep {
BUF_POOL.with(|p| p.borrow_mut().entry(self.bytes).or_default().push(self.ptr));
} else {
unsafe { ffi::vetta_buf_free(self.ptr); }
}
} else {
unsafe { ffi::vetta_buf_free(self.ptr); }
}
}
}
+24 -8
View File
@@ -84,6 +84,7 @@ pub struct WeightCache {
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
arenas: RefCell<HashMap<(usize, String), Arc<ExpertArena>>>,
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
msgq: RefCell<HashMap<usize, Arc<DeviceBuf>>>,
}
impl WeightCache {
@@ -98,6 +99,7 @@ impl WeightCache {
experts: RefCell::new(HashMap::new()),
arenas: RefCell::new(HashMap::new()),
ctrl: RefCell::new(HashMap::new()),
msgq: RefCell::new(HashMap::new()),
}
}
@@ -162,6 +164,17 @@ impl WeightCache {
Ok(v)
}
/// Stacked cross-pass msg_queries [4, hidden] for core layer ip, memoized.
/// These are STATIC model weights: building them per visit did 2 sync D2H + 1
/// sync H2D each (72 PCIe stalls/chunk in prefill, 24/token in decode). Cache
/// the device buffer once => zero host round-trips on the hot path.
pub fn msg_queries(&self, ip: usize, hidden: usize) -> Result<Arc<DeviceBuf>, String> {
if let Some(v) = self.msgq.borrow().get(&ip) { return Ok(v.clone()); }
let v = Arc::new(load_msg_queries(self, ip, hidden)?);
self.msgq.borrow_mut().insert(ip, v.clone());
Ok(v)
}
/// Eagerly load the WHOLE model to device: trunk (embed/norms/unembed/output
/// query/cross-pass queries), every attention layer (SWA or full), the core
/// loop controllers, and all expert ARENAS (the contiguous device-MoE layout).
@@ -228,7 +241,7 @@ pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<La
}
pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState, String> {
let zero = |n: usize| -> Result<DeviceBuf, String> { let b = DeviceBuf::alloc(n * 4)?; b.h2d(&vec![0f32; n])?; Ok(b) };
let zero = |n: usize| -> Result<DeviceBuf, String> { let b = DeviceBuf::alloc(n * 4)?; b.zero_async()?; Ok(b) };
// KV cache dtype: F32 by default (the verified CPU-oracle baseline); FP16 via
// VETTA_F16_KV=1 matches the strata default (KvDtype::FP16) and its
// length-dependent rounding (the F32 cache diverges on near-ties as it grows).
@@ -236,12 +249,15 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState
// KV is unpooled: its size scales with max_seq (prompt+max_new), which varies
// per request. Pooling by exact size would retain every distinct KV size and
// grow VRAM without bound across a multi-turn chat; free it on request end.
// Zero-filled with ASYNC device memset (hipMemsetAsync, ~7.5ms GPU for 3.75GB),
// NOT a host vec![0]+sync h2d: the latter allocated ~3.75GB system RAM, zeroed
// it on CPU and copied it over blocking PCIe every request (~0.5-1.5s stall).
// Causal attention only reads [0..=pos] (kv_store overwrites before read), so
// the zero is defensive/deterministic rather than required, but keeps the
// full-cache byte-parity tests stable across pool reuse.
let kv_buf = || -> Result<DeviceBuf, String> {
if f16_kv() {
let b = DeviceBuf::alloc_unpooled(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b)
} else {
let b = DeviceBuf::alloc_unpooled(kv_n * 4)?; b.h2d(&vec![0f32; kv_n])?; Ok(b)
}
let b = if f16_kv() { DeviceBuf::alloc_unpooled(kv_n * 2)? } else { DeviceBuf::alloc_unpooled(kv_n * 4)? };
b.zero_async()?; Ok(b)
};
let kv_vec = || -> Result<Vec<DeviceBuf>, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() };
Ok(LayerState {
@@ -883,7 +899,7 @@ pub fn forward_inkling_with_state(
}
for ip in 6..18 {
if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() {
let mq = load_msg_queries(cache, ip, h)?;
let mq = cache.msg_queries(ip, h)?;
let n_bank = bank.len();
let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
let mut bh = vec![0f32; n_bank.max(1) * h];
@@ -996,7 +1012,7 @@ pub fn forward_batch(
}
for ip in 6..18 {
if p > 0 && !no_ctrl {
let mq = load_msg_queries(cache, ip, h)?;
let mq = cache.msg_queries(ip, h)?;
let msgs_buf = DeviceBuf::alloc(bu * 4 * h * 4)?;
vetta_infer_hip::attn_res_mix(&bank_buf, &bank_out, &mq, &msgs_buf, n_bank as i32, b, 4, h as i32, d.eps)?;
let cw = cache.controllers(ip)?;
+1
View File
@@ -2120,6 +2120,7 @@ __global__ void __launch_bounds__(256) k_moe_scatter_buckets(
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= total) return;
const int e = topk_ids[i];
if (e < 0 || e >= 128) return; // symmetric with k_moe_count_buckets: never OOB exp_cur[e]
const int pos = atomicAdd(&exp_cur[e], 1);
bucket_tok[pos] = i / top_k;
slotk_to_bidx[i] = pos;