interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / generation.rs

551 lines · 20849 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//! The generation controller and the forward-pass seam (ADR 0004 sections 2.2 to 2.5).
17//!
18//! [`GenerationController`] owns the sequence ledger (history, and so the position), prefix
19//! reuse, rewind, KV export and restore, sampling, constraints, termination and streaming. It is
20//! written once and drives any model through [`ForwardPass`]. A forward pass owns its weights,
21//! its maths and its KV cache, and lends the controller only the model-independent half of the
22//! cache ([`KvStore`]).
23//!
24//! Step 2 of the ADR's migration: this module is pure addition. No production caller uses it
25//! yet; the 30B engine keeps its own loop until step 4. The host fake `generation::echo_chain` (feature
26//! `host-test-engine`) is the only forward pass so far.
27
28use std::sync::Mutex;
29use std::time::Instant;
30
31use crate::qwen3_moe_omega::{
32 sample_next, FinishReason, GenerateOutcome, GenerateParams, KvStore, StepTiming,
33};
34use crate::tensor::sample_argmax;
35
36#[cfg(any(test, feature = "host-test-engine"))]
37pub mod echo_chain;
38
39#[cfg(test)]
40pub(crate) mod tests;
41
42/// What the controller wants from a head.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Want {
45 /// The plain argmax: the model may answer with a token it already holds.
46 Greedy,
47 /// The full logits, always.
48 Logits,
49}
50
51/// One head's answer.
52#[derive(Debug, PartialEq)]
53pub enum Next<'a> {
54 /// The argmax the model already held (only for [`Want::Greedy`], under the
55 /// [`sample_argmax`] tie rule: lowest index of the maximum).
56 Token(u32),
57 /// `vocab()` logits.
58 Logits(&'a [f32]),
59}
60
61/// Every setting of a forward pass that can change a K/V byte, as named entries, plus its kind.
62/// Built by exhaustive destructuring inside the adapter (no `..`), so a new switch cannot be
63/// forgotten.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct KvIdentityInputs {
66 pub kind: &'static str,
67 pub entries: Vec<(&'static str, String)>,
68}
69
70/// One model implementation behind the seam (ADR 0004 section 2.2). Invariants I1 to I6 of the
71/// ADR hold for every adapter; the contract suite in this module's tests checks them.
72pub trait ForwardPass: Send {
73 /// "qwen3-moe-omega", "qwen3-dense-omega", "echo-chain".
74 fn kind(&self) -> &'static str;
75 fn vocab(&self) -> usize;
76 /// The cache, lent as its model-independent half. Safe to truncate, export and import
77 /// between forward calls; the model holds no pending state across them.
78 fn kv(&mut self) -> &mut dyn KvStore;
79 /// Draft tokens one `decode` call may verify at once. 1 until speculative decode lands.
80 fn max_decode_batch(&self) -> usize {
81 1
82 }
83 /// Prompt phase. Writes K/V for positions `pos..pos + tokens.len()` in every layer and
84 /// leaves ONE head (head 0, the last token). The model chooses its prefill strategy.
85 fn prefill(
86 &mut self,
87 pos: usize,
88 tokens: &[u32],
89 timing: &mut StepTiming,
90 ) -> Result<(), String>;
91 /// Generation phase. `1 <= tokens.len() <= max_decode_batch()`. Writes `tokens.len()`
92 /// positions and leaves that many heads; head `j` predicts the token after `tokens[j]`.
93 fn decode(&mut self, pos: usize, tokens: &[u32], timing: &mut StepTiming)
94 -> Result<(), String>;
95 /// Reads head `head` once. [`Want::Greedy`]: `Token` only if the model already holds the
96 /// argmax, else `Logits` (the controller then takes the argmax itself). [`Want::Logits`]:
97 /// always `Logits`. A host output head adds its own time to `timing`.
98 fn next(
99 &mut self,
100 head: usize,
101 want: Want,
102 timing: &mut StepTiming,
103 ) -> Result<Next<'_>, String>;
104 /// Sparse output head: the logits of head `head` for `rows` only, into
105 /// `out[..rows.len()]`. The default is [`gather_rows`] (read the full logits, then pick the
106 /// rows). Never called when no constraint is active.
107 fn next_rows(
108 &mut self,
109 head: usize,
110 rows: &[u32],
111 out: &mut [f32],
112 timing: &mut StepTiming,
113 ) -> Result<(), String> {
114 gather_rows(self, head, rows, out, timing)
115 }
116 /// Forgets every unread head. Called by the controller on rewind, a forced token, an error
117 /// and at the start of every generation.
118 fn clear_pending(&mut self);
119 /// The sequence starts over: forget heads and any per-sequence diagnostics. Called by the
120 /// controller's `reset` (and so by `restore_kv`).
121 fn begin_sequence(&mut self) {
122 self.clear_pending()
123 }
124 /// The K/V identity entries, or `Err(reason)` when K/V from this run must never be stored.
125 fn kv_identity(&self) -> Result<KvIdentityInputs, String>;
126 /// Migration only (ADR 0004 steps 3 and 4; step 5 deletes it): the controller shows the
127 /// model its ledger before every forward call, so a model that still keeps its own copy of
128 /// the history (the 30B's mirror) can take the tokens of a restore or import it did not see
129 /// (I1). Default: nothing.
130 fn mirror_ledger(&mut self, _history: &[u32]) {}
131}
132
133/// The default sparse output head: `next(head, Logits)`, then the rows gathered into
134/// `out[..rows.len()]`. Public so an adapter that instruments `next_rows` can still run it.
135pub fn gather_rows<M: ForwardPass + ?Sized>(
136 model: &mut M,
137 head: usize,
138 rows: &[u32],
139 out: &mut [f32],
140 timing: &mut StepTiming,
141) -> Result<(), String> {
142 if out.len() < rows.len() {
143 return Err(format!(
144 "next_rows: {} rows into a buffer of {}",
145 rows.len(),
146 out.len()
147 ));
148 }
149 match model.next(head, Want::Logits, timing)? {
150 Next::Logits(l) => {
151 for (o, &r) in out.iter_mut().zip(rows) {
152 *o = *l.get(r as usize).ok_or_else(|| {
153 format!(
154 "next_rows: row {r} is outside the vocabulary of {}",
155 l.len()
156 )
157 })?;
158 }
159 Ok(())
160 }
161 Next::Token(_) => Err("next_rows: the model answered Want::Logits with a token".into()),
162 }
163}
164
165/// Picks the next token from logits.
166pub trait Sampler {
167 /// `false`: the plain argmax; on an unconstrained step `pick` is never called and the chip's
168 /// own argmax may stand in. Under an `Allow` rule `pick` is always called, on the masked
169 /// buffer.
170 fn wants_logits(&self) -> bool;
171 fn pick(&mut self, logits: &[f32], step: usize) -> u32;
172}
173
174/// The door's sampling rule ([`sample_next`]) as a [`Sampler`]: what today's `generate`
175/// convenience runs. `wants_logits()` is `temperature > 0.001`, today's `argmax_sampler` flag
176/// inverted.
177#[derive(Debug, Clone)]
178pub struct SampleNext(pub GenerateParams);
179
180impl Sampler for SampleNext {
181 fn wants_logits(&self) -> bool {
182 self.0.temperature > 0.001
183 }
184 fn pick(&mut self, logits: &[f32], step: usize) -> u32 {
185 sample_next(logits, &self.0, step)
186 }
187}
188
189/// What a constraint allows at one decode step.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum StepRule {
192 /// No constraint this step: the unconstrained path, byte for byte.
193 Any,
194 /// The legal token ids (strictly ascending, non-empty); the sampler sees only these.
195 Allow(Vec<u32>),
196 /// Exactly one legal token: emitted without reading a head.
197 Force(u32),
198 /// The output is complete: stop with [`FinishReason::Constraint`].
199 Finish,
200}
201
202/// A per-step rule source applied between the head and the sampler (ADR 0004 section 2.3).
203pub trait Constraint {
204 /// Called once per step before the sampler, with the prompt and the tokens generated so far.
205 fn rule(&mut self, prompt: &[u32], generated: &[u32]) -> Result<StepRule, String>;
206}
207
208/// The one generation loop for every forward pass (ADR 0004 section 2.4). Between calls every
209/// layer of the model's cache holds exactly positions `0..position()`.
210pub struct GenerationController<M: ForwardPass> {
211 /// Owns the cache; declared first, drops first.
212 model: M,
213 /// Positions `0..history.len()` are stored in every layer.
214 history: Vec<u32>,
215 /// The cache's capacity, read once: the cache is fixed for the adapter's lifetime (I6).
216 capacity: usize,
217 /// Sparse-head output, `rows.len()` long; allocated on the first `Allow`.
218 rows_buf: Vec<f32>,
219 /// Vocab-sized, negative infinity except the allowed rows; allocated on the first `Allow`.
220 masked: Vec<f32>,
221}
222
223impl<M: ForwardPass> GenerationController<M> {
224 /// Takes the model with an empty sequence (its cache is emptied).
225 pub fn new(mut model: M) -> Self {
226 let capacity = model.kv().capacity();
227 let mut c = Self {
228 model,
229 history: Vec::new(),
230 capacity,
231 rows_buf: Vec::new(),
232 masked: Vec::new(),
233 };
234 c.reset();
235 c
236 }
237
238 pub fn max_context_tokens(&self) -> usize {
239 self.capacity
240 }
241
242 pub fn position(&self) -> usize {
243 self.history.len()
244 }
245
246 pub fn history(&self) -> &[u32] {
247 &self.history
248 }
249
250 /// Empties the sequence: the model begins a new one, the cache and the ledger are emptied.
251 pub fn reset(&mut self) {
252 self.model.begin_sequence();
253 self.model.kv().truncate(0);
254 self.history.clear();
255 }
256
257 /// Keeps positions `0..len` (forgets unread heads).
258 pub fn rewind(&mut self, len: usize) {
259 self.model.clear_pending();
260 self.model.kv().truncate(len);
261 self.history.truncate(len);
262 }
263
264 /// Tokens `generate` would keep from the stored history for `prompt`: the longest common
265 /// prefix, capped at `prompt.len() - 1` (the last prompt token is always prefilled).
266 pub fn reusable_prefix(&self, prompt: &[u32]) -> usize {
267 let common = self
268 .history
269 .iter()
270 .zip(prompt)
271 .take_while(|(a, b)| a == b)
272 .count();
273 common.min(prompt.len().saturating_sub(1))
274 }
275
276 /// The K/V of stored positions `start..start + len` as the `HostPagedPoolV1` payload
277 /// (`start` a multiple of the block size, `start + len <= position()`).
278 pub fn export_kv(&mut self, start: usize, len: usize) -> Result<Vec<u8>, String> {
279 if start + len > self.history.len() {
280 return Err(format!(
281 "kv export {start}+{len}: only {} positions stored",
282 self.history.len()
283 ));
284 }
285 let kv = self.model.kv();
286 kv.export_blocks(start, len).unwrap_or_else(|| {
287 Err(format!(
288 "the {} attention cache cannot export its KV",
289 kv.path_name()
290 ))
291 })
292 }
293
294 /// Replaces the sequence by `tokens` with the K/V of `payload` (positions from 0). On
295 /// success the next `generate` reuses them by the usual prefix rule. On any error the
296 /// sequence is reset (empty ledger, empty cache).
297 pub fn restore_kv(&mut self, tokens: &[u32], payload: &[u8]) -> Result<(), String> {
298 self.reset();
299 if tokens.is_empty() || tokens.len() >= self.capacity {
300 return Err(format!(
301 "kv restore of {} tokens, context is {}",
302 tokens.len(),
303 self.capacity
304 ));
305 }
306 let kv = self.model.kv();
307 let r = kv
308 .import_blocks(0, tokens.len(), payload)
309 .unwrap_or_else(|| {
310 Err(format!(
311 "the {} attention cache cannot import KV",
312 kv.path_name()
313 ))
314 });
315 match r {
316 Ok(()) => {
317 self.history = tokens.to_vec();
318 Ok(())
319 }
320 Err(e) => {
321 self.reset();
322 Err(e)
323 }
324 }
325 }
326
327 pub fn kv_identity(&self) -> Result<KvIdentityInputs, String> {
328 self.model.kv_identity()
329 }
330
331 /// Generates from `prompt`: prefix reuse, one prefill of the un-reused suffix, then one
332 /// token at a time. `on_token` sees each emitted token and may return `false` to cancel.
333 /// Stop ids are consumed, never emitted. With `constraint` `None` (or a constraint that
334 /// always answers [`StepRule::Any`]) this is today's loop, byte for byte.
335 pub fn generate(
336 &mut self,
337 prompt: &[u32],
338 params: &GenerateParams,
339 sampler: &mut dyn Sampler,
340 mut constraint: Option<&mut dyn Constraint>,
341 on_token: &mut dyn FnMut(u32) -> bool,
342 ) -> Result<GenerateOutcome, String> {
343 self.model.clear_pending();
344 if prompt.is_empty() {
345 return Err("empty prompt".into());
346 }
347 if prompt.len() >= self.capacity {
348 return Err(format!(
349 "prompt of {} tokens, context is {}",
350 prompt.len(),
351 self.capacity
352 ));
353 }
354 let reused = self.reusable_prefix(prompt);
355 if reused > 0 {
356 self.rewind(reused);
357 } else {
358 self.reset();
359 }
360 let t0 = Instant::now();
361 let mut prefill_timing = StepTiming::default();
362 let suffix = &prompt[reused..];
363 // I5: the whole un-reused suffix in one call; the model slices it as it must.
364 self.forward(suffix, |m, pos| m.prefill(pos, suffix, &mut prefill_timing))?;
365 let prefill_ms = t0.elapsed().as_millis() as u64;
366 let t1 = Instant::now();
367 let mut decode_timing = StepTiming::default();
368 let mut emitted = 0usize;
369 let mut finish = FinishReason::Length;
370 let mut step = 0usize;
371 while emitted < params.max_new_tokens {
372 let next = match self.choose(prompt, sampler, &mut constraint, step, &mut decode_timing)
373 {
374 Ok(Some(t)) => t,
375 Ok(None) => {
376 finish = FinishReason::Constraint;
377 break;
378 }
379 Err(e) => {
380 self.rollback();
381 return Err(e);
382 }
383 };
384 step += 1;
385 if params.stop_token_ids.contains(&next) {
386 // Consumed, never emitted, never stepped.
387 finish = FinishReason::Stop;
388 break;
389 }
390 emitted += 1;
391 if !on_token(next) {
392 // Emitted, not stepped.
393 finish = FinishReason::Cancelled;
394 break;
395 }
396 if emitted >= params.max_new_tokens || self.position() >= self.capacity {
397 break;
398 }
399 let tok = [next];
400 self.forward(&tok, |m, pos| m.decode(pos, &tok, &mut decode_timing))?;
401 }
402 Ok(GenerateOutcome {
403 emitted_tokens: emitted,
404 finish,
405 prefill_ms,
406 decode_ms: t1.elapsed().as_millis() as u64,
407 prompt_tokens: prompt.len(),
408 reused_prompt_tokens: reused,
409 decode_timing,
410 prefill_timing,
411 })
412 }
413
414 pub fn model(&self) -> &M {
415 &self.model
416 }
417
418 /// The side door (traces, mutants, switches). Anything that touches the cache through it
419 /// must be followed by [`Self::reset`].
420 pub fn model_mut(&mut self) -> &mut M {
421 &mut self.model
422 }
423
424 /// One step's token: `Some(t)` to emit (or stop on), `None` when a constraint finished.
425 fn choose(
426 &mut self,
427 prompt: &[u32],
428 sampler: &mut dyn Sampler,
429 constraint: &mut Option<&mut dyn Constraint>,
430 step: usize,
431 timing: &mut StepTiming,
432 ) -> Result<Option<u32>, String> {
433 let rule = match constraint.as_deref_mut() {
434 Some(c) => c.rule(prompt, &self.history[prompt.len()..])?,
435 None => StepRule::Any,
436 };
437 let vocab = self.model.vocab();
438 Ok(Some(match rule {
439 StepRule::Finish => return Ok(None),
440 StepRule::Force(t) => {
441 if t as usize >= vocab {
442 return Err(format!(
443 "constraint forced token {t}, vocabulary is {vocab}"
444 ));
445 }
446 self.model.clear_pending();
447 t
448 }
449 StepRule::Allow(rows) => {
450 check_allowed(&rows, vocab)?;
451 self.rows_buf.resize(rows.len(), 0.0);
452 self.model.next_rows(0, &rows, &mut self.rows_buf, timing)?;
453 // The constrained argmax is the argmax over the allowed set: never the chip's.
454 self.masked.clear();
455 self.masked.resize(vocab, f32::NEG_INFINITY);
456 for (&r, &v) in rows.iter().zip(&self.rows_buf) {
457 self.masked[r as usize] = v;
458 }
459 let t = sampler.pick(&self.masked, step);
460 // All-negative-infinity or NaN logits make an argmax fall back to token 0;
461 // whatever the sampler did, a token outside the set never leaves this step.
462 if rows.binary_search(&t).is_err() {
463 return Err(format!(
464 "the sampler picked token {t}, outside the {} allowed",
465 rows.len()
466 ));
467 }
468 t
469 }
470 StepRule::Any => {
471 let wants = sampler.wants_logits();
472 let want = if wants { Want::Logits } else { Want::Greedy };
473 match self.model.next(0, want, timing)? {
474 Next::Token(t) if !wants => t,
475 Next::Token(_) => {
476 return Err("the model answered Want::Logits with a token".into())
477 }
478 Next::Logits(l) if wants => sampler.pick(l, step),
479 // Today's host path: the plain argmax over the host lm_head.
480 Next::Logits(l) => sample_argmax(l).0,
481 }
482 }
483 }))
484 }
485
486 /// Runs one forward call at the ledger's position. On `Ok` the ledger takes `tokens`; on
487 /// `Err` the cache is cut back to the ledger (I3) and every head is forgotten.
488 fn forward(
489 &mut self,
490 tokens: &[u32],
491 f: impl FnOnce(&mut M, usize) -> Result<(), String>,
492 ) -> Result<(), String> {
493 let pos = self.history.len();
494 self.model.mirror_ledger(&self.history);
495 match f(&mut self.model, pos) {
496 Ok(()) => {
497 self.history.extend_from_slice(tokens);
498 Ok(())
499 }
500 Err(e) => {
501 self.rollback();
502 Err(e)
503 }
504 }
505 }
506
507 /// Every layer back to exactly `0..position()`, no unread head.
508 fn rollback(&mut self) {
509 let n = self.history.len();
510 self.model.kv().truncate(n);
511 self.model.clear_pending();
512 }
513}
514
515/// An `Allow` set must be non-empty, strictly ascending and inside the vocabulary.
516fn check_allowed(rows: &[u32], vocab: usize) -> Result<(), String> {
517 if rows.is_empty() {
518 return Err("constraint allowed no token".into());
519 }
520 if rows.windows(2).any(|w| w[0] >= w[1]) {
521 return Err("constraint's allowed tokens are not strictly ascending".into());
522 }
523 if let Some(&r) = rows.iter().find(|&&r| r as usize >= vocab) {
524 return Err(format!(
525 "constraint allowed token {r}, vocabulary is {vocab}"
526 ));
527 }
528 Ok(())
529}
530
531/// One generation at a time behind one lock (today's `OmegaEngine`). `Send + Sync`.
532pub struct Locked<M: ForwardPass>(Mutex<GenerationController<M>>);
533
534impl<M: ForwardPass> Locked<M> {
535 pub fn new(controller: GenerationController<M>) -> Self {
536 Self(Mutex::new(controller))
537 }
538
539 /// Runs `f` on the controller under the lock. Model-only calls go through
540 /// `controller.model()` / `model_mut()`.
541 pub fn with_controller<R>(
542 &self,
543 f: impl FnOnce(&mut GenerationController<M>) -> R,
544 ) -> Result<R, String> {
545 let mut g = self
546 .0
547 .lock()
548 .map_err(|_| "generation controller lock poisoned".to_string())?;
549 Ok(f(&mut g))
550 }
551}