Dissolve the M0 crates (core/io/proto/telemetry/hip/cli) into the approved service layout abi/kn/ld/cc/rt/lab/sp/nt/tm/gw (docs/ARCHITECTURE.md). - kn: Lean-verified control bus + service registry (bus_lifecycle.lean, 14 thms) and SlabRing/UMA broker; rt: PrefixState + hybrid checkpoint pool. - sp: faithful throughput-aware Adaptive-K port of clover_policy.h (cooldowns, probes, throughput guards) with scenario parity tests. - gw: strata-ctl-compatible wire emitters + serve session FSM (serve_session.lean, 10 thms); abi::serve accepts image= (Vision delta closed). - abi: pure contracts, checked JSON/VTC1/GEN parsers, zero-alloc sampler. - ld/cc: checked safetensors reader + write-once VTC1 writer / O_RDONLY reader. - tm: lock-free telemetry; nt: LyraRpc; lab shares the rt executor core. - Docs: ARCHITECTURE.md decision-complete spec (MoE-only scope, .vbundle, .vplan->CompiledPlan, wire contract, migration map); AGENTS.md Lean rule + tandem/review workflow. Verified live: cargo test --workspace -D warnings = 46/46 PASS; lean proofs = 34 theorems (slab_ring_dma 10, bus_lifecycle 14, serve_session 10), 0 sorryAx, standard axioms only; vetta-infer info on Inkling = 1244 tensors, 18.18 GiB, checked bounds.
21 KiB
vetta-infer Architecture Specification
Status: approved design (2026-11-29), supersedes the M0 crate layout.
The M0 skeleton (commit 63b1668) remains the source of reusable, audit-hardened
components; this document defines the target structure they are migrated into.
Ground truth for behavior: the hardened strata C++/HIP engines
(../strata, ../strata-safetensors, ../strata-clover, ../strata-dense)
and strata/review/RELAZIONE_COMPLETA_MOTORI_HIP_2026-11-28.md. Every ported
policy/kernel carries a parity test against the measured strata behavior.
Principal consumer: strata-ctl (../strata-ctl), developed in tandem
(see §6 and AGENTS.md).
1. Hardware Ground Truth (Measured on Sogliola)
| Resource | Measured Value | Architectural Implication |
|---|---|---|
| GPU | AMD Radeon 890M (gfx1150, RDNA 3.5, 16 CU) |
Wave32 native, 16×16×16 INT8 WMMA (~44 TFLOP/s), 16×16×16 FP16 WMMA (22.14 TFLOP/s) |
| Memory | 48 GiB VRAM carveout + 46 GiB GTT/RAM (96 GiB UMA) |
VRAM and RAM share the same LPDDR5X (81.7 GB/s raw, ~75 GB/s sustained GEMM). Zero-copy hipHostRegister avoids redundant DRAM→DRAM copies |
| Storage | Dual Gen4 NVMe (~4.8 GB/s single, ~9 GB/s striped) |
`O_RDONLY |
| LAN Peer | Lyra over 2.5 Gbps Ethernet (~300 MB/s, ~0.3 ms RTT) |
Unsuitable for per-layer Tensor Parallelism; ideal for <1 KB/step remote drafting, domain routing, and Vision/RAG offload |
Scope decision: MoE-only (Federico, 2026-11-28)
Dense models are out of scope — "questo non è un HW per modelli densi".
The physics is decisive: a dense >80 GB model in pure NVMe streaming reads
40–70 GB/token → 0.07–0.22 tok/s (DRAM/NVMe bandwidth ratio ~17× single,
~9× striped). The engine is designed vertically for MoE: few active
parameters (2B–6B/tok), large total capacity (35B–300B+). strata-dense
remains a technique donor (Q4 SWAR unpack, MTP lossless verification),
not a target engine.
Residency & streaming policy
| Model footprint | Policy |
|---|---|
<= ~80 GiB (Inkling, Clover, MoE 35B–100B) |
Fully UMA-resident zero-copy — VRAM carveout and GTT are the same LPDDR5X; NVMe is used only for the write-once boot cache, never at runtime |
> ~80 GiB MoE (120B–300B+) |
Hot experts pinned in ~70 GiB UMA (LFU/LRU, Zipf: 70–85% of hits are the same experts) + cold misses streamed from NVMe (~10–25 MB/layer, 1.3–3 ms) hidden behind hot-expert compute → target ~3–8 tok/s |
Prefill / speculative verify (B=8..128) |
GPU compute 15–60 ms/layer hides 70–500 MB/layer DMA almost perfectly |
Zero-copy pipeline ("GPUDirect Storage gratis" via UMA, M2): CPU, NVMe
controller and GPU see the same physical memory. Ring of fixed aligned pages
(mmap, 4 KiB or MAP_HUGETLB 2 MiB) registered on both sides:
io_uring O_DIRECT + IORING_REGISTER_BUFFERS (NVMe DMA straight into the ring,
zero page-cache, zero CPU copies) and hipHostRegister(..., Mapped) (GPU
device pointer to the same pages, zero hipMemcpy). Triple-buffering
ping-pong: while the GPU computes layer L on slot[L % 3], the DMA of
L+1 is already in flight. Synchronization is per-slot hipEvent + a
dedicated io_uring_wait_cqe thread — never hipDeviceSynchronize().
Optional striping across both NVMe (~4.8 → ~9 GB/s).
Lookahead prefetch: while layer L executes, the router of L+1 applied
to the residual predicts ~70–85% of the cold experts of L+1 and starts
their DMA early (PrefetchAdvisor::on_layer_routed).
2. Pure Microkernel + Services
The microkernel contains no model logic. It does exactly three things: service registry & lifecycle, a typed control bus, and the memory/DMA broker. Inference engines are services on the bus, peers of loader/cache/network/telemetry.
- Control plane: typed messages on the bus (commands, events, domain hints, STOP/cancellation, telemetry). Default transport is in-process (thread/task, sub-microsecond); the contract allows out-of-process or Lyra transports later.
- Data plane: the hot GPU loop never copies tensors through the bus.
Services exchange only memory handles/capabilities granted by the UMA broker
(
SlabRingslots + fences). Two services can never own the same buffer.
Crate map (vetta-infer-*)
| Crate | Responsibility | unsafe |
|---|---|---|
vetta-infer-abi |
Shared contracts: domain types, bus message formats, .vplan opcodes, wire-protocol types, pure checked parsers (JSON, vplan, GEN), sampling algorithms & Leviathan verifier, DraftProvider/PrefetchAdvisor traits. Zero external dependencies. |
none |
vetta-infer-kn |
Microkernel: control bus, registry & lifecycle, STOP/cancellation, UMA/DMA broker (SlabRing + fence ownership). |
none |
vetta-infer-ld |
Loader & compiler (dual-step): ModelImporter per family → canonical IR → BackendPacker per HW target → .vbundle/. Checked .safetensors reader, write-once pack. |
none (pread via std) |
vetta-infer-cc |
Cache & storage: UMA residency, NVMe io_uring O_DIRECT streaming, Hot/Cold expert cache, domain pre-warm, .vbundle read-only reload. |
io_uring/pread syscalls |
vetta-infer-rt |
Operational runtime: executes CompiledPlan on the HIP backend at full speed, zero probes on the hot path. Thin HIP FFI + fence-guarded buffers. |
HIP FFI/DMA |
vetta-infer-lab |
Laboratory runtime: the same executor as rt (shared crate-internal core) with the probe-hook table from probe.vplan populated. Zero divergence by construction, not by discipline. |
via rt core |
vetta-infer-sp |
Speculative coordinator: lossless verification, throughput-aware Adaptive-K (faithful port of clover_policy.h), local MTP/BD drafter or remote via nt. |
none |
vetta-infer-nt |
LAN bridge to Lyra: remote drafting, domain routing, Vision/RAG offload (LyraRpc). |
none |
vetta-infer-tm |
Telemetry: passive bus observer, lock-free capture, JSONL/SQLite sink, writes stats/ profiles. |
none |
vetta-infer-gw |
Gateway & CLI: --serve (strata-ctl compatible), HTTP OpenAI/Anthropic, vetta-infer binary (info, serve, bench, stats). |
none |
unsafe is confined to cc (syscalls) and rt (HIP FFI/DMA). Everything else
is safe, CPU-testable Rust. Dependency rule: zero external deps in abi/kn
and all domain logic; audited crates allowed at the edges where correctness is
harder than the dependency risk (tokenizer: tokenizers; io_uring: libc or
a dedicated crate).
Lyra control/co-processor split
Sogliola = heavy MoE compute plane; Lyra = control plane / co-processor.
Only tokens, metadata and hints (<1 KB/step, ~0.3 ms) cross the LAN —
never per-layer tensors (no tensor parallelism: 64–128 AllReduce/token would
burn 20–40 ms/tok in latency alone).
- Remote drafter (
DraftProviderovernt): accepted tokens out (~48 B), K proposals + K scalar probabilities back (~64–128 B) for lossless Leviathan verification. A second physical GPU means target and drafter never contend for VRAM/DRAM bandwidth; Lyra can pipeline drafting (prepare the next block while Sogliola verifies the current one). Constraint: the drafter must share the target's tokenizer. - Semantic domain router (30–80 ms classification): simple requests can
be answered by Lyra directly; complex ones activate the right specialist
on Sogliola — full model swap from NVMe (
~4 s) or domain LoRA adapter swap (100–400 MB,20–80 ms) on a resident base model. - Domain-aware expert prefetch (the fusion with NVMe streaming):
tmrecords which experts activate per domain (zero training); Lyra's hint ("Dante/letteratura") preloads the historical top-64 experts of that domain into the Hot cache during prefill →85–95%hit rate from the first token. Model math stays 100% exact: an out-of-domain expert still triggers a normal NVMe miss.
3. Dual-Step Loader → .vbundle/
Streaming, two stages, zero intermediate files:
[.safetensors / config.json]
│ ModelImporter (1 per MoE family: Inkling / Clover / Qwen-MoE…)
▼ canonical IR in memory (standard names L03.moe.e042.w13, topology, logical shape/dtype)
│ BackendPacker (1 per HW target: rdna35-t16, …)
▼ packed directly into the inference-ready layout (4 KB aligned)
[<model>.vbundle/] written once: .tmp.<pid> + fsync + rename; always O_RDONLY afterwards
- New model = write only its
ModelImporter. New HW/layout = write only itsBackendPacker. No model-specific code in any service. manifest.jsoncarries: model identity, source fingerprint (FNV-1a), packer fingerprint + ABI version + backend target. A bundle produced by an incompatible packer/ABI is rejected explicitly, never misread.
<model>.vbundle/
├── manifest.json # identity, source+packer fingerprints, ABI version, target (gfx1150)
├── weights/ # IMMUTABLE — write-once, then O_RDONLY | O_DIRECT
│ ├── trunk.vbin # always-resident: embed, norms, attn/GDN proj, router, shared, lm_head, vision
│ └── experts.vbin # MoE experts, 4 KB aligned for DMA (striping experts.0/1.vbin on dual NVMe)
├── plan/ # declarative "programs" (KB), compiled by ld for the services
│ ├── graph.vplan # flat micro-bytecode (~15–20 opcodes, 1:1 with HIP microkernels)
│ ├── memory.vplan # static arena plan (scratch/KV/GDN): exact offsets, validated before launch
│ ├── prefetch.vplan # program for cc: layer/expert preload order & priorities
│ └── probe.vplan # optional measurement program for lab
├── tokenizer/ # tokenizer + chat template + special IDs (EOS, mask, thinking)
└── stats/ # UPDATABLE (KB), never touches weights/
├── routing_zipf.bin # historical global Zipf curve → cc pins hot experts at boot
└── domains/ # per-domain profiles written by tm (lean4.json, dante.json, …)
The auto-optimization loop closes through stats/: tm/lab write profiles →
on next turn/boot cc (with Lyra domain hints) pre-warms the right experts.
GB-scale weights are never rewritten (0 SSD wear).
4. Microcode: .vplan → CompiledPlan at Boot
Decision: lowering at boot, not interpretation, not codegen.
graph.vplan+memory.vplan(JSON, one uniform textual format with manifest/stats, inspectable withjq) are lowered atLoadModel(< 2 ms) into a flat array ofResolvedOp: device pointers, grids and parameters already resolved. Zero strings, zero HashMaps, zero allocations per token.- On decode
B=1the resolved plan can be captured into ahipGraphExec_t(critical: Inkling issues ~576 kernel launches/token). - No runtime source generation/compiler: the AOT microkernels already reach 92.5% of DRAM bandwidth on a memory-bound part; codegen would add 10–40 s of startup and a large debug surface for zero bandwidth gain.
memory.vplanis statically validated before the first GPU launch: no arena overlap, no use-before-write. The flat, non-Turing-complete opcode set makes this formally verifiable in Lean 4 (§8).rtandlabexecute the identicalCompiledPlan;labonly interleaves the observation points declared inprobe.vplan.
Initial opcode set (flat, fixed, 1:1 with microkernels)
embed_bf16, rms_norm (+residual/+1.0 offset flags), quantize_x_g64,
gemm_q8_g64_t16, gemm_q4_g64_t16, gemm_nvfp4_mxfp8, rope_kv_write,
flash_gqa_wmma (prefill / split-KV decode variants), gdn_chunkwise_wy,
gdn_recurrent_step (+history snapshot), moe_route_bucket, moe_w13_wmma
(fused SwiGLU+quantize), moe_w2_wmma, moe_reduce, vit_flash_attn_wmma,
gpu_penalties_topk. Control-flow opcodes are limited to loop_layer /
branch_b (batch-size dispatch) — no general computation in the plan.
5. Execution Engines
rt(operational): zero probes, zero debug branching on the hot path.lab(laboratory): same executor core, probe hooks enabled. Used for deep statistics collection without ever pollutingrt.- Both are services on the
knbus; a future backend (Vulkan/CUDA/RDNA4) is a newBackendPacker+ executor service, not a fork of the engine.
6. Wire Contract with strata-ctl (Principal Consumer)
Living consumer spec: strata-ctl/src/engine/protocol.rs + supervisor.rs.
The engine is a resident child process speaking lines on stdin/stdout,
one request at a time (FIFO, one conversation cache).
Engine → consumer (stdout)
| Line | Semantics |
|---|---|
READY <ctx> [stop] [hold] [holdb] |
first meaningful line; real context size + honoured controls. INFO may precede it; ERR before READY = startup refusal |
INFO k=v … |
engine facts (version, expert slots, …), also mid-request |
T <id> |
one generated token id |
PP <read> <total> [ms] [tok_s] |
prefill progress, one per chunk |
RESUME <n> |
prompt tokens served from cache, not re-read |
DONE <gen> <prompt> <prompt_ms> <decode_ms> <finish> [extra…] |
fields 1–5 stable; tail raw (spec/cache/expert stats may grow without breaking the consumer) |
ERR <msg> |
request/command failed; may be followed by a trailing DONE (consumer swallows it) |
Unknown lines are preserved verbatim by the consumer (Other): the protocol
may grow forward-compatibly.
Consumer → engine (stdin)
GEN <max_new> [key=value …] <id,id,…>, STOP, QUIT (also BGEN <slot> …
reserved). Keys emitted today by Sampling::keys(): temperature (>0 only),
top_p (<1 only), top_k (clamped 1..64, 0→64), min_p,
penalty_repeat/freq/present, penalty_last_n, seed (>0), image=<path>
(repeatable, Vision). Floats use Python-repr spelling (1.0).
Engine guarantees
STOPalways terminates the in-flight request with a drainableDONE.GEN 0= prefill + immediateDONE(pre-warm), neverERR.QUITexits the process promptly (clean shutdown, no hang).- Strict numeric/bounds parsing; unknown keys →
ERR(explicit, never silent). - Non-finite logits are reported (
finish=nonfinite/ explicit count), never silently masked.
Known deltas to close in tandem (tracked, not silent)
image=key: CLOSED on the parsing side (2026-11-30):abi::serveaccepts repeatableimage=<path>keys in prompt order;gwemits the consumer-compatible lines. Routing to GPU Vision lands with M1.top_kclamp: strata-ctl maps 0→64 and clamps to 64 (legacy engine path). vetta-infer supports full-vocabtop_k=0(F-09 fix) and GPU top-64 extraction; oncek_gpu_penalties_topklands, the consumer can drop the clamp. Coordinate the change in both repos in the same review cycle.spec/domain/draft_top_kkeys: engine-side extensions already parsed byabi; strata-ctl does not emit them yet (its Python CLI sibling did). Additive, no breakage.
7. Minimal Reusable HIP Microkernel Set (< 15 Primitives)
k_embed_bf16— BF16 embedding gatherk_rms_norm— fused RMSNorm (+ optional residual add /+1.0weight offset)k_quantize_x_g64— per-64 activation INT8 quantization (fusable with SwiGLU)k_gemm_q8_g64_t16— native RDNA 3.5 INT8 WMMA ([N/16, K/64, 4, 16, 16], FP16 scales)k_gemm_q4_g64_t16— SWAR 3-instruction INT4→INT8 WMMA (0.5625 B/param)k_gemm_nvfp4_mxfp8— direct Inkling NVFP4 / MXFP8 expert & trunk GEMMk_rope_kv_write— rotary embedding + FP8/FP16 KV cache write (SWA ring or linear)k_flash_gqa_wmma— fused FlashAttention-2 / GQA prefill (B >= 16) & Split-KV decode (B <= 2)k_gdn_chunkwise_wy— Chunkwise Parallel GDN (WY-representation) for250–350+ pptsprefill (new engineering; strata's sequential GDN is the measured bottleneck at ~95 ppts)k_gdn_recurrent_step— 0-spill GDN decode + history snapshot for<1 msspeculative rollbackk_moe_route_bucket— 100% GPU MoE routing + bitonic coreset + NaN/mask-safe compaction (0host sync)k_moe_grouped_wmma— compacted active-expertw13(fused SwiGLU + quantize) &w2+k_moe_reducek_vit_flash_attn_wmma—64×64FP16 WMMA Vision encoder attentionk_gpu_penalties_topk— GPU penalties +top-64extraction (<= 512 BD2H per row instead of6–16 MBwithtemp > 0)
Porting rule: strata kernels are the reference implementation; each ported
kernel ships a bit-exact parity test (as clover_gpu_parity_test did).
8. Formal Contracts (Lean 4)
Rule (Federico): simple logic is written directly with CPU tests; complex
logic (state machines, rings, pools, speculative/rollback, arena plans) is
verified by the Lean kernel before implementation. 0 sorryAx, standard
axioms only, lean proofs/<file>.lean.
Verified today (proofs/slab_ring_dma.lean, 10 theorems):
SlabRingDMA safety: mutual exclusionio_uringwrites / GPU reads, fence-gated reclaim, slot isolation (eliminates audit F-01 by construction).PrefixStatesoundness: no uninitialized MTP hidden-state reuse (F-03).- Checkpoint grid: guaranteed trigger on non-aligned post-
RESUMEchunks (F-06).
New obligations before the corresponding implementation:
memory.vplanarena safety: no overlap, no use-before-write, offsets within declared arenas (flat opcodes make this decidable). (pending, M1)- Bus lifecycle: STOP/cancellation drains to a terminal state; no service
observes a half-committed registry entry. VERIFIED (
bus_lifecycle.lean, 14 theorems) and implemented inkn. - Serve session lifecycle: STOP always drains to DONE,
GEN 0pre-warm skips decode, tokens only while decoding, one DONE per request cycle. VERIFIED (serve_session.lean, 10 theorems) and implemented ingw. - Adaptive-K exactness: port
adaptive_spec_exact_vs_arfromstrata-clover/proofs/clover_gdn_ckpt.leanto the faithful Rust controller. (controller ported with scenario parity tests; formal port pending) - Hybrid GDN+KV restore: port
restore_then_continue_equiv/kv_only_restore_unsoundwhen the unified prefix pool lands (M2).
9. Migration Map (M0 → target)
Status: completed 2026-11-30. The M0 crates were dissolved into the target
crates below; the workspace is vetta-infer-* only, all CPU tests and Lean
proofs green, and the vetta-infer binary (now in gw) verified live on
Inkling (1244 tensors, 18.18 GiB, checked bounds).
| M0 source | Destination | Note |
|---|---|---|
vetta-core::slab |
kn (broker) |
state machine already Lean-verified |
vetta-core::prefix |
rt (pool) + abi (types) |
extend to unified SWA+Full-KV+GDN pool in M2 |
vetta-core::sampler |
abi (pure algorithms) |
used by rt/sp/gw; GPU path added by k_gpu_penalties_topk |
vetta-core::moe |
cc |
Hot/Cold + pre-warm |
vetta-core::traits (AdaptiveKController) |
sp |
rewrite as faithful port of clover_policy.h (cooldowns, probes, throughput guards) + parity tests |
vetta-core::traits (DraftProvider, PrefetchAdvisor) |
abi |
unchanged |
vetta-io (safetensors reader, VTC1 cache) |
ld (pack) / cc (reload+stream) |
checked parsers move to abi as pure functions |
vetta-proto (serve parsing) |
abi (types/parsers) + gw (emitter/lifecycle) |
add image=, DONE/PP/RESUME emitters, STOP→DONE guarantee |
vetta-proto (LyraRpc) |
nt |
unchanged |
vetta-telemetry |
tm |
add stats/ profile writer |
vetta-hip (UmaSlabPool) |
kn (ownership) + rt (FFI) |
M2: real mmap + hipHostRegister + io_uring |
vetta-cli |
gw |
binary stays vetta-infer |
kernels/hip/vetta_kernels.h |
unchanged | ABI grows with M1/M2 kernels |
10. Milestones
- M0 (done): workspace skeleton, Lean contracts, checked IO, serve parsing, telemetry, HIP ABI — all audit-hardened, 11/11 CPU tests, 10/10 theorems.
- M0.5 (current): this specification + crate realignment to
vetta-infer-*, faithful policy ports with parity tests, wire-contract deltas closed. - M1 (Resident MoE End-to-End — Inkling-2-Mini): HIP microkernels,
NVFP4/MXFP8 +
Q8_G64_T16trunk, GPU Vision (image=key), write-once.vbundle, strata-ctl drop-in--serveparity & speed vs C++ baseline (>= 18 tok/s,< 4 sreload). - M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming): Chunkwise Parallel GDN
(WY,
250–350+ ppts), Clover-35B-A3B & MTP support,io_uring O_DIRECT+hipHostRegisterSlabRingping-pong, Hot/Cold cache + lookahead prefetch, unified hybrid prefix pool (Lean-verified restore). Goal: giant MoE (120B–300B+) running on 96 GiB UMA via cold-expert streaming (~3–8 tok/s). - M3 (Distributed Control Plane — Lyra): remote
DraftProvider+ domainPrefetchAdvisorover LAN, telemetry-driven domain pre-warming.
11. Verification & Review Workflow
- Proofs:
lean proofs/<file>.lean(0sorryAx). CPU:cargo test --workspacewith-D warnings. GPU parity tests on Sogliola for every ported kernel. - Tandem: the strata-ctl coder and the vetta-infer coder periodically review each other's work; an external reviewer audits both. Wire-protocol changes land in coordinated review cycles (§6 deltas).
- No silent regressions, no unmeasured claims: every performance number carries
hardware/model/flags. Commit prefixes:
[ABI],[KN],[LD],[CC],[RT],[LAB],[SP],[NT],[TM],[GW],[Proofs],[Docs].