Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

rivoli

Male Rivoli's hummingbird in flight
Rivoli's hummingbird, male. Bettina Arrigoni, CC BY 2.0; background removed

rivoli.

Decode LLMs bigger than memory, on one box. Weights stream from NVMe overlapped with compute.

RustHIP / ROCmunified memory systemsNVMe streamingMoE

rivoli is a decode engine for large language models that do not fit in memory. It is designed for ROCm unified memory systems, where the CPU and GPU share one pool of RAM. Whatever does not fit stays on NVMe. In each layer the GPU starts on the experts already in memory while the missing ones stream in, so NVMe reads hide behind compute.

CPUNVMe → RAMGPUattnroutesubmitread misseshitsreapmisseslayer 1attnroutesubmitread misseshitsreapmisseslayer 2time →

In each mixture-of-experts layer:

  1. GPU: attention, then the router’s gate logits.
  2. CPU, route: reads the gate logits and picks the top-k experts for each token (sigmoid, bias, top-k), then merges the picks across tokens.
  3. CPU, submit: looks up each chosen expert in the cache. A hit gets a ticket that is already satisfied. A miss gets a slot and an NVMe read, and a ticket that the read will satisfy.
  4. GPU, hits: runs the resident experts immediately, while the misses stream in.
  5. CPU, reap: collects completed reads and releases their tickets.
  6. GPU, misses: runs the experts that just arrived. Every expert launch waits on its ticket, so there is no “is it resident?” branch.

The overlap is the whole design. A model that fits in memory is not a separate mode. It is the trivial case of the streaming path, where everything happens to be resident.

What makes it different

  • Built for unified memory. rivoli targets ROCm systems where the GPU reads system RAM directly, so there is no separate VRAM copy to manage. When a hardware-specific path is faster, it wins over portability (P3).
  • Bytes per token is the currency. Decode speed is traffic divided by bandwidth. Quantization, residency, prefetch and speculative decode are all ways to cut traffic. Each one’s quality cost is measured, never assumed (P5).
  • The memory knob trades speed, never text. --max-mem changes tok/s and hit rate. It does not change the output (P4).
  • Every claim is a gate that can go red. Each test is shown failing on purpose before its pass counts (Quality gates).

Where to go next

  • The overlap: how streaming, residency and caching fit together.
  • Principles: the seven rules every change is checked against.
  • Architecture: six crates whose dependency graph is the layering.
  • Models: the model families in the tree.
  • Building: toolchain, build and test commands.

The overlap

A decode step walks the model one layer at a time. On a model bigger than memory, some of each layer’s weights live on NVMe. rivoli’s job is to keep the GPU busy while the missing bytes arrive.

Three tiers

tierholdsreached by
Pinwhatever the memory budget leaves room forthe GPU directly, from shared RAM
Cacherecently or frequently used experts and layersthe GPU directly, from shared RAM
Streameverything elseNVMe reads into staging slots, then a copy the GPU waits on

On a unified memory system the GPU reads system RAM directly, so “resident” just means “already in RAM”, with no separate VRAM copy. The NVMe-to-RAM leg is what has to hide behind compute.

The pin is a function of free memory

What stays resident is decided at run time from how much memory is actually free. That depends on other tenants, on the KV cache at the configured context, and on scratch space. It is never decided by model architecture (P6).

In the code, a single function, rivoli-core::residency::partition(ordered, free, floor), makes that decision. It has no architecture parameter to consult. Its result is a prefix of the caller’s priority order, so more memory only ever extends the pin. A dense model that fits is the same code path with the prefix covering everything. A budget below the floor is refused with the arithmetic in the message, so a run never silently degrades.

Caching is a trade

The cache is not a transparency layer. Memory space, bandwidth and compute form a triangle, and which format a layer or expert takes is a decision made against it (P2). For example, a 4-bit format can be cheaper to compute but more expensive to store than a 3-bit vector-quantized one. The 4-bit format is used where there is bandwidth and space to load it, and the 3-bit one where there is not.

No residency branch in the loop

For mixture-of-experts layers, submitting the routed experts returns one ticket per expert, not a “this one is resident” mask. The kernel launch waits on the ticket. A resident expert’s ticket is already satisfied, so resident, missing and in-flight experts all take the same path. The loop has nothing to branch on, so it cannot branch wrong.

Waits can be enqueued on the device before their producer exists, and any wait can be released from the host. So a fetch that fails returns an error instead of hanging the GPU.

Principles

Seven principles, confirmed by the project owner on 2026-08-12. A change that violates one is wrong even if every test passes.

P1 — Decode models bigger than memory, on one box

A ROCm unified memory system, with weights streamed from NVMe overlapped with compute. The overlap is the whole design; everything else serves it. A model that fits is the trivial case of the streaming path, never a separate resident-only design.

P2 — Caching is a key principle

The engine trades in the triangle of memory space, bandwidth and compute. Which format an expert or layer occupies is a first-class decision made against that triangle, not a detail hidden behind a cache.

P3 — Maximize hardware features

Running everywhere is not a goal when it costs performance: hardware compatibility is always traded away for efficiency. Hardware-specific kernel decisions need no apology. If the NPU becomes valuable, rivoli will use it.

P4 — The memory knob trades speed, never text

--max-mem and cache policy move tok/s and hit rate, not output. Any scheme that picks a format based on residency must state where it stands against this principle.

P5 — Bytes per token are the currency

Decode speed = traffic ÷ bandwidth. Quantization, residency, prefetch and speculative decode are all traffic levers. The quality price of each is measured on paired per-token NLL differences, never assumed. A win counts even when another bottleneck hides it, and one-time costs amortize to nearly zero over millions of decodes.

P6 — The pin is a function of free memory

What is resident is decided by how much memory is free at run time, never by model architecture. “This model is dense, so everything is pinned” and “this model routes, so experts stream” are both category errors. The pin holds whatever the budget leaves room for, and the streaming path must be able to carry anything the pin dropped.

P7 — Every claim is a gate that can go red

Tolerances are measured before the kernel exists. Red proofs are run and reverted. Invariants are registered with tests. A gate is proven able to fail before its pass is believed. This is method rather than product, but it decides what any plan may call “done”. See Quality gates.

Architecture

rivoli is a Rust workspace with one backend, HIP/ROCm. Its six crates are the layering: crate edges are the only layering Rust enforces, so the boundaries that matter are crates.

crateismay depend on
rivoli-corepure planning: residency, spans, legality, gates, tolerancesnothing
rivoli-artifactformats, per-model configs, sniffing, tokenizer, converterscore
rivoli-oraclesfrozen references, golden container, anchor readerscore
rivoli-backendthe waist: HIP streams, launchers, kernels; owns rocmnothing
rivoli-enginethe interpreter: fetch, executors, per-architecture loopsall above
rivoli (cli)thin main, serve and tool binariesengine

Pure core, imperative shell

rivoli-core is total functions over plain data. It emits values (directives, spans, verdicts) and never acts. rivoli-engine is the interpreter that spends those values on the device. Nothing in core can name a stream, a pointer or a weight format, and the dependency graph enforces it. That is what makes “residency selects arithmetic” impossible to write here, rather than merely tested against.

Types carry the rules

  • Newtypes for units. Bytes, tokens, layers and expert ids are never bare usize.
  • Typestate for lifecycles. A fetch ticket is consumed by waiting on it, a writer is sealed, and an unloaded artifact is a different type from a loaded one.
  • No panicking shortcuts. unwrap and expect are denied across the workspace.

Kernels in Rust

The device kernels are written in Rust (crates/kernels) and built with a pinned nightly toolchain against ROCm’s device bitcode. hipcc is not a build input. Every kernel is checked bit-for-bit against the original HIP C++ implementation it replaced, at a pinned tag.

The artifact is the model

rivoli <artifact> takes a converted artifact directory: a manifest, codebooks, resident tensors, per-layer expert files and a tokenizer. The artifact names its own architecture. CLI flags are checked against it at startup, and an illegal one is refused with the reason.

Models

rivoli targets large mixture-of-experts models. Supporting a model means an artifact converter, a per-architecture decode loop, and first-party reference goldens that the loop is scored against. Which models belong to which code path is data in a checked census table, not something encoded in code names.

At a glance

modelparams1experts2attentionformatstok/s3Intelligence Index1
GLM-5.2753B / 40B256 (8)MLA4VQ3, INT453.06N/A7
DeepSeek-V4-flash284B / 13B256+1 (6)MQA, SWA + blocks8FP49.29N/A7
Kimi-K32.8T / 104B896+2 (16)KDA + MLA10MXFP411—121713
Muse Glimmer30B dense—GQA, SWA14BF16, FP815—16617
Inkling 2 Mini26B / 5.4B128 (8)SWA + full, sinks18BF161911.7 / 2.32020
Inkling 2 Small594B / 17B384 (8)SWA + full, sinks18MXFP811—1231
Qwen3.8-Flash-Next180B / 6B512+1 (10)GDN + sparse21FP815—1228

Pipeline and verification

modelconvertdecodeservePPL22vs. referencesmokeopen
GLM-5.2✓✓✓✓32/32 ids12/12stale-read defect23
DeepSeek-V4-flash✓✓✓24—30/32 ids253/3NLL-by-position gate
Kimi-K3✓✓26✗27—KDA 2.3e-728—context alloc. vs. floor29
Muse Glimmer✓✓✓✓goldens 3/3halves30drafter31
Inkling 2 Mini✓✓✓✓8/8 ids16/16—
Inkling 2 Small✓pending——logits 1.5e-5326/633live GPU decode
Qwen3.8-Flash-Next✓✗✗—anchors vendored—decode arm (S6–S8)

✓ built and passing · ✗ refused at startup with the reason · — not built or not measured. “ids” means greedy token ids identical to the first-party reference on the pinned prompt. Every model runs text only: multi-token-prediction heads and vision towers are refused or left out of the artifact. The repository’s docs/ hold the evidence for every row; see the docs index.


  1. Parameter counts (total / active per token) and Intelligence Index scores as published by Artificial Analysis on its v5.0.2 index, read on 2026-11-25. Scores from earlier index versions are on a different scale and are not mixed in. ↩ ↩2

  2. Routed experts per MoE layer (+ shared experts), with the number active per token in parentheses. From the model configs in the repository. ↩

  3. Decode tokens per second, release build, measured under the GPU lock with an empty contention witness. Test machine: AMD Ryzen AI Max+ 395 (Radeon 8060S, ROCm), 128 GB unified LPDDR5, artifacts on a local Samsung 9100 PRO 1 TB (PCIe 5.0) NVMe with btrfs. Numbers move with the memory budget (--max-mem) and the prompt; each footnote names its arm. ↩

  4. Multi-head latent attention. ↩

  5. VQ3: 3-bit vector (codebook) quantization. INT4: 4-bit integer. ↩

  6. 3.03 tok/s, mean of three arms, 512 tokens, --max-mem 115, 3-bit VQ, 2026-11-20. About 2.1 GB of expert slots streamed per token. ↩

  7. Deprecated on Artificial Analysis, with no score on the v5 index. ↩ ↩2

  8. Multi-query attention with a shared K=V head; a 128-token sliding window plus compressed blocks chosen by an indexer. ↩

  9. 9.17 tok/s, 512 tokens, --max-mem 100, 2026-08-16. Its prompt was not recorded, so the arm has not been reproduced. ↩

  10. Hybrid: 69 Kimi Delta Attention (linear) layers and 24 gated MLA layers. ↩

  11. OCP microscaling formats: 4- or 8-bit floats sharing one scale per 32-element block. Kimi-K3’s MXFP4 is repacked bit-exact. ↩ ↩2

  12. No witnessed decode speed yet. ↩ ↩2 ↩3

  13. Low reasoning effort; the max-effort score is not listed. ↩

  14. Grouped-query attention (32 query, 2 KV heads); three sliding-window layers (2048 tokens) per full-attention layer. ↩

  15. FP8 e4m3 with one scale per 128-element block. ↩ ↩2

  16. A bf16 figure from 2026-08-16 (2.56 tok/s) is superseded; the re-take is owed. ↩

  17. High reasoning effort. ↩

  18. Sliding-window and full-attention layers, with attention sinks. ↩ ↩2

  19. Converted to bf16 from the checkpoint’s NVFP4/MXFP8 weights. ↩

  20. 11.7 tok/s with all 24 layers resident (90 GiB budget); 2.3 tok/s at a 20 GiB budget, streaming 16 of 24 layers. 64 tokens, 2026-11-25. Both arms produced identical token ids. ↩

  21. Hybrid: 36 Gated DeltaNet (linear) layers and 12 indexed sparse-attention layers. ↩

  22. Teacher-forced perplexity scoring, the producer for paired per-token NLL comparisons. ↩

  23. Under some timing, a GPU read of memory the NVMe has just written can return stale data, so long stock runs have not always reproduced their own output. --copy-via-cpu is a validated fix candidate; --arena-refresh is a lighter mitigation. ↩

  24. Uses GLM’s chat framing, a known gap. ↩

  25. Both differing positions are near-ties between the top two tokens. ↩

  26. Correctness only so far: a first 16-token decode, coherent. ↩

  27. No chat encoding yet. ↩

  28. Linear-attention (KDA) layer outputs match the reference captures to 2.3e-7. ↩

  29. At --ctx 4096 an allocation that grows with context is not yet charged to the memory floor, so the run can fail after the pin is placed. ↩

  30. Covered by the device-halves gate rather than an end-to-end smoke script. ↩

  31. The DFlash speculative drafter has a converter and an oracle so far. ↩

  32. MXFP8 logits within 1.5e-5 (relative) of the bf16 reference. ↩

  33. Deviceless cells only. ↩

Quality gates

Every claim is a gate that can go red, and a gate is proven able to fail before its pass is believed. A check that has never failed is not evidence. A check that can silently examine zero items is not a check.

Test-first, against first-party references

  • Anchors come first. Golden outputs come from the model’s own reference stack, never a transliteration. They are vendored with self-describing pins and gated by a defect matrix: every planted defect must turn the gate red where it should.
  • Tolerances carry provenance. They are measured from fp32 floors on at least two weight draws before the kernel exists. A tolerance picked to make a kernel pass is not a tolerance.
  • Red proofs are recorded. Every new gate ships with a run that shows it failing.

What runs

gatechecks
duplication (jscpd)zero clones, on every build
CodeScene10/10 across the whole tree
line caps1200 lines hard, 800 soft
clippy, warningsdenied as errors workspace-wide
paritygreedy token ids identical to the pinned reference
perplexity gatespaired per-token NLL inside a pre-registered equivalence band
bit-identityevery Rust kernel byte-identical to its HIP C++ predecessor
kernel censusevery launcher has an oracle and a production caller
invariant registryevery documented invariant has a test, and the reverse
docs registryevery doc carries status, scope and verdict

Measurement discipline

  • The GPU is sole-tenant. Every device run takes a lock and samples a contention witness. Any arm with another tenant present is discarded.
  • Quality is ranked on paired dNLL, never on a perplexity column. An interval that straddles zero is inconclusive, not a pass.
  • Run the A-vs-A control. Some streaming configurations are not bit-reproducible, so the noise floor is measured per arm. A difference below it is not a measurement.
  • An unwitnessed number is unciteable.

Building

Requirements

  • A ROCm unified memory system (an AMD APU), with ROCm’s device bitcode (ocml.bc and friends) and libamdhip64.
  • rustup, with the nightly toolchain pinned in crates/kernels/rust-toolchain.toml for the device crate.
  • Fast NVMe for the streamed weights.

The default build is the ROCm build: default = ["rocm"] everywhere. The deviceless build, which is what CI runs, is --no-default-features.

Commands

git clone https://github.com/Constructive-Programming/rivoli
cd rivoli

# Deviceless tests (safe anywhere, what CI runs)
cargo test --workspace --no-default-features

# Full battery, host and device. Device suites must run single-threaded.
cargo test --workspace -- --test-threads=1

# Release build: for benchmarks and performance work only
cargo build --release

A run that is not timing something should use the dev profile: release builds compile out every debug_assert!.

Running

# Decode 64 tokens and print the text plus a DECODE timing line
rivoli /path/to/artifact --bench 64

# Serve an OpenAI-compatible API (/v1/models, chat completions, SSE streaming)
rivoli /path/to/artifact --port 8080

Artifacts are built from Hugging Face checkpoints with the per-model convert_* binaries.

References

Constructive

Constructive is the consultancy behind rivoli. It works with platform teams on type-driven architecture: fewer representable states, fewer bugs, and claims that are backed by a check that can fail.

It offers architecture reviews, embedded senior engineers in Scala, Rust and TypeScript, agent-native development workflows, and workshops.

rivoli makes the same argument the consultancy makes in its engagements. Put the rules in the types and the crate graph, and whole classes of wrong programs stop compiling. Then prove every remaining claim with a gate that has been seen to go red.

Sister projects

Assumptions and limits

rivoli’s guarantees hold on the machine it is designed for, under the conditions below. Outside them a run may be refused, slower, or not reproducible. It should never be silently wrong.

The machine

  • Unified memory. The GPU reads system RAM directly through ROCm. A discrete GPU with its own VRAM is not a target: the design has no host-to-device copy to hide.
  • ROCm and HIP. There is one backend. Other vendors and APIs are out of scope by choice (P3).
  • Fast local NVMe. Streamed weights are read from local NVMe. An artifact on a network filesystem works, but its speed figures are not meaningful.

Memory

  • The budget is measured at run time. What is resident follows from free memory when the run starts: other tenants, the KV cache at the configured context, and scratch.
  • Below the floor, the run is refused. If the budget cannot hold the minimum working set, rivoli refuses with the arithmetic rather than degrading.
  • Other GPU tenants change the numbers. A second process using GPU memory shrinks the pin, and speed measurements taken while it runs are discarded.

Output

  • The memory knob does not change text. --max-mem and cache policy move speed only (P4). Where a format is chosen by residency, that is called out as a defect, not a feature.
  • Not every configuration is bit-reproducible. Some streaming arms vary slightly between runs of the same input. Quality comparisons measure that noise floor first, and differences below it are not reported.
  • Parity means greedy decoding. “Token-identical to the reference” is checked with greedy sampling on a pinned prompt, for a stated number of tokens.

Models

  • The artifact decides. Each model is converted once into a rivoli artifact, which names its architecture. Flags that the architecture does not support are refused at startup with the reason.
  • Text only. Vision towers and multi-token-prediction heads are not run, even when the checkpoint includes them.

Bibliography

The papers, formats and evidence behind rivoli’s design. Each entry gives the authors, the title, the venue and year, and a note on why it matters here.

Offloading and streaming

Caching and the cost model

Mixture of experts and attention

Number formats and quantization

Decoding

Measurement

Repository evidence

  • Principles: P1 to P7 as confirmed by the owner.
  • Architecture: the crate layering, the residency contract and the invariant registry.
  • Kernel inventory: every device kernel and its launcher.
  • How to measure: the measurement rules every cited number follows.
  • Gate red proofs: the recorded runs in which each gate was shown to fail.
  • Docs index: every investigation with its status and verdict.