README + ORIENTATION refreshed to the measured current state (the 618s sequential first-token is now historical): chunked batched prefill + FP16 WMMA MoE + BF16 WMMA dense + FlashAttention-2 WMMA prefill => synthetic 2048 prefill 60->12.9s (-78%), ~6.3ms/token (16k agent prompt ~105s, was ~7min); greedy-vs-reference EXACT gate, internal M=1-vs-M=B parity global-scale tolerance (P1 policy). Flat bounded VRAM (persistent states, SWA-window ckpt, cap8 grid-protected prefix cache, 512MiB pool cap, long->short KV reuse). Budget clamp (clamp_max_new) + configurable window (--max-context): 16504-token prompt generates live (was ERR 0). Roadmap: drafter integration next, then DMA layer streaming (io_uring O_DIRECT + hipHostRegister SlabRing) as the hard memory frontier; INT8 fused MoE + HIP graph capture remain. Lean verify list now 6 files (prefix_cache.lean). Includes the two 2026-12-02 peer audits in review/.
87 lines
8.1 KiB
Markdown
87 lines
8.1 KiB
Markdown
# Diagnosi Prefill (~70 s vs ~5 s) e Prefix Cache (`restored=0`) — Nota di Allineamento
|
||
|
||
- **Data:** 2026-12-02
|
||
- **Stato ispezionato:** `vetta-infer` `main` @ `01d8a48` (+ diff locale `VETTA_DBG_PREFIX` in `serve.rs`), `inkling-server.service` live su Sogliola (`gfx1150`, RDNA 3.5).
|
||
- **Modalità:** Analisi in sola lettura (nessun sorgente toccato).
|
||
- **Premessa:** La base costruita su `vetta-infer` è eccellente — parità **BIT-EXACT** end-to-end su `forward_batch`, 6 file di prove Lean 4 (`0 sorryAx`), MoE grouped CSR su GPU, fix VRAM `01d8a48`. Il divario misurato rispetto al riferimento C++/HIP `strata-inkling` (`~70 s` vs `~5 s` sul prefill di ~2646 token, e `restored=0` al Turno 2) **non è dovuto all'architettura Rust/microkernel**, ma a **5 punti molto precisi** rimasti alla fase *correctness-first*.
|
||
|
||
---
|
||
|
||
## 1. Perché la Prefix Cache non scatta tra Turno 1 e Turno 2 (`restored=0`)
|
||
|
||
Dai log live di `journalctl --user -u inkling-server.service` (01:14–01:18):
|
||
|
||
```text
|
||
01:14:41 [prefix] prompt_len=2646 restored=0
|
||
01:15:51 [prefix] prompt-boundary save seq=2646 (~70 s prefill)
|
||
01:16:02 [prefix] full-sequence save seq=2698
|
||
01:16:36 [prefix] prompt_len=2738 restored=0
|
||
01:16:36 [prefix] ck[0] len=2646 common_prefix=2644
|
||
01:16:36 [prefix] ck[1] len=2698 common_prefix=2644
|
||
01:17:49 [prefix] prompt-boundary save seq=2738 (~73 s prefill da zero!)
|
||
```
|
||
|
||
### Causa esatta
|
||
- Al Turno 2 i primi **`2644` token su `2646` (`99.92%`) sono identici**, ma il prompt diverge sugli **ultimi 2 token** (`2644..2646`, il tag di apertura/chiusura turno che `strata-ctl` serializza diversamente quando il Turno 1 diventa storico).
|
||
- In `crates/vetta-infer-gw/src/serve.rs:379-384` viene salvato un checkpoint **solo** a fine prompt (`seq=2646`) e a fine risposta (`seq=2698`), e `best_match()` richiede match esatto sull'intero `ck.tokens`. Per soli **2 token di coda**, scarta tutto e riparte da `0`.
|
||
|
||
### Fix consigliato (impatto immediato sul multi-turno)
|
||
1. **Salvataggio su griglia multi-livello durante il loop di prefill** (come `--auto-ckpt` in `strata` / `proofs/auto_ckpt_pool.lean`): salvare checkpoint intermedi ogni `512` token (o su ancore pinnate `{512, 1024}` + griglia `2048, 2560, ...` usando `next_ckpt_boundary`), **oppure** al confine di ciascun chunk `256` quando si supera la soglia `512`.
|
||
2. Su quel Turno 2 (`common_prefix=2644`), un checkpoint intermedio a `2560` (o `2048`) fa scattare subito `RESUME 2560` riducendo il prefill del Turno 2 da **2738 token** a **178 token** (**`-93.5%`**!).
|
||
3. *(Bonus per la memoria VRAM dei checkpoint):* come in `strata-inkling`, sui 40 pool SWA serve salvare solo gli ultimi `min(seq_len, 1024)` token della finestra SWA, non l'intero `0..seq_len`.
|
||
|
||
---
|
||
|
||
## 2. Perché il prefill a contesto vuoto impiega ~70 s (`38 ppts`) vs ~5.8 s (`458 ppts`) di `strata`
|
||
|
||
In ordine di peso stimato sui ~70 s di prefill (`B=256`, 11 chunk, 48 visite/chunk):
|
||
|
||
### P0 — `k_gemm_bf16` è scalare `1 thread = 1 elemento` (ZERO tiling / LDS / WMMA)
|
||
- **Dove:** `kernels/hip/vetta_kernels.hip:192-214`, usato da tutte le proiezioni trunk (`wq, wk, wv, wr, wg, ws, wo`, i 4 controller `down/gain/forget`, `k_proj/v_proj` e `unembed_logits`).
|
||
- **Impatto:** ogni thread fa `for (int kk = 0; kk < K; ++kk)` leggendo `X` e `W` senza shared memory né WMMA → una frazione di TFLOP/s contro i **22.14 TFLOP/s FP16/BF16 WMMA** (o **~44 TFLOP/s INT8 WMMA** con `--trunk-q8` / `Q8_G64`) su `gfx1150`.
|
||
- **Riferimento in `strata-safetensors`:**
|
||
- `hipBLASLt` BF16 (o `rocBLAS` / kernel `16×16×16` WMMA LDS-tiled) per `M > 24`, e `Q8_G64` (`k_q8_g64_gemm_small<16>` per `M <= 24`, `k_q8_g64_gemv` Wave32 per `M = 1`) — in `strata-safetensors/engine/src/inkling2/hip/ink_hip_ops.hip.h`.
|
||
- Inoltre `wq/wk/wv/wr/wg` condividono lo stesso input `in0_bf` nei 40 layer SWA: fonderli in un solo `qkvrg` GEMM (come `trunk_qkvrg_q8_` in `strata`) elimina 4 lanci + 4 riletture di `X` per visita.
|
||
|
||
### P1 — `25.2 MB` di `vec![0f32]` + `hipMemcpy` SINCRONO dentro OGNI visita solo per azzerare `rel_bias` (+ altri `h2d` sincroni in `moe_batched`)
|
||
- **Dove:**
|
||
- `crates/vetta-infer-ld/src/layer.rs:1281-1282` (e ramo SWA batched):
|
||
```rust
|
||
let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?;
|
||
rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?;
|
||
```
|
||
Con `bu=256, n_head=24, rel_extent=1024`: **`25.17 MB` allocati/azzerati su CPU e trasferiti con `hipMemcpy` bloccante × 48 visite × 11 chunk ≈ `13.3 GB` di copie sincrone** per un solo prompt!
|
||
- `crates/vetta-infer-ld/src/layer.rs:776` (`dcnt.h2d_bytes(&vec![0u8; 129 * 4])`) e `layer.rs:790-792` (`didx.h2d_bytes(&idx_bytes)` per l'identità `0..total`): altri **96 `hipMemcpy` sincroni per chunk** che drenano la coda GPU dentro ogni layer MoE!
|
||
- **Fix (pochi minuti, guadagno immediato):**
|
||
1. In `k_relpos_bias_batched` (`vetta_kernels.hip:1726-1730`), scrivere `0.0f` direttamente per `dist >= lim` (oppure `hipMemsetAsync`) → **0 byte di `h2d`**.
|
||
2. Esporre `vetta_buf_zero_async` (`hipMemsetAsync`) per `dcnt`, e permettere `bucket_tok == nullptr` nei kernel `grouped_gemv` (usando `tok = beg + t0 + m` per `w2`) → **0 sync host dentro `moe_batched`**.
|
||
|
||
### P1 — `k_flash_swa_gqa_prefill_f16` è scalare con `scores_scratch` in VRAM globale
|
||
- **Dove:** `kernels/hip/vetta_kernels.hip:500-578`.
|
||
- **Impatto:** lancia `grid(24, 256)` con loop scalare `for d=0..128` e materializza `scores_scratch` in VRAM (`256 * 24 * 2646 * 4 B ≈ 65 MB` di scritture+letture per visita full-attn!).
|
||
- **Riferimento in `strata-safetensors`:** `k3_flash_swa_gqa_prefill_wmma` (`64×64` FP16 WMMA online-softmax interamente in LDS, `0 B` di `scores_scratch` in VRAM, misurato **`8.5×` più veloce** già a `B=63` e `>12×` a `B=256`).
|
||
|
||
### P2 — Layer 20–23 (`k_mxfp8_grouped_gemv_f16`) scalare senza `fdot2` + grid pieno su 128 expert
|
||
- **Dove:** `kernels/hip/vetta_kernels.hip:1303-1356`.
|
||
- **Impatto:** usa `for j=0..32` scalare con riduzione in shared memory (`256` thread per 1 riga!) invece di Wave32 `fdot2` + `wave32_sum` come nel path NVFP4 (`k_nvfp4_grouped_gemv_f16` che invece è già scritto benissimo!).
|
||
|
||
---
|
||
|
||
## 3. Nota rapida sul Decode `M=1` (~4–6 tok/s oggi vs ~17–18 tok/s in `strata`)
|
||
Anche il decode (senza drafter) può salire ~3–4× con 3 interventi mirati sugli stessi punti:
|
||
1. **Sostituire `k_gemm_bf16` con Wave32 GEMV (`fdot2` / `Q8_G64`)** su trunk e soprattutto su `unembed_logits` (`layer.rs:622`: `N=200058, K=2304` con 1 thread/elemento scalare pesa decine di ms a ogni token!).
|
||
2. **Eliminare i round-trip `d2h`/`h2d` sincroni dal decode `M=1`:** in `forward_inkling_with_state` (`layer.rs:864-895`), `layer_forward_full` (`layer.rs:1109-1120`), `final_logits` (`layer.rs:634-635`) e `LoopMsgs::channel` (`layer.rs:1367-1370`), il path `M=1` fa ancora `d2h`+`h2d` sincroni su `blocks` e `msgs` — quando in `forward_batch` avete **già** `BatchBlocks` + `copy_f32` + `gather_channel` 100% device-side! Riusarli con `B=1` azzera i sync nel decode.
|
||
3. **Cache NVMe `VTC1` (`O_RDONLY`) + arena scratch riusabile:** riusare i `DeviceBuf` scratch pre-allocati per chunk/token invece di chiamare `DeviceBuf::alloc` ~40 volte per layer (e poi catturare il decode `B=1` in HIP Graph).
|
||
|
||
---
|
||
|
||
## 4. Ordine di attacco suggerito (massimo ritorno per minimo sforzo)
|
||
|
||
| Passo | Intervento | Sforzo | Effetto atteso |
|
||
| --- | --- | --- | --- |
|
||
| **1** | Griglia checkpoint `512/1024/2048` (o fine chunk 256) in `serve.rs` | ~15 righe | Turno 2+: `restored=2560`, prefill multi-turno **`-93%`** subito |
|
||
| **2** | Via i `h2d` sincroni (`rel_bias` in-kernel, `hipMemsetAsync`, `bucket_tok=nullptr` su `w2`, `BatchBlocks` su `M=1`) | ~1 ora | Elimina `~13.3 GB` di `h2d` bloccanti/prompt + sblocca la pipeline GPU |
|
||
| **3** | Sostituire `k_gemm_bf16` con WMMA / `hipBLASLt` (prefill) + Wave32 GEMV / `Q8_G64` (decode + `unembed`) | ~mezza giornata | Taglia il 60–70% del prefill e porta il decode verso `~14–18 tok/s` |
|
||
| **4** | Portare `k3_flash_swa_gqa_prefill_wmma` (`64×64` FP16 WMMA LDS) + Wave32 `fdot2` su `mxfp8` | ~mezza giornata | Prefill cold da `~70 s` → **`~5–6 s` (`~400–450+ ppts`)** |
|
||
| **5** | Arena scratch riusabile + HIP Graph sul decode `B=1` | ~1 giorno | Abbattimento overhead CPU launch (`54%` → `< 5%`) |
|