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 / indexer.rs
| 1 | //! Deterministic, read-only checkpoint-to-artifact indexer. |
| 2 | //! |
| 3 | //! The source checkpoint (`model.safetensors.index.json` plus its shards) is |
| 4 | //! opened read-only and only the tensors of the requested experts are read, |
| 5 | //! through their header byte ranges, so one expert can be fetched without |
| 6 | //! scanning or decoding the other shards. The weight and scale bytes are |
| 7 | //! copied unchanged into artifacts (reversible: `ReadyExpert::weights` and |
| 8 | //! `scales` return exactly the checkpoint bytes). The same checkpoint and |
| 9 | //! arguments always produce the same artifacts, digests and index. |
| 10 | //! |
| 11 | //! The shard checks mirror the resident loader's reader |
| 12 | //! (`aien-inference-abi` `qwen3_moe::Shard`): plain shard file names only, |
| 13 | //! bounded header length, exact dtype, shape and byte range per tensor. |
| 14 | |
| 15 | use crate::error::StoreError; |
| 16 | use crate::format::{ExpertKey, IndexEntry, Projection, QuantFormat, ScaleDtype, FP8_BLOCK}; |
| 17 | use crate::store::ExpertStore; |
| 18 | use std::collections::HashMap; |
| 19 | use std::fs::File; |
| 20 | use std::io::Read; |
| 21 | use std::os::unix::fs::FileExt; |
| 22 | use std::path::{Component, Path, PathBuf}; |
| 23 | |
| 24 | /// Same bound as the resident loader. |
| 25 | const MAX_HEADER_BYTES: u64 = 256 << 20; |
| 26 | /// Bound on `model.safetensors.index.json`. |
| 27 | const MAX_INDEX_JSON_BYTES: u64 = 64 << 20; |
| 28 | |
| 29 | /// One tensor's dtype, shape and absolute byte range in its shard. |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct TensorInfo { |
| 32 | pub dtype: String, |
| 33 | pub shape: Vec<u64>, |
| 34 | pub start: u64, |
| 35 | pub end: u64, |
| 36 | } |
| 37 | |
| 38 | struct Shard { |
| 39 | file: File, |
| 40 | payload_start: u64, |
| 41 | file_len: u64, |
| 42 | header: serde_json::Map<String, serde_json::Value>, |
| 43 | } |
| 44 | |
| 45 | /// A read-only view of a safetensors checkpoint directory. |
| 46 | pub struct Checkpoint { |
| 47 | dir: PathBuf, |
| 48 | weight_map: serde_json::Map<String, serde_json::Value>, |
| 49 | shards: HashMap<String, Shard>, |
| 50 | } |
| 51 | |
| 52 | fn ck(msg: impl Into<String>) -> StoreError { |
| 53 | StoreError::Checkpoint(msg.into()) |
| 54 | } |
| 55 | |
| 56 | fn shard_path(dir: &Path, filename: &str) -> Result<PathBuf, StoreError> { |
| 57 | let mut c = Path::new(filename).components(); |
| 58 | match (c.next(), c.next()) { |
| 59 | (Some(Component::Normal(name)), None) if name == filename => Ok(dir.join(name)), |
| 60 | _ => Err(ck(format!( |
| 61 | "shard file name {filename:?} is not a plain name" |
| 62 | ))), |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl Checkpoint { |
| 67 | pub fn open(dir: &Path) -> Result<Self, StoreError> { |
| 68 | let f = File::open(dir.join("model.safetensors.index.json"))?; |
| 69 | let mut raw = Vec::new(); |
| 70 | f.take(MAX_INDEX_JSON_BYTES + 1).read_to_end(&mut raw)?; |
| 71 | if raw.len() as u64 > MAX_INDEX_JSON_BYTES { |
| 72 | return Err(ck("index json too large")); |
| 73 | } |
| 74 | let v: serde_json::Value = |
| 75 | serde_json::from_slice(&raw).map_err(|e| ck(format!("index json: {e}")))?; |
| 76 | let weight_map = v |
| 77 | .get("weight_map") |
| 78 | .and_then(|m| m.as_object()) |
| 79 | .cloned() |
| 80 | .ok_or_else(|| ck("index json: missing weight_map object"))?; |
| 81 | Ok(Self { |
| 82 | dir: dir.to_path_buf(), |
| 83 | weight_map, |
| 84 | shards: HashMap::new(), |
| 85 | }) |
| 86 | } |
| 87 | |
| 88 | pub fn dir(&self) -> &Path { |
| 89 | &self.dir |
| 90 | } |
| 91 | |
| 92 | fn shard_for(&mut self, name: &str) -> Result<&Shard, StoreError> { |
| 93 | let filename = self |
| 94 | .weight_map |
| 95 | .get(name) |
| 96 | .ok_or_else(|| StoreError::MissingTensor(name.to_string()))? |
| 97 | .as_str() |
| 98 | .ok_or_else(|| ck(format!("index: shard of {name} is not a string")))? |
| 99 | .to_string(); |
| 100 | if !self.shards.contains_key(&filename) { |
| 101 | let shard = open_shard(&shard_path(&self.dir, &filename)?)?; |
| 102 | self.shards.insert(filename.clone(), shard); |
| 103 | } |
| 104 | Ok(&self.shards[&filename]) |
| 105 | } |
| 106 | |
| 107 | /// The header entry of `name`, with its byte range checked against the shard. |
| 108 | pub fn info(&mut self, name: &str) -> Result<TensorInfo, StoreError> { |
| 109 | let shard = self.shard_for(name)?; |
| 110 | let entry = shard |
| 111 | .header |
| 112 | .get(name) |
| 113 | .ok_or_else(|| StoreError::MissingTensor(name.to_string()))?; |
| 114 | let dtype = entry |
| 115 | .get("dtype") |
| 116 | .and_then(|v| v.as_str()) |
| 117 | .ok_or_else(|| ck(format!("{name}: no dtype")))? |
| 118 | .to_string(); |
| 119 | let shape = entry |
| 120 | .get("shape") |
| 121 | .and_then(|v| v.as_array()) |
| 122 | .ok_or_else(|| ck(format!("{name}: no shape")))? |
| 123 | .iter() |
| 124 | .map(|d| d.as_u64().ok_or_else(|| ck(format!("{name}: bad shape")))) |
| 125 | .collect::<Result<Vec<u64>, _>>()?; |
| 126 | let offs = entry |
| 127 | .get("data_offsets") |
| 128 | .and_then(|v| v.as_array()) |
| 129 | .ok_or_else(|| ck(format!("{name}: no data_offsets")))?; |
| 130 | let (Some(s), Some(e), 2) = ( |
| 131 | offs.first().and_then(|v| v.as_u64()), |
| 132 | offs.get(1).and_then(|v| v.as_u64()), |
| 133 | offs.len(), |
| 134 | ) else { |
| 135 | return Err(ck(format!("{name}: data_offsets must hold two integers"))); |
| 136 | }; |
| 137 | let start = shard |
| 138 | .payload_start |
| 139 | .checked_add(s) |
| 140 | .ok_or(StoreError::Overflow)?; |
| 141 | let end = shard |
| 142 | .payload_start |
| 143 | .checked_add(e) |
| 144 | .ok_or(StoreError::Overflow)?; |
| 145 | if s > e || end > shard.file_len { |
| 146 | return Err(ck(format!("{name}: byte range outside the shard"))); |
| 147 | } |
| 148 | Ok(TensorInfo { |
| 149 | dtype, |
| 150 | shape, |
| 151 | start, |
| 152 | end, |
| 153 | }) |
| 154 | } |
| 155 | |
| 156 | /// Reads `name` after checking its dtype and shape. `max_bytes` bounds the read. |
| 157 | pub fn read( |
| 158 | &mut self, |
| 159 | name: &str, |
| 160 | dtype: &str, |
| 161 | shape: &[u64], |
| 162 | max_bytes: u64, |
| 163 | ) -> Result<Vec<u8>, StoreError> { |
| 164 | let info = self.info(name)?; |
| 165 | if info.dtype != dtype { |
| 166 | return Err(StoreError::DtypeMismatch { |
| 167 | name: name.to_string(), |
| 168 | found: info.dtype, |
| 169 | }); |
| 170 | } |
| 171 | if info.shape != shape { |
| 172 | return Err(StoreError::ShapeMismatch { |
| 173 | name: name.to_string(), |
| 174 | }); |
| 175 | } |
| 176 | let len = info.end - info.start; |
| 177 | if len > max_bytes { |
| 178 | return Err(StoreError::ObjectTooLarge { |
| 179 | len, |
| 180 | max: max_bytes, |
| 181 | }); |
| 182 | } |
| 183 | let mut out = vec![0u8; usize::try_from(len).map_err(|_| StoreError::Overflow)?]; |
| 184 | self.shard_for(name)? |
| 185 | .file |
| 186 | .read_exact_at(&mut out, info.start)?; |
| 187 | Ok(out) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | fn open_shard(path: &Path) -> Result<Shard, StoreError> { |
| 192 | let file = File::open(path)?; |
| 193 | let file_len = file.metadata()?.len(); |
| 194 | let mut prefix = [0u8; 8]; |
| 195 | file.read_exact_at(&mut prefix, 0)?; |
| 196 | let header_len = u64::from_le_bytes(prefix); |
| 197 | if header_len > MAX_HEADER_BYTES || header_len.saturating_add(8) > file_len { |
| 198 | return Err(ck("shard header length is invalid")); |
| 199 | } |
| 200 | let mut raw = vec![0u8; header_len as usize]; |
| 201 | file.read_exact_at(&mut raw, 8)?; |
| 202 | let header = match serde_json::from_slice(&raw) { |
| 203 | Ok(serde_json::Value::Object(m)) => m, |
| 204 | Ok(_) => return Err(ck("shard header is not a JSON object")), |
| 205 | Err(e) => return Err(ck(format!("shard header json: {e}"))), |
| 206 | }; |
| 207 | Ok(Shard { |
| 208 | file, |
| 209 | payload_start: 8 + header_len, |
| 210 | file_len, |
| 211 | header, |
| 212 | }) |
| 213 | } |
| 214 | |
| 215 | /// The Qwen3-MoE expert geometry the indexer needs. |
| 216 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 217 | pub struct Qwen3MoeExperts { |
| 218 | pub model_digest: [u8; 32], |
| 219 | pub hidden: u64, |
| 220 | pub moe_intermediate: u64, |
| 221 | pub experts: u32, |
| 222 | } |
| 223 | |
| 224 | impl Qwen3MoeExperts { |
| 225 | /// `(rows, cols)` of a projection's weight: gate/up `[i][h]`, down `[h][i]`. |
| 226 | pub fn shape(&self, p: Projection) -> (u64, u64) { |
| 227 | match p { |
| 228 | Projection::Gate | Projection::Up => (self.moe_intermediate, self.hidden), |
| 229 | Projection::Down => (self.hidden, self.moe_intermediate), |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | /// The checkpoint name of a projection's weight (scales add `_scale_inv`). |
| 234 | pub fn weight_name(layer: u32, expert: u32, p: Projection) -> String { |
| 235 | format!( |
| 236 | "model.layers.{layer}.mlp.experts.{expert}.{}.weight", |
| 237 | p.checkpoint_name() |
| 238 | ) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | /// Reads one projection of one expert straight from the checkpoint (weights, |
| 243 | /// scales, scale dtype), with full dtype and shape checks. |
| 244 | pub fn read_expert( |
| 245 | ckpt: &mut Checkpoint, |
| 246 | shape: &Qwen3MoeExperts, |
| 247 | layer: u32, |
| 248 | expert: u32, |
| 249 | p: Projection, |
| 250 | max_bytes: u64, |
| 251 | ) -> Result<(Vec<u8>, Vec<u8>, ScaleDtype), StoreError> { |
| 252 | if expert >= shape.experts { |
| 253 | return Err(StoreError::MissingTensor(format!( |
| 254 | "expert {expert} of {}", |
| 255 | shape.experts |
| 256 | ))); |
| 257 | } |
| 258 | let (rows, cols) = shape.shape(p); |
| 259 | let wname = Qwen3MoeExperts::weight_name(layer, expert, p); |
| 260 | let sname = format!("{wname}_scale_inv"); |
| 261 | let weights = ckpt.read(&wname, "F8_E4M3", &[rows, cols], max_bytes)?; |
| 262 | let sinfo = ckpt.info(&sname)?; |
| 263 | let sdt = ScaleDtype::from_safetensors(&sinfo.dtype).ok_or(StoreError::DtypeMismatch { |
| 264 | name: sname.clone(), |
| 265 | found: sinfo.dtype.clone(), |
| 266 | })?; |
| 267 | let sshape = [rows.div_ceil(FP8_BLOCK), cols.div_ceil(FP8_BLOCK)]; |
| 268 | let scales = ckpt.read(&sname, sdt.safetensors_name(), &sshape, max_bytes)?; |
| 269 | Ok((weights, scales, sdt)) |
| 270 | } |
| 271 | |
| 272 | fn inside(child: &Path, parent: &Path) -> bool { |
| 273 | match (child.canonicalize(), parent.canonicalize()) { |
| 274 | (Ok(c), Ok(p)) => c.starts_with(p), |
| 275 | _ => false, |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// Indexes every gate, up and down projection of `experts` in `layers` into |
| 280 | /// `store`, in (layer, expert, projection) order, and commits the index. |
| 281 | /// Refuses a store root inside the checkpoint directory. Any missing tensor, |
| 282 | /// dtype or shape mismatch, or a key already bound to other content aborts |
| 283 | /// before the index is committed. |
| 284 | pub fn index_qwen3_moe( |
| 285 | ckpt: &mut Checkpoint, |
| 286 | shape: &Qwen3MoeExperts, |
| 287 | layers: core::ops::Range<u32>, |
| 288 | store: &mut ExpertStore, |
| 289 | ) -> Result<Vec<IndexEntry>, StoreError> { |
| 290 | if inside(store.root(), ckpt.dir()) { |
| 291 | return Err(StoreError::StoreInsideCheckpoint); |
| 292 | } |
| 293 | let max = store.limits().max_object_bytes; |
| 294 | let mut out = Vec::new(); |
| 295 | for layer in layers { |
| 296 | for expert in 0..shape.experts { |
| 297 | for p in Projection::ALL { |
| 298 | let (w, s, sdt) = read_expert(ckpt, shape, layer, expert, p, max)?; |
| 299 | let (rows, cols) = shape.shape(p); |
| 300 | let key = ExpertKey { |
| 301 | model_digest: shape.model_digest, |
| 302 | layer, |
| 303 | expert, |
| 304 | projection: p, |
| 305 | quant: QuantFormat::Fp8E4m3Block128, |
| 306 | }; |
| 307 | out.push(store.put(key, rows, cols, sdt, &w, &s)?); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | store.commit()?; |
| 312 | Ok(out) |
| 313 | } |