Compare commits

...
60 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
17 changed files with 8505 additions and 387 deletions

No files matched your search

+9 -2
View File
@@ -39,19 +39,26 @@ Built from the measured hardware physics and engineering lessons of our hardened
- **M0.5 (Architecture realignment — done):** approved microkernel design fixed in `docs/ARCHITECTURE.md`; crates realigned to `vetta-infer-*` (abi/kn/ld/cc/rt/lab/sp/nt/tm/gw); bus lifecycle Lean-verified (`bus_lifecycle.lean`); faithful Adaptive-K port; `strata-ctl` wire emitters + `image=` key.
- **M1 (Resident MoE End-to-End — Target 1: `Inkling-2-Mini`, inference landed):** full 48-visit forward on real `gfx1150` weights, **EXACT multi-token greedy parity** vs the `strata` reference (per-pass KV pools + unpadded vocab 200058), `strata-ctl` drop-in `--serve` link (OpenAI-compatible API, field-for-field wire). Serve-session FSM (`serve_session.lean`), arena safety (`arena_plan.lean` + `abi::arena`), `.vbundle` contract (`abi::bundle` + `ld::bundle`), loop proof (`inkling_loop.lean`). Speed vs C++ baseline (`>= 18 tok/s`, `< 4 s` reload) is the remaining M2 work.
- **🎉 First real interactive GUI conversation — 2026-12-01 (measured):** via the `strata-ctl` web GUI on Sogliola, *"Ciao, sono Federico"* → *"Ciao Federico! Piacere di conoscerti. Come posso aiutarti oggi?"* — **2650 prompt + 53 completion tokens · 4.2 tok/s decode · first token 618 s** (the 618 s is sequential prefill of the ~2650-token agent prompt, ~140 ms/token; decode ~4.2 tok/s). Host-CPU busy-wait eliminated via `hipDeviceScheduleBlockingSync` (measured A/B 101.2% → 54.2%); the residual ~54% is kernel-launch cost, removed by HIP graph capture (M2).
- **⚡ Prefill batched + tensor-core — 2026-12-02 (measured):** chunked batched forward (M=B) + FP16 WMMA grouped MoE + BF16 WMMA dense projections + FlashAttention-2 WMMA prefill (P staged in LDS, no global scores scratch). Synthetic 2048-token prefill on `gfx1150` (FP16 KV, chunk 256): **60 s → 12.9 s (-78%)**, ~6.3 ms/token (a 16 k-token agent prompt ~105 s, was ~7 min). Greedy-vs-reference stays EXACT (blocking gate); internal M=1-vs-M=B parity relaxed to a global-scale tolerance (approved P1 policy). The 618 s first-token above is historical (sequential prefill).
- **🧠 Flat VRAM + pinned host checkpoints + long-prompt clamp — 2026-12-02 (measured):** persistent per-layer KV/ShortConv states (40 SWA pools on 1280-slot rings + 8 Global pools), DSpark SWA layers 0/2 on 1280-slot rings (-258 MiB VRAM at 32k), and **zero-VRAM `PrefixCache` checkpoints** (`LayerSnapshot` + `DsparkSnapshot` stored in page-locked host RAM via `PinnedBuf`/`hipHostMallocDefault`, pipelined async SDMA on stream 0; `PinnedBuf` 64 MiB VRAM delta = `+0.00 MiB`, 4-turn multi-checkpoint test up to 2100 tokens with 8 full checkpoints + `VETTA_SPEC=1` stays completely flat at `20,674 → 20,672 → 20,676 → 20,676 MiB`, delta `+2.00 MiB`). Generation budget clamped to the window (`clamp_max_new`) instead of hard-erroring past 16382 prompt tokens with strata-ctl's fixed max_new=16384; window configurable via `serve --max-context N`. Verified live: a 16504-token prompt generates (was ERR 0 tokens).
- **🚀 DSpark speculative drafter (opt-in `VETTA_SPEC=1`, 100% GPU) — 2026-12-02 (measured):** single-pass base-unembed Top-512 screen + on-GPU Markov head + GPU verify argmax (`<=32 B` D2H), 0-LDS Wave32 online-softmax block attention (safe past 16k+ context), M-tiled Wave32 BF16 router GEMV, zero-scratch small-M SWA GQA, `PrefixCache` `DsparkSnapshot` save/restore for multi-turn, and accepted-count EMA governor (`n_draft` starts at 5, adapts 2..7). Lossless contract proven in `proofs/speculative_draft.lean` (200-token `spec_lossless_gate` EXACT + multi-turn `RESUME` EXACT). Measured on `gfx1150` (`Inkling-2-Mini`, `temperature=0`):
- **Rust coding prompt (`RingBuffer<T>`, 128 tok):** OFF **`6.83 tok/s`** → `VETTA_SPEC=1` **`13.93 tok/s`** (**2.04×**, `n_draft=5`, 100% EXACT — matching/edging `strata-inkling --draft dspark` at `13.66 tok/s`).
- **Short prose prompt (`"The capital of France is"`, 96 tok):** `nd=5` **`4.58 → 9.09 tok/s`** (**+98.5%**); adaptive EMA **`8.93 tok/s`** decode.
- **M1.5 (Embedder lane — BGE-M3):** native encoder forward-pass (LayerNorm, bidirectional full-attn, GELU-erf, CLS pooling + L2 — recipe declared in the manifest), XLM-R importer, SPM tokenizer, `vetta-infer embed` wire; acceptance cosine ≥ 0.999 vs the live `vetta-semantics` oracle (`:8091`) + publisher fixture + anisotropy canary. Optional reranker head. May double as the HIP kernel bring-up bench.
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** DSpark drafter ✅ landed; next is layer streaming in DMA — the hard memory frontier: Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
## Quick Verification
```sh
# Lean 4 formal proofs (0 sorryAx, 5 files)
# Lean 4 formal proofs (0 sorryAx, 7 files)
lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean
lean proofs/arena_plan.lean
lean proofs/inkling_loop.lean
lean proofs/prefix_cache.lean
lean proofs/speculative_draft.lean
# Pure-Rust workspace tests (no GPU required)
cargo test --workspace
+8 -1
View File
@@ -11,7 +11,7 @@ fn usage() {
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)");
eprintln!(" vetta-infer serve <safetensors-dir> Resident GEN/STOP/QUIT wire service (GPU, --features hip)");
eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it)");
eprintln!(" (alias: --serve <dir>, as strata-ctl spawns it; [--max-context N])");
eprintln!(" vetta-infer chat <dir> [effort] [max_new] Interactive multi-turn chat (GPU, --features hip)");
eprintln!(" vetta-infer version Print version & build info");
}
@@ -101,6 +101,13 @@ fn main() -> ExitCode {
usage();
return ExitCode::from(2);
};
// Optional resident window override (like strata --max-context):
// `serve <dir> --max-context N`. Defaults to 32768 when absent.
if let Some(i) = args.iter().position(|a| a == "--max-context") {
if let Some(v) = args.get(i + 1).and_then(|s| s.parse::<usize>().ok()) {
unsafe { std::env::set_var("VETTA_MAX_CONTEXT", v.to_string()) };
}
}
#[cfg(feature = "hip")]
{
match vetta_infer_gw::serve::run_serve(dir) {
+637 -73
View File
@@ -27,8 +27,12 @@ use vetta_infer_abi::sampler::{
use vetta_infer_abi::serve::{parse_serve_line, ParsedGen, ServeCommand};
use vetta_infer_hip::DeviceBuf;
use vetta_infer_ld::inkling::parse_config;
use vetta_infer_ld::layer::{forward_inkling_with_state, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, is_swa, new_state, Dims, LayerSnapshot, LayerState, WeightCache};
use vetta_infer_ld::SafetensorsArchive;
#[cfg(feature = "hip")]
use vetta_infer_ld::layer::forward_batch_taps;
#[cfg(feature = "hip")]
use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkSnapshot, DsparkWeights, DS_HIDDEN};
use crate::session::ServeSession;
use crate::{err_line, ready_line};
@@ -51,17 +55,33 @@ const SITU_LB: f32 = 25.0;
/// not limited by the 64 KB LDS cap.
const MAX_CONTEXT: usize = 32768;
/// Clamp the generation budget to the resident window instead of hard-erroring.
/// strata-ctl always sends the default budget max_new=16384, so a prompt longer
/// than MAX_CONTEXT-16386 (e.g. 16504/16686 seen live) must still run with a
/// reduced budget rather than return 0 tokens and kill the agent mid-window.
/// `None` = the prompt itself no longer fits (true overflow, hard error).
fn clamp_max_new(n_prompt: usize, max_new: usize, max_context: usize) -> Option<usize> {
if n_prompt + 2 >= max_context { return None; }
Some(max_new.min(max_context - n_prompt - 2))
}
/// Prefix checkpoint cache (concept ported from strata `--auto-ckpt`, verified in
/// proofs/prefix_cache.lean). Keeps snapshots of KV+ShortConv at prefix boundaries
/// so a new request whose prompt extends a cached prefix restores it and prefills
/// only the NEW tokens (restore_equiv: exact). Pinned anchors {512,1024} are never
/// evicted (I3); otherwise LRU eviction at the cap.
const PREFIX_CACHE_CAP: usize = 6;
const PREFIX_CACHE_CAP: usize = 8;
fn pinned_anchor(seq: usize) -> bool { seq == 512 || seq == 1024 }
/// Grid checkpoints (multiples of 512) are the STABLE prefixes that survive the
/// turn-tag tail divergence; boundary/full-sequence checkpoints rarely hit again.
/// Eviction prefers dropping non-grid entries so the useful grid is protected.
fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
struct Checkpoint {
tokens: Vec<i32>,
layers: Vec<Option<LayerSnapshot>>,
#[cfg(feature = "hip")]
dspark: Option<DsparkSnapshot>,
lru: u64,
}
@@ -92,46 +112,89 @@ impl PrefixCache {
}
/// Allocate + restore every checkpointed layer into `states` at `max_seq`.
fn restore(&self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
let ck = &self.pool[idx];
// A usable checkpoint must cover EVERY layer: a partially-restored state
// would cold-start the missing layers and break prefix equivalence.
if ck.layers.len() != states.len() || ck.layers.iter().any(|s| s.is_none()) {
return Err("incomplete prefix checkpoint".into());
}
for (ip, snap) in ck.layers.iter().enumerate() {
if let Some(s) = snap {
let mut st = new_state(d, max_seq, s.k_cache.len())?;
st.restore(d, s)?;
states[ip] = Some(st);
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a
/// just-restored grid checkpoint keeps its old tick and gets evicted by the
/// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor.
/// Returns `(restored_len, dspark_restored)`.
fn restore(
&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize,
#[cfg(feature = "hip")] dctx: Option<&mut DsparkContext>,
) -> Result<(usize, bool), String> {
let mut dspark_ok = false;
{
let ck = &self.pool[idx];
// A usable checkpoint must cover EVERY layer: a partially-restored state
// would cold-start the missing layers and break prefix equivalence.
if ck.layers.len() != states.len() || ck.layers.iter().any(|s| s.is_none()) {
return Err("incomplete prefix checkpoint".into());
}
for (ip, snap) in ck.layers.iter().enumerate() {
if let Some(s) = snap {
// Reuse the persistent state when it is already sized for this
// request (same cap + pass count); restore overwrites its KV
// prefix + hist rings. The stale KV tail beyond seq_len is never
// read (causal attention), so reuse is exact (restore_equiv).
let want = if is_swa(ip) { vetta_infer_ld::layer::swa_ring(d) } else { max_seq };
let reuse = states[ip].as_ref()
.map_or(false, |st| st.max_seq == want && st.k_cache.len() == s.k_cache.len());
if !reuse {
states[ip] = Some(new_state(d, want, s.k_cache.len())?);
}
states[ip].as_mut().unwrap().restore(d, s)?;
}
}
#[cfg(feature = "hip")]
if let (Some(dc), Some(ds)) = (dctx, ck.dspark.as_ref()) {
dc.restore(ds)?;
dspark_ok = true;
}
}
Ok(ck.tokens.len())
self.tick += 1;
self.pool[idx].lru = self.tick;
Ok((self.pool[idx].tokens.len(), dspark_ok))
}
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
/// evict oldest unpinned). Mirrors poolInsert in proofs/prefix_cache.lean.
fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> {
/// Snapshot all layer states (and optional DSpark context) at `tokens.len()`
/// and insert (update / grow / evict oldest unpinned). Mirrors poolInsert in
/// proofs/prefix_cache.lean.
fn save(
&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims,
#[cfg(feature = "hip")] dctx: Option<&DsparkContext>,
) -> Result<(), String> {
let seq = tokens.len();
if seq == 0 { return Ok(()); }
let layers: Vec<Option<LayerSnapshot>> = states.iter()
.map(|st| st.as_ref().map(|s| s.snapshot(d, seq)).transpose())
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
.collect::<Result<_, _>>()?;
#[cfg(feature = "hip")]
let dspark = match dctx {
Some(dc) if dc.len >= seq => Some(dc.snapshot(seq, d.swa_win as usize)?),
_ => None,
};
self.tick += 1;
let lru = self.tick;
if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) {
ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru;
#[cfg(feature = "hip")] { ck.dspark = dspark; }
return Ok(());
}
if self.pool.len() < PREFIX_CACHE_CAP {
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
self.pool.push(Checkpoint {
tokens: tokens.to_vec(), layers,
#[cfg(feature = "hip")] dspark,
lru,
});
return Ok(());
}
let victim = self.pool.iter().enumerate()
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
.min_by_key(|(_, c)| c.lru).map(|(i, _)| i);
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
if let Some(i) = victim {
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
self.pool[i] = Checkpoint {
tokens: tokens.to_vec(), layers,
#[cfg(feature = "hip")] dspark,
lru,
};
}
Ok(())
}
@@ -139,13 +202,27 @@ impl PrefixCache {
/// A loaded Inkling model ready to run autoregressive forwards.
pub struct InklingEngine {
ar: SafetensorsArchive,
cache: WeightCache,
d: Dims,
vocab: usize,
n_layers: usize,
eos: i32,
cap: f32,
prefix: RefCell<PrefixCache>,
/// Persistent per-layer KV/ShortConv states reused across requests, sized to
/// `states_cap` (a 4096-bucket >= prompt+max_new). Eliminates the per-request
/// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket.
states: RefCell<Vec<Option<LayerState>>>,
/// Resident context window (advertised in READY). Defaults to MAX_CONTEXT;
/// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents.
max_context: usize,
/// DSpark drafter weights (resident), loaded only when VETTA_SPEC=1 and
/// mtp.safetensors passes layout_check. Enables opt-in greedy speculation.
#[cfg(feature = "hip")]
spec_dw: Option<DsparkWeights>,
/// Persistent DSpark context rings reused across requests (mirrors `states`).
#[cfg(feature = "hip")]
dctx: RefCell<Option<DsparkContext>>,
}
impl InklingEngine {
@@ -155,7 +232,11 @@ impl InklingEngine {
// half the VRAM of the F32 CPU-oracle baseline). The ld parity tests keep
// the F32 default; the resident serve opts in here.
vetta_infer_ld::layer::set_kv_f16(true);
let ar = SafetensorsArchive::open(dir)?;
// Batched prefill uses the device-resident f16 MoE (moe_batched). Align the
// M=1 decode to the same f16 device path (moe_device, bit-identical math) so
// prefill and decode share one expert precision (verified EXACT greedy).
unsafe { std::env::set_var("VETTA_DEVICE_MOE", "1") };
let ar = Arc::new(SafetensorsArchive::open(dir)?);
let cfg_path = ar.dir.join("config.json");
let raw = std::fs::read_to_string(&cfg_path)
.map_err(|e| format!("read {}: {e}", cfg_path.display()))?;
@@ -180,8 +261,22 @@ impl InklingEngine {
lb: SITU_LB,
swa_win: t.swa_win as i32,
};
let max_context = std::env::var("VETTA_MAX_CONTEXT").ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|&v| v >= 4096)
.unwrap_or(MAX_CONTEXT);
// Opt-in DSpark drafter: load resident weights iff VETTA_SPEC=1 and the
// mtp shard passes the strict layout check (else disable, never guess).
#[cfg(feature = "hip")]
let spec_dw = if std::env::var("VETTA_SPEC").is_ok() {
let mtp = ar.dir.join("mtp.safetensors");
match SafetensorsArchive::open_file(mtp.to_str().unwrap_or_default()) {
Ok(mar) if layout_check(&mar).is_ok() => DsparkWeights::load(&mar).ok(),
_ => None,
}
} else { None };
Ok(Self {
ar,
cache: WeightCache::new(ar),
d,
// The served/logit vocab is the UNPADDED size (exact strata
// k_unembed_softcap V = vocab_unpadded): rows >= unpadded are padding
@@ -192,6 +287,12 @@ impl InklingEngine {
eos: cfg.eos_token_id as i32,
cap: t.final_logit_softcapping as f32,
prefix: RefCell::new(PrefixCache::new()),
states: RefCell::new(Vec::new()),
max_context,
#[cfg(feature = "hip")]
spec_dw,
#[cfg(feature = "hip")]
dctx: RefCell::new(None),
})
}
@@ -199,21 +300,40 @@ impl InklingEngine {
self.vocab
}
fn fresh_states(&self, _max_seq: usize) -> Result<Vec<Option<LayerState>>, String> {
// States are allocated lazily per layer by run_layer; start all None.
Ok((0..self.n_layers).map(|_| None).collect())
pub fn max_context(&self) -> usize {
self.max_context
}
fn forward(
&self,
cache: &WeightCache,
token: i32,
pos: i32,
max_seq: usize,
states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
forward_inkling_with_state(cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
forward_inkling_with_state(&self.cache, &self.d, token, self.vocab, max_seq, pos, self.cap, states)
}
/// Batched prefill chunk (M=B): one forward over B tokens, logits for the last.
fn forward_batched(
&self,
tokens: &[i32],
pos: i32,
max_seq: usize,
states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
forward_batch(&self.cache, &self.d, tokens, self.vocab, max_seq, pos, self.cap, states)
}
}
/// Prefill chunk size (M=B per batched forward). Default 256 amortizes weight
/// streaming + kernel launches across 256 tokens vs the old M=1 per-token path.
/// VETTA_PREFILL_CHUNK overrides; 1 forces the sequential path (A/B parity).
fn prefill_chunk_size() -> usize {
std::env::var("VETTA_PREFILL_CHUNK").ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|&c| c >= 1)
.unwrap_or(256)
}
fn emit_all(emit: &mut dyn FnMut(String), lines: Vec<String>) {
@@ -242,49 +362,130 @@ pub fn serve_gen(
}
let n_prompt = g.ids.len();
let max_seq = (n_prompt + g.max_new + 2).min(MAX_CONTEXT);
if n_prompt + g.max_new + 2 > MAX_CONTEXT {
emit_all(emit, sess.on_error("prompt + max_new exceeds context window"));
let max_context = eng.max_context();
// Clamp the budget to the window (reviewer 2026-12-02): only a prompt that
// itself overflows is a hard error; otherwise generate up to the room left.
let Some(effective_max_new) = clamp_max_new(n_prompt, g.max_new, max_context) else {
emit_all(emit, sess.on_error("prompt exceeds context window"));
return;
}
let mut states = match eng.fresh_states(max_seq) {
Ok(s) => s,
Err(e) => {
emit_all(emit, sess.on_error(&e));
return;
}
};
// KV capacities are FIXED per layer kind (SWA ring = swa_win+chunk_cap, global
// = max_context), allocated once and never resized across requests: no
// drop+realloc when a session crosses a 4096 multiple (reviewer punto 2).
if eng.states.borrow().len() != eng.n_layers {
*eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
}
let cap = max_context;
let mut states = eng.states.borrow_mut();
// Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps
// during prefill to build the drafter context rings, then run a batched
// speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft).
#[cfg(feature = "hip")]
let mut spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties();
#[cfg(not(feature = "hip"))]
let spec_enabled = false;
#[cfg(feature = "hip")]
let mut dctx_guard = eng.dctx.borrow_mut();
#[cfg(feature = "hip")]
if spec_enabled {
let need_new = dctx_guard.as_ref().map_or(true, |c| c.cap < cap);
if need_new {
match DsparkContext::new(cap, DS_HIDDEN) {
Ok(c) => *dctx_guard = Some(c),
Err(e) => {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
}
}
}
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
// the longest cached strict prefix of this prompt and prefill only the NEW
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
let mut start = 0usize;
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
if let Some((idx, _l)) = eng.prefix.borrow().best_match(&g.ids) {
match eng.prefix.borrow().restore(idx, &mut states, &eng.d, max_seq) {
Ok(n) => start = n,
let matched = eng.prefix.borrow().best_match(&g.ids);
if let Some((idx, _l)) = matched {
#[cfg(feature = "hip")]
let res = eng.prefix.borrow_mut().restore(
idx, &mut states[..], &eng.d, cap,
if spec_enabled { dctx_guard.as_mut() } else { None },
);
#[cfg(not(feature = "hip"))]
let res = eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap);
match res {
Ok((n, dspark_ok)) => {
start = n;
#[cfg(feature = "hip")]
if spec_enabled && !dspark_ok {
// Checkpoint lacked DSpark state (e.g. saved while spec was off):
// never run the drafter over zeroed prefix rings.
spec_enabled = false;
}
#[cfg(not(feature = "hip"))]
let _ = dspark_ok;
}
Err(_) => {
// Incomplete/failed restore: fall back to a clean cold prefill.
states = match eng.fresh_states(max_seq) {
Ok(s) => s,
Err(e) => { emit_all(emit, sess.on_error(&e)); return; }
};
*states = (0..eng.n_layers).map(|_| None).collect();
}
}
}
}
// Cold request (no prefix restored): the persistent states carry the previous
// conversation's ShortConv history. Reset the hist rings (the KV prefix is
// overwritten by prefill before any causal read) so a fresh conversation starts
// empty. A restored request instead overwrites hist via the checkpoint.
if start == 0 {
for st in states.iter_mut().flatten() {
if let Err(e) = st.reset_history() {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
}
#[cfg(feature = "hip")]
if let Some(dc) = dctx_guard.as_mut() {
dc.len = 0;
}
}
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
if start == 0 {
// No match: show each cached checkpoint's length and how many leading
// tokens it shares with this prompt, to pinpoint a token divergence
// (common < len => the re-rendered prompt differs at that position).
let p = eng.prefix.borrow();
for (i, ck) in p.pool.iter().enumerate() {
let common = ck.tokens.iter().zip(g.ids.iter()).take_while(|(a, b)| a == b).count();
eprintln!("[prefix] ck[{i}] len={} common_prefix={common}", ck.tokens.len());
}
}
}
// Resident weight cache for this request: weights upload once and stay on
// the GPU across prefill + decode (no per-token NVMe expert re-reads).
let cache = WeightCache::new(&eng.ar);
// Weights are resident in eng.cache (loaded once at boot, reused across all
// requests): no per-request NVMe re-read or re-upload.
// --- Prefill: run the forward over the NEW prompt tokens, growing KV/history. ---
// --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. ---
// Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel
// launches amortized across B), growing KV/history; logits come from the last
// token of the final chunk. VETTA_PREFILL_CHUNK=1 restores the M=1 path (A/B).
let t0 = Instant::now();
let mut pos = start as i32;
let mut history: Vec<i32> = g.ids[..start].to_vec();
history.reserve(n_prompt - start + g.max_new);
history.reserve(n_prompt - start + effective_max_new);
let mut logits: Option<DeviceBuf> = None;
for (i, &tok) in g.ids.iter().enumerate().skip(start) {
let chunk = prefill_chunk_size().min(vetta_infer_ld::layer::SWA_CHUNK_CAP);
let suffix = &g.ids[start..];
let mut done = 0usize;
// Monotonic 512-grid threshold: split a chunk exactly on the next grid boundary
// so a checkpoint always lands on every multiple of 512 regardless of `start`
// (pos % 512 == 0 would miss boundaries when start/suffix aren't aligned).
let mut next_grid = ((start / 512) + 1) * 512;
while done < suffix.len() {
if stop.load(Ordering::Relaxed) {
sess.on_stop();
let ms = t0.elapsed().as_secs_f64() * 1000.0;
@@ -292,24 +493,72 @@ pub fn serve_gen(
stop.store(false, Ordering::Relaxed);
return;
}
match eng.forward(&cache, tok, pos, max_seq, &mut states) {
Ok(lg) => logits = Some(lg),
let mut take = chunk.min(suffix.len() - done);
let pos_now = start + done;
if pos_now < next_grid && pos_now + take > next_grid {
take = next_grid - pos_now;
}
let toks = &suffix[done..done + take];
let lg = if spec_enabled {
#[cfg(feature = "hip")]
{
(|| -> Result<DeviceBuf, String> {
let h = eng.d.hidden;
let mut taps = [DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?];
let l = forward_batch_taps(&eng.cache, &eng.d, toks, eng.vocab, cap, pos, eng.cap, &mut states[..], &mut taps)?;
let pb = DeviceBuf::alloc(take * 4)?;
pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
let dw = eng.spec_dw.as_ref().unwrap();
let dc = dctx_guard.as_mut().unwrap();
dc.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?;
dc.len = (pos + take as i32) as usize;
Ok(l)
})()
}
#[cfg(not(feature = "hip"))]
{ Err("spec requires hip".into()) }
} else if take == 1 {
eng.forward(toks[0], pos, cap, &mut states[..])
} else {
eng.forward_batched(toks, pos, cap, &mut states[..])
};
match lg {
Ok(l) => logits = Some(l),
Err(e) => {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
}
history.push(tok);
pos += 1;
history.extend_from_slice(toks);
pos += take as i32;
done += take;
// Multi-level checkpoint grid (strata --auto-ckpt): save an intermediate
// checkpoint on every 512 boundary so the next turn can restore a stable
// prefix even when the prompt's trailing turn-tag tokens re-render
// differently. best_match picks the longest grid checkpoint that is a full
// prefix; grid entries are protected from eviction (is_grid) and refreshed
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid {
#[cfg(feature = "hip")]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
#[cfg(not(feature = "hip"))]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] grid save seq={pos}");
}
next_grid += 512;
}
let ms = t0.elapsed().as_secs_f64() * 1000.0;
if let Ok(pp) = sess.on_prefill_chunk((i + 1) as u32, n_prompt as u32, ms) {
if let Ok(pp) = sess.on_prefill_chunk((start + done) as u32, n_prompt as u32, ms) {
emit_all(emit, pp);
}
}
let prompt_ms = t0.elapsed().as_secs_f64() * 1000.0;
// GEN 0 pre-warm: on_prefill_complete emits DONE directly (never decodes).
match sess.on_prefill_complete(0, prompt_ms) {
// `start` is the restored prefix length: >0 emits RESUME <start> (wire-compatible
// with strata, so strata-ctl reports the reused/cached prompt tokens).
match sess.on_prefill_complete(start as u32, prompt_ms) {
Ok(lines) => emit_all(emit, lines),
Err(e) => {
emit_all(emit, sess.on_error(&e));
@@ -317,11 +566,23 @@ pub fn serve_gen(
return;
}
}
if g.max_new == 0 {
// Pre-warm folded the full prompt into `states`: checkpoint it for reuse.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
// Checkpoint the PROMPT boundary. This is the prefix that stays token-identical
// across turns: strata-ctl re-renders the same system+history text each turn,
// while the assistant reply round-trips through detokenize/re-encode (special
// tokens stripped) and is NOT token-identical to the generated ids. Saving here
// — not only at the post-decode `pos` — is what lets the next turn restore the
// stable prefix and prefill only the new dialogue suffix. Mirrors strata
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
#[cfg(feature = "hip")]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
#[cfg(not(feature = "hip"))]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt-boundary save seq={pos}");
}
}
if effective_max_new == 0 {
stop.store(false, Ordering::Relaxed);
return;
}
@@ -339,8 +600,108 @@ pub fn serve_gen(
return;
}
};
// --- Opt-in DSpark speculative decode (greedy, lossless vs batched B=1). ---
#[cfg(feature = "hip")]
if spec_enabled {
let dw = eng.spec_dw.as_ref().unwrap();
let dc = dctx_guard.as_mut().unwrap();
let t1 = Instant::now();
let mut lg = vec![0f32; eng.vocab];
if let Err(e) = logits.d2h(&mut lg) {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
let argmax = |v: &[f32]| -> i32 {
let mut best = 0usize; let mut bz = f32::NEG_INFINITY;
for (i, &z) in v.iter().enumerate() { if z > bz { bz = z; best = i; } }
best as i32
};
let tok0 = argmax(&lg);
let mut finish = "length";
let mut generated = 0usize;
let emit_tok = |t: i32, emit: &mut dyn FnMut(String), sess: &mut ServeSession, history: &mut Vec<i32>, generated: &mut usize| -> bool {
match sess.on_token(t as u32) {
Ok(lines) => emit_all(emit, lines),
Err(e) => { emit_all(emit, sess.on_error(&e)); return false; }
}
history.push(t); *generated += 1;
true
};
if !emit_tok(tok0, emit, &mut sess, &mut history, &mut generated) {
stop.store(false, Ordering::Relaxed);
return;
}
let mut cur_pos = pos; let mut next_tok = tok0;
// Measured on gfx1150 after single-pass GPU drafter + WMMA/fdot2 + small-M SWA:
// Rust coding prompt (128 tok): OFF 6.83 | nd=2 11.93 | nd=3 13.90 | nd=4 13.97 | nd=5 13.69 tok/s
// Short prose prompt (96 tok): OFF 4.70 | nd=2 9.21 | nd=3 9.09 | nd=4 8.93 | nd=5 9.09 tok/s
// Track an EMA of ACCEPTED tokens per round (not acceptance ratio, which
// naturally drops as nd grows and used to clamp code generation down to nd=2).
// Start at 5 (optimal on code/structured text) and adapt smoothly 2..7.
let mut ema_acc = 2.0f32; let mut n_draft = 5usize;
// VETTA_SPEC_ND fixes n_draft (bypasses the EMA) for A/B measurement.
let nd_override = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::<usize>().ok());
let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize;
if tok0 == eng.eos {
finish = "stop";
} else {
while generated < effective_max_new {
if stop.load(Ordering::Relaxed) {
sess.on_stop();
let ms = t1.elapsed().as_secs_f64() * 1000.0;
emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default());
stop.store(false, Ordering::Relaxed);
return;
}
let left = effective_max_new - generated;
let nd = nd_override.unwrap_or(n_draft).min(left.saturating_sub(1));
let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) {
Ok(v) => v,
Err(e) => {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
};
let mut hit_eos = false;
for &t in &em {
if !emit_tok(t, emit, &mut sess, &mut history, &mut generated) {
stop.store(false, Ordering::Relaxed);
return;
}
if t == eng.eos { hit_eos = true; break; }
if generated >= effective_max_new { break; }
}
if nd > 0 {
let acc = em.len().saturating_sub(1);
ema_acc = 0.85 * ema_acc + 0.15 * (acc as f32);
n_draft = if ema_acc >= 3.5 { 7 }
else if ema_acc >= 2.0 { 5 }
else if ema_acc >= 1.1 { 4 }
else if ema_acc >= 0.6 { 3 }
else { 2 };
offered += nd; accepted += acc;
}
rounds += 1;
cur_pos = nc; next_tok = nt; pos = nc;
if hit_eos { finish = "stop"; break; }
if done || generated >= effective_max_new { finish = "length"; break; }
}
}
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
if std::env::var("VETTA_DBG_SPEC").is_ok() {
eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema_acc={ema_acc:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0));
}
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, Some(dc));
}
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
stop.store(false, Ordering::Relaxed);
return;
}
let mut finish = "length";
for step in 0..g.max_new {
for step in 0..effective_max_new {
if stop.load(Ordering::Relaxed) {
sess.on_stop();
let ms = t1.elapsed().as_secs_f64() * 1000.0;
@@ -382,11 +743,11 @@ pub fn serve_gen(
break;
}
history.push(rep.token);
if step + 1 == g.max_new {
if step + 1 == effective_max_new {
finish = "length";
break;
}
match eng.forward(&cache, rep.token, pos, max_seq, &mut states) {
match eng.forward(rep.token, pos, cap, &mut states[..]) {
Ok(l) => logits = l,
Err(e) => {
emit_all(emit, sess.on_error(&e));
@@ -397,12 +758,19 @@ pub fn serve_gen(
pos += 1;
}
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
// Checkpoint the full processed prefix (prompt + generated tokens) so the next
// turn restores it and prefills only its new suffix. `pos` counts the tokens
// actually folded into `states` (history[..pos]); a sampled token that was not
// forwarded (EOS / last length step) is excluded, keeping the checkpoint valid.
// Also checkpoint the full processed sequence (prompt + generated tokens). This
// is a bonus reuse when the next prompt IS token-identical (e.g. a retry); the
// prompt-boundary checkpoint above is the robust one for normal chat. `pos`
// counts tokens actually folded into `states` (history[..pos]); a sampled token
// not forwarded (EOS / last length step) is excluded, keeping the ckpt valid.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states, &eng.d);
#[cfg(feature = "hip")]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, None);
#[cfg(not(feature = "hip"))]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] full-sequence save seq={pos}");
}
}
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
stop.store(false, Ordering::Relaxed);
@@ -421,6 +789,12 @@ enum Msg {
/// drains to DONE). One request at a time (FIFO), matching the consumer.
pub fn run_serve(dir: &str) -> Result<(), String> {
let eng = InklingEngine::new(dir)?;
// Default: eager full-model residency at boot — VRAM is populated immediately
// (like the reference) and no request pays NVMe reads/uploads. The cache is
// resident across requests either way. VETTA_LAZY_LOAD=1 defers to first use.
if std::env::var("VETTA_LAZY_LOAD").is_err() {
eng.cache.prewarm(&eng.d, eng.n_layers)?;
}
let vocab = eng.vocab();
let stop = Arc::new(AtomicBool::new(false));
let quit = Arc::new(AtomicBool::new(false));
@@ -467,7 +841,7 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
let _ = writeln!(out, "{line}");
let _ = out.flush();
};
emit(ready_line(MAX_CONTEXT as u32, true, false, false));
emit(ready_line(eng.max_context() as u32, true, false, false));
loop {
if quit.load(Ordering::Relaxed) {
@@ -492,6 +866,27 @@ pub fn run_serve(dir: &str) -> Result<(), String> {
mod tests {
use super::*;
/// CPU: the budget clamp must keep long agent prompts runnable (strata-ctl
/// always sends max_new=16384) instead of hard-erroring past 16382 tokens, and
/// only reject a prompt that itself overflows the window.
#[test]
fn clamp_max_new_budget() {
// live agent prompts 16504/16686 with the default 16384 budget: clamp, run.
assert_eq!(clamp_max_new(16504, 16384, 32768), Some(32768 - 16504 - 2));
assert_eq!(clamp_max_new(16686, 16384, 32768), Some(32768 - 16686 - 2));
// small prompt keeps the full budget.
assert_eq!(clamp_max_new(2648, 16384, 32768), Some(16384));
// exactly at the last usable prompt position: 1 token of room.
assert_eq!(clamp_max_new(32765, 16384, 32768), Some(1));
// prompt itself overflows: hard error (None).
assert_eq!(clamp_max_new(32766, 16384, 32768), None);
assert_eq!(clamp_max_new(40000, 16384, 32768), None);
// configurable larger window accepts the same long prompt unclamped.
assert_eq!(clamp_max_new(16504, 16384, 65536), Some(16384));
// GEN 0 pre-warm stays 0 regardless of prompt.
assert_eq!(clamp_max_new(2648, 0, 32768), Some(0));
}
/// GPU integration: drive `serve_gen` over the wire for the canonical prompt
/// "The capital of France is" (ids from the tokenizer) and check the emitted
/// lines: first `T` is 152717 (" Paris", exact reference match) and the
@@ -589,4 +984,173 @@ mod tests {
assert!(done.ends_with(" stop"), "finish must be stop, got {done}");
});
}
/// GPU: the opt-in DSpark speculative serve path (VETTA_SPEC=1, batched
/// verify + rollback + EMA) must emit EXACTLY the same reference tokens as
/// the default M=1 decode for the canonical capital prompt. Verifies the
/// serve orchestration (pos/history/EOS/length) AND that the batched decode
/// path is greedy-vs-reference exact.
#[test]
#[ignore]
fn serve_gen_spec_multi_token_parity() {
crate::gpu_isolated(|| {
unsafe { std::env::set_var("VETTA_SPEC", "1"); }
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
assert!(eng.spec_dw.is_some(), "drafter weights must load with VETTA_SPEC=1");
let g = match parse_serve_line("GEN 16 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let stop = AtomicBool::new(false);
let mut lines: Vec<String> = Vec::new();
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
let tokens: Vec<i32> = lines.iter()
.filter(|l| l.starts_with("T "))
.map(|l| l[2..].trim().parse().unwrap())
.collect();
let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014];
unsafe { std::env::remove_var("VETTA_SPEC"); }
assert_eq!(tokens, want, "speculative serve path must match reference exactly");
});
}
/// GPU perf probe: spec-on vs spec-off decode tok/s + acceptance on a real
/// prompt (GEN 96). Prints measured numbers; no speedup claim without them.
#[test]
#[ignore]
fn serve_gen_spec_perf() {
crate::gpu_isolated(|| {
let ids = "371,151451,149879,151194,149884";
let run = |spec: bool| -> (f64, usize) {
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
unsafe { std::env::set_var("VETTA_DBG_SPEC", "1"); }
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
let g = match parse_serve_line(&format!("GEN 96 temperature=0 {ids}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let stop = AtomicBool::new(false);
let mut lines: Vec<String> = Vec::new();
let t = Instant::now();
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
let ms = t.elapsed().as_secs_f64() * 1000.0;
let n = lines.iter().filter(|l| l.starts_with("T ")).count();
unsafe { std::env::remove_var("VETTA_SPEC"); std::env::remove_var("VETTA_DBG_SPEC"); }
(ms, n)
};
let (off_ms, off_n) = run(false);
let (on_ms, on_n) = run(true);
eprintln!("spec_perf: OFF {off_n} tok {off_ms:.1}ms {:.2} tok/s | ON {on_n} tok {on_ms:.1}ms {:.2} tok/s", off_n as f64 / (off_ms / 1000.0), on_n as f64 / (on_ms / 1000.0));
assert_eq!(off_n, on_n, "spec must emit the same token count");
});
}
/// GPU: multi-turn PrefixCache + DsparkSnapshot restore regression test.
/// Turn 1 prefills + generates 16 tokens and saves a checkpoint with DSpark
/// state; Turn 2 extends Turn 1's exact prompt + generated tokens with a
/// follow-up suffix, hitting RESUME on Turn 1's checkpoint and restoring
/// DSpark rings + frnn_last. Turn 2 output with VETTA_SPEC=1 must match
/// VETTA_SPEC=0 100% EXACT and emit a non-zero RESUME.
#[test]
#[ignore]
fn serve_gen_spec_prefix_cache_multi_turn_parity() {
crate::gpu_isolated(|| {
let turn1_ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,10970,261,4660,11,5603,59195,9268,328,261,6164,12,13448,8459,6462,13,200010,200001,200004";
let run_two_turns = |spec: bool| -> (Vec<i32>, Vec<i32>, usize) {
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
let stop = AtomicBool::new(false);
// Turn 1
let g1 = match parse_serve_line(&format!("GEN 16 temperature=0 {turn1_ids}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let mut l1 = Vec::new();
serve_gen(&eng, &g1, &stop, &mut |l| l1.push(l));
let t1: Vec<i32> = l1.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
// Turn 2 extends Turn 1 prompt + Turn 1 reply + short follow-up prompt
let mut turn2_vec: Vec<String> = turn1_ids.split(',').map(|s| s.to_string()).collect();
for &id in &t1 { turn2_vec.push(id.to_string()); }
for extra in [200010, 200000, 200004, 10970, 261, 2324, 13, 200010, 200001, 200004] {
turn2_vec.push(extra.to_string());
}
let turn2_ids = turn2_vec.join(",");
let g2 = match parse_serve_line(&format!("GEN 24 temperature=0 {turn2_ids}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let mut l2 = Vec::new();
serve_gen(&eng, &g2, &stop, &mut |l| l2.push(l));
let t2: Vec<i32> = l2.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
let resumed: usize = l2.iter()
.find(|l| l.starts_with("RESUME "))
.and_then(|l| l[7..].trim().parse().ok())
.unwrap_or(0);
unsafe { std::env::remove_var("VETTA_SPEC"); }
(t1, t2, resumed)
};
let (off_t1, off_t2, off_resumed) = run_two_turns(false);
let (on_t1, on_t2, on_resumed) = run_two_turns(true);
eprintln!("multi-turn prefix cache: off_resumed={off_resumed} on_resumed={on_resumed} t1_len={} t2_len={}", on_t1.len(), on_t2.len());
assert!(on_resumed > 0, "Turn 2 with VETTA_SPEC=1 must hit PrefixCache RESUME");
assert_eq!(on_resumed, off_resumed, "Turn 2 RESUME length must match OFF");
assert_eq!(on_t1, off_t1, "Turn 1 tokens must match OFF exactly");
assert_eq!(on_t2, off_t2, "Turn 2 tokens after PrefixCache+DsparkSnapshot restore must match OFF exactly");
});
}
/// GPU: verify that saving multiple large PrefixCache checkpoints (trunk KV +
/// ShortConv + DsparkSnapshot across grid boundaries 512, 1024, 1536, 2048)
/// keeps GPU VRAM completely flat (0 bytes added per checkpoint in VRAM,
/// since all snapshots live in pinned host RAM via `PinnedBuf`).
#[test]
#[ignore]
fn serve_gen_pinned_prefix_cache_vram_flat() {
crate::gpu_isolated(|| {
unsafe { std::env::set_var("VETTA_SPEC", "1"); }
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
let stop = AtomicBool::new(false);
let mut prompt: Vec<i32> = Vec::with_capacity(2200);
let seed = [200002, 200004, 34182, 279, 154554, 150628, 25, 220, 15, 200010, 200000, 200004];
prompt.extend_from_slice(&seed);
let mut vram_samples: Vec<(usize, usize, usize)> = Vec::new();
for target_len in [600usize, 1100, 1600, 2100] {
while prompt.len() < target_len {
prompt.push(10970 + ((prompt.len() * 17) % 500) as i32);
}
let ids_str = prompt.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",");
let g = match parse_serve_line(&format!("GEN 8 temperature=0 {ids_str}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let mut lines = Vec::new();
serve_gen(&eng, &g, &stop, &mut |l| lines.push(l));
let resumed: usize = lines.iter()
.find(|l| l.starts_with("RESUME "))
.and_then(|l| l[7..].trim().parse().ok())
.unwrap_or(0);
let ckpts = eng.prefix.borrow().pool.len();
let vram = vetta_infer_hip::vram_used();
eprintln!(
"pinned_ckpt_vram: prompt={} resumed={} ckpts={} vram={:.2} MiB",
target_len, resumed, ckpts, vram as f64 / (1024.0 * 1024.0)
);
vram_samples.push((target_len, resumed, vram));
}
unsafe { std::env::remove_var("VETTA_SPEC"); }
assert!(vram_samples[1].1 >= 512, "Turn 2 must hit >=512 checkpoint, got {}", vram_samples[1].1);
assert!(vram_samples[2].1 >= 1024, "Turn 3 must hit >=1024 checkpoint, got {}", vram_samples[2].1);
assert!(vram_samples[3].1 >= 1536, "Turn 4 must hit >=1536 checkpoint, got {}", vram_samples[3].1);
// Compare VRAM after Turn 1 (once KV + DsparkContext + BUF_POOL are warm)
// against Turn 4 (after filling 8 checkpoints up to 2100 tokens).
let v1 = vram_samples[0].2;
let v4 = vram_samples[3].2;
let delta_mb = (v4 as isize - v1 as isize) as f64 / (1024.0 * 1024.0);
eprintln!("pinned_ckpt_vram: Turn1->Turn4 delta = {delta_mb:+.2} MiB (expected ~0 MiB)");
assert!(
delta_mb.abs() < 32.0,
"PrefixCache in pinned RAM must keep VRAM flat across checkpoints, got {delta_mb:+.2} MiB"
);
});
}
}
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
+103 -91
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,102 +77,26 @@ impl SafetensorsArchive {
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let file = OpenOptions::new()
.read(true)
.open(&path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
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()
}
@@ -200,6 +125,93 @@ impl SafetensorsArchive {
}
}
fn load_shard(
path: &Path,
shard_idx: usize,
tensors: &mut HashMap<String, TensorInfo>,
) -> Result<SafetensorsShard, String> {
let file = OpenOptions::new()
.read(true)
.open(path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo { shard_idx, dtype, shape, begin, end },
);
}
Ok(SafetensorsShard { path: path.to_path_buf(), file, file_size, data_start })
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
let idx_path = dir.join("model.safetensors.index.json");
if idx_path.is_file() {
+144 -17
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);
@@ -716,7 +843,7 @@ mod tests {
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}");
@@ -839,7 +966,7 @@ mod tests {
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}");
+63 -14
View File
@@ -87,9 +87,9 @@ Five ideas explain almost everything that will surprise you:
- prompt *"Ciao, sono Federico"* → *"Ciao Federico! Piacere di conoscerti.
Come posso aiutarti oggi?"*
- **2650 prompt + 53 completion tokens · 4.2 tok/s decode · first token 618 s.**
- The 618 s time-to-first-token is the **sequential prefill** of the GUI's
~2650-token agent prompt (~140 ms/token); decode itself is ~4.2 tok/s. This
is the honest current performance frontier, not a hang.
- That 618 s was the *sequential* prefill of the day (2026-12-01). It is now
historical: batched prefill + WMMA (below) cut prefill to ~6.3 ms/token, so
the same prompt is seconds and a 16 k-token agent prompt ~105 s (was ~7 min).
- **Host CPU during inference is no longer a busy-wait.** ROCm's default spin
host-wait schedule pinned the process at ~100% CPU; setting
`hipDeviceScheduleBlockingSync` before context creation (as the reference does)
@@ -108,11 +108,55 @@ Five ideas explain almost everything that will surprise you:
600-token cached prefix prefills in **2.29 s vs 132.5 s cold (57.8×)**, end-to-end
**3.2 s vs 133.2 s (41.8×)**. This collapses the *second-turn* time-to-first-token;
the *first* turn still pays sequential prefill (batched prefill is the next brick).
- **What is NOT done yet (the frontier):** HIP graph capture (collapse the
per-token launches → near-zero host CPU), batched/chunked prefill (M>1 attention
+ grouped MoE, make the *first* large-prompt time-to-first-token seconds, not
minutes), and the expert-GEMV math speedup (WMMA). These are the M2 performance
work — correctness is already there; speed is the next axis.
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
@@ -130,12 +174,15 @@ on 2026-12-01 (see *Current state*). The path, in order:
4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load).
5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity,
first real GUI conversation 2026-12-01).
6. **M2 performance** — ⏳ the current frontier: prefix checkpoint cache ✅ landed
(multi-turn prefill reuse, EXACT parity, 57.8× measured); HIP graph capture
(host CPU), batched/chunked prefill (first-turn time-to-first-token), and
expert-GEMV WMMA (decode tok/s) still pending. Measured against the reference,
no unmeasured claims.
7. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
6. **M2 performance** — ⏳ prefix checkpoint cache ✅ (multi-turn reuse, EXACT,
57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense +
flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp
✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU).
7. **Drafter + DMA layer streaming** — ⏳ DSpark speculative drafter ✅ landed
(`13.93 tok/s` on Rust coding, 2.04× vs OFF, matching `strata-inkling`); next is
layer streaming in DMA (`io_uring O_DIRECT` + `hipHostRegister` SlabRing,
Hot/Cold expert cache + lookahead prefetch) — the hard memory frontier.
8. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
domain-aware expert prefetch.
## How to verify
@@ -149,7 +196,9 @@ lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean
lean proofs/arena_plan.lean
lean proofs/inkling_loop.lean
lean proofs/prefix_cache.lean
lean proofs/speculative_draft.lean
# Opt-in live tests against the real Inkling artifact:
cargo test -p vetta-infer-ld -- --ignored inkling
+12 -2
View File
@@ -34,10 +34,20 @@ int vetta_buf_alloc(void** out, size_t bytes);
int vetta_buf_free(void* p);
int vetta_buf_h2d(void* dst, const void* src, size_t bytes);
int vetta_buf_d2h(void* dst, const void* src, size_t bytes);
// Device-to-device copies (prefix-checkpoint snapshot/restore).
// Device-to-device copies (legacy/internal).
int vetta_buf_copy(void* dst, const void* src, size_t bytes);
int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src, size_t spitch,
size_t width, size_t height);
// Pinned host RAM lifecycle + async D2H/H2D copies for zero-VRAM PrefixCache
// checkpoints (hipHostMallocDefault / hipHostFree with stream sync on free).
int vetta_host_alloc(void** out, size_t bytes);
int vetta_host_free(void* p);
int vetta_buf_d2h_async(void* dst_host, const void* src_dev, size_t bytes);
int vetta_buf_h2d_async(void* dst_dev, const void* src_host, size_t bytes);
int vetta_buf_copy2d_d2h_async(void* dst_host, size_t dpitch, const void* src_dev,
size_t spitch, size_t width, size_t height);
int vetta_buf_copy2d_h2d_async(void* dst_dev, size_t dpitch, const void* src_host,
size_t spitch, size_t width, size_t height);
// k_rms_norm (kernel #2): y[row] = x[row] * rsqrt(mean(x^2)+eps) * w.
int vetta_rms_norm_f32(const float* x, const float* w, float* y,
@@ -149,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
+129
View File
@@ -255,4 +255,133 @@ theorem poolInsert_nodup (cap : Nat) (pool : List Nat) (seq : Nat)
pinned. The engine relies on this combinatorial fact (cap ≥ 3) when evicting;
`poolInsert_preserves_pinned` proves the I3 invariant that anchors survive. -/
/-! ## Part D: SWA-window checkpoint observational equivalence
A SWA layer attends only to the causal window `[winStart w p, p]` at position
`p` (kernel `k_flash_swa_gqa_*`: `k_start = p - w + 1` when `p ≥ w`, else 0).
So a checkpoint at `seq_len = n` need only store KV from `kvStart w n = n - min n w`
(the last `min n w` positions); the older KV is never read again. Restoring that
window and prefilling the suffix is observationally exact for every future
position `p ≥ n`. Full-attention layers keep the whole prefix (`kvStart = 0`).
This is the memory refinement that shrinks SWA checkpoints (~40 of 48 pools). -/
/-- First KV position a SWA checkpoint at `n` must retain (window `w`). -/
def kvStart (w n : Nat) : Nat := n - min n w
/-- First KV position the SWA attention reads at position `p` (window `w`). -/
def winStart (w p : Nat) : Nat := if p ≥ w then p - w + 1 else 0
/-- CONTAINMENT: for any future position `p ≥ n`, the attention window starts at
or after the checkpoint's retained start, so the window is fully covered by
`[kvStart w n, p]` (restored window `[kvStart, n)` + suffix `[n, p]`). -/
theorem kvStart_le_winStart (w n p : Nat) (h : n ≤ p) :
kvStart w n ≤ winStart w p := by
unfold kvStart winStart
split
· omega
· have hn : n ≤ w := by omega
have : min n w = n := Nat.min_eq_left hn
omega
/-- Observational equivalence of windowed restore. `read kv p` is the SWA attention
output, which by the kernel contract depends only on KV in `[winStart w p, p]`
(`hwin`). If the restored+suffix cache `kv'` agrees with the cold cache `kv` on
`[kvStart w n, p]` (`hagree` — restored window + causal suffix), then the read
at `p` is identical. The containment lemma lifts the agreement to the window. -/
theorem swa_window_restore_equiv {V R : Type} (w n p : Nat)
(read : (Nat → V) → Nat → R)
(hwin : ∀ kv kv' : Nat → V,
(∀ i, winStart w p ≤ i → i ≤ p → kv i = kv' i) → read kv p = read kv' p)
(kv kv' : Nat → V) (hn : n ≤ p)
(hagree : ∀ i, kvStart w n ≤ i → i ≤ p → kv i = kv' i) :
read kv p = read kv' p := by
apply hwin
intro i hi1 hi2
exact hagree i (Nat.le_trans (kvStart_le_winStart w n p hn) hi1) hi2
/-- A full-attention checkpoint retains everything: its window covers the whole
prefix (`n ≤ w`), so `kvStart w n = 0` and no KV is discarded. -/
theorem kvStart_full (n w : Nat) (h : n ≤ w) : kvStart w n = 0 := by
unfold kvStart
have : min n w = n := Nat.min_eq_left h
omega
/-!
Part E — SWA KV ring (2026-12-02). The 40 SWA pools store a circular ring of
`R = swa_win + chunk_cap` positions (`slot R p = p % R`); the 8 global pools keep
a linear cache of `MAX_CONTEXT` positions, where `p < R` makes `%` the identity
(`global_slot_id`). Correctness of the ring rests on three facts, proved here
BEFORE the kernel/`LayerState` change (AGENTS.md invariant 6):
E1 `slot_inj` / `window_slots_distinct`: a causal window spans ≤ R positions, so
its slots are pairwise distinct (a read never aliases two logical positions).
E2 `ring_no_clobber`: with `R ≥ swa_win + chunk`, the writes of one batched chunk
(`[c, c+chunk)`) cannot overwrite a slot still needed by an earlier token's
window read (`[c-swa_win, c+chunk)`), except the same logical position.
E3 `global_slot_id`: below the ring length the modulo is the identity, so the
global (linear) pools and all small-seq parity tests are unaffected.
-/
/-- Ring slot of logical position `p` in a ring of `R` positions. -/
def slot (R p : Nat) : Nat := p % R
/-- E1 core: two positions at distance < R with the same slot are equal. -/
theorem slot_inj (R x y : Nat) (_hR : 0 < R) (hxy : x ≤ y) (hlt : y - x < R)
(h : x % R = y % R) : x = y := by
have hx := Nat.mod_add_div x R
have hy := Nat.mod_add_div y R
rw [h] at hx
have hq : x / R ≤ y / R := Nat.div_le_div_right hxy
have hAB : R * (x / R) ≤ R * (y / R) := Nat.mul_le_mul_left R hq
have hyx : y - x = R * (y / R) - R * (x / R) := by omega
have h2 : y - x = R * (y / R - x / R) := by
rw [← Nat.mul_sub_left_distrib] at hyx
exact hyx
have hd : y / R - x / R = 0 := by
cases Nat.eq_zero_or_pos (y / R - x / R) with
| inl h0 => exact h0
| inr hpos =>
have h1d : 1 ≤ y / R - x / R := by omega
have hge : R ≤ R * (y / R - x / R) := by
simpa [Nat.mul_one] using Nat.mul_le_mul_left R h1d
omega
rw [hd, Nat.mul_zero] at h2
omega
/-- E1: within any half-open interval of length ≤ R the ring slot is injective,
so a causal window (span ≤ swa_win < R) never reads one slot as two positions. -/
theorem window_slots_distinct (R a b p q : Nat) (hR : 0 < R) (hb : b ≤ R)
(hp : a ≤ p) (hp' : p < a + b) (hq : a ≤ q) (hq' : q < a + b)
(h : slot R p = slot R q) : p = q := by
unfold slot at h
have hlt : p - q < R := by omega
have hlt' : q - p < R := by omega
cases Nat.le_total p q with
| inl hle => exact slot_inj R p q hR hle (by omega) h
| inr hle => exact (slot_inj R q p hR hle (by omega) h.symm).symm
/-- E2: a batched chunk's KV writes cannot clobber a slot an earlier token of the
same chunk still reads, provided `R ≥ swa_win + chunk`. `w` ranges over the
chunk's writes `[c, c+chunk)`, `r` over the union of window reads
`[c-swa_win, c+chunk)`; equal slots force `w = r` (the causal same-position
write-then-read, which is ordered by the kernel). -/
theorem ring_no_clobber (R win chunk c w r : Nat) (hR : 0 < R)
(hcap : win + chunk ≤ R)
(hw : c ≤ w) (hw' : w < c + chunk)
(hr : c - win ≤ r) (hr' : r < c + chunk)
(h : slot R w = slot R r) : w = r := by
unfold slot at h
cases Nat.le_total w r with
| inl hle =>
have hlt : r - w < R := by omega
exact slot_inj R w r hR hle hlt h
| inr hle =>
have hlt : w - r < R := by omega
exact (slot_inj R r w hR hle hlt h.symm).symm
/-- E3: below the ring length the modulo is the identity — global (linear) pools
and every small-`seq` parity test behave exactly as before the ring. -/
theorem global_slot_id (R p : Nat) (h : p < R) : slot R p = p := by
unfold slot
exact Nat.mod_eq_of_lt h
end VettaPrefixCache
+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`).