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 / src / bin / own30b_selfdraft.rs

385 lines · 15925 bytes Raw Blame History
1//! OWN-30B self-draft acceptance (aienix#4, Heartbeat H0): the 30B drafts with only a resident
2//! subset of experts per layer, the exact full-router 30B verifies.
3//!
4//! own30b_selfdraft <checkpoint> <receipt-dir> [--new 256] [--rs 16,32,64] [--ks 4,8,16,32]
5//! [--max-context 4096] [--cross-check 3] [--force-memory]
6//!
7//! 1. Calibration: greedy decode of the CALIB prompts (distinct from the EVAL prompts) on the
8//! full router with `expert_counts` on; per layer the R most chosen experts (ties: lower id)
9//! form the resident set.
10//! 2. Reference: per EVAL prompt, the full model's greedy continuation T (token-at-a-time
11//! `step`, stop at EOS or `--new`).
12//! 3. Run lengths: at every position p of T, from the full-model KV of prompt + T[..p], the
13//! masked model drafts greedily (`set_draft_experts`) until it misses T or 32 tokens; L_R(p)
14//! = matched tokens. Greedy verify is exact, so a block of k drafted at p accepts
15//! a = min(L_R(p), k) and advances a + 1 tokens (the verifier's own next token).
16//! 4. Simulation per (R, k): p = 0; while p < |T|: blocks += 1; p += min(L, k) + 1.
17//! Tokens per block = |T| / blocks.
18//! 5. Cross-check on the first `--cross-check` prompts at k = 8: the literal loop (draft k with
19//! the mask, rewind, full-model step + logits over the drafted tokens, accept the matching
20//! prefix + 1, rewind) must give the same blocks and the same tokens as T.
21//!
22//! Writes run.txt and run.json into the receipt dir.
23use std::path::PathBuf;
24use std::time::Instant;
25
26use aien_inference_abi::qwen3_moe_omega::{
27 sample_next, AttnPath, DevicePaths, GenerateParams, Qwen3MoeOmegaEngine, WeightFormat,
28};
29use aien_inference_abi::tokenizer::ChatTokenizer as Tokenizer;
30
31const CALIB: [&str; 8] = [
32 "Write a short story about a lighthouse keeper who finds a message in a bottle.",
33 "Explain how a refrigerator moves heat from inside to outside, step by step.",
34 "Write a Rust function that parses a CSV line with quoted fields, and explain it.",
35 "List ten practical tips for keeping a vegetable garden healthy through a dry summer.",
36 "Describe the causes and consequences of the fall of the Western Roman Empire.",
37 "Solve: a train leaves at 3 pm at 80 km/h, another at 4 pm at 100 km/h on the same track. When does the second catch the first? Show the working.",
38 "Translate into French and then explain the grammar: 'We would have gone if it had not rained.'",
39 "Write a product description for a solar-powered camping lantern.",
40];
41
42const EVAL: [&str; 20] = [
43 "Write a poem about the ocean at night.",
44 "Explain what a hash table is and when you would use one.",
45 "Write a Python function that returns the n-th Fibonacci number iteratively, with comments.",
46 "What are the main differences between a diesel and a petrol engine?",
47 "Give me a recipe for a simple tomato soup.",
48 "Summarize the plot of Romeo and Juliet in plain words.",
49 "How does a bicycle stay upright while moving?",
50 "Write a polite email asking a landlord to fix a leaking tap.",
51 "Explain the Pythagorean theorem with an example.",
52 "What should I check before buying a used car?",
53 "Write a short dialogue between a robot and a child who meet for the first time.",
54 "Describe how photosynthesis works.",
55 "Write a C function that reverses a string in place, and explain each line.",
56 "What are good habits for getting better sleep?",
57 "Explain inflation to a twelve-year-old.",
58 "Compare TCP and UDP and say when each is used.",
59 "Write a cover letter opening paragraph for a mechanical engineering job.",
60 "Explain how a transistor works as a switch.",
61 "Plan a three-day walking trip in the mountains, with a packing list.",
62 "Write a JSON object describing a library book, then explain each field.",
63];
64
65/// Draft run lengths are counted up to this many tokens (the largest block size).
66const L_CAP: usize = 32;
67
68fn mem_available_gb() -> f64 {
69 std::fs::read_to_string("/proc/meminfo")
70 .ok()
71 .and_then(|t| {
72 t.lines()
73 .find(|l| l.starts_with("MemAvailable:"))
74 .and_then(|l| l.split_whitespace().nth(1))
75 .and_then(|v| v.parse::<f64>().ok())
76 })
77 .map(|kb| kb / 1024.0 / 1024.0)
78 .unwrap_or(0.0)
79}
80
81fn chat(tok: &Tokenizer, user: &str) -> Vec<u32> {
82 tok.encode_with_special(
83 &format!("<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n"),
84 false,
85 )
86 .expect("encode")
87}
88
89struct Ctx {
90 greedy: GenerateParams,
91 eos: Vec<u32>,
92}
93
94impl Ctx {
95 fn next(&self, e: &mut Qwen3MoeOmegaEngine, token: u32) -> u32 {
96 let h = e.step(token).expect("step");
97 let lg = e.logits(&h).expect("logits");
98 sample_next(&lg, &self.greedy, 0)
99 }
100}
101
102/// Prefill all but the last prompt token (KV only); returns the last token (not yet stepped).
103fn prefill(e: &mut Qwen3MoeOmegaEngine, prompt: &[u32]) -> u32 {
104 e.reset();
105 let body = &prompt[..prompt.len() - 1];
106 for chunk in body.chunks(e.prefill_chunk.max(1)) {
107 e.step_batch(chunk).expect("prefill");
108 }
109 *prompt.last().unwrap()
110}
111
112/// Full-model greedy continuation, token at a time, stop at EOS (not included) or `n`.
113fn reference(e: &mut Qwen3MoeOmegaEngine, cx: &Ctx, prompt: &[u32], n: usize) -> Vec<u32> {
114 let mut last = prefill(e, prompt);
115 let mut t = Vec::with_capacity(n);
116 while t.len() < n {
117 let nx = cx.next(e, last);
118 if cx.eos.contains(&nx) {
119 break;
120 }
121 t.push(nx);
122 last = nx;
123 }
124 t
125}
126
127fn main() {
128 let args: Vec<String> = std::env::args().collect();
129 let checkpoint = PathBuf::from(args.get(1).expect("checkpoint dir"));
130 let receipt = PathBuf::from(args.get(2).expect("receipt dir"));
131 let (mut new, mut max_context, mut force, mut cross) = (256usize, 4096usize, false, 3usize);
132 let (mut rs, mut ks) = (vec![16usize, 32, 64], vec![4usize, 8, 16, 32]);
133 let list = |s: &str| -> Vec<usize> { s.split(',').map(|v| v.parse().expect("n")).collect() };
134 let mut it = args[3..].iter();
135 while let Some(a) = it.next() {
136 match a.as_str() {
137 "--new" => new = it.next().expect("--new").parse().expect("n"),
138 "--rs" => rs = list(it.next().expect("--rs")),
139 "--ks" => ks = list(it.next().expect("--ks")),
140 "--max-context" => max_context = it.next().expect("n").parse().expect("n"),
141 "--cross-check" => cross = it.next().expect("n").parse().expect("n"),
142 "--force-memory" => force = true,
143 o => panic!("unknown argument {o}"),
144 }
145 }
146 assert!(ks.iter().all(|&k| k <= L_CAP), "block size above {L_CAP}");
147 std::fs::create_dir_all(&receipt).expect("receipt dir");
148 let mut log: Vec<String> = Vec::new();
149 let mut say = |s: String| {
150 println!("{s}");
151 log.push(s);
152 };
153 let avail = mem_available_gb();
154 say(format!("mem available before load: {avail:.1} GB"));
155 if avail < 70.0 && !force {
156 say("REFUSED: less than 70 GB available; --force-memory to override".into());
157 std::process::exit(3);
158 }
159 if let Some(us) =
160 aien_omega_gpu::parse_spin_us(std::env::var(aien_omega_gpu::SPIN_US_ENV).ok().as_deref())
161 .expect("spin env")
162 {
163 aien_omega_gpu::set_spin_us(us).expect("set spin window");
164 }
165 say(format!(
166 "build native={} spin_us={:?}",
167 aien_omega_gpu::is_native(),
168 aien_omega_gpu::spin_us()
169 ));
170 let tok = Tokenizer::from_file(checkpoint.join("tokenizer.json")).expect("tokenizer");
171 let t0 = Instant::now();
172 let (mut e, report) = Qwen3MoeOmegaEngine::load_omega_paths(
173 &checkpoint,
174 max_context,
175 WeightFormat::Fp8All,
176 AttnPath::Fused,
177 DevicePaths::default(),
178 &mut |_| {},
179 )
180 .expect("load on Omega");
181 let (layers, experts) = (e.config().layers, e.config().experts);
182 let cx = Ctx {
183 greedy: GenerateParams::greedy(new, Vec::new()),
184 eos: e.config().eos_token_ids.clone(),
185 };
186 say(format!(
187 "LOAD {:.1}s resident {:.2} GB attention {} device_routing {}",
188 t0.elapsed().as_secs_f64(),
189 report.resident_bytes as f64 / 1e9,
190 e.attention_path(),
191 e.device_routing
192 ));
193
194 // 1. Calibration trace.
195 let t1 = Instant::now();
196 e.expert_counts = Some(vec![0; layers * experts]);
197 let mut calib_tokens = 0usize;
198 for p in CALIB {
199 calib_tokens += reference(&mut e, &cx, &chat(&tok, p), new).len();
200 }
201 let counts = e.expert_counts.take().unwrap();
202 let mut residents: Vec<(usize, Vec<Vec<u32>>, f64)> = Vec::new();
203 for &r in &rs {
204 let mut sets = Vec::with_capacity(layers);
205 let (mut covered, mut total) = (0u64, 0u64);
206 for l in 0..layers {
207 let row = &counts[l * experts..(l + 1) * experts];
208 let mut ids: Vec<u32> = (0..experts as u32).collect();
209 ids.sort_by(|&a, &b| row[b as usize].cmp(&row[a as usize]).then(a.cmp(&b)));
210 ids.truncate(r);
211 covered += ids.iter().map(|&x| row[x as usize]).sum::<u64>();
212 total += row.iter().sum::<u64>();
213 sets.push(ids);
214 }
215 let cov = covered as f64 / total.max(1) as f64;
216 say(format!(
217 "CALIB R={r} trace-coverage {:.4} ({covered}/{total} routed picks)",
218 cov
219 ));
220 residents.push((r, sets, cov));
221 }
222 say(format!(
223 "CALIB {} prompts, {calib_tokens} decode tokens traced, {:.1}s",
224 CALIB.len(),
225 t1.elapsed().as_secs_f64()
226 ));
227
228 // 2 + 3. Reference and draft run lengths per position.
229 // runs[ri][prompt] = L_R(p) for every p in T.
230 let mut runs: Vec<Vec<Vec<usize>>> = vec![Vec::new(); residents.len()];
231 let mut refs: Vec<Vec<u32>> = Vec::new();
232 let t2 = Instant::now();
233 for (pi, text) in EVAL.iter().enumerate() {
234 let prompt = chat(&tok, text);
235 let t = reference(&mut e, &cx, &prompt, new);
236 let base = prompt.len() - 1; // KV positions holding the committed prefix minus its last token
237 let mut per_r: Vec<Vec<usize>> = vec![Vec::with_capacity(t.len()); residents.len()];
238 let mut last = prefill(&mut e, &prompt);
239 for p in 0..t.len() {
240 for (ri, (_, sets, _)) in residents.iter().enumerate() {
241 e.set_draft_experts(Some(sets.clone())).expect("mask");
242 let mut cur = last;
243 let mut l = 0usize;
244 while l < L_CAP && p + l < t.len() {
245 let d = cx.next(&mut e, cur);
246 if d != t[p + l] {
247 break;
248 }
249 cur = d;
250 l += 1;
251 }
252 per_r[ri].push(l);
253 e.set_draft_experts(None).expect("unmask");
254 e.rewind(base + p);
255 }
256 // Advance the full-model KV by the committed token and check it reproduces T.
257 let v = cx.next(&mut e, last);
258 assert_eq!(
259 v, t[p],
260 "prompt {pi} position {p}: full model not deterministic"
261 );
262 last = v;
263 }
264 say(format!(
265 "EVAL prompt {pi:02} prompt_tokens {} generated {} mean L {}",
266 prompt.len(),
267 t.len(),
268 per_r
269 .iter()
270 .map(|v| format!(
271 "{:.2}",
272 v.iter().sum::<usize>() as f64 / v.len().max(1) as f64
273 ))
274 .collect::<Vec<_>>()
275 .join("/")
276 ));
277 for (ri, v) in per_r.into_iter().enumerate() {
278 runs[ri].push(v);
279 }
280 refs.push(t);
281 }
282 say(format!(
283 "EVAL run lengths {:.1}s",
284 t2.elapsed().as_secs_f64()
285 ));
286
287 // 4. Simulation.
288 let simulate = |l: &[usize], k: usize| -> usize {
289 let (mut p, mut blocks) = (0usize, 0usize);
290 while p < l.len() {
291 blocks += 1;
292 p += l[p].min(k) + 1;
293 }
294 blocks
295 };
296 let total_tokens: usize = refs.iter().map(|t| t.len()).sum();
297 let mut table = Vec::new();
298 for (ri, (r, _, cov)) in residents.iter().enumerate() {
299 for &k in &ks {
300 let blocks: usize = runs[ri].iter().map(|l| simulate(l, k)).sum();
301 let accepted: usize = total_tokens - blocks;
302 let tpb = total_tokens as f64 / blocks as f64;
303 say(format!(
304 "ACCEPT R={r} k={k} tokens {total_tokens} blocks {blocks} accepted_draft {accepted} tokens_per_block {tpb:.3} accept_rate {:.4}",
305 accepted as f64 / (blocks * k) as f64
306 ));
307 table.push(serde_json::json!({
308 "R": r, "k": k, "tokens": total_tokens, "blocks": blocks,
309 "accepted_draft_tokens": accepted, "trace_coverage": cov,
310 }));
311 }
312 }
313
314 // 5. Literal cross-check at k = 8.
315 let k = 8usize;
316 let mut cross_ok = true;
317 for (pi, text) in EVAL.iter().enumerate().take(cross) {
318 let prompt = chat(&tok, text);
319 let base = prompt.len() - 1;
320 for (ri, (r, sets, _)) in residents.iter().enumerate() {
321 let t = &refs[pi];
322 let mut last = prefill(&mut e, &prompt);
323 let (mut out, mut blocks) = (Vec::<u32>::new(), 0usize);
324 while out.len() < t.len() {
325 blocks += 1;
326 let committed = base + out.len();
327 // Draft k with the mask.
328 e.set_draft_experts(Some(sets.clone())).expect("mask");
329 let mut draft = Vec::with_capacity(k);
330 let mut cur = last;
331 for _ in 0..k {
332 cur = cx.next(&mut e, cur);
333 draft.push(cur);
334 }
335 e.set_draft_experts(None).expect("unmask");
336 e.rewind(committed);
337 // Verify exactly: full-model step + logits over last, d1, ..., stop at a miss.
338 let mut cur = last;
339 let mut i = 0usize;
340 loop {
341 let v = cx.next(&mut e, cur);
342 out.push(v);
343 if i < k && draft[i] == v && out.len() < t.len() {
344 cur = v;
345 i += 1;
346 } else {
347 break;
348 }
349 }
350 last = *out.last().unwrap();
351 // KV holds committed + accepted + 1 positions; the new last token is not stepped.
352 e.rewind(base + out.len());
353 }
354 out.truncate(t.len());
355 let want = simulate(&runs[ri][pi], k);
356 let ok = &out == t && blocks == want;
357 cross_ok &= ok;
358 say(format!(
359 "CROSS prompt {pi:02} R={r} k={k} literal blocks {blocks} simulated {want} tokens_match {} {}",
360 &out == t,
361 if ok { "OK" } else { "MISMATCH" }
362 ));
363 }
364 }
365 say(format!(
366 "SUMMARY eval_prompts {} tokens {total_tokens} cross_check {}",
367 EVAL.len(),
368 if cross_ok { "PASS" } else { "FAIL" }
369 ));
370 let json = serde_json::json!({
371 "calib_prompts": CALIB.len(), "calib_decode_tokens": calib_tokens,
372 "eval_prompts": EVAL.len(), "new": new, "table": table, "cross_check": cross_ok,
373 "resident_sets": residents.iter().map(|(r, s, _)| serde_json::json!({"R": r, "sets": s})).collect::<Vec<_>>(),
374 "runs": runs,
375 });
376 std::fs::write(
377 receipt.join("run.json"),
378 serde_json::to_string(&json).unwrap(),
379 )
380 .unwrap();
381 std::fs::write(receipt.join("run.txt"), log.join("\n") + "\n").unwrap();
382 if !cross_ok {
383 std::process::exit(1);
384 }
385}