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-runtime / examples / qwen3_8b_specverify.rs

478 lines · 20557 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-8B draft-reuse speculative verification, development measurement (sc#384 speed lane,
17//! preregistered in ~/workspace/investigations/2026-10-12-qwen3-8b-decode-speed/plan.md,
18//! decision 14:30Z 2026-10-12). NOT a campaign run; nothing is promoted by it.
19//!
20//! The question: when the corrective second attempt of a document task regenerates the whole
21//! answer, can the rejected first draft be reused as a free drafter (propose short stretches of
22//! it, verify them with the unchanged model in one row-batched pass) without changing a single
23//! output token, and does that save enough time to matter?
24//!
25//! M1 baseline: plain greedy decode of the real v8-style corrective prompt for task D1 (goal
26//! text fixed below, refused reply and reason read from the v7 run receipt).
27//! M2 draft reuse: the same prompt, greedy, with blocks of B = 8, 4, 2 draft tokens proposed from
28//! the v7 refused reply (suffix match of the last three emitted tokens), verified by
29//! `NativeTransformerBackend::verify_block`; rejected K/V dropped by `truncate_kv`.
30//! M3 primitive cost: one verify_block call of 2, 4, 8 and 16 rows against one plain decode step,
31//! at the baseline's final context.
32//!
33//! usage: qwen3_8b_specverify <model_dir> <v7 run receipt json> <cpu|gb10>
34//! Prints ONE JSON object on stdout (ids, timings, counts, VmHWM). Exit 5 when the GPU backend
35//! reports any CPU fallback (the leg is then not a chip measurement).
36use aien_inference_abi::{sample_argmax, ChatTokenizer, TensorBackend};
37use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing};
38use std::sync::Arc;
39use std::time::Instant;
40
41const SYSTEM: &str = "You are a careful assistant.";
42/// tasks-oq3-v5.json D1, verbatim.
43const GOAL: &str = "Please create the file docs/knife-sharpening.md, a short how-to guide on sharpening a kitchen knife by hand. It should have at least 22 non-empty lines and three sections titled \"Gather Your Tools\", \"Sharpen the Edge\" and \"Test and Store\". Make sure the words whetstone and angle both appear somewhere in it.";
44const MAX_TOKENS: usize = 1024;
45const BLOCKS: &[usize] = &[8, 4, 2];
46const SUFFIX: usize = 3;
47
48fn die(code: i32, msg: &str) -> ! {
49 eprintln!("qwen3_8b_specverify: {msg}");
50 std::process::exit(code)
51}
52
53fn vm_hwm_kb() -> u64 {
54 std::fs::read_to_string("/proc/self/status")
55 .ok()
56 .and_then(|s| {
57 s.lines()
58 .find(|l| l.starts_with("VmHWM:"))
59 .and_then(|l| l.split_whitespace().nth(1).and_then(|v| v.parse().ok()))
60 })
61 .unwrap_or(0)
62}
63
64/// Where the draft continues after `out`: the position just past the LAST place in `draft`
65/// whose preceding `SUFFIX` tokens equal the last `SUFFIX` emitted tokens.
66fn propose(draft: &[u32], out: &[u32], want: usize) -> Option<Vec<u32>> {
67 let k = out.len().min(SUFFIX);
68 if k == 0 || want == 0 {
69 return None;
70 }
71 let tail = &out[out.len() - k..];
72 let mut j = None;
73 for i in k..draft.len() {
74 if &draft[i - k..i] == tail {
75 j = Some(i);
76 }
77 }
78 let j = j?;
79 let end = (j + want).min(draft.len());
80 if end <= j {
81 return None;
82 }
83 Some(draft[j..end].to_vec())
84}
85
86fn main() {
87 let a: Vec<String> = std::env::args().collect();
88 if a.len() != 4 || !matches!(a[3].as_str(), "cpu" | "gb10") {
89 die(
90 2,
91 "usage: qwen3_8b_specverify <model_dir> <v7 run receipt json> <cpu|gb10>",
92 );
93 }
94 let dir = std::path::PathBuf::from(&a[1]);
95 let gb10 = a[3] == "gb10";
96 let receipt: serde_json::Value = serde_json::from_str(
97 &std::fs::read_to_string(&a[2]).unwrap_or_else(|e| die(2, &format!("receipt: {e}"))),
98 )
99 .unwrap_or_else(|e| die(2, &format!("receipt json: {e}")));
100 let att = &receipt["runs"][0]["proposal_attempts"][0];
101 let refused_text = att["text"]
102 .as_str()
103 .unwrap_or_else(|| die(2, "receipt .text"));
104 let reason = att["reason"]
105 .as_str()
106 .unwrap_or_else(|| die(2, "receipt .reason"));
107 let draft: Vec<u32> = att["token_ids"]
108 .as_array()
109 .unwrap_or_else(|| die(2, "receipt .token_ids"))
110 .iter()
111 .map(|v| v.as_u64().unwrap_or_else(|| die(2, "token id")) as u32)
112 .collect();
113
114 let cta_budget: Option<aien_omega_gpu::CtaBudget> = if gb10 {
115 let raw = std::env::var(aien_omega_gpu::CTA_BUDGET_ENV).ok();
116 Some(
117 aien_omega_gpu::parse_cta_budget(raw.as_deref())
118 .unwrap_or_else(|e| die(2, &e))
119 .unwrap_or(aien_omega_gpu::DAEMON_DEFAULT_CTA_BUDGET),
120 )
121 } else {
122 None
123 };
124 let spin_us: Option<u32> = if gb10 {
125 let raw = std::env::var(aien_omega_gpu::SPIN_US_ENV).ok();
126 Some(
127 aien_omega_gpu::parse_spin_us(raw.as_deref())
128 .unwrap_or_else(|e| die(2, &e))
129 .unwrap_or(aien_omega_gpu::DAEMON_DEFAULT_SPIN_US),
130 )
131 } else {
132 None
133 };
134 let config = aien_inference_abi::load_model_config(&dir).expect("config.json");
135 let (weights, tb): (_, Arc<dyn TensorBackend>) = if gb10 {
136 if !aien_inference_abi::strict::production_strict() {
137 die(
138 3,
139 "gb10 leg needs a production-strict build (no dev fallback)",
140 );
141 }
142 let omega = aien_inference_abi::OmegaGb10Backend::new();
143 if !omega.is_available() {
144 die(3, "the Omega GB10 engine is not linked (stub build)");
145 }
146 if let Some(why) = aien_inference_abi::omega_model_refusal(&config) {
147 die(3, &why);
148 }
149 aien_inference_abi::open_gpu_session_with_retry(
150 aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS,
151 aien_inference_abi::GPU_SESSION_RETRY_DELAY,
152 aien_inference_abi::GPU_SESSION_OPEN_DEADLINE,
153 &aien_runtime::shared_kv::read_mem_available,
154 )
155 .unwrap_or_else(|e| die(3, &format!("GPU session: {e}")));
156 if let Some(b) = cta_budget {
157 aien_omega_gpu::set_cta_budget(b)
158 .unwrap_or_else(|e| die(3, &format!("CTA budget {}: {e}", b.get())));
159 }
160 if let Some(us) = spin_us {
161 aien_omega_gpu::set_spin_us(us)
162 .unwrap_or_else(|e| die(3, &format!("spin window {us} us: {e}")));
163 }
164 let weights = aien_inference_abi::load_resident_weights(
165 &dir,
166 &config,
167 &aien_inference_abi::OmegaUploader,
168 &mut |_| {},
169 )
170 .unwrap_or_else(|e| die(3, &format!("resident load: {e}")));
171 (weights, Arc::new(omega))
172 } else {
173 let weights = aien_inference_abi::TransformerWeights::load_from_safetensors(&dir, &config)
174 .expect("weights");
175 (
176 weights,
177 Arc::new(aien_inference_abi::ReferenceCpuBackend::new()),
178 )
179 };
180 let tok = ChatTokenizer::from_model_dir(&dir, None).expect("tokenizer");
181 let cfg = aien_scheduler::SchedulerConfig {
182 max_batch_size: 256,
183 max_batch_tokens: 16384,
184 max_prefill_tokens: 8192,
185 prefill_chunk_size: 128,
186 chunk_prefill: true,
187 watermark_blocks: 64,
188 };
189 let sizing = SharedKvSizing {
190 arena_capacity: 4096,
191 total_blocks: 1536,
192 };
193 let (_spine, mut backend) =
194 build_shared_kv_runtime(weights, tb.clone(), cfg, sizing).expect("shared KV");
195 let stop = tok.stop_token_ids().to_vec();
196 let hwm_loaded = vm_hwm_kb();
197
198 // The prompt: exactly what the production second attempt sends (compose/bridge.rs, corrective path).
199 let user = aien_runtime::compose::rederive::corrective_retry_prompt(
200 &aien_runtime::compose::rederive::proposal_prompt(GOAL),
201 reason,
202 Some(refused_text),
203 );
204 let msgs = vec![
205 aien_runtime::ChatTurn {
206 role: "system".into(),
207 content: SYSTEM.into(),
208 },
209 aien_runtime::ChatTurn {
210 role: "user".into(),
211 content: user.clone(),
212 },
213 ];
214 let text = aien_runtime::format_chat(tok.template(), &msgs).expect("chat");
215 let ids = tok.encode(&text).expect("encode");
216 eprintln!(
217 " prompt {} tokens, draft {} tokens",
218 ids.len(),
219 draft.len()
220 );
221
222 // Warm-up (one token, discarded), same as serving.
223 let wm = vec![aien_runtime::ChatTurn {
224 role: "user".into(),
225 content: aien_runtime::WARM_UP_TEXT.into(),
226 }];
227 let wids = tok
228 .encode(&aien_runtime::format_chat(tok.template(), &wm).expect("chat"))
229 .expect("encode");
230 backend
231 .generate_tokens(1, &wids, 1, 0.0, &stop)
232 .expect("warm-up");
233
234 // Tie check (AIEN_SPECVERIFY_TIE=<pos>, AIEN_SPECVERIFY_BASE=<earlier receipt>): no runs; the
235 // prompt plus the earlier baseline's first `pos` tokens are read, then the next position is
236 // scored by the plain one-row path and by the batched path at 1, 3, 5 and 9 rows. Prints the
237 // top two token ids and scores of each, so a divergence between the paths can be told apart
238 // from a fault: a near-tie flipped by summation order shows as a tiny gap.
239 if let Ok(pos) = std::env::var("AIEN_SPECVERIFY_TIE") {
240 let pos: usize = pos
241 .parse()
242 .unwrap_or_else(|_| die(2, "AIEN_SPECVERIFY_TIE=<pos>"));
243 let prev: serde_json::Value = serde_json::from_str(
244 &std::fs::read_to_string(std::env::var("AIEN_SPECVERIFY_BASE").unwrap_or_default())
245 .unwrap_or_else(|e| die(2, &format!("AIEN_SPECVERIFY_BASE: {e}"))),
246 )
247 .unwrap_or_else(|e| die(2, &format!("base json: {e}")));
248 let base: Vec<u32> = prev["baseline"]["output_ids"]
249 .as_array()
250 .unwrap_or_else(|| die(2, "base .baseline.output_ids"))
251 .iter()
252 .map(|v| v.as_u64().unwrap() as u32)
253 .collect();
254 if pos + 9 > base.len() {
255 die(2, "pos too close to the end of the baseline");
256 }
257 let top2 = |row: &[f32]| -> serde_json::Value {
258 let mut idx: Vec<usize> = (0..row.len()).collect();
259 idx.sort_by(|&a, &b| row[b].partial_cmp(&row[a]).unwrap().then(a.cmp(&b)));
260 serde_json::json!({ "top": [idx[0], idx[1]], "scores": [row[idx[0]], row[idx[1]]],
261 "gap": row[idx[0]] - row[idx[1]] })
262 };
263 let seq = 400u64;
264 let mut ctx_ids = ids.clone();
265 ctx_ids.extend_from_slice(&base[..pos]);
266 backend
267 .prefill_sequence(seq, &ctx_ids)
268 .unwrap_or_else(|e| die(4, &format!("tie prefill: {e}")));
269 let offset = ctx_ids.len();
270 let mut rows_out = Vec::new();
271 backend
272 .sequences
273 .get_mut(&seq)
274 .expect("seq")
275 .tokens
276 .push(base[pos]);
277 let l1 = backend
278 .decode_pending(seq)
279 .unwrap_or_else(|e| die(4, &format!("tie decode: {e}")));
280 backend.sequences.get_mut(&seq).expect("seq").tokens.pop();
281 backend.truncate_kv(seq, offset).unwrap();
282 rows_out.push(serde_json::json!({ "path": "plain m=1", "row0": top2(&l1) }));
283 let vocab = l1.len();
284 for &rows in &[1usize, 3, 5, 9] {
285 let l = backend
286 .verify_block_logits(seq, &base[pos..pos + rows])
287 .unwrap_or_else(|e| die(4, &format!("tie verify {rows}: {e}")));
288 backend.truncate_kv(seq, offset).unwrap();
289 rows_out.push(serde_json::json!({ "path": format!("verify rows={rows}"), "row0": top2(&l[..vocab]) }));
290 }
291 backend.release_sequence(seq);
292 println!(
293 "{}",
294 serde_json::json!({ "tie_check": { "position": pos, "expected_next": base[pos + 1],
295 "context": offset, "paths": rows_out }, "fallback_count": tb.fallback_count() })
296 );
297 return;
298 }
299
300 // M1: plain greedy baseline.
301 tb.reset_op_timing();
302 let t0 = Instant::now();
303 let base = backend
304 .generate_tokens(101, &ids, MAX_TOKENS, 0.0, &stop)
305 .unwrap_or_else(|e| die(4, &format!("baseline: {e}")));
306 let base_ms = t0.elapsed().as_secs_f64() * 1e3;
307 let base_timing = tb.op_timing_report();
308 eprintln!(" M1 baseline: {} tokens in {:.0} ms", base.len(), base_ms);
309
310 // M2: draft reuse, one run per block size.
311 let mut spec_runs = Vec::new();
312 for (i, &b) in BLOCKS.iter().enumerate() {
313 let seq = 200 + i as u64;
314 tb.reset_op_timing();
315 let t0 = Instant::now();
316 let logits = backend
317 .prefill_sequence(seq, &ids)
318 .unwrap_or_else(|e| die(4, &format!("spec B={b} prefill: {e}")));
319 let (first, _) = sample_argmax(&logits);
320 let mut out: Vec<u32> = Vec::new();
321 let mut finished = stop.contains(&first);
322 if !finished {
323 out.push(first);
324 backend
325 .sequences
326 .get_mut(&seq)
327 .expect("seq")
328 .tokens
329 .push(first);
330 }
331 let (mut verify_calls, mut proposed, mut accepted, mut plain_steps) =
332 (0usize, 0usize, 0usize, 0usize);
333 let mut verify_ms: Vec<f64> = Vec::new();
334 let mut plain_ms: Vec<f64> = Vec::new();
335 while !finished && out.len() < MAX_TOKENS {
336 let pending = *out.last().expect("pending");
337 let want = b.min(MAX_TOKENS - out.len());
338 let mut emitted: Vec<u32> = Vec::new();
339 match propose(&draft, &out, want) {
340 Some(d) => {
341 let mut block = Vec::with_capacity(d.len() + 1);
342 block.push(pending);
343 block.extend_from_slice(&d);
344 let offset = ids.len() + out.len() - 1;
345 let tv = Instant::now();
346 let preds = backend
347 .verify_block(seq, &block)
348 .unwrap_or_else(|e| die(4, &format!("spec B={b} verify: {e}")));
349 verify_ms.push(tv.elapsed().as_secs_f64() * 1e3);
350 verify_calls += 1;
351 proposed += d.len();
352 let mut acc = 0usize;
353 while acc < d.len() && preds[acc] == d[acc] {
354 acc += 1;
355 }
356 accepted += acc;
357 emitted.extend_from_slice(&d[..acc]);
358 emitted.push(preds[acc]);
359 backend
360 .truncate_kv(seq, offset + acc + 1)
361 .unwrap_or_else(|e| die(4, &format!("spec B={b} truncate: {e}")));
362 }
363 None => {
364 let tp = Instant::now();
365 let logits = backend
366 .decode_pending(seq)
367 .unwrap_or_else(|e| die(4, &format!("spec B={b} decode: {e}")));
368 plain_ms.push(tp.elapsed().as_secs_f64() * 1e3);
369 plain_steps += 1;
370 emitted.push(sample_argmax(&logits).0);
371 }
372 }
373 // Same stop and cap rule as the plain generator: a stop token ends the reply unemitted.
374 for t in emitted {
375 if stop.contains(&t) || out.len() >= MAX_TOKENS {
376 finished = true;
377 break;
378 }
379 out.push(t);
380 backend.sequences.get_mut(&seq).expect("seq").tokens.push(t);
381 }
382 if out.len() >= MAX_TOKENS {
383 finished = true;
384 }
385 }
386 // The verify K/V for emitted-but-not-forwarded tokens is already pruned; the pending
387 // token's K/V is never computed (same as the plain path). Release the sequence.
388 let ms = t0.elapsed().as_secs_f64() * 1e3;
389 backend.release_sequence(seq);
390 let identical = out == base;
391 let mean = |v: &[f64]| {
392 if v.is_empty() {
393 0.0
394 } else {
395 v.iter().sum::<f64>() / v.len() as f64
396 }
397 };
398 eprintln!(
399 " M2 B={b}: {} tokens in {:.0} ms ({:.2}x baseline), identical={identical}, verify {verify_calls} calls mean {:.1} ms, accepted {accepted}/{proposed}, plain {plain_steps} steps mean {:.1} ms",
400 out.len(), ms, ms / base_ms, mean(&verify_ms), mean(&plain_ms)
401 );
402 spec_runs.push(serde_json::json!({
403 "block": b, "rows": b + 1, "tokens": out.len(), "ms": ms, "ratio_to_baseline": ms / base_ms,
404 "identical_to_baseline": identical,
405 "first_divergence": out.iter().zip(base.iter()).position(|(x, y)| x != y),
406 "verify_calls": verify_calls, "proposed": proposed, "accepted": accepted,
407 "verify_ms_mean": mean(&verify_ms), "plain_steps": plain_steps, "plain_ms_mean": mean(&plain_ms),
408 "output_ids": out, "op_timing": tb.op_timing_report(),
409 }));
410 }
411
412 // M3: primitive cost at the baseline's final context (prompt + all but the last 17 tokens
413 // re-read as one prompt, then the next tokens as the block), each size three times.
414 let mut m3 = Vec::new();
415 if base.len() > 20 {
416 let seq = 300u64;
417 let cut = base.len() - 17;
418 let mut ctx_ids = ids.clone();
419 ctx_ids.extend_from_slice(&base[..cut]);
420 backend
421 .prefill_sequence(seq, &ctx_ids)
422 .unwrap_or_else(|e| die(4, &format!("M3 prefill: {e}")));
423 let offset = ctx_ids.len();
424 for &rows in &[1usize, 2, 4, 8, 16] {
425 let mut ms = Vec::new();
426 for _ in 0..3 {
427 let t = Instant::now();
428 if rows == 1 {
429 backend
430 .sequences
431 .get_mut(&seq)
432 .expect("seq")
433 .tokens
434 .push(base[cut]);
435 backend
436 .decode_pending(seq)
437 .unwrap_or_else(|e| die(4, &format!("M3 decode: {e}")));
438 backend.sequences.get_mut(&seq).expect("seq").tokens.pop();
439 } else {
440 backend
441 .verify_block(seq, &base[cut..cut + rows])
442 .unwrap_or_else(|e| die(4, &format!("M3 verify {rows}: {e}")));
443 }
444 ms.push(t.elapsed().as_secs_f64() * 1e3);
445 backend
446 .truncate_kv(seq, offset)
447 .unwrap_or_else(|e| die(4, &format!("M3 truncate: {e}")));
448 }
449 eprintln!(
450 " M3 rows={rows} at ctx {offset}: {:?} ms",
451 ms.iter().map(|v| v.round()).collect::<Vec<_>>()
452 );
453 m3.push(serde_json::json!({ "rows": rows, "context": offset, "ms": ms }));
454 }
455 backend.release_sequence(seq);
456 }
457 let fallback = tb.fallback_count();
458 println!(
459 "{}",
460 serde_json::json!({
461 "leg": a[3], "backend": TensorBackend::name(tb.as_ref()),
462 "cta_budget": cta_budget.map(|b| b.get()), "spin_us": spin_us,
463 "model_id": config.model_id, "prompt_tokens": ids.len(), "draft_tokens": draft.len(),
464 "goal": GOAL, "reason": reason,
465 "baseline": { "tokens": base.len(), "ms": base_ms, "output_ids": base, "op_timing": base_timing,
466 "reply": tok.decode_opts(&base, true).unwrap_or_default() },
467 "spec_runs": spec_runs, "m3_primitive_cost": m3,
468 "vm_hwm_kb_after_load": hwm_loaded, "vm_hwm_kb_end": vm_hwm_kb(),
469 "fallback_count": fallback,
470 })
471 );
472 if fallback > 0 {
473 die(
474 5,
475 &format!("{fallback} CPU fallback(s): not a chip measurement"),
476 );
477 }
478}