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_session_check.rs

224 lines · 9041 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//! Next-turn resume check for the Qwen3.8 serving session (sc #642), on the chip.
17//!
18//! qwen38_session_check <checkpoint-dir> <layers|all> <new-tokens> <out.json>
19//!
20//! Two-turn chat, thinking off, greedy. Turn 2 is served three ways and compared:
21//! - resumed: the session restores the snapshot taken before turn 1's last `<|im_start|>` and
22//! feeds only the new turns;
23//! - cold: the session forgets everything and feeds the whole turn 2 prompt;
24//! - live: turn 3 extends turn 2's prompt plus its reply tokens exactly, so the live state goes on.
25//!
26//! Pass: resumed == cold token for token (and live == its cold twin), the first logits close
27//! (cosine >= 0.999), and both controls caught: a different second question must give different
28//! tokens, and a stale state (turn 2's new tokens fed on top of turn 1's live state, the bug a
29//! wrong restore would be) must give different greedy tokens than cold. `layers` below 64 runs the first layers only
30//! (fits beside another model; the tokens are then not English, the comparison still holds).
31use std::path::Path;
32use std::time::Instant;
33
34use aien_inference_abi::qwen38::Qwen38Config;
35use aien_inference_abi::qwen38_omega::{need_bytes, Qwen38Omega, Qwen38Session, Reuse};
36use aien_inference_abi::qwen3_moe::parity_stats;
37use aien_inference_abi::tokenizer::{ChatOptions, ChatTokenizer};
38use serde_json::json;
39
40const KEEP_FREE: u64 = 12 << 30;
41const COSINE_MIN: f64 = 0.999;
42const CHUNK: usize = 4096;
43
44fn mem_available() -> Result<u64, String> {
45 let text = std::fs::read_to_string("/proc/meminfo").map_err(|e| e.to_string())?;
46 text.lines()
47 .find_map(|l| l.strip_prefix("MemAvailable:"))
48 .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok())
49 .map(|kb| kb * 1024)
50 .ok_or_else(|| "/proc/meminfo: no MemAvailable".into())
51}
52
53fn argmax(l: &[f32]) -> u32 {
54 let mut best = 0;
55 for (i, &v) in l.iter().enumerate() {
56 if v > l[best] {
57 best = i;
58 }
59 }
60 best as u32
61}
62
63/// Feeds `prompt`, then `n` greedy tokens: (ids, first logits, reuse).
64fn turn(
65 s: &mut Qwen38Session,
66 prompt: &[u32],
67 n: usize,
68) -> Result<(Vec<u32>, Vec<f32>, Reuse, f64), String> {
69 let t = Instant::now();
70 let (mut logits, st) = s.start(prompt)?;
71 let ms = t.elapsed().as_secs_f64() * 1e3;
72 let first = logits.clone();
73 let mut ids = Vec::new();
74 while ids.len() < n {
75 let tok = argmax(&logits);
76 ids.push(tok);
77 if ids.len() < n {
78 logits = s.advance(tok)?.0;
79 }
80 }
81 Ok((ids, first, st.reuse.unwrap_or(Reuse::Cold), ms))
82}
83
84fn run() -> Result<bool, String> {
85 let a: Vec<String> = std::env::args().collect();
86 if a.len() != 5 {
87 return Err(
88 "usage: qwen38_session_check <checkpoint-dir> <layers|all> <new-tokens> <out.json>"
89 .into(),
90 );
91 }
92 let dir = Path::new(&a[1]);
93 let layers = if a[2] == "all" {
94 None
95 } else {
96 Some(a[2].parse::<usize>().map_err(|e| e.to_string())?)
97 };
98 let n: usize = a[3]
99 .parse()
100 .map_err(|e: std::num::ParseIntError| e.to_string())?;
101 let max_pos = 2048;
102 let c = Qwen38Config::from_checkpoint(dir)?;
103 let c = match layers {
104 Some(l) => c.prefix(l).ok_or("layers outside the model")?,
105 None => c,
106 };
107 let need = need_bytes(&c, max_pos, CHUNK);
108 let avail = mem_available()?;
109 if avail < need + KEEP_FREE {
110 return Err(format!(
111 "needs {} MiB + {} MiB free, MemAvailable {} MiB; refusing",
112 need >> 20,
113 KEEP_FREE >> 20,
114 avail >> 20
115 ));
116 }
117 eprintln!(
118 "upload: {} layers, need {} MiB, MemAvailable {} MiB",
119 c.layers,
120 need >> 20,
121 avail >> 20
122 );
123 let tk = ChatTokenizer::from_model_dir(dir, None).map_err(|e| e.to_string())?;
124 let off = ChatOptions {
125 enable_thinking: Some(false),
126 reasoning_effort: None,
127 preserve_thinking: None,
128 };
129 let enc = |turns: &[(&str, &str)]| -> Result<Vec<u32>, String> {
130 let text = tk
131 .try_format_chat_with(turns, &off)
132 .map_err(|e| e.to_string())?;
133 tk.encode_with_special(&text, true)
134 .map_err(|e| e.to_string())
135 };
136 let q1 = "Write a C function that returns the larger of two ints.";
137 let q2 = "Now make it work for three ints.";
138 let q2x = "Explain what a pointer is in one sentence.";
139 let p1 = enc(&[("user", q1)])?;
140
141 let model = Qwen38Omega::open(dir, layers, max_pos)?;
142 let mut s = Qwen38Session::new(model, CHUNK);
143
144 let (a1, _, r1, ms1) = turn(&mut s, &p1, n)?;
145 let reply1 = tk.decode_opts(&a1, true).map_err(|e| e.to_string())?;
146 let p2 = enc(&[("user", q1), ("assistant", &reply1), ("user", q2)])?;
147 let snap_len = s.snapshot_tokens().map_or(0, <[u32]>::len);
148
149 // Control 2 (stale state): turn 2's new tokens fed on top of turn 1's live state.
150 let (stale, stale_ids) = {
151 let m = s.model_mut();
152 let rest = &p2[snap_len..];
153 let (_, logits, _) = m.prefill(rest, CHUNK)?;
154 let mut ids = vec![argmax(&logits)];
155 while ids.len() < n {
156 m.step(*ids.last().unwrap())?;
157 ids.push(argmax(&m.logits()?));
158 }
159 (logits, ids)
160 };
161 s.forget();
162 // Re-run turn 1 so the snapshot exists again, then turn 2 resumed.
163 let (a1b, _, _, _) = turn(&mut s, &p1, n)?;
164 let (b_res, f_res, r2, ms2) = turn(&mut s, &p2, n)?;
165 // Live: turn 3 = turn 2's prompt + its reply tokens fed so far + a closing and a new question.
166 let mut p3 = s.history().to_vec();
167 p3.extend(tk.encode_with_special("<|im_end|>\n<|im_start|>user\nThanks.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n", true).map_err(|e| e.to_string())?);
168 let (c_live, f_live, r3, ms3) = turn(&mut s, &p3, n)?;
169
170 s.forget();
171 let (b_cold, f_cold, r2c, ms2c) = turn(&mut s, &p2, n)?;
172 s.forget();
173 let (c_cold, f_ccold, _, _) = turn(&mut s, &p3, n)?;
174 s.forget();
175 let p2x = enc(&[("user", q1), ("assistant", &reply1), ("user", q2x)])?;
176 let (b_x, _, _, _) = turn(&mut s, &p2x, n)?;
177
178 let pr = parity_stats(&f_res, &f_cold);
179 let pl = parity_stats(&f_live, &f_ccold);
180 let ps = parity_stats(&stale, &f_cold);
181 let checks = json!({
182 "turn1_repeatable": a1 == a1b,
183 "turn1_cold": r1 == Reuse::Cold,
184 "turn2_used_snapshot": matches!(r2, Reuse::Snapshot(k) if k == snap_len),
185 "turn3_used_live": matches!(r3, Reuse::Live(_)),
186 "cold_was_cold": r2c == Reuse::Cold,
187 "resumed_equals_cold": b_res == b_cold,
188 "resumed_cosine_ok": pr.cosine >= COSINE_MIN,
189 "live_equals_cold": c_live == c_cold,
190 "live_cosine_ok": pl.cosine >= COSINE_MIN,
191 "control_other_question_differs": b_x != b_cold,
192 "control_stale_state_caught": stale_ids != b_cold,
193 });
194 let pass = checks
195 .as_object()
196 .unwrap()
197 .values()
198 .all(|v| v.as_bool() == Some(true));
199 let out = json!({
200 "layers": c.layers, "new_tokens": n, "pass": pass, "checks": checks,
201 "prompt_tokens": [p1.len(), p2.len(), p3.len()], "snapshot_tokens": snap_len,
202 "reuse": [format!("{r1:?}"), format!("{r2:?}"), format!("{r3:?}"), format!("{r2c:?}")],
203 "start_ms": {"turn1_cold": ms1, "turn2_resumed": ms2, "turn3_live": ms3, "turn2_cold": ms2c},
204 "cosine": {"resumed_vs_cold": pr.cosine, "live_vs_cold": pl.cosine, "stale_vs_cold": ps.cosine},
205 "max_abs": {"resumed_vs_cold": pr.max_abs, "live_vs_cold": pl.max_abs, "stale_vs_cold": ps.max_abs},
206 "ids": {"turn1": a1, "turn2_resumed": b_res, "turn2_cold": b_cold, "turn3_live": c_live,
207 "turn3_cold": c_cold, "turn2_other_question": b_x, "turn2_stale_state": stale_ids},
208 });
209 std::fs::write(&a[4], serde_json::to_string_pretty(&out).unwrap())
210 .map_err(|e| e.to_string())?;
211 println!("{}", serde_json::to_string(&json!({"pass": pass, "checks": out["checks"], "cosine": out["cosine"], "start_ms": out["start_ms"], "reuse": out["reuse"]})).unwrap());
212 Ok(pass)
213}
214
215fn main() {
216 match run() {
217 Ok(true) => {}
218 Ok(false) => std::process::exit(1),
219 Err(e) => {
220 eprintln!("qwen38_session_check: {e}");
221 std::process::exit(2);
222 }
223 }
224}