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-heartbeat / src / layout.rs
| 1 | //! Qwen3-MoE FP8 expert layout (Expert Ribbon P1, sc#629): which bytes of a verified expert payload are the |
| 2 | //! gate|up and down projections and their block-128 scales, checked against the model shape before any byte |
| 3 | //! is handed to a GPU slot. |
| 4 | //! |
| 5 | //! A payload is the expert's six tensors in file order (manifest [`crate::manifest::TensorRange`] offsets). |
| 6 | //! The chip wants, per expert, exactly what the resident loader uploads (`qwen3_moe_omega.rs`): |
| 7 | //! * gate|up weights `[2i][h]` e4m3 = `gate_proj.weight [i][h]` then `up_proj.weight [i][h]`, scales |
| 8 | //! `[2i/128][h/128]` bf16 = gate scales then up scales; |
| 9 | //! * down weights `[h][i]` e4m3, scales `[h/128][i/128]` bf16. |
| 10 | //! |
| 11 | //! Gate and up are adjacent in the checkpoint (safetensors orders tensors by name within a dtype), so the |
| 12 | //! gate|up weights are normally one borrowed slice; when they are not adjacent they are copied, never assumed. |
| 13 | |
| 14 | use std::borrow::Cow; |
| 15 | |
| 16 | use crate::error::HeartbeatError; |
| 17 | use crate::manifest::{ExpertEntry, TensorRange}; |
| 18 | |
| 19 | /// Quantisation format name recorded with every expert identity. |
| 20 | pub const FORMAT_FP8_BLOCK128: &str = "qwen3-fp8-e4m3/bf16-scale-inv/block128"; |
| 21 | pub const FP8_BLOCK: u64 = 128; |
| 22 | |
| 23 | /// Model dimensions the layout is checked against (config.json `hidden_size`, `moe_intermediate_size`). |
| 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 25 | pub struct ExpertShape { |
| 26 | pub hidden: u64, |
| 27 | pub inter: u64, |
| 28 | } |
| 29 | |
| 30 | impl ExpertShape { |
| 31 | pub fn gate_up_weight_bytes(&self) -> usize { |
| 32 | (2 * self.inter * self.hidden) as usize |
| 33 | } |
| 34 | pub fn down_weight_bytes(&self) -> usize { |
| 35 | (self.hidden * self.inter) as usize |
| 36 | } |
| 37 | pub fn gate_up_scales(&self) -> usize { |
| 38 | (2 * (self.inter / FP8_BLOCK) * (self.hidden / FP8_BLOCK)) as usize |
| 39 | } |
| 40 | pub fn down_scales(&self) -> usize { |
| 41 | ((self.hidden / FP8_BLOCK) * (self.inter / FP8_BLOCK)) as usize |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /// Payload ranges `(offset, len)` of the six tensors of one expert, validated. |
| 46 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 47 | pub struct ExpertLayout { |
| 48 | pub gate_w: (u64, u64), |
| 49 | pub up_w: (u64, u64), |
| 50 | pub down_w: (u64, u64), |
| 51 | pub gate_s: (u64, u64), |
| 52 | pub up_s: (u64, u64), |
| 53 | pub down_s: (u64, u64), |
| 54 | } |
| 55 | |
| 56 | fn find<'a>(e: &'a ExpertEntry, suffix: &str) -> Result<&'a TensorRange, HeartbeatError> { |
| 57 | let want = format!("model.layers.{}.mlp.experts.{}.{suffix}", e.layer, e.expert); |
| 58 | let mut hits = e.tensors.iter().filter(|t| t.name == want); |
| 59 | let t = hits.next().ok_or_else(|| { |
| 60 | HeartbeatError::Manifest(format!("expert ({},{}): missing {want}", e.layer, e.expert)) |
| 61 | })?; |
| 62 | if hits.next().is_some() { |
| 63 | return Err(HeartbeatError::Manifest(format!( |
| 64 | "expert ({},{}): duplicate {want}", |
| 65 | e.layer, e.expert |
| 66 | ))); |
| 67 | } |
| 68 | Ok(t) |
| 69 | } |
| 70 | |
| 71 | fn check( |
| 72 | t: &TensorRange, |
| 73 | dtype: &str, |
| 74 | shape: [u64; 2], |
| 75 | elem: u64, |
| 76 | ) -> Result<(u64, u64), HeartbeatError> { |
| 77 | if t.dtype != dtype || t.shape != shape || t.len != shape[0] * shape[1] * elem { |
| 78 | return Err(HeartbeatError::Manifest(format!( |
| 79 | "{}: dtype {} shape {:?} len {} (want {dtype} {shape:?} len {})", |
| 80 | t.name, |
| 81 | t.dtype, |
| 82 | t.shape, |
| 83 | t.len, |
| 84 | shape[0] * shape[1] * elem |
| 85 | ))); |
| 86 | } |
| 87 | Ok((t.offset, t.len)) |
| 88 | } |
| 89 | |
| 90 | impl ExpertLayout { |
| 91 | /// Validates the six tensors of `e` (names, dtypes, shapes, lengths; no extra tensors) for `shape`. |
| 92 | pub fn for_entry(e: &ExpertEntry, shape: ExpertShape) -> Result<Self, HeartbeatError> { |
| 93 | let (h, i) = (shape.hidden, shape.inter); |
| 94 | if h % FP8_BLOCK != 0 || i % FP8_BLOCK != 0 { |
| 95 | return Err(HeartbeatError::Manifest(format!( |
| 96 | "shape {h}x{i} is not block-128" |
| 97 | ))); |
| 98 | } |
| 99 | if e.tensors.len() != 6 { |
| 100 | return Err(HeartbeatError::Manifest(format!( |
| 101 | "expert ({},{}): {} tensors, want 6", |
| 102 | e.layer, |
| 103 | e.expert, |
| 104 | e.tensors.len() |
| 105 | ))); |
| 106 | } |
| 107 | let (hb, ib) = (h / FP8_BLOCK, i / FP8_BLOCK); |
| 108 | let l = Self { |
| 109 | gate_w: check(find(e, "gate_proj.weight")?, "F8_E4M3", [i, h], 1)?, |
| 110 | up_w: check(find(e, "up_proj.weight")?, "F8_E4M3", [i, h], 1)?, |
| 111 | down_w: check(find(e, "down_proj.weight")?, "F8_E4M3", [h, i], 1)?, |
| 112 | gate_s: check(find(e, "gate_proj.weight_scale_inv")?, "BF16", [ib, hb], 2)?, |
| 113 | up_s: check(find(e, "up_proj.weight_scale_inv")?, "BF16", [ib, hb], 2)?, |
| 114 | down_s: check(find(e, "down_proj.weight_scale_inv")?, "BF16", [hb, ib], 2)?, |
| 115 | }; |
| 116 | let end = e.len; |
| 117 | for (o, n) in [l.gate_w, l.up_w, l.down_w, l.gate_s, l.up_s, l.down_s] { |
| 118 | if o + n > end { |
| 119 | return Err(HeartbeatError::Manifest(format!( |
| 120 | "expert ({},{}): tensor past payload end", |
| 121 | e.layer, e.expert |
| 122 | ))); |
| 123 | } |
| 124 | } |
| 125 | Ok(l) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// An expert payload as its segments in order (a ring lease, or a read adapter result). |
| 130 | pub struct Payload<'a> { |
| 131 | segs: Vec<&'a [u8]>, |
| 132 | } |
| 133 | |
| 134 | impl<'a> Payload<'a> { |
| 135 | pub fn new(segs: Vec<&'a [u8]>) -> Self { |
| 136 | Self { segs } |
| 137 | } |
| 138 | |
| 139 | pub fn len(&self) -> usize { |
| 140 | self.segs.iter().map(|s| s.len()).sum() |
| 141 | } |
| 142 | |
| 143 | pub fn is_empty(&self) -> bool { |
| 144 | self.len() == 0 |
| 145 | } |
| 146 | |
| 147 | /// `len` bytes at payload offset `off`, borrowed when they lie in one segment. |
| 148 | pub fn bytes(&self, off: u64, len: u64) -> Result<Cow<'a, [u8]>, HeartbeatError> { |
| 149 | let (off, len) = (off as usize, len as usize); |
| 150 | if off.checked_add(len).is_none_or(|end| end > self.len()) { |
| 151 | return Err(HeartbeatError::Manifest(format!( |
| 152 | "payload range {off}+{len} past the {}-byte payload", |
| 153 | self.len() |
| 154 | ))); |
| 155 | } |
| 156 | let mut base = 0usize; |
| 157 | for s in &self.segs { |
| 158 | if off >= base && off + len <= base + s.len() { |
| 159 | return Ok(Cow::Borrowed(&s[off - base..off - base + len])); |
| 160 | } |
| 161 | base += s.len(); |
| 162 | } |
| 163 | // Straddles a segment boundary (never for whole tensors, but correct anyway): copy. |
| 164 | let flat: Vec<u8> = self.segs.iter().flat_map(|s| s.iter().copied()).collect(); |
| 165 | Ok(Cow::Owned(flat[off..off + len].to_vec())) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// What a GPU slot pair is loaded from: gate|up and down weights (e4m3) and scales (bf16 bits). |
| 170 | #[derive(Debug)] |
| 171 | pub struct ExpertParts<'a> { |
| 172 | pub gate_up_w: Cow<'a, [u8]>, |
| 173 | pub gate_up_s: Vec<u16>, |
| 174 | pub down_w: Cow<'a, [u8]>, |
| 175 | pub down_s: Vec<u16>, |
| 176 | } |
| 177 | |
| 178 | fn bf16_words(b: &[u8]) -> Vec<u16> { |
| 179 | b.as_chunks::<2>() |
| 180 | .0 |
| 181 | .iter() |
| 182 | .map(|c| u16::from_le_bytes(*c)) |
| 183 | .collect() |
| 184 | } |
| 185 | |
| 186 | impl ExpertLayout { |
| 187 | /// Splits a verified payload into the chip layout. |
| 188 | pub fn parts<'a>(&self, p: &Payload<'a>) -> Result<ExpertParts<'a>, HeartbeatError> { |
| 189 | let gate_up_w = if self.up_w.0 == self.gate_w.0 + self.gate_w.1 { |
| 190 | p.bytes(self.gate_w.0, self.gate_w.1 + self.up_w.1)? |
| 191 | } else { |
| 192 | let mut v = p.bytes(self.gate_w.0, self.gate_w.1)?.into_owned(); |
| 193 | v.extend_from_slice(&p.bytes(self.up_w.0, self.up_w.1)?); |
| 194 | Cow::Owned(v) |
| 195 | }; |
| 196 | let mut gate_up_s = bf16_words(&p.bytes(self.gate_s.0, self.gate_s.1)?); |
| 197 | gate_up_s.extend(bf16_words(&p.bytes(self.up_s.0, self.up_s.1)?)); |
| 198 | Ok(ExpertParts { |
| 199 | gate_up_w, |
| 200 | gate_up_s, |
| 201 | down_w: p.bytes(self.down_w.0, self.down_w.1)?, |
| 202 | down_s: bf16_words(&p.bytes(self.down_s.0, self.down_s.1)?), |
| 203 | }) |
| 204 | } |
| 205 | } |