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-kernel / src / lib.rs

346 lines · 12816 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//! Kernel-side entry for native inference (aienos#34 lane 4 cut 1 + lane 5
17//! cut 2).
18//!
19//! The C kernel (built -mgeneral-regs-only) hands this staticlib the Llama
20//! GGUF bytes it ingested into RAM; the unit parses the header with
21//! `aienos_infer::Gguf`, binds the `Model`, tokenizes the fixed chat prompt,
22//! runs prefill, greedy-decodes until `<|eot_id|>` (128009) or [`MAX_NEW`]
23//! tokens and hands the ids, the decoded bytes and per-token timings back in
24//! an [`InferResult`] for the kernel to print. The weights stay quantised in
25//! the ingested bytes (Q4_K/Q6_K blocks are dequantised inside each dot
26//! product by `aienos_infer`); only norms, the KV cache and activations live
27//! on this unit's heap.
28//!
29//! Allocator: `aienos-infer` needs `alloc`. This crate installs a bump
30//! allocator over ONE region the kernel provides (`aienos_infer_heap_init`,
31//! a contiguous run of frames from `ck_mm_frames_alloc`). Allocation moves a
32//! cursor; `dealloc` only reclaims when the block is the newest one and
33//! `realloc` grows the newest block in place, otherwise memory is not
34//! reused. The forward pass allocates nothing (`DecodeState` is sized up
35//! front), so this is enough for one load + one generation; it is NOT a
36//! general allocator. Single core, interrupts masked by the caller: no
37//! locking. Exhaustion returns null, which Rust turns into a panic, which
38//! calls `aienos_infer_panic` (the C kernel prints and stops; it never
39//! returns). Unload: the kernel returns the region's frames and calls
40//! `aienos_infer_heap_init(0, 0)`, after which every allocation fails closed.
41#![no_std]
42
43extern crate alloc;
44
45/// Bounded resident session (open / prompt / step / cancel / close); see
46/// `session.rs`. The one-shot probe below stays as the golden regression.
47pub mod session;
48
49use alloc::vec::Vec;
50use core::alloc::{GlobalAlloc, Layout};
51use core::cell::UnsafeCell;
52use core::slice;
53
54use aienos_infer::{argmax, DecodeState, Gguf, Model, Tokenizer};
55
56/// The fixed chat prompt (user turn) of the lane's golden reference.
57pub const PROMPT: &str = "What is the capital of France?";
58
59/// `<|eot_id|>`: end of the assistant turn (tokenizer.ggml.eos_token_id of
60/// the frozen model; `crates/aienos-infer/tests/forward.rs` asserts 128009).
61pub const EOT: u32 = 128009;
62
63/// Generation stops after this many tokens if no EOT came first.
64pub const MAX_NEW: usize = 16;
65
66/// KV-cache positions: the 17-token prompt plus [`MAX_NEW`], rounded up.
67pub const KV_CAPACITY: usize = 64;
68
69/// Bytes of decoded text kept for the kernel to print.
70pub const TEXT_BYTES: usize = 256;
71
72/// Words in [`InferResult::words`] (the cut-1 probe words).
73pub const OUT_WORDS: usize = 9;
74
75/// What the kernel gets back. `#[repr(C)]`: the C side declares the same
76/// struct (native/kernel/core/infer.c `struct infer_result`).
77#[repr(C)]
78pub struct InferResult {
79 /// [0] tensor count, [1] vocab size, [2..6] first four prompt ids,
80 /// [6] prompt token count, [7] layer count, [8] allocator peak in KiB.
81 pub words: [u32; OUT_WORDS],
82 /// Generated tokens (`tokens[..ntok]`), EOT included when it came.
83 pub ntok: u32,
84 pub tokens: [u32; MAX_NEW],
85 /// Microseconds of the forward pass that produced `tokens[i]`'s logits
86 /// for i >= 1 (`tok_us[0]` is 0: token 0 comes from the prefill).
87 pub tok_us: [u64; MAX_NEW],
88 /// Microseconds of the whole prefill (one forward per prompt token).
89 pub prefill_us: u64,
90 /// Decoded bytes of `tokens[..ntok]` (`text[..text_len]`, truncated to
91 /// [`TEXT_BYTES`]; control tokens decode to nothing).
92 pub text_len: u32,
93 pub text: [u8; TEXT_BYTES],
94}
95
96extern "C" {
97 /// Provided by native/kernel/core/infer.c: prints a message and halts the
98 /// kernel with a panic report. Never returns.
99 fn aienos_infer_panic() -> !;
100 /// Kernel monotonic clock in microseconds (native/kernel/include/ck.h).
101 /// General-registers-only C: safe to call with FP state live.
102 fn ck_time_us() -> u64;
103}
104
105#[panic_handler]
106fn panic(_: &core::panic::PanicInfo) -> ! {
107 // SAFETY: plain C function with no arguments, defined by the kernel.
108 unsafe { aienos_infer_panic() }
109}
110
111struct Bump {
112 base: UnsafeCell<usize>,
113 end: UnsafeCell<usize>,
114 next: UnsafeCell<usize>,
115 last: UnsafeCell<usize>, // start of the newest block, 0 if none
116 peak: UnsafeCell<usize>,
117}
118
119// SAFETY: used from one core with interrupts masked (documented above).
120unsafe impl Sync for Bump {}
121
122#[global_allocator]
123static HEAP: Bump = Bump {
124 base: UnsafeCell::new(0),
125 end: UnsafeCell::new(0),
126 next: UnsafeCell::new(0),
127 last: UnsafeCell::new(0),
128 peak: UnsafeCell::new(0),
129};
130
131unsafe impl GlobalAlloc for Bump {
132 unsafe fn alloc(&self, l: Layout) -> *mut u8 {
133 let next = *self.next.get();
134 let start = match next.checked_add(l.align() - 1) {
135 Some(v) => v & !(l.align() - 1),
136 None => return core::ptr::null_mut(),
137 };
138 match start.checked_add(l.size()) {
139 Some(e) if e <= *self.end.get() && *self.base.get() != 0 => {
140 *self.next.get() = e;
141 *self.last.get() = start;
142 let used = e - *self.base.get();
143 if used > *self.peak.get() {
144 *self.peak.get() = used;
145 }
146 start as *mut u8
147 }
148 _ => core::ptr::null_mut(),
149 }
150 }
151
152 unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
153 if p as usize == *self.last.get() && p as usize + l.size() == *self.next.get() {
154 *self.next.get() = p as usize;
155 *self.last.get() = 0;
156 }
157 }
158
159 unsafe fn realloc(&self, p: *mut u8, l: Layout, new_size: usize) -> *mut u8 {
160 if p as usize == *self.last.get() && p as usize + l.size() == *self.next.get() {
161 if let Some(e) = (p as usize).checked_add(new_size) {
162 if e <= *self.end.get() {
163 *self.next.get() = e;
164 let used = e - *self.base.get();
165 if used > *self.peak.get() {
166 *self.peak.get() = used;
167 }
168 return p;
169 }
170 }
171 return core::ptr::null_mut();
172 }
173 let n = self.alloc(Layout::from_size_align_unchecked(new_size, l.align()));
174 if !n.is_null() {
175 core::ptr::copy_nonoverlapping(p, n, l.size().min(new_size));
176 }
177 n
178 }
179}
180
181/// Bytes of the region still unallocated (0 when no region is set).
182pub(crate) fn heap_remaining() -> usize {
183 // SAFETY: single core, interrupts masked (see the allocator contract).
184 unsafe { (*HEAP.end.get()).saturating_sub(*HEAP.next.get()) }
185}
186
187/// Bytes allocated so far (cursor minus base; 0 when no region is set).
188pub(crate) fn heap_used() -> usize {
189 // SAFETY: as above.
190 unsafe { (*HEAP.next.get()).saturating_sub(*HEAP.base.get()) }
191}
192
193/// Reports the allocator's used and peak bytes, for the kernel's evidence
194/// lines (a session's creep across prompts is visible here).
195///
196/// # Safety
197/// `used` and `peak` must be valid or null.
198#[no_mangle]
199pub unsafe extern "C" fn aienos_infer_heap_stats(used: *mut u64, peak: *mut u64) {
200 if !used.is_null() {
201 *used = heap_used() as u64;
202 }
203 if !peak.is_null() {
204 *peak = *HEAP.peak.get() as u64;
205 }
206}
207
208/// Gives the allocator its region `[base, base+len)`. Call once, before
209/// `aienos_infer_run`. Calling it again with `(0, 0)` after the kernel has
210/// returned the frames forgets the region: every later allocation fails
211/// closed (null -> panic) instead of touching freed memory.
212///
213/// # Safety
214/// The region must be writable RAM owned by the caller for the rest of the
215/// run, 16-byte aligned, and not overlap the model bytes.
216#[no_mangle]
217pub unsafe extern "C" fn aienos_infer_heap_init(base: usize, len: usize) {
218 *HEAP.base.get() = base;
219 *HEAP.end.get() = base + len;
220 *HEAP.next.get() = base;
221 *HEAP.last.get() = 0;
222 *HEAP.peak.get() = 0;
223}
224
225/// Error codes (negative): -1 null/short args, -2 GGUF parse, -3 model bind,
226/// -4 tokenizer data, -5 tokenizer build, -6 encode, -7 fewer than 4 ids,
227/// -8 prompt longer than the KV cache, -9 prefill, -10 decode forward,
228/// -11 token-to-text decode.
229fn run(bytes: &[u8], r: &mut InferResult) -> i32 {
230 let g = match Gguf::parse(bytes) {
231 Ok(g) => g,
232 Err(_) => return -2,
233 };
234 r.words[0] = g.tensors().len() as u32;
235 let model = match Model::new(&g) {
236 Ok(m) => m,
237 Err(_) => return -3,
238 };
239 let td = match g.tokenizer() {
240 Ok(t) => t,
241 Err(_) => return -4,
242 };
243 let tok = match Tokenizer::new(&td) {
244 Ok(t) => t,
245 Err(_) => return -5,
246 };
247 r.words[1] = tok.vocab_size() as u32;
248 let ids: Vec<u32> = match tok.encode_chat(PROMPT) {
249 Ok(v) => v,
250 Err(_) => return -6,
251 };
252 if ids.len() < 4 {
253 return -7;
254 }
255 r.words[2..6].copy_from_slice(&ids[..4]);
256 r.words[6] = ids.len() as u32;
257 r.words[7] = model.params.block_count;
258 if ids.len() + MAX_NEW > KV_CAPACITY {
259 return -8;
260 }
261
262 // Same path as the host test (crates/aienos-infer/tests/forward.rs):
263 // DecodeState + prefill + argmax + forward(t, true), f32 activations.
264 let mut st = DecodeState::new(&model, KV_CAPACITY);
265 // SAFETY: ck_time_us is a plain C function with no arguments.
266 let t0 = unsafe { ck_time_us() };
267 if st.prefill(&model, &ids).is_err() {
268 return -9;
269 }
270 r.prefill_us = unsafe { ck_time_us() } - t0;
271 let mut n = 0usize;
272 loop {
273 let t = argmax(&st.logits);
274 r.tokens[n] = t;
275 n += 1;
276 if t == EOT || n == MAX_NEW {
277 break;
278 }
279 let t1 = unsafe { ck_time_us() };
280 if st.forward(&model, t, true).is_err() {
281 r.ntok = n as u32;
282 return -10;
283 }
284 r.tok_us[n] = unsafe { ck_time_us() } - t1;
285 }
286 r.ntok = n as u32;
287 let text = match tok.decode(&r.tokens[..n]) {
288 Ok(v) => v,
289 Err(_) => return -11,
290 };
291 let keep = text.len().min(TEXT_BYTES);
292 r.text[..keep].copy_from_slice(&text[..keep]);
293 r.text_len = keep as u32;
294 0
295 // st, tok, model, g drop here: nothing of the model outlives this call.
296}
297
298/// Parses the GGUF at `model[..len]`, binds the `Model`, tokenizes [`PROMPT`]
299/// with the chat template, runs prefill and greedy decode and fills `out`.
300/// Fields are only meaningful up to the stage that failed. Returns 0 on
301/// success, a negative code otherwise (see `run`).
302///
303/// # Safety
304/// `model` must point to `len` readable bytes and `out` to one writable
305/// `InferResult`. FP/SIMD must be enabled and interrupts masked (the kernel
306/// does not save FP state). `aienos_infer_heap_init` must have been called.
307#[no_mangle]
308pub unsafe extern "C" fn aienos_infer_run(
309 model: *const u8,
310 len: u64,
311 out: *mut InferResult,
312) -> i32 {
313 if model.is_null() || out.is_null() || len == 0 || len > usize::MAX as u64 {
314 return -1;
315 }
316 let bytes = slice::from_raw_parts(model, len as usize);
317 let r = &mut *out;
318 *r = InferResult {
319 words: [0; OUT_WORDS],
320 ntok: 0,
321 tokens: [0; MAX_NEW],
322 tok_us: [0; MAX_NEW],
323 prefill_us: 0,
324 text_len: 0,
325 text: [0; TEXT_BYTES],
326 };
327 let rc = run(bytes, r);
328 r.words[8] = (*HEAP.peak.get() / 1024) as u32;
329 rc
330}
331
332/// Record the CPU's dot product feature (`ck_cpu_features.dotprod`, decoded by
333/// the kernel from `ID_AA64ISAR0_EL1.DP`; native/kernel/core/cpufeat.c). Call
334/// before opening a model: new decode states take the SDOT int8-activation
335/// matvec path only when this is nonzero, otherwise the scalar f32 path runs
336/// unchanged. Nothing in this crate detects features itself.
337#[no_mangle]
338pub extern "C" fn aienos_infer_set_cpu_features(dotprod: u32) {
339 aienos_infer::set_cpu_dotprod(dotprod != 0);
340}
341
342/// 1 when a decode state created now would use the SDOT path, else 0.
343#[no_mangle]
344pub extern "C" fn aienos_infer_dot_path() -> u32 {
345 aienos_infer::cpu_dotprod().is_some() as u32
346}