Commit Graph
76 Commits
Author SHA1 Message Date
adm b41a71f2f7 [Core] forward_batch: batched prefill orchestration (M=B) BIT-EXACT end-to-end
forward_batch embeds B tokens and runs the proven schedule (inkling_loop.lean)
at M=B: prelude [0,6) -> core [6,18) x3 with DEVICE-SIDE bank rollback (arena
sub-range via copy_f32_sub, cur<-prelude copy, blocks.truncate) + cross-pass
msgs (attn_res_mix over bank, nq=4) + controllers on passes 1,2 -> coda [18,24)
-> final depth mix + unembed LAST token. run_layer_batched dispatches SWA/full.
No host D2H/H2D gather anywhere in the batched path (graph-capturable shape).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Additive — decode default unchanged.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Verified: CPU 91 + gw GPU 5 + hip GPU 18 + ld GPU 18 green; Lean 0 sorryAx.
Multi-turn parity EXACT (restore == cold re-prefill), both prewarm- and
decode-state checkpoints. Measured (gfx1150, Inkling-2-Mini, FP16 KV, greedy):
605-token prompt, 600-token cached prefix -> prefill 132.5s cold vs 2.29s warm
(57.8x), end-to-end 133.2s vs 3.2s (41.8x).
2026-12-01 20:30:13 +01:00
adm f12281ec61 [Proofs] Prefix checkpoint cache: restore-equivalence + pool invariants (0 sorryAx)
Proof-first for the prefix-reuse cache adopted in concept from strata's
--auto-ckpt (reference proofs/auto_ckpt_pool.lean), adapted to vetta's contiguous
per-pass KV + ShortConv history (single conversation slot, no paged SWA ring).

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

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

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

Measured (new binary, 3 requests of 200/400/600 prompt tokens): VRAM 7.66 ->
8.07 -> 8.33 GiB (small bounded expert lazy-load growth, NOT +7 GiB/step);
clean release to 0.34 GiB on QUIT. Parity EXACT (16 tok); 18 ld + 18 hip + 5 gw
GPU green; workspace -D warnings green; 5 Lean 0 sorryAx.
2026-12-01 20:02:33 +01:00
adm b1f65942c8 [Docs] Document the first real interactive GUI inference (2026-12-01, measured)
Federico completed the first real conversation with vetta-infer through the
strata-ctl web GUI on Sogliola:
  'Ciao, sono Federico' -> 'Ciao Federico! Piacere di conoscerti. Come posso aiutarti oggi?'
  2650 prompt + 53 completion tokens, 4.2 tok/s decode, first token 618 s.

The 618 s time-to-first-token is the sequential prefill of the ~2650-token agent
prompt (~140 ms/token); decode is ~4.2 tok/s. Recorded honestly as the current
performance frontier (not a hang).

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

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

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

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

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

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

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

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

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

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

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

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

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

Suite: workspace -D warnings green; 18 ld + 18 hip + 4 gw GPU; 5 Lean 0 sorryAx.
2026-12-01 18:04:01 +01:00
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
adm 1df8342f96 [LD] Resident WeightCache: memoize device uploads across decode tokens
Per-token forward re-read ~3 GiB of NVFP4/MXFP8 expert blobs from NVMe and
re-uploaded every layer/norm/query tensor. WeightCache borrows the archive and
memoizes raw tensors, BF16->F32 norms, per-layer weights, controllers and expert
matrices (Arc, interior mutability) so autoregressive decode reuses GPU-resident
weights. The forward path now takes &WeightCache; serve_gen creates one cache
per request shared across prefill + decode.

MEASURED (gfx1150, debug): 21 forwards 36s -> 8.8s (~4x); parity unchanged
(first tokens [152717,13,68014,32,13] exact). Release steady decode ~3.8 tok/s
(DONE 64: decode_ms 16909 over 64 tokens). Suite green: 18 ld GPU + 17 hip GPU.
2026-12-01 17:18:21 +01:00
adm 5ec55f753f [LD] Fix mlp loop-controller order: gate RAW mix BEFORE mlp_norm (exact strata)
Root cause of the residual argmax gap (tok100: 220 vs ref 68014). Per-visit norm bisection vs the reference localized it: prelude + core pass 0 matched (~1e-4), but pass 1/2 diverged ~3x. Stage dump at visit 18 (ip6 pass1) showed attention matched (q/k_cv/v_cv/aout/cur_after_attn ~1e-3) while mlpin diverged 2.8% and y_part 2.85x (router top-k flip).

The reference (ink_hip_backend.hip.cpp ~5049) applies the mlp loop controller to the RAW depth-mix THEN rms_norm: run_attnres -> run_loop_ctrl(mlpin,3) -> k_rms_norm_rows. vetta applied it AFTER rms_norm (to the normalized mlpin). Swapped order in both layer_forward_swa and layer_forward_full: apply_controller(&mix,...) before rms_norm.

MEASURED after fix: tok100 argmax = 68014 EXACT reference match (logit 18.371). All 48 per-visit cur norms now match reference to ~1e-3 (pass1/2 + coda restored). Generation 'The capital of France is' -> first 5 tokens [152717,13,68014,32,13] EXACT reference (was 2); coherent continuation ' Paris.\n\nA. True\nB. False\nAnswer A. True'.

Verified: 18 ld GPU + 17 hip GPU + workspace (-D warnings) green, 5 Lean files 0 sorryAx. Reference debug patch reverted + rebuilt clean.
2026-12-01 17:00:33 +01:00
adm e4dcc5e015 [HIP] FP16 expert-path kernels (strata B=1 parity), opt-in; refactor run_experts
Add the exact strata B=1 FP16 expert path as verified kernels: k_cast_f32_f16 (RNE), k_nvfp4_gemv_f16 / k_mxfp8_gemv_f16 (FP16 activations, group partial dot then scale-fma, fdot2 order), k_situ_f16 (SiTU f32 -> stored FP16). Rust wrappers + expert_gemv_f16 dispatch.

Refactor the duplicated SWA/full expert loops into ld::layer::run_experts. Default stays all-f32 (verified parity baseline); VETTA_F16_EXPERT=1 selects the FP16 path.

MEASURED A/B (tok100): f32 argmax 220 (23.074) / 68014 22.643; fp16 argmax 220 (23.069) / 68014 22.632. FP16 shifts logits ~0.01 but does NOT flip the near-tie: the residual gap vs reference is the core-loop pass 1/2, NOT expert precision. FP16 kept opt-in for once the loop is fixed.

New real_expert_nvfp4_gemv_f16_parity (GPU fp16 vs CPU oracle over same fp16-rounded x) green. Verified: workspace -D warnings, 18 ld GPU + 17 hip GPU green.
2026-12-01 16:53:18 +01:00
adm 26bff57645 [GW] Real GPU --serve: wire the verified forward + sampler + Lean-proven session
Resident GEN/STOP/QUIT service (strata-ctl contract) composing the three verified pieces:

- ld::layer::forward_inkling_with_state (48-visit autoregressive forward, persistent KV/ShortConv);

- abi::sampler (hardened zero-alloc greedy/top-k/p/min-p + penalties, non-finite tracking);

- gw::session::ServeSession (proofs/serve_session.lean FSM: GEN 0 pre-warm, STOP->DONE drain).

serve_gen is a pure orchestration fn (engine + ParsedGen + stop flag + emit closure), GPU-integration-tested. run_serve adds a stdin reader thread raising stop/quit atomics so STOP interrupts decode and drains to DONE. Token-id based (no tokenizer needed). gw 'hip' feature default OFF keeps the gateway host-independent.

Measured: live binary over pipe -> READY 8192 stop; 'The capital of France is' -> T 152717 (' Paris', exact ref) T 13 T 198 T 3967; DONE length. STOP after 2 tokens -> DONE 2 ... stop, no further tokens (Theorem 4/9). QUIT exits clean.

Verified: cargo test --workspace green (-D warnings), gw hip 10 default + 2 GPU serve tests green, 5 Lean files 0 sorryAx.
2026-12-01 16:42:24 +01:00
adm 08514e81b1 [HIP] SiTU interleaved gate/up + F32 router: generation matches reference
Root-cause fixes that make Inkling-2-Mini generation match strata-inkling:

- k_situ: w13 rows are INTERLEAVED gate/up (row 2j=gate[j], 2j+1=up[j]), exact strata k_moe_direct_w13_situ. Was reading block layout gu[j]/gu[inter+j] -> sign-flipped y_part. Now gu[2j]/gu[2j+1].

- k_router_gemv (new): B=1 router reads F32 mlpin @ bf16 gate promoted to f32 (strata launch_f32_linear). bf16-rounding the router input flipped top-k expert selection. Used in both layer_forward_swa/full.

- situ_cpu oracle + situ_parity_vs_cpu updated to interleaved.

- real_full_layer/full_attn CPU oracle: router reads F32 mlpin (was bf16) -> experts now match GPU exactly.

- real_attention_block parity: allclose (atol 2e-3 + rtol 3e-3). Stage bisection proved aout matches CPU to <1e-6 abs; pure-relative metric exploded only at near-cancellation O-proj elements after bf16 cast (benign accumulation artifact).

- gated VETTA_DBG_NORM per-visit norm dumps for future bisection.

Verified: 'The capital of France is' -> ' Paris.' (152717, exact ref). cargo test --workspace green (-D warnings), 17 ld GPU + 17 hip GPU green, 5 Lean files 0 sorryAx.
2026-12-01 16:31:18 +01:00
adm df120e6f5f [Core] Per-visit ShortConv history (exact strata hist_pool_all + visit*stride)
Root cause found by reading strata run_sconv: the ShortConv history pool is
indexed by GLOBAL VISIT (hist_pool_all + rec_visit*stride), so each core pass
has its OWN history ring -- history does NOT carry across the 3 passes for the
same token. The previous shared-per-layer history made pass 1 read pass 0's
input as history (wrong). LayerState now holds hist_k/v/a/m as [DeviceBuf;3]
indexed by pass; layer_forward_swa/full + run_layer take a pass index (prelude/
coda=0, core=0/1/2). For a fresh token every visit reads zero history, matching
the reference. Single-token argmax moved (8->183618), confirming history matters.

Verified: cargo test --workspace + hip 17/17 + lean 0 sorryAx green.
2026-12-01 15:51:34 +01:00
adm 1221ac094a [HIP] BF16 round-to-nearest-even parity (cast, ctrl pack, shortconv history)
Reference comparison (strata-inkling --serve ground truth) exposed a systematic
precision bug: vetta truncated f32->bf16 (>>16) while the reference f32_to_bf16
rounds to nearest even (0x7FFF + ((u>>16)&1)). Truncation bias accumulates over
the 48-visit loop and drifts the residual stream.

- k_cast_f32_bf16: round-to-nearest-even (was truncation).
- k_ctrl_pack: packed cur/msg bf16 now round-to-nearest-even.
- k_shortconv4_decode / k_shortconv4_dyn_decode: history ring rounded through
  bf16 between steps (exact strata "Round through BF16 between steps"), via a
  new bf16_round device helper.
- CPU oracles updated to match (packer bf16_trunc, hip f32_to_bf16 + the
  shortconv/controller test history shifts).

Effect on the full forward (single token 100, reference argmax 68014):
argmax moved 100 -> 8 and logit[68014] rose 8.6 -> 11.1 (toward the reference),
confirming the rounding fix is real and directional. Generation from "The
capital of France is" (prompt ids verified identical to the reference) now
produces structured text but the argmax still diverges from the reference
" Paris" — further precision/composition parity is in progress (reference uses
fp16 KV cache + fp16 expert input; candidate next mismatches).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
GPU 17/17 (--features hip, --ignored) green with the rounded oracles;
lean proofs (5 files) green.
2026-12-01 15:43:31 +01:00
adm edcfab6548 [LD] correctness debugging infra: full-attn CPU parity + stage bisect + dbg taps
Reference-ground-truth debugging continues (strata-inkling --serve gives the
correct continuations). Added diagnostics to isolate the remaining divergence:

- real_full_attn_layer_end_to_end: full CPU oracle for the full-attn layer
  (ip=5): 3-query mix split + separate q/k/v norms + distinct-input projections
  + dyn ShortConv (reversed taps) + global attention + MoE. Currently FAILS
  (max_rel_err 5.876) with IDENTICAL expert selection GPU==CPU — so the bug is
  downstream of routing, in the attention-output -> MoE-input path, not a
  router tie-flip. Kept as an #[ignore] diagnostic tracking the open bug.
- full_attn_bisect: stage-by-stage GPU-vs-CPU comparison (mix/norm/projections/
  dyn-shortconv) reporting max_rel + max_abs + rel-on-large-values. Findings:
  mix/norm match (~1e-6); GEMM absolute error ~1e-3 (benign bf16 rounding, the
  large max_rel is an artifact of the 1e-3 floor on near-zero outputs).
- sconv_dyn_step CPU helper; env-gated VETTA_DBG_NORM (residual/block norms)
  and VETTA_DBG_IDS (selected experts) taps in the layer forwards.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green. The full-attn parity diagnostic is #[ignore] and
known-failing (open correctness bug under investigation).
2026-12-01 15:36:03 +01:00
adm b1bb4e13be [LD] autoregressive generation + 2 correctness fixes vs reference engine
Added a reference-ground-truth debugging loop: drove the strata-inkling
reference engine (--serve, GEN protocol) on the same prompts to obtain the
correct continuations, then compared against vetta's forward.

- tokenizers crate (fancy-regex) added to vetta-infer-ld for real BPE
  encode/decode from tokenizer.json.
- forward_inkling_with_state: stateful variant exposing the persistent
  per-layer KV cache + shortconv history across decode positions, enabling
  autoregressive prefill + generation. forward_inkling wraps it with fresh state.
- generate_continuation_real_prompt test: encode prompt -> token-by-token
  prefill -> greedy sampling via the hardened abi sampler -> decode.

TWO REAL BUGS FOUND via reference comparison (reference: "The capital of
France is" -> " Paris."; single token 100 -> argmax 68014):
1. embed_token omitted embed_norm: the reference k_embed_lookup fuses gather +
   RMS-normalize with embed_norm.weight. Fixed (gather then rms_norm).
2. full-attn ShortConv static_w transpose had REVERSED tap order: reference
   upload_sc uses kt[c*4+(3-lag)] = kw[lag*kv_dim+c]; fixed to match.

NOTE: generation is still divergent after these two fixes (single-token argmax
moved 120533 -> 100, reference 68014); further correctness debugging is in
progress. These two fixes are verified-correct against the reference semantics.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; generation + full-forward tests run
(--features hip, --ignored).
2026-12-01 15:28:20 +01:00
adm 3c870743fe [LD] FULL Inkling-2-Mini forward runs end-to-end (loop + controllers + MXFP8)
The complete 48-visit Inkling forward now runs on real weights on gfx1150:
prelude [0,6) -> core [6,18) x3 passes (bank rollback + cross-pass msgs +
gain/forget controllers on passes 1,2) -> coda [18,24) -> final depth mix +
unembed + softcap. Produces finite, softcap-bounded logits over vocab 201024
(argmax 120533, logit 19.219) in ~1.9s.

- k_mxfp8_gemv / vetta_mxfp8_gemv + ue8m0_to_f32: MXFP8 experts (layers 20..23
  are F8_E4M3 + UE8M0/32, NOT NVFP4). y[n] = sum_k e4m3(W[n,k]) *
  ue8m0(scale[n,k/32]) * x[k], no outer scale. Real layer-20 expert parity
  1.45e-4 vs CPU dequant oracle. This is the engine-side per-layer precision
  composition: layers 0..19 NVFP4, 20..23 MXFP8, dispatched transparently.
- packer: ExpertMatrix.mxfp8 flag + load_expert_matrix auto-detects the format
  (amax tensor presence) + expert_gemv dispatch.
- ld::layer: ControllerWeights/load_controllers + apply_controller (RMS pack ->
  down GEMM -> gain/forget GEMM -> gating); LoopMsgs; layer_forward_swa/full
  take Option<(&ControllerWeights,&LoopMsgs)> (has_msgs path: 3 separate
  controlled inputs for SWA, controllers before attn norm / after mlp norm).
- is_swa + load_msg_queries (stacked cross-pass queries) + run_layer (SWA/full
  dispatch, persistent per-layer state across passes) + forward_inkling (the
  proven schedule from proofs/inkling_loop.lean, incl. bank rollback).
- full_inkling_forward_logits test: whole-model forward -> finite bounded logits.

NOTE: the forward RUNS and is bounded; bit-parity of the generated token vs the
reference engine is the next verification step (no correctness claim yet).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; GPU 18/18 + MXFP8 real parity + full forward PASS
(--features hip, --ignored).
2026-12-01 15:14:05 +01:00
adm 38ac957b26 [HIP] loop-controller kernels (RMS pack + gain/forget apply) verified
- k_ctrl_pack / vetta_ctrl_pack: exact strata k1_loop_ctrl_rms +
  k1_loop_ctrl_pack_in_bf16 — inv_c=rsqrt(mean(cur^2)+eps),
  inv_m=rsqrt(mean(msg^2)+eps); packed BF16 [2D] = [cur*inv_c ; msg*inv_m].
- k_ctrl_apply / vetta_ctrl_apply: exact k1_loop_ctrl_apply_out —
  out = (1-tanh(forget))*cur + tanh(gain)*msg (gain/forget gating of the loop
  message). The down/gain/forget low-rank projections reuse gemm_bf16.
- loop_controller_parity_vs_cpu: full controller chain (pack -> down GEMM
  [gate_rank] -> cast -> gain/forget GEMM [D] -> apply) vs a CPU oracle:
  max_rel_err 1.6e-7. The loop controller composes correctly.

This is the last kernel needed for the full Inkling forward. All mechanisms
(SWA + full-attn attention, MoE NVFP4, deep-residual block-mix, shortconv
static/dyn, loop controllers) are now verified microkernels.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; GPU 17/17 (--features hip).
2026-12-01 15:07:02 +01:00
adm 5ae2072981 [LD] full-attention layer forward (3-query mix, dyn ShortConv, tau, global attn)
- ld::layer: FullLayerWeights + load_full_layer + layer_forward_full +
  load_sconv_transposed (the full-attn k/v_sconv.static_w tensor is [4,C],
  transposed to the kernel's [C,4] layout). The full-attn layer step:
    mx3 = attn_res_mix(blocks, cur, attn_queries[ip-1] (3 queries)) -> split
    in0/in1/in2 = rms_norm(mx3[j], q/k/v_input_norm.weight)  (separate norms)
    q/r/gate/sink from in0; k from in1; v from in2 (distinct inputs)
    k_dyn/v_dyn = in1/in2 @ k/v_sconv.weight_proj; dyn ShortConv4 K/V (1/3)
    Q/R L2-clip with tau (full-attn), K clip without; relpos bias; KV store
    global flash attention (window=0); O-proj + attn ShortConv; block cadence
    MoE sublayer identical to SWA.
- full_attn_layer_end_to_end test: layer 5 on real weights, seeded with one
  depth block; finite residual + correct cadence (ip=5 %6!=0 -> no snapshot).
  Smoke-verified composition (all constituent kernels are individually
  parity-verified); a full CPU-oracle parity of the full-attn wiring is a
  follow-up refinement.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files) green; full-attn layer end-to-end PASS
(--features hip, --ignored).
2026-12-01 15:02:17 +01:00
adm 38a983ce80 [HIP] dynamic-tap ShortConv4 kernel (full-attn layers) verified
- k_shortconv4_dyn_decode / vetta_shortconv4_dyn_decode: exact strata
  k2_shortconv4 dyn semantics for the full-attention layers — y = x0 +
  sw0*h0+sw1*h1+sw2*h2+sw3*x0, then y += dt0*x0+dt1*h2+dt2*h1+dt3*h0, scaled
  by 1/3 (vs 1/sqrt(5) for the static SWA variant). dyn_taps [M,n_heads,4],
  head = c/(C/n_heads); static_w [C,4]; history ring shifted in place.
- Multi-step parity test: 5-token recurrence vs CPU oracle, per-step match
  (<1e-5) AND device history ring == host history ring (exact). The dynamic
  short-conv (driven by k/v_sconv.weight_proj taps) evolves correctly.

This is the last shortconv variant needed for the full-attn layers {5,11,17,23}
(3-query mix split + separate q/k/v norms + dyn shortconv + tau + global attn).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (5 files incl. inkling_loop) green; GPU 16/16 (--features hip).
2026-12-01 15:00:00 +01:00
adm 04aae6db9d [Proofs] Inkling loop schedule + AttnRes block cadence + bank rollback (proof-first)
- proofs/inkling_loop.lean: formal model of the Inkling-2-Mini physical forward
  schedule (prelude [0,6) + core [6,18) x3 passes + coda [18,24) = 48 visits)
  and its AttnRes deep-residual block cadence + multi-pass bank rollback,
  extracted from the reference run_visit / core loop. 12 theorems + 5
  computational examples, 0 sorryAx, standard axioms only:
  * snapshot iff ip % blockSize(6) == 0; prelude snapshots {0}, core {6,12},
    coda {18}; full schedule snapshots [0,6,12,18].
  * prelude=1 block, core=2/pass, coda=1; final depth = 4 (earlier core passes'
    blocks rolled back, not accumulated).
  * totalVisits = 48.
  * bank rollback restores the prelude depth (idempotent reset).
  * controllers (has_msgs) active only on core passes p>0, never pass 0.
- This is the proof-first foundation (Federico's Lean rule for complex state
  machines) for implementing the loop runner: the snapshot cadence and rollback
  invariant are verified by construction before the implementation is written.

Verified: lean proofs/inkling_loop.lean green (0 sorryAx); all 5 proof files
green (slab_ring_dma, bus_lifecycle, serve_session, arena_plan, inkling_loop).
2026-12-01 14:53:43 +01:00
adm 2dd9ff952c [HIP][LD] softcap kernel + correct final output path (AttnRes output mix + softcap)
- k_softcap / vetta_softcap: logits = cap*tanh(x/cap), the final logit
  softcapping (Inkling cap=30). Parity vs CPU 9.7e-8; bounds |logits| <= cap.
- ld::layer::final_logits: the CORRECT final output path extracted from the
  reference — the final norm is itself an AttnRes depth mix over the block
  snapshots + cur with the learned output_query, then norm + unembed + softcap:
    h_norm = norm(attn_res_mix(blocks, cur, output_query))
    logits = softcap(unembed(h_norm), 30)
  (The earlier unembed_logits used a plain rms_norm(cur), missing the final
  depth mix; final_logits fixes that.)
- multi_layer_prelude_forward now uses final_logits: argmax token 128538
  (logit 19.16, bounded by 30). The token shifts vs the plain-norm path,
  confirming the final output mix materially affects the result.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU softcap + multi-layer final PASS
(--features hip, --ignored).
2026-12-01 14:51:40 +01:00
adm ff524df917 [LD] multi-layer SWA forward + final norm + unembed -> logits on real weights
- ld::layer: embed_token (real BF16 embed table gather), unembed_logits
  (final norm -> cast -> unembed GEMM over vocab 201024), forward_swa_layers
  (run a schedule of SWA layer steps over an embedded token, threading the
  shared depth-block residual stream across layers).
- multi_layer_prelude_forward test: layers 0..4 composed end-to-end on real
  weights + final norm + unembed -> finite logits, argmax token 183248
  (logit 23.94). Asserts the cross-layer depth-block cadence (prelude 0..4
  snapshots only at ip=0 -> exactly one block). Proves the verified layers
  compose across the deep-residual stream, not just in isolation.

This is a partial (prelude, single-pass) forward — a real multi-layer run
producing logits, NOT yet correct generation. Remaining for a correct first
token: full-attn layers {5,11,17,23} (3-query mix split + tau + dyn shortconv +
global attention), loop controllers (gain/forget/down) for the 3x core passes,
multi-pass bank rollback (prelude/core/coda), final logit softcap + sampling.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; multi-layer prelude forward PASS
(--features hip, --ignored).
2026-12-01 14:46:54 +01:00
adm 0929bde578 [LD] reusable GPU layer forward (ld::layer) with persistent per-layer state
- ld::layer (feature hip): LayerWeights (load_layer reads all attention + MoE
  weights + learned depth-mix queries for a physical step ip), LayerState
  (persistent KV cache + ShortConv history rings, new_state), Dims, and
  layer_forward_swa — a complete SWA layer step composing the verified
  microkernels with the exact Inkling deep-residual cadence:
    ip==0: in0=attn_norm(cur); ip>0: in0=attn_norm(mix(blocks,cur,attn_query))
    attention block -> asc; ip%block_size==0: snapshot cur->blocks, cur=asc
      else cur+=asc
    mlpin=mlp_norm(mix(blocks,cur,mlp_query)); MoE block; cur+=mlp_sconv(moeout)
  The depth-block snapshots are owned by the caller (the forward residual
  stream); experts loaded on demand (zero requantization).
- Refactored real_full_layer_end_to_end to drive the GPU side through
  layer_forward_swa; the unchanged full CPU oracle still verifies it
  (max_rel_err 6.6e-4, identical experts) AND asserts the ip=0 block snapshot.
  This is the reusable foundation for the multi-layer forward.

Scope: SWA layers without loop controllers (prelude). Full-attn 3-query split,
loop controllers (gain/forget/down) and multi-pass bank rollback come next.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real full layer via reusable fn PASS
(--features hip, --ignored).
2026-12-01 14:46:05 +01:00
adm 25ffc820f8 [LD] FULL real Inkling layer end-to-end — deep-residual block-mix cadence verified
- real_full_layer_end_to_end test: a complete Inkling layer-0 (SWA, ip=0) runs
  end-to-end on real weights with the EXACT deep-residual cadence:
    in0 = attn_norm(cur)                 (ip==0: no attention mix)
    asc = attention block(in0)           (projections..flash SWA..O-proj..sconv)
    ip%block_size(6)==0: block0 <- cur; cur = asc   (snapshot + replace)
    mlpin = mlp_norm(attn_res_mix([block0], cur, mlp_queries[0]))
    moeout = MoE block(mlpin)            (router..8 NVFP4 experts..reduce)
    cur += mlp_sconv(moeout)             (MoE residual is a plain add)
- Extracted the exact residual rules from the reference: the AttnRes block
  snapshot/replace applies ONLY to the attention output (ip%6==0 snapshots cur
  then cur=asc, else cur+=asc); the MoE output is always a plain residual add.
  The MoE input is a learned AttnRes mix over block snapshots + cur (mlp_queries).
- Parity vs a full CPU oracle (incl. the block-mix softmax over depth states):
  max_rel_err 6.6e-4, router experts [116,69,124,72,18,64,106,0]. A complete
  real Inkling layer now composes correctly — the deep residual is not a plain
  add but the learned block mixture, reproduced exactly.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real full layer PASS
(--features hip, --ignored).
2026-12-01 14:43:01 +01:00
adm 77c86535d0 [LD] REAL attention block end-to-end on Inkling weights — both layer halves now compose
- real_attention_block_end_to_end test: the attention half of a real Inkling
  layer-0 (SWA) runs end-to-end on real weights, composing the verified kernels:
  attn_norm -> cast -> 6 projections (wq_du/wk_dv/wv_dv/wr_du/gate_attn/
  attn_sink_proj via gemm_bf16) -> ShortConv4 K/V -> Q/R/K L2-clip (qk_clip
  22.627, rel_clip 8.0, tau off for SWA) -> relpos bias projection -> KV store
  (K clipped, V RMS-normalized) -> flash SWA GQA (window 1024 + relpos + sink +
  sigmoid gate) -> cast -> O-proj (wo_ud) -> attn ShortConv4.
- Run T=3 sequential decode steps so the KV cache + shortconv history rings
  grow autoregressively; parity vs a FULL CPU oracle at every step:
  max_rel_err 2.9e-6 / 3.9e-6 / 5.1e-6. The bf16 cast boundaries (input norm ->
  projections, attn out -> O-proj) are handled explicitly.
- With the real MoE block (5.6e-4), BOTH halves of a real Inkling layer now
  compose correctly on real data. Next: join them into a full layer with the
  AttnRes block-mix residual cadence (block_size=6), then loop controllers +
  multi-layer forward + lowering + sampling.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real attention block PASS
(--features hip, --ignored).
2026-12-01 14:40:20 +01:00
adm b5d6d7cee3 [HIP] k2 attention-prep kernels: L2 clip, relpos bias projection, KV store
- k_l2_clip / vetta_l2_clip: exact strata Q/R/K per-head L2 clip — v = x*scale
  (scale nullable), fac = min(1, clip/(sqrt(sum v^2)+1e-6)), optional tau
  fac *= 1 + 0.1*log(max(1,(pos+1)/8192)) (kLogScaleAlpha=0.1, floor=8192);
  x = v*fac, in place. Config: qk_clip=22.627, rel_clip=8.0; tau=!is_swa.
- k_relpos_bias / vetta_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc] *
  rel_proj[rc,dist] for dist < lim=min(pos+1,rel_extent). R pre-clipped
  [n_head,d_rel=16], rel_proj [d_rel,rel_extent=1024] (rel_logits_proj.proj).
- k_kv_store / vetta_kv_store: K (pre-clipped) stored as-is, V RMS-normalized
  (rsqrt(mean v^2 + eps)), into a contiguous f32 KV cache [n_kv,seq,hd] at pos.
  (Paged FP16/FP8 KV pool is a later perf refinement; contiguous f32 first.)
- Combined parity test vs CPU oracles: l2_clip (scale+tau and plain), relpos
  bias, kv_store (K exact, V <1e-5). These complete the k2 attention prep; with
  gemm_bf16 (projections) + shortconv4 + flash_swa_gqa the full attention block
  can now be composed.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 14/14 (--features hip).
2026-12-01 14:38:38 +01:00
adm a5ee804641 [LD] REAL MoE block end-to-end on Inkling weights — verified kernels compose
- real_moe_block_end_to_end test: the MoE half of a real Inkling layer runs
  end-to-end on real layer-0 weights, composing the verified kernels:
  mlp_norm (rms_norm) -> cast f32->bf16 -> router GEMM (gate.weight [128,2304]
  BF16) -> sigmoid top-8 router (gate.bias, route_scale=8) -> 8 real NVFP4
  experts (w13 GEMV -> SiTU beta4/lb25 -> w2 GEMV, outer=amax/denominator) ->
  weighted reduce.
- Parity vs a FULL CPU oracle (rms_norm + bf16-truncate cast + BF16 router GEMM
  + sigmoid top-8 + per-expert NVFP4 dequant GEMV + SiTU + reduce): router ids
  match exactly ([31,124,0,7,69,121,14,2]), output max_rel_err 5.6e-4.
- This is the integration milestone: the individually-verified kernels compose
  into a correct real MoE block on real data, with the bf16 cast boundary
  handled explicitly (the dtype-mismatch bug class). The MoE half of a real
  Inkling layer now runs correctly; the attention half is next.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real MoE block PASS
(--features hip, --ignored).
2026-12-01 14:33:27 +01:00
adm 61c0b21a93 [HIP] AttnRes block-mix kernel — Inkling deep-residual parity (last defining mechanism)
- k_attn_res_mix / vetta_attn_res_mix: exact strata k1_attn_res_mix semantics.
  For each learned query q and token m, mix n_states = n_blocks+1 depth states
  (block snapshots + current): per state inv_rms = rsqrt(mean(x^2)+eps),
  score = (x.q)*inv_rms/sqrt(D); softmax over scores -> w; final weight =
  w*inv_rms; out = sum_s weight[s]*state_s (RMS-normalized depth mix). This is
  Inkling's deep residual that replaces the standard additive residual stream.
  Contiguous blocks [n_blocks,M,D] snapshot buffer (FFI-friendly vs ptr array).
- Parity test vs CPU oracle (nb=3, M=2, nq=2, D=64): max_rel_err 1.0e-5.

With this, ALL defining Inkling mechanisms are verified kernels: ShortConv4,
flash SWA GQA (window+relpos+sink+gate), AttnRes block-mix, NVFP4 experts +
SiTU + sigmoid router. The kernel parity foundation is complete; what remains
is integration (lowering the full graph + wiring a complete layer + loop
controllers + KV store + projections).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 13/13 (--features hip).
2026-12-01 14:30:10 +01:00
adm aea1c437d4 [HIP] flash SWA GQA decode kernel — Inkling attention parity (window+relpos+sink+gate)
- k_flash_swa_gqa_decode / vetta_flash_swa_gqa_decode: exact strata
  k3_flash_swa_gqa semantics on a contiguous f32 KV cache:
  * SWA window: k_start = (window>0 && cur_pos>=window) ? cur_pos-window+1 : 0;
  * relpos bias rel_bias[h,dist] added to the score (dist=cur_pos-s, <max_rel);
  * attention sink_logit[h]: virtual sink token (value 0) contributing
    exp(sink-m) to the softmax denominator only;
  * sigmoid gate_attn[h,d] applied per output dim.
  Two-pass softmax over the windowed range, f32 throughout. rel_bias /
  sink_logit / gate are optional (NULL disables each).
- Parity test vs a CPU oracle across 4 configs (window on/off x relpos x sink
  x gate): max_rel_err 9.4e-7 .. 3.6e-6. The Inkling-specific attention math
  (local window, relative position, sink, gate) is verified.

With ShortConv4, this covers the defining Inkling attention mechanisms; the
AttnRes block-mix deep residual is the remaining parity piece.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 12/12 (--features hip).
2026-12-01 14:28:54 +01:00
adm e060862660 [HIP] ShortConv4 decode kernel (Inkling causal depthwise conv + history ring) verified
- k_shortconv4_decode / vetta_shortconv4_decode: exact strata
  k2_shortconv4_batched static (no-dyn) semantics — per channel
  y = x0 + sw0*h0 + sw1*h1 + sw2*h2 + sw3*x0, scaled by 1/sqrt(5); the 3-tap
  history ring (t-3,t-2,t-1) shifts h0<-h1<-h2<-x0 in place. This is a defining
  Inkling mechanism (applied to k/v/attn/mlp). f32 history here; the BF16 ring
  for bit-exact CPU match is a later parity refinement.
- Multi-step parity test: 6-token recurrence vs a CPU oracle, per-step output
  match (<1e-5) AND device history ring == host history ring after all steps
  (exact). The stateful short-conv evolves correctly across tokens.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 11/11 (--features hip).
2026-12-01 14:26:14 +01:00
adm 00a6993c50 [LD] NVFP4 expert packer (amax/denominator scaling) verified on real Inkling weights
- ld::packer: ExpertMatrix + load_expert_matrix(layer, e, "w13"|"w2") loads a
  real NVFP4 expert from safetensors with ZERO requantization — packed E2M1
  [N,K/2] + E4M3 group scales [N,K/16] to device as-is, outer_scale =
  amax[e] / denominator (denominator tensor read, default 2688 = 448*6 when
  absent — exact strata ink_safetensors_loader semantics).
- Real-weight parity test: layer-0 expert-0 w13 [2304,2304] loaded from the
  real archive, nvfp4_gemv on GPU vs a CPU dequant oracle over the real
  packed bytes + scales + outer_scale. max_rel_err 2.8e-4 (f32 accumulation
  order over K=2304; math identical). Confirms the expert scaling + layout
  against real Inkling data — the key brick for the layered MoE forward.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real expert NVFP4 parity PASS
(--features hip, --ignored).
2026-12-01 14:24:07 +01:00
adm fb94f2321c [LD] GPU weight packer + FIRST real-weight GPU run (Inkling trunk)
- ld::packer (feature hip): load_raw (tensor bytes -> DeviceBuf, dtype
  preserved) + load_bf16_as_f32 (BF16 norm weights upcast to f32 for the
  rms_norm kernel, matching the reference). The bridge from canonical IR to
  GPU-resident weights; the seam where the per-layer loading/precision policy
  (engine-side composition) will be applied.
- FIRST REAL-WEIGHT GPU RUN: load the real Inkling trunk (~1.85 GB: embed +
  unembed [201024,2304] BF16, embed_norm + final_norm) and run embed ->
  embed_norm -> final_norm -> cast -> unembed on gfx1150, producing real
  logits over vocab 201024 + argmax token (20612, logit 27.77, all finite).
  Trunk-only skip-layer baseline — proves packer + executor + sampling on
  real data end-to-end. The full layered forward + Inkling parity refinements
  (AttnRes block-mix etc.) come next for correct generation.
- ld: optional hip + rt deps, feature-gated (default workspace stays
  host-independent).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; real-weight trunk run PASS
(--features hip, --ignored).
2026-12-01 14:19:54 +01:00
adm 1b3896bba9 [RT][ABI] executor dispatches full MoE path; composed MoE expert forward verified on GPU
- rt::executor: dispatch NVFP4 expert GEMV (MoeW13Wmma/MoeW2Wmma -> nvfp4_gemv),
  SiTU activation, MoE weighted reduce. execute_with(get) core + execute /
  execute_refs wrappers (owned or borrowed buffer tables, for shared weights).
- abi::vplan: Situ opcode (32 total).
- Composed MoE expert path test: router -> per-expert (w13 NVFP4 GEMV -> SiTU
  -> w2 NVFP4 GEMV) -> weighted reduce, verified end-to-end vs a full CPU
  oracle (router sigmoid top-k + NVFP4 dequant + SiTU). max_rel_err 9.2e-7.
  The entire MoE compute of the base decode graph now runs composed on GPU.

With the trunk composed forward, the executor proves both halves of the base
graph (attention trunk + MoE experts) compose correctly on real hardware.
Remaining for full inference: lowering CompiledPlans+IR -> ExecOp (shape
attachment) + .vbundle packer (real weights -> device), then Inkling parity
refinements + serve wiring.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 10/10 + rt composed 2/2
(--features hip).
2026-12-01 14:16:04 +01:00
adm 529709cc64 [HIP] SiTU activation + MoE reduce kernels — full MoE primitive set verified
- k_situ: SiTU double-softcapped MoE activation, exact strata situ_f32 —
  g_act = beta*tanh(g/beta)*sigmoid(g), u_act = lb*tanh(u/lb), act = g_act*u_act
  (beta=4, lb=25). gu=[gate;up] from w13 -> act[inter].
- k_moe_reduce: out[d] = sum_e tk_w[e]*y_part[e,d] (weighted expert sum).
- C ABI + safe wrappers (situ, moe_reduce) + CPU-oracle parity tests.

With nvfp4_gemv (w13/w2) + moe_router_topk, the full MoE compute primitive
set is now verified on gfx1150: router -> per-expert nvfp4 GEMV -> SiTU ->
nvfp4 GEMV -> weighted reduce. Parity: SiTU ~4e-7 (inter 1152/64/256),
moe_reduce ~3e-6 (top-8, hidden 2304). Ten GPU kernels verified.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU parity 10/10 (--features hip).
2026-12-01 14:13:30 +01:00
adm bd49da5636 [HIP] NVFP4 expert GEMV kernel (exact E2M1+E4M3 dequant, GPU-verified ~4e-7)
- kernels/hip: NVFP4 (SF4) codecs ported exactly from strata ink_hip_common —
  sf4_e2m1_f32 (E2M1 nibble LUT {0,0.5,1,1.5,2,3,4,6,...}), e4m3fn_to_f32
  (F8_E4M3FN: subnormal mant*2^-9, NaN->0, bias 7). Layout: packed_e2m1
  [N,K/2] (low nib even col), scales_e4m3 [N,K/16], f32 outer_scale.
- k_nvfp4_gemv (M=1 decode): y[N] = dequant(W)[N,K] @ x[K], one block/row,
  threads stride K/16 groups, f32 accumulate. Correctness-first; the Wave32
  bandwidth-saturated path is the performance pass. This is the core of the
  MoE expert compute (w13/w2); the full direct path (SiTU activation +
  weighted reduce) builds on it.
- C ABI + safe wrapper nvfp4_gemv + CPU-oracle parity test (Rust e2m1/e4m3
  matching the kernel).

Verified LIVE on gfx1150: nvfp4_gemv max_rel_err ~4e-7 across (8,64)/(16,256)/
(32,128). Eight compute kernels now verified. Default suite 97/97, lean 4
files green; GPU parity 8/8 (--features hip).
2026-12-01 14:07:14 +01:00
adm 87a66aee37 [RT][HIP] GPU executor core + first composed trunk forward verified on gfx1150
- rt::executor (feature `hip`): the bridge from the arena-validated plan to
  GPU compute. ExecOp { op, reads, writes, params } + OpParams (concrete
  shapes) + execute() dispatching the verified microkernels (embed, rms_norm,
  gemm_bf16, flash_gqa, moe_router, vec_add, cast). Lowering CompiledPlans+IR
  -> ExecOp lands with the packer; this core proves dispatch + composition.
- First COMPOSED GPU forward: embed gather -> rms_norm -> cast f32->bf16 ->
  gemm(unembed), verified end-to-end vs a CPU oracle (<1e-4). The composition
  test caught a real dtype-transition bug (f32 activation fed to a BF16 GEMM)
  — fixed by adding the cast kernel the reference also inserts before matmul.
- kernels/hip: k_cast_f32_bf16 (f32 activation -> BF16 truncate) + C ABI +
  wrapper. abi::vplan: CastF32Bf16 opcode (31 total).
- rt: optional hip dependency, feature-gated (default workspace stays
  host-independent).

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU parity 7/7 + composed trunk
forward 1/1 (--features hip). Principle recorded: parity-first baseline, then
our own measured improvements (Federico).
2026-12-01 13:57:07 +01:00
adm b99d3a7a6a [HIP] attention + MoE router + vec_add kernels (GPU-verified, parity vs reference semantics)
- k_flash_gqa_decode: single-token GQA attention over a f32 KV cache,
  two-pass softmax, correctness-first base. Parity vs CPU oracle ~3e-6 on the
  real Inkling shape (24 heads / 8 KV, hd 128). SWA window / relpos bias /
  sinks / split-KV / WMMA are the later parity+performance refinements.
- k_moe_router_topk: Inkling EXACT sigmoid router, semantics verified against
  strata k4_moe_router_topk — p=sigmoid(logit), score=p+bias, top-K by score
  (smallest eid wins ties), weight=p[chosen], renormalized to route_scale.
  Parity: top-k ids exact, weights ~1e-5 (128 experts, top-8, route_scale 8).
- k_vec_add: y=a+b elementwise (residual stream), exact.
- C ABI + safe Rust wrappers + DeviceBuf byte/i32 transfers + CPU-oracle tests.

Six compute kernels now verified on gfx1150 (embed, rms_norm, gemm_bf16,
flash_gqa, moe_router, vec_add); the base decode graph is covered except the
NVFP4 expert GEMMs (w13/w2) + reduce. Approach: standard correctness-first
math, Inkling-specific features ported from the measured reference (no
invented attention variants); performance pass (WMMA/split-KV) comes after.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU parity 7/7 (--features hip).
2026-12-01 13:53:56 +01:00
adm 356f9c458e [HIP][Docs] embed_bf16 + gemm_bf16 kernels (GPU-verified) + newcomer orientation guide
- kernels/hip: k_embed_bf16_gather (BF16 table -> f32 token rows, exact) and
  k_gemm_bf16 (y[M,N] = x[M,K] @ w[N,K]^T, BF16 in / f32 accumulate,
  correctness-first per-element; WMMA tiling is the later performance pass).
  C ABI + safe Rust wrappers (embed_bf16_gather, gemm_bf16) + DeviceBuf
  byte-level h2d/d2h.
- Verified LIVE on gfx1150: embed exact, gemm max_rel_err 0.0 across
  (2,8,16)/(4,32,64)/(1,128,256), rms_norm ~1e-6. Three kernels now cover the
  trunk + projection compute path (embed, norm, gemm).
- docs/ORIENTATION.md: a guide for newcomers arriving from vLLM/llama.cpp/
  SGLang — what this engine is, the five ideas behind the mental-model shift
  (microkernel+services, models compiled to .vbundle, forward pass as a
  Lean-proven validated plan, proof-first, parity discipline), the crate map,
  the honest current state (CPU pipeline done, GPU begun, no token yet), and
  the ordered road to the first agent chat and beyond. Linked from README.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU parity 4/4 (--features hip).
2026-12-01 04:54:05 +01:00
adm bd0d4f2a63 [HIP] GPU backend bring-up: feature-gated hipcc build + first verified kernel on gfx1150
- New crate vetta-infer-hip: HIP FFI/DMA backend (unsafe isolated here per
  AGENTS.md). Kernel build is feature-gated (`hip`, default OFF) so
  `cargo test --workspace` stays host-independent (97/97, no toolchain).
  build.rs invokes hipcc --offload-arch=gfx1150, archives libvetta_kernels.a,
  links amdhip64 from ROCM_PATH/lib.
- kernels/hip/vetta_kernels.hip: device query, minimal device-buffer
  lifecycle (alloc/free/h2d/d2h, RAII DeviceBuf), and the first microkernel
  k_rms_norm_f32 (one block/row, shared-mem reduction). C ABI extended in
  vetta_kernels.h.
- Safe wrappers: query_device, DeviceBuf, rms_norm_f32.

Verified LIVE on Sogliola (cargo test -p vetta-infer-hip --features hip
-- --ignored): device = AMD Radeon 890M Graphics gfx1150 CU=8 UMA=true;
rms_norm parity vs CPU oracle max_rel_err ~1.3e-6 across rows 1/4/3/2 and
d 2304/128/1024 (tolerance 1e-4). First GPU compute verified end-to-end:
hipcc -> static lib -> FFI -> launch -> parity. This opens the GPU execution
half (executor + remaining kernels toward the first served token).
2026-12-01 04:46:14 +01:00
adm f57060caa7 [LD][ABI][Docs] Inkling base decode graph emitter (675 ops, arena-validated) + full forward blueprint
- ld::inkling_graph: emit_decode_base() generates the complete base decode
  forward from the IR over the unrolled physical schedule: embed ->
  [per-layer: norm -> QKV -> flash -> O-proj -> residual-add -> MLP norm ->
  router -> experts w13/w2 -> reduce -> residual-add] -> final norm ->
  unembed. Live-verified on Inkling: 675 ops, 236 arena decls, validated by
  abi::arena (no overlap / checked bounds / no use-before-write). This is
  the structurally-complete base; Inkling parity refinements (learned
  AttnRes block-mix, loop controllers, ShortConv4, relpos, SWA window,
  paged KV) layer on top next.
- abi::vplan: add the Inkling stage opcodes AttnResMix, ShortConv4, LoopCtrl,
  L2Clip, KvStore, RelPosBias, MoeRouterTopk, VecAdd (30 total, roundtrip).
- ld::inkling_ir: LlmComp derives Copy (used by value in the emitter).
- docs/inkling-forward-design.md: full per-layer sequence extracted from
  forward_batch_chunk (k1 AttnRes block-mix + controllers, k2 projections +
  shortconv + relpos + KV store, k3 flash, O-proj block-boundary rule, k4
  sigmoid router + SiTU experts), real scratch buffer set, deep-residual
  block mechanism (block_size=6 snapshots + learned queries).

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
5 ignored live tests pass (base graph 675 ops); lean proofs (4 files, 42
theorems) green.
2026-12-01 04:39:08 +01:00
adm d478787863 [LD][ABI] Inkling plan foundations: physical schedule + scratch arenas + graph emitter (trunk)
- ld::inkling_plan: physical_schedule() unrolls the looped core (verified
  against the reference logical->physical mapping; Inkling = 6 + 3x12 + 6 =
  48 physical steps over 24 logical layers). scratch_layout()/scratch_plan()
  lay out the decode activation arenas (residual/q/k/v/attn_out/moe/logits),
  4 KiB-aligned with checked offsets, validated by abi::arena.
- ld::inkling_graph: GraphBuilder accumulates arena decls (scratch=0,
  weights=1, inputs=2) + a flat op sequence and validates the whole plan
  (no overlap, checked bounds, no use-before-write) via abi::arena.
  emit_trunk() emits the first complete sub-graph: embed(+embed_norm fused)
  -> final norm -> unembed, arena-validated. The per-layer k1->k4 body plugs
  into the same builder next.
- abi::vplan: add GemmBf16 opcode (BF16 trunk/unembed GEMM).
- docs/inkling-forward-design.md: forward blueprint grounded in the strata
  reference (k1->k4 stage order from kernel numbering, real scratch buffer
  set, loop structure, two forward paths main-LLM + MTP DSpark).

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 96/96 PASS;
4 ignored live tests pass; lean proofs (4 files, 42 theorems) green.
2026-12-01 04:35:46 +01:00
adm 465315ae94 [LD] Inkling ModelImporter foundation: typed config + total tensor classification + validated IR assembly
- ld::inkling: parse_config(config.json) -> InklingConfig (TextConfig,
  LoopConfig, MtpConfig), checked extraction + consistency guards
  (top_k <= n_experts, n_head % n_kv == 0, core_start < core_end).
  full_attention_layers() = complement of local_layer_ids ({5,11,17,23}).
- ld::inkling_ir: classify(name) -> TensorRole, the total tensor-name ->
  typed-role mapping (trunk, per-layer attn projections/sconv/controllers/
  norms, NVFP4 router+experts, attention-residual/cross-pass queries, vision).
  Unknown names -> None (explicit rejection). Verified TOTAL on the live
  archive: 1244/1244 classified, 24 layers.
- ld::inkling_ir: assemble()/assemble_archive() -> InklingIr (trunk + 24
  LayerIr + vision), structural validation vs config (layer count, embed
  shape = vocab x hidden, required per-layer components, expert first dim =
  n_experts). Attention-norm validation is type-aware: SWA layers use
  attn_norm, full-attention layers use q/k/v_input_norm (discovered + fixed
  via the live test, verified on the inventory).
- Opt-in #[ignore] live tests against /mnt/models/Inkling/safetensors
  (config, classification completeness, IR assembly) — all pass; default
  suite stays host-independent.

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 87/87 PASS;
3 ignored live tests pass; lean proofs (4 files, 42 theorems) green.
2026-12-01 04:27:56 +01:00
adm 4de272beb1 [ABI][GW][Docs] encoder guard fields + sha256 provenance; Inkling tensor inventory; BGE-M3 recipe correction
- abi::bundle: manifest guard fields from the strata-ctl encoder incident
  (review/2026-12-01-guardie-encoder.md): provenance {repo_id, revision,
  shards sha256 = HF lfs.oid anchor, 64 lowercase hex validated},
  model_kind decoder|encoder (encoder REQUIRES the full encoder_recipe:
  pooling, end_text_token id, append_end_text, max_tokens, query/doc prefix,
  native_dim — never derived from architecture), calibration {floor_hit,
  peak_noise} finite in [-1,1]. Identity is provenance, not tensor shape.
- abi::sha256: pure FIPS 180-4, streaming update for GB shards, zero deps;
  NIST vectors + million-a + streaming/chunk parity tests.
- abi::vplan: pool_l2norm generalized (mode mean|cls|last_token from the
  manifest recipe), replacing mean_pool_l2norm.
- gw: `vetta-infer tensors <dir> [prefix]` subcommand; captured the live
  Inkling inventory (docs/inkling-tensor-inventory.txt, 1244 tensors:
  994 BF16 / 154 F32 / 48 F8_E4M3 / 48 U8) — ground truth for the importer.
- BGE-M3 recipe verified on the artifact: dense = CLS (1_Pooling/config.json
  + reference converter), 16 heads x 64, absolute position embeddings present;
  spec/README corrected. Ordering: Inkling first, utility after (Federico).
- review/: tandem exchange (guardie + nostra risposta + osservazioni-recipe).

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 75/75 PASS;
lean proofs/{slab_ring_dma,bus_lifecycle,serve_session,arena_plan}.lean green
(42 theorems, 0 sorryAx, standard axioms only).
2026-12-01 04:17:12 +01:00
adm fb92662106 [ABI][LD][Proofs][Docs] M1 groundwork: arena-safety proof + .vbundle contract; embedder lane (M1.5) accepted
- proofs/arena_plan.lean: memory.vplan arena safety (8 theorems + 4
  computational examples, 0 sorryAx): no overlap, checked index bounds,
  no use-before-write, overlap-rejection completeness.
- abi::arena: validator mirroring the proof, checked offset arithmetic
  (invariant #2), explicit error per violation class; 8 tests.
- abi::bundle: .vbundle manifest (ABI_VERSION=1, source+packer fingerprints,
  backend target; incompatible ABI rejected explicitly), checked
  memory.vplan/graph.vplan parsing, arena-validated compile(); 7 tests.
- ld::bundle: read-only load_bundle_plans(dir) over manifest + plan/*.vplan;
  3 tests (good bundle, missing file, ABI mismatch).
- abi::vplan: encoder-lane opcodes (layer_norm, flash_full_attn, gelu_erf,
  mean_pool_l2norm) + wire name mapping for all 22 opcodes, roundtrip test.
- Docs: utility-encoder scope carve-out (dense decoder LMs out, small
  fully-resident encoders in), embedder-lane wire proposal + characteristic
  parity vs vetta-semantics (cosine vs oracle, internal bit-exact goldens),
  16-primitive kernel set, M1.5 milestone; README/AGENTS aligned
  (65 tests, 42 theorems across 4 proof files).
- review/: tandem exchange with the strata-ctl coder (their request +
  observations, our formal reply: embedder accepted, M0 dir cleanup done).

Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 65/65 PASS;
lean proofs/{slab_ring_dma,bus_lifecycle,serve_session,arena_plan}.lean green,
standard axioms only.
2026-11-30 15:22:00 +01:00
adm 7b50f1c07c [ABI][KN][LD][CC][RT][LAB][SP][NT][TM][GW][Proofs][Docs] M0.5: realign workspace to vetta-infer-* microkernel architecture
Dissolve the M0 crates (core/io/proto/telemetry/hip/cli) into the approved
service layout abi/kn/ld/cc/rt/lab/sp/nt/tm/gw (docs/ARCHITECTURE.md).

- kn: Lean-verified control bus + service registry (bus_lifecycle.lean, 14 thms)
  and SlabRing/UMA broker; rt: PrefixState + hybrid checkpoint pool.
- sp: faithful throughput-aware Adaptive-K port of clover_policy.h
  (cooldowns, probes, throughput guards) with scenario parity tests.
- gw: strata-ctl-compatible wire emitters + serve session FSM
  (serve_session.lean, 10 thms); abi::serve accepts image= (Vision delta closed).
- abi: pure contracts, checked JSON/VTC1/GEN parsers, zero-alloc sampler.
- ld/cc: checked safetensors reader + write-once VTC1 writer / O_RDONLY reader.
- tm: lock-free telemetry; nt: LyraRpc; lab shares the rt executor core.
- Docs: ARCHITECTURE.md decision-complete spec (MoE-only scope, .vbundle,
  .vplan->CompiledPlan, wire contract, migration map); AGENTS.md Lean rule
  + tandem/review workflow.

Verified live: cargo test --workspace -D warnings = 46/46 PASS;
lean proofs = 34 theorems (slab_ring_dma 10, bus_lifecycle 14, serve_session 10),
0 sorryAx, standard axioms only; vetta-infer info on Inkling = 1244 tensors,
18.18 GiB, checked bounds.
2026-11-30 00:54:00 +01:00
adm 63b1668a92 [Core] M0 foundation: workspace, Lean 4 SlabRing/PrefixState contracts, checked safetensors/cache IO, serve proto, telemetry, and HIP ABI 2026-11-29 21:32:44 +01:00