Compare commits
69
Commits
cd853cda8b
..
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 | ||
|
|
c059a20aa9 | ||
|
|
b41a71f2f7 | ||
|
|
1aaf7f12c2 | ||
|
|
3dbb6bb1b4 | ||
|
|
51b230cdd2 | ||
|
|
3a2ad4da49 | ||
|
|
48de65d395 | ||
|
|
388e9108e5 | ||
|
|
708a40d91b | ||
|
|
10db2f11e4 | ||
|
|
a7a1ab11b0 | ||
|
|
ec2ad3fdc5 | ||
|
|
b6113b549a | ||
|
|
870133d6e5 | ||
|
|
e1b16b5874 | ||
|
|
bfdd665434 | ||
|
|
0914fae8c8 | ||
|
|
752edeaade | ||
|
|
4c82040610 | ||
|
|
8d886bd56f | ||
|
|
58940840d6 | ||
|
|
20e152640e | ||
|
|
442d26c90c | ||
|
|
8c8ae4485a | ||
|
|
736c541887 | ||
|
|
f12281ec61 | ||
|
|
c9713c8bc1 | ||
|
|
b1f65942c8 | ||
|
|
25200e2e79 | ||
|
|
59c41cb613 | ||
|
|
7790f48c27 | ||
|
|
b9cac6d0df |
No files matched your search
@@ -37,20 +37,29 @@ Built from the measured hardware physics and engineering lessons of our hardened
|
|||||||
|
|
||||||
- **M0 (Foundation — done):** Workspace skeleton, Lean contracts (`slab_ring_dma.lean`), checked IO, serve parsing, telemetry, HIP ABI, full CPU test suite.
|
- **M0 (Foundation — done):** Workspace skeleton, Lean contracts (`slab_ring_dma.lean`), checked IO, serve parsing, telemetry, HIP ABI, full CPU test suite.
|
||||||
- **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.
|
- **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`, in progress):** `rt` HIP RDNA 3.5 microkernels, NVFP4/MXFP8 + `Q8_G64_T16` trunk, Vision WMMA, write-once `.vbundle`, `strata-ctl` drop-in `--serve` parity & speed vs C++ baseline (`>= 18 tok/s`, `< 4 s` reload). Landed so far: serve-session FSM (`serve_session.lean`), `memory.vplan` arena safety (`arena_plan.lean` + `abi::arena`), `.vbundle` manifest/plan contract (`abi::bundle` + `ld::bundle`).
|
- **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.
|
- **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.
|
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
|
||||||
|
|
||||||
## Quick Verification
|
## Quick Verification
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Lean 4 formal proofs (0 sorryAx, 42 theorems across 4 files)
|
# Lean 4 formal proofs (0 sorryAx, 7 files)
|
||||||
lean proofs/slab_ring_dma.lean
|
lean proofs/slab_ring_dma.lean
|
||||||
lean proofs/bus_lifecycle.lean
|
lean proofs/bus_lifecycle.lean
|
||||||
lean proofs/serve_session.lean
|
lean proofs/serve_session.lean
|
||||||
lean proofs/arena_plan.lean
|
lean proofs/arena_plan.lean
|
||||||
|
lean proofs/inkling_loop.lean
|
||||||
|
lean proofs/prefix_cache.lean
|
||||||
|
lean proofs/speculative_draft.lean
|
||||||
|
|
||||||
# Pure-Rust workspace tests (no GPU required, 65 tests)
|
# Pure-Rust workspace tests (no GPU required)
|
||||||
cargo test --workspace
|
cargo test --workspace
|
||||||
```
|
```
|
||||||
@@ -125,6 +125,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn chat_turn_paris() {
|
fn chat_turn_paris() {
|
||||||
|
crate::gpu_isolated(|| {
|
||||||
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
||||||
let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap();
|
let tok = Tokenizer::from_file("/mnt/models/Inkling/safetensors/tokenizer.json").unwrap();
|
||||||
let history = [ChatMessage::new("user", "What is the capital of France? Answer in one word.")];
|
let history = [ChatMessage::new("user", "What is the capital of France? Answer in one word.")];
|
||||||
@@ -133,5 +134,6 @@ mod tests {
|
|||||||
eprintln!("[chat] reply={reply:?} streamed={streamed:?}");
|
eprintln!("[chat] reply={reply:?} streamed={streamed:?}");
|
||||||
assert_eq!(reply, streamed, "streamed text must equal the full reply");
|
assert_eq!(reply, streamed, "streamed text must equal the full reply");
|
||||||
assert!(reply.to_lowercase().contains("paris"), "reply should name Paris: {reply:?}");
|
assert!(reply.to_lowercase().contains("paris"), "reply should name Paris: {reply:?}");
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,26 @@ pub mod serve;
|
|||||||
#[cfg(feature = "hip")]
|
#[cfg(feature = "hip")]
|
||||||
pub mod chat;
|
pub mod chat;
|
||||||
|
|
||||||
|
/// Serializes the heavy full-model GPU integration tests. Each loads the whole
|
||||||
|
/// Inkling engine (weights + KV), so running them concurrently exhausts GPU
|
||||||
|
/// memory; only one engine is resident at a time.
|
||||||
|
#[cfg(all(test, feature = "hip"))]
|
||||||
|
pub(crate) static GPU_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||||
|
|
||||||
|
/// Run a heavy GPU test body under the serial lock with the buffer pool OFF.
|
||||||
|
/// Two isolation guarantees: (1) only one full-model engine is resident at a
|
||||||
|
/// time (concurrent engines exhaust GPU memory); (2) the DeviceBuf pool is
|
||||||
|
/// disabled process-wide so every drop calls hipFree and device memory is
|
||||||
|
/// actually released between tests — the thread-local pool otherwise retains
|
||||||
|
/// buffers for the lifetime of each libtest worker thread and OOMs the GPU by
|
||||||
|
/// the fifth test. Safe: no env mutation, no `unsafe` in the gw crate.
|
||||||
|
#[cfg(all(test, feature = "hip"))]
|
||||||
|
pub(crate) fn gpu_isolated<F: FnOnce()>(f: F) {
|
||||||
|
let _serial = GPU_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
vetta_infer_hip::set_buf_pool_enabled(false);
|
||||||
|
f();
|
||||||
|
}
|
||||||
|
|
||||||
/// Python-repr float spelling (always a decimal point), as `strata-ctl` emits.
|
/// Python-repr float spelling (always a decimal point), as `strata-ctl` emits.
|
||||||
fn fmt_float(v: f64) -> String {
|
fn fmt_float(v: f64) -> String {
|
||||||
let s = format!("{v}");
|
let s = format!("{v}");
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ fn usage() {
|
|||||||
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
|
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 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!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)");
|
||||||
|
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 chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)");
|
||||||
eprintln!(" vetta-infer version Print version & build info");
|
eprintln!(" vetta-infer version Print version & build info");
|
||||||
}
|
}
|
||||||
@@ -94,12 +95,19 @@ fn main() -> ExitCode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some("serve") => {
|
Some("serve") | Some("--serve") => {
|
||||||
let Some(dir) = args.get(1) else {
|
let Some(dir) = args.get(1) else {
|
||||||
eprintln!("error: missing <safetensors-dir>");
|
eprintln!("error: missing <safetensors-dir>");
|
||||||
usage();
|
usage();
|
||||||
return ExitCode::from(2);
|
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")]
|
#[cfg(feature = "hip")]
|
||||||
{
|
{
|
||||||
match vetta_infer_gw::serve::run_serve(dir) {
|
match vetta_infer_gw::serve::run_serve(dir) {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
+2038
-15
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+1045
-53
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,7 @@
|
|||||||
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
|
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
|
||||||
|
|
||||||
pub mod bundle;
|
pub mod bundle;
|
||||||
|
pub mod dspark;
|
||||||
pub mod inkling;
|
pub mod inkling;
|
||||||
pub mod inkling_ir;
|
pub mod inkling_ir;
|
||||||
pub mod inkling_plan;
|
pub mod inkling_plan;
|
||||||
@@ -76,9 +77,62 @@ impl SafetensorsArchive {
|
|||||||
let mut tensors = HashMap::new();
|
let mut tensors = HashMap::new();
|
||||||
|
|
||||||
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
|
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()
|
let file = OpenOptions::new()
|
||||||
.read(true)
|
.read(true)
|
||||||
.open(&path)
|
.open(path)
|
||||||
.map_err(|e| format!("open {}: {e}", path.display()))?;
|
.map_err(|e| format!("open {}: {e}", path.display()))?;
|
||||||
let file_size = file
|
let file_size = file
|
||||||
.metadata()
|
.metadata()
|
||||||
@@ -151,53 +205,11 @@ impl SafetensorsArchive {
|
|||||||
}
|
}
|
||||||
tensors.insert(
|
tensors.insert(
|
||||||
name.clone(),
|
name.clone(),
|
||||||
TensorInfo {
|
TensorInfo { shard_idx, dtype, shape, begin, end },
|
||||||
shard_idx,
|
|
||||||
dtype,
|
|
||||||
shape,
|
|
||||||
begin,
|
|
||||||
end,
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
shards.push(SafetensorsShard {
|
Ok(SafetensorsShard { path: path.to_path_buf(), file, file_size, data_start })
|
||||||
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()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
|
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 bytes = info.byte_len() as usize;
|
||||||
let mut host = vec![0u8; bytes];
|
let mut host = vec![0u8; bytes];
|
||||||
ar.read_slice(name, 0, &mut host)?;
|
ar.read_slice(name, 0, &mut host)?;
|
||||||
let buf = DeviceBuf::alloc(bytes)?;
|
let buf = DeviceBuf::alloc_unpooled(bytes)?;
|
||||||
buf.h2d_bytes(&host)?;
|
buf.h2d_bytes(&host)?;
|
||||||
Ok(buf)
|
Ok(buf)
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ pub fn load_bf16_as_f32(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf
|
|||||||
let mut host = vec![0u8; bytes];
|
let mut host = vec![0u8; bytes];
|
||||||
ar.read_slice(name, 0, &mut host)?;
|
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 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)?;
|
buf.h2d(&f)?;
|
||||||
Ok(buf)
|
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)?;
|
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
|
||||||
let mut sbytes = vec![0u8; s_per_e];
|
let mut sbytes = vec![0u8; s_per_e];
|
||||||
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
|
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
|
||||||
let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?;
|
let packed = DeviceBuf::alloc_unpooled(w_per_e)?; packed.h2d_bytes(&wbytes)?;
|
||||||
let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?;
|
let scales = DeviceBuf::alloc_unpooled(s_per_e)?; scales.h2d_bytes(&sbytes)?;
|
||||||
return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true });
|
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 outer = amax / den;
|
||||||
|
|
||||||
let packed = DeviceBuf::alloc(w_per_e)?;
|
let packed = DeviceBuf::alloc_unpooled(w_per_e)?;
|
||||||
packed.h2d_bytes(&wbytes)?;
|
packed.h2d_bytes(&wbytes)?;
|
||||||
let scales = DeviceBuf::alloc(s_per_e)?;
|
let scales = DeviceBuf::alloc_unpooled(s_per_e)?;
|
||||||
scales.h2d_bytes(&sbytes)?;
|
scales.h2d_bytes(&sbytes)?;
|
||||||
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
|
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
|
||||||
}
|
}
|
||||||
@@ -124,6 +124,101 @@ pub fn expert_gemv_f16(em: &ExpertMatrix, x: &DeviceBuf, y: &DeviceBuf) -> Resul
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A whole layer's expert matrices packed in ONE contiguous device arena, exactly
|
||||||
|
/// as the safetensors already store them ([n_exp, N, K/2] NVFP4 / [n_exp, N, K]
|
||||||
|
/// MXFP8). The device-routed (indirect) GEMV indexes expert `id` via
|
||||||
|
/// `id * w_stride`, so the MoE dispatch needs NO host ids round-trip and the
|
||||||
|
/// launch parameters stay static => graph-capturable. `outer` holds one
|
||||||
|
/// precomputed amax/denominator per expert (NVFP4) or 1.0 (MXFP8).
|
||||||
|
pub struct ExpertArena {
|
||||||
|
pub packed: DeviceBuf,
|
||||||
|
pub scales: DeviceBuf,
|
||||||
|
pub outer: DeviceBuf,
|
||||||
|
pub n: i32,
|
||||||
|
pub k: i32,
|
||||||
|
pub n_exp: usize,
|
||||||
|
pub mxfp8: bool,
|
||||||
|
pub w_stride: i64,
|
||||||
|
pub sc_stride: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the full expert arena for `layer`/`mat` ("w13" or "w2") in one upload.
|
||||||
|
/// Zero requantization: bytes go to device as-is (same format detection as
|
||||||
|
/// load_expert_matrix: amax presence => NVFP4, else MXFP8).
|
||||||
|
pub fn load_expert_arena(ar: &SafetensorsArchive, layer: usize, mat: &str) -> Result<ExpertArena, String> {
|
||||||
|
let base = format!("model.llm.layers.{layer}.mlp.experts.{mat}");
|
||||||
|
let wname = format!("{base}_weight");
|
||||||
|
let sname = format!("{base}_weight_scale");
|
||||||
|
let aname = format!("{base}_weight_amax");
|
||||||
|
let dname = format!("{base}_weight_outer_scale_denominator");
|
||||||
|
let winfo = ar.tensors.get(&wname).ok_or_else(|| format!("missing {wname}"))?;
|
||||||
|
let n_exp = winfo.shape[0] as usize;
|
||||||
|
let n = winfo.shape[1] as i32;
|
||||||
|
let mxfp8 = !ar.tensors.contains_key(&aname);
|
||||||
|
|
||||||
|
let (k, w_per_e, s_per_e) = if mxfp8 {
|
||||||
|
let k = winfo.shape[2] as i32;
|
||||||
|
(k, (n as usize) * (k as usize), (n as usize) * (k as usize / 32))
|
||||||
|
} else {
|
||||||
|
let k_half = winfo.shape[2] as usize;
|
||||||
|
let k = (k_half * 2) as i32;
|
||||||
|
(k, (n as usize) * k_half, (n as usize) * (k as usize / 16))
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut wbytes = vec![0u8; n_exp * w_per_e];
|
||||||
|
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_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]
|
||||||
|
} else {
|
||||||
|
let mut amax_b = vec![0u8; n_exp * 4];
|
||||||
|
ar.read_slice(&aname, 0, &mut amax_b)?;
|
||||||
|
let den = if ar.tensors.contains_key(&dname) {
|
||||||
|
let mut d_b = [0u8; 4]; ar.read_slice(&dname, 0, &mut d_b)?;
|
||||||
|
let d = f32::from_le_bytes(d_b); if d == 0.0 { 2688.0 } else { d }
|
||||||
|
} else { 2688.0 };
|
||||||
|
amax_b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]) / den).collect()
|
||||||
|
};
|
||||||
|
let outer = DeviceBuf::alloc(n_exp * 4)?; outer.h2d(&outer_h)?;
|
||||||
|
|
||||||
|
Ok(ExpertArena { packed, scales, outer, n, k, n_exp, mxfp8, w_stride: w_per_e as i64, sc_stride: s_per_e as i64 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Device-routed expert GEMV from an arena: expert id read from `ids[slot]` on
|
||||||
|
/// device. Dispatches NVFP4 / MXFP8. Bit-identical math to expert_gemv_f16.
|
||||||
|
pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &DeviceBuf, y: &DeviceBuf, y_offset: i64) -> Result<(), String> {
|
||||||
|
if a.mxfp8 {
|
||||||
|
vetta_infer_hip::mxfp8_gemv_f16_indirect(&a.packed, &a.scales, ids, slot, x, y, a.n, a.k, a.w_stride, a.sc_stride, y_offset)
|
||||||
|
} else {
|
||||||
|
vetta_infer_hip::nvfp4_gemv_f16_indirect(&a.packed, &a.scales, &a.outer, ids, slot, x, y, a.n, a.k, a.w_stride, a.sc_stride, y_offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Grouped (batched) expert GEMM from an arena: one launch over all experts,
|
||||||
|
/// 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.
|
||||||
|
/// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -138,7 +233,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore] // requires GPU + --features hip + /mnt/models/Inkling
|
#[ignore] // requires GPU + --features hip + /mnt/models/Inkling
|
||||||
fn trunk_run_real_weights() {
|
fn trunk_run_real_weights() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let hidden = 2304usize;
|
let hidden = 2304usize;
|
||||||
let vocab = 201024usize;
|
let vocab = 201024usize;
|
||||||
let token_id = 100i32;
|
let token_id = 100i32;
|
||||||
@@ -200,7 +295,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_expert_nvfp4_gemv_parity() {
|
fn real_expert_nvfp4_gemv_parity() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap();
|
let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap();
|
||||||
let (n, k) = (em.n as usize, em.k as usize);
|
let (n, k) = (em.n as usize, em.k as usize);
|
||||||
assert_eq!((n, k), (2304, 2304));
|
assert_eq!((n, k), (2304, 2304));
|
||||||
@@ -259,7 +354,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_expert_nvfp4_gemv_f16_parity() {
|
fn real_expert_nvfp4_gemv_f16_parity() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap();
|
let em = load_expert_matrix(&ar, 0, 0, "w13").unwrap();
|
||||||
let (n, k) = (em.n as usize, em.k as usize);
|
let (n, k) = (em.n as usize, em.k as usize);
|
||||||
let x: Vec<f32> = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
|
let x: Vec<f32> = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
|
||||||
@@ -309,7 +404,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_expert_mxfp8_gemv_parity() {
|
fn real_expert_mxfp8_gemv_parity() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let em = load_expert_matrix(&ar, 20, 0, "w13").unwrap();
|
let em = load_expert_matrix(&ar, 20, 0, "w13").unwrap();
|
||||||
assert!(em.mxfp8, "layer 20 must be MXFP8");
|
assert!(em.mxfp8, "layer 20 must be MXFP8");
|
||||||
let (n, k) = (em.n as usize, em.k as usize);
|
let (n, k) = (em.n as usize, em.k as usize);
|
||||||
@@ -338,6 +433,38 @@ mod tests {
|
|||||||
assert!(max_rel < 1e-3, "real expert MXFP8 parity failed: {max_rel}");
|
assert!(max_rel < 1e-3, "real expert MXFP8 parity failed: {max_rel}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Arena (device-routed) expert GEMV must be BIT-EXACT vs the per-expert
|
||||||
|
/// direct GEMV on real weights: same shared device body, only the base
|
||||||
|
/// address is selected on device from ids[slot]. Covers NVFP4 (layer 0) and
|
||||||
|
/// MXFP8 (layer 20). Validates the contiguous-arena foundation for
|
||||||
|
/// graph-capturable MoE dispatch (no host ids round-trip).
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn real_expert_arena_indirect_parity() {
|
||||||
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
|
for &layer in &[0usize, 20] {
|
||||||
|
let arena = load_expert_arena(&ar, layer, "w13").unwrap();
|
||||||
|
let (n, k) = (arena.n as usize, arena.k as usize);
|
||||||
|
let x: Vec<f32> = (0..k).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
|
||||||
|
let dx = DeviceBuf::alloc(k * 4).unwrap(); dx.h2d(&x).unwrap();
|
||||||
|
let dx16 = DeviceBuf::alloc(k * 2).unwrap(); vetta_infer_hip::cast_f32_f16(&dx, &dx16, k).unwrap();
|
||||||
|
let ids_vec: Vec<i32> = vec![0, 1, 5, 127];
|
||||||
|
let ids_bytes: Vec<u8> = ids_vec.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||||
|
let dids = DeviceBuf::alloc(ids_bytes.len()).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap();
|
||||||
|
let yi = DeviceBuf::alloc(n * 4).unwrap();
|
||||||
|
let yd = DeviceBuf::alloc(n * 4).unwrap();
|
||||||
|
for slot in 0..ids_vec.len() {
|
||||||
|
expert_arena_gemv_f16(&arena, &dids, slot as i32, &dx16, &yi, 0).unwrap();
|
||||||
|
let em = load_expert_matrix(&ar, layer, ids_vec[slot] as usize, "w13").unwrap();
|
||||||
|
expert_gemv_f16(&em, &dx16, &yd).unwrap();
|
||||||
|
let mut gi = vec![0f32; n]; yi.d2h(&mut gi).unwrap();
|
||||||
|
let mut gd = vec![0f32; n]; yd.d2h(&mut gd).unwrap();
|
||||||
|
assert_eq!(gi, gd, "arena indirect != direct (layer {layer}, slot {slot})");
|
||||||
|
}
|
||||||
|
eprintln!("expert arena indirect bit-exact vs direct: layer {layer} ({})", if arena.mxfp8 { "MXFP8" } else { "NVFP4" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn bf16_trunc(x: f32) -> f32 { let u = x.to_bits(); let r = 0x7FFFu32 + ((u >> 16) & 1); f32::from_bits(((u + r) >> 16) << 16) }
|
fn bf16_trunc(x: f32) -> f32 { let u = x.to_bits(); let r = 0x7FFFu32 + ((u >> 16) & 1); f32::from_bits(((u + r) >> 16) << 16) }
|
||||||
fn rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> {
|
fn rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> {
|
||||||
let d = x.len();
|
let d = x.len();
|
||||||
@@ -397,7 +524,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_moe_block_end_to_end() {
|
fn real_moe_block_end_to_end() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let (hidden, inter, n_experts, top_k) = (2304usize, 1152usize, 128usize, 8usize);
|
let (hidden, inter, n_experts, top_k) = (2304usize, 1152usize, 128usize, 8usize);
|
||||||
let route_scale = 8.0f32;
|
let route_scale = 8.0f32;
|
||||||
let (beta, lb) = (4.0f32, 25.0f32);
|
let (beta, lb) = (4.0f32, 25.0f32);
|
||||||
@@ -524,7 +651,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_attention_block_end_to_end() {
|
fn real_attention_block_end_to_end() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let p = "model.llm.layers.0.attn";
|
let p = "model.llm.layers.0.attn";
|
||||||
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
|
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
|
||||||
let (qk_clip, rel_clip, eps) = (22.627416997969522f32, 8.0f32, 1e-6f32);
|
let (qk_clip, rel_clip, eps) = (22.627416997969522f32, 8.0f32, 1e-6f32);
|
||||||
@@ -699,7 +826,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_full_layer_end_to_end() {
|
fn real_full_layer_end_to_end() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let p = "model.llm.layers.0.attn";
|
let p = "model.llm.layers.0.attn";
|
||||||
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
|
let (hidden, n_head, n_kv, hd, d_rel, rel_extent) = (2304usize, 24usize, 8usize, 128usize, 16usize, 1024usize);
|
||||||
let (inter, n_experts, top_k) = (1152usize, 128usize, 8usize);
|
let (inter, n_experts, top_k) = (1152usize, 128usize, 8usize);
|
||||||
@@ -713,10 +840,10 @@ mod tests {
|
|||||||
// === GPU full layer via the reusable layer forward (ld::layer) ===
|
// === GPU full layer via the reusable layer forward (ld::layer) ===
|
||||||
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
|
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
|
||||||
let lw = crate::layer::load_layer(&ar, 0, true).unwrap();
|
let lw = crate::layer::load_layer(&ar, 0, true).unwrap();
|
||||||
let mut st = crate::layer::new_state(&dims, steps).unwrap();
|
let mut st = crate::layer::new_state(&dims, steps, 3).unwrap();
|
||||||
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
|
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
|
||||||
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
||||||
let cache = crate::layer::WeightCache::new(&ar);
|
let cache = crate::layer::WeightCache::new(ar.clone());
|
||||||
crate::layer::layer_forward_swa(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
|
crate::layer::layer_forward_swa(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
|
||||||
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
|
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
|
||||||
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
|
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
|
||||||
@@ -822,7 +949,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn real_full_attn_layer_end_to_end() {
|
fn real_full_attn_layer_end_to_end() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let ip = 5usize;
|
let ip = 5usize;
|
||||||
let p = format!("model.llm.layers.{ip}.attn");
|
let p = format!("model.llm.layers.{ip}.attn");
|
||||||
let l = format!("model.llm.layers.{ip}");
|
let l = format!("model.llm.layers.{ip}");
|
||||||
@@ -836,10 +963,10 @@ mod tests {
|
|||||||
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
|
let x: Vec<f32> = (0..hidden).map(|i| ((i % 53) as f32 - 26.0) * 0.02).collect();
|
||||||
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
|
let dims = crate::layer::Dims { hidden, n_head, n_kv, hd, d_rel, rel_extent, inter, n_experts, top_k, block_size: 6, qk_clip, rel_clip, eps, route_scale, beta, lb, swa_win: 1024 };
|
||||||
let lw = crate::layer::load_full_layer(&ar, ip, &dims).unwrap();
|
let lw = crate::layer::load_full_layer(&ar, ip, &dims).unwrap();
|
||||||
let mut st = crate::layer::new_state(&dims, 1).unwrap();
|
let mut st = crate::layer::new_state(&dims, 1, 3).unwrap();
|
||||||
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
|
let cur = DeviceBuf::alloc(hidden * 4).unwrap(); cur.h2d(&x).unwrap();
|
||||||
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
let mut blocks: Vec<DeviceBuf> = Vec::new();
|
||||||
let cache = crate::layer::WeightCache::new(&ar);
|
let cache = crate::layer::WeightCache::new(ar.clone());
|
||||||
crate::layer::layer_forward_full(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
|
crate::layer::layer_forward_full(&cache, &lw, &mut st, &dims, &cur, &mut blocks, pos, 0, None).unwrap();
|
||||||
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
|
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
|
||||||
// CPU oracle
|
// CPU oracle
|
||||||
@@ -931,7 +1058,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn full_attn_bisect() {
|
fn full_attn_bisect() {
|
||||||
let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap());
|
||||||
let ip = 5usize;
|
let ip = 5usize;
|
||||||
let p = format!("model.llm.layers.{ip}.attn");
|
let p = format!("model.llm.layers.{ip}.attn");
|
||||||
let l = format!("model.llm.layers.{ip}");
|
let l = format!("model.llm.layers.{ip}");
|
||||||
|
|||||||
+109
-27
@@ -71,39 +71,118 @@ Five ideas explain almost everything that will surprise you:
|
|||||||
|
|
||||||
## Current state (honest)
|
## Current state (honest)
|
||||||
|
|
||||||
- **CPU planning pipeline: complete and live-verified.** Inkling config →
|
- **The engine runs real inference, end-to-end, and it is correct.** The full
|
||||||
total tensor classification (1244/1244) → canonical IR → physical schedule
|
48-visit Inkling-2-Mini forward (prelude + looped core ×3 passes with bank
|
||||||
(looped core unrolled to 48 steps) → a full base decode graph (675 ops) that
|
rollback + coda + final depth-mix/softcap) runs on the real `gfx1150` weights.
|
||||||
passes the Lean-proven arena validator.
|
Greedy decoding is **EXACT multi-token parity** against the hardened `strata`
|
||||||
- **GPU execution: begun.** Three kernels verified on the real `gfx1150`
|
reference (16 and 40 tokens, F32 and FP16 KV). The two root causes of the old
|
||||||
(embed_bf16 exact, gemm_bf16 exact, rms_norm ~1e-6 relative error). The
|
token-2+ gap were structural, not precision: per-pass KV pools and the
|
||||||
hipcc → static-lib → FFI → launch → parity pipeline works end-to-end.
|
unpadded logit vocab (200058).
|
||||||
- **No token generated yet.** The engine does not currently run inference. The
|
- **Linked to the agent framework.** `strata-ctl --serve` spawns `vetta-infer`
|
||||||
GPU execution half (remaining kernels + executor + packer + serve wiring) is
|
and serves its OpenAI-compatible API; the wire protocol (READY/INFO/T/PP/
|
||||||
the work in progress. Do not mistake the validated *plan* for a running
|
RESUME/DONE/ERR) is field-for-field compatible. Verified live: capital queries,
|
||||||
*engine*.
|
Italian multi-turn, EOS/stop handling.
|
||||||
|
- **First real interactive GUI conversation (2026-12-01, measured).** Through the
|
||||||
|
`strata-ctl` web GUI on Sogliola (`http://sogliola:1234`), engine `vetta-infer`:
|
||||||
|
- 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.**
|
||||||
|
- 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)
|
||||||
|
dropped it to ~54% (measured A/B 101.2% → 54.2%). The residual ~54% is genuine
|
||||||
|
kernel-launch submission cost (~1300 launches/token), removed only by HIP graph
|
||||||
|
capture.
|
||||||
|
- **Multi-turn prefill is no longer re-paid: the prefix checkpoint cache landed
|
||||||
|
(2026-12-01, measured).** Ported in concept from strata `--auto-ckpt` and proven
|
||||||
|
in `proofs/prefix_cache.lean` (`restore_equiv`, 0 `sorryAx`), `serve_gen` restores
|
||||||
|
the longest cached prefix of a prompt and prefills only the NEW suffix tokens;
|
||||||
|
the checkpoint saves at `pos` (prompt + generated tokens) so the next turn reuses
|
||||||
|
the whole prior context. Pinned anchors {512,1024} are never evicted (I3), LRU at
|
||||||
|
cap 6, KV snapshots unpooled (freed on eviction). **Parity EXACT** (restore ==
|
||||||
|
cold re-prefill, token-for-token, both prewarm- and decode-state checkpoints).
|
||||||
|
Measured on `gfx1150`, Inkling-2-Mini, FP16 KV, greedy: a 605-token prompt with a
|
||||||
|
600-token cached prefix prefills in **2.29 s vs 132.5 s cold (57.8×)**, end-to-end
|
||||||
|
**3.2 s vs 133.2 s (41.8×)**. This collapses the *second-turn* time-to-first-token;
|
||||||
|
the *first* turn still pays sequential prefill (batched prefill is the next brick).
|
||||||
|
Validated at scale too: 8 checkpoints past cap 6 keep VRAM bounded (19.0→19.8 GiB,
|
||||||
|
0.5 GiB spread — no per-turn accumulation), the pinned anchors {512,1024} survive
|
||||||
|
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).
|
||||||
|
- **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
|
## The road to the goal
|
||||||
|
|
||||||
The destination: a working, measured inference engine that the agent framework
|
The destination: a working, measured inference engine that the agent framework
|
||||||
can talk to over the wire, replacing the old `strata` engine for a real
|
can talk to over the wire, replacing the old `strata` engine for a real
|
||||||
conversation. The path, in order:
|
conversation. **Steps 1–5 are landed** — the first real GUI conversation happened
|
||||||
|
on 2026-12-01 (see *Current state*). The path, in order:
|
||||||
|
|
||||||
1. **Inkling graph parity** — layer the model-specific refinements onto the base
|
1. **Inkling graph parity** — ✅ landed (attention-residual block-mix, loop
|
||||||
graph: the learned attention-residual block-mix, loop controllers, ShortConv4,
|
controllers, ShortConv4, relative-position bias, sliding-window attention,
|
||||||
relative-position bias, sliding-window attention, paged KV. (Blueprint:
|
per-pass KV). Blueprint: `docs/inkling-forward-design.md`.
|
||||||
`docs/inkling-forward-design.md`.)
|
2. **Remaining kernels** — ✅ landed (flash GQA/SWA, MoE NVFP4/MXFP8 routing +
|
||||||
2. **Remaining kernels** — flash attention (GQA, SWA, split-KV), MoE NVFP4
|
experts + reduce, KV-write, L2-clip, relpos). Each parity-verified.
|
||||||
routing + experts + reduce, RoPE/KV-write, penalties/top-k. Each
|
3. **Executor** — ✅ landed (full 48-visit forward on real weights).
|
||||||
parity-verified before use.
|
4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load).
|
||||||
3. **Executor (`rt`)** — lower the `CompiledPlan` to kernel launches, UMA arena
|
5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity,
|
||||||
broker, KV-cache management.
|
first real GUI conversation 2026-12-01).
|
||||||
4. **BackendPacker + `.vbundle`** — weights → device, the real bundle build.
|
6. **M2 performance** — ⏳ prefix checkpoint cache ✅ (multi-turn reuse, EXACT,
|
||||||
5. **Serve wiring** — connect the (already proven) serve-session FSM to real
|
57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense +
|
||||||
generation and to `vetta-agents` over the line protocol. **First chat.**
|
flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp
|
||||||
6. **M2 performance** — WMMA tiling, expert residency/streaming, measured
|
✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU).
|
||||||
tok/s against the reference.
|
7. **Drafter + DMA layer streaming** — ⏳ DSpark speculative drafter ✅ landed
|
||||||
7. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
|
(`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.
|
domain-aware expert prefetch.
|
||||||
|
|
||||||
## How to verify
|
## How to verify
|
||||||
@@ -117,6 +196,9 @@ lean proofs/slab_ring_dma.lean
|
|||||||
lean proofs/bus_lifecycle.lean
|
lean proofs/bus_lifecycle.lean
|
||||||
lean proofs/serve_session.lean
|
lean proofs/serve_session.lean
|
||||||
lean proofs/arena_plan.lean
|
lean proofs/arena_plan.lean
|
||||||
|
lean proofs/inkling_loop.lean
|
||||||
|
lean proofs/prefix_cache.lean
|
||||||
|
lean proofs/speculative_draft.lean
|
||||||
|
|
||||||
# Opt-in live tests against the real Inkling artifact:
|
# Opt-in live tests against the real Inkling artifact:
|
||||||
cargo test -p vetta-infer-ld -- --ignored inkling
|
cargo test -p vetta-infer-ld -- --ignored inkling
|
||||||
|
|||||||
@@ -27,10 +27,27 @@ int vetta_hip_register_uma_pages(void* host_aligned_ptr, size_t bytes, void** ou
|
|||||||
int vetta_hip_unregister_uma_pages(void* host_aligned_ptr);
|
int vetta_hip_unregister_uma_pages(void* host_aligned_ptr);
|
||||||
|
|
||||||
// Minimal device buffer lifecycle (executor foundation).
|
// Minimal device buffer lifecycle (executor foundation).
|
||||||
|
// Set blocking host-wait schedule (no 100% CPU spin during GPU waits); call once
|
||||||
|
// before the first allocation creates the device context.
|
||||||
|
int vetta_hip_init_blocking_sync(void);
|
||||||
int vetta_buf_alloc(void** out, size_t bytes);
|
int vetta_buf_alloc(void** out, size_t bytes);
|
||||||
int vetta_buf_free(void* p);
|
int vetta_buf_free(void* p);
|
||||||
int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
|
int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
|
||||||
int vetta_buf_d2h(void* dst, const void* src, size_t bytes);
|
int vetta_buf_d2h(void* dst, const void* src, size_t bytes);
|
||||||
|
// Device-to-device copies (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.
|
// k_rms_norm (kernel #2): y[row] = x[row] * rsqrt(mean(x^2)+eps) * w.
|
||||||
int vetta_rms_norm_f32(const float* x, const float* w, float* y,
|
int vetta_rms_norm_f32(const float* x, const float* w, float* y,
|
||||||
@@ -62,7 +79,7 @@ int vetta_flash_swa_gqa_decode(const float* q, const float* k, const float* v,
|
|||||||
float scale, int swa_window, int cur_pos,
|
float scale, int swa_window, int cur_pos,
|
||||||
const float* rel_bias, int max_rel,
|
const float* rel_bias, int max_rel,
|
||||||
const float* sink_logit, const float* gate,
|
const float* sink_logit, const float* gate,
|
||||||
vetta_stream_t stream);
|
float* scores_scratch, vetta_stream_t stream);
|
||||||
|
|
||||||
// k_flash_swa_gqa_decode_f16: FP16 KV cache variant (strata default FP16 KV).
|
// k_flash_swa_gqa_decode_f16: FP16 KV cache variant (strata default FP16 KV).
|
||||||
int vetta_flash_swa_gqa_decode_f16(const float* q, const uint16_t* k, const uint16_t* v,
|
int vetta_flash_swa_gqa_decode_f16(const float* q, const uint16_t* k, const uint16_t* v,
|
||||||
@@ -70,7 +87,7 @@ int vetta_flash_swa_gqa_decode_f16(const float* q, const uint16_t* k, const uint
|
|||||||
float scale, int swa_window, int cur_pos,
|
float scale, int swa_window, int cur_pos,
|
||||||
const float* rel_bias, int max_rel,
|
const float* rel_bias, int max_rel,
|
||||||
const float* sink_logit, const float* gate,
|
const float* sink_logit, const float* gate,
|
||||||
vetta_stream_t stream);
|
float* scores_scratch, vetta_stream_t stream);
|
||||||
|
|
||||||
// k_moe_router_topk: Inkling exact sigmoid router (top-K, route_scale norm).
|
// k_moe_router_topk: Inkling exact sigmoid router (top-K, route_scale norm).
|
||||||
int vetta_moe_router_topk(const float* logits, const float* bias,
|
int vetta_moe_router_topk(const float* logits, const float* bias,
|
||||||
@@ -142,7 +159,7 @@ int vetta_attn_res_mix(const float* blocks, const float* cur, const float* queri
|
|||||||
|
|
||||||
// k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau (in place).
|
// k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau (in place).
|
||||||
int vetta_l2_clip(float* x, const float* scale, int rows, int hd, float clip,
|
int vetta_l2_clip(float* x, const float* scale, int rows, int hd, float clip,
|
||||||
int apply_tau, int pos, vetta_stream_t stream);
|
int apply_tau, int pos, int scale_rows, const int32_t* pos_arr, vetta_stream_t stream);
|
||||||
|
|
||||||
// k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist], dist<lim.
|
// k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist], dist<lim.
|
||||||
int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias,
|
int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias,
|
||||||
|
|||||||
+2563
-107
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,387 @@
|
|||||||
|
/-
|
||||||
|
vetta-infer — Prefix Checkpoint Cache formal verification (Lean 4 core)
|
||||||
|
|
||||||
|
Models the prefix-reuse cache adopted in concept from strata's `--auto-ckpt`
|
||||||
|
(reference `proofs/auto_ckpt_pool.lean`), adapted to vetta's contiguous per-pass
|
||||||
|
KV + ShortConv history in a single conversation slot. Because vetta's KV is a
|
||||||
|
contiguous `[n_kv, max_seq, hd]` cache (not a paged SWA ring), the reference's
|
||||||
|
ring-page arithmetic is unnecessary. The core correctness invariant is the
|
||||||
|
observational equivalence of restore+suffix-prefill vs cold prefill, which
|
||||||
|
follows from causality of the forward (KV attention and ShortConv are causal:
|
||||||
|
the state after position p depends only on tokens [0..p)).
|
||||||
|
|
||||||
|
Part A — Causal prefill fold & restore equivalence (the correctness core).
|
||||||
|
Part B — Checkpoint validity is intrinsic and preserved by pool operations.
|
||||||
|
Part C — Auto-pool eviction: pinned anchors {512,1024} never evicted (I3),
|
||||||
|
size cap, no duplicate seq_len, an unpinned victim exists when cap ≥ 3.
|
||||||
|
|
||||||
|
0 sorryAx; core tactics only (no Mathlib).
|
||||||
|
-/
|
||||||
|
|
||||||
|
namespace VettaPrefixCache
|
||||||
|
|
||||||
|
/-- Token ids are natural numbers. -/
|
||||||
|
abbrev Tok := Nat
|
||||||
|
|
||||||
|
/-! ## Part A: causal prefill fold & restore equivalence -/
|
||||||
|
|
||||||
|
variable {S : Type}
|
||||||
|
|
||||||
|
/-- Prefill folds the causal step over a token list starting from state `s`.
|
||||||
|
The state encapsulates all history `[0..pos)`, so each step is causal. -/
|
||||||
|
def prefill (step : S → Tok → S) (s : S) : List Tok → S
|
||||||
|
| [] => s
|
||||||
|
| t :: ts => prefill step (step s t) ts
|
||||||
|
|
||||||
|
/-- Cold prefill from the initial state. -/
|
||||||
|
def cold (init : S) (step : S → Tok → S) (toks : List Tok) : S :=
|
||||||
|
prefill step init toks
|
||||||
|
|
||||||
|
theorem prefill_nil (step : S → Tok → S) (s : S) : prefill step s [] = s := rfl
|
||||||
|
|
||||||
|
theorem prefill_cons (step : S → Tok → S) (s : S) (t : Tok) (ts : List Tok) :
|
||||||
|
prefill step s (t :: ts) = prefill step (step s t) ts := rfl
|
||||||
|
|
||||||
|
/-- Folding over a concatenation composes: prefill (prefill s a) b = prefill s (a ++ b). -/
|
||||||
|
theorem prefill_append (step : S → Tok → S) (s : S) (a b : List Tok) :
|
||||||
|
prefill step (prefill step s a) b = prefill step s (a ++ b) := by
|
||||||
|
induction a generalizing s with
|
||||||
|
| nil => simp [prefill]
|
||||||
|
| cons t ts ih => simp [prefill, ih]
|
||||||
|
|
||||||
|
/-- A checkpoint stores the state reached after cold-prefilling its token prefix. -/
|
||||||
|
structure Ckpt (S : Type) where
|
||||||
|
toks : List Tok
|
||||||
|
state : S
|
||||||
|
|
||||||
|
/-- Validity: the stored state equals cold prefill of the stored prefix. -/
|
||||||
|
def Valid (init : S) (step : S → Tok → S) (ck : Ckpt S) : Prop :=
|
||||||
|
ck.state = cold init step ck.toks
|
||||||
|
|
||||||
|
/-- CORE correctness: restoring a valid checkpoint and prefilling the suffix is
|
||||||
|
observationally identical to cold-prefilling the whole `prefix ++ suffix`.
|
||||||
|
This is what makes partial prefill (only the new tokens) exact. -/
|
||||||
|
theorem restore_equiv (init : S) (step : S → Tok → S) (ck : Ckpt S) (suffix : List Tok)
|
||||||
|
(h : Valid init step ck) :
|
||||||
|
prefill step ck.state suffix = cold init step (ck.toks ++ suffix) := by
|
||||||
|
unfold Valid cold at h
|
||||||
|
rw [h]
|
||||||
|
exact prefill_append step init ck.toks suffix
|
||||||
|
|
||||||
|
/-- Restoring with an empty suffix reproduces the checkpoint state exactly. -/
|
||||||
|
theorem restore_nil (init : S) (step : S → Tok → S) (ck : Ckpt S)
|
||||||
|
(_h : Valid init step ck) : prefill step ck.state [] = ck.state := by
|
||||||
|
simp [prefill]
|
||||||
|
|
||||||
|
/-! ## Part B: validity is intrinsic and preserved by pool operations -/
|
||||||
|
|
||||||
|
/-- A pool is a list of checkpoints; the slot invariant is that every stored
|
||||||
|
checkpoint is valid (its state is the cold prefill of its own prefix). -/
|
||||||
|
def PoolValid (init : S) (step : S → Tok → S) (pool : List (Ckpt S)) : Prop :=
|
||||||
|
∀ ck ∈ pool, Valid init step ck
|
||||||
|
|
||||||
|
theorem poolValid_nil (init : S) (step : S → Tok → S) :
|
||||||
|
PoolValid init step [] := by
|
||||||
|
intro ck h; cases h
|
||||||
|
|
||||||
|
/-- Filtering a pool (invalidation) preserves validity of the survivors. -/
|
||||||
|
theorem poolValid_filter (init : S) (step : S → Tok → S) (p : Ckpt S → Bool)
|
||||||
|
(pool : List (Ckpt S)) (h : PoolValid init step pool) :
|
||||||
|
PoolValid init step (pool.filter p) := by
|
||||||
|
intro ck hck
|
||||||
|
exact h ck (List.mem_filter.mp hck).1
|
||||||
|
|
||||||
|
/-- Appending a checkpoint preserves validity when the new checkpoint is valid. -/
|
||||||
|
theorem poolValid_append (init : S) (step : S → Tok → S) (pool : List (Ckpt S))
|
||||||
|
(ck : Ckpt S) (h : PoolValid init step pool) (hck : Valid init step ck) :
|
||||||
|
PoolValid init step (pool ++ [ck]) := by
|
||||||
|
intro x hx
|
||||||
|
rcases List.mem_append.mp hx with hx | hx
|
||||||
|
· exact h x hx
|
||||||
|
· simp at hx; subst hx; exact hck
|
||||||
|
|
||||||
|
/-- Invalidation above a limit keeps only checkpoints whose prefix length ≤ limit;
|
||||||
|
validity is preserved (a corollary of filter preservation). -/
|
||||||
|
theorem invalidate_above_valid (init : S) (step : S → Tok → S) (pool : List (Ckpt S))
|
||||||
|
(limit : Nat) (h : PoolValid init step pool) :
|
||||||
|
PoolValid init step (pool.filter (fun ck => ck.toks.length ≤ limit)) :=
|
||||||
|
poolValid_filter init step (fun ck => ck.toks.length ≤ limit) pool h
|
||||||
|
|
||||||
|
/-! ## Part C: auto-pool eviction invariants (I3 pinned anchors, cap, nodup) -/
|
||||||
|
|
||||||
|
/-- Pinned static anchors are never evicted (reference invariant I3). -/
|
||||||
|
def pinned (seq : Nat) : Bool := seq == 512 || seq == 1024
|
||||||
|
|
||||||
|
theorem pinned_512 : pinned 512 = true := by simp [pinned]
|
||||||
|
theorem pinned_1024 : pinned 1024 = true := by simp [pinned]
|
||||||
|
|
||||||
|
/-- Membership of a `find?` result (self-contained, core only). -/
|
||||||
|
theorem mem_of_find_some {p : Nat → Bool} {l : List Nat} {a : Nat}
|
||||||
|
(h : l.find? p = some a) : a ∈ l := by
|
||||||
|
induction l with
|
||||||
|
| nil => simp [List.find?] at h
|
||||||
|
| cons x xs ih =>
|
||||||
|
simp only [List.find?] at h
|
||||||
|
split at h
|
||||||
|
· injection h with hx; subst hx; simp
|
||||||
|
· exact List.mem_cons.mpr (Or.inr (ih h))
|
||||||
|
|
||||||
|
/-- The predicate of a `find?` result holds. -/
|
||||||
|
theorem pred_of_find_some {p : Nat → Bool} {l : List Nat} {a : Nat}
|
||||||
|
(h : l.find? p = some a) : p a = true := by
|
||||||
|
induction l with
|
||||||
|
| nil => simp [List.find?] at h
|
||||||
|
| cons x xs ih =>
|
||||||
|
simp only [List.find?] at h
|
||||||
|
split at h
|
||||||
|
· injection h with hx; subst hx; assumption
|
||||||
|
· exact ih h
|
||||||
|
|
||||||
|
/-- Filtering out a present element strictly shrinks the list (no Nodup needed). -/
|
||||||
|
theorem length_filter_ne_lt {l : List Nat} {a : Nat} (hmem : a ∈ l) :
|
||||||
|
(l.filter (· != a)).length < l.length := by
|
||||||
|
induction l with
|
||||||
|
| nil => cases hmem
|
||||||
|
| cons x xs ih =>
|
||||||
|
by_cases hxa : x = a
|
||||||
|
· have hf : (x :: xs).filter (· != a) = xs.filter (· != a) := by
|
||||||
|
simp only [List.filter]; split <;> simp_all
|
||||||
|
rw [hf]
|
||||||
|
have := List.length_filter_le (· != a) xs
|
||||||
|
simp; omega
|
||||||
|
· have hf : (x :: xs).filter (· != a) = x :: xs.filter (· != a) := by
|
||||||
|
simp only [List.filter]; split <;> simp_all
|
||||||
|
rw [hf]
|
||||||
|
have hmem' : a ∈ xs := by
|
||||||
|
rcases List.mem_cons.mp hmem with h | h
|
||||||
|
· exact absurd h.symm hxa
|
||||||
|
· exact h
|
||||||
|
have := ih hmem'
|
||||||
|
simp; omega
|
||||||
|
|
||||||
|
/-- Filtering preserves distinctness (self-contained, core only). -/
|
||||||
|
theorem nodup_filter {l : List Nat} (p : Nat → Bool) (h : l.Nodup) :
|
||||||
|
(l.filter p).Nodup := by
|
||||||
|
induction l with
|
||||||
|
| nil => simp [List.filter]
|
||||||
|
| cons x xs ih =>
|
||||||
|
have hc := List.nodup_cons.mp h
|
||||||
|
simp only [List.filter]
|
||||||
|
split
|
||||||
|
· apply List.nodup_cons.mpr
|
||||||
|
constructor
|
||||||
|
· intro hh; exact hc.1 (List.mem_filter.mp hh).1
|
||||||
|
· exact ih hc.2
|
||||||
|
· exact ih hc.2
|
||||||
|
|
||||||
|
/-- Pool insert models `save_auto_checkpoint`: keep existing seq, else grow below
|
||||||
|
cap, else evict the first unpinned victim and append. If every entry is pinned
|
||||||
|
the pool is left unchanged (no unpinned victim). -/
|
||||||
|
def poolInsert (cap : Nat) (pool : List Nat) (seq : Nat) : List Nat :=
|
||||||
|
if seq ∈ pool then pool
|
||||||
|
else if pool.length < cap then pool ++ [seq]
|
||||||
|
else match pool.find? (fun s => !pinned s) with
|
||||||
|
| some v => pool.filter (· != v) ++ [seq]
|
||||||
|
| none => pool
|
||||||
|
|
||||||
|
/-- Inserting an already-present seq is a no-op. -/
|
||||||
|
theorem poolInsert_mem (cap : Nat) (pool : List Nat) (seq : Nat) (h : seq ∈ pool) :
|
||||||
|
poolInsert cap pool seq = pool := by
|
||||||
|
simp [poolInsert, h]
|
||||||
|
|
||||||
|
/-- The pool size never exceeds the cap (assuming it started ≤ cap). -/
|
||||||
|
theorem poolInsert_length_le (cap : Nat) (pool : List Nat) (seq : Nat)
|
||||||
|
(h : pool.length ≤ cap) : (poolInsert cap pool seq).length ≤ cap := by
|
||||||
|
unfold poolInsert
|
||||||
|
split
|
||||||
|
· exact h
|
||||||
|
· split
|
||||||
|
· rename_i hlt
|
||||||
|
simp only [List.length_append, List.length_singleton]
|
||||||
|
omega
|
||||||
|
· split
|
||||||
|
· rename_i v hv
|
||||||
|
have hmem : v ∈ pool := mem_of_find_some hv
|
||||||
|
have hfull : pool.length = cap := by omega
|
||||||
|
have hf : (pool.filter (· != v)).length < pool.length := length_filter_ne_lt hmem
|
||||||
|
simp only [List.length_append, List.length_singleton]
|
||||||
|
omega
|
||||||
|
· exact h
|
||||||
|
|
||||||
|
/-- I3: a pinned anchor present in the pool survives insertion. -/
|
||||||
|
theorem poolInsert_preserves_pinned (cap : Nat) (pool : List Nat) (seq s : Nat)
|
||||||
|
(hs : pinned s = true) (hmem : s ∈ pool) : s ∈ poolInsert cap pool seq := by
|
||||||
|
unfold poolInsert
|
||||||
|
split
|
||||||
|
· exact hmem
|
||||||
|
· split
|
||||||
|
· exact List.mem_append_left _ hmem
|
||||||
|
· split
|
||||||
|
· rename_i v hv
|
||||||
|
have hvun : pinned v = false := by
|
||||||
|
have := pred_of_find_some hv
|
||||||
|
simp at this
|
||||||
|
exact this
|
||||||
|
have hne : s ≠ v := by
|
||||||
|
intro heq; subst heq; rw [hs] at hvun; simp at hvun
|
||||||
|
have hf : s ∈ pool.filter (· != v) := by
|
||||||
|
apply List.mem_filter.mpr; exact ⟨hmem, by simp [hne]⟩
|
||||||
|
exact List.mem_append_left _ hf
|
||||||
|
· exact hmem
|
||||||
|
|
||||||
|
/-- Insertion preserves distinctness of seq_len entries. -/
|
||||||
|
theorem poolInsert_nodup (cap : Nat) (pool : List Nat) (seq : Nat)
|
||||||
|
(hnd : pool.Nodup) : (poolInsert cap pool seq).Nodup := by
|
||||||
|
unfold poolInsert
|
||||||
|
split
|
||||||
|
· exact hnd
|
||||||
|
· rename_i hnotmem
|
||||||
|
split
|
||||||
|
· exact List.nodup_append.mpr ⟨hnd, (by simp : [seq].Nodup), by
|
||||||
|
intro a ha b hb; simp only [List.mem_singleton] at hb; subst hb
|
||||||
|
intro heq; subst heq; exact hnotmem ha⟩
|
||||||
|
· split
|
||||||
|
· rename_i v hv
|
||||||
|
have hfnd : (pool.filter (· != v)).Nodup := nodup_filter _ hnd
|
||||||
|
have hseqnot' : seq ∉ pool.filter (· != v) := by
|
||||||
|
intro hh; exact hnotmem (List.mem_filter.mp hh).1
|
||||||
|
exact List.nodup_append.mpr ⟨hfnd, (by simp : [seq].Nodup), by
|
||||||
|
intro a ha b hb; simp only [List.mem_singleton] at hb; subst hb
|
||||||
|
intro heq; subst heq; exact hseqnot' ha⟩
|
||||||
|
· exact hnd
|
||||||
|
|
||||||
|
/- With cap ≥ 3 the pool always holds an unpinned victim: the only pinned anchors
|
||||||
|
are {512, 1024} (two values), so a Nodup pool of length ≥ 3 cannot be all
|
||||||
|
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