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 / q36_exact_head.rs
| 1 | //! Exact two-pass lm_head study on the host reference (HUM lever L314). |
| 2 | //! |
| 3 | //! q36_exact_head hidden <checkpoint-dir> <out.bin> <gen.json>... |
| 4 | //! q36_exact_head passage <checkpoint-dir> <out.bin> <text-file> <count> <source-id> |
| 5 | //! q36_exact_head analyze <checkpoint-dir> <hidden.bin> <out.json> |
| 6 | //! q36_exact_head export <checkpoint-dir> <out-dir> |
| 7 | //! q36_exact_head gate <checkpoint-dir> <w4|fp8> <row|group|linf|min> <scale> <out.json> <gen.json>... |
| 8 | //! |
| 9 | //! `hidden` replays each golden run (prompt_ids, then generated_ids token by token, exactly as |
| 10 | //! `qwen38_check generate` ran it) and appends the final normed hidden vector of every position; |
| 11 | //! `passage` appends the hidden vectors of a teacher-forced text. Records: `src pos next full` (u32, |
| 12 | //! `next` = the token that followed, u32::MAX when none) then `hidden` f32s. |
| 13 | //! `analyze` builds the W4 and FP8 screens of the bf16 lm_head and reports |C| for every bound, |
| 14 | //! the bytes per token, and checks the two-pass argmax against the full one on every record. |
| 15 | //! `gate` decodes greedily with the two-pass head choosing every token and compares the ids with |
| 16 | //! the golden run; 0 <= `scale` < 1 is a shrunken-bound mutant, `scale` < 0 drops the full argmax from the |
| 17 | //! candidates (a mutant that must fail). |
| 18 | use aien_inference_abi::exact_head::{self, BoundKind, Screen, ScreenKind, CHIP_GAMMA_LEN, GROUP}; |
| 19 | use aien_inference_abi::qwen38::{argmax, Logits, Qwen38Reference}; |
| 20 | use aien_inference_abi::qwen3_moe_omega::{sample_next, GenerateParams}; |
| 21 | use aien_inference_abi::tokenizer::ChatTokenizer; |
| 22 | use rayon::prelude::*; |
| 23 | use std::io::{Read, Write}; |
| 24 | use std::path::Path; |
| 25 | use std::time::Instant; |
| 26 | |
| 27 | const NONE: u32 = u32::MAX; |
| 28 | /// The 35B generation_config's top_k, and seeds per record for the sampled-draw check. |
| 29 | const TOP_K: usize = 20; |
| 30 | const SEEDS: u64 = 8; |
| 31 | |
| 32 | fn ids(v: &serde_json::Value, key: &str) -> Result<Vec<u32>, String> { |
| 33 | v[key] |
| 34 | .as_array() |
| 35 | .ok_or(format!("golden json has no {key}"))? |
| 36 | .iter() |
| 37 | .map(|x| { |
| 38 | x.as_u64() |
| 39 | .map(|x| x as u32) |
| 40 | .ok_or(format!("{key}: not an id")) |
| 41 | }) |
| 42 | .collect() |
| 43 | } |
| 44 | |
| 45 | fn golden(path: &str) -> Result<(Vec<u32>, Vec<u32>), String> { |
| 46 | let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; |
| 47 | let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| format!("{path}: {e}"))?; |
| 48 | Ok((ids(&v, "prompt_ids")?, ids(&v, "generated_ids")?)) |
| 49 | } |
| 50 | |
| 51 | fn append( |
| 52 | out: &mut std::fs::File, |
| 53 | src: u32, |
| 54 | pos: u32, |
| 55 | next: u32, |
| 56 | full: u32, |
| 57 | h: &[f32], |
| 58 | ) -> Result<(), String> { |
| 59 | let mut buf = Vec::with_capacity(16 + h.len() * 4); |
| 60 | for v in [src, pos, next, full] { |
| 61 | buf.extend_from_slice(&v.to_le_bytes()); |
| 62 | } |
| 63 | for v in h { |
| 64 | buf.extend_from_slice(&v.to_le_bytes()); |
| 65 | } |
| 66 | out.write_all(&buf).map_err(|e| e.to_string()) |
| 67 | } |
| 68 | |
| 69 | /// The last position's normed hidden vector and the full argmax, from one tapped forward. |
| 70 | fn step( |
| 71 | model: &mut Qwen38Reference<aien_inference_abi::qwen3_moe_omega::ShardSource>, |
| 72 | state: &mut aien_inference_abi::qwen38::Qwen38State, |
| 73 | tokens: &[u32], |
| 74 | ) -> Result<(Vec<f32>, usize), String> { |
| 75 | let mut taps = Vec::new(); |
| 76 | let layers = model.config.layers; |
| 77 | let logits = model.forward_tapped(state, tokens, Logits::Last, &[layers], &mut taps)?; |
| 78 | Ok((model.final_hidden(&taps[0]), argmax(&logits))) |
| 79 | } |
| 80 | |
| 81 | fn open_out(path: &str) -> Result<std::fs::File, String> { |
| 82 | std::fs::OpenOptions::new() |
| 83 | .create(true) |
| 84 | .append(true) |
| 85 | .open(path) |
| 86 | .map_err(|e| format!("{path}: {e}")) |
| 87 | } |
| 88 | |
| 89 | fn hidden(dir: &Path, out_path: &str, goldens: &[String]) -> Result<(), String> { |
| 90 | let mut model = Qwen38Reference::open(dir)?; |
| 91 | let h = model.config.hidden; |
| 92 | let mut out = open_out(out_path)?; |
| 93 | for (src, path) in goldens.iter().enumerate() { |
| 94 | let (prompt, gen) = golden(path)?; |
| 95 | let t0 = Instant::now(); |
| 96 | let mut state = model.new_state(); |
| 97 | let (rows, full) = step(&mut model, &mut state, &prompt)?; |
| 98 | // Prompt positions: the normed rows of every prompt token (all from one call). |
| 99 | let t = prompt.len(); |
| 100 | for p in 0..t { |
| 101 | let next = if p + 1 < t { prompt[p + 1] } else { gen[0] }; |
| 102 | let f = if p + 1 == t { full as u32 } else { NONE }; |
| 103 | append( |
| 104 | &mut out, |
| 105 | src as u32, |
| 106 | p as u32, |
| 107 | next, |
| 108 | f, |
| 109 | &rows[p * h..(p + 1) * h], |
| 110 | )?; |
| 111 | } |
| 112 | let mut mism = usize::from(full as u32 != gen[0]); |
| 113 | for (i, &tok) in gen.iter().enumerate().take(gen.len() - 1) { |
| 114 | let (row, full) = step(&mut model, &mut state, &[tok])?; |
| 115 | mism += usize::from(full as u32 != gen[i + 1]); |
| 116 | append( |
| 117 | &mut out, |
| 118 | src as u32, |
| 119 | (t + i) as u32, |
| 120 | gen[i + 1], |
| 121 | full as u32, |
| 122 | &row, |
| 123 | )?; |
| 124 | } |
| 125 | eprintln!( |
| 126 | "{path}: {} prompt + {} generated positions in {:.1} s, full argmax != golden at {mism} steps", |
| 127 | t, |
| 128 | gen.len() - 1, |
| 129 | t0.elapsed().as_secs_f64() |
| 130 | ); |
| 131 | } |
| 132 | Ok(()) |
| 133 | } |
| 134 | |
| 135 | fn passage( |
| 136 | dir: &Path, |
| 137 | out_path: &str, |
| 138 | text_path: &str, |
| 139 | count: usize, |
| 140 | src: u32, |
| 141 | ) -> Result<(), String> { |
| 142 | let mut text = std::fs::read_to_string(text_path).map_err(|e| format!("{text_path}: {e}"))?; |
| 143 | if let Some((cut, _)) = text.char_indices().nth(count * 8) { |
| 144 | text.truncate(cut); |
| 145 | } |
| 146 | let tok = ChatTokenizer::from_file(dir.join("tokenizer.json")).map_err(|e| e.to_string())?; |
| 147 | let mut ids = tok.encode(&text).map_err(|e| e.to_string())?; |
| 148 | ids.truncate(count); |
| 149 | let mut model = Qwen38Reference::open(dir)?; |
| 150 | let h = model.config.hidden; |
| 151 | let mut state = model.new_state(); |
| 152 | let t0 = Instant::now(); |
| 153 | let (rows, _) = step(&mut model, &mut state, &ids)?; |
| 154 | let mut out = open_out(out_path)?; |
| 155 | for p in 0..ids.len() { |
| 156 | let next = ids.get(p + 1).copied().unwrap_or(NONE); |
| 157 | append( |
| 158 | &mut out, |
| 159 | src, |
| 160 | p as u32, |
| 161 | next, |
| 162 | NONE, |
| 163 | &rows[p * h..(p + 1) * h], |
| 164 | )?; |
| 165 | } |
| 166 | eprintln!( |
| 167 | "{text_path}: {} positions in {:.1} s", |
| 168 | ids.len(), |
| 169 | t0.elapsed().as_secs_f64() |
| 170 | ); |
| 171 | Ok(()) |
| 172 | } |
| 173 | |
| 174 | struct Record { |
| 175 | src: u32, |
| 176 | pos: u32, |
| 177 | next: u32, |
| 178 | full: u32, |
| 179 | h: Vec<f32>, |
| 180 | } |
| 181 | |
| 182 | fn read_records(path: &str, k: usize) -> Result<Vec<Record>, String> { |
| 183 | let mut bytes = Vec::new(); |
| 184 | std::fs::File::open(path) |
| 185 | .and_then(|mut f| f.read_to_end(&mut bytes)) |
| 186 | .map_err(|e| format!("{path}: {e}"))?; |
| 187 | let size = 16 + 4 * k; |
| 188 | if bytes.len() % size != 0 { |
| 189 | return Err(format!( |
| 190 | "{path}: {} bytes is not a whole number of records", |
| 191 | bytes.len() |
| 192 | )); |
| 193 | } |
| 194 | let u = |b: &[u8]| u32::from_le_bytes(b.try_into().unwrap()); |
| 195 | Ok(bytes |
| 196 | .chunks_exact(size) |
| 197 | .map(|r| Record { |
| 198 | src: u(&r[0..4]), |
| 199 | pos: u(&r[4..8]), |
| 200 | next: u(&r[8..12]), |
| 201 | full: u(&r[12..16]), |
| 202 | h: r[16..] |
| 203 | .as_chunks::<4>() |
| 204 | .0 |
| 205 | .iter() |
| 206 | .map(|b| f32::from_le_bytes(*b)) |
| 207 | .collect(), |
| 208 | }) |
| 209 | .collect()) |
| 210 | } |
| 211 | |
| 212 | fn quantiles(v: &mut [usize]) -> serde_json::Value { |
| 213 | v.sort_unstable(); |
| 214 | let q = |p: f64| v[((v.len() - 1) as f64 * p).round() as usize]; |
| 215 | let mean = v.iter().sum::<usize>() as f64 / v.len() as f64; |
| 216 | serde_json::json!({ "mean": mean, "p50": q(0.5), "p90": q(0.9), "p99": q(0.99), "max": v[v.len() - 1], "min": v[0] }) |
| 217 | } |
| 218 | |
| 219 | /// First-on-ties argmax over the candidate rows `c` (ascending) of the logits `l`. |
| 220 | fn pick(c: &[u32], l: &[f32]) -> usize { |
| 221 | let mut best = c[0] as usize; |
| 222 | for &r in c { |
| 223 | if l[r as usize] > l[best] { |
| 224 | best = r as usize; |
| 225 | } |
| 226 | } |
| 227 | best |
| 228 | } |
| 229 | |
| 230 | /// Mutant scales swept per bound: the largest one that loses an argmax is the bound's slack. |
| 231 | const SCALES: [f64; 12] = [ |
| 232 | 1.0, 0.5, 0.25, 0.1, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001, 0.0005, 0.0, |
| 233 | ]; |
| 234 | |
| 235 | fn analyze(dir: &Path, hidden_path: &str, out_path: &str) -> Result<(), String> { |
| 236 | let model = Qwen38Reference::open(dir)?; |
| 237 | let head = model.lm_head(); |
| 238 | let (n, k) = (head.n(), head.k()); |
| 239 | let recs = read_records(hidden_path, k)?; |
| 240 | eprintln!("{} records, head [{n}][{k}]", recs.len()); |
| 241 | let full_bytes = (n * k * 2) as u64; |
| 242 | let row_bytes = (k * 2) as u64; |
| 243 | // Exact logits once per record (today's host head: Matrix::matmul). |
| 244 | let t0 = Instant::now(); |
| 245 | let full: Vec<(usize, Vec<f32>)> = recs |
| 246 | .iter() |
| 247 | .map(|r| { |
| 248 | let l = head.matmul(&r.h, 1); |
| 249 | (argmax(&l), l) |
| 250 | }) |
| 251 | .collect(); |
| 252 | eprintln!( |
| 253 | "full head on every record in {:.1} s", |
| 254 | t0.elapsed().as_secs_f64() |
| 255 | ); |
| 256 | let stored = recs |
| 257 | .iter() |
| 258 | .zip(&full) |
| 259 | .filter(|(r, f)| r.full != NONE && r.full as usize != f.0) |
| 260 | .count(); |
| 261 | let mut variants = Vec::new(); |
| 262 | for kind in [ScreenKind::W4, ScreenKind::Fp8, ScreenKind::Fp8Block] { |
| 263 | let t0 = Instant::now(); |
| 264 | let screen = Screen::build(head, kind)?; |
| 265 | eprintln!( |
| 266 | "{kind:?} screen built in {:.1} s", |
| 267 | t0.elapsed().as_secs_f64() |
| 268 | ); |
| 269 | let s: Vec<Vec<f32>> = recs.iter().map(|r| screen.logits(&r.h)).collect(); |
| 270 | let screen_top1 = s |
| 271 | .iter() |
| 272 | .zip(&full) |
| 273 | .filter(|(s, f)| argmax(s) == f.0) |
| 274 | .count(); |
| 275 | for bk in [ |
| 276 | BoundKind::Row, |
| 277 | BoundKind::Group, |
| 278 | BoundKind::GroupLinf, |
| 279 | BoundKind::Min, |
| 280 | ] { |
| 281 | let mut sizes = Vec::new(); |
| 282 | let mut sizes_tau = Vec::new(); |
| 283 | let mut wrong = 0; |
| 284 | let mut wrong_tau = 0; |
| 285 | let mut first_fail: Option<f64> = None; |
| 286 | let mut fails_at = Vec::new(); |
| 287 | for (i, r) in recs.iter().enumerate() { |
| 288 | let b = screen.bounds(&r.h, bk, 1.0); |
| 289 | let c = exact_head::candidates(&s[i], &b); |
| 290 | // The recheck's logits are the full head's bits (same widen + dot), so the |
| 291 | // full logits stand in for it here; gate mode and the unit tests run the recheck. |
| 292 | let got = pick(&c, &full[i].1); |
| 293 | if i == 0 { |
| 294 | assert_eq!( |
| 295 | exact_head::recheck(head, &r.h, &c).0, |
| 296 | got, |
| 297 | "recheck != full head bits" |
| 298 | ); |
| 299 | } |
| 300 | wrong += usize::from(got != full[i].0); |
| 301 | sizes.push(c.len()); |
| 302 | // Exact threshold: recheck the best upper bound first; its exact logit is a lower |
| 303 | // bound on the winner's, so tau = max(that, max_j (s_j - B_j)). |
| 304 | let ub = (0..n) |
| 305 | .max_by(|&a, &z| (s[i][a] as f64 + b[a]).total_cmp(&(s[i][z] as f64 + b[z]))) |
| 306 | .unwrap(); |
| 307 | let ct = exact_head::candidates_from(&s[i], &b, full[i].1[ub] as f64); |
| 308 | wrong_tau += usize::from(pick(&ct, &full[i].1) != full[i].0); |
| 309 | sizes_tau.push(ct.len() + usize::from(ct.binary_search(&(ub as u32)).is_err())); |
| 310 | } |
| 311 | // Mutant sweep on the plain threshold: scaled bounds until an argmax is lost. |
| 312 | for &sc in &SCALES[1..] { |
| 313 | let fails = recs |
| 314 | .iter() |
| 315 | .enumerate() |
| 316 | .filter(|(i, r)| { |
| 317 | let b = screen.bounds(&r.h, bk, sc); |
| 318 | pick(&exact_head::candidates(&s[*i], &b), &full[*i].1) != full[*i].0 |
| 319 | }) |
| 320 | .count(); |
| 321 | fails_at.push(serde_json::json!({ "scale": sc, "argmax_lost": fails })); |
| 322 | if fails > 0 && first_fail.is_none() { |
| 323 | first_fail = Some(sc); |
| 324 | } |
| 325 | } |
| 326 | // Sampling (the 35B's generation_config: temperature 1.0, top_k 20, top_p 0.95): the |
| 327 | // door masks to the top 20 first, so candidates that certify the top 20 make the draw |
| 328 | // a function of exact logits only. Checked bit for bit against the full head's draw. |
| 329 | let topk: Vec<(usize, usize)> = recs |
| 330 | .par_iter() |
| 331 | .enumerate() |
| 332 | .map(|(i, r)| { |
| 333 | let b = screen.bounds(&r.h, bk, 1.0); |
| 334 | let c = exact_head::candidates_topk(&s[i], &b, TOP_K, f64::NEG_INFINITY); |
| 335 | let mut masked = vec![f32::NEG_INFINITY; n]; |
| 336 | for &row in &c { |
| 337 | masked[row as usize] = full[i].1[row as usize]; |
| 338 | } |
| 339 | let differ = if bk == BoundKind::Min { |
| 340 | (0..SEEDS) |
| 341 | .filter(|&seed| { |
| 342 | let p = GenerateParams { |
| 343 | max_new_tokens: 1, |
| 344 | temperature: 1.0, |
| 345 | top_p: 0.95, |
| 346 | top_k: TOP_K, |
| 347 | seed, |
| 348 | stop_token_ids: Vec::new(), |
| 349 | }; |
| 350 | sample_next(&full[i].1, &p, i) != sample_next(&masked, &p, i) |
| 351 | }) |
| 352 | .count() |
| 353 | } else { |
| 354 | 0 |
| 355 | }; |
| 356 | (c.len(), differ) |
| 357 | }) |
| 358 | .collect(); |
| 359 | let mut qk: Vec<usize> = topk.iter().map(|v| v.0).collect(); |
| 360 | let draws_differ: usize = topk.iter().map(|v| v.1).sum(); |
| 361 | let fixed = kind.bytes(n, k) + bk.bytes(n, k); |
| 362 | let mut q = sizes.clone(); |
| 363 | let mut qt = sizes_tau.clone(); |
| 364 | let mean = |v: &[usize]| v.iter().sum::<usize>() as f64 / v.len() as f64; |
| 365 | let bpt = |c: f64| fixed as f64 + c * row_bytes as f64; |
| 366 | eprintln!( |
| 367 | "{kind:?} {bk:?}: |C| mean {:.1} max {}, exact-tau mean {:.1} max {}, wrong {wrong}/{wrong_tau}, first mutant fail at x{first_fail:?}", |
| 368 | mean(&sizes), |
| 369 | sizes.iter().max().unwrap(), |
| 370 | mean(&sizes_tau), |
| 371 | sizes_tau.iter().max().unwrap() |
| 372 | ); |
| 373 | variants.push(serde_json::json!({ |
| 374 | "screen": format!("{kind:?}"), "bound": format!("{bk:?}"), |
| 375 | "screen_top1_equals_full": screen_top1, "records": recs.len(), |
| 376 | "C": quantiles(&mut q), "C_exact_tau": quantiles(&mut qt), |
| 377 | "argmax_wrong": wrong, "argmax_wrong_exact_tau": wrong_tau, |
| 378 | "fixed_bytes": fixed, "bytes_per_token_mean": bpt(mean(&sizes)), |
| 379 | "bytes_per_token_mean_exact_tau": bpt(mean(&sizes_tau)), |
| 380 | "bytes_per_token_p99_exact_tau": bpt(qt[((qt.len() - 1) as f64 * 0.99).round() as usize] as f64), |
| 381 | "mutant_sweep": fails_at, "largest_scale_that_fails": first_fail, |
| 382 | "C_top20": quantiles(&mut qk), "bytes_per_token_mean_top20": bpt(qk.iter().sum::<usize>() as f64 / qk.len() as f64), |
| 383 | "sampled_draws_checked": if bk == BoundKind::Min { recs.len() as u64 * SEEDS } else { 0 }, |
| 384 | "sampled_draws_differ": draws_differ, |
| 385 | "C_per_record": sizes, "C_exact_tau_per_record": sizes_tau, |
| 386 | })); |
| 387 | } |
| 388 | } |
| 389 | let per: Vec<_> = recs |
| 390 | .iter() |
| 391 | .zip(&full) |
| 392 | .map(|(r, f)| { |
| 393 | let mut sorted = f.1.clone(); |
| 394 | sorted.sort_unstable_by(|a, b| b.total_cmp(a)); |
| 395 | let hn = r.h.iter().map(|v| (*v as f64).powi(2)).sum::<f64>().sqrt(); |
| 396 | serde_json::json!({ "src": r.src, "pos": r.pos, "next": r.next, "full_argmax": f.0, |
| 397 | "top1": sorted[0], "gap12": sorted[0] - sorted[1], "hidden_norm": hn }) |
| 398 | }) |
| 399 | .collect(); |
| 400 | let report = serde_json::json!({ |
| 401 | "head": { "rows": n, "cols": k, "group": GROUP, "full_bytes": full_bytes, "row_bytes": row_bytes }, |
| 402 | "gamma": exact_head::gamma(k), "records": recs.len(), |
| 403 | "stored_full_argmax_disagrees_with_recomputed": stored, |
| 404 | "variants": variants, "per_record": per, |
| 405 | }); |
| 406 | std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap()) |
| 407 | .map_err(|e| e.to_string()) |
| 408 | } |
| 409 | |
| 410 | fn gate( |
| 411 | dir: &Path, |
| 412 | kind: ScreenKind, |
| 413 | bk: BoundKind, |
| 414 | scale: f64, |
| 415 | out_path: &str, |
| 416 | goldens: &[String], |
| 417 | ) -> Result<bool, String> { |
| 418 | let mut model = Qwen38Reference::open(dir)?; |
| 419 | let screen = Screen::build(model.lm_head(), kind)?; |
| 420 | let mut results = Vec::new(); |
| 421 | let mut pass = true; |
| 422 | for path in goldens { |
| 423 | let (prompt, gen) = golden(path)?; |
| 424 | let mut state = model.new_state(); |
| 425 | let (rows, mut full) = step(&mut model, &mut state, &prompt)?; |
| 426 | // step returns the normed rows of every prompt position: the next token reads the last one. |
| 427 | let k = model.config.hidden; |
| 428 | let mut row = rows[rows.len() - k..].to_vec(); |
| 429 | let mut out = Vec::new(); |
| 430 | let mut cs = Vec::new(); |
| 431 | let mut diverged = None; |
| 432 | for i in 0..gen.len() { |
| 433 | let (tok, c) = if scale < 0.0 { |
| 434 | // Guaranteed-red mutant: the proven candidate set minus the full argmax. |
| 435 | let s = screen.logits(&row); |
| 436 | let b = screen.bounds(&row, bk, 1.0); |
| 437 | let mut c = exact_head::candidates(&s, &b); |
| 438 | c.retain(|&r| r as usize != full); |
| 439 | // An empty set (the winner was the only candidate) picks no row: a divergence. |
| 440 | if c.is_empty() { |
| 441 | (usize::MAX, 0) |
| 442 | } else { |
| 443 | (exact_head::recheck(model.lm_head(), &row, &c).0, c.len()) |
| 444 | } |
| 445 | } else { |
| 446 | exact_head::argmax(model.lm_head(), &screen, &row, bk, scale) |
| 447 | }; |
| 448 | out.push(tok as u32); |
| 449 | cs.push(c); |
| 450 | if tok as u32 != gen[i] || tok != full { |
| 451 | diverged = Some(i); |
| 452 | break; |
| 453 | } |
| 454 | if i + 1 < gen.len() { |
| 455 | (row, full) = step(&mut model, &mut state, &[tok as u32])?; |
| 456 | } |
| 457 | } |
| 458 | pass &= diverged.is_none(); |
| 459 | eprintln!( |
| 460 | "{path}: {} ({} tokens, max |C| {})", |
| 461 | if diverged.is_none() { |
| 462 | "IDENTICAL" |
| 463 | } else { |
| 464 | "DIVERGED" |
| 465 | }, |
| 466 | out.len(), |
| 467 | cs.iter().max().unwrap() |
| 468 | ); |
| 469 | results.push(serde_json::json!({ "golden": path, "identical": diverged.is_none(), "first_divergence": diverged, |
| 470 | "ids": out, "golden_ids": gen, "C": cs })); |
| 471 | } |
| 472 | let report = serde_json::json!({ "screen": format!("{kind:?}"), "bound": format!("{bk:?}"), "scale": scale, |
| 473 | "verdict": if pass { "PASS" } else { "FAIL" }, "runs": results }); |
| 474 | std::fs::write(out_path, serde_json::to_string_pretty(&report).unwrap()) |
| 475 | .map_err(|e| e.to_string())?; |
| 476 | Ok(pass) |
| 477 | } |
| 478 | |
| 479 | /// The chip test's inputs (weights: outside git): head.bf16 [n][k] u16, fp8b.codes [n][k] e4m3, |
| 480 | /// fp8b.scales [n/128][k/128] bf16, coef.f32 [n] (the Row bound coefficient, gamma(2100)). |
| 481 | fn export(dir: &Path, out: &str) -> Result<(), String> { |
| 482 | let model = Qwen38Reference::open(dir)?; |
| 483 | let head = model.lm_head(); |
| 484 | let (n, k) = (head.n(), head.k()); |
| 485 | std::fs::create_dir_all(out).map_err(|e| e.to_string())?; |
| 486 | let put = |name: &str, bytes: &[u8]| { |
| 487 | std::fs::write(format!("{out}/{name}"), bytes).map_err(|e| format!("{name}: {e}")) |
| 488 | }; |
| 489 | let mut raw = Vec::with_capacity(n * k * 2); |
| 490 | for r in 0..n { |
| 491 | raw.extend( |
| 492 | head.bf16_row(r) |
| 493 | .unwrap() |
| 494 | .iter() |
| 495 | .flat_map(|v| v.to_le_bytes()), |
| 496 | ); |
| 497 | } |
| 498 | put("head.bf16", &raw)?; |
| 499 | drop(raw); |
| 500 | let scales = exact_head::fp8_block_scales(head); |
| 501 | let codes = exact_head::fp8_block_codes(head, &scales); |
| 502 | let screen = Screen::build(head, ScreenKind::Fp8Block)?; |
| 503 | let bad = screen.codes_mismatch(&codes, &scales); |
| 504 | if bad != 0 { |
| 505 | return Err(format!( |
| 506 | "export: {bad} rows of codes do not reproduce the screen" |
| 507 | )); |
| 508 | } |
| 509 | put("fp8b.codes", &codes)?; |
| 510 | let sb: Vec<u8> = scales |
| 511 | .iter() |
| 512 | .flat_map(|&s| aien_inference_abi::qwen3_moe::f32_to_bf16(s).to_le_bytes()) |
| 513 | .collect(); |
| 514 | put("fp8b.scales", &sb)?; |
| 515 | let coef = screen.row_coef(CHIP_GAMMA_LEN); |
| 516 | put( |
| 517 | "coef.f32", |
| 518 | &coef |
| 519 | .iter() |
| 520 | .flat_map(|v| v.to_le_bytes()) |
| 521 | .collect::<Vec<u8>>(), |
| 522 | )?; |
| 523 | let manifest = serde_json::json!({ "n": n, "k": k, "group": GROUP, "gamma_len": CHIP_GAMMA_LEN, |
| 524 | "files": ["head.bf16", "fp8b.codes", "fp8b.scales", "coef.f32"], "codes_reproduce_screen_rows": n }); |
| 525 | put( |
| 526 | "manifest.json", |
| 527 | serde_json::to_string_pretty(&manifest).unwrap().as_bytes(), |
| 528 | )?; |
| 529 | eprintln!("export: {n} x {k} to {out}, codes reproduce the fp8b screen on every row"); |
| 530 | Ok(()) |
| 531 | } |
| 532 | |
| 533 | fn run() -> Result<i32, String> { |
| 534 | let a: Vec<String> = std::env::args().collect(); |
| 535 | let usage = "usage: q36_exact_head hidden|passage|analyze|gate ... (see the file header)"; |
| 536 | match a.get(1).map(String::as_str) { |
| 537 | Some("hidden") if a.len() >= 5 => hidden(Path::new(&a[2]), &a[3], &a[4..]).map(|_| 0), |
| 538 | Some("passage") if a.len() == 7 => { |
| 539 | let count = a[5].parse().map_err(|_| usage.to_string())?; |
| 540 | let src = a[6].parse().map_err(|_| usage.to_string())?; |
| 541 | passage(Path::new(&a[2]), &a[3], &a[4], count, src).map(|_| 0) |
| 542 | } |
| 543 | Some("analyze") if a.len() == 5 => analyze(Path::new(&a[2]), &a[3], &a[4]).map(|_| 0), |
| 544 | Some("export") if a.len() == 4 => export(Path::new(&a[2]), &a[3]).map(|_| 0), |
| 545 | Some("gate") if a.len() >= 8 => { |
| 546 | let kind = ScreenKind::parse(&a[3]).ok_or(usage)?; |
| 547 | let bk = BoundKind::parse(&a[4]).ok_or(usage)?; |
| 548 | let scale = a[5].parse().map_err(|_| usage.to_string())?; |
| 549 | gate(Path::new(&a[2]), kind, bk, scale, &a[6], &a[7..]).map(|p| if p { 0 } else { 1 }) |
| 550 | } |
| 551 | _ => Err(usage.into()), |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | fn main() { |
| 556 | match run() { |
| 557 | Ok(code) => std::process::exit(code), |
| 558 | Err(e) => { |
| 559 | eprintln!("q36_exact_head: {e}"); |
| 560 | std::process::exit(2); |
| 561 | } |
| 562 | } |
| 563 | } |