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-runtime / examples / qwen3_8b_smoke.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-8B correctness smoke driver (docs/campaigns/open-model-qwen3/SMOKE-8B-v1.md, sc#384). |
| 17 | //! Two fixed conversations (PROMPTS), thinking off, greedy, on the daemon's path (strict |
| 18 | //! safetensors load, shared-KV runtime, `ChatTokenizer::from_model_dir`, one warm-up turn). |
| 19 | //! Prints ONE JSON object: prompt text and ids, output ids, finish reason, fallback_count. |
| 20 | //! |
| 21 | //! usage: qwen3_8b_smoke <model_dir> <cpu|gb10> |
| 22 | //! cpu = `ReferenceCpuBackend`, host f32 weights (never touches the GPU). |
| 23 | //! gb10 = the daemon's GB10 construction (session open with retry, resident bf16 load through |
| 24 | //! `OmegaUploader`, `OmegaGb10Backend`). Refuses by name when the engine is not linked, |
| 25 | //! the build is not production-strict, or the model is refused; never falls back. |
| 26 | //! UNVERIFIED: compiled but not run on the chip when this file was written. |
| 27 | use aien_inference_abi::{ChatTokenizer, SamplingParams, TensorBackend}; |
| 28 | use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; |
| 29 | use aien_scheduler::{ChannelCompletionSink, CompletionEvent}; |
| 30 | use sha2::Digest; |
| 31 | use std::sync::Arc; |
| 32 | |
| 33 | const SYSTEM: &str = "You are a careful assistant."; |
| 34 | const GEN_PROMPT: &str = "<|im_start|>assistant\n<think>\n\n</think>\n\n"; |
| 35 | /// (name, user text, max new tokens). Prompt 1 is the original one-token check; prompt 2 must reply with |
| 36 | /// at least 16 tokens before eos (SMOKE-8B-v1.md). |
| 37 | const PROMPTS: &[(&str, &str, usize)] = &[ |
| 38 | ("p1", "Reply with the single word OK.", 16), |
| 39 | ( |
| 40 | "p2", |
| 41 | "List the months of the year, one per line, nothing else.", |
| 42 | 48, |
| 43 | ), |
| 44 | ]; |
| 45 | |
| 46 | async fn turn( |
| 47 | spine: &mut aien_runtime::AienRuntimeSpine, |
| 48 | backend: &mut aien_inference_abi::NativeTransformerBackend, |
| 49 | ids: &[u32], |
| 50 | max_tokens: usize, |
| 51 | stop: &[u32], |
| 52 | ) -> Result<(Vec<u32>, String, f64), String> { |
| 53 | let (sink, mut ev) = ChannelCompletionSink::channel(); |
| 54 | let sid = spine.register_completion_sink(Arc::new(sink)); |
| 55 | let sampling = SamplingParams { |
| 56 | temperature: 0.0, |
| 57 | top_p: 0.95, |
| 58 | max_tokens, |
| 59 | stop_token_ids: stop.to_vec(), |
| 60 | }; |
| 61 | spine.submit_work(Arc::from(ids), sampling, 2, Some(sid))?; |
| 62 | let t0 = std::time::Instant::now(); |
| 63 | let mut out = Vec::new(); |
| 64 | loop { |
| 65 | if spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0 { |
| 66 | spine.step(backend).await.map_err(|e| format!("{e:?}"))?; |
| 67 | } |
| 68 | while let Ok(e) = ev.try_recv() { |
| 69 | match e { |
| 70 | CompletionEvent::Token { token, .. } => out.push(token), |
| 71 | CompletionEvent::Finished { finish_reason, .. } => { |
| 72 | let label = aien_runtime::server::finish_reason_label(&finish_reason); |
| 73 | return Ok((out, label.into(), t0.elapsed().as_secs_f64() * 1e3)); |
| 74 | } |
| 75 | CompletionEvent::Error { message, .. } => return Err(message), |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn die(code: i32, msg: &str) -> ! { |
| 82 | eprintln!("qwen3_8b_smoke: {msg}"); |
| 83 | std::process::exit(code) |
| 84 | } |
| 85 | |
| 86 | #[tokio::main] |
| 87 | async fn main() { |
| 88 | let a: Vec<String> = std::env::args().collect(); |
| 89 | if a.len() != 3 || !matches!(a[2].as_str(), "cpu" | "gb10") { |
| 90 | die(2, "usage: qwen3_8b_smoke <model_dir> <cpu|gb10>"); |
| 91 | } |
| 92 | let dir = std::path::PathBuf::from(&a[1]); |
| 93 | let gb10 = a[2] == "gb10"; |
| 94 | // The matmul CTA budget the daemon serves with (AIEN_OMEGA_CTA_BUDGET, else the AIEN default), |
| 95 | // applied before the first chip call; omega's own library default (64) is never what the smoke |
| 96 | // measures. Set after the GPU session opens, below. |
| 97 | let cta_budget: Option<aien_omega_gpu::CtaBudget> = if gb10 { |
| 98 | let raw = std::env::var(aien_omega_gpu::CTA_BUDGET_ENV).ok(); |
| 99 | Some( |
| 100 | aien_omega_gpu::parse_cta_budget(raw.as_deref()) |
| 101 | .unwrap_or_else(|e| die(2, &e)) |
| 102 | .unwrap_or(aien_omega_gpu::DAEMON_DEFAULT_CTA_BUDGET), |
| 103 | ) |
| 104 | } else { |
| 105 | None |
| 106 | }; |
| 107 | // The daemon's marker-wait spin window as well (AIEN_OMEGA_SPIN_US, else the daemon default): |
| 108 | // without it every launch pays the 50 us sleep-poll floor and the smoke does not time the daemon's path. |
| 109 | let spin_us: Option<u32> = if gb10 { |
| 110 | let raw = std::env::var(aien_omega_gpu::SPIN_US_ENV).ok(); |
| 111 | Some( |
| 112 | aien_omega_gpu::parse_spin_us(raw.as_deref()) |
| 113 | .unwrap_or_else(|e| die(2, &e)) |
| 114 | .unwrap_or(aien_omega_gpu::DAEMON_DEFAULT_SPIN_US), |
| 115 | ) |
| 116 | } else { |
| 117 | None |
| 118 | }; |
| 119 | // AIEN_SMOKE_LONG=1 adds a third, longer prompt (not part of the golden; for decode timing only). |
| 120 | // AIEN_SMOKE_CTX=1 adds a fourth with a long prompt (32 numbered rules, about 900 tokens: the |
| 121 | // campaign's document tasks decode at 700 to 1000 tokens of context) and 64 new tokens, so the |
| 122 | // timing table shows what attention costs at that context. Not part of the golden. |
| 123 | let long_user: String = { |
| 124 | let rules: Vec<String> = (1..=32) |
| 125 | .map(|i| { |
| 126 | format!( |
| 127 | "Rule {i}: a book borrowed on day {} of the month is due back after {} days, and the fine for a late return is {} cents per day.", |
| 128 | i, i % 7 + 3, i * 3 % 50 + 5 |
| 129 | ) |
| 130 | }) |
| 131 | .collect(); |
| 132 | format!( |
| 133 | "Here are the rules of a small library.\n{}\nSummarize these rules in two sentences.", |
| 134 | rules.join("\n") |
| 135 | ) |
| 136 | }; |
| 137 | let mut prompts: Vec<(&str, &str, usize)> = PROMPTS.to_vec(); |
| 138 | if std::env::var("AIEN_SMOKE_LONG") |
| 139 | .map(|v| v == "1") |
| 140 | .unwrap_or(false) |
| 141 | { |
| 142 | prompts.push(( |
| 143 | "p3", |
| 144 | "Describe how a bicycle works, in about 250 words.", |
| 145 | 256, |
| 146 | )); |
| 147 | } |
| 148 | if std::env::var("AIEN_SMOKE_CTX") |
| 149 | .map(|v| v == "1") |
| 150 | .unwrap_or(false) |
| 151 | { |
| 152 | prompts.push(("p4", long_user.as_str(), 64)); |
| 153 | } |
| 154 | let config = aien_inference_abi::load_model_config(&dir).expect("config.json"); |
| 155 | let (weights, tb): (_, Arc<dyn TensorBackend>) = if gb10 { |
| 156 | if !aien_inference_abi::strict::production_strict() { |
| 157 | die( |
| 158 | 3, |
| 159 | "gb10 leg needs a production-strict build (no dev fallback)", |
| 160 | ); |
| 161 | } |
| 162 | let omega = aien_inference_abi::OmegaGb10Backend::new(); |
| 163 | if !omega.is_available() { |
| 164 | die(3, "the Omega GB10 engine is not linked (stub build)"); |
| 165 | } |
| 166 | if let Some(why) = aien_inference_abi::omega_model_refusal(&config) { |
| 167 | die(3, &why); |
| 168 | } |
| 169 | aien_inference_abi::open_gpu_session_with_retry( |
| 170 | aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS, |
| 171 | aien_inference_abi::GPU_SESSION_RETRY_DELAY, |
| 172 | aien_inference_abi::GPU_SESSION_OPEN_DEADLINE, |
| 173 | &aien_runtime::shared_kv::read_mem_available, |
| 174 | ) |
| 175 | .unwrap_or_else(|e| die(3, &format!("GPU session: {e}"))); |
| 176 | if let Some(b) = cta_budget { |
| 177 | aien_omega_gpu::set_cta_budget(b) |
| 178 | .unwrap_or_else(|e| die(3, &format!("CTA budget {}: {e}", b.get()))); |
| 179 | eprintln!(" matmul CTA budget {} (daemon setting)", b.get()); |
| 180 | } |
| 181 | if let Some(us) = spin_us { |
| 182 | aien_omega_gpu::set_spin_us(us) |
| 183 | .unwrap_or_else(|e| die(3, &format!("spin window {us} us: {e}"))); |
| 184 | eprintln!(" marker spin window {us} us (daemon setting)"); |
| 185 | } |
| 186 | let weights = aien_inference_abi::load_resident_weights( |
| 187 | &dir, |
| 188 | &config, |
| 189 | &aien_inference_abi::OmegaUploader, |
| 190 | &mut |_| {}, |
| 191 | ) |
| 192 | .unwrap_or_else(|e| die(3, &format!("resident load: {e}"))); |
| 193 | (weights, Arc::new(omega)) |
| 194 | } else { |
| 195 | let weights = aien_inference_abi::TransformerWeights::load_from_safetensors(&dir, &config) |
| 196 | .expect("weights"); |
| 197 | ( |
| 198 | weights, |
| 199 | Arc::new(aien_inference_abi::ReferenceCpuBackend::new()), |
| 200 | ) |
| 201 | }; |
| 202 | let tok = ChatTokenizer::from_model_dir(&dir, None).expect("tokenizer"); |
| 203 | let cfg = aien_scheduler::SchedulerConfig { |
| 204 | max_batch_size: 256, |
| 205 | max_batch_tokens: 16384, |
| 206 | max_prefill_tokens: 8192, |
| 207 | prefill_chunk_size: 128, |
| 208 | chunk_prefill: true, |
| 209 | watermark_blocks: 64, |
| 210 | }; |
| 211 | let sizing = SharedKvSizing { |
| 212 | arena_capacity: 4096, |
| 213 | // 24k tokens of KV. Every block id then passes the resident pool's 32-bit rule (block |
| 214 | // 1819 is the edge for this geometry), so the paged attention reads the pool in place. |
| 215 | total_blocks: 1536, |
| 216 | }; |
| 217 | let (mut spine, mut backend) = |
| 218 | build_shared_kv_runtime(weights, tb.clone(), cfg, sizing).expect("shared KV"); |
| 219 | let stop = tok.stop_token_ids().to_vec(); |
| 220 | let wm = vec![aien_runtime::ChatTurn { |
| 221 | role: "user".into(), |
| 222 | content: aien_runtime::WARM_UP_TEXT.into(), |
| 223 | }]; |
| 224 | let wids = tok |
| 225 | .encode(&aien_runtime::format_chat(tok.template(), &wm).expect("chat")) |
| 226 | .expect("encode"); |
| 227 | turn(&mut spine, &mut backend, &wids, 1, &stop) |
| 228 | .await |
| 229 | .expect("warm-up"); |
| 230 | let sha = |b: &[u8]| -> String { |
| 231 | sha2::Sha256::digest(b) |
| 232 | .iter() |
| 233 | .map(|x| format!("{x:02x}")) |
| 234 | .collect() |
| 235 | }; |
| 236 | let mut results = Vec::new(); |
| 237 | let mut p3_timing: Option<String> = None; |
| 238 | for (name, user, max_tokens) in prompts.iter() { |
| 239 | // The timing table covers one prompt at a time (its prompt read and its decode steps). |
| 240 | tb.reset_op_timing(); |
| 241 | let msgs = vec![ |
| 242 | aien_runtime::ChatTurn { |
| 243 | role: "system".into(), |
| 244 | content: SYSTEM.into(), |
| 245 | }, |
| 246 | aien_runtime::ChatTurn { |
| 247 | role: "user".into(), |
| 248 | content: (*user).into(), |
| 249 | }, |
| 250 | ]; |
| 251 | let text = aien_runtime::format_chat(tok.template(), &msgs).expect("chat"); |
| 252 | let expected = format!( |
| 253 | "<|im_start|>system\n{SYSTEM}<|im_end|>\n<|im_start|>user\n{user}<|im_end|>\n{GEN_PROMPT}" |
| 254 | ); |
| 255 | if text != expected { |
| 256 | die( |
| 257 | 4, |
| 258 | &format!("rendered prompt {name} differs from the golden text: {text:?}"), |
| 259 | ); |
| 260 | } |
| 261 | let ids = tok.encode(&text).expect("encode"); |
| 262 | let (out, finish, ms) = turn(&mut spine, &mut backend, &ids, *max_tokens, &stop) |
| 263 | .await |
| 264 | .expect("turn"); |
| 265 | let reply = tok.decode_opts(&out, true).expect("decode"); |
| 266 | let prompt_timing = tb.op_timing_report(); |
| 267 | if let Some(t) = &prompt_timing { |
| 268 | eprintln!(" {name} op timing: {t}"); |
| 269 | } |
| 270 | if *name == "p3" { |
| 271 | p3_timing = prompt_timing.clone(); |
| 272 | } |
| 273 | results.push(serde_json::json!({ |
| 274 | "name": name, "prompt_sha256": sha(text.as_bytes()), "prompt_ids": ids, |
| 275 | "max_tokens": max_tokens, "output_ids": out, "finish": finish, "ms": ms, |
| 276 | "reply": reply, "op_timing": prompt_timing, |
| 277 | })); |
| 278 | } |
| 279 | // Per-operation wall and chip time for p3 (AIEN_SMOKE_LONG=1), from the GPU backend's table; |
| 280 | // every prompt also carries its own table. |
| 281 | let op_timing = p3_timing; |
| 282 | println!( |
| 283 | "{}", |
| 284 | serde_json::json!({ |
| 285 | "leg": a[2], "backend": TensorBackend::name(tb.as_ref()), |
| 286 | "cta_budget": cta_budget.map(|b| b.get()), "spin_us": spin_us, "op_timing": op_timing, |
| 287 | "model_dir": dir, "model_id": config.model_id, "template": tok.template().name(), |
| 288 | "prompts": results, "fallback_count": tb.fallback_count(), |
| 289 | }) |
| 290 | ); |
| 291 | } |