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-inference-abi / src / bin / qwen38_prefill.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Qwen3.8-27B whole-prompt prefill on the Omega engine (sc #642 step 9): parity and time to |
| 17 | //! first token. |
| 18 | //! |
| 19 | //! qwen38_prefill golden <checkpoint-dir> <golden.json> <chunk> <out.json> |
| 20 | //! qwen38_prefill score <checkpoint-dir> <score.json> <chunk> <out.json> |
| 21 | //! qwen38_prefill ttft <checkpoint-dir> <corpus.txt> <len,len,...> <chunk> <out.json> |
| 22 | //! |
| 23 | //! `golden`: a `qwen38_check generate` record (host reference). The prompt is prefilled in chunks |
| 24 | //! of `chunk`, then the decode graph continues greedily; every generated token must equal the |
| 25 | //! reference's. The prefill's last logits are also held to the decode graph's logits for the same |
| 26 | //! prompt fed one token at a time (cosine), with a control: the decode graph's logits one position |
| 27 | //! earlier must fall below the bar. |
| 28 | //! |
| 29 | //! `score`: a `qwen38_check score` record (host reference, per-token NLL of a passage). The |
| 30 | //! passage is prefilled in chunks and every position's next-token NLL comes from the prefill's |
| 31 | //! residual rows; the mean NLL must be within 2% of the reference's and the next-token accuracy |
| 32 | //! within 2 points. Control: the NLL against the token two ahead must be at least 1 nat worse. |
| 33 | //! |
| 34 | //! `ttft`: for each length, a fresh sequence (state reset) prefilled with the first `len` tokens |
| 35 | //! of `corpus.txt` (tokenised in pieces of at most 2000 characters, the tokenizer's limit); |
| 36 | //! the time from the call to the first generated token, with the breakdown. |
| 37 | //! |
| 38 | //! The whole model is resident (about 25.7 GiB) plus the KV cache for the longest sequence. The |
| 39 | //! upload is refused unless MemAvailable covers that plus 12 GiB kept free (the resident 30B server |
| 40 | //! shares the memory; OOM lesson of 2026-10-18 16:43:58Z). |
| 41 | |
| 42 | use std::path::Path; |
| 43 | use std::time::Instant; |
| 44 | |
| 45 | use aien_inference_abi::qwen38::{argmax, Qwen38Config}; |
| 46 | use aien_inference_abi::qwen38_omega::{need_bytes, PrefillStats, Qwen38Omega}; |
| 47 | use aien_inference_abi::qwen3_moe::parity_stats; |
| 48 | use aien_inference_abi::tokenizer::ChatTokenizer; |
| 49 | use serde_json::{json, Value}; |
| 50 | |
| 51 | const COSINE_MIN: f64 = 0.999; |
| 52 | const KEEP_FREE: u64 = 12 << 30; |
| 53 | const TOKENIZE_PIECE: usize = 2000; |
| 54 | |
| 55 | fn mem_available() -> Result<u64, String> { |
| 56 | let text = std::fs::read_to_string("/proc/meminfo").map_err(|e| e.to_string())?; |
| 57 | text.lines() |
| 58 | .find_map(|l| l.strip_prefix("MemAvailable:")) |
| 59 | .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok()) |
| 60 | .map(|kb| kb * 1024) |
| 61 | .ok_or_else(|| "/proc/meminfo: no MemAvailable".into()) |
| 62 | } |
| 63 | |
| 64 | fn open(dir: &Path, max_pos: usize, chunk: usize) -> Result<Qwen38Omega, String> { |
| 65 | // The attention cache holds whole score passes of 256 positions (OMEGA_DATTN256_CHUNK). |
| 66 | let max_pos = max_pos.next_multiple_of(256); |
| 67 | let c = Qwen38Config::from_checkpoint(dir)?; |
| 68 | let need = need_bytes(&c, max_pos, chunk); |
| 69 | let avail = mem_available()?; |
| 70 | if avail < need + KEEP_FREE { |
| 71 | return Err(format!( |
| 72 | "needs {} MiB with {} MiB kept free, MemAvailable {} MiB; refusing", |
| 73 | need >> 20, |
| 74 | KEEP_FREE >> 20, |
| 75 | avail >> 20 |
| 76 | )); |
| 77 | } |
| 78 | eprintln!( |
| 79 | "upload: need {} MiB, MemAvailable {} MiB", |
| 80 | need >> 20, |
| 81 | avail >> 20 |
| 82 | ); |
| 83 | Qwen38Omega::open(dir, None, max_pos) |
| 84 | } |
| 85 | |
| 86 | fn stats_json(s: &PrefillStats) -> Value { |
| 87 | json!({ |
| 88 | "tokens": s.tokens, "chunks": s.chunks, "wall_ns": s.wall_ns, |
| 89 | "gemm_chip_ns": s.gemm_chip_ns, "gemm_call_ns": s.gemm_call_ns, |
| 90 | "gemm_launches": s.gemm_launches, "ab_call_ns": s.ab_call_ns, |
| 91 | "gdn_chip_ns": s.gdn_chip_ns, "gdn_call_ns": s.gdn_call_ns, |
| 92 | "attn_chip_ns": s.attn_chip_ns, "attn_call_ns": s.attn_call_ns, |
| 93 | "host_ns": s.host_ns, "head_ns": s.head_ns, |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | fn read_json(p: &str) -> Result<Value, String> { |
| 98 | serde_json::from_str(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?) |
| 99 | .map_err(|e| format!("{p}: {e}")) |
| 100 | } |
| 101 | |
| 102 | fn ids(v: &Value, key: &str) -> Result<Vec<u32>, String> { |
| 103 | v[key] |
| 104 | .as_array() |
| 105 | .ok_or_else(|| format!("no {key}"))? |
| 106 | .iter() |
| 107 | .map(|x| x.as_u64().map(|t| t as u32).ok_or("bad id".to_string())) |
| 108 | .collect() |
| 109 | } |
| 110 | |
| 111 | fn golden(dir: &Path, golden: &str, chunk: usize) -> Result<(bool, Value), String> { |
| 112 | let g = read_json(golden)?; |
| 113 | let prompt = ids(&g, "prompt_ids")?; |
| 114 | let want = ids(&g, "generated_ids")?; |
| 115 | let mut e = open(dir, prompt.len() + want.len() + 1, chunk)?; |
| 116 | |
| 117 | // Decode graph, one token at a time: the logits after the last and second to last prompt token. |
| 118 | e.reset()?; |
| 119 | let mut dec_prev = Vec::new(); |
| 120 | for (i, &t) in prompt.iter().enumerate() { |
| 121 | e.step(t)?; |
| 122 | if i + 2 == prompt.len() { |
| 123 | dec_prev = e.logits()?; |
| 124 | } |
| 125 | } |
| 126 | let dec = e.logits()?; |
| 127 | |
| 128 | // Prefill, then greedy decode. |
| 129 | e.reset()?; |
| 130 | let (first, logits, st) = e.prefill(&prompt, chunk)?; |
| 131 | let mut got = vec![first]; |
| 132 | while got.len() < want.len() { |
| 133 | let (next, _) = e.step(*got.last().unwrap())?; |
| 134 | got.push(next); |
| 135 | } |
| 136 | let p = parity_stats(&logits, &dec); |
| 137 | let control = parity_stats(&logits, &dec_prev); |
| 138 | let same = got == want; |
| 139 | let pass = same |
| 140 | && p.cosine >= COSINE_MIN |
| 141 | && control.cosine < COSINE_MIN |
| 142 | && argmax(&dec) as u32 == first; |
| 143 | Ok(( |
| 144 | pass, |
| 145 | json!({ |
| 146 | "mode": "golden", "prompt_tokens": prompt.len(), "chunk": chunk, |
| 147 | "generated": got, "expected": want, "tokens_equal": same, |
| 148 | "first_token_decode_graph": argmax(&dec), "first_token_prefill": first, |
| 149 | "cosine_vs_decode_graph": p.cosine, "max_abs_vs_decode_graph": p.max_abs, |
| 150 | "control_cosine_vs_previous_position": control.cosine, |
| 151 | "cosine_min": COSINE_MIN, "stats": stats_json(&st), "pass": pass, |
| 152 | }), |
| 153 | )) |
| 154 | } |
| 155 | |
| 156 | fn log_softmax_at(logits: &[f32], t: usize) -> f64 { |
| 157 | let max = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max) as f64; |
| 158 | let sum: f64 = logits.iter().map(|&v| (v as f64 - max).exp()).sum(); |
| 159 | logits[t] as f64 - max - sum.ln() |
| 160 | } |
| 161 | |
| 162 | fn score(dir: &Path, record: &str, chunk: usize) -> Result<(bool, Value), String> { |
| 163 | let r = read_json(record)?; |
| 164 | let toks = ids(&r, "ids")?; |
| 165 | let ref_mean = r["mean_nll"].as_f64().ok_or("no mean_nll")?; |
| 166 | let ref_acc = r["next_token_accuracy"] |
| 167 | .as_f64() |
| 168 | .ok_or("no next_token_accuracy")?; |
| 169 | let ref_nll: Vec<f64> = r["nll"] |
| 170 | .as_array() |
| 171 | .ok_or("no nll")? |
| 172 | .iter() |
| 173 | .filter_map(Value::as_f64) |
| 174 | .collect(); |
| 175 | let n = toks.len(); |
| 176 | let h = Qwen38Config::from_checkpoint(dir)?.hidden; |
| 177 | let mut e = open(dir, n + 1, chunk)?; |
| 178 | e.reset()?; |
| 179 | let (rows, st) = e.prefill_rows(&toks, chunk, true)?; |
| 180 | let (mut nll, mut ctrl, mut hits) = (Vec::with_capacity(n), 0f64, 0usize); |
| 181 | for p in 0..n - 1 { |
| 182 | let logits = e.head_logits(&rows[p * h..(p + 1) * h])?; |
| 183 | let next = toks[p + 1] as usize; |
| 184 | nll.push(-log_softmax_at(&logits, next)); |
| 185 | if argmax(&logits) == next { |
| 186 | hits += 1; |
| 187 | } |
| 188 | if p + 2 < n { |
| 189 | ctrl += -log_softmax_at(&logits, toks[p + 2] as usize); |
| 190 | } |
| 191 | } |
| 192 | let mean = nll.iter().sum::<f64>() / nll.len() as f64; |
| 193 | let acc = hits as f64 / nll.len() as f64; |
| 194 | let ctrl_mean = ctrl / (n - 2) as f64; |
| 195 | let (mut max_d, mut sum_d) = (0f64, 0f64); |
| 196 | for (a, b) in nll.iter().zip(&ref_nll) { |
| 197 | let d = (a - b).abs(); |
| 198 | max_d = max_d.max(d); |
| 199 | sum_d += d; |
| 200 | } |
| 201 | let mean_ok = (mean - ref_mean).abs() <= 0.02 * ref_mean; |
| 202 | let acc_ok = (acc - ref_acc).abs() <= 0.02; |
| 203 | let ctrl_ok = ctrl_mean >= ref_mean + 1.0; |
| 204 | let pass = mean_ok && acc_ok && ctrl_ok && ref_nll.len() == nll.len(); |
| 205 | Ok(( |
| 206 | pass, |
| 207 | json!({ |
| 208 | "mode": "score", "tokens": n, "chunk": chunk, |
| 209 | "mean_nll": mean, "reference_mean_nll": ref_mean, |
| 210 | "perplexity": mean.exp(), "reference_perplexity": ref_mean.exp(), |
| 211 | "next_token_accuracy": acc, "reference_next_token_accuracy": ref_acc, |
| 212 | "max_abs_nll_diff": max_d, "mean_abs_nll_diff": sum_d / nll.len() as f64, |
| 213 | "control_mean_nll_two_ahead": ctrl_mean, |
| 214 | "stats": stats_json(&st), "pass": pass, |
| 215 | }), |
| 216 | )) |
| 217 | } |
| 218 | |
| 219 | fn corpus_tokens(dir: &Path, corpus: &str, want: usize) -> Result<Vec<u32>, String> { |
| 220 | let tk = ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?; |
| 221 | let text = std::fs::read_to_string(corpus).map_err(|e| format!("{corpus}: {e}"))?; |
| 222 | let mut out = encode_pieces(&tk, &text, want)?; |
| 223 | if out.len() < want { |
| 224 | return Err(format!("{corpus}: {} tokens, {want} wanted", out.len())); |
| 225 | } |
| 226 | out.truncate(want); |
| 227 | Ok(out) |
| 228 | } |
| 229 | |
| 230 | /// The tokenizer refuses sequences over 2048 tokens, so text goes in pieces of at most TOKENIZE_PIECE bytes, |
| 231 | /// stopping once `want` tokens are in hand. |
| 232 | fn encode_pieces(tk: &ChatTokenizer, text: &str, want: usize) -> Result<Vec<u32>, String> { |
| 233 | let mut out = Vec::with_capacity(want.min(text.len())); |
| 234 | let mut rest = text; |
| 235 | while out.len() < want && !rest.is_empty() { |
| 236 | let mut cut = rest.len().min(TOKENIZE_PIECE); |
| 237 | while !rest.is_char_boundary(cut) { |
| 238 | cut -= 1; |
| 239 | } |
| 240 | out.extend(tk.encode(&rest[..cut]).map_err(|e| e.to_string())?); |
| 241 | rest = &rest[cut..]; |
| 242 | } |
| 243 | Ok(out) |
| 244 | } |
| 245 | |
| 246 | fn ttft(dir: &Path, corpus: &str, lens: &[usize], chunk: usize) -> Result<(bool, Value), String> { |
| 247 | let max = *lens.iter().max().ok_or("no lengths")?; |
| 248 | let t = Instant::now(); |
| 249 | let toks = corpus_tokens(dir, corpus, max)?; |
| 250 | eprintln!( |
| 251 | "corpus: {} tokens in {:.1} s", |
| 252 | toks.len(), |
| 253 | t.elapsed().as_secs_f64() |
| 254 | ); |
| 255 | let mut e = open(dir, max, chunk)?; |
| 256 | let mut runs = Vec::new(); |
| 257 | for &n in lens { |
| 258 | e.reset()?; |
| 259 | let (first, _, st) = e.prefill(&toks[..n], chunk)?; |
| 260 | let s = st.wall_ns as f64 / 1e9; |
| 261 | eprintln!( |
| 262 | "len {n}: TTFT {s:.3} s ({:.0} tok/s), first token {first}; gemm chip {:.1} s, gdn call {:.1} s, attn call {:.1} s, a|b {:.1} s, host {:.1} s", |
| 263 | n as f64 / s, |
| 264 | st.gemm_chip_ns as f64 / 1e9, |
| 265 | st.gdn_call_ns as f64 / 1e9, |
| 266 | st.attn_call_ns as f64 / 1e9, |
| 267 | st.ab_call_ns as f64 / 1e9, |
| 268 | st.host_ns as f64 / 1e9 |
| 269 | ); |
| 270 | runs.push(json!({ |
| 271 | "tokens": n, "ttft_s": s, "first_token": first, "stats": stats_json(&st), |
| 272 | })); |
| 273 | } |
| 274 | Ok(( |
| 275 | true, |
| 276 | json!({ "mode": "ttft", "chunk": chunk, "corpus": corpus, "runs": runs }), |
| 277 | )) |
| 278 | } |
| 279 | |
| 280 | /// Writes prompt-<len>.txt, the text of the first <len> corpus tokens, so other servers can be sent the same |
| 281 | /// bytes the ttft mode prefills. Re-encoding that text in one piece is timed: the tokenizer cost the |
| 282 | /// in-process ttft leaves out. |
| 283 | fn prompts(dir: &Path, corpus: &str, lens: &[usize], out: &Path) -> Result<(bool, Value), String> { |
| 284 | let max = *lens.iter().max().ok_or("no lengths")?; |
| 285 | let toks = corpus_tokens(dir, corpus, max)?; |
| 286 | let tk = ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?; |
| 287 | std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; |
| 288 | let mut rows = Vec::new(); |
| 289 | let mut pass = true; |
| 290 | for &n in lens { |
| 291 | let text = tk.decode(&toks[..n]).map_err(|e| e.to_string())?; |
| 292 | let t = Instant::now(); |
| 293 | let again = encode_pieces(&tk, &text, usize::MAX)?.len(); |
| 294 | let encode_ms = t.elapsed().as_secs_f64() * 1e3; |
| 295 | let path = out.join(format!("prompt-{n}.txt")); |
| 296 | std::fs::write(&path, &text).map_err(|e| format!("{}: {e}", path.display()))?; |
| 297 | // The servers count the re-encoded text plus their chat template; 1% is the side-by-side's void line. |
| 298 | let ok = again.abs_diff(n) * 100 <= n; |
| 299 | pass &= ok; |
| 300 | eprintln!( |
| 301 | "len {n}: {} bytes, re-encoded {again} tokens in {encode_ms:.1} ms", |
| 302 | text.len() |
| 303 | ); |
| 304 | rows.push(json!({"tokens": n, "bytes": text.len(), "reencoded_tokens": again, |
| 305 | "encode_ms": encode_ms, "file": path.display().to_string(), "within_1pct": ok})); |
| 306 | } |
| 307 | Ok(( |
| 308 | pass, |
| 309 | json!({"mode": "prompts", "corpus": corpus, "prompts": rows}), |
| 310 | )) |
| 311 | } |
| 312 | |
| 313 | fn main() { |
| 314 | let a: Vec<String> = std::env::args().collect(); |
| 315 | let usage = "usage: qwen38_prefill golden|score <dir> <record.json> <chunk> <out.json> | ttft <dir> <corpus.txt> <len,...> <chunk> <out.json> | prompts <dir> <corpus.txt> <len,...> <out-dir>"; |
| 316 | let res = (|| -> Result<(bool, Value, String), String> { |
| 317 | match a.get(1).map(String::as_str) { |
| 318 | Some(mode @ ("golden" | "score")) if a.len() == 6 => { |
| 319 | let chunk: usize = a[4].parse().map_err(|_| usage.to_string())?; |
| 320 | let dir = Path::new(&a[2]); |
| 321 | let (pass, v) = if mode == "golden" { |
| 322 | golden(dir, &a[3], chunk)? |
| 323 | } else { |
| 324 | score(dir, &a[3], chunk)? |
| 325 | }; |
| 326 | Ok((pass, v, a[5].clone())) |
| 327 | } |
| 328 | Some("ttft") if a.len() == 7 => { |
| 329 | let lens: Vec<usize> = a[4] |
| 330 | .split(',') |
| 331 | .map(|s| s.parse().map_err(|_| usage.to_string())) |
| 332 | .collect::<Result<_, _>>()?; |
| 333 | let chunk: usize = a[5].parse().map_err(|_| usage.to_string())?; |
| 334 | let (pass, v) = ttft(Path::new(&a[2]), &a[3], &lens, chunk)?; |
| 335 | Ok((pass, v, a[6].clone())) |
| 336 | } |
| 337 | Some("prompts") if a.len() == 6 => { |
| 338 | let lens: Vec<usize> = a[4] |
| 339 | .split(',') |
| 340 | .map(|s| s.parse().map_err(|_| usage.to_string())) |
| 341 | .collect::<Result<_, _>>()?; |
| 342 | let (pass, v) = prompts(Path::new(&a[2]), &a[3], &lens, Path::new(&a[5]))?; |
| 343 | Ok(( |
| 344 | pass, |
| 345 | v, |
| 346 | Path::new(&a[5]).join("prompts.json").display().to_string(), |
| 347 | )) |
| 348 | } |
| 349 | _ => Err(usage.to_string()), |
| 350 | } |
| 351 | })(); |
| 352 | match res { |
| 353 | Ok((pass, v, out)) => { |
| 354 | let text = serde_json::to_string_pretty(&v).expect("json"); |
| 355 | if let Err(e) = std::fs::write(&out, &text) { |
| 356 | eprintln!("{out}: {e}"); |
| 357 | std::process::exit(2); |
| 358 | } |
| 359 | println!("{text}"); |
| 360 | println!("{}", if pass { "PASS" } else { "FAIL" }); |
| 361 | std::process::exit(if pass { 0 } else { 1 }); |
| 362 | } |
| 363 | Err(e) => { |
| 364 | eprintln!("qwen38_prefill: {e}"); |
| 365 | std::process::exit(2); |
| 366 | } |
| 367 | } |
| 368 | } |