[Docs] record 2026-12-02 landed state: batched+WMMA prefill, flat VRAM, budget clamp
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/.
This commit is contained in:
1 parent
ee8ac8f5df
commit
a4752953fb
4 files changed
+341
-16
No files matched your search
@@ -39,19 +39,22 @@ Built from the measured hardware physics and engineering lessons of our hardened
|
||||
- **M0.5 (Architecture realignment — done):** approved microkernel design fixed in `docs/ARCHITECTURE.md`; crates realigned to `vetta-infer-*` (abi/kn/ld/cc/rt/lab/sp/nt/tm/gw); bus lifecycle Lean-verified (`bus_lifecycle.lean`); faithful Adaptive-K port; `strata-ctl` wire emitters + `image=` key.
|
||||
- **M1 (Resident MoE End-to-End — Target 1: `Inkling-2-Mini`, inference landed):** full 48-visit forward on real `gfx1150` weights, **EXACT multi-token greedy parity** vs the `strata` reference (per-pass KV pools + unpadded vocab 200058), `strata-ctl` drop-in `--serve` link (OpenAI-compatible API, field-for-field wire). Serve-session FSM (`serve_session.lean`), arena safety (`arena_plan.lean` + `abi::arena`), `.vbundle` contract (`abi::bundle` + `ld::bundle`), loop proof (`inkling_loop.lean`). Speed vs C++ baseline (`>= 18 tok/s`, `< 4 s` reload) is the remaining M2 work.
|
||||
- **🎉 First real interactive GUI conversation — 2026-12-01 (measured):** via 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 is sequential prefill of the ~2650-token agent prompt, ~140 ms/token; decode ~4.2 tok/s). Host-CPU busy-wait eliminated via `hipDeviceScheduleBlockingSync` (measured A/B 101.2% → 54.2%); the residual ~54% is kernel-launch cost, removed by HIP graph capture (M2).
|
||||
- **⚡ Prefill batched + tensor-core — 2026-12-02 (measured):** chunked batched forward (M=B) + FP16 WMMA grouped MoE + BF16 WMMA dense projections + FlashAttention-2 WMMA prefill (P staged in LDS, no global scores scratch). Synthetic 2048-token prefill on `gfx1150` (FP16 KV, chunk 256): **60 s → 12.9 s (-78%)**, ~6.3 ms/token (a 16 k-token agent prompt ~105 s, was ~7 min). Greedy-vs-reference stays EXACT (blocking gate); internal M=1-vs-M=B parity relaxed to a global-scale tolerance (approved P1 policy). The 618 s first-token above is historical (sequential prefill).
|
||||
- **🧠 Flat VRAM + long-prompt clamp — 2026-12-02:** persistent per-layer KV/ShortConv states reused across requests (no ±3.75 GB alloc/free sawtooth), SWA-window checkpoints + prefix cache cap 8 (grid-protected, LRU-on-restore), 512 MiB buffer-pool cap; long→short session switches reuse the persistent KV. Generation budget clamped to the window (`clamp_max_new`) instead of hard-erroring past 16382 prompt tokens with strata-ctl's fixed max_new=16384; window configurable via `serve --max-context N`. Verified live: a 16504-token prompt generates (was ERR 0 tokens).
|
||||
- **M1.5 (Embedder lane — BGE-M3):** native encoder forward-pass (LayerNorm, bidirectional full-attn, GELU-erf, CLS pooling + L2 — recipe declared in the manifest), XLM-R importer, SPM tokenizer, `vetta-infer embed` wire; acceptance cosine ≥ 0.999 vs the live `vetta-semantics` oracle (`:8091`) + publisher fixture + anisotropy canary. Optional reranker head. May double as the HIP kernel bring-up bench.
|
||||
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
|
||||
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** speculative drafter integration (next), then layer streaming in DMA — the hard memory frontier: Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
|
||||
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
|
||||
|
||||
## Quick Verification
|
||||
|
||||
```sh
|
||||
# Lean 4 formal proofs (0 sorryAx, 5 files)
|
||||
# Lean 4 formal proofs (0 sorryAx, 6 files)
|
||||
lean proofs/slab_ring_dma.lean
|
||||
lean proofs/bus_lifecycle.lean
|
||||
lean proofs/serve_session.lean
|
||||
lean proofs/arena_plan.lean
|
||||
lean proofs/inkling_loop.lean
|
||||
lean proofs/prefix_cache.lean
|
||||
|
||||
# Pure-Rust workspace tests (no GPU required)
|
||||
cargo test --workspace
|
||||
|
||||
+36
-14
@@ -87,9 +87,9 @@ Five ideas explain almost everything that will surprise you:
|
||||
- prompt *"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 GUI's
|
||||
~2650-token agent prompt (~140 ms/token); decode itself is ~4.2 tok/s. This
|
||||
is the honest current performance frontier, not a hang.
|
||||
- That 618 s was the *sequential* prefill of the day (2026-12-01). It is now
|
||||
historical: batched prefill + WMMA (below) cut prefill to ~6.3 ms/token, so
|
||||
the same prompt is seconds and a 16 k-token agent prompt ~105 s (was ~7 min).
|
||||
- **Host CPU during inference is no longer a busy-wait.** ROCm's default spin
|
||||
host-wait schedule pinned the process at ~100% CPU; setting
|
||||
`hipDeviceScheduleBlockingSync` before context creation (as the reference does)
|
||||
@@ -113,11 +113,31 @@ Five ideas explain almost everything that will surprise you:
|
||||
eviction (restore probes 2.4 s vs ~77/154 s cold), and parity stays EXACT at 1024
|
||||
(warm 2.41 s vs cold 230.4 s). The speedup materialises whenever the next prompt
|
||||
extends the previous token prefix (standard chat reconstruction).
|
||||
- **What is NOT done yet (the frontier):** HIP graph capture (collapse the
|
||||
per-token launches → near-zero host CPU), batched/chunked prefill (M>1 attention
|
||||
+ grouped MoE, make the *first* large-prompt time-to-first-token seconds, not
|
||||
minutes), and the expert-GEMV math speedup (WMMA). These are the M2 performance
|
||||
work — correctness is already there; speed is the next axis.
|
||||
- **Prefill is batched + tensor-core (2026-12-02, measured).** Chunked batched
|
||||
forward (M=B, `VETTA_PREFILL_CHUNK`), FP16 WMMA grouped MoE, BF16 WMMA dense
|
||||
projections, and FlashAttention-2 WMMA prefill (P staged in LDS, no global
|
||||
scores scratch). Synthetic 2048-token prefill on `gfx1150`, FP16 KV, chunk 256:
|
||||
**60 s → 12.9 s (-78%)** (MoE 41.6→36.9, BF16 36.2→27.8, flash 27.6→12.9),
|
||||
~6.3 ms/token. Internal M=1-vs-M=B parity is relaxed to a global-scale numeric
|
||||
tolerance per the approved P1 policy; greedy-vs-reference remains the EXACT
|
||||
blocking gate (serve_gen 4/4).
|
||||
- **VRAM is flat and bounded (2026-12-02).** Persistent per-layer KV/ShortConv
|
||||
states reused across requests (no ±3.75 GB alloc/free sawtooth), SWA-window
|
||||
checkpoints (only the last 1024 KV positions for the 40 SWA pools, full prefix
|
||||
for the 8 full-attn pools), prefix cache cap 8 with grid protection +
|
||||
LRU-on-restore, and a 512 MiB cap on the buffer pool. Long→short session
|
||||
switches reuse the persistent KV instead of reallocating it.
|
||||
- **Long agent prompts are no longer refused (2026-12-02).** strata-ctl always
|
||||
sends max_new=16384; the budget is now clamped to the window (`clamp_max_new`)
|
||||
instead of hard-erroring past 16382 prompt tokens, and the window is
|
||||
configurable (`serve --max-context N` / `VETTA_MAX_CONTEXT`, advertised in
|
||||
READY). Verified live: a 16504-token prompt generates (previously ERR 0 tokens).
|
||||
- **What is NOT done yet (the frontier):** speculative **drafter integration**
|
||||
(next), **layer streaming in DMA** (the hard one: `io_uring O_DIRECT` +
|
||||
`hipHostRegister` SlabRing, Hot/Cold expert cache + lookahead prefetch), HIP
|
||||
graph capture (collapse per-token launches → near-zero host CPU), and the INT8
|
||||
`sf4_i8` fused MoE (the reference's further 2×/5-8× MoE axis). Correctness is
|
||||
already there; speed and memory streaming are the next axes.
|
||||
|
||||
## The road to the goal
|
||||
|
||||
@@ -135,12 +155,14 @@ on 2026-12-01 (see *Current state*). The path, in order:
|
||||
4. **Weights → device** — ✅ landed (resident `WeightCache`, lazy expert load).
|
||||
5. **Serve wiring + first chat** — ✅ landed (`strata-ctl` link, EXACT parity,
|
||||
first real GUI conversation 2026-12-01).
|
||||
6. **M2 performance** — ⏳ the current frontier: prefix checkpoint cache ✅ landed
|
||||
(multi-turn prefill reuse, EXACT parity, 57.8× measured); HIP graph capture
|
||||
(host CPU), batched/chunked prefill (first-turn time-to-first-token), and
|
||||
expert-GEMV WMMA (decode tok/s) still pending. Measured against the reference,
|
||||
no unmeasured claims.
|
||||
7. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
|
||||
6. **M2 performance** — ⏳ prefix checkpoint cache ✅ (multi-turn reuse, EXACT,
|
||||
57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense +
|
||||
flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp
|
||||
✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU).
|
||||
7. **Drafter + DMA layer streaming** — ⏳ next: speculative drafter integration,
|
||||
then layer streaming in DMA (`io_uring O_DIRECT` + `hipHostRegister` SlabRing,
|
||||
Hot/Cold expert cache + lookahead prefetch) — the hard memory frontier.
|
||||
8. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
|
||||
domain-aware expert prefetch.
|
||||
|
||||
## How to verify
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# Audit approfondito: regressione Prefix Cache al 3° turno, Memory Leak VRAM e prefill lento
|
||||
|
||||
**Data:** 2026-12-02
|
||||
**Revisione analizzata:** `vetta-infer` @ `088ac1f` (`main`) — sola lettura, nessuna modifica al codice
|
||||
**Riferimento prestazionale:** `strata-inkling` (stessa GPU AMD RDNA 4, ~458 pp/s, 2048 tok in ~4.5 s, Turno 2+ <1 s)
|
||||
|
||||
---
|
||||
|
||||
## Sintesi esecutiva
|
||||
|
||||
I tre sintomi osservati live su `inkling-server.service` hanno cause distinte, tutte confermate direttamente nel codice sorgente:
|
||||
|
||||
| # | Sintomo osservato | Causa radice verificata | Impatto |
|
||||
|---|---|---|---|
|
||||
| **1** | **Turno 2 veloce, ma Turno 3 torna a ~1 minuto** | `PrefixCache::best_match` / `restore` non aggiornano `ck.lru`, e `PREFIX_CACHE_CAP = 6` (solo 4 slot non-pinnati) viene saturato dai salvataggi `prompt-boundary` + `full-sequence` che **evittano il checkpoint `2560` appena usato al Turno 2**. Al Turno 3 si riprecipita all'anchor `1024`. Inoltre `pos % 512 == 0` salta i grid-save non allineati. | Regressione completa della cache dal Turno 3 in poi |
|
||||
| **2a** | **Memory leak lento e monotono in VRAM** | `BUF_POOL` (`vetta-infer-hip/src/lib.rs:199`) è una `HashMap<usize, Vec<ptr>>` indicizzata per **byte esatti** senza cap né eviction. Ogni turno ha un tail chunk `bu = suffix.len() % 256` diverso: tutti i ~30–40 buffer temporanei per visit (`rel_bias`, `gu`, `y_part`, `BatchBlocks`, ecc. — **~100–250 MiB per ogni `bu` distinto**) usano `DeviceBuf::alloc` e restano intrappolati nel pool **fino al termine del processo**. | Crescita VRAM illimitata multi-turno |
|
||||
| **2b** | **Rimbalzo VRAM su e giù (±3.75 GB a ogni turno)** | `serve.rs:269` dimensiona `max_seq = n_prompt + max_new + 2` (~19.100 con `max_new = 16384` di `strata-ctl`). `new_state` (`layer.rs:230-245`) alloca **~3.75 GB** `unpooled` a ogni richiesta, li **azzera da CPU con `vec![0u8]` + `h2d_bytes` sincrono su PCIe** (anche su cache hit!), e li dealloca a fine turno. | Sawtooth ±3.75 GB + ~0.5–1.5 s di overhead per richiesta |
|
||||
| **3** | **Turno 1 ancora ~41–55 s (~1 min su ~2650 tok)** | Gli ultimi commit (`f25cd27`..`088ac1f`) hanno portato 2048 tok da ~60 s a `40.9 s` (`~50 pp/s`, ancora **~9×** sotto `strata`). Restano: MoE prefill ancora GEMV `fdot2` con gather sparso (niente WMMA), `k_gemm_bf16` FMA scalare senza WMMA/`hipBLASLt` e senza proiezione fusa `qkvrg`, attention prefill scalare con scratch in VRAM, più **72 stalli sincroni `d2h`/`h2d` per chunk (e per decode token)** in `load_msg_queries` (`layer.rs:662-674`). | Turno 1 ~1 min e overhead residuo anche in decode |
|
||||
|
||||
> **Nota positiva sul percorso fin qui:** l'architettura microkernel, la correttezza bit-exact (`forward_batch_parity max_abs=0.0`), la disciplina dei test e i progressi su `01d8a48`, `f25cd27`, `45d039d`, `088ac1f` sono molto solidi. I problemi 1, 2a, 2b e gli stalli PCIe si chiudono in poco tempo con fix mirati; il problema 3 richiede il passaggio a WMMA sui 3 kernel caldi del prefill.
|
||||
|
||||
---
|
||||
|
||||
## 1. Perché il Turno 2 è veloce e il Turno 3 torna a ~1 minuto (`serve.rs`)
|
||||
|
||||
### 1.1 Bug critico: `best_match` e `restore` non aggiornano `ck.lru` (`serve.rs:82-110`)
|
||||
|
||||
In `crates/vetta-infer-gw/src/serve.rs`:
|
||||
- `PREFIX_CACHE_CAP = 6` (`serve.rs:59`)
|
||||
- `pinned_anchor(seq)` blocca `{512, 1024}` (`serve.rs:60`), lasciando **solo 4 slot non-pinnati**.
|
||||
- `best_match(&self, ids)` (`serve.rs:82`) e `restore(&self, idx, ...)` (`serve.rs:95`) prendono `&self` e **non chiamano mai un aggiornamento LRU (`self.tick += 1; self.pool[idx].lru = self.tick`)**.
|
||||
|
||||
Ecco la traccia esatta di ciò che accade nei primi 3 turni di chat reale con `strata-ctl` (dove i 2 token finali del prompt cambiano quando il turno entra in history, e la risposta generata viene ri-tokenizzata diversamente):
|
||||
|
||||
1. **Turno 1** (`prompt_len = 2646`, `start = 0`, `chunk = 256`):
|
||||
- Grid saves (`serve.rs:361`): `512*` (`lru=1`), `1024*` (`lru=2`), `1536` (`lru=3`), `2048` (`lru=4`), `2560` (`lru=5`).
|
||||
- Prompt-boundary save (`serve.rs:392`): `2646` (`lru=6`). Pool pieno (6/6).
|
||||
- Full-sequence save (`serve.rs:479`): `2698` (`lru=7`) → evitta il più vecchio non-pinnato (`1536`, `lru=3`).
|
||||
- **Pool a fine Turno 1:** `{512*, 1024*, 2048(lru=4), 2560(lru=5), 2646(lru=6), 2698(lru=7)}`.
|
||||
|
||||
2. **Turno 2** (`prompt_len = 2738`, prefisso comune col Turno 1 = `2644`):
|
||||
- `2646` e `2698` falliscono per i 2 token finali di turn-tag (`common = 2644 < 2646`).
|
||||
- `best_match` trova **`2560`** → `restored = 2560` → solo 178 nuovi token → **Turno 2 VELOCE!**
|
||||
- **MA `ck[2560].lru` NON viene toccato**: resta bloccato a `lru = 5`!
|
||||
- Fine prefill: prompt-boundary save `2738` (`lru=8`) → evitta `2048` (`lru=4`).
|
||||
- Fine decode: full-sequence save `2829` (`lru=9`) → **evitta `2560` (`lru=5`) — esattamente il checkpoint appena usato con successo al Turno 2!**
|
||||
- **Pool a fine Turno 2:** `{512*, 1024*, 2646, 2698, 2738, 2829}` — **ZERO grid checkpoint > 1024 rimasti!**
|
||||
|
||||
3. **Turno 3** (`prompt_len ≈ 2870`):
|
||||
- Tutti e 4 gli slot non-pinnati (`2646`, `2698`, `2738`, `2829`) divergono sul confine di turno!
|
||||
- `best_match` non trova più `2560` (evitto!) né `2048` (evitto!) e **precipita all'anchor pinnato `1024`**!
|
||||
- Deve rifare **~1850 token a freddo** → **di nuovo ~40–55 secondi (~1 minuto)!**
|
||||
|
||||
### 1.2 Bug secondario: `pos % 512 == 0` salta i grid-save non allineati (`serve.rs:361`)
|
||||
|
||||
```rust
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 && pos % 512 == 0 {
|
||||
```
|
||||
|
||||
Se `start` o `suffix.len()` non sono multipli di 256/512 (oppure se un turno aggiunge token che scavalcano `3072` con `take = 256` partendo da `start = 2738`), `pos` non colpisce mai `pos % 512 == 0` e **nessun nuovo grid checkpoint viene salvato**, condannando i turni successivi a non avanzare mai la griglia oltre `2560`.
|
||||
|
||||
### 1.3 Spreco di slot e VRAM nei salvataggi
|
||||
|
||||
- Salvare sia `prompt-boundary` (`L392`) sia `full-sequence` (`L479`) brucia **2 slot su 4 a ogni turno** con entry che nella chat normale (`strata-ctl`) non faranno quasi mai hit al turno successivo, scacciando i grid checkpoint che invece funzionano sempre.
|
||||
- Inoltre `LayerState::snapshot` (`layer.rs:272-292`) copia tutti i `seq_len` token su **tutti e 48 i pool KV**, ma **40 dei 48 pool sono SWA (`swa_win = 1024`)**: per i layer SWA servono solo gli ultimi `min(seq_len, 1024)` token! Salvando l'intero `seq_len` su tutti i 48 pool, ogni checkpoint a `seq = 8192` occupa ~1.6 GB invece di ~350 MB.
|
||||
|
||||
### Fix consigliato per §1
|
||||
|
||||
1. **Aggiornare `ck.lru` su `restore` (`restore(&mut self, ...)`):** quando `best_match` fa hit, fare `self.tick += 1; self.pool[idx].lru = self.tick;`.
|
||||
2. **Sostituire `pos % 512 == 0` con soglia monotona `next_grid`:**
|
||||
- Calcolare `let mut next_grid = ((start / 512) + 1) * 512;`
|
||||
- In `while done < suffix.len()`, se `(pos as usize) < next_grid` e `(pos as usize + take) > next_grid`, spezzare il chunk esattamente a `next_grid - pos as usize` (oppure salvare al superamento di `next_grid`) e incrementare `next_grid += 512`. Così ogni multiplo di 512 viene sempre catturato indipendentemente da `start`.
|
||||
3. **Alzare `PREFIX_CACHE_CAP` (es. `12`) e proteggere i grid checkpoint:**
|
||||
- Non lasciare che `full-sequence` evitti un grid checkpoint (o salvarlo solo in 1 slot dedicato "last-turn" separato dal pool principale; o meglio ancora, salvare `prompt_len - 4` se si vuole coprire il margine di turn-tag).
|
||||
- *(Opzionale ma ad alto impatto)*: in `LayerState::snapshot` / `restore`, per i layer SWA (`is_swa(ip)`), salvare/ripristinare solo la finestra `[seq_len.saturating_sub(swa_win)..seq_len)`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Perché la VRAM rimbalza (±3.75 GB) e accumula un Memory Leak lento
|
||||
|
||||
### 2.1 Causa del Memory Leak monotono: `BUF_POOL` senza cap né bucketing su `bu` variabile
|
||||
|
||||
In `crates/vetta-infer-hip/src/lib.rs:199, 266, 334`:
|
||||
```rust
|
||||
static BUF_POOL: RefCell<HashMap<usize, Vec<*mut c_void>>> = ...
|
||||
```
|
||||
- Il pool è indicizzato per **taglia esatta in byte** (`self.bytes`).
|
||||
- Al `Drop` di ogni `DeviceBuf` con `pooled == true`, il puntatore viene spinto in `BUF_POOL[self.bytes]` e **`hipFree` non viene MAI chiamato** fino alla chiusura del processo.
|
||||
- L'autore aveva già individuato questo meccanismo per il KV cache (`layer.rs:236-238`), per `flash_scores_scratch` (`vetta-infer-hip/src/lib.rs:407-412`, bucket power-of-two) e per `flash_swa_gqa_prefill_f16` (`lib.rs:458`, `alloc_unpooled`).
|
||||
- **Tuttavia, l'intero percorso di batched prefill alloca decine di buffer proporzionali a `bu` con `DeviceBuf::alloc(...)` (`pooled = true`)!**
|
||||
|
||||
Ogni turno di chat ha un tail chunk diverso (`bu = suffix.len() % 256`, es. `86`, `178`, `94`, `211`, `133`...). Per ciascun `bu` mai visto prima vengono creati e **trattenuti per sempre** in `BUF_POOL`:
|
||||
|
||||
| File / Riga | Buffer allocati con `DeviceBuf::alloc` (proporzionali a `bu`) | Peso indicativo a `bu=180` |
|
||||
|---|---|---|
|
||||
| `layer.rs:497-591` (`layer_forward_swa_batched`) | `rel_bias` (`bu*24*1024*4`), `q`, `gatea`, `aout`, `aout_bf`, `k_cv`, `v_cv`, `k_raw`, `v_raw`, `r_raw`, `oproj`, `asc`, `base`, `in1`, `in2`, `msg0..3`, `in0/1/2_bf`, `mix`, `mlpin`, `rlog`, `ids`, `weights`, `msc` | ~45 MiB |
|
||||
| `layer.rs:1225+` (`layer_forward_full_batched`) | stessi tensori Q/K/V/O/mix/mlpin/router per i layer full-attention | (condivide taglie) |
|
||||
| `layer.rs:773-794` (`moe_batched`) | `gu` (`bu*8*2304*4`), `y_part` (`bu*8*2304*4`), `act16` (`bu*8*1152*2`), `mlpin16`, `moeout`, `dbtk`, `ds2b` | ~32 MiB |
|
||||
| `layer.rs:1375-1381` (`apply_controller_batched`) | `packed` (`bu*2*2304*2`), `gate`, `gate_bf`, `gain`, `forget` | ~7 MiB |
|
||||
| `layer.rs:968-1015` + `1403` (`forward_batch` & `BatchBlocks::new`) | `BatchBlocks.arena` (`8*bu*2304*4`), `bank_buf` (`n_bank*bu*2304*4`), `msgs_buf` (`4*bu*2304*4`), `cur`, `prelude`, `bank_out`, `mix`, `dtok`, `dpos` | ~32 MiB |
|
||||
|
||||
Totale: **~100–160 MiB di VRAM permanentemente trattenuti per OGNI valore distinto di `bu` incontrato nella vita del processo**. Dopo 15–20 turni con lunghezze diverse si accumulano **2–3+ GiB di VRAM morta** dentro `BUF_POOL` che non vengono mai rilasciati — esattamente il leak lento osservato!
|
||||
|
||||
### 2.2 Causa del rimbalzo ±3.75 GB a ogni turno (+ stall sincrono di ~0.5–1.5 s)
|
||||
|
||||
In `crates/vetta-infer-gw/src/serve.rs:269` e `crates/vetta-infer-ld/src/layer.rs:230-245`:
|
||||
- `strata-ctl` imposta `max_new = 16384` (verificato dai log `journalctl`: `max_new (generation budget): 16384`).
|
||||
- Con `n_prompt ≈ 2700`, `max_seq = 2700 + 16384 + 2 = 19.086`.
|
||||
- Ogni layer alloca `k_cache` e `v_cache` per ogni pass (`48` pool totali × 2 = `96` buffer):
|
||||
$$96 \times 8 \times 19086 \times 128 \times 2\text{ B} = 3.752\text{ GB}$$
|
||||
- A **ogni singola richiesta** (anche quando la prefix cache fa hit in `restore` a `serve.rs:104`!):
|
||||
1. `new_state` fa 96 `hipMalloc` per **~3.75 GB** (`alloc_unpooled`).
|
||||
2. Per **ognuno** dei 96 buffer fa (`layer.rs:241`):
|
||||
```rust
|
||||
let b = DeviceBuf::alloc_unpooled(kv_n * 2)?; b.h2d_bytes(&vec![0u8; kv_n * 2])?; Ok(b)
|
||||
```
|
||||
ovvero alloca ~39 MB in RAM di sistema, li azzera su CPU, li copia **sincronamente via PCIe (`hipMemcpy` H2D)** sulla GPU, e libera la RAM — ripetuto 96 volte = **3.75 GB di allocazione RAM + zero CPU + copia PCIe sincrona** a ogni turno!
|
||||
3. Alla fine del turno `states` esce di scope e fa 96 `hipFree` (VRAM giù di 3.75 GB).
|
||||
|
||||
### Fix consigliato per §2
|
||||
|
||||
1. **Chiudere subito il leak di `BUF_POOL` (`crates/vetta-infer-hip/src/lib.rs`):**
|
||||
- **Soluzione A (più semplice e immediata):** in `BUF_POOL`, arrotondare le allocazioni al bucket power-of-two (o multipli di 64 KiB/1 MiB per buffer grandi) **E** imporre un tetto massimo di byte trattenuti (es. `MAX_POOL_BYTES = 512 MiB`): quando il pool supera il budget, chiamare `hipFree` sulle entry LRU.
|
||||
- **Soluzione B (ancora più pulita per il prefill):** pre-allocare uno `ScratchArena` / buffer di lavoro dimensionati una sola volta per `MAX_CHUNK = 256` (o passare `bu_alloc = 256` per i buffer di `forward_batch`) e riutilizzarne i prefissi `bu <= 256` senza allocare mai taglie arbitrarie.
|
||||
2. **Eliminare il rimbalzo ±3.75 GB e la copia H2D sincrona di 3.75 GB (`serve.rs` + `layer.rs`):**
|
||||
- Tenere **un solo `states` persistente** su `InklingEngine` (riutilizzato tra una richiesta e l'altra, cresciuto solo se `max_seq > current_cap`, oppure dimensionato a `MAX_CONTEXT` / `8192` + crescita geometrica).
|
||||
- **Non azzerare mai il KV cache con `vec![0u8]` + `h2d_bytes`!** L'attenzione causale legge rigorosamente `[0..=pos]` e `kv_store` sovrascrive ogni posizione prima che venga letta; al massimo basta un `zero_async` (`hipMemsetAsync`) sui soli piccoli ring `hist_k/v/a/m` (pochi KB)!
|
||||
|
||||
---
|
||||
|
||||
## 3. Perché il prefill del Turno 1 è ancora ~41–55 s (vs ~4.5–5 s in `strata`)
|
||||
|
||||
Gli ultimi 4 commit hanno ridotto 2048 token da ~60 s a `40.9 s` (`~50 pp/s`), ma su un prompt reale di ~2650 token + 3.75 GB di zero-copy KV si resta comunque intorno ai **53–58 secondi** (~9× più lento di `strata-inkling` a `458 pp/s`).
|
||||
|
||||
### 3.1 Bonus scoperto: 72 stalli sincroni PCIe per chunk (e per token in decode!) in `load_msg_queries`
|
||||
|
||||
In `crates/vetta-infer-ld/src/layer.rs:662-674`, chiamata **24 volte per ogni chunk di prefill** (`layer.rs:999`) e **24 volte per ogni token di decode** (`layer.rs:886`):
|
||||
```rust
|
||||
fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
|
||||
let q_cp = cache.raw("model.llm.middle_cycle_cross_pass_queries")?;
|
||||
let kv_cp = cache.raw("model.llm.middle_cycle_cross_pass_kv_queries")?;
|
||||
let mut qh = vec![0f32; 24 * hidden]; q_cp.d2h(&mut qh)?;
|
||||
let mut kh = vec![0f32; 24 * hidden]; kv_cp.d2h(&mut kh)?;
|
||||
...
|
||||
let buf = DeviceBuf::alloc(4 * hidden * 4)?; buf.h2d(&mq)?; Ok(buf)
|
||||
}
|
||||
```
|
||||
Questi due tensori sono **pesi statici del modello**, ma ad ogni singolo core layer di pass 1 e 2 vengono scaricati interamente su CPU (`2× hipMemcpy D2H` sincroni → drena la pipeline GPU!) e ri-caricati su GPU (`1× hipMemcpy H2D` sincrono)!
|
||||
- **In prefill:** `24 × 3 = 72` sincronizzazioni GPU-CPU per chunk (720 stalli su 10 chunk!).
|
||||
- **In decode M=1:** oltre a quei 72 stalli, in `forward_inkling_with_state` (`layer.rs:863-891`) anche il bank rollback e la raccolta di `bank` fanno `d2h`/`h2d` sincroni a ogni layer/pass (mentre `forward_batch` usa già copie device-side `copy_f32_sub`).
|
||||
- **Fix banale:** pre-costruire i 12 `DeviceBuf` `[4, hidden]` una sola volta in `WeightCache` all'avvio, e portare `BatchBlocks` (o `copy_f32` device-side) anche nel decode M=1.
|
||||
|
||||
### 3.2 I 4 colli di bottiglia GPU che spiegano il gap ~9× (`40.9 s` → target `~5–8 s`)
|
||||
|
||||
> **Nota sul test di parità:** in `088ac1f` stai mantenendo `forward_batch_parity` a **`max_abs = 0.0` (bit-exact contro `M=1`)**. Quel vincolo ti costringe a usare le stesse riduzioni `fdot2` / FMA scalari del decode, inchiodandoti al tetto delle ALU scalari. I kernel **WMMA** (FP16/BF16 o INT8) sommano su alberi 16×16×16 diversi e danno fisiologicamente `max_abs ~ 1e-3 / 1e-2` rispetto a `M=1`, esattamente come accetta `strata-safetensors`. Per passare a WMMA va allentata la soglia di parity da `0.0` a tolleranza numerica reale (es. cos_sim / top-k / logit tol).
|
||||
|
||||
Riferimenti esatti in `strata-safetensors/engine/src/inkling2/hip/`:
|
||||
|
||||
1. **MoE prefill (`k_nvfp4_grouped_gemv_f16` `vetta_kernels.hip:2161` & `k_mxfp8_grouped_gemv_f16` `L1365`) — ancora ~1.89 s/chunk (~45% del tempo totale):**
|
||||
- Con `B = 256` e `top_k = 8`, ogni expert riceve in media `16` token.
|
||||
- Il kernel attuale usa `fdot2` in stile GEMV (1 wave per riga, gather sparsi `X[bucket_tok[...]]` dentro il loop interno su `K`) e lancia W13, SiTU e W2 in 3 kernel separati.
|
||||
- In `strata-safetensors/engine/src/inkling2/hip/ink_hip_codecs.hip.h`:
|
||||
- **`k_moe_grouped_w13_situ_wmma` (`L4927`, `_128` `L6897`) / `k_moe_grouped_w2_wmma` (`L5141`, `_128` `L7108`)**: gather contiguo in LDS + **FP16 WMMA `16×16×16`**, con **W1+W3+SiTU fusi** in un unico kernel.
|
||||
- **`k_moe_grouped_w13_situ_wmma_sf4_i8` (`L5716`, `_128` `L6532`) / `k_moe_grouped_w2_wmma_sf4_i8` (`L5897`, `_128` `L6720`)**: usa l'**INT8 WMMA nativo di RDNA 4 a doppia velocità (`wmma_i32_16x16x16_iu8`)** sui gruppi SF4 (NVFP4)!
|
||||
2. **Proiezioni dense BF16 (`k_gemm_bf16` `vetta_kernels.hip:208`) — secondo hotspot (~35% del tempo):**
|
||||
- Il commit `45d039d` ha aggiunto il tiling LDS `16×16`, ma il calcolo resta **FMA scalare FP32** (`acc += bf16_to_f32(As) * bf16_to_f32(Bs)`), ~8× sotto il throughput WMMA su RDNA 4.
|
||||
- Riferimenti in `strata-safetensors/engine/src/inkling2/hip/ink_hip_codecs.hip.h`: **`k_bf16_wmma_bf16_64x128` (`L2676`)** e **`k_bf16_wmma_bf16_128x128_swiz` (`L2547`)** (oppure `hipBLASLt` in `ink_hip_blaslt.hpp`).
|
||||
- Inoltre in `layer_forward_swa_batched` (`layer.rs:534-549`) e `full_batched` vengono fatti **6 lanci separati** (`wq`, `wk`, `wv`, `wr`, `wg`, `ws`) leggendo 6 volte `in0_bf` invece di una GEMM fusa.
|
||||
3. **Loop controllers (`apply_controller_batched`, `layer.rs:1373-1386`):**
|
||||
- Oggi lancia 5 kernel per canale × 4 canali × 24 visit (`ctrl_pack_batched` + 3 `gemm_bf16` scalari su `gate_rank=64` + `ctrl_apply`).
|
||||
- Riferimento in `ink_hip_ops.hip.h`: **`k1_loop_ctrl_down_wmma_fused` (`L802`)** e **`k1_loop_ctrl_up_wmma_fused` (`L910`)**.
|
||||
4. **Attention prefill (`k_flash_swa_gqa_prefill_f16` `vetta_kernels.hip:531` + `lib.rs:458`):**
|
||||
- Esegue ancora prodotto scalare `for d = 0..128` + scrittura/lettura di `scores_scratch` in global VRAM (allocato e liberato `unpooled` con `hipMalloc`/`hipFree` **48 volte per ogni chunk**, cioè 480 `hipMalloc`+`hipFree` per un prompt da 2560 token!).
|
||||
- Riferimento in `ink_hip_ops.hip.h`: **`k3_flash_swa_gqa_prefill_wmma` (`L2102`)** (FlashAttention-2 online-softmax in LDS con WMMA, zero scratch in global VRAM).
|
||||
|
||||
### 3.3 Bug minore di sicurezza/robustezza notato durante l'audit
|
||||
|
||||
In `kernels/hip/vetta_kernels.hip:2116-2126`:
|
||||
```cpp
|
||||
__global__ void __launch_bounds__(256) k_moe_scatter_buckets(...) {
|
||||
const int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i >= total) return;
|
||||
const int e = topk_ids[i];
|
||||
const int pos = atomicAdd(&exp_cur[e], 1); // <-- manca il guard `if (e < 0 || e >= 128) return;`!
|
||||
```
|
||||
In `k_moe_count_buckets` il guard `if (e >= 0 && e < 128)` è presente, ma in `k_moe_scatter_buckets` manca: in caso di NaN/corruzione del router scriverebbe out-of-bounds su `exp_cur[e]`. Conviene aggiungerlo per simmetria.
|
||||
|
||||
---
|
||||
|
||||
## Piano d'azione suggerito (ordinato per ROI)
|
||||
|
||||
### Fase P0 — Risolve subito Turno 3, Memory Leak, rimbalzo ±3.75 GB e stalli PCIe (basso rischio, zero nuovi kernel)
|
||||
1. **`serve.rs` (`PrefixCache`):**
|
||||
- Aggiornare `ck.lru` in `restore(&mut self, ...)`.
|
||||
- Sostituire `pos % 512 == 0` con soglia `next_grid` monotona (spezzando il chunk sul confine 512).
|
||||
- Alzare `PREFIX_CACHE_CAP` (es. `12`) e impedire a `full-sequence` / `prompt-boundary` di evittare i grid checkpoint (o tenere 1 slot separato per l'ultimo turno).
|
||||
2. **`vetta-infer-hip/src/lib.rs` (`BUF_POOL`):**
|
||||
- Introdurre bucketing power-of-two + cap globale (es. `512 MiB` con `hipFree` LRU), oppure allocare i temporanei del prefill a taglia fissa `chunk = 256` (niente più leak per ogni `bu` distinto).
|
||||
3. **`serve.rs` + `layer.rs` (`new_state` & `load_msg_queries`):**
|
||||
- Riusare un singolo `states` persistente tra le richieste (eliminando il ±3.75 GB sawtooth) e rimuovere `vec![0u8; kv_n*2]` + `h2d_bytes` sincrono sul KV cache (`layer.rs:241`).
|
||||
- Cachare `load_msg_queries` in `WeightCache` (elimina 72 stalli sincroni PCIe per chunk e per decode token).
|
||||
- (Opzionale) Portare il bank rollback device-side anche in `forward_inkling_with_state` M=1 (boost diretto ai tok/s di decode!).
|
||||
|
||||
### Fase P1 — Abbattere il Turno 1 da ~41 s a <8 s (stesso ordine di grandezza di `strata`)
|
||||
1. **`k_gemm_bf16` → WMMA BF16** (`k_bf16_wmma_bf16_64x128` / `128x128_swiz` in `ink_hip_codecs.hip.h`, o `hipBLASLt`) + fusione `wq/wk/wv/wr/wg/ws` sui 48 visit.
|
||||
2. **MoE prefill (`k_nvfp4_grouped_gemv_f16` / `k_mxfp8_grouped_gemv_f16`) → WMMA fuso W1+W3+SiTU** (`k_moe_grouped_w13_situ_wmma_sf4_i8` / `k_moe_grouped_w13_situ_wmma` / `k_moe_grouped_w2_wmma*` in `ink_hip_codecs.hip.h`, accettando tolleranza numerica reale al posto del bit-exact `max_abs=0.0`).
|
||||
3. **Loop controllers → WMMA fuso** (`k1_loop_ctrl_down_wmma_fused` / `k1_loop_ctrl_up_wmma_fused` in `ink_hip_ops.hip.h`).
|
||||
4. **`k_flash_swa_gqa_prefill_f16` → FlashAttention-2 WMMA in LDS** (`k3_flash_swa_gqa_prefill_wmma` in `ink_hip_ops.hip.h`, elimina anche i 48 `hipMalloc`/`hipFree` per chunk di `scores_scratch`).
|
||||
|
||||
---
|
||||
|
||||
### Verifica rapida consigliata dopo P0 (senza toccare il benchmark principale)
|
||||
1. Avviare con `VETTA_DBG_PREFIX=1` e fare 4 turni di chat consecutivi: verificare `restored=2560` (o superiore) sia al Turno 2 **sia al Turno 3 e 4**, senza mai ricadere a `1024` o `0`.
|
||||
2. Monitorare `rocm-smi` / `/sys/class/drm/card*/device/mem_info_vram_used` prima, durante e dopo 5 turni con prompt di lunghezze diverse: la VRAM deve restare piatta (zero sawtooth ±3.75 GB, zero crescita monotona tra turno 2 e turno 5).
|
||||
@@ -0,0 +1,86 @@
|
||||
# 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%`) |
|
||||
Reference in new issue
Block a user