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.
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).
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.
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.
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.
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.
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.
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.