Files
adm 1772050087 [HIP][Core] Zero-VRAM PrefixCache in pinned host RAM (PinnedBuf) + DSpark SWA ring
Close Punto 3 of the flat-VRAM plan:
- Add PinnedBuf (hipHostMallocDefault / hipHostFree with stream 0 sync on drop) and pipelined async 1D/2D D2H/H2D copy helpers in vetta_kernels.{h,hip} and vetta-infer-hip.
- Migrate LayerSnapshot (KV + ShortConv hist) and DsparkSnapshot (drafter KV + frnn_last) from VRAM DeviceBuf to host PinnedBuf (0 bytes VRAM per checkpoint).
- Size DSpark SWA layers 0/2 in DsparkContext to DS_SWA_RING=1280 (-258 MiB VRAM at 32k context).
- Add GPU regression tests: pinned_buf_zero_vram_and_roundtrip_2d (+0.00 MiB VRAM on 64 MiB alloc) and serve_gen_pinned_prefix_cache_vram_flat (4 turns up to 2100 tok, 8/8 checkpoints full, VETTA_SPEC=1: 20674->20672->20676->20676 MiB, +2.00 MiB delta).
- Update README.md, docs/ORIENTATION.md, and review/2026-12-02-fix-drafter-e-ottimizzazioni.md.
2026-12-02 23:23:07 +01:00

14 KiB
Raw Permalink Blame History

Orientation: what you're looking at

If you come from vLLM, llama.cpp, SGLang, or TensorRT-LLM, this repo will feel alien at first. That's expected — it's built on a different mental model. This document explains what vetta-infer is, why it looks the way it does, and the road ahead. Read this before diving into the code.

What it is, in one paragraph

vetta-infer is a MoE-first microkernel inference engine written in safe Rust with a minimal set of AMD ROCm HIP kernels. It is not a general-purpose engine: it targets one specific machine — an AMD Ryzen AI 9 HX 370 APU (gfx1150, RDNA 3.5) with 96 GiB of unified memory and dual NVMe — and one class of models: Mixture-of-Experts decoder LMs (first target: Inkling-2-Mini). Small dense utility encoders (e.g. BGE-M3 embeddings) are in scope as a secondary lane; dense decoder LMs are deliberately out of scope. The engine is co-designed with its consumer, the vetta-agents framework (evolved from strata-ctl), and ultimately serves a principal named Iris.

Why it looks different (the mental-model shift)

Five ideas explain almost everything that will surprise you:

  1. Pure microkernel + services. There is no monolithic runtime. A tiny kernel (kn) owns the bus, registry, and UMA/DMA broker and contains zero model logic. Everything else — loading, compilation, execution, sampling, speculative decoding, telemetry, the wire gateway — is a separate service crate. Control flow stays in safe, CPU-testable Rust; unsafe is confined to the HIP FFI (hip) and IO syscalls (io).

  2. Models are compiled, not loaded. A dual-step loader turns a HuggingFace .safetensors model into a canonical IR, then a BackendPacker lowers it into a portable .vbundle/ (manifest + weights + plans). You don't point the engine at raw weights; you build a bundle once and boot from it. The manifest carries identity-by-provenance (sha256), ABI version, and target.

  3. The forward pass is a declared, validated plan. Instead of imperative kernel calls scattered through C++ files, the model's compute is expressed as graph.vplan (an op sequence) + memory.vplan (buffer arenas). At boot these lower to a flat CompiledPlan. Before any GPU launch, the plan is checked by an arena validator (no buffer overlap, checked bounds, no use-before-write) whose correctness is proven in Lean 4. The graph is data, not code.

  4. Proof-first for complex logic. Non-trivial state machines — the DMA slab ring, bus lifecycle, serve session, arena plans — are modeled and verified in proofs/*.lean (0 sorryAx, standard axioms only) before the Rust is written. Simple logic just gets ordinary CPU tests. This is a hard rule, not a nicety: it eliminates whole classes of bugs by construction.

  5. Parity discipline, no unmeasured claims. Every kernel is checked against a CPU oracle (and the hardened strata C++/HIP reference) before it is wired in. Every performance claim must carry real measurements and the exact hardware/model/flags. "It should be fast" is not a sentence we accept.

The crate map

Crate Responsibility
vetta-infer-abi Shared contracts: .vbundle manifest/plans, vplan opcodes, arena validator, JSON, sha256, serve wire types.
vetta-infer-kn The microkernel: bus, registry, UMA/DMA broker. No model logic.
vetta-infer-ld Loader: safetensors reader, ModelImporter (config → IR → graph), BackendPacker, bundle I/O.
vetta-infer-hip HIP FFI/DMA backend (gfx1150). unsafe isolated here. Feature-gated kernel build.
vetta-infer-cc Compilation/control services.
vetta-infer-rt Operational runtime: executes the CompiledPlan on the HIP backend.
vetta-infer-lab Laboratory/probing runtime; shares the rt executor core.
vetta-infer-sp Speculative decoding / MTP verification.
vetta-infer-nt NVMe streaming / disk cache (io_uring, write-once O_RDONLY).
vetta-infer-tm Telemetry.
vetta-infer-gw Wire gateway: the stdin/stdout line protocol the agent speaks; CLI.

Current state (honest)

  • The engine runs real inference, end-to-end, and it is correct. The full 48-visit Inkling-2-Mini forward (prelude + looped core ×3 passes with bank rollback + coda + final depth-mix/softcap) runs on the real gfx1150 weights. Greedy decoding is EXACT multi-token parity against the hardened strata reference (16 and 40 tokens, F32 and FP16 KV). The two root causes of the old token-2+ gap were structural, not precision: per-pass KV pools and the unpadded logit vocab (200058).
  • Linked to the agent framework. strata-ctl --serve spawns vetta-infer and serves its OpenAI-compatible API; the wire protocol (READY/INFO/T/PP/ RESUME/DONE/ERR) is field-for-field compatible. Verified live: capital queries, Italian multi-turn, EOS/stop handling.
  • First real interactive GUI conversation (2026-12-01, measured). Through the strata-ctl web GUI on Sogliola (http://sogliola:1234), engine vetta-infer:
    • 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.
    • 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) dropped it to ~54% (measured A/B 101.2% → 54.2%). The residual ~54% is genuine kernel-launch submission cost (~1300 launches/token), removed only by HIP graph capture.
  • Multi-turn prefill is no longer re-paid: the prefix checkpoint cache landed (2026-12-01, measured). Ported in concept from strata --auto-ckpt and proven in proofs/prefix_cache.lean (restore_equiv, 0 sorryAx), serve_gen restores the longest cached prefix of a prompt and prefills only the NEW suffix tokens; the checkpoint saves at pos (prompt + generated tokens) so the next turn reuses the whole prior context. Pinned anchors {512,1024} are never evicted (I3), LRU at cap 6, KV snapshots unpooled (freed on eviction). Parity EXACT (restore == cold re-prefill, token-for-token, both prewarm- and decode-state checkpoints). Measured on gfx1150, Inkling-2-Mini, FP16 KV, greedy: a 605-token prompt with a 600-token cached prefix prefills in 2.29 s vs 132.5 s cold (57.8×), end-to-end 3.2 s vs 133.2 s (41.8×). This collapses the second-turn time-to-first-token; the first turn still pays sequential prefill (batched prefill is the next brick). Validated at scale too: 8 checkpoints past cap 6 keep VRAM bounded (19.0→19.8 GiB, 0.5 GiB spread — no per-turn accumulation), the pinned anchors {512,1024} survive 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).
  • 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 — zero-VRAM checkpoints in pinned host RAM (2026-12-02, measured). Persistent per-layer KV/ShortConv states reused across requests (40 SWA pools on 1280-slot rings + 8 Global pools; DSpark SWA layers 0/2 also on 1280-slot rings, saving ~258 MiB at 32k), power-of-two BUF_POOL bucketing (512 MiB cap), and all PrefixCache snapshots (LayerSnapshot KV + ShortConv + DsparkSnapshot) stored in page-locked host RAM (PinnedBuf via hipHostMallocDefault, async SDMA transfers on stream 0, hipStreamSynchronize before hipHostFree on drop). Verified on gfx1150: 64 MiB PinnedBuf adds +0.00 MiB VRAM, and a 4-turn multi-checkpoint sweep up to 2100 tokens filling all 8 PrefixCache slots with VETTA_SPEC=1 holds VRAM flat at 20,674 → 20,672 → 20,676 → 20,676 MiB (Turn 1→4 delta +2.00 MiB, RESUME 0→607→1107→1607, 100% EXACT parity).
  • 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).
  • DSpark speculative drafter landed at strata parity (2026-12-02, measured). Opt-in via VETTA_SPEC=1 (lossless contract proven in proofs/speculative_draft.lean, 200-token spec_lossless_gate EXACT, multi-turn PrefixCache + DsparkSnapshot restore EXACT). All drafting runs 100% on GPU: single-pass base-unembed Top-512 screen (reads 922 MB unembed once per round), on-GPU Markov loop + candidate argmax (<=32 B D2H), 0-LDS Wave32 online-softmax block attention (regression-tested at c_len = 17_000), M-tiled Wave32 router GEMV, zero-scratch small-M SWA GQA, fdot2 MoE for b <= 12, and an accepted-count EMA governor starting at n_draft = 5. Measured on gfx1150 (Inkling-2-Mini, temperature=0):
    • Rust coding prompt (RingBuffer<T>, 128 tok): OFF 6.83 tok/s → VETTA_SPEC=1 13.93 tok/s (2.04×, n_draft=5, 100% EXACT) vs strata-inkling --draft dspark 13.66 tok/s on the exact same prompt.
    • Short prose prompt ("The capital of France is", 96 tok): nd=5 jumped from 4.58 → 9.09 tok/s (+98.5%); default adaptive EMA 8.93 tok/s decode. Full changelog & root-cause breakdown: review/2026-12-02-fix-drafter-e-ottimizzazioni.md.
  • What is NOT done yet (the frontier): 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 and speculative drafting are landed; DMA memory streaming is next.

The road to the goal

The destination: a working, measured inference engine that the agent framework can talk to over the wire, replacing the old strata engine for a real conversation. Steps 1–5 are landed — the first real GUI conversation happened on 2026-12-01 (see Current state). The path, in order:

  1. Inkling graph parity — ✅ landed (attention-residual block-mix, loop controllers, ShortConv4, relative-position bias, sliding-window attention, per-pass KV). Blueprint: docs/inkling-forward-design.md.
  2. Remaining kernels — ✅ landed (flash GQA/SWA, MoE NVFP4/MXFP8 routing + experts + reduce, KV-write, L2-clip, relpos). Each parity-verified.
  3. Executor — ✅ landed (full 48-visit forward on real weights).
  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 — ⏳ 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 — ⏳ DSpark speculative drafter ✅ landed (13.93 tok/s on Rust coding, 2.04× vs OFF, matching strata-inkling); next is 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

# CPU workspace tests (host-independent, no GPU/toolchain needed):
RUSTFLAGS="-D warnings" cargo test --workspace

# Lean proofs (0 sorryAx, standard axioms):
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
lean proofs/speculative_draft.lean

# Opt-in live tests against the real Inkling artifact:
cargo test -p vetta-infer-ld -- --ignored inkling

# GPU kernel parity (requires gfx1150 + ROCm; builds kernels via hipcc):
cargo test -p vetta-infer-hip --features hip -- --ignored
  • docs/ARCHITECTURE.md — the decision-complete spec (microkernel, services, .vbundle, plans, wire contract, milestones).
  • docs/inkling-forward-design.md — the Inkling forward pass, extracted from the reference, that the graph emitter follows.
  • proofs/*.lean — the verified state machines and arena plan.
  • AGENTS.md — the engineering rules and hard invariants.

Welcome. Take your time with the mental model first; the code reads much more naturally once the five ideas above click.