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

399 lines · 13244 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//! Bounded inference session for the resident kernel (native v1 P06).
17//!
18//! The one-shot probe (`aienos_infer_run`) parses, prefills, decodes and
19//! drops everything inside one call with a fixed prompt. A resident product
20//! needs the same work split into steps the kernel drives: load the model
21//! once, accept an operator prompt, advance one token at a time so the
22//! kernel can look at the console between steps (cancellation), decode the
23//! result, unload. Every bound is a number the kernel configures
24//! ([`SessionLimits`]); nothing here loops without the kernel asking.
25//!
26//! One session at a time (single core, interrupts masked by the caller).
27//! Memory: the session's buffers come from the bump allocator the kernel
28//! gave this unit; the decode state is sized once at open and reused by
29//! every prompt (`DecodeState::reset`), so a prompt allocates only its id
30//! list and its decoded text. The allocator never reclaims old blocks, so a
31//! long run of prompts creeps upward; `heap_reserve` turns that creep into a
32//! refusal (`E_HEAP`) before any allocation can fail, and the kernel can
33//! read the creep (`aienos_infer_heap_stats`) and show it.
34
35use alloc::vec::Vec;
36use core::cell::UnsafeCell;
37use core::slice;
38
39use aienos_infer::{argmax, DecodeState, Gguf, Model, Tokenizer};
40
41use crate::{ck_time_us, heap_remaining, EOT};
42
43/// Limits the kernel sets at open. All are hard bounds, none is advisory.
44#[repr(C)]
45pub struct SessionLimits {
46 /// KV-cache positions: prompt tokens + generated tokens never exceed it.
47 pub kv_capacity: u32,
48 /// Generated tokens per prompt (EOT counts).
49 pub max_new: u32,
50 /// Prompt text bytes the session accepts.
51 pub max_prompt_bytes: u32,
52 /// Heap bytes that must still be free before a prompt is accepted.
53 pub heap_reserve: u32,
54}
55
56/// What open reports back.
57#[repr(C)]
58pub struct SessionInfo {
59 pub tensors: u32,
60 pub vocab: u32,
61 pub layers: u32,
62 pub heap_used_kib: u32,
63}
64
65/// Session error codes (negative). The one-shot probe's codes -1..-11 keep
66/// their meaning; these continue the list.
67pub const E_ARG: i32 = -1;
68pub const E_GGUF: i32 = -2;
69pub const E_MODEL: i32 = -3;
70pub const E_TOK_DATA: i32 = -4;
71pub const E_TOK_BUILD: i32 = -5;
72pub const E_ENCODE: i32 = -6;
73pub const E_TOO_LONG: i32 = -8;
74pub const E_FORWARD: i32 = -10;
75pub const E_DECODE: i32 = -11;
76pub const E_STATE: i32 = -12; /* no session / session already open / no prompt */
77pub const E_LIMITS: i32 = -13;
78pub const E_UTF8: i32 = -14;
79pub const E_HEAP: i32 = -15;
80pub const E_PROMPT_BYTES: i32 = -16;
81
82/// Step results (non-negative).
83pub const STEP_DONE: i32 = 0; /* nothing left: EOT or max_new reached, or no prompt */
84pub const STEP_PREFILL: i32 = 1; /* one prompt token fed, no token produced */
85pub const STEP_TOKEN: i32 = 2; /* one token produced, more may follow */
86pub const STEP_LAST: i32 = 3; /* one token produced and the reply is complete */
87
88/// The largest KV capacity a session may ask for (a bound on the cache
89/// allocation; 4096 positions of Llama-3.2-1B is about 256 MiB of f32 KV,
90/// which is the whole probe heap, so real limits sit far below).
91pub const KV_CAPACITY_MAX: u32 = 4096;
92
93struct Session {
94 model: Model<'static>,
95 tok: Tokenizer<'static>,
96 st: DecodeState,
97 limits: SessionLimits,
98 /// Prompt ids of the current request; `fed` of them are in the cache.
99 prompt: Vec<u32>,
100 fed: usize,
101 /// Tokens produced for the current request.
102 out: Vec<u32>,
103 done: bool,
104}
105
106struct Slot(UnsafeCell<Option<Session>>);
107// SAFETY: one core, interrupts masked by the caller (see the module doc).
108unsafe impl Sync for Slot {}
109static SLOT: Slot = Slot(UnsafeCell::new(None));
110
111fn slot() -> &'static mut Option<Session> {
112 // SAFETY: single-threaded by contract; no reference escapes a call.
113 unsafe { &mut *SLOT.0.get() }
114}
115
116/// Load the model at `model[..len]` and size the decode state for
117/// `limits`. Returns 0 and fills `info`, or a negative code. `E_STATE` when
118/// a session is already open.
119///
120/// # Safety
121/// `model` must point to `len` bytes that stay readable and unchanged until
122/// `aienos_infer_session_close`; `limits` and `info` must be valid. FP/SIMD
123/// enabled, interrupts masked, heap initialised (as for `aienos_infer_run`).
124#[no_mangle]
125pub unsafe extern "C" fn aienos_infer_session_open(
126 model: *const u8,
127 len: u64,
128 limits: *const SessionLimits,
129 info: *mut SessionInfo,
130) -> i32 {
131 if model.is_null() || limits.is_null() || info.is_null() || len == 0 || len > usize::MAX as u64
132 {
133 return E_ARG;
134 }
135 if slot().is_some() {
136 return E_STATE;
137 }
138 let l = SessionLimits {
139 kv_capacity: (*limits).kv_capacity,
140 max_new: (*limits).max_new,
141 max_prompt_bytes: (*limits).max_prompt_bytes,
142 heap_reserve: (*limits).heap_reserve,
143 };
144 if l.kv_capacity == 0
145 || l.kv_capacity > KV_CAPACITY_MAX
146 || l.max_new == 0
147 || l.max_new > l.kv_capacity
148 || l.max_prompt_bytes == 0
149 {
150 return E_LIMITS;
151 }
152 let bytes: &'static [u8] = slice::from_raw_parts(model, len as usize);
153 let g = match Gguf::parse(bytes) {
154 Ok(g) => g,
155 Err(_) => return E_GGUF,
156 };
157 let tensors = g.tensors().len() as u32;
158 let model = match Model::new(&g) {
159 Ok(m) => m,
160 Err(_) => return E_MODEL,
161 };
162 let td = match g.tokenizer() {
163 Ok(t) => t,
164 Err(_) => return E_TOK_DATA,
165 };
166 let tok = match Tokenizer::new(&td) {
167 Ok(t) => t,
168 Err(_) => return E_TOK_BUILD,
169 };
170 let st = DecodeState::new(&model, l.kv_capacity as usize);
171 (*info).tensors = tensors;
172 (*info).vocab = tok.vocab_size() as u32;
173 (*info).layers = model.params.block_count;
174 (*info).heap_used_kib = (crate::heap_used() / 1024) as u32;
175 *slot() = Some(Session {
176 model,
177 tok,
178 st,
179 limits: l,
180 prompt: Vec::new(),
181 fed: 0,
182 out: Vec::new(),
183 done: true,
184 });
185 0
186}
187
188/// Accept a new prompt (UTF-8 text of the user turn; the chat template is
189/// applied as in the probe). Forgets the previous request. Returns the
190/// prompt's token count, or a negative code: `E_PROMPT_BYTES` (over
191/// `max_prompt_bytes`), `E_HEAP` (less than `heap_reserve` free), `E_UTF8`,
192/// `E_ENCODE`, `E_TOO_LONG` (prompt + max_new would not fit the cache).
193/// Nothing is fed to the model here; the first steps do that.
194///
195/// # Safety
196/// `text` must point to `len` readable bytes. Same execution contract as open.
197#[no_mangle]
198pub unsafe extern "C" fn aienos_infer_session_prompt(text: *const u8, len: u32) -> i32 {
199 let s = match slot() {
200 Some(s) => s,
201 None => return E_STATE,
202 };
203 if text.is_null() && len != 0 {
204 return E_ARG;
205 }
206 if len > s.limits.max_prompt_bytes {
207 return E_PROMPT_BYTES;
208 }
209 if heap_remaining() < s.limits.heap_reserve as usize {
210 return E_HEAP;
211 }
212 let bytes = if len == 0 {
213 &[][..]
214 } else {
215 slice::from_raw_parts(text, len as usize)
216 };
217 let user = match core::str::from_utf8(bytes) {
218 Ok(u) => u,
219 Err(_) => return E_UTF8,
220 };
221 let ids = match s.tok.encode_chat(user) {
222 Ok(v) => v,
223 Err(_) => return E_ENCODE,
224 };
225 if ids.len() + s.limits.max_new as usize > s.limits.kv_capacity as usize {
226 return E_TOO_LONG;
227 }
228 s.st.reset();
229 s.prompt = ids;
230 s.fed = 0;
231 s.out = Vec::new();
232 s.done = false;
233 s.prompt.len() as i32
234}
235
236/// Advance the current request by one unit of work:
237/// `STEP_PREFILL` (one prompt token entered the cache), `STEP_TOKEN` (a
238/// token was produced into `*token` and its forward pass ran),
239/// `STEP_LAST` (a token was produced and the reply is complete: EOT or
240/// `max_new`), `STEP_DONE` (nothing left). `*us` receives the microseconds
241/// the step took. Negative: `E_STATE` (no session), `E_FORWARD`.
242///
243/// # Safety
244/// `token` and `us` must be valid or null. Same execution contract as open.
245#[no_mangle]
246pub unsafe extern "C" fn aienos_infer_session_step(token: *mut u32, us: *mut u64) -> i32 {
247 let s = match slot() {
248 Some(s) => s,
249 None => return E_STATE,
250 };
251 if s.done {
252 return STEP_DONE;
253 }
254 let t0 = ck_time_us();
255 let rc;
256 if s.fed < s.prompt.len() {
257 let id = s.prompt[s.fed];
258 let last = s.fed + 1 == s.prompt.len();
259 if s.st.forward(&s.model, id, last).is_err() {
260 s.done = true;
261 return E_FORWARD;
262 }
263 s.fed += 1;
264 rc = STEP_PREFILL;
265 } else {
266 let t = argmax(&s.st.logits);
267 s.out.push(t);
268 if !token.is_null() {
269 *token = t;
270 }
271 if t == EOT || s.out.len() >= s.limits.max_new as usize {
272 s.done = true;
273 rc = STEP_LAST;
274 } else {
275 if s.st.forward(&s.model, t, true).is_err() {
276 s.done = true;
277 return E_FORWARD;
278 }
279 rc = STEP_TOKEN;
280 }
281 }
282 if !us.is_null() {
283 *us = ck_time_us() - t0;
284 }
285 rc
286}
287
288/// Copy the token ids of the current request's prompt (chat template included) into `out[..cap]`.
289/// Returns the number of prompt ids (which may exceed `cap`; only `cap` are copied), 0 when no prompt
290/// is pending, or `E_STATE` without a session. The kernel uses the first four ids to check the chat
291/// template the tokenizer built (PI5-6 agent: restores the one-shot probe's expect_ids check).
292///
293/// # Safety
294/// `out` must point to `cap` writable u32s (or be null with `cap` 0). Same execution contract as open.
295#[no_mangle]
296pub unsafe extern "C" fn aienos_infer_session_prompt_ids(out: *mut u32, cap: u32) -> i32 {
297 let s = match slot() {
298 Some(s) => s,
299 None => return E_STATE,
300 };
301 if out.is_null() && cap != 0 {
302 return E_ARG;
303 }
304 let n = s.prompt.len().min(cap as usize);
305 if n > 0 {
306 core::ptr::copy_nonoverlapping(s.prompt.as_ptr(), out, n);
307 }
308 s.prompt.len() as i32
309}
310
311/// Abandon the current request: the cache is forgotten and no further step
312/// does work. Returns the number of tokens produced before the cancel, or
313/// `E_STATE` without a session. Idempotent.
314///
315/// # Safety
316/// Same execution contract as open.
317#[no_mangle]
318pub unsafe extern "C" fn aienos_infer_session_cancel() -> i32 {
319 let s = match slot() {
320 Some(s) => s,
321 None => return E_STATE,
322 };
323 let n = s.out.len() as i32;
324 s.st.reset();
325 s.prompt = Vec::new();
326 s.fed = 0;
327 s.out = Vec::new();
328 s.done = true;
329 n
330}
331
332/// Copy the tokens produced for the current request into `out[..cap]`.
333/// Returns the count produced so far (which may exceed `cap`; only `cap`
334/// are copied), or `E_STATE`.
335///
336/// # Safety
337/// `out` must point to `cap` writable u32s. Same execution contract as open.
338#[no_mangle]
339pub unsafe extern "C" fn aienos_infer_session_tokens(out: *mut u32, cap: u32) -> i32 {
340 let s = match slot() {
341 Some(s) => s,
342 None => return E_STATE,
343 };
344 let n = s.out.len().min(cap as usize);
345 if n > 0 {
346 core::ptr::copy_nonoverlapping(s.out.as_ptr(), out, n);
347 }
348 s.out.len() as i32
349}
350
351/// Decode `ids[..n]` to bytes into `out[..cap]` (truncated to `cap`).
352/// Returns the number of bytes written, or `E_STATE` / `E_DECODE`.
353///
354/// # Safety
355/// `ids` must point to `n` u32s and `out` to `cap` writable bytes.
356#[no_mangle]
357pub unsafe extern "C" fn aienos_infer_session_text(
358 ids: *const u32,
359 n: u32,
360 out: *mut u8,
361 cap: u32,
362) -> i32 {
363 let s = match slot() {
364 Some(s) => s,
365 None => return E_STATE,
366 };
367 if (ids.is_null() && n != 0) || (out.is_null() && cap != 0) {
368 return E_ARG;
369 }
370 let ids = if n == 0 {
371 &[][..]
372 } else {
373 slice::from_raw_parts(ids, n as usize)
374 };
375 let text = match s.tok.decode(ids) {
376 Ok(v) => v,
377 Err(_) => return E_DECODE,
378 };
379 let keep = text.len().min(cap as usize);
380 if keep > 0 {
381 core::ptr::copy_nonoverlapping(text.as_ptr(), out, keep);
382 }
383 keep as i32
384}
385
386/// Drop the session: model binding, tokenizer, cache, request. Returns 0,
387/// or `E_STATE` when none is open. The kernel then forgets the heap region
388/// and returns its frames, as after `aienos_infer_run`.
389///
390/// # Safety
391/// Same execution contract as open.
392#[no_mangle]
393pub unsafe extern "C" fn aienos_infer_session_close() -> i32 {
394 if slot().is_none() {
395 return E_STATE;
396 }
397 *slot() = None;
398 0
399}