- abi::bundle: manifest guard fields from the strata-ctl encoder incident
(review/2026-12-01-guardie-encoder.md): provenance {repo_id, revision,
shards sha256 = HF lfs.oid anchor, 64 lowercase hex validated},
model_kind decoder|encoder (encoder REQUIRES the full encoder_recipe:
pooling, end_text_token id, append_end_text, max_tokens, query/doc prefix,
native_dim — never derived from architecture), calibration {floor_hit,
peak_noise} finite in [-1,1]. Identity is provenance, not tensor shape.
- abi::sha256: pure FIPS 180-4, streaming update for GB shards, zero deps;
NIST vectors + million-a + streaming/chunk parity tests.
- abi::vplan: pool_l2norm generalized (mode mean|cls|last_token from the
manifest recipe), replacing mean_pool_l2norm.
- gw: `vetta-infer tensors <dir> [prefix]` subcommand; captured the live
Inkling inventory (docs/inkling-tensor-inventory.txt, 1244 tensors:
994 BF16 / 154 F32 / 48 F8_E4M3 / 48 U8) — ground truth for the importer.
- BGE-M3 recipe verified on the artifact: dense = CLS (1_Pooling/config.json
+ reference converter), 16 heads x 64, absolute position embeddings present;
spec/README corrected. Ordering: Inkling first, utility after (Federico).
- review/: tandem exchange (guardie + nostra risposta + osservazioni-recipe).
Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 75/75 PASS;
lean proofs/{slab_ring_dma,bus_lifecycle,serve_session,arena_plan}.lean green
(42 theorems, 0 sorryAx, standard axioms only).
449 lines
29 KiB
Markdown
449 lines
29 KiB
Markdown
# 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 | O_DIRECT` + `io_uring` into `hipHostRegister` buffers gives **zero-copy NVMe → GPU DMA** on UMA |
|
||
| 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.
|
||
|
||
**Carve-out — utility encoder models (2026-11-30):** the dense exclusion
|
||
applies to dense *decoder LMs* (40–70 GB read per generated token). Small
|
||
dense **encoders** are a different execution shape — a single forward pass,
|
||
fully UMA-resident, no KV growth — and are **in scope** as the M1.5 embedder
|
||
lane (BGE-M3 q8 ~600 MB, requested by the strata-ctl agent for its vector
|
||
memory; see §6 embedder wire). Utility ≠ generative: the "MoE-only" rule
|
||
governs generation only.
|
||
|
||
### 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
|
||
(`SlabRing` slots + 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).
|
||
|
||
1. **Remote drafter** (`DraftProvider` over `nt`): 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.
|
||
2. **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.
|
||
3. **Domain-aware expert prefetch** (the fusion with NVMe streaming): `tm`
|
||
records 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 its
|
||
`BackendPacker`. No model-specific code in any service.
|
||
- `manifest.json` carries: 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.
|
||
**Implemented** (2026-11-30): `abi::bundle` (manifest + `memory.vplan` +
|
||
`graph.vplan` parsing, arena-validated `compile`) and `ld::bundle::
|
||
load_bundle_plans` (read-only directory load). Device-pointer resolution
|
||
into the flat `CompiledPlan` lands with the M1 packer/executor.
|
||
- **Identity is provenance, not tensor shape** (guard from the strata-ctl
|
||
incident 2026-12-01, `review/2026-12-01-guardie-encoder.md`): an embedder
|
||
and a reranker of the same base share tensor names, shapes, layer count and
|
||
`architectures`. The manifest therefore carries optional but strictly
|
||
validated `provenance {repo_id, revision, shards[{name, sha256}]}` — the
|
||
sha256 is the HuggingFace `lfs.oid` anchor, verified by the packer at import
|
||
time (M1). `model_kind: decoder|encoder` (default decoder); **encoder
|
||
bundles MUST declare the full input recipe** `encoder_recipe {pooling
|
||
(mean|cls|last_token), end_text_token?, append_end_text, max_tokens,
|
||
query_prefix, doc_prefix, native_dim}` — pooling and prefixes are declared
|
||
properties, never derived from the architecture string, never defaulted
|
||
silently. Optional `calibration {floor_hit, peak_noise}` (finite, in
|
||
`[-1,1]`) hands the measured cosine scale to the consumer's per-model
|
||
threshold table. All implemented in `abi::bundle` (2026-12-01).
|
||
|
||
```
|
||
<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 with `jq`) are lowered at `LoadModel` (< 2 ms)
|
||
into a flat array of `ResolvedOp`: device pointers, grids and parameters
|
||
already resolved. Zero strings, zero HashMaps, zero allocations per token.
|
||
- On decode `B=1` the resolved plan can be captured into a `hipGraphExec_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.vplan` is **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).
|
||
- `rt` and `lab` execute the *identical* `CompiledPlan`; `lab` only interleaves
|
||
the observation points declared in `probe.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.
|
||
|
||
**Encoder-lane additions (M1.5, embedder):** `layer_norm` (true LN: mean +
|
||
variance + affine — not RMSNorm), `flash_full_attn` (bidirectional variant of
|
||
`flash_gqa_wmma`: padding mask only, no causal mask — a mask parameter, not a
|
||
new primitive), `gelu_erf` (exact-erf FFN epilogue, replaces the SwiGLU
|
||
fusion), `pool_l2norm` (pooling mode `mean|cls|last_token` taken from the
|
||
manifest `encoder_recipe` + L2 normalize, one small fused kernel — BGE-M3
|
||
dense is **CLS**, declared in its `1_Pooling/config.json`, not mean). GEMMs, allocator, SlabRing and the HIP
|
||
backend are reused unchanged. The executor is selected by the `.vplan` itself
|
||
(encoder = single-pass plan, decoder = token loop): `kn` stays model-agnostic.
|
||
|
||
## 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 polluting `rt`.
|
||
- Both are services on the `kn` bus; a future backend (Vulkan/CUDA/RDNA4) is a
|
||
new `BackendPacker` + 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
|
||
|
||
1. `STOP` always terminates the in-flight request with a drainable `DONE`.
|
||
2. `GEN 0` = prefill + immediate `DONE` (pre-warm), never `ERR`.
|
||
3. `QUIT` exits the process promptly (clean shutdown, no hang).
|
||
4. Strict numeric/bounds parsing; unknown keys → `ERR` (explicit, never silent).
|
||
5. 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::serve`
|
||
accepts repeatable `image=<path>` keys in prompt order; `gw` emits the
|
||
consumer-compatible lines. Routing to GPU Vision lands with M1.
|
||
- **`top_k` clamp:** strata-ctl maps 0→64 and clamps to 64 (legacy engine
|
||
path). vetta-infer supports full-vocab `top_k=0` (F-09 fix) and GPU top-64
|
||
extraction; once `k_gpu_penalties_topk` lands, the consumer can drop the
|
||
clamp. Coordinate the change in both repos in the same review cycle.
|
||
- **`spec`/`domain`/`draft_top_k` keys:** engine-side extensions already
|
||
parsed by `abi`; strata-ctl does not emit them yet (its Python CLI sibling
|
||
did). Additive, no breakage.
|
||
|
||
### Embedder-lane wire (M1.5, proposal for the next review cycle)
|
||
|
||
Origin: `review/richieste-embedder.md` + `review/osservazioni-embedder-e-scope.md`
|
||
(strata-ctl agent, 2026-11-30). Reference fork: Gitea `iz0eyj/vetta-semantics`,
|
||
branch `vetta-semantic` (HEAD `549ebf8d`), local original `../vetta-semantics`
|
||
(the `tmp/` clone was removed 2026-11-30). Math source:
|
||
`embedder/src/encoder_graph.cpp` / `encoder_runtime.cpp`;
|
||
parity oracle: live `vetta-embedder` on `:8091`. First cut = **separate
|
||
resident process** `vetta-infer embed` (does not touch the Lean-verified
|
||
`serve_session` FSM; different model set, reuses supervision/parsing):
|
||
|
||
- handshake: `READY` + `INFO embedder=bge-m3 dim=1024 sparse=0 colbert=0 reranker=<0|1>`
|
||
(capability discovery is mandatory; transport is negotiable, capabilities are not);
|
||
- `ENC <n> [k=v…]` followed by `n` text lines → `n` vector lines + `DONE`;
|
||
payload **base64 f32** (lossless, compact, no float-repr ambiguity); CSV only
|
||
if the consumer prefers debuggability — to be settled in the review cycle;
|
||
- `RERANK <query>` + doc payload → scores + `DONE` (only when `reranker=1`);
|
||
- `QUIT` clean. Scope per §6 of the request: **dense only** in the first cut
|
||
(batch = slice interface, one-by-one execution), reranker head optional;
|
||
sparse/ColBERT/ordered-walk stay in `vetta-semantics`, explicitly excluded.
|
||
|
||
Acceptance (request §8): `encode([it, code, mixed])` → L2-norm ≈ 1.0 and
|
||
**cosine ≥ 0.999 vs `:8091`** on the same corpus; no prompt prefixes for
|
||
BGE-M3 (verified: the fork excludes `m3` explicitly); batch result
|
||
bit-parity/cosine ≈ 1 vs one-by-one. **Plus two cheap guards before any
|
||
benchmark** (strata-ctl note 2026-12-01): (a) reproduce the publisher's
|
||
model-card numeric fixture (4 sentences, expected cosines — catches attention
|
||
mask / pooling / input-composition bugs together in seconds); (b) anisotropy
|
||
canary: 8 unrelated texts, mean pairwise cosine `< ~0.45` healthy,
|
||
`> 0.85` broken regardless of what any label says. The bidirectional mask
|
||
must be EXPLICIT in the encoder attention opcode (`flash_full_attn`): a
|
||
causal mask on an encoder finishes cleanly and produces a semantically wrong
|
||
space with no error anywhere. On delivery, hand the consumer the measured
|
||
`calibration {floor_hit, peak_noise}` (or a control-query fixture) so its
|
||
per-model threshold table is calibrated, never guessed; the int8 in-process
|
||
path re-probes the cosine scale, it does not assume the q8 scale transfers.
|
||
|
||
**Characteristic parity with the reference engine** (decided 2026-11-30):
|
||
per-token activations as first-class outputs are *native* here — the `[T, d]`
|
||
pre-pool activation lives in a `memory.vplan` arena and `probe.vplan`/`lab`
|
||
is exactly the declared observation mechanism (semantic-walk/ColBERT-style
|
||
emission = an output mode, not a fork); sparse/ColBERT heads are extra GEMMs
|
||
on the same pass, deferred by scope choice, not by capability. Two honest
|
||
exceptions: (1) **bit-identity is internal-only** — our golden/parity tests
|
||
are bit-exact against our own CPU references (strata porting rule); against
|
||
the ggml oracle the metric is semantic (cosine ≥ 0.999), since WMMA
|
||
accumulation order differs by construction; Qdrant Edge is rebuildable, a
|
||
one-shot batch re-embed covers any zero-delta migration. (2) Vulkan/portable
|
||
CPU fallback is replaced by the `BackendPacker` abstraction (§5); the CPU
|
||
reference built for parity tests is the seed of a future CPU backend.
|
||
|
||
## 7. Minimal Reusable HIP Microkernel Set (`< 15` Primitives)
|
||
|
||
1. `k_embed_bf16` — BF16 embedding gather
|
||
2. `k_rms_norm` — fused RMSNorm (+ optional residual add / `+1.0` weight offset)
|
||
3. `k_quantize_x_g64` — per-64 activation INT8 quantization (fusable with SwiGLU)
|
||
4. `k_gemm_q8_g64_t16` — native RDNA 3.5 INT8 WMMA (`[N/16, K/64, 4, 16, 16]`, FP16 scales)
|
||
5. `k_gemm_q4_g64_t16` — SWAR 3-instruction INT4→INT8 WMMA (`0.5625 B/param`)
|
||
6. `k_gemm_nvfp4_mxfp8` — direct Inkling NVFP4 / MXFP8 expert & trunk GEMM
|
||
7. `k_rope_kv_write` — rotary embedding + FP8/FP16 KV cache write (SWA ring or linear)
|
||
8. `k_flash_gqa_wmma` — fused FlashAttention-2 / GQA prefill (`B >= 16`) & Split-KV decode (`B <= 2`)
|
||
9. `k_gdn_chunkwise_wy` — **Chunkwise Parallel GDN (WY-representation)** for `250–350+ ppts` prefill (new engineering; strata's sequential GDN is the measured bottleneck at ~95 ppts)
|
||
10. `k_gdn_recurrent_step` — 0-spill GDN decode + history snapshot for `<1 ms` speculative rollback
|
||
11. `k_moe_route_bucket` — 100% GPU MoE routing + bitonic coreset + NaN/mask-safe compaction (`0` host sync)
|
||
12. `k_moe_grouped_wmma` — compacted active-expert `w13` (fused SwiGLU + quantize) & `w2` + `k_moe_reduce`
|
||
13. `k_vit_flash_attn_wmma` — `64×64` FP16 WMMA Vision encoder attention
|
||
14. `k_gpu_penalties_topk` — GPU penalties + `top-64` extraction (`<= 512 B` D2H per row instead of `6–16 MB` with `temp > 0`)
|
||
15. `k_layer_norm` — true LayerNorm (mean+var+affine) for the encoder lane
|
||
16. `k_pool_normalize` — fused pooling (mean / cls / last-token per recipe) + L2 normalize
|
||
|
||
Bidirectional encoder attention (`flash_full_attn`) and GELU-erf FFN are
|
||
mask-parameter / epilogue variants of primitives 4/8, not new kernels — the
|
||
encoder lane keeps the set at 16 and reuses everything else.
|
||
|
||
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 (`proofs/slab_ring_dma.lean`, 10 theorems):
|
||
- **`SlabRing` DMA safety:** mutual exclusion `io_uring` writes / GPU reads,
|
||
fence-gated reclaim, slot isolation (eliminates audit F-01 by construction).
|
||
- **`PrefixState` soundness:** no uninitialized MTP hidden-state reuse (F-03).
|
||
- **Checkpoint grid:** guaranteed trigger on non-aligned post-`RESUME` chunks (F-06).
|
||
|
||
New obligations before the corresponding implementation:
|
||
- **`memory.vplan` arena safety:** no overlap, no use-before-write, offsets
|
||
within declared arenas (flat opcodes make this decidable). **VERIFIED**
|
||
(`arena_plan.lean`, 8 theorems + 4 computational examples) and implemented
|
||
in `abi::arena` (checked offset arithmetic, invariant #2).
|
||
- **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 in `kn`.
|
||
- **Serve session lifecycle:** STOP always drains to DONE, `GEN 0` pre-warm
|
||
skips decode, tokens only while decoding, one DONE per request cycle.
|
||
**VERIFIED** (`serve_session.lean`, 10 theorems) and implemented in `gw`.
|
||
- **Adaptive-K exactness:** port `adaptive_spec_exact_vs_ar` from
|
||
`strata-clover/proofs/clover_gdn_ckpt.lean` to 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_unsound` when 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 (done):** 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, in progress):** HIP
|
||
microkernels, NVFP4/MXFP8 + `Q8_G64_T16` trunk, GPU Vision (`image=` key),
|
||
write-once `.vbundle`, strata-ctl drop-in `--serve` parity & speed vs C++
|
||
baseline (`>= 18 tok/s`, `< 4 s` reload). Landed: serve-session FSM
|
||
(`serve_session.lean` + `gw::session`), arena safety (`arena_plan.lean` +
|
||
`abi::arena`), `.vbundle` manifest/plan contract (`abi::bundle` +
|
||
`ld::bundle`). Next: ModelImporter/BackendPacker → first real `.vbundle`,
|
||
device-pointer resolution, HIP kernel ports with parity tests.
|
||
- **M1.5 (Embedder lane — BGE-M3):** encoder `.vplan` family + XLM-R
|
||
ModelImporter (`ld`), SPM unigram tokenizer + `nmt_nfkc` (`nt`),
|
||
`layer_norm`/`flash_full_attn`/`gelu_erf`/`pool_l2norm` kernels (`rt`),
|
||
`vetta-infer embed` wire (§6). Acceptance: cosine ≥ 0.999 vs the live
|
||
`:8091` oracle on it/code/mixed corpus. May be **pulled before M1 decode**
|
||
as the HIP kernel bring-up bench: a standard dense encoder is the easiest
|
||
real GPU target and shares the GEMM/flash backend the MoE loop needs.
|
||
Reranker head (BGE-Reranker-v2-m3) rides the same executor, only the
|
||
`INFO reranker=1` capability is added.
|
||
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** Chunkwise Parallel GDN
|
||
(WY, `250–350+ ppts`), Clover-35B-A3B & MTP support, `io_uring O_DIRECT` +
|
||
`hipHostRegister` `SlabRing` ping-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` + domain
|
||
`PrefetchAdvisor` over LAN, telemetry-driven domain pre-warming.
|
||
|
||
## 11. Verification & Review Workflow
|
||
|
||
- Proofs: `lean proofs/<file>.lean` (0 `sorryAx`). CPU: `cargo test --workspace`
|
||
with `-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]`. |