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 / own_tern_check.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 | //! OWN-TERN check, stage T2: the sealed golden of our CPU reference for BitNet b1.58 2B-4T. |
| 17 | //! |
| 18 | //! own_tern_check golden <checkpoint-dir> <passage.txt|passage.json> <out-dir> |
| 19 | //! |
| 20 | //! Host only (no chip). Loads the bf16 master with our loader into i8 trit matrices, then: |
| 21 | //! - teacher-forced loss and perplexity over the whole passage (BOS first), for the reference and |
| 22 | //! the three negative controls (wrong norm order, skipped sub-norms, q and v scales swapped); |
| 23 | //! - greedy continuations (32 tokens) of our five prompts, and of the spec's five acceptance |
| 24 | //! prompts for information; |
| 25 | //! - hidden-state dumps after layers 0, 1, 15, 29 and after the final norm, plus the last |
| 26 | //! position's logits, for every prompt and for a 512-token prompt (BOS and the passage's |
| 27 | //! first 511 tokens). |
| 28 | //! |
| 29 | //! Writes `<out-dir>/golden.json` (ids, perplexity receipt, decode timing, dump sha256s), |
| 30 | //! `<out-dir>/passage-nll-<variant>.f64` (per-token losses, little-endian f64) and |
| 31 | //! `<out-dir>/dumps/*.f32` (little-endian f32, `[tokens][hidden]`; logits `[vocab]`). |
| 32 | |
| 33 | use std::path::{Path, PathBuf}; |
| 34 | use std::time::Instant; |
| 35 | |
| 36 | use aien_inference_abi::bitnet_forward::{ |
| 37 | argmax, HostBitNetForward, HostRefUploader, KvCache, Variant, |
| 38 | }; |
| 39 | use aien_inference_abi::bitnet_omega::{ |
| 40 | load_bitnet_omega, sha256_file, BITNET_2B4T_SAFETENSORS_SHA256, BITNET_2B4T_TOKENIZER_SHA256, |
| 41 | TERN_LAYOUT_ID, |
| 42 | }; |
| 43 | use aien_inference_abi::bitnet_tokenizer::BitNetTokenizer; |
| 44 | use serde_json::{json, Value}; |
| 45 | use sha2::{Digest, Sha256}; |
| 46 | |
| 47 | const OWN_PROMPTS: [(&str, &str); 5] = [ |
| 48 | ( |
| 49 | "own1-flat-tyre", |
| 50 | "The first thing to do when a bicycle tyre goes flat is", |
| 51 | ), |
| 52 | ( |
| 53 | "own2-mountain-water", |
| 54 | "Water boils at a lower temperature high on a mountain because", |
| 55 | ), |
| 56 | ( |
| 57 | "own3-bread", |
| 58 | "A simple loaf of bread needs only four ingredients:", |
| 59 | ), |
| 60 | ("own4-light", "The three primary colours of light are"), |
| 61 | ( |
| 62 | "own5-lighthouse", |
| 63 | "Once upon a time, an old lighthouse keeper", |
| 64 | ), |
| 65 | ]; |
| 66 | |
| 67 | /// Spec section 6 acceptance prompts: recorded for information, not a gate. |
| 68 | const SPEC_PROMPTS: [(&str, &str); 5] = [ |
| 69 | ("spec1-france", "The capital of France is"), |
| 70 | ("spec2-germany", "The capital of Germany is"), |
| 71 | ("spec3-count", "Count from 6 to 10:"), |
| 72 | ("spec4-boiling", "The boiling point of water in Celsius is"), |
| 73 | ("spec5-planet", "The largest planet in the solar system is"), |
| 74 | ]; |
| 75 | |
| 76 | const TAP_LAYERS: [usize; 4] = [0, 1, 15, 29]; |
| 77 | const NEW_TOKENS: usize = 32; |
| 78 | const LONG_PROMPT: usize = 512; |
| 79 | const MIN_PASSAGE_TOKENS: usize = 2000; |
| 80 | |
| 81 | fn main() { |
| 82 | let args: Vec<String> = std::env::args().collect(); |
| 83 | let r = match args.get(1).map(String::as_str) { |
| 84 | Some("golden") if args.len() == 5 => golden( |
| 85 | Path::new(&args[2]), |
| 86 | Path::new(&args[3]), |
| 87 | Path::new(&args[4]), |
| 88 | ), |
| 89 | _ => Err( |
| 90 | "usage: own_tern_check golden <checkpoint-dir> <passage.txt|passage.json> <out-dir>" |
| 91 | .into(), |
| 92 | ), |
| 93 | }; |
| 94 | if let Err(e) = r { |
| 95 | eprintln!("own_tern_check: {e}"); |
| 96 | std::process::exit(1); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | fn sha_hex(bytes: &[u8]) -> String { |
| 101 | Sha256::digest(bytes) |
| 102 | .iter() |
| 103 | .map(|b| format!("{b:02x}")) |
| 104 | .collect() |
| 105 | } |
| 106 | |
| 107 | fn write_f32(path: &Path, v: &[f32]) -> Result<String, String> { |
| 108 | let bytes: Vec<u8> = v.iter().flat_map(|x| x.to_le_bytes()).collect(); |
| 109 | std::fs::write(path, &bytes).map_err(|e| format!("{}: {e}", path.display()))?; |
| 110 | Ok(sha_hex(&bytes)) |
| 111 | } |
| 112 | |
| 113 | fn golden(ckpt: &Path, passage_path: &Path, out: &Path) -> Result<(), String> { |
| 114 | let t_all = Instant::now(); |
| 115 | let dumps = out.join("dumps"); |
| 116 | std::fs::create_dir_all(&dumps).map_err(|e| format!("{}: {e}", dumps.display()))?; |
| 117 | |
| 118 | for (file, want) in [ |
| 119 | ("model.safetensors", BITNET_2B4T_SAFETENSORS_SHA256), |
| 120 | ("tokenizer.json", BITNET_2B4T_TOKENIZER_SHA256), |
| 121 | ] { |
| 122 | let got = sha256_file(&ckpt.join(file))?; |
| 123 | if got != want { |
| 124 | return Err(format!("{file} sha256 {got} is not the pinned {want}")); |
| 125 | } |
| 126 | } |
| 127 | let tok = BitNetTokenizer::from_file(&ckpt.join("tokenizer.json"))?; |
| 128 | let passage = read_passage(passage_path)?; |
| 129 | let passage_sha = sha_hex(passage.as_bytes()); |
| 130 | let ids = tok.encode(&passage, true); |
| 131 | if ids.len() - 1 < MIN_PASSAGE_TOKENS { |
| 132 | return Err(format!( |
| 133 | "passage has {} tokens, the gate needs at least {MIN_PASSAGE_TOKENS}", |
| 134 | ids.len() - 1 |
| 135 | )); |
| 136 | } |
| 137 | if tok.decode(&ids[1..])? != passage { |
| 138 | return Err("passage does not round-trip through the tokenizer".into()); |
| 139 | } |
| 140 | eprintln!( |
| 141 | "passage: {} tokens after BOS, sha256 {passage_sha}", |
| 142 | ids.len() - 1 |
| 143 | ); |
| 144 | |
| 145 | let t_load = Instant::now(); |
| 146 | let (w, report) = load_bitnet_omega(ckpt, &HostRefUploader, &mut |m| eprintln!("load: {m}"))?; |
| 147 | let load_s = t_load.elapsed().as_secs_f64(); |
| 148 | let eos = w.config.eos_token_ids.clone(); |
| 149 | let mut f = HostBitNetForward::new(&w); |
| 150 | let h = w.config.hidden; |
| 151 | |
| 152 | // Perplexity: row i predicts ids[i + 1]. |
| 153 | let mut ppl = serde_json::Map::new(); |
| 154 | for v in [ |
| 155 | Variant::Reference, |
| 156 | Variant::SubNormAfterO, |
| 157 | Variant::SkipSubNorms, |
| 158 | Variant::SwapQvScales, |
| 159 | ] { |
| 160 | f.variant = v; |
| 161 | let t0 = Instant::now(); |
| 162 | let normed = f.forward(&ids, &mut KvCache::new(&w.config), &[], &mut Vec::new())?; |
| 163 | let n = ids.len() - 1; |
| 164 | let nll = f.nll(&normed[..n * h], &ids[1..])?; |
| 165 | let sum: f64 = nll.iter().sum(); |
| 166 | let bytes: Vec<u8> = nll.iter().flat_map(|x| x.to_le_bytes()).collect(); |
| 167 | let file = format!("passage-nll-{}.f64", v.name()); |
| 168 | std::fs::write(out.join(&file), &bytes).map_err(|e| format!("{file}: {e}"))?; |
| 169 | let mean = sum / n as f64; |
| 170 | eprintln!( |
| 171 | "{}: {n} tokens, sum nll {sum:.17e}, perplexity {:.6} ({:.1} s)", |
| 172 | v.name(), |
| 173 | mean.exp(), |
| 174 | t0.elapsed().as_secs_f64() |
| 175 | ); |
| 176 | ppl.insert( |
| 177 | v.name().into(), |
| 178 | json!({ |
| 179 | "predicted_tokens": n, |
| 180 | "sum_nll_nats": format!("{sum:.17e}"), |
| 181 | "mean_nll_nats": format!("{mean:.17e}"), |
| 182 | "perplexity": format!("{:.9}", mean.exp()), |
| 183 | "nll_file": file, |
| 184 | "nll_sha256": sha_hex(&bytes), |
| 185 | "seconds": t0.elapsed().as_secs_f64(), |
| 186 | }), |
| 187 | ); |
| 188 | } |
| 189 | f.variant = Variant::Reference; |
| 190 | |
| 191 | // Prompts: dumps, then greedy decode with the KV cache. |
| 192 | let mut prompts = Vec::new(); |
| 193 | let mut step_ms = Vec::new(); |
| 194 | let mut texts: Vec<(String, String, Vec<u32>, bool)> = OWN_PROMPTS |
| 195 | .iter() |
| 196 | .map(|(n, t)| (n.to_string(), t.to_string(), tok.encode(t, true), true)) |
| 197 | .collect(); |
| 198 | texts.extend( |
| 199 | SPEC_PROMPTS |
| 200 | .iter() |
| 201 | .map(|(n, t)| (n.to_string(), t.to_string(), tok.encode(t, true), true)), |
| 202 | ); |
| 203 | texts.push(( |
| 204 | format!("long{LONG_PROMPT}-passage-head"), |
| 205 | format!("BOS and the first {} passage tokens", LONG_PROMPT - 1), |
| 206 | ids[..LONG_PROMPT].to_vec(), |
| 207 | false, |
| 208 | )); |
| 209 | for (name, text, pids, generate) in texts { |
| 210 | let mut cache = KvCache::new(&w.config); |
| 211 | let mut taps = Vec::new(); |
| 212 | let normed = f.forward(&pids, &mut cache, &TAP_LAYERS, &mut taps)?; |
| 213 | let t = pids.len(); |
| 214 | let mut files = Vec::new(); |
| 215 | for (layer, rows) in &taps { |
| 216 | let file = format!("{name}.layer{layer:02}.f32"); |
| 217 | let sha = write_f32(&dumps.join(&file), rows)?; |
| 218 | files.push(json!({"tap": format!("layer{layer:02}"), "file": file, "shape": [t, h], "sha256": sha})); |
| 219 | } |
| 220 | let file = format!("{name}.final-norm.f32"); |
| 221 | let sha = write_f32(&dumps.join(&file), &normed)?; |
| 222 | files.push(json!({"tap": "final_norm", "file": file, "shape": [t, h], "sha256": sha})); |
| 223 | let last = f.logits(&normed[(t - 1) * h..]); |
| 224 | let file = format!("{name}.last-logits.f32"); |
| 225 | let sha = write_f32(&dumps.join(&file), &last)?; |
| 226 | files.push( |
| 227 | json!({"tap": "last_logits", "file": file, "shape": [w.config.vocab], "sha256": sha}), |
| 228 | ); |
| 229 | |
| 230 | let mut entry = json!({"name": name, "text": text, "ids": pids, "dumps": files}); |
| 231 | if generate { |
| 232 | let mut next = argmax(&last); |
| 233 | let mut gen = Vec::new(); |
| 234 | while gen.len() < NEW_TOKENS { |
| 235 | gen.push(next); |
| 236 | if eos.contains(&next) || gen.len() == NEW_TOKENS { |
| 237 | break; |
| 238 | } |
| 239 | let t0 = Instant::now(); |
| 240 | let row = f.forward(&[next], &mut cache, &[], &mut Vec::new())?; |
| 241 | next = argmax(&f.logits(&row)); |
| 242 | step_ms.push(t0.elapsed().as_secs_f64() * 1e3); |
| 243 | } |
| 244 | let cont = tok.decode(&gen)?; |
| 245 | eprintln!("{name}: {text:?} -> {cont:?}"); |
| 246 | entry["greedy_ids"] = json!(gen); |
| 247 | entry["greedy_text"] = json!(cont); |
| 248 | } |
| 249 | prompts.push(entry); |
| 250 | } |
| 251 | step_ms.sort_by(f64::total_cmp); |
| 252 | let median = step_ms.get(step_ms.len() / 2).copied().unwrap_or(0.0); |
| 253 | |
| 254 | let golden: Value = json!({ |
| 255 | "stage": "bitnet-t2-host-reference", |
| 256 | "layout_id": TERN_LAYOUT_ID, |
| 257 | "model_sha256": BITNET_2B4T_SAFETENSORS_SHA256, |
| 258 | "tokenizer_sha256": BITNET_2B4T_TOKENIZER_SHA256, |
| 259 | "arithmetic": "f32; exact int32 ternary products; per-token int8 activation absmax, round half to even; RMSNorm square sums in f64; half-split RoPE, f64 angles; tied bf16 table widened to f32", |
| 260 | "bos": "every prompt and the passage start with BOS 128000 at position 0", |
| 261 | "passage": {"file": passage_path.file_name().and_then(|s| s.to_str()), "sha256": passage_sha, "tokens_after_bos": ids.len() - 1}, |
| 262 | "passage_ids_sha256": sha_hex(&ids.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()), |
| 263 | "perplexity": ppl, |
| 264 | "prompts": prompts, |
| 265 | "greedy": {"new_tokens_max": NEW_TOKENS, "stop_ids": eos}, |
| 266 | "decode": {"steps": step_ms.len(), "median_ms_per_token": median, "note": "host reference: one-token forward plus the full-vocabulary logits, i8 trits and f32 table"}, |
| 267 | "load": {"seconds": load_s, "resident_bytes": report.resident_bytes}, |
| 268 | "total_seconds": t_all.elapsed().as_secs_f64(), |
| 269 | }); |
| 270 | let text = serde_json::to_string_pretty(&golden).map_err(|e| e.to_string())?; |
| 271 | let path: PathBuf = out.join("golden.json"); |
| 272 | std::fs::write(&path, text + "\n").map_err(|e| format!("{}: {e}", path.display()))?; |
| 273 | eprintln!("wrote {}", path.display()); |
| 274 | Ok(()) |
| 275 | } |
| 276 | |
| 277 | /// The passage text: a plain file, or the `text` field of a JSON file whose `text_sha256` must |
| 278 | /// match (the evidence keeps the passage as JSON data, dashes and all). |
| 279 | fn read_passage(path: &Path) -> Result<String, String> { |
| 280 | let raw = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; |
| 281 | if path.extension().and_then(|e| e.to_str()) != Some("json") { |
| 282 | return Ok(raw); |
| 283 | } |
| 284 | let j: Value = serde_json::from_str(&raw).map_err(|e| format!("{}: {e}", path.display()))?; |
| 285 | let text = j["text"] |
| 286 | .as_str() |
| 287 | .ok_or_else(|| format!("{}: no text field", path.display()))?; |
| 288 | let sha = sha_hex(text.as_bytes()); |
| 289 | if j["text_sha256"] != sha.as_str() { |
| 290 | return Err(format!( |
| 291 | "{}: text sha256 {sha} is not the recorded {}", |
| 292 | path.display(), |
| 293 | j["text_sha256"] |
| 294 | )); |
| 295 | } |
| 296 | Ok(text.to_string()) |
| 297 | } |