Compare commits
37
Commits
c059a20aa9
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85187d80a8 | ||
|
|
1772050087 | ||
|
|
c1c5221642 | ||
|
|
91c1baaf27 | ||
|
|
ba5149956e | ||
|
|
df537bf84f | ||
|
|
11404c4486 | ||
|
|
7b617bc333 | ||
|
|
6e854a9d73 | ||
|
|
ca12801b40 | ||
|
|
3812845f1a | ||
|
|
f9cde4954a | ||
|
|
142580e9ca | ||
|
|
1b10258e6e | ||
|
|
b6ed89b2d2 | ||
|
|
0cbec2d847 | ||
|
|
7e74db7ba5 | ||
|
|
3a9533afd0 | ||
|
|
afce5cbbfe | ||
|
|
ca3a6b0e15 | ||
|
|
a4752953fb | ||
|
|
ee8ac8f5df | ||
|
|
cfa5586447 | ||
|
|
216983abae | ||
|
|
99cd458d3b | ||
|
|
755626fae2 | ||
|
|
47f8b52070 | ||
|
|
a6ca73105c | ||
|
|
844d9e68ee | ||
|
|
ac1b55425c | ||
|
|
088ac1f66d | ||
|
|
0f0bb42949 | ||
|
|
45d039dcb4 | ||
|
|
f25cd27cf0 | ||
|
|
ac31924ebb | ||
|
|
01d8a48d51 | ||
|
|
66a40631ee |
No files matched your search
@@ -39,19 +39,26 @@ Built from the measured hardware physics and engineering lessons of our hardened
|
||||
- **M0.5 (Architecture realignment — done):** approved microkernel design fixed in `docs/ARCHITECTURE.md`; crates realigned to `vetta-infer-*` (abi/kn/ld/cc/rt/lab/sp/nt/tm/gw); bus lifecycle Lean-verified (`bus_lifecycle.lean`); faithful Adaptive-K port; `strata-ctl` wire emitters + `image=` key.
|
||||
- **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 + 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.
|
||||
- **M1.5 (Embedder lane — BGE-M3):** native encoder forward-pass (LayerNorm, bidirectional full-attn, GELU-erf, CLS pooling + L2 — recipe declared in the manifest), XLM-R importer, SPM tokenizer, `vetta-infer embed` wire; acceptance cosine ≥ 0.999 vs the live `vetta-semantics` oracle (`:8091`) + publisher fixture + anisotropy canary. Optional reranker head. May double as the HIP kernel bring-up bench.
|
||||
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
|
||||
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** DSpark drafter ✅ landed; next is layer streaming in DMA — the hard memory frontier: Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
|
||||
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
|
||||
|
||||
## Quick Verification
|
||||
|
||||
```sh
|
||||
# Lean 4 formal proofs (0 sorryAx, 5 files)
|
||||
# Lean 4 formal proofs (0 sorryAx, 7 files)
|
||||
lean proofs/slab_ring_dma.lean
|
||||
lean proofs/bus_lifecycle.lean
|
||||
lean proofs/serve_session.lean
|
||||
lean proofs/arena_plan.lean
|
||||
lean proofs/inkling_loop.lean
|
||||
lean proofs/prefix_cache.lean
|
||||
lean proofs/speculative_draft.lean
|
||||
|
||||
# Pure-Rust workspace tests (no GPU required)
|
||||
cargo test --workspace
|
||||
|
||||
@@ -11,7 +11,7 @@ fn usage() {
|
||||
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
|
||||
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)");
|
||||
eprintln!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)");
|
||||
eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it)");
|
||||
eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it; [--max-context N])");
|
||||
eprintln!(" vetta-infer chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)");
|
||||
eprintln!(" vetta-infer version Print version & build info");
|
||||
}
|
||||
@@ -101,6 +101,13 @@ fn main() -> ExitCode {
|
||||
usage();
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
// Optional resident window override (like strata --max-context):
|
||||
// `serve <dir> --max-context N`. Defaults to 32768 when absent.
|
||||
if let Some(i) = args.iter().position(|a| a == "--max-context") {
|
||||
if let Some(v) = args.get(i + 1).and_then(|s| s.parse::<usize>().ok()) {
|
||||
unsafe { std::env::set_var("VETTA_MAX_CONTEXT", v.to_string()) };
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "hip")]
|
||||
{
|
||||
match vetta_infer_gw::serve::run_serve(dir) {
|
||||
|
||||
@@ -27,8 +27,12 @@ use vetta_infer_abi::sampler::{
|
||||
use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
|
||||
use vetta_infer_hip::DeviceBuf;
|
||||
use vetta_infer_ld::inkling::parse_config;
|
||||
use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
|
||||
use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, is_swa, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
|
||||
use vetta_infer_ld::SafetensorsArchive;
|
||||
#[cfg(feature = "hip")]
|
||||
use vetta_infer_ld::layer::forward_batch_taps;
|
||||
#[cfg(feature = "hip")]
|
||||
use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkSnapshot, DsparkWeights, DS_HIDDEN};
|
||||
|
||||
use crate::session::ServeSession;
|
||||
use crate::{err_line, ready_line};
|
||||
@@ -51,17 +55,33 @@ const SITU_LB: f32 = 25.0;
|
||||
/// not limited by the 64 KB LDS cap.
|
||||
const MAX_CONTEXT: usize = 32768;
|
||||
|
||||
/// Clamp the generation budget to the resident window instead of hard-erroring.
|
||||
/// strata-ctl always sends the default budget max_new=16384, so a prompt longer
|
||||
/// than MAX_CONTEXT-16386 (e.g. 16504/16686 seen live) must still run with a
|
||||
/// reduced budget rather than return 0 tokens and kill the agent mid-window.
|
||||
/// `None` = the prompt itself no longer fits (true overflow, hard error).
|
||||
fn clamp_max_new(n_prompt: usize, max_new: usize, max_context: usize) -> Option<usize> {
|
||||
if n_prompt + 2 >= max_context { return None; }
|
||||
Some(max_new.min(max_context - n_prompt - 2))
|
||||
}
|
||||
|
||||
/// 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;
|
||||
const PREFIX_CACHE_CAP: usize = 8;
|
||||
fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 }
|
||||
/// Grid checkpoints (multiples of 512) are the STABLE prefixes that survive the
|
||||
/// turn-tag tail divergence; boundary/full-sequence checkpoints rarely hit again.
|
||||
/// Eviction prefers dropping non-grid entries so the useful grid is protected.
|
||||
fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
|
||||
|
||||
struct Checkpoint {
|
||||
tokens: Vec<i32>,
|
||||
layers: Vec<Option<LayerSnapshot>>,
|
||||
#[cfg(feature = "hip")]
|
||||
dspark: Option<DsparkSnapshot>,
|
||||
lru: u64,
|
||||
}
|
||||
|
||||
@@ -92,7 +112,16 @@ impl PrefixCache {
|
||||
}
|
||||
|
||||
/// Allocate + restore every checkpointed layer into `states` at `max_seq`.
|
||||
fn restore(&self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
|
||||
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a
|
||||
/// just-restored grid checkpoint keeps its old tick and gets evicted by the
|
||||
/// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor.
|
||||
/// Returns `(restored_len, dspark_restored)`.
|
||||
fn restore(
|
||||
&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize,
|
||||
#[cfg(feature = "hip")] dctx: Option<&mut DsparkContext>,
|
||||
) -> Result<(usize, bool), String> {
|
||||
let mut dspark_ok = false;
|
||||
{
|
||||
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.
|
||||
@@ -101,37 +130,71 @@ impl PrefixCache {
|
||||
}
|
||||
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);
|
||||
// Reuse the persistent state when it is already sized for this
|
||||
// request (same cap + pass count); restore overwrites its KV
|
||||
// prefix + hist rings. The stale KV tail beyond seq_len is never
|
||||
// read (causal attention), so reuse is exact (restore_equiv).
|
||||
let want = if is_swa(ip) { vetta_infer_ld::layer::swa_ring(d) } else { max_seq };
|
||||
let reuse = states[ip].as_ref()
|
||||
.map_or(false, |st| st.max_seq == want && st.k_cache.len() == s.k_cache.len());
|
||||
if !reuse {
|
||||
states[ip] = Some(new_state(d, want, s.k_cache.len())?);
|
||||
}
|
||||
states[ip].as_mut().unwrap().restore(d, s)?;
|
||||
}
|
||||
}
|
||||
Ok(ck.tokens.len())
|
||||
#[cfg(feature = "hip")]
|
||||
if let (Some(dc), Some(ds)) = (dctx, ck.dspark.as_ref()) {
|
||||
dc.restore(ds)?;
|
||||
dspark_ok = true;
|
||||
}
|
||||
}
|
||||
self.tick += 1;
|
||||
self.pool[idx].lru = self.tick;
|
||||
Ok((self.pool[idx].tokens.len(), dspark_ok))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
/// Snapshot all layer states (and optional DSpark context) 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,
|
||||
#[cfg(feature = "hip")] dctx: Option<&DsparkContext>,
|
||||
) -> 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())
|
||||
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
|
||||
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
|
||||
.collect::<Result<_, _>>()?;
|
||||
#[cfg(feature = "hip")]
|
||||
let dspark = match dctx {
|
||||
Some(dc) if dc.len >= seq => Some(dc.snapshot(seq, d.swa_win as usize)?),
|
||||
_ => None,
|
||||
};
|
||||
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;
|
||||
#[cfg(feature = "hip")] { ck.dspark = dspark; }
|
||||
return Ok(());
|
||||
}
|
||||
if self.pool.len() < PREFIX_CACHE_CAP {
|
||||
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
|
||||
self.pool.push(Checkpoint {
|
||||
tokens: tokens.to_vec(), layers,
|
||||
#[cfg(feature = "hip")] dspark,
|
||||
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);
|
||||
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
|
||||
if let Some(i) = victim {
|
||||
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
|
||||
self.pool[i] = Checkpoint {
|
||||
tokens: tokens.to_vec(), layers,
|
||||
#[cfg(feature = "hip")] dspark,
|
||||
lru,
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -146,6 +209,20 @@ pub struct InklingEngine {
|
||||
eos: i32,
|
||||
cap: f32,
|
||||
prefix: RefCell<PrefixCache>,
|
||||
/// Persistent per-layer KV/ShortConv states reused across requests, sized to
|
||||
/// `states_cap` (a 4096-bucket >= prompt+max_new). Eliminates the per-request
|
||||
/// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket.
|
||||
states: RefCell<Vec<Option<LayerState>>>,
|
||||
/// Resident context window (advertised in READY). Defaults to MAX_CONTEXT;
|
||||
/// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents.
|
||||
max_context: usize,
|
||||
/// DSpark drafter weights (resident), loaded only when VETTA_SPEC=1 and
|
||||
/// mtp.safetensors passes layout_check. Enables opt-in greedy speculation.
|
||||
#[cfg(feature = "hip")]
|
||||
spec_dw: Option<DsparkWeights>,
|
||||
/// Persistent DSpark context rings reused across requests (mirrors `states`).
|
||||
#[cfg(feature = "hip")]
|
||||
dctx: RefCell<Option<DsparkContext>>,
|
||||
}
|
||||
|
||||
impl InklingEngine {
|
||||
@@ -184,6 +261,20 @@ impl InklingEngine {
|
||||
lb: SITU_LB,
|
||||
swa_win: t.swa_win as i32,
|
||||
};
|
||||
let max_context = std::env::var("VETTA_MAX_CONTEXT").ok()
|
||||
.and_then(|s| s.parse::<usize>().ok())
|
||||
.filter(|&v| v >= 4096)
|
||||
.unwrap_or(MAX_CONTEXT);
|
||||
// Opt-in DSpark drafter: load resident weights iff VETTA_SPEC=1 and the
|
||||
// mtp shard passes the strict layout check (else disable, never guess).
|
||||
#[cfg(feature = "hip")]
|
||||
let spec_dw = if std::env::var("VETTA_SPEC").is_ok() {
|
||||
let mtp = ar.dir.join("mtp.safetensors");
|
||||
match SafetensorsArchive::open_file(mtp.to_str().unwrap_or_default()) {
|
||||
Ok(mar) if layout_check(&mar).is_ok() => DsparkWeights::load(&mar).ok(),
|
||||
_ => None,
|
||||
}
|
||||
} else { None };
|
||||
Ok(Self {
|
||||
cache: WeightCache::new(ar),
|
||||
d,
|
||||
@@ -196,6 +287,12 @@ impl InklingEngine {
|
||||
eos: cfg.eos_token_id as i32,
|
||||
cap: t.final_logit_softcapping as f32,
|
||||
prefix: RefCell::new(PrefixCache::new()),
|
||||
states: RefCell::new(Vec::new()),
|
||||
max_context,
|
||||
#[cfg(feature = "hip")]
|
||||
spec_dw,
|
||||
#[cfg(feature = "hip")]
|
||||
dctx: RefCell::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -203,9 +300,8 @@ impl InklingEngine {
|
||||
self.vocab
|
||||
}
|
||||
|
||||
fn fresh_states(&self, _max_seq: usize) -> Result<Vec<Option<LayerState>>, String> {
|
||||
// States are allocated lazily per layer by run_layer; start all None.
|
||||
Ok((0..self.n_layers).map(|_| None).collect())
|
||||
pub fn max_context(&self) -> usize {
|
||||
self.max_context
|
||||
}
|
||||
|
||||
fn forward(
|
||||
@@ -266,39 +362,108 @@ pub fn serve_gen(
|
||||
}
|
||||
|
||||
let n_prompt = g.ids.len();
|
||||
let max_seq = (n_prompt + g.max_new + 2).min(MAX_CONTEXT);
|
||||
if n_prompt + g.max_new + 2 > MAX_CONTEXT {
|
||||
emit_all(emit, sess.on_error("prompt + max_new exceeds context window"));
|
||||
let max_context = eng.max_context();
|
||||
// Clamp the budget to the window (reviewer 2026-12-02): only a prompt that
|
||||
// itself overflows is a hard error; otherwise generate up to the room left.
|
||||
let Some(effective_max_new) = clamp_max_new(n_prompt, g.max_new, max_context) else {
|
||||
emit_all(emit, sess.on_error("prompt exceeds context window"));
|
||||
return;
|
||||
};
|
||||
// KV capacities are FIXED per layer kind (SWA ring = swa_win+chunk_cap, global
|
||||
// = max_context), allocated once and never resized across requests: no
|
||||
// drop+realloc when a session crosses a 4096 multiple (reviewer punto 2).
|
||||
if eng.states.borrow().len() != eng.n_layers {
|
||||
*eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
|
||||
}
|
||||
let mut states = match eng.fresh_states(max_seq) {
|
||||
Ok(s) => s,
|
||||
let cap = max_context;
|
||||
let mut states = eng.states.borrow_mut();
|
||||
|
||||
// Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps
|
||||
// during prefill to build the drafter context rings, then run a batched
|
||||
// speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft).
|
||||
#[cfg(feature = "hip")]
|
||||
let mut spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties();
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let spec_enabled = false;
|
||||
#[cfg(feature = "hip")]
|
||||
let mut dctx_guard = eng.dctx.borrow_mut();
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled {
|
||||
let need_new = dctx_guard.as_ref().map_or(true, |c| c.cap < cap);
|
||||
if need_new {
|
||||
match DsparkContext::new(cap, DS_HIDDEN) {
|
||||
Ok(c) => *dctx_guard = Some(c),
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
let matched = eng.prefix.borrow().best_match(&g.ids);
|
||||
if let Some((idx, _l)) = matched {
|
||||
#[cfg(feature = "hip")]
|
||||
let res = eng.prefix.borrow_mut().restore(
|
||||
idx, &mut states[..], &eng.d, cap,
|
||||
if spec_enabled { dctx_guard.as_mut() } else { None },
|
||||
);
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let res = eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap);
|
||||
match res {
|
||||
Ok((n, dspark_ok)) => {
|
||||
start = n;
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled && !dspark_ok {
|
||||
// Checkpoint lacked DSpark state (e.g. saved while spec was off):
|
||||
// never run the drafter over zeroed prefix rings.
|
||||
spec_enabled = false;
|
||||
}
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = dspark_ok;
|
||||
}
|
||||
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; }
|
||||
};
|
||||
*states = (0..eng.n_layers).map(|_| None).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Cold request (no prefix restored): the persistent states carry the previous
|
||||
// conversation's ShortConv history. Reset the hist rings (the KV prefix is
|
||||
// overwritten by prefill before any causal read) so a fresh conversation starts
|
||||
// empty. A restored request instead overwrites hist via the checkpoint.
|
||||
if start == 0 {
|
||||
for st in states.iter_mut().flatten() {
|
||||
if let Err(e) = st.reset_history() {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "hip")]
|
||||
if let Some(dc) = dctx_guard.as_mut() {
|
||||
dc.len = 0;
|
||||
}
|
||||
}
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
|
||||
if start == 0 {
|
||||
// No match: show each cached checkpoint's length and how many leading
|
||||
// tokens it shares with this prompt, to pinpoint a token divergence
|
||||
// (common < len => the re-rendered prompt differs at that position).
|
||||
let p = eng.prefix.borrow();
|
||||
for (i, ck) in p.pool.iter().enumerate() {
|
||||
let common = ck.tokens.iter().zip(g.ids.iter()).take_while(|(a, b)| a == b).count();
|
||||
eprintln!("[prefix] ck[{i}] len={} common_prefix={common}", ck.tokens.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Weights are resident in eng.cache (loaded once at boot, reused across all
|
||||
@@ -311,11 +476,15 @@ pub fn serve_gen(
|
||||
let t0 = Instant::now();
|
||||
let mut pos = start as i32;
|
||||
let mut history: Vec<i32> = g.ids[..start].to_vec();
|
||||
history.reserve(n_prompt - start + g.max_new);
|
||||
history.reserve(n_prompt - start + effective_max_new);
|
||||
let mut logits: Option<DeviceBuf> = None;
|
||||
let chunk = prefill_chunk_size();
|
||||
let chunk = prefill_chunk_size().min(vetta_infer_ld::layer::SWA_CHUNK_CAP);
|
||||
let suffix = &g.ids[start..];
|
||||
let mut done = 0usize;
|
||||
// Monotonic 512-grid threshold: split a chunk exactly on the next grid boundary
|
||||
// so a checkpoint always lands on every multiple of 512 regardless of `start`
|
||||
// (pos % 512 == 0 would miss boundaries when start/suffix aren't aligned).
|
||||
let mut next_grid = ((start / 512) + 1) * 512;
|
||||
while done < suffix.len() {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
sess.on_stop();
|
||||
@@ -324,12 +493,34 @@ pub fn serve_gen(
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let take = chunk.min(suffix.len() - done);
|
||||
let mut take = chunk.min(suffix.len() - done);
|
||||
let pos_now = start + done;
|
||||
if pos_now < next_grid && pos_now + take > next_grid {
|
||||
take = next_grid - pos_now;
|
||||
}
|
||||
let toks = &suffix[done..done + take];
|
||||
let lg = if take == 1 {
|
||||
eng.forward(toks[0], pos, max_seq, &mut states)
|
||||
let lg = if spec_enabled {
|
||||
#[cfg(feature = "hip")]
|
||||
{
|
||||
(|| -> Result<DeviceBuf, String> {
|
||||
let h = eng.d.hidden;
|
||||
let mut taps = [DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?];
|
||||
let l = forward_batch_taps(&eng.cache, &eng.d, toks, eng.vocab, cap, pos, eng.cap, &mut states[..], &mut taps)?;
|
||||
let pb = DeviceBuf::alloc(take * 4)?;
|
||||
pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
|
||||
let dw = eng.spec_dw.as_ref().unwrap();
|
||||
let dc = dctx_guard.as_mut().unwrap();
|
||||
dc.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?;
|
||||
dc.len = (pos + take as i32) as usize;
|
||||
Ok(l)
|
||||
})()
|
||||
}
|
||||
#[cfg(not(feature = "hip"))]
|
||||
{ Err("spec requires hip".into()) }
|
||||
} else if take == 1 {
|
||||
eng.forward(toks[0], pos, cap, &mut states[..])
|
||||
} else {
|
||||
eng.forward_batched(toks, pos, max_seq, &mut states)
|
||||
eng.forward_batched(toks, pos, cap, &mut states[..])
|
||||
};
|
||||
match lg {
|
||||
Ok(l) => logits = Some(l),
|
||||
@@ -342,6 +533,22 @@ pub fn serve_gen(
|
||||
history.extend_from_slice(toks);
|
||||
pos += take as i32;
|
||||
done += take;
|
||||
// Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate
|
||||
// checkpoint on every 512 boundary so the next turn can restore a stable
|
||||
// prefix even when the prompt's trailing turn-tag tokens re-render
|
||||
// differently. best_match picks the longest grid checkpoint that is a full
|
||||
// prefix; grid entries are protected from eviction (is_grid) and refreshed
|
||||
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid {
|
||||
#[cfg(feature = "hip")]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] grid save seq={pos}");
|
||||
}
|
||||
next_grid += 512;
|
||||
}
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
if let Ok(pp) = sess.on_prefill_chunk((start + done) as u32, n_prompt as u32, ms) {
|
||||
emit_all(emit, pp);
|
||||
@@ -367,12 +574,15 @@ pub fn serve_gen(
|
||||
// stable prefix and prefill only the new dialogue suffix. Mirrors strata
|
||||
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
|
||||
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);
|
||||
#[cfg(feature = "hip")]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] prompt-boundary save seq={pos}");
|
||||
}
|
||||
}
|
||||
if g.max_new == 0 {
|
||||
if effective_max_new == 0 {
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
@@ -390,8 +600,108 @@ pub fn serve_gen(
|
||||
return;
|
||||
}
|
||||
};
|
||||
// --- Opt-in DSpark speculative decode (greedy, lossless vs batched B=1). ---
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled {
|
||||
let dw = eng.spec_dw.as_ref().unwrap();
|
||||
let dc = dctx_guard.as_mut().unwrap();
|
||||
let t1 = Instant::now();
|
||||
let mut lg = vec![0f32; eng.vocab];
|
||||
if let Err(e) = logits.d2h(&mut lg) {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let argmax = |v: &[f32]| -> i32 {
|
||||
let mut best = 0usize; let mut bz = f32::NEG_INFINITY;
|
||||
for (i, &z) in v.iter().enumerate() { if z > bz { bz = z; best = i; } }
|
||||
best as i32
|
||||
};
|
||||
let tok0 = argmax(&lg);
|
||||
let mut finish = "length";
|
||||
for step in 0..g.max_new {
|
||||
let mut generated = 0usize;
|
||||
let emit_tok = |t: i32, emit: &mut dyn FnMut(String), sess: &mut ServeSession, history: &mut Vec<i32>, generated: &mut usize| -> bool {
|
||||
match sess.on_token(t as u32) {
|
||||
Ok(lines) => emit_all(emit, lines),
|
||||
Err(e) => { emit_all(emit, sess.on_error(&e)); return false; }
|
||||
}
|
||||
history.push(t); *generated += 1;
|
||||
true
|
||||
};
|
||||
if !emit_tok(tok0, emit, &mut sess, &mut history, &mut generated) {
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let mut cur_pos = pos; let mut next_tok = tok0;
|
||||
// Measured on gfx1150 after single-pass GPU drafter + WMMA/fdot2 + small-M SWA:
|
||||
// Rust coding prompt (128 tok): OFF 6.83 | nd=2 11.93 | nd=3 13.90 | nd=4 13.97 | nd=5 13.69 tok/s
|
||||
// Short prose prompt (96 tok): OFF 4.70 | nd=2 9.21 | nd=3 9.09 | nd=4 8.93 | nd=5 9.09 tok/s
|
||||
// Track an EMA of ACCEPTED tokens per round (not acceptance ratio, which
|
||||
// naturally drops as nd grows and used to clamp code generation down to nd=2).
|
||||
// Start at 5 (optimal on code/structured text) and adapt smoothly 2..7.
|
||||
let mut ema_acc = 2.0f32; let mut n_draft = 5usize;
|
||||
// VETTA_SPEC_ND fixes n_draft (bypasses the EMA) for A/B measurement.
|
||||
let nd_override = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::<usize>().ok());
|
||||
let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize;
|
||||
if tok0 == eng.eos {
|
||||
finish = "stop";
|
||||
} else {
|
||||
while generated < effective_max_new {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
sess.on_stop();
|
||||
let ms = t1.elapsed().as_secs_f64() * 1000.0;
|
||||
emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default());
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let left = effective_max_new - generated;
|
||||
let nd = nd_override.unwrap_or(n_draft).min(left.saturating_sub(1));
|
||||
let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut hit_eos = false;
|
||||
for &t in &em {
|
||||
if !emit_tok(t, emit, &mut sess, &mut history, &mut generated) {
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
if t == eng.eos { hit_eos = true; break; }
|
||||
if generated >= effective_max_new { break; }
|
||||
}
|
||||
if nd > 0 {
|
||||
let acc = em.len().saturating_sub(1);
|
||||
ema_acc = 0.85 * ema_acc + 0.15 * (acc as f32);
|
||||
n_draft = if ema_acc >= 3.5 { 7 }
|
||||
else if ema_acc >= 2.0 { 5 }
|
||||
else if ema_acc >= 1.1 { 4 }
|
||||
else if ema_acc >= 0.6 { 3 }
|
||||
else { 2 };
|
||||
offered += nd; accepted += acc;
|
||||
}
|
||||
rounds += 1;
|
||||
cur_pos = nc; next_tok = nt; pos = nc;
|
||||
if hit_eos { finish = "stop"; break; }
|
||||
if done || generated >= effective_max_new { finish = "length"; break; }
|
||||
}
|
||||
}
|
||||
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
|
||||
if std::env::var("VETTA_DBG_SPEC").is_ok() {
|
||||
eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema_acc={ema_acc:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0));
|
||||
}
|
||||
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, Some(dc));
|
||||
}
|
||||
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let mut finish = "length";
|
||||
for step in 0..effective_max_new {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
sess.on_stop();
|
||||
let ms = t1.elapsed().as_secs_f64() * 1000.0;
|
||||
@@ -433,11 +743,11 @@ pub fn serve_gen(
|
||||
break;
|
||||
}
|
||||
history.push(rep.token);
|
||||
if step + 1 == g.max_new {
|
||||
if step + 1 == effective_max_new {
|
||||
finish = "length";
|
||||
break;
|
||||
}
|
||||
match eng.forward(rep.token, pos, max_seq, &mut states) {
|
||||
match eng.forward(rep.token, pos, cap, &mut states[..]) {
|
||||
Ok(l) => logits = l,
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
@@ -454,7 +764,10 @@ pub fn serve_gen(
|
||||
// counts tokens actually folded into `states` (history[..pos]); a sampled token
|
||||
// not forwarded (EOS / last length step) is excluded, keeping the ckpt 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);
|
||||
#[cfg(feature = "hip")]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, None);
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] full-sequence save seq={pos}");
|
||||
}
|
||||
@@ -528,7 +841,7 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
|
||||
let _ = writeln!(out, "{line}");
|
||||
let _ = out.flush();
|
||||
};
|
||||
emit(ready_line(MAX_CONTEXT as u32, true, false, false));
|
||||
emit(ready_line(eng.max_context() as u32, true, false, false));
|
||||
|
||||
loop {
|
||||
if quit.load(Ordering::Relaxed) {
|
||||
@@ -553,6 +866,27 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// CPU: the budget clamp must keep long agent prompts runnable (strata-ctl
|
||||
/// always sends max_new=16384) instead of hard-erroring past 16382 tokens, and
|
||||
/// only reject a prompt that itself overflows the window.
|
||||
#[test]
|
||||
fn clamp_max_new_budget() {
|
||||
// live agent prompts 16504/16686 with the default 16384 budget: clamp, run.
|
||||
assert_eq!(clamp_max_new(16504, 16384, 32768), Some(32768 - 16504 - 2));
|
||||
assert_eq!(clamp_max_new(16686, 16384, 32768), Some(32768 - 16686 - 2));
|
||||
// small prompt keeps the full budget.
|
||||
assert_eq!(clamp_max_new(2648, 16384, 32768), Some(16384));
|
||||
// exactly at the last usable prompt position: 1 token of room.
|
||||
assert_eq!(clamp_max_new(32765, 16384, 32768), Some(1));
|
||||
// prompt itself overflows: hard error (None).
|
||||
assert_eq!(clamp_max_new(32766, 16384, 32768), None);
|
||||
assert_eq!(clamp_max_new(40000, 16384, 32768), None);
|
||||
// configurable larger window accepts the same long prompt unclamped.
|
||||
assert_eq!(clamp_max_new(16504, 16384, 65536), Some(16384));
|
||||
// GEN 0 pre-warm stays 0 regardless of prompt.
|
||||
assert_eq!(clamp_max_new(2648, 0, 32768), Some(0));
|
||||
}
|
||||
|
||||
/// GPU integration: drive `serve_gen` over the wire for the canonical prompt
|
||||
/// "The capital of France is" (ids from the tokenizer) and check the emitted
|
||||
/// lines: first `T` is 152717 (" Paris", exact reference match) and the
|
||||
@@ -650,4 +984,173 @@ mod tests {
|
||||
assert!(done.ends_with(" stop"), "finish must be stop, got {done}");
|
||||
});
|
||||
}
|
||||
|
||||
/// GPU: the opt-in DSpark speculative serve path (VETTA_SPEC=1, batched
|
||||
/// verify + rollback + EMA) must emit EXACTLY the same reference tokens as
|
||||
/// the default M=1 decode for the canonical capital prompt. Verifies the
|
||||
/// serve orchestration (pos/history/EOS/length) AND that the batched decode
|
||||
/// path is greedy-vs-reference exact.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn serve_gen_spec_multi_token_parity() {
|
||||
crate::gpu_isolated(|| {
|
||||
unsafe { std::env::set_var("VETTA_SPEC", "1"); }
|
||||
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
||||
assert!(eng.spec_dw.is_some(), "drafter weights must load with VETTA_SPEC=1");
|
||||
let g = match parse_serve_line("GEN 16 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() {
|
||||
ServeCommand::Gen(g) => g,
|
||||
_ => panic!("expected Gen"),
|
||||
};
|
||||
let stop = AtomicBool::new(false);
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
|
||||
let tokens: Vec<i32> = lines.iter()
|
||||
.filter(|l| l.starts_with("T "))
|
||||
.map(|l| l[2..].trim().parse().unwrap())
|
||||
.collect();
|
||||
let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014];
|
||||
unsafe { std::env::remove_var("VETTA_SPEC"); }
|
||||
assert_eq!(tokens, want, "speculative serve path must match reference exactly");
|
||||
});
|
||||
}
|
||||
|
||||
/// GPU perf probe: spec-on vs spec-off decode tok/s + acceptance on a real
|
||||
/// prompt (GEN 96). Prints measured numbers; no speedup claim without them.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn serve_gen_spec_perf() {
|
||||
crate::gpu_isolated(|| {
|
||||
let ids = "371,151451,149879,151194,149884";
|
||||
let run = |spec: bool| -> (f64, usize) {
|
||||
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
|
||||
unsafe { std::env::set_var("VETTA_DBG_SPEC", "1"); }
|
||||
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
||||
let g = match parse_serve_line(&format!("GEN 96 temperature=0 {ids}"), eng.vocab()).unwrap() {
|
||||
ServeCommand::Gen(g) => g,
|
||||
_ => panic!("expected Gen"),
|
||||
};
|
||||
let stop = AtomicBool::new(false);
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
let t = Instant::now();
|
||||
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
|
||||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
let n = lines.iter().filter(|l| l.starts_with("T ")).count();
|
||||
unsafe { std::env::remove_var("VETTA_SPEC"); std::env::remove_var("VETTA_DBG_SPEC"); }
|
||||
(ms, n)
|
||||
};
|
||||
let (off_ms, off_n) = run(false);
|
||||
let (on_ms, on_n) = run(true);
|
||||
eprintln!("spec_perf: OFF {off_n} tok {off_ms:.1}ms {:.2} tok/s | ON {on_n} tok {on_ms:.1}ms {:.2} tok/s", off_n as f64 / (off_ms / 1000.0), on_n as f64 / (on_ms / 1000.0));
|
||||
assert_eq!(off_n, on_n, "spec must emit the same token count");
|
||||
});
|
||||
}
|
||||
|
||||
/// GPU: multi-turn PrefixCache + DsparkSnapshot restore regression test.
|
||||
/// Turn 1 prefills + generates 16 tokens and saves a checkpoint with DSpark
|
||||
/// state; Turn 2 extends Turn 1's exact prompt + generated tokens with a
|
||||
/// follow-up suffix, hitting RESUME on Turn 1's checkpoint and restoring
|
||||
/// DSpark rings + frnn_last. Turn 2 output with VETTA_SPEC=1 must match
|
||||
/// VETTA_SPEC=0 100% EXACT and emit a non-zero RESUME.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn serve_gen_spec_prefix_cache_multi_turn_parity() {
|
||||
crate::gpu_isolated(|| {
|
||||
let turn1_ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,10970,261,4660,11,5603,59195,9268,328,261,6164,12,13448,8459,6462,13,200010,200001,200004";
|
||||
let run_two_turns = |spec: bool| -> (Vec<i32>, Vec<i32>, usize) {
|
||||
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
|
||||
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
||||
let stop = AtomicBool::new(false);
|
||||
// Turn 1
|
||||
let g1 = match parse_serve_line(&format!("GEN 16 temperature=0 {turn1_ids}"), eng.vocab()).unwrap() {
|
||||
ServeCommand::Gen(g) => g,
|
||||
_ => panic!("expected Gen"),
|
||||
};
|
||||
let mut l1 = Vec::new();
|
||||
serve_gen(&eng, &g1, &stop, &mut |l| l1.push(l));
|
||||
let t1: Vec<i32> = l1.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
|
||||
// Turn 2 extends Turn 1 prompt + Turn 1 reply + short follow-up prompt
|
||||
let mut turn2_vec: Vec<String> = turn1_ids.split(',').map(|s| s.to_string()).collect();
|
||||
for &id in &t1 { turn2_vec.push(id.to_string()); }
|
||||
for extra in [200010, 200000, 200004, 10970, 261, 2324, 13, 200010, 200001, 200004] {
|
||||
turn2_vec.push(extra.to_string());
|
||||
}
|
||||
let turn2_ids = turn2_vec.join(",");
|
||||
let g2 = match parse_serve_line(&format!("GEN 24 temperature=0 {turn2_ids}"), eng.vocab()).unwrap() {
|
||||
ServeCommand::Gen(g) => g,
|
||||
_ => panic!("expected Gen"),
|
||||
};
|
||||
let mut l2 = Vec::new();
|
||||
serve_gen(&eng, &g2, &stop, &mut |l| l2.push(l));
|
||||
let t2: Vec<i32> = l2.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
|
||||
let resumed: usize = l2.iter()
|
||||
.find(|l| l.starts_with("RESUME "))
|
||||
.and_then(|l| l[7..].trim().parse().ok())
|
||||
.unwrap_or(0);
|
||||
unsafe { std::env::remove_var("VETTA_SPEC"); }
|
||||
(t1, t2, resumed)
|
||||
};
|
||||
let (off_t1, off_t2, off_resumed) = run_two_turns(false);
|
||||
let (on_t1, on_t2, on_resumed) = run_two_turns(true);
|
||||
eprintln!("multi-turn prefix cache: off_resumed={off_resumed} on_resumed={on_resumed} t1_len={} t2_len={}", on_t1.len(), on_t2.len());
|
||||
assert!(on_resumed > 0, "Turn 2 with VETTA_SPEC=1 must hit PrefixCache RESUME");
|
||||
assert_eq!(on_resumed, off_resumed, "Turn 2 RESUME length must match OFF");
|
||||
assert_eq!(on_t1, off_t1, "Turn 1 tokens must match OFF exactly");
|
||||
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"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
+1126
-10
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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 {
|
||||
@@ -48,6 +48,13 @@ pub struct LayerState {
|
||||
pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3], // [3, n_kv*hd] each
|
||||
pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3], // [3, hidden] each
|
||||
pub max_seq: usize,
|
||||
// DSpark speculative rollback: per-prefix ShortConv history snapshots
|
||||
// [(B+1)*3*C] captured during a spec verify batch (spec_recording). On
|
||||
// partial accept, hist <- snap[accepted]; the KV ring truncates with no
|
||||
// restore (proofs/speculative_draft.lean kept_rejected_disjoint).
|
||||
pub spec_b: usize,
|
||||
pub snap_k: [Option<DeviceBuf>; 3], pub snap_v: [Option<DeviceBuf>; 3],
|
||||
pub snap_a: [Option<DeviceBuf>; 3], pub snap_m: [Option<DeviceBuf>; 3],
|
||||
}
|
||||
|
||||
/// Forward-pass dimensions (subset of TextConfig needed by a layer).
|
||||
@@ -84,6 +91,7 @@ pub struct WeightCache {
|
||||
experts: RefCell<HashMap<(usize, usize, String), Arc<ExpertMatrix>>>,
|
||||
arenas: RefCell<HashMap<(usize, String), Arc<ExpertArena>>>,
|
||||
ctrl: RefCell<HashMap<usize, Arc<ControllerWeights>>>,
|
||||
msgq: RefCell<HashMap<usize, Arc<DeviceBuf>>>,
|
||||
}
|
||||
|
||||
impl WeightCache {
|
||||
@@ -98,6 +106,7 @@ impl WeightCache {
|
||||
experts: RefCell::new(HashMap::new()),
|
||||
arenas: RefCell::new(HashMap::new()),
|
||||
ctrl: RefCell::new(HashMap::new()),
|
||||
msgq: RefCell::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,14 +171,32 @@ impl WeightCache {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Stacked cross-pass msg_queries [4, hidden] for core layer ip, memoized.
|
||||
/// These are STATIC model weights: building them per visit did 2 sync D2H + 1
|
||||
/// sync H2D each (72 PCIe stalls/chunk in prefill, 24/token in decode). Cache
|
||||
/// the device buffer once => zero host round-trips on the hot path.
|
||||
pub fn msg_queries(&self, ip: usize, hidden: usize) -> Result<Arc<DeviceBuf>, String> {
|
||||
if let Some(v) = self.msgq.borrow().get(&ip) { return Ok(v.clone()); }
|
||||
let v = Arc::new(load_msg_queries(self, ip, hidden)?);
|
||||
self.msgq.borrow_mut().insert(ip, v.clone());
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Eagerly load the WHOLE model to device: trunk (embed/norms/unembed/output
|
||||
/// query/cross-pass queries), every attention layer (SWA or full), the core
|
||||
/// loop controllers, and all expert matrices. After this the cache is fully
|
||||
/// resident: VRAM is populated at boot and NO request pays NVMe reads or
|
||||
/// uploads (the model is ~18 GiB, within the <=80 GiB full-UMA-residency
|
||||
/// policy). This is the serve default; `VETTA_LAZY_LOAD=1` defers to first use
|
||||
/// (still resident across requests once loaded). Idempotent: each loader
|
||||
/// memoizes, so calling it twice uploads nothing new.
|
||||
/// loop controllers, and all expert ARENAS (the contiguous device-MoE layout).
|
||||
/// After this the cache is fully resident: VRAM is populated at boot and NO
|
||||
/// request pays NVMe reads or uploads (the model is ~18 GiB, within the <=80
|
||||
/// GiB full-UMA-residency policy). This is the serve default; `VETTA_LAZY_LOAD=1`
|
||||
/// defers to first use (still resident across requests once loaded). Idempotent:
|
||||
/// each loader memoizes, so calling it twice uploads nothing new.
|
||||
///
|
||||
/// Loads the expert ARENAS (not the per-expert `ExpertMatrix` copies): the
|
||||
/// production serve uses the device-routed MoE (`VETTA_DEVICE_MOE`), which
|
||||
/// reads the arena. Prewarming the per-expert matrices too would hold a SECOND
|
||||
/// full copy of the ~16 GiB expert weights (the arena loads lazily on the first
|
||||
/// forward), nearly doubling VRAM. The legacy host `run_experts` path loads
|
||||
/// per-expert matrices lazily on demand if ever selected.
|
||||
pub fn prewarm(&self, d: &Dims, n_layers: usize) -> Result<(), String> {
|
||||
self.raw("model.llm.embed.weight")?;
|
||||
self.bf16_f32("model.llm.embed_norm.weight")?;
|
||||
@@ -183,10 +210,8 @@ impl WeightCache {
|
||||
if (6..18).contains(&ip) { self.controllers(ip)?; }
|
||||
}
|
||||
for ip in 0..n_layers {
|
||||
for e in 0..d.n_experts {
|
||||
self.expert(ip, e, "w13")?;
|
||||
self.expert(ip, e, "w2")?;
|
||||
}
|
||||
self.expert_arena(ip, "w13")?;
|
||||
self.expert_arena(ip, "w2")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -223,7 +248,7 @@ pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<La
|
||||
}
|
||||
|
||||
pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState, String> {
|
||||
let zero = |n: usize| -> Result<DeviceBuf, String> { let b = DeviceBuf::alloc(n * 4)?; b.h2d(&vec![0f32; n])?; Ok(b) };
|
||||
let zero = |n: usize| -> Result<DeviceBuf, String> { let b = DeviceBuf::alloc(n * 4)?; b.zero_async()?; Ok(b) };
|
||||
// KV cache dtype: F32 by default (the verified CPU-oracle baseline); FP16 via
|
||||
// VETTA_F16_KV=1 matches the strata default (KvDtype::FP16) and its
|
||||
// length-dependent rounding (the F32 cache diverges on near-ties as it grows).
|
||||
@@ -231,12 +256,15 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState
|
||||
// KV is unpooled: its size scales with max_seq (prompt+max_new), which varies
|
||||
// per request. Pooling by exact size would retain every distinct KV size and
|
||||
// grow VRAM without bound across a multi-turn chat; free it on request end.
|
||||
// Zero-filled with ASYNC device memset (hipMemsetAsync, ~7.5ms GPU for 3.75GB),
|
||||
// NOT a host vec![0]+sync h2d: the latter allocated ~3.75GB system RAM, zeroed
|
||||
// it on CPU and copied it over blocking PCIe every request (~0.5-1.5s stall).
|
||||
// Causal attention only reads [0..=pos] (kv_store overwrites before read), so
|
||||
// the zero is defensive/deterministic rather than required, but keeps the
|
||||
// full-cache byte-parity tests stable across pool reuse.
|
||||
let kv_buf = || -> Result<DeviceBuf, String> {
|
||||
if f16_kv() {
|
||||
let b = DeviceBuf::alloc_unpooled(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b)
|
||||
} else {
|
||||
let b = DeviceBuf::alloc_unpooled(kv_n * 4)?; b.h2d(&vec![0f32; kv_n])?; Ok(b)
|
||||
}
|
||||
let b = if f16_kv() { DeviceBuf::alloc_unpooled(kv_n * 2)? } else { DeviceBuf::alloc_unpooled(kv_n * 4)? };
|
||||
b.zero_async()?; Ok(b)
|
||||
};
|
||||
let kv_vec = || -> Result<Vec<DeviceBuf>, String> { (0..n_passes.max(1)).map(|_| kv_buf()).collect() };
|
||||
Ok(LayerState {
|
||||
@@ -247,38 +275,101 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result<LayerState
|
||||
hist_a: [zero(3 * d.hidden)?, zero(3 * d.hidden)?, zero(3 * d.hidden)?],
|
||||
hist_m: [zero(3 * d.hidden)?, zero(3 * d.hidden)?, zero(3 * d.hidden)?],
|
||||
max_seq,
|
||||
spec_b: 0,
|
||||
snap_k: [None, None, None], snap_v: [None, None, None],
|
||||
snap_a: [None, None, None], snap_m: [None, None, None],
|
||||
})
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SPEC_REC: std::cell::Cell<(bool, usize)> = const { std::cell::Cell::new((false, 0)) };
|
||||
}
|
||||
/// Enable DSpark spec capture for a verify batch of `b` tokens (thread-local).
|
||||
pub fn spec_begin(b: usize) { SPEC_REC.with(|c| c.set((true, b))); }
|
||||
/// Disable spec capture (snapshots stay allocated for reuse across rounds).
|
||||
pub fn spec_end() { SPEC_REC.with(|c| c.set((false, c.get().1))); }
|
||||
fn spec_recording() -> bool { SPEC_REC.with(|c| c.get().0) }
|
||||
|
||||
/// update_hist + (when spec-recording) per-prefix history snapshots. The snaps
|
||||
/// kernel reads hist BEFORE update_hist rolls it, so snaps[0]=hist0.
|
||||
fn spec_update_hist(in_x: &DeviceBuf, hist: &DeviceBuf, snap: &mut Option<DeviceBuf>, b: i32, c: i32) -> Result<(), String> {
|
||||
if spec_recording() {
|
||||
let n = (b as usize + 1) * 3 * c as usize;
|
||||
if snap.as_ref().map_or(true, |s| s.bytes != n * 4) {
|
||||
*snap = Some(DeviceBuf::alloc(n * 4)?);
|
||||
}
|
||||
vetta_infer_hip::shortconv4_hist_snaps(in_x, hist, snap.as_ref().unwrap(), b, c)?;
|
||||
}
|
||||
vetta_infer_hip::shortconv4_update_hist(in_x, hist, b, c)
|
||||
}
|
||||
|
||||
/// Roll back every layer's ShortConv history to the state after `accepted` tokens
|
||||
/// of the spec verify batch (hist <- snap[accepted]). KV needs no restore.
|
||||
pub fn rollback_spec(d: &Dims, states: &mut [Option<LayerState>], accepted: usize) -> Result<(), String> {
|
||||
let kv = 3 * d.kv_dim(); let hh = 3 * d.hidden;
|
||||
for st in states.iter_mut().flatten() {
|
||||
for p in 0..3 {
|
||||
if let Some(s) = st.snap_k[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * kv, &st.hist_k[p], kv)?; }
|
||||
if let Some(s) = st.snap_v[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * kv, &st.hist_v[p], kv)?; }
|
||||
if let Some(s) = st.snap_a[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * hh, &st.hist_a[p], hh)?; }
|
||||
if let Some(s) = st.snap_m[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * hh, &st.hist_m[p], hh)?; }
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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],
|
||||
/// 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<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 `[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> {
|
||||
/// 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 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)?;
|
||||
let win = if swa { seq_len.min(d.swa_win.max(0) as usize) } else { seq_len };
|
||||
let kv_start = seq_len - win;
|
||||
// Ring-aware source slots: the window [kv_start, seq_len) maps to
|
||||
// [kv_start % r, ..) in the SWA ring (r = self.max_seq); it wraps at most
|
||||
// once because win <= swa_win < r. Global pools have kv_start = 0, no wrap.
|
||||
let r = self.max_seq;
|
||||
let s0 = kv_start % r;
|
||||
let first = win.min(r - s0);
|
||||
let row = win * d.hd * es;
|
||||
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_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, k_cache, v_cache,
|
||||
seq_len, kv_start, 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])?],
|
||||
@@ -286,23 +377,50 @@ impl LayerState {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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].
|
||||
/// 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 row = snap.seq_len * d.hd * es;
|
||||
let win = snap.seq_len - snap.kv_start;
|
||||
let r = self.max_seq;
|
||||
let s0 = snap.kv_start % r;
|
||||
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_from(src, self.max_seq * d.hd * es, row, row, 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_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_from(src, self.max_seq * d.hd * es, row, row, 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_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(())
|
||||
}
|
||||
|
||||
/// Zero the ShortConv history rings (async device memset). Used when reusing
|
||||
/// persistent states for a COLD request (no prefix restore): the KV prefix is
|
||||
/// overwritten by prefill before any causal read, but the hist rings seed the
|
||||
/// first 3 shortconv steps and must start empty for a fresh conversation.
|
||||
pub fn reset_history(&mut self) -> Result<(), String> {
|
||||
for i in 0..3 {
|
||||
self.hist_k[i].zero_async()?;
|
||||
self.hist_v[i].zero_async()?;
|
||||
self.hist_a[i].zero_async()?;
|
||||
self.hist_m[i].zero_async()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -337,8 +455,7 @@ pub fn layer_forward_swa(
|
||||
let slot0 = DeviceBuf::alloc(4)?; slot0.h2d_bytes(&0i32.to_le_bytes())?;
|
||||
let k_cv = DeviceBuf::alloc(kv_dim * 4)?;
|
||||
let v_cv = DeviceBuf::alloc(kv_dim * 4)?;
|
||||
let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?;
|
||||
rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?;
|
||||
let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill
|
||||
let aout = DeviceBuf::alloc(q_dim * 4)?;
|
||||
let aout_bf = DeviceBuf::alloc(q_dim * 2)?;
|
||||
let oproj = DeviceBuf::alloc(h * 4)?;
|
||||
@@ -492,8 +609,7 @@ fn layer_forward_swa_batched(
|
||||
let bu = b as usize;
|
||||
let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
|
||||
let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
|
||||
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?;
|
||||
rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?;
|
||||
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill
|
||||
let aout = DeviceBuf::alloc(bu * q_dim * 4)?;
|
||||
let aout_bf = DeviceBuf::alloc(bu * q_dim * 2)?;
|
||||
let oproj = DeviceBuf::alloc(bu * h * 4)?;
|
||||
@@ -547,9 +663,9 @@ fn layer_forward_swa_batched(
|
||||
}
|
||||
// k2: ShortConv prefill (parallel causal) + history roll, then clip/relpos/KV.
|
||||
vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_sconv, None, &st.hist_k[pass], &k_cv, b, kv_dim as i32, 0)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?;
|
||||
spec_update_hist(&k_raw, &st.hist_k[pass], &mut st.snap_k[pass], b, kv_dim as i32)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_sconv, None, &st.hist_v[pass], &v_cv, b, kv_dim as i32, 0)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?;
|
||||
spec_update_hist(&v_raw, &st.hist_v[pass], &mut st.snap_v[pass], b, kv_dim as i32)?;
|
||||
vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_head as i32, None)?;
|
||||
vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, false, 0, d.n_head as i32, None)?;
|
||||
vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?;
|
||||
@@ -561,7 +677,7 @@ fn layer_forward_swa_batched(
|
||||
vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, bu * q_dim)?;
|
||||
vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?;
|
||||
spec_update_hist(&oproj, &st.hist_a[pass], &mut st.snap_a[pass], b, h as i32)?;
|
||||
if w.ip % d.block_size == 0 {
|
||||
blocks.snapshot(cur)?;
|
||||
vetta_infer_hip::copy_f32(&asc, cur, bu * h)?;
|
||||
@@ -587,7 +703,7 @@ fn layer_forward_swa_batched(
|
||||
// k7: mlp shortconv + plain residual add.
|
||||
let msc = DeviceBuf::alloc(bu * h * 4)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?;
|
||||
spec_update_hist(&moeout, &st.hist_m[pass], &mut st.snap_m[pass], b, h as i32)?;
|
||||
vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -639,13 +755,13 @@ pub fn final_logits(cache: &WeightCache, cur: &DeviceBuf, blocks: &[DeviceBuf],
|
||||
/// final residual stream + the accumulated depth-block snapshots. (Prelude /
|
||||
/// single-pass; full-attn layers + loop controllers + bank rollback come next.)
|
||||
pub fn forward_swa_layers(
|
||||
cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32,
|
||||
cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, _max_seq: usize, pos: i32,
|
||||
) -> Result<(DeviceBuf, Vec<DeviceBuf>), String> {
|
||||
let cur = embed_token(cache, token, d.hidden, /*vocab*/ 201024)?;
|
||||
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
||||
for &ip in schedule {
|
||||
let w = cache.swa_layer(ip)?;
|
||||
let mut st = new_state(d, max_seq, 1)?;
|
||||
let mut st = new_state(d, swa_ring(d), 1)?;
|
||||
layer_forward_swa(cache, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?;
|
||||
}
|
||||
Ok((cur, blocks))
|
||||
@@ -654,6 +770,15 @@ pub fn forward_swa_layers(
|
||||
/// Full-attention physical layers (the rest are sliding-window).
|
||||
pub fn is_swa(ip: usize) -> bool { !matches!(ip, 5 | 11 | 17 | 23) }
|
||||
|
||||
/// Max batched-prefill chunk the SWA ring is sized for. The ring invariant
|
||||
/// (proofs/prefix_cache.lean Part E `ring_no_clobber`) requires
|
||||
/// `ring >= swa_win + chunk`; serve clamps the chunk to this cap.
|
||||
pub const SWA_CHUNK_CAP: usize = 512;
|
||||
/// Circular KV capacity of a SWA pool: `swa_win + SWA_CHUNK_CAP` positions instead
|
||||
/// of the whole context (the causal window never reads older rows). Global pools
|
||||
/// keep a linear `max_context` cache. Sized once, never resized across requests.
|
||||
pub fn swa_ring(d: &Dims) -> usize { d.swa_win.max(0) as usize + SWA_CHUNK_CAP }
|
||||
|
||||
/// Build the stacked cross-pass msg_queries [4, hidden] for a core layer ip:
|
||||
/// [q_cp[2i], kv_cp[2i], kv_cp[2i+1], q_cp[2i+1]] with i = ip - core_start.
|
||||
fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
|
||||
@@ -760,6 +885,8 @@ fn moe_batched(
|
||||
cache: &WeightCache, ip: usize, mlpin: &DeviceBuf, ids: &DeviceBuf, weights: &DeviceBuf, d: &Dims, h: usize, b: i32,
|
||||
) -> Result<DeviceBuf, String> {
|
||||
let t0 = std::time::Instant::now();
|
||||
let prof = std::env::var("VETTA_PROF").is_ok();
|
||||
if prof { vetta_infer_hip::synchronize()?; } // isolate real MoE GPU time (drain prior work)
|
||||
let w13 = cache.expert_arena(ip, "w13")?;
|
||||
let w2 = cache.expert_arena(ip, "w2")?;
|
||||
let top_k = d.top_k;
|
||||
@@ -768,7 +895,7 @@ fn moe_batched(
|
||||
let mlpin16 = DeviceBuf::alloc((b as usize) * h * 2)?;
|
||||
vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, (b as usize) * h)?;
|
||||
// Bucket CSR (device-side).
|
||||
let dcnt = DeviceBuf::alloc(129 * 4)?; dcnt.h2d_bytes(&vec![0u8; 129 * 4])?;
|
||||
let dcnt = DeviceBuf::alloc(129 * 4)?; dcnt.zero_async()?;
|
||||
let doff = DeviceBuf::alloc(129 * 4)?;
|
||||
let dcur = DeviceBuf::alloc(128 * 4)?;
|
||||
let dbtk = DeviceBuf::alloc(total * 4)?;
|
||||
@@ -778,18 +905,17 @@ fn moe_batched(
|
||||
vetta_infer_hip::moe_scatter_buckets(ids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32)?;
|
||||
// w13 grouped GEMM: gather input tokens via bucket_tok -> gu [total, 2*inter].
|
||||
let gu = DeviceBuf::alloc(total * 2 * inter * 4)?;
|
||||
expert_arena_grouped_gemv_f16(&w13, &doff, &dbtk, &mlpin16, &gu)?;
|
||||
expert_arena_grouped_gemv_f16(&w13, &doff, Some(&dbtk), &mlpin16, &gu, b)?;
|
||||
let act16 = DeviceBuf::alloc(total * inter * 2)?;
|
||||
vetta_infer_hip::situ_f16_batched(&gu, &act16, inter as i32, d.beta, d.lb, total as i32)?;
|
||||
// w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index.
|
||||
let idx: Vec<i32> = (0..total as i32).collect();
|
||||
let idx_bytes: Vec<u8> = idx.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
let didx = DeviceBuf::alloc(total * 4)?; didx.h2d_bytes(&idx_bytes)?;
|
||||
// w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index
|
||||
// (bucket_tok=None reads tok = beg+t0+m in-kernel; no host identity h2d sync).
|
||||
let y_part = DeviceBuf::alloc(total * h * 4)?;
|
||||
expert_arena_grouped_gemv_f16(&w2, &doff, &didx, &act16, &y_part)?;
|
||||
expert_arena_grouped_gemv_f16(&w2, &doff, None, &act16, &y_part, b)?;
|
||||
// Scatter-back + weighted reduce per token.
|
||||
let moeout = DeviceBuf::alloc((b as usize) * h * 4)?;
|
||||
vetta_infer_hip::moe_reduce_buckets_masked(&y_part, &ds2b, weights, &moeout, b, top_k as i32, h as i32)?;
|
||||
if prof { vetta_infer_hip::synchronize()?; }
|
||||
EXPERT_NS.with(|c| c.set(c.get() + t0.elapsed().as_nanos()));
|
||||
Ok(moeout)
|
||||
}
|
||||
@@ -804,7 +930,7 @@ fn run_layer(
|
||||
if states[ip].is_none() {
|
||||
// Core layers run 3 loop passes (3 distinct KV pools); prelude/coda run 1.
|
||||
let n_passes = if (6..18).contains(&ip) { 3 } else { 1 };
|
||||
states[ip] = Some(new_state(d, max_seq, n_passes)?);
|
||||
states[ip] = Some(new_state(d, if is_swa(ip) { swa_ring(d) } else { max_seq }, n_passes)?);
|
||||
}
|
||||
let st = states[ip].as_mut().unwrap();
|
||||
let r = if is_swa(ip) {
|
||||
@@ -879,7 +1005,7 @@ pub fn forward_inkling_with_state(
|
||||
}
|
||||
for ip in 6..18 {
|
||||
if p > 0 && std::env::var("VETTA_NO_CTRL").is_err() {
|
||||
let mq = load_msg_queries(cache, ip, h)?;
|
||||
let mq = cache.msg_queries(ip, h)?;
|
||||
let n_bank = bank.len();
|
||||
let blk = DeviceBuf::alloc(n_bank.max(1) * h * 4)?;
|
||||
let mut bh = vec![0f32; n_bank.max(1) * h];
|
||||
@@ -927,7 +1053,7 @@ fn run_layer_batched(
|
||||
) -> Result<(), String> {
|
||||
if states[ip].is_none() {
|
||||
let n_passes = if (6..18).contains(&ip) { 3 } else { 1 };
|
||||
states[ip] = Some(new_state(d, max_seq, n_passes)?);
|
||||
states[ip] = Some(new_state(d, if is_swa(ip) { swa_ring(d) } else { max_seq }, n_passes)?);
|
||||
}
|
||||
let st = states[ip].as_mut().unwrap();
|
||||
if is_swa(ip) {
|
||||
@@ -950,10 +1076,45 @@ pub fn forward_batch(
|
||||
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
|
||||
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
|
||||
) -> Result<DeviceBuf, String> {
|
||||
Ok(forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, None, false)?.unwrap())
|
||||
}
|
||||
|
||||
/// forward_batch + DSpark target-tap capture: visits 5/23/41 entry residual and
|
||||
/// visit 48 = output-normed final depth mix. `taps_out[k]` must be [B*hidden] f32.
|
||||
/// These feed dspark_context (the drafter's committed context) per token.
|
||||
pub fn forward_batch_taps(
|
||||
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
|
||||
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
|
||||
taps_out: &mut [DeviceBuf; 4],
|
||||
) -> Result<DeviceBuf, String> {
|
||||
Ok(forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, Some(taps_out), false)?.unwrap())
|
||||
}
|
||||
|
||||
/// forward_batch_taps skipping the single-row unembed: used by `spec_round`
|
||||
/// verify, which computes all B rows of logits directly from `taps_out[3]` in
|
||||
/// one batched unembed + GPU argmax (avoids running unembed twice per round!).
|
||||
pub fn forward_batch_taps_no_logits(
|
||||
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
|
||||
base_pos: i32, states: &mut [Option<LayerState>],
|
||||
taps_out: &mut [DeviceBuf; 4],
|
||||
) -> Result<(), String> {
|
||||
let _ = forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, 0.0, states, Some(taps_out), true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn forward_batch_inner(
|
||||
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
|
||||
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
|
||||
mut taps: Option<&mut [DeviceBuf; 4]>, skip_unembed: bool,
|
||||
) -> Result<Option<DeviceBuf>, String> {
|
||||
let h = d.hidden; let bu = tokens.len();
|
||||
if bu == 0 { return Err("forward_batch: empty tokens".into()); }
|
||||
let b = bu as i32;
|
||||
let max_pos = base_pos + b - 1;
|
||||
let prof = std::env::var("VETTA_PROF").is_ok();
|
||||
let tp0 = std::time::Instant::now();
|
||||
let gb = |x: usize| x as f64 / 1e9;
|
||||
if prof { eprintln!("[BPROF] B={bu} base_pos={base_pos} vram_start={:.2}GB", gb(vetta_infer_hip::vram_used())); }
|
||||
// Embed B tokens (gather + RMS-norm rows=B).
|
||||
let table = cache.raw("model.llm.embed.weight")?;
|
||||
let tok_bytes: Vec<u8> = tokens.iter().flat_map(|t| t.to_le_bytes()).collect();
|
||||
@@ -967,7 +1128,13 @@ pub fn forward_batch(
|
||||
let dpos = DeviceBuf::alloc(bu * 4)?; dpos.h2d_bytes(&pos_bytes)?;
|
||||
let mut blocks = BatchBlocks::new(bu, h, 8)?;
|
||||
// Prelude.
|
||||
for ip in 0..6 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; }
|
||||
for ip in 0..6 {
|
||||
if ip == 5 {
|
||||
if let Some(t) = taps.as_deref_mut() { vetta_infer_hip::copy_f32(&cur, &t[0], bu * h)?; }
|
||||
}
|
||||
run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?;
|
||||
}
|
||||
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] prelude {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
|
||||
let n_prelude_blocks = blocks.count;
|
||||
let prelude = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&cur, &prelude, bu * h)?;
|
||||
// Core: 3 passes with device-side bank rollback.
|
||||
@@ -986,8 +1153,15 @@ pub fn forward_batch(
|
||||
blocks.truncate(n_prelude_blocks);
|
||||
}
|
||||
for ip in 6..18 {
|
||||
let visit = 6 + p * 12 + (ip - 6);
|
||||
if visit == 23 || visit == 41 {
|
||||
if let Some(t) = taps.as_deref_mut() {
|
||||
let k = if visit == 23 { 1 } else { 2 };
|
||||
vetta_infer_hip::copy_f32(&cur, &t[k], bu * h)?;
|
||||
}
|
||||
}
|
||||
if p > 0 && !no_ctrl {
|
||||
let mq = load_msg_queries(cache, ip, h)?;
|
||||
let mq = cache.msg_queries(ip, h)?;
|
||||
let msgs_buf = DeviceBuf::alloc(bu * 4 * h * 4)?;
|
||||
vetta_infer_hip::attn_res_mix(&bank_buf, &bank_out, &mq, &msgs_buf, n_bank as i32, b, 4, h as i32, d.eps)?;
|
||||
let cw = cache.controllers(ip)?;
|
||||
@@ -998,14 +1172,30 @@ pub fn forward_batch(
|
||||
}
|
||||
}
|
||||
// Coda.
|
||||
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] core {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
|
||||
for ip in 18..24 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; }
|
||||
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] coda {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
|
||||
// Final depth mix + unembed the LAST token.
|
||||
let oq = cache.raw("model.llm.attn_res.output_query")?;
|
||||
let mix = DeviceBuf::alloc(bu * h * 4)?;
|
||||
vetta_infer_hip::attn_res_mix(&blocks.arena, &cur, &oq, &mix, blocks.count as i32, b, 1, h as i32, d.eps)?;
|
||||
if let Some(t) = taps.as_deref_mut() {
|
||||
let onorm = cache.bf16_f32("model.llm.norm.weight")?;
|
||||
vetta_infer_hip::rms_norm_f32(&mix, Some(&onorm), &t[3], b, h as i32, d.eps)?;
|
||||
}
|
||||
let logits = if skip_unembed {
|
||||
None
|
||||
} else {
|
||||
let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?;
|
||||
let logits = unembed_logits(cache, &last, h, vocab, d.eps)?;
|
||||
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
|
||||
let l = unembed_logits(cache, &last, h, vocab, d.eps)?;
|
||||
if cap > 0.0 { vetta_infer_hip::softcap(&l, &l, vocab, cap)?; }
|
||||
Some(l)
|
||||
};
|
||||
if prof {
|
||||
vetta_infer_hip::synchronize()?;
|
||||
let exp = EXPERT_NS.with(|c| c.replace(0));
|
||||
eprintln!("[BPROF] total {:.1}ms moe_launch={:.1}ms vram_end={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, exp as f64/1e6, gb(vetta_infer_hip::vram_used()));
|
||||
}
|
||||
Ok(logits)
|
||||
}
|
||||
|
||||
@@ -1134,8 +1324,7 @@ pub fn layer_forward_full(
|
||||
vetta_infer_hip::l2_clip(&q, Some(&w.q_sc), d.n_head as i32, d.hd as i32, d.qk_clip, true, pos)?;
|
||||
vetta_infer_hip::l2_clip(&r_raw, Some(&w.r_sc), d.n_head as i32, d.d_rel as i32, d.rel_clip, true, pos)?;
|
||||
vetta_infer_hip::l2_clip(&k_cv, None, d.n_kv as i32, d.hd as i32, d.qk_clip, false, pos)?;
|
||||
let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?;
|
||||
rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?;
|
||||
let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill
|
||||
let lim = (pos + 1).min(d.rel_extent as i32);
|
||||
vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?;
|
||||
if f16_kv() {
|
||||
@@ -1254,15 +1443,14 @@ fn layer_forward_full_batched(
|
||||
let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
|
||||
let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_static, Some(&k_dyn), &st.hist_k[pass], &k_cv, b, kv_dim as i32, d.n_kv as i32)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?;
|
||||
spec_update_hist(&k_raw, &st.hist_k[pass], &mut st.snap_k[pass], b, kv_dim as i32)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_static, Some(&v_dyn), &st.hist_v[pass], &v_cv, b, kv_dim as i32, d.n_kv as i32)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?;
|
||||
spec_update_hist(&v_raw, &st.hist_v[pass], &mut st.snap_v[pass], b, kv_dim as i32)?;
|
||||
// tau on Q/R (per-token pos), K clip without tau.
|
||||
vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, true, 0, d.n_head as i32, Some(pos))?;
|
||||
vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, true, 0, d.n_head as i32, Some(pos))?;
|
||||
vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?;
|
||||
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?;
|
||||
rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?;
|
||||
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill
|
||||
vetta_infer_hip::relpos_bias_batched(&r_raw, &w.rel_proj, &rel_bias, pos, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, b)?;
|
||||
vetta_infer_hip::kv_store_f16_batched(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps, b)?;
|
||||
let aout = DeviceBuf::alloc(bu * q_dim * 4)?;
|
||||
@@ -1273,7 +1461,7 @@ fn layer_forward_full_batched(
|
||||
vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?;
|
||||
let asc = DeviceBuf::alloc(bu * h * 4)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?;
|
||||
spec_update_hist(&oproj, &st.hist_a[pass], &mut st.snap_a[pass], b, h as i32)?;
|
||||
if w.ip % d.block_size == 0 {
|
||||
blocks.snapshot(cur)?;
|
||||
vetta_infer_hip::copy_f32(&asc, cur, bu * h)?;
|
||||
@@ -1297,7 +1485,7 @@ fn layer_forward_full_batched(
|
||||
let moeout = moe_batched(cache, w.ip, &mlpin, &ids, &weights, d, h, b)?;
|
||||
let msc = DeviceBuf::alloc(bu * h * 4)?;
|
||||
vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?;
|
||||
vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?;
|
||||
spec_update_hist(&moeout, &st.hist_m[pass], &mut st.snap_m[pass], b, h as i32)?;
|
||||
vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1539,7 +1727,7 @@ mod tests {
|
||||
let mut ids_b = vec![0u8; b * top_k * 4]; ids.d2h_bytes(&mut ids_b).unwrap();
|
||||
let ids_h: Vec<i32> = ids_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
||||
let mut weights_h = vec![0f32; b * top_k]; weights.d2h(&mut weights_h).unwrap();
|
||||
let mut max_rel = 0f32;
|
||||
let mut os_all = vec![0f32; b * h];
|
||||
for m in 0..b {
|
||||
let mlpin_m = DeviceBuf::alloc(h * 4).unwrap(); mlpin_m.h2d(&mlpin_h[m * h..(m + 1) * h]).unwrap();
|
||||
let ids_m = DeviceBuf::alloc(top_k * 4).unwrap();
|
||||
@@ -1548,8 +1736,14 @@ mod tests {
|
||||
let weights_m = DeviceBuf::alloc(top_k * 4).unwrap(); weights_m.h2d(&weights_h[m * top_k..(m + 1) * top_k]).unwrap();
|
||||
let moeout_s = moe_device(&cache, ip, &mlpin_m, &ids_m, &weights_m, &d, h).unwrap();
|
||||
let mut os = vec![0f32; h]; moeout_s.d2h(&mut os).unwrap();
|
||||
for j in 0..h { max_rel = max_rel.max((ob[m * h + j] - os[j]).abs() / os[j].abs().max(1e-3)); }
|
||||
os_all[m * h..(m + 1) * h].copy_from_slice(&os);
|
||||
}
|
||||
// Global-scale normalization: P1 WMMA (ip=0 NVFP4) vs serial fdot2 differs
|
||||
// ~1e-4 absolute, which explodes per-entry on near-zero expert outputs.
|
||||
// ip=20 MXFP8 uses the same Wave32 fdot2 on both paths => bit-exact.
|
||||
let scale = os_all.iter().fold(0f32, |mx, v| mx.max(v.abs())).max(1e-3);
|
||||
let mut max_rel = 0f32;
|
||||
for (g, w) in ob.iter().zip(os_all.iter()) { max_rel = max_rel.max((g - w).abs() / scale); }
|
||||
eprintln!("moe_batched ip={ip} B={b} max_rel_err={max_rel:.3e}");
|
||||
assert!(max_rel < 3e-3, "batched MoE parity failed at ip={ip}: {max_rel}");
|
||||
}
|
||||
@@ -1593,8 +1787,13 @@ mod tests {
|
||||
let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap();
|
||||
cs[m * h..(m + 1) * h].copy_from_slice(&o);
|
||||
}
|
||||
// Normalize by the GLOBAL cur scale, not per-entry: the P1 WMMA MoE differs
|
||||
// from serial fdot2 by ~1e-4 absolute, which explodes as a per-entry relative
|
||||
// error on near-zero residual entries. The KV cache stays byte-identical
|
||||
// (attention precedes MoE) — that is the strong correctness gate here.
|
||||
let cscale = cs.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-3);
|
||||
let mut max_rel = 0f32;
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); }
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / cscale); }
|
||||
// KV cache byte-compare (f16).
|
||||
let kvn = d.n_kv * max_seq * d.hd * 2;
|
||||
let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap();
|
||||
@@ -1643,8 +1842,13 @@ mod tests {
|
||||
let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap();
|
||||
cs[m * h..(m + 1) * h].copy_from_slice(&o);
|
||||
}
|
||||
// Normalize by the GLOBAL cur scale, not per-entry: the P1 WMMA MoE differs
|
||||
// from serial fdot2 by ~1e-4 absolute, which explodes as a per-entry relative
|
||||
// error on near-zero residual entries. The KV cache stays byte-identical
|
||||
// (attention precedes MoE) — that is the strong correctness gate here.
|
||||
let cscale = cs.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-3);
|
||||
let mut max_rel = 0f32;
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); }
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / cscale); }
|
||||
let kvn = d.n_kv * max_seq * d.hd * 2;
|
||||
let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap();
|
||||
let mut ks = vec![0u8; kvn]; st_s.k_cache[0].d2h_bytes(&mut ks).unwrap();
|
||||
@@ -1682,10 +1886,59 @@ mod tests {
|
||||
let args = ls.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0;
|
||||
let mut max_abs = 0f32; let mut max_rel = 0f32;
|
||||
for (g, w) in lb.iter().zip(ls.iter()) { max_abs = max_abs.max((g - w).abs()); max_rel = max_rel.max((g - w).abs() / w.abs().max(1.0)); }
|
||||
eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e}");
|
||||
let gscale = ls.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
|
||||
eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e} global_rel={:.3e}", max_abs / gscale);
|
||||
set_kv_f16(false);
|
||||
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
|
||||
assert_eq!(argb, args, "forward_batch argmax must match sequential (greedy gate)");
|
||||
// P1 tolerance: prefill uses FP16 WMMA MoE (tensor-core f32 accumulation
|
||||
// order) + FA2 flash prefill (f16 P/Q rounding) while M=1 decode uses serial
|
||||
// fdot2 + f32 two-pass softmax. Per-kernel ~1e-4..1e-3 compounds through 24
|
||||
// layers to ~5e-3 of the GLOBAL logit scale (per-entry rel explodes on
|
||||
// near-zero logits). The argmax above + gw serve_gen_multi_token_parity
|
||||
// (greedy-vs-reference EXACT) are the blocking production gates.
|
||||
assert!(max_abs / gscale < 1e-2, "forward_batch logits parity failed: global_rel={}", max_abs / gscale);
|
||||
}
|
||||
|
||||
/// DSpark tap capture: forward_batch_taps must (a) leave logits BIT-IDENTICAL
|
||||
/// to forward_batch (capture is pure copies) and (b) tap48 = output-normed
|
||||
/// final mix, whose last row unembeds to exactly those logits.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn forward_batch_taps_capture() {
|
||||
set_kv_f16(true);
|
||||
unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") };
|
||||
let ar = Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||
let cache = WeightCache::new(ar.clone());
|
||||
let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 };
|
||||
let vocab = 200058usize; let b = 4usize; let max_seq = b + 2; let h = d.hidden;
|
||||
let tokens: Vec<i32> = vec![100, 200, 300, 400];
|
||||
let mut st_b: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
|
||||
let lb_buf = forward_batch(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut st_b).unwrap();
|
||||
let mut lb = vec![0f32; vocab]; lb_buf.d2h(&mut lb).unwrap();
|
||||
let mut st_t: Vec<Option<LayerState>> = (0..24).map(|_| None).collect();
|
||||
let mut taps: [DeviceBuf; 4] = std::array::from_fn(|_| DeviceBuf::alloc(b * h * 4).unwrap());
|
||||
let lt_buf = forward_batch_taps(&cache, &d, &tokens, vocab, max_seq, 0, 0.0, &mut st_t, &mut taps).unwrap();
|
||||
let mut lt = vec![0f32; vocab]; lt_buf.d2h(&mut lt).unwrap();
|
||||
assert_eq!(lb, lt, "tap capture must not perturb logits");
|
||||
let last = DeviceBuf::alloc(h * 4).unwrap();
|
||||
vetta_infer_hip::copy_f32_sub(&taps[3], (b - 1) * h, &last, h).unwrap();
|
||||
// tap48 is ALREADY output-normed, so unembed it directly (cast bf16 +
|
||||
// gemm), NOT via unembed_logits (which would norm a second time).
|
||||
let nb = DeviceBuf::alloc(h * 2).unwrap();
|
||||
vetta_infer_hip::cast_f32_bf16(&last, &nb, h).unwrap();
|
||||
let unembed = cache.raw("model.llm.unembed.weight").unwrap();
|
||||
let lo = DeviceBuf::alloc(vocab * 4).unwrap();
|
||||
vetta_infer_hip::gemm_bf16(&nb, &unembed, &lo, 1, vocab as i32, h as i32).unwrap();
|
||||
let mut l48 = vec![0f32; vocab]; lo.d2h(&mut l48).unwrap();
|
||||
assert_eq!(lt, l48, "tap48 (output-normed mix) must reproduce logits");
|
||||
for k in 0..4 {
|
||||
let mut v = vec![0f32; b * h]; taps[k].d2h(&mut v).unwrap();
|
||||
assert!(v.iter().all(|x| x.is_finite()), "tap{k} non-finite");
|
||||
assert!(v.iter().any(|x| *x != 0.0), "tap{k} all zero");
|
||||
}
|
||||
eprintln!("forward_batch_taps: logits bit-identical, tap48 reproduces logits, taps finite");
|
||||
set_kv_f16(false);
|
||||
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
|
||||
assert_eq!(argb, args, "forward_batch argmax must match sequential");
|
||||
assert!(max_abs < 1e-2, "forward_batch logits parity failed: max_abs={max_abs}");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
|
||||
|
||||
pub mod bundle;
|
||||
pub mod dspark;
|
||||
pub mod inkling;
|
||||
pub mod inkling_ir;
|
||||
pub mod inkling_plan;
|
||||
@@ -76,9 +77,62 @@ impl SafetensorsArchive {
|
||||
let mut tensors = HashMap::new();
|
||||
|
||||
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
|
||||
let sh = load_shard(&path, shard_idx, &mut tensors)?;
|
||||
shards.push(sh);
|
||||
}
|
||||
|
||||
Ok(Self { dir, shards, tensors })
|
||||
}
|
||||
|
||||
/// Open a SINGLE safetensors file (e.g. `mtp.safetensors`, which is not in
|
||||
/// the trunk index weight_map). Same checked header/bounds validation.
|
||||
pub fn open_file(path: impl AsRef<Path>) -> Result<Self, String> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let dir = path
|
||||
.parent()
|
||||
.unwrap_or_else(|| Path::new("."))
|
||||
.to_path_buf();
|
||||
let mut tensors = HashMap::new();
|
||||
let sh = load_shard(&path, 0, &mut tensors)?;
|
||||
Ok(Self { dir, shards: vec![sh], tensors })
|
||||
}
|
||||
|
||||
pub fn total_tensor_bytes(&self) -> u64 {
|
||||
self.tensors.values().map(|t| t.byte_len()).sum()
|
||||
}
|
||||
|
||||
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
|
||||
let info = self
|
||||
.tensors
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("tensor not found: {name}"))?;
|
||||
let total = info.byte_len();
|
||||
let req = dst.len() as u64;
|
||||
if rel_off > total || req > total - rel_off {
|
||||
return Err(format!(
|
||||
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
|
||||
));
|
||||
}
|
||||
let sh = &self.shards[info.shard_idx];
|
||||
let file_off = sh
|
||||
.data_start
|
||||
.checked_add(info.begin)
|
||||
.and_then(|v| v.checked_add(rel_off))
|
||||
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
|
||||
sh.file
|
||||
.read_exact_at(dst, file_off)
|
||||
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
fn load_shard(
|
||||
path: &Path,
|
||||
shard_idx: usize,
|
||||
tensors: &mut HashMap<String, TensorInfo>,
|
||||
) -> Result<SafetensorsShard, String> {
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&path)
|
||||
.open(path)
|
||||
.map_err(|e| format!("open {}: {e}", path.display()))?;
|
||||
let file_size = file
|
||||
.metadata()
|
||||
@@ -151,53 +205,11 @@ impl SafetensorsArchive {
|
||||
}
|
||||
tensors.insert(
|
||||
name.clone(),
|
||||
TensorInfo {
|
||||
shard_idx,
|
||||
dtype,
|
||||
shape,
|
||||
begin,
|
||||
end,
|
||||
},
|
||||
TensorInfo { shard_idx, dtype, shape, begin, end },
|
||||
);
|
||||
}
|
||||
|
||||
shards.push(SafetensorsShard {
|
||||
path,
|
||||
file,
|
||||
file_size,
|
||||
data_start,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Self { dir, shards, tensors })
|
||||
}
|
||||
|
||||
pub fn total_tensor_bytes(&self) -> u64 {
|
||||
self.tensors.values().map(|t| t.byte_len()).sum()
|
||||
}
|
||||
|
||||
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
|
||||
let info = self
|
||||
.tensors
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("tensor not found: {name}"))?;
|
||||
let total = info.byte_len();
|
||||
let req = dst.len() as u64;
|
||||
if rel_off > total || req > total - rel_off {
|
||||
return Err(format!(
|
||||
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
|
||||
));
|
||||
}
|
||||
let sh = &self.shards[info.shard_idx];
|
||||
let file_off = sh
|
||||
.data_start
|
||||
.checked_add(info.begin)
|
||||
.and_then(|v| v.checked_add(rel_off))
|
||||
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
|
||||
sh.file
|
||||
.read_exact_at(dst, file_off)
|
||||
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
|
||||
}
|
||||
Ok(SafetensorsShard { path: path.to_path_buf(), file, file_size, data_start })
|
||||
}
|
||||
|
||||
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
|
||||
@@ -13,7 +13,7 @@ pub fn load_raw(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf, String
|
||||
let bytes = info.byte_len() as usize;
|
||||
let mut host = vec![0u8; bytes];
|
||||
ar.read_slice(name, 0, &mut host)?;
|
||||
let buf = DeviceBuf::alloc(bytes)?;
|
||||
let buf = DeviceBuf::alloc_unpooled(bytes)?;
|
||||
buf.h2d_bytes(&host)?;
|
||||
Ok(buf)
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub fn load_bf16_as_f32(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf
|
||||
let mut host = vec![0u8; bytes];
|
||||
ar.read_slice(name, 0, &mut host)?;
|
||||
let f: Vec<f32> = host.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
|
||||
let buf = DeviceBuf::alloc(f.len() * 4)?;
|
||||
let buf = DeviceBuf::alloc_unpooled(f.len() * 4)?;
|
||||
buf.h2d(&f)?;
|
||||
Ok(buf)
|
||||
}
|
||||
@@ -70,8 +70,8 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
|
||||
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
|
||||
let mut sbytes = vec![0u8; s_per_e];
|
||||
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
|
||||
let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?;
|
||||
let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?;
|
||||
let packed = DeviceBuf::alloc_unpooled(w_per_e)?; packed.h2d_bytes(&wbytes)?;
|
||||
let scales = DeviceBuf::alloc_unpooled(s_per_e)?; scales.h2d_bytes(&sbytes)?;
|
||||
return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true });
|
||||
}
|
||||
|
||||
@@ -99,9 +99,9 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
|
||||
};
|
||||
let outer = amax / den;
|
||||
|
||||
let packed = DeviceBuf::alloc(w_per_e)?;
|
||||
let packed = DeviceBuf::alloc_unpooled(w_per_e)?;
|
||||
packed.h2d_bytes(&wbytes)?;
|
||||
let scales = DeviceBuf::alloc(s_per_e)?;
|
||||
let scales = DeviceBuf::alloc_unpooled(s_per_e)?;
|
||||
scales.h2d_bytes(&sbytes)?;
|
||||
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
|
||||
}
|
||||
@@ -169,8 +169,8 @@ pub fn load_expert_arena(ar: &SafetensorsArchive, layer: usize, mat: &str) -> Re
|
||||
ar.read_slice(&wname, 0, &mut wbytes)?;
|
||||
let mut sbytes = vec![0u8; n_exp * s_per_e];
|
||||
ar.read_slice(&sname, 0, &mut sbytes)?;
|
||||
let packed = DeviceBuf::alloc(wbytes.len())?; packed.h2d_bytes(&wbytes)?;
|
||||
let scales = DeviceBuf::alloc(sbytes.len())?; scales.h2d_bytes(&sbytes)?;
|
||||
let packed = DeviceBuf::alloc_unpooled(wbytes.len())?; packed.h2d_bytes(&wbytes)?;
|
||||
let scales = DeviceBuf::alloc_unpooled(sbytes.len())?; scales.h2d_bytes(&sbytes)?;
|
||||
|
||||
let outer_h: Vec<f32> = if mxfp8 {
|
||||
vec![1.0; n_exp]
|
||||
@@ -202,9 +202,18 @@ pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &De
|
||||
/// expert eid processes its bucket tokens [exp_off[eid],exp_off[eid+1]) indexed
|
||||
/// by `bucket_tok`. X [B,K] f16 (gathered) or [total,K] f16 (bucket order, pass an
|
||||
/// identity index). Y [total_pairs,N] f32 in bucket order. Dispatches NVFP4/MXFP8.
|
||||
pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> {
|
||||
/// For small verify/decode batches (`b <= 12`, avg <=1 token/expert), NVFP4 uses
|
||||
/// Wave32 fdot2 (`nvfp4_grouped_gemv_f16`: bit-exact vs M=1, avoids 16-row WMMA
|
||||
/// zero-padding waste); larger prefill chunks (`b > 12`) use FP16 WMMA.
|
||||
pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf, b: i32) -> Result<(), String> {
|
||||
if a.mxfp8 {
|
||||
vetta_infer_hip::mxfp8_grouped_gemv_f16(&a.packed, &a.scales, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
|
||||
} else if a.k % 64 == 0
|
||||
&& (b > 12 || std::env::var("VETTA_FORCE_MOE_WMMA").is_ok())
|
||||
&& std::env::var("VETTA_NO_MOE_WMMA").is_err()
|
||||
{
|
||||
// P1: FP16 WMMA tensor-core grouped GEMM (~8x fdot2 ALU throughput on prefill).
|
||||
vetta_infer_hip::nvfp4_grouped_gemm_wmma(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
|
||||
} else {
|
||||
vetta_infer_hip::nvfp4_grouped_gemv_f16(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
|
||||
}
|
||||
|
||||
+58
-14
@@ -87,9 +87,9 @@ Five ideas explain almost everything that will surprise you:
|
||||
- prompt *"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 time-to-first-token is the **sequential prefill** of the GUI's
|
||||
~2650-token agent prompt (~140 ms/token); decode itself is ~4.2 tok/s. This
|
||||
is the honest current performance frontier, not a hang.
|
||||
- That 618 s was the *sequential* prefill of the day (2026-12-01). It is now
|
||||
historical: batched prefill + WMMA (below) cut prefill to ~6.3 ms/token, so
|
||||
the same prompt is seconds and a 16 k-token agent prompt ~105 s (was ~7 min).
|
||||
- **Host CPU during inference is no longer a busy-wait.** ROCm's default spin
|
||||
host-wait schedule pinned the process at ~100% CPU; setting
|
||||
`hipDeviceScheduleBlockingSync` before context creation (as the reference does)
|
||||
@@ -113,11 +113,50 @@ Five ideas explain almost everything that will surprise you:
|
||||
eviction (restore probes 2.4 s vs ~77/154 s cold), and parity stays EXACT at 1024
|
||||
(warm 2.41 s vs cold 230.4 s). The speedup materialises whenever the next prompt
|
||||
extends the previous token prefix (standard chat reconstruction).
|
||||
- **What is NOT done yet (the frontier):** HIP graph capture (collapse the
|
||||
per-token launches → near-zero host CPU), batched/chunked prefill (M>1 attention
|
||||
+ grouped MoE, make the *first* large-prompt time-to-first-token seconds, not
|
||||
minutes), and the expert-GEMV math speedup (WMMA). These are the M2 performance
|
||||
work — correctness is already there; speed is the next axis.
|
||||
- **Prefill is batched + tensor-core (2026-12-02, measured).** Chunked batched
|
||||
forward (M=B, `VETTA_PREFILL_CHUNK`), FP16 WMMA grouped MoE, BF16 WMMA dense
|
||||
projections, and 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%)** (MoE 41.6→36.9, BF16 36.2→27.8, flash 27.6→12.9),
|
||||
~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 — 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
|
||||
configurable (`serve --max-context N` / `VETTA_MAX_CONTEXT`, advertised in
|
||||
READY). Verified live: a 16504-token prompt generates (previously ERR 0 tokens).
|
||||
- **DSpark speculative drafter landed at `strata` parity (2026-12-02, measured).**
|
||||
Opt-in via `VETTA_SPEC=1` (lossless contract proven in `proofs/speculative_draft.lean`,
|
||||
200-token `spec_lossless_gate` EXACT, multi-turn `PrefixCache` + `DsparkSnapshot`
|
||||
restore EXACT). All drafting runs 100% on GPU: single-pass base-unembed Top-512
|
||||
screen (reads 922 MB `unembed` once per round), on-GPU Markov loop + candidate
|
||||
argmax (`<=32 B` D2H), 0-LDS Wave32 online-softmax block attention (regression-tested
|
||||
at `c_len = 17_000`), M-tiled Wave32 router GEMV, zero-scratch small-M SWA GQA,
|
||||
`fdot2` MoE for `b <= 12`, and an accepted-count EMA governor starting at `n_draft = 5`.
|
||||
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) vs
|
||||
`strata-inkling --draft dspark` **`13.66 tok/s`** on the exact same prompt.
|
||||
- **Short prose prompt (`"The capital of France is"`, 96 tok):** `nd=5` jumped from
|
||||
**`4.58` → `9.09 tok/s`** (**+98.5%**); default adaptive EMA **`8.93 tok/s`** decode.
|
||||
Full changelog & root-cause breakdown: `review/2026-12-02-fix-drafter-e-ottimizzazioni.md`.
|
||||
- **What is NOT done yet (the frontier):** **layer streaming in DMA** (the hard one:
|
||||
`io_uring O_DIRECT` + `hipHostRegister` SlabRing, Hot/Cold expert cache + lookahead
|
||||
prefetch), HIP graph capture (collapse per-token launches → near-zero host CPU),
|
||||
and the INT8 `sf4_i8` fused MoE (the reference's further 2×/5-8× MoE axis).
|
||||
Correctness and speculative drafting are landed; DMA memory streaming is next.
|
||||
|
||||
## The road to the goal
|
||||
|
||||
@@ -135,12 +174,15 @@ on 2026-12-01 (see *Current state*). The path, in order:
|
||||
4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load).
|
||||
5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity,
|
||||
first real GUI conversation 2026-12-01).
|
||||
6. **M2 performance** — ⏳ the current frontier: prefix checkpoint cache ✅ landed
|
||||
(multi-turn prefill reuse, EXACT parity, 57.8× measured); HIP graph capture
|
||||
(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,
|
||||
6. **M2 performance** — ⏳ prefix checkpoint cache ✅ (multi-turn reuse, EXACT,
|
||||
57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense +
|
||||
flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp
|
||||
✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU).
|
||||
7. **Drafter + DMA layer streaming** — ⏳ DSpark speculative drafter ✅ landed
|
||||
(`13.93 tok/s` on Rust coding, 2.04× vs OFF, matching `strata-inkling`); next is
|
||||
layer streaming in DMA (`io_uring O_DIRECT` + `hipHostRegister` SlabRing,
|
||||
Hot/Cold expert cache + lookahead prefetch) — the hard memory frontier.
|
||||
8. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
|
||||
domain-aware expert prefetch.
|
||||
|
||||
## How to verify
|
||||
@@ -154,7 +196,9 @@ lean proofs/slab_ring_dma.lean
|
||||
lean proofs/bus_lifecycle.lean
|
||||
lean proofs/serve_session.lean
|
||||
lean proofs/arena_plan.lean
|
||||
lean proofs/inkling_loop.lean
|
||||
lean proofs/prefix_cache.lean
|
||||
lean proofs/speculative_draft.lean
|
||||
|
||||
# Opt-in live tests against the real Inkling artifact:
|
||||
cargo test -p vetta-infer-ld -- --ignored inkling
|
||||
|
||||
@@ -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,
|
||||
|
||||
+1689
-117
File diff suppressed because it is too large.
Load diff
@@ -255,4 +255,133 @@ theorem poolInsert_nodup (cap : Nat) (pool : List Nat) (seq : Nat)
|
||||
pinned. The engine relies on this combinatorial fact (cap ≥ 3) when evicting;
|
||||
`poolInsert_preserves_pinned` proves the I3 invariant that anchors survive. -/
|
||||
|
||||
/-! ## Part D: SWA-window checkpoint observational equivalence
|
||||
|
||||
A SWA layer attends only to the causal window `[winStart w p, p]` at position
|
||||
`p` (kernel `k_flash_swa_gqa_*`: `k_start = p - w + 1` when `p ≥ w`, else 0).
|
||||
So a checkpoint at `seq_len = n` need only store KV from `kvStart w n = n - min n w`
|
||||
(the last `min n w` positions); the older KV is never read again. Restoring that
|
||||
window and prefilling the suffix is observationally exact for every future
|
||||
position `p ≥ n`. Full-attention layers keep the whole prefix (`kvStart = 0`).
|
||||
This is the memory refinement that shrinks SWA checkpoints (~40 of 48 pools). -/
|
||||
|
||||
/-- First KV position a SWA checkpoint at `n` must retain (window `w`). -/
|
||||
def kvStart (w n : Nat) : Nat := n - min n w
|
||||
|
||||
/-- First KV position the SWA attention reads at position `p` (window `w`). -/
|
||||
def winStart (w p : Nat) : Nat := if p ≥ w then p - w + 1 else 0
|
||||
|
||||
/-- CONTAINMENT: for any future position `p ≥ n`, the attention window starts at
|
||||
or after the checkpoint's retained start, so the window is fully covered by
|
||||
`[kvStart w n, p]` (restored window `[kvStart, n)` + suffix `[n, p]`). -/
|
||||
theorem kvStart_le_winStart (w n p : Nat) (h : n ≤ p) :
|
||||
kvStart w n ≤ winStart w p := by
|
||||
unfold kvStart winStart
|
||||
split
|
||||
· omega
|
||||
· have hn : n ≤ w := by omega
|
||||
have : min n w = n := Nat.min_eq_left hn
|
||||
omega
|
||||
|
||||
/-- Observational equivalence of windowed restore. `read kv p` is the SWA attention
|
||||
output, which by the kernel contract depends only on KV in `[winStart w p, p]`
|
||||
(`hwin`). If the restored+suffix cache `kv'` agrees with the cold cache `kv` on
|
||||
`[kvStart w n, p]` (`hagree` — restored window + causal suffix), then the read
|
||||
at `p` is identical. The containment lemma lifts the agreement to the window. -/
|
||||
theorem swa_window_restore_equiv {V R : Type} (w n p : Nat)
|
||||
(read : (Nat → V) → Nat → R)
|
||||
(hwin : ∀ kv kv' : Nat → V,
|
||||
(∀ i, winStart w p ≤ i → i ≤ p → kv i = kv' i) → read kv p = read kv' p)
|
||||
(kv kv' : Nat → V) (hn : n ≤ p)
|
||||
(hagree : ∀ i, kvStart w n ≤ i → i ≤ p → kv i = kv' i) :
|
||||
read kv p = read kv' p := by
|
||||
apply hwin
|
||||
intro i hi1 hi2
|
||||
exact hagree i (Nat.le_trans (kvStart_le_winStart w n p hn) hi1) hi2
|
||||
|
||||
/-- A full-attention checkpoint retains everything: its window covers the whole
|
||||
prefix (`n ≤ w`), so `kvStart w n = 0` and no KV is discarded. -/
|
||||
theorem kvStart_full (n w : Nat) (h : n ≤ w) : kvStart w n = 0 := by
|
||||
unfold kvStart
|
||||
have : min n w = n := Nat.min_eq_left h
|
||||
omega
|
||||
|
||||
/-!
|
||||
Part E — SWA KV ring (2026-12-02). The 40 SWA pools store a circular ring of
|
||||
`R = swa_win + chunk_cap` positions (`slot R p = p % R`); the 8 global pools keep
|
||||
a linear cache of `MAX_CONTEXT` positions, where `p < R` makes `%` the identity
|
||||
(`global_slot_id`). Correctness of the ring rests on three facts, proved here
|
||||
BEFORE the kernel/`LayerState` change (AGENTS.md invariant 6):
|
||||
E1 `slot_inj` / `window_slots_distinct`: a causal window spans ≤ R positions, so
|
||||
its slots are pairwise distinct (a read never aliases two logical positions).
|
||||
E2 `ring_no_clobber`: with `R ≥ swa_win + chunk`, the writes of one batched chunk
|
||||
(`[c, c+chunk)`) cannot overwrite a slot still needed by an earlier token's
|
||||
window read (`[c-swa_win, c+chunk)`), except the same logical position.
|
||||
E3 `global_slot_id`: below the ring length the modulo is the identity, so the
|
||||
global (linear) pools and all small-seq parity tests are unaffected.
|
||||
-/
|
||||
|
||||
/-- Ring slot of logical position `p` in a ring of `R` positions. -/
|
||||
def slot (R p : Nat) : Nat := p % R
|
||||
|
||||
/-- E1 core: two positions at distance < R with the same slot are equal. -/
|
||||
theorem slot_inj (R x y : Nat) (_hR : 0 < R) (hxy : x ≤ y) (hlt : y - x < R)
|
||||
(h : x % R = y % R) : x = y := by
|
||||
have hx := Nat.mod_add_div x R
|
||||
have hy := Nat.mod_add_div y R
|
||||
rw [h] at hx
|
||||
have hq : x / R ≤ y / R := Nat.div_le_div_right hxy
|
||||
have hAB : R * (x / R) ≤ R * (y / R) := Nat.mul_le_mul_left R hq
|
||||
have hyx : y - x = R * (y / R) - R * (x / R) := by omega
|
||||
have h2 : y - x = R * (y / R - x / R) := by
|
||||
rw [← Nat.mul_sub_left_distrib] at hyx
|
||||
exact hyx
|
||||
have hd : y / R - x / R = 0 := by
|
||||
cases Nat.eq_zero_or_pos (y / R - x / R) with
|
||||
| inl h0 => exact h0
|
||||
| inr hpos =>
|
||||
have h1d : 1 ≤ y / R - x / R := by omega
|
||||
have hge : R ≤ R * (y / R - x / R) := by
|
||||
simpa [Nat.mul_one] using Nat.mul_le_mul_left R h1d
|
||||
omega
|
||||
rw [hd, Nat.mul_zero] at h2
|
||||
omega
|
||||
|
||||
/-- E1: within any half-open interval of length ≤ R the ring slot is injective,
|
||||
so a causal window (span ≤ swa_win < R) never reads one slot as two positions. -/
|
||||
theorem window_slots_distinct (R a b p q : Nat) (hR : 0 < R) (hb : b ≤ R)
|
||||
(hp : a ≤ p) (hp' : p < a + b) (hq : a ≤ q) (hq' : q < a + b)
|
||||
(h : slot R p = slot R q) : p = q := by
|
||||
unfold slot at h
|
||||
have hlt : p - q < R := by omega
|
||||
have hlt' : q - p < R := by omega
|
||||
cases Nat.le_total p q with
|
||||
| inl hle => exact slot_inj R p q hR hle (by omega) h
|
||||
| inr hle => exact (slot_inj R q p hR hle (by omega) h.symm).symm
|
||||
|
||||
/-- E2: a batched chunk's KV writes cannot clobber a slot an earlier token of the
|
||||
same chunk still reads, provided `R ≥ swa_win + chunk`. `w` ranges over the
|
||||
chunk's writes `[c, c+chunk)`, `r` over the union of window reads
|
||||
`[c-swa_win, c+chunk)`; equal slots force `w = r` (the causal same-position
|
||||
write-then-read, which is ordered by the kernel). -/
|
||||
theorem ring_no_clobber (R win chunk c w r : Nat) (hR : 0 < R)
|
||||
(hcap : win + chunk ≤ R)
|
||||
(hw : c ≤ w) (hw' : w < c + chunk)
|
||||
(hr : c - win ≤ r) (hr' : r < c + chunk)
|
||||
(h : slot R w = slot R r) : w = r := by
|
||||
unfold slot at h
|
||||
cases Nat.le_total w r with
|
||||
| inl hle =>
|
||||
have hlt : r - w < R := by omega
|
||||
exact slot_inj R w r hR hle hlt h
|
||||
| inr hle =>
|
||||
have hlt : w - r < R := by omega
|
||||
exact (slot_inj R r w hR hle hlt h.symm).symm
|
||||
|
||||
/-- E3: below the ring length the modulo is the identity — global (linear) pools
|
||||
and every small-`seq` parity test behave exactly as before the ring. -/
|
||||
theorem global_slot_id (R p : Nat) (h : p < R) : slot R p = p := by
|
||||
unfold slot
|
||||
exact Nat.mod_eq_of_lt h
|
||||
|
||||
end VettaPrefixCache
|
||||
@@ -0,0 +1,108 @@
|
||||
/-
|
||||
vetta-infer — lossless greedy speculative decoding (DSpark Step 1).
|
||||
|
||||
Models the accept/rollback control flow of block speculative decoding and
|
||||
proves the two invariants that make it safe to ship:
|
||||
|
||||
(A) LOSSLESS GREEDY: one speculative round (draft ds, batched causal verify,
|
||||
accept longest matching prefix, emit correction/bonus) emits EXACTLY the
|
||||
plain-greedy prefix of length (match_len + 1). The draft therefore only
|
||||
changes HOW MANY tokens are produced per round, never WHICH tokens.
|
||||
Iterating rounds reproduces plain greedy token-for-token.
|
||||
|
||||
(B) ROLLBACK = TRUNCATE: with the SWA ring capacity R >= window + chunk
|
||||
(proofs/prefix_cache.lean Part E), the rejected draft tail occupies ring
|
||||
slots disjoint from the kept window, so rolling back to the accepted
|
||||
length needs NO data restore — truncating the history length suffices.
|
||||
|
||||
Core prover tactics only; no Mathlib. `#print axioms` must show no sorryAx.
|
||||
-/
|
||||
|
||||
namespace Vetta.Spec
|
||||
|
||||
/-- Longest prefix of the draft `ds` that equals plain greedy from `p`. -/
|
||||
def match_len (g : List Nat → Nat) (p : List Nat) : List Nat → Nat
|
||||
| [] => 0
|
||||
| d :: rest => if g p = d then 1 + match_len g (p ++ [d]) rest else 0
|
||||
|
||||
/-- Plain greedy: `greedy_seq g p n` = the next n greedy tokens after p. -/
|
||||
def greedy_seq (g : List Nat → Nat) (p : List Nat) : Nat → List Nat
|
||||
| 0 => []
|
||||
| n + 1 => greedy_seq g p n ++ [g (p ++ greedy_seq g p n)]
|
||||
|
||||
/-- One speculative round as the accept/correction loop: walk the draft while it
|
||||
matches greedy; on the first mismatch (or end) emit one greedy token. -/
|
||||
def spec_out (g : List Nat → Nat) (p : List Nat) : List Nat → List Nat
|
||||
| [] => p ++ [g p]
|
||||
| d :: rest => if g p = d then spec_out g (p ++ [d]) rest else p ++ [g p]
|
||||
|
||||
/-- Greedy shift: starting one token later (at the greedy token) drops the head. -/
|
||||
theorem greedy_shift (g : List Nat → Nat) (p : List Nat) (n : Nat) :
|
||||
greedy_seq g p (n + 1) = [g p] ++ greedy_seq g (p ++ [g p]) n := by
|
||||
induction n with
|
||||
| zero => simp [greedy_seq]
|
||||
| succ n ih =>
|
||||
show greedy_seq g p (n + 1) ++ [g (p ++ greedy_seq g p (n + 1))]
|
||||
= [g p] ++ (greedy_seq g (p ++ [g p]) n
|
||||
++ [g ((p ++ [g p]) ++ greedy_seq g (p ++ [g p]) n)])
|
||||
rw [ih]
|
||||
simp [List.append_assoc]
|
||||
|
||||
/-- (A) LOSSLESS GREEDY: a speculative round emits exactly the plain-greedy
|
||||
prefix of length match_len+1, for ANY draft (even an adversarial one). -/
|
||||
theorem spec_lossless (g : List Nat → Nat) (p : List Nat) (ds : List Nat) :
|
||||
spec_out g p ds = p ++ greedy_seq g p (match_len g p ds + 1) := by
|
||||
induction ds generalizing p with
|
||||
| nil => simp [spec_out, match_len, greedy_seq]
|
||||
| cons d rest ih =>
|
||||
simp only [spec_out, match_len]
|
||||
split
|
||||
· -- g p = d : accept head, recurse on (p ++ [d])
|
||||
rename_i h
|
||||
rw [ih (p ++ [d])]
|
||||
rw [greedy_shift (p := p)]
|
||||
simp [h, List.append_assoc, Nat.add_comm]
|
||||
· -- g p != d : reject immediately, emit the greedy correction
|
||||
simp [greedy_seq]
|
||||
|
||||
/-- Local ring injectivity (same statement as prefix_cache.lean Part E, kept
|
||||
here so this file verifies standalone with `lean`). -/
|
||||
theorem slot_inj (R x y : Nat) (_hR : 0 < R) (hxy : x ≤ y) (hlt : y - x < R)
|
||||
(h : x % R = y % R) : x = y := by
|
||||
have hx := (Nat.mod_add_div x R).symm
|
||||
have hy := (Nat.mod_add_div y R).symm
|
||||
rw [h] at hx
|
||||
have hq : x / R ≤ y / R := Nat.div_le_div_right hxy
|
||||
have hlt' : R * (y / R - x / R) < R := by
|
||||
have h1 : R * (y / R - x / R) = R * (y / R) - R * (x / R) := by
|
||||
rw [Nat.mul_sub_left_distrib]
|
||||
have h2 : R * (y / R) - R * (x / R) = y - x := by omega
|
||||
omega
|
||||
have h0 : y / R - x / R = 0 := by
|
||||
cases Nat.eq_zero_or_pos (y / R - x / R) with
|
||||
| inl hz => exact hz
|
||||
| inr hp =>
|
||||
have hge : R ≤ R * (y / R - x / R) := by
|
||||
simpa [Nat.mul_one] using Nat.mul_le_mul_left R hp
|
||||
exfalso
|
||||
exact Nat.not_le_of_gt hlt' hge
|
||||
have hqeq : x / R = y / R := by omega
|
||||
rw [hqeq] at hx
|
||||
omega
|
||||
|
||||
/-- (B) kept window and rejected tail occupy disjoint ring slots when the span
|
||||
fits the ring: positions [a, k) kept vs [k, b) rejected, b - a < R. Hence
|
||||
rollback can truncate the history length without restoring any KV data. -/
|
||||
theorem kept_rejected_disjoint (R a k b i j : Nat) (hR : 0 < R)
|
||||
(hi : a ≤ i) (hi2 : i < k) (hj : k ≤ j) (hj2 : j < b) (hspan : b - a < R) :
|
||||
i % R ≠ j % R := by
|
||||
intro heq
|
||||
have hle : i ≤ j := Nat.le_trans (Nat.le_of_lt hi2) hj
|
||||
have hlt : j - i < R := by omega
|
||||
have := slot_inj R i j hR hle hlt heq
|
||||
omega
|
||||
|
||||
end Vetta.Spec
|
||||
|
||||
#print axioms Vetta.Spec.spec_lossless
|
||||
#print axioms Vetta.Spec.kept_rejected_disjoint
|
||||
@@ -0,0 +1,214 @@
|
||||
# Audit approfondito: regressione Prefix Cache al 3° turno, Memory Leak VRAM e prefill lento
|
||||
|
||||
**Data:** 2026-12-02
|
||||
**Revisione analizzata:** `vetta-infer` @ `088ac1f` (`main`) — sola lettura, nessuna modifica al codice
|
||||
**Riferimento prestazionale:** `strata-inkling` (stessa GPU AMD RDNA 4, ~458 pp/s, 2048 tok in ~4.5 s, Turno 2+ <1 s)
|
||||
|
||||
---
|
||||
|
||||
## Sintesi esecutiva
|
||||
|
||||
I tre sintomi osservati live su `inkling-server.service` hanno cause distinte, tutte confermate direttamente nel codice sorgente:
|
||||
|
||||
| # | Sintomo osservato | Causa radice verificata | Impatto |
|
||||
|---|---|---|---|
|
||||
| **1** | **Turno 2 veloce, ma Turno 3 torna a ~1 minuto** | `PrefixCache::best_match` / `restore` non aggiornano `ck.lru`, e `PREFIX_CACHE_CAP = 6` (solo 4 slot non-pinnati) viene saturato dai salvataggi `prompt-boundary` + `full-sequence` che **evittano il checkpoint `2560` appena usato al Turno 2**. Al Turno 3 si riprecipita all'anchor `1024`. Inoltre `pos % 512 == 0` salta i grid-save non allineati. | Regressione completa della cache dal Turno 3 in poi |
|
||||
| **2a** | **Memory leak lento e monotono in VRAM** | `BUF_POOL` (`vetta-infer-hip/src/lib.rs:199`) è una `HashMap<usize, Vec<ptr>>` indicizzata per **byte esatti** senza cap né eviction. Ogni turno ha un tail chunk `bu = suffix.len() % 256` diverso: tutti i ~30–40 buffer temporanei per visit (`rel_bias`, `gu`, `y_part`, `BatchBlocks`, ecc. — **~100–250 MiB per ogni `bu` distinto**) usano `DeviceBuf::alloc` e restano intrappolati nel pool **fino al termine del processo**. | Crescita VRAM illimitata multi-turno |
|
||||
| **2b** | **Rimbalzo VRAM su e giù (±3.75 GB a ogni turno)** | `serve.rs:269` dimensiona `max_seq = n_prompt + max_new + 2` (~19.100 con `max_new = 16384` di `strata-ctl`). `new_state` (`layer.rs:230-245`) alloca **~3.75 GB** `unpooled` a ogni richiesta, li **azzera da CPU con `vec![0u8]` + `h2d_bytes` sincrono su PCIe** (anche su cache hit!), e li dealloca a fine turno. | Sawtooth ±3.75 GB + ~0.5–1.5 s di overhead per richiesta |
|
||||
| **3** | **Turno 1 ancora ~41–55 s (~1 min su ~2650 tok)** | Gli ultimi commit (`f25cd27`..`088ac1f`) hanno portato 2048 tok da ~60 s a `40.9 s` (`~50 pp/s`, ancora **~9×** sotto `strata`). Restano: MoE prefill ancora GEMV `fdot2` con gather sparso (niente WMMA), `k_gemm_bf16` FMA scalare senza WMMA/`hipBLASLt` e senza proiezione fusa `qkvrg`, attention prefill scalare con scratch in VRAM, più **72 stalli sincroni `d2h`/`h2d` per chunk (e per decode token)** in `load_msg_queries` (`layer.rs:662-674`). | Turno 1 ~1 min e overhead residuo anche in decode |
|
||||
|
||||
> **Nota positiva sul percorso fin qui:** l'architettura microkernel, la correttezza bit-exact (`forward_batch_parity max_abs=0.0`), la disciplina dei test e i progressi su `01d8a48`, `f25cd27`, `45d039d`, `088ac1f` sono molto solidi. I problemi 1, 2a, 2b e gli stalli PCIe si chiudono in poco tempo con fix mirati; il problema 3 richiede il passaggio a WMMA sui 3 kernel caldi del prefill.
|
||||
|
||||
---
|
||||
|
||||
## 1. Perché il Turno 2 è veloce e il Turno 3 torna a ~1 minuto (`serve.rs`)
|
||||
|
||||
### 1.1 Bug critico: `best_match` e `restore` non aggiornano `ck.lru` (`serve.rs:82-110`)
|
||||
|
||||
In `crates/vetta-infer-gw/src/serve.rs`:
|
||||
- `PREFIX_CACHE_CAP = 6` (`serve.rs:59`)
|
||||
- `pinned_anchor(seq)` blocca `{512, 1024}` (`serve.rs:60`), lasciando **solo 4 slot non-pinnati**.
|
||||
- `best_match(&self, ids)` (`serve.rs:82`) e `restore(&self, idx, ...)` (`serve.rs:95`) prendono `&self` e **non chiamano mai un aggiornamento LRU (`self.tick += 1; self.pool[idx].lru = self.tick`)**.
|
||||
|
||||
Ecco la traccia esatta di ciò che accade nei primi 3 turni di chat reale con `strata-ctl` (dove i 2 token finali del prompt cambiano quando il turno entra in history, e la risposta generata viene ri-tokenizzata diversamente):
|
||||
|
||||
1. **Turno 1** (`prompt_len = 2646`, `start = 0`, `chunk = 256`):
|
||||
- Grid saves (`serve.rs:361`): `512*` (`lru=1`), `1024*` (`lru=2`), `1536` (`lru=3`), `2048` (`lru=4`), `2560` (`lru=5`).
|
||||
- Prompt-boundary save (`serve.rs:392`): `2646` (`lru=6`). Pool pieno (6/6).
|
||||
- Full-sequence save (`serve.rs:479`): `2698` (`lru=7`) → evitta il più vecchio non-pinnato (`1536`, `lru=3`).
|
||||
- **Pool a fine Turno 1:** `{512*, 1024*, 2048(lru=4), 2560(lru=5), 2646(lru=6), 2698(lru=7)}`.
|
||||
|
||||
2. **Turno 2** (`prompt_len = 2738`, prefisso comune col Turno 1 = `2644`):
|
||||
- `2646` e `2698` falliscono per i 2 token finali di turn-tag (`common = 2644 < 2646`).
|
||||
- `best_match` trova **`2560`** → `restored = 2560` → solo 178 nuovi token → **Turno 2 VELOCE!**
|
||||
- **MA `ck[2560].lru` NON viene toccato**: resta bloccato a `lru = 5`!
|
||||
- Fine prefill: prompt-boundary save `2738` (`lru=8`) → evitta `2048` (`lru=4`).
|
||||
- Fine decode: full-sequence save `2829` (`lru=9`) → **evitta `2560` (`lru=5`) — esattamente il checkpoint appena usato con successo al Turno 2!**
|
||||
- **Pool a fine Turno 2:** `{512*, 1024*, 2646, 2698, 2738, 2829}` — **ZERO grid checkpoint > 1024 rimasti!**
|
||||
|
||||
3. **Turno 3** (`prompt_len ≈ 2870`):
|
||||
- Tutti e 4 gli slot non-pinnati (`2646`, `2698`, `2738`, `2829`) divergono sul confine di turno!
|
||||
- `best_match` non trova più `2560` (evitto!) né `2048` (evitto!) e **precipita all'anchor pinnato `1024`**!
|
||||
- Deve rifare **~1850 token a freddo** → **di nuovo ~40–55 secondi (~1 minuto)!**
|
||||
|
||||
### 1.2 Bug secondario: `pos % 512 == 0` salta i grid-save non allineati (`serve.rs:361`)
|
||||
|
||||
```rust
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 && pos % 512 == 0 {
|
||||
```
|
||||
|
||||
Se `start` o `suffix.len()` non sono multipli di 256/512 (oppure se un turno aggiunge token che scavalcano `3072` con `take = 256` partendo da `start = 2738`), `pos` non colpisce mai `pos % 512 == 0` e **nessun nuovo grid checkpoint viene salvato**, condannando i turni successivi a non avanzare mai la griglia oltre `2560`.
|
||||
|
||||
### 1.3 Spreco di slot e VRAM nei salvataggi
|
||||
|
||||
- Salvare sia `prompt-boundary` (`L392`) sia `full-sequence` (`L479`) brucia **2 slot su 4 a ogni turno** con entry che nella chat normale (`strata-ctl`) non faranno quasi mai hit al turno successivo, scacciando i grid checkpoint che invece funzionano sempre.
|
||||
- Inoltre `LayerState::snapshot` (`layer.rs:272-292`) copia tutti i `seq_len` token su **tutti e 48 i pool KV**, ma **40 dei 48 pool sono SWA (`swa_win = 1024`)**: per i layer SWA servono solo gli ultimi `min(seq_len, 1024)` token! Salvando l'intero `seq_len` su tutti i 48 pool, ogni checkpoint a `seq = 8192` occupa ~1.6 GB invece di ~350 MB.
|
||||
|
||||
### Fix consigliato per §1
|
||||
|
||||
1. **Aggiornare `ck.lru` su `restore` (`restore(&mut self, ...)`):** quando `best_match` fa hit, fare `self.tick += 1; self.pool[idx].lru = self.tick;`.
|
||||
2. **Sostituire `pos % 512 == 0` con soglia monotona `next_grid`:**
|
||||
- Calcolare `let mut next_grid = ((start / 512) + 1) * 512;`
|
||||
- In `while done < suffix.len()`, se `(pos as usize) < next_grid` e `(pos as usize + take) > next_grid`, spezzare il chunk esattamente a `next_grid - pos as usize` (oppure salvare al superamento di `next_grid`) e incrementare `next_grid += 512`. Così ogni multiplo di 512 viene sempre catturato indipendentemente da `start`.
|
||||
3. **Alzare `PREFIX_CACHE_CAP` (es. `12`) e proteggere i grid checkpoint:**
|
||||
- Non lasciare che `full-sequence` evitti un grid checkpoint (o salvarlo solo in 1 slot dedicato "last-turn" separato dal pool principale; o meglio ancora, salvare `prompt_len - 4` se si vuole coprire il margine di turn-tag).
|
||||
- *(Opzionale ma ad alto impatto)*: in `LayerState::snapshot` / `restore`, per i layer SWA (`is_swa(ip)`), salvare/ripristinare solo la finestra `[seq_len.saturating_sub(swa_win)..seq_len)`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Perché la VRAM rimbalza (±3.75 GB) e accumula un Memory Leak lento
|
||||
|
||||
### 2.1 Causa del Memory Leak monotono: `BUF_POOL` senza cap né bucketing su `bu` variabile
|
||||
|
||||
In `crates/vetta-infer-hip/src/lib.rs:199, 266, 334`:
|
||||
```rust
|
||||
static BUF_POOL: RefCell<HashMap<usize, Vec<*mut c_void>>> = ...
|
||||
```
|
||||
- Il pool è indicizzato per **taglia esatta in byte** (`self.bytes`).
|
||||
- Al `Drop` di ogni `DeviceBuf` con `pooled == true`, il puntatore viene spinto in `BUF_POOL[self.bytes]` e **`hipFree` non viene MAI chiamato** fino alla chiusura del processo.
|
||||
- L'autore aveva già individuato questo meccanismo per il KV cache (`layer.rs:236-238`), per `flash_scores_scratch` (`vetta-infer-hip/src/lib.rs:407-412`, bucket power-of-two) e per `flash_swa_gqa_prefill_f16` (`lib.rs:458`, `alloc_unpooled`).
|
||||
- **Tuttavia, l'intero percorso di batched prefill alloca decine di buffer proporzionali a `bu` con `DeviceBuf::alloc(...)` (`pooled = true`)!**
|
||||
|
||||
Ogni turno di chat ha un tail chunk diverso (`bu = suffix.len() % 256`, es. `86`, `178`, `94`, `211`, `133`...). Per ciascun `bu` mai visto prima vengono creati e **trattenuti per sempre** in `BUF_POOL`:
|
||||
|
||||
| File / Riga | Buffer allocati con `DeviceBuf::alloc` (proporzionali a `bu`) | Peso indicativo a `bu=180` |
|
||||
|---|---|---|
|
||||
| `layer.rs:497-591` (`layer_forward_swa_batched`) | `rel_bias` (`bu*24*1024*4`), `q`, `gatea`, `aout`, `aout_bf`, `k_cv`, `v_cv`, `k_raw`, `v_raw`, `r_raw`, `oproj`, `asc`, `base`, `in1`, `in2`, `msg0..3`, `in0/1/2_bf`, `mix`, `mlpin`, `rlog`, `ids`, `weights`, `msc` | ~45 MiB |
|
||||
| `layer.rs:1225+` (`layer_forward_full_batched`) | stessi tensori Q/K/V/O/mix/mlpin/router per i layer full-attention | (condivide taglie) |
|
||||
| `layer.rs:773-794` (`moe_batched`) | `gu` (`bu*8*2304*4`), `y_part` (`bu*8*2304*4`), `act16` (`bu*8*1152*2`), `mlpin16`, `moeout`, `dbtk`, `ds2b` | ~32 MiB |
|
||||
| `layer.rs:1375-1381` (`apply_controller_batched`) | `packed` (`bu*2*2304*2`), `gate`, `gate_bf`, `gain`, `forget` | ~7 MiB |
|
||||
| `layer.rs:968-1015` + `1403` (`forward_batch` & `BatchBlocks::new`) | `BatchBlocks.arena` (`8*bu*2304*4`), `bank_buf` (`n_bank*bu*2304*4`), `msgs_buf` (`4*bu*2304*4`), `cur`, `prelude`, `bank_out`, `mix`, `dtok`, `dpos` | ~32 MiB |
|
||||
|
||||
Totale: **~100–160 MiB di VRAM permanentemente trattenuti per OGNI valore distinto di `bu` incontrato nella vita del processo**. Dopo 15–20 turni con lunghezze diverse si accumulano **2–3+ GiB di VRAM morta** dentro `BUF_POOL` che non vengono mai rilasciati — esattamente il leak lento osservato!
|
||||
|
||||
### 2.2 Causa del rimbalzo ±3.75 GB a ogni turno (+ stall sincrono di ~0.5–1.5 s)
|
||||
|
||||
In `crates/vetta-infer-gw/src/serve.rs:269` e `crates/vetta-infer-ld/src/layer.rs:230-245`:
|
||||
- `strata-ctl` imposta `max_new = 16384` (verificato dai log `journalctl`: `max_new (generation budget): 16384`).
|
||||
- Con `n_prompt ≈ 2700`, `max_seq = 2700 + 16384 + 2 = 19.086`.
|
||||
- Ogni layer alloca `k_cache` e `v_cache` per ogni pass (`48` pool totali × 2 = `96` buffer):
|
||||
$$96 \times 8 \times 19086 \times 128 \times 2\text{ B} = 3.752\text{ GB}$$
|
||||
- A **ogni singola richiesta** (anche quando la prefix cache fa hit in `restore` a `serve.rs:104`!):
|
||||
1. `new_state` fa 96 `hipMalloc` per **~3.75 GB** (`alloc_unpooled`).
|
||||
2. Per **ognuno** dei 96 buffer fa (`layer.rs:241`):
|
||||
```rust
|
||||
let b = DeviceBuf::alloc_unpooled(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b)
|
||||
```
|
||||
ovvero alloca ~39 MB in RAM di sistema, li azzera su CPU, li copia **sincronamente via PCIe (`hipMemcpy` H2D)** sulla GPU, e libera la RAM — ripetuto 96 volte = **3.75 GB di allocazione RAM + zero CPU + copia PCIe sincrona** a ogni turno!
|
||||
3. Alla fine del turno `states` esce di scope e fa 96 `hipFree` (VRAM giù di 3.75 GB).
|
||||
|
||||
### Fix consigliato per §2
|
||||
|
||||
1. **Chiudere subito il leak di `BUF_POOL` (`crates/vetta-infer-hip/src/lib.rs`):**
|
||||
- **Soluzione A (più semplice e immediata):** in `BUF_POOL`, arrotondare le allocazioni al bucket power-of-two (o multipli di 64 KiB/1 MiB per buffer grandi) **E** imporre un tetto massimo di byte trattenuti (es. `MAX_POOL_BYTES = 512 MiB`): quando il pool supera il budget, chiamare `hipFree` sulle entry LRU.
|
||||
- **Soluzione B (ancora più pulita per il prefill):** pre-allocare uno `ScratchArena` / buffer di lavoro dimensionati una sola volta per `MAX_CHUNK = 256` (o passare `bu_alloc = 256` per i buffer di `forward_batch`) e riutilizzarne i prefissi `bu <= 256` senza allocare mai taglie arbitrarie.
|
||||
2. **Eliminare il rimbalzo ±3.75 GB e la copia H2D sincrona di 3.75 GB (`serve.rs` + `layer.rs`):**
|
||||
- Tenere **un solo `states` persistente** su `InklingEngine` (riutilizzato tra una richiesta e l'altra, cresciuto solo se `max_seq > current_cap`, oppure dimensionato a `MAX_CONTEXT` / `8192` + crescita geometrica).
|
||||
- **Non azzerare mai il KV cache con `vec![0u8]` + `h2d_bytes`!** L'attenzione causale legge rigorosamente `[0..=pos]` e `kv_store` sovrascrive ogni posizione prima che venga letta; al massimo basta un `zero_async` (`hipMemsetAsync`) sui soli piccoli ring `hist_k/v/a/m` (pochi KB)!
|
||||
|
||||
---
|
||||
|
||||
## 3. Perché il prefill del Turno 1 è ancora ~41–55 s (vs ~4.5–5 s in `strata`)
|
||||
|
||||
Gli ultimi 4 commit hanno ridotto 2048 token da ~60 s a `40.9 s` (`~50 pp/s`), ma su un prompt reale di ~2650 token + 3.75 GB di zero-copy KV si resta comunque intorno ai **53–58 secondi** (~9× più lento di `strata-inkling` a `458 pp/s`).
|
||||
|
||||
### 3.1 Bonus scoperto: 72 stalli sincroni PCIe per chunk (e per token in decode!) in `load_msg_queries`
|
||||
|
||||
In `crates/vetta-infer-ld/src/layer.rs:662-674`, chiamata **24 volte per ogni chunk di prefill** (`layer.rs:999`) e **24 volte per ogni token di decode** (`layer.rs:886`):
|
||||
```rust
|
||||
fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
|
||||
let q_cp = cache.raw("model.llm.middle_cycle_cross_pass_queries")?;
|
||||
let kv_cp = cache.raw("model.llm.middle_cycle_cross_pass_kv_queries")?;
|
||||
let mut qh = vec![0f32; 24 * hidden]; q_cp.d2h(&mut qh)?;
|
||||
let mut kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?;
|
||||
...
|
||||
let buf = DeviceBuf::alloc(4 * hidden * 4)?; buf.h2d(&mq)?; Ok(buf)
|
||||
}
|
||||
```
|
||||
Questi due tensori sono **pesi statici del modello**, ma ad ogni singolo core layer di pass 1 e 2 vengono scaricati interamente su CPU (`2× hipMemcpy D2H` sincroni → drena la pipeline GPU!) e ri-caricati su GPU (`1× hipMemcpy H2D` sincrono)!
|
||||
- **In prefill:** `24 × 3 = 72` sincronizzazioni GPU-CPU per chunk (720 stalli su 10 chunk!).
|
||||
- **In decode M=1:** oltre a quei 72 stalli, in `forward_inkling_with_state` (`layer.rs:863-891`) anche il bank rollback e la raccolta di `bank` fanno `d2h`/`h2d` sincroni a ogni layer/pass (mentre `forward_batch` usa già copie device-side `copy_f32_sub`).
|
||||
- **Fix banale:** pre-costruire i 12 `DeviceBuf` `[4, hidden]` una sola volta in `WeightCache` all'avvio, e portare `BatchBlocks` (o `copy_f32` device-side) anche nel decode M=1.
|
||||
|
||||
### 3.2 I 4 colli di bottiglia GPU che spiegano il gap ~9× (`40.9 s` → target `~5–8 s`)
|
||||
|
||||
> **Nota sul test di parità:** in `088ac1f` stai mantenendo `forward_batch_parity` a **`max_abs = 0.0` (bit-exact contro `M=1`)**. Quel vincolo ti costringe a usare le stesse riduzioni `fdot2` / FMA scalari del decode, inchiodandoti al tetto delle ALU scalari. I kernel **WMMA** (FP16/BF16 o INT8) sommano su alberi 16×16×16 diversi e danno fisiologicamente `max_abs ~ 1e-3 / 1e-2` rispetto a `M=1`, esattamente come accetta `strata-safetensors`. Per passare a WMMA va allentata la soglia di parity da `0.0` a tolleranza numerica reale (es. cos_sim / top-k / logit tol).
|
||||
|
||||
Riferimenti esatti in `strata-safetensors/engine/src/inkling2/hip/`:
|
||||
|
||||
1. **MoE prefill (`k_nvfp4_grouped_gemv_f16` `vetta_kernels.hip:2161` & `k_mxfp8_grouped_gemv_f16` `L1365`) — ancora ~1.89 s/chunk (~45% del tempo totale):**
|
||||
- Con `B = 256` e `top_k = 8`, ogni expert riceve in media `16` token.
|
||||
- Il kernel attuale usa `fdot2` in stile GEMV (1 wave per riga, gather sparsi `X[bucket_tok[...]]` dentro il loop interno su `K`) e lancia W13, SiTU e W2 in 3 kernel separati.
|
||||
- In `strata-safetensors/engine/src/inkling2/hip/ink_hip_codecs.hip.h`:
|
||||
- **`k_moe_grouped_w13_situ_wmma` (`L4927`, `_128` `L6897`) / `k_moe_grouped_w2_wmma` (`L5141`, `_128` `L7108`)**: gather contiguo in LDS + **FP16 WMMA `16×16×16`**, con **W1+W3+SiTU fusi** in un unico kernel.
|
||||
- **`k_moe_grouped_w13_situ_wmma_sf4_i8` (`L5716`, `_128` `L6532`) / `k_moe_grouped_w2_wmma_sf4_i8` (`L5897`, `_128` `L6720`)**: usa l'**INT8 WMMA nativo di RDNA 4 a doppia velocità (`wmma_i32_16x16x16_iu8`)** sui gruppi SF4 (NVFP4)!
|
||||
2. **Proiezioni dense BF16 (`k_gemm_bf16` `vetta_kernels.hip:208`) — secondo hotspot (~35% del tempo):**
|
||||
- Il commit `45d039d` ha aggiunto il tiling LDS `16×16`, ma il calcolo resta **FMA scalare FP32** (`acc += bf16_to_f32(As) * bf16_to_f32(Bs)`), ~8× sotto il throughput WMMA su RDNA 4.
|
||||
- Riferimenti in `strata-safetensors/engine/src/inkling2/hip/ink_hip_codecs.hip.h`: **`k_bf16_wmma_bf16_64x128` (`L2676`)** e **`k_bf16_wmma_bf16_128x128_swiz` (`L2547`)** (oppure `hipBLASLt` in `ink_hip_blaslt.hpp`).
|
||||
- Inoltre in `layer_forward_swa_batched` (`layer.rs:534-549`) e `full_batched` vengono fatti **6 lanci separati** (`wq`, `wk`, `wv`, `wr`, `wg`, `ws`) leggendo 6 volte `in0_bf` invece di una GEMM fusa.
|
||||
3. **Loop controllers (`apply_controller_batched`, `layer.rs:1373-1386`):**
|
||||
- Oggi lancia 5 kernel per canale × 4 canali × 24 visit (`ctrl_pack_batched` + 3 `gemm_bf16` scalari su `gate_rank=64` + `ctrl_apply`).
|
||||
- Riferimento in `ink_hip_ops.hip.h`: **`k1_loop_ctrl_down_wmma_fused` (`L802`)** e **`k1_loop_ctrl_up_wmma_fused` (`L910`)**.
|
||||
4. **Attention prefill (`k_flash_swa_gqa_prefill_f16` `vetta_kernels.hip:531` + `lib.rs:458`):**
|
||||
- Esegue ancora prodotto scalare `for d = 0..128` + scrittura/lettura di `scores_scratch` in global VRAM (allocato e liberato `unpooled` con `hipMalloc`/`hipFree` **48 volte per ogni chunk**, cioè 480 `hipMalloc`+`hipFree` per un prompt da 2560 token!).
|
||||
- Riferimento in `ink_hip_ops.hip.h`: **`k3_flash_swa_gqa_prefill_wmma` (`L2102`)** (FlashAttention-2 online-softmax in LDS con WMMA, zero scratch in global VRAM).
|
||||
|
||||
### 3.3 Bug minore di sicurezza/robustezza notato durante l'audit
|
||||
|
||||
In `kernels/hip/vetta_kernels.hip:2116-2126`:
|
||||
```cpp
|
||||
__global__ void __launch_bounds__(256) k_moe_scatter_buckets(...) {
|
||||
const int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i >= total) return;
|
||||
const int e = topk_ids[i];
|
||||
const int pos = atomicAdd(&exp_cur[e], 1); // <-- manca il guard `if (e < 0 || e >= 128) return;`!
|
||||
```
|
||||
In `k_moe_count_buckets` il guard `if (e >= 0 && e < 128)` è presente, ma in `k_moe_scatter_buckets` manca: in caso di NaN/corruzione del router scriverebbe out-of-bounds su `exp_cur[e]`. Conviene aggiungerlo per simmetria.
|
||||
|
||||
---
|
||||
|
||||
## Piano d'azione suggerito (ordinato per ROI)
|
||||
|
||||
### Fase P0 — Risolve subito Turno 3, Memory Leak, rimbalzo ±3.75 GB e stalli PCIe (basso rischio, zero nuovi kernel)
|
||||
1. **`serve.rs` (`PrefixCache`):**
|
||||
- Aggiornare `ck.lru` in `restore(&mut self, ...)`.
|
||||
- Sostituire `pos % 512 == 0` con soglia `next_grid` monotona (spezzando il chunk sul confine 512).
|
||||
- Alzare `PREFIX_CACHE_CAP` (es. `12`) e impedire a `full-sequence` / `prompt-boundary` di evittare i grid checkpoint (o tenere 1 slot separato per l'ultimo turno).
|
||||
2. **`vetta-infer-hip/src/lib.rs` (`BUF_POOL`):**
|
||||
- Introdurre bucketing power-of-two + cap globale (es. `512 MiB` con `hipFree` LRU), oppure allocare i temporanei del prefill a taglia fissa `chunk = 256` (niente più leak per ogni `bu` distinto).
|
||||
3. **`serve.rs` + `layer.rs` (`new_state` & `load_msg_queries`):**
|
||||
- Riusare un singolo `states` persistente tra le richieste (eliminando il ±3.75 GB sawtooth) e rimuovere `vec![0u8; kv_n*2]` + `h2d_bytes` sincrono sul KV cache (`layer.rs:241`).
|
||||
- Cachare `load_msg_queries` in `WeightCache` (elimina 72 stalli sincroni PCIe per chunk e per decode token).
|
||||
- (Opzionale) Portare il bank rollback device-side anche in `forward_inkling_with_state` M=1 (boost diretto ai tok/s di decode!).
|
||||
|
||||
### Fase P1 — Abbattere il Turno 1 da ~41 s a <8 s (stesso ordine di grandezza di `strata`)
|
||||
1. **`k_gemm_bf16` → WMMA BF16** (`k_bf16_wmma_bf16_64x128` / `128x128_swiz` in `ink_hip_codecs.hip.h`, o `hipBLASLt`) + fusione `wq/wk/wv/wr/wg/ws` sui 48 visit.
|
||||
2. **MoE prefill (`k_nvfp4_grouped_gemv_f16` / `k_mxfp8_grouped_gemv_f16`) → WMMA fuso W1+W3+SiTU** (`k_moe_grouped_w13_situ_wmma_sf4_i8` / `k_moe_grouped_w13_situ_wmma` / `k_moe_grouped_w2_wmma*` in `ink_hip_codecs.hip.h`, accettando tolleranza numerica reale al posto del bit-exact `max_abs=0.0`).
|
||||
3. **Loop controllers → WMMA fuso** (`k1_loop_ctrl_down_wmma_fused` / `k1_loop_ctrl_up_wmma_fused` in `ink_hip_ops.hip.h`).
|
||||
4. **`k_flash_swa_gqa_prefill_f16` → FlashAttention-2 WMMA in LDS** (`k3_flash_swa_gqa_prefill_wmma` in `ink_hip_ops.hip.h`, elimina anche i 48 `hipMalloc`/`hipFree` per chunk di `scores_scratch`).
|
||||
|
||||
---
|
||||
|
||||
### Verifica rapida consigliata dopo P0 (senza toccare il benchmark principale)
|
||||
1. Avviare con `VETTA_DBG_PREFIX=1` e fare 4 turni di chat consecutivi: verificare `restored=2560` (o superiore) sia al Turno 2 **sia al Turno 3 e 4**, senza mai ricadere a `1024` o `0`.
|
||||
2. Monitorare `rocm-smi` / `/sys/class/drm/card*/device/mem_info_vram_used` prima, durante e dopo 5 turni con prompt di lunghezze diverse: la VRAM deve restare piatta (zero sawtooth ±3.75 GB, zero crescita monotona tra turno 2 e turno 5).
|
||||
@@ -0,0 +1,86 @@
|
||||
# Diagnosi Prefill (~70 s vs ~5 s) e Prefix Cache (`restored=0`) — Nota di Allineamento
|
||||
|
||||
- **Data:** 2026-12-02
|
||||
- **Stato ispezionato:** `vetta-infer` `main` @ `01d8a48` (+ diff locale `VETTA_DBG_PREFIX` in `serve.rs`), `inkling-server.service` live su Sogliola (`gfx1150`, RDNA 3.5).
|
||||
- **Modalità:** Analisi in sola lettura (nessun sorgente toccato).
|
||||
- **Premessa:** La base costruita su `vetta-infer` è eccellente — parità **BIT-EXACT** end-to-end su `forward_batch`, 6 file di prove Lean 4 (`0 sorryAx`), MoE grouped CSR su GPU, fix VRAM `01d8a48`. Il divario misurato rispetto al riferimento C++/HIP `strata-inkling` (`~70 s` vs `~5 s` sul prefill di ~2646 token, e `restored=0` al Turno 2) **non è dovuto all'architettura Rust/microkernel**, ma a **5 punti molto precisi** rimasti alla fase *correctness-first*.
|
||||
|
||||
---
|
||||
|
||||
## 1. Perché la Prefix Cache non scatta tra Turno 1 e Turno 2 (`restored=0`)
|
||||
|
||||
Dai log live di `journalctl --user -u inkling-server.service` (01:14–01:18):
|
||||
|
||||
```text
|
||||
01:14:41 [prefix] prompt_len=2646 restored=0
|
||||
01:15:51 [prefix] prompt-boundary save seq=2646 (~70 s prefill)
|
||||
01:16:02 [prefix] full-sequence save seq=2698
|
||||
01:16:36 [prefix] prompt_len=2738 restored=0
|
||||
01:16:36 [prefix] ck[0] len=2646 common_prefix=2644
|
||||
01:16:36 [prefix] ck[1] len=2698 common_prefix=2644
|
||||
01:17:49 [prefix] prompt-boundary save seq=2738 (~73 s prefill da zero!)
|
||||
```
|
||||
|
||||
### Causa esatta
|
||||
- Al Turno 2 i primi **`2644` token su `2646` (`99.92%`) sono identici**, ma il prompt diverge sugli **ultimi 2 token** (`2644..2646`, il tag di apertura/chiusura turno che `strata-ctl` serializza diversamente quando il Turno 1 diventa storico).
|
||||
- In `crates/vetta-infer-gw/src/serve.rs:379-384` viene salvato un checkpoint **solo** a fine prompt (`seq=2646`) e a fine risposta (`seq=2698`), e `best_match()` richiede match esatto sull'intero `ck.tokens`. Per soli **2 token di coda**, scarta tutto e riparte da `0`.
|
||||
|
||||
### Fix consigliato (impatto immediato sul multi-turno)
|
||||
1. **Salvataggio su griglia multi-livello durante il loop di prefill** (come `--auto-ckpt` in `strata` / `proofs/auto_ckpt_pool.lean`): salvare checkpoint intermedi ogni `512` token (o su ancore pinnate `{512, 1024}` + griglia `2048, 2560, ...` usando `next_ckpt_boundary`), **oppure** al confine di ciascun chunk `256` quando si supera la soglia `512`.
|
||||
2. Su quel Turno 2 (`common_prefix=2644`), un checkpoint intermedio a `2560` (o `2048`) fa scattare subito `RESUME 2560` riducendo il prefill del Turno 2 da **2738 token** a **178 token** (**`-93.5%`**!).
|
||||
3. *(Bonus per la memoria VRAM dei checkpoint):* come in `strata-inkling`, sui 40 pool SWA serve salvare solo gli ultimi `min(seq_len, 1024)` token della finestra SWA, non l'intero `0..seq_len`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Perché il prefill a contesto vuoto impiega ~70 s (`38 ppts`) vs ~5.8 s (`458 ppts`) di `strata`
|
||||
|
||||
In ordine di peso stimato sui ~70 s di prefill (`B=256`, 11 chunk, 48 visite/chunk):
|
||||
|
||||
### P0 — `k_gemm_bf16` è scalare `1 thread = 1 elemento` (ZERO tiling / LDS / WMMA)
|
||||
- **Dove:** `kernels/hip/vetta_kernels.hip:192-214`, usato da tutte le proiezioni trunk (`wq, wk, wv, wr, wg, ws, wo`, i 4 controller `down/gain/forget`, `k_proj/v_proj` e `unembed_logits`).
|
||||
- **Impatto:** ogni thread fa `for (int kk = 0; kk < K; ++kk)` leggendo `X` e `W` senza shared memory né WMMA → una frazione di TFLOP/s contro i **22.14 TFLOP/s FP16/BF16 WMMA** (o **~44 TFLOP/s INT8 WMMA** con `--trunk-q8` / `Q8_G64`) su `gfx1150`.
|
||||
- **Riferimento in `strata-safetensors`:**
|
||||
- `hipBLASLt` BF16 (o `rocBLAS` / kernel `16×16×16` WMMA LDS-tiled) per `M > 24`, e `Q8_G64` (`k_q8_g64_gemm_small<16>` per `M <= 24`, `k_q8_g64_gemv` Wave32 per `M = 1`) — in `strata-safetensors/engine/src/inkling2/hip/ink_hip_ops.hip.h`.
|
||||
- Inoltre `wq/wk/wv/wr/wg` condividono lo stesso input `in0_bf` nei 40 layer SWA: fonderli in un solo `qkvrg` GEMM (come `trunk_qkvrg_q8_` in `strata`) elimina 4 lanci + 4 riletture di `X` per visita.
|
||||
|
||||
### P1 — `25.2 MB` di `vec![0f32]` + `hipMemcpy` SINCRONO dentro OGNI visita solo per azzerare `rel_bias` (+ altri `h2d` sincroni in `moe_batched`)
|
||||
- **Dove:**
|
||||
- `crates/vetta-infer-ld/src/layer.rs:1281-1282` (e ramo SWA batched):
|
||||
```rust
|
||||
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?;
|
||||
rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?;
|
||||
```
|
||||
Con `bu=256, n_head=24, rel_extent=1024`: **`25.17 MB` allocati/azzerati su CPU e trasferiti con `hipMemcpy` bloccante × 48 visite × 11 chunk ≈ `13.3 GB` di copie sincrone** per un solo prompt!
|
||||
- `crates/vetta-infer-ld/src/layer.rs:776` (`dcnt.h2d_bytes(&vec![0u8; 129 * 4])`) e `layer.rs:790-792` (`didx.h2d_bytes(&idx_bytes)` per l'identità `0..total`): altri **96 `hipMemcpy` sincroni per chunk** che drenano la coda GPU dentro ogni layer MoE!
|
||||
- **Fix (pochi minuti, guadagno immediato):**
|
||||
1. In `k_relpos_bias_batched` (`vetta_kernels.hip:1726-1730`), scrivere `0.0f` direttamente per `dist >= lim` (oppure `hipMemsetAsync`) → **0 byte di `h2d`**.
|
||||
2. Esporre `vetta_buf_zero_async` (`hipMemsetAsync`) per `dcnt`, e permettere `bucket_tok == nullptr` nei kernel `grouped_gemv` (usando `tok = beg + t0 + m` per `w2`) → **0 sync host dentro `moe_batched`**.
|
||||
|
||||
### P1 — `k_flash_swa_gqa_prefill_f16` è scalare con `scores_scratch` in VRAM globale
|
||||
- **Dove:** `kernels/hip/vetta_kernels.hip:500-578`.
|
||||
- **Impatto:** lancia `grid(24, 256)` con loop scalare `for d=0..128` e materializza `scores_scratch` in VRAM (`256 * 24 * 2646 * 4 B ≈ 65 MB` di scritture+letture per visita full-attn!).
|
||||
- **Riferimento in `strata-safetensors`:** `k3_flash_swa_gqa_prefill_wmma` (`64×64` FP16 WMMA online-softmax interamente in LDS, `0 B` di `scores_scratch` in VRAM, misurato **`8.5×` più veloce** già a `B=63` e `>12×` a `B=256`).
|
||||
|
||||
### P2 — Layer 20–23 (`k_mxfp8_grouped_gemv_f16`) scalare senza `fdot2` + grid pieno su 128 expert
|
||||
- **Dove:** `kernels/hip/vetta_kernels.hip:1303-1356`.
|
||||
- **Impatto:** usa `for j=0..32` scalare con riduzione in shared memory (`256` thread per 1 riga!) invece di Wave32 `fdot2` + `wave32_sum` come nel path NVFP4 (`k_nvfp4_grouped_gemv_f16` che invece è già scritto benissimo!).
|
||||
|
||||
---
|
||||
|
||||
## 3. Nota rapida sul Decode `M=1` (~4–6 tok/s oggi vs ~17–18 tok/s in `strata`)
|
||||
Anche il decode (senza drafter) può salire ~3–4× con 3 interventi mirati sugli stessi punti:
|
||||
1. **Sostituire `k_gemm_bf16` con Wave32 GEMV (`fdot2` / `Q8_G64`)** su trunk e soprattutto su `unembed_logits` (`layer.rs:622`: `N=200058, K=2304` con 1 thread/elemento scalare pesa decine di ms a ogni token!).
|
||||
2. **Eliminare i round-trip `d2h`/`h2d` sincroni dal decode `M=1`:** in `forward_inkling_with_state` (`layer.rs:864-895`), `layer_forward_full` (`layer.rs:1109-1120`), `final_logits` (`layer.rs:634-635`) e `LoopMsgs::channel` (`layer.rs:1367-1370`), il path `M=1` fa ancora `d2h`+`h2d` sincroni su `blocks` e `msgs` — quando in `forward_batch` avete **già** `BatchBlocks` + `copy_f32` + `gather_channel` 100% device-side! Riusarli con `B=1` azzera i sync nel decode.
|
||||
3. **Cache NVMe `VTC1` (`O_RDONLY`) + arena scratch riusabile:** riusare i `DeviceBuf` scratch pre-allocati per chunk/token invece di chiamare `DeviceBuf::alloc` ~40 volte per layer (e poi catturare il decode `B=1` in HIP Graph).
|
||||
|
||||
---
|
||||
|
||||
## 4. Ordine di attacco suggerito (massimo ritorno per minimo sforzo)
|
||||
|
||||
| Passo | Intervento | Sforzo | Effetto atteso |
|
||||
| --- | --- | --- | --- |
|
||||
| **1** | Griglia checkpoint `512/1024/2048` (o fine chunk 256) in `serve.rs` | ~15 righe | Turno 2+: `restored=2560`, prefill multi-turno **`-93%`** subito |
|
||||
| **2** | Via i `h2d` sincroni (`rel_bias` in-kernel, `hipMemsetAsync`, `bucket_tok=nullptr` su `w2`, `BatchBlocks` su `M=1`) | ~1 ora | Elimina `~13.3 GB` di `h2d` bloccanti/prompt + sblocca la pipeline GPU |
|
||||
| **3** | Sostituire `k_gemm_bf16` con WMMA / `hipBLASLt` (prefill) + Wave32 GEMV / `Q8_G64` (decode + `unembed`) | ~mezza giornata | Taglia il 60–70% del prefill e porta il decode verso `~14–18 tok/s` |
|
||||
| **4** | Portare `k3_flash_swa_gqa_prefill_wmma` (`64×64` FP16 WMMA LDS) + Wave32 `fdot2` su `mxfp8` | ~mezza giornata | Prefill cold da `~70 s` → **`~5–6 s` (`~400–450+ ppts`)** |
|
||||
| **5** | Arena scratch riusabile + HIP Graph sul decode `B=1` | ~1 giorno | Abbattimento overhead CPU launch (`54%` → `< 5%`) |
|
||||
@@ -0,0 +1,115 @@
|
||||
# DSpark drafter — Step 1 completato (2026-12-02)
|
||||
|
||||
Stato: **Step 1 del drafter speculativo MTP è completo, verificato e cablato in
|
||||
serve (opt-in `VETTA_SPEC=1`)**. HEAD `ba51499` (pushed origin/main).
|
||||
|
||||
Riferimento piano: `review/2026-12-02-piano-vram-piatta-e-guida-drafter.md`.
|
||||
Ground truth: `strata-safetensors/engine/src/inkling2/` (`ink_dspark.cuh`,
|
||||
`ink_cpu_backend.cpp`, `ink_serve.h`).
|
||||
|
||||
## Catena verificata (brick per brick)
|
||||
|
||||
| Brick | Contenuto | Commit |
|
||||
|---|---|---|
|
||||
| b1 | Lean `spec_lossless` + `kept_rejected_disjoint` (0 sorryAx) | `afce5cb` |
|
||||
| b2 | loader `mtp.safetensors` + `layout_check` (54 tensori BF16) | `3a9533a` |
|
||||
| b3a | kernel `mix_taps` + `rmsnorm_rope` (RoPE f64 interno) | `7e74db7` |
|
||||
| b3b | `dspark_context` (pesi proj BF16, parity 3e-6) | `0cbec2d` |
|
||||
| b3c | tap capture nel trunk `[5,23,41,48]` (logits bit-identici) | `b6ed89b` |
|
||||
| b4a | `block_attn` + `swiglu` | `1b10258` |
|
||||
| b4b | `markov_gru` + `corr_combine` | `142580e` |
|
||||
| b4c | `split3` + `dspark_draft` block-8 (ids exact vs oracle) | `f9cde49` |
|
||||
| b5a | `spec_accept_greedy` (indexing fedele a ink_serve.h) | `3812845` |
|
||||
| b5b-1 | kernel `hist_snaps` (snapshot shortconv per-prefisso) | `ca12801` |
|
||||
| b5b-2/3 | `LayerState` snaps + `rollback_spec` + `DsparkContext` + `spec_round` | `7b617bc` |
|
||||
| b6 | gate lossless: 200 token EXACT vs plain batched greedy | `7b617bc` |
|
||||
| flash fix | dispatch per-M (WMMA prefill / scalare decode+verify) | `11404c4` |
|
||||
| b5b-4 | wiring serve opt-in + EMA + parity reference exact | `df537bf` |
|
||||
| tuning | n_draft optimum misurato = 2 + override `VETTA_SPEC_ND` | `ba51499` |
|
||||
|
||||
## Bug di correttezza trovato e risolto: flash WMMA batch-dipendente
|
||||
|
||||
La divergenza iniziale del gate (token 46) **non** era nel runner: il flash FA2
|
||||
WMMA (`k_flash_swa_gqa_prefill_wmma`) su un query-tile a posizioni miste fa
|
||||
dipendere l'output di una query dai vicini di batch di ~1 ulp. Causa confermata
|
||||
sperimentalmente: una chiave KV extra reale (oltre `pos` della query ma entro
|
||||
`q_max_pos` del tile), sebbene mascherata (P=0), filtra ~1 ulp nella PV WMMA.
|
||||
Azzerando K13/V13 nel test, M=2 == M=1 exact.
|
||||
|
||||
Quel drift da 1 ulp, roundato bf16 nell'hist shortconv, accumula finché un
|
||||
near-tie greedy si ribalta. Il gate greedy-vs-reference del **prefill** tollera
|
||||
~1 ulp (infatti passava con WMMA); la **speculazione** richiede exact tra decode
|
||||
(M=1) e verify (M=nd+1).
|
||||
|
||||
**Fix (preserva la perf misurata)**: dispatch del flash per M.
|
||||
- `M >= 16` (chunk prefill): WMMA flash → win misurato preservato.
|
||||
- `M < 16` (decode B=1 + verify spec M<=8): flash scalare f16 per-query
|
||||
deterministico → verify e decode concordano bit-a-bit.
|
||||
- `VETTA_FLASH_WMMA=1` forza WMMA (test), `VETTA_NO_FLASH_WMMA=1` forza scalare.
|
||||
|
||||
Misura prefill 1024 tok chunk 256: **WMMA 5.786 ms/tok vs scalare 10.047 ms/tok
|
||||
(1.74x)** → nessuna regressione prefill. (Il precedente default scalare globale
|
||||
`6e854a9` regrediva ~2x; superato da `11404c4`.)
|
||||
|
||||
Nota: il kernel WMMA resta batch-dipendente per tile misti (opt-in/test); il
|
||||
guard `alpha=1.0` quando `nm==row_max` è un miglioramento minore ma non elimina
|
||||
il leak PV. Fix radicale del kernel WMMA = lavoro futuro se si vuole WMMA anche
|
||||
sul decode.
|
||||
|
||||
## Rollback speculativo (provato + verificato)
|
||||
|
||||
- **KV ring**: troncamento di lunghezza, nessun restore dati
|
||||
(`kept_rejected_disjoint`: slot kept vs rejected disgiunti con R >= window+chunk).
|
||||
- **ShortConv hist**: shift-register `[3]` per pass → snapshot per-prefisso
|
||||
(`k_shortconv4_hist_snaps`, `snaps[t] == update_hist` sul prefisso t, exact) e
|
||||
`rollback_spec` ripristina `hist <- snaps[accepted]`.
|
||||
- Diagnostic lockstep: 200 round hist+KV **exact** vs plain batched.
|
||||
|
||||
## Misure reali (gfx1150, capital prompt "The capital of France is", GEN 96)
|
||||
|
||||
Sweep n_draft (decode tok/s):
|
||||
|
||||
| n_draft | 1 | **2** | 3 | 4 | 5 | 7 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| decode tok/s | 5.25 | **6.09** | 5.78 | 5.54 | 4.58 | 5.15 |
|
||||
| acceptance | 57% | 50% | 35% | 28% | 26% | 19% |
|
||||
|
||||
**Optimum = n_draft 2.** Ipotesi "fissare a 5" smentita dalla misura: a
|
||||
~30-50% acceptance un verify batch più grande spreca compute su draft rifiutati.
|
||||
EMA ritarata: parte da 2, escala solo ad acceptance molto alta (>=0.75→4,
|
||||
>=0.9→7). Run adattivo: nd=2, decode **6.10 tok/s**, ON **4.59** vs OFF **3.97**
|
||||
tok/s totale richiesta → **~1.16x**. Gain modesto ma reale, misurato, nessun
|
||||
overclaim.
|
||||
|
||||
Parity: `serve_gen_spec_multi_token_parity` → il path spec emette i **16 token
|
||||
reference EXACT** (batched decode == M=1 == reference). `spec_lossless_gate` →
|
||||
**200 token EXACT** vs plain batched greedy su trunk+mtp reali.
|
||||
|
||||
## Stato serve
|
||||
|
||||
- Spec **opt-in** `VETTA_SPEC=1`: carica i pesi drafter resident iff
|
||||
`mtp.safetensors` passa `layout_check`; prefill cattura taps + commit ctx rings;
|
||||
decode `spec_round` con EMA. Solo greedy puro senza penalties. EOS/stop/length
|
||||
gestiti per token emesso. Prefix save invariato.
|
||||
- Decode default M=1 **invariato** (spec off).
|
||||
- Server **fermo** (per i test GPU). Riavvio con `VETTA_SPEC=1` per chattare col
|
||||
drafter attivo.
|
||||
|
||||
## Verifica totale
|
||||
|
||||
CPU `-D warnings` pulito · Lean 0 sorryAx · hip **45/45** · ld GPU **65/65** ·
|
||||
gw GPU **22/22**.
|
||||
|
||||
## Prossimi passi (domani)
|
||||
|
||||
1. **Bisect acceptance drafter** (raccomandato): 50% sul primo draft è sotto le
|
||||
attese per un head MTP addestrato → possibile disallineamento ctx ring o
|
||||
anchor. Confrontare i draft vetta vs reference (`dspark_draft` call site) su
|
||||
testo reale; se acceptance sale a ~70-80%, nd=3-4 diventerebbero vantaggiosi
|
||||
e lo speedup crescerebbe davvero.
|
||||
2. **Step 2 tree drafter** (opzionale): albero invece del block-8 lineare.
|
||||
3. **DMA layer streaming** (la "parte difficile" del piano): io_uring + slab ring
|
||||
DMA per flat-VRAM a contesti lunghi / modelli >80 GiB. Cuore architetturale
|
||||
microkernel.
|
||||
|
||||
Leva vera per lo speedup spec = **acceptance**, non n_draft più alto.
|
||||
@@ -0,0 +1,202 @@
|
||||
# Fix e ottimizzazioni DSpark drafter (`vetta-infer`)
|
||||
|
||||
**Data:** 2026-12-02
|
||||
**Hardware di misura:** AMD Radeon 890M (`gfx1150`, RDNA 3.5 UMA, 48 GiB VRAM)
|
||||
**Modello:** `/mnt/models/Inkling/safetensors/` (trunk 19 GB NVFP4/BF16 + `mtp.safetensors` 607 MB BF16)
|
||||
**Baseline di partenza:** commit `91c1baa` / `ba51499` (Step 1 completato)
|
||||
|
||||
---
|
||||
|
||||
## 1. Sintesi del risultato
|
||||
|
||||
La matematica del drafter DSpark era corretta (`dspark_draft_parity` 7/7 e `spec_lossless_gate` 200/200), ma il throughput crollava con `n_draft` crescente (`4.58 tok/s` a `nd=5`, `6.11 tok/s` a `nd=2` sul prompt breve) invece di scalare come in `strata-inkling`.
|
||||
|
||||
Dopo gli interventi descritti sotto, su **entrambi** i workload misurati il drafter scala in modo pulito e **eguaglia/supera `strata-inkling --draft dspark`** con parità greedy **100% bit-exact**:
|
||||
|
||||
- **Coding reale in Rust (`RingBuffer<T>`, 128 token, chat template Inkling):**
|
||||
- `vetta-infer` spec OFF: **`6.83 tok/s`** (`18,742 ms`)
|
||||
- `vetta-infer` spec ON (default `VETTA_SPEC=1`, EMA adattivo, `n_draft=5`): **`13.93 tok/s`** (`9,188 ms`, **2.04× speedup**, 100% EXACT)
|
||||
- `strata-inkling --draft dspark` (stesso prompt): **`13.66 tok/s`** (`9,372 ms`, 100% EXACT)
|
||||
- **Prosa breve (`"The capital of France is"`, 96 token):**
|
||||
- Prima (`ba51499`): `OFF 4.01` | `nd=2 6.11` | `nd=5 4.58 tok/s`
|
||||
- Dopo: `OFF 4.63–4.70` | `nd=2 9.21` | `nd=5 9.09 tok/s` (**+98.5% / ~2× più veloce a `nd=5`**; EMA adattivo `8.93 tok/s` decode)
|
||||
|
||||
---
|
||||
|
||||
## 2. Cause radice trovate (7 colli di bottiglia + 2 bug di correttezza)
|
||||
|
||||
### Prestazioni (perché `nd=5` collassava a `4.58 tok/s`)
|
||||
|
||||
1. **`dspark_draft` leggeva `unembed` (922 MB BF16) `nd` volte con 4 sync CPU↔GPU per ogni step:**
|
||||
Ad ogni step `1..=nd` veniva lanciato un full GEMV `[200058 × 2304]` su `unembed` (4.6 GB di banda buttati a `nd=5`), più un loop di copie D2H/H2D sincrone per il Markov head e l'argmax su CPU.
|
||||
2. **Doppio `unembed` + 4.8 MB D2H + argmax su CPU in `spec_round`:**
|
||||
`spec_round` chiamava `forward_batch_taps` (che faceva già 1 `unembed` sull'ultima riga) e poi rifaceva un `gemm_bf16` su tutte le `B = nd + 1` righe di `taps[3]`, copiava `B × 200058 × 4 B` (`4.8 MB` a `nd=5`) su CPU e cercava l'argmax in Rust.
|
||||
3. **`gemm_bf16` usava il kernel scalare lento per `m < 16`:**
|
||||
Il dispatch WMMA si attivava solo per `m >= 16`; tutte le verify speculative (`m = 2..8`) e il decode (`m = 1`) cadevano sul kernel scalare.
|
||||
4. **MoE `expert_arena_grouped_gemv_f16` usava WMMA `16×16` anche per `b <= 12`:**
|
||||
In verify speculativo (`b = 3..8`) quasi tutti i bucket di esperti hanno 1–2 token: il tile WMMA `M=16` paddava 14–15 righe a zero sprecando compute.
|
||||
5. **48 `hipMalloc` + 48 `hipFree` sincroni per round nella SWA GQA verify (`m < 16`):**
|
||||
`flash_swa_gqa_prefill_f16` allocava e liberava `scores_scratch` a ogni layer SWA quando `m > 1`, inserendo 96 sincronizzazioni di driver per singolo round speculativo.
|
||||
6. **`k_router_gemv_batched` scalare (non vettorizzato e non M-tiled):**
|
||||
I 3 layer DSpark (`B = 8`) rileggevano i pesi BF16 8 volte invece di 1 sola volta.
|
||||
7. **Governatore EMA bloccato su `n_draft = 2`:**
|
||||
La vecchia soglia era basata sul **rapporto** `accepted / nd` (`>= 0.90 -> 7`, `>= 0.75 -> 4`, altrimenti `2`). A `nd=5` sul codice accettare 2.3 token/round significa `ratio = 0.46`, che forzava il governatore a scendere a `n_draft = 2` (tagliando del ~17% la velocità sul codice!).
|
||||
|
||||
### Bug di correttezza in produzione (chat lunga e multi-turn)
|
||||
|
||||
8. **Crash garantito LDS > 64 KiB su contesto lungo (`k_dspark_block_attn`):**
|
||||
Il vecchio kernel allocava `(c_len + B + hd) * 4` byte di shared memory. Sul layer Global `il = 1` (`c_len = anchor_pos`), sopra `~16,248` token superava i 64 KiB di LDS di RDNA 3.5 causando il fallimento del lancio HIP.
|
||||
9. **`PrefixCache` non salvava/ripristinava `DsparkContext`:**
|
||||
Al Turno 2+ di una conversazione, il `RESUME` ripristinava solo i KV del trunk lasciando i ring `k/v` e `frnn` di `DsparkContext` azzerati o di un'altra sessione, corrompendo i draft del turno successivo. Inoltre `DsparkContext` veniva riallocato a ogni richiesta invece di restare persistente su `InklingEngine`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Modifiche applicate (file per file)
|
||||
|
||||
### [`kernels/hip/vetta_kernels.hip`](../kernels/hip/vetta_kernels.hip)
|
||||
- **`k_dspark_block_attn_w32` (fast path `hd == 128` in `vetta_dspark_block_attn`):** online-softmax Wave32 interamente nei registri con **0 byte di LDS** (risolve il crash >16.2k token) e load vettorizzati `float4`/`uint2`.
|
||||
- **`k_router_gemv` e `k_router_gemv_batched`:** riscritti con Wave32 vettorizzato `uint4`/`float4` (`8` wave/blocco) e **M-tiling per 8 righe**, così `B = 8` nei layer DSpark legge i pesi una sola volta (8× meno banda).
|
||||
- **Drafter 100% su GPU (zero sync nel loop Markov):**
|
||||
- `k_dspark_base_top2_screen`: singolo passaggio su `unembed` per tutti gli `nd <= 7` step contemporaneamente, producendo i Top-512 candidati per step (`n_cand = 512`, con modalità esatta all-tokens se `V <= n_cand`).
|
||||
- `k_dspark_markov_proj_bf16`, `k_dspark_markov_corr_bf16`, `k_dspark_cand_argmax_s1`/`s2`: proiezione Markov ricorrente, correzione sui 512 candidati e argmax interamente on-device.
|
||||
- **`k_batched_argmax_f32`:** argmax batched su GPU per la fase di verify (`B * 4` byte D2H invece di `B * 800 KB`).
|
||||
- **`k_flash_swa_gqa_smallm_f16`:** kernel Wave32 deterministico per-query online-softmax (`hd == 128`) condiviso tra decode `M = 1` e verify `M < 16` con **0 allocazioni `scores_scratch`** (elimina le 48 `hipMalloc` + 48 `hipFree` per round).
|
||||
|
||||
### [`crates/vetta-infer-hip/src/lib.rs`](../crates/vetta-infer-hip/src/lib.rs)
|
||||
- Aggiunti binding FFI e wrapper Rust safe con bounds checking per `dspark_base_top2_screen`, `dspark_markov_proj_bf16`, `dspark_markov_corr_bf16`, `dspark_cand_argmax`, `batched_argmax_f32`.
|
||||
- Cablato `k_flash_swa_gqa_smallm_f16` in `flash_swa_gqa_decode_f16` e `flash_swa_gqa_prefill_f16` (`m < 16`).
|
||||
- Esteso il dispatch WMMA in `gemm_bf16` a `m >= 1 && k % 64 == 0` (prima era `m >= 16`).
|
||||
- Aggiunto test GPU di regressione `dspark_block_attn_long_context_no_lds_overflow` a `c_len = 17_000`.
|
||||
|
||||
### [`crates/vetta-infer-ld/src/packer.rs`](../crates/vetta-infer-ld/src/packer.rs) e [`crates/vetta-infer-ld/src/layer.rs`](../crates/vetta-infer-ld/src/layer.rs)
|
||||
- `expert_arena_grouped_gemv_f16` ora riceve `b: i32` e usa `nvfp4_grouped_gemv_f16` (`fdot2`, bit-exact rispetto a `M=1`) per `b <= 12` e `nvfp4_grouped_gemm_wmma` per `b > 12` (override `VETTA_FORCE_MOE_WMMA=1` mantenuto per A/B).
|
||||
- Aggiunta `forward_batch_taps_no_logits` (`skip_unembed = true`) usata da `spec_round` per eliminare il doppio `unembed`.
|
||||
|
||||
### [`crates/vetta-infer-ld/src/dspark.rs`](../crates/vetta-infer-ld/src/dspark.rs)
|
||||
- Riscritta `dspark_draft` con `dspark_base_top2_screen` + loop Markov su GPU e una sola copia D2H finale (`<= 32 byte`).
|
||||
- Riscritta `spec_round` usando `forward_batch_taps_no_logits` + singolo `gemm_bf16` batched + `batched_argmax_f32` (`B * 4` byte D2H) + commit di `dctx` solo per i token effettivamente accettati.
|
||||
- Aggiunti `DsparkSnapshot`, `DsparkContext::snapshot` e `DsparkContext::restore` (gestione corretta del wrap-around sui ring SWA dei layer 0/2, stato completo sul layer Global 1 e `frnn[seq - 1]`).
|
||||
|
||||
### [`crates/vetta-infer-gw/src/serve.rs`](../crates/vetta-infer-gw/src/serve.rs)
|
||||
- `dctx: RefCell<Option<DsparkContext>>` reso persistente su `InklingEngine` (riallocato solo se `cap > c.cap`).
|
||||
- Integrato `dspark: Option<DsparkSnapshot>` in `Checkpoint` / `PrefixCache::save` / `PrefixCache::restore`: se un checkpoint ripristinato non ha stato DSpark (es. salvato con spec OFF), `spec_enabled` scende pulitamente a `false` per quel turno evitando di eseguire il drafter su ring azzerati.
|
||||
- Aggiornato il governatore adattivo da ratio (`accepted / nd`) a **EMA dei token accettati per round** (`ema_acc`, partenza `2.0`, `n_draft = 5`, aggiornamento `0.85 * ema_acc + 0.15 * acc`, scala `7 / 5 / 4 / 3 / 2` per soglie `>= 3.5 / 2.0 / 1.1 / 0.6`).
|
||||
- Aggiunto test GPU di regressione `serve_gen_spec_prefix_cache_multi_turn_parity`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Benchmark misurati (`gfx1150`, stesso hardware e modello)
|
||||
|
||||
### A. Prompt reale di coding Rust (`RingBuffer<T>`, 69 token prompt, `GEN 128`, `temperature=0`, warm)
|
||||
|
||||
| Motore / Configurazione | Decode ms (128 tok) | Decode tok/s | Speedup vs OFF | Rounds | Accettati / Offerti | Match vs OFF |
|
||||
|---|---:|---:|---:|---:|---:|:---:|
|
||||
| `vetta-infer` OFF | `18,742.3 ms` | `6.83 tok/s` | `1.00×` | — | — | baseline |
|
||||
| `vetta-infer` `VETTA_SPEC_ND=2` | `10,730.6 ms` | `11.93 tok/s` | `1.75×` | 53 | `74 / 104` (71.2%) | **EXACT** |
|
||||
| `vetta-infer` `VETTA_SPEC_ND=3` | `9,208.9 ms` | `13.90 tok/s` | `2.04×` | 43 | `84 / 128` (65.6%) | **EXACT** |
|
||||
| `vetta-infer` `VETTA_SPEC_ND=4` | `9,164.0 ms` | `13.97 tok/s` | `2.05×` | 40 | `87 / 157` (55.4%) | **EXACT** |
|
||||
| `vetta-infer` `VETTA_SPEC_ND=5` | `9,347.0 ms` | `13.69 tok/s` | `2.00×` | 39 | `88 / 190` (46.3%) | **EXACT** |
|
||||
| `vetta-infer` `VETTA_SPEC_ND=6` | `9,382.9 ms` | `13.64 tok/s` | `2.00×` | 37 | `90 / 222` (40.5%) | **EXACT** |
|
||||
| `vetta-infer` `VETTA_SPEC_ND=7` | `9,421.8 ms` | `13.59 tok/s` | `1.99×` | 36 | `91 / 251` (36.3%) | **EXACT** |
|
||||
| **`vetta-infer` `VETTA_SPEC=1` (EMA default)** | **`9,188.0 ms`** | **`13.93 tok/s`** | **`2.04×`** | **39** | **`88 / 177` (49.7%, `n_draft=5`)** | **EXACT** |
|
||||
| `strata-inkling --draft dspark` | `9,372.2 ms` | `13.66 tok/s` | — | ~39 | `90 / 195` (46.2%) | **EXACT** |
|
||||
|
||||
*(Overhead di `dc.commit` in prefill misurato sul medesimo prompt: `509.6 ms` SPEC vs `506.0 ms` OFF wall-time = `+3.6 ms` / `+0.7%`.)*
|
||||
|
||||
### B. Prompt breve canonico (`"The capital of France is"`, 5 token prompt, `GEN 96`, `temperature=0`)
|
||||
|
||||
| Configurazione | Prima (`ba51499`) decode tok/s | Dopo decode tok/s | Delta |
|
||||
|---|---:|---:|---:|
|
||||
| `OFF` (totale `serve_gen_spec_perf`) | `4.01 tok/s` | `4.63–4.70 tok/s` | `+16%` |
|
||||
| `VETTA_SPEC_ND=2` | `6.11 tok/s` | `9.21 tok/s` | `+51%` |
|
||||
| `VETTA_SPEC_ND=3` | `5.78 tok/s` | `8.98–9.09 tok/s` | `+57%` |
|
||||
| `VETTA_SPEC_ND=4` | `5.54 tok/s` | `8.83–8.93 tok/s` | `+61%` |
|
||||
| `VETTA_SPEC_ND=5` | **`4.58 tok/s`** | **`9.02–9.09 tok/s`** | **`+98.5%`** |
|
||||
| `VETTA_SPEC_ND=7` | `5.15 tok/s` | `8.43–8.72 tok/s` | `+69%` |
|
||||
| `VETTA_SPEC=1` (EMA default) | `6.09 tok/s` | `8.93 tok/s` (`n_draft=4`, `48/155`) | `+47%` |
|
||||
|
||||
---
|
||||
|
||||
## 5. Validazione eseguita (tutto verde)
|
||||
|
||||
- **Workspace CPU con `-D warnings`:** `RUSTFLAGS="-D warnings" cargo test --workspace` → **100% PASS, 0 warning**.
|
||||
- **Prove formali Lean 4:** tutti e 7 i file in `proofs/*.lean` verificati con `lean` → **0 `sorryAx`**.
|
||||
- **Kernel HIP GPU (`vetta-infer-hip --ignored --test-threads=1`):**
|
||||
- `dspark_block_attn_parity`: `max_rel_err = 5.668e-7` (**PASS**)
|
||||
- `dspark_block_attn_long_context_no_lds_overflow` (`c_len = 17_000`): `max_rel_err = 5.091e-5` (**PASS**)
|
||||
- `router_gemv_batched_parity`: `max_rel_err = 0.000e0` (**PASS**)
|
||||
- `gemm_bf16_parity_vs_cpu`: `max_rel_err = 1.570e-6` (**PASS**)
|
||||
- **Drafter & lossless gate (`vetta-infer-ld --ignored --test-threads=1`):**
|
||||
- `dspark_draft_parity`: 7/7 EXACT (**PASS**)
|
||||
- `spec_lossless_gate`: **200 token EXACT match** (`rounds=165 offered=1127 accepted=34`) (**PASS**)
|
||||
- **Serve & PrefixCache (`vetta-infer-gw --ignored --test-threads=1`):**
|
||||
- `serve_gen_spec_multi_token_parity`: 16 token di riferimento EXACT (**PASS**)
|
||||
- `serve_gen_spec_prefix_cache_multi_turn_parity`: `off_resumed=45 on_resumed=45`, Turn 1 (16 tok) e Turn 2 (24 tok) 100% EXACT (**PASS**)
|
||||
- `serve_gen_spec_perf`: OFF `4.63 tok/s` | ON decode `8.93 tok/s` (**PASS**)
|
||||
- **Build release:** `cargo build --release --features hip` completata senza warning (`target/release/vetta-infer` aggiornato).
|
||||
|
||||
---
|
||||
|
||||
## 6. Note operative
|
||||
|
||||
- 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 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**).
|
||||
|
||||
---
|
||||
|
||||
## 8. Audit codebase: magagne residue trovate (analisi statica, pronte per domani)
|
||||
|
||||
Verificate direttamente sui file sorgenti dopo il commit `1772050`:
|
||||
|
||||
### P0 — Da sistemare subito (bug / overhead evitabili)
|
||||
|
||||
1. **`spec_update_hist` rialloca 192 buffer a ogni singolo round speculativo** ([`layer.rs:298`](../crates/vetta-infer-ld/src/layer.rs#L298)):
|
||||
`if snap.as_ref().map_or(true, |s| s.bytes != n * 4)` confronta per uguaglianza stretta, ma `DeviceBuf::alloc` arrotonda `s.bytes` a `next_power_of_two()` (es. `165,888 B -> 262,144 B`). La condizione è **sempre vera** e fa churn di `48 × 4 = 192` alloc/drop per round. Fix: `s.bytes < n * 4`.
|
||||
2. **Flag env booleani controllati con `.is_ok()` invece di parsare `"0"`/`"false"`** ([`serve.rs:271`](../crates/vetta-infer-gw/src/serve.rs#L271), `serve.rs:409`, `serve.rs:795`, `lib.rs:328`):
|
||||
Impostare `VETTA_SPEC=0` (o `VETTA_NO_PREFIX_CACHE=0`, `VETTA_LAZY_LOAD=0`, `VETTA_NO_BUF_POOL=0`) **attiva** il flag invece di spegnerlo. Serve un helper unico `env_flag("VETTA_SPEC")` che ignora `"0"`, `"false"`, `"off"`, `""`.
|
||||
|
||||
### P1 — Compatibilità `strata-ctl` / chat reale e velocità path AR
|
||||
|
||||
3. **Drafter spento appena `temperature > 0` o con penalty** ([`serve.rs:385`](../crates/vetta-infer-gw/src/serve.rs#L385)):
|
||||
`spec_enabled` richiede `is_greedy() && !has_penalties()`. Inoltre, se un turno non-greedy (o un `GEN 0` pre-warm non-greedy) salva un checkpoint con `dspark: None`, anche il turno successivo greedy che fa `RESUME` su quel checkpoint disattiva il drafter (`serve.rs:423`).
|
||||
*Per abilitare `temperature > 0` domani:* `vetta-infer-abi::sampler::verify_draft_logits` (rejection sampling esatto 0 KLD) è già in codebase; attenzione però che in `spec_round` (`dspark.rs:492`) oggi manca `softcap(lg, eng.cap)` (innocuo in greedy perché `tanh` è monotona, **obbligatorio** con `temperature > 0`!).
|
||||
4. **`ParsedGen.spec_mode` (`spec=off|auto|5`) e `ParsedGen.images` parsati ma ignorati in `serve_gen`** ([`serve.rs:352`](../crates/vetta-infer-gw/src/serve.rs#L352), [`main.rs:98`](../crates/vetta-infer-gw/src/main.rs#L98)):
|
||||
- `spec=0` / `spec=5` sul wire non hanno effetto; manca anche un flag CLI `--spec` / `--draft dspark|off` in `main.rs` (oggi `vetta-infer.json` di `strata-ctl` lancia solo `--serve <dir>` senza `VETTA_SPEC=1`).
|
||||
- `g.images` viene scartato silenziosamente invece di rispondere `ERR vision not supported`.
|
||||
5. **Path decode M=1 (`layer_forward_swa`, `layer_forward_full`, `forward_inkling_with_state`) fa ~120 `d2h`/`h2d` sincroni per token** ([`layer.rs:540-556`](../crates/vetta-infer-ld/src/layer.rs#L540-L556), `985-1015`, `1280-1360`):
|
||||
`blocks`, `mx3`, `prelude` e `bank` rimbalzano su CPU a ogni layer/pass mentre `forward_batch` usa già `BatchBlocks` interamente su GPU. Unificare il decode M=1 su `BatchBlocks` (o instradare `forward(tok)` su `forward_batch(&[tok])`) toglierebbe ~120 sync CPU↔GPU per token anche con spec OFF / `temperature > 0`.
|
||||
|
||||
### P2 — Igiene e propedeutici allo streaming DMA
|
||||
|
||||
6. **Telemetria `DONE` e `RESET` (`serve.rs:699, 855`):**
|
||||
- `DONE` non appende nella coda raw `accepted / offered` del drafter (oggi stampati solo su `stderr` con `VETTA_DBG_SPEC=1`).
|
||||
- `Msg::Reset` è no-op (non svuota `PrefixCache`; verificare se `strata-ctl` si aspetta lo svuotamento su `RESET`).
|
||||
7. **Pesi permanenti allocati dal pool** ([`layer.rs:795`](../crates/vetta-infer-ld/src/layer.rs#L795), [`layer.rs:1217`](../crates/vetta-infer-ld/src/layer.rs#L1217)):
|
||||
`load_msg_queries` e `load_sconv_transposed` usano `DeviceBuf::alloc` (pooled + arrotondato a potenza di 2) invece di `DeviceBuf::alloc_unpooled`.
|
||||
8. **Ponte mancante per lo streaming dei layer in DMA (M2):**
|
||||
- `vetta_hip_register_uma_pages` / `vetta_hip_unregister_uma_pages` sono dichiarati in `vetta_kernels.h:26-27` ma non implementati in `vetta_kernels.hip` né wrappati in `vetta-infer-hip`.
|
||||
- `UmaSlabPool` (`crates/vetta-infer-kn/src/uma.rs`) alloca ancora `Vec<u8>` non allineati a 4 KiB (`O_DIRECT`) e non registrati con `hipHostRegisterMapped`.
|
||||
- `HotColdExpertCache` (`vetta-infer-cc`) e `vetta-infer-rt::executor` non sono ancora collegati a `WeightCache` (che oggi carica tutti gli `ExpertArena` in VRAM al boot via `prewarm`).
|
||||
Reference in new issue
Block a user