aien-sovereign-core-mv
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
aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen3_moe_omega / ribbon.rs
| 1 | //! Expert Ribbon in the OWN-30B engine (aienix#4, sc#632): FP8 experts paged from the NVMe into a |
| 2 | //! fixed pool of GPU slots instead of all 6144 experts resident. |
| 3 | //! |
| 4 | //! Per layer and token, [`PagedExperts::ffn`] takes the router's exact top-k, pins those experts in |
| 5 | //! slots through the [`ExpertPager`] (hits pin; misses are read from the checkpoint, BLAKE3-verified, |
| 6 | //! split into the chip layout and loaded into a free slot), runs one gate|up and one down grouped |
| 7 | //! launch over the pinned (slot, version) pairs (`omega_gpu_fp8_slots_gemv_grouped_f32`, the same |
| 8 | //! kernel as the resident tensor) and releases the pins. Nothing is substituted: a miss that cannot be |
| 9 | //! served fails the step. |
| 10 | //! |
| 11 | //! Exactness against the resident path: the activation row is the same bits. With the device router |
| 12 | //! the resident path reads the router's normed row on the chip (`grouped_dev`); here it is read back |
| 13 | //! (`read_post`: the router's row times 2^-64) and packed again (times 2^64), both exact powers of two. |
| 14 | //! The expert bytes and scales are the checkpoint's, as the resident loader uploads them. |
| 15 | //! |
| 16 | //! The router still writes its group tables from a directory; the paged path never reads them, so |
| 17 | //! [`directory_placeholder`] fills the directory with fixed non-zero words (the router refuses zero |
| 18 | //! words). A device-side slot table that would let the router address slots directly is P3, not here. |
| 19 | |
| 20 | use std::sync::Arc; |
| 21 | use std::time::{Duration, Instant}; |
| 22 | |
| 23 | use aien_heartbeat::reader::ReadStats; |
| 24 | use aien_heartbeat::{ |
| 25 | ExpertId, ExpertPager, ExpertParts, ExpertShape, Manifest, PagerStats, ReadAdapter, ReadConfig, |
| 26 | ResidencyStats, ShardDevice, SlotBackend, SlotVersion, |
| 27 | }; |
| 28 | |
| 29 | /// One pool of FP8 slots of a single projection shape `[n][k]` (gate|up or down). |
| 30 | pub trait SlotGemv: Send + Sync + std::fmt::Debug { |
| 31 | fn slots(&self) -> usize; |
| 32 | fn n(&self) -> usize; |
| 33 | fn k(&self) -> usize; |
| 34 | /// Copies one expert projection into `slot` and returns its new version. Refused while pinned. |
| 35 | fn load(&self, slot: u32, key: u64, w: &[u8], scales: &[u16]) -> Result<u64, String>; |
| 36 | /// One grouped launch over `(slots[g], versions[g])`; `x` is one shared row or one row per group. |
| 37 | /// Returns the chip-reported kernel ns. |
| 38 | fn grouped( |
| 39 | &self, |
| 40 | slots: &[u32], |
| 41 | versions: &[u64], |
| 42 | x: &[f32], |
| 43 | y: &mut [f32], |
| 44 | ) -> Result<u64, String>; |
| 45 | } |
| 46 | |
| 47 | /// The chip pool (`omega_gpu_fp8_slots`, omega#533). |
| 48 | #[derive(Debug)] |
| 49 | pub struct OmegaSlotGemv(aien_omega_fp8::Fp8Slots); |
| 50 | |
| 51 | impl OmegaSlotGemv { |
| 52 | pub fn alloc(slots: usize, n: usize, k: usize) -> Result<Self, String> { |
| 53 | aien_omega_fp8::Fp8Slots::alloc(slots, n, k) |
| 54 | .map(Self) |
| 55 | .map_err(|e| format!("fp8 slot pool {slots} x [{n}][{k}]: {e}")) |
| 56 | } |
| 57 | pub fn pool_stats(&self) -> aien_omega_fp8::SlotPoolStats { |
| 58 | self.0.stats() |
| 59 | } |
| 60 | /// Device bytes of one slot (weights + f32 scales). |
| 61 | pub fn slot_bytes(&self) -> usize { |
| 62 | self.0.slot_bytes() |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl SlotGemv for OmegaSlotGemv { |
| 67 | fn slots(&self) -> usize { |
| 68 | self.0.slots() |
| 69 | } |
| 70 | fn n(&self) -> usize { |
| 71 | self.0.n() |
| 72 | } |
| 73 | fn k(&self) -> usize { |
| 74 | self.0.k() |
| 75 | } |
| 76 | fn load(&self, slot: u32, key: u64, w: &[u8], scales: &[u16]) -> Result<u64, String> { |
| 77 | self.0 |
| 78 | .load(slot as usize, key, w, scales) |
| 79 | .map_err(|e| e.to_string()) |
| 80 | } |
| 81 | fn grouped( |
| 82 | &self, |
| 83 | slots: &[u32], |
| 84 | versions: &[u64], |
| 85 | x: &[f32], |
| 86 | y: &mut [f32], |
| 87 | ) -> Result<u64, String> { |
| 88 | self.0 |
| 89 | .grouped_f32(slots, versions, x, y) |
| 90 | .map(|i| i.elapsed_ns) |
| 91 | .map_err(|e| e.to_string()) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | /// Content key of one projection of one expert in a slot (omega records it with the slot). |
| 96 | pub fn slot_key(id: ExpertId, down: bool) -> u64 { |
| 97 | ((id.0 as u64) << 17) | ((id.1 as u64) << 1) | down as u64 |
| 98 | } |
| 99 | |
| 100 | /// The two pools as the pager's slot pair: slot `s` of gate|up and slot `s` of down hold one expert. |
| 101 | #[derive(Debug)] |
| 102 | struct SlotPair { |
| 103 | gate_up: Arc<dyn SlotGemv>, |
| 104 | down: Arc<dyn SlotGemv>, |
| 105 | } |
| 106 | |
| 107 | impl SlotBackend for SlotPair { |
| 108 | fn slots(&self) -> usize { |
| 109 | self.gate_up.slots() |
| 110 | } |
| 111 | fn load( |
| 112 | &self, |
| 113 | slot: u32, |
| 114 | id: ExpertId, |
| 115 | parts: &ExpertParts<'_>, |
| 116 | ) -> Result<SlotVersion, String> { |
| 117 | let gate_up = self.gate_up.load( |
| 118 | slot, |
| 119 | slot_key(id, false), |
| 120 | &parts.gate_up_w, |
| 121 | &parts.gate_up_s, |
| 122 | )?; |
| 123 | let down = self |
| 124 | .down |
| 125 | .load(slot, slot_key(id, true), &parts.down_w, &parts.down_s)?; |
| 126 | Ok(SlotVersion { gate_up, down }) |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// Where one paged FFN call spent its time. |
| 131 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 132 | pub struct FfnTiming { |
| 133 | /// Wall time in `ensure` (hits are near zero; misses read, verify and load). |
| 134 | pub page_ns: u64, |
| 135 | pub chip_ns: u64, |
| 136 | pub host_ns: u64, |
| 137 | pub launches: u64, |
| 138 | } |
| 139 | |
| 140 | /// The paged expert weights of every layer: one slot pool pair shared by all layers. |
| 141 | pub struct PagedExperts { |
| 142 | pager: ExpertPager, |
| 143 | gate_up: Arc<dyn SlotGemv>, |
| 144 | down: Arc<dyn SlotGemv>, |
| 145 | inter: usize, |
| 146 | hidden: usize, |
| 147 | #[cfg(feature = "ribbon-omega")] |
| 148 | pipeline_buffers: Option<usize>, |
| 149 | } |
| 150 | |
| 151 | impl std::fmt::Debug for PagedExperts { |
| 152 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 153 | write!( |
| 154 | f, |
| 155 | "PagedExperts {{ slots: {}, resident: {}, gate_up: {:?}, down: {:?} }}", |
| 156 | self.pager.capacity(), |
| 157 | self.pager.resident(), |
| 158 | self.gate_up, |
| 159 | self.down |
| 160 | ) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Fixed non-zero directory words for the router in paged mode (never dereferenced: see the module doc). |
| 165 | pub fn directory_placeholder(experts: usize) -> Vec<u64> { |
| 166 | (0..2 * experts as u64) |
| 167 | .map(|j| 0xDEAD_0000_0000_0000 | (j + 1)) |
| 168 | .collect() |
| 169 | } |
| 170 | |
| 171 | impl PagedExperts { |
| 172 | /// `manifest` must describe the same checkpoint the rest of the model is loaded from; every |
| 173 | /// expert's layout is checked against `hidden` x `inter` here. |
| 174 | pub fn new( |
| 175 | manifest: Arc<Manifest>, |
| 176 | hidden: usize, |
| 177 | inter: usize, |
| 178 | dev: Arc<dyn ShardDevice>, |
| 179 | read: ReadConfig, |
| 180 | gate_up: Arc<dyn SlotGemv>, |
| 181 | down: Arc<dyn SlotGemv>, |
| 182 | read_deadline: Duration, |
| 183 | ) -> Result<Self, String> { |
| 184 | if gate_up.slots() != down.slots() || gate_up.slots() == 0 { |
| 185 | return Err(format!( |
| 186 | "slot pools differ or are empty: gate|up {} slots, down {}", |
| 187 | gate_up.slots(), |
| 188 | down.slots() |
| 189 | )); |
| 190 | } |
| 191 | if (gate_up.n(), gate_up.k()) != (2 * inter, hidden) |
| 192 | || (down.n(), down.k()) != (hidden, inter) |
| 193 | { |
| 194 | return Err(format!( |
| 195 | "slot shapes gate|up [{}][{}] down [{}][{}] do not fit hidden {hidden} inter {inter}", |
| 196 | gate_up.n(), |
| 197 | gate_up.k(), |
| 198 | down.n(), |
| 199 | down.k() |
| 200 | )); |
| 201 | } |
| 202 | let reader = ReadAdapter::new(manifest.clone(), dev, read); |
| 203 | let backend = Arc::new(SlotPair { |
| 204 | gate_up: gate_up.clone(), |
| 205 | down: down.clone(), |
| 206 | }); |
| 207 | let shape = ExpertShape { |
| 208 | hidden: hidden as u64, |
| 209 | inter: inter as u64, |
| 210 | }; |
| 211 | let pager = ExpertPager::new(manifest, shape, reader, backend, read_deadline) |
| 212 | .map_err(|e| e.to_string())?; |
| 213 | let pipeline_buffers = std::env::var("AIEN_RIBBON_OMEGA_BUFFERS") |
| 214 | .ok() |
| 215 | .map(|v| { |
| 216 | v.parse::<usize>() |
| 217 | .map_err(|_| "AIEN_RIBBON_OMEGA_BUFFERS must be 1 or 2") |
| 218 | }) |
| 219 | .transpose()?; |
| 220 | if let Some(n) = pipeline_buffers { |
| 221 | if !(1..=2).contains(&n) { |
| 222 | return Err("AIEN_RIBBON_OMEGA_BUFFERS must be 1 or 2".into()); |
| 223 | } |
| 224 | if !cfg!(feature = "ribbon-omega") { |
| 225 | return Err("Omega ribbon binding is not built".into()); |
| 226 | } |
| 227 | } |
| 228 | Ok(Self { |
| 229 | pager, |
| 230 | gate_up, |
| 231 | down, |
| 232 | inter, |
| 233 | hidden, |
| 234 | #[cfg(feature = "ribbon-omega")] |
| 235 | pipeline_buffers, |
| 236 | }) |
| 237 | } |
| 238 | |
| 239 | pub fn capacity(&self) -> usize { |
| 240 | self.pager.capacity() |
| 241 | } |
| 242 | pub fn resident(&self) -> usize { |
| 243 | self.pager.resident() |
| 244 | } |
| 245 | pub fn pinned(&self) -> u32 { |
| 246 | self.pager.pinned() |
| 247 | } |
| 248 | pub fn stats(&self) -> PagerStats { |
| 249 | self.pager.stats() |
| 250 | } |
| 251 | pub fn residency_stats(&self) -> ResidencyStats { |
| 252 | self.pager.residency_stats() |
| 253 | } |
| 254 | pub fn read_stats(&self) -> ReadStats { |
| 255 | self.pager.read_stats() |
| 256 | } |
| 257 | pub fn manifest(&self) -> &Manifest { |
| 258 | self.pager.manifest() |
| 259 | } |
| 260 | |
| 261 | /// The expert FFN of one token in one layer: `gu_out = gate|up(x)`, SwiGLU into `act_all`, |
| 262 | /// `down_all = down(act_all)`, one row per expert in router order. The combine stays with the caller. |
| 263 | pub fn ffn( |
| 264 | &self, |
| 265 | layer: usize, |
| 266 | experts: &[u32], |
| 267 | x: &[f32], |
| 268 | gu_out: &mut [f32], |
| 269 | act_all: &mut [f32], |
| 270 | down_all: &mut [f32], |
| 271 | ) -> Result<FfnTiming, String> { |
| 272 | let (i, h, k) = (self.inter, self.hidden, experts.len()); |
| 273 | if x.len() != h |
| 274 | || gu_out.len() < k * 2 * i |
| 275 | || act_all.len() < k * i |
| 276 | || down_all.len() < k * h |
| 277 | { |
| 278 | return Err(format!( |
| 279 | "paged ffn layer {layer}: buffer sizes do not fit {k} experts" |
| 280 | )); |
| 281 | } |
| 282 | let ids: Vec<u16> = experts |
| 283 | .iter() |
| 284 | .map(|&e| u16::try_from(e).map_err(|_| format!("expert id {e}"))) |
| 285 | .collect::<Result<_, _>>()?; |
| 286 | let layer16 = u16::try_from(layer).map_err(|_| format!("layer {layer}"))?; |
| 287 | let mut t = FfnTiming::default(); |
| 288 | let t0 = Instant::now(); |
| 289 | #[cfg(feature = "ribbon-omega")] |
| 290 | if let Some(buffers) = self.pipeline_buffers { |
| 291 | self.pager |
| 292 | .for_each_ready(layer16, &ids, buffers, |g, slot, ver| { |
| 293 | t.chip_ns += self.gate_up.grouped( |
| 294 | &[slot], |
| 295 | &[ver.gate_up], |
| 296 | x, |
| 297 | &mut gu_out[g * 2 * i..(g + 1) * 2 * i], |
| 298 | )?; |
| 299 | let host = Instant::now(); |
| 300 | super::swiglu( |
| 301 | &gu_out[g * 2 * i..(g + 1) * 2 * i], |
| 302 | i, |
| 303 | &mut act_all[g * i..(g + 1) * i], |
| 304 | ); |
| 305 | t.host_ns += host.elapsed().as_nanos() as u64; |
| 306 | t.chip_ns += self.down.grouped( |
| 307 | &[slot], |
| 308 | &[ver.down], |
| 309 | &act_all[g * i..(g + 1) * i], |
| 310 | &mut down_all[g * h..(g + 1) * h], |
| 311 | )?; |
| 312 | t.launches += 2; |
| 313 | Ok(()) |
| 314 | }) |
| 315 | .map_err(|e| format!("layer {layer} Omega pipeline: {e}"))?; |
| 316 | t.page_ns = (t0.elapsed().as_nanos() as u64).saturating_sub(t.chip_ns + t.host_ns); |
| 317 | return Ok(t); |
| 318 | } |
| 319 | let pinned = self |
| 320 | .pager |
| 321 | .ensure(layer16, &ids) |
| 322 | .map_err(|e| format!("layer {layer} expert pager: {e}"))?; |
| 323 | t.page_ns = t0.elapsed().as_nanos() as u64; |
| 324 | // The pins are dropped on every exit from here on. |
| 325 | struct Release<'a>(&'a ExpertPager, &'a aien_heartbeat::Pinned); |
| 326 | impl Drop for Release<'_> { |
| 327 | fn drop(&mut self) { |
| 328 | self.0.release(self.1); |
| 329 | } |
| 330 | } |
| 331 | let _release = Release(&self.pager, &pinned); |
| 332 | let gu_ver: Vec<u64> = pinned.versions.iter().map(|v| v.gate_up).collect(); |
| 333 | let dn_ver: Vec<u64> = pinned.versions.iter().map(|v| v.down).collect(); |
| 334 | t.chip_ns += self |
| 335 | .gate_up |
| 336 | .grouped(&pinned.slots, &gu_ver, x, &mut gu_out[..k * 2 * i]) |
| 337 | .map_err(|e| format!("layer {layer} gate_up slots: {e}"))?; |
| 338 | t.launches += 1; |
| 339 | let th = Instant::now(); |
| 340 | for g in 0..k { |
| 341 | super::swiglu( |
| 342 | &gu_out[g * 2 * i..(g + 1) * 2 * i], |
| 343 | i, |
| 344 | &mut act_all[g * i..(g + 1) * i], |
| 345 | ); |
| 346 | } |
| 347 | t.host_ns += th.elapsed().as_nanos() as u64; |
| 348 | t.chip_ns += self |
| 349 | .down |
| 350 | .grouped( |
| 351 | &pinned.slots, |
| 352 | &dn_ver, |
| 353 | &act_all[..k * i], |
| 354 | &mut down_all[..k * h], |
| 355 | ) |
| 356 | .map_err(|e| format!("layer {layer} down slots: {e}"))?; |
| 357 | t.launches += 1; |
| 358 | Ok(t) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | #[cfg(test)] |
| 363 | mod tests { |
| 364 | //! Paged vs resident on the tiny in-memory model, with host fakes for the slot pools: the same |
| 365 | //! logits bit for bit at every position, at the smallest capacity (top_k slots: every layer |
| 366 | //! evicts) and with room for everything; a corrupted slot load changes them (the check has teeth); |
| 367 | //! a capacity below top_k fails the step instead of computing something else. |
| 368 | use super::super::test_support::*; |
| 369 | use super::super::*; |
| 370 | use super::*; |
| 371 | use std::collections::BTreeMap; |
| 372 | use std::sync::Mutex; |
| 373 | |
| 374 | /// Host slot pool: the resident host GEMV over `slots` expert-sized regions, with omega's |
| 375 | /// version rule (a launch names the version it pinned; a reloaded slot refuses the old one). |
| 376 | #[derive(Debug)] |
| 377 | struct HostSlots { |
| 378 | inner: Mutex<(HostFp8, Vec<u64>, u64)>, |
| 379 | corrupt: bool, |
| 380 | } |
| 381 | |
| 382 | impl HostSlots { |
| 383 | fn new(slots: usize, n: usize, k: usize, corrupt: bool) -> Arc<Self> { |
| 384 | let sc = (n / FP8_BLOCK) * (k / FP8_BLOCK); |
| 385 | Arc::new(Self { |
| 386 | inner: Mutex::new(( |
| 387 | HostFp8 { |
| 388 | experts: slots, |
| 389 | n, |
| 390 | k, |
| 391 | w: vec![0; slots * n * k], |
| 392 | scales: vec![0; slots * sc], |
| 393 | dev: None, |
| 394 | gemm: None, |
| 395 | }, |
| 396 | vec![0; slots], |
| 397 | 0, |
| 398 | )), |
| 399 | corrupt, |
| 400 | }) |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | impl SlotGemv for HostSlots { |
| 405 | fn slots(&self) -> usize { |
| 406 | self.inner.lock().unwrap().1.len() |
| 407 | } |
| 408 | fn n(&self) -> usize { |
| 409 | self.inner.lock().unwrap().0.n |
| 410 | } |
| 411 | fn k(&self) -> usize { |
| 412 | self.inner.lock().unwrap().0.k |
| 413 | } |
| 414 | fn load(&self, slot: u32, _key: u64, w: &[u8], scales: &[u16]) -> Result<u64, String> { |
| 415 | let mut g = self.inner.lock().unwrap(); |
| 416 | let (n, k) = (g.0.n, g.0.k); |
| 417 | let sc = (n / FP8_BLOCK) * (k / FP8_BLOCK); |
| 418 | let s = slot as usize; |
| 419 | assert_eq!((w.len(), scales.len()), (n * k, sc)); |
| 420 | g.0.w[s * n * k..(s + 1) * n * k].copy_from_slice(w); |
| 421 | if self.corrupt { |
| 422 | g.0.w[s * n * k] ^= 0x01; |
| 423 | } |
| 424 | g.0.scales[s * sc..(s + 1) * sc].copy_from_slice(scales); |
| 425 | g.2 += 1; |
| 426 | let v = g.2; |
| 427 | g.1[s] = v; |
| 428 | Ok(v) |
| 429 | } |
| 430 | fn grouped( |
| 431 | &self, |
| 432 | slots: &[u32], |
| 433 | versions: &[u64], |
| 434 | x: &[f32], |
| 435 | y: &mut [f32], |
| 436 | ) -> Result<u64, String> { |
| 437 | let g = self.inner.lock().unwrap(); |
| 438 | for (&s, &v) in slots.iter().zip(versions) { |
| 439 | if g.1[s as usize] != v { |
| 440 | return Err(format!( |
| 441 | "slot {s}: version {v} is stale (now {})", |
| 442 | g.1[s as usize] |
| 443 | )); |
| 444 | } |
| 445 | } |
| 446 | g.0.grouped_f32(slots, x, y) |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | /// The in-memory checkpoint as one safetensors shard + index (F8 tensors first, then BF16, each |
| 451 | /// sorted by name, as safetensors groups them), so the manifest and reader see real files. |
| 452 | fn write_checkpoint(src: &MemorySource, dir: &std::path::Path) { |
| 453 | let mut all: Vec<_> = src.tensors.iter().collect(); |
| 454 | all.sort_by(|a, b| (a.1 .0 != "F8_E4M3", a.0).cmp(&(b.1 .0 != "F8_E4M3", b.0))); |
| 455 | let shard = "model-00001-of-00001.safetensors"; |
| 456 | let (mut header, mut data, mut map) = (serde_json::Map::new(), Vec::new(), BTreeMap::new()); |
| 457 | for (name, (dtype, shape, bytes)) in all { |
| 458 | let a = data.len(); |
| 459 | data.extend_from_slice(bytes); |
| 460 | header.insert( |
| 461 | name.clone(), |
| 462 | serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [a, data.len()]}), |
| 463 | ); |
| 464 | map.insert(name.clone(), shard.to_string()); |
| 465 | } |
| 466 | let h = serde_json::to_vec(&header).unwrap(); |
| 467 | let mut file = (h.len() as u64).to_le_bytes().to_vec(); |
| 468 | file.extend(&h); |
| 469 | file.extend(&data); |
| 470 | std::fs::write(dir.join(shard), file).unwrap(); |
| 471 | std::fs::write( |
| 472 | dir.join("model.safetensors.index.json"), |
| 473 | serde_json::to_vec(&serde_json::json!({"metadata": {}, "weight_map": map})).unwrap(), |
| 474 | ) |
| 475 | .unwrap(); |
| 476 | } |
| 477 | |
| 478 | fn tmpdir(tag: &str) -> std::path::PathBuf { |
| 479 | let d = std::env::temp_dir().join(format!( |
| 480 | "aien-ribbon-{tag}-{}-{}", |
| 481 | std::process::id(), |
| 482 | std::time::SystemTime::now() |
| 483 | .duration_since(std::time::UNIX_EPOCH) |
| 484 | .unwrap() |
| 485 | .as_nanos() |
| 486 | )); |
| 487 | std::fs::create_dir_all(&d).unwrap(); |
| 488 | d |
| 489 | } |
| 490 | |
| 491 | fn paged_engine( |
| 492 | c: &Qwen3MoeConfig, |
| 493 | dir: &std::path::Path, |
| 494 | slots: usize, |
| 495 | fakes: bool, |
| 496 | corrupt: bool, |
| 497 | ) -> (Qwen3MoeOmegaEngine, Arc<PagedExperts>) { |
| 498 | paged_engine_mode(c, dir, slots, fakes, corrupt, None) |
| 499 | } |
| 500 | |
| 501 | fn paged_engine_mode( |
| 502 | c: &Qwen3MoeConfig, |
| 503 | dir: &Path, |
| 504 | slots: usize, |
| 505 | fakes: bool, |
| 506 | corrupt: bool, |
| 507 | pipeline: Option<usize>, |
| 508 | ) -> (Qwen3MoeOmegaEngine, Arc<PagedExperts>) { |
| 509 | let m = Arc::new(Manifest::build(dir).unwrap()); |
| 510 | let dev = Arc::new(aien_heartbeat::FileShards::open(&m.shard_paths(), false).unwrap()); |
| 511 | let (h, i) = (c.hidden, c.moe_intermediate); |
| 512 | #[allow(unused_mut)] |
| 513 | let mut paged = PagedExperts::new( |
| 514 | m, |
| 515 | h, |
| 516 | i, |
| 517 | dev, |
| 518 | ReadConfig { |
| 519 | workers: 2, |
| 520 | queue_depth: 4, |
| 521 | }, |
| 522 | HostSlots::new(slots, 2 * i, h, corrupt), |
| 523 | HostSlots::new(slots, h, i, false), |
| 524 | Duration::from_secs(10), |
| 525 | ) |
| 526 | .unwrap(); |
| 527 | #[cfg(feature = "ribbon-omega")] |
| 528 | { |
| 529 | paged.pipeline_buffers = pipeline; |
| 530 | } |
| 531 | #[cfg(not(feature = "ribbon-omega"))] |
| 532 | { |
| 533 | assert!(pipeline.is_none()); |
| 534 | } |
| 535 | let paged = Arc::new(paged); |
| 536 | let mut src = MemorySource::for_config(c); |
| 537 | let up = RecordingUploader { |
| 538 | device_fakes: fakes, |
| 539 | ..Default::default() |
| 540 | }; |
| 541 | let (w, _) = load_qwen3_moe_omega_paged_from( |
| 542 | c, |
| 543 | &mut src, |
| 544 | &up, |
| 545 | WeightFormat::Fp8All, |
| 546 | DevicePaths::default(), |
| 547 | paged.clone(), |
| 548 | &mut |_| {}, |
| 549 | ) |
| 550 | .unwrap(); |
| 551 | assert!( |
| 552 | !src.reads.iter().any(|n| n.contains(".mlp.experts.")), |
| 553 | "a paged load must not read expert bytes" |
| 554 | ); |
| 555 | let kv = HostKv::new(&KvGeometry::from(c), 32); |
| 556 | (Qwen3MoeOmegaEngine::new(w, Box::new(kv)), paged) |
| 557 | } |
| 558 | |
| 559 | fn resident_engine(c: &Qwen3MoeConfig, fakes: bool) -> Qwen3MoeOmegaEngine { |
| 560 | let mut src = MemorySource::for_config(c); |
| 561 | let up = RecordingUploader { |
| 562 | device_fakes: fakes, |
| 563 | ..Default::default() |
| 564 | }; |
| 565 | let (w, _) = load_qwen3_moe_omega_from_paths( |
| 566 | c, |
| 567 | &mut src, |
| 568 | &up, |
| 569 | WeightFormat::Fp8All, |
| 570 | DevicePaths::default(), |
| 571 | &mut |_| {}, |
| 572 | ) |
| 573 | .unwrap(); |
| 574 | Qwen3MoeOmegaEngine::new(w, Box::new(HostKv::new(&KvGeometry::from(c), 32))) |
| 575 | } |
| 576 | |
| 577 | /// Prompt then greedy decode; logits bits at every position. |
| 578 | fn run(e: &mut Qwen3MoeOmegaEngine, steps: usize) -> Vec<Vec<u32>> { |
| 579 | let mut out = Vec::new(); |
| 580 | let mut tok = 5u32; |
| 581 | for p in 0..steps { |
| 582 | let hidden = e.step(if p < 4 { [5, 9, 17, 2][p] } else { tok }).unwrap(); |
| 583 | let lg = e.logits(&hidden).unwrap(); |
| 584 | tok = lg |
| 585 | .iter() |
| 586 | .enumerate() |
| 587 | .fold((0, f32::MIN), |b, (j, &v)| if v > b.1 { (j, v) } else { b }) |
| 588 | .0 as u32; |
| 589 | out.push(lg.iter().map(|v| v.to_bits()).collect()); |
| 590 | } |
| 591 | out |
| 592 | } |
| 593 | |
| 594 | #[test] |
| 595 | fn paged_experts_give_the_resident_logits_bit_for_bit_at_any_capacity() { |
| 596 | let c = tiny_config(); |
| 597 | let dir = tmpdir("parity"); |
| 598 | write_checkpoint(&MemorySource::for_config(&c), &dir); |
| 599 | let all = c.layers * c.experts; |
| 600 | for fakes in [false, true] { |
| 601 | let want = run(&mut resident_engine(&c, fakes), 10); |
| 602 | for slots in [c.top_k, c.top_k + 1, all] { |
| 603 | let (mut e, paged) = paged_engine(&c, &dir, slots, fakes, false); |
| 604 | let got = run(&mut e, 10); |
| 605 | assert_eq!(got, want, "device router {fakes}, {slots} slots"); |
| 606 | let s = paged.stats(); |
| 607 | assert_eq!(s.requests, (10 * c.layers) as u64); |
| 608 | assert_eq!( |
| 609 | s.experts_hit + s.experts_missed, |
| 610 | (10 * c.layers * c.top_k) as u64 |
| 611 | ); |
| 612 | assert!( |
| 613 | s.experts_missed >= (c.layers * c.top_k) as u64, |
| 614 | "the first token misses everything" |
| 615 | ); |
| 616 | if slots == all { |
| 617 | // Room for everything: each expert is read at most once. |
| 618 | assert!(s.experts_missed <= all as u64, "{s:?}"); |
| 619 | } else { |
| 620 | assert!( |
| 621 | s.experts_missed > all as u64, |
| 622 | "smallest pools must evict: {s:?}" |
| 623 | ); |
| 624 | } |
| 625 | assert_eq!(paged.pinned(), 0, "every pin released"); |
| 626 | assert!(e.last_timing.page_ns > 0 || s.experts_missed > 0); |
| 627 | } |
| 628 | } |
| 629 | std::fs::remove_dir_all(&dir).ok(); |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | #[cfg(feature = "ribbon-omega")] |
| 634 | fn omega_pipeline_matches_resident_logits_with_one_and_two_buffers() { |
| 635 | let c = tiny_config(); |
| 636 | let dir = tmpdir("omega-pipeline"); |
| 637 | write_checkpoint(&MemorySource::for_config(&c), &dir); |
| 638 | for device in [false, true] { |
| 639 | let expected = run(&mut resident_engine(&c, device), 10); |
| 640 | for buffers in [1, 2] { |
| 641 | for slots in [c.top_k, c.layers * c.experts] { |
| 642 | let (mut engine, pager) = |
| 643 | paged_engine_mode(&c, &dir, slots, device, false, Some(buffers)); |
| 644 | assert_eq!( |
| 645 | run(&mut engine, 10), |
| 646 | expected, |
| 647 | "device {device}, buffers {buffers}, slots {slots}" |
| 648 | ); |
| 649 | assert_eq!(pager.pinned(), 0); |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | std::fs::remove_dir_all(dir).unwrap(); |
| 654 | } |
| 655 | |
| 656 | #[test] |
| 657 | fn a_corrupted_slot_load_changes_the_logits_and_too_few_slots_fail_the_step() { |
| 658 | let c = tiny_config(); |
| 659 | let dir = tmpdir("neg"); |
| 660 | write_checkpoint(&MemorySource::for_config(&c), &dir); |
| 661 | let want = run(&mut resident_engine(&c, true), 4); |
| 662 | let (mut bad, _) = paged_engine(&c, &dir, c.layers * c.experts, true, true); |
| 663 | assert_ne!( |
| 664 | run(&mut bad, 4), |
| 665 | want, |
| 666 | "negative control: one flipped weight byte per load" |
| 667 | ); |
| 668 | |
| 669 | let (mut small, paged) = paged_engine(&c, &dir, c.top_k - 1, true, false); |
| 670 | let err = small.step(5).unwrap_err(); |
| 671 | assert!(err.contains("pinned or loading"), "{err}"); |
| 672 | assert_eq!(paged.pinned(), 0, "a failed step leaves nothing pinned"); |
| 673 | std::fs::remove_dir_all(&dir).ok(); |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | /// What [`open_omega`] needs: the checkpoint's expert manifest, the slot count and the read queue. |
| 678 | #[derive(Debug, Clone)] |
| 679 | pub struct RibbonOptions { |
| 680 | /// Saved manifest (built from the checkpoint and saved here when missing or for another model). |
| 681 | pub manifest: std::path::PathBuf, |
| 682 | pub slots: usize, |
| 683 | pub read: ReadConfig, |
| 684 | /// O_DIRECT reads (the SSD figure); false reads through the page cache. |
| 685 | pub direct: bool, |
| 686 | pub read_deadline: Duration, |
| 687 | } |
| 688 | |
| 689 | /// The chip slot pools for a checkpoint: gate|up `[2i][h]` and down `[h][i]`, `slots` each. |
| 690 | /// Every expert read is BLAKE3-checked against the manifest, so a stale manifest fails closed. |
| 691 | pub fn open_omega( |
| 692 | dir: &std::path::Path, |
| 693 | hidden: usize, |
| 694 | inter: usize, |
| 695 | o: &RibbonOptions, |
| 696 | progress: &mut dyn FnMut(&str), |
| 697 | ) -> Result<Arc<PagedExperts>, String> { |
| 698 | let m = match Manifest::load(&o.manifest) { |
| 699 | Ok(m) if m.model_dir == dir => m, |
| 700 | _ => { |
| 701 | let t = Instant::now(); |
| 702 | let m = Manifest::build(dir).map_err(|e| format!("expert manifest: {e}"))?; |
| 703 | m.save(&o.manifest) |
| 704 | .map_err(|e| format!("save manifest {}: {e}", o.manifest.display()))?; |
| 705 | progress(&format!( |
| 706 | "ribbon manifest built in {:.1} s ({} experts)", |
| 707 | t.elapsed().as_secs_f64(), |
| 708 | m.experts.len() |
| 709 | )); |
| 710 | m |
| 711 | } |
| 712 | }; |
| 713 | progress(&format!( |
| 714 | "ribbon manifest {} experts, model digest {}", |
| 715 | m.experts.len(), |
| 716 | m.model_digest |
| 717 | )); |
| 718 | let m = Arc::new(m); |
| 719 | let dev = Arc::new( |
| 720 | aien_heartbeat::FileShards::open(&m.shard_paths(), o.direct) |
| 721 | .map_err(|e| format!("open shards: {e}"))?, |
| 722 | ); |
| 723 | let gate_up = Arc::new(OmegaSlotGemv::alloc(o.slots, 2 * inter, hidden)?); |
| 724 | let down = Arc::new(OmegaSlotGemv::alloc(o.slots, hidden, inter)?); |
| 725 | progress(&format!( |
| 726 | "ribbon slots {} x {} B = {} B device", |
| 727 | o.slots, |
| 728 | gate_up.slot_bytes() + down.slot_bytes(), |
| 729 | o.slots * (gate_up.slot_bytes() + down.slot_bytes()) |
| 730 | )); |
| 731 | PagedExperts::new( |
| 732 | m, |
| 733 | hidden, |
| 734 | inter, |
| 735 | dev, |
| 736 | o.read, |
| 737 | gate_up, |
| 738 | down, |
| 739 | o.read_deadline, |
| 740 | ) |
| 741 | .map(Arc::new) |
| 742 | } |