Compare commits
3
Commits
088ac1f66d
...
a6ca73105c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6ca73105c | ||
|
|
844d9e68ee | ||
|
|
ac1b55425c |
No files matched your search
@@ -56,8 +56,12 @@ const MAX_CONTEXT: usize = 32768;
|
|||||||
/// so a new request whose prompt extends a cached prefix restores it and prefills
|
/// 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
|
/// only the NEW tokens (restore_equiv: exact). Pinned anchors {512,1024} are never
|
||||||
/// evicted (I3); otherwise LRU eviction at the cap.
|
/// 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 }
|
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 {
|
struct Checkpoint {
|
||||||
tokens: Vec<i32>,
|
tokens: Vec<i32>,
|
||||||
@@ -92,7 +96,11 @@ impl PrefixCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Allocate + restore every checkpointed layer into `states` at `max_seq`.
|
/// 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];
|
let ck = &self.pool[idx];
|
||||||
// A usable checkpoint must cover EVERY layer: a partially-restored state
|
// A usable checkpoint must cover EVERY layer: a partially-restored state
|
||||||
// would cold-start the missing layers and break prefix equivalence.
|
// would cold-start the missing layers and break prefix equivalence.
|
||||||
@@ -106,7 +114,10 @@ impl PrefixCache {
|
|||||||
states[ip] = Some(st);
|
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 /
|
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
|
||||||
@@ -129,7 +140,7 @@ impl PrefixCache {
|
|||||||
}
|
}
|
||||||
let victim = self.pool.iter().enumerate()
|
let victim = self.pool.iter().enumerate()
|
||||||
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
|
.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 {
|
if let Some(i) = victim {
|
||||||
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
|
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).
|
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
|
||||||
let mut start = 0usize;
|
let mut start = 0usize;
|
||||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
|
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
|
||||||
if let Some((idx, _l)) = eng.prefix.borrow().best_match(&g.ids) {
|
let matched = eng.prefix.borrow().best_match(&g.ids);
|
||||||
match eng.prefix.borrow().restore(idx, &mut states, &eng.d, max_seq) {
|
if let Some((idx, _l)) = matched {
|
||||||
|
match eng.prefix.borrow_mut().restore(idx, &mut states, &eng.d, max_seq) {
|
||||||
Ok(n) => start = n,
|
Ok(n) => start = n,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// Incomplete/failed restore: fall back to a clean cold prefill.
|
// Incomplete/failed restore: fall back to a clean cold prefill.
|
||||||
@@ -326,6 +338,10 @@ pub fn serve_gen(
|
|||||||
let chunk = prefill_chunk_size();
|
let chunk = prefill_chunk_size();
|
||||||
let suffix = &g.ids[start..];
|
let suffix = &g.ids[start..];
|
||||||
let mut done = 0usize;
|
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() {
|
while done < suffix.len() {
|
||||||
if stop.load(Ordering::Relaxed) {
|
if stop.load(Ordering::Relaxed) {
|
||||||
sess.on_stop();
|
sess.on_stop();
|
||||||
@@ -334,7 +350,11 @@ pub fn serve_gen(
|
|||||||
stop.store(false, Ordering::Relaxed);
|
stop.store(false, Ordering::Relaxed);
|
||||||
return;
|
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 toks = &suffix[done..done + take];
|
||||||
let lg = if take == 1 {
|
let lg = if take == 1 {
|
||||||
eng.forward(toks[0], pos, max_seq, &mut states)
|
eng.forward(toks[0], pos, max_seq, &mut states)
|
||||||
@@ -353,16 +373,17 @@ pub fn serve_gen(
|
|||||||
pos += take as i32;
|
pos += take as i32;
|
||||||
done += take;
|
done += take;
|
||||||
// Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate
|
// Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate
|
||||||
// checkpoint every 512 tokens so the next turn can restore a stable prefix
|
// checkpoint on every 512 boundary so the next turn can restore a stable
|
||||||
// even when the prompt's trailing turn-tag tokens re-render differently
|
// prefix even when the prompt's trailing turn-tag tokens re-render
|
||||||
// (strata-ctl serializes the turn boundary differently once turn 1 becomes
|
// differently. best_match picks the longest grid checkpoint that is a full
|
||||||
// history). best_match then picks the longest 512-grid checkpoint that is a
|
// prefix; grid entries are protected from eviction (is_grid) and refreshed
|
||||||
// full prefix, instead of discarding everything over a 2-token tail mismatch.
|
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
|
||||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 && pos % 512 == 0 {
|
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);
|
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
|
||||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||||
eprintln!("[prefix] grid save seq={pos}");
|
eprintln!("[prefix] grid save seq={pos}");
|
||||||
}
|
}
|
||||||
|
next_grid += 512;
|
||||||
}
|
}
|
||||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
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) {
|
if let Ok(pp) = sess.on_prefill_chunk((start + done) as u32, n_prompt as u32, ms) {
|
||||||
|
|||||||
@@ -198,8 +198,19 @@ pub struct DeviceBuf {
|
|||||||
thread_local! {
|
thread_local! {
|
||||||
static BUF_POOL: std::cell::RefCell<std::collections::HashMap<usize, Vec<*mut std::os::raw::c_void>>> =
|
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());
|
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")]
|
#[cfg(feature = "hip")]
|
||||||
static POOL_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
|
static POOL_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
|
||||||
|
|
||||||
@@ -264,6 +275,7 @@ impl DeviceBuf {
|
|||||||
ensure_sync_init();
|
ensure_sync_init();
|
||||||
if pool_enabled() {
|
if pool_enabled() {
|
||||||
if let Some(ptr) = BUF_POOL.with(|p| p.borrow_mut().get_mut(&bytes).and_then(|v| v.pop())) {
|
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 });
|
return Ok(Self { ptr, bytes, pooled: true });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -331,10 +343,21 @@ impl DeviceBuf {
|
|||||||
impl Drop for DeviceBuf {
|
impl Drop for DeviceBuf {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if self.pooled && pool_enabled() && !self.ptr.is_null() {
|
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));
|
BUF_POOL.with(|p| p.borrow_mut().entry(self.bytes).or_default().push(self.ptr));
|
||||||
} else {
|
} else {
|
||||||
unsafe { ffi::vetta_buf_free(self.ptr); }
|
unsafe { ffi::vetta_buf_free(self.ptr); }
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
unsafe { ffi::vetta_buf_free(self.ptr); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ pub struct WeightCache {
|
|||||||
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
|
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
|
||||||
arenas: RefCell<HashMap<(usize, String), Arc<ExpertArena>>>,
|
arenas: RefCell<HashMap<(usize, String), Arc<ExpertArena>>>,
|
||||||
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
|
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
|
||||||
|
msgq: RefCell<HashMap<usize, Arc<DeviceBuf>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WeightCache {
|
impl WeightCache {
|
||||||
@@ -98,6 +99,7 @@ impl WeightCache {
|
|||||||
experts: RefCell::new(HashMap::new()),
|
experts: RefCell::new(HashMap::new()),
|
||||||
arenas: RefCell::new(HashMap::new()),
|
arenas: RefCell::new(HashMap::new()),
|
||||||
ctrl: RefCell::new(HashMap::new()),
|
ctrl: RefCell::new(HashMap::new()),
|
||||||
|
msgq: RefCell::new(HashMap::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,6 +164,17 @@ impl WeightCache {
|
|||||||
Ok(v)
|
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
|
/// Eagerly load the WHOLE model to device: trunk (embed/norms/unembed/output
|
||||||
/// query/cross-pass queries), every attention layer (SWA or full), the core
|
/// query/cross-pass queries), every attention layer (SWA or full), the core
|
||||||
/// loop controllers, and all expert ARENAS (the contiguous device-MoE layout).
|
/// 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> {
|
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
|
// 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
|
// 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).
|
// 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
|
// 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
|
// 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.
|
// 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> {
|
let kv_buf = || -> Result<DeviceBuf, String> {
|
||||||
if f16_kv() {
|
let b = if f16_kv() { DeviceBuf::alloc_unpooled(kv_n * 2)? } else { DeviceBuf::alloc_unpooled(kv_n * 4)? };
|
||||||
let b = DeviceBuf::alloc_unpooled(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b)
|
b.zero_async()?; Ok(b)
|
||||||
} else {
|
|
||||||
let b = DeviceBuf::alloc_unpooled(kv_n * 4)?; b.h2d(&vec![0f32; kv_n])?; Ok(b)
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let kv_vec = || -> Result<Vec<DeviceBuf>, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() };
|
let kv_vec = || -> Result<Vec<DeviceBuf>, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() };
|
||||||
Ok(LayerState {
|
Ok(LayerState {
|
||||||
@@ -883,7 +899,7 @@ pub fn forward_inkling_with_state(
|
|||||||
}
|
}
|
||||||
for ip in 6..18 {
|
for ip in 6..18 {
|
||||||
if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() {
|
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 n_bank = bank.len();
|
||||||
let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
|
let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
|
||||||
let mut bh = vec![0f32; n_bank.max(1) * h];
|
let mut bh = vec![0f32; n_bank.max(1) * h];
|
||||||
@@ -996,7 +1012,7 @@ pub fn forward_batch(
|
|||||||
}
|
}
|
||||||
for ip in 6..18 {
|
for ip in 6..18 {
|
||||||
if p > 0 && !no_ctrl {
|
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)?;
|
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)?;
|
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)?;
|
let cw = cache.controllers(ip)?;
|
||||||
|
|||||||
@@ -2120,6 +2120,7 @@ __global__ void __launch_bounds__(256) k_moe_scatter_buckets(
|
|||||||
const int i = blockIdx.x * blockDim.x + threadIdx.x;
|
const int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||||
if (i >= total) return;
|
if (i >= total) return;
|
||||||
const int e = topk_ids[i];
|
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);
|
const int pos = atomicAdd(&exp_cur[e], 1);
|
||||||
bucket_tok[pos] = i / top_k;
|
bucket_tok[pos] = i / top_k;
|
||||||
slotk_to_bidx[i] = pos;
|
slotk_to_bidx[i] = pos;
|
||||||
|
|||||||
Reference in new issue
Block a user