[HIP][Core] Zero-VRAM PrefixCache in pinned host RAM (PinnedBuf) + DSpark SWA ring

Close Punto 3 of the flat-VRAM plan:
- Add PinnedBuf (hipHostMallocDefault / hipHostFree with stream 0 sync on drop) and pipelined async 1D/2D D2H/H2D copy helpers in vetta_kernels.{h,hip} and vetta-infer-hip.
- Migrate LayerSnapshot (KV + ShortConv hist) and DsparkSnapshot (drafter KV + frnn_last) from VRAM DeviceBuf to host PinnedBuf (0 bytes VRAM per checkpoint).
- Size DSpark SWA layers 0/2 in DsparkContext to DS_SWA_RING=1280 (-258 MiB VRAM at 32k context).
- Add GPU regression tests: pinned_buf_zero_vram_and_roundtrip_2d (+0.00 MiB VRAM on 64 MiB alloc) and serve_gen_pinned_prefix_cache_vram_flat (4 turns up to 2100 tok, 8/8 checkpoints full, VETTA_SPEC=1: 20674->20672->20676->20676 MiB, +2.00 MiB delta).
- Update README.md, docs/ORIENTATION.md, and review/2026-12-02-fix-drafter-e-ottimizzazioni.md.
This commit is contained in:
adm committed 2026-12-02 23:23:07 +01:00
1 parent c1c5221642
commit 1772050087
9 files changed
+370 -88

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ Built from the measured hardware physics and engineering lessons of our hardened
- **M1 (Resident MoE End-to-End — Target 1: `Inkling-2-Mini`, inference landed):** full 48-visit forward on real `gfx1150` weights, **EXACT multi-token greedy parity** vs the `strata` reference (per-pass KV pools + unpadded vocab 200058), `strata-ctl` drop-in `--serve` link (OpenAI-compatible API, field-for-field wire). Serve-session FSM (`serve_session.lean`), arena safety (`arena_plan.lean` + `abi::arena`), `.vbundle` contract (`abi::bundle` + `ld::bundle`), loop proof (`inkling_loop.lean`). Speed vs C++ baseline (`>= 18 tok/s`, `< 4 s` reload) is the remaining M2 work.
- **🎉 First real interactive GUI conversation — 2026-12-01 (measured):** via the `strata-ctl` web GUI on Sogliola, *"Ciao, sono Federico"* → *"Ciao Federico! Piacere di conoscerti. Come posso aiutarti oggi?"* — **2650 prompt + 53 completion tokens · 4.2 tok/s decode · first token 618 s** (the 618 s is sequential prefill of the ~2650-token agent prompt, ~140 ms/token; decode ~4.2 tok/s). Host-CPU busy-wait eliminated via `hipDeviceScheduleBlockingSync` (measured A/B 101.2% → 54.2%); the residual ~54% is kernel-launch cost, removed by HIP graph capture (M2).
- **⚡ Prefill batched + tensor-core — 2026-12-02 (measured):** chunked batched forward (M=B) + FP16 WMMA grouped MoE + BF16 WMMA dense projections + FlashAttention-2 WMMA prefill (P staged in LDS, no global scores scratch). Synthetic 2048-token prefill on `gfx1150` (FP16 KV, chunk 256): **60 s → 12.9 s (-78%)**, ~6.3 ms/token (a 16 k-token agent prompt ~105 s, was ~7 min). Greedy-vs-reference stays EXACT (blocking gate); internal M=1-vs-M=B parity relaxed to a global-scale tolerance (approved P1 policy). The 618 s first-token above is historical (sequential prefill).
- **🧠 Flat VRAM + long-prompt clamp — 2026-12-02:** persistent per-layer KV/ShortConv states reused across requests (no ±3.75 GB alloc/free sawtooth), SWA-window checkpoints + prefix cache cap 8 (grid-protected, LRU-on-restore), 512 MiB buffer-pool cap; long→short session switches reuse the persistent KV. Generation budget clamped to the window (`clamp_max_new`) instead of hard-erroring past 16382 prompt tokens with strata-ctl's fixed max_new=16384; window configurable via `serve --max-context N`. Verified live: a 16504-token prompt generates (was ERR 0 tokens).
- **🧠 Flat VRAM + pinned host checkpoints + long-prompt clamp — 2026-12-02 (measured):** persistent per-layer KV/ShortConv states (40 SWA pools on 1280-slot rings + 8 Global pools), DSpark SWA layers 0/2 on 1280-slot rings (-258 MiB VRAM at 32k), and **zero-VRAM `PrefixCache` checkpoints** (`LayerSnapshot` + `DsparkSnapshot` stored in page-locked host RAM via `PinnedBuf`/`hipHostMallocDefault`, pipelined async SDMA on stream 0; `PinnedBuf` 64 MiB VRAM delta = `+0.00 MiB`, 4-turn multi-checkpoint test up to 2100 tokens with 8 full checkpoints + `VETTA_SPEC=1` stays completely flat at `20,674 → 20,672 → 20,676 → 20,676 MiB`, delta `+2.00 MiB`). Generation budget clamped to the window (`clamp_max_new`) instead of hard-erroring past 16382 prompt tokens with strata-ctl's fixed max_new=16384; window configurable via `serve --max-context N`. Verified live: a 16504-token prompt generates (was ERR 0 tokens).
- **🚀 DSpark speculative drafter (opt-in `VETTA_SPEC=1`, 100% GPU) — 2026-12-02 (measured):** single-pass base-unembed Top-512 screen + on-GPU Markov head + GPU verify argmax (`<=32 B` D2H), 0-LDS Wave32 online-softmax block attention (safe past 16k+ context), M-tiled Wave32 BF16 router GEMV, zero-scratch small-M SWA GQA, `PrefixCache` `DsparkSnapshot` save/restore for multi-turn, and accepted-count EMA governor (`n_draft` starts at 5, adapts 2..7). Lossless contract proven in `proofs/speculative_draft.lean` (200-token `spec_lossless_gate` EXACT + multi-turn `RESUME` EXACT). Measured on `gfx1150` (`Inkling-2-Mini`, `temperature=0`):
- **Rust coding prompt (`RingBuffer<T>`, 128 tok):** OFF **`6.83 tok/s`** → `VETTA_SPEC=1` **`13.93 tok/s`** (**2.04×**, `n_draft=5`, 100% EXACT — matching/edging `strata-inkling --draft dspark` at `13.66 tok/s`).
- **Short prose prompt (`"The capital of France is"`, 96 tok):** `nd=5` **`4.58 → 9.09 tok/s`** (**+98.5%**); adaptive EMA **`8.93 tok/s`** decode.
+55
View File
@@ -1098,4 +1098,59 @@ mod tests {
assert_eq!(on_t2, off_t2, "Turn 2 tokens after PrefixCache+DsparkSnapshot restore must match OFF exactly");
});
}
/// GPU: verify that saving multiple large PrefixCache checkpoints (trunk KV +
/// ShortConv + DsparkSnapshot across grid boundaries 512, 1024, 1536, 2048)
/// keeps GPU VRAM completely flat (0 bytes added per checkpoint in VRAM,
/// since all snapshots live in pinned host RAM via `PinnedBuf`).
#[test]
#[ignore]
fn serve_gen_pinned_prefix_cache_vram_flat() {
crate::gpu_isolated(|| {
unsafe { std::env::set_var("VETTA_SPEC", "1"); }
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
let stop = AtomicBool::new(false);
let mut prompt: Vec<i32> = Vec::with_capacity(2200);
let seed = [200002, 200004, 34182, 279, 154554, 150628, 25, 220, 15, 200010, 200000, 200004];
prompt.extend_from_slice(&seed);
let mut vram_samples: Vec<(usize, usize, usize)> = Vec::new();
for target_len in [600usize, 1100, 1600, 2100] {
while prompt.len() < target_len {
prompt.push(10970 + ((prompt.len() * 17) % 500) as i32);
}
let ids_str = prompt.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",");
let g = match parse_serve_line(&format!("GEN 8 temperature=0 {ids_str}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let mut lines = Vec::new();
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
let resumed: usize = lines.iter()
.find(|l| l.starts_with("RESUME "))
.and_then(|l| l[7..].trim().parse().ok())
.unwrap_or(0);
let ckpts = eng.prefix.borrow().pool.len();
let vram = vetta_infer_hip::vram_used();
eprintln!(
"pinned_ckpt_vram: prompt={} resumed={} ckpts={} vram={:.2} MiB",
target_len, resumed, ckpts, vram as f64 / (1024.0 * 1024.0)
);
vram_samples.push((target_len, resumed, vram));
}
unsafe { std::env::remove_var("VETTA_SPEC"); }
assert!(vram_samples[1].1 >= 512, "Turn 2 must hit >=512 checkpoint, got {}", vram_samples[1].1);
assert!(vram_samples[2].1 >= 1024, "Turn 3 must hit >=1024 checkpoint, got {}", vram_samples[2].1);
assert!(vram_samples[3].1 >= 1536, "Turn 4 must hit >=1536 checkpoint, got {}", vram_samples[3].1);
// Compare VRAM after Turn 1 (once KV + DsparkContext + BUF_POOL are warm)
// against Turn 4 (after filling 8 checkpoints up to 2100 tokens).
let v1 = vram_samples[0].2;
let v4 = vram_samples[3].2;
let delta_mb = (v4 as isize - v1 as isize) as f64 / (1024.0 * 1024.0);
eprintln!("pinned_ckpt_vram: Turn1->Turn4 delta = {delta_mb:+.2} MiB (expected ~0 MiB)");
assert!(
delta_mb.abs() < 32.0,
"PrefixCache in pinned RAM must keep VRAM flat across checkpoints, got {delta_mb:+.2} MiB"
);
});
}
}
+129
View File
@@ -31,6 +31,12 @@ mod ffi {
pub fn vetta_buf_d2h(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy2d(dst: *mut c_void, dpitch: usize, src: *const c_void, spitch: usize, width: usize, height: usize) -> c_int;
pub fn vetta_host_alloc(out: *mut *mut c_void, bytes: usize) -> c_int;
pub fn vetta_host_free(p: *mut c_void) -> c_int;
pub fn vetta_buf_d2h_async(dst_host: *mut c_void, src_dev: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_h2d_async(dst_dev: *mut c_void, src_host: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy2d_d2h_async(dst_host: *mut c_void, dpitch: usize, src_dev: *const c_void, spitch: usize, width: usize, height: usize) -> c_int;
pub fn vetta_buf_copy2d_h2d_async(dst_dev: *mut c_void, dpitch: usize, src_host: *const c_void, spitch: usize, width: usize, height: usize) -> c_int;
pub fn vetta_synchronize() -> c_int;
pub fn vetta_vram_used(out: *mut usize) -> c_int;
pub fn vetta_buf_zero_async(dst: *mut c_void, bytes: usize, stream: *mut c_void) -> c_int;
@@ -442,6 +448,89 @@ impl DeviceBuf {
if rc != 0 { return Err("memset async failed".into()); }
Ok(())
}
/// Async host-to-device copy from a pinned host buffer on the default stream.
pub fn copy_from_pinned(&self, src: &PinnedBuf, bytes: usize) -> Result<(), String> {
if bytes > self.bytes || bytes > src.bytes { return Err("copy_from_pinned overflow".into()); }
let rc = unsafe { ffi::vetta_buf_h2d_async(self.ptr, src.ptr, bytes) };
if rc != 0 { return Err("h2d_async copy failed".into()); }
Ok(())
}
/// Pitched async host-to-device copy from a pinned host buffer with byte
/// offsets into both buffers (PrefixCache restore into KV/DSpark rings).
pub fn copy2d_from_pinned_at(&self, dst_off: usize, src: &PinnedBuf, src_off: usize, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
if height > 0 {
let dlast = dst_off + (height - 1) * dpitch + width;
let slast = src_off + (height - 1) * spitch + width;
if dlast > self.bytes || slast > src.bytes { return Err("copy2d_from_pinned_at overflow".into()); }
}
let dp = unsafe { (self.ptr as *mut u8).add(dst_off) as *mut std::os::raw::c_void };
let sp = unsafe { (src.ptr as *const u8).add(src_off) as *const std::os::raw::c_void };
let rc = unsafe { ffi::vetta_buf_copy2d_h2d_async(dp, dpitch, sp, spitch, width, height) };
if rc != 0 { return Err("h2d_async copy2d_at failed".into()); }
Ok(())
}
}
/// Owned page-locked (pinned) host buffer (`hipHostMallocDefault` / `hipHostFree`).
/// Occupies **0 bytes of GPU VRAM** while transferring via SDMA asynchronously on
/// stream 0 (`hipMemcpy[2D]Async`). Used for PrefixCache snapshots (`LayerSnapshot`
/// and `DsparkSnapshot`) so multi-turn checkpoints keep VRAM completely flat.
#[cfg(feature = "hip")]
pub struct PinnedBuf {
pub ptr: *mut std::os::raw::c_void,
pub bytes: usize,
}
#[cfg(feature = "hip")]
impl PinnedBuf {
/// Allocate `bytes` of page-locked host RAM (0 bytes VRAM).
pub fn alloc(bytes: usize) -> Result<Self, String> {
ensure_sync_init();
let alloc_b = bytes.max(1);
let mut ptr: *mut std::os::raw::c_void = std::ptr::null_mut();
let rc = unsafe { ffi::vetta_host_alloc(&mut ptr, alloc_b) };
if rc != 0 || ptr.is_null() { return Err(format!("hipHostMalloc({alloc_b}) failed")); }
Ok(Self { ptr, bytes })
}
/// Zero-fill the pinned host buffer on CPU (only call when no async GPU copy
/// is in flight, e.g. right after `alloc`).
pub fn zero(&self) {
if self.bytes > 0 && !self.ptr.is_null() {
unsafe { std::ptr::write_bytes(self.ptr as *mut u8, 0, self.bytes); }
}
}
/// Async device-to-host copy of `bytes` from `src` into this pinned host buffer.
pub fn copy_from_dev(&self, src: &DeviceBuf, bytes: usize) -> Result<(), String> {
if bytes > self.bytes || bytes > src.bytes { return Err("copy_from_dev overflow".into()); }
let rc = unsafe { ffi::vetta_buf_d2h_async(self.ptr, src.ptr, bytes) };
if rc != 0 { return Err("d2h_async copy failed".into()); }
Ok(())
}
/// Pitched async device-to-host copy with byte offsets into both buffers
/// (PrefixCache snapshot out of KV/DSpark rings into host RAM).
pub fn copy2d_from_dev_at(&self, dst_off: usize, src: &DeviceBuf, src_off: usize, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
if height > 0 {
let dlast = dst_off + (height - 1) * dpitch + width;
let slast = src_off + (height - 1) * spitch + width;
if dlast > self.bytes || slast > src.bytes { return Err("copy2d_from_dev_at overflow".into()); }
}
let dp = unsafe { (self.ptr as *mut u8).add(dst_off) as *mut std::os::raw::c_void };
let sp = unsafe { (src.ptr as *const u8).add(src_off) as *const std::os::raw::c_void };
let rc = unsafe { ffi::vetta_buf_copy2d_d2h_async(dp, dpitch, sp, spitch, width, height) };
if rc != 0 { return Err("d2h_async copy2d_at failed".into()); }
Ok(())
}
}
#[cfg(feature = "hip")]
impl Drop for PinnedBuf {
fn drop(&mut self) {
if !self.ptr.is_null() {
// vetta_host_free synchronizes stream 0 before hipHostFree so any
// pipelined async D2H/H2D copy completes before the host pages free.
unsafe { ffi::vetta_host_free(self.ptr); }
}
}
}
#[cfg(feature = "hip")]
@@ -1525,6 +1614,46 @@ mod gpu_tests {
assert!(max_rel < 1e-4, "long-context dspark_block_attn parity failed: {max_rel}");
}
/// Verify that `PinnedBuf` (`hipHostMallocDefault`) consumes 0 bytes of GPU
/// VRAM (measured via `vram_used`) and round-trips pitched 2D async copies
/// bit-identically with wrap-around offsets (mirroring PrefixCache SWA rings).
#[test]
#[ignore]
fn pinned_buf_zero_vram_and_roundtrip_2d() {
// Warm device context first so context creation isn't counted in delta.
let _warm = DeviceBuf::alloc_unpooled(4096).unwrap();
let vram_before = vram_used();
let big = PinnedBuf::alloc(64 * 1024 * 1024).unwrap();
let vram_after = vram_used();
let delta_mb = (vram_after as isize - vram_before as isize) as f64 / (1024.0 * 1024.0);
eprintln!("PinnedBuf 64 MiB VRAM delta: {delta_mb:+.2} MiB (before={} after={})", vram_before, vram_after);
assert!(vram_after <= vram_before + 4 * 1024 * 1024, "PinnedBuf must not allocate GPU VRAM, delta={delta_mb:.2} MiB");
drop(big);
// Pitched 2D wrap-around round-trip: height=8 heads, ring=16 cols, win=10 cols, s0=12 -> first=4, rem=6.
let (heads, ring, win, s0, elem_b) = (8usize, 16usize, 10usize, 12usize, 8usize);
let first = win.min(ring - s0);
let src_data: Vec<u8> = (0..heads * ring * elem_b).map(|i| ((i * 37 + 11) % 251) as u8).collect();
let dev_src = DeviceBuf::alloc_unpooled(src_data.len()).unwrap();
dev_src.h2d_bytes(&src_data).unwrap();
let pin = PinnedBuf::alloc(heads * win * elem_b).unwrap();
pin.copy2d_from_dev_at(0, &dev_src, s0 * elem_b, win * elem_b, ring * elem_b, first * elem_b, heads).unwrap();
pin.copy2d_from_dev_at(first * elem_b, &dev_src, 0, win * elem_b, ring * elem_b, (win - first) * elem_b, heads).unwrap();
let dev_dst = DeviceBuf::alloc_unpooled(src_data.len()).unwrap();
dev_dst.zero_async().unwrap();
dev_dst.copy2d_from_pinned_at(s0 * elem_b, &pin, 0, ring * elem_b, win * elem_b, first * elem_b, heads).unwrap();
dev_dst.copy2d_from_pinned_at(0, &pin, first * elem_b, ring * elem_b, win * elem_b, (win - first) * elem_b, heads).unwrap();
let mut got = vec![0u8; src_data.len()];
dev_dst.d2h_bytes(&mut got).unwrap();
for h in 0..heads {
for k in 0..win {
let col = (s0 + k) % ring;
let off = (h * ring + col) * elem_b;
assert_eq!(&got[off..off + elem_b], &src_data[off..off + elem_b], "mismatch at h={h} col={col}");
}
}
}
/// DSpark SwiGLU vs CPU oracle (silu(g)*u).
#[test]
#[ignore]
+64 -47
View File
@@ -91,9 +91,14 @@ pub fn layout_check(ar: &SafetensorsArchive) -> Result<(), String> {
mod gpu {
use super::*;
use crate::packer;
use vetta_infer_hip::DeviceBuf;
use vetta_infer_hip::{DeviceBuf, PinnedBuf};
use vetta_infer_hip as hip;
/// SWA ring capacity for DSpark layers 0 and 2 (`swa_win + max_prefill_chunk`):
/// matches `LayerState`'s SWA ring (`1024 + 256 = 1280`), saving ~258 MiB VRAM
/// at 32k context vs allocating full `max_seq` for SWA layers.
pub const DS_SWA_RING: usize = 1024 + crate::layer::SWA_CHUNK_CAP;
pub struct DsparkLayer {
pub dflare_norm: DeviceBuf,
pub input_ln: DeviceBuf,
@@ -235,7 +240,7 @@ mod gpu {
pub fn dspark_draft(
w: &DsparkWeights, embed: &DeviceBuf, embed_norm: &DeviceBuf, unembed: &DeviceBuf,
ctx_k: [&DeviceBuf; 3], ctx_v: [&DeviceBuf; 3], frnn: &DeviceBuf,
anchor_tok: i32, anchor_pos: i32, n_draft: i32, ctx_cap: i32, frnn_cap: i32,
anchor_tok: i32, anchor_pos: i32, n_draft: i32, ctx_cap: [i32; 3], frnn_cap: i32,
swa_win: i32, eps: f32, theta: f32, vocab: i32, out_ids: &mut [i32],
) -> Result<(), String> {
use vetta_infer_hip as hip;
@@ -276,7 +281,7 @@ mod gpu {
let is_swa = DS_SWA_LAYERS.contains(&il);
let c0 = if is_swa { (anchor_pos - swa_win + 1).max(0) } else { 0 };
let c_len = anchor_pos - c0;
hip::dspark_block_attn(&q, &kd, &vd, ctx_k[il], ctx_v[il], &attn, b, h as i32, kv as i32, hd as i32, c0, c_len, ctx_cap, scale)?;
hip::dspark_block_attn(&q, &kd, &vd, ctx_k[il], ctx_v[il], &attn, b, h as i32, kv as i32, hd as i32, c0, c_len, ctx_cap[il], scale)?;
hip::router_gemv_batched(&attn, &lw.o_w, &o, d as i32, q_dim as i32, b)?;
hip::vec_add(&res, &o, &cur, b as usize * d)?;
hip::copy_f32(&cur, &res, b as usize * d)?;
@@ -325,24 +330,26 @@ mod gpu {
Ok(())
}
/// Snapshot of DSpark context rings at `seq_len` for PrefixCache restore.
/// Stores SWA window `min(seq_len, swa_win)` for layers 0/2, full `[0..seq_len)`
/// for global layer 1, and the single `frnn[seq_len - 1]` row (4.6 KiB).
/// Snapshot of DSpark context rings at `seq_len` stored in **pinned host RAM**
/// (`PinnedBuf`, 0 bytes GPU VRAM) for PrefixCache restore. Stores SWA window
/// `min(seq_len, swa_win)` for layers 0/2, full `[0..seq_len)` for global
/// layer 1, and the single `frnn[seq_len - 1]` row (4.6 KiB).
pub struct DsparkSnapshot {
pub seq_len: usize,
pub k: [DeviceBuf; 3],
pub v: [DeviceBuf; 3],
pub k: [PinnedBuf; 3],
pub v: [PinnedBuf; 3],
pub kv_start: [usize; 3],
pub n_rows: [usize; 3],
pub frnn_last: DeviceBuf,
pub frnn_last: PinnedBuf,
}
/// Persistent DSpark context rings (bf16): per-layer k/v [cap, kv_dim] +
/// frnn [frnn_cap, D]. `len` = committed context length (truncated on
/// partial accept; ring slots of kept vs rejected spans are disjoint).
/// Persistent DSpark context rings (bf16): per-layer k/v `[layer_cap[il], kv_dim]`
/// (SWA layers 0/2 sized to `cap.min(DS_SWA_RING)`, global layer 1 sized to `cap`)
/// + `frnn [frnn_cap, D]`. `len` = committed context length (truncated on partial
/// accept; ring slots of kept vs rejected spans are disjoint).
pub struct DsparkContext {
pub k: [DeviceBuf; 3], pub v: [DeviceBuf; 3], pub frnn: DeviceBuf,
pub cap: usize, pub frnn_cap: usize, pub len: usize,
pub cap: usize, pub layer_cap: [usize; 3], pub frnn_cap: usize, pub len: usize,
}
impl DsparkContext {
@@ -350,86 +357,94 @@ mod gpu {
let ring = |n: usize| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc_unpooled(n * 2)?; b.zero_async()?; Ok(b)
};
let kv = cap * DS_KV * DS_HD;
let layer_cap = [
cap.min(DS_SWA_RING),
cap,
cap.min(DS_SWA_RING),
];
let kv_dim = DS_KV * DS_HD;
Ok(Self {
k: [ring(kv)?, ring(kv)?, ring(kv)?],
v: [ring(kv)?, ring(kv)?, ring(kv)?],
k: [ring(layer_cap[0] * kv_dim)?, ring(layer_cap[1] * kv_dim)?, ring(layer_cap[2] * kv_dim)?],
v: [ring(layer_cap[0] * kv_dim)?, ring(layer_cap[1] * kv_dim)?, ring(layer_cap[2] * kv_dim)?],
frnn: ring(frnn_cap * DS_HIDDEN)?,
cap, frnn_cap, len: 0,
cap, layer_cap, frnn_cap, len: 0,
})
}
/// Snapshot committed DSpark context at `seq_len` so PrefixCache hits
/// restore exact drafter KV/frnn instead of running with zeroed rings.
/// Snapshot committed DSpark context at `seq_len` into pinned host RAM
/// (0 bytes GPU VRAM) so PrefixCache hits restore exact drafter KV/frnn.
pub fn snapshot(&self, seq_len: usize, swa_win: usize) -> Result<DsparkSnapshot, String> {
let kv_row_b = DS_KV * DS_HD * 2;
let mut k_snaps: Vec<DeviceBuf> = Vec::with_capacity(DS_LAYERS);
let mut v_snaps: Vec<DeviceBuf> = Vec::with_capacity(DS_LAYERS);
let mut k_snaps: Vec<PinnedBuf> = Vec::with_capacity(DS_LAYERS);
let mut v_snaps: Vec<PinnedBuf> = Vec::with_capacity(DS_LAYERS);
let mut kv_start = [0usize; 3];
let mut n_rows = [0usize; 3];
for il in 0..DS_LAYERS {
let is_swa = DS_SWA_LAYERS.contains(&il);
let lcap = self.layer_cap[il];
let n = if is_swa { seq_len.min(swa_win) } else { seq_len };
let s0 = seq_len.saturating_sub(n);
kv_start[il] = s0;
n_rows[il] = n;
let kb = DeviceBuf::alloc_unpooled((n * kv_row_b).max(2))?;
let vb = DeviceBuf::alloc_unpooled((n * kv_row_b).max(2))?;
let kb = PinnedBuf::alloc((n * kv_row_b).max(2))?;
let vb = PinnedBuf::alloc((n * kv_row_b).max(2))?;
if n > 0 {
let slot0 = s0 % self.cap;
let first = n.min(self.cap - slot0);
kb.copy2d_at(0, &self.k[il], slot0 * kv_row_b, kv_row_b, kv_row_b, kv_row_b, first)?;
vb.copy2d_at(0, &self.v[il], slot0 * kv_row_b, kv_row_b, kv_row_b, kv_row_b, first)?;
let slot0 = s0 % lcap;
let first = n.min(lcap - slot0);
kb.copy2d_from_dev_at(0, &self.k[il], slot0 * kv_row_b, kv_row_b, kv_row_b, kv_row_b, first)?;
vb.copy2d_from_dev_at(0, &self.v[il], slot0 * kv_row_b, kv_row_b, kv_row_b, kv_row_b, first)?;
if first < n {
let rem = n - first;
kb.copy2d_at(first * kv_row_b, &self.k[il], 0, kv_row_b, kv_row_b, kv_row_b, rem)?;
vb.copy2d_at(first * kv_row_b, &self.v[il], 0, kv_row_b, kv_row_b, kv_row_b, rem)?;
kb.copy2d_from_dev_at(first * kv_row_b, &self.k[il], 0, kv_row_b, kv_row_b, kv_row_b, rem)?;
vb.copy2d_from_dev_at(first * kv_row_b, &self.v[il], 0, kv_row_b, kv_row_b, kv_row_b, rem)?;
}
}
k_snaps.push(kb);
v_snaps.push(vb);
}
let fr_row_b = DS_HIDDEN * 2;
let frnn_last = DeviceBuf::alloc_unpooled(fr_row_b)?;
let frnn_last = PinnedBuf::alloc(fr_row_b)?;
if seq_len > 0 {
let slot = (seq_len - 1) % self.frnn_cap;
frnn_last.copy2d_at(0, &self.frnn, slot * fr_row_b, fr_row_b, fr_row_b, fr_row_b, 1)?;
frnn_last.copy2d_from_dev_at(0, &self.frnn, slot * fr_row_b, fr_row_b, fr_row_b, fr_row_b, 1)?;
} else {
frnn_last.zero_async()?;
frnn_last.zero();
}
let [k0, k1, k2]: [DeviceBuf; 3] = k_snaps.try_into().map_err(|_| "dspark snap k len")?;
let [v0, v1, v2]: [DeviceBuf; 3] = v_snaps.try_into().map_err(|_| "dspark snap v len")?;
let [k0, k1, k2]: [PinnedBuf; 3] = k_snaps.try_into().map_err(|_| "dspark snap k len")?;
let [v0, v1, v2]: [PinnedBuf; 3] = v_snaps.try_into().map_err(|_| "dspark snap v len")?;
Ok(DsparkSnapshot { seq_len, k: [k0, k1, k2], v: [v0, v1, v2], kv_start, n_rows, frnn_last })
}
/// Restore a `DsparkSnapshot` into `self` (whose `cap` must be >= `snap.seq_len`).
/// Restore a `DsparkSnapshot` from pinned host RAM into `self`
/// (whose `cap` must be >= `snap.seq_len`).
pub fn restore(&mut self, snap: &DsparkSnapshot) -> Result<(), String> {
let kv_row_b = DS_KV * DS_HD * 2;
for il in 0..DS_LAYERS {
let n = snap.n_rows[il];
let lcap = self.layer_cap[il];
if n > 0 {
let slot0 = snap.kv_start[il] % self.cap;
let first = n.min(self.cap - slot0);
self.k[il].copy2d_at(slot0 * kv_row_b, &snap.k[il], 0, kv_row_b, kv_row_b, kv_row_b, first)?;
self.v[il].copy2d_at(slot0 * kv_row_b, &snap.v[il], 0, kv_row_b, kv_row_b, kv_row_b, first)?;
let slot0 = snap.kv_start[il] % lcap;
let first = n.min(lcap - slot0);
self.k[il].copy2d_from_pinned_at(slot0 * kv_row_b, &snap.k[il], 0, kv_row_b, kv_row_b, kv_row_b, first)?;
self.v[il].copy2d_from_pinned_at(slot0 * kv_row_b, &snap.v[il], 0, kv_row_b, kv_row_b, kv_row_b, first)?;
if first < n {
let rem = n - first;
self.k[il].copy2d_at(0, &snap.k[il], first * kv_row_b, kv_row_b, kv_row_b, kv_row_b, rem)?;
self.v[il].copy2d_at(0, &snap.v[il], first * kv_row_b, kv_row_b, kv_row_b, kv_row_b, rem)?;
self.k[il].copy2d_from_pinned_at(0, &snap.k[il], first * kv_row_b, kv_row_b, kv_row_b, kv_row_b, rem)?;
self.v[il].copy2d_from_pinned_at(0, &snap.v[il], first * kv_row_b, kv_row_b, kv_row_b, kv_row_b, rem)?;
}
}
}
if snap.seq_len > 0 {
let fr_row_b = DS_HIDDEN * 2;
let slot = (snap.seq_len - 1) % self.frnn_cap;
self.frnn.copy2d_at(slot * fr_row_b, &snap.frnn_last, 0, fr_row_b, fr_row_b, fr_row_b, 1)?;
self.frnn.copy2d_from_pinned_at(slot * fr_row_b, &snap.frnn_last, 0, fr_row_b, fr_row_b, fr_row_b, 1)?;
}
self.len = snap.seq_len;
Ok(())
}
/// Commit the context for `m` fed tokens (taps [4][m,D], pos[m]) into the
/// rings at slot pos%cap. Caller truncates `len` on partial accept.
/// rings at slot `pos % layer_cap[il]`. Caller truncates `len` on partial accept.
pub fn commit(&mut self, w: &DsparkWeights, taps: &[DeviceBuf; 4], pos: &DeviceBuf, m: i32, eps: f32, theta: f32) -> Result<(), String> {
let kv = DS_KV * DS_HD; let mu = m as usize;
let ko = [DeviceBuf::alloc(mu * kv * 4)?, DeviceBuf::alloc(mu * kv * 4)?, DeviceBuf::alloc(mu * kv * 4)?];
@@ -440,8 +455,9 @@ mod gpu {
let vref = [&vo[0], &vo[1], &vo[2]];
dspark_context(w, tref, pos, m, kref, vref, &fr, eps, theta)?;
for il in 0..DS_LAYERS {
hip::dspark_scatter_bf16(&ko[il], &self.k[il], pos, m, kv as i32, self.cap as i32)?;
hip::dspark_scatter_bf16(&vo[il], &self.v[il], pos, m, kv as i32, self.cap as i32)?;
let lcap = self.layer_cap[il] as i32;
hip::dspark_scatter_bf16(&ko[il], &self.k[il], pos, m, kv as i32, lcap)?;
hip::dspark_scatter_bf16(&vo[il], &self.v[il], pos, m, kv as i32, lcap)?;
}
hip::dspark_scatter_bf16(&fr, &self.frnn, pos, m, DS_HIDDEN as i32, self.frnn_cap as i32)?;
Ok(())
@@ -472,8 +488,9 @@ mod gpu {
if nd > 0 {
let kref = [&dctx.k[0], &dctx.k[1], &dctx.k[2]];
let vref = [&dctx.v[0], &dctx.v[1], &dctx.v[2]];
let lcap = [dctx.layer_cap[0] as i32, dctx.layer_cap[1] as i32, dctx.layer_cap[2] as i32];
dspark_draft(dw, &embed, &embed_norm, &unembed, kref, vref, &dctx.frnn,
next_tok, cur_pos, nd as i32, dctx.cap as i32, dctx.frnn_cap as i32,
next_tok, cur_pos, nd as i32, lcap, dctx.frnn_cap as i32,
d.swa_win, d.eps, 1e6, vocab as i32, &mut draft)?;
}
// 2. batched verify B=nd+1 (anchor + drafts), capture taps + hist snaps (skip single-row unembed)
@@ -824,7 +841,7 @@ mod tests {
let frnn = up(&frnn_h);
let mut ids = [0i32; 7];
dspark_draft(&w, &embed, &enorm, &unembed, [&ck[0], &ck[1], &ck[2]], [&cv[0], &cv[1], &cv[2]], &frnn,
anchor_tok, anchor_pos, n_draft, cap as i32, frnn_cap as i32, swa_win, eps, theta, vocab as i32, &mut ids).unwrap();
anchor_tok, anchor_pos, n_draft, [cap as i32; 3], frnn_cap as i32, swa_win, eps, theta, vocab as i32, &mut ids).unwrap();
// ---- CPU oracle ----
let rms = |x: &[f32], nw: &[f32]| -> Vec<f32> {
let ss: f32 = x.iter().map(|v| v * v).sum();
+37 -32
View File
@@ -15,7 +15,7 @@ use crate::SafetensorsArchive;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use vetta_infer_hip::DeviceBuf;
use vetta_infer_hip::{DeviceBuf, PinnedBuf};
/// Resident weights for one physical layer step `ip`.
pub struct LayerWeights {
@@ -319,27 +319,29 @@ pub fn rollback_spec(d: &Dims, states: &mut [Option<LayerState>], accepted: usiz
}
/// A checkpoint of one layer's decode state at a prefix boundary `seq_len`: the
/// KV prefix `[n_kv, seq_len, hd]` per pass + the ShortConv history rings. Sized
/// to seq_len (KV unpooled), held in the prefix cache across requests. Restoring
/// it and prefilling the suffix is exact (proofs/prefix_cache.lean restore_equiv).
/// KV prefix `[n_kv, win, hd]` per pass + the ShortConv history rings, stored in
/// **pinned host RAM** (`PinnedBuf`, 0 bytes GPU VRAM) and transferred via async
/// SDMA on stream 0. Restoring it and prefilling the suffix is exact
/// (`proofs/prefix_cache.lean restore_equiv`).
pub struct LayerSnapshot {
pub seq_len: usize,
/// First KV position stored in this snapshot. For full-attn layers it is 0
/// (whole prefix); for SWA layers it is seq_len - min(seq_len, swa_win), so
/// only the causal window is checkpointed (the older KV is never read again).
pub kv_start: usize,
pub k_cache: Vec<DeviceBuf>, pub v_cache: Vec<DeviceBuf>,
pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3],
pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3],
pub k_cache: Vec<PinnedBuf>, pub v_cache: Vec<PinnedBuf>,
pub hist_k: [PinnedBuf; 3], pub hist_v: [PinnedBuf; 3],
pub hist_a: [PinnedBuf; 3], pub hist_m: [PinnedBuf; 3],
}
impl LayerState {
/// Snapshot the KV prefix plus the current ShortConv history rings. For a
/// SWA layer (`swa`) only the last `min(seq_len, swa_win)` KV positions are
/// stored (the causal window): attention at any future pos >= seq_len reads
/// [pos-swa_win+1..pos] ⊆ [kv_start..pos], so the discarded older KV is never
/// observed (proofs/prefix_cache.lean swa_window_restore_equiv). Full-attn
/// layers attend globally and keep the whole `[0, seq_len)` prefix.
/// Snapshot the KV prefix plus the current ShortConv history rings into
/// pinned host RAM (0 bytes VRAM). For a SWA layer (`swa`) only the last
/// `min(seq_len, swa_win)` KV positions are stored (the causal window):
/// attention at any future pos >= seq_len reads [pos-swa_win+1..pos] ⊆
/// [kv_start..pos], so the discarded older KV is never observed
/// (`proofs/prefix_cache.lean swa_window_restore_equiv`). Full-attn layers
/// attend globally and keep the whole `[0, seq_len)` prefix.
pub fn snapshot(&self, d: &Dims, seq_len: usize, swa: bool) -> Result<LayerSnapshot, String> {
let es = if f16_kv() { 2 } else { 4 };
let win = if swa { seq_len.min(d.swa_win.max(0) as usize) } else { seq_len };
@@ -351,18 +353,20 @@ impl LayerState {
let s0 = kv_start % r;
let first = win.min(r - s0);
let row = win * d.hd * es;
let snap_kv = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc_unpooled(d.n_kv * row)?;
b.copy2d_at(0, src, s0 * d.hd * es, row, r * d.hd * es, first * d.hd * es, d.n_kv)?;
let snap_kv = |src: &DeviceBuf| -> Result<PinnedBuf, String> {
let b = PinnedBuf::alloc(d.n_kv * row)?;
b.copy2d_from_dev_at(0, src, s0 * d.hd * es, row, r * d.hd * es, first * d.hd * es, d.n_kv)?;
if win > first {
b.copy2d_at(first * d.hd * es, src, 0, row, r * d.hd * es, (win - first) * d.hd * es, d.n_kv)?;
b.copy2d_from_dev_at(first * d.hd * es, src, 0, row, r * d.hd * es, (win - first) * d.hd * es, d.n_kv)?;
}
Ok(b)
};
let k_cache = self.k_cache.iter().map(snap_kv).collect::<Result<Vec<_>, _>>()?;
let v_cache = self.v_cache.iter().map(snap_kv).collect::<Result<Vec<_>, _>>()?;
let cp = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc(src.bytes)?; b.copy_from(src, src.bytes)?; Ok(b)
let cp = |src: &DeviceBuf| -> Result<PinnedBuf, String> {
let b = PinnedBuf::alloc(src.bytes)?;
b.copy_from_dev(src, src.bytes)?;
Ok(b)
};
Ok(LayerSnapshot {
seq_len, kv_start, k_cache, v_cache,
@@ -373,11 +377,12 @@ impl LayerState {
})
}
/// Restore the KV prefix `[kv_start, seq_len)` + history into `self` (whose
/// max_seq must be >= snap.seq_len). For SWA snapshots kv_start > 0: positions
/// below it are left untouched (never read by the causal window); the suffix
/// prefill fills `[seq_len, pos)`. Attention at pos >= seq_len reads only the
/// restored window + suffix, so this is observationally exact (restore_equiv).
/// Restore the KV prefix `[kv_start, seq_len)` + history from pinned host RAM
/// into `self` (whose max_seq must be >= snap.seq_len). For SWA snapshots
/// kv_start > 0: positions below it are left untouched (never read by the
/// causal window); the suffix prefill fills `[seq_len, pos)`. Attention at
/// pos >= seq_len reads only the restored window + suffix, so this is
/// observationally exact (restore_equiv).
pub fn restore(&mut self, d: &Dims, snap: &LayerSnapshot) -> Result<(), String> {
let es = if f16_kv() { 2 } else { 4 };
let win = snap.seq_len - snap.kv_start;
@@ -386,22 +391,22 @@ impl LayerState {
let first = win.min(r - s0);
let row = win * d.hd * es;
for (dst, src) in self.k_cache.iter().zip(&snap.k_cache) {
dst.copy2d_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?;
dst.copy2d_from_pinned_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?;
if win > first {
dst.copy2d_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?;
dst.copy2d_from_pinned_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?;
}
}
for (dst, src) in self.v_cache.iter().zip(&snap.v_cache) {
dst.copy2d_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?;
dst.copy2d_from_pinned_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?;
if win > first {
dst.copy2d_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?;
dst.copy2d_from_pinned_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?;
}
}
for i in 0..3 {
self.hist_k[i].copy_from(&snap.hist_k[i], snap.hist_k[i].bytes)?;
self.hist_v[i].copy_from(&snap.hist_v[i], snap.hist_v[i].bytes)?;
self.hist_a[i].copy_from(&snap.hist_a[i], snap.hist_a[i].bytes)?;
self.hist_m[i].copy_from(&snap.hist_m[i], snap.hist_m[i].bytes)?;
self.hist_k[i].copy_from_pinned(&snap.hist_k[i], snap.hist_k[i].bytes)?;
self.hist_v[i].copy_from_pinned(&snap.hist_v[i], snap.hist_v[i].bytes)?;
self.hist_a[i].copy_from_pinned(&snap.hist_a[i], snap.hist_a[i].bytes)?;
self.hist_m[i].copy_from_pinned(&snap.hist_m[i], snap.hist_m[i].bytes)?;
}
Ok(())
}
+11 -6
View File
@@ -121,12 +121,17 @@ Five ideas explain almost everything that will surprise you:
~6.3 ms/token. Internal M=1-vs-M=B parity is relaxed to a global-scale numeric
tolerance per the approved P1 policy; greedy-vs-reference remains the EXACT
blocking gate (serve_gen 4/4).
- **VRAM is flat and bounded (2026-12-02).** Persistent per-layer KV/ShortConv
states reused across requests (no ±3.75 GB alloc/free sawtooth), SWA-window
checkpoints (only the last 1024 KV positions for the 40 SWA pools, full prefix
for the 8 full-attn pools), prefix cache cap 8 with grid protection +
LRU-on-restore, and a 512 MiB cap on the buffer pool. Long→short session
switches reuse the persistent KV instead of reallocating it.
- **VRAM is flat and bounded — zero-VRAM checkpoints in pinned host RAM (2026-12-02, measured).**
Persistent per-layer KV/ShortConv states reused across requests (40 SWA pools on
1280-slot rings + 8 Global pools; DSpark SWA layers 0/2 also on 1280-slot rings,
saving ~258 MiB at 32k), power-of-two `BUF_POOL` bucketing (512 MiB cap), and all
`PrefixCache` snapshots (`LayerSnapshot` KV + ShortConv + `DsparkSnapshot`) stored
in **page-locked host RAM** (`PinnedBuf` via `hipHostMallocDefault`, async SDMA
transfers on stream 0, `hipStreamSynchronize` before `hipHostFree` on drop).
Verified on `gfx1150`: 64 MiB `PinnedBuf` adds `+0.00 MiB` VRAM, and a 4-turn
multi-checkpoint sweep up to 2100 tokens filling all 8 `PrefixCache` slots with
`VETTA_SPEC=1` holds VRAM flat at **`20,674 → 20,672 → 20,676 → 20,676 MiB`**
(Turn 1→4 delta `+2.00 MiB`, `RESUME 0→607→1107→1607`, 100% EXACT parity).
- **Long agent prompts are no longer refused (2026-12-02).** strata-ctl always
sends max_new=16384; the budget is now clamped to the window (`clamp_max_new`)
instead of hard-erroring past 16382 prompt tokens, and the window is
+11 -1
View File
@@ -34,10 +34,20 @@ int vetta_buf_alloc(void** out, size_t bytes);
int vetta_buf_free(void* p);
int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
int vetta_buf_d2h(void* dst, const void* src, size_t bytes);
// Device-to-device copies (prefix-checkpoint snapshot/restore).
// Device-to-device copies (legacy/internal).
int vetta_buf_copy(void* dst, const void* src, size_t bytes);
int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src, size_t spitch,
size_t width, size_t height);
// Pinned host RAM lifecycle + async D2H/H2D copies for zero-VRAM PrefixCache
// checkpoints (hipHostMallocDefault / hipHostFree with stream sync on free).
int vetta_host_alloc(void** out, size_t bytes);
int vetta_host_free(void* p);
int vetta_buf_d2h_async(void* dst_host, const void* src_dev, size_t bytes);
int vetta_buf_h2d_async(void* dst_dev, const void* src_host, size_t bytes);
int vetta_buf_copy2d_d2h_async(void* dst_host, size_t dpitch, const void* src_dev,
size_t spitch, size_t width, size_t height);
int vetta_buf_copy2d_h2d_async(void* dst_dev, size_t dpitch, const void* src_host,
size_t spitch, size_t width, size_t height);
// k_rms_norm (kernel #2): y[row] = x[row] * rsqrt(mean(x^2)+eps) * w.
int vetta_rms_norm_f32(const float* x, const float* w, float* y,
+39
View File
@@ -82,6 +82,45 @@ extern "C" int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src,
HIP_CHECK(hipMemcpy2D(dst, dpitch, src, spitch, width, height, hipMemcpyDeviceToDevice));
return 0;
}
// Pinned host RAM buffers for zero-VRAM PrefixCache checkpoints (matches strata
// PromptCkpt): hipHostMallocDefault lives in host RAM (0 bytes VRAM) and transfers
// via SDMA on stream 0 with hipMemcpy[2D]Async. vetta_host_free syncs stream 0
// before hipHostFree so in-flight async copies never race with eviction/drop.
extern "C" int vetta_host_alloc(void** out, size_t bytes) {
if (!out) return 1;
HIP_CHECK(hipHostMalloc(out, bytes, hipHostMallocDefault));
return 0;
}
extern "C" int vetta_host_free(void* p) {
if (!p) return 0;
(void)hipStreamSynchronize((hipStream_t)0);
HIP_CHECK(hipHostFree(p));
return 0;
}
extern "C" int vetta_buf_d2h_async(void* dst_host, const void* src_dev, size_t bytes) {
if (bytes == 0) return 0;
HIP_CHECK(hipMemcpyAsync(dst_host, src_dev, bytes, hipMemcpyDeviceToHost, (hipStream_t)0));
return 0;
}
extern "C" int vetta_buf_h2d_async(void* dst_dev, const void* src_host, size_t bytes) {
if (bytes == 0) return 0;
HIP_CHECK(hipMemcpyAsync(dst_dev, src_host, bytes, hipMemcpyHostToDevice, (hipStream_t)0));
return 0;
}
extern "C" int vetta_buf_copy2d_d2h_async(void* dst_host, size_t dpitch, const void* src_dev,
size_t spitch, size_t width, size_t height) {
if (width == 0 || height == 0) return 0;
HIP_CHECK(hipMemcpy2DAsync(dst_host, dpitch, src_dev, spitch, width, height,
hipMemcpyDeviceToHost, (hipStream_t)0));
return 0;
}
extern "C" int vetta_buf_copy2d_h2d_async(void* dst_dev, size_t dpitch, const void* src_host,
size_t spitch, size_t width, size_t height) {
if (width == 0 || height == 0) return 0;
HIP_CHECK(hipMemcpy2DAsync(dst_dev, dpitch, src_host, spitch, width, height,
hipMemcpyHostToDevice, (hipStream_t)0));
return 0;
}
// Block until all queued GPU work completes (profiling phase boundaries; the
// batched forward is otherwise fully async with no host sync until final d2h).
extern "C" int vetta_synchronize(void) {
@@ -141,4 +141,26 @@ Dopo gli interventi descritti sotto, su **entrambi** i workload misurati il draf
- Il drafter resta **opt-in** via `VETTA_SPEC=1` (path di default `OFF` invariato e +16% più veloce grazie al dispatch WMMA su `gemm_bf16` e al kernel SWA small-M).
- `VETTA_SPEC_ND=<k>` permette comunque di fissare `n_draft` per A/B; `VETTA_DBG_SPEC=1` stampa le statistiche per richiesta su `stderr`.
- Le modifiche sono pronte nel working tree (non ancora committate) e `inkling-server.service` è rimasto spento durante i test.
- Le modifiche sono state committate e pushate su `main` (commit `c1c5221`).
---
## 7. Chiusura Punto 3 memoria: `PrefixCache` in RAM pinned (`0 byte VRAM`) + SWA ring DSpark
Chiuso anche l'ultimo punto del piano VRAM piatta ([`2026-12-02-piano-vram-piatta-e-guida-drafter.md`](2026-12-02-piano-vram-piatta-e-guida-drafter.md)):
- **`PinnedBuf` (`hipHostMallocDefault` / `hipHostFree`) in `vetta_kernels.{h,hip}` e `crates/vetta-infer-hip/src/lib.rs`:**
- Aggiunte `vetta_host_alloc`, `vetta_host_free` (con `hipStreamSynchronize(0)` prima di `hipHostFree` per escludere race con copie async), e copie asincrone 1D/2D `vetta_buf_{d2h,h2d}_async`, `vetta_buf_copy2d_{d2h,h2d}_async` su stream 0.
- Wrapper safe `PinnedBuf` + `DeviceBuf::{copy_from_pinned, copy2d_from_pinned_at}`.
- **Spostati `LayerSnapshot` (`layer.rs`) e `DsparkSnapshot` (`dspark.rs`) da `DeviceBuf` a `PinnedBuf`:**
- Tutti i checkpoint della `PrefixCache` (KV trunk + ShortConv hist + KV/frnn DSpark) ora vivono in RAM host pinned (**0 byte di VRAM**, liberando 3–6 GiB su conversazioni lunghe e preparando il terreno allo streaming dei layer in DMA).
- **SWA ring da `1280` posizioni (`DS_SWA_RING`) sui layer SWA 0 e 2 di `DsparkContext` (`dspark.rs`):**
- Riduce la VRAM permanente di `DsparkContext` a 32k da ~413 MiB a ~155 MiB (**-258 MiB**).
- **Validazione misurata su `gfx1150`:**
- `pinned_buf_zero_vram_and_roundtrip_2d`: 64 MiB `PinnedBuf` → delta VRAM **`+0.00 MiB`** (`165675008 → 165675008`), round-trip 2D con wrap-around bit-exact (**PASS**).
- `serve_gen_pinned_prefix_cache_vram_flat` (4 turni fino a 2100 token, `VETTA_SPEC=1`, 8/8 checkpoint pieni):
- Turn 1 (`prompt=600`, `ckpts=3`): `20,674.00 MiB`
- Turn 2 (`prompt=1100`, `resumed=607`, `ckpts=6`): `20,672.00 MiB`
- Turn 3 (`prompt=1600`, `resumed=1107`, `ckpts=8`): `20,676.00 MiB`
- Turn 4 (`prompt=2100`, `resumed=1607`, `ckpts=8`): `20,676.00 MiB` (**delta Turn 1→4 = `+2.00 MiB`** — VRAM completamente piatta!).
- `dspark_draft_parity` (7/7 EXACT), `serve_gen_spec_multi_token_parity` (16/16 EXACT), `serve_gen_spec_prefix_cache_multi_turn_parity` (Turn 1+2 `RESUME 45` EXACT), `RUSTFLAGS="-D warnings" cargo test --workspace` (**PASS**).