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 / qwen36_prefill_gate.rs

240 lines · 9697 bytes Raw Blame History
1//! Prefill gate for the 35B (L369): a prompt read in chunks through the chip must leave the
2//! conversation in the same state, bit for bit, as the same prompt fed token by token through the
3//! decode graph (today's served path), and the replies after it must be the same.
4//!
5//! ```text
6//! qwen36_prefill_gate <checkpoint-dir> <corpus.txt> <len,len,...> <chunk> <decode> <out.json> [layers]
7//! ```
8//!
9//! One graph with two head slots over one upload ([`Qwen38Omega::open_window_heads`]). For each
10//! length, both slots are emptied, then the first `len` tokens of `corpus.txt`:
11//! - slot 0 token by token ([`Qwen38Omega::step`], the decode graph): time A;
12//! - slot 1 in chunks of `chunk` ([`Qwen38Omega::prefill_moe_head`]): time B.
13//!
14//! PASS needs, for every length: the last prompt token's greedy token and logits bit-identical;
15//! every DeltaNet state and conv tail bit-identical ([`Qwen38Snapshot::first_diff`]); then
16//! `decode` greedy steps with both slots in one stroke, each step's tokens and logits
17//! bit-identical (this reads the KV caches the prompt wrote). Exit 0 PASS, 1 FAIL, 2 error.
18//! Prompt tokens per second, A and B, are in the record (a receipt only inside a chip window).
19//!
20//! Negative controls, each must FAIL: `AIEN_OMEGA_Q36_PF_MUTANT=1` (the last two tokens' GDN
21//! steps swapped), `=2` (every expert segment one row short) and `=3` (each token's DeltaNet output copied
22//! after the whole chunk instead of right after its step).
23//!
24//! `layers`: a model prefix (the first `layers` layers) for a small load; the full 35B loads only
25//! under `q36-extra` (one extra 35B beside the live server).
26use std::path::Path;
27use std::time::Instant;
28
29use aien_inference_abi::qwen38_omega::{Qwen38Omega, Qwen38Snapshot};
30use aien_inference_abi::tokenizer::ChatTokenizer;
31use serde_json::{json, Value};
32
33const TOKENIZE_PIECE: usize = 2000;
34
35fn corpus_tokens(dir: &Path, corpus: &str, want: usize) -> Result<Vec<u32>, String> {
36 let tk = ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?;
37 let text = std::fs::read_to_string(corpus).map_err(|e| format!("{corpus}: {e}"))?;
38 let mut out = Vec::with_capacity(want);
39 let mut rest = text.as_str();
40 while out.len() < want && !rest.is_empty() {
41 let mut cut = rest.len().min(TOKENIZE_PIECE);
42 while !rest.is_char_boundary(cut) {
43 cut -= 1;
44 }
45 out.extend(tk.encode(&rest[..cut]).map_err(|e| e.to_string())?);
46 rest = &rest[cut..];
47 }
48 if out.len() < want {
49 return Err(format!("{corpus}: {} tokens, {want} wanted", out.len()));
50 }
51 out.truncate(want);
52 Ok(out)
53}
54
55fn first_bit_diff(a: &[f32], b: &[f32]) -> Option<usize> {
56 if a.len() != b.len() {
57 return Some(a.len().min(b.len()));
58 }
59 a.iter()
60 .zip(b)
61 .position(|(x, y)| x.to_bits() != y.to_bits())
62}
63
64/// Head 1's state as a snapshot: the snapshot reads slot 0, so the slots trade places around it.
65fn snap_head(m: &mut Qwen38Omega, head: usize) -> Result<Qwen38Snapshot, String> {
66 let mut s = Qwen38Snapshot::default();
67 if head == 0 {
68 m.snapshot(&mut s)?;
69 } else {
70 m.swap_heads(0, head)?;
71 let r = m.snapshot(&mut s);
72 m.swap_heads(0, head)?;
73 r?;
74 }
75 Ok(s)
76}
77
78fn one(m: &mut Qwen38Omega, prompt: &[u32], chunk: usize, decode: usize) -> Result<Value, String> {
79 let n = prompt.len();
80 m.reset_head(0)?;
81 m.reset_head(1)?;
82 let t = Instant::now();
83 let mut next_a = 0u32;
84 for &tok in prompt {
85 next_a = m.step(tok)?.0;
86 }
87 let ms_a = t.elapsed().as_secs_f64() * 1e3;
88 let logits_a = m.logits_head(0)?;
89 let s0 = m.q36_prefill_streamed();
90 let t = Instant::now();
91 let (next_b, chunks) = m.prefill_moe_head(1, prompt, chunk, true)?;
92 let ms_b = t.elapsed().as_secs_f64() * 1e3;
93 let streamed = m.q36_prefill_streamed() - s0;
94 let next_b = next_b.ok_or("prefill gave no token")?;
95 let logits_b = m.logits_head(1)?;
96 let logits_diff = first_bit_diff(&logits_a, &logits_b);
97 let (sa, sb) = (snap_head(m, 0)?, snap_head(m, 1)?);
98 let state_diff = sa.first_diff(&sb);
99 let (mut a, mut b) = (next_a, next_b);
100 let mut decode_diff: Option<usize> = None;
101 let (mut toks_a, mut toks_b) = (Vec::new(), Vec::new());
102 for d in 0..decode {
103 let (out, _) = m.stroke(&[a, b])?;
104 let (la, lb) = (m.logits_head(0)?, m.logits_head(1)?);
105 toks_a.push(out[0]);
106 toks_b.push(out[1]);
107 if decode_diff.is_none() && (out[0] != out[1] || first_bit_diff(&la, &lb).is_some()) {
108 decode_diff = Some(d);
109 }
110 (a, b) = (out[0], out[1]);
111 }
112 let pass =
113 next_a == next_b && logits_diff.is_none() && state_diff.is_none() && decode_diff.is_none();
114 let rec = json!({
115 "len": n, "chunk": chunk, "chunks": chunks, "pass": pass,
116 "token_by_token_ms": ms_a, "chunked_ms": ms_b,
117 "token_by_token_tok_s": n as f64 / (ms_a / 1e3), "chunked_tok_s": n as f64 / (ms_b / 1e3),
118 "next": [next_a, next_b], "logits_first_diff": logits_diff, "state_first_diff": state_diff,
119 "decode_first_diff": decode_diff, "decode_tokens": [toks_a, toks_b],
120 "chunked_fp8_streamed_bytes": streamed, "chunked_fp8_gb_s": streamed as f64 / (ms_b * 1e6),
121 });
122 eprintln!(
123 "len {n}: {} | token by token {ms_a:.0} ms ({:.1} tok/s), chunked {ms_b:.0} ms ({:.1} tok/s, {chunks} chunks, fp8 {:.1} GB/s) | logits {:?} state {:?} decode {:?}",
124 if pass { "PASS" } else { "FAIL" },
125 n as f64 / (ms_a / 1e3),
126 n as f64 / (ms_b / 1e3),
127 streamed as f64 / (ms_b * 1e6),
128 logits_diff,
129 state_diff,
130 decode_diff
131 );
132 Ok(rec)
133}
134
135/// `L369_PROFILE=1`: one chunk on head 1 with the launch timestamps on, chip time per kind of launch
136/// (the first launch of each list also carries the host gap before it). Not a receipt outside a window.
137fn profile(m: &mut Qwen38Omega, prompt: &[u32], chunk: usize) -> Result<(), String> {
138 use aien_omega_q38::q36;
139 m.reset_head(1)?;
140 m.q36_graph_mut().ok_or("no q36 graph")?.set_stamps(true);
141 let t = Instant::now();
142 let r = m.prefill_moe_head(1, prompt, chunk, true);
143 let wall = t.elapsed().as_secs_f64() * 1e3;
144 let g = m.q36_graph_mut().ok_or("no q36 graph")?;
145 let tl = g.timeline().map_err(|e| format!("timeline: {e}"));
146 g.set_stamps(false);
147 r?;
148 let tl = tl?;
149 let mut per: Vec<(String, u64, u32)> = Vec::new();
150 for &(kind, d) in &tl {
151 let name = q36::Q36Graph::kind_name(kind);
152 match per.iter_mut().find(|e| e.0 == name) {
153 Some(e) => {
154 e.1 += d;
155 e.2 += 1
156 }
157 None => per.push((name, d, 1)),
158 }
159 }
160 per.sort_by_key(|e| std::cmp::Reverse(e.1));
161 let span: u64 = tl.iter().map(|e| e.1).sum();
162 eprintln!(
163 "profile: {} tokens, wall {wall:.1} ms, {} launches, stamp span {:.1} ms",
164 prompt.len(),
165 tl.len(),
166 span as f64 / 1e6
167 );
168 for (name, ns, c) in per {
169 eprintln!(
170 " {name:<12} {:>8.2} ms {:>5.1}% {c} launches",
171 ns as f64 / 1e6,
172 100.0 * ns as f64 / span as f64
173 );
174 }
175 Ok(())
176}
177
178fn run(args: &[String]) -> Result<bool, String> {
179 if args.len() < 7 {
180 return Err("usage: qwen36_prefill_gate <checkpoint-dir> <corpus.txt> <len,len,...> <chunk> <decode> <out.json> [layers]".into());
181 }
182 let dir = Path::new(&args[1]);
183 let lens: Vec<usize> = args[3]
184 .split(',')
185 .map(|s| {
186 s.trim()
187 .parse::<usize>()
188 .map_err(|e| format!("len {s}: {e}"))
189 })
190 .collect::<Result<_, _>>()?;
191 let chunk: usize = args[4].parse().map_err(|e| format!("chunk: {e}"))?;
192 let decode: usize = args[5].parse().map_err(|e| format!("decode: {e}"))?;
193 let out = &args[6];
194 let max_len = *lens.iter().max().ok_or("no lengths")?;
195 let prompt = corpus_tokens(dir, &args[2], max_len)?;
196 let full = aien_inference_abi::qwen38::Qwen38Config::from_checkpoint(dir)?;
197 let count = match args.get(7) {
198 Some(l) => l.parse::<usize>().map_err(|e| format!("layers: {e}"))?,
199 None => full.layers,
200 };
201 let t = Instant::now();
202 // the attention cache holds whole score passes of 256 positions
203 let max_pos = (max_len + decode + 1).next_multiple_of(256);
204 let mut m = Qwen38Omega::open_window_heads(dir, 0, count, max_pos, 2)?;
205 eprintln!(
206 "loaded {count} layers in {:.1} s",
207 t.elapsed().as_secs_f64()
208 );
209 let mut runs = Vec::new();
210 let mut all = true;
211 for &len in &lens {
212 let r = one(&mut m, &prompt[..len], chunk, decode)?;
213 all &= r["pass"].as_bool() == Some(true);
214 runs.push(r);
215 }
216 if std::env::var("L369_PROFILE").is_ok_and(|v| v == "1") {
217 profile(&mut m, &prompt[..chunk.min(max_len)], chunk)?;
218 }
219 let mutant = std::env::var("AIEN_OMEGA_Q36_PF_MUTANT").unwrap_or_default();
220 let rec = json!({ "gate": "qwen36_prefill_gate", "pass": all, "layers": count, "mutant": mutant, "runs": runs });
221 std::fs::write(
222 out,
223 serde_json::to_string_pretty(&rec).map_err(|e| e.to_string())? + "\n",
224 )
225 .map_err(|e| format!("{out}: {e}"))?;
226 eprintln!("{}", if all { "GATE PASS" } else { "GATE FAIL" });
227 Ok(all)
228}
229
230fn main() {
231 let args: Vec<String> = std::env::args().collect();
232 match run(&args) {
233 Ok(true) => {}
234 Ok(false) => std::process::exit(1),
235 Err(e) => {
236 eprintln!("qwen36_prefill_gate: {e}");
237 std::process::exit(2);
238 }
239 }
240}