Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-runtime/examples/np1_reference.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-runtime / examples / np1_reference.rs` 461 lines ยท 20655 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-PHASE-1 v6 CPU reference driver (ACCEPTANCE-v6 R1 and the pre-freeze 17 //! ground checks). Runs one compose prompt through the CPU reference backend 18 //! (`ReferenceCpuBackend`, never the GPU) on the daemon's path: config.json -> 19 //! ModelConfig, strict safetensors load, the daemon's scheduler config and 20 //! shared KV sizing, `ChatTokenizer::from_model_dir`, one warm-up turn on 21 //! `WARM_UP_TEXT`, then `format_chat` + `COMPOSE_ASSISTANT_PREFIX`, greedy, 22 //! the model's stop set. Prints one JSON object. 23 //! 24 //! usage: np1_reference [retry reason] 25 //! new = the product's NEW-destination prompt (`compose::rederive::task_decision`, `TargetClass::New`): 26 //! `proposal_prompt(goal)` plus `new_document_block` for the destination the 27 //! goal names, from the product's own public pieces, so it still holds after the run wrote 28 //! that destination (the v5 template alone when the goal names none) 29 //! task = `task_prompt(goal, workspace)` on the workspace as it is now 30 //! retry reason: the prompt of attempt k > 1, `retry_prompt(, reason)` 31 use aien_inference_abi::{ChatTokenizer, SamplingParams}; 32 use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; 33 use aien_scheduler::{ChannelCompletionSink, CompletionEvent}; 34 use sha2::Digest; 35 use std::sync::Arc; 36 37 async fn turn( 38 spine: &mut aien_runtime::AienRuntimeSpine, 39 backend: &mut aien_inference_abi::NativeTransformerBackend, 40 ids: &[u32], 41 max_tokens: usize, 42 stop: &[u32], 43 ) -> Result<(Vec, String, f64), String> { 44 let (sink, mut ev) = ChannelCompletionSink::channel(); 45 let sid = spine.register_completion_sink(Arc::new(sink)); 46 let sampling = SamplingParams { 47 temperature: 0.0, 48 top_p: 0.95, 49 max_tokens, 50 stop_token_ids: stop.to_vec(), 51 }; 52 spine.submit_work(Arc::from(ids), sampling, 2, Some(sid))?; 53 let t0 = std::time::Instant::now(); 54 let mut out = Vec::new(); 55 loop { 56 if spine.scheduler.running_count() > 0 || spine.scheduler.waiting_count() > 0 { 57 spine.step(backend).await.map_err(|e| format!("{e:?}"))?; 58 } 59 while let Ok(e) = ev.try_recv() { 60 match e { 61 CompletionEvent::Token { token, .. } => out.push(token), 62 CompletionEvent::Finished { finish_reason, .. } => { 63 let label = aien_runtime::server::finish_reason_label(&finish_reason); 64 return Ok((out, label.into(), t0.elapsed().as_secs_f64() * 1e3)); 65 } 66 CompletionEvent::Error { message, .. } => return Err(message), 67 } 68 } 69 } 70 } 71 72 #[tokio::main] 73 async fn main() { 74 let a: Vec = std::env::args().collect(); 75 if !(6..=7).contains(&a.len()) || !matches!(a[5].as_str(), "new" | "task") { 76 eprintln!( 77 "usage: np1_reference [retry reason]" 78 ); 79 std::process::exit(2); 80 } 81 let dir = std::path::PathBuf::from(&a[1]); 82 let (goal, ws, mode) = (&a[2], std::path::PathBuf::from(&a[3]), a[5].as_str()); 83 let max_tokens: usize = a[4].parse().expect("max_tokens"); 84 let config = aien_inference_abi::load_model_config(&dir).expect("config.json"); 85 let weights = aien_inference_abi::TransformerWeights::load_from_safetensors(&dir, &config) 86 .expect("weights"); 87 let tok = ChatTokenizer::from_model_dir(&dir, None).expect("tokenizer"); 88 let tb: Arc = 89 Arc::new(aien_inference_abi::ReferenceCpuBackend::new()); 90 // The daemon's values (aien-cli run_daemon_server). 91 let cfg = aien_scheduler::SchedulerConfig { 92 max_batch_size: 256, 93 max_batch_tokens: 16384, 94 max_prefill_tokens: 8192, 95 prefill_chunk_size: 128, 96 chunk_prefill: true, 97 watermark_blocks: 64, 98 }; 99 let sizing = SharedKvSizing { 100 arena_capacity: 4096, 101 total_blocks: 8192, 102 }; 103 let (mut spine, mut backend) = 104 build_shared_kv_runtime(weights, tb.clone(), cfg, sizing).expect("shared KV"); 105 let stop = tok.stop_token_ids().to_vec(); 106 let wm = vec![aien_runtime::ChatTurn { 107 role: "user".into(), 108 content: aien_runtime::WARM_UP_TEXT.into(), 109 }]; 110 let wids = tok 111 .encode(&aien_runtime::format_chat(tok.template(), &wm).expect("chat")) 112 .expect("encode"); 113 let (w, _, _) = turn(&mut spine, &mut backend, &wids, 1, &stop) 114 .await 115 .expect("warm-up"); 116 let base = reference_prompt(mode, goal, &ws); 117 let retry = a.get(6).cloned(); 118 let prompt = match &retry { 119 Some(why) => aien_runtime::compose::rederive::retry_prompt(&base, why), 120 None => base, 121 }; 122 let allen = std::env::var("NP1_REFERENCE_ALLEN").unwrap_or_else(|_| "none".into()); 123 let prompt = allen_prompt(&prompt, &allen); 124 let msgs = vec![aien_runtime::ChatTurn { 125 role: "user".into(), 126 content: prompt.clone(), 127 }]; 128 let text = format!( 129 "{}{}", 130 aien_runtime::format_chat(tok.template(), &msgs).expect("chat"), 131 aien_runtime::compose::rederive::COMPOSE_ASSISTANT_PREFIX 132 ); 133 let ids = tok.encode(&text).expect("encode"); 134 let (out, finish, ms) = turn(&mut spine, &mut backend, &ids, max_tokens, &stop) 135 .await 136 .expect("turn"); 137 let reply = format!( 138 "{}{}", 139 aien_runtime::compose::rederive::COMPOSE_ASSISTANT_PREFIX, 140 tok.decode_opts(&out, true).expect("decode") 141 ); 142 let hex = |b: &[u8]| -> String { 143 sha2::Sha256::digest(b) 144 .iter() 145 .map(|x| format!("{x:02x}")) 146 .collect() 147 }; 148 println!( 149 "{}", 150 serde_json::json!({ 151 "backend": aien_inference_abi::TensorBackend::name(tb.as_ref()), "allen": allen, 152 "model_dir": dir, "model_id": config.model_id, "template": tok.template().name(), 153 "stop_ids": stop, "warm_up_ids": w, "mode": mode, "retry_reason": retry, "goal": goal, "workspace": ws, 154 "prompt_sha256": hex(prompt.as_bytes()), 155 "prompt_tokens": ids.len(), "prompt_ids_sha256": aien_runtime::token_ids_sha256(&ids), 156 "prompt_ids": ids, "max_tokens": max_tokens, "output_ids": out, "n_out": out.len(), 157 "finish": finish, "ms": ms, "reply": reply, "reply_sha256": hex(reply.as_bytes()), 158 }) 159 ); 160 } 161 162 /// The prompt of one reference run. `new` repeats the `TargetClass::New` branch of 163 /// `compose::rederive::task_decision` (the template plus `new_document_block` for the named 164 /// destination) with the product's own functions; it does not call `task_decision` 165 /// because the run being replayed may already have written that destination, which 166 /// would turn the live decision into an edit. `task` is the product's `task_prompt` 167 /// on the workspace as it is now. The tests below hold both byte-equal to the product. 168 /// Limit: a word without an extension is a destination only once it exists as a file 169 /// (`destination::path_like`), so a goal like "save it into notes/tea" can gain the block 170 /// after the run wrote `notes/tea`; name replayed destinations with an extension (v5 R1: 171 /// `notes/swim-tip.txt`). 172 fn reference_prompt(mode: &str, goal: &str, ws: &std::path::Path) -> String { 173 use aien_runtime::compose::rederive::{ 174 classify_destination, new_document_block, proposal_prompt, task_prompt, 175 }; 176 match mode { 177 "new" => { 178 let mut prompt = proposal_prompt(goal); 179 if let Some(dest) = classify_destination(goal, ws).1 { 180 prompt.push_str(&new_document_block(&dest)); 181 } 182 prompt 183 } 184 _ => task_prompt(goal, ws), 185 } 186 } 187 188 #[cfg(test)] 189 mod tests { 190 use super::reference_prompt; 191 use aien_runtime::compose::rederive::{task_decision, ProposalKind}; 192 use std::path::{Path, PathBuf}; 193 194 fn workspace() -> (tempfile::TempDir, PathBuf) { 195 let t = tempfile::tempdir().unwrap(); 196 let ws = std::fs::canonicalize(t.path()).unwrap(); 197 std::fs::create_dir_all(ws.join("docs")).unwrap(); 198 std::fs::write(ws.join("README.md"), "# workspace\n").unwrap(); 199 (t, ws) 200 } 201 202 fn product(goal: &str, ws: &Path) -> (String, ProposalKind) { 203 let ((prompt, _, kind), _) = task_decision(goal, ws).unwrap(); 204 (prompt, kind) 205 } 206 207 // NEW: a goal naming a missing file (here in a folder that does not exist yet, like 208 // v5 R1). The reference prompt equals the product prompt before the run, and stays 209 // byte-equal to it after the run wrote the destination. 210 #[test] 211 fn new_destination_prompt_equals_the_product_before_and_after_the_write() { 212 let (_t, ws) = workspace(); 213 let goal = "Save a one-sentence reminder about stretching the shoulders before swimming into notes/swim-tip.txt."; 214 let (want, kind) = product(goal, &ws); 215 assert_eq!(kind, ProposalKind::Document); 216 assert!(want.ends_with("filename: notes/swim-tip.txt"), "{want}"); 217 assert_eq!(reference_prompt("new", goal, &ws), want); 218 std::fs::create_dir_all(ws.join("notes")).unwrap(); 219 std::fs::write(ws.join("notes/swim-tip.txt"), "Stretch first.\n").unwrap(); 220 assert_eq!(reference_prompt("new", goal, &ws), want); 221 } 222 223 // EDIT: a goal naming an existing file. The reference `task` mode is the product 224 // prompt with the edit block. 225 #[test] 226 fn edit_destination_prompt_equals_the_product() { 227 let (_t, ws) = workspace(); 228 std::fs::write(ws.join("docs/plan.md"), "## Steps\n1. Start.\n").unwrap(); 229 let goal = "In the existing file docs/plan.md, add the line \"2. Finish.\" at the end."; 230 let (want, kind) = product(goal, &ws); 231 assert_eq!(kind, ProposalKind::Edit); 232 assert!( 233 want.contains("The file docs/plan.md already exists."), 234 "{want}" 235 ); 236 assert_eq!(reference_prompt("task", goal, &ws), want); 237 } 238 239 // Plain task: a goal naming no destination. Both reference modes are the product 240 // prompt, the template with no added block. 241 #[test] 242 fn plain_task_prompt_equals_the_product() { 243 let (_t, ws) = workspace(); 244 let goal = "Write a short note about brewing green tea."; 245 let (want, kind) = product(goal, &ws); 246 assert_eq!(kind, ProposalKind::Document); 247 assert_eq!(want, aien_runtime::compose::rederive::proposal_prompt(goal)); 248 assert_eq!(reference_prompt("new", goal, &ws), want); 249 assert_eq!(reference_prompt("task", goal, &ws), want); 250 } 251 } 252 253 /// The model-visible prompt with the ALLEN context the product adds in front of 254 /// the task prompt (sc#384, v7 row R1-P): `NP1_REFERENCE_ALLEN=default` repeats 255 /// `spine` exactly, `persona::prefix_prompt` with `PersonaContext::defaults()` 256 /// (an engaged subject with no saved profile: persona state "default", revision 257 /// 0, as the campaign's fixture subject reports). `none` (the default) adds 258 /// nothing, the v6 prompt. Any other value is refused: a replay must say what 259 /// it replays. A saved profile (state "applied") is not replayed by this tool. 260 fn allen_prompt(prompt: &str, allen: &str) -> String { 261 match allen { 262 "none" => prompt.to_string(), 263 "default" => aien_runtime::persona::prefix_prompt( 264 prompt, 265 Some(&aien_allen_profile::PersonaContext::defaults()), 266 ), 267 other => { 268 eprintln!("NP1_REFERENCE_ALLEN={other}: only \"none\" or \"default\" is replayed"); 269 std::process::exit(2); 270 } 271 } 272 } 273 274 #[cfg(test)] 275 mod allen_tests { 276 use super::{allen_prompt, reference_prompt}; 277 use aien_allen_profile::PersonaContext; 278 279 const R1_GOAL: &str = "Save a one-sentence reminder about stretching the shoulders before swimming into notes/swim-tip.txt."; 280 281 // The default ALLEN block goes in front of the whole task prompt, as the 282 // product does it (persona::prefix_prompt after the plan is built), not 283 // in front of the goal inside the "Goal:" line. v7 R1-P failed because the 284 // replay carried no block at all. 285 #[test] 286 fn default_allen_block_prefixes_the_whole_task_prompt() { 287 let t = tempfile::tempdir().unwrap(); 288 let ws = std::fs::canonicalize(t.path()).unwrap(); 289 let base = reference_prompt("new", R1_GOAL, &ws); 290 let got = allen_prompt(&base, "default"); 291 let want = aien_runtime::persona::prefix_prompt(&base, Some(&PersonaContext::defaults())); 292 assert_eq!(got, want); 293 assert!( 294 got.starts_with("[ALLEN style preferences saved by the user]\n"), 295 "{got}" 296 ); 297 assert!( 298 got.contains("[end of style preferences]\n\nGoal: Save a one-sentence"), 299 "{got}" 300 ); 301 assert_eq!(allen_prompt(&base, "none"), base); 302 } 303 304 // Deterministic replay check against the v7 GB10 run (evidence-v7/run/ 305 // s3-reports/s3-report-R1.json, attempt 1: prompt_tokens 164, 306 // prompt_ids_sha256 `eee4e094`...): the bytes this tool sends for R1 with 307 // the default block, through the product's template and assistant prefix, 308 // tokenize to exactly those ids. Needs the Qwen3-8B tokenizer: 309 // AIEN_QWEN3_MODEL_DIR=; skipped otherwise. 310 #[test] 311 fn v7_r1_prompt_ids_are_reproduced_exactly() { 312 let Ok(dir) = std::env::var("AIEN_QWEN3_MODEL_DIR") else { 313 eprintln!("AIEN_QWEN3_MODEL_DIR not set: v7 R1 replay check skipped"); 314 return; 315 }; 316 let tok = 317 aien_inference_abi::ChatTokenizer::from_model_dir(std::path::Path::new(&dir), None) 318 .expect("tokenizer"); 319 let t = tempfile::tempdir().unwrap(); 320 let ws = std::fs::canonicalize(t.path()).unwrap(); 321 let prompt = allen_prompt(&reference_prompt("new", R1_GOAL, &ws), "default"); 322 let msgs = vec![aien_runtime::ChatTurn { 323 role: "user".into(), 324 content: prompt, 325 }]; 326 let text = format!( 327 "{}{}", 328 aien_runtime::format_chat(tok.template(), &msgs).expect("chat"), 329 aien_runtime::compose::rederive::COMPOSE_ASSISTANT_PREFIX 330 ); 331 let ids = tok.encode(&text).expect("encode"); 332 assert_eq!(ids.len(), 164, "prompt tokens"); 333 assert_eq!( 334 aien_runtime::token_ids_sha256(&ids), 335 "`eee4e094335087285f3c4ff52fda6f9ecc946c3f145abbe9fbbccf403a6adfe6`" 336 ); 337 } 338 } 339 340 /// SPEC-v8 Section 5 deterministic replay checks (tokenizer only, no model run; 341 /// `AIEN_QWEN3_MODEL_DIR=`, skipped otherwise). Every prompt of 342 /// the v7 GB10 run is rebuilt from the frozen task file and seeds with the 343 /// product's own functions and the default ALLEN block, and its token ids must 344 /// equal the v7 record: attempt 1 of every model launch, and every retry 345 /// (`retry_prompt` with the previous attempt's recorded reason). Then each v7 346 /// refused reply is put through the v8 `corrective_retry_prompt`, and that 347 /// prompt plus the task's token cap must fit the 4096-token KV context. 348 #[cfg(test)] 349 mod v8_replay { 350 use super::allen_prompt; 351 use aien_runtime::compose::rederive::{corrective_retry_prompt, retry_prompt, task_decision}; 352 use aien_runtime::token_ids_sha256; 353 use serde_json::Value; 354 use std::path::{Path, PathBuf}; 355 356 const KV_CONTEXT_TOKENS: usize = 4096; 357 358 fn read(p: &Path) -> Value { 359 serde_json::from_slice(&std::fs::read(p).unwrap_or_else(|e| panic!("{p:?}: {e}"))).unwrap() 360 } 361 362 fn copy_dir(from: &Path, to: &Path) { 363 for e in std::fs::read_dir(from).unwrap() { 364 let e = e.unwrap(); 365 let t = to.join(e.file_name()); 366 if e.file_type().unwrap().is_dir() { 367 std::fs::create_dir_all(&t).unwrap(); 368 copy_dir(&e.path(), &t); 369 } else { 370 std::fs::copy(e.path(), &t).unwrap(); 371 } 372 } 373 } 374 375 #[test] 376 fn v7_prompts_replay_exactly_and_v8_corrective_prompts_fit() { 377 let Ok(dir) = std::env::var("AIEN_QWEN3_MODEL_DIR") else { 378 eprintln!("AIEN_QWEN3_MODEL_DIR not set: v8 replay checks skipped"); 379 return; 380 }; 381 let tok = aien_inference_abi::ChatTokenizer::from_model_dir(Path::new(&dir), None) 382 .expect("tokenizer"); 383 let ids = |prompt: &str| { 384 let msgs = vec![aien_runtime::ChatTurn { 385 role: "user".into(), 386 content: prompt.to_string(), 387 }]; 388 let text = format!( 389 "{}{}", 390 aien_runtime::format_chat(tok.template(), &msgs).expect("chat"), 391 aien_runtime::compose::rederive::COMPOSE_ASSISTANT_PREFIX 392 ); 393 tok.encode(&text).expect("encode") 394 }; 395 let camp: PathBuf = 396 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/campaigns/open-model-qwen3"); 397 let tasks = read(&camp.join("tasks-oq3-v5.json")); 398 let (mut checked, mut fits, mut bad) = (0, 0, Vec::::new()); 399 for t in tasks["tasks"].as_array().unwrap() { 400 let id = t["id"].as_str().unwrap(); 401 let rep = read(&camp.join(format!("evidence-v7/run/s3-reports/s3-report-{id}.json"))); 402 let attempts = rep["proposal_attempts"] 403 .as_array() 404 .cloned() 405 .unwrap_or_default(); 406 if attempts.is_empty() { 407 continue; // N1: refused before any model call 408 } 409 let tmp = tempfile::tempdir().unwrap(); 410 let ws = std::fs::canonicalize(tmp.path()).unwrap(); 411 if let Some(seed) = t["seed"].as_str() { 412 copy_dir(&camp.join(seed), &ws); 413 } 414 let ((base, _, _), _) = task_decision(t["goal"].as_str().unwrap(), &ws).unwrap(); 415 let base = allen_prompt(&base, "default"); 416 let cap = t["max_tokens"].as_u64().unwrap() as usize; 417 for (k, a) in attempts.iter().enumerate() { 418 let prompt = if k == 0 { 419 base.clone() 420 } else { 421 retry_prompt(&base, attempts[k - 1]["reason"].as_str().unwrap()) 422 }; 423 if let (Some(n), Some(h)) = 424 (a["prompt_tokens"].as_u64(), a["prompt_ids_sha256"].as_str()) 425 { 426 let got = ids(&prompt); 427 checked += 1; 428 if got.len() as u64 != n || token_ids_sha256(&got) != h { 429 bad.push(format!( 430 "{id} attempt {}: {} tokens vs v7 {n}", 431 k + 1, 432 got.len() 433 )); 434 } 435 } 436 if a["outcome"] == "refused" { 437 if let Some(text) = a["text"].as_str() { 438 let reason = a["reason"].as_str().unwrap(); 439 let n = ids(&corrective_retry_prompt(&base, reason, Some(text))).len(); 440 eprintln!( 441 "{id} after attempt {}: corrective prompt {n} tokens + cap {cap} = {}", 442 k + 1, 443 n + cap 444 ); 445 if n + cap <= KV_CONTEXT_TOKENS { 446 fits += 1; 447 } else { 448 bad.push(format!( 449 "{id} after attempt {}: {n} + {cap} > {KV_CONTEXT_TOKENS}", 450 k + 1 451 )); 452 } 453 } 454 } 455 } 456 } 457 eprintln!("v8 replay: {checked} v7 prompts checked, {fits} corrective prompts fit"); 458 assert!(checked >= 10, "{checked}"); 459 assert!(bad.is_empty(), "{bad:#?}"); 460 } 461 }