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-inference-abi / src / bin / qwen36_stroke_gate.rs
| 1 | //! Stroke gate: N conversations per stroke on the chip, judged word for word (L312, the motor). |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! qwen36_stroke_gate <checkpoint-dir> <out.json> <golden.json>... (1..=8 goldens, one per head) |
| 5 | //! ``` |
| 6 | //! |
| 7 | //! Every golden is a `qwen38_check generate` record (`prompt_ids`, `generated_ids`); conversation |
| 8 | //! `c` lives in head slot `c` of ONE multi-head graph ([`Qwen38Omega::open_window_heads`]). Each |
| 9 | //! step is one [`Qwen38Omega::stroke`]: every head takes its own next token (teacher forcing with |
| 10 | //! the reference's own tokens, as `qwen38_omega_full`) in one command list, one submit. A head |
| 11 | //! whose sequence has ended keeps taking its last token; nothing of it is judged after its end. |
| 12 | //! |
| 13 | //! The rule is `qwen38_omega_full`'s, applied to every conversation: words identical to its golden |
| 14 | //! except where the host reference's top-two margin is below the written band (`MARGIN_MIN`, fixed |
| 15 | //! in advance, never from the run under test); the chip's greedy choice agrees with the reference |
| 16 | //! at every position outside the band; the shifted-by-one control is caught; the reference equals |
| 17 | //! the golden. Logit cosine and max error are recorded, not gated (open precision item). |
| 18 | //! |
| 19 | //! Negative controls, both must FAIL this gate: |
| 20 | //! - `AIEN_Q36_TEST_MUTANT=4` (the shared expert dropped), as gate 1; |
| 21 | //! - `AIEN_STROKE_SWAP=control`: half way, slots 0 and 1 exchange their state objects |
| 22 | //! ([`Qwen38Omega::swap_heads`]) while the feeds stay: each continues the OTHER conversation. |
| 23 | //! |
| 24 | //! Head swap as a feature, must PASS: `AIEN_STROKE_SWAP=feature` does the same exchange AND moves |
| 25 | //! the feeds with it (conversation 0 now lives in slot 1 and is fed and read there). |
| 26 | //! |
| 27 | //! The tool takes the hive's chip lock itself around the chip part. Inside a `spark-window` (whose |
| 28 | //! holder already owns that lock) set `AIEN_STROKE_IN_WINDOW=1` to skip it; never elsewhere. |
| 29 | //! |
| 30 | //! `AIEN_STROKE_STAMPS=1`: chip timestamps around every launch; the last stroke's chip time per launch kind |
| 31 | //! is printed and written as `timeline_last_stroke` (stamps cost chip time: never for the speed receipt). |
| 32 | //! |
| 33 | //! `AIEN_STROKE_V2=1`: the batch (L312 v2, "the ignition"): each layer is recorded for every head at |
| 34 | //! once and every weight is read once per layer for all of them; the same gate, the same controls. |
| 35 | //! The report carries `"batch": true`. |
| 36 | |
| 37 | use std::path::Path; |
| 38 | use std::time::{Duration, Instant}; |
| 39 | |
| 40 | use aien_inference_abi::qwen38::{argmax, Logits, Qwen38Config, Qwen38Reference}; |
| 41 | use aien_inference_abi::qwen38_omega::{mem_available, window_bytes, Qwen38Omega, KEEP_FREE}; |
| 42 | use aien_inference_abi::qwen3_moe::parity_stats; |
| 43 | use aien_inference_abi::qwen3_moe_omega::ShardSource; |
| 44 | use serde_json::{json, Value}; |
| 45 | |
| 46 | /// Recorded, not gated (see the crate's `qwen38_omega_full`). |
| 47 | const COSINE_MIN: f64 = 0.9999; |
| 48 | /// The written band (`qwen38_omega_full::MARGIN_MIN`): fixed 2026-10-21 02:10Z, never from the run. |
| 49 | const MARGIN_MIN: f32 = 0.1; |
| 50 | /// How long the memory wait may go on, with or without the lock, before the tool refuses. |
| 51 | const MEMORY_WAIT: Duration = Duration::from_secs(40 * 60); |
| 52 | |
| 53 | fn margin(logits: &[f32]) -> f32 { |
| 54 | let top = argmax(logits); |
| 55 | let second = logits |
| 56 | .iter() |
| 57 | .enumerate() |
| 58 | .filter(|&(i, _)| i != top) |
| 59 | .map(|(_, &v)| v) |
| 60 | .fold(f32::NEG_INFINITY, f32::max); |
| 61 | logits[top] - second |
| 62 | } |
| 63 | |
| 64 | fn ids(v: &Value, key: &str) -> Result<Vec<u32>, String> { |
| 65 | v[key] |
| 66 | .as_array() |
| 67 | .ok_or_else(|| format!("golden: no {key}"))? |
| 68 | .iter() |
| 69 | .map(|x| { |
| 70 | x.as_u64() |
| 71 | .and_then(|n| u32::try_from(n).ok()) |
| 72 | .ok_or_else(|| format!("golden: {key} holds a non-id")) |
| 73 | }) |
| 74 | .collect() |
| 75 | } |
| 76 | |
| 77 | /// One conversation: its golden, the teacher-forced sequence and where generation starts. |
| 78 | struct Conv { |
| 79 | name: String, |
| 80 | prompt: Vec<u32>, |
| 81 | generated: Vec<u32>, |
| 82 | /// `prompt ++ generated[..n-1]`: what is fed; position `p` predicts `seq[p + 1]`. |
| 83 | seq: Vec<u32>, |
| 84 | /// The position whose prediction is the first generated token. |
| 85 | first_gen: usize, |
| 86 | } |
| 87 | |
| 88 | fn load_conv(path: &str) -> Result<Conv, String> { |
| 89 | let golden: Value = |
| 90 | serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?) |
| 91 | .map_err(|e| format!("{path}: {e}"))?; |
| 92 | let prompt = ids(&golden, "prompt_ids")?; |
| 93 | let generated = ids(&golden, "generated_ids")?; |
| 94 | if prompt.is_empty() || generated.is_empty() { |
| 95 | return Err(format!("{path}: empty prompt or continuation")); |
| 96 | } |
| 97 | let mut seq = prompt.clone(); |
| 98 | seq.extend_from_slice(&generated[..generated.len() - 1]); |
| 99 | let first_gen = prompt.len() - 1; |
| 100 | let name = Path::new(path) |
| 101 | .file_stem() |
| 102 | .map_or(path.to_string(), |s| s.to_string_lossy().into_owned()); |
| 103 | Ok(Conv { |
| 104 | name, |
| 105 | prompt, |
| 106 | generated, |
| 107 | seq, |
| 108 | first_gen, |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | #[derive(Clone, Copy, PartialEq)] |
| 113 | enum Swap { |
| 114 | None, |
| 115 | /// Exchange the states of slots 0 and 1, feeds unchanged: must be caught. |
| 116 | Control, |
| 117 | /// Exchange the states and move the feeds with them: must pass. |
| 118 | Feature, |
| 119 | } |
| 120 | |
| 121 | /// The hive's chip lock (`/tmp/aien-gb10.lock`, taken as aien-serve-http takes it): held from the |
| 122 | /// upload to the end of the strokes and released when the file drops. The host reference runs |
| 123 | /// before it, so the chip is never held idle; the memory wait runs before it too. |
| 124 | /// This binary's sha256, stamped on every receipt: the script's start line is not enough once the |
| 125 | /// binary is rebuilt while a run is queued. |
| 126 | fn self_sha256() -> String { |
| 127 | use sha2::Digest; |
| 128 | match std::fs::read("/proc/self/exe") { |
| 129 | Ok(b) => format!("{:x}", sha2::Sha256::digest(&b)), |
| 130 | Err(e) => format!("unreadable: {e}"), |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn chip_lock() -> Result<std::fs::File, String> { |
| 135 | use std::os::fd::AsRawFd; |
| 136 | let f = std::fs::OpenOptions::new() |
| 137 | .read(true) |
| 138 | .write(true) |
| 139 | .create(true) |
| 140 | .truncate(false) |
| 141 | .open("/tmp/aien-gb10.lock") |
| 142 | .map_err(|e| format!("/tmp/aien-gb10.lock: {e}"))?; |
| 143 | // SAFETY: a live fd; flock blocks until the lock is ours and the kernel releases it on close. |
| 144 | if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } != 0 { |
| 145 | return Err(format!( |
| 146 | "/tmp/aien-gb10.lock: flock: {}", |
| 147 | std::io::Error::last_os_error() |
| 148 | )); |
| 149 | } |
| 150 | Ok(f) |
| 151 | } |
| 152 | |
| 153 | /// Waits (no lock held) until the box has `need` plus KEEP_FREE available, at most MEMORY_WAIT: |
| 154 | /// test servers on 18093 come and go, and an upload into a full box reaches the OOM killer. |
| 155 | fn wait_for_memory(need: u64) -> Result<u64, String> { |
| 156 | let t0 = Instant::now(); |
| 157 | let mut said = 0u64; |
| 158 | loop { |
| 159 | let avail = mem_available()?; |
| 160 | if avail >= need + KEEP_FREE { |
| 161 | return Ok(avail); |
| 162 | } |
| 163 | let s = t0.elapsed().as_secs(); |
| 164 | if t0.elapsed() >= MEMORY_WAIT { |
| 165 | return Err(format!( |
| 166 | "the whole stack needs {} MiB with {} MiB kept free, MemAvailable {} MiB after {s} s; refusing", |
| 167 | need >> 20, |
| 168 | KEEP_FREE >> 20, |
| 169 | avail >> 20 |
| 170 | )); |
| 171 | } |
| 172 | if s >= said { |
| 173 | eprintln!( |
| 174 | "waiting for memory: need {} MiB + {} MiB free, MemAvailable {} MiB ({s} s)", |
| 175 | need >> 20, |
| 176 | KEEP_FREE >> 20, |
| 177 | avail >> 20 |
| 178 | ); |
| 179 | said = s + 120; |
| 180 | } |
| 181 | std::thread::sleep(Duration::from_secs(10)); |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | fn median(v: &mut [u64]) -> u64 { |
| 186 | if v.is_empty() { |
| 187 | return 0; |
| 188 | } |
| 189 | v.sort_unstable(); |
| 190 | v[v.len() / 2] |
| 191 | } |
| 192 | |
| 193 | fn run() -> Result<bool, String> { |
| 194 | let args: Vec<String> = std::env::args().collect(); |
| 195 | let usage = "usage: qwen36_stroke_gate <checkpoint-dir> <out.json> <golden.json>... (1..=8)"; |
| 196 | if args.len() < 4 || args.len() > 11 { |
| 197 | return Err(usage.into()); |
| 198 | } |
| 199 | let dir = Path::new(&args[1]); |
| 200 | let out_path = &args[2]; |
| 201 | let convs: Vec<Conv> = args[3..] |
| 202 | .iter() |
| 203 | .map(|p| load_conv(p)) |
| 204 | .collect::<Result<_, _>>()?; |
| 205 | let heads = convs.len(); |
| 206 | let bin_sha = self_sha256(); |
| 207 | eprintln!("binary sha256 {bin_sha}"); |
| 208 | let swap = match std::env::var("AIEN_STROKE_SWAP").ok().as_deref() { |
| 209 | None | Some("") => Swap::None, |
| 210 | Some("control") => Swap::Control, |
| 211 | Some("feature") => Swap::Feature, |
| 212 | Some(v) => return Err(format!("AIEN_STROKE_SWAP={v}: control, feature or unset")), |
| 213 | }; |
| 214 | if swap != Swap::None && heads < 2 { |
| 215 | return Err(format!( |
| 216 | "AIEN_STROKE_SWAP exchanges slots 0 and 1: {heads} head(s) given, two needed" |
| 217 | )); |
| 218 | } |
| 219 | |
| 220 | let config = Qwen38Config::from_checkpoint(dir)?; |
| 221 | let layers = config.layers; |
| 222 | let vocab = config.vocab; |
| 223 | let t_max = convs.iter().map(|c| c.seq.len()).max().unwrap(); |
| 224 | let t_min = convs.iter().map(|c| c.seq.len()).min().unwrap(); |
| 225 | // The swap lands half way through the shortest conversation: both are mid-sequence. |
| 226 | let swap_at = t_min / 2; |
| 227 | eprintln!( |
| 228 | "model: {layers} layers, {heads} heads; positions {}; swap {}", |
| 229 | convs |
| 230 | .iter() |
| 231 | .map(|c| format!("{} {}", c.name, c.seq.len())) |
| 232 | .collect::<Vec<_>>() |
| 233 | .join(", "), |
| 234 | match swap { |
| 235 | Swap::None => "none".to_string(), |
| 236 | Swap::Control => format!("CONTROL at step {swap_at} (slots 0<->1, feeds stay)"), |
| 237 | Swap::Feature => format!("feature at step {swap_at} (slots 0<->1 with their feeds)"), |
| 238 | } |
| 239 | ); |
| 240 | |
| 241 | // The host reference of every conversation: logits at every position. |
| 242 | let t0 = Instant::now(); |
| 243 | let mut reference: Vec<Vec<f32>> = Vec::with_capacity(heads); |
| 244 | { |
| 245 | let mut r = Qwen38Reference::new(config.clone(), ShardSource::open(dir)?)?; |
| 246 | for c in &convs { |
| 247 | let mut state = r.new_state(); |
| 248 | reference.push(r.forward(&mut state, &c.seq, Logits::All)?); |
| 249 | } |
| 250 | } |
| 251 | let ref_s = t0.elapsed().as_secs_f64(); |
| 252 | let ref_matches_golden: Vec<bool> = convs |
| 253 | .iter() |
| 254 | .zip(&reference) |
| 255 | .map(|(c, r)| { |
| 256 | (0..c.generated.len()).all(|i| { |
| 257 | argmax(&r[(c.first_gen + i) * vocab..(c.first_gen + i + 1) * vocab]) |
| 258 | == c.generated[i] as usize |
| 259 | }) |
| 260 | }) |
| 261 | .collect(); |
| 262 | eprintln!( |
| 263 | "reference: {heads} conversations in {ref_s:.1} s; greedy tokens {} the golden records", |
| 264 | if ref_matches_golden.iter().all(|&b| b) { |
| 265 | "equal" |
| 266 | } else { |
| 267 | "DIFFER FROM" |
| 268 | } |
| 269 | ); |
| 270 | |
| 271 | // The chip: every conversation in its own head slot, one stroke per step. Uploaded only when |
| 272 | // the box keeps KEEP_FREE after it (the 18091 server shares the pool; never starve it), and |
| 273 | // only under the hive's chip lock. |
| 274 | let need = window_bytes(&config, 0, layers); |
| 275 | let in_window = std::env::var("AIEN_STROKE_IN_WINDOW").is_ok_and(|v| v == "1"); |
| 276 | // Memory moves between the wait and the lock (another lane's server loads while this process |
| 277 | // queues for the lock), so: wait, lock, look again under the lock; if short, let the lock go |
| 278 | // (the lane holding the memory may need the chip to finish) and wait on, up to MEMORY_WAIT. |
| 279 | let t_mem = Instant::now(); |
| 280 | let lock = loop { |
| 281 | let avail = wait_for_memory(need)?; |
| 282 | if in_window { |
| 283 | eprintln!( |
| 284 | "AIEN_STROKE_IN_WINDOW=1: the spark-window holds the chip lock; not taking it" |
| 285 | ); |
| 286 | break None; |
| 287 | } |
| 288 | eprintln!( |
| 289 | "memory: MemAvailable {} MiB for {} MiB; taking the chip lock", |
| 290 | avail >> 20, |
| 291 | need >> 20 |
| 292 | ); |
| 293 | let lock = chip_lock()?; |
| 294 | let avail = mem_available()?; |
| 295 | if avail >= need + KEEP_FREE { |
| 296 | break Some(lock); |
| 297 | } |
| 298 | eprintln!( |
| 299 | "under the lock MemAvailable is {} MiB (need {} + {} MiB); letting the lock go, waiting on", |
| 300 | avail >> 20, |
| 301 | need >> 20, |
| 302 | KEEP_FREE >> 20 |
| 303 | ); |
| 304 | drop(lock); |
| 305 | if t_mem.elapsed() >= MEMORY_WAIT { |
| 306 | return Err(format!( |
| 307 | "memory never stayed free under the lock within {} min; refusing", |
| 308 | MEMORY_WAIT.as_secs() / 60 |
| 309 | )); |
| 310 | } |
| 311 | std::thread::sleep(Duration::from_secs(10)); |
| 312 | }; |
| 313 | let t1 = Instant::now(); |
| 314 | let mut engine = Qwen38Omega::open_window_heads(dir, 0, layers, t_max.max(256), heads)?; |
| 315 | let upload_s = t1.elapsed().as_secs_f64(); |
| 316 | // AIEN_STROKE_V2=1: the batch (every layer recorded for all heads at once, one weight read per layer) |
| 317 | if std::env::var("AIEN_STROKE_V2").is_ok_and(|v| v == "1") { |
| 318 | engine.set_batch(true)?; |
| 319 | } |
| 320 | let batch = engine.batch(); |
| 321 | eprintln!("graph: batch (v2) {}", if batch { "ON" } else { "off" }); |
| 322 | // AIEN_STROKE_STAMPS=1: chip timestamps around every launch; the last stroke's time per launch kind |
| 323 | // goes to the report ("timeline_last_stroke"). Stamps cost chip time: not for the speed receipt. |
| 324 | let stamps = std::env::var("AIEN_STROKE_STAMPS").is_ok_and(|v| v == "1"); |
| 325 | if stamps { |
| 326 | engine.set_stamps(true)?; |
| 327 | eprintln!("graph: stamps ON (a timeline per stroke; slower)"); |
| 328 | } |
| 329 | eprintln!( |
| 330 | "graph: {heads} heads uploaded in {upload_s:.1} s, weights {} MB, KV {} MB per head", |
| 331 | engine.weight_bytes() >> 20, |
| 332 | engine.kv_bytes() >> 20 |
| 333 | ); |
| 334 | let mut slot_of: Vec<usize> = (0..heads).collect(); |
| 335 | let mut tokens: Vec<Vec<u32>> = convs |
| 336 | .iter() |
| 337 | .map(|c| Vec::with_capacity(c.seq.len())) |
| 338 | .collect(); |
| 339 | let mut gpu_logits: Vec<Vec<Vec<f32>>> = (0..heads).map(|_| Vec::new()).collect(); |
| 340 | let mut stroke_ns = Vec::with_capacity(t_max); |
| 341 | let mut swapped_at = None; |
| 342 | for p in 0..t_max { |
| 343 | if p == swap_at && swap != Swap::None { |
| 344 | engine.swap_heads(0, 1)?; |
| 345 | if swap == Swap::Feature { |
| 346 | slot_of.swap(0, 1); |
| 347 | } |
| 348 | swapped_at = Some(p); |
| 349 | } |
| 350 | let mut feed = vec![0u32; heads]; |
| 351 | for (c, conv) in convs.iter().enumerate() { |
| 352 | feed[slot_of[c]] = conv.seq[p.min(conv.seq.len() - 1)]; |
| 353 | } |
| 354 | let (out, st) = engine.stroke(&feed)?; |
| 355 | stroke_ns.push(st.chip_ns); |
| 356 | for (c, conv) in convs.iter().enumerate() { |
| 357 | if p < conv.seq.len() { |
| 358 | tokens[c].push(out[slot_of[c]]); |
| 359 | gpu_logits[c].push(engine.logits_head(slot_of[c])?); |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | let timeline = if stamps { |
| 364 | let tl = engine.timeline()?; |
| 365 | let mut per: std::collections::BTreeMap<String, (u64, u64)> = |
| 366 | std::collections::BTreeMap::new(); |
| 367 | let mut total = 0u64; |
| 368 | for (k, ns) in &tl { |
| 369 | let e = per.entry(k.clone()).or_insert((0, 0)); |
| 370 | e.0 += 1; |
| 371 | e.1 += ns; |
| 372 | total += ns; |
| 373 | } |
| 374 | let mut rows: Vec<_> = per.iter().collect(); |
| 375 | rows.sort_by_key(|r| std::cmp::Reverse(r.1 .1)); |
| 376 | for (k, (n, ns)) in &rows { |
| 377 | eprintln!( |
| 378 | "timeline: {k:>8} {n:5} launches {:9.3} ms ({:5.1}%)", |
| 379 | *ns as f64 / 1e6, |
| 380 | 100.0 * *ns as f64 / total.max(1) as f64 |
| 381 | ); |
| 382 | } |
| 383 | eprintln!( |
| 384 | "timeline: total {:.3} ms over {} launches (last stroke)", |
| 385 | total as f64 / 1e6, |
| 386 | tl.len() |
| 387 | ); |
| 388 | json!({"launches": tl.len(), "total_ns": total, |
| 389 | "per_kind": per.iter().map(|(k, (n, ns))| json!({"kind": k, "launches": n, "ns": ns})).collect::<Vec<_>>()}) |
| 390 | } else { |
| 391 | serde_json::Value::Null |
| 392 | }; |
| 393 | drop(engine); |
| 394 | drop(lock); |
| 395 | |
| 396 | // Judge every conversation by the written rule. |
| 397 | let mut convs_report = Vec::with_capacity(heads); |
| 398 | let mut all_pass = true; |
| 399 | for (c, conv) in convs.iter().enumerate() { |
| 400 | let t = conv.seq.len(); |
| 401 | let r = &reference[c]; |
| 402 | let (mut cos_min, mut p95_max, mut greedy_ok) = (f64::INFINITY, 0f32, true); |
| 403 | let (mut flips_allowed, mut flips_beyond) = (Vec::new(), Vec::new()); |
| 404 | let mut gen_tokens = Vec::new(); |
| 405 | let mut steps = Vec::with_capacity(t); |
| 406 | for (p, (logits, &tok)) in gpu_logits[c].iter().zip(&tokens[c]).enumerate() { |
| 407 | let expected = &r[p * vocab..(p + 1) * vocab]; |
| 408 | let s = parity_stats(logits, expected); |
| 409 | let (ref_tok, m) = (argmax(expected), margin(expected)); |
| 410 | let tok = tok as usize; |
| 411 | let agree = tok == ref_tok && argmax(logits) == tok; |
| 412 | if m >= MARGIN_MIN && !agree { |
| 413 | greedy_ok = false; |
| 414 | } |
| 415 | let gold = (p >= conv.first_gen).then(|| conv.generated[p - conv.first_gen] as usize); |
| 416 | if let Some(g) = gold { |
| 417 | gen_tokens.push(tok); |
| 418 | if tok != g { |
| 419 | let flip = json!({"pos": p, "token": tok, "golden": g, "ref_margin": m, "max_abs": s.max_abs}); |
| 420 | if m < MARGIN_MIN { |
| 421 | flips_allowed.push(flip); |
| 422 | } else { |
| 423 | flips_beyond.push(flip); |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | cos_min = cos_min.min(if s.non_finite > 0 { |
| 428 | f64::NEG_INFINITY |
| 429 | } else { |
| 430 | s.cosine |
| 431 | }); |
| 432 | p95_max = p95_max.max(s.p95_rel); |
| 433 | println!( |
| 434 | "{} step {p:3}: token {tok:6} ref {ref_tok:6}{} margin {m:7.3} cosine {:.6} p95_rel {:.4} max_abs {:.4}{}", |
| 435 | conv.name, |
| 436 | gold.map_or(String::new(), |g| format!(" golden {g:6}")), |
| 437 | s.cosine, |
| 438 | s.p95_rel, |
| 439 | s.max_abs, |
| 440 | if gold.is_some_and(|g| g != tok) { " GOLDEN DIFFERS" } else if agree { "" } else { " (differs)" } |
| 441 | ); |
| 442 | steps.push(json!({"pos": p, "token": tok, "ref_token": ref_tok, "golden": gold, "ref_margin": m, |
| 443 | "cosine": s.cosine, "p95_rel": s.p95_rel, "max_abs": s.max_abs, "non_finite": s.non_finite})); |
| 444 | } |
| 445 | let shift_cos = (0..t - 1) |
| 446 | .map(|p| parity_stats(&gpu_logits[c][p], &r[(p + 1) * vocab..(p + 2) * vocab]).cosine) |
| 447 | .fold(f64::NEG_INFINITY, f64::max); |
| 448 | let caught = shift_cos < COSINE_MIN; |
| 449 | let words_ok = flips_beyond.is_empty(); |
| 450 | let text_ok = gen_tokens.len() == conv.generated.len(); |
| 451 | let cosine_floor_held = cos_min >= COSINE_MIN; |
| 452 | let pass = words_ok && greedy_ok && text_ok && caught && ref_matches_golden[c]; |
| 453 | all_pass &= pass; |
| 454 | let identical = gen_tokens |
| 455 | .iter() |
| 456 | .zip(&conv.generated) |
| 457 | .filter(|(a, b)| **a == **b as usize) |
| 458 | .count(); |
| 459 | println!( |
| 460 | "{} (slot {} -> {}): {identical}/{} identical to golden ({} flips inside the written band {MARGIN_MIN}, {} beyond it); greedy {} the reference outside the band; cosine min {cos_min:.6} ({}); shifted-by-one {} -> {}", |
| 461 | conv.name, |
| 462 | c, |
| 463 | slot_of[c], |
| 464 | conv.generated.len(), |
| 465 | flips_allowed.len(), |
| 466 | flips_beyond.len(), |
| 467 | if greedy_ok { "agrees with" } else { "DIFFERS FROM" }, |
| 468 | if cosine_floor_held { "held" } else { "NOT held: open precision item" }, |
| 469 | if caught { "caught" } else { "NOT CAUGHT" }, |
| 470 | if pass { "PASS" } else { "FAIL" } |
| 471 | ); |
| 472 | convs_report.push(json!({ |
| 473 | "name": conv.name, "slot_start": c, "slot_end": slot_of[c], "positions": t, |
| 474 | "prompt_ids": conv.prompt, "golden_ids": conv.generated, "chip_ids": gen_tokens, |
| 475 | "reference_matches_golden": ref_matches_golden[c], |
| 476 | "cosine_min": cos_min, "p95_rel_max": p95_max, "greedy_agrees": greedy_ok, |
| 477 | "words_identical_outside_margin_band": words_ok, |
| 478 | "flips_allowed": flips_allowed, "flips_beyond_error": flips_beyond, |
| 479 | "cosine_floor_held": cosine_floor_held, "control_shift_best_cosine": shift_cos, |
| 480 | "control_caught": caught, "steps": steps, "pass": pass, |
| 481 | })); |
| 482 | } |
| 483 | |
| 484 | let mut ns = stroke_ns.clone(); |
| 485 | let med = median(&mut ns); |
| 486 | println!( |
| 487 | "QWEN36_STROKE_GATE heads {heads} strokes {}: chip per stroke median {:.3} ms ({} tokens per stroke; shared chip, a receipt only under spark-window); swap {}; {}", |
| 488 | stroke_ns.len(), |
| 489 | med as f64 / 1e6, |
| 490 | heads, |
| 491 | match (swap, swapped_at) { |
| 492 | (Swap::None, _) => "none".to_string(), |
| 493 | (Swap::Control, Some(p)) => format!("CONTROL at step {p} (expected FAIL)"), |
| 494 | (Swap::Feature, Some(p)) => format!("feature at step {p} (expected PASS)"), |
| 495 | (_, None) => "requested but never reached".to_string(), |
| 496 | }, |
| 497 | if all_pass { "PASS" } else { "FAIL" } |
| 498 | ); |
| 499 | let report = json!({ |
| 500 | "checkpoint": dir.display().to_string(), "layers": layers, "heads": heads, |
| 501 | "reference_s": ref_s, "upload_s": upload_s, |
| 502 | "bin_sha256": bin_sha, |
| 503 | "in_window": in_window, |
| 504 | "batch": batch, |
| 505 | "swap_mode": match swap { Swap::None => "none", Swap::Control => "control", Swap::Feature => "feature" }, |
| 506 | "swapped_at_step": swapped_at, |
| 507 | "stroke_chip_ns": stroke_ns, "stroke_chip_ns_median": med, |
| 508 | "stamps": stamps, "timeline_last_stroke": timeline, |
| 509 | "thresholds": {"cosine_min_recorded": COSINE_MIN, "margin_band_logits": MARGIN_MIN}, |
| 510 | "gate": "every conversation: words identical to its golden except where the reference's top-two margin is below the written band (0.1 logit, fixed in advance, never from the run under test); chip greedy agrees at every position outside the band; shifted-by-one caught; reference equals golden. Controls: AIEN_Q36_TEST_MUTANT=4 and AIEN_STROKE_SWAP=control must FAIL; AIEN_STROKE_SWAP=feature must PASS (L312 stroke v1)", |
| 511 | "conversations": convs_report, "pass": all_pass, |
| 512 | }); |
| 513 | std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap()) |
| 514 | .map_err(|e| format!("{out_path}: {e}"))?; |
| 515 | Ok(all_pass) |
| 516 | } |
| 517 | |
| 518 | fn main() { |
| 519 | match run() { |
| 520 | Ok(true) => {} |
| 521 | Ok(false) => std::process::exit(1), |
| 522 | Err(e) => { |
| 523 | eprintln!("qwen36_stroke_gate: {e}"); |
| 524 | std::process::exit(2); |
| 525 | } |
| 526 | } |
| 527 | } |