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 / tests / forward.rs

254 lines · 8948 bytes Raw Blame History
1#![allow(clippy::chunks_exact_to_as_chunks)]
2// SPDX-License-Identifier: Apache-2.0
3// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Golden tests for the Llama-3.2-1B forward pass, tokenizer and greedy decode
18//! against llama.cpp (aienos#34 lanes 2+3).
19//!
20//! Reference fixtures `tests/fixtures/ref_*.txt` were produced by
21//! `tests/ref/llama_ref.c` linked against the local llama.cpp build
22//! (command in the header of that file and in the PR body). The tests need the frozen
23//! model file (`AIENOS_MODEL`, default `~/models/aien-mail/
24//! Llama-3.2-1B-Instruct-Q4_K_M.gguf`) and print SKIPPED when it is absent.
25
26use aienos_infer::{argmax, DecodeState, DotProd, Gguf, Model, Tokenizer};
27use std::time::Instant;
28
29fn model_bytes() -> Option<Vec<u8>> {
30 let p = std::env::var("AIENOS_MODEL").unwrap_or_else(|_| {
31 format!(
32 "{}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
33 std::env::var("HOME").unwrap_or_default()
34 )
35 });
36 match std::fs::read(&p) {
37 Ok(b) => Some(b),
38 Err(_) => {
39 eprintln!("SKIPPED: model file {p} not present");
40 None
41 }
42 }
43}
44
45struct Reference {
46 ids: Vec<u32>,
47 /// (token, top1-top2 logit gap)
48 steps: Vec<(u32, f32)>,
49}
50
51fn reference(name: &str) -> Reference {
52 let path = format!(
53 "{}/tests/fixtures/ref_{name}.txt",
54 env!("CARGO_MANIFEST_DIR")
55 );
56 let text = std::fs::read_to_string(path).unwrap();
57 let mut r = Reference {
58 ids: vec![],
59 steps: vec![],
60 };
61 for line in text.lines() {
62 let f: Vec<&str> = line.split_whitespace().collect();
63 match f.first() {
64 Some(&"ids") => r.ids = f[1..].iter().map(|s| s.parse().unwrap()).collect(),
65 Some(&"step") => r.steps.push((f[2].parse().unwrap(), f[3].parse().unwrap())),
66 _ => {}
67 }
68 }
69 r
70}
71
72const PROMPTS: [(&str, &str); 3] = [
73 ("cow", "Explain copy-on-write in one sentence."),
74 ("fr", "What is the capital of France?"),
75 (
76 "uni",
77 "Say hi in 3 languages: caf\u{e9}, \u{65e5}\u{672c}\u{8a9e}, \u{1F600} (it's 100% fine).\n\n Thanks!",
78 ),
79];
80
81#[test]
82fn tokenization_matches_llama_cpp() {
83 let Some(bytes) = model_bytes() else { return };
84 let g = Gguf::parse(&bytes).unwrap();
85 let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap();
86 assert_eq!(tok.vocab_size(), 128256);
87 assert_eq!(tok.eot_id, Some(128009));
88 for (name, prompt) in PROMPTS {
89 let want = reference(name).ids;
90 assert_eq!(tok.encode_chat(prompt).unwrap(), want, "prompt {name}");
91 }
92}
93
94#[test]
95fn decode_round_trips_text() {
96 let Some(bytes) = model_bytes() else { return };
97 let g = Gguf::parse(&bytes).unwrap();
98 let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap();
99 for s in [
100 "Hello, world!",
101 " caf\u{e9} \u{65e5}\u{672c}\u{8a9e} \u{1F600}\n\n",
102 "a\tb\r\nc 12345",
103 ] {
104 let ids = tok.encode(s, false).unwrap();
105 assert_eq!(tok.decode(&ids).unwrap(), s.as_bytes(), "{s:?}");
106 }
107}
108
109fn check(q8k: bool, dot: bool, max_logit_diff: f32) {
110 let dp = if dot { host_dotprod() } else { None };
111 if dot && dp.is_none() {
112 eprintln!("SKIPPED: this CPU has no dotprod");
113 return;
114 }
115 let Some(bytes) = model_bytes() else { return };
116 let g = Gguf::parse(&bytes).unwrap();
117 let m = Model::new(&g).unwrap();
118 let tok = Tokenizer::new(&g.tokenizer().unwrap()).unwrap();
119 let mut total_match = 0;
120 let mut total = 0;
121 for (name, prompt) in PROMPTS {
122 let r = reference(name);
123 let ids = tok.encode_chat(prompt).unwrap();
124 // (c) free-running greedy
125 let mut st = DecodeState::new(&m, 256);
126 st.emulate_q8k = q8k;
127 st.dotprod = dp;
128 let t0 = Instant::now();
129 st.prefill(&m, &ids).unwrap();
130 if name == "cow" {
131 // (b)+(d) first-position logits vs llama.cpp
132 let raw = std::fs::read(format!(
133 "{}/tests/fixtures/ref_cow_logits0.f32",
134 env!("CARGO_MANIFEST_DIR")
135 ))
136 .unwrap();
137 let want: Vec<f32> = raw
138 .chunks_exact(4)
139 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
140 .collect();
141 assert_eq!(want.len(), st.logits.len());
142 let maxdiff = st
143 .logits
144 .iter()
145 .zip(&want)
146 .map(|(a, b)| (a - b).abs())
147 .fold(0f32, f32::max);
148 eprintln!("q8k={q8k} first-position logits: max abs diff vs llama.cpp = {maxdiff}");
149 let n = want.len() as f32;
150 let mean = st
151 .logits
152 .iter()
153 .zip(&want)
154 .map(|(a, b)| (a - b).abs())
155 .sum::<f32>()
156 / n;
157 let top = argmax(&want) as usize;
158 let rms_ref = (want.iter().map(|v| v * v).sum::<f32>() / n).sqrt();
159 eprintln!(
160 "mean abs diff {mean}, diff at top token {} (ref {}), ref logit rms {rms_ref}",
161 st.logits[top] - want[top],
162 want[top]
163 );
164 assert_eq!(argmax(&st.logits), argmax(&want));
165 assert!(maxdiff < max_logit_diff, "max abs logit diff {maxdiff}");
166 }
167 let mut free = Vec::new();
168 for i in 0..r.steps.len() {
169 let t = argmax(&st.logits);
170 free.push(t);
171 if t == 128009 || i + 1 == r.steps.len() {
172 break;
173 }
174 st.forward(&m, t, true).unwrap();
175 }
176 let secs = t0.elapsed().as_secs_f64();
177 let want: Vec<u32> = r.steps.iter().map(|s| s.0).collect();
178 let first_div = free.iter().zip(&want).position(|(a, b)| a != b);
179 eprintln!(
180 "{name}: {} tokens in {secs:.2}s (prefill {} + decode) {:.2} tok/s overall; free-run divergence at {:?}{}",
181 free.len(),
182 ids.len(),
183 (free.len() + ids.len()) as f64 / secs,
184 first_div,
185 first_div
186 .map(|p| format!(" (ref gap there {:.4}, ours {} vs ref {})", r.steps[p].1, free[p], want[p]))
187 .unwrap_or_default()
188 );
189 match first_div {
190 None => assert_eq!(free.len(), want.len()),
191 // A divergence is only acceptable at a near-tie in llama.cpp's own logits.
192 Some(p) => assert!(
193 r.steps[p].1 < 0.05,
194 "diverged at {p} with gap {}",
195 r.steps[p].1
196 ),
197 }
198 // teacher-forced top-1 match rate
199 let mut st = DecodeState::new(&m, 256);
200 st.emulate_q8k = q8k;
201 st.dotprod = dp;
202 st.prefill(&m, &ids).unwrap();
203 let mut hit = 0;
204 for (i, &(t, gap)) in r.steps.iter().enumerate() {
205 let mine = argmax(&st.logits);
206 if mine == t {
207 hit += 1;
208 } else {
209 eprintln!("{name}: teacher-forced mismatch at {i}: ours {mine} ref {t} (ref gap {gap:.4})");
210 assert!(gap < 0.05, "mismatch at {i} with gap {gap}");
211 }
212 if t == 128009 {
213 break;
214 }
215 st.forward(&m, t, true).unwrap();
216 }
217 total_match += hit;
218 total += r.steps.len();
219 }
220 eprintln!("teacher-forced top-1 match {total_match}/{total}");
221}
222
223/// Plain f32 activations (more accurate than ggml's int8 activations, so a
224/// small, bounded logit difference is expected).
225#[test]
226fn forward_matches_llama_cpp_f32_activations() {
227 check(false, false, 1.0);
228}
229
230/// Runtime dotprod detection on the host (the kernel uses its own decode).
231fn host_dotprod() -> Option<DotProd> {
232 #[cfg(target_arch = "aarch64")]
233 {
234 DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod"))
235 }
236 #[cfg(not(target_arch = "aarch64"))]
237 {
238 None
239 }
240}
241
242/// SDOT path: int8 Q8_K activations, integer dots (aienos#34 PI5-6). Same
243/// bounds as the f32 and Q8_K-emulation tests.
244#[test]
245fn forward_matches_llama_cpp_dotprod() {
246 check(false, true, 1.0);
247}
248
249/// Activations rounded to ggml's Q8_K grid before every quantized dot.
250#[test]
251#[ignore = "slow; run with --ignored"]
252fn forward_matches_llama_cpp_q8k_emulation() {
253 check(true, false, 1.0);
254}