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

210 lines · 9828 bytes Raw Blame History
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 host reference check (plan `~/handoffs/2026-10-18-qwen38-27b-on-omega.md`, step 2).
17//!
18//! qwen38_check score <checkpoint-dir> <passage.txt> <max-tokens> <out.json>
19//! qwen38_check generate <checkpoint-dir> <prompt.txt> <new-tokens> <out.json>
20//!
21//! Host only (no chip). `score` runs the passage's first `max-tokens` tokens through the
22//! reference in one pass and reports teacher-forced perplexity and next-token accuracy (wrong
23//! maths shows as a perplexity far above a few units). `generate` continues the prompt greedily
24//! and writes the ids and each step's top five logits: the golden tokens later stages are held
25//! to. Every pass streams the whole checkpoint from disk, so a generated token costs one pass.
26
27use std::path::Path;
28use std::time::Instant;
29
30use aien_inference_abi::qwen38::{argmax, negative_log_likelihood, Logits, Qwen38Reference};
31use aien_inference_abi::tokenizer::ChatTokenizer;
32use serde_json::json;
33
34fn top5(logits: &[f32]) -> Vec<(usize, f32)> {
35 let mut idx: Vec<usize> = (0..logits.len()).collect();
36 idx.sort_by(|&a, &b| logits[b].total_cmp(&logits[a]));
37 idx.into_iter().take(5).map(|i| (i, logits[i])).collect()
38}
39
40fn run() -> Result<(), String> {
41 let args: Vec<String> = std::env::args().collect();
42 let usage =
43 "usage: qwen38_check score|generate <checkpoint-dir> <text-file> <count> <out.json>";
44 if args.len() != 6 {
45 return Err(usage.into());
46 }
47 let (mode, dir, text_path, out_path) = (&args[1], Path::new(&args[2]), &args[3], &args[5]);
48 let count: usize = args[4].parse().map_err(|_| usage.to_string())?;
49 let mut text = std::fs::read_to_string(text_path).map_err(|e| format!("{text_path}: {e}"))?;
50 if mode == "score" {
51 // The tokenizer refuses more than 2048 tokens; a token is at least one character, so
52 // eight characters per wanted token leaves room and the ids are cut to `count` below.
53 if let Some((cut, _)) = text.char_indices().nth(count * 8) {
54 text.truncate(cut);
55 }
56 }
57 if mode == "jittercmp" {
58 // The text argument is a generate record (JSON), not a passage to encode.
59 text.clear();
60 }
61 let tokenizer =
62 ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?;
63 let mut ids = tokenizer.encode(&text).map_err(|e| e.to_string())?;
64
65 let t0 = Instant::now();
66 let mut model = Qwen38Reference::open(dir)?;
67 // Negative control (Q36): AIEN_Q36_ROUTING_MUTANT=1 swaps each token's 8th expert for its 9th,
68 // =2 sends every routed pick to the next expert id.
69 model.routing_mutant = std::env::var("AIEN_Q36_ROUTING_MUTANT")
70 .ok()
71 .and_then(|v| v.parse().ok())
72 .unwrap_or(0);
73 let open_s = t0.elapsed().as_secs_f64();
74 eprintln!("opened in {open_s:.1} s (embedding, final norm, lm_head)");
75 let vocab = model.config.vocab;
76 let mut state = model.new_state();
77
78 let report = match mode.as_str() {
79 "score" => {
80 ids.truncate(count);
81 if ids.len() < 2 {
82 return Err("score: the passage needs at least two tokens".into());
83 }
84 let t1 = Instant::now();
85 let logits = model.forward(&mut state, &ids, Logits::All)?;
86 let pass_s = t1.elapsed().as_secs_f64();
87 let mut nll = Vec::with_capacity(ids.len() - 1);
88 let mut hits = 0usize;
89 for (i, row) in logits.chunks_exact(vocab).take(ids.len() - 1).enumerate() {
90 let next = ids[i + 1] as usize;
91 nll.push(negative_log_likelihood(row, next));
92 hits += usize::from(argmax(row) == next);
93 }
94 let mean = nll.iter().sum::<f64>() / nll.len() as f64;
95 let ppl = mean.exp();
96 let acc = hits as f64 / nll.len() as f64;
97 eprintln!(
98 "scored {} tokens in {pass_s:.1} s: perplexity {ppl:.3}, next-token accuracy {acc:.3}",
99 ids.len()
100 );
101 json!({
102 "mode": "score", "passage": text_path, "tokens": ids.len(), "ids": ids,
103 "mean_nll": mean, "perplexity": ppl, "next_token_accuracy": acc,
104 "nll": nll, "pass_seconds": pass_s, "open_seconds": open_s,
105 })
106 }
107 "jittercmp" => {
108 // L306 noise-floor probe: the golden sequence (prompt + generated but the last) run
109 // clean, then once per AIEN_Q36_JITTER item `where:rel` (see Qwen38Reference::jitter);
110 // per position the logits cosine against the clean run.
111 let g: serde_json::Value = serde_json::from_str(
112 &std::fs::read_to_string(text_path).map_err(|e| format!("{text_path}: {e}"))?,
113 )
114 .map_err(|e| format!("{text_path}: {e}"))?;
115 let ids_of = |k: &str| -> Vec<u32> {
116 g[k].as_array()
117 .map(|a| {
118 a.iter()
119 .filter_map(|v| v.as_u64())
120 .map(|v| v as u32)
121 .collect()
122 })
123 .unwrap_or_default()
124 };
125 let mut toks = ids_of("prompt_ids");
126 let gen = ids_of("generated_ids");
127 toks.extend_from_slice(&gen[..gen.len().saturating_sub(1)]);
128 let clean = model.forward(&mut state, &toks, Logits::All)?;
129 let spec = std::env::var("AIEN_Q36_JITTER").unwrap_or_else(|_| "0:0".into());
130 let mut runs = Vec::new();
131 for item in spec.split(',') {
132 let (w, r) = item.split_once(':').ok_or("AIEN_Q36_JITTER: where:rel")?;
133 let w: u8 = w.parse().map_err(|_| "jitter where")?;
134 let r: f32 = r.parse().map_err(|_| "jitter rel")?;
135 model.jitter = (w, r);
136 let mut st = model.new_state();
137 let lg = model.forward(&mut st, &toks, Logits::All)?;
138 let cos: Vec<f64> = clean
139 .chunks_exact(vocab)
140 .zip(lg.chunks_exact(vocab))
141 .map(|(a, b)| {
142 let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64);
143 for (&x, &y) in a.iter().zip(b) {
144 ab += x as f64 * y as f64;
145 aa += x as f64 * x as f64;
146 bb += y as f64 * y as f64;
147 }
148 ab / (aa.sqrt() * bb.sqrt())
149 })
150 .collect();
151 let min = cos.iter().cloned().fold(1.0, f64::min);
152 let below = cos.iter().filter(|&&c| c < 0.9999).count();
153 eprintln!(
154 "jitter {w}:{r}: cosine(min) {min:.6}, {below}/{} positions under 0.9999",
155 cos.len()
156 );
157 runs.push(json!({"where": w, "rel": r, "cosine": cos, "cosine_min": min, "under_0_9999": below}));
158 }
159 model.jitter = (0, 0.0);
160 json!({"mode": "jittercmp", "golden": text_path, "positions": toks.len(), "runs": runs})
161 }
162 "generate" => {
163 let prompt = ids.clone();
164 let mut steps = Vec::new();
165 let t1 = Instant::now();
166 let mut logits = model.forward(&mut state, &prompt, Logits::Last)?;
167 let prefill_s = t1.elapsed().as_secs_f64();
168 let mut routes = vec![model.routes.clone()];
169 let mut gaps = vec![model.route_gaps.clone()];
170 let mut out = Vec::new();
171 let mut step_s = Vec::new();
172 for step in 0..count {
173 let next = argmax(&logits) as u32;
174 steps.push(top5(&logits));
175 out.push(next);
176 let piece = tokenizer.decode(&[next]).unwrap_or_default();
177 eprintln!("step {step}: {next} {piece:?}");
178 if model.config.eos_token_ids.contains(&next) || step + 1 == count {
179 break;
180 }
181 let t2 = Instant::now();
182 logits = model.forward(&mut state, &[next], Logits::Last)?;
183 routes.push(model.routes.clone());
184 gaps.push(model.route_gaps.clone());
185 step_s.push(t2.elapsed().as_secs_f64());
186 }
187 let text_out = tokenizer.decode(&out).map_err(|e| e.to_string())?;
188 eprintln!("continuation: {text_out:?}");
189 json!({
190 "mode": "generate", "prompt_file": text_path, "prompt_ids": prompt,
191 "generated_ids": out, "generated_text": text_out, "top5": steps,
192 "prefill_seconds": prefill_s, "step_seconds": step_s, "open_seconds": open_s,
193 "routes": routes, "route_gaps": gaps,
194 })
195 }
196 _ => return Err(usage.into()),
197 };
198 std::fs::write(
199 out_path,
200 serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?,
201 )
202 .map_err(|e| format!("{out_path}: {e}"))
203}
204
205fn main() {
206 if let Err(e) = run() {
207 eprintln!("qwen38_check: {e}");
208 std::process::exit(1);
209 }
210}