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-expert-store / src / format.rs
| 1 | //! Canonical byte formats: the expert artifact and the versioned index. |
| 2 | //! |
| 3 | //! Artifact (all integers little endian): |
| 4 | //! |
| 5 | //! ```text |
| 6 | //! 0..4096 header region (fields below, every other byte zero) |
| 7 | //! 4096..4096+W FP8 E4M3 weight bytes, row major [rows][cols], as in the checkpoint |
| 8 | //! S..S+L scale bytes [ceil(rows/128)][ceil(cols/128)], as in the checkpoint |
| 9 | //! (S = round_up(4096 + W, 4096)) |
| 10 | //! S+L..object_len zero padding to a 4096 multiple |
| 11 | //! ``` |
| 12 | //! |
| 13 | //! Header fields: magic `AIENXPRT` (0..8), version (8..12), header_len 4096 |
| 14 | //! (12..16), model digest (16..48), layer (48..52), expert (52..56), |
| 15 | //! projection (56), quantization (57), weight dtype (58, 1 = F8_E4M3), scale |
| 16 | //! dtype (59), block (60..64), rows (64..72), cols (72..80), scale rows |
| 17 | //! (80..88), scale cols (88..96), weight offset (96..104), weight length |
| 18 | //! (104..112), scale offset (112..120), scale length (120..128), object length |
| 19 | //! (128..136). |
| 20 | //! |
| 21 | //! The content address is SHA-256 of the whole artifact. Because the digest |
| 22 | //! covers the header, the payload and the padding, it binds the weight bytes |
| 23 | //! themselves, not only an index of them (sc#338). |
| 24 | //! |
| 25 | //! Index: magic `AIENXIDX` (0..8), version (8..12), entry length 84 (12..16), |
| 26 | //! entry count (16..24), the entries in strictly ascending key order (so a |
| 27 | //! duplicate key is a format error), then SHA-256 of everything before it. |
| 28 | |
| 29 | use crate::error::StoreError; |
| 30 | use sha2::{Digest, Sha256}; |
| 31 | use subtle::ConstantTimeEq; |
| 32 | |
| 33 | pub const OBJECT_MAGIC: [u8; 8] = *b"AIENXPRT"; |
| 34 | pub const INDEX_MAGIC: [u8; 8] = *b"AIENXIDX"; |
| 35 | pub const FORMAT_VERSION: u32 = 1; |
| 36 | /// Size of the artifact header region; the weight bytes start here. |
| 37 | pub const HEADER_REGION: usize = 4096; |
| 38 | /// Alignment of every payload offset and of the artifact length (direct I/O). |
| 39 | pub const ALIGN: u64 = 4096; |
| 40 | /// FP8 quantization block edge (rows and columns). |
| 41 | pub const FP8_BLOCK: u64 = 128; |
| 42 | /// Bytes of one index entry. |
| 43 | pub const INDEX_ENTRY_LEN: usize = 84; |
| 44 | const INDEX_PREFIX_LEN: usize = 24; |
| 45 | const HEADER_FIELDS_END: usize = 136; |
| 46 | const WEIGHT_DTYPE_F8_E4M3: u8 = 1; |
| 47 | |
| 48 | /// Which projection of an expert's MLP. |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 50 | #[repr(u8)] |
| 51 | pub enum Projection { |
| 52 | Gate = 1, |
| 53 | Up = 2, |
| 54 | Down = 3, |
| 55 | } |
| 56 | |
| 57 | impl Projection { |
| 58 | pub const ALL: [Projection; 3] = [Projection::Gate, Projection::Up, Projection::Down]; |
| 59 | |
| 60 | pub fn from_u8(v: u8) -> Option<Self> { |
| 61 | match v { |
| 62 | 1 => Some(Self::Gate), |
| 63 | 2 => Some(Self::Up), |
| 64 | 3 => Some(Self::Down), |
| 65 | _ => None, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// The checkpoint tensor name component (`gate_proj`, `up_proj`, `down_proj`). |
| 70 | pub fn checkpoint_name(self) -> &'static str { |
| 71 | match self { |
| 72 | Self::Gate => "gate_proj", |
| 73 | Self::Up => "up_proj", |
| 74 | Self::Down => "down_proj", |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Quantization format of the weight bytes. |
| 80 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 81 | #[repr(u8)] |
| 82 | pub enum QuantFormat { |
| 83 | /// FP8 E4M3 weights with one scale per 128 x 128 block. |
| 84 | Fp8E4m3Block128 = 1, |
| 85 | } |
| 86 | |
| 87 | impl QuantFormat { |
| 88 | pub fn from_u8(v: u8) -> Option<Self> { |
| 89 | match v { |
| 90 | 1 => Some(Self::Fp8E4m3Block128), |
| 91 | _ => None, |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Element type of the stored scale bytes (kept exactly as the checkpoint has them). |
| 97 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 98 | #[repr(u8)] |
| 99 | pub enum ScaleDtype { |
| 100 | Bf16 = 1, |
| 101 | F32 = 2, |
| 102 | } |
| 103 | |
| 104 | impl ScaleDtype { |
| 105 | pub fn from_u8(v: u8) -> Option<Self> { |
| 106 | match v { |
| 107 | 1 => Some(Self::Bf16), |
| 108 | 2 => Some(Self::F32), |
| 109 | _ => None, |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub fn from_safetensors(s: &str) -> Option<Self> { |
| 114 | match s { |
| 115 | "BF16" => Some(Self::Bf16), |
| 116 | "F32" => Some(Self::F32), |
| 117 | _ => None, |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | pub fn safetensors_name(self) -> &'static str { |
| 122 | match self { |
| 123 | Self::Bf16 => "BF16", |
| 124 | Self::F32 => "F32", |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | pub fn size(self) -> u64 { |
| 129 | match self { |
| 130 | Self::Bf16 => 2, |
| 131 | Self::F32 => 4, |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// The identity of one stored tensor pair. Ordered field by field, in |
| 137 | /// declaration order (the index order). |
| 138 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 139 | pub struct ExpertKey { |
| 140 | pub model_digest: [u8; 32], |
| 141 | pub layer: u32, |
| 142 | pub expert: u32, |
| 143 | pub projection: Projection, |
| 144 | pub quant: QuantFormat, |
| 145 | } |
| 146 | |
| 147 | /// One index record: the key, the content address and the artifact length. |
| 148 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 149 | pub struct IndexEntry { |
| 150 | pub key: ExpertKey, |
| 151 | pub data_digest: [u8; 32], |
| 152 | pub object_len: u64, |
| 153 | } |
| 154 | |
| 155 | /// The decoded artifact header. Every field after `scale_dtype` is derived |
| 156 | /// from `(rows, cols, scale_dtype)`; `decode` recomputes and compares them. |
| 157 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 158 | pub struct ArtifactHeader { |
| 159 | pub key: ExpertKey, |
| 160 | pub rows: u64, |
| 161 | pub cols: u64, |
| 162 | pub scale_dtype: ScaleDtype, |
| 163 | pub scale_rows: u64, |
| 164 | pub scale_cols: u64, |
| 165 | pub weight_offset: u64, |
| 166 | pub weight_len: u64, |
| 167 | pub scale_offset: u64, |
| 168 | pub scale_len: u64, |
| 169 | pub object_len: u64, |
| 170 | } |
| 171 | |
| 172 | fn round_up(v: u64, align: u64) -> Option<u64> { |
| 173 | v.checked_add(align - 1).map(|x| x / align * align) |
| 174 | } |
| 175 | |
| 176 | fn rd_u32(b: &[u8], at: usize) -> u32 { |
| 177 | let mut a = [0u8; 4]; |
| 178 | a.copy_from_slice(&b[at..at + 4]); |
| 179 | u32::from_le_bytes(a) |
| 180 | } |
| 181 | |
| 182 | fn rd_u64(b: &[u8], at: usize) -> u64 { |
| 183 | let mut a = [0u8; 8]; |
| 184 | a.copy_from_slice(&b[at..at + 8]); |
| 185 | u64::from_le_bytes(a) |
| 186 | } |
| 187 | |
| 188 | impl ArtifactHeader { |
| 189 | /// The canonical layout for a `[rows][cols]` FP8 weight with block-128 scales. |
| 190 | pub fn new( |
| 191 | key: ExpertKey, |
| 192 | rows: u64, |
| 193 | cols: u64, |
| 194 | scale_dtype: ScaleDtype, |
| 195 | ) -> Result<Self, StoreError> { |
| 196 | if rows == 0 || cols == 0 { |
| 197 | return Err(StoreError::BadHeader("zero rows or cols")); |
| 198 | } |
| 199 | let ov = StoreError::Overflow; |
| 200 | let weight_len = rows.checked_mul(cols).ok_or(ov.clone())?; |
| 201 | let scale_rows = rows.div_ceil(FP8_BLOCK); |
| 202 | let scale_cols = cols.div_ceil(FP8_BLOCK); |
| 203 | let scale_len = scale_rows |
| 204 | .checked_mul(scale_cols) |
| 205 | .and_then(|n| n.checked_mul(scale_dtype.size())) |
| 206 | .ok_or(ov.clone())?; |
| 207 | let weight_offset = HEADER_REGION as u64; |
| 208 | let scale_offset = weight_offset |
| 209 | .checked_add(weight_len) |
| 210 | .and_then(|e| round_up(e, ALIGN)) |
| 211 | .ok_or(ov.clone())?; |
| 212 | let object_len = scale_offset |
| 213 | .checked_add(scale_len) |
| 214 | .and_then(|e| round_up(e, ALIGN)) |
| 215 | .ok_or(ov)?; |
| 216 | Ok(Self { |
| 217 | key, |
| 218 | rows, |
| 219 | cols, |
| 220 | scale_dtype, |
| 221 | scale_rows, |
| 222 | scale_cols, |
| 223 | weight_offset, |
| 224 | weight_len, |
| 225 | scale_offset, |
| 226 | scale_len, |
| 227 | object_len, |
| 228 | }) |
| 229 | } |
| 230 | |
| 231 | /// The 4096-byte canonical header region. |
| 232 | pub fn encode(&self) -> Vec<u8> { |
| 233 | let mut h = vec![0u8; HEADER_REGION]; |
| 234 | h[0..8].copy_from_slice(&OBJECT_MAGIC); |
| 235 | h[8..12].copy_from_slice(&FORMAT_VERSION.to_le_bytes()); |
| 236 | h[12..16].copy_from_slice(&(HEADER_REGION as u32).to_le_bytes()); |
| 237 | h[16..48].copy_from_slice(&self.key.model_digest); |
| 238 | h[48..52].copy_from_slice(&self.key.layer.to_le_bytes()); |
| 239 | h[52..56].copy_from_slice(&self.key.expert.to_le_bytes()); |
| 240 | h[56] = self.key.projection as u8; |
| 241 | h[57] = self.key.quant as u8; |
| 242 | h[58] = WEIGHT_DTYPE_F8_E4M3; |
| 243 | h[59] = self.scale_dtype as u8; |
| 244 | h[60..64].copy_from_slice(&(FP8_BLOCK as u32).to_le_bytes()); |
| 245 | let fields = [ |
| 246 | self.rows, |
| 247 | self.cols, |
| 248 | self.scale_rows, |
| 249 | self.scale_cols, |
| 250 | self.weight_offset, |
| 251 | self.weight_len, |
| 252 | self.scale_offset, |
| 253 | self.scale_len, |
| 254 | self.object_len, |
| 255 | ]; |
| 256 | for (i, v) in fields.iter().enumerate() { |
| 257 | let at = 64 + i * 8; |
| 258 | h[at..at + 8].copy_from_slice(&v.to_le_bytes()); |
| 259 | } |
| 260 | h |
| 261 | } |
| 262 | |
| 263 | /// Parses and fully re-derives a header region; any disagreement is refused. |
| 264 | pub fn decode(region: &[u8]) -> Result<Self, StoreError> { |
| 265 | if region.len() < HEADER_REGION { |
| 266 | return Err(StoreError::BadHeader("short header region")); |
| 267 | } |
| 268 | let h = ®ion[..HEADER_REGION]; |
| 269 | if h[0..8] != OBJECT_MAGIC { |
| 270 | return Err(StoreError::BadMagic); |
| 271 | } |
| 272 | if rd_u32(h, 8) != FORMAT_VERSION { |
| 273 | return Err(StoreError::UnsupportedVersion); |
| 274 | } |
| 275 | if rd_u32(h, 12) != HEADER_REGION as u32 { |
| 276 | return Err(StoreError::BadHeader("header_len")); |
| 277 | } |
| 278 | let projection = Projection::from_u8(h[56]).ok_or(StoreError::BadHeader("projection"))?; |
| 279 | let quant = QuantFormat::from_u8(h[57]).ok_or(StoreError::BadHeader("quant"))?; |
| 280 | if h[58] != WEIGHT_DTYPE_F8_E4M3 { |
| 281 | return Err(StoreError::BadHeader("weight dtype")); |
| 282 | } |
| 283 | let scale_dtype = ScaleDtype::from_u8(h[59]).ok_or(StoreError::BadHeader("scale dtype"))?; |
| 284 | if u64::from(rd_u32(h, 60)) != FP8_BLOCK { |
| 285 | return Err(StoreError::BadHeader("block")); |
| 286 | } |
| 287 | if h[HEADER_FIELDS_END..].iter().any(|&b| b != 0) { |
| 288 | return Err(StoreError::BadHeader("nonzero reserved bytes")); |
| 289 | } |
| 290 | let mut model_digest = [0u8; 32]; |
| 291 | model_digest.copy_from_slice(&h[16..48]); |
| 292 | let key = ExpertKey { |
| 293 | model_digest, |
| 294 | layer: rd_u32(h, 48), |
| 295 | expert: rd_u32(h, 52), |
| 296 | projection, |
| 297 | quant, |
| 298 | }; |
| 299 | let want = Self::new(key, rd_u64(h, 64), rd_u64(h, 72), scale_dtype)?; |
| 300 | if want.encode() != h { |
| 301 | return Err(StoreError::BadHeader("derived fields disagree")); |
| 302 | } |
| 303 | Ok(want) |
| 304 | } |
| 305 | |
| 306 | /// The weight byte range inside the artifact. |
| 307 | pub fn weight_range(&self) -> core::ops::Range<usize> { |
| 308 | self.weight_offset as usize..(self.weight_offset + self.weight_len) as usize |
| 309 | } |
| 310 | |
| 311 | /// The scale byte range inside the artifact. |
| 312 | pub fn scale_range(&self) -> core::ops::Range<usize> { |
| 313 | self.scale_offset as usize..(self.scale_offset + self.scale_len) as usize |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | /// SHA-256 of `bytes`. |
| 318 | pub fn sha256(bytes: &[u8]) -> [u8; 32] { |
| 319 | Sha256::digest(bytes).into() |
| 320 | } |
| 321 | |
| 322 | /// Constant-time equality of two digests. |
| 323 | pub fn digest_eq(a: &[u8; 32], b: &[u8; 32]) -> bool { |
| 324 | a.ct_eq(b).into() |
| 325 | } |
| 326 | |
| 327 | /// Builds the canonical artifact bytes for one projection. `weights` and |
| 328 | /// `scales` are copied verbatim (checkpoint byte order is preserved). |
| 329 | pub fn build_artifact( |
| 330 | key: ExpertKey, |
| 331 | rows: u64, |
| 332 | cols: u64, |
| 333 | scale_dtype: ScaleDtype, |
| 334 | weights: &[u8], |
| 335 | scales: &[u8], |
| 336 | max_object_bytes: u64, |
| 337 | ) -> Result<(ArtifactHeader, Vec<u8>), StoreError> { |
| 338 | let hdr = ArtifactHeader::new(key, rows, cols, scale_dtype)?; |
| 339 | if weights.len() as u64 != hdr.weight_len { |
| 340 | return Err(StoreError::PayloadLength { |
| 341 | expected: hdr.weight_len, |
| 342 | found: weights.len() as u64, |
| 343 | }); |
| 344 | } |
| 345 | if scales.len() as u64 != hdr.scale_len { |
| 346 | return Err(StoreError::PayloadLength { |
| 347 | expected: hdr.scale_len, |
| 348 | found: scales.len() as u64, |
| 349 | }); |
| 350 | } |
| 351 | if hdr.object_len > max_object_bytes { |
| 352 | return Err(StoreError::ObjectTooLarge { |
| 353 | len: hdr.object_len, |
| 354 | max: max_object_bytes, |
| 355 | }); |
| 356 | } |
| 357 | let len = usize::try_from(hdr.object_len).map_err(|_| StoreError::Overflow)?; |
| 358 | let mut bytes = vec![0u8; len]; |
| 359 | bytes[..HEADER_REGION].copy_from_slice(&hdr.encode()); |
| 360 | bytes[hdr.weight_range()].copy_from_slice(weights); |
| 361 | bytes[hdr.scale_range()].copy_from_slice(scales); |
| 362 | Ok((hdr, bytes)) |
| 363 | } |
| 364 | |
| 365 | /// Encodes an index. Entries must be in strictly ascending key order. |
| 366 | pub fn encode_index(entries: &[IndexEntry]) -> Result<Vec<u8>, StoreError> { |
| 367 | if entries.windows(2).any(|w| w[0].key >= w[1].key) { |
| 368 | return Err(StoreError::BadIndex("entries not strictly ascending")); |
| 369 | } |
| 370 | let mut out = Vec::with_capacity(INDEX_PREFIX_LEN + entries.len() * INDEX_ENTRY_LEN + 32); |
| 371 | out.extend_from_slice(&INDEX_MAGIC); |
| 372 | out.extend_from_slice(&FORMAT_VERSION.to_le_bytes()); |
| 373 | out.extend_from_slice(&(INDEX_ENTRY_LEN as u32).to_le_bytes()); |
| 374 | out.extend_from_slice(&(entries.len() as u64).to_le_bytes()); |
| 375 | for e in entries { |
| 376 | out.extend_from_slice(&e.key.model_digest); |
| 377 | out.extend_from_slice(&e.key.layer.to_le_bytes()); |
| 378 | out.extend_from_slice(&e.key.expert.to_le_bytes()); |
| 379 | out.push(e.key.projection as u8); |
| 380 | out.push(e.key.quant as u8); |
| 381 | out.extend_from_slice(&[0, 0]); |
| 382 | out.extend_from_slice(&e.data_digest); |
| 383 | out.extend_from_slice(&e.object_len.to_le_bytes()); |
| 384 | } |
| 385 | let trailer = sha256(&out); |
| 386 | out.extend_from_slice(&trailer); |
| 387 | Ok(out) |
| 388 | } |
| 389 | |
| 390 | /// The largest index file `decode_index` accepts for `max_entries`. |
| 391 | pub fn max_index_bytes(max_entries: usize) -> u64 { |
| 392 | (INDEX_PREFIX_LEN + 32) as u64 + max_entries as u64 * INDEX_ENTRY_LEN as u64 |
| 393 | } |
| 394 | |
| 395 | /// Decodes and validates an index: size, trailer (constant time), version, |
| 396 | /// strict key order (no duplicates), reserved bytes, enums and object lengths. |
| 397 | pub fn decode_index(bytes: &[u8], max_entries: usize) -> Result<Vec<IndexEntry>, StoreError> { |
| 398 | if bytes.len() < INDEX_PREFIX_LEN + 32 { |
| 399 | return Err(StoreError::BadIndex("short index")); |
| 400 | } |
| 401 | if bytes[0..8] != INDEX_MAGIC { |
| 402 | return Err(StoreError::BadMagic); |
| 403 | } |
| 404 | let (body, trailer) = bytes.split_at(bytes.len() - 32); |
| 405 | let mut t = [0u8; 32]; |
| 406 | t.copy_from_slice(trailer); |
| 407 | if !digest_eq(&sha256(body), &t) { |
| 408 | return Err(StoreError::IndexChecksum); |
| 409 | } |
| 410 | if rd_u32(body, 8) != FORMAT_VERSION { |
| 411 | return Err(StoreError::UnsupportedVersion); |
| 412 | } |
| 413 | if rd_u32(body, 12) as usize != INDEX_ENTRY_LEN { |
| 414 | return Err(StoreError::BadIndex("entry length")); |
| 415 | } |
| 416 | let count = rd_u64(body, 16); |
| 417 | if count > max_entries as u64 { |
| 418 | return Err(StoreError::TooManyEntries); |
| 419 | } |
| 420 | let records = &body[INDEX_PREFIX_LEN..]; |
| 421 | if records.len() as u64 != count * INDEX_ENTRY_LEN as u64 { |
| 422 | return Err(StoreError::BadIndex("size disagrees with count")); |
| 423 | } |
| 424 | let mut out: Vec<IndexEntry> = Vec::with_capacity(count as usize); |
| 425 | let (chunks, rest) = records.as_chunks::<INDEX_ENTRY_LEN>(); |
| 426 | debug_assert!(rest.is_empty()); |
| 427 | for r in chunks { |
| 428 | let mut model_digest = [0u8; 32]; |
| 429 | model_digest.copy_from_slice(&r[0..32]); |
| 430 | let projection = Projection::from_u8(r[40]).ok_or(StoreError::BadIndex("projection"))?; |
| 431 | let quant = QuantFormat::from_u8(r[41]).ok_or(StoreError::BadIndex("quant"))?; |
| 432 | if r[42] != 0 || r[43] != 0 { |
| 433 | return Err(StoreError::BadIndex("nonzero reserved bytes")); |
| 434 | } |
| 435 | let mut data_digest = [0u8; 32]; |
| 436 | data_digest.copy_from_slice(&r[44..76]); |
| 437 | let object_len = rd_u64(r, 76); |
| 438 | if object_len <= HEADER_REGION as u64 || !object_len.is_multiple_of(ALIGN) { |
| 439 | return Err(StoreError::BadIndex("object length")); |
| 440 | } |
| 441 | let e = IndexEntry { |
| 442 | key: ExpertKey { |
| 443 | model_digest, |
| 444 | layer: rd_u32(r, 32), |
| 445 | expert: rd_u32(r, 36), |
| 446 | projection, |
| 447 | quant, |
| 448 | }, |
| 449 | data_digest, |
| 450 | object_len, |
| 451 | }; |
| 452 | if let Some(prev) = out.last() { |
| 453 | if prev.key >= e.key { |
| 454 | return Err(StoreError::BadIndex("entries not strictly ascending")); |
| 455 | } |
| 456 | } |
| 457 | out.push(e); |
| 458 | } |
| 459 | Ok(out) |
| 460 | } |
| 461 | |
| 462 | /// Lowercase hex of a digest (the object file name). |
| 463 | pub fn hex(d: &[u8; 32]) -> String { |
| 464 | const H: &[u8; 16] = b"0123456789abcdef"; |
| 465 | let mut s = String::with_capacity(64); |
| 466 | for b in d { |
| 467 | s.push(H[(b >> 4) as usize] as char); |
| 468 | s.push(H[(b & 15) as usize] as char); |
| 469 | } |
| 470 | s |
| 471 | } |