Root cause of speculative losslessness divergence: the FA2 WMMA prefill flash
rescales o_acc/row_sum over a mixed-position query tile up to q_max_pos, so a
query's output depended on its batch neighbours by ~1 ulp (masked extra KV block
still rescales; __expf(0) is not exactly 1). That 1-ulp drift bf16-rounds into the
ShortConv hist and accumulates until a greedy near-tie flips (gate diverged at
token 46). The scalar f16 flash is per-query deterministic. Make WMMA flash OPT-IN
(VETTA_FLASH_WMMA=1); default to the verified scalar baseline. Guard alpha=1.0
exactly when nm==row_max. New flash_batch_determinism test: query0 M=2 vs M=1
maxdiff=0. Also add k_dspark_scatter_bf16 (f32 rows -> bf16 ring at pos%cap) for
DSpark context commit. hip suite 45/45.
k_shortconv4_hist_snaps: snaps[t] (t=0..B) = [3,C] history after t tokens of
in_x from hist0, same bf16-round/shift semantics as update_hist. Enables exact
DSpark partial-accept rollback (hist <- snaps[accepted]); the KV ring truncates
with no data restore (proofs/speculative_draft.lean kept_rejected_disjoint).
Parity: snaps[t] == verified update_hist on prefix t, all 9 prefixes EXACT.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
- 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).
- 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).
- 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).
- 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).
- 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).
- 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).