[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

+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]