Compare commits

...
2 Commits
Author SHA1 Message Date
adm 8c8ae4485a [Docs] Prefix checkpoint cache landed: multi-turn prefill reuse, EXACT parity, 57.8x measured 2026-12-01 20:30:33 +01:00
adm 736c541887 [GW][LD][HIP][Proofs] Wire prefix checkpoint cache into serve: restore longest prefix, prefill only new suffix
Concept ported from strata --auto-ckpt, adapted to vetta's contiguous per-pass
KV + ShortConv history (proofs/prefix_cache.lean, restore_equiv). serve_gen now
restores the longest cached STRICT prefix of a prompt and prefills only the new
suffix tokens; the final logits still come from a real forward of the last prompt
token. Checkpoints save at pos (prompt + generated non-EOS tokens) so the next
turn reuses the full prior context. Pinned anchors {512,1024} never evicted (I3),
LRU at cap 6; KV snapshots unpooled (freed on eviction). VETTA_NO_PREFIX_CACHE
forces cold prefill for A/B.

Device-to-device copy FFI (vetta_buf_copy / vetta_buf_copy2d) + DeviceBuf
copy_from/copy2d_from; LayerState snapshot/restore (pitched KV prefix + hist).

Verified: CPU 91 + gw GPU 5 + hip GPU 18 + ld GPU 18 green; Lean 0 sorryAx.
Multi-turn parity EXACT (restore == cold re-prefill), both prewarm- and
decode-state checkpoints. Measured (gfx1150, Inkling-2-Mini, FP16 KV, greedy):
605-token prompt, 600-token cached prefix -> prefill 132.5s cold vs 2.29s warm
(57.8x), end-to-end 133.2s vs 3.2s (41.8x).
2026-12-01 20:30:13 +01:00
7 changed files with 242 additions and 17 deletions

No files matched your search

+128 -7
View File
@@ -16,6 +16,7 @@
//! is callable from an integration test without spawning the binary. //! is callable from an integration test without spawning the binary.
use std::io::{self, BufRead, Write}; use std::io::{self, BufRead, Write};
use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc}; use std::sync::{mpsc, Arc};
use std::time::Instant; use std::time::Instant;
@@ -26,7 +27,7 @@ use vetta_infer_abi::sampler::{
use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand}; use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
use vetta_infer_hip::DeviceBuf; use vetta_infer_hip::DeviceBuf;
use vetta_infer_ld::inkling::parse_config; use vetta_infer_ld::inkling::parse_config;
use vetta_infer_ld::layer::{forward_inkling_with_state, Dims, LayerState, WeightCache}; use vetta_infer_ld::layer::{forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
use vetta_infer_ld::SafetensorsArchive; use vetta_infer_ld::SafetensorsArchive;
use crate::session::ServeSession; use crate::session::ServeSession;
@@ -50,6 +51,92 @@ const SITU_LB: f32 = 25.0;
/// not limited by the 64 KB LDS cap. /// not limited by the 64 KB LDS cap.
const MAX_CONTEXT: usize = 32768; const MAX_CONTEXT: usize = 32768;
/// Prefix checkpoint cache (concept ported from strata `--auto-ckpt`, verified in
/// proofs/prefix_cache.lean). Keeps snapshots of KV+ShortConv at prefix boundaries
/// so a new request whose prompt extends a cached prefix restores it and prefills
/// only the NEW tokens (restore_equiv: exact). Pinned anchors {512,1024} are never
/// evicted (I3); otherwise LRU eviction at the cap.
const PREFIX_CACHE_CAP: usize = 6;
fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 }
struct Checkpoint {
tokens: Vec<i32>,
layers: Vec<Option<LayerSnapshot>>,
lru: u64,
}
/// Resident pool of prefix checkpoints (interior mutability: serve_gen holds
/// `&InklingEngine`). Single conversation slot (FIFO serve).
pub struct PrefixCache {
pool: Vec<Checkpoint>,
tick: u64,
}
impl PrefixCache {
pub fn new() -> Self { Self { pool: Vec::new(), tick: 0 } }
/// Index + length of the longest checkpoint whose tokens are a STRICT prefix
/// of ids (l < ids.len()). The suffix must be non-empty: the final logits come
/// from a real forward of the last prompt token, which a full-length restore
/// (l == ids.len()) would not produce. Longer next-turn prompts still match.
fn best_match(&self, ids: &[i32]) -> Option<(usize, usize)> {
let mut best: Option<(usize, usize)> = None;
for (i, ck) in self.pool.iter().enumerate() {
let l = ck.tokens.len();
if l == 0 || l >= ids.len() { continue; }
if ck.tokens[..] == ids[..l] && best.map_or(true, |(_, bl)| l > bl) {
best = Some((i, l));
}
}
best
}
/// 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> {
let ck = &self.pool[idx];
// A usable checkpoint must cover EVERY layer: a partially-restored state
// would cold-start the missing layers and break prefix equivalence.
if ck.layers.len() != states.len() || ck.layers.iter().any(|s| s.is_none()) {
return Err("incomplete prefix checkpoint".into());
}
for (ip, snap) in ck.layers.iter().enumerate() {
if let Some(s) = snap {
let mut st = new_state(d, max_seq, s.k_cache.len())?;
st.restore(d, s)?;
states[ip] = Some(st);
}
}
Ok(ck.tokens.len())
}
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
/// evict oldest unpinned). Mirrors poolInsert in proofs/prefix_cache.lean.
fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> {
let seq = tokens.len();
if seq == 0 { return Ok(()); }
let layers: Vec<Option<LayerSnapshot>> = states.iter()
.map(|st| st.as_ref().map(|s| s.snapshot(d, seq)).transpose())
.collect::<Result<_, _>>()?;
self.tick += 1;
let lru = self.tick;
if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) {
ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru;
return Ok(());
}
if self.pool.len() < PREFIX_CACHE_CAP {
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
return Ok(());
}
let victim = self.pool.iter().enumerate()
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
.min_by_key(|(_, c)| c.lru).map(|(i, _)| i);
if let Some(i) = victim {
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
}
Ok(())
}
}
/// A loaded Inkling model ready to run autoregressive forwards. /// A loaded Inkling model ready to run autoregressive forwards.
pub struct InklingEngine { pub struct InklingEngine {
ar: SafetensorsArchive, ar: SafetensorsArchive,
@@ -58,6 +145,7 @@ pub struct InklingEngine {
n_layers: usize, n_layers: usize,
eos: i32, eos: i32,
cap: f32, cap: f32,
prefix: RefCell<PrefixCache>,
} }
impl InklingEngine { impl InklingEngine {
@@ -103,6 +191,7 @@ impl InklingEngine {
n_layers: t.n_layers, n_layers: t.n_layers,
eos: cfg.eos_token_id as i32, eos: cfg.eos_token_id as i32,
cap: t.final_logit_softcapping as f32, cap: t.final_logit_softcapping as f32,
prefix: RefCell::new(PrefixCache::new()),
}) })
} }
@@ -137,8 +226,9 @@ fn emit_all(emit: &mut dyn FnMut(String), lines: Vec<String>) {
/// wire lines through `emit`. `stop` is set asynchronously (stdin reader thread) /// wire lines through `emit`. `stop` is set asynchronously (stdin reader thread)
/// to interrupt decode; it is consumed here (drain→DONE) and reset on exit. /// to interrupt decode; it is consumed here (drain→DONE) and reset on exit.
/// ///
/// Each request resets the per-layer state and re-prefills the prompt (prefix /// Each request restores the longest cached prefix of its prompt (if any) and
/// cache reuse is a later performance refinement; correctness is identical). /// prefills only the new suffix tokens; with no match it cold-prefills the whole
/// prompt. Both paths are observationally identical (proofs/prefix_cache.lean).
pub fn serve_gen( pub fn serve_gen(
eng: &InklingEngine, eng: &InklingEngine,
g: &ParsedGen, g: &ParsedGen,
@@ -165,16 +255,36 @@ pub fn serve_gen(
} }
}; };
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
// the longest cached strict prefix of this prompt and prefill only the NEW
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
let mut start = 0usize;
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
if let Some((idx, _l)) = eng.prefix.borrow().best_match(&g.ids) {
match eng.prefix.borrow().restore(idx, &mut states, &eng.d, max_seq) {
Ok(n) => start = n,
Err(_) => {
// Incomplete/failed restore: fall back to a clean cold prefill.
states = match eng.fresh_states(max_seq) {
Ok(s) => s,
Err(e) => { emit_all(emit, sess.on_error(&e)); return; }
};
}
}
}
}
// Resident weight cache for this request: weights upload once and stay on // Resident weight cache for this request: weights upload once and stay on
// the GPU across prefill + decode (no per-token NVMe expert re-reads). // the GPU across prefill + decode (no per-token NVMe expert re-reads).
let cache = WeightCache::new(&eng.ar); let cache = WeightCache::new(&eng.ar);
// --- Prefill: run the forward over every prompt token, growing KV/history. --- // --- Prefill: run the forward over the NEW prompt tokens, growing KV/history. ---
let t0 = Instant::now(); let t0 = Instant::now();
let mut pos = 0i32; let mut pos = start as i32;
let mut history: Vec<i32> = Vec::with_capacity(n_prompt + g.max_new); let mut history: Vec<i32> = g.ids[..start].to_vec();
history.reserve(n_prompt - start + g.max_new);
let mut logits: Option<DeviceBuf> = None; let mut logits: Option<DeviceBuf> = None;
for (i, &tok) in g.ids.iter().enumerate() { for (i, &tok) in g.ids.iter().enumerate().skip(start) {
if stop.load(Ordering::Relaxed) { if stop.load(Ordering::Relaxed) {
sess.on_stop(); sess.on_stop();
let ms = t0.elapsed().as_secs_f64() * 1000.0; let ms = t0.elapsed().as_secs_f64() * 1000.0;
@@ -208,6 +318,10 @@ pub fn serve_gen(
} }
} }
if g.max_new == 0 { if g.max_new == 0 {
// Pre-warm folded the full prompt into `states`: checkpoint it for reuse.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
}
stop.store(false, Ordering::Relaxed); stop.store(false, Ordering::Relaxed);
return; return;
} }
@@ -283,6 +397,13 @@ pub fn serve_gen(
pos += 1; pos += 1;
} }
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0; let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
// Checkpoint the full processed prefix (prompt + generated tokens) so the next
// turn restores it and prefills only its new suffix. `pos` counts the tokens
// actually folded into `states` (history[..pos]); a sampled token that was not
// forwarded (EOS / last length step) is excluded, keeping the checkpoint valid.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
}
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default()); emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
stop.store(false, Ordering::Relaxed); stop.store(false, Ordering::Relaxed);
} }
+16
View File
@@ -29,6 +29,8 @@ mod ffi {
pub fn vetta_buf_free(p: *mut c_void) -> c_int; pub fn vetta_buf_free(p: *mut c_void) -> c_int;
pub fn vetta_buf_h2d(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int; pub fn vetta_buf_h2d(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_d2h(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int; 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_rms_norm_f32( pub fn vetta_rms_norm_f32(
x: *const c_float, w: *const c_float, y: *mut c_float, x: *const c_float, w: *const c_float, y: *mut c_float,
rows: c_int, d: c_int, eps: c_float, stream: *mut c_void, rows: c_int, d: c_int, eps: c_float, stream: *mut c_void,
@@ -242,6 +244,20 @@ impl DeviceBuf {
if rc != 0 { return Err("d2h failed".into()); } if rc != 0 { return Err("d2h failed".into()); }
Ok(()) Ok(())
} }
/// Device-to-device copy of `bytes` from `src` into `self`.
pub fn copy_from(&self, src: &DeviceBuf, bytes: usize) -> Result<(), String> {
if bytes > self.bytes || bytes > src.bytes { return Err("copy overflow".into()); }
let rc = unsafe { ffi::vetta_buf_copy(self.ptr, src.ptr, bytes) };
if rc != 0 { return Err("d2d copy failed".into()); }
Ok(())
}
/// Pitched device-to-device copy: `height` rows of `width` bytes, source row
/// stride `spitch`, destination row stride `dpitch` (KV prefix sub-block).
pub fn copy2d_from(&self, src: &DeviceBuf, dpitch: usize, spitch: usize, width: usize, height: usize) -> Result<(), String> {
let rc = unsafe { ffi::vetta_buf_copy2d(self.ptr, dpitch, src.ptr, spitch, width, height) };
if rc != 0 { return Err("d2d copy2d failed".into()); }
Ok(())
}
} }
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
+58
View File
@@ -207,6 +207,64 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState
}) })
} }
/// 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).
pub struct LayerSnapshot {
pub seq_len: 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],
}
impl LayerState {
/// Snapshot the KV prefix `[0, seq_len)` (pitched copy out of the
/// `[n_kv, max_seq, hd]` cache) plus the current ShortConv history rings.
pub fn snapshot(&self, d: &Dims, seq_len: usize) -> Result<LayerSnapshot, String> {
let es = if f16_kv() { 2 } else { 4 };
let row = seq_len * d.hd * es;
let snap_kv = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc_unpooled(d.n_kv * row)?;
b.copy2d_from(src, row, self.max_seq * d.hd * es, row, 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)
};
Ok(LayerSnapshot {
seq_len, k_cache, v_cache,
hist_k: [cp(&self.hist_k[0])?, cp(&self.hist_k[1])?, cp(&self.hist_k[2])?],
hist_v: [cp(&self.hist_v[0])?, cp(&self.hist_v[1])?, cp(&self.hist_v[2])?],
hist_a: [cp(&self.hist_a[0])?, cp(&self.hist_a[1])?, cp(&self.hist_a[2])?],
hist_m: [cp(&self.hist_m[0])?, cp(&self.hist_m[1])?, cp(&self.hist_m[2])?],
})
}
/// Restore the KV prefix `[0, snap.seq_len)` + history into `self` (whose
/// max_seq must be >= snap.seq_len). Positions >= seq_len stay zero for the
/// suffix prefill to fill; attention at pos >= seq_len reads only [0, pos].
pub fn restore(&mut self, d: &Dims, snap: &LayerSnapshot) -> Result<(), String> {
let es = if f16_kv() { 2 } else { 4 };
let row = snap.seq_len * d.hd * es;
for (dst, src) in self.k_cache.iter().zip(&snap.k_cache) {
dst.copy2d_from(src, self.max_seq * d.hd * es, row, row, d.n_kv)?;
}
for (dst, src) in self.v_cache.iter().zip(&snap.v_cache) {
dst.copy2d_from(src, self.max_seq * d.hd * es, row, row, 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)?;
}
Ok(())
}
}
/// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer /// KV cache dtype switch. The CPU-oracle parity baseline (and the ld packer
/// tests) use F32; the resident serve opts into FP16 — the exact strata default /// tests) use F32; the resident serve opts into FP16 — the exact strata default
/// (KvDtype::FP16, "default lossless FP16"), parity-verified EXACT (16/40 greedy /// (KvDtype::FP16, "default lossless FP16"), parity-verified EXACT (16/40 greedy
+22 -7
View File
@@ -96,11 +96,23 @@ Five ideas explain almost everything that will surprise you:
dropped it to ~54% (measured A/B 101.2% → 54.2%). The residual ~54% is genuine dropped it to ~54% (measured A/B 101.2% → 54.2%). The residual ~54% is genuine
kernel-launch submission cost (~1300 launches/token), removed only by HIP graph kernel-launch submission cost (~1300 launches/token), removed only by HIP graph
capture. capture.
- **Multi-turn prefill is no longer re-paid: the prefix checkpoint cache landed
(2026-12-01, measured).** Ported in concept from strata `--auto-ckpt` and proven
in `proofs/prefix_cache.lean` (`restore_equiv`, 0 `sorryAx`), `serve_gen` restores
the longest cached prefix of a prompt and prefills only the NEW suffix tokens;
the checkpoint saves at `pos` (prompt + generated tokens) so the next turn reuses
the whole prior context. Pinned anchors {512,1024} are never evicted (I3), LRU at
cap 6, KV snapshots unpooled (freed on eviction). **Parity EXACT** (restore ==
cold re-prefill, token-for-token, both prewarm- and decode-state checkpoints).
Measured on `gfx1150`, Inkling-2-Mini, FP16 KV, greedy: a 605-token prompt with a
600-token cached prefix prefills in **2.29 s vs 132.5 s cold (57.8×)**, end-to-end
**3.2 s vs 133.2 s (41.8×)**. This collapses the *second-turn* time-to-first-token;
the *first* turn still pays sequential prefill (batched prefill is the next brick).
- **What is NOT done yet (the frontier):** HIP graph capture (collapse the - **What is NOT done yet (the frontier):** HIP graph capture (collapse the
per-token launches → near-zero host CPU), batched prefill / prefix cache (make per-token launches → near-zero host CPU), batched/chunked prefill (M>1 attention
large-prompt time-to-first-token seconds, not minutes), and the expert-GEMV + grouped MoE, make the *first* large-prompt time-to-first-token seconds, not
math speedup (WMMA). These are the M2 performance work — correctness is minutes), and the expert-GEMV math speedup (WMMA). These are the M2 performance
already there; speed is the next axis. work — correctness is already there; speed is the next axis.
## The road to the goal ## The road to the goal
@@ -118,9 +130,11 @@ on 2026-12-01 (see *Current state*). The path, in order:
4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load). 4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load).
5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity, 5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity,
first real GUI conversation 2026-12-01). first real GUI conversation 2026-12-01).
6. **M2 performance** — ⏳ the current frontier: HIP graph capture (host CPU), 6. **M2 performance** — ⏳ the current frontier: prefix checkpoint cache ✅ landed
batched prefill / prefix cache (time-to-first-token), expert-GEMV WMMA (multi-turn prefill reuse, EXACT parity, 57.8× measured); HIP graph capture
(decode tok/s). Measured against the reference, no unmeasured claims. (host CPU), batched/chunked prefill (first-turn time-to-first-token), and
expert-GEMV WMMA (decode tok/s) still pending. Measured against the reference,
no unmeasured claims.
7. **M3 Lyra co-processor** — remote drafting, semantic domain routing, 7. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
domain-aware expert prefetch. domain-aware expert prefetch.
@@ -135,6 +149,7 @@ lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean lean proofs/serve_session.lean
lean proofs/arena_plan.lean lean proofs/arena_plan.lean
lean proofs/prefix_cache.lean
# Opt-in live tests against the real Inkling artifact: # Opt-in live tests against the real Inkling artifact:
cargo test -p vetta-infer-ld -- --ignored inkling cargo test -p vetta-infer-ld -- --ignored inkling
+4
View File
@@ -34,6 +34,10 @@ int vetta_buf_alloc(void** out, size_t bytes);
int vetta_buf_free(void* p); int vetta_buf_free(void* p);
int vetta_buf_h2d(void* dst, const void* src, size_t bytes); int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
int vetta_buf_d2h(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).
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);
// k_rms_norm (kernel #2): y[row] = x[row] * rsqrt(mean(x^2)+eps) * w. // 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, int vetta_rms_norm_f32(const float* x, const float* w, float* y,
+11
View File
@@ -71,6 +71,17 @@ extern "C" int vetta_buf_d2h(void* dst, const void* src, size_t bytes) {
HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyDeviceToHost)); HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyDeviceToHost));
return 0; return 0;
} }
// Device-to-device copies for prefix-checkpoint snapshot/restore (KV prefix is a
// strided sub-block of the contiguous [n_kv, max_seq, hd] cache).
extern "C" int vetta_buf_copy(void* dst, const void* src, size_t bytes) {
HIP_CHECK(hipMemcpy(dst, src, bytes, hipMemcpyDeviceToDevice));
return 0;
}
extern "C" int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src,
size_t spitch, size_t width, size_t height) {
HIP_CHECK(hipMemcpy2D(dst, dpitch, src, spitch, width, height, hipMemcpyDeviceToDevice));
return 0;
}
// ---- k_rms_norm (kernel #2): y = x * rsqrt(mean(x^2)+eps) * w -------------- // ---- k_rms_norm (kernel #2): y = x * rsqrt(mean(x^2)+eps) * w --------------
// One block per row; block-wide reduction over D. f32 in/out. // One block per row; block-wide reduction over D. f32 in/out.
+3 -3
View File
@@ -70,7 +70,7 @@ theorem restore_equiv (init : S) (step : S → Tok → S) (ck : Ckpt S) (suffix
/-- Restoring with an empty suffix reproduces the checkpoint state exactly. -/ /-- Restoring with an empty suffix reproduces the checkpoint state exactly. -/
theorem restore_nil (init : S) (step : S → Tok → S) (ck : Ckpt S) theorem restore_nil (init : S) (step : S → Tok → S) (ck : Ckpt S)
(h : Valid init step ck) : prefill step ck.state [] = ck.state := by (_h : Valid init step ck) : prefill step ck.state [] = ck.state := by
simp [prefill] simp [prefill]
/-! ## Part B: validity is intrinsic and preserved by pool operations -/ /-! ## Part B: validity is intrinsic and preserved by pool operations -/
@@ -145,12 +145,12 @@ theorem length_filter_ne_lt {l : List Nat} {a : Nat} (hmem : a ∈ l) :
| cons x xs ih => | cons x xs ih =>
by_cases hxa : x = a by_cases hxa : x = a
· have hf : (x :: xs).filter (· != a) = xs.filter (· != a) := by · have hf : (x :: xs).filter (· != a) = xs.filter (· != a) := by
simp only [List.filter]; split <;> simp_all [Nat.beq_eq] simp only [List.filter]; split <;> simp_all
rw [hf] rw [hf]
have := List.length_filter_le (· != a) xs have := List.length_filter_le (· != a) xs
simp; omega simp; omega
· have hf : (x :: xs).filter (· != a) = x :: xs.filter (· != a) := by · have hf : (x :: xs).filter (· != a) = x :: xs.filter (· != a) := by
simp only [List.filter]; split <;> simp_all [Nat.beq_eq] simp only [List.filter]; split <;> simp_all
rw [hf] rw [hf]
have hmem' : a ∈ xs := by have hmem' : a ∈ xs := by
rcases List.mem_cons.mp hmem with h | h rcases List.mem_cons.mp hmem with h | h