AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
Expert Ribbon P1: page OWN-30B experts from the SSD with identical output
closed f526b89d3cb4a9a3 #660 · opened 2026-10-18 17:27 UTC · closed 2026-10-29 19:00 UTC
Imported from GitHub aien-dev/aien-sovereign-core-mv#660, by drakestapleton
Base 753e60d3c3ff4f2f636b274872dbf299ca23b74d · Head 836a53446d3674e86cbfc435d814775a0b8503a8
drakestapleton wrote on 2026-10-18 17:27 UTC
Refs aienix#4, #629, #632. Stacked on #634 (feat/heartbeat-ring).
What
Expert store and paged load for OWN-30B: GPU expert slots (omega ribbon/slots-on-4799f9eb 1549caae via omega.lock), experts fetched from NVMe with a fingerprint check on every read (+4130/-123, 34 files).
Evidence (worker report, 2026-10-18)
cargo test -p aien-heartbeat: 16 + 12 + 8 passed. cargo test -p aien-inference-abi --lib ribbon: 2 passed; paged logits equal the all-in-memory run bit for bit on the small test model for 3 pool sizes and both routing modes; a corrupted expert load is caught; a pool under 8 experts fails cleanly with nothing pinned.
Chip: docs/inference/evidence/ribbon-paged-20261018T1719Z. Identical output on 2 prompts at 1/8 resident, 4 prompts at 1/2 resident.
SSD random whole-expert reads: 1.32 GB/s (1 reader, calc:b43572b8 ), 8.69 GB/s (8, calc:84b90d97 ), 10.60 GB/s (16, calc:8d297d5b ) = 0.673 of the link (calc:cf3a961c ).
Decode: 2.396 words/s cold at 1/8 resident (calc:eac8a69d ), 2.738 cold at 1/2 (calc:440646a6 ), 7.07 warm at 1/2 with 96% hits (calc:59123200 ). All-from-SSD ceiling 5.849 words/s (calc:1fc0715c ). Bottleneck: per-layer fetch waits (SSD at 1.715 of 10.60 GB/s during misses, calc:ff9762d7 ); read-ahead is sc#631.
Not tested / limits
All-in-memory speed under today's load (the 70 GB safety check refused to share the machine with the live server).
native-artifacts.lock has no fingerprint line for omega 1549caae yet (builds warn unrecorded until an abi-qualify run).
Router placeholder entries in paged mode (part 3 fixes).
Merge order
Draft until #634 is clean and merged; .crumb files not yet recompiled (desk does it at rebase).
🤖 Generated with Claude Code
drakestapleton wrote on 2026-10-29 19:00 UTC
Closing in org cleanup (Drake, 2026-10-29): abandoned; no activity in 11 days and merge conflicts with base. Reopen if still needed.
Apply it
git checkout -b patch-f526b89d3cb4a9a3 753e60d3c3ff4f2f636b274872dbf299ca23b74d
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/f526b89d3cb4a9a3 .patch | git am
Raw patch (mbox) · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aien-sovereign-core-mv
660
836a53446d3674e86cbfc435d814775a0b8503a8
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":660,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/660","export_sha256":"d815604dc795b494a931d4c9d256159461266bed51d6da460421ed1d94dab90f ","imported_utc":"2026-11-18T16:35:49Z"}
Changes
diff --git a/Cargo.lock b/Cargo.lock
index 3e29fdb0 ..2a52fe3c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -182,6 +182,7 @@ name = "aien-inference-abi"
version = "0.1.0"
dependencies = [
"aien-abi-core",
+ "aien-heartbeat",
"aien-kv-cache",
"aien-omega-bf16",
"aien-omega-dattn",
diff --git a/crates/aien-heartbeat/Cargo.toml b/crates/aien-heartbeat/Cargo.toml
index afaf12ac ..7b62ed96 100644
--- a/crates/aien-heartbeat/Cargo.toml
+++ b/crates/aien-heartbeat/Cargo.toml
@@ -16,3 +16,7 @@ serde_json = "1.0"
[[bin]]
name = "heartbeat_bench"
path = "src/bin/heartbeat_bench.rs"
+
+[[bin]]
+name = "ribbon_read_bench"
+path = "src/bin/ribbon_read_bench.rs"
diff --git a/crates/aien-heartbeat/README.md b/crates/aien-heartbeat/README.md
index 742b6ba7 ..9744b71f 100644
--- a/crates/aien-heartbeat/README.md
+++ b/crates/aien-heartbeat/README.md
@@ -31,9 +31,36 @@ One rotation = 6,144 experts, 28,994,568,192 payload bytes. 3 rotations per row,
- Digest cost: BLAKE3 runs at 1.50 GB/s per worker core (calc:ec3efd8e ), about 58 worker-seconds per 3 rotations. With 16 workers the verified beat is 8.7% longer than the raw beat (calc:d216067c ).
- io_uring was not built or measured. The `pread` pool reaches 11.26 GB/s raw; whether a raw io_uring path closes the remaining gap to the link ceiling is NOT MEASURED and is the next comparison to run.
+## Expert Ribbon: on-demand paging (sc#629, sc#630, sc#632)
+
+The ring above streams every expert in a fixed rhythm. The Ribbon path reads only the experts the router picks:
+
+- **Layout** (`layout.rs`): checks each expert's six tensors (names, dtypes, shapes, lengths) against the model shape and splits a verified payload into what a GPU slot takes: gate|up `[2i][h]` e4m3 + bf16 scales, down `[h][i]` + scales.
+- **Read adapter** (`reader.rs`): a bounded queue of `O_DIRECT` reads into a fixed pool of aligned buffers, BLAKE3-checked before a caller sees a byte. Full queue, I/O error, short read, digest mismatch, deadline, cancel and shutdown are distinct errors; nothing waits forever. `FakeShards` injects faults for tests.
+- **Residency** (`residency.rs`): which expert sits in which slot, pins, LRU eviction of unpinned slots only, and a memory budget check.
+- **Pager** (`pager.rs`): `ensure(layer, experts)` pins exactly the router's experts in router order; misses are read and loaded in parallel; any failure releases everything and fails the call. Nothing is substituted.
+- The GPU side is omega's versioned slot pool (`omega_gpu_fp8_slots`, omega#533) and the engine path is `ExpertWeights::Paged` in `aien-inference-abi` (`qwen3_moe_omega/ribbon.rs`).
+
+Random verified expert reads through the adapter (`ribbon_read_bench`, 3,000 reads, 4,719,168 payload bytes each, real checkpoint):
+
+| Workers | Queue depth | Payload GB/s | Receipt |
+|---|---|---|---|
+| 1 | 1 | 1.32 | calc:b43572b8 |
+| 8 | 16 | 8.69 | calc:84b90d97 |
+| 16 | 32 | 10.60 | calc:8d297d5b |
+
+At depth 32 random single-expert reads reach 0.673 of the PCIe Gen5 x4 link (calc:cf3a961c ), about the same as the sequential verified beat.
+
+OWN-30B on the GB10 with paged experts (evidence `docs/inference/evidence/ribbon-paged-20261018T1719Z`): greedy tokens IDENTICAL to the CPU golden with 768 slots (1/8 of the experts, prompts 1-2) and 3072 slots (1/2, prompts 1-4), 1.53 GB of other weights resident. Decode 2.396 tok/s cold at 768 slots (calc:eac8a69d ) and 7.07 tok/s warm at 3072 slots (calc:59123200 ); the all-miss ceiling at the measured read rate is 5.849 tok/s (calc:1fc0715c ). Paging is bound by per-layer read latency, not SSD bandwidth (1.715 GB/s delivered during misses, calc:ff9762d7 ); overlap and prefetch (sc#631) are next.
+
+```
+target/release/ribbon_read_bench --model ~/models/qwen3-30b-a3b-instruct-2507-fp8 --reads 3000 --workers 16 --depth 32
+own30b_check chip <ckpt> <golden.json> <dir> --tokens-only --weights fp8 --router device --paged-experts 768
+```
+
## Limits
-- No GPU visibility fence. On the GB10 unified memory a slot still needs an explicit fence before a kernel may read it; that is H2 work (with station queues and the batched expert GEMM).
+- The ring (H1) has no GPU fence of its own; the Ribbon path loads into omega's slot pool, which publishes a version only after the platform sync and refuses to reload a slot a launch has pinned.
- Linux-hosted only; native AIENOS NVMe is a separate qualification.
- Digest runs on the worker after its read, not overlapped inside a worker.
- Bench uses no concurrent readers; lease waits are exercised by the tests.
diff --git a/crates/aien-heartbeat/src/bin/ribbon_read_bench.rs b/crates/aien-heartbeat/src/bin/ribbon_read_bench.rs
new file mode 100644
index 00000000 ..0f1bf844
--- /dev/null
+++ b/crates/aien-heartbeat/src/bin/ribbon_read_bench.rs
@@ -0,0 +1,112 @@
+//! Expert Ribbon P1 (sc#629) read receipt: random verified expert reads through the bounded read adapter
+//! from the real checkpoint on the NVMe. Read-only on the model; no GPU.
+//!
+//! ribbon_read_bench --model DIR [--manifest PATH] [--reads N] [--workers W] [--depth D] [--buffered] [--seed S]
+//!
+//! Each read = one whole expert (all six tensors, the two aligned segments), BLAKE3-verified before it counts.
+//! Keeps `depth` reads in flight. Prints one JSON summary: payload GB/s, device GB/s, latency mean/p50/p95/max.
+//! --buffered reads through the page cache: a warm cache makes it a memory copy, not an SSD figure.
+
+use std::collections::VecDeque;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use aien_heartbeat::{FileShards, Manifest, ReadAdapter, ReadConfig};
+
+fn arg<T: std::str::FromStr>(args: &[String], name: &str, default: T) -> T {
+ args.iter()
+ .position(|a| a == name)
+ .and_then(|i| args.get(i + 1))
+ .map(|v| v.parse().unwrap_or_else(|_| panic!("bad value for {name}")))
+ .unwrap_or(default)
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let model: PathBuf = arg(&args, "--model", PathBuf::from("."));
+ let manifest_path: PathBuf = arg(
+ &args,
+ "--manifest",
+ std::env::temp_dir().join("aien-ribbon-manifest.json"),
+ );
+ let reads: usize = arg(&args, "--reads", 2000);
+ let workers: usize = arg(&args, "--workers", 8);
+ let depth: usize = arg(&args, "--depth", 16);
+ let seed: u64 = arg(&args, "--seed", 2026);
+ let direct = !args.iter().any(|a| a == "--buffered");
+
+ let m = match Manifest::load(&manifest_path) {
+ Ok(m) if m.model_dir == model => m,
+ _ => {
+ let t = Instant::now();
+ let m = Manifest::build(&model).expect("manifest");
+ m.save(&manifest_path).expect("save manifest");
+ eprintln!(
+ "manifest built in {:.1} s ({} experts, model digest {})",
+ t.elapsed().as_secs_f64(),
+ m.experts.len(),
+ m.model_digest
+ );
+ m
+ }
+ };
+ let m = Arc::new(m);
+ let dev = Arc::new(FileShards::open(&m.shard_paths(), direct).expect("open shards"));
+ let r = ReadAdapter::new(
+ m.clone(),
+ dev,
+ ReadConfig {
+ workers,
+ queue_depth: depth,
+ },
+ );
+
+ let mut s = seed;
+ let mut next = || {
+ s = s
+ .wrapping_mul(6364136223846793005 )
+ .wrapping_add(1442695040888963407 );
+ (s >> 33) as usize % m.experts.len()
+ };
+ let mut lat: Vec<f64> = Vec::with_capacity(reads);
+ let mut inflight = VecDeque::new();
+ let mut payload = 0u64;
+ let t0 = Instant::now();
+ let mut submitted = 0usize;
+ while lat.len() < reads {
+ while submitted < reads && inflight.len() < depth {
+ let i = next();
+ inflight.push_back((Instant::now(), r.submit(i).expect("submit")));
+ submitted += 1;
+ }
+ let (ts, t) = inflight.pop_front().expect("in flight");
+ let v = t.wait(Duration::from_secs(30)).expect("verified read");
+ payload += v.payload().len() as u64;
+ lat.push(ts.elapsed().as_secs_f64() * 1e3);
+ }
+ let wall = t0.elapsed().as_secs_f64();
+ let st = r.stats();
+ lat.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ let pct = |p: f64| lat[((lat.len() as f64 * p) as usize).min(lat.len() - 1)];
+ println!(
+ "{}",
+ serde_json::json!({
+ "tool": "ribbon_read_bench",
+ "model_digest": m.model_digest,
+ "direct": direct,
+ "workers": workers,
+ "depth": depth,
+ "reads": reads,
+ "seed": seed,
+ "payload_bytes": payload,
+ "device_bytes": st.device_bytes,
+ "wall_s": wall,
+ "payload_GBps": payload as f64 / wall / 1e9,
+ "device_GBps": st.device_bytes as f64 / wall / 1e9,
+ "read_worker_s": st.read_ns as f64 / 1e9,
+ "digest_worker_s": st.digest_ns as f64 / 1e9,
+ "latency_ms": {"mean": lat.iter().sum::<f64>() / lat.len() as f64, "p50": pct(0.5), "p95": pct(0.95), "max": lat[lat.len() - 1]},
+ })
+ );
+}
diff --git a/crates/aien-heartbeat/src/layout.rs b/crates/aien-heartbeat/src/layout.rs
new file mode 100644
index 00000000 ..b78de54a
--- /dev/null
+++ b/crates/aien-heartbeat/src/layout.rs
@@ -0,0 +1,205 @@
+//! Qwen3-MoE FP8 expert layout (Expert Ribbon P1, sc#629): which bytes of a verified expert payload are the
+//! gate|up and down projections and their block-128 scales, checked against the model shape before any byte
+//! is handed to a GPU slot.
+//!
+//! A payload is the expert's six tensors in file order (manifest [`crate::manifest::TensorRange`] offsets).
+//! The chip wants, per expert, exactly what the resident loader uploads (`qwen3_moe_omega.rs`):
+//! * gate|up weights `[2i][h]` e4m3 = `gate_proj.weight [i][h]` then `up_proj.weight [i][h]`, scales
+//! `[2i/128][h/128]` bf16 = gate scales then up scales;
+//! * down weights `[h][i]` e4m3, scales `[h/128][i/128]` bf16.
+//!
+//! Gate and up are adjacent in the checkpoint (safetensors orders tensors by name within a dtype), so the
+//! gate|up weights are normally one borrowed slice; when they are not adjacent they are copied, never assumed.
+
+use std::borrow::Cow;
+
+use crate::error::HeartbeatError;
+use crate::manifest::{ExpertEntry, TensorRange};
+
+/// Quantisation format name recorded with every expert identity.
+pub const FORMAT_FP8_BLOCK128: &str = "qwen3-fp8-e4m3/bf16-scale-inv/block128";
+pub const FP8_BLOCK: u64 = 128;
+
+/// Model dimensions the layout is checked against (config.json `hidden_size`, `moe_intermediate_size`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ExpertShape {
+ pub hidden: u64,
+ pub inter: u64,
+}
+
+impl ExpertShape {
+ pub fn gate_up_weight_bytes(&self) -> usize {
+ (2 * self.inter * self.hidden) as usize
+ }
+ pub fn down_weight_bytes(&self) -> usize {
+ (self.hidden * self.inter) as usize
+ }
+ pub fn gate_up_scales(&self) -> usize {
+ (2 * (self.inter / FP8_BLOCK) * (self.hidden / FP8_BLOCK)) as usize
+ }
+ pub fn down_scales(&self) -> usize {
+ ((self.hidden / FP8_BLOCK) * (self.inter / FP8_BLOCK)) as usize
+ }
+}
+
+/// Payload ranges `(offset, len)` of the six tensors of one expert, validated.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExpertLayout {
+ pub gate_w: (u64, u64),
+ pub up_w: (u64, u64),
+ pub down_w: (u64, u64),
+ pub gate_s: (u64, u64),
+ pub up_s: (u64, u64),
+ pub down_s: (u64, u64),
+}
+
+fn find<'a>(e: &'a ExpertEntry, suffix: &str) -> Result<&'a TensorRange, HeartbeatError> {
+ let want = format!("model.layers.{}.mlp.experts.{}.{suffix}", e.layer, e.expert);
+ let mut hits = e.tensors.iter().filter(|t| t.name == want);
+ let t = hits.next().ok_or_else(|| {
+ HeartbeatError::Manifest(format!("expert ({},{}): missing {want}", e.layer, e.expert))
+ })?;
+ if hits.next().is_some() {
+ return Err(HeartbeatError::Manifest(format!(
+ "expert ({},{}): duplicate {want}",
+ e.layer, e.expert
+ )));
+ }
+ Ok(t)
+}
+
+fn check(
+ t: &TensorRange,
+ dtype: &str,
+ shape: [u64; 2],
+ elem: u64,
+) -> Result<(u64, u64), HeartbeatError> {
+ if t.dtype != dtype || t.shape != shape || t.len != shape[0] * shape[1] * elem {
+ return Err(HeartbeatError::Manifest(format!(
+ "{}: dtype {} shape {:?} len {} (want {dtype} {shape:?} len {})",
+ t.name,
+ t.dtype,
+ t.shape,
+ t.len,
+ shape[0] * shape[1] * elem
+ )));
+ }
+ Ok((t.offset, t.len))
+}
+
+impl ExpertLayout {
+ /// Validates the six tensors of `e` (names, dtypes, shapes, lengths; no extra tensors) for `shape`.
+ pub fn for_entry(e: &ExpertEntry, shape: ExpertShape) -> Result<Self, HeartbeatError> {
+ let (h, i) = (shape.hidden, shape.inter);
+ if h % FP8_BLOCK != 0 || i % FP8_BLOCK != 0 {
+ return Err(HeartbeatError::Manifest(format!(
+ "shape {h}x{i} is not block-128"
+ )));
+ }
+ if e.tensors.len() != 6 {
+ return Err(HeartbeatError::Manifest(format!(
+ "expert ({},{}): {} tensors, want 6",
+ e.layer,
+ e.expert,
+ e.tensors.len()
+ )));
+ }
+ let (hb, ib) = (h / FP8_BLOCK, i / FP8_BLOCK);
+ let l = Self {
+ gate_w: check(find(e, "gate_proj.weight")?, "F8_E4M3", [i, h], 1)?,
+ up_w: check(find(e, "up_proj.weight")?, "F8_E4M3", [i, h], 1)?,
+ down_w: check(find(e, "down_proj.weight")?, "F8_E4M3", [h, i], 1)?,
+ gate_s: check(find(e, "gate_proj.weight_scale_inv")?, "BF16", [ib, hb], 2)?,
+ up_s: check(find(e, "up_proj.weight_scale_inv")?, "BF16", [ib, hb], 2)?,
+ down_s: check(find(e, "down_proj.weight_scale_inv")?, "BF16", [hb, ib], 2)?,
+ };
+ let end = e.len;
+ for (o, n) in [l.gate_w, l.up_w, l.down_w, l.gate_s, l.up_s, l.down_s] {
+ if o + n > end {
+ return Err(HeartbeatError::Manifest(format!(
+ "expert ({},{}): tensor past payload end",
+ e.layer, e.expert
+ )));
+ }
+ }
+ Ok(l)
+ }
+}
+
+/// An expert payload as its segments in order (a ring lease, or a read adapter result).
+pub struct Payload<'a> {
+ segs: Vec<&'a [u8]>,
+}
+
+impl<'a> Payload<'a> {
+ pub fn new(segs: Vec<&'a [u8]>) -> Self {
+ Self { segs }
+ }
+
+ pub fn len(&self) -> usize {
+ self.segs.iter().map(|s| s.len()).sum()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ /// `len` bytes at payload offset `off`, borrowed when they lie in one segment.
+ pub fn bytes(&self, off: u64, len: u64) -> Result<Cow<'a, [u8]>, HeartbeatError> {
+ let (off, len) = (off as usize, len as usize);
+ if off.checked_add(len).is_none_or(|end| end > self.len()) {
+ return Err(HeartbeatError::Manifest(format!(
+ "payload range {off}+{len} past the {}-byte payload",
+ self.len()
+ )));
+ }
+ let mut base = 0usize;
+ for s in &self.segs {
+ if off >= base && off + len <= base + s.len() {
+ return Ok(Cow::Borrowed(&s[off - base..off - base + len]));
+ }
+ base += s.len();
+ }
+ // Straddles a segment boundary (never for whole tensors, but correct anyway): copy.
+ let flat: Vec<u8> = self.segs.iter().flat_map(|s| s.iter().copied()).collect();
+ Ok(Cow::Owned(flat[off..off + len].to_vec()))
+ }
+}
+
+/// What a GPU slot pair is loaded from: gate|up and down weights (e4m3) and scales (bf16 bits).
+#[derive(Debug)]
+pub struct ExpertParts<'a> {
+ pub gate_up_w: Cow<'a, [u8]>,
+ pub gate_up_s: Vec<u16>,
+ pub down_w: Cow<'a, [u8]>,
+ pub down_s: Vec<u16>,
+}
+
+fn bf16_words(b: &[u8]) -> Vec<u16> {
+ b.as_chunks::<2>()
+ .0
+ .iter()
+ .map(|c| u16::from_le_bytes(*c))
+ .collect()
+}
+
+impl ExpertLayout {
+ /// Splits a verified payload into the chip layout.
+ pub fn parts<'a>(&self, p: &Payload<'a>) -> Result<ExpertParts<'a>, HeartbeatError> {
+ let gate_up_w = if self.up_w.0 == self.gate_w.0 + self.gate_w.1 {
+ p.bytes(self.gate_w.0, self.gate_w.1 + self.up_w.1)?
+ } else {
+ let mut v = p.bytes(self.gate_w.0, self.gate_w.1)?.into_owned();
+ v.extend_from_slice(&p.bytes(self.up_w.0, self.up_w.1)?);
+ Cow::Owned(v)
+ };
+ let mut gate_up_s = bf16_words(&p.bytes(self.gate_s.0, self.gate_s.1)?);
+ gate_up_s.extend(bf16_words(&p.bytes(self.up_s.0, self.up_s.1)?));
+ Ok(ExpertParts {
+ gate_up_w,
+ gate_up_s,
+ down_w: p.bytes(self.down_w.0, self.down_w.1)?,
+ down_s: bf16_words(&p.bytes(self.down_s.0, self.down_s.1)?),
+ })
+ }
+}
diff --git a/crates/aien-heartbeat/src/lib.rs b/crates/aien-heartbeat/src/lib.rs
index 0f1905a3 ..0cbb3046 100644
--- a/crates/aien-heartbeat/src/lib.rs
+++ b/crates/aien-heartbeat/src/lib.rs
@@ -12,12 +12,22 @@
pub mod aligned;
pub mod error;
+pub mod layout;
pub mod manifest;
+pub mod pager;
+pub mod reader;
+pub mod residency;
pub mod ring;
pub mod stream;
pub use error::HeartbeatError;
+pub use layout::{ExpertLayout, ExpertParts, ExpertShape, Payload};
pub use manifest::{ExpertEntry, Manifest};
+pub use pager::{ExpertPager, PagerError, PagerStats, Pinned, SlotBackend};
+pub use reader::{
+ FakeShards, Fault, FileShards, ReadAdapter, ReadConfig, ReadError, ShardDevice, VerifiedExpert,
+};
+pub use residency::{Acquire, ExpertId, MemoryBudget, Residency, ResidencyStats, SlotVersion};
pub use ring::{Lease, Ring, SlotTag};
pub use stream::{RotationStats, Schedule, StreamConfig, Streamer};
diff --git a/crates/aien-heartbeat/src/manifest.rs b/crates/aien-heartbeat/src/manifest.rs
index 98eca08f ..e80d1951 100644
--- a/crates/aien-heartbeat/src/manifest.rs
+++ b/crates/aien-heartbeat/src/manifest.rs
@@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
use crate::error::HeartbeatError;
-pub const MANIFEST_SCHEMA: &str = "aien-heartbeat-manifest/1";
+pub const MANIFEST_SCHEMA: &str = "aien-heartbeat-manifest/2";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TensorRange {
@@ -59,6 +59,10 @@ impl ExpertEntry {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Manifest {
pub schema: String,
+ /// BLAKE3 over the index file, every expert shard's name and header bytes, and every expert's
+ /// `(layer, expert, digest)` in order: names the checkpoint by content, not by path. The per-expert
+ /// digests cover the weight bytes themselves, so this is not an index-only digest (sc#338).
+ pub model_digest: String,
pub model_dir: PathBuf,
pub shards: Vec<String>,
pub num_layers: u16,
@@ -92,7 +96,10 @@ fn parse_expert_name(name: &str) -> Option<(u16, u16)> {
}
/// Read a safetensors header: returns (data section start, tensors).
-fn read_header(path: &Path) -> Result<(u64, BTreeMap<String, serde_json::Value>), HeartbeatError> {
+#[allow(clippy::type_complexity)]
+fn read_header(
+ path: &Path,
+) -> Result<(u64, BTreeMap<String, serde_json::Value>, Vec<u8>), HeartbeatError> {
let f = File::open(path).map_err(|e| HeartbeatError::io(path.display().to_string(), e))?;
let mut lenb = [0u8; 8];
f.read_exact_at(&mut lenb, 0)
@@ -108,7 +115,7 @@ fn read_header(path: &Path) -> Result<(u64, BTreeMap<String, serde_json::Value>)
.map_err(|e| HeartbeatError::io("header", e))?;
let map: BTreeMap<String, serde_json::Value> = serde_json::from_slice(&h)
.map_err(|e| HeartbeatError::Manifest(format!("header json: {e}")))?;
- Ok((8 + hlen, map))
+ Ok((8 + hlen, map, h))
}
impl Manifest {
@@ -116,11 +123,14 @@ impl Manifest {
/// expert span once to compute its digest. Read-only on the model.
pub fn build(model_dir: &Path) -> Result<Self, HeartbeatError> {
let idx_path = model_dir.join("model.safetensors.index.json");
- let idx: Index = serde_json::from_slice(
- &std::fs::read(&idx_path).map_err(|e| HeartbeatError::io("index", e))?,
- )
- .map_err(|e| HeartbeatError::Manifest(format!("index json: {e}")))?;
+ let idx_bytes = std::fs::read(&idx_path).map_err(|e| HeartbeatError::io("index", e))?;
+ let idx: Index = serde_json::from_slice(&idx_bytes)
+ .map_err(|e| HeartbeatError::Manifest(format!("index json: {e}")))?;
+ let mut model_h = blake3::Hasher::new();
+ model_h.update(b"aien-heartbeat-model/1\0");
+ model_h.update(&(idx_bytes.len() as u64).to_le_bytes());
+ model_h.update(&idx_bytes);
let mut shards: Vec<String> = Vec::new();
for (name, shard) in &idx.weight_map {
if parse_expert_name(name).is_some() && !shards.contains(shard) {
@@ -132,7 +142,11 @@ impl Manifest {
// (layer, expert) -> tensors (shard, name, dtype, shape, abs offset, len)
let mut groups: BTreeMap<(u16, u16), Vec<(u32, RawTensor)>> = BTreeMap::new();
for (si, shard) in shards.iter().enumerate() {
- let (data_start, header) = read_header(&model_dir.join(shard))?;
+ let (data_start, header, raw_header) = read_header(&model_dir.join(shard))?;
+ model_h.update(&(shard.len() as u64).to_le_bytes());
+ model_h.update(shard.as_bytes());
+ model_h.update(&(raw_header.len() as u64).to_le_bytes());
+ model_h.update(&raw_header);
for (name, v) in header {
let Some(key) = parse_expert_name(&name) else {
continue;
@@ -197,6 +211,9 @@ impl Manifest {
h.update(&buf);
}
let digest = h.finalize().to_hex().to_string();
+ model_h.update(&layer.to_le_bytes());
+ model_h.update(&expert.to_le_bytes());
+ model_h.update(digest.as_bytes());
experts.push(ExpertEntry {
layer,
expert,
@@ -216,6 +233,7 @@ impl Manifest {
}
Ok(Self {
schema: MANIFEST_SCHEMA.into(),
+ model_digest: model_h.finalize().to_hex().to_string(),
model_dir: model_dir.to_path_buf(),
shards,
num_layers,
diff --git a/crates/aien-heartbeat/src/pager.rs b/crates/aien-heartbeat/src/pager.rs
new file mode 100644
index 00000000 ..24ccbd72
--- /dev/null
+++ b/crates/aien-heartbeat/src/pager.rs
@@ -0,0 +1,302 @@
+//! Expert pager (Expert Ribbon P2, sc#630/#632): turns the router's exact top-k for one layer into pinned,
+//! resident GPU slots. Hits pin; misses read the expert from the checkpoint (bounded, digest-verified
+//! [`ReadAdapter`]), split it into the chip layout and load it into a slot pair through a [`SlotBackend`].
+//! Misses of one layer are read and loaded in parallel (each on its own thread; the read adapter bounds how
+//! many reads are in the kernel at once).
+//!
+//! Exactness: the experts returned are exactly the ones asked for, in the same order. A miss that cannot be
+//! served (read error, digest mismatch, every slot pinned) is an error; nothing is substituted or skipped.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::{Duration, Instant};
+
+use crate::layout::{ExpertLayout, ExpertParts, ExpertShape};
+use crate::manifest::Manifest;
+use crate::reader::{ReadAdapter, ReadError};
+use crate::residency::{Acquire, ExpertId, Residency, ResidencyStats, SlotVersion};
+
+/// The GPU side of a slot pair. The real one wraps two omega_gpu_fp8_slots pools (gate|up and down);
+/// tests use a host fake. Must be callable from several threads at once (one load per slot at a time).
+pub trait SlotBackend: Send + Sync {
+ fn slots(&self) -> usize;
+ /// Load `parts` into slot pair `slot`, returning the published versions. Refused (error) if the slot is
+ /// still read by a launch: the residency manager never asks for that, so a refusal is a bug, fail closed.
+ fn load(&self, slot: u32, id: ExpertId, parts: &ExpertParts<'_>)
+ -> Result<SlotVersion, String>;
+}
+
+#[derive(Debug)]
+pub enum PagerError {
+ Read {
+ id: ExpertId,
+ err: ReadError,
+ },
+ Layout(String),
+ Backend {
+ id: ExpertId,
+ err: String,
+ },
+ /// Every slot is pinned or being fetched: the capacity is too small for this request.
+ Exhausted {
+ id: ExpertId,
+ capacity: usize,
+ },
+ UnknownExpert(ExpertId),
+}
+
+impl std::fmt::Display for PagerError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Read { id, err } => write!(f, "expert {id:?}: read failed: {err}"),
+ Self::Layout(s) => write!(f, "expert layout: {s}"),
+ Self::Backend { id, err } => write!(f, "expert {id:?}: slot load failed: {err}"),
+ Self::Exhausted { id, capacity } => write!(
+ f,
+ "expert {id:?}: all {capacity} slots are pinned or loading (capacity too small for one request)"
+ ),
+ Self::UnknownExpert(id) => write!(f, "expert {id:?} is not in the manifest"),
+ }
+ }
+}
+impl std::error::Error for PagerError {}
+
+#[derive(Debug, Clone, Default)]
+pub struct PagerStats {
+ pub requests: u64,
+ pub experts_hit: u64,
+ pub experts_missed: u64,
+ pub bytes_loaded: u64,
+ /// Wall time inside `ensure` spent on misses (read + verify + slot load), summed per call.
+ pub miss_wall_ns: u64,
+ /// Summed over miss threads: waiting for the verified read, and loading the slot pair.
+ pub read_wait_ns: u64,
+ pub slot_load_ns: u64,
+}
+
+/// Slots pinned for one layer's launch, in the order the router gave the experts.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Pinned {
+ pub slots: Vec<u32>,
+ pub versions: Vec<SlotVersion>,
+}
+
+pub struct ExpertPager {
+ manifest: Arc<Manifest>,
+ layouts: Vec<ExpertLayout>,
+ index_of: HashMap<ExpertId, usize>,
+ reader: ReadAdapter,
+ backend: Arc<dyn SlotBackend>,
+ res: Mutex<Residency>,
+ fetch_done: Condvar,
+ stats: Mutex<PagerStats>,
+ read_deadline: Duration,
+}
+
+impl ExpertPager {
+ /// Validates every expert's layout against `shape` up front (a format mismatch fails here, not mid-run).
+ pub fn new(
+ manifest: Arc<Manifest>,
+ shape: ExpertShape,
+ reader: ReadAdapter,
+ backend: Arc<dyn SlotBackend>,
+ read_deadline: Duration,
+ ) -> Result<Self, PagerError> {
+ let layouts = manifest
+ .experts
+ .iter()
+ .map(|e| ExpertLayout::for_entry(e, shape))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| PagerError::Layout(e.to_string()))?;
+ let index_of = manifest
+ .experts
+ .iter()
+ .enumerate()
+ .map(|(i, e)| ((e.layer, e.expert), i))
+ .collect();
+ let slots = backend.slots();
+ Ok(Self {
+ manifest,
+ layouts,
+ index_of,
+ reader,
+ backend,
+ res: Mutex::new(Residency::new(slots)),
+ fetch_done: Condvar::new(),
+ stats: Mutex::new(PagerStats::default()),
+ read_deadline,
+ })
+ }
+
+ pub fn manifest(&self) -> &Manifest {
+ &self.manifest
+ }
+ pub fn capacity(&self) -> usize {
+ self.res.lock().unwrap().capacity()
+ }
+ pub fn resident(&self) -> usize {
+ self.res.lock().unwrap().resident()
+ }
+ pub fn stats(&self) -> PagerStats {
+ self.stats.lock().unwrap().clone()
+ }
+ pub fn residency_stats(&self) -> ResidencyStats {
+ self.res.lock().unwrap().stats()
+ }
+ pub fn read_stats(&self) -> crate::reader::ReadStats {
+ self.reader.stats()
+ }
+ pub fn pinned(&self) -> u32 {
+ self.res.lock().unwrap().pinned()
+ }
+
+ /// Pins exactly `experts` of `layer` (router order). On error nothing stays pinned.
+ pub fn ensure(&self, layer: u16, experts: &[u16]) -> Result<Pinned, PagerError> {
+ let mut out: Vec<Option<(u32, SlotVersion)>> = vec![None; experts.len()];
+ let mut fetch: Vec<(usize, u32, ExpertId)> = Vec::new(); // (position, slot, id)
+ {
+ let mut r = self.res.lock().unwrap();
+ for (pos, &ex) in experts.iter().enumerate() {
+ let id = (layer, ex);
+ if !self.index_of.contains_key(&id) {
+ self.undo(&mut r, &out, &fetch);
+ return Err(PagerError::UnknownExpert(id));
+ }
+ loop {
+ match r.acquire(id) {
+ Acquire::Hit { slot, ver } => {
+ out[pos] = Some((slot, ver));
+ break;
+ }
+ Acquire::Fetch { slot, .. } => {
+ fetch.push((pos, slot, id));
+ break;
+ }
+ Acquire::Pending => {
+ r = self.fetch_done.wait(r).unwrap();
+ }
+ Acquire::Exhausted => {
+ let capacity = r.capacity();
+ self.undo(&mut r, &out, &fetch);
+ return Err(PagerError::Exhausted { id, capacity });
+ }
+ }
+ }
+ }
+ }
+ let hits = (experts.len() - fetch.len()) as u64;
+ let t0 = Instant::now();
+ let results: Vec<Result<(SlotVersion, u64, u64, u64), PagerError>> = if fetch.is_empty() {
+ Vec::new()
+ } else {
+ std::thread::scope(|sc| {
+ let hs: Vec<_> = fetch
+ .iter()
+ .map(|&(_, slot, id)| sc.spawn(move || self.fetch_one(slot, id)))
+ .collect();
+ hs.into_iter()
+ .map(|h| {
+ h.join().unwrap_or_else(|_| {
+ Err(PagerError::Layout("miss thread panicked".into()))
+ })
+ })
+ .collect()
+ })
+ };
+ let miss_wall = t0.elapsed().as_nanos() as u64;
+ let mut first_err = None;
+ {
+ let mut r = self.res.lock().unwrap();
+ for (&(pos, slot, _), res) in fetch.iter().zip(&results) {
+ match res {
+ Ok((ver, ..)) => {
+ r.fetched(slot, *ver);
+ out[pos] = Some((slot, *ver));
+ }
+ Err(_) => r.fetch_failed(slot),
+ }
+ }
+ for res in &results {
+ if let Err(e) = res {
+ first_err.get_or_insert_with(|| format!("{e}"));
+ }
+ }
+ if first_err.is_some() {
+ for (slot, _) in out.iter().flatten() {
+ r.release(*slot);
+ }
+ }
+ }
+ self.fetch_done.notify_all();
+ let mut s = self.stats.lock().unwrap();
+ s.requests += 1;
+ s.experts_hit += hits;
+ s.experts_missed += fetch.len() as u64;
+ s.miss_wall_ns += miss_wall;
+ for (_, rw, sl, b) in results.iter().flatten() {
+ s.read_wait_ns += rw;
+ s.slot_load_ns += sl;
+ s.bytes_loaded += b;
+ }
+ drop(s);
+ if let Some(e) = results.into_iter().find_map(|r| r.err()) {
+ return Err(e);
+ }
+ let (slots, versions) = out
+ .into_iter()
+ .map(|o| o.expect("every position filled"))
+ .unzip();
+ Ok(Pinned { slots, versions })
+ }
+
+ /// Drops the pins of a finished launch.
+ pub fn release(&self, p: &Pinned) {
+ let mut r = self.res.lock().unwrap();
+ for &s in &p.slots {
+ r.release(s);
+ }
+ }
+
+ fn undo(
+ &self,
+ r: &mut Residency,
+ out: &[Option<(u32, SlotVersion)>],
+ fetch: &[(usize, u32, ExpertId)],
+ ) {
+ for (slot, _) in out.iter().flatten() {
+ r.release(*slot);
+ }
+ for &(_, slot, _) in fetch {
+ r.fetch_failed(slot);
+ }
+ }
+
+ /// Read + verify + split + slot load. Returns (version, read wait ns, slot load ns, bytes).
+ fn fetch_one(
+ &self,
+ slot: u32,
+ id: ExpertId,
+ ) -> Result<(SlotVersion, u64, u64, u64), PagerError> {
+ let idx = self.index_of[&id];
+ let t0 = Instant::now();
+ let v = self
+ .reader
+ .submit_wait(idx, self.read_deadline)
+ .and_then(|t| t.wait(self.read_deadline))
+ .map_err(|err| PagerError::Read { id, err })?;
+ let rw = t0.elapsed().as_nanos() as u64;
+ let t1 = Instant::now();
+ let payload = v.payload();
+ let parts = self.layouts[idx]
+ .parts(&payload)
+ .map_err(|e| PagerError::Layout(e.to_string()))?;
+ let bytes = (parts.gate_up_w.len()
+ + parts.down_w.len()
+ + 2 * (parts.gate_up_s.len() + parts.down_s.len())) as u64;
+ let ver = self
+ .backend
+ .load(slot, id, &parts)
+ .map_err(|err| PagerError::Backend { id, err })?;
+ Ok((ver, rw, t1.elapsed().as_nanos() as u64, bytes))
+ }
+}
diff --git a/crates/aien-heartbeat/src/reader.rs b/crates/aien-heartbeat/src/reader.rs
new file mode 100644
index 00000000 ..b35e6484
--- /dev/null
+++ b/crates/aien-heartbeat/src/reader.rs
@@ -0,0 +1,530 @@
+//! Bounded expert read adapter (Expert Ribbon P1, sc#629): random reads of one selected expert from the
+//! checkpoint shards into a fixed pool of aligned staging buffers, verified against the manifest digest
+//! before anyone can see the bytes.
+//!
+//! * Bounded: `queue_depth` staging buffers, allocated once. `submit` refuses with [`ReadError::QueueFull`]
+//! when all are in use (no unbounded queue, no hidden allocation).
+//! * Verified: a [`VerifiedExpert`] exists only after the whole expert was read and its BLAKE3 matched. A short
+//! read, EOF, I/O error or digest mismatch returns an explicit error and publishes nothing.
+//! * Cancellation and deadlines: [`Ticket::cancel`] and [`Ticket::wait`]'s deadline. A read that is already in
+//! the kernel cannot be interrupted; its result is discarded and the buffer returns to the pool when it ends.
+//! * Shutdown: dropping the adapter closes the queue and joins every worker (outstanding tickets see
+//! [`ReadError::Shutdown`]).
+//! * Device: [`ShardDevice`]. [`FileShards`] is the Linux one (O_DIRECT or buffered, chosen by measurement, see
+//! the README); [`FakeShards`] is a deterministic in-memory one with injectable latency and faults for tests.
+
+use std::collections::VecDeque;
+use std::fs::{File, OpenOptions};
+use std::os::unix::fs::{FileExt, OpenOptionsExt};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender};
+use std::sync::{Arc, Condvar, Mutex};
+use std::thread::JoinHandle;
+use std::time::{Duration, Instant};
+
+use crate::aligned::{round_down, round_up, AlignedBuf};
+use crate::layout::Payload;
+use crate::manifest::{ExpertEntry, Manifest};
+
+/// Positional reads from the checkpoint shards.
+pub trait ShardDevice: Send + Sync {
+ fn read_at(&self, shard: u32, buf: &mut [u8], off: u64) -> std::io::Result<usize>;
+ /// Alignment of buffers, offsets and lengths the device needs (4096 for O_DIRECT, 1 otherwise).
+ fn align(&self) -> usize;
+}
+
+/// The shard files, read-only, O_DIRECT or buffered.
+pub struct FileShards {
+ files: Vec<File>,
+ direct: bool,
+}
+
+impl FileShards {
+ pub fn open(paths: &[PathBuf], direct: bool) -> Result<Self, ReadError> {
+ let mut files = Vec::with_capacity(paths.len());
+ for p in paths {
+ let mut o = OpenOptions::new();
+ o.read(true);
+ if direct {
+ o.custom_flags(libc::O_DIRECT);
+ }
+ files.push(
+ o.open(p)
+ .map_err(|e| ReadError::Io(format!("open {}: {e}", p.display())))?,
+ );
+ }
+ Ok(Self { files, direct })
+ }
+}
+
+impl ShardDevice for FileShards {
+ fn read_at(&self, shard: u32, buf: &mut [u8], off: u64) -> std::io::Result<usize> {
+ let f = self
+ .files
+ .get(shard as usize)
+ .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "shard index"))?;
+ f.read_at(buf, off)
+ }
+ fn align(&self) -> usize {
+ if self.direct {
+ crate::IO_ALIGN
+ } else {
+ 1
+ }
+ }
+}
+
+/// A fault the fake device applies to one read call (counted from 0 over the device's life).
+#[derive(Debug)]
+pub enum Fault {
+ /// The call returns EIO.
+ Eio,
+ /// The call returns at most this many bytes, then every later call on the same request returns 0 (EOF).
+ Short(usize),
+ /// The call succeeds but flips one byte of what it returns.
+ Flip,
+ /// The call blocks until the sender is dropped or sends (a stalled NVMe), then reads normally.
+ Stall(Receiver<()>),
+}
+
+/// Deterministic in-memory shards for tests: optional fixed latency per read and a fault plan by call index.
+pub struct FakeShards {
+ pub shards: Vec<Vec<u8>>,
+ pub latency: Duration,
+ faults: Mutex<VecDeque<(u64, Fault)>>,
+ calls: AtomicU64,
+ eof_after_short: Mutex<Option<u64>>,
+}
+
+impl FakeShards {
+ pub fn new(shards: Vec<Vec<u8>>, latency: Duration) -> Self {
+ Self {
+ shards,
+ latency,
+ faults: Mutex::new(VecDeque::new()),
+ calls: AtomicU64::new(0),
+ eof_after_short: Mutex::new(None),
+ }
+ }
+ /// Apply `f` to read call number `call` (0-based over the device's life).
+ pub fn fault_at(&self, call: u64, f: Fault) {
+ self.faults.lock().unwrap().push_back((call, f));
+ }
+ pub fn calls(&self) -> u64 {
+ self.calls.load(Ordering::Relaxed)
+ }
+}
+
+impl ShardDevice for FakeShards {
+ fn read_at(&self, shard: u32, buf: &mut [u8], off: u64) -> std::io::Result<usize> {
+ let call = self.calls.fetch_add(1, Ordering::Relaxed);
+ if !self.latency.is_zero() {
+ std::thread::sleep(self.latency);
+ }
+ if let Some(c) = *self.eof_after_short.lock().unwrap() {
+ if call == c + 1 {
+ return Ok(0);
+ }
+ }
+ let fault = {
+ let mut q = self.faults.lock().unwrap();
+ q.iter()
+ .position(|(c, _)| *c == call)
+ .and_then(|i| q.remove(i))
+ .map(|(_, f)| f)
+ };
+ let data = &self.shards[shard as usize];
+ let start = (off as usize).min(data.len());
+ let mut n = buf.len().min(data.len() - start);
+ match fault {
+ Some(Fault::Eio) => return Err(std::io::Error::from_raw_os_error(libc::EIO)),
+ Some(Fault::Short(m)) => {
+ n = n.min(m);
+ *self.eof_after_short.lock().unwrap() = Some(call);
+ }
+ Some(Fault::Stall(ref rx)) => {
+ let _ = rx.recv();
+ }
+ _ => {}
+ }
+ buf[..n].copy_from_slice(&data[start..start + n]);
+ if let (Some(Fault::Flip), true) = (&fault, n > 0) {
+ buf[n / 2] ^= 0x5A;
+ }
+ Ok(n)
+ }
+ fn align(&self) -> usize {
+ 1
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ReadError {
+ /// Every staging buffer is in use (bounded queue).
+ QueueFull,
+ /// The expert does not fit one staging buffer.
+ TooLarge {
+ need: usize,
+ cap: usize,
+ },
+ Io(String),
+ /// Fewer bytes than the manifest span (EOF or a short read that never completed).
+ ShortRead {
+ expert: (u16, u16),
+ wanted: usize,
+ got: usize,
+ },
+ DigestMismatch {
+ expert: (u16, u16),
+ },
+ Cancelled,
+ /// The waiter's deadline passed before the read finished (a stalled read).
+ Deadline,
+ Shutdown,
+ Manifest(String),
+}
+
+impl std::fmt::Display for ReadError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{self:?}")
+ }
+}
+impl std::error::Error for ReadError {}
+
+#[derive(Debug, Clone, Copy)]
+pub struct ReadConfig {
+ /// Reader threads (parallel reads in flight).
+ pub workers: usize,
+ /// Staging buffers = the most requests in flight or waiting to be consumed.
+ pub queue_depth: usize,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct ReadStats {
+ pub reads_ok: u64,
+ pub payload_bytes: u64,
+ pub device_bytes: u64,
+ pub read_ns: u64,
+ pub digest_ns: u64,
+ pub errors: u64,
+ pub queue_full: u64,
+}
+
+struct Pool {
+ bufs: Mutex<Vec<AlignedBuf>>,
+ returned: Condvar,
+ cap: usize,
+}
+
+impl Pool {
+ fn give_back(&self, b: AlignedBuf) {
+ self.bufs.lock().unwrap().push(b);
+ self.returned.notify_all();
+ }
+}
+
+/// A whole, digest-checked expert in a staging buffer. The buffer returns to the pool on drop.
+pub struct VerifiedExpert {
+ pub index: usize,
+ pub layer: u16,
+ pub expert: u16,
+ buf: Option<AlignedBuf>,
+ ranges: Vec<(usize, usize)>,
+ pool: Arc<Pool>,
+}
+
+impl VerifiedExpert {
+ pub fn payload(&self) -> Payload<'_> {
+ let b = self.buf.as_ref().expect("buffer").as_slice();
+ Payload::new(self.ranges.iter().map(|&(o, l)| &b[o..o + l]).collect())
+ }
+}
+
+impl Drop for VerifiedExpert {
+ fn drop(&mut self) {
+ if let Some(b) = self.buf.take() {
+ self.pool.give_back(b);
+ }
+ }
+}
+
+type Reply = Result<VerifiedExpert, ReadError>;
+
+struct Job {
+ index: usize,
+ buf: AlignedBuf,
+ cancel: Arc<AtomicBool>,
+ reply: SyncSender<Reply>,
+}
+
+/// One submitted read.
+pub struct Ticket {
+ rx: Receiver<Reply>,
+ cancel: Arc<AtomicBool>,
+}
+
+impl Ticket {
+ /// Request cancellation: a read not yet started is skipped; one in progress is discarded.
+ pub fn cancel(&self) {
+ self.cancel.store(true, Ordering::Release);
+ }
+ /// Wait up to `deadline` for the verified expert. On timeout the request is cancelled.
+ pub fn wait(self, deadline: Duration) -> Result<VerifiedExpert, ReadError> {
+ match self.rx.recv_timeout(deadline) {
+ Ok(r) => r,
+ Err(RecvTimeoutError::Timeout) => {
+ self.cancel();
+ Err(ReadError::Deadline)
+ }
+ Err(RecvTimeoutError::Disconnected) => Err(ReadError::Shutdown),
+ }
+ }
+}
+
+pub struct ReadAdapter {
+ manifest: Arc<Manifest>,
+ pool: Arc<Pool>,
+ tx: Option<SyncSender<Job>>,
+ workers: Vec<JoinHandle<()>>,
+ stats: Arc<Mutex<ReadStats>>,
+}
+
+/// Bytes one staging buffer needs for any expert of `m` on a device of alignment `align`.
+pub fn staging_bytes(m: &Manifest, align: usize) -> usize {
+ m.experts
+ .iter()
+ .map(|e| {
+ e.segments
+ .iter()
+ .map(|s| round_up(s.len as usize + align, align.max(crate::IO_ALIGN)))
+ .sum::<usize>()
+ })
+ .max()
+ .unwrap_or(crate::IO_ALIGN)
+}
+
+impl ReadAdapter {
+ pub fn new(manifest: Arc<Manifest>, dev: Arc<dyn ShardDevice>, cfg: ReadConfig) -> Self {
+ assert!(cfg.workers > 0 && cfg.queue_depth > 0);
+ let cap = staging_bytes(&manifest, dev.align());
+ let pool = Arc::new(Pool {
+ bufs: Mutex::new((0..cfg.queue_depth).map(|_| AlignedBuf::new(cap)).collect()),
+ returned: Condvar::new(),
+ cap,
+ });
+ let (tx, rx) = mpsc::sync_channel::<Job>(cfg.queue_depth);
+ let rx = Arc::new(Mutex::new(rx));
+ let stats = Arc::new(Mutex::new(ReadStats::default()));
+ let workers = (0..cfg.workers)
+ .map(|_| {
+ let (rx, dev, m, pool, stats) = (
+ rx.clone(),
+ dev.clone(),
+ manifest.clone(),
+ pool.clone(),
+ stats.clone(),
+ );
+ std::thread::spawn(move || loop {
+ let job = match rx.lock().unwrap().recv() {
+ Ok(j) => j,
+ Err(_) => return,
+ };
+ let r = run_job(&*dev, &m, &pool, &stats, job.index, job.buf, &job.cancel);
+ // A waiter that gave up (deadline) dropped its receiver: the buffer comes back via drop.
+ let _ = job.reply.send(r);
+ })
+ })
+ .collect();
+ Self {
+ manifest,
+ pool,
+ tx: Some(tx),
+ workers,
+ stats,
+ }
+ }
+
+ pub fn manifest(&self) -> &Manifest {
+ &self.manifest
+ }
+
+ pub fn staging_capacity(&self) -> usize {
+ self.pool.cap
+ }
+
+ pub fn stats(&self) -> ReadStats {
+ self.stats.lock().unwrap().clone()
+ }
+
+ /// Queue a read of `manifest.experts[index]`. Refuses (QueueFull) when every staging buffer is in use.
+ pub fn submit(&self, index: usize) -> Result<Ticket, ReadError> {
+ if index >= self.manifest.experts.len() {
+ return Err(ReadError::Manifest(format!("expert index {index}")));
+ }
+ let buf = match self.pool.bufs.lock().unwrap().pop() {
+ Some(b) => b,
+ None => {
+ self.stats.lock().unwrap().queue_full += 1;
+ return Err(ReadError::QueueFull);
+ }
+ };
+ let (rtx, rrx) = mpsc::sync_channel(1);
+ let cancel = Arc::new(AtomicBool::new(false));
+ let job = Job {
+ index,
+ buf,
+ cancel: cancel.clone(),
+ reply: rtx,
+ };
+ let tx = self.tx.as_ref().ok_or(ReadError::Shutdown)?;
+ if let Err(mpsc::SendError(j)) = tx.send(job) {
+ self.pool.give_back(j.buf);
+ return Err(ReadError::Shutdown);
+ }
+ Ok(Ticket { rx: rrx, cancel })
+ }
+
+ /// Submit, waiting (up to `wait`) for a free staging buffer instead of refusing.
+ pub fn submit_wait(&self, index: usize, wait: Duration) -> Result<Ticket, ReadError> {
+ let t0 = Instant::now();
+ loop {
+ match self.submit(index) {
+ Err(ReadError::QueueFull) => {
+ let left = wait.saturating_sub(t0.elapsed());
+ if left.is_zero() {
+ return Err(ReadError::QueueFull);
+ }
+ let g = self.pool.bufs.lock().unwrap();
+ if g.is_empty() {
+ let _ = self.pool.returned.wait_timeout(g, left).unwrap();
+ }
+ }
+ r => return r,
+ }
+ }
+ }
+}
+
+impl Drop for ReadAdapter {
+ fn drop(&mut self) {
+ self.tx.take();
+ for w in self.workers.drain(..) {
+ let _ = w.join();
+ }
+ }
+}
+
+fn run_job(
+ dev: &dyn ShardDevice,
+ m: &Manifest,
+ pool: &Arc<Pool>,
+ stats: &Mutex<ReadStats>,
+ index: usize,
+ mut buf: AlignedBuf,
+ cancel: &AtomicBool,
+) -> Reply {
+ let e = &m.experts[index];
+ let fail = |buf: AlignedBuf, err: ReadError| {
+ pool.give_back(buf);
+ if err != ReadError::Cancelled {
+ stats.lock().unwrap().errors += 1;
+ }
+ Err(err)
+ };
+ if cancel.load(Ordering::Acquire) {
+ return fail(buf, ReadError::Cancelled);
+ }
+ let t0 = Instant::now();
+ let (ranges, device) = match read_expert(dev, e, buf.as_mut_slice()) {
+ Ok(v) => v,
+ Err(err) => return fail(buf, err),
+ };
+ let read_ns = t0.elapsed().as_nanos() as u64;
+ if cancel.load(Ordering::Acquire) {
+ return fail(buf, ReadError::Cancelled);
+ }
+ let t1 = Instant::now();
+ let expected = match e.digest_bytes() {
+ Ok(d) => d,
+ Err(err) => return fail(buf, ReadError::Manifest(err.to_string())),
+ };
+ let mut h = blake3::Hasher::new();
+ for &(o, l) in &ranges {
+ h.update(&buf.as_slice()[o..o + l]);
+ }
+ if h.finalize().as_bytes() != &expected {
+ return fail(
+ buf,
+ ReadError::DigestMismatch {
+ expert: (e.layer, e.expert),
+ },
+ );
+ }
+ {
+ let mut s = stats.lock().unwrap();
+ s.reads_ok += 1;
+ s.payload_bytes += e.len;
+ s.device_bytes += device;
+ s.read_ns += read_ns;
+ s.digest_ns += t1.elapsed().as_nanos() as u64;
+ }
+ Ok(VerifiedExpert {
+ index,
+ layer: e.layer,
+ expert: e.expert,
+ buf: Some(buf),
+ ranges,
+ pool: pool.clone(),
+ })
+}
+
+/// Reads every segment of `e` into its own aligned window of `buf`. Returns the payload ranges and the device bytes.
+pub fn read_expert(
+ dev: &dyn ShardDevice,
+ e: &ExpertEntry,
+ buf: &mut [u8],
+) -> Result<(Vec<(usize, usize)>, u64), ReadError> {
+ let align = dev.align().max(1);
+ let window_align = align.max(crate::IO_ALIGN);
+ let mut ranges = Vec::with_capacity(e.segments.len());
+ let (mut base, mut device) = (0usize, 0u64);
+ for seg in &e.segments {
+ let astart = round_down(seg.start, align as u64);
+ let off = (seg.start - astart) as usize;
+ let need = off + seg.len as usize;
+ let window = round_up(need, align);
+ if base + window > buf.len() {
+ return Err(ReadError::TooLarge {
+ need: base + window,
+ cap: buf.len(),
+ });
+ }
+ let w = &mut buf[base..base + window];
+ let mut got = 0usize;
+ while got < need {
+ match dev.read_at(seg.shard, &mut w[got..], astart + got as u64) {
+ Ok(0) => break,
+ Ok(n) => got += n,
+ Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {}
+ Err(err) => {
+ return Err(ReadError::Io(format!(
+ "read expert ({},{}): {err}",
+ e.layer, e.expert
+ )))
+ }
+ }
+ }
+ if got < need {
+ return Err(ReadError::ShortRead {
+ expert: (e.layer, e.expert),
+ wanted: need,
+ got,
+ });
+ }
+ ranges.push((base + off, seg.len as usize));
+ device += got as u64;
+ base += round_up(window, window_align);
+ }
+ Ok((ranges, device))
+}
diff --git a/crates/aien-heartbeat/src/residency.rs b/crates/aien-heartbeat/src/residency.rs
new file mode 100644
index 00000000 ..298b5ae9
--- /dev/null
+++ b/crates/aien-heartbeat/src/residency.rs
@@ -0,0 +1,405 @@
+//! Bounded expert residency (Expert Ribbon P2, sc#630): which (layer, expert) lives in which GPU slot,
+//! who is using it, and which slot to reuse next. Host-only; the GPU side is behind
+//! [`crate::pager::SlotBackend`].
+//!
+//! Slot life cycle (one slot = one gate|up slot + one down slot on the device):
+//! ```text
+//! FREE --acquire(miss)--> FETCHING(id) --fetched(ver)--> READY(id, ver) pinned by the requester
+//! FETCHING(id) --fetch_failed--> FREE (nothing published)
+//! READY, pins > 0 = IN USE (never chosen as a victim)
+//! READY, pins == 0 = EVICTABLE (least recently used one is reused on a miss)
+//! ```
+//! Exactly the router's experts run: a miss waits for that expert or fails; nothing is substituted.
+//! When every slot is pinned or fetching the request fails with [`Acquire::Exhausted`] (backpressure, explicit).
+
+use std::collections::HashMap;
+
+/// `(layer, expert)`.
+pub type ExpertId = (u16, u16);
+
+/// Device versions of one slot pair (omega_gpu_fp8_slots versions of the gate|up and the down slot).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct SlotVersion {
+ pub gate_up: u64,
+ pub down: u64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum State {
+ Free,
+ Fetching(ExpertId),
+ Ready(ExpertId, SlotVersion),
+}
+
+#[derive(Debug, Clone, Copy)]
+struct Slot {
+ state: State,
+ pins: u32,
+ last_use: u64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Acquire {
+ /// Resident: pinned for the caller.
+ Hit { slot: u32, ver: SlotVersion },
+ /// Not resident: `slot` is reserved (FETCHING) for the caller, who must call `fetched` or `fetch_failed`.
+ Fetch {
+ slot: u32,
+ evicted: Option<ExpertId>,
+ },
+ /// Another request is fetching this expert right now.
+ Pending,
+ /// Every slot is pinned or fetching.
+ Exhausted,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ResidencyStats {
+ pub hits: u64,
+ pub misses: u64,
+ pub evictions: u64,
+ pub fetch_failures: u64,
+ pub exhausted: u64,
+ pub pinned_high: u32,
+}
+
+#[derive(Debug)]
+pub struct Residency {
+ slots: Vec<Slot>,
+ map: HashMap<ExpertId, u32>,
+ tick: u64,
+ pinned: u32,
+ stats: ResidencyStats,
+}
+
+impl Residency {
+ pub fn new(slots: usize) -> Self {
+ assert!(slots > 0 && slots <= u32::MAX as usize);
+ Self {
+ slots: vec![
+ Slot {
+ state: State::Free,
+ pins: 0,
+ last_use: 0,
+ };
+ slots
+ ],
+ map: HashMap::new(),
+ tick: 0,
+ pinned: 0,
+ stats: ResidencyStats::default(),
+ }
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.slots.len()
+ }
+
+ pub fn stats(&self) -> ResidencyStats {
+ self.stats.clone()
+ }
+
+ /// Experts currently READY (resident).
+ pub fn resident(&self) -> usize {
+ self.slots
+ .iter()
+ .filter(|s| matches!(s.state, State::Ready(..)))
+ .count()
+ }
+
+ /// Slot and version of `id` if READY (no pin taken).
+ pub fn lookup(&self, id: ExpertId) -> Option<(u32, SlotVersion)> {
+ let s = *self.map.get(&id)?;
+ match self.slots[s as usize].state {
+ State::Ready(_, v) => Some((s, v)),
+ _ => None,
+ }
+ }
+
+ pub fn pins(&self, slot: u32) -> u32 {
+ self.slots[slot as usize].pins
+ }
+
+ fn pin(&mut self, slot: u32) {
+ self.tick += 1;
+ let s = &mut self.slots[slot as usize];
+ s.pins += 1;
+ s.last_use = self.tick;
+ self.pinned += 1;
+ self.stats.pinned_high = self.stats.pinned_high.max(self.pinned);
+ }
+
+ pub fn acquire(&mut self, id: ExpertId) -> Acquire {
+ if let Some(&slot) = self.map.get(&id) {
+ return match self.slots[slot as usize].state {
+ State::Ready(_, ver) => {
+ self.pin(slot);
+ self.stats.hits += 1;
+ Acquire::Hit { slot, ver }
+ }
+ State::Fetching(_) => Acquire::Pending,
+ State::Free => unreachable!("map points at a free slot"),
+ };
+ }
+ // Victim: a free slot first, else the least recently used unpinned READY slot.
+ let victim = self
+ .slots
+ .iter()
+ .position(|s| s.state == State::Free)
+ .or_else(|| {
+ self.slots
+ .iter()
+ .enumerate()
+ .filter(|(_, s)| s.pins == 0 && matches!(s.state, State::Ready(..)))
+ .min_by_key(|(_, s)| s.last_use)
+ .map(|(i, _)| i)
+ });
+ let Some(v) = victim else {
+ self.stats.exhausted += 1;
+ return Acquire::Exhausted;
+ };
+ let evicted = match self.slots[v].state {
+ State::Ready(old, _) => {
+ self.map.remove(&old);
+ self.stats.evictions += 1;
+ Some(old)
+ }
+ _ => None,
+ };
+ self.slots[v].state = State::Fetching(id);
+ self.map.insert(id, v as u32);
+ self.stats.misses += 1;
+ Acquire::Fetch {
+ slot: v as u32,
+ evicted,
+ }
+ }
+
+ /// The fetch into `slot` completed and was published at `ver`: READY, pinned for the requester.
+ pub fn fetched(&mut self, slot: u32, ver: SlotVersion) {
+ let State::Fetching(id) = self.slots[slot as usize].state else {
+ panic!("fetched on a slot that is not fetching");
+ };
+ self.slots[slot as usize].state = State::Ready(id, ver);
+ self.pin(slot);
+ }
+
+ /// The fetch into `slot` failed: the slot is FREE, the expert is not resident.
+ pub fn fetch_failed(&mut self, slot: u32) {
+ let State::Fetching(id) = self.slots[slot as usize].state else {
+ panic!("fetch_failed on a slot that is not fetching");
+ };
+ self.map.remove(&id);
+ self.slots[slot as usize].state = State::Free;
+ self.stats.fetch_failures += 1;
+ }
+
+ pub fn release(&mut self, slot: u32) {
+ let s = &mut self.slots[slot as usize];
+ assert!(s.pins > 0, "release without a pin");
+ s.pins -= 1;
+ self.pinned -= 1;
+ }
+
+ /// Total pins outstanding (0 between requests).
+ pub fn pinned(&self) -> u32 {
+ self.pinned
+ }
+}
+
+/// Memory ledger for admitting expert slots (sc#630): everything else is budgeted first, slots get what is
+/// left, and a request for more is refused rather than assumed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct MemoryBudget {
+ /// MemAvailable at load time (bytes).
+ pub available: u64,
+ /// Kept free for the OS, the driver and other processes.
+ pub headroom: u64,
+ /// Resident non-expert weights (attention, router, lm_head, host embedding).
+ pub non_expert: u64,
+ /// KV cache at the configured max context.
+ pub kv: u64,
+ /// Launch scratch, staging buffers and other transients.
+ pub scratch: u64,
+}
+
+impl MemoryBudget {
+ pub fn for_slots(&self) -> u64 {
+ self.available
+ .saturating_sub(self.headroom)
+ .saturating_sub(self.non_expert)
+ .saturating_sub(self.kv)
+ .saturating_sub(self.scratch)
+ }
+
+ /// Admits `want` slots of `slot_bytes` each, or refuses with the ledger.
+ pub fn admit(&self, want: usize, slot_bytes: u64) -> Result<(), String> {
+ let need = want as u64 * slot_bytes;
+ if need > self.for_slots() {
+ return Err(format!(
+ "expert slots need {need} bytes ({want} x {slot_bytes}) but only {} are left: available {} - headroom {} - non-expert {} - kv {} - scratch {}",
+ self.for_slots(),
+ self.available,
+ self.headroom,
+ self.non_expert,
+ self.kv,
+ self.scratch
+ ));
+ }
+ Ok(())
+ }
+}
+
+/// `MemAvailable` from /proc/meminfo, bytes.
+pub fn mem_available() -> Option<u64> {
+ let s = std::fs::read_to_string("/proc/meminfo").ok()?;
+ let l = s.lines().find(|l| l.starts_with("MemAvailable:"))?;
+ let kb: u64 = l.split_whitespace().nth(1)?.parse().ok()?;
+ Some(kb * 1024)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn v(n: u64) -> SlotVersion {
+ SlotVersion {
+ gate_up: n,
+ down: n + 1000,
+ }
+ }
+
+ fn load(r: &mut Residency, id: ExpertId, n: u64) -> u32 {
+ match r.acquire(id) {
+ Acquire::Fetch { slot, .. } => {
+ r.fetched(slot, v(n));
+ slot
+ }
+ other => panic!("{other:?}"),
+ }
+ }
+
+ #[test]
+ fn miss_then_hit_and_release() {
+ let mut r = Residency::new(2);
+ let s = load(&mut r, (0, 5), 1);
+ assert_eq!(r.pins(s), 1);
+ r.release(s);
+ assert_eq!(r.acquire((0, 5)), Acquire::Hit { slot: s, ver: v(1) });
+ r.release(s);
+ assert_eq!(r.stats().hits, 1);
+ assert_eq!(r.stats().misses, 1);
+ assert_eq!(r.pinned(), 0);
+ }
+
+ #[test]
+ fn lru_eviction_order_and_layer_crossing_identities() {
+ let mut r = Residency::new(3);
+ for (i, id) in [(0, 1), (1, 1), (2, 1)].into_iter().enumerate() {
+ let s = load(&mut r, id, i as u64 + 1);
+ r.release(s);
+ }
+ // touch (0,1) so (1,1) is the least recent
+ let Acquire::Hit { slot, .. } = r.acquire((0, 1)) else {
+ panic!()
+ };
+ r.release(slot);
+ match r.acquire((3, 1)) {
+ Acquire::Fetch { evicted, slot } => {
+ assert_eq!(
+ evicted,
+ Some((1, 1)),
+ "same expert number, other layer: distinct ids"
+ );
+ r.fetched(slot, v(9));
+ r.release(slot);
+ }
+ o => panic!("{o:?}"),
+ }
+ assert!(r.lookup((1, 1)).is_none());
+ assert!(r.lookup((0, 1)).is_some() && r.lookup((2, 1)).is_some());
+ assert_eq!(r.stats().evictions, 1);
+ }
+
+ #[test]
+ fn pinned_slots_are_never_evicted_and_exhaustion_is_explicit() {
+ let mut r = Residency::new(2);
+ let a = load(&mut r, (0, 0), 1);
+ let b = load(&mut r, (0, 1), 2);
+ assert_eq!(r.acquire((0, 2)), Acquire::Exhausted);
+ assert_eq!(r.stats().exhausted, 1);
+ r.release(b);
+ match r.acquire((0, 2)) {
+ Acquire::Fetch { slot, evicted } => {
+ assert_eq!((slot, evicted), (b, Some((0, 1))));
+ r.fetched(slot, v(3));
+ r.release(slot);
+ }
+ o => panic!("{o:?}"),
+ }
+ assert_eq!(r.lookup((0, 0)).map(|x| x.0), Some(a), "pinned slot kept");
+ r.release(a);
+ }
+
+ #[test]
+ fn simultaneous_readers_share_a_slot() {
+ let mut r = Residency::new(1);
+ let s = load(&mut r, (4, 4), 1);
+ assert!(matches!(r.acquire((4, 4)), Acquire::Hit { .. }));
+ assert_eq!(r.pins(s), 2);
+ assert_eq!(r.acquire((4, 5)), Acquire::Exhausted);
+ r.release(s);
+ assert_eq!(
+ r.acquire((4, 5)),
+ Acquire::Exhausted,
+ "one reader still holds it"
+ );
+ r.release(s);
+ assert!(matches!(r.acquire((4, 5)), Acquire::Fetch { .. }));
+ }
+
+ #[test]
+ fn fetching_is_pending_for_others_and_failure_recovers() {
+ let mut r = Residency::new(2);
+ let Acquire::Fetch { slot, .. } = r.acquire((1, 2)) else {
+ panic!()
+ };
+ assert_eq!(r.acquire((1, 2)), Acquire::Pending);
+ r.fetch_failed(slot);
+ assert!(r.lookup((1, 2)).is_none());
+ assert_eq!(r.stats().fetch_failures, 1);
+ let s2 = load(&mut r, (1, 2), 7);
+ assert_eq!(r.lookup((1, 2)), Some((s2, v(7))));
+ r.release(s2);
+ }
+
+ #[test]
+ fn aba_reuse_gets_new_versions() {
+ // The same slot holds (0,0), then (0,1), then (0,0) again: the backend version differs each time,
+ // so a stale (slot, version) handle from the first load can never match the third.
+ let mut r = Residency::new(1);
+ let s = load(&mut r, (0, 0), 1);
+ r.release(s);
+ let s1 = load(&mut r, (0, 1), 2);
+ r.release(s1);
+ let s2 = load(&mut r, (0, 0), 3);
+ assert_eq!((s, s1, s2), (0, 0, 0));
+ assert_eq!(r.lookup((0, 0)), Some((0, v(3))));
+ r.release(s2);
+ }
+
+ #[test]
+ fn budget_admits_and_refuses() {
+ let b = MemoryBudget {
+ available: 100,
+ headroom: 10,
+ non_expert: 20,
+ kv: 30,
+ scratch: 5,
+ };
+ assert_eq!(b.for_slots(), 35);
+ assert!(b.admit(7, 5).is_ok());
+ let e = b.admit(8, 5).unwrap_err();
+ assert!(e.contains("need 40"), "{e}");
+ }
+}
diff --git a/crates/aien-heartbeat/tests/ribbon_store.rs b/crates/aien-heartbeat/tests/ribbon_store.rs
new file mode 100644
index 00000000 ..9c93f3bb
--- /dev/null
+++ b/crates/aien-heartbeat/tests/ribbon_store.rs
@@ -0,0 +1,543 @@
+//! Expert Ribbon P1/P2 host tests (sc#629, sc#630): FP8 expert layout, bounded verified read adapter with
+//! injected faults, residency through the pager with a fake GPU backend. Synthetic checkpoint with the real
+//! Qwen3 FP8 names, dtypes and shapes (hidden 256, moe intermediate 128), F8 tensors first then the BF16
+//! scales, as safetensors groups them, so every expert is two segments.
+
+use std::collections::{BTreeMap, HashMap};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{mpsc, Arc, Mutex};
+use std::time::Duration;
+
+use aien_heartbeat::{
+ ExpertId, ExpertLayout, ExpertPager, ExpertParts, ExpertShape, FakeShards, Fault, FileShards,
+ Manifest, PagerError, ReadAdapter, ReadConfig, ReadError, SlotBackend, SlotVersion,
+};
+
+const L: u16 = 3;
+const E: u16 = 4;
+const SHAPE: ExpertShape = ExpertShape {
+ hidden: 256,
+ inter: 128,
+};
+
+fn tmpdir(tag: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("aien-ribbon-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+fn byte(l: u16, e: u16, p: usize, k: usize) -> u8 {
+ ((l as usize * 131 + e as usize * 17 + p * 7 + k * 13) % 251) as u8
+}
+
+/// (name, dtype, shape, bytes) for one expert's six tensors.
+fn expert_tensors(l: u16, e: u16) -> Vec<(String, &'static str, Vec<u64>, Vec<u8>)> {
+ let (h, i) = (SHAPE.hidden, SHAPE.inter);
+ let mut v = Vec::new();
+ for (p, (proj, shape)) in [
+ ("gate_proj", [i, h]),
+ ("up_proj", [i, h]),
+ ("down_proj", [h, i]),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let n = (shape[0] * shape[1]) as usize;
+ v.push((
+ format!("model.layers.{l}.mlp.experts.{e}.{proj}.weight"),
+ "F8_E4M3",
+ shape.to_vec(),
+ (0..n).map(|k| byte(l, e, p, k)).collect(),
+ ));
+ let sshape = [shape[0] / 128, shape[1] / 128];
+ let sn = (sshape[0] * sshape[1]) as usize;
+ v.push((
+ format!("model.layers.{l}.mlp.experts.{e}.{proj}.weight_scale_inv"),
+ "BF16",
+ sshape.to_vec(),
+ (0..sn)
+ .flat_map(|k| (0x3C00u16 + (l * 8 + e) + k as u16 + p as u16).to_le_bytes())
+ .collect(),
+ ));
+ }
+ v
+}
+
+/// One shard: all F8 tensors sorted by name, then all BF16 tensors sorted by name (safetensors' grouping).
+fn write_model(dir: &Path) -> Vec<u8> {
+ let mut all: Vec<(String, &str, Vec<u64>, Vec<u8>)> = Vec::new();
+ for l in 0..L {
+ for e in 0..E {
+ all.extend(expert_tensors(l, e));
+ }
+ }
+ all.push((
+ "model.norm.weight".into(),
+ "BF16",
+ vec![256],
+ vec![1u8; 512],
+ ));
+ all.sort_by(|a, b| (a.1 != "F8_E4M3", &a.0).cmp(&(b.1 != "F8_E4M3", &b.0)));
+ let mut header = serde_json::Map::new();
+ let mut data = Vec::new();
+ let mut weight_map = BTreeMap::new();
+ for (name, dtype, shape, bytes) in &all {
+ let a = data.len();
+ data.extend(bytes);
+ header.insert(
+ name.clone(),
+ serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [a, data.len()]}),
+ );
+ weight_map.insert(name.clone(), "model-00001-of-00001.safetensors".to_string());
+ }
+ let h = serde_json::to_vec(&header).unwrap();
+ let mut file = (h.len() as u64).to_le_bytes().to_vec();
+ file.extend(&h);
+ file.extend(&data);
+ std::fs::write(dir.join("model-00001-of-00001.safetensors"), &file).unwrap();
+ std::fs::write(
+ dir.join("model.safetensors.index.json"),
+ serde_json::to_vec(&serde_json::json!({"metadata": {}, "weight_map": weight_map})).unwrap(),
+ )
+ .unwrap();
+ file
+}
+
+/// What the resident loader uploads for one expert, built straight from the tensors (the oracle).
+fn oracle(l: u16, e: u16) -> (Vec<u8>, Vec<u16>, Vec<u8>, Vec<u16>) {
+ let t = expert_tensors(l, e);
+ let get = |suffix: &str| t.iter().find(|x| x.0.ends_with(suffix)).unwrap().3.clone();
+ let words = |b: Vec<u8>| -> Vec<u16> {
+ b.as_chunks::<2>()
+ .0
+ .iter()
+ .map(|c| u16::from_le_bytes(*c))
+ .collect()
+ };
+ let mut gu = get("gate_proj.weight");
+ gu.extend(get("up_proj.weight"));
+ let mut gus = words(get("gate_proj.weight_scale_inv"));
+ gus.extend(words(get("up_proj.weight_scale_inv")));
+ (
+ gu,
+ gus,
+ get("down_proj.weight"),
+ words(get("down_proj.weight_scale_inv")),
+ )
+}
+
+fn setup(tag: &str) -> (PathBuf, Arc<Manifest>, Vec<u8>) {
+ let d = tmpdir(tag);
+ let file = write_model(&d);
+ let m = Arc::new(Manifest::build(&d).unwrap());
+ (d, m, file)
+}
+
+fn fake(file: &[u8], latency: Duration) -> Arc<FakeShards> {
+ Arc::new(FakeShards::new(vec![file.to_vec()], latency))
+}
+
+fn idx(m: &Manifest, id: ExpertId) -> usize {
+ m.experts
+ .iter()
+ .position(|e| (e.layer, e.expert) == id)
+ .unwrap()
+}
+
+// ---------------- sc#629: layout, index, verified reads ----------------
+
+#[test]
+fn manifest_has_a_content_model_digest_and_two_segments_per_expert() {
+ let (d, m, _) = setup("digest");
+ assert_eq!(m.experts.len(), (L * E) as usize);
+ assert!(m.experts.iter().all(|e| e.segments.len() == 2));
+ assert_eq!(m.model_digest.len(), 64);
+ // Same bytes -> same digest; one weight byte changed -> different model digest.
+ assert_eq!(Manifest::build(&d).unwrap().model_digest, m.model_digest);
+ let p = d.join("model-00001-of-00001.safetensors");
+ let mut f = std::fs::read(&p).unwrap();
+ let off = m.experts[5].segments[0].start as usize + 3;
+ f[off] ^= 1;
+ std::fs::write(&p, &f).unwrap();
+ let m2 = Manifest::build(&d).unwrap();
+ assert_ne!(m2.model_digest, m.model_digest);
+ assert_ne!(m2.experts[5].digest, m.experts[5].digest);
+}
+
+#[test]
+fn every_expert_round_trips_byte_for_byte_through_a_verified_random_read() {
+ let (d, m, _) = setup("roundtrip");
+ let dev = Arc::new(FileShards::open(&m.shard_paths(), false).unwrap());
+ let r = ReadAdapter::new(
+ m.clone(),
+ dev,
+ ReadConfig {
+ workers: 3,
+ queue_depth: 4,
+ },
+ );
+ // Random order, not layer order: (2,1), (0,3), (1,0), ...
+ let order: Vec<ExpertId> = (0..L * E)
+ .map(|k| ((k * 7 % (L * E)) / E, (k * 7 % (L * E)) % E))
+ .collect();
+ for id in order {
+ let i = idx(&m, id);
+ let v = r.submit(i).unwrap().wait(Duration::from_secs(5)).unwrap();
+ assert_eq!((v.layer, v.expert), id);
+ let layout = ExpertLayout::for_entry(&m.experts[i], SHAPE).unwrap();
+ let parts = layout.parts(&v.payload()).unwrap();
+ let (gu, gus, dn, dns) = oracle(id.0, id.1);
+ assert_eq!(&*parts.gate_up_w, &gu[..], "{id:?} gate|up weights");
+ assert!(
+ matches!(parts.gate_up_w, std::borrow::Cow::Borrowed(_)),
+ "gate and up adjacent: no copy"
+ );
+ assert_eq!(parts.gate_up_s, gus);
+ assert_eq!(&*parts.down_w, &dn[..]);
+ assert_eq!(parts.down_s, dns);
+ }
+ assert_eq!(r.stats().reads_ok, (L * E) as u64);
+ let _ = std::fs::remove_dir_all(d);
+}
+
+#[test]
+fn layout_refuses_wrong_shape_and_missing_tensor() {
+ let (_, m, _) = setup("layout");
+ let e = &m.experts[0];
+ let bad = ExpertShape {
+ hidden: 256,
+ inter: 256,
+ };
+ assert!(ExpertLayout::for_entry(e, bad).is_err());
+ let mut e2 = e.clone();
+ e2.tensors.retain(|t| !t.name.ends_with("up_proj.weight"));
+ let err = ExpertLayout::for_entry(&e2, SHAPE).unwrap_err().to_string();
+ assert!(err.contains("5 tensors"), "{err}");
+ let mut e3 = e.clone();
+ e3.tensors[0].dtype = "BF16".into();
+ assert!(ExpertLayout::for_entry(&e3, SHAPE).is_err());
+}
+
+fn adapter(m: &Arc<Manifest>, dev: Arc<FakeShards>, depth: usize) -> ReadAdapter {
+ ReadAdapter::new(
+ m.clone(),
+ dev,
+ ReadConfig {
+ workers: 2,
+ queue_depth: depth,
+ },
+ )
+}
+
+#[test]
+fn eio_short_read_eof_and_corruption_return_explicit_errors_and_free_the_buffer() {
+ let (_, m, file) = setup("faults");
+ let dev = fake(&file, Duration::ZERO);
+ let r = adapter(&m, dev.clone(), 1);
+ let w = Duration::from_secs(5);
+ dev.fault_at(0, Fault::Eio);
+ assert!(matches!(
+ r.submit(0).unwrap().wait(w),
+ Err(ReadError::Io(_))
+ ));
+ // Short read then EOF on the same segment.
+ let c = dev.calls();
+ dev.fault_at(c, Fault::Short(100));
+ assert!(matches!(
+ r.submit(1).unwrap().wait(w),
+ Err(ReadError::ShortRead { .. })
+ ));
+ let c = dev.calls();
+ dev.fault_at(c + 1, Fault::Flip); // second segment (scales) corrupted
+ assert!(matches!(
+ r.submit(2).unwrap().wait(w),
+ Err(ReadError::DigestMismatch { expert: (0, 2) })
+ ));
+ // Depth 1: the single staging buffer came back after every failure.
+ let ok = r.submit(3).unwrap().wait(w).unwrap();
+ assert_eq!((ok.layer, ok.expert), (0, 3));
+ assert_eq!(r.stats().errors, 3);
+}
+
+#[test]
+fn bounded_queue_refuses_when_every_staging_buffer_is_in_use() {
+ let (_, m, file) = setup("bounded");
+ let r = adapter(&m, fake(&file, Duration::ZERO), 2);
+ let w = Duration::from_secs(5);
+ let a = r.submit(0).unwrap().wait(w).unwrap();
+ let b = r.submit(1).unwrap().wait(w).unwrap();
+ assert_eq!(r.submit(2).err(), Some(ReadError::QueueFull));
+ drop(a);
+ let c = r.submit(2).unwrap().wait(w).unwrap();
+ assert_eq!(c.expert, 2);
+ drop((b, c));
+ assert!(r.stats().queue_full >= 1);
+}
+
+#[test]
+fn stalled_read_hits_the_deadline_and_cancel_skips_queued_work() {
+ let (_, m, file) = setup("stall");
+ let dev = fake(&file, Duration::ZERO);
+ let r = ReadAdapter::new(
+ m.clone(),
+ dev.clone(),
+ ReadConfig {
+ workers: 1,
+ queue_depth: 3,
+ },
+ );
+ let (tx, rx) = mpsc::channel();
+ dev.fault_at(0, Fault::Stall(rx));
+ let stalled = r.submit(0).unwrap();
+ let queued = r.submit(1).unwrap(); // behind the stalled one (one worker)
+ queued.cancel();
+ assert_eq!(
+ stalled.wait(Duration::from_millis(50)).err(),
+ Some(ReadError::Deadline)
+ );
+ tx.send(()).unwrap(); // the NVMe "recovers"; its result is discarded
+ assert_eq!(
+ queued.wait(Duration::from_secs(5)).err(),
+ Some(ReadError::Cancelled)
+ );
+ // Every buffer returns: three more reads fit.
+ let w = Duration::from_secs(5);
+ let held: Vec<_> = (2..5)
+ .map(|i| r.submit_wait(i, w).unwrap().wait(w).unwrap())
+ .collect();
+ assert_eq!(held.len(), 3);
+}
+
+#[test]
+fn shutdown_with_reads_in_flight_is_deterministic() {
+ let (_, m, file) = setup("shutdown");
+ let r = adapter(&m, fake(&file, Duration::from_millis(5)), 4);
+ let ts: Vec<_> = (0..4).map(|i| r.submit(i).unwrap()).collect();
+ drop(r); // joins the workers after the queue drains
+ for t in ts {
+ // finished before shutdown, or the reply channel closed: never a hang, never a partial result
+ match t.wait(Duration::from_secs(5)) {
+ Ok(v) => assert!(!v.payload().is_empty()),
+ Err(e) => assert_eq!(e, ReadError::Shutdown),
+ }
+ }
+}
+
+// ---------------- sc#630: pager + residency with a fake GPU backend ----------------
+
+/// (expert, gate|up weights, gate|up scales, down weights, down scales) held by one fake slot pair.
+type SlotBytes = (ExpertId, Vec<u8>, Vec<u16>, Vec<u8>, Vec<u16>);
+
+/// Host stand-in for the two omega slot pools: keeps the bytes per slot and versions like the chip API.
+struct FakeBackend {
+ slots: usize,
+ data: Mutex<HashMap<u32, SlotBytes>>,
+ next: AtomicU64,
+ fail_on: Mutex<Option<ExpertId>>,
+ loads: AtomicU64,
+}
+
+impl FakeBackend {
+ fn new(slots: usize) -> Arc<Self> {
+ Arc::new(Self {
+ slots,
+ data: Mutex::new(HashMap::new()),
+ next: AtomicU64::new(1),
+ fail_on: Mutex::new(None),
+ loads: AtomicU64::new(0),
+ })
+ }
+}
+
+impl SlotBackend for FakeBackend {
+ fn slots(&self) -> usize {
+ self.slots
+ }
+ fn load(&self, slot: u32, id: ExpertId, p: &ExpertParts<'_>) -> Result<SlotVersion, String> {
+ if *self.fail_on.lock().unwrap() == Some(id) {
+ return Err("injected GPU copy failure".into());
+ }
+ self.loads.fetch_add(1, Ordering::Relaxed);
+ self.data.lock().unwrap().insert(
+ slot,
+ (
+ id,
+ p.gate_up_w.to_vec(),
+ p.gate_up_s.clone(),
+ p.down_w.to_vec(),
+ p.down_s.clone(),
+ ),
+ );
+ let v = self.next.fetch_add(2, Ordering::Relaxed);
+ Ok(SlotVersion {
+ gate_up: v,
+ down: v + 1,
+ })
+ }
+}
+
+fn pager(m: &Arc<Manifest>, file: &[u8], slots: usize) -> (ExpertPager, Arc<FakeBackend>) {
+ let be = FakeBackend::new(slots);
+ let r = ReadAdapter::new(
+ m.clone(),
+ fake(file, Duration::ZERO),
+ ReadConfig {
+ workers: 4,
+ queue_depth: 8,
+ },
+ );
+ let p = ExpertPager::new(m.clone(), SHAPE, r, be.clone(), Duration::from_secs(5)).unwrap();
+ (p, be)
+}
+
+#[test]
+fn pager_pins_exactly_the_routed_experts_and_slots_hold_their_bytes() {
+ let (_, m, file) = setup("pager");
+ let (p, be) = pager(&m, &file, 6);
+ let want = [3u16, 0, 2];
+ let pin = p.ensure(1, &want).unwrap();
+ assert_eq!(pin.slots.len(), 3);
+ {
+ let d = be.data.lock().unwrap();
+ for (k, &s) in pin.slots.iter().enumerate() {
+ let (id, gu, gus, dn, dns) = &d[&s];
+ assert_eq!(*id, (1, want[k]), "router order kept");
+ assert_eq!(
+ (gu, gus, dn, dns),
+ (
+ &oracle(1, want[k]).0,
+ &oracle(1, want[k]).1,
+ &oracle(1, want[k]).2,
+ &oracle(1, want[k]).3
+ )
+ );
+ }
+ }
+ assert_eq!(p.pinned(), 3);
+ p.release(&pin);
+ assert_eq!(p.pinned(), 0);
+ // Same request again: all hits, no new loads, same slots and versions.
+ let again = p.ensure(1, &want).unwrap();
+ assert_eq!(again, pin);
+ p.release(&again);
+ assert_eq!(be.loads.load(Ordering::Relaxed), 3);
+ let s = p.stats();
+ assert_eq!((s.experts_missed, s.experts_hit), (3, 3));
+}
+
+#[test]
+fn cache_pressure_evicts_lru_never_a_pinned_slot() {
+ let (_, m, file) = setup("pressure");
+ let (p, be) = pager(&m, &file, 4);
+ let a = p.ensure(0, &[0, 1]).unwrap(); // held
+ let b = p.ensure(1, &[0, 1]).unwrap();
+ p.release(&b);
+ // 2 free-able slots left (layer 1); layer 2 needs 2: evicts layer 1, not layer 0 (pinned)
+ let c = p.ensure(2, &[2, 3]).unwrap();
+ assert!(c.slots.iter().all(|s| !a.slots.contains(s)));
+ assert_eq!(p.residency_stats().evictions, 2);
+ // Everything pinned now: a third request cannot be served, and says so.
+ match p.ensure(0, &[3]) {
+ Err(PagerError::Exhausted { capacity: 4, .. }) => {}
+ o => panic!("{o:?}"),
+ }
+ assert_eq!(p.pinned(), 4, "the failed request left nothing pinned");
+ p.release(&a);
+ p.release(&c);
+ // Repeated layer-crossing churn keeps bytes right.
+ for round in 0..20u16 {
+ let l = round % L;
+ let ex = [(round % E), ((round + 1) % E)];
+ let pin = p.ensure(l, &ex).unwrap();
+ let d = be.data.lock().unwrap();
+ for (k, s) in pin.slots.iter().enumerate() {
+ assert_eq!(d[s].0, (l, ex[k]));
+ assert_eq!(d[s].1, oracle(l, ex[k]).0);
+ }
+ drop(d);
+ p.release(&pin);
+ }
+ assert_eq!(p.pinned(), 0);
+}
+
+#[test]
+fn a_failed_fetch_fails_closed_and_recovers() {
+ let (_, m, file) = setup("failclosed");
+ let (p, be) = pager(&m, &file, 4);
+ *be.fail_on.lock().unwrap() = Some((2, 1));
+ match p.ensure(2, &[0, 1, 2]) {
+ Err(PagerError::Backend { id: (2, 1), .. }) => {}
+ o => panic!("{o:?}"),
+ }
+ assert_eq!(
+ p.pinned(),
+ 0,
+ "the good experts of the failed request were released"
+ );
+ assert_eq!(
+ p.resident(),
+ 2,
+ "experts that did load stay resident and correct"
+ );
+ *be.fail_on.lock().unwrap() = None;
+ let ok = p.ensure(2, &[0, 1, 2]).unwrap();
+ p.release(&ok);
+ assert_eq!(p.resident(), 3);
+}
+
+#[test]
+fn corrupt_checkpoint_bytes_never_reach_a_slot() {
+ let (_, m, file) = setup("corrupt");
+ let be = FakeBackend::new(4);
+ let dev = fake(&file, Duration::ZERO);
+ dev.fault_at(0, Fault::Flip);
+ let r = ReadAdapter::new(
+ m.clone(),
+ dev,
+ ReadConfig {
+ workers: 1,
+ queue_depth: 2,
+ },
+ );
+ let p = ExpertPager::new(m.clone(), SHAPE, r, be.clone(), Duration::from_secs(5)).unwrap();
+ match p.ensure(0, &[1]) {
+ Err(PagerError::Read {
+ err: ReadError::DigestMismatch { .. },
+ ..
+ }) => {}
+ o => panic!("{o:?}"),
+ }
+ assert_eq!(be.loads.load(Ordering::Relaxed), 0);
+ assert_eq!(p.resident(), 0);
+}
+
+#[test]
+fn simultaneous_requests_share_slots_and_wait_for_in_flight_fetches() {
+ let (_, m, file) = setup("concurrent");
+ let (p, be) = pager(&m, &file, 8);
+ let p = Arc::new(p);
+ let hs: Vec<_> = (0..4)
+ .map(|_| {
+ let p = p.clone();
+ std::thread::spawn(move || {
+ let pin = p.ensure(1, &[0, 1, 2, 3]).unwrap();
+ std::thread::sleep(Duration::from_millis(5));
+ p.release(&pin);
+ pin
+ })
+ })
+ .collect();
+ let pins: Vec<_> = hs.into_iter().map(|h| h.join().unwrap()).collect();
+ assert!(
+ pins.windows(2).all(|w| w[0] == w[1]),
+ "everyone got the same slots and versions"
+ );
+ assert_eq!(
+ be.loads.load(Ordering::Relaxed),
+ 4,
+ "each expert loaded once"
+ );
+ assert_eq!(p.pinned(), 0);
+}
diff --git a/crates/aien-inference-abi/Cargo.toml b/crates/aien-inference-abi/Cargo.toml
index 1131a028 ..878a0086 100644
--- a/crates/aien-inference-abi/Cargo.toml
+++ b/crates/aien-inference-abi/Cargo.toml
@@ -21,6 +21,7 @@ aien-omega-moe = { path = "../aien-omega-moe" }
aien-omega-fp8 = { path = "../aien-omega-fp8" }
aien-omega-dattn = { path = "../aien-omega-dattn" }
aien-omega-router = { path = "../aien-omega-router" }
+aien-heartbeat = { path = "../aien-heartbeat" }
aien-omega-bf16 = { path = "../aien-omega-bf16" }
aien-omega-pf = { path = "../aien-omega-pf" }
aien-omega-dgraph = { path = "../aien-omega-dgraph" }
diff --git a/crates/aien-inference-abi/src/bin/own30b_check.rs b/crates/aien-inference-abi/src/bin/own30b_check.rs
index ba3874bb ..16f300fe 100644
--- a/crates/aien-inference-abi/src/bin/own30b_check.rs
+++ b/crates/aien-inference-abi/src/bin/own30b_check.rs
@@ -5,6 +5,7 @@
//! runs greedy continuations of the 4 fixed prompts, writes tokens and top-2 margins.
//! own30b_check chip <checkpoint> <golden.json> <receipt-dir> [--new N] [--layers 0,23,47]
//! [--max-context 8192] [--prompts 1,2,3,4] [--force-memory]
+//! [--paged-experts SLOTS [--manifest PATH] [--read-workers W] [--read-depth D]]
//! [--weights bf16|fp8-experts|fp8]
//! [--router auto|host|device] [--lm-head auto|dense|gemv] [--router-mutants 1,2,3,4]
//! [--prefill auto|gemv|gemm] [--prefill-routing host|device] [--prefill-chunk N]
@@ -25,12 +26,12 @@ use aien_inference_abi::qwen3_coder::{
compute_logits, forward_token, load_qwen3_coder, Qwen3CoderState,
};
use aien_inference_abi::qwen3_moe::load_qwen3_fp8_moe_layer;
-use aien_inference_abi::qwen3_moe_omega::dgraph;
use aien_inference_abi::qwen3_moe_omega::{
current_rss_bytes, load_attention_layer_f32, peak_rss_bytes, replay_attention, replay_moe,
AttnPath, DevicePaths, GenerateParams, LmHead, OmegaModelUploader, PathChoice, Qwen3MoeConfig,
Qwen3MoeOmegaEngine, StepTiming, WeightFormat,
};
+use aien_inference_abi::qwen3_moe_omega::{dgraph, ribbon};
use aien_inference_abi::tokenizer::ChatTokenizer as Tokenizer;
const PROMPT_TEXTS: [(&str, &str); 4] = [
@@ -225,6 +226,11 @@ struct Args {
gemm_mutants: Vec<i32>,
/// Also run a prompt of at least this many tokens: chunk 1 against the batched chunk, tokens and hidden state.
long_prompt: usize,
+ /// Expert Ribbon: page the experts into this many GPU slots (0 = all resident).
+ paged_slots: usize,
+ ribbon_manifest: PathBuf,
+ read_workers: usize,
+ read_depth: usize,
}
fn parse_choice(v: &str, host_word: &str, flag: &str) -> PathChoice {
@@ -263,6 +269,10 @@ fn parse_args() -> Args {
prefill_device_routing: false,
gemm_mutants: vec![1, 2, 3],
long_prompt: 0,
+ paged_slots: 0,
+ ribbon_manifest: std::env::temp_dir().join("aien-ribbon-manifest.json"),
+ read_workers: 16,
+ read_depth: 32,
};
while let Some(arg) = it.next() {
match arg.as_str() {
@@ -329,6 +339,24 @@ fn parse_args() -> Args {
)
}
"--tokens-only" => a.tokens_only = true,
+ "--paged-experts" => {
+ a.paged_slots = it
+ .next()
+ .expect("--paged-experts SLOTS")
+ .parse()
+ .expect("number")
+ }
+ "--manifest" => a.ribbon_manifest = PathBuf::from(it.next().expect("--manifest PATH")),
+ "--read-workers" => {
+ a.read_workers = it
+ .next()
+ .expect("--read-workers N")
+ .parse()
+ .expect("number")
+ }
+ "--read-depth" => {
+ a.read_depth = it.next().expect("--read-depth N").parse().expect("number")
+ }
"--whole-prompt" => a.whole_prompt = true,
"--prefill-device-host" => a.wp_device_host = true,
"--prefill" => {
@@ -442,8 +470,24 @@ fn chip(a: &Args) {
};
let avail = mem_available_gb();
say(format!("mem available before load: {avail:.1} GB"));
- if avail < 70.0 && !a.force_memory {
- say("REFUSED: less than 70 GB available (another model may be loaded); --force-memory to override".into());
+ let config0 = Qwen3MoeConfig::from_checkpoint(&a.checkpoint).expect("config.json");
+ // Paged experts: the slot pools (exact) plus a fixed 6 GB for attention, lm_head, KV and scratch.
+ let (h0, i0) = (config0.hidden, config0.moe_intermediate);
+ let pool_bytes = a.paged_slots * (3 * h0 * i0 + 4 * 3 * (h0 / 128) * (i0 / 128));
+ let need_gb = if a.paged_slots > 0 {
+ pool_bytes as f64 / 1e9 + 6.0
+ } else {
+ 70.0
+ };
+ if a.paged_slots > 0 {
+ say(format!(
+ "RIBBON: {} slots, pools {:.2} GB; memory gate {need_gb:.1} GB",
+ a.paged_slots,
+ pool_bytes as f64 / 1e9
+ ));
+ }
+ if avail < need_gb && !a.force_memory {
+ say(format!("REFUSED: less than {need_gb:.1} GB available (another model may be loaded); --force-memory to override"));
std::process::exit(3);
}
let golden: serde_json::Value =
@@ -474,12 +518,32 @@ fn chip(a: &Args) {
// ---- load ----
let t0 = Instant::now();
let mut n = 0usize;
- let (mut engine, report) = Qwen3MoeOmegaEngine::load_omega_paths(
+ let paged = (a.paged_slots > 0).then(|| {
+ ribbon::open_omega(
+ &a.checkpoint,
+ h0,
+ i0,
+ &ribbon::RibbonOptions {
+ manifest: a.ribbon_manifest.clone(),
+ slots: a.paged_slots,
+ read: aien_heartbeat::ReadConfig {
+ workers: a.read_workers,
+ queue_depth: a.read_depth,
+ },
+ direct: true,
+ read_deadline: std::time::Duration::from_secs(30),
+ },
+ &mut |s| eprintln!(" {s}"),
+ )
+ .expect("expert ribbon")
+ });
+ let (mut engine, report) = Qwen3MoeOmegaEngine::load_omega_experts(
&a.checkpoint,
a.max_context,
a.format,
a.attn,
a.paths,
+ paged.clone(),
&mut |s| {
n += 1;
if n.is_multiple_of(20) || s.starts_with("kv") || s == "lm_head" {
@@ -952,6 +1016,7 @@ fn chip(a: &Args) {
let params = GenerateParams::greedy(a.new_tokens, config.eos_token_ids.clone());
// Start this prompt's timeline from zero (earlier sections also ran graph tokens).
let _ = engine.take_decode_timeline();
+ let rb0 = paged.as_ref().map(|p| (p.stats(), p.read_stats()));
let o = engine
.generate(ids, ¶ms, &mut |t| {
got.push(t);
@@ -1039,6 +1104,32 @@ fn chip(a: &Args) {
per_graph(dt.graph_submits),
per_graph(dt.graph_record_ns) / 1e3,
));
+ let mut ribbon_json = serde_json::Value::Null;
+ if let (Some(p), Some((s0, r0))) = (&paged, &rb0) {
+ let (s, r) = (p.stats(), p.read_stats());
+ let hit = s.experts_hit - s0.experts_hit;
+ let miss = s.experts_missed - s0.experts_missed;
+ let bytes = s.bytes_loaded - s0.bytes_loaded;
+ let slot_ns = s.slot_load_ns - s0.slot_load_ns;
+ let read_ns = s.read_wait_ns - s0.read_wait_ns;
+ let miss_wall = s.miss_wall_ns - s0.miss_wall_ns;
+ let dev_bytes = r.device_bytes - r0.device_bytes;
+ say(format!(
+ " RIBBON {} slots: experts hit {hit} miss {miss} (hit rate {:.4}); loaded {bytes} B; miss wall {:.1} ms; per decode step page {:.2} ms; prefill page {:.1} ms; summed read wait {:.1} ms; summed slot load {:.1} ms; device read {dev_bytes} B; resident {}",
+ p.capacity(),
+ hit as f64 / (hit + miss).max(1) as f64,
+ miss_wall as f64 / 1e6,
+ dt.page_ns as f64 / steps / 1e6,
+ pt.page_ns as f64 / 1e6,
+ read_ns as f64 / 1e6,
+ slot_ns as f64 / 1e6,
+ p.resident(),
+ ));
+ ribbon_json = serde_json::json!({"slots": p.capacity(), "hit": hit, "miss": miss,
+ "bytes_loaded": bytes, "miss_wall_ns": miss_wall, "read_wait_ns": read_ns,
+ "slot_load_ns": slot_ns, "device_read_bytes": dev_bytes, "decode_page_ns": dt.page_ns,
+ "prefill_page_ns": pt.page_ns, "decode_steps": o.emitted_tokens});
+ }
let mut timeline_json = serde_json::Value::Null;
if let Some(t) = engine.take_decode_timeline() {
let lines = timeline_table(&t, &config);
@@ -1057,7 +1148,7 @@ fn chip(a: &Args) {
));
results.push(serde_json::json!({
"name": name, "prompt_tokens": ids.len(), "chip": got, "golden": want, "first_diff": first_diff,
- "prefill_ms": o.prefill_ms, "decode_ms": o.decode_ms, "emitted": o.emitted_tokens, "tok_s": tok_s,
+ "prefill_ms": o.prefill_ms, "decode_ms": o.decode_ms, "emitted": o.emitted_tokens, "tok_s": tok_s, "ribbon": ribbon_json,
"per_step_ms": {"attention": dt.attention_ns as f64 / 1e6 / steps, "experts": dt.experts_ns as f64 / 1e6 / steps,
"lm_head": dt.lm_head_ns as f64 / 1e6 / steps, "host": dt.host_ns as f64 / 1e6 / steps, "chip_reported": dt.chip_ns as f64 / 1e6 / steps,
"launches": dt.launches as f64 / steps},
diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega.rs b/crates/aien-inference-abi/src/qwen3_moe_omega.rs
index 8ffa23ac ..5f79f893 100644
--- a/crates/aien-inference-abi/src/qwen3_moe_omega.rs
+++ b/crates/aien-inference-abi/src/qwen3_moe_omega.rs
@@ -28,6 +28,8 @@ use rayon::prelude::*;
use crate::moe_plan::MoeBatchPlan;
use crate::qwen3_moe::{bf16_to_f32, f32_to_bf16, fp8_table, shard_path, Shard, FP8_BLOCK};
use crate::resident::transpose_bf16_for_upload;
+/// Expert Ribbon: FP8 experts paged from the NVMe into GPU slots (aienix#4, sc#632).
+pub mod ribbon;
pub mod w8a8_control;
mod whole_prompt;
@@ -1074,6 +1076,8 @@ pub enum ExpertWeights {
gate_up: Arc<dyn Fp8Gemv>,
down: Arc<dyn Fp8Gemv>,
},
+ /// FP8 experts paged from the NVMe into GPU slots (Expert Ribbon); one pool shared by all layers.
+ Paged(Arc<ribbon::PagedExperts>),
}
/// The whole model: resident matmuls on the device, bf16 embedding and f32 norms/routers on the host.
@@ -1219,6 +1223,65 @@ pub fn load_qwen3_moe_omega_from_paths(
format: WeightFormat,
paths: DevicePaths,
progress: &mut dyn FnMut(&str),
+) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
+ load_from_inner(config, source, uploader, format, paths, None, progress)
+}
+
+/// As [`load_qwen3_moe_omega_from_paths`] with the experts paged (Expert Ribbon): no expert bytes are read
+/// or uploaded; every layer gets [`ExpertWeights::Paged`] over the one shared slot pool. Needs FP8 experts.
+pub fn load_qwen3_moe_omega_paged_from(
+ config: &Qwen3MoeConfig,
+ source: &mut dyn TensorSource,
+ uploader: &dyn ModelUploader,
+ format: WeightFormat,
+ paths: DevicePaths,
+ paged: Arc<ribbon::PagedExperts>,
+ progress: &mut dyn FnMut(&str),
+) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
+ if !format.fp8_experts() {
+ return Err("paged experts need FP8 experts (--weights fp8-experts or fp8)".into());
+ }
+ load_from_inner(
+ config,
+ source,
+ uploader,
+ format,
+ paths,
+ Some(paged),
+ progress,
+ )
+}
+
+/// As [`load_qwen3_moe_omega_paged_from`] from a checkpoint directory.
+pub fn load_qwen3_moe_omega_paged(
+ dir: &Path,
+ uploader: &dyn ModelUploader,
+ format: WeightFormat,
+ paths: DevicePaths,
+ paged: Arc<ribbon::PagedExperts>,
+ progress: &mut dyn FnMut(&str),
+) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
+ let config = Qwen3MoeConfig::from_checkpoint(dir)?;
+ let mut source = ShardSource::open(dir)?;
+ load_qwen3_moe_omega_paged_from(
+ &config,
+ &mut source,
+ uploader,
+ format,
+ paths,
+ paged,
+ progress,
+ )
+}
+
+fn load_from_inner(
+ config: &Qwen3MoeConfig,
+ source: &mut dyn TensorSource,
+ uploader: &dyn ModelUploader,
+ format: WeightFormat,
+ paths: DevicePaths,
+ paged: Option<Arc<ribbon::PagedExperts>>,
+ progress: &mut dyn FnMut(&str),
) -> Result<(Qwen3MoeOmegaWeights, LoadReport), String> {
config.validate()?;
let device_router: Option<Arc<dyn DeviceRouter>> = if paths.router == PathChoice::Host {
@@ -1247,10 +1310,18 @@ pub fn load_qwen3_moe_omega_from_paths(
let qkv_n = config.qkv_n();
// Transient host buffers, sized once for the largest use and reused for every layer.
- let mut bits: Vec<u16> = vec![0; h * config.gate_up_n().max(qkv_n).max(qd)];
- let mut fp8: Vec<u8> = vec![0; (e * 2 * i * h).max(qd * h + 2 * kvd * h)];
+ let gu_cols = if paged.is_some() {
+ 0
+ } else {
+ config.gate_up_n()
+ };
+ let mut bits: Vec<u16> = vec![0; h * gu_cols.max(qkv_n).max(qd)];
+ // Paged experts never pass through these buffers: size them for attention only.
+ let ex_bytes = if paged.is_some() { 0 } else { e * 2 * i * h };
+ let ex_scales = if paged.is_some() { 0 } else { e * 2 * ib * kb };
+ let mut fp8: Vec<u8> = vec![0; ex_bytes.max(qd * h + 2 * kvd * h)];
let mut scales: Vec<u16> =
- vec![0; (e * 2 * ib * kb).max((qd / FP8_BLOCK + 2 * (kvd / FP8_BLOCK)) * kb)];
+ vec![0; ex_scales.max((qd / FP8_BLOCK + 2 * (kvd / FP8_BLOCK)) * kb)];
let mut small: Vec<u8> = Vec::new();
let read_bf16_f32 = |source: &mut dyn TensorSource,
@@ -1365,104 +1436,112 @@ pub fn load_qwen3_moe_omega_from_paths(
};
progress(&format!("{p}.self_attn.o_proj"));
- // --- experts gate|up: per expert gate [i][h] then up [i][h]; columns e*2i (gate), e*2i+i (up) ---
- let gu_n = config.gate_up_n();
- for ex in 0..e {
- for (j, proj) in ["gate_proj", "up_proj"].into_iter().enumerate() {
- let w0 = (ex * 2 + j) * i * h;
- let s0 = (ex * 2 + j) * ib * kb;
- let base = format!("{p}.mlp.experts.{ex}.{proj}");
+ // Expert Ribbon: no expert bytes are read here; the pager reads them on first use.
+ let experts = if let Some(pe) = &paged {
+ progress(&format!("{p}.mlp.experts paged"));
+ ExpertWeights::Paged(pe.clone())
+ } else {
+ // --- experts gate|up: per expert gate [i][h] then up [i][h]; columns e*2i (gate), e*2i+i (up) ---
+ let gu_n = config.gate_up_n();
+ for ex in 0..e {
+ for (j, proj) in ["gate_proj", "up_proj"].into_iter().enumerate() {
+ let w0 = (ex * 2 + j) * i * h;
+ let s0 = (ex * 2 + j) * ib * kb;
+ let base = format!("{p}.mlp.experts.{ex}.{proj}");
+ source.read_into(
+ &format!("{base}.weight"),
+ "F8_E4M3",
+ &[i, h],
+ &mut fp8[w0..w0 + i * h],
+ )?;
+ read_scales(
+ source,
+ &format!("{base}.weight_scale_inv"),
+ &[ib, kb],
+ &mut scales[s0..s0 + ib * kb],
+ )?;
+ }
+ }
+ let sources: Vec<Fp8Source> = (0..e)
+ .flat_map(|ex| (0..2).map(move |j| (ex, j)))
+ .map(|(ex, j)| {
+ let w0 = (ex * 2 + j) * i * h;
+ let s0 = (ex * 2 + j) * ib * kb;
+ Fp8Source {
+ weights: &fp8[w0..w0 + i * h],
+ scales: &scales[s0..s0 + ib * kb],
+ rows: i,
+ col0: config.gate_up_col0(ex) + j * i,
+ }
+ })
+ .collect();
+ let gate_up_fp8 = if format.fp8_experts() {
+ // [e][2i][h] bytes with scales [e][2ib][kb]: the capsule GATE_UP layout, as the chip wants it.
+ resident += e * 2 * i * h + e * 2 * ib * kb * 4;
+ Some(uploader.upload_fp8(
+ e,
+ 2 * i,
+ h,
+ &fp8[..e * 2 * i * h],
+ &scales[..e * 2 * ib * kb],
+ )?)
+ } else {
+ None
+ };
+ let gate_up = if gate_up_fp8.is_none() {
+ dequant_fp8_sources_to_bf16_cols(&sources, h, &mut bits[..h * gu_n], gu_n)?;
+ resident += 2 * h * gu_n;
+ Some(uploader.upload_experts(h, gu_n, &bits[..h * gu_n])?)
+ } else {
+ None
+ };
+ progress(&format!("{p}.mlp.experts.gate_up"));
+
+ // --- experts down: per expert [h][i]; columns e*h ---
+ let dn_n = config.down_n();
+ for ex in 0..e {
+ let base = format!("{p}.mlp.experts.{ex}.down_proj");
source.read_into(
&format!("{base}.weight"),
"F8_E4M3",
- &[i, h],
- &mut fp8[w0..w0 + i * h],
+ &[h, i],
+ &mut fp8[ex * h * i..(ex + 1) * h * i],
)?;
read_scales(
source,
&format!("{base}.weight_scale_inv"),
- &[ib, kb],
- &mut scales[s0..s0 + ib * kb],
+ &[kb, ib],
+ &mut scales[ex * kb * ib..(ex + 1) * kb * ib],
)?;
}
- }
- let sources: Vec<Fp8Source> = (0..e)
- .flat_map(|ex| (0..2).map(move |j| (ex, j)))
- .map(|(ex, j)| {
- let w0 = (ex * 2 + j) * i * h;
- let s0 = (ex * 2 + j) * ib * kb;
- Fp8Source {
- weights: &fp8[w0..w0 + i * h],
- scales: &scales[s0..s0 + ib * kb],
- rows: i,
- col0: config.gate_up_col0(ex) + j * i,
+ let sources: Vec<Fp8Source> = (0..e)
+ .map(|ex| Fp8Source {
+ weights: &fp8[ex * h * i..(ex + 1) * h * i],
+ scales: &scales[ex * kb * ib..(ex + 1) * kb * ib],
+ rows: h,
+ col0: config.down_col0(ex),
+ })
+ .collect();
+ let experts = if format.fp8_experts() {
+ resident += e * h * i + e * kb * ib * 4;
+ let down =
+ uploader.upload_fp8(e, h, i, &fp8[..e * h * i], &scales[..e * kb * ib])?;
+ ExpertWeights::Fp8 {
+ gate_up: gate_up_fp8.expect("fp8 gate_up"),
+ down,
}
- })
- .collect();
- let gate_up_fp8 = if format.fp8_experts() {
- // [e][2i][h] bytes with scales [e][2ib][kb]: the capsule GATE_UP layout, as the chip wants it.
- resident += e * 2 * i * h + e * 2 * ib * kb * 4;
- Some(uploader.upload_fp8(
- e,
- 2 * i,
- h,
- &fp8[..e * 2 * i * h],
- &scales[..e * 2 * ib * kb],
- )?)
- } else {
- None
- };
- let gate_up = if gate_up_fp8.is_none() {
- dequant_fp8_sources_to_bf16_cols(&sources, h, &mut bits[..h * gu_n], gu_n)?;
- resident += 2 * h * gu_n;
- Some(uploader.upload_experts(h, gu_n, &bits[..h * gu_n])?)
- } else {
- None
- };
- progress(&format!("{p}.mlp.experts.gate_up"));
-
- // --- experts down: per expert [h][i]; columns e*h ---
- let dn_n = config.down_n();
- for ex in 0..e {
- let base = format!("{p}.mlp.experts.{ex}.down_proj");
- source.read_into(
- &format!("{base}.weight"),
- "F8_E4M3",
- &[h, i],
- &mut fp8[ex * h * i..(ex + 1) * h * i],
- )?;
- read_scales(
- source,
- &format!("{base}.weight_scale_inv"),
- &[kb, ib],
- &mut scales[ex * kb * ib..(ex + 1) * kb * ib],
- )?;
- }
- let sources: Vec<Fp8Source> = (0..e)
- .map(|ex| Fp8Source {
- weights: &fp8[ex * h * i..(ex + 1) * h * i],
- scales: &scales[ex * kb * ib..(ex + 1) * kb * ib],
- rows: h,
- col0: config.down_col0(ex),
- })
- .collect();
- let experts = if format.fp8_experts() {
- resident += e * h * i + e * kb * ib * 4;
- let down = uploader.upload_fp8(e, h, i, &fp8[..e * h * i], &scales[..e * kb * ib])?;
- ExpertWeights::Fp8 {
- gate_up: gate_up_fp8.expect("fp8 gate_up"),
- down,
- }
- } else {
- dequant_fp8_sources_to_bf16_cols(&sources, i, &mut bits[..i * dn_n], dn_n)?;
- resident += 2 * i * dn_n;
- let down = uploader.upload_experts(i, dn_n, &bits[..i * dn_n])?;
- ExpertWeights::Bf16 {
- gate_up: gate_up.expect("bf16 gate_up"),
- down,
- }
+ } else {
+ dequant_fp8_sources_to_bf16_cols(&sources, i, &mut bits[..i * dn_n], dn_n)?;
+ resident += 2 * i * dn_n;
+ let down = uploader.upload_experts(i, dn_n, &bits[..i * dn_n])?;
+ ExpertWeights::Bf16 {
+ gate_up: gate_up.expect("bf16 gate_up"),
+ down,
+ }
+ };
+ progress(&format!("{p}.mlp.experts.down"));
+ experts
};
- progress(&format!("{p}.mlp.experts.down"));
layers.push(OmegaLayer {
input_norm: read_bf16_f32(
@@ -1495,9 +1574,6 @@ pub fn load_qwen3_moe_omega_from_paths(
});
if let (Some(router), Some(layer)) = (&device_router, layers.last()) {
let li = layers.len() - 1;
- let ExpertWeights::Fp8 { gate_up, down } = &layer.experts else {
- return Err(format!("layer {li}: the device router needs FP8 experts"));
- };
// The router carries the bf16 gate weights; the host copy is an exact widening of them.
let gate_bf16: Vec<u16> = layer
.router
@@ -1507,13 +1583,26 @@ pub fn load_qwen3_moe_omega_from_paths(
router
.set_layer(li, &gate_bf16, &layer.post_norm)
.map_err(|e| format!("router layer {li}: {e}"))?;
- let (mut gu, mut dn) = (Vec::with_capacity(2 * e), Vec::with_capacity(2 * e));
- for ex in 0..e {
- let (w, s) = gate_up.tensor_entry(ex)?;
- gu.extend([w, s]);
- let (w, s) = down.tensor_entry(ex)?;
- dn.extend([w, s]);
- }
+ let (gu, dn) = match &layer.experts {
+ ExpertWeights::Fp8 { gate_up, down } => {
+ let (mut gu, mut dn) = (Vec::with_capacity(2 * e), Vec::with_capacity(2 * e));
+ for ex in 0..e {
+ let (w, s) = gate_up.tensor_entry(ex)?;
+ gu.extend([w, s]);
+ let (w, s) = down.tensor_entry(ex)?;
+ dn.extend([w, s]);
+ }
+ (gu, dn)
+ }
+ // The paged path never reads the router's group tables (ribbon.rs).
+ ExpertWeights::Paged(_) => (
+ ribbon::directory_placeholder(e),
+ ribbon::directory_placeholder(e),
+ ),
+ ExpertWeights::Bf16 { .. } => {
+ return Err(format!("layer {li}: the device router needs FP8 experts"))
+ }
+ };
router
.set_directory(li, &gu, &dn)
.map_err(|e| format!("router directory layer {li}: {e}"))?;
@@ -1935,11 +2024,16 @@ pub(crate) mod test_support {
}
fn set_directory(&self, layer: usize, gu: &[u64], dn: &[u64]) -> Result<(), String> {
assert_eq!((gu.len(), dn.len()), (2 * self.experts, 2 * self.experts));
- // tensor_entry of expert x is (x + 1, 0): the directory must list them in order.
- assert!(gu
- .chunks(2)
- .enumerate()
- .all(|(x, p)| p == [x as u64 + 1, 0]));
+ // tensor_entry of expert x is (x + 1, 0): the directory must list them in order. A paged
+ // load (Expert Ribbon) sets the fixed placeholder instead: its tables are never read.
+ let placeholder = super::ribbon::directory_placeholder(self.experts);
+ assert!(
+ (gu == placeholder.as_slice() && dn == placeholder.as_slice())
+ || gu
+ .chunks(2)
+ .enumerate()
+ .all(|(x, p)| p == [x as u64 + 1, 0])
+ );
self.directories.lock().unwrap().push(layer);
Ok(())
}
@@ -3188,6 +3282,9 @@ pub struct StepTiming {
pub graph_launches: u64,
pub graph_submits: u64,
pub graph_record_ns: u64,
+ /// Expert Ribbon only (inside `experts_ns`): wall time pinning the top-k in slots, misses read
+ /// from the NVMe and loaded included.
+ pub page_ns: u64,
}
impl StepTiming {
@@ -3196,6 +3293,7 @@ impl StepTiming {
self.graph_launches += o.graph_launches;
self.graph_submits += o.graph_submits;
self.graph_record_ns += o.graph_record_ns;
+ self.page_ns += o.page_ns;
self.route_ns += o.route_ns;
self.moe_host_ns += o.moe_host_ns;
self.total_ns += o.total_ns;
@@ -3840,12 +3938,30 @@ impl Qwen3MoeOmegaEngine {
attn: AttnPath,
paths: DevicePaths,
progress: &mut dyn FnMut(&str),
+ ) -> Result<(Self, LoadReport), String> {
+ Self::load_omega_experts(dir, max_context, format, attn, paths, None, progress)
+ }
+
+ /// As [`Self::load_omega_paths`] with the experts paged into GPU slots (Expert Ribbon) when
+ /// `paged` is given: no expert bytes are read at load, every expert comes from the pager.
+ pub fn load_omega_experts(
+ dir: &Path,
+ max_context: usize,
+ format: WeightFormat,
+ attn: AttnPath,
+ paths: DevicePaths,
+ paged: Option<Arc<ribbon::PagedExperts>>,
+ progress: &mut dyn FnMut(&str),
) -> Result<(Self, LoadReport), String> {
if !aien_omega_gpu::is_native() {
return Err("this binary carries the CPU stub of the Omega engine (build with AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB)".into());
}
- let (weights, report) =
- load_qwen3_moe_omega_paths(dir, &OmegaModelUploader, format, paths, progress)?;
+ let (weights, report) = match paged {
+ None => load_qwen3_moe_omega_paths(dir, &OmegaModelUploader, format, paths, progress)?,
+ Some(p) => {
+ load_qwen3_moe_omega_paged(dir, &OmegaModelUploader, format, paths, p, progress)?
+ }
+ };
let geometry = KvGeometry::from(&weights.config);
let fused = match attn {
AttnPath::Split => false,
@@ -4105,7 +4221,7 @@ impl Qwen3MoeOmegaEngine {
// group table on the chip: no host RMSNorm, router matmul, top-k or table build.
// The host routing mutant (a host-side swap of the chosen ids) needs the host path.
let device_router = match (&self.weights.device_router, &layer.experts) {
- (Some(r), ExpertWeights::Fp8 { .. })
+ (Some(r), ExpertWeights::Fp8 { .. } | ExpertWeights::Paged(_))
if self.device_routing && !self.routing_mutant =>
{
Some(r)
@@ -4211,6 +4327,42 @@ impl Qwen3MoeOmegaEngine {
}
timing.host_ns += th.elapsed().as_nanos() as u64;
}
+ // --- Expert Ribbon: pin the top-k in GPU slots (misses paged in), two grouped launches ---
+ ExpertWeights::Paged(paged) => {
+ // With the device router the resident path reads the router's normed row on the
+ // chip; read the same row back (exact: see ribbon.rs). Host routing already has it.
+ let row: &[f32] = match (device_router, addrs.is_some()) {
+ (Some(router), true) => {
+ if post_device.is_empty() {
+ post_device = vec![0.0f32; h];
+ router.read_post(&mut post_device).map_err(|e| {
+ format!("layer {layer_idx} router readback: {e}")
+ })?;
+ }
+ &post_device
+ }
+ _ => &post,
+ };
+ let f = paged.ffn(
+ layer_idx,
+ &experts,
+ row,
+ &mut gu_out,
+ &mut act_all,
+ &mut down_all,
+ )?;
+ timing.chip_ns += f.chip_ns;
+ timing.host_ns += f.host_ns;
+ timing.launches += f.launches;
+ timing.page_ns += f.page_ns;
+ let th = Instant::now();
+ for (slot, &w) in topk_weights.iter().enumerate() {
+ for (m, d) in moe_out.iter_mut().zip(&down_all[slot * h..(slot + 1) * h]) {
+ *m += w * d;
+ }
+ }
+ timing.host_ns += th.elapsed().as_nanos() as u64;
+ }
}
for (xi, m) in x.iter_mut().zip(&moe_out) {
*xi += m;
diff --git a/crates/aien-inference-abi/src/qwen3_moe_omega/ribbon.rs b/crates/aien-inference-abi/src/qwen3_moe_omega/ribbon.rs
new file mode 100644
index 00000000 ..7ae4b976
--- /dev/null
+++ b/crates/aien-inference-abi/src/qwen3_moe_omega/ribbon.rs
@@ -0,0 +1,650 @@
+//! Expert Ribbon in the OWN-30B engine (aienix#4, sc#632): FP8 experts paged from the NVMe into a
+//! fixed pool of GPU slots instead of all 6144 experts resident.
+//!
+//! Per layer and token, [`PagedExperts::ffn`] takes the router's exact top-k, pins those experts in
+//! slots through the [`ExpertPager`] (hits pin; misses are read from the checkpoint, BLAKE3-verified,
+//! split into the chip layout and loaded into a free slot), runs one gate|up and one down grouped
+//! launch over the pinned (slot, version) pairs (`omega_gpu_fp8_slots_gemv_grouped_f32`, the same
+//! kernel as the resident tensor) and releases the pins. Nothing is substituted: a miss that cannot be
+//! served fails the step.
+//!
+//! Exactness against the resident path: the activation row is the same bits. With the device router
+//! the resident path reads the router's normed row on the chip (`grouped_dev`); here it is read back
+//! (`read_post`: the router's row times 2^-64) and packed again (times 2^64), both exact powers of two.
+//! The expert bytes and scales are the checkpoint's, as the resident loader uploads them.
+//!
+//! The router still writes its group tables from a directory; the paged path never reads them, so
+//! [`directory_placeholder`] fills the directory with fixed non-zero words (the router refuses zero
+//! words). A device-side slot table that would let the router address slots directly is P3, not here.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use aien_heartbeat::reader::ReadStats;
+use aien_heartbeat::{
+ ExpertId, ExpertPager, ExpertParts, ExpertShape, Manifest, PagerStats, ReadAdapter, ReadConfig,
+ ResidencyStats, ShardDevice, SlotBackend, SlotVersion,
+};
+
+/// One pool of FP8 slots of a single projection shape `[n][k]` (gate|up or down).
+pub trait SlotGemv: Send + Sync + std::fmt::Debug {
+ fn slots(&self) -> usize;
+ fn n(&self) -> usize;
+ fn k(&self) -> usize;
+ /// Copies one expert projection into `slot` and returns its new version. Refused while pinned.
+ fn load(&self, slot: u32, key: u64, w: &[u8], scales: &[u16]) -> Result<u64, String>;
+ /// One grouped launch over `(slots[g], versions[g])`; `x` is one shared row or one row per group.
+ /// Returns the chip-reported kernel ns.
+ fn grouped(
+ &self,
+ slots: &[u32],
+ versions: &[u64],
+ x: &[f32],
+ y: &mut [f32],
+ ) -> Result<u64, String>;
+}
+
+/// The chip pool (`omega_gpu_fp8_slots`, omega#533).
+#[derive(Debug)]
+pub struct OmegaSlotGemv(aien_omega_fp8::Fp8Slots);
+
+impl OmegaSlotGemv {
+ pub fn alloc(slots: usize, n: usize, k: usize) -> Result<Self, String> {
+ aien_omega_fp8::Fp8Slots::alloc(slots, n, k)
+ .map(Self)
+ .map_err(|e| format!("fp8 slot pool {slots} x [{n}][{k}]: {e}"))
+ }
+ pub fn pool_stats(&self) -> aien_omega_fp8::SlotPoolStats {
+ self.0.stats()
+ }
+ /// Device bytes of one slot (weights + f32 scales).
+ pub fn slot_bytes(&self) -> usize {
+ self.0.slot_bytes()
+ }
+}
+
+impl SlotGemv for OmegaSlotGemv {
+ fn slots(&self) -> usize {
+ self.0.slots()
+ }
+ fn n(&self) -> usize {
+ self.0.n()
+ }
+ fn k(&self) -> usize {
+ self.0.k()
+ }
+ fn load(&self, slot: u32, key: u64, w: &[u8], scales: &[u16]) -> Result<u64, String> {
+ self.0
+ .load(slot as usize, key, w, scales)
+ .map_err(|e| e.to_string())
+ }
+ fn grouped(
+ &self,
+ slots: &[u32],
+ versions: &[u64],
+ x: &[f32],
+ y: &mut [f32],
+ ) -> Result<u64, String> {
+ self.0
+ .grouped_f32(slots, versions, x, y)
+ .map(|i| i.elapsed_ns)
+ .map_err(|e| e.to_string())
+ }
+}
+
+/// Content key of one projection of one expert in a slot (omega records it with the slot).
+pub fn slot_key(id: ExpertId, down: bool) -> u64 {
+ ((id.0 as u64) << 17) | ((id.1 as u64) << 1) | down as u64
+}
+
+/// The two pools as the pager's slot pair: slot `s` of gate|up and slot `s` of down hold one expert.
+#[derive(Debug)]
+struct SlotPair {
+ gate_up: Arc<dyn SlotGemv>,
+ down: Arc<dyn SlotGemv>,
+}
+
+impl SlotBackend for SlotPair {
+ fn slots(&self) -> usize {
+ self.gate_up.slots()
+ }
+ fn load(
+ &self,
+ slot: u32,
+ id: ExpertId,
+ parts: &ExpertParts<'_>,
+ ) -> Result<SlotVersion, String> {
+ let gate_up = self.gate_up.load(
+ slot,
+ slot_key(id, false),
+ &parts.gate_up_w,
+ &parts.gate_up_s,
+ )?;
+ let down = self
+ .down
+ .load(slot, slot_key(id, true), &parts.down_w, &parts.down_s)?;
+ Ok(SlotVersion { gate_up, down })
+ }
+}
+
+/// Where one paged FFN call spent its time.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct FfnTiming {
+ /// Wall time in `ensure` (hits are near zero; misses read, verify and load).
+ pub page_ns: u64,
+ pub chip_ns: u64,
+ pub host_ns: u64,
+ pub launches: u64,
+}
+
+/// The paged expert weights of every layer: one slot pool pair shared by all layers.
+pub struct PagedExperts {
+ pager: ExpertPager,
+ gate_up: Arc<dyn SlotGemv>,
+ down: Arc<dyn SlotGemv>,
+ inter: usize,
+ hidden: usize,
+}
+
+impl std::fmt::Debug for PagedExperts {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "PagedExperts {{ slots: {}, resident: {}, gate_up: {:?}, down: {:?} }}",
+ self.pager.capacity(),
+ self.pager.resident(),
+ self.gate_up,
+ self.down
+ )
+ }
+}
+
+/// Fixed non-zero directory words for the router in paged mode (never dereferenced: see the module doc).
+pub fn directory_placeholder(experts: usize) -> Vec<u64> {
+ (0..2 * experts as u64)
+ .map(|j| 0xDEAD_0000_0000_0000 | (j + 1))
+ .collect()
+}
+
+impl PagedExperts {
+ /// `manifest` must describe the same checkpoint the rest of the model is loaded from; every
+ /// expert's layout is checked against `hidden` x `inter` here.
+ pub fn new(
+ manifest: Arc<Manifest>,
+ hidden: usize,
+ inter: usize,
+ dev: Arc<dyn ShardDevice>,
+ read: ReadConfig,
+ gate_up: Arc<dyn SlotGemv>,
+ down: Arc<dyn SlotGemv>,
+ read_deadline: Duration,
+ ) -> Result<Self, String> {
+ if gate_up.slots() != down.slots() || gate_up.slots() == 0 {
+ return Err(format!(
+ "slot pools differ or are empty: gate|up {} slots, down {}",
+ gate_up.slots(),
+ down.slots()
+ ));
+ }
+ if (gate_up.n(), gate_up.k()) != (2 * inter, hidden)
+ || (down.n(), down.k()) != (hidden, inter)
+ {
+ return Err(format!(
+ "slot shapes gate|up [{}][{}] down [{}][{}] do not fit hidden {hidden} inter {inter}",
+ gate_up.n(),
+ gate_up.k(),
+ down.n(),
+ down.k()
+ ));
+ }
+ let reader = ReadAdapter::new(manifest.clone(), dev, read);
+ let backend = Arc::new(SlotPair {
+ gate_up: gate_up.clone(),
+ down: down.clone(),
+ });
+ let shape = ExpertShape {
+ hidden: hidden as u64,
+ inter: inter as u64,
+ };
+ let pager = ExpertPager::new(manifest, shape, reader, backend, read_deadline)
+ .map_err(|e| e.to_string())?;
+ Ok(Self {
+ pager,
+ gate_up,
+ down,
+ inter,
+ hidden,
+ })
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.pager.capacity()
+ }
+ pub fn resident(&self) -> usize {
+ self.pager.resident()
+ }
+ pub fn pinned(&self) -> u32 {
+ self.pager.pinned()
+ }
+ pub fn stats(&self) -> PagerStats {
+ self.pager.stats()
+ }
+ pub fn residency_stats(&self) -> ResidencyStats {
+ self.pager.residency_stats()
+ }
+ pub fn read_stats(&self) -> ReadStats {
+ self.pager.read_stats()
+ }
+ pub fn manifest(&self) -> &Manifest {
+ self.pager.manifest()
+ }
+
+ /// The expert FFN of one token in one layer: `gu_out = gate|up(x)`, SwiGLU into `act_all`,
+ /// `down_all = down(act_all)`, one row per expert in router order. The combine stays with the caller.
+ pub fn ffn(
+ &self,
+ layer: usize,
+ experts: &[u32],
+ x: &[f32],
+ gu_out: &mut [f32],
+ act_all: &mut [f32],
+ down_all: &mut [f32],
+ ) -> Result<FfnTiming, String> {
+ let (i, h, k) = (self.inter, self.hidden, experts.len());
+ if x.len() != h
+ || gu_out.len() < k * 2 * i
+ || act_all.len() < k * i
+ || down_all.len() < k * h
+ {
+ return Err(format!(
+ "paged ffn layer {layer}: buffer sizes do not fit {k} experts"
+ ));
+ }
+ let ids: Vec<u16> = experts
+ .iter()
+ .map(|&e| u16::try_from(e).map_err(|_| format!("expert id {e}")))
+ .collect::<Result<_, _>>()?;
+ let layer16 = u16::try_from(layer).map_err(|_| format!("layer {layer}"))?;
+ let mut t = FfnTiming::default();
+ let t0 = Instant::now();
+ let pinned = self
+ .pager
+ .ensure(layer16, &ids)
+ .map_err(|e| format!("layer {layer} expert pager: {e}"))?;
+ t.page_ns = t0.elapsed().as_nanos() as u64;
+ // The pins are dropped on every exit from here on.
+ struct Release<'a>(&'a ExpertPager, &'a aien_heartbeat::Pinned);
+ impl Drop for Release<'_> {
+ fn drop(&mut self) {
+ self.0.release(self.1);
+ }
+ }
+ let _release = Release(&self.pager, &pinned);
+ let gu_ver: Vec<u64> = pinned.versions.iter().map(|v| v.gate_up).collect();
+ let dn_ver: Vec<u64> = pinned.versions.iter().map(|v| v.down).collect();
+ t.chip_ns += self
+ .gate_up
+ .grouped(&pinned.slots, &gu_ver, x, &mut gu_out[..k * 2 * i])
+ .map_err(|e| format!("layer {layer} gate_up slots: {e}"))?;
+ t.launches += 1;
+ let th = Instant::now();
+ for g in 0..k {
+ super::swiglu(
+ &gu_out[g * 2 * i..(g + 1) * 2 * i],
+ i,
+ &mut act_all[g * i..(g + 1) * i],
+ );
+ }
+ t.host_ns += th.elapsed().as_nanos() as u64;
+ t.chip_ns += self
+ .down
+ .grouped(
+ &pinned.slots,
+ &dn_ver,
+ &act_all[..k * i],
+ &mut down_all[..k * h],
+ )
+ .map_err(|e| format!("layer {layer} down slots: {e}"))?;
+ t.launches += 1;
+ Ok(t)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ //! Paged vs resident on the tiny in-memory model, with host fakes for the slot pools: the same
+ //! logits bit for bit at every position, at the smallest capacity (top_k slots: every layer
+ //! evicts) and with room for everything; a corrupted slot load changes them (the check has teeth);
+ //! a capacity below top_k fails the step instead of computing something else.
+ use super::super::test_support::*;
+ use super::super::*;
+ use super::*;
+ use std::collections::BTreeMap;
+ use std::sync::Mutex;
+
+ /// Host slot pool: the resident host GEMV over `slots` expert-sized regions, with omega's
+ /// version rule (a launch names the version it pinned; a reloaded slot refuses the old one).
+ #[derive(Debug)]
+ struct HostSlots {
+ inner: Mutex<(HostFp8, Vec<u64>, u64)>,
+ corrupt: bool,
+ }
+
+ impl HostSlots {
+ fn new(slots: usize, n: usize, k: usize, corrupt: bool) -> Arc<Self> {
+ let sc = (n / FP8_BLOCK) * (k / FP8_BLOCK);
+ Arc::new(Self {
+ inner: Mutex::new((
+ HostFp8 {
+ experts: slots,
+ n,
+ k,
+ w: vec![0; slots * n * k],
+ scales: vec![0; slots * sc],
+ dev: None,
+ gemm: None,
+ },
+ vec![0; slots],
+ 0,
+ )),
+ corrupt,
+ })
+ }
+ }
+
+ impl SlotGemv for HostSlots {
+ fn slots(&self) -> usize {
+ self.inner.lock().unwrap().1.len()
+ }
+ fn n(&self) -> usize {
+ self.inner.lock().unwrap().0.n
+ }
+ fn k(&self) -> usize {
+ self.inner.lock().unwrap().0.k
+ }
+ fn load(&self, slot: u32, _key: u64, w: &[u8], scales: &[u16]) -> Result<u64, String> {
+ let mut g = self.inner.lock().unwrap();
+ let (n, k) = (g.0.n, g.0.k);
+ let sc = (n / FP8_BLOCK) * (k / FP8_BLOCK);
+ let s = slot as usize;
+ assert_eq!((w.len(), scales.len()), (n * k, sc));
+ g.0.w[s * n * k..(s + 1) * n * k].copy_from_slice(w);
+ if self.corrupt {
+ g.0.w[s * n * k] ^= 0x01;
+ }
+ g.0.scales[s * sc..(s + 1) * sc].copy_from_slice(scales);
+ g.2 += 1;
+ let v = g.2;
+ g.1[s] = v;
+ Ok(v)
+ }
+ fn grouped(
+ &self,
+ slots: &[u32],
+ versions: &[u64],
+ x: &[f32],
+ y: &mut [f32],
+ ) -> Result<u64, String> {
+ let g = self.inner.lock().unwrap();
+ for (&s, &v) in slots.iter().zip(versions) {
+ if g.1[s as usize] != v {
+ return Err(format!(
+ "slot {s}: version {v} is stale (now {})",
+ g.1[s as usize]
+ ));
+ }
+ }
+ g.0.grouped_f32(slots, x, y)
+ }
+ }
+
+ /// The in-memory checkpoint as one safetensors shard + index (F8 tensors first, then BF16, each
+ /// sorted by name, as safetensors groups them), so the manifest and reader see real files.
+ fn write_checkpoint(src: &MemorySource, dir: &std::path::Path) {
+ let mut all: Vec<_> = src.tensors.iter().collect();
+ all.sort_by(|a, b| (a.1 .0 != "F8_E4M3", a.0).cmp(&(b.1 .0 != "F8_E4M3", b.0)));
+ let shard = "model-00001-of-00001.safetensors";
+ let (mut header, mut data, mut map) = (serde_json::Map::new(), Vec::new(), BTreeMap::new());
+ for (name, (dtype, shape, bytes)) in all {
+ let a = data.len();
+ data.extend_from_slice(bytes);
+ header.insert(
+ name.clone(),
+ serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [a, data.len()]}),
+ );
+ map.insert(name.clone(), shard.to_string());
+ }
+ let h = serde_json::to_vec(&header).unwrap();
+ let mut file = (h.len() as u64).to_le_bytes().to_vec();
+ file.extend(&h);
+ file.extend(&data);
+ std::fs::write(dir.join(shard), file).unwrap();
+ std::fs::write(
+ dir.join("model.safetensors.index.json"),
+ serde_json::to_vec(&serde_json::json!({"metadata": {}, "weight_map": map})).unwrap(),
+ )
+ .unwrap();
+ }
+
+ fn tmpdir(tag: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!(
+ "aien-ribbon-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ fn paged_engine(
+ c: &Qwen3MoeConfig,
+ dir: &std::path::Path,
+ slots: usize,
+ fakes: bool,
+ corrupt: bool,
+ ) -> (Qwen3MoeOmegaEngine, Arc<PagedExperts>) {
+ let m = Arc::new(Manifest::build(dir).unwrap());
+ let dev = Arc::new(aien_heartbeat::FileShards::open(&m.shard_paths(), false).unwrap());
+ let (h, i) = (c.hidden, c.moe_intermediate);
+ let paged = Arc::new(
+ PagedExperts::new(
+ m,
+ h,
+ i,
+ dev,
+ ReadConfig {
+ workers: 2,
+ queue_depth: 4,
+ },
+ HostSlots::new(slots, 2 * i, h, corrupt),
+ HostSlots::new(slots, h, i, false),
+ Duration::from_secs(10),
+ )
+ .unwrap(),
+ );
+ let mut src = MemorySource::for_config(c);
+ let up = RecordingUploader {
+ device_fakes: fakes,
+ ..Default::default()
+ };
+ let (w, _) = load_qwen3_moe_omega_paged_from(
+ c,
+ &mut src,
+ &up,
+ WeightFormat::Fp8All,
+ DevicePaths::default(),
+ paged.clone(),
+ &mut |_| {},
+ )
+ .unwrap();
+ assert!(
+ !src.reads.iter().any(|n| n.contains(".mlp.experts.")),
+ "a paged load must not read expert bytes"
+ );
+ let kv = HostKv::new(&KvGeometry::from(c), 32);
+ (Qwen3MoeOmegaEngine::new(w, Box::new(kv)), paged)
+ }
+
+ fn resident_engine(c: &Qwen3MoeConfig, fakes: bool) -> Qwen3MoeOmegaEngine {
+ let mut src = MemorySource::for_config(c);
+ let up = RecordingUploader {
+ device_fakes: fakes,
+ ..Default::default()
+ };
+ let (w, _) = load_qwen3_moe_omega_from_paths(
+ c,
+ &mut src,
+ &up,
+ WeightFormat::Fp8All,
+ DevicePaths::default(),
+ &mut |_| {},
+ )
+ .unwrap();
+ Qwen3MoeOmegaEngine::new(w, Box::new(HostKv::new(&KvGeometry::from(c), 32)))
+ }
+
+ /// Prompt then greedy decode; logits bits at every position.
+ fn run(e: &mut Qwen3MoeOmegaEngine, steps: usize) -> Vec<Vec<u32>> {
+ let mut out = Vec::new();
+ let mut tok = 5u32;
+ for p in 0..steps {
+ let hidden = e.step(if p < 4 { [5, 9, 17, 2][p] } else { tok }).unwrap();
+ let lg = e.logits(&hidden).unwrap();
+ tok = lg
+ .iter()
+ .enumerate()
+ .fold((0, f32::MIN), |b, (j, &v)| if v > b.1 { (j, v) } else { b })
+ .0 as u32;
+ out.push(lg.iter().map(|v| v.to_bits()).collect());
+ }
+ out
+ }
+
+ #[test]
+ fn paged_experts_give_the_resident_logits_bit_for_bit_at_any_capacity() {
+ let c = tiny_config();
+ let dir = tmpdir("parity");
+ write_checkpoint(&MemorySource::for_config(&c), &dir);
+ let all = c.layers * c.experts;
+ for fakes in [false, true] {
+ let want = run(&mut resident_engine(&c, fakes), 10);
+ for slots in [c.top_k, c.top_k + 1, all] {
+ let (mut e, paged) = paged_engine(&c, &dir, slots, fakes, false);
+ let got = run(&mut e, 10);
+ assert_eq!(got, want, "device router {fakes}, {slots} slots");
+ let s = paged.stats();
+ assert_eq!(s.requests, (10 * c.layers) as u64);
+ assert_eq!(
+ s.experts_hit + s.experts_missed,
+ (10 * c.layers * c.top_k) as u64
+ );
+ assert!(
+ s.experts_missed >= (c.layers * c.top_k) as u64,
+ "the first token misses everything"
+ );
+ if slots == all {
+ // Room for everything: each expert is read at most once.
+ assert!(s.experts_missed <= all as u64, "{s:?}");
+ } else {
+ assert!(
+ s.experts_missed > all as u64,
+ "smallest pools must evict: {s:?}"
+ );
+ }
+ assert_eq!(paged.pinned(), 0, "every pin released");
+ assert!(e.last_timing.page_ns > 0 || s.experts_missed > 0);
+ }
+ }
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn a_corrupted_slot_load_changes_the_logits_and_too_few_slots_fail_the_step() {
+ let c = tiny_config();
+ let dir = tmpdir("neg");
+ write_checkpoint(&MemorySource::for_config(&c), &dir);
+ let want = run(&mut resident_engine(&c, true), 4);
+ let (mut bad, _) = paged_engine(&c, &dir, c.layers * c.experts, true, true);
+ assert_ne!(
+ run(&mut bad, 4),
+ want,
+ "negative control: one flipped weight byte per load"
+ );
+
+ let (mut small, paged) = paged_engine(&c, &dir, c.top_k - 1, true, false);
+ let err = small.step(5).unwrap_err();
+ assert!(err.contains("pinned or loading"), "{err}");
+ assert_eq!(paged.pinned(), 0, "a failed step leaves nothing pinned");
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
+
+/// What [`open_omega`] needs: the checkpoint's expert manifest, the slot count and the read queue.
+#[derive(Debug, Clone)]
+pub struct RibbonOptions {
+ /// Saved manifest (built from the checkpoint and saved here when missing or for another model).
+ pub manifest: std::path::PathBuf,
+ pub slots: usize,
+ pub read: ReadConfig,
+ /// O_DIRECT reads (the SSD figure); false reads through the page cache.
+ pub direct: bool,
+ pub read_deadline: Duration,
+}
+
+/// The chip slot pools for a checkpoint: gate|up `[2i][h]` and down `[h][i]`, `slots` each.
+/// Every expert read is BLAKE3-checked against the manifest, so a stale manifest fails closed.
+pub fn open_omega(
+ dir: &std::path::Path,
+ hidden: usize,
+ inter: usize,
+ o: &RibbonOptions,
+ progress: &mut dyn FnMut(&str),
+) -> Result<Arc<PagedExperts>, String> {
+ let m = match Manifest::load(&o.manifest) {
+ Ok(m) if m.model_dir == dir => m,
+ _ => {
+ let t = Instant::now();
+ let m = Manifest::build(dir).map_err(|e| format!("expert manifest: {e}"))?;
+ m.save(&o.manifest)
+ .map_err(|e| format!("save manifest {}: {e}", o.manifest.display()))?;
+ progress(&format!(
+ "ribbon manifest built in {:.1} s ({} experts)",
+ t.elapsed().as_secs_f64(),
+ m.experts.len()
+ ));
+ m
+ }
+ };
+ progress(&format!(
+ "ribbon manifest {} experts, model digest {}",
+ m.experts.len(),
+ m.model_digest
+ ));
+ let m = Arc::new(m);
+ let dev = Arc::new(
+ aien_heartbeat::FileShards::open(&m.shard_paths(), o.direct)
+ .map_err(|e| format!("open shards: {e}"))?,
+ );
+ let gate_up = Arc::new(OmegaSlotGemv::alloc(o.slots, 2 * inter, hidden)?);
+ let down = Arc::new(OmegaSlotGemv::alloc(o.slots, hidden, inter)?);
+ progress(&format!(
+ "ribbon slots {} x {} B = {} B device",
+ o.slots,
+ gate_up.slot_bytes() + down.slot_bytes(),
+ o.slots * (gate_up.slot_bytes() + down.slot_bytes())
+ ));
+ PagedExperts::new(
+ m,
+ hidden,
+ inter,
+ dev,
+ o.read,
+ gate_up,
+ down,
+ o.read_deadline,
+ )
+ .map(Arc::new)
+}
diff --git a/crates/aien-omega-fp8/build.rs b/crates/aien-omega-fp8/build.rs
index 3fe1c955 ..5c1d492a 100644
--- a/crates/aien-omega-fp8/build.rs
+++ b/crates/aien-omega-fp8/build.rs
@@ -7,6 +7,9 @@
//! `omega_gpu_fp8_gemv_grouped_f32` defined in that archive.
//! * `AIEN_OMEGA_DIR=<checkout>`: native when the checkout has `src/omega_gpu_fp8_api.h`.
//!
+//! `cfg(has_omega_fp8_slots)` (Expert Ribbon slot pools, omega#533) is set when the archive defines
+//! `omega_gpu_fp8_slots_alloc` or the checkout has `src/omega_gpu_fp8_slots.h`.
+//!
//! `cfg(has_omega_fp8gemm)` (the prefill grouped GEMM) is set when the archive defines
//! `omega_gpu_fp8gemm_f32` or the checkout has `src/omega_gpu_fp8gemm_api.h`.
//! * otherwise: stub (every call returns `Unavailable`).
@@ -20,6 +23,7 @@ fn main() {
println!("cargo:rustc-check-cfg=cfg(has_omega_fp8)");
println!("cargo:rustc-check-cfg=cfg(has_omega_fp8_dev)");
println!("cargo:rustc-check-cfg=cfg(has_omega_fp8gemm)");
+ println!("cargo:rustc-check-cfg=cfg(has_omega_fp8_slots)");
for v in [
"AIEN_FORCE_CPU_STUB",
"AIEN_OMEGA_GPU_LIB",
@@ -42,6 +46,9 @@ fn main() {
if archive_defines(Path::new(&lib), "omega_gpu_fp8gemm_f32") {
println!("cargo:rustc-cfg=has_omega_fp8gemm");
}
+ if archive_defines(Path::new(&lib), "omega_gpu_fp8_slots_alloc") {
+ println!("cargo:rustc-cfg=has_omega_fp8_slots");
+ }
} else {
println!("cargo:warning=aien-omega-fp8: {lib} does not define the FP8 GEMV API; FP8 calls are stubbed");
}
@@ -64,6 +71,9 @@ fn main() {
{
println!("cargo:rustc-cfg=has_omega_fp8gemm");
}
+ if Path::new(&dir).join("src/omega_gpu_fp8_slots.h").is_file() {
+ println!("cargo:rustc-cfg=has_omega_fp8_slots");
+ }
} else {
println!("cargo:warning=aien-omega-fp8: {dir} has no src/omega_gpu_fp8_api.h (omega before OWN-30B cut 5); FP8 calls are stubbed");
}
diff --git a/crates/aien-omega-fp8/src/lib.rs b/crates/aien-omega-fp8/src/lib.rs
index a27c2b74 ..d15b1ba2 100644
--- a/crates/aien-omega-fp8/src/lib.rs
+++ b/crates/aien-omega-fp8/src/lib.rs
@@ -769,3 +769,297 @@ mod tests {
assert_eq!(std::mem::offset_of!(GemmInfo, kernel_cache_hit), 76);
}
}
+
+// ---------------------------------------------------------------------------------------------
+// Expert Ribbon (aienix#4, omega#533): versioned replaceable FP8 expert slots.
+// ---------------------------------------------------------------------------------------------
+
+#[cfg(has_omega_fp8_slots)]
+mod slots_ffi {
+ use super::Fp8Info;
+ #[repr(C)]
+ pub struct OmegaGpuFp8Slots {
+ _private: [u8; 0],
+ }
+ #[repr(C)]
+ #[derive(Default, Debug, Clone, Copy)]
+ pub struct OmegaGpuFp8SlotsStats {
+ pub slots: u32,
+ pub n: u32,
+ pub k: u32,
+ pub device_bytes: u64,
+ pub loads: u64,
+ pub load_failures: u64,
+ pub busy_refusals: u64,
+ pub stale_refusals: u64,
+ pub evictions: u64,
+ pub pins: u64,
+ pub pinned_now: u32,
+ pub pinned_high: u32,
+ pub bytes_loaded: u64,
+ pub load_ns: u64,
+ }
+ extern "C" {
+ pub fn omega_gpu_fp8_slots_alloc(
+ slots: u32,
+ n: u32,
+ k: u32,
+ out: *mut *mut OmegaGpuFp8Slots,
+ ) -> i32;
+ pub fn omega_gpu_fp8_slots_free(p: *mut OmegaGpuFp8Slots) -> i32;
+ pub fn omega_gpu_fp8_slots_load(
+ p: *mut OmegaGpuFp8Slots,
+ slot: u32,
+ key: u64,
+ w: *const u8,
+ scale_inv_bf16: *const u16,
+ version: *mut u64,
+ ) -> i32;
+ pub fn omega_gpu_fp8_slots_gemv_grouped_f32(
+ p: *mut OmegaGpuFp8Slots,
+ groups: u32,
+ slots: *const u32,
+ versions: *const u64,
+ x: *const f32,
+ x_rows: u32,
+ y: *mut f32,
+ info: *mut Fp8Info,
+ ) -> i32;
+ pub fn omega_gpu_fp8_slots_stats(p: *mut OmegaGpuFp8Slots, out: *mut OmegaGpuFp8SlotsStats);
+ pub fn omega_gpu_fp8_slots_rc_name(rc: i32) -> *const std::os::raw::c_char;
+ }
+}
+
+/// Counters of one slot pool (omega `OmegaGpuFp8SlotsStats`).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct SlotPoolStats {
+ pub slots: u32,
+ pub device_bytes: u64,
+ pub loads: u64,
+ pub load_failures: u64,
+ pub busy_refusals: u64,
+ pub stale_refusals: u64,
+ pub pins: u64,
+ pub pinned_now: u32,
+ pub pinned_high: u32,
+ pub bytes_loaded: u64,
+ pub load_ns: u64,
+}
+
+/// A pool of `slots` versioned FP8 expert slots of one shape `[n][k]` (omega_gpu_fp8_slots.h): GPU-uncached,
+/// refilled while the model runs. `load` hides the slot, copies and publishes a fresh version; it is refused
+/// while a launch reads the slot. `grouped_f32` pins the given (slot, version) pairs for exactly its launch.
+/// Thread-safe in omega (pool mutex; launches take the session lock), so `Sync`.
+pub struct Fp8Slots {
+ #[cfg(has_omega_fp8_slots)]
+ ptr: *mut slots_ffi::OmegaGpuFp8Slots,
+ slots: usize,
+ n: usize,
+ k: usize,
+}
+
+// SAFETY: the omega pool serialises its own state (pthread mutex) and launches take the session lock.
+unsafe impl Send for Fp8Slots {}
+unsafe impl Sync for Fp8Slots {}
+
+impl fmt::Debug for Fp8Slots {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ f,
+ "Fp8Slots {{ slots: {}, n: {}, k: {} }}",
+ self.slots, self.n, self.k
+ )
+ }
+}
+
+#[cfg(has_omega_fp8_slots)]
+fn slots_err(rc: i32) -> OmegaGpuError {
+ // SAFETY: static NUL-terminated strings (last_error may be NULL).
+ let name = unsafe {
+ let n = slots_ffi::omega_gpu_fp8_slots_rc_name(rc);
+ let n = if n.is_null() {
+ String::from("?")
+ } else {
+ std::ffi::CStr::from_ptr(n).to_string_lossy().into_owned()
+ };
+ let e = ffi::omega_gpu_fp8_last_error();
+ if e.is_null() || rc == -6 || rc == -7 {
+ n
+ } else {
+ format!("{n}: {}", std::ffi::CStr::from_ptr(e).to_string_lossy())
+ }
+ };
+ OmegaGpuError::Rc { rc, name }
+}
+
+/// Whether this binary carries the slot pool API.
+pub fn slots_native() -> bool {
+ cfg!(has_omega_fp8_slots)
+}
+
+impl Fp8Slots {
+ pub fn alloc(slots: usize, n: usize, k: usize) -> Result<Self, OmegaGpuError> {
+ check_shape(slots, n, k)?;
+ #[cfg(has_omega_fp8_slots)]
+ {
+ let mut ptr = std::ptr::null_mut();
+ // SAFETY: shape checked; omega writes the handle or leaves it NULL.
+ let rc = unsafe {
+ slots_ffi::omega_gpu_fp8_slots_alloc(slots as u32, n as u32, k as u32, &mut ptr)
+ };
+ if rc != 0 || ptr.is_null() {
+ return Err(slots_err(rc));
+ }
+ Ok(Self { ptr, slots, n, k })
+ }
+ #[cfg(not(has_omega_fp8_slots))]
+ {
+ let _ = (slots, n, k);
+ Err(OmegaGpuError::Unavailable)
+ }
+ }
+
+ pub fn slots(&self) -> usize {
+ self.slots
+ }
+ pub fn n(&self) -> usize {
+ self.n
+ }
+ pub fn k(&self) -> usize {
+ self.k
+ }
+ /// Device bytes per slot (weights + f32 scales).
+ pub fn slot_bytes(&self) -> usize {
+ self.n * self.k + (self.n / BLOCK) * (self.k / BLOCK) * 4
+ }
+
+ /// Load one expert projection into `slot`; returns the published version.
+ pub fn load(
+ &self,
+ slot: usize,
+ key: u64,
+ w: &[u8],
+ scale_inv_bf16: &[u16],
+ ) -> Result<u64, OmegaGpuError> {
+ check_len("fp8 slot weight bytes", self.n * self.k, w.len())?;
+ check_len(
+ "fp8 slot scale words",
+ (self.n / BLOCK) * (self.k / BLOCK),
+ scale_inv_bf16.len(),
+ )?;
+ if slot >= self.slots {
+ return Err(bad(format!("slot {slot} of {}", self.slots)));
+ }
+ #[cfg(has_omega_fp8_slots)]
+ {
+ let mut v = 0u64;
+ // SAFETY: lengths checked; omega copies before returning.
+ let rc = unsafe {
+ slots_ffi::omega_gpu_fp8_slots_load(
+ self.ptr,
+ slot as u32,
+ key,
+ w.as_ptr(),
+ scale_inv_bf16.as_ptr(),
+ &mut v,
+ )
+ };
+ if rc != 0 {
+ return Err(slots_err(rc));
+ }
+ Ok(v)
+ }
+ #[cfg(not(has_omega_fp8_slots))]
+ {
+ let _ = key;
+ Err(OmegaGpuError::Unavailable)
+ }
+ }
+
+ /// One grouped launch over (slot, version) pairs, pinned for the launch (`x`: `k` values shared, or
+ /// `slots.len() * k`, one row per group). Returns the chip info.
+ pub fn grouped_f32(
+ &self,
+ slots: &[u32],
+ versions: &[u64],
+ x: &[f32],
+ y: &mut [f32],
+ ) -> Result<Fp8Info, OmegaGpuError> {
+ let g = slots.len();
+ check_len("fp8 slot versions", g, versions.len())?;
+ if g == 0 || g > MAX_GROUPS {
+ return Err(bad(format!("fp8 slot groups {g} (1..={MAX_GROUPS})")));
+ }
+ let x_rows = if x.len() == self.k {
+ 1
+ } else {
+ check_len("fp8 slot x", g * self.k, x.len())?;
+ g
+ };
+ check_len("fp8 slot y", g * self.n, y.len())?;
+ #[cfg(has_omega_fp8_slots)]
+ {
+ let mut info = Fp8Info::default();
+ // SAFETY: lengths checked above; omega pins, launches, waits for the marker, unpins.
+ let rc = unsafe {
+ slots_ffi::omega_gpu_fp8_slots_gemv_grouped_f32(
+ self.ptr,
+ g as u32,
+ slots.as_ptr(),
+ versions.as_ptr(),
+ x.as_ptr(),
+ x_rows as u32,
+ y.as_mut_ptr(),
+ &mut info,
+ )
+ };
+ if rc != 0 {
+ return Err(slots_err(rc));
+ }
+ Ok(info)
+ }
+ #[cfg(not(has_omega_fp8_slots))]
+ {
+ let _ = x_rows;
+ Err(OmegaGpuError::Unavailable)
+ }
+ }
+
+ pub fn stats(&self) -> SlotPoolStats {
+ #[cfg(has_omega_fp8_slots)]
+ {
+ let mut s = slots_ffi::OmegaGpuFp8SlotsStats::default();
+ // SAFETY: valid handle, plain C struct out.
+ unsafe { slots_ffi::omega_gpu_fp8_slots_stats(self.ptr, &mut s) };
+ SlotPoolStats {
+ slots: s.slots,
+ device_bytes: s.device_bytes,
+ loads: s.loads,
+ load_failures: s.load_failures,
+ busy_refusals: s.busy_refusals,
+ stale_refusals: s.stale_refusals,
+ pins: s.pins,
+ pinned_now: s.pinned_now,
+ pinned_high: s.pinned_high,
+ bytes_loaded: s.bytes_loaded,
+ load_ns: s.load_ns,
+ }
+ }
+ #[cfg(not(has_omega_fp8_slots))]
+ {
+ SlotPoolStats::default()
+ }
+ }
+}
+
+impl Drop for Fp8Slots {
+ fn drop(&mut self) {
+ #[cfg(has_omega_fp8_slots)]
+ {
+ // SAFETY: owned handle. BUSY means a launch still pins a slot, which cannot happen here (launches
+ // are synchronous and borrow &self); the pool is then leaked rather than freed under a reader.
+ let rc = unsafe { slots_ffi::omega_gpu_fp8_slots_free(self.ptr) };
+ debug_assert_eq!(rc, 0, "slot pool freed while pinned");
+ }
+ }
+}
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/NOTES.md b/docs/inference/evidence/ribbon-paged-20261018T1719Z/NOTES.md
new file mode 100644
index 00000000 ..bdf4eca0
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/NOTES.md
@@ -0,0 +1,42 @@
+# Expert Ribbon: OWN-30B decode with paged FP8 experts (2026-10-18)
+
+sc ribbon/p1-store 79e46d77 + omega 1549caae (omega 4799f9eb + the slot pool, omega#533; slot chip gate PASS 3/3
+on this base). Model Qwen3-30B-A3B-Instruct-2507-FP8, 6,144 experts, model digest 57e416ad49 ...
+Flags as the resident gate in own30b-omega4799-20261015 , tokens only: `--weights fp8 --attn fused --router device
+--lm-head gemv --prefill auto --new 16`, plus `--paged-experts SLOTS` (`run.sh`). The live aien-serve-http and CI jobs
+shared the chip and memory during both runs. Prefill runs token by token in paged mode (batched prefill and the
+decode graph need resident experts and refuse a paged load).
+
+## Tokens: identical to the CPU golden at both capacities
+
+| Run | Slots (of 6,144) | Prompts | Tokens vs golden | Weights resident | Peak RSS |
+|---|---|---|---|---|---|
+| s768-p12 | 768 (1/8) | p1, p2 | IDENTICAL x2 | 1.53 GB + 3.62 GB slots | 6.94 GB |
+| s3072-p1234 | 3072 (1/2) | p1, p2, p3, p4 | IDENTICAL x4 | 1.53 GB + 14.5 GB slots | 17.82 GB |
+
+The resident run of the same flags matched the same golden (own30b-omega4799-20261015 , tokens IDENTICAL x4).
+Host tests prove the paged path gives the resident logits bit for bit on the tiny model
+(`cargo test -p aien-inference-abi --lib ribbon`).
+
+## Speed (decode, 16 tokens)
+
+| Run | Prompt | Hit rate (whole prompt) | Decode tok/s | Page time per decode step | Receipt |
+|---|---|---|---|---|---|
+| 768 slots | p1 (cold) | 0.60 | 2.396 | 388.5 ms | calc:eac8a69d |
+| 3072 slots | p1 (cold) | 0.68 | 2.738 | 336.5 ms | calc:440646a6 |
+| 3072 slots | p4 (warm, after 657 prompt tokens) | 0.96 | 7.07 | 112.2 ms | calc:59123200 |
+
+- Ceiling: every expert of every token missed, read at the measured random verified rate 10.60 GB/s
+ (calc:8d297d5b ): 5.849 tok/s (calc:1fc0715c ). Cold 768-slot decode is 0.41 of it (calc:3bf87234 ); warm 3072-slot
+ decode is 1.21 times it (calc:d185ac62 ), because hits skip the SSD.
+- The SSD is not the limit yet: during misses the device delivered 1.715 GB/s (768 slots, p1, calc:ff9762d7 ) and
+ 0.729 GB/s (3072 slots, p4, calc:2f952a9d ) of the 10.60 GB/s it gives a full queue. Misses are read layer by
+ layer (a layer's misses in parallel, the next layer only after the router picks), so paging waits on read latency
+ (about 3.5 ms per expert at queue depth 1, read-bench.jsonl). Overlap and prefetch (sc#631) is the next step.
+- Resident decode speed under the same load was NOT MEASURED in this session: a resident load needs about 31.5 GB
+ and own30b_check's 70 GB gate refused to share the box with the live server; it was not overridden.
+
+## Read adapter (ribbon_read_bench, random whole experts, O_DIRECT, BLAKE3-verified, 3,000 reads)
+
+1 worker depth 1: 1.32 GB/s (calc:b43572b8 ); 8/16: 8.69 GB/s (calc:84b90d97 ); 16/32: 10.60 GB/s (calc:8d297d5b ),
+0.673 of the PCIe Gen5 x4 link (calc:cf3a961c ). Raw JSON in read-bench.jsonl.
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/binary.sha256 b/docs/inference/evidence/ribbon-paged-20261018T1719Z/binary.sha256
new file mode 100644
index 00000000 ..531ec839
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/binary.sha256
@@ -0,0 +1 @@
+20b4465b30626a374f6ad6c70361e87d1614f61278c4dcc372736035b4b910fd
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/read-bench.jsonl b/docs/inference/evidence/ribbon-paged-20261018T1719Z/read-bench.jsonl
new file mode 100644
index 00000000 ..332c7d62
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/read-bench.jsonl
@@ -0,0 +1,3 @@
+{"depth":16,"device_GBps":8.708568122249922 ,"device_bytes":14182019072 ,"digest_worker_s":7.889717213 ,"direct":true,"latency_ms":{"max":15.471307999999999 ,"mean":8.664574630666678 ,"p50":8.552819999999999 ,"p95":10.728074000000001 },"model_digest":"57e416ad499a06d6b63edfc849a9363f7d983e8fad9eed3d6aaeb791e0fe6885 ","payload_GBps":8.693514470618938 ,"payload_bytes":14157504000 ,"read_worker_s":5.109837988 ,"reads":3000,"seed":2026,"tool":"ribbon_read_bench","wall_s":1.628513307 ,"workers":8}
+{"depth":32,"device_GBps":10.618523967988583 ,"device_bytes":14182019072 ,"digest_worker_s":9.669338542 ,"direct":true,"latency_ms":{"max":21.319856,"mean":14.180576624999997 ,"p50":14.146612,"p95":16.580270000000002 },"model_digest":"57e416ad499a06d6b63edfc849a9363f7d983e8fad9eed3d6aaeb791e0fe6885 ","payload_GBps":10.600168762126328 ,"payload_bytes":14157504000 ,"read_worker_s":11.617293559 ,"reads":3000,"seed":2026,"tool":"ribbon_read_bench","wall_s":1.335592321 ,"workers":16}
+{"depth":1,"device_GBps":1.3258201959215046 ,"device_bytes":14182019072 ,"digest_worker_s":7.073243358 ,"direct":true,"latency_ms":{"max":6.239868,"mean":3.5634329086666625 ,"p50":3.529868,"p95":3.963508},"model_digest":"57e416ad499a06d6b63edfc849a9363f7d983e8fad9eed3d6aaeb791e0fe6885 ","payload_GBps":1.323528379968003 ,"payload_bytes":14157504000 ,"read_worker_s":3.103852454 ,"reads":3000,"seed":2026,"tool":"ribbon_read_bench","wall_s":10.696789139 ,"workers":1}
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/run.sh b/docs/inference/evidence/ribbon-paged-20261018T1719Z/run.sh
new file mode 100755
index 00000000 ..0f22004b
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/run.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# run.sh NAME SLOTS PROMPTS : one paged OWN-30B tokens run under the GB10 lock (quietlock check first).
+set -u
+EV=$(cd "$(dirname "$0")" && pwd); NAME=$1; SLOTS=$2; PROMPTS=$3
+B=$HOME/workspace/targets/ribbon-sc/release/own30b_check
+CK=$HOME/models/qwen3-30b-a3b-instruct-2507-fp8
+G=$HOME/workspace/sc-408/docs/inference/evidence/own30b-f-20261013T1745Z/golden.json
+quietlock check || { echo "quiet flag raised: not running" > "$EV/$NAME.rc"; exit 3; }
+{ echo "queued $(date -u +%FT%TZ) sc $(git -C "$EV" rev-parse HEAD) omega $(cat "$EV/../../../../omega.lock")"
+ echo "binary sha256 $(sha256sum "$B" | cut -d' ' -f1)"; uptime; free -g | head -2; } > "$EV/$NAME.start"
+flock /tmp/aien-gb10.lock sh -c 'echo "lock acquired $(date -u +%FT%TZ)" >> "$0"; shift; exec "$@"' "$EV/$NAME.start" x \
+ env AIEN_OMEGA_SPIN_US=2000 "$B" chip "$CK" "$G" "$EV/$NAME" --tokens-only --prompts "$PROMPTS" --new 16 \
+ --weights fp8 --attn fused --router device --lm-head gemv --prefill auto --paged-experts "$SLOTS" \
+ > "$EV/$NAME.raw" 2> "$EV/$NAME.err"
+echo $? > "$EV/$NAME.rc"; date -u +%FT%TZ > "$EV/$NAME.end"
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.end b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.end
new file mode 100644
index 00000000 ..43a5bca7
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.end
@@ -0,0 +1 @@
+2026-10-18T17:23:54Z
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.err b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.err
new file mode 100644
index 00000000 ..c3fbfb4d
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.err
@@ -0,0 +1,11 @@
+ ribbon manifest 6144 experts, model digest 57e416ad499a06d6b63edfc849a9363f7d983e8fad9eed3d6aaeb791e0fe6885
+ ribbon slots 3072 x 4719744 B = 14499053568 B device
+ [2s] model.layers.6.self_attn.o_proj
+ [2s] model.layers.13.self_attn.qkv
+ [2s] model.layers.19.mlp.experts paged
+ [2s] model.layers.26.self_attn.o_proj
+ [2s] model.layers.33.self_attn.qkv
+ [2s] model.layers.39.mlp.experts paged
+ [2s] model.layers.46.self_attn.o_proj
+ [3s] lm_head
+ [3s] kv fused cache 768 MB resident=true
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.raw b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.raw
new file mode 100644
index 00000000 ..ab8ffd30
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.raw
@@ -0,0 +1,32 @@
+mem available before load: 48.2 GB
+RIBBON: 3072 slots, pools 14.50 GB; memory gate 20.5 GB
+engine native=true window_api=true fp8_api=true dattn_api=true weights=Fp8All attn=Fused spin_us=Some(2000) cta_budget=Some(64)
+prefill path gemv routing host (gemm_api=true)
+attention path fused prefill_chunk 8 batched_prefill_possible false
+router path device lm_head path gemv (router_api=true bf16_api=true)
+decode graph OFF (dgraph_api=true, OWN30B_DECODE_GRAPH=1 to turn on) mutant none
+whole-prompt prefill OFF device router/combine OFF
+LOAD: 1.4s resident 1.53 GB host 0.67 GB peak_rss 17.62 GB (before 14.75 GB) kv_resident=true mem_available_after 32.1 GB
+LOAD peak over resident+host: 15.42 GB (budget 6 GB) -> FAIL
+TOKENS p1-one-token: 1 prompt tokens, prefill 0.56s (557.0 ms/token; chunk 8, per token attention 10.8 ms experts 546.1 ms host 1.2 ms launches 288.0), decode 16 tokens in 5844 ms = 365.2 ms/token = 2.7 tok/s; per step: attention 9.3 ms experts 352.0 ms lm_head 3.6 ms host 1.0 ms chip-reported 24.5 ms launches 271; IDENTICAL
+ DECODE GRAPH OFF: 0 of 16 decode steps as one list (the first step is the prefill's lm_head); per step launches 271.0 submits 271.0; per graph token launches 0.0 submits 0.0 record 0.0 us
+ RIBBON 3072 slots: experts hit 4182 miss 1962 (hit rate 0.6807); loaded 9259007616 B; miss wall 5906.2 ms; per decode step page 336.46 ms; prefill page 528.1 ms; summed read wait 13263.5 ms; summed slot load 4329.6 ms; device read 9275092992 B; resident 1962
+ chip text: " and welcome to the 2024-25 season of the National"
+ cpu text: " and welcome to the 2024-25 season of the National"
+TOKENS p2-short: 20 prompt tokens, prefill 5.19s (259.6 ms/token; chunk 8, per token attention 9.9 ms experts 249.5 ms host 1.2 ms launches 288.0), decode 7 tokens in 1542 ms = 220.3 ms/token = 4.5 tok/s; per step: attention 10.0 ms experts 206.3 ms lm_head 3.6 ms host 1.4 ms chip-reported 26.0 ms launches 289.14285714285717 ; IDENTICAL
+ DECODE GRAPH OFF: 0 of 7 decode steps as one list (the first step is the prefill's lm_head); per step launches 289.1 submits 289.1; per graph token launches 0.0 submits 0.0 record 0.0 us
+ RIBBON 3072 slots: experts hit 8918 miss 1450 (hit rate 0.8601); loaded 6842793600 B; miss wall 5979.2 ms; per decode step page 189.80 ms; prefill page 4661.2 ms; summed read wait 7475.5 ms; summed slot load 3123.4 ms; device read 6854583440 B; resident 3072
+ chip text: "The capital of France is Paris."
+ cpu text: "The capital of France is Paris.<|im_end|>"
+TOKENS p3-medium: 204 prompt tokens, prefill 23.74s (116.4 ms/token; chunk 8, per token attention 11.2 ms experts 105.1 ms host 1.4 ms launches 283.8), decode 16 tokens in 3138 ms = 196.1 ms/token = 5.1 tok/s; per step: attention 10.4 ms experts 182.2 ms lm_head 3.1 ms host 1.1 ms chip-reported 25.2 ms launches 271; IDENTICAL
+ DECODE GRAPH OFF: 0 of 16 decode steps as one list (the first step is the prefill's lm_head); per step launches 271.0 submits 271.0; per graph token launches 0.0 submits 0.0 record 0.0 us
+ RIBBON 3072 slots: experts hit 79811 miss 3133 (hit rate 0.9622); loaded 14785153344 B; miss wall 20518.6 ms; per decode step page 166.92 ms; prefill page 17925.0 ms; summed read wait 21224.3 ms; summed slot load 7458.1 ms; device read 14810735760 B; resident 3072
+ chip text: "- The DGX Spark uses the GB10 Grace Blackwell superchip,"
+ cpu text: "- The DGX Spark uses the GB10 Grace Blackwell superchip,"
+TOKENS p4-long: 657 prompt tokens, prefill 76.74s (116.8 ms/token; chunk 8, per token attention 11.3 ms experts 105.3 ms host 1.1 ms launches 286.7), decode 16 tokens in 2263 ms = 141.4 ms/token = 7.1 tok/s; per step: attention 10.8 ms experts 127.2 ms lm_head 3.1 ms host 1.1 ms chip-reported 25.5 ms launches 271; IDENTICAL
+ DECODE GRAPH OFF: 0 of 16 decode steps as one list (the first step is the prefill's lm_head); per step launches 271.0 submits 271.0; per graph token launches 0.0 submits 0.0 record 0.0 us
+ RIBBON 3072 slots: experts hit 247590 miss 9306 (hit rate 0.9638); loaded 43916577408 B; miss wall 60363.6 ms; per decode step page 112.20 ms; prefill page 58726.2 ms; summed read wait 55679.9 ms; summed slot load 20735.7 ms; device read 43992697120 B; resident 3072
+ chip text: "What went wrong: \nIn **run 10**, the model's output"
+ cpu text: "What went wrong: \nIn **run 10**, the model's output"
+SUMMARY parity=PASS tokens=PASS peak_rss=17.82 GB
+receipt: /home/drakestapleton/workspace/ribbon-sc/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.rc b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.rc
new file mode 100644
index 00000000 ..573541ac
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.rc
@@ -0,0 +1 @@
+0
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.start b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.start
new file mode 100644
index 00000000 ..ffa03752
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234.start
@@ -0,0 +1,6 @@
+queued 2026-10-18T17:21:34Z sc 79e46d77ee7217515b9b1ec7bd9832919c39c1dd omega 1549caaedfd73d7d885eab4363ab4fd36eb16feb
+binary sha256 20b4465b30626a374f6ad6c70361e87d1614f61278c4dcc372736035b4b910fd
+ 12:21:34 up 7:29, 9 users, load average: 8.27, 7.88, 9.73
+ total used free shared buff/cache available
+Mem: 121 72 14 6 46 48
+lock acquired 2026-10-18T17:21:51Z
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234/run.json b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234/run.json
new file mode 100644
index 00000000 ..bc8cd83d
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s3072-p1234/run.json
@@ -0,0 +1,325 @@
+{
+ "checkpoint": "/home/drakestapleton/models/qwen3-30b-a3b-instruct-2507-fp8",
+ "controls": [],
+ "engine": {
+ "attention": "fused",
+ "bf16_api": true,
+ "cta_budget": 64,
+ "dattn_api": true,
+ "fp8_api": true,
+ "kv_resident": true,
+ "lm_head": "gemv",
+ "max_context": 8192,
+ "native": true,
+ "prefill_chunk": 8,
+ "prefill_path": "gemv",
+ "prefill_routing": "host",
+ "router": "device",
+ "router_api": true,
+ "spin_us": 2000,
+ "weights": "Fp8All",
+ "window_api": true
+ },
+ "golden": "/home/drakestapleton/workspace/sc-408/docs/inference/evidence/own30b-f-20261013T1745Z/golden.json",
+ "load": {
+ "host_bytes": 673505280 ,
+ "peak_rss_before_bytes": 14746312704 ,
+ "peak_rss_bytes": 17619107840 ,
+ "resident_bytes": 1528520704 ,
+ "seconds": 1.40426899 ,
+ "transient_gb": 15.417081856000001
+ },
+ "long_prompt": null,
+ "parity": [],
+ "pass": true,
+ "prefill": null,
+ "prompts": [
+ {
+ "chip": [
+ 323,
+ 10565,
+ 311,
+ 279,
+ 220,
+ 17,
+ 15,
+ 17,
+ 19,
+ 12,
+ 17,
+ 20,
+ 3200,
+ 315,
+ 279,
+ 5055
+ ],
+ "decode_graph": {
+ "graph_launches": 0,
+ "graph_record_ns": 0,
+ "graph_submits": 0,
+ "graph_tokens": 0,
+ "mutant": "none",
+ "on": false,
+ "submits": 4336,
+ "timeline": null
+ },
+ "decode_ms": 5844,
+ "emitted": 16,
+ "first_diff": null,
+ "golden": [
+ 323,
+ 10565,
+ 311,
+ 279,
+ 220,
+ 17,
+ 15,
+ 17,
+ 19,
+ 12,
+ 17,
+ 20,
+ 3200,
+ 315,
+ 279,
+ 5055
+ ],
+ "name": "p1-one-token",
+ "per_step_ms": {
+ "attention": 9.3292460625 ,
+ "chip_reported": 24.450390375 ,
+ "experts": 351.992626625 ,
+ "host": 1.0376580625 ,
+ "launches": 271.0,
+ "lm_head": 3.5873094375
+ },
+ "prefill_ms": 557,
+ "prompt_tokens": 1,
+ "ribbon": {
+ "bytes_loaded": 9259007616 ,
+ "decode_page_ns": 5383413306 ,
+ "decode_steps": 16,
+ "device_read_bytes": 9275092992 ,
+ "hit": 4182,
+ "miss": 1962,
+ "miss_wall_ns": 5906160175 ,
+ "prefill_page_ns": 528085723 ,
+ "read_wait_ns": 13263461077 ,
+ "slot_load_ns": 4329622441 ,
+ "slots": 3072
+ },
+ "tok_s": 2.737850787132101
+ },
+ {
+ "chip": [
+ 785,
+ 6722,
+ 315,
+ 9625,
+ 374,
+ 12095,
+ 13
+ ],
+ "decode_graph": {
+ "graph_launches": 0,
+ "graph_record_ns": 0,
+ "graph_submits": 0,
+ "graph_tokens": 0,
+ "mutant": "none",
+ "on": false,
+ "submits": 2024,
+ "timeline": null
+ },
+ "decode_ms": 1542,
+ "emitted": 7,
+ "first_diff": null,
+ "golden": [
+ 785,
+ 6722,
+ 315,
+ 9625,
+ 374,
+ 12095,
+ 13,
+ 151645
+ ],
+ "name": "p2-short",
+ "per_step_ms": {
+ "attention": 10.040865857142858 ,
+ "chip_reported": 25.96933142857143 ,
+ "experts": 206.27539842857144 ,
+ "host": 1.3653612857142858 ,
+ "launches": 289.14285714285717 ,
+ "lm_head": 3.572241857142857
+ },
+ "prefill_ms": 5191,
+ "prompt_tokens": 20,
+ "ribbon": {
+ "bytes_loaded": 6842793600 ,
+ "decode_page_ns": 1328620379 ,
+ "decode_steps": 7,
+ "device_read_bytes": 6854583440 ,
+ "hit": 8918,
+ "miss": 1450,
+ "miss_wall_ns": 5979181328 ,
+ "prefill_page_ns": 4661241495 ,
+ "read_wait_ns": 7475488738 ,
+ "slot_load_ns": 3123384450 ,
+ "slots": 3072
+ },
+ "tok_s": 4.539559014267185
+ },
+ {
+ "chip": [
+ 12,
+ 576,
+ 50275,
+ 55,
+ 26467,
+ 5711,
+ 279,
+ 18865,
+ 16,
+ 15,
+ 31071,
+ 5235,
+ 9157,
+ 2256,
+ 29662,
+ 11
+ ],
+ "decode_graph": {
+ "graph_launches": 0,
+ "graph_record_ns": 0,
+ "graph_submits": 0,
+ "graph_tokens": 0,
+ "mutant": "none",
+ "on": false,
+ "submits": 4336,
+ "timeline": null
+ },
+ "decode_ms": 3138,
+ "emitted": 16,
+ "first_diff": null,
+ "golden": [
+ 12,
+ 576,
+ 50275,
+ 55,
+ 26467,
+ 5711,
+ 279,
+ 18865,
+ 16,
+ 15,
+ 31071,
+ 5235,
+ 9157,
+ 2256,
+ 29662,
+ 11
+ ],
+ "name": "p3-medium",
+ "per_step_ms": {
+ "attention": 10.426308,
+ "chip_reported": 25.2269181875 ,
+ "experts": 182.199620625 ,
+ "host": 1.147312875 ,
+ "launches": 271.0,
+ "lm_head": 3.098443125
+ },
+ "prefill_ms": 23744,
+ "prompt_tokens": 204,
+ "ribbon": {
+ "bytes_loaded": 14785153344 ,
+ "decode_page_ns": 2670672336 ,
+ "decode_steps": 16,
+ "device_read_bytes": 14810735760 ,
+ "hit": 79811,
+ "miss": 3133,
+ "miss_wall_ns": 20518604199 ,
+ "prefill_page_ns": 17924981539 ,
+ "read_wait_ns": 21224253403 ,
+ "slot_load_ns": 7458093664 ,
+ "slots": 3072
+ },
+ "tok_s": 5.098789037603569
+ },
+ {
+ "chip": [
+ 3838,
+ 3937,
+ 4969,
+ 25,
+ 2303,
+ 641,
+ 3070,
+ 6108,
+ 220,
+ 16,
+ 15,
+ 97219,
+ 279,
+ 1614,
+ 594,
+ 2550
+ ],
+ "decode_graph": {
+ "graph_launches": 0,
+ "graph_record_ns": 0,
+ "graph_submits": 0,
+ "graph_tokens": 0,
+ "mutant": "none",
+ "on": false,
+ "submits": 4336,
+ "timeline": null
+ },
+ "decode_ms": 2263,
+ "emitted": 16,
+ "first_diff": null,
+ "golden": [
+ 3838,
+ 3937,
+ 4969,
+ 25,
+ 2303,
+ 641,
+ 3070,
+ 6108,
+ 220,
+ 16,
+ 15,
+ 97219,
+ 279,
+ 1614,
+ 594,
+ 2550
+ ],
+ "name": "p4-long",
+ "per_step_ms": {
+ "attention": 10.7919954375 ,
+ "chip_reported": 25.4705513125 ,
+ "experts": 127.2035771875 ,
+ "host": 1.10738925 ,
+ "launches": 271.0,
+ "lm_head": 3.075953
+ },
+ "prefill_ms": 76744,
+ "prompt_tokens": 657,
+ "ribbon": {
+ "bytes_loaded": 43916577408 ,
+ "decode_page_ns": 1795163681 ,
+ "decode_steps": 16,
+ "device_read_bytes": 43992697120 ,
+ "hit": 247590,
+ "miss": 9306,
+ "miss_wall_ns": 60363591759 ,
+ "prefill_page_ns": 58726179382 ,
+ "read_wait_ns": 55679926681 ,
+ "slot_load_ns": 20735702999 ,
+ "slots": 3072
+ },
+ "tok_s": 7.070260715863897
+ }
+ ]
+}
\ No newline at end of file
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.end b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.end
new file mode 100644
index 00000000 ..3c048ef3
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.end
@@ -0,0 +1 @@
+2026-10-18T17:21:24Z
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.err b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.err
new file mode 100644
index 00000000 ..a6c0acb3
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.err
@@ -0,0 +1,12 @@
+ ribbon manifest built in 51.8 s (6144 experts)
+ ribbon manifest 6144 experts, model digest 57e416ad499a06d6b63edfc849a9363f7d983e8fad9eed3d6aaeb791e0fe6885
+ ribbon slots 768 x 4719744 B = 3624763392 B device
+ [53s] model.layers.6.self_attn.o_proj
+ [53s] model.layers.13.self_attn.qkv
+ [53s] model.layers.19.mlp.experts paged
+ [53s] model.layers.26.self_attn.o_proj
+ [54s] model.layers.33.self_attn.qkv
+ [54s] model.layers.39.mlp.experts paged
+ [54s] model.layers.46.self_attn.o_proj
+ [55s] lm_head
+ [56s] kv fused cache 768 MB resident=true
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.raw b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.raw
new file mode 100644
index 00000000 ..b8cbd61d
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.raw
@@ -0,0 +1,22 @@
+mem available before load: 48.5 GB
+RIBBON: 768 slots, pools 3.62 GB; memory gate 9.6 GB
+engine native=true window_api=true fp8_api=true dattn_api=true weights=Fp8All attn=Fused spin_us=Some(2000) cta_budget=Some(64)
+prefill path gemv routing host (gemm_api=true)
+attention path fused prefill_chunk 8 batched_prefill_possible false
+router path device lm_head path gemv (router_api=true bf16_api=true)
+decode graph OFF (dgraph_api=true, OWN30B_DECODE_GRAPH=1 to turn on) mutant none
+whole-prompt prefill OFF device router/combine OFF
+LOAD: 3.6s resident 1.53 GB host 0.67 GB peak_rss 6.74 GB (before 3.88 GB) kv_resident=true mem_available_after 41.6 GB
+LOAD peak over resident+host: 4.54 GB (budget 6 GB) -> PASS
+TOKENS p1-one-token: 1 prompt tokens, prefill 0.60s (604.0 ms/token; chunk 8, per token attention 11.5 ms experts 592.7 ms host 1.3 ms launches 288.0), decode 16 tokens in 6677 ms = 417.3 ms/token = 2.4 tok/s; per step: attention 9.0 ms experts 404.8 ms lm_head 3.1 ms host 1.2 ms chip-reported 24.4 ms launches 271; IDENTICAL
+ DECODE GRAPH OFF: 0 of 16 decode steps as one list (the first step is the prefill's lm_head); per step launches 271.0 submits 271.0; per graph token launches 0.0 submits 0.0 record 0.0 us
+ RIBBON 768 slots: experts hit 3683 miss 2461 (hit rate 0.5994); loaded 11613872448 B; miss wall 6782.3 ms; per decode step page 388.50 ms; prefill page 573.7 ms; summed read wait 15860.6 ms; summed slot load 5751.2 ms; device read 11634057216 B; resident 768
+ chip text: " and welcome to the 2024-25 season of the National"
+ cpu text: " and welcome to the 2024-25 season of the National"
+TOKENS p2-short: 20 prompt tokens, prefill 9.19s (459.4 ms/token; chunk 8, per token attention 9.5 ms experts 449.7 ms host 1.1 ms launches 288.0), decode 7 tokens in 3138 ms = 448.3 ms/token = 2.2 tok/s; per step: attention 9.6 ms experts 434.9 ms lm_head 3.5 ms host 1.1 ms chip-reported 25.9 ms launches 289.14285714285717 ; IDENTICAL
+ DECODE GRAPH OFF: 0 of 7 decode steps as one list (the first step is the prefill's lm_head); per step launches 289.1 submits 289.1; per graph token launches 0.0 submits 0.0 record 0.0 us
+ RIBBON 768 slots: experts hit 4904 miss 5464 (hit rate 0.4730); loaded 25785533952 B; miss wall 11566.0 ms; per decode step page 418.15 ms; prefill page 8652.7 ms; summed read wait 31560.4 ms; summed slot load 11658.3 ms; device read 25830225040 B; resident 768
+ chip text: "The capital of France is Paris."
+ cpu text: "The capital of France is Paris.<|im_end|>"
+SUMMARY parity=PASS tokens=PASS peak_rss=6.94 GB
+receipt: /home/drakestapleton/workspace/ribbon-sc/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.rc b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.rc
new file mode 100644
index 00000000 ..573541ac
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.rc
@@ -0,0 +1 @@
+0
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.start b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.start
new file mode 100644
index 00000000 ..d84da4fe
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12.start
@@ -0,0 +1,6 @@
+queued 2026-10-18T17:20:08Z sc 79e46d77ee7217515b9b1ec7bd9832919c39c1dd omega 1549caaedfd73d7d885eab4363ab4fd36eb16feb
+binary sha256 20b4465b30626a374f6ad6c70361e87d1614f61278c4dcc372736035b4b910fd
+ 12:20:08 up 7:27, 9 users, load average: 6.27, 7.38, 9.76
+ total used free shared buff/cache available
+Mem: 121 73 34 5 24 48
+lock acquired 2026-10-18T17:20:08Z
diff --git a/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12/run.json b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12/run.json
new file mode 100644
index 00000000 ..9c48fb2b
--- /dev/null
+++ b/docs/inference/evidence/ribbon-paged-20261018T1719Z/s768-p12/run.json
@@ -0,0 +1,173 @@
+{
+ "checkpoint": "/home/drakestapleton/models/qwen3-30b-a3b-instruct-2507-fp8",
+ "controls": [],
+ "engine": {
+ "attention": "fused",
+ "bf16_api": true,
+ "cta_budget": 64,
+ "dattn_api": true,
+ "fp8_api": true,
+ "kv_resident": true,
+ "lm_head": "gemv",
+ "max_context": 8192,
+ "native": true,
+ "prefill_chunk": 8,
+ "prefill_path": "gemv",
+ "prefill_routing": "host",
+ "router": "device",
+ "router_api": true,
+ "spin_us": 2000,
+ "weights": "Fp8All",
+ "window_api": true
+ },
+ "golden": "/home/drakestapleton/workspace/sc-408/docs/inference/evidence/own30b-f-20261013T1745Z/golden.json",
+ "load": {
+ "host_bytes": 673505280 ,
+ "peak_rss_before_bytes": 3878871040 ,
+ "peak_rss_bytes": 6741327872 ,
+ "resident_bytes": 1528520704 ,
+ "seconds": 3.611270313 ,
+ "transient_gb": 4.539301888000001
+ },
+ "long_prompt": null,
+ "parity": [],
+ "pass": true,
+ "prefill": null,
+ "prompts": [
+ {
+ "chip": [
+ 323,
+ 10565,
+ 311,
+ 279,
+ 220,
+ 17,
+ 15,
+ 17,
+ 19,
+ 12,
+ 17,
+ 20,
+ 3200,
+ 315,
+ 279,
+ 5055
+ ],
+ "decode_graph": {
+ "graph_launches": 0,
+ "graph_record_ns": 0,
+ "graph_submits": 0,
+ "graph_tokens": 0,
+ "mutant": "none",
+ "on": false,
+ "submits": 4336,
+ "timeline": null
+ },
+ "decode_ms": 6677,
+ "emitted": 16,
+ "first_diff": null,
+ "golden": [
+ 323,
+ 10565,
+ 311,
+ 279,
+ 220,
+ 17,
+ 15,
+ 17,
+ 19,
+ 12,
+ 17,
+ 20,
+ 3200,
+ 315,
+ 279,
+ 5055
+ ],
+ "name": "p1-one-token",
+ "per_step_ms": {
+ "attention": 9.0207946875 ,
+ "chip_reported": 24.4270205 ,
+ "experts": 404.753208875 ,
+ "host": 1.154906125 ,
+ "launches": 271.0,
+ "lm_head": 3.1371196875
+ },
+ "prefill_ms": 604,
+ "prompt_tokens": 1,
+ "ribbon": {
+ "bytes_loaded": 11613872448 ,
+ "decode_page_ns": 6216027937 ,
+ "decode_steps": 16,
+ "device_read_bytes": 11634057216 ,
+ "hit": 3683,
+ "miss": 2461,
+ "miss_wall_ns": 6782268108 ,
+ "prefill_page_ns": 573675877 ,
+ "read_wait_ns": 15860599238 ,
+ "slot_load_ns": 5751169868 ,
+ "slots": 768
+ },
+ "tok_s": 2.3962857570765315
+ },
+ {
+ "chip": [
+ 785,
+ 6722,
+ 315,
+ 9625,
+ 374,
+ 12095,
+ 13
+ ],
+ "decode_graph": {
+ "graph_launches": 0,
+ "graph_record_ns": 0,
+ "graph_submits": 0,
+ "graph_tokens": 0,
+ "mutant": "none",
+ "on": false,
+ "submits": 2024,
+ "timeline": null
+ },
+ "decode_ms": 3138,
+ "emitted": 7,
+ "first_diff": null,
+ "golden": [
+ 785,
+ 6722,
+ 315,
+ 9625,
+ 374,
+ 12095,
+ 13,
+ 151645
+ ],
+ "name": "p2-short",
+ "per_step_ms": {
+ "attention": 9.641969142857144 ,
+ "chip_reported": 25.890115,
+ "experts": 434.8543087142857 ,
+ "host": 1.136105857142857 ,
+ "launches": 289.14285714285717 ,
+ "lm_head": 3.464156
+ },
+ "prefill_ms": 9188,
+ "prompt_tokens": 20,
+ "ribbon": {
+ "bytes_loaded": 25785533952 ,
+ "decode_page_ns": 2927020115 ,
+ "decode_steps": 7,
+ "device_read_bytes": 25830225040 ,
+ "hit": 4904,
+ "miss": 5464,
+ "miss_wall_ns": 11565978831 ,
+ "prefill_page_ns": 8652699632 ,
+ "read_wait_ns": 31560412979 ,
+ "slot_load_ns": 11658324479 ,
+ "slots": 768
+ },
+ "tok_s": 2.2307202039515617
+ }
+ ]
+}
\ No newline at end of file
diff --git a/omega.lock b/omega.lock
index fe479524 ..b6440261 100644
--- a/omega.lock
+++ b/omega.lock
@@ -1 +1 @@
-4799f9eba563e9c69579b47c477e7d9c2b0f15cb
+1549caaedfd73d7d885eab4363ab4fd36eb16feb