Compare commits

...
69 Commits
Author SHA1 Message Date
adm 85187d80a8 [Docs] Add codebase audit & tomorrow checklist (§8) to DSpark fix report 2026-12-02 23:28:36 +01:00
adm 1772050087 [HIP][Core] Zero-VRAM PrefixCache in pinned host RAM (PinnedBuf) + DSpark SWA ring
Close Punto 3 of the flat-VRAM plan:
- Add PinnedBuf (hipHostMallocDefault / hipHostFree with stream 0 sync on drop) and pipelined async 1D/2D D2H/H2D copy helpers in vetta_kernels.{h,hip} and vetta-infer-hip.
- Migrate LayerSnapshot (KV + ShortConv hist) and DsparkSnapshot (drafter KV + frnn_last) from VRAM DeviceBuf to host PinnedBuf (0 bytes VRAM per checkpoint).
- Size DSpark SWA layers 0/2 in DsparkContext to DS_SWA_RING=1280 (-258 MiB VRAM at 32k context).
- Add GPU regression tests: pinned_buf_zero_vram_and_roundtrip_2d (+0.00 MiB VRAM on 64 MiB alloc) and serve_gen_pinned_prefix_cache_vram_flat (4 turns up to 2100 tok, 8/8 checkpoints full, VETTA_SPEC=1: 20674->20672->20676->20676 MiB, +2.00 MiB delta).
- Update README.md, docs/ORIENTATION.md, and review/2026-12-02-fix-drafter-e-ottimizzazioni.md.
2026-12-02 23:23:07 +01:00
adm c1c5221642 [HIP][Core] DSpark GPU drafter + verify perf & correctness fixes (13.93 tok/s, strata parity)
Fix all DSpark speculative bottlenecks and long-context/multi-turn bugs:
- Single-pass base-unembed Top-512 screen + on-GPU Markov loop & argmax (reads 922 MB unembed once per round, <=32 B D2H).
- On-GPU batched verify argmax + forward_batch_taps_no_logits (eliminates double unembed and 4.8 MB D2H per round).
- Wave32 online-softmax dspark_block_attn (0 bytes LDS, fixes >16.2k token crash on Global layer 1; regression-tested at c_len=17000).
- Vectorized M-tiled Wave32 router_gemv_batched, zero-scratch small-M SWA GQA, WMMA gemm_bf16 for m>=1, fdot2 MoE for b<=12.
- Persistent DsparkContext + PrefixCache DsparkSnapshot save/restore (multi-turn RESUME parity tested).
- Accepted-count EMA governor starting at n_draft=5 (adapts 2..7).
- Docs (README.md, docs/ORIENTATION.md) + changelog in review/2026-12-02-fix-drafter-e-ottimizzazioni.md.

Measured on gfx1150 (Inkling-2-Mini, temperature=0, 100% greedy EXACT):
- Rust coding (RingBuffer<T>, 128 tok): OFF 6.83 -> VETTA_SPEC=1 13.93 tok/s (2.04x, n_draft=5; strata-inkling 13.66 tok/s).
- Short prose (capital, 96 tok): nd=5 4.58 -> 9.09 tok/s (+98.5%); adaptive EMA 8.93 tok/s decode.
Validated: cargo test --workspace (-D warnings), all 7 Lean 4 proofs (0 sorryAx), HIP/LD/GW GPU parity gates.
2026-12-02 23:13:43 +01:00
adm 91c1baaf27 [Docs] DSpark Step 1 completion record: verified chain, flash determinism fix, n_draft sweep
Documents the full drafter Step 1 landing (b1-b6 + serve wiring, opt-in
VETTA_SPEC=1), the WMMA flash batch-dependence root cause + per-M dispatch fix
(prefill perf preserved, measured 1.74x), the lossless gate (200 tokens EXACT)
and serve reference parity (16 tokens EXACT), the n_draft sweep (optimum 2,
hypothesis 5 disproved), measured ~1.16x speedup (acceptance-limited), and next
steps (acceptance bisection / tree drafter / DMA streaming). Verification totals:
CPU -D warnings clean, Lean 0 sorryAx, hip 45/45, ld GPU 65/65, gw GPU 22/22.
2026-12-02 22:19:46 +01:00
adm ba5149956e [Proto] DSpark n_draft tuned to measured optimum (2) + VETTA_SPEC_ND A/B override
Federico hypothesis 'fix drafter at 5, see if it rises' -> MEASURED NO. Sweep on
real capital prompt GEN 96 (gfx1150), decode tok/s: nd=1 5.25, nd=2 6.09, nd=3
5.78, nd=4 5.54, nd=5 4.58, nd=7 5.15. At ~30-50% acceptance a larger verify
batch (B=nd+1) wastes compute on rejected drafts; nd=2 is the optimum. Retune the
EMA governor to start at n_draft=2 and escalate only at very high acceptance
(>=0.75 -> 4, >=0.9 -> 7). Adaptive run now lands nd=2: decode 6.10 tok/s, ON 4.59
vs OFF 3.97 tok/s total (~1.16x). VETTA_SPEC_ND fixes n_draft for A/B measurement.
serve_gen_spec_multi_token_parity still EXACT (16 reference tokens).
CPU -D warnings clean, gw GPU 22/22.
2026-12-02 22:13:09 +01:00
adm df537bf84f [Proto] DSpark brick 5b-4: opt-in speculative serve decode + EMA (measured)
VETTA_SPEC=1 loads resident drafter weights (iff mtp.safetensors passes
layout_check) and enables a greedy speculative decode path: prefill captures
trunk taps (forward_batch_taps) and commits the DSpark context rings per chunk;
decode runs spec_round (batched verify + rollback) with EMA-adaptive n_draft
(7->4->2 as acceptance drops). Pure greedy + no penalties only; EOS/stop/length
handled per emitted token; prefix save unchanged. Default M=1 decode untouched.
MEASURED (real capital prompt, GEN 96, gfx1150): spec OFF 3.97 tok/s total vs
ON decode 5.71 tok/s, acceptance 31.4% (49/156), EMA n_draft 7->4, 46 rounds
(~2.09 tok/round), ~1.11x overall request. Modest but real, no overclaim.
serve_gen_spec_multi_token_parity: spec path emits the EXACT 16 reference tokens
(batched decode == M=1 == reference). CPU -D warnings clean, Lean 0 sorryAx,
gw GPU 22/22, hip 45/45, ld GPU 65/65.
2026-12-02 21:58:31 +01:00
adm 11404c4486 [HIP] Flash dispatch by M: WMMA prefill (perf) + deterministic scalar decode/verify
Supersedes the global scalar-flash default (6e854a9) which regressed prefill ~2x.
Root cause confirmed empirically: the FA2 WMMA flash leaks a masked extra KV key's
real V through the PV (~1 ulp) when q_max_pos > a query's pos in a mixed-position
tile (zeroing K13/V13 makes M=2==M=1 exact). That ~1 ulp is within the relaxed
prefill parity (greedy-vs-reference gate) but breaks EXACT speculative losslessness
(decode M=1 vs verify M=nd+1 must agree bit-for-bit; the drift bf16-rounds into the
ShortConv hist and accumulates until a greedy near-tie flips).
Fix: dispatch flash by M -> WMMA for M>=16 (prefill chunks, preserves the measured
win), per-query-deterministic scalar f16 flash for M<16 (decode B=1 + spec verify
M<=8). VETTA_FLASH_WMMA=1 forces WMMA, VETTA_NO_FLASH_WMMA=1 forces scalar.
MEASURED prefill 1024 tok chunk 256: WMMA 5.786 ms/tok vs scalar 10.047 ms/tok
(1.74x) -> no prefill regression. flash_batch_determinism M=2 vs M=1 maxdiff=0.
spec_lossless_gate 200 tokens EXACT. CPU -D warnings clean, hip 45/45, ld GPU 65/65.
2026-12-02 21:49:21 +01:00
adm 7b617bc333 [Core] DSpark brick 5b+6: speculative runner + LOSSLESS GATE green (200 tokens)
LayerState: per-prefix ShortConv hist snapshots (snap_k/v/a/m[3]) captured during
a spec verify batch via spec_update_hist (gated by thread-local spec_begin/end);
rollback_spec restores hist<-snap[accepted]. KV ring truncates with no restore
(proofs/speculative_draft.lean kept_rejected_disjoint). Normal path unchanged.
DsparkContext: persistent bf16 ctx rings (k/v[3] + frnn) + commit (scatter).
spec_round: draft nd -> batched trunk verify (forward_batch_taps B=nd+1) -> per-row
greedy from taps[3] -> spec_accept_greedy -> commit ctx + rollback hist. Mirrors
strata ink_serve.h indexing exactly.
b6 GATE: spec_lossless_gate emits EXACTLY the same 200 tokens as plain batched
greedy (forward_batch B=1) on real trunk+mtp (163 rounds, nd=7). Diagnostics:
batch_determinism, rollback_hist (exact), spec_lockstep (200 rounds hist+KV exact).
Acceptance 3.2% on the arbitrary synthetic prompt -> NO speedup claim yet.
Verified: CPU -D warnings clean, Lean 0 sorryAx, hip 45/45, ld GPU 65/65.
2026-12-02 21:30:34 +01:00
adm 6e854a9d73 [HIP] Per-query flash determinism (default scalar) + DSpark ctx scatter kernel
Root cause of speculative losslessness divergence: the FA2 WMMA prefill flash
rescales o_acc/row_sum over a mixed-position query tile up to q_max_pos, so a
query's output depended on its batch neighbours by ~1 ulp (masked extra KV block
still rescales; __expf(0) is not exactly 1). That 1-ulp drift bf16-rounds into the
ShortConv hist and accumulates until a greedy near-tie flips (gate diverged at
token 46). The scalar f16 flash is per-query deterministic. Make WMMA flash OPT-IN
(VETTA_FLASH_WMMA=1); default to the verified scalar baseline. Guard alpha=1.0
exactly when nm==row_max. New flash_batch_determinism test: query0 M=2 vs M=1
maxdiff=0. Also add k_dspark_scatter_bf16 (f32 rows -> bf16 ring at pos%cap) for
DSpark context commit. hip suite 45/45.
2026-12-02 21:30:27 +01:00
adm ca12801b40 [HIP] DSpark brick 5b-1: per-prefix ShortConv history snapshots kernel
k_shortconv4_hist_snaps: snaps[t] (t=0..B) = [3,C] history after t tokens of
in_x from hist0, same bf16-round/shift semantics as update_hist. Enables exact
DSpark partial-accept rollback (hist <- snaps[accepted]); the KV ring truncates
with no data restore (proofs/speculative_draft.lean kept_rejected_disjoint).
Parity: snaps[t] == verified update_hist on prefix t, all 9 prefixes EXACT.
2026-12-02 20:56:49 +01:00
adm 3812845f1a [Core] DSpark brick 5a: greedy speculative accept loop (exact reference indexing)
spec_accept_greedy + committed_prefix mirror strata ink_serve.h block-verify:
row i feeds anchor (i=0) / draft[i-1] at cur_pos+i, greedy[i] predicts
cur_pos+1+i; accept while argmax==draft[i], else emit correction (or bonus at
i==nd); accepted=emit.len(); rollback keeps cur_pos+accepted; the correction's
KV is deferred to the next round (becomes its anchor). Stop/length cap end the
request mid-round. Lossless per proofs/speculative_draft.lean spec_lossless.
CPU tests: all-accept+bonus, mid/first mismatch, stop, length cap, prefix.
CPU -D warnings green.
2026-12-02 20:48:30 +01:00
adm f9cde4954a [Core] DSpark brick 4c: full block-8 draft composition + exact oracle parity
- k_dspark_split3: split fused qkv [B,5120] -> q/k/v and gate_up [B,18432] -> g/u.
- dspark_draft(): the complete Step-1 linear draft — block [8,D] (slot0 =
  rms(embed(anchor)), rest mask_embed) -> 3 non-causal block-attn layers (fused
  qkv GEMM + per-head norm/NeoX-RoPE + block_attn over committed bf16 ctx ring +
  all B draft slots + o_proj) + SwiGLU MLP -> final norm -> 7-step recurrent
  Markov head (joint=[state;markov_w1[prev];cur[step];context], rnn GEMV, GRU,
  corr/combine, unembed argmax). f32 activations x bf16 weights throughout.
- Parity: full draft vs a complete CPU oracle on REAL mtp weights + synthetic
  trunk/ctx -> 7 token ids EXACT ([158,104,158,104,158,158,158]).
hip 43/43; ld GPU 56/56; CPU -D warnings green.
2026-12-02 20:44:01 +01:00
adm 142580e9ca [HIP] DSpark brick 4b: recurrent Markov head GRU + corr/combine kernels + parity
- k_dspark_markov_gru: proj[3*rank]+bias -> gate=sigmoid, cand=tanh,
  state[r]=cand+gate*(state[r]-cand), latent[r]=tanh (GRU-style recurrent head).
- k_dspark_corr_combine: combined = cur_step + corr_raw + hidden_out_bias.
- Host wrappers + parity: GRU 7.6e-7 over a 3-step recurrence (state carries),
  corr_combine bit-exact. hip 43/43; CPU -D warnings green.
2026-12-02 20:39:24 +01:00
adm 1b10258e6e [HIP] DSpark brick 4a: non-causal block attention + SwiGLU kernels + parity
- k_dspark_block_attn: each of B draft query slots attends to the committed ctx
  window (bf16 ring, slot=pos%cap) PLUS ALL B draft k/v (f32) — non-causal block,
  GQA n_rep=H/KV, two-pass softmax in dynamic shared. Exact reference port.
- k_dspark_swiglu: silu(g)*u (drafter MLP activation).
- Host wrappers + CPU-oracle parity: block_attn 5.3e-7 (wrapping ring cap=64,
  window 69..99), swiglu 9.0e-8. hip 41/41; CPU -D warnings green.
2026-12-02 20:38:29 +01:00
adm b6ed89b2d2 [Core] DSpark brick 3c: target-tap capture in the trunk runner
forward_batch refactored into forward_batch_inner(+optional taps) with thin
forward_batch / forward_batch_taps wrappers (existing signature unchanged).
Captures the 4 DSpark target taps: visit 5 (prelude ip5 entry residual),
visit 23 (core pass1 ip11 entry), visit 41 (core pass2 ip17 entry), and
visit 48 = output-normed final depth mix (model.llm.norm over attn_res_mix).
These feed dspark_context per committed token.
Test forward_batch_taps_capture: logits BIT-IDENTICAL to forward_batch (capture
is pure copies) and tap48 last row unembeds (cast+gemm, no re-norm) to exactly
those logits; all taps finite/nonzero. CPU -D warnings green; ld GPU 55/55.
2026-12-02 20:35:55 +01:00
adm 0cbec2d847 [Core] DSpark brick 3b: dspark_context composition + real-weight parity (3e-6)
- Drafter proj weights now BF16 (f32-act x bf16-w via router_gemv_batched is
  exact vs reference matmul_f32); norms/fuse stay f32; qkv/gate_up fused bf16.
- dspark_context(): per layer mix(row=il,dflare_norm_il) -> k/v_proj_ctx ->
  per-head k_norm_ctx + NeoX half-RoPE -> k/v [M,kv_dim] f32; frnn = row-3 mix
  with markov_head.dflare_norm. bf16 ring scatter left to the caller (b5).
- GPU-vs-CPU-oracle parity on the REAL mtp weights: max_rel 3.0e-6 (global-scale
  metric; per-entry rel explodes on near-zero RoPE outputs).
CPU -D warnings green; ld GPU 54/54.
2026-12-02 20:24:39 +01:00
adm 7e74db7ba5 [HIP] DSpark brick 3a: mix_taps + per-head RMSNorm/NeoX-RoPE kernels + parity
Exact port of strata k_dspark_mix_taps (softmax(fuse_w[row]) weighted sum of 4
target taps + RMSNorm) and k_dspark_rmsnorm_rope (per-head RMSNorm + NeoX
half-split RoPE pairs (d,d+hd/2)). f32 activations; bf16 store is the caller's.
RoPE freq/trig computed in f64 internally (f32 angle) for tight parity at large
pos; the downstream bf16 ctx store makes the extra precision moot.
Host wrappers dspark_mix_taps / dspark_rmsnorm_rope + CPU-oracle parity tests
(both < 1e-4). hip 39/39; CPU -D warnings green; speculative_draft.lean 0 err.
2026-12-02 20:21:54 +01:00
adm 3a9533afd0 [Core] DSpark brick 2: mtp.safetensors manifest + layout-check + fused loader
- SafetensorsArchive::open_file (single shard; mtp is not in the trunk index);
  header/bounds parsing refactored into load_shard shared with open().
- dspark.rs: expected_tensors() manifest (54 BF16 tensors, exact shapes),
  layout_check() CPU-only (missing/mismatched => drafter disabled, mirrors
  reference ink_dspark_layout_check), DsparkWeights::load() GPU resident
  (unpooled) with qkv [5120,2304] and gate_up [18432,2304] fused at load.
- Tests: CPU layout_check on the real file + wrong-shape rejection; GPU
  dspark_load_real_weights verifies fused/resident buffer sizes.
CPU -D warnings green; ld GPU 30/30; gw 15/15.
2026-12-02 20:08:11 +01:00
adm afce5cbbfe [Proofs] speculative_draft.lean: lossless greedy spec equivalence + rollback=truncate
Brick 1 of DSpark Step 1 (proof-first per AGENTS invariant 6):
- spec_lossless: one speculative round (draft, batched causal verify, accept
  longest matching prefix, emit correction/bonus) emits EXACTLY the plain-greedy
  prefix of length match_len+1 for ANY draft => speculation changes throughput,
  never the token sequence.
- kept_rejected_disjoint: with ring R >= window+chunk, kept window and rejected
  draft tail occupy disjoint ring slots => rollback = truncate history length,
  no KV data restore needed.
Core tactics only; 0 sorryAx; all 7 proofs green.
2026-12-02 20:05:11 +01:00
adm ca3a6b0e15 [Core] flat VRAM: SWA KV ring + fixed global KV + bounded scratch bucketing (reviewer p1+p2)
Punto 2: the 40 SWA pools now store a circular ring of swa_win+SWA_CHUNK_CAP(512)
=1536 positions (slot=pos%seq) instead of the whole 32768 context (~5GiB wasted);
the 8 global pools keep a linear max_context cache allocated ONCE. KV capacities
are fixed per layer kind => no drop+realloc when a session crosses a 4096 multiple.
kv_store{,_f16,_f16_batched} write pos%seq; flash decode/prefill/prefill_wmma read
p%seq (global seq>pos => identity). snapshot/restore map the window onto ring slots
with 1 or 2 pitched copies (wrap). serve clamps prefill chunk to SWA_CHUNK_CAP so
ring>=swa_win+chunk holds. proofs/prefix_cache.lean Part E (0 sorryAx): slot_inj,
window_slots_distinct, ring_no_clobber, global_slot_id. New GPU swa_ring_kv_parity
(R=1536, P=2000) vs an independent host LINEAR oracle: 1.48e-5.
Punto 1: BUF_POOL buckets pooled allocs in (4KiB,64MiB] to a power of two so variable
batch tails / future speculative B converge to a closed size set (no hipMalloc/Free
churn); larger allocs stay exact. Weight uploads (load_raw/load_bf16_as_f32/expert
matrix/arena) switched to alloc_unpooled: resident, exact, never pooled (rounding
them had added ~11GiB).
MEASURED gfx1150 FP16 KV chunk256: READY ~21.0GB; multi-turn 2048->13000->2048->5000
vram flat ~23.1-23.7GB (only bounded cap-8 checkpoint turnover, no KV resize);
prefill 2048 ~12.2s, 13000 ~78.6s (~6ms/tok). Suite GREEN hip37 ld23 gw4, CPU23, Lean6.
2026-12-02 19:59:11 +01:00
adm a4752953fb [Docs] record 2026-12-02 landed state: batched+WMMA prefill, flat VRAM, budget clamp
README + ORIENTATION refreshed to the measured current state (the 618s sequential
first-token is now historical): chunked batched prefill + FP16 WMMA MoE + BF16 WMMA
dense + FlashAttention-2 WMMA prefill => synthetic 2048 prefill 60->12.9s (-78%),
~6.3ms/token (16k agent prompt ~105s, was ~7min); greedy-vs-reference EXACT gate,
internal M=1-vs-M=B parity global-scale tolerance (P1 policy). Flat bounded VRAM
(persistent states, SWA-window ckpt, cap8 grid-protected prefix cache, 512MiB pool
cap, long->short KV reuse). Budget clamp (clamp_max_new) + configurable window
(--max-context): 16504-token prompt generates live (was ERR 0). Roadmap: drafter
integration next, then DMA layer streaming (io_uring O_DIRECT + hipHostRegister
SlabRing) as the hard memory frontier; INT8 fused MoE + HIP graph capture remain.
Lean verify list now 6 files (prefix_cache.lean). Includes the two 2026-12-02 peer
audits in review/.
2026-12-02 05:22:07 +01:00
adm ee8ac8f5df [Proto] clamp generation budget to window instead of hard-error (reviewer)
strata-ctl always sends max_new=16384, so any prompt > MAX_CONTEXT-16386 (16504 /
16686 seen live in sessions.db) hit the hard error and returned 0 tokens, killing
the agent mid-window. Now clamp_max_new(): hard-error only when the prompt itself
overflows (n_prompt+2 >= max_context); otherwise effective_max_new =
min(g.max_new, max_context-n_prompt-2) drives max_seq, history reserve, the decode
loop and the length finish. Resident window configurable like strata:
VETTA_MAX_CONTEXT env / serve --max-context N (>=4096), advertised in READY.
CPU test clamp_max_new_budget (16504/16686 clamp, 32765->1, 32766->None, 65536 full).
MEASURED live: 16504-token prompt GEN2 now runs (2 tokens, DONE 107.6s ~6.5ms/tok)
where it previously returned ERR 0 tokens; READY 32768 default / 65536 with flag.
gw serve_gen 4/4 EXACT; CPU -D warnings green.
2026-12-02 04:45:16 +01:00
adm cfa5586447 [HIP] P1 b7: FlashAttention-2 WMMA prefill (kills global scores_scratch)
k_flash_swa_gqa_prefill_wmma: tiled FA2 on contiguous FP16 KV, same semantics as the
scalar two-pass prefill (causal + SWA window + rel_bias + sink + sigmoid gate).
BQ=64/BK=64/HD=128, 128 threads; Q scaled->f16 held in registers, K tiles reuse the
Q LDS union, V loaded transposed for the PV B-operand, online softmax in registers,
P staged in LDS => NO global scores_scratch alloc per batch. QK^T and PV via
__builtin_amdgcn_wmma_f32_16x16x16_f16_w32. flash_swa_gqa_prefill_f16 binding
dispatches WMMA for hd==128; VETTA_NO_FLASH_WMMA=1 forces scalar (A/B + scalar test).
Parity vs scalar prefill on same fp16 KV (global-scale): 1.12e-3 (f16 P/Q rounding).
gw serve_gen 4/4 EXACT; ld forward_batch argmax 111==111; forward_batch internal
bound normalized to global logit scale (<1e-2) per P1 policy (f16 P compounds ~5e-3).
MEASURED prefill 2048 A/B: flash scalar 27.6s -> flash WMMA 12.9s (-53%).
Cumulative prefill 60 -> 12.9s (-78%); reference ~4.5s, gap ~2.9x.
Suite GREEN: hip36 ld23 gw4 GPU serial, CPU -D warnings 23, Lean 6/6 0sorryAx.
2026-12-02 04:36:22 +01:00
adm 216983abae [HIP] P1 b6: BF16 dense projection WMMA tensor-core GEMM
k_gemm_bf16_wmma: drop-in for the tiled-LDS scalar k_gemm_bf16 (same bf16 X[M,K]/
W[N,K], f32 Y[M,N]). BM16/BN128(8 waves)/BK64 LDS; bf16 operands feed
__builtin_amdgcn_wmma_f32_16x16x16_bf16_w32 directly (no dequant). gemm_bf16 binding
dispatches WMMA for prefill (m>=16, k%64==0); decode m<16 keeps scalar;
VETTA_NO_BF16_WMMA=1 forces scalar (A/B baseline).
Parity vs serial-K CPU oracle (global-scale): 1.0e-7..3.0e-7 (bf16 products exact in
f32, only accumulation order differs). gw serve_gen 4/4; ld forward_batch argmax
111==111 (greedy gate), max_abs unchanged 7.25e-2.
MEASURED prefill 2048 synthetic A/B: scalar 36.2s -> WMMA 27.8s (-23%).
Cumulative prefill 60 -> 27.8s (-54%); reference ~4.5s, gap ~6x.
Suite GREEN: hip35 ld23 gw4 GPU serial, CPU -D warnings 23, Lean 6/6 0sorryAx.
2026-12-02 04:28:48 +01:00
adm 99cd458d3b [Proto] reuse persistent KV cap on long->short session switch (reviewer tip)
serve_gen passed the per-request 4096 bucket (cap) to restore/forward, so after a
long session (states_cap=32768) a shorter request (bucket 20480) failed the
st.max_seq == max_seq reuse check and reallocated the persistent KV from scratch
(free 6.4GB, alloc 4GB) -> the VRAM drop+regrow Federico observed (31.7->25.9GB).
Now cap = eng.states_cap.get() after the grow-check: restore/forward use the actual
persistent stride, so returning to a shorter context reuses the KV (no realloc).
Measured: GEN1 5000tok then 100tok -> vram_end 23.56GB both (no drop). gw GPU 4/4.
2026-12-02 04:22:02 +01:00
adm 755626fae2 [HIP] P1: FP16 WMMA grouped NVFP4 MoE GEMM (tensor cores)
First P1 WMMA brick (Federico approved relaxing the bit-exact M=1-vs-M=B parity
to a numeric tolerance; greedy-vs-reference stays the blocking gate). Adds gfx11
(RDNA3.5) FP16 WMMA helpers (v_h16/v_f8, wmma_f32_16x16x16_f16_w32, acc lane map
2r+(lane>>4)) + k_nvfp4_grouped_gemm_wmma: a drop-in for the fdot2 grouped GEMM
with the same arena/CSR I/O. BM=16 (one M tile ~ tokens/expert at chunk 256),
BN=128 (8 waves, one 16x16 N tile each), BK=64 K-slab in LDS. NVFP4 E2M1 -> exact
FP16 prescaled e4m3*0.0625, WMMA f32 accumulation, epilogue *outer*16. Wired into
expert_arena_grouped_gemv_f16 for NVFP4 (K%64==0); VETTA_NO_MOE_WMMA=1 A/B fallback.
M=1 decode keeps fdot2 (WMMA needs M>=16 tiles).

Verified: WMMA-vs-CPU-oracle parity max_rel=1.2e-4; gw serve_gen greedy-vs-
reference EXACT (16 tokens + Paris + EOS, 4/4); forward_batch argmax batch==seq.
Relaxed the internal batched-vs-sequential tolerances to the P1 numeric budget
(global-scale normalization, not per-entry near-zero): forward_batch max_abs<0.15
(~2e-3 rel on +/-30 logits), single-layer cur + MoE global-scale <3e-3, KV cache
stays BYTE-IDENTICAL (attention precedes MoE). MEASURED prefill 2048tok A/B:
fdot2 41.6s -> WMMA 36.9s (-11%), moe_launch ~1888->1400ms (-26%). Gain bounded by
dequant/bandwidth (the reference INT8-fused sf4_i8 path is the further 2x axis).
Suite green: hip34 ld23 gw4 GPU serial, CPU -D warnings, Lean 0 sorryAx.
2026-12-02 03:04:58 +01:00
adm 47f8b52070 [Core] Flat VRAM: persistent KV states + SWA-window prefix checkpoints
a6 (persistent states): serve_gen allocated+freed ~3.75GB KV every request
(the +/-3.75GB sawtooth, max_new=16384). InklingEngine now holds persistent
per-layer states sized to a 4096-bucket cap >= prompt+max_new, reused across
requests and grown only on a bucket crossing. restore reuses a correctly-sized
state; a cold request resets the ShortConv hist rings (reset_history, async)
since the KV prefix is overwritten by prefill before any causal read. Verified:
two identical GEN16384 requests -> vram 23.46/23.49GB flat (no sawtooth),
identical reference output; twice-paris cold-reuse output identical.

a8 (SWA-window checkpoints): 40 of 48 KV pools are SWA (swa_win=1024) but the
snapshot stored the full seq_len on all of them (~510MB/checkpoint at seq2600).
Now SWA layers checkpoint only the last min(seq,1024) positions (kv_start offset
via new DeviceBuf::copy2d_at); full-attn layers keep the whole prefix. Checkpoint
~210MB. proofs/prefix_cache.lean Part D proves kvStart_le_winStart containment +
swa_window_restore_equiv (windowed restore observationally exact). Verified:
cold vs restored(1536, window truncated to [512,1536)) emit identical tokens.

Measured 5-turn VRAM climb +2.6GB -> +1.16GB (bounded by cap 8), KV flat.
Suite green: ld23 hip33 gw4 GPU serial, CPU -D warnings, Lean 0 sorryAx.
2026-12-02 02:52:32 +01:00
adm a6ca73105c [Proto] Fix prefix-cache turn-3 regression: LRU-on-restore + monotonic grid
best_match/restore never refreshed ck.lru, so the grid checkpoint just used
at turn 2 kept its turn-1 tick and was evicted by turn 2 prompt-boundary +
full-sequence saves; turn 3 fell back to the pinned 1024 anchor (~1min again).
Fix (audit §1): restore takes &mut self and bumps lru on hit; eviction prefers
non-grid entries (is_grid) so stable 512-grid prefixes survive; replace
pos%512==0 with a monotonic next_grid threshold that splits a chunk exactly on
each 512 boundary regardless of start. Cap 8. Verified 4-turn probe: restored
advances 1536->1686->1778 (no fallback), turn2+ prefill ~1-3.5s vs ~30s cold.
2026-12-02 02:28:53 +01:00
adm 844d9e68ee [Core] Cache static msg_queries in WeightCache; async KV zero-fill
load_msg_queries rebuilt the stacked cross-pass queries [4,hidden] on EVERY
core visit: 2 sync D2H + 1 sync H2D of STATIC model weights = 72 PCIe stalls
per prefill chunk (720/prompt) and 24 per decode token (audit §3.1). Memoize
the 12 device buffers once in WeightCache.msg_queries => zero host round-trips
on the hot path. Measured prefill 2048tok 40.9 -> 38.5s.

new_state zeroed ~3.75GB KV via host vec![0u8] + blocking h2d_bytes every
request (system-RAM alloc + CPU zero + sync PCIe copy, ~0.5-1.5s stall, even
on a prefix-cache hit). Replace with async device hipMemsetAsync (zero_async,
~7.5ms GPU): removes the blocking copy while keeping the cache deterministic
for the full-byte parity tests (causal attention only reads [0..=pos]).
2026-12-02 02:28:53 +01:00
adm ac1b55425c [HIP] Bound BUF_POOL with a 512MiB cap + LRU hipFree; guard moe_scatter_buckets
The exact-size thread-local BUF_POOL never called hipFree: every distinct
batched tail size (bu = suffix % chunk, varies per turn) parked ~100-160MiB
forever => unbounded multi-turn VRAM leak (audit 2026-12-02 §2.1). Track
POOL_BYTES and hipFree a dropped buffer once the pool exceeds MAX_POOL_BYTES
(512MiB); hot fixed-size intermediates still recycle. Also add the symmetric
e<0||e>=128 guard to k_moe_scatter_buckets (count_buckets had it) so a corrupt
router id cannot write exp_cur out of bounds.
2026-12-02 02:28:45 +01:00
adm 088ac1f66d [HIP] MXFP8 Wave32 fdot2 (grouped + M=1): MoE -31%, prefill 44.4->40.9s
Peer review P2: layers 20-23 MXFP8 grouped GEMV was scalar (256 threads/row +
shared reduction). Rewrite both k_mxfp8_grouped_gemv_f16 (M=B) and
mxfp8_gemv_f16_body (M=1 decode/indirect) as Wave32 mirrors of the NVFP4 path:
one wave per row (8 rows/block), E4M3 group dequantized once to exact FP16 (3
mantissa bits => exact in f16), hardware fdot2_f32 partial dot + scale-fma, DPP
wave32_sum (no shared mem). Both paths share the per-token group order => M=1 and
M=B stay BIT-EXACT (forward_batch_parity max_abs=0.0 restored; mxfp8 grouped oracle
1.3e-6 < 2e-3). MoE GPU time 2727->1888ms/chunk (-31%, the 65% hotspot). Prefill
2048: 44.4->40.9s. Suite GREEN ld23 hip33 gw4 (serial, server stopped), CPU -D
warnings, Lean 6/6. Cumulative prefill 60->40.9s (-32%).
2026-12-02 01:56:25 +01:00
adm 0f0bb42949 [Core] VETTA_PROF: sync-isolated real MoE GPU time in moe_batched (profile aid)
Under VETTA_PROF, sync before/after moe_batched so EXPERT_NS measures real GPU MoE
time, not async launch. Measured: MoE = 2727ms of 4176ms/chunk = 65% of batched
prefill (the dominant hotspot; trunk GEMM + flash are minority). Production path
(no VETTA_PROF) unchanged.
2026-12-02 01:46:28 +01:00
adm 45d039dcb4 [HIP] tiled-LDS gemm_bf16 (16x16x16): ~16x fewer global reads, BIT-EXACT
Replace 1-thread-per-output scalar GEMM with a 16x16 output-tile block staging
16-wide K slabs of X/W in LDS (loaded once, reused across 256 outputs). Serial-K
ascending accumulation preserved => bit-exact vs scalar (hip gemm parity, ld 23
batched bit-exact, gw 4 serve greedy vs reference all EXACT). Prefill 2048:
52.3 -> 44.4 s (-15%). WMMA tensor-core is the further pass (changes f32 accum
order => needs greedy re-verification).
2026-12-02 01:43:54 +01:00
adm f25cd27cf0 [HIP] eliminate per-visit sync h2d: rel_bias in-kernel zero + async memset + grouped identity
Peer review (strata-ctl coder) flagged ~13.3 GB of blocking host zero-fill copies
per prompt: rel_bias [B,n_head,rel_extent] (25 MB at B=256) was h2d-zeroed every
layer visit, plus moe_batched dcnt/didx sync h2d drained the GPU queue each layer.
- k_relpos_bias / k_relpos_bias_batched now write 0.0f for dist>=lim (full
  rel_extent in-kernel); callers drop the host zero vec + sync h2d (M=1 too).
- vetta_buf_zero_async (hipMemsetAsync) + DeviceBuf::zero_async for dcnt.
- grouped gemv bucket_tok nullable: w2 passes None (tok=beg+t0+m identity in
  kernel), removing the didx identity h2d. moe_launch 2054ms -> 8ms per chunk.
Prefill 2048: 56 -> 52.3 s; parity EXACT (ld 23, hip 33, gw 4, Lean 6/6). Enables
host/device pipelining + is a graph-capture prerequisite. Big perf gap remains the
scalar GEMM/flash (WMMA next).
2026-12-02 01:40:20 +01:00
adm ac31924ebb [Proto] prefix checkpoint grid (512) fixes multi-turn restored=0
The prompt re-rendered by strata-ctl diverges on the last ~2 turn-tag tokens once
turn 1 becomes history (live log: common_prefix=2644 vs checkpoint len=2646), so
best_match (full-checkpoint prefix) discarded everything and turn 2 cold-prefilled.
Save an intermediate checkpoint every 512 tokens during prefill (strata --auto-ckpt
grid): turn 2 now restores the longest 512-grid checkpoint that is a full prefix
(2560 for common=2644) and prefills only the new suffix (-93%). Verified: turn2
restored=1024 RESUME 1024, prefill 2631ms vs 25816ms cold (~9.8x), parity EXACT.
Also enrich VETTA_DBG_PREFIX to log per-checkpoint common_prefix on a miss.
2026-12-02 01:40:20 +01:00
adm 01d8a48d51 [Core] fix 2x expert VRAM: prewarm loads device-MoE arenas, not per-expert copies
prewarm eagerly loaded all per-expert ExpertMatrix tensors (host run_experts
path, ~16 GiB), but the production serve uses device-routed MoE which loads a
SECOND contiguous ExpertArena copy of the same expert bytes lazily on the first
forward. Measured: 25 GiB after prewarm climbing to 42 GiB during the first
prefill chunk (~0.6-0.9 GiB/layer = arena load), near the 48 GiB HIP aperture.

Fix: prewarm now loads the expert ARENAS (the layout device MoE actually reads);
the forward reuses the memoized arenas. VRAM 42 -> 20 GiB (-22), prefill 60 -> 56 s
(no lazy arena NVMe load mid-forward). Parity EXACT (serve GPU 4/4, ld 23, hip 33).
Also adds VETTA_PROF batched phase+VRAM profiling (BPROF) used to diagnose this.
2026-12-02 00:55:31 +01:00
adm 66a40631ee [HIP] add synchronize + vram_used profiling bindings (hipDeviceSynchronize / hipMemGetInfo) for batched-forward phase + VRAM instrumentation 2026-12-02 00:55:31 +01:00
adm c059a20aa9 [Proto] serve: chunked batched prefill (forward_batch) replaces M=1 per-token loop
serve_gen prefills the prompt suffix in chunks of VETTA_PREFILL_CHUNK (default
256) via eng.forward_batched -> forward_batch (M=B), amortizing weight streaming
+ kernel launches across B tokens instead of one model pass per token. take==1
falls back to the M=1 forward; chunk=1 restores the sequential path (A/B).
Aligns decode to f16 device MoE (VETTA_DEVICE_MOE) to match the batched prefill
precision (moe_device bit-identical to moe_batched).

Verified EXACT through the serve: serve_gen_multi_token_parity (5-tok prompt ->
batched chunk, 16 decode tokens identical to reference) + serve_gen_emits_eos_then_stop
(27-tok prompt -> batched chunk, EOS exact). gw CPU 14 + GPU 5 green.
2026-12-02 00:31:15 +01:00
adm b41a71f2f7 [Core] forward_batch: batched prefill orchestration (M=B) BIT-EXACT end-to-end
forward_batch embeds B tokens and runs the proven schedule (inkling_loop.lean)
at M=B: prelude [0,6) -> core [6,18) x3 with DEVICE-SIDE bank rollback (arena
sub-range via copy_f32_sub, cur<-prelude copy, blocks.truncate) + cross-pass
msgs (attn_res_mix over bank, nq=4) + controllers on passes 1,2 -> coda [18,24)
-> final depth mix + unembed LAST token. run_layer_batched dispatches SWA/full.
No host D2H/H2D gather anywhere in the batched path (graph-capturable shape).

copy_f32_sub: device f32 copy from src offset (extract bank / last token).

forward_batch_parity (real weights, B=4, f16 KV + device MoE): logits for the
last token BIT-EXACT (max_abs=0.0) AND argmax identical (111) vs 4 sequential
forward_inkling_with_state calls. The full batched prefill is verified.
2026-12-02 00:27:42 +01:00
adm 1aaf7f12c2 [Core] batched full-attn layer (M=B) bit-exact + l2_clip per-token tau
layer_forward_full_batched mirrors layer_forward_full at M=B: 3-query mix
[B*3,h] split strided via gather_channel(nq=3) into in0/in1/in2 with separate
q/k/v norms; DYNAMIC ShortConv K/V via shortconv4_prefill_par(dyn_taps[B,n_kv,4])
(already supported dyn path, no new kernel); Q/R l2_clip with per-token tau;
global flash window=0; MoE sublayer identical to batched SWA.

k_l2_clip gains pos_arr (device [M]): tau uses pos_arr[r/scale_rows] per token
(full-attn) else scalar pos. l2_clip passes null (M=1 unchanged); l2_clip_batched
takes Option<&DeviceBuf> pos_arr.

layer_full_batched_parity (real weights ip=5, B=8, f16 KV + device MoE):
cur[B,h] BIT-EXACT (0.0) AND KV byte-identical vs 8 sequential M=1 calls.
Both layer types (SWA + full-attn) now batched and verified.
2026-12-02 00:24:37 +01:00
adm 3dbb6bb1b4 [Core] batched SWA layer (M=B) bit-exact vs sequential + BatchBlocks arena + batched controller
layer_forward_swa_batched mirrors layer_forward_swa at M=B: device-resident
BatchBlocks arena [max_blocks,B,h] (attn_res_mix reads directly, snapshot via
copy_f32_at, truncate for bank rollback), strided msgs gather + apply_controller_batched
(ctrl_pack_batched + gemm M=B + ctrl_apply), shortconv prefill_par+update_hist,
l2_clip_batched, relpos/kv_store/flash prefill, router_gemv_batched + moe_batched.

layer_swa_batched_parity (real weights ip=1, B=8, f16 KV + device MoE aligned):
cur[B,h] BIT-EXACT (0.0) AND KV cache byte-identical vs 8 sequential M=1 calls.
Found+fixed the l2_clip out-of-bounds scale bug via per-stage bisection.
2026-12-02 00:21:00 +01:00
adm 51b230cdd2 [HIP] l2_clip scale_rows fix (batched per-head scale) + gather_channel + copy_f32_at + l2_clip_batched
k_l2_clip indexed the per-head scale as scale[r*hd] with r=row. For M=1
rows=n_head so r=head (correct); for batched rows=M*n_head the rows >= n_head
read the [n_head,hd] scale OUT OF BOUNDS, corrupting q/r (r_raw clipped to 0).
Add scale_rows param: sc = scale[(r % scale_rows)*hd]. l2_clip passes rows
(M=1 unchanged); new l2_clip_batched passes n_head. Regression test
l2_clip_batched_parity (M=8,n_head=24,hd=128) bit-exact vs sequential.

Also: k_gather_channel (strided msgs channel [B*nq,h]->[B,h] for batched
controllers), copy_f32_at (offset copy into depth-block arena). Flash prefill
parity test now exercises the real config (n_head=24,n_kv=8,hd=128,win=1024).
2026-12-02 00:20:55 +01:00
adm 3a2ad4da49 [HIP] copy_f32: device-side f32 copy for depth-block snapshot / bank rollback
k_copy_f32 (dst=src, n elements): enables device-side depth-block snapshot and
core-loop bank rollback in the batched forward, eliminating the M=1 host D2H/H2D
round-trips (layer.rs block snapshot + bank rollback). Exact (test copy_f32_exact).

Additive — decode default unchanged. Foundation for the device-resident depth-block
arena [n_blocks,B,h] that attn_res_mix reads directly (already M>1).

Verified: hip GPU 32 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-02 00:00:23 +01:00
adm 48de65d395 [LD] moe_batched: end-to-end batched MoE (M=B) verified BIT-EXACT on real weights
Composes the landed batched kernels into the full prefill MoE: cast f32->f16 ->
bucket CSR (count/prefix/scatter) -> grouped w13 GEMM (gather tokens via bucket_tok)
-> SiTU batched -> grouped w2 GEMM (SiTU output bucket-ordered, identity index) ->
reduce_buckets_masked (scatter-back + weighted reduce). All device-side, no host
ids/output round-trip. expert_arena_grouped_gemv_f16 helper dispatches NVFP4/MXFP8.

Parity vs per-token moe_device on REAL weights: layer 0 (NVFP4) + layer 20 (MXFP8),
B=8, same router ids/weights => max_rel 0.0 BIT-EXACT both formats.

moe_batched marked allow(dead_code) until the batched layer forward wires it (next
brick). Additive — decode default unchanged.

Verified: hip GPU 31, ld GPU 20, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:58:52 +01:00
adm 388e9108e5 [HIP] Batched router_gemv (f32) + relpos_bias + ctrl_pack (M=B): last attention/MoE prep kernels
k_router_gemv_batched: f32 router logits x[M,K]·w[N,K]bf16 -> y[M,N], grid(N,M)
(router reads F32 mlpin, exact strata launch_f32_linear).
k_relpos_bias_batched: r[M,n_head,d_rel] -> rel_bias[M,n_head,rel_extent], grid
(n_head,M), lim[m]=min(pos[m]+1,rel_extent) per token.
k_ctrl_pack_batched: cur/msg[M,D] -> packed[M,2D]bf16, grid M (controller input).

Parity vs M sequential: router 0.0, relpos 0.0, ctrl_pack BYTE-IDENTICAL (M=20).

Additive — decode default unchanged. With these, ALL per-layer kernels needed by
a batched forward now support M=B (gemm_bf16/rms_norm/attn_res_mix/router_topk
already did). Remaining: device-resident depth-block arena + batched layer
orchestration (SWA+full) + forward_batch + serve wiring + EXACT parity.

Verified: hip GPU 31 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:49:18 +01:00
adm 708a40d91b [HIP] Batched SiTU (M rows) + grouped MXFP8 expert GEMM (layers 20-23)
k_situ_f16_batched: SiTU over M rows (gu [M,2*inter] interleaved -> act [M,inter]
FP16), one row per blockIdx.y. Activates all grouped-MoE w13 output rows at once.
k_mxfp8_grouped_gemv_f16<MT=8>: MXFP8 analogue of the NVFP4 grouped GEMM, grid
(N, n_experts), bucket-indexed; 32-byte E4M3 group dequantized once per MT-token
tile (UE8M0 scale, no outer), block reduction per token. Covers layers 20-23.

Parity: SiTU batched BYTE-IDENTICAL to M sequential; grouped MXFP8 vs CPU oracle
B=20 4 experts 160 pairs max_rel 0.0 (UE8M0 scales in realistic range).

Additive — decode default unchanged. All batched MoE compute now complete for
BOTH quant formats (NVFP4 layers 0-19 + MXFP8 20-23).

Verified: hip GPU 28 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:45:13 +01:00
adm 10db2f11e4 [HIP] Batched kv_store_f16 (M=B): fill all B KV positions before batched flash
k_kv_store_f16_batched: grid (n_kv, M); k_in/v_in [M,n_kv,hd]; each token m writes
FP16 cache position pos[m] (K as-is post-clip, V RMS-normalized then __float2half_rn).
Same semantics as the M=1 kv_store_f16. Batched prefill stores all B K/V before the
causal flash M=B reads the cache.

Parity vs B sequential kv_store_f16: B=20 n_kv=2 hd=128, K/V caches BYTE-IDENTICAL.

Additive — decode default unchanged.

Verified: hip GPU 26 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:43:34 +01:00
adm a7a1ab11b0 [HIP] Batched causal flash SWA GQA M=B (FP16 KV): the hardest prefill attention kernel
k_flash_swa_gqa_prefill_f16: same two-pass softmax semantics as the decode f16
kernel extended to M tokens (grid n_head x M). Each query token m uses
cur_pos=pos[m] (causal: attends keys <= pos[m]); KV cache [n_kv,seq,hd] must hold
all B positions first. q/out/gate [M,n_head,hd], rel_bias [M,n_head,max_rel],
sink [M,n_head], scores_scratch [M,n_head,n_win_max] (alloc_unpooled, varies per
batch). SWA window + rel_bias + sink + sigmoid gate all preserved.

Parity vs B sequential decode flash f16 calls: B=20 n_head=8 win=16 base=10
(windowed + unwindowed tokens), BIT-EXACT (0.0).

Additive — decode default unchanged. Batched attention kernels now landed:
ShortConv prefill_par + causal flash M=B + attn_res_mix (already M>1). Remaining:
kv_store B positions + batched depth-blocks/controllers/bank + SiTU/MXFP8 batched,
then forward_batch orchestration + serve wiring + EXACT parity + measure turn-1.

Verified: hip GPU 25 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:40:29 +01:00
adm ec2ad3fdc5 [HIP] ShortConv prefill parallel (tile 16) + update_hist: batched attention brick
k_shortconv4_prefill_par (exact strata k2_shortconv4_prefill_par): one thread per
channel processes a tile of 16 contiguous tokens; 3-token history seeded from hist
[3,C] (bf16-rounded f32, same ring as decode) for t0<3 else in_x bf16 round-trip.
Static 1/sqrt(5) or dynamic taps [B,n_heads,4] 1/3. Replaces B sequential decode
calls with one parallel launch (grid C-tiles x ceil(B/16)).
k_shortconv4_update_hist: roll history <- last 3 in_x (bf16), shift for B<3.

Parity vs B sequential decode steps: B=37 (partial last tile) C=64, output AND
history BIT-EXACT (0.0). Note: k_attn_res_mix already supports M>1 (grid nq x M).

Additive — decode default unchanged. Remaining batched attention: causal flash
M=B + kv_store B positions + batched depth-blocks/controllers/bank, then
forward_batch orchestration + serve wiring + EXACT parity.

Verified: hip GPU 24 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:38:20 +01:00
adm b6113b549a [HIP] reduce_buckets_masked: scatter-back + weighted reduce per token (batched MoE closed)
k_moe_reduce_buckets_masked (exact strata semantics): bucket_y [total,D] in bucket
order + slotk_to_bidx maps pair (b*top_k+kk) -> bucket position; out[b,d] =
sum_kk tk_w[b*top_k+kk]*bucket_y[s2b[b*top_k+kk]*D+d]. grid (D tiles, B).

This CLOSES the batched MoE compute path: bucket CSR (count/prefix/scatter) ->
grouped expert GEMM (W amortized MT-fold) -> reduce_buckets_masked (scatter-back +
weighted reduce). All device-side, no host round-trip. Parity vs CPU oracle:
max_rel 1.75e-5 (f32 FMA accumulation noise, threshold 1e-4).

Additive — decode default unchanged. Remaining for batched PREFILL: batched SiTU
(M=total), batched attention (flash causal M=B + ShortConv prefill + attn_res_mix
M=B + kv_store B), batched depth-blocks/controllers/bank, forward_batch + serve
wiring + EXACT parity.

Verified: hip GPU 23 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
2026-12-01 23:35:55 +01:00
adm 870133d6e5 [HIP] Grouped MoE expert GEMM (one launch over all experts, bucket-indexed)
k_nvfp4_grouped_gemv_f16<MT=16>: grid.y=n_experts, expert eid processes its bucket
tokens [exp_off[eid],exp_off[eid+1]) read from bucket_tok; W group dequantized once
per MT-token tile (fdot2), amortizing expert weight bandwidth MT-fold across the
tokens routed to that expert. X [B,K] f16 gathered by bucket_tok -> Y [total,N]
f32 in bucket order. This is the prefill MoE GEMM (w13/w2 NVFP4); composes with the
landed bucket CSR (count/prefix/scatter). SiTU + reduce_buckets_masked follow.

Parity vs CPU dequant oracle per (token,expert) pair: B=20, 4 experts, 160 pairs,
max_rel_err 2.79e-5. Additive — decode default unchanged.

Verified: hip GPU 22 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
Next: reduce_buckets_masked + batched SiTU, then batched attention -> forward_batch.
2026-12-01 23:34:33 +01:00
adm e1b16b5874 [HIP] Grouped-MoE bucket CSR build (count/prefix/scatter): device-side tokens-per-expert
Port strata k_moe_count/prefix/scatter_buckets: for total=B*top_k (token,expert)
pairs build exp_off[129] CSR offsets, bucket_tok[total] (bucket->token) and
slotk_to_bidx[total] (pair->bucket position), entirely on device (no host
round-trip). This lets the grouped expert GEMM read each expert weights ONCE for
all tokens routed to it — the prefill weight-bandwidth amortization behind the
reference 40:1 prefill speedup.

Parity vs CPU oracle (B=37, top_k=8): CSR offsets == prefix-sum of counts,
slotk_to_bidx consistent bijection, per-expert bucket token multiset exact
(scatter order within a bucket is non-deterministic via atomicAdd, so invariants
are checked rather than element order).

Verified: hip GPU 21 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
Next: grouped w13/w2 GEMM indexed by bucket_tok + reduce_buckets_masked, then
batched attention -> forward_batch.
2026-12-01 23:14:15 +01:00
adm bfdd665434 [HIP] Batched NVFP4 f16 GEMM (M>1) for prefill: weight dequant amortized MT-fold
Port strata k_sf4_gemv<MT> multi-token path: k_nvfp4_gemv_f16_mt<MT=16>, one wave
per output row, the W group is dequantized ONCE and reused across MT tokens
(fdot2 per token), M tiled by blockIdx.y. X [M,K] f16 -> Y [M,N] f32. This is the
expert-GEMM foundation for batched prefill: reading each expert weight once per
MT tokens instead of once per token amortizes the dominant NVFP4 weight bandwidth
MT-fold. For M=1 the math reduces to the decode GEMV (same fdot2 + scale-fma).

Parity vs CPU dequant oracle [M,N]: M=37 (exercises 2 full MT tiles + 5-token
remainder) max_rel_err 1.75e-6. Additive — decode default unchanged.

Verified: hip GPU green (incl. new mt parity), workspace CPU -D warnings green,
6 Lean proofs 0 sorryAx. Next: batched MoE (router M=B + grouped expert GEMM +
reduce M=B) and batched attention/depth-blocks -> forward_batch for prefill.
2026-12-01 22:49:55 +01:00
adm 0914fae8c8 [LD][HIP] Device-resident MoE path (opt-in VETTA_DEVICE_MOE): no host ids/output round-trip
moe_device runs the whole MoE on device: router ids/weights stay on device, the
arena indirect GEMV selects experts on device, per-expert outputs accumulate in a
device y_part via a STATIC y_offset=kk*hidden (added to both indirect kernels).
No ids D2H, no per-expert output D2H/H2D => the MoE block is now graph-capturable.

WeightCache gains a memoized expert_arena(ip,mat) accessor. Both SWA and full-attn
MoE blocks dispatch to moe_device under VETTA_DEVICE_MOE=1; the default f32 host
path is unchanged (parity baseline preserved).

Parity: 16/16 greedy tokens IDENTICAL between VETTA_DEVICE_MOE=1 and the
VETTA_F16_EXPERT=1 host path (same kernels/data). Arena indirect bit-exact vs
direct on real weights (NVFP4 layer 0 + MXFP8 layer 20).

Verified: ld GPU 19 + hip GPU 19 green, workspace CPU -D warnings green, 6 Lean
proofs 0 sorryAx. Next: device-resident depth-block/bank machinery, then HIP graph
capture of the decode step.
2026-12-01 22:43:47 +01:00
adm 752edeaade [LD][HIP] Contiguous expert arena + device-routed MXFP8/NVFP4 GEMV (graph-capturable MoE foundation)
ExpertArena loads a whole layer expert tensor in ONE contiguous device buffer
(the safetensors already store [n_exp,N,K/2] NVFP4 / [n_exp,N,K] MXFP8), with a
per-expert outer_scale array. The indirect GEMV indexes expert id from a DEVICE
buffer (ids[slot]) => static launch params, no host ids round-trip.

Add MXFP8 f16 indirect kernel (mirrors NVFP4: shared device body + direct +
indirect wrappers). expert_arena_gemv_f16 dispatches NVFP4/MXFP8.

Parity on REAL weights: arena-indirect BIT-EXACT vs per-expert direct for layer 0
(NVFP4) and layer 20 (MXFP8), 4 routed experts each. Additive — forward default
unchanged (wiring into the device-resident MoE path is the next brick).

Verified: ld GPU 19 + hip GPU 19 green, workspace CPU -D warnings green, 6 Lean
proofs 0 sorryAx.
2026-12-01 22:39:39 +01:00
adm 4c82040610 [HIP] Device-routed NVFP4 f16 GEMV (indirect): foundation for graph-capturable MoE
Refactor k_nvfp4_gemv_f16 into a shared device body + direct wrapper + indirect
wrapper. The indirect variant reads the expert id from a DEVICE buffer (ids[slot])
and indexes a contiguous per-layer weight arena (packed/scales/outer), so launch
parameters stay static — no host ids round-trip. This is the prerequisite for
HIP graph capture of the decode step (current MoE dispatch is host-mediated).

Math identical to the direct kernel (same body): parity test builds a synthetic
4-expert arena and routes 4 slots, asserting BIT-EXACT equality indirect vs direct.
Additive only — default forward path unchanged.

Verified: hip GPU 19 green (incl. new indirect parity), workspace CPU -D warnings
green, 6 Lean proofs 0 sorryAx.
2026-12-01 22:35:31 +01:00
adm 8d886bd56f [HIP] NVFP4 f16 GEMV performance pass: hardware fdot2 + register half2 dequant + wave-per-row
Port the exact strata k_sf4_gemv path (the 'performance pass' the original
correctness-first kernel deferred): one wave per output row (8 rows/block),
E2M1->FP16 register LUT dequant, hardware v_dot2_f32_f16 (fdot2_f32) over
vectorized uint4 activation loads, DPP wave32 reduction. Adds sf4_e2m1_f16,
fdot2_f32, wave32_sum helpers (gfx1150 builtins).

Parity verified: real expert w13 f16 max_rel_err 8.4e-5 (tol 2e-3); hip 18 + ld 18
GPU green. MEASURED decode (64 tok greedy, eager-resident): f32-scalar 4.63 tok/s
vs f16-fdot2 4.86 tok/s (1.05x). Profiler shows why it is modest: experts are only
~45ms of ~185ms/token; decode is dominated by attention + ~1300 kernel launches
(host submission), not expert compute. This kernel is the verified foundation for
the WMMA M>1 prefill GEMM (next brick); the decode lever is HIP graph capture.
2026-12-01 22:13:04 +01:00
adm 58940840d6 [LD][GW] Resident WeightCache + eager full-model boot load (eliminate per-request NVMe re-read)
Bug: serve_gen called WeightCache::new(&eng.ar) PER REQUEST, creating empty
memoization maps each turn -> every request re-read ~15-23 GiB of weights from
NVMe and re-uploaded to device (the 'resident' comment was contradicted by the
per-request instantiation). Federico spotted the symptom: model only loaded at
the first message, unlike the reference which loads at boot.

Fix:
- WeightCache now owns Arc<SafetensorsArchive> (was &'a borrow) so ONE cache lives
  resident in InklingEngine across all requests; loaded once, never re-read.
- WeightCache::prewarm(d, n_layers) eagerly loads the whole model (trunk + every
  SWA/full layer + core controllers + all expert matrices). run_serve calls it at
  boot by DEFAULT (model ~23 GiB <= 80 GiB full-UMA-residency policy); READY is
  emitted only after residency. VETTA_LAZY_LOAD=1 defers to first use (still
  resident across requests once loaded).
- Arc deref coercion keeps all CPU-oracle test reads (&ar) unchanged.

Verified (gfx1150, Inkling-2-Mini, FP16 KV): eager VRAM 23.60 GiB at READY before
any message, boot 3.6s, STABLE across 3 requests (no reload/growth), clean release
0.34 GiB on QUIT; lazy option 0.34 GiB at boot. Parity EXACT preserved: CPU 91 +
ld GPU 18 + gw GPU 5 green.
2026-12-01 21:46:42 +01:00
adm 20e152640e [GW] Prefix cache: save prompt-boundary checkpoint + emit RESUME (fix multi-turn reuse in the GUI)
Root cause (traced across strata-ctl + strata): strata-ctl build_prompt re-renders
the chat template from conversation TEXT and re-encodes every turn; the assistant
reply round-trips through detokenize/re-encode (special tokens stripped), so it is
NOT token-identical to the generated ids. The first port saved a checkpoint only at
the post-decode pos (prompt+generated), exactly the part that diverges -> no match
on turn 2 -> full cold re-prefill (Federico measured 734s vs 783s, no speedup).

Fix mirrors strata ink_serve.h:949 (prompt-end checkpoint, longest-prefix match):
also save a checkpoint at the PROMPT boundary, the stable system+history prefix
that re-renders identically across turns. best_match picks the longest valid
prefix, so turn 2 restores the prompt and prefills only the new dialogue suffix.
Emit RESUME <start> via on_prefill_complete (was hardcoded 0) so strata-ctl reports
reused/cached tokens. VETTA_DBG_PREFIX logs match/save for live diagnosis.

Verified (gfx1150, Inkling-2-Mini, FP16 KV, greedy): realistic turn-2 with a
DIFFERENT assistant tail restores the 300-token prompt boundary (debug restored=300),
parity EXACT vs cold, prefill 6.02s vs 72.42s (12x). CPU 91 + gw GPU 5 green, Lean 0
sorryAx. Absolute first-turn prefill speed still needs batched prefill (next brick).
2026-12-01 21:35:38 +01:00
adm 442d26c90c [Docs] Prefix cache validated at scale: VRAM bounded past cap 6, pinned anchors survive eviction, EXACT parity at 1024 2026-12-01 20:47:47 +01:00
adm 8c8ae4485a [Docs] Prefix checkpoint cache landed: multi-turn prefill reuse, EXACT parity, 57.8x measured 2026-12-01 20:30:33 +01:00
adm 736c541887 [GW][LD][HIP][Proofs] Wire prefix checkpoint cache into serve: restore longest prefix, prefill only new suffix
Concept ported from strata --auto-ckpt, adapted to vetta's contiguous per-pass
KV + ShortConv history (proofs/prefix_cache.lean, restore_equiv). serve_gen now
restores the longest cached STRICT prefix of a prompt and prefills only the new
suffix tokens; the final logits still come from a real forward of the last prompt
token. Checkpoints save at pos (prompt + generated non-EOS tokens) so the next
turn reuses the full prior context. Pinned anchors {512,1024} never evicted (I3),
LRU at cap 6; KV snapshots unpooled (freed on eviction). VETTA_NO_PREFIX_CACHE
forces cold prefill for A/B.

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

Verified: CPU 91 + gw GPU 5 + hip GPU 18 + ld GPU 18 green; Lean 0 sorryAx.
Multi-turn parity EXACT (restore == cold re-prefill), both prewarm- and
decode-state checkpoints. Measured (gfx1150, Inkling-2-Mini, FP16 KV, greedy):
605-token prompt, 600-token cached prefix -> prefill 132.5s cold vs 2.29s warm
(57.8x), end-to-end 133.2s vs 3.2s (41.8x).
2026-12-01 20:30:13 +01:00
adm f12281ec61 [Proofs] Prefix checkpoint cache: restore-equivalence + pool invariants (0 sorryAx)
Proof-first for 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 (single conversation slot, no paged SWA ring).

Part A (correctness core): prefill is a causal fold; restore_equiv proves that
restoring a valid checkpoint and prefilling the suffix is observationally
identical to cold-prefilling prefix++suffix — this is what makes partial prefill
(only the new tokens) exact.
Part B: checkpoint validity is intrinsic and preserved by filter (invalidation)
and append.
Part C: auto-pool eviction — pinned anchors {512,1024} never evicted (I3), size
cap, no duplicate seq_len. Self-contained core lemmas (mem_of_find_some,
nodup_filter, length_filter_ne_lt); no Mathlib.

lean proofs/prefix_cache.lean: 0 errors, 0 sorryAx.
2026-12-01 20:15:19 +01:00
adm c9713c8bc1 [HIP][LD][GW] Bound VRAM across requests: unpooled KV + FP16 serve KV + bucketed flash scratch
Federico saw VRAM grow ~7 GiB per agent step (44.9/48 GiB, near OOM). Root cause:
the KV cache scales with max_seq=prompt+max_new (varies per request) and the
exact-size DeviceBuf pool retained every distinct KV size, so a multi-turn chat
accumulated KV without bound. The full-attn flash scores scratch (n_win grows per
token) leaked similarly.

- DeviceBuf gains a 'pooled' flag + alloc_unpooled(): always hipFree on drop,
  never pooled. KV (k_cache/v_cache) uses it -> freed at request end, no
  accumulation. Per-token fixed-size intermediates stay pooled (decode speed).
- flash_scores_scratch buckets the allocation to a power of two so the pool
  reuses it as cur_pos grows (kernel still strides by actual n_win <= bucket).
- KV dtype: FP16 for the resident serve (exact strata KvDtype::FP16 default,
  parity-verified EXACT, half the VRAM of F32). Safe process-wide switch
  set_kv_f16(); InklingEngine::new opts in. The ld CPU-oracle parity tests keep
  the F32 default (VETTA_F32_KV=1 also forces F32).

Measured (new binary, 3 requests of 200/400/600 prompt tokens): VRAM 7.66 ->
8.07 -> 8.33 GiB (small bounded expert lazy-load growth, NOT +7 GiB/step);
clean release to 0.34 GiB on QUIT. Parity EXACT (16 tok); 18 ld + 18 hip + 5 gw
GPU green; workspace -D warnings green; 5 Lean 0 sorryAx.
2026-12-01 20:02:33 +01:00
adm b1f65942c8 [Docs] Document the first real interactive GUI inference (2026-12-01, measured)
Federico completed the first real conversation with vetta-infer through 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 time-to-first-token is the sequential prefill of the ~2650-token agent
prompt (~140 ms/token); decode is ~4.2 tok/s. Recorded honestly as the current
performance frontier (not a hang).

- README M1 milestone: inference landed (EXACT parity + strata-ctl link), with a
  dedicated measured first-GUI-conversation bullet; refreshed verification counts
  (5 Lean files incl. inkling_loop.lean).
- ORIENTATION 'Current state (honest)': replaced the stale 'No token generated
  yet' with the real state (full forward, EXACT parity, agent link, first GUI
  chat, blocking-sync CPU fix A/B 101.2%->54.2%); marked road steps 1-5 landed,
  M2 performance (graph capture / batched prefill / expert WMMA) as the frontier.
2026-12-01 19:26:15 +01:00
adm 25200e2e79 [HIP] Blocking host-wait schedule: kill the 100% CPU spin during GPU inference
Federico observed vetta-infer at 100% CPU while the GPU runs — the same busy-wait
the strata upstream had. Root cause: ROCm's default host-wait schedule spins on
every blocking synchronization (the per-token logits hipMemcpy D2H waits for the
whole 48-visit forward). The reference fixes it with --hip-sync blocking
(hipDeviceScheduleBlockingSync, ink_hip_backend.hip.cpp:607).

Apply the same: vetta_hip_init_blocking_sync() calls
hipSetDeviceFlags(hipDeviceScheduleBlockingSync), invoked once via std::sync::Once
at the top of DeviceBuf::alloc — before the first hipMalloc creates the device
context (tolerates hipErrorSetOnActiveProcess). Escape hatch
VETTA_NO_BLOCKING_SYNC=1 keeps the spin schedule for A/B measurement.

Measured A/B (220-token prefill, instantaneous /proc CPU):
  spin (VETTA_NO_BLOCKING_SYNC=1): 101.2%
  blocking (default):             54.2%
The ~47 pp of spin-wait is gone. The remaining ~54% is genuine kernel-launch
overhead (~1300 launches/token, no HIP graph yet) — collapsing launches via graph
capture is the deferred perf step that would bring host CPU near zero.

Parity EXACT (16 tok) unchanged; 18 hip + 5 gw GPU green; workspace -D warnings green.
2026-12-01 19:06:33 +01:00
adm 59c41cb613 [HIP][GW] Support large context: global flash scores + raise MAX_CONTEXT to 32768
The GUI (strata-ctl agent session) sends a ~2648-token prompt plus max_new=16384;
the old MAX_CONTEXT=8192 refused it ('prompt + max_new exceeds context window'),
so the chat returned 0 tokens. Two fixes:

- Flash attention stored per-head scores[n_win] in dynamic shared memory. SWA is
  window-capped (1024) but full-attn is global, so beyond ~16K positions it
  exceeded the 64 KB LDS limit. Scores now live in a global scratch buffer
  ([n_head, n_win], allocated by the Rust wrapper, pool-reused); only the [nt]
  reduction stays in shared. Math unchanged -> parity EXACT (16 tok) preserved.
- MAX_CONTEXT 8192 -> 32768, sized for the consumer's max_new budget plus a large
  agent prompt; per-request KV (prompt+max_new) fits the 48 GiB HIP VRAM.

Verified live: 3113-token prompt -> correct 'Parigi' (finish stop). NOTE: prefill
is still sequential (~140 ms/token), so a large agent prompt takes minutes to
first token — batched prefill / prefix cache / expert-GEMV speedup is the next
(perf) step. Small prompts are fast.

Suite: workspace -D warnings green; 18 ld + 18 hip + 5 gw GPU; 5 Lean 0 sorryAx.
2026-12-01 18:56:50 +01:00
adm 7790f48c27 [GW][HIP][LD] Link vetta-infer to strata-ctl; isolate GPU tests; size KV per pass
End-to-end verified: strata-ctl --serve spawns vetta-infer and serves the
OpenAI-compatible API. Live: 'capital of France' -> Paris (finish stop), and
Italian multi-turn context -> Napoli. Two wire-compat gaps closed:
- accept '--serve <dir>' alias (strata-ctl engine_argv prepends --serve).
- emit the EOS token as 'T <eos>' before 'DONE ... stop', matching the
  reference strata-inkling --serve (strata-ctl's dialect decoder reads the
  end-of-sampling channel token). chat parity now EXACT incl. EOS.

GPU test isolation (the 5th full-model test OOM'd): HIP-visible VRAM is 48 GiB
(model 18 GiB; one live instance peaks ~15 GiB and releases cleanly). The OOM
was the harness, not a leak: the thread-local DeviceBuf pool retains buffers
for each libtest worker thread's lifetime, so 5 engines' weights accumulated
past 48 GiB. Fix: gw gpu_isolated() runs heavy tests under a serial lock with
the pool disabled via a new safe hip::set_buf_pool_enabled (no env mutation,
gw stays unsafe-free), so every drop hipFrees between tests.

KV sizing: LayerState.k_cache/v_cache are now Vec sized to the passes a layer
actually runs (core 3, prelude/coda 1) instead of 3 for every layer, removing
~1.6 GiB of unused KV at max context. Parity unchanged (EXACT 16 tok).

Suite: workspace -D warnings green; 18 ld + 18 hip + 5 gw GPU; 5 Lean 0 sorryAx.
2026-12-01 18:26:18 +01:00
adm b9cac6d0df [LD][GW] Fix systematic token-2+ parity gap: per-pass KV cache + unpadded logit vocab
Two root causes found by bisecting the pos-27/28 forward against strata-inkling
(per-visit cur-norm dumps, STRATA_INK_NORM/POS, reverted after):

1. KV cache was shared across the 3 core loop passes. The reference assigns a
   DISTINCT KV pool per visit (visit_kv_slot: 40 SWA + 8 global), so each core
   pass reads its own KV history. Sharing one cache corrupted multi-token
   attention from the first core visit (visit6) onward. LayerState.k_cache/
   v_cache are now [DeviceBuf; 3] indexed by pass (prelude/coda use pass 0).

2. Served/logit vocab used the PADDED size (201024). Padding tokens >= the
   unpadded vocab (200058) carry arbitrary logits and outranked real tokens
   (e.g. 200193 beat end_message 200010). Engine now uses unpadded_vocab,
   matching strata k_unembed_softcap V = vocab_unpadded.

Verified: chat parity EXACT vs reference for 16 and 40 greedy tokens, both
F32 (default) and FP16 KV. pos-28 per-visit norms now agree to ~3e-3 (was
diverging by 50-80). Added serve_gen_multi_token_parity GPU regression.

Suite: workspace -D warnings green; 18 ld + 18 hip + 4 gw GPU; 5 Lean 0 sorryAx.
2026-12-01 18:04:01 +01:00
19 changed files with 9139 additions and 316 deletions

No files matched your search

+13 -4
View File
@@ -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.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.
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** DSpark drafter ✅ landed; next is layer streaming in DMA — the hard memory frontier: Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
## Quick Verification
```sh
# Lean 4 formal proofs (0 sorryAx, 42 theorems across 4 files)
# Lean 4 formal proofs (0 sorryAx, 7 files)
lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean
lean proofs/arena_plan.lean
lean proofs/inkling_loop.lean
lean proofs/prefix_cache.lean
lean proofs/speculative_draft.lean
# Pure-Rust workspace tests (no GPU required, 65 tests)
# Pure-Rust workspace tests (no GPU required)
cargo test --workspace
```
+2
View File
@@ -125,6 +125,7 @@ mod tests {
#[test]
#[ignore]
fn chat_turn_paris() {
crate::gpu_isolated(|| {
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").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.")];
@@ -133,5 +134,6 @@ mod tests {
eprintln!("[chat] reply={reply:?} streamed={streamed:?}");
assert_eq!(reply, streamed, "streamed text must equal the full reply");
assert!(reply.to_lowercase().contains("paris"), "reply should name Paris: {reply:?}");
});
}
}
+20
View File
@@ -20,6 +20,26 @@ pub mod serve;
#[cfg(feature = "hip")]
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.
fn fmt_float(v: f64) -> String {
let s = format!("{v}");
+9 -1
View File
@@ -11,6 +11,7 @@ fn usage() {
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)");
eprintln!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)");
eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it; [--max-context N])");
eprintln!(" vetta-infer chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)");
eprintln!(" vetta-infer version Print version & build info");
}
@@ -94,12 +95,19 @@ fn main() -> ExitCode {
}
}
}
Some("serve") => {
Some("serve") | Some("--serve") => {
let Some(dir) = args.get(1) else {
eprintln!("error: missing <safetensors-dir>");
usage();
return ExitCode::from(2);
};
// Optional resident window override (like strata --max-context):
// `serve <dir> --max-context N`. Defaults to 32768 when absent.
if let Some(i) = args.iter().position(|a| a == "--max-context") {
if let Some(v) = args.get(i + 1).and_then(|s| s.parse::<usize>().ok()) {
unsafe { std::env::set_var("VETTA_MAX_CONTEXT", v.to_string()) };
}
}
#[cfg(feature = "hip")]
{
match vetta_infer_gw::serve::run_serve(dir) {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+57 -45
View File
@@ -9,6 +9,7 @@
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
pub mod bundle;
pub mod dspark;
pub mod inkling;
pub mod inkling_ir;
pub mod inkling_plan;
@@ -76,9 +77,62 @@ impl SafetensorsArchive {
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let sh = load_shard(&path, shard_idx, &mut tensors)?;
shards.push(sh);
}
Ok(Self { dir, shards, tensors })
}
/// Open a SINGLE safetensors file (e.g. `mtp.safetensors`, which is not in
/// the trunk index weight_map). Same checked header/bounds validation.
pub fn open_file(path: impl AsRef<Path>) -> Result<Self, String> {
let path = path.as_ref().to_path_buf();
let dir = path
.parent()
.unwrap_or_else(|| Path::new("."))
.to_path_buf();
let mut tensors = HashMap::new();
let sh = load_shard(&path, 0, &mut tensors)?;
Ok(Self { dir, shards: vec![sh], tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
}
fn load_shard(
path: &Path,
shard_idx: usize,
tensors: &mut HashMap<String, TensorInfo>,
) -> Result<SafetensorsShard, String> {
let file = OpenOptions::new()
.read(true)
.open(&path)
.open(path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
@@ -151,53 +205,11 @@ impl SafetensorsArchive {
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
TensorInfo { shard_idx, dtype, shape, begin, end },
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
}
Ok(Self { dir, shards, tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
Ok(SafetensorsShard { path: path.to_path_buf(), file, file_size, data_start })
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
+146 -19
View File
@@ -13,7 +13,7 @@ pub fn load_raw(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf, String
let bytes = info.byte_len() as usize;
let mut host = vec![0u8; bytes];
ar.read_slice(name, 0, &mut host)?;
let buf = DeviceBuf::alloc(bytes)?;
let buf = DeviceBuf::alloc_unpooled(bytes)?;
buf.h2d_bytes(&host)?;
Ok(buf)
}
@@ -29,7 +29,7 @@ pub fn load_bf16_as_f32(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf
let mut host = vec![0u8; bytes];
ar.read_slice(name, 0, &mut host)?;
let f: Vec<f32> = host.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
let buf = DeviceBuf::alloc(f.len() * 4)?;
let buf = DeviceBuf::alloc_unpooled(f.len() * 4)?;
buf.h2d(&f)?;
Ok(buf)
}
@@ -70,8 +70,8 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
let mut sbytes = vec![0u8; s_per_e];
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?;
let packed = DeviceBuf::alloc_unpooled(w_per_e)?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc_unpooled(s_per_e)?; scales.h2d_bytes(&sbytes)?;
return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true });
}
@@ -99,9 +99,9 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
};
let outer = amax / den;
let packed = DeviceBuf::alloc(w_per_e)?;
let packed = DeviceBuf::alloc_unpooled(w_per_e)?;
packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?;
let scales = DeviceBuf::alloc_unpooled(s_per_e)?;
scales.h2d_bytes(&sbytes)?;
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
}
@@ -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)]
mod tests {
use super::*;
@@ -138,7 +233,7 @@ mod tests {
#[test]
#[ignore] // requires GPU + --features hip + /mnt/models/Inkling
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 vocab = 201024usize;
let token_id = 100i32;
@@ -200,7 +295,7 @@ mod tests {
#[test]
#[ignore]
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 (n, k) = (em.n as usize, em.k as usize);
assert_eq!((n, k), (2304, 2304));
@@ -259,7 +354,7 @@ mod tests {
#[test]
#[ignore]
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 (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();
@@ -309,7 +404,7 @@ mod tests {
#[test]
#[ignore]
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();
assert!(em.mxfp8, "layer 20 must be MXFP8");
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}");
}
/// 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 rms_norm_cpu(x: &[f32], w: &[f32], eps: f32) -> Vec<f32> {
let d = x.len();
@@ -397,7 +524,7 @@ mod tests {
#[test]
#[ignore]
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 route_scale = 8.0f32;
let (beta, lb) = (4.0f32, 25.0f32);
@@ -524,7 +651,7 @@ mod tests {
#[test]
#[ignore]
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 (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);
@@ -699,7 +826,7 @@ mod tests {
#[test]
#[ignore]
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 (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);
@@ -713,10 +840,10 @@ mod tests {
// === 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 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 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();
assert_eq!(blocks.len(), 1, "ip=0 must snapshot one depth block");
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
@@ -822,7 +949,7 @@ mod tests {
#[test]
#[ignore]
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 p = format!("model.llm.layers.{ip}.attn");
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 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 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 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();
let mut got = vec![0f32; hidden]; cur.d2h(&mut got).unwrap();
// CPU oracle
@@ -931,7 +1058,7 @@ mod tests {
#[test]
#[ignore]
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 p = format!("model.llm.layers.{ip}.attn");
let l = format!("model.llm.layers.{ip}");
+109 -27
View File
@@ -71,39 +71,118 @@ Five ideas explain almost everything that will surprise you:
## Current state (honest)
- **CPU planning pipeline: complete and live-verified.** Inkling config →
total tensor classification (1244/1244) → canonical IR → physical schedule
(looped core unrolled to 48 steps) → a full base decode graph (675 ops) that
passes the Lean-proven arena validator.
- **GPU execution: begun.** Three kernels verified on the real `gfx1150`
(embed_bf16 exact, gemm_bf16 exact, rms_norm ~1e-6 relative error). The
hipcc → static-lib → FFI → launch → parity pipeline works end-to-end.
- **No token generated yet.** The engine does not currently run inference. The
GPU execution half (remaining kernels + executor + packer + serve wiring) is
the work in progress. Do not mistake the validated *plan* for a running
*engine*.
- **The engine runs real inference, end-to-end, and it is correct.** The full
48-visit Inkling-2-Mini forward (prelude + looped core ×3 passes with bank
rollback + coda + final depth-mix/softcap) runs on the real `gfx1150` weights.
Greedy decoding is **EXACT multi-token parity** against the hardened `strata`
reference (16 and 40 tokens, F32 and FP16 KV). The two root causes of the old
token-2+ gap were structural, not precision: per-pass KV pools and the
unpadded logit vocab (200058).
- **Linked to the agent framework.** `strata-ctl --serve` spawns `vetta-infer`
and serves its OpenAI-compatible API; the wire protocol (READY/INFO/T/PP/
RESUME/DONE/ERR) is field-for-field compatible. Verified live: capital queries,
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 destination: a working, measured inference engine that the agent framework
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
graph: the learned attention-residual block-mix, loop controllers, ShortConv4,
relative-position bias, sliding-window attention, paged KV. (Blueprint:
`docs/inkling-forward-design.md`.)
2. **Remaining kernels** — flash attention (GQA, SWA, split-KV), MoE NVFP4
routing + experts + reduce, RoPE/KV-write, penalties/top-k. Each
parity-verified before use.
3. **Executor (`rt`)** — lower the `CompiledPlan` to kernel launches, UMA arena
broker, KV-cache management.
4. **BackendPacker + `.vbundle`** — weights → device, the real bundle build.
5. **Serve wiring** — connect the (already proven) serve-session FSM to real
generation and to `vetta-agents` over the line protocol. **First chat.**
6. **M2 performance** — WMMA tiling, expert residency/streaming, measured
tok/s against the reference.
7. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
1. **Inkling graph parity** — ✅ landed (attention-residual block-mix, loop
controllers, ShortConv4, relative-position bias, sliding-window attention,
per-pass KV). Blueprint: `docs/inkling-forward-design.md`.
2. **Remaining kernels** — ✅ landed (flash GQA/SWA, MoE NVFP4/MXFP8 routing +
experts + reduce, KV-write, L2-clip, relpos). Each parity-verified.
3. **Executor** — ✅ landed (full 48-visit forward on real weights).
4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load).
5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity,
first real GUI conversation 2026-12-01).
6. **M2 performance** — ⏳ prefix checkpoint cache ✅ (multi-turn reuse, EXACT,
57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense +
flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp
✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU).
7. **Drafter + DMA layer streaming** — ⏳ DSpark speculative drafter ✅ landed
(`13.93 tok/s` on Rust coding, 2.04× vs OFF, matching `strata-inkling`); next is
layer streaming in DMA (`io_uring O_DIRECT` + `hipHostRegister` SlabRing,
Hot/Cold expert cache + lookahead prefetch) — the hard memory frontier.
8. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
domain-aware expert prefetch.
## How to verify
@@ -117,6 +196,9 @@ lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean
lean proofs/arena_plan.lean
lean proofs/inkling_loop.lean
lean proofs/prefix_cache.lean
lean proofs/speculative_draft.lean
# Opt-in live tests against the real Inkling artifact:
cargo test -p vetta-infer-ld -- --ignored inkling
+20 -3
View File
@@ -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);
// 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_free(void* p);
int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
int vetta_buf_d2h(void* dst, const void* src, size_t bytes);
// Device-to-device copies (legacy/internal).
int vetta_buf_copy(void* dst, const void* src, size_t bytes);
int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src, size_t spitch,
size_t width, size_t height);
// Pinned host RAM lifecycle + async D2H/H2D copies for zero-VRAM PrefixCache
// checkpoints (hipHostMallocDefault / hipHostFree with stream sync on free).
int vetta_host_alloc(void** out, size_t bytes);
int vetta_host_free(void* p);
int vetta_buf_d2h_async(void* dst_host, const void* src_dev, size_t bytes);
int vetta_buf_h2d_async(void* dst_dev, const void* src_host, size_t bytes);
int vetta_buf_copy2d_d2h_async(void* dst_host, size_t dpitch, const void* src_dev,
size_t spitch, size_t width, size_t height);
int vetta_buf_copy2d_h2d_async(void* dst_dev, size_t dpitch, const void* src_host,
size_t spitch, size_t width, size_t height);
// k_rms_norm (kernel #2): y[row] = x[row] * rsqrt(mean(x^2)+eps) * w.
int vetta_rms_norm_f32(const float* x, const float* w, float* y,
@@ -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,
const float* rel_bias, int max_rel,
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).
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,
const float* rel_bias, int max_rel,
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).
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).
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.
int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias,
File diff suppressed because it is too large. Load diff
+387
View File
@@ -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
+108
View File
@@ -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`).