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

201 lines · 7975 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//! L6-A host-side tokens-per-second harness (aienos#34 lane 6).
17//!
18//! Runs the same code path as the kernel (`aienos-infer-kernel`) and the host
19//! tests: `encode_chat` + `DecodeState::prefill` + greedy `argmax`/`forward`,
20//! f32 activations, single thread. Part A checks the first 8 ids against the
21//! golden reply; Part B keeps decoding (ignoring end-of-turn) to N tokens and
22//! times each `forward` call in microseconds.
23//!
24//! Env: AIENOS_DOT (`sdot` = dotprod int8 path if present, default f32 scalar),
25//! AIENOS_MODEL (default $HOME/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf),
26//! AIENOS_N (default 64), AIENOS_COMMIT (printed as `commit`).
27//! Output: one `key: value` line per fact. Exit 0 ok, 1 parity FAIL, 2 wrong model.
28
29use aienos_infer::{argmax, DecodeState, DotProd, Gguf, Model, Tokenizer};
30use std::time::Instant;
31
32const PROMPT: &str = "What is the capital of France?";
33const MODEL_SHA256: &str = "3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1";
34const GOLDEN: [u32; 8] = [791, 6864, 315, 9822, 374, 12366, 13, 128009];
35
36fn sha256_hex(data: &[u8]) -> String {
37 const K: [u32; 64] = [
38 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
39 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
40 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
41 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
42 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
43 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
44 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
45 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
46 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
47 0xc67178f2,
48 ];
49 let mut h: [u32; 8] = [
50 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
51 0x5be0cd19,
52 ];
53 let mut block = |b: &[u8]| {
54 let mut w = [0u32; 64];
55 for i in 0..16 {
56 w[i] = u32::from_be_bytes([b[4 * i], b[4 * i + 1], b[4 * i + 2], b[4 * i + 3]]);
57 }
58 for i in 16..64 {
59 let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
60 let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
61 w[i] = w[i - 16]
62 .wrapping_add(s0)
63 .wrapping_add(w[i - 7])
64 .wrapping_add(s1);
65 }
66 let mut v = h;
67 for i in 0..64 {
68 let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
69 let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
70 let t1 = v[7]
71 .wrapping_add(s1)
72 .wrapping_add(ch)
73 .wrapping_add(K[i])
74 .wrapping_add(w[i]);
75 let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
76 let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
77 let t2 = s0.wrapping_add(maj);
78 v = [
79 t1.wrapping_add(t2),
80 v[0],
81 v[1],
82 v[2],
83 v[3].wrapping_add(t1),
84 v[4],
85 v[5],
86 v[6],
87 ];
88 }
89 for i in 0..8 {
90 h[i] = h[i].wrapping_add(v[i]);
91 }
92 };
93 let (blocks, rem) = data.as_chunks::<64>();
94 for c in blocks {
95 block(c);
96 }
97 let mut tail = rem.to_vec();
98 tail.push(0x80);
99 while tail.len() % 64 != 56 {
100 tail.push(0);
101 }
102 tail.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
103 for c in tail.as_chunks::<64>().0 {
104 block(c);
105 }
106 h.iter().map(|x| format!("{x:08x}")).collect()
107}
108
109fn join(v: &[impl ToString]) -> String {
110 v.iter()
111 .map(|x| x.to_string())
112 .collect::<Vec<_>>()
113 .join(" ")
114}
115
116fn main() {
117 let path = std::env::var("AIENOS_MODEL").unwrap_or_else(|_| {
118 format!(
119 "{}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
120 std::env::var("HOME").unwrap_or_default()
121 )
122 });
123 let n: usize = std::env::var("AIENOS_N")
124 .ok()
125 .and_then(|s| s.parse().ok())
126 .unwrap_or(64);
127 let bytes = std::fs::read(&path).unwrap_or_else(|e| {
128 eprintln!("cannot read model {path}: {e}");
129 std::process::exit(2);
130 });
131 let sha = sha256_hex(&bytes);
132 println!(
133 "commit: {}",
134 std::env::var("AIENOS_COMMIT").unwrap_or_else(|_| "unknown".into())
135 );
136 println!("model_path: {path}");
137 println!("model_sha256: {sha}");
138 println!("model_size_bytes: {}", bytes.len());
139 if sha != MODEL_SHA256 {
140 eprintln!("model sha256 mismatch, want {MODEL_SHA256}");
141 std::process::exit(2);
142 }
143 let g = Gguf::parse(&bytes).expect("gguf");
144 let m = Model::new(&g).expect("model");
145 let tok = Tokenizer::new(&g.tokenizer().expect("tokenizer data")).expect("tokenizer");
146 let ids = tok.encode_chat(PROMPT).expect("encode");
147 println!("prompt: {PROMPT}");
148 println!("prompt_ids: {}", join(&ids));
149 println!("threads: 1");
150
151 let mut st = DecodeState::new(&m, ids.len() + n + 8);
152 // AIENOS_DOT=sdot uses the dotprod int8 path when the CPU reports it (runtime
153 // detection here; the kernel passes its own decode); f32 (default) is the scalar path.
154 let want_sdot = std::env::var("AIENOS_DOT")
155 .map(|v| v == "sdot")
156 .unwrap_or(false);
157 st.dotprod = None;
158 if want_sdot {
159 #[cfg(target_arch = "aarch64")]
160 {
161 st.dotprod = DotProd::new(std::arch::is_aarch64_feature_detected!("dotprod"));
162 }
163 }
164 let _: Option<DotProd> = st.dotprod;
165 println!("dot: {}", if st.dotprod.is_some() { "sdot" } else { "f32" });
166 let t0 = Instant::now();
167 st.prefill(&m, &ids).expect("prefill");
168 let prefill_us = t0.elapsed().as_micros() as u64;
169 println!("prefill_us: {prefill_us}");
170
171 // Same loop as the kernel, except the end-of-turn stop is ignored.
172 let mut out: Vec<u32> = Vec::with_capacity(n);
173 let mut tok_us: Vec<u64> = Vec::with_capacity(n);
174 loop {
175 let t = argmax(&st.logits);
176 out.push(t);
177 if out.len() == n {
178 break;
179 }
180 let t1 = Instant::now();
181 st.forward(&m, t, true).expect("forward");
182 tok_us.push(t1.elapsed().as_micros() as u64);
183 }
184 println!("tokens: {}", join(&out));
185 println!("tok_us: {}", join(&tok_us));
186 let mean = tok_us.iter().sum::<u64>() as f64 / tok_us.len().max(1) as f64;
187 println!("decode_tokens: {}", tok_us.len());
188 println!("mean_tok_us: {mean:.1}");
189 println!("tok_per_s: {:.3}", 1e6 / mean);
190 println!(
191 "text: {}",
192 String::from_utf8_lossy(&tok.decode(&out).expect("decode")).escape_debug()
193 );
194
195 let pass = out.len() >= GOLDEN.len() && out[..GOLDEN.len()] == GOLDEN;
196 println!("golden_ids: {}", join(&GOLDEN));
197 println!("PARITY: {}", if pass { "PASS" } else { "FAIL" });
198 if !pass {
199 std::process::exit(1);
200 }
201}