Files
vetta-infer/review/2026-12-02-fix-drafter-e-ottimizzazioni.md

203 lines
18 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Fix e ottimizzazioni DSpark drafter (`vetta-infer`)
**Data:** 2026-12-02
**Hardware di misura:** AMD Radeon 890M (`gfx1150`, RDNA 3.5 UMA, 48 GiB VRAM)
**Modello:** `/mnt/models/Inkling/safetensors/` (trunk 19 GB NVFP4/BF16 + `mtp.safetensors` 607 MB BF16)
**Baseline di partenza:** commit `91c1baa` / `ba51499` (Step 1 completato)
---
## 1. Sintesi del risultato
La matematica del drafter DSpark era corretta (`dspark_draft_parity` 7/7 e `spec_lossless_gate` 200/200), ma il throughput crollava con `n_draft` crescente (`4.58 tok/s` a `nd=5`, `6.11 tok/s` a `nd=2` sul prompt breve) invece di scalare come in `strata-inkling`.
Dopo gli interventi descritti sotto, su **entrambi** i workload misurati il drafter scala in modo pulito e **eguaglia/supera `strata-inkling --draft dspark`** con parità greedy **100% bit-exact**:
- **Coding reale in Rust (`RingBuffer<T>`, 128 token, chat template Inkling):**
- `vetta-infer` spec OFF: **`6.83 tok/s`** (`18,742 ms`)
- `vetta-infer` spec ON (default `VETTA_SPEC=1`, EMA adattivo, `n_draft=5`): **`13.93 tok/s`** (`9,188 ms`, **2.04× speedup**, 100% EXACT)
- `strata-inkling --draft dspark` (stesso prompt): **`13.66 tok/s`** (`9,372 ms`, 100% EXACT)
- **Prosa breve (`"The capital of France is"`, 96 token):**
- Prima (`ba51499`): `OFF 4.01` | `nd=2 6.11` | `nd=5 4.58 tok/s`
- Dopo: `OFF 4.63–4.70` | `nd=2 9.21` | `nd=5 9.09 tok/s` (**+98.5% / ~2× più veloce a `nd=5`**; EMA adattivo `8.93 tok/s` decode)
---
## 2. Cause radice trovate (7 colli di bottiglia + 2 bug di correttezza)
### Prestazioni (perché `nd=5` collassava a `4.58 tok/s`)
1. **`dspark_draft` leggeva `unembed` (922 MB BF16) `nd` volte con 4 sync CPU↔GPU per ogni step:**
Ad ogni step `1..=nd` veniva lanciato un full GEMV `[200058 × 2304]` su `unembed` (4.6 GB di banda buttati a `nd=5`), più un loop di copie D2H/H2D sincrone per il Markov head e l'argmax su CPU.
2. **Doppio `unembed` + 4.8 MB D2H + argmax su CPU in `spec_round`:**
`spec_round` chiamava `forward_batch_taps` (che faceva già 1 `unembed` sull'ultima riga) e poi rifaceva un `gemm_bf16` su tutte le `B = nd + 1` righe di `taps[3]`, copiava `B × 200058 × 4 B` (`4.8 MB` a `nd=5`) su CPU e cercava l'argmax in Rust.
3. **`gemm_bf16` usava il kernel scalare lento per `m < 16`:**
Il dispatch WMMA si attivava solo per `m >= 16`; tutte le verify speculative (`m = 2..8`) e il decode (`m = 1`) cadevano sul kernel scalare.
4. **MoE `expert_arena_grouped_gemv_f16` usava WMMA `16×16` anche per `b <= 12`:**
In verify speculativo (`b = 3..8`) quasi tutti i bucket di esperti hanno 1–2 token: il tile WMMA `M=16` paddava 14–15 righe a zero sprecando compute.
5. **48 `hipMalloc` + 48 `hipFree` sincroni per round nella SWA GQA verify (`m < 16`):**
`flash_swa_gqa_prefill_f16` allocava e liberava `scores_scratch` a ogni layer SWA quando `m > 1`, inserendo 96 sincronizzazioni di driver per singolo round speculativo.
6. **`k_router_gemv_batched` scalare (non vettorizzato e non M-tiled):**
I 3 layer DSpark (`B = 8`) rileggevano i pesi BF16 8 volte invece di 1 sola volta.
7. **Governatore EMA bloccato su `n_draft = 2`:**
La vecchia soglia era basata sul **rapporto** `accepted / nd` (`>= 0.90 -> 7`, `>= 0.75 -> 4`, altrimenti `2`). A `nd=5` sul codice accettare 2.3 token/round significa `ratio = 0.46`, che forzava il governatore a scendere a `n_draft = 2` (tagliando del ~17% la velocità sul codice!).
### Bug di correttezza in produzione (chat lunga e multi-turn)
8. **Crash garantito LDS > 64 KiB su contesto lungo (`k_dspark_block_attn`):**
Il vecchio kernel allocava `(c_len + B + hd) * 4` byte di shared memory. Sul layer Global `il = 1` (`c_len = anchor_pos`), sopra `~16,248` token superava i 64 KiB di LDS di RDNA 3.5 causando il fallimento del lancio HIP.
9. **`PrefixCache` non salvava/ripristinava `DsparkContext`:**
Al Turno 2+ di una conversazione, il `RESUME` ripristinava solo i KV del trunk lasciando i ring `k/v` e `frnn` di `DsparkContext` azzerati o di un'altra sessione, corrompendo i draft del turno successivo. Inoltre `DsparkContext` veniva riallocato a ogni richiesta invece di restare persistente su `InklingEngine`.
---
## 3. Modifiche applicate (file per file)
### [`kernels/hip/vetta_kernels.hip`](../kernels/hip/vetta_kernels.hip)
- **`k_dspark_block_attn_w32` (fast path `hd == 128` in `vetta_dspark_block_attn`):** online-softmax Wave32 interamente nei registri con **0 byte di LDS** (risolve il crash >16.2k token) e load vettorizzati `float4`/`uint2`.
- **`k_router_gemv` e `k_router_gemv_batched`:** riscritti con Wave32 vettorizzato `uint4`/`float4` (`8` wave/blocco) e **M-tiling per 8 righe**, così `B = 8` nei layer DSpark legge i pesi una sola volta (8× meno banda).
- **Drafter 100% su GPU (zero sync nel loop Markov):**
- `k_dspark_base_top2_screen`: singolo passaggio su `unembed` per tutti gli `nd <= 7` step contemporaneamente, producendo i Top-512 candidati per step (`n_cand = 512`, con modalità esatta all-tokens se `V <= n_cand`).
- `k_dspark_markov_proj_bf16`, `k_dspark_markov_corr_bf16`, `k_dspark_cand_argmax_s1`/`s2`: proiezione Markov ricorrente, correzione sui 512 candidati e argmax interamente on-device.
- **`k_batched_argmax_f32`:** argmax batched su GPU per la fase di verify (`B * 4` byte D2H invece di `B * 800 KB`).
- **`k_flash_swa_gqa_smallm_f16`:** kernel Wave32 deterministico per-query online-softmax (`hd == 128`) condiviso tra decode `M = 1` e verify `M < 16` con **0 allocazioni `scores_scratch`** (elimina le 48 `hipMalloc` + 48 `hipFree` per round).
### [`crates/vetta-infer-hip/src/lib.rs`](../crates/vetta-infer-hip/src/lib.rs)
- Aggiunti binding FFI e wrapper Rust safe con bounds checking per `dspark_base_top2_screen`, `dspark_markov_proj_bf16`, `dspark_markov_corr_bf16`, `dspark_cand_argmax`, `batched_argmax_f32`.
- Cablato `k_flash_swa_gqa_smallm_f16` in `flash_swa_gqa_decode_f16` e `flash_swa_gqa_prefill_f16` (`m < 16`).
- Esteso il dispatch WMMA in `gemm_bf16` a `m >= 1 && k % 64 == 0` (prima era `m >= 16`).
- Aggiunto test GPU di regressione `dspark_block_attn_long_context_no_lds_overflow` a `c_len = 17_000`.
### [`crates/vetta-infer-ld/src/packer.rs`](../crates/vetta-infer-ld/src/packer.rs) e [`crates/vetta-infer-ld/src/layer.rs`](../crates/vetta-infer-ld/src/layer.rs)
- `expert_arena_grouped_gemv_f16` ora riceve `b: i32` e usa `nvfp4_grouped_gemv_f16` (`fdot2`, bit-exact rispetto a `M=1`) per `b <= 12` e `nvfp4_grouped_gemm_wmma` per `b > 12` (override `VETTA_FORCE_MOE_WMMA=1` mantenuto per A/B).
- Aggiunta `forward_batch_taps_no_logits` (`skip_unembed = true`) usata da `spec_round` per eliminare il doppio `unembed`.
### [`crates/vetta-infer-ld/src/dspark.rs`](../crates/vetta-infer-ld/src/dspark.rs)
- Riscritta `dspark_draft` con `dspark_base_top2_screen` + loop Markov su GPU e una sola copia D2H finale (`<= 32 byte`).
- Riscritta `spec_round` usando `forward_batch_taps_no_logits` + singolo `gemm_bf16` batched + `batched_argmax_f32` (`B * 4` byte D2H) + commit di `dctx` solo per i token effettivamente accettati.
- Aggiunti `DsparkSnapshot`, `DsparkContext::snapshot` e `DsparkContext::restore` (gestione corretta del wrap-around sui ring SWA dei layer 0/2, stato completo sul layer Global 1 e `frnn[seq - 1]`).
### [`crates/vetta-infer-gw/src/serve.rs`](../crates/vetta-infer-gw/src/serve.rs)
- `dctx: RefCell<Option<DsparkContext>>` reso persistente su `InklingEngine` (riallocato solo se `cap > c.cap`).
- Integrato `dspark: Option<DsparkSnapshot>` in `Checkpoint` / `PrefixCache::save` / `PrefixCache::restore`: se un checkpoint ripristinato non ha stato DSpark (es. salvato con spec OFF), `spec_enabled` scende pulitamente a `false` per quel turno evitando di eseguire il drafter su ring azzerati.
- Aggiornato il governatore adattivo da ratio (`accepted / nd`) a **EMA dei token accettati per round** (`ema_acc`, partenza `2.0`, `n_draft = 5`, aggiornamento `0.85 * ema_acc + 0.15 * acc`, scala `7 / 5 / 4 / 3 / 2` per soglie `>= 3.5 / 2.0 / 1.1 / 0.6`).
- Aggiunto test GPU di regressione `serve_gen_spec_prefix_cache_multi_turn_parity`.
---
## 4. Benchmark misurati (`gfx1150`, stesso hardware e modello)
### A. Prompt reale di coding Rust (`RingBuffer<T>`, 69 token prompt, `GEN 128`, `temperature=0`, warm)
| Motore / Configurazione | Decode ms (128 tok) | Decode tok/s | Speedup vs OFF | Rounds | Accettati / Offerti | Match vs OFF |
|---|---:|---:|---:|---:|---:|:---:|
| `vetta-infer` OFF | `18,742.3 ms` | `6.83 tok/s` | `1.00×` | — | — | baseline |
| `vetta-infer` `VETTA_SPEC_ND=2` | `10,730.6 ms` | `11.93 tok/s` | `1.75×` | 53 | `74 / 104` (71.2%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=3` | `9,208.9 ms` | `13.90 tok/s` | `2.04×` | 43 | `84 / 128` (65.6%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=4` | `9,164.0 ms` | `13.97 tok/s` | `2.05×` | 40 | `87 / 157` (55.4%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=5` | `9,347.0 ms` | `13.69 tok/s` | `2.00×` | 39 | `88 / 190` (46.3%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=6` | `9,382.9 ms` | `13.64 tok/s` | `2.00×` | 37 | `90 / 222` (40.5%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=7` | `9,421.8 ms` | `13.59 tok/s` | `1.99×` | 36 | `91 / 251` (36.3%) | **EXACT** |
| **`vetta-infer` `VETTA_SPEC=1` (EMA default)** | **`9,188.0 ms`** | **`13.93 tok/s`** | **`2.04×`** | **39** | **`88 / 177` (49.7%, `n_draft=5`)** | **EXACT** |
| `strata-inkling --draft dspark` | `9,372.2 ms` | `13.66 tok/s` | — | ~39 | `90 / 195` (46.2%) | **EXACT** |
*(Overhead di `dc.commit` in prefill misurato sul medesimo prompt: `509.6 ms` SPEC vs `506.0 ms` OFF wall-time = `+3.6 ms` / `+0.7%`.)*
### B. Prompt breve canonico (`"The capital of France is"`, 5 token prompt, `GEN 96`, `temperature=0`)
| Configurazione | Prima (`ba51499`) decode tok/s | Dopo decode tok/s | Delta |
|---|---:|---:|---:|
| `OFF` (totale `serve_gen_spec_perf`) | `4.01 tok/s` | `4.63–4.70 tok/s` | `+16%` |
| `VETTA_SPEC_ND=2` | `6.11 tok/s` | `9.21 tok/s` | `+51%` |
| `VETTA_SPEC_ND=3` | `5.78 tok/s` | `8.98–9.09 tok/s` | `+57%` |
| `VETTA_SPEC_ND=4` | `5.54 tok/s` | `8.83–8.93 tok/s` | `+61%` |
| `VETTA_SPEC_ND=5` | **`4.58 tok/s`** | **`9.02–9.09 tok/s`** | **`+98.5%`** |
| `VETTA_SPEC_ND=7` | `5.15 tok/s` | `8.43–8.72 tok/s` | `+69%` |
| `VETTA_SPEC=1` (EMA default) | `6.09 tok/s` | `8.93 tok/s` (`n_draft=4`, `48/155`) | `+47%` |
---
## 5. Validazione eseguita (tutto verde)
- **Workspace CPU con `-D warnings`:** `RUSTFLAGS="-D warnings" cargo test --workspace` → **100% PASS, 0 warning**.
- **Prove formali Lean 4:** tutti e 7 i file in `proofs/*.lean` verificati con `lean` → **0 `sorryAx`**.
- **Kernel HIP GPU (`vetta-infer-hip --ignored --test-threads=1`):**
- `dspark_block_attn_parity`: `max_rel_err = 5.668e-7` (**PASS**)
- `dspark_block_attn_long_context_no_lds_overflow` (`c_len = 17_000`): `max_rel_err = 5.091e-5` (**PASS**)
- `router_gemv_batched_parity`: `max_rel_err = 0.000e0` (**PASS**)
- `gemm_bf16_parity_vs_cpu`: `max_rel_err = 1.570e-6` (**PASS**)
- **Drafter & lossless gate (`vetta-infer-ld --ignored --test-threads=1`):**
- `dspark_draft_parity`: 7/7 EXACT (**PASS**)
- `spec_lossless_gate`: **200 token EXACT match** (`rounds=165 offered=1127 accepted=34`) (**PASS**)
- **Serve & PrefixCache (`vetta-infer-gw --ignored --test-threads=1`):**
- `serve_gen_spec_multi_token_parity`: 16 token di riferimento EXACT (**PASS**)
- `serve_gen_spec_prefix_cache_multi_turn_parity`: `off_resumed=45 on_resumed=45`, Turn 1 (16 tok) e Turn 2 (24 tok) 100% EXACT (**PASS**)
- `serve_gen_spec_perf`: OFF `4.63 tok/s` | ON decode `8.93 tok/s` (**PASS**)
- **Build release:** `cargo build --release --features hip` completata senza warning (`target/release/vetta-infer` aggiornato).
---
## 6. Note operative
- Il drafter resta **opt-in** via `VETTA_SPEC=1` (path di default `OFF` invariato e +16% più veloce grazie al dispatch WMMA su `gemm_bf16` e al kernel SWA small-M).
- `VETTA_SPEC_ND=<k>` permette comunque di fissare `n_draft` per A/B; `VETTA_DBG_SPEC=1` stampa le statistiche per richiesta su `stderr`.
- Le modifiche sono state committate e pushate su `main` (commit `c1c5221`).
---
## 7. Chiusura Punto 3 memoria: `PrefixCache` in RAM pinned (`0 byte VRAM`) + SWA ring DSpark
Chiuso anche l'ultimo punto del piano VRAM piatta ([`2026-12-02-piano-vram-piatta-e-guida-drafter.md`](2026-12-02-piano-vram-piatta-e-guida-drafter.md)):
- **`PinnedBuf` (`hipHostMallocDefault` / `hipHostFree`) in `vetta_kernels.{h,hip}` e `crates/vetta-infer-hip/src/lib.rs`:**
- Aggiunte `vetta_host_alloc`, `vetta_host_free` (con `hipStreamSynchronize(0)` prima di `hipHostFree` per escludere race con copie async), e copie asincrone 1D/2D `vetta_buf_{d2h,h2d}_async`, `vetta_buf_copy2d_{d2h,h2d}_async` su stream 0.
- Wrapper safe `PinnedBuf` + `DeviceBuf::{copy_from_pinned, copy2d_from_pinned_at}`.
- **Spostati `LayerSnapshot` (`layer.rs`) e `DsparkSnapshot` (`dspark.rs`) da `DeviceBuf` a `PinnedBuf`:**
- Tutti i checkpoint della `PrefixCache` (KV trunk + ShortConv hist + KV/frnn DSpark) ora vivono in RAM host pinned (**0 byte di VRAM**, liberando 3–6 GiB su conversazioni lunghe e preparando il terreno allo streaming dei layer in DMA).
- **SWA ring da `1280` posizioni (`DS_SWA_RING`) sui layer SWA 0 e 2 di `DsparkContext` (`dspark.rs`):**
- Riduce la VRAM permanente di `DsparkContext` a 32k da ~413 MiB a ~155 MiB (**-258 MiB**).
- **Validazione misurata su `gfx1150`:**
- `pinned_buf_zero_vram_and_roundtrip_2d`: 64 MiB `PinnedBuf` → delta VRAM **`+0.00 MiB`** (`165675008 → 165675008`), round-trip 2D con wrap-around bit-exact (**PASS**).
- `serve_gen_pinned_prefix_cache_vram_flat` (4 turni fino a 2100 token, `VETTA_SPEC=1`, 8/8 checkpoint pieni):
- Turn 1 (`prompt=600`, `ckpts=3`): `20,674.00 MiB`
- Turn 2 (`prompt=1100`, `resumed=607`, `ckpts=6`): `20,672.00 MiB`
- Turn 3 (`prompt=1600`, `resumed=1107`, `ckpts=8`): `20,676.00 MiB`
- Turn 4 (`prompt=2100`, `resumed=1607`, `ckpts=8`): `20,676.00 MiB` (**delta Turn 1→4 = `+2.00 MiB`** — VRAM completamente piatta!).
- `dspark_draft_parity` (7/7 EXACT), `serve_gen_spec_multi_token_parity` (16/16 EXACT), `serve_gen_spec_prefix_cache_multi_turn_parity` (Turn 1+2 `RESUME 45` EXACT), `RUSTFLAGS="-D warnings" cargo test --workspace` (**PASS**).
---
## 8. Audit codebase: magagne residue trovate (analisi statica, pronte per domani)
Verificate direttamente sui file sorgenti dopo il commit `1772050`:
### P0 — Da sistemare subito (bug / overhead evitabili)
1. **`spec_update_hist` rialloca 192 buffer a ogni singolo round speculativo** ([`layer.rs:298`](../crates/vetta-infer-ld/src/layer.rs#L298)):
`if snap.as_ref().map_or(true, |s| s.bytes != n * 4)` confronta per uguaglianza stretta, ma `DeviceBuf::alloc` arrotonda `s.bytes` a `next_power_of_two()` (es. `165,888 B -> 262,144 B`). La condizione è **sempre vera** e fa churn di `48 × 4 = 192` alloc/drop per round. Fix: `s.bytes < n * 4`.
2. **Flag env booleani controllati con `.is_ok()` invece di parsare `"0"`/`"false"`** ([`serve.rs:271`](../crates/vetta-infer-gw/src/serve.rs#L271), `serve.rs:409`, `serve.rs:795`, `lib.rs:328`):
Impostare `VETTA_SPEC=0` (o `VETTA_NO_PREFIX_CACHE=0`, `VETTA_LAZY_LOAD=0`, `VETTA_NO_BUF_POOL=0`) **attiva** il flag invece di spegnerlo. Serve un helper unico `env_flag("VETTA_SPEC")` che ignora `"0"`, `"false"`, `"off"`, `""`.
### P1 — Compatibilità `strata-ctl` / chat reale e velocità path AR
3. **Drafter spento appena `temperature > 0` o con penalty** ([`serve.rs:385`](../crates/vetta-infer-gw/src/serve.rs#L385)):
`spec_enabled` richiede `is_greedy() && !has_penalties()`. Inoltre, se un turno non-greedy (o un `GEN 0` pre-warm non-greedy) salva un checkpoint con `dspark: None`, anche il turno successivo greedy che fa `RESUME` su quel checkpoint disattiva il drafter (`serve.rs:423`).
*Per abilitare `temperature > 0` domani:* `vetta-infer-abi::sampler::verify_draft_logits` (rejection sampling esatto 0 KLD) è già in codebase; attenzione però che in `spec_round` (`dspark.rs:492`) oggi manca `softcap(lg, eng.cap)` (innocuo in greedy perché `tanh` è monotona, **obbligatorio** con `temperature > 0`!).
4. **`ParsedGen.spec_mode` (`spec=off|auto|5`) e `ParsedGen.images` parsati ma ignorati in `serve_gen`** ([`serve.rs:352`](../crates/vetta-infer-gw/src/serve.rs#L352), [`main.rs:98`](../crates/vetta-infer-gw/src/main.rs#L98)):
- `spec=0` / `spec=5` sul wire non hanno effetto; manca anche un flag CLI `--spec` / `--draft dspark|off` in `main.rs` (oggi `vetta-infer.json` di `strata-ctl` lancia solo `--serve <dir>` senza `VETTA_SPEC=1`).
- `g.images` viene scartato silenziosamente invece di rispondere `ERR vision not supported`.
5. **Path decode M=1 (`layer_forward_swa`, `layer_forward_full`, `forward_inkling_with_state`) fa ~120 `d2h`/`h2d` sincroni per token** ([`layer.rs:540-556`](../crates/vetta-infer-ld/src/layer.rs#L540-L556), `985-1015`, `1280-1360`):
`blocks`, `mx3`, `prelude` e `bank` rimbalzano su CPU a ogni layer/pass mentre `forward_batch` usa già `BatchBlocks` interamente su GPU. Unificare il decode M=1 su `BatchBlocks` (o instradare `forward(tok)` su `forward_batch(&[tok])`) toglierebbe ~120 sync CPU↔GPU per token anche con spec OFF / `temperature > 0`.
### P2 — Igiene e propedeutici allo streaming DMA
6. **Telemetria `DONE` e `RESET` (`serve.rs:699, 855`):**
- `DONE` non appende nella coda raw `accepted / offered` del drafter (oggi stampati solo su `stderr` con `VETTA_DBG_SPEC=1`).
- `Msg::Reset` è no-op (non svuota `PrefixCache`; verificare se `strata-ctl` si aspetta lo svuotamento su `RESET`).
7. **Pesi permanenti allocati dal pool** ([`layer.rs:795`](../crates/vetta-infer-ld/src/layer.rs#L795), [`layer.rs:1217`](../crates/vetta-infer-ld/src/layer.rs#L1217)):
`load_msg_queries` e `load_sconv_transposed` usano `DeviceBuf::alloc` (pooled + arrotondato a potenza di 2) invece di `DeviceBuf::alloc_unpooled`.
8. **Ponte mancante per lo streaming dei layer in DMA (M2):**
- `vetta_hip_register_uma_pages` / `vetta_hip_unregister_uma_pages` sono dichiarati in `vetta_kernels.h:26-27` ma non implementati in `vetta_kernels.hip` né wrappati in `vetta-infer-hip`.
- `UmaSlabPool` (`crates/vetta-infer-kn/src/uma.rs`) alloca ancora `Vec<u8>` non allineati a 4 KiB (`O_DIRECT`) e non registrati con `hipHostRegisterMapped`.
- `HotColdExpertCache` (`vetta-infer-cc`) e `vetta-infer-rt::executor` non sono ancora collegati a `WeightCache` (che oggi carica tutti gli `ExpertArena` in VRAM al boot via `prewarm`).