interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-infer / examples / model_probe.rs

164 lines · 6630 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//! PI5-8 host probe: can the engine's forward pass run an arbitrary llama-architecture GGUF,
17//! and does it produce the same greedy tokens as llama.cpp?
18//!
19//! The prompt is given as token ids (the `ids` line printed by `tests/ref/llama_ref.c`), so the
20//! engine's own tokenizer is NOT exercised: this judges only the weights loader, the quant paths
21//! and the transformer forward pass. Greedy decode stops after the end-of-generation id (kept in
22//! the output, like llama_ref) or after N tokens.
23//!
24//! usage: model_probe MODEL.gguf IDS_FILE N EOS_ID
25//! IDS_FILE: text file whose first line is `ids <id> <id> ...` (or bare ids)
26//! Env: AIENOS_DOT=sdot (dotprod int8 path when the CPU has it; default f32 scalar).
27//! Env: AIENOS_BITS=1 also prints `bits <i> <u32>`, the f32 bits of each chosen logit.
28//! Output: one `key: value` line per fact, `step <i> <id>` lines in llama_ref's style.
29
30#![allow(clippy::chunks_exact_to_as_chunks)]
31
32use aienos_infer::{argmax, DecodeState, DotProd, GgmlType, Gguf, Model};
33use std::collections::BTreeMap;
34use std::time::Instant;
35
36fn main() {
37 let a: Vec<String> = std::env::args().collect();
38 if a.len() != 5 {
39 eprintln!("usage: model_probe MODEL.gguf IDS_FILE N EOS_ID");
40 std::process::exit(2);
41 }
42 let bytes = std::fs::read(&a[1]).expect("read model");
43 let line = std::fs::read_to_string(&a[2]).expect("read ids");
44 let ids: Vec<u32> = line
45 .lines()
46 .next()
47 .unwrap_or("")
48 .split_whitespace()
49 .filter_map(|w| w.parse().ok())
50 .collect();
51 let n: usize = a[3].parse().expect("N");
52 let eos: u32 = a[4].parse().expect("EOS_ID");
53 let g = Gguf::parse(&bytes).expect("gguf");
54 println!("arch: {}", g.architecture().unwrap_or("?"));
55 let mut hist: BTreeMap<String, usize> = BTreeMap::new();
56 for t in g.tensors() {
57 let name = match t.ty {
58 GgmlType::Q4K => "Q4_K".to_string(),
59 GgmlType::Q6K => "Q6_K".to_string(),
60 GgmlType::F32 => "F32".to_string(),
61 GgmlType::F16 => "F16".to_string(),
62 GgmlType::BF16 => "BF16".to_string(),
63 other => format!("{other:?}"),
64 };
65 *hist.entry(name).or_default() += 1;
66 }
67 println!("tensor_types: {hist:?}");
68 let m = match Model::new(&g) {
69 Ok(m) => m,
70 Err(e) => {
71 println!("MODEL_REFUSED: {e:?}");
72 std::process::exit(3);
73 }
74 };
75 let p = &m.params;
76 println!(
77 "params: layers={} embd={} heads={} kv_heads={} ff={} vocab={} rope_base={} ctx={} tied_output={}",
78 p.block_count, p.embedding_length, p.head_count, p.head_count_kv, p.feed_forward_length,
79 p.vocab_size, p.rope_freq_base, p.context_length, g.tensor("output.weight").is_none()
80 );
81 println!(
82 "gguf_eos_id: {:?} bos_id: {:?}",
83 g.u32_key("tokenizer.ggml.eos_token_id").ok(),
84 g.u32_key("tokenizer.ggml.bos_token_id").ok()
85 );
86 println!("prompt_ids: {}", ids.len());
87 let mut st = DecodeState::new(&m, ids.len() + n + 8);
88 st.dotprod = None;
89 if std::env::var("AIENOS_DOT")
90 .map(|v| v == "sdot")
91 .unwrap_or(false)
92 {
93 #[cfg(target_arch = "aarch64")]
94 {
95 st.dotprod = DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod"));
96 }
97 }
98 let _: Option<DotProd> = st.dotprod;
99 println!("dot: {}", if st.dotprod.is_some() { "sdot" } else { "f32" });
100 let t0 = Instant::now();
101 st.prefill(&m, &ids).expect("prefill");
102 println!("prefill_us: {}", t0.elapsed().as_micros());
103 // Optional: compare the first-position logits with llama.cpp's (f32 LE file written by llama_ref).
104 if let Ok(path) = std::env::var("AIENOS_LOGITS") {
105 let b = std::fs::read(&path).expect("read logits");
106 let r: Vec<f32> = b
107 .chunks_exact(4)
108 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
109 .collect();
110 let e = &st.logits;
111 if r.len() == e.len() {
112 let (mut mx, mut se, mut dot, mut na, mut nb) = (0f64, 0f64, 0f64, 0f64, 0f64);
113 for (x, y) in r.iter().zip(e.iter()) {
114 let d = (*x as f64 - *y as f64).abs();
115 mx = mx.max(d);
116 se += d * d;
117 dot += *x as f64 * *y as f64;
118 na += (*x as f64).powi(2);
119 nb += (*y as f64).powi(2);
120 }
121 let top = |v: &[f32]| {
122 v.iter()
123 .enumerate()
124 .fold(
125 (0usize, f32::MIN),
126 |a, (i, x)| if *x > a.1 { (i, *x) } else { a },
127 )
128 .0
129 };
130 println!("logits_vs_llama: n={} max_abs_diff={mx:.4} rms_diff={:.4} cosine={:.6} argmax_llama={} argmax_engine={}", r.len(), (se / r.len() as f64).sqrt(), dot / (na.sqrt() * nb.sqrt()), top(&r), top(e));
131 } else {
132 println!(
133 "logits_vs_llama: SIZE MISMATCH llama={} engine={}",
134 r.len(),
135 e.len()
136 );
137 }
138 }
139 // AIENOS_BITS=1: also print the f32 bits of each chosen logit (oracle for native/om/lm1b).
140 let bits = std::env::var("AIENOS_BITS")
141 .map(|v| v == "1")
142 .unwrap_or(false);
143 let mut tok_us = Vec::new();
144 for i in 0..n {
145 let t = argmax(&st.logits);
146 println!("step {i} {t}");
147 if bits {
148 println!("bits {i} {}", st.logits[t as usize].to_bits());
149 }
150 if t == eos {
151 println!("eog");
152 break;
153 }
154 if i + 1 == n {
155 break;
156 }
157 let t1 = Instant::now();
158 st.forward(&m, t, true).expect("forward");
159 tok_us.push(t1.elapsed().as_micros() as f64);
160 }
161 let mean = tok_us.iter().sum::<f64>() / tok_us.len().max(1) as f64;
162 println!("mean_tok_us: {mean:.1}");
163 println!("tok_per_s: {:.3}", 1e6 / mean);
164}