interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / tests / expert_store_roundtrip.rs

156 lines · 5847 bytes Raw Blame History
1//! sc#629 acceptance: random-access expert weight/scale reads from the
2//! content-addressed expert store equal, byte for byte, what the resident
3//! OWN-30B loader's shard reader (`ShardSource`, the source behind
4//! `load_qwen3_moe_omega`) returns for the same FP8 checkpoint tensors.
5
6use aien_expert_store::indexer::{index_qwen3_moe, Checkpoint, Qwen3MoeExperts};
7use aien_expert_store::{
8 ExpertKey, ExpertStore, IoMode, Outcome, Projection, QuantFormat, ReadAdapter, ReadLimits,
9 StagingBuffer, StoreLimits,
10};
11use aien_inference_abi::qwen3_moe_omega::{ShardSource, TensorSource};
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16const H: usize = 256;
17const I: usize = 192;
18const LAYERS: u32 = 2;
19const EXPERTS: u32 = 4;
20const MODEL: [u8; 32] = [0x30; 32];
21
22fn fill(len: usize, seed: u32) -> Vec<u8> {
23 let mut x = seed.wrapping_mul(2_654_435_761) | 1;
24 (0..len)
25 .map(|_| {
26 x ^= x << 13;
27 x ^= x >> 17;
28 x ^= x << 5;
29 (x >> 8) as u8
30 })
31 .collect()
32}
33
34fn dims(p: Projection) -> (usize, usize) {
35 match p {
36 Projection::Gate | Projection::Up => (I, H),
37 Projection::Down => (H, I),
38 }
39}
40
41fn write_checkpoint(dir: &Path) {
42 let mut weight_map = serde_json::Map::new();
43 for l in 0..LAYERS {
44 let shard = format!("model-{:05}-of-{LAYERS:05}.safetensors", l + 1);
45 let mut header = serde_json::Map::new();
46 let mut data = Vec::new();
47 for e in 0..EXPERTS {
48 for p in Projection::ALL {
49 let (r, c) = dims(p);
50 let base = format!("model.layers.{l}.mlp.experts.{e}.{}", p.checkpoint_name());
51 let seed = l * 1000 + e * 10 + p as u32;
52 for (name, dtype, shape, bytes) in [
53 (
54 format!("{base}.weight"),
55 "F8_E4M3",
56 vec![r, c],
57 fill(r * c, seed),
58 ),
59 (
60 format!("{base}.weight_scale_inv"),
61 "BF16",
62 vec![r.div_ceil(128), c.div_ceil(128)],
63 fill(r.div_ceil(128) * c.div_ceil(128) * 2, seed + 7),
64 ),
65 ] {
66 let start = data.len();
67 data.extend_from_slice(&bytes);
68 header.insert(
69 name.clone(),
70 serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [start, data.len()]}),
71 );
72 weight_map.insert(name, serde_json::Value::String(shard.clone()));
73 }
74 }
75 }
76 let h = serde_json::to_vec(&serde_json::Value::Object(header)).unwrap();
77 let mut out = (h.len() as u64).to_le_bytes().to_vec();
78 out.extend_from_slice(&h);
79 out.extend_from_slice(&data);
80 std::fs::write(dir.join(shard), out).unwrap();
81 }
82 std::fs::write(
83 dir.join("model.safetensors.index.json"),
84 serde_json::to_vec(&serde_json::json!({"weight_map": weight_map})).unwrap(),
85 )
86 .unwrap();
87}
88
89fn temp(tag: &str) -> PathBuf {
90 let p = std::env::temp_dir().join(format!("sc629-{tag}-{}", std::process::id()));
91 let _ = std::fs::remove_dir_all(&p);
92 std::fs::create_dir_all(&p).unwrap();
93 p
94}
95
96#[test]
97fn expert_store_reads_equal_the_resident_loader_bytes() {
98 let ck = temp("ckpt");
99 let st = temp("store");
100 write_checkpoint(&ck);
101 let shape = Qwen3MoeExperts {
102 model_digest: MODEL,
103 hidden: H as u64,
104 moe_intermediate: I as u64,
105 experts: EXPERTS,
106 };
107 let mut store = ExpertStore::open(&st, StoreLimits::default()).unwrap();
108 let mut ckpt = Checkpoint::open(&ck).unwrap();
109 index_qwen3_moe(&mut ckpt, &shape, 0..LAYERS, &mut store).unwrap();
110
111 let reader = ReadAdapter::new(
112 Arc::new(store.file_source(IoMode::Buffered)),
113 ReadLimits::default(),
114 )
115 .unwrap();
116 let mut resident = ShardSource::open(&ck).unwrap();
117 let mut checked = 0;
118 // A scattered order: each read touches one expert only.
119 for (l, e) in [(1u32, 3u32), (0, 0), (1, 0), (0, 2), (1, 1), (0, 3)] {
120 for p in Projection::ALL {
121 let key = ExpertKey {
122 model_digest: MODEL,
123 layer: l,
124 expert: e,
125 projection: p,
126 quant: QuantFormat::Fp8E4m3Block128,
127 };
128 let entry = store.get(&key).expect("indexed");
129 let buf = StagingBuffer::new(entry.object_len as usize).unwrap();
130 reader
131 .submit(entry, buf, Instant::now() + Duration::from_secs(30))
132 .unwrap();
133 let Outcome::Ready(ready) = reader.wait(Duration::from_secs(10)).unwrap().outcome
134 else {
135 panic!("read of {key:?} did not verify");
136 };
137 let (r, c) = dims(p);
138 let base = format!("model.layers.{l}.mlp.experts.{e}.{}", p.checkpoint_name());
139 let mut w = vec![0u8; r * c];
140 resident
141 .read_into(&format!("{base}.weight"), "F8_E4M3", &[r, c], &mut w)
142 .unwrap();
143 let sshape = [r.div_ceil(128), c.div_ceil(128)];
144 let mut s = vec![0u8; sshape[0] * sshape[1] * 2];
145 resident
146 .read_into(&format!("{base}.weight_scale_inv"), "BF16", &sshape, &mut s)
147 .unwrap();
148 assert_eq!(ready.weights(), &w[..], "weights {key:?}");
149 assert_eq!(ready.scales(), &s[..], "scales {key:?}");
150 checked += 1;
151 }
152 }
153 assert_eq!(checked, 18);
154 let _ = std::fs::remove_dir_all(&ck);
155 let _ = std::fs::remove_dir_all(&st);
156}