[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

+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(())
}