Commit Graph
89 Commits
Author SHA1 Message Date
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 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 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 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 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 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 736c541887 [GW][LD][HIP][Proofs] Wire prefix checkpoint cache into serve: restore longest prefix, prefill only new suffix
Concept ported from strata --auto-ckpt, adapted to vetta's contiguous per-pass
KV + ShortConv history (proofs/prefix_cache.lean, restore_equiv). serve_gen now
restores the longest cached STRICT prefix of a prompt and prefills only the new
suffix tokens; the final logits still come from a real forward of the last prompt
token. Checkpoints save at pos (prompt + generated non-EOS tokens) so the next
turn reuses the full prior context. Pinned anchors {512,1024} never evicted (I3),
LRU at cap 6; KV snapshots unpooled (freed on eviction). VETTA_NO_PREFIX_CACHE
forces cold prefill for A/B.

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

Verified: CPU 91 + gw GPU 5 + hip GPU 18 + ld GPU 18 green; Lean 0 sorryAx.
Multi-turn parity EXACT (restore == cold re-prefill), both prewarm- and
decode-state checkpoints. Measured (gfx1150, Inkling-2-Mini, FP16 KV, greedy):
605-token prompt, 600-token cached prefix -> prefill 132.5s cold vs 2.29s warm
(57.8x), end-to-end 133.2s vs 3.2s (41.8x).
2026-12-01 20:30:13 +01:00
adm c9713c8bc1 [HIP][LD][GW] Bound VRAM across requests: unpooled KV + FP16 serve KV + bucketed flash scratch
Federico saw VRAM grow ~7 GiB per agent step (44.9/48 GiB, near OOM). Root cause:
the KV cache scales with max_seq=prompt+max_new (varies per request) and the
exact-size DeviceBuf pool retained every distinct KV size, so a multi-turn chat
accumulated KV without bound. The full-attn flash scores scratch (n_win grows per
token) leaked similarly.

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

Measured (new binary, 3 requests of 200/400/600 prompt tokens): VRAM 7.66 ->
8.07 -> 8.33 GiB (small bounded expert lazy-load growth, NOT +7 GiB/step);
clean release to 0.34 GiB on QUIT. Parity EXACT (16 tok); 18 ld + 18 hip + 5 gw
GPU green; workspace -D warnings green; 5 Lean 0 sorryAx.
2026-12-01 20:02:33 +01:00
adm 25200e2e79 [HIP] Blocking host-wait schedule: kill the 100% CPU spin during GPU inference
Federico observed vetta-infer at 100% CPU while the GPU runs — the same busy-wait
the strata upstream had. Root cause: ROCm's default host-wait schedule spins on
every blocking synchronization (the per-token logits hipMemcpy D2H waits for the
whole 48-visit forward). The reference fixes it with --hip-sync blocking
(hipDeviceScheduleBlockingSync, ink_hip_backend.hip.cpp:607).

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

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

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

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

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

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

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

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

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

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

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

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

Suite: workspace -D warnings green; 18 ld + 18 hip + 4 gw GPU; 5 Lean 0 sorryAx.
2026-12-01 18:04:01 +01:00
adm cd853cda8b [GW] Chat reliability: clean stop at end_message + debug instrumentation
In the plain-content path (effort none) the assistant channel closes at
<|end_message|> (200010); chat_turn now raises stop there so the reply is exactly
the content even when the trailing EOS is delayed by a near-tie (the model used
to emit unused special tokens past end_message and run to max_new). Live: the
one-word capital question now returns clean 'Paris' instead of 'Paris'+garbage.
Add VETTA_DBG_PROMPT (rendered prompt + ids) and VETTA_DBG_LOGITS (per-step top-5)
for parity bisection. chat_turn_paris GPU test green; workspace -D warnings green.
2026-12-01 17:43:03 +01:00
adm 74b3384270 [HIP] FP16 KV cache path (strata default), opt-in VETTA_F16_KV
strata stores K/V in FP16 by default (KvDtype::FP16, 'default lossless FP16');
vetta used F32. Add k_kv_store_f16 (RNE round to u16 cache) + k_flash_swa_gqa_decode_f16
(f32 attention math over FP16 KV), FFI/wrappers, and a new_state/forward branch
gated by VETTA_F16_KV=1 (F32 stays the CPU-oracle baseline). New GPU parity test
fp16_kv_store_and_flash_parity: stored K == cast_f32_f16 bits, attention over the
decoded FP16 KV matches a CPU oracle fed the same values (18 hip GPU green).

MEASURED honestly: FP16 KV does NOT fix the chat token-2+ divergence (still
~3.6 logit gap vs reference, robust also to VETTA_F16_EXPERT and -ffp-contract=off).
The gap is a systematic multi-token accumulation difference, not KV precision;
kept as faithful opt-in infrastructure, not claimed as a parity fix.
2026-12-01 17:42:57 +01:00
adm dfa6013bfd [LD] VETTA_PROF per-phase forward profiler
Gated (VETTA_PROF=1) timing of embed/prelude/core/coda/final plus a thread-local
expert-time accumulator, to locate decode hotspots without perturbing the normal
path. Used to measure the M2 perf increment.
2026-12-01 17:27:07 +01:00
adm 4bc268f69c [HIP] Device buffer pool + right-sized GEMV blocks (decode perf)
DeviceBuf::alloc/Drop now reuse freed buffers via a thread-local size-bucketed
free list instead of hipMalloc/hipFree per intermediate (~1200 alloc/free per
token). Safe: all launches share the default stream and host copies are blocking,
so a recycled buffer's prior use is ordered before its next launch. Escape hatch
VETTA_NO_BUF_POOL=1. nvfp4_gemv 256->128 threads (K/16=144 groups: half the waves
were idle), mxfp8_gemv 256->64 (K/32<=72 groups); cheaper block reduction.

MEASURED (gfx1150 release, GEN 64): decode 269ms/tok -> 234ms/tok (3.72->4.27
tok/s, ~15%). Parity unchanged: 18 ld GPU + 17 hip GPU green. Profiling shows the
remaining hotspot is the scalar-dequant expert GEMV (~87ms/tok) — the fdot2
hardware-dot + device-resident blocks + hipGraph path is the next big lever.
2026-12-01 17:27:07 +01:00
adm 0a46c4dd7b [GW] Real multi-turn chat: Inkling template + streaming REPL
chat_template renders the plain-text subset of chat_template.jinja (effort
header before first non-system message, role/content_text/end_message tags,
assistant turns closed with content_model_end_sampling, effort-0 model opener);
4 CPU tests. chat::chat_turn tokenizes the rendered prompt and drives the
Lean-proven serve_gen FSM, streaming decoded text; run_chat is an interactive
multi-turn REPL. CLI: vetta-infer chat <dir> [effort] [max_new].

MEASURED live (release, gfx1150): 3-turn Italian chat answers correctly and
keeps context ('La capitale della Francia e Parigi.' / '...del Giappone e
Tokyo.'). GPU test chat_turn_paris green. Workspace -D warnings green.
2026-12-01 17:18:27 +01:00