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 / own30b_wp_gate.rs

636 lines · 26749 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//! OWN-30B whole-prompt prefill correctness gate (W-L1G-C, 2026-10-14): is the ON path's token
17//! drift activation rounding or a bug?
18//!
19//! own30b_wp_gate <checkpoint> <receipt-dir> [--lens 512,2048] [--ops-layer 0] [--mutants]
20//! (W-RC: --lens 1 is own30b_check p1 "Hello"; other short lens take the preamble head)
21//! [--max-context 8192] [--force-memory]
22//! [--devhost] (W-L1G-E: ON and the mutants run with the router logits + combine on the chip)
23//!
24//! Loads the FP8 model once (fused attention). Per prompt length, three runs of the same prompt
25//! from an empty KV, each recording every layer's residual after attention (`x_mid`) and after
26//! the experts (`x_out`), the chosen experts, and every op of `--ops-layer`:
27//! OFF the engine's per-token OFF kernels, f32 activations (`control_step`, mode Off);
28//! CTRL the same, with the ON path's activation quantiser at every GEMM input (mode W8A8);
29//! ON the whole-prompt path (`set_whole_prompt(true)`), recorder installed, one pass.
30//! CHUNK the same ON path with the pass split in half, so the recorder is filled at each
31//! pass's `from` row. CHUNK vs ON must stay inside the same budget B as ON vs CTRL,
32//! and the first-step top-1 token must match. A trace no longer forces one pass.
33//! Then per layer the relative error (L2 over all tokens) of ON vs OFF, CTRL vs OFF and ON vs
34//! CTRL, the expert-set flips, the first-step logits, and the per-op errors at `--ops-layer`.
35//!
36//! Pass rule (fixed before the ON numbers were looked at; see the receipt's NOTES):
37//! B = max over layers of relerr(CTRL, OFF) on x_out: the rounding budget, measured by the
38//! control (first-order e4m3 activation rounding plus the routing flips it causes).
39//! PASS iff max over layers of relerr(ON, CTRL) on x_out <= B, and at `--ops-layer` (0: the
40//! layer whose inputs are identical) relerr(ON, CTRL) <= relerr(CTRL, OFF) for qkv, oproj and
41//! moe_out (the three GEMM-fed outputs with a non-zero budget).
42//! The negative controls (`--mutants`: ON with the routing mutant, ON with the gate|up scale
43//! mutant) must FAIL that rule (their max relerr vs CTRL > B).
44//! Writes run.json (every per-layer number) and run.txt into the receipt dir.
45use std::path::PathBuf;
46use std::sync::atomic::{AtomicBool, Ordering};
47use std::time::Instant;
48
49/// `--devhost` (W-L1G-E): ON runs use the device router logits + MoE combine.
50static DEVHOST: AtomicBool = AtomicBool::new(false);
51
52use aien_inference_abi::qwen3_moe_omega::w8a8_control::ControlMode;
53use aien_inference_abi::qwen3_moe_omega::{
54 AttnPath, DevicePaths, GenerateParams, Qwen3MoeOmegaEngine, WeightFormat,
55};
56use aien_inference_abi::qwen3_moe_omega_prefill::fake_quant::fake_quant_row;
57use aien_inference_abi::qwen3_moe_omega_prefill::{WpMutant, WpTrace};
58use aien_inference_abi::tokenizer::ChatTokenizer as Tokenizer;
59
60fn mem_available_gb() -> f64 {
61 std::fs::read_to_string("/proc/meminfo")
62 .ok()
63 .and_then(|t| {
64 t.lines()
65 .find(|l| l.starts_with("MemAvailable:"))
66 .and_then(|l| l.split_whitespace().nth(1))
67 .and_then(|v| v.parse::<f64>().ok())
68 })
69 .map(|kb| kb / 1024.0 / 1024.0)
70 .unwrap_or(0.0)
71}
72
73/// The TTFT tool's prompt of exactly `n` tokens (own30b_ttft.rs, copied so the gate sees the
74/// same prompt the TTFT receipts used).
75fn prompt_ids(tok: &Tokenizer, n: usize) -> Vec<u32> {
76 let enc = |t: &str| tok.encode_with_special(t, false).expect("encode");
77 let mut ids = enc("<|im_start|>user\nYou are a careful engineering assistant. Read the log below and say, in plain words, which block number has the largest decode time.\n\n");
78 let tail = enc("\nAnswer with the block number only.<|im_end|>\n<|im_start|>assistant\n");
79 // W-RC: short prompts (what the server prefills after prefix reuse). n = 1 is own30b_check's
80 // p1 ("Hello", the prompt whose ON token 0 differs); 2.. are the first n tokens of the preamble.
81 if n == 1 {
82 let one = enc("Hello");
83 assert_eq!(one.len(), 1, "\"Hello\" is one token");
84 return one;
85 }
86 if n <= ids.len() + tail.len() + 8 {
87 assert!(
88 n <= ids.len(),
89 "prompt length {n} too short for the preamble"
90 );
91 ids.truncate(n);
92 return ids;
93 }
94 let mut b = 0usize;
95 while ids.len() + tail.len() < n {
96 ids.extend(enc(&format!(
97 "[block {b}] loaded 48 layers in {} s, resident {}.{} GB\n[block {b}] prompt {} tokens, prefill {}.{} s\n[block {b}] decode 16 tokens, {} ms/token\n",
98 200 + (b * 7) % 23,
99 58 + b % 5,
100 (b * 3) % 10,
101 20 + (b * 37) % 700,
102 1 + (b * 5) % 40,
103 (b * 7) % 10,
104 50 + (b * 11) % 37,
105 )));
106 b += 1;
107 }
108 ids.truncate(n - tail.len());
109 ids.extend(tail);
110 assert_eq!(ids.len(), n);
111 ids
112}
113
114struct Run {
115 name: String,
116 trace: WpTrace,
117 logits0: Vec<f32>,
118 secs: f64,
119}
120
121/// Relative L2 error of `a` against the reference `b`, and the largest per-row relative error.
122fn relerr(a: &[f32], b: &[f32], row: usize) -> (f64, f64) {
123 let (e, w, _) = relerr_idx(a, b, row);
124 (e, w)
125}
126
127/// As [`relerr`], plus the index of the worst row.
128fn relerr_idx(a: &[f32], b: &[f32], row: usize) -> (f64, f64, usize) {
129 assert_eq!(a.len(), b.len());
130 let (mut d2, mut b2, mut worst, mut wi) = (0.0f64, 0.0f64, 0.0f64, 0usize);
131 if row > 0 {
132 for (ri, (ra, rb)) in a.chunks(row).zip(b.chunks(row)).enumerate() {
133 let (mut rd, mut rr) = (0.0f64, 0.0f64);
134 for (x, y) in ra.iter().zip(rb) {
135 let d = *x as f64 - *y as f64;
136 rd += d * d;
137 rr += *y as f64 * *y as f64;
138 }
139 d2 += rd;
140 b2 += rr;
141 if rr > 0.0 && (rd / rr).sqrt() > worst {
142 worst = (rd / rr).sqrt();
143 wi = ri;
144 }
145 }
146 }
147 (if b2 > 0.0 { (d2 / b2).sqrt() } else { 0.0 }, worst, wi)
148}
149
150/// Relative L2 error over only the rows whose expert sets agree (`same` marks them): the GEMM
151/// outputs of tokens whose routing did not flip, i.e. the GEMMs alone, without routing effects.
152fn relerr_rows(a: &[f32], b: &[f32], row: usize, same: &[bool]) -> (f64, usize) {
153 let (mut d2, mut b2, mut n) = (0.0f64, 0.0f64, 0usize);
154 for (ri, (ra, rb)) in a.chunks(row).zip(b.chunks(row)).enumerate() {
155 if !same[ri] {
156 continue;
157 }
158 n += 1;
159 for (x, y) in ra.iter().zip(rb) {
160 let d = *x as f64 - *y as f64;
161 d2 += d * d;
162 b2 += *y as f64 * *y as f64;
163 }
164 }
165 (if b2 > 0.0 { (d2 / b2).sqrt() } else { 0.0 }, n)
166}
167
168/// Per token: the two expert sets are equal.
169fn same_route(a: &[u32], b: &[u32], top_k: usize) -> Vec<bool> {
170 a.chunks(top_k)
171 .zip(b.chunks(top_k))
172 .map(|(ra, rb)| ra.iter().all(|x| rb.contains(x)))
173 .collect()
174}
175
176/// Tokens whose expert SET differs, and the number of ids of `a` not in `b`'s set for that token.
177fn flips(a: &[u32], b: &[u32], top_k: usize) -> (usize, usize) {
178 let (mut tokens, mut ids) = (0, 0);
179 for (ra, rb) in a.chunks(top_k).zip(b.chunks(top_k)) {
180 let missing = ra.iter().filter(|x| !rb.contains(x)).count();
181 if missing > 0 {
182 tokens += 1;
183 ids += missing;
184 }
185 }
186 (tokens, ids)
187}
188
189fn cosine(a: &[f32], b: &[f32]) -> f64 {
190 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
191 for (x, y) in a.iter().zip(b) {
192 ab += *x as f64 * *y as f64;
193 aa += *x as f64 * *x as f64;
194 bb += *y as f64 * *y as f64;
195 }
196 ab / (aa.sqrt() * bb.sqrt())
197}
198
199fn argmax(l: &[f32]) -> usize {
200 (0..l.len())
201 .max_by(|&a, &b| l[a].total_cmp(&l[b]))
202 .unwrap_or(0)
203}
204
205fn control_run(
206 engine: &mut Qwen3MoeOmegaEngine,
207 name: &str,
208 ids: &[u32],
209 mode: ControlMode,
210 ops_layer: usize,
211) -> Run {
212 let c = engine.weights().config.clone();
213 engine.set_whole_prompt(false).expect("off");
214 engine.reset();
215 let mut trace = WpTrace::new(Some(ops_layer));
216 trace.begin(ids.len(), c.layers, c.hidden, c.top_k);
217 let t0 = Instant::now();
218 let mut hidden = Vec::new();
219 for (row, &tok) in ids.iter().enumerate() {
220 hidden = engine
221 .control_step(tok, mode, WpMutant::None, &mut trace, row)
222 .unwrap_or_else(|e| panic!("{name} token {row}: {e}"));
223 }
224 let logits0 = engine.logits(&hidden).expect("logits");
225 Run {
226 name: name.to_string(),
227 trace,
228 logits0,
229 secs: t0.elapsed().as_secs_f64(),
230 }
231}
232
233fn on_run(
234 engine: &mut Qwen3MoeOmegaEngine,
235 name: &str,
236 ids: &[u32],
237 mutant: WpMutant,
238 ops_layer: usize,
239 chunk: usize,
240) -> Run {
241 engine
242 .set_whole_prompt(true)
243 .expect("whole-prompt prefill refused");
244 engine
245 .set_whole_prompt_device_host(DEVHOST.load(Ordering::Relaxed))
246 .expect("device router / combine refused");
247 engine.set_whole_prompt_chunk(chunk);
248 engine.whole_prompt_set_mutant(mutant).expect("mutant");
249 engine
250 .whole_prompt_set_trace(Some(WpTrace::new(Some(ops_layer))))
251 .expect("trace");
252 engine.reset();
253 let mut logits0 = Vec::new();
254 let t0 = Instant::now();
255 engine
256 .generate_with(
257 ids,
258 &GenerateParams::greedy(1, Vec::new()),
259 &mut |logits, step| {
260 if step == 0 {
261 logits0 = logits.to_vec();
262 }
263 aien_inference_abi::tensor::sample_argmax(logits).0
264 },
265 &mut |_| true,
266 )
267 .unwrap_or_else(|e| panic!("{name}: {e}"));
268 let secs = t0.elapsed().as_secs_f64();
269 let trace = engine.whole_prompt_take_trace().expect("recorder");
270 engine
271 .whole_prompt_set_mutant(WpMutant::None)
272 .expect("mutant off");
273 assert_eq!(
274 trace.m,
275 ids.len(),
276 "{name}: the whole-prompt path did not run (recorder empty)"
277 );
278 let st = engine.whole_prompt_stats().cloned().unwrap_or_default();
279 let passes = if chunk == 0 {
280 1
281 } else {
282 ids.len().div_ceil(chunk)
283 };
284 let want = if DEVHOST.load(Ordering::Relaxed) {
285 st.layers.saturating_mul(passes)
286 } else {
287 0
288 };
289 assert!(
290 st.router == want && st.combine == want,
291 "{name}: device router / combine launches {} / {}, want {want} each",
292 st.router,
293 st.combine
294 );
295 println!(
296 "{name}: routing path {} (router launches {}, combine launches {})",
297 if want > 0 { "DEVICE" } else { "HOST" },
298 st.router,
299 st.combine
300 );
301 Run {
302 name: name.to_string(),
303 trace,
304 logits0,
305 secs,
306 }
307}
308
309/// Per-layer comparison of `a` against `b`: x_mid / x_out relative errors, worst token, flips.
310fn compare_layers(a: &Run, b: &Run) -> Vec<serde_json::Value> {
311 let (h, k) = (a.trace.hidden, a.trace.top_k);
312 (0..a.trace.layers())
313 .map(|l| {
314 let (mid, mid_worst, mid_wi) = relerr_idx(&a.trace.x_mid[l], &b.trace.x_mid[l], h);
315 let (out, out_worst, out_wi) = relerr_idx(&a.trace.x_out[l], &b.trace.x_out[l], h);
316 let (ft, fi) = flips(&a.trace.experts[l], &b.trace.experts[l], k);
317 let same = same_route(&a.trace.experts[l], &b.trace.experts[l], k);
318 let (out_same, n_same) = relerr_rows(&a.trace.x_out[l], &b.trace.x_out[l], h, &same);
319 serde_json::json!({"layer": l, "mid": mid, "mid_worst_token": mid_worst, "mid_worst_idx": mid_wi, "out": out, "out_worst_token": out_worst, "out_worst_idx": out_wi, "flip_tokens": ft, "flip_ids": fi, "out_same_route": out_same, "same_route_tokens": n_same})
320 })
321 .collect()
322}
323
324fn compare_ops(a: &Run, b: &Run) -> serde_json::Value {
325 let m = a.trace.m;
326 let one = |x: &[f32], y: &[f32]| {
327 if x.is_empty() || x.len() != y.len() {
328 serde_json::Value::Null
329 } else {
330 serde_json::json!(relerr(x, y, x.len() / m).0)
331 }
332 };
333 let (oa, ob) = (&a.trace.ops, &b.trace.ops);
334 let l = a.trace.ops_layer.unwrap_or(0);
335 let same = same_route(&a.trace.experts[l], &b.trace.experts[l], a.trace.top_k);
336 let (moe_same, n_same) = if oa.moe_out.len() == ob.moe_out.len() && !oa.moe_out.is_empty() {
337 relerr_rows(&oa.moe_out, &ob.moe_out, oa.moe_out.len() / m, &same)
338 } else {
339 (f64::NAN, 0)
340 };
341 // How far apart the two runs' QUANTISED GEMM inputs are (host quantiser on the recorded pre-quant rows):
342 // the rounding-decision flips a small input difference causes, the floor of any GEMM-output comparison.
343 let quantised = |x: &[f32], y: &[f32]| {
344 if x.is_empty() || x.len() != y.len() {
345 return serde_json::Value::Null;
346 }
347 let (mut qx, mut qy) = (x.to_vec(), y.to_vec());
348 let k = x.len() / m;
349 qx.chunks_mut(k).for_each(fake_quant_row);
350 qy.chunks_mut(k).for_each(fake_quant_row);
351 serde_json::json!(relerr(&qx, &qy, k).0)
352 };
353 serde_json::json!({
354 "moe_out_same_route": moe_same, "same_route_tokens": n_same,
355 "post_quantised": quantised(&oa.post, &ob.post), "attn_quantised": quantised(&oa.attn, &ob.attn), "x_norm_quantised": quantised(&oa.x_norm, &ob.x_norm),
356 "x_norm": one(&oa.x_norm, &ob.x_norm), "qkv": one(&oa.qkv, &ob.qkv), "attn": one(&oa.attn, &ob.attn), "oproj": one(&oa.oproj, &ob.oproj),
357 "post": one(&oa.post, &ob.post), "logits": one(&oa.logits, &ob.logits), "moe_out": one(&oa.moe_out, &ob.moe_out),
358 })
359}
360
361fn max_out(layers: &[serde_json::Value]) -> f64 {
362 layers
363 .iter()
364 .map(|v| v["out"].as_f64().unwrap_or(0.0))
365 .fold(0.0, f64::max)
366}
367
368fn main() {
369 let args: Vec<String> = std::env::args().collect();
370 let checkpoint = PathBuf::from(args.get(1).expect("checkpoint dir"));
371 let receipt = PathBuf::from(args.get(2).expect("receipt dir"));
372 let (mut lens, mut ops_layer, mut mutants, mut max_context, mut force) =
373 (vec![512usize, 2048], 0usize, false, 8192usize, false);
374 let mut it = args[3..].iter();
375 while let Some(a) = it.next() {
376 match a.as_str() {
377 "--lens" => {
378 lens = it
379 .next()
380 .expect("--lens")
381 .split(',')
382 .map(|s| s.parse().expect("len"))
383 .collect()
384 }
385 "--ops-layer" => ops_layer = it.next().expect("--ops-layer").parse().expect("n"),
386 "--mutants" => mutants = true,
387 "--devhost" => DEVHOST.store(true, Ordering::Relaxed),
388 "--max-context" => max_context = it.next().expect("--max-context").parse().expect("n"),
389 "--force-memory" => force = true,
390 o => panic!("unknown argument {o}"),
391 }
392 }
393 std::fs::create_dir_all(&receipt).expect("receipt dir");
394 let mut log: Vec<String> = Vec::new();
395 let mut say = |s: String| {
396 println!("{s}");
397 log.push(s);
398 };
399 let avail = mem_available_gb();
400 say(format!("mem available before load: {avail:.1} GB"));
401 if avail < 70.0 && !force {
402 say("REFUSED: less than 70 GB available; --force-memory to override".into());
403 std::process::exit(3);
404 }
405 if let Some(us) =
406 aien_omega_gpu::parse_spin_us(std::env::var(aien_omega_gpu::SPIN_US_ENV).ok().as_deref())
407 .expect("spin env")
408 {
409 aien_omega_gpu::set_spin_us(us).expect("set spin window");
410 }
411 say(format!(
412 "build native={} pf={} pattn={} pattn_dev={}",
413 aien_omega_gpu::is_native(),
414 aien_omega_pf::is_native(),
415 aien_omega_pf::has_attention(),
416 aien_omega_pf::has_attention_dev()
417 ));
418 let tok = Tokenizer::from_file(checkpoint.join("tokenizer.json")).expect("tokenizer");
419 let t0 = Instant::now();
420 let (mut engine, report) = Qwen3MoeOmegaEngine::load_omega_paths(
421 &checkpoint,
422 max_context,
423 WeightFormat::Fp8All,
424 AttnPath::Fused,
425 DevicePaths::default(),
426 &mut |_| {},
427 )
428 .expect("load on Omega");
429 say(format!(
430 "LOAD {:.1}s resident {:.2} GB attention {} mem_available_after {:.1} GB",
431 t0.elapsed().as_secs_f64(),
432 report.resident_bytes as f64 / 1e9,
433 engine.attention_path(),
434 mem_available_gb()
435 ));
436
437 let mut docs = Vec::new();
438 let mut all_pass = true;
439 for &n in &lens {
440 let ids = prompt_ids(&tok, n);
441 let off = control_run(&mut engine, "OFF", &ids, ControlMode::Off, ops_layer);
442 say(format!(
443 "len {n} OFF (per-token OFF kernels, f32 activations): {:.1} s",
444 off.secs
445 ));
446 let ctrl = control_run(&mut engine, "CTRL", &ids, ControlMode::W8A8, ops_layer);
447 say(format!(
448 "len {n} CTRL (OFF kernels + the ON quantiser at every GEMM input): {:.1} s",
449 ctrl.secs
450 ));
451 let on = on_run(&mut engine, "ON", &ids, WpMutant::None, ops_layer, 0);
452 say(format!(
453 "len {n} ON (whole-prompt path): {:.1} s",
454 on.secs
455 ));
456 let mut runs: Vec<(&str, &Run, &Run, Vec<serde_json::Value>, serde_json::Value)> =
457 Vec::new();
458 for (a, b) in [(&on, &off), (&ctrl, &off), (&on, &ctrl)] {
459 let name = format!("{}_vs_{}", a.name, b.name);
460 let layers = compare_layers(a, b);
461 let ops = compare_ops(a, b);
462 runs.push((Box::leak(name.into_boxed_str()), a, b, layers, ops));
463 }
464 say(format!("len {n} per-layer relative error on x_out (L2 over all {n} tokens) | expert-set flips (tokens/ids):"));
465 say(format!(
466 "{:>5} {:>12} {:>12} {:>12} | {:>11} {:>11} {:>11}",
467 "layer", "ON-OFF", "CTRL-OFF", "ON-CTRL", "ON-OFF", "CTRL-OFF", "ON-CTRL"
468 ));
469 for l in 0..off.trace.layers() {
470 let v = |i: usize, key: &str| runs[i].3[l][key].as_f64().unwrap_or(0.0);
471 let f = |i: usize| {
472 format!(
473 "{}/{}",
474 runs[i].3[l]["flip_tokens"], runs[i].3[l]["flip_ids"]
475 )
476 };
477 say(format!(
478 "{l:>5} {:>12.3e} {:>12.3e} {:>12.3e} | {:>11} {:>11} {:>11}",
479 v(0, "out"),
480 v(1, "out"),
481 v(2, "out"),
482 f(0),
483 f(1),
484 f(2)
485 ));
486 }
487 say(format!(
488 "len {n} ops at layer {ops_layer} (relative error): {}",
489 ["ON-OFF", "CTRL-OFF", "ON-CTRL"]
490 .iter()
491 .zip(&runs)
492 .map(|(nm, r)| format!("{nm} {}", r.4))
493 .collect::<Vec<_>>()
494 .join(" ; ")
495 ));
496 let (c_on_off, c_ctrl_off, c_on_ctrl) = (
497 cosine(&on.logits0, &off.logits0),
498 cosine(&ctrl.logits0, &off.logits0),
499 cosine(&on.logits0, &ctrl.logits0),
500 );
501 say(format!(
502 "len {n} first-step logits cosine: ON-OFF {c_on_off:.6} CTRL-OFF {c_ctrl_off:.6} ON-CTRL {c_on_ctrl:.6}; top-1 OFF {} CTRL {} ON {}",
503 argmax(&off.logits0),
504 argmax(&ctrl.logits0),
505 argmax(&on.logits0)
506 ));
507 let budget = max_out(&runs[1].3);
508 let on_ctrl = max_out(&runs[2].3);
509 let ops_ok: Vec<(String, bool)> = ["qkv", "oproj", "moe_out"]
510 .iter()
511 .map(|k| {
512 let (a, b) = (
513 runs[2].4[*k].as_f64().unwrap_or(f64::NAN),
514 runs[1].4[*k].as_f64().unwrap_or(f64::NAN),
515 );
516 (format!("{k} ON-CTRL {a:.3e} <= CTRL-OFF {b:.3e}"), a <= b)
517 })
518 .collect();
519 let pass = on_ctrl <= budget && ops_ok.iter().all(|o| o.1);
520 all_pass &= pass;
521 say(format!("len {n} RULE: budget B = max_l relerr(CTRL,OFF) = {budget:.3e}; max_l relerr(ON,CTRL) = {on_ctrl:.3e} ({:.2} x B); ops: {}", on_ctrl / budget, ops_ok.iter().map(|o| format!("{} {}", o.0, if o.1 { "ok" } else { "VIOLATED" })).collect::<Vec<_>>().join(", ")));
522 say(format!(
523 "len {n} VERDICT: {}",
524 if pass {
525 "PASS (ON within the control's rounding budget: drift = activation rounding)"
526 } else {
527 "FAIL (ON differs from the W8A8 control beyond the rounding budget)"
528 }
529 ));
530 // Chunked arm: split the prompt so pass 2 reads the KV pass 1 wrote. The trace is
531 // indexed by `from`, so this is the path a recorder used to skip (it forced chunk 0).
532 let split = (n / 2).max(1);
533 let (chunk_pass, chunk_worst, chunk_top1) = if split < n {
534 let chunked = on_run(
535 &mut engine,
536 "ON_CHUNK",
537 &ids,
538 WpMutant::None,
539 ops_layer,
540 split,
541 );
542 engine.set_whole_prompt_chunk(0);
543 let worst = max_out(&compare_layers(&chunked, &on));
544 let same_top1 = argmax(&chunked.logits0) == argmax(&on.logits0);
545 let ok = worst <= budget && same_top1;
546 say(format!(
547 "len {n} CHUNK vs ON (chunk {split}): max_l relerr {worst:.3e} ({:.2} x B), top-1 {} vs {}: {}",
548 worst / budget,
549 argmax(&chunked.logits0),
550 argmax(&on.logits0),
551 if ok {
552 "PASS (chunked within the same budget, same top-1)"
553 } else {
554 "FAIL (chunked leaves the one-pass budget or the top-1 token)"
555 }
556 ));
557 (ok, worst, argmax(&chunked.logits0))
558 } else {
559 say(format!(
560 "len {n} CHUNK: skipped (prompt shorter than two passes)"
561 ));
562 (true, 0.0, argmax(&on.logits0))
563 };
564 all_pass &= chunk_pass;
565 // Negative controls on the chunked arm. The chunk-0 mutants below do not exercise
566 // pass 2 reading pass-1 KV. Caught means the chunk rule fails: relerr above B, or
567 // a different first-step top-1. The bound is the same B, not a wider one.
568 if mutants && split < n {
569 for (mutant, name) in [
570 (WpMutant::Routing, "MUT_ROUTING_CHUNK"),
571 (WpMutant::GateUpScales, "MUT_GUSCALES_CHUNK"),
572 ] {
573 let mu = on_run(&mut engine, name, &ids, mutant, ops_layer, split);
574 engine.set_whole_prompt_chunk(0);
575 let worst = max_out(&compare_layers(&mu, &on));
576 let caught = worst > budget || argmax(&mu.logits0) != argmax(&on.logits0);
577 all_pass &= caught;
578 say(format!(
579 "len {n} NEGATIVE CONTROL {name} vs ON (chunk {split}): max_l relerr {worst:.3e} ({:.1} x B), top-1 {} vs {}: {}",
580 worst / budget,
581 argmax(&mu.logits0),
582 argmax(&on.logits0),
583 if caught {
584 "CAUGHT (chunk rule fails it)"
585 } else {
586 "NOT CAUGHT: the chunk rule is too loose"
587 }
588 ));
589 }
590 }
591 let mut doc = serde_json::json!({
592 "len": n, "ops_layer": ops_layer, "secs": {"off": off.secs, "ctrl": ctrl.secs, "on": on.secs},
593 "layers": runs.iter().map(|r| (r.0, &r.3)).collect::<std::collections::BTreeMap<_, _>>(),
594 "ops": runs.iter().map(|r| (r.0, &r.4)).collect::<std::collections::BTreeMap<_, _>>(),
595 "logits0": {"cos_on_off": c_on_off, "cos_ctrl_off": c_ctrl_off, "cos_on_ctrl": c_on_ctrl, "top1_off": argmax(&off.logits0), "top1_ctrl": argmax(&ctrl.logits0), "top1_on": argmax(&on.logits0)},
596 "rule": {"budget": budget, "on_ctrl": on_ctrl, "ratio": on_ctrl / budget, "ops": ops_ok, "pass": pass, "chunk_vs_on": chunk_worst, "chunk_pass": chunk_pass, "chunk_top1": chunk_top1},
597 });
598 if mutants {
599 let mut mres = Vec::new();
600 for (mutant, name) in [
601 (WpMutant::Routing, "MUT_ROUTING"),
602 (WpMutant::GateUpScales, "MUT_GUSCALES"),
603 ] {
604 let mu = on_run(&mut engine, name, &ids, mutant, ops_layer, 0);
605 let layers = compare_layers(&mu, &ctrl);
606 let worst = max_out(&layers);
607 let caught = worst > budget;
608 all_pass &= caught;
609 let l0 = &layers[0];
610 say(format!(
611 "len {n} NEGATIVE CONTROL {name} vs CTRL: max_l relerr {worst:.3e} ({:.1} x B), layer 0 out {:.3e} flips {}/{}, logits cosine vs OFF {:.6}: {}",
612 worst / budget,
613 l0["out"].as_f64().unwrap_or(0.0),
614 l0["flip_tokens"],
615 l0["flip_ids"],
616 cosine(&mu.logits0, &off.logits0),
617 if caught { "CAUGHT (rule fails it)" } else { "NOT CAUGHT: the rule is too loose" }
618 ));
619 mres.push(serde_json::json!({"mutant": name, "max_out_vs_ctrl": worst, "ratio": worst / budget, "caught": caught, "layers": layers, "ops_vs_ctrl": compare_ops(&mu, &ctrl), "cos_vs_off": cosine(&mu.logits0, &off.logits0)}));
620 }
621 doc["mutants"] = serde_json::Value::Array(mres);
622 }
623 docs.push(doc);
624 }
625 say(format!(
626 "SUMMARY {}",
627 if all_pass { "PASS" } else { "FAIL" }
628 ));
629 let out = serde_json::json!({"checkpoint": checkpoint, "lens": lens, "ops_layer": ops_layer, "mutants": mutants, "runs": docs});
630 std::fs::write(
631 receipt.join("run.json"),
632 serde_json::to_string_pretty(&out).unwrap(),
633 )
634 .expect("run.json");
635 std::fs::write(receipt.join("run.txt"), log.join("\n") + "\n").expect("run.txt");
636}