# 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 (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 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** — ⏳ 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 ```sh # 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/prefix_cache.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 ``` ## Where to read next - `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.