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
aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen38_omega / session.rs
| 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 | //! One conversation on the resident model (sc #642 serving): prompts fed through the prefill, |
| 17 | //! replies through the decode graph, and the next turn resumed from what the device holds. |
| 18 | //! |
| 19 | //! The DeltaNet layers carry a recurrent state that cannot be rewound, so a turn can only reuse |
| 20 | //! a state whose tokens are an exact prefix of the new prompt. Two such states are kept: |
| 21 | //! |
| 22 | //! - live: everything fed so far (the last prompt and the reply tokens fed back). It matches the |
| 23 | //! next prompt only when the client returns the reply byte for byte, thinking included. |
| 24 | //! - snapshot: the DeltaNet tails and states copied to host memory just before the prompt's last |
| 25 | //! `<|im_start|>` (the header of the turn being answered), or an earlier prefix chosen by Omega |
| 26 | //! to avoid additional 27B model passes. A short cold prompt may have no snapshot. The chat template renders every |
| 27 | //! earlier turn the same way on the next request, so the next prompt starts with these tokens |
| 28 | //! and only the new turns are fed. The attention KV needs no copy: the rows past the snapshot |
| 29 | //! are rewritten before anything reads them. |
| 30 | //! |
| 31 | //! The longer of the two that is a strict prefix of the prompt wins; otherwise the state is reset |
| 32 | //! and the whole prompt is fed (cold). |
| 33 | use std::time::Instant; |
| 34 | |
| 35 | use super::{PrefillStats, Qwen38Omega, Qwen38Snapshot}; |
| 36 | use aien_omega_q38 as q; |
| 37 | |
| 38 | /// `<|im_start|>` in the Qwen3.8 vocabulary (tokenizer.json added token 248045). |
| 39 | pub const IM_START: u32 = 248045; |
| 40 | |
| 41 | /// What the next prompt continues from. |
| 42 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 43 | pub enum Reuse { |
| 44 | /// Reset and feed the whole prompt. |
| 45 | Cold, |
| 46 | /// Continue the live state, which holds this many prompt tokens. |
| 47 | Live(usize), |
| 48 | /// Restore the snapshot, which holds this many prompt tokens. |
| 49 | Snapshot(usize), |
| 50 | } |
| 51 | |
| 52 | impl Reuse { |
| 53 | pub fn tokens(self) -> usize { |
| 54 | match self { |
| 55 | Self::Cold => 0, |
| 56 | Self::Live(n) | Self::Snapshot(n) => n, |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /// The longer of `live` and `snapshot` that is a strict prefix of `prompt` (at least one prompt |
| 62 | /// token must be fed: its logits give the first reply token). Live wins a tie (no copy). |
| 63 | pub fn plan_reuse(live: &[u32], snapshot: Option<&[u32]>, prompt: &[u32]) -> Reuse { |
| 64 | let fits = |s: &[u32]| !s.is_empty() && s.len() < prompt.len() && prompt.starts_with(s); |
| 65 | let live_n = if fits(live) { live.len() } else { 0 }; |
| 66 | let snap_n = snapshot.filter(|s| fits(s)).map_or(0, <[u32]>::len); |
| 67 | if live_n == 0 && snap_n == 0 { |
| 68 | Reuse::Cold |
| 69 | } else if live_n >= snap_n { |
| 70 | Reuse::Live(live_n) |
| 71 | } else { |
| 72 | Reuse::Snapshot(snap_n) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// What feeding one prompt cost. |
| 77 | #[derive(Debug, Clone, Default)] |
| 78 | pub struct FeedStats { |
| 79 | pub reuse: Option<Reuse>, |
| 80 | /// Prompt tokens fed this turn (prompt length minus the reused prefix). |
| 81 | pub fed: usize, |
| 82 | /// Of those, fed one at a time through the decode graph (pieces shorter than the prefill's |
| 83 | /// minimum). |
| 84 | pub stepped: usize, |
| 85 | pub prefill: PrefillStats, |
| 86 | pub restore_ns: u64, |
| 87 | pub snapshot_ns: u64, |
| 88 | pub wall_ns: u64, |
| 89 | } |
| 90 | |
| 91 | fn ns(t: Instant) -> u64 { |
| 92 | t.elapsed().as_nanos() as u64 |
| 93 | } |
| 94 | |
| 95 | fn add(sum: &mut PrefillStats, s: &PrefillStats) { |
| 96 | sum.tokens += s.tokens; |
| 97 | sum.chunks += s.chunks; |
| 98 | sum.wall_ns += s.wall_ns; |
| 99 | sum.gemm_chip_ns += s.gemm_chip_ns; |
| 100 | sum.gemm_call_ns += s.gemm_call_ns; |
| 101 | sum.gemm_launches += s.gemm_launches; |
| 102 | sum.ab_call_ns += s.ab_call_ns; |
| 103 | sum.gdn_chip_ns += s.gdn_chip_ns; |
| 104 | sum.gdn_call_ns += s.gdn_call_ns; |
| 105 | sum.attn_chip_ns += s.attn_chip_ns; |
| 106 | sum.attn_call_ns += s.attn_call_ns; |
| 107 | sum.host_ns += s.host_ns; |
| 108 | sum.head_ns += s.head_ns; |
| 109 | } |
| 110 | |
| 111 | /// The resident model plus the token record of its live state and of its snapshot. |
| 112 | #[derive(Debug)] |
| 113 | pub struct Qwen38Session { |
| 114 | model: Qwen38Omega, |
| 115 | chunk: usize, |
| 116 | /// Tokens the live state holds (`model.pos == history.len()` whenever this is trusted). |
| 117 | history: Vec<u32>, |
| 118 | snap: Qwen38Snapshot, |
| 119 | /// Tokens the snapshot holds; `None` until one is taken (or after a failed copy). |
| 120 | snap_tokens: Option<Vec<u32>>, |
| 121 | } |
| 122 | |
| 123 | impl Qwen38Session { |
| 124 | /// `chunk`: the prefill's chunk length (`6 ..= 32768`). |
| 125 | pub fn new(model: Qwen38Omega, chunk: usize) -> Self { |
| 126 | Self { |
| 127 | model, |
| 128 | chunk, |
| 129 | history: Vec::new(), |
| 130 | snap: Qwen38Snapshot::default(), |
| 131 | snap_tokens: None, |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | pub fn model(&self) -> &Qwen38Omega { |
| 136 | &self.model |
| 137 | } |
| 138 | |
| 139 | pub fn model_mut(&mut self) -> &mut Qwen38Omega { |
| 140 | &mut self.model |
| 141 | } |
| 142 | |
| 143 | /// Tokens the live state holds. |
| 144 | pub fn history(&self) -> &[u32] { |
| 145 | &self.history |
| 146 | } |
| 147 | |
| 148 | /// Tokens the snapshot holds. |
| 149 | pub fn snapshot_tokens(&self) -> Option<&[u32]> { |
| 150 | self.snap_tokens.as_deref() |
| 151 | } |
| 152 | |
| 153 | /// Positions the KV cache holds: prompt plus reply must stay below this. |
| 154 | pub fn max_pos(&self) -> usize { |
| 155 | self.model.max_pos() |
| 156 | } |
| 157 | |
| 158 | /// Drops both reuse candidates: the next prompt is fed cold. |
| 159 | pub fn forget(&mut self) { |
| 160 | self.history.clear(); |
| 161 | self.snap_tokens = None; |
| 162 | } |
| 163 | |
| 164 | /// Feeds `prompt` (reusing what [`plan_reuse`] allows) and returns the logits after its last |
| 165 | /// token. On error the live state is dropped. A snapshot is retained only while its attention prefix stays valid. |
| 166 | pub fn start(&mut self, prompt: &[u32]) -> Result<(Vec<f32>, FeedStats), String> { |
| 167 | let r = self.start_inner(prompt); |
| 168 | if r.is_err() { |
| 169 | self.history.clear(); |
| 170 | } |
| 171 | r |
| 172 | } |
| 173 | |
| 174 | fn start_inner(&mut self, prompt: &[u32]) -> Result<(Vec<f32>, FeedStats), String> { |
| 175 | let t0 = Instant::now(); |
| 176 | if prompt.is_empty() { |
| 177 | return Err("qwen38 session: empty prompt".into()); |
| 178 | } |
| 179 | if prompt.len() >= self.model.max_pos() { |
| 180 | return Err(format!( |
| 181 | "qwen38 session: prompt of {} tokens, the KV cache holds {}", |
| 182 | prompt.len(), |
| 183 | self.model.max_pos() |
| 184 | )); |
| 185 | } |
| 186 | let reuse = plan_reuse(&self.history, self.snap_tokens.as_deref(), prompt); |
| 187 | let mut st = FeedStats { |
| 188 | reuse: Some(reuse), |
| 189 | ..Default::default() |
| 190 | }; |
| 191 | match reuse { |
| 192 | Reuse::Live(_) => {} |
| 193 | Reuse::Snapshot(n) => { |
| 194 | let t = Instant::now(); |
| 195 | self.history.clear(); |
| 196 | self.model.restore(&self.snap)?; |
| 197 | self.history.extend_from_slice(&prompt[..n]); |
| 198 | st.restore_ns = ns(t); |
| 199 | } |
| 200 | Reuse::Cold => { |
| 201 | self.history.clear(); |
| 202 | // An unrelated prompt overwrites the attention KV prefix that the old snapshot needs. |
| 203 | self.snap_tokens = None; |
| 204 | self.model.reset()?; |
| 205 | } |
| 206 | } |
| 207 | let from = self.history.len(); |
| 208 | st.fed = prompt.len() - from; |
| 209 | // Preserve scalar pieces; otherwise keep a checkpoint without extra dense 27B passes. |
| 210 | // The 35B retains its existing scheduling; its prefill has a separate chunk policy. |
| 211 | let header = prompt |
| 212 | .iter() |
| 213 | .rposition(|&t| t == IM_START) |
| 214 | .filter(|&k| k >= from); |
| 215 | let cut = if self.model.is_moe() { |
| 216 | header |
| 217 | } else { |
| 218 | header |
| 219 | .map(|k| q::checkpoint_cut(from, k, prompt.len(), self.chunk)) |
| 220 | .transpose() |
| 221 | .map_err(|e| format!("qwen38 checkpoint: {e}"))? |
| 222 | .flatten() |
| 223 | }; |
| 224 | if let Some(k) = cut { |
| 225 | self.feed_rows(&prompt[from..k], &mut st)?; |
| 226 | if self.snap_tokens.as_deref() != Some(&prompt[..k]) && k > 0 { |
| 227 | let t = Instant::now(); |
| 228 | self.snap_tokens = None; |
| 229 | self.model.snapshot(&mut self.snap)?; |
| 230 | self.snap_tokens = Some(prompt[..k].to_vec()); |
| 231 | st.snapshot_ns = ns(t); |
| 232 | } |
| 233 | } |
| 234 | let rest = &prompt[self.history.len()..]; |
| 235 | let logits = self.feed_last(rest, &mut st)?; |
| 236 | st.wall_ns = ns(t0); |
| 237 | Ok((logits, st)) |
| 238 | } |
| 239 | |
| 240 | /// Feeds `tokens` without the head (the residual rows are dropped). |
| 241 | fn feed_rows(&mut self, tokens: &[u32], st: &mut FeedStats) -> Result<(), String> { |
| 242 | if tokens.len() >= q::GDN_PF_MIN_T { |
| 243 | let (_, s) = self.model.prefill_rows(tokens, self.chunk, false)?; |
| 244 | add(&mut st.prefill, &s); |
| 245 | } else { |
| 246 | for &t in tokens { |
| 247 | self.model.step(t)?; |
| 248 | } |
| 249 | st.stepped += tokens.len(); |
| 250 | } |
| 251 | self.history.extend_from_slice(tokens); |
| 252 | Ok(()) |
| 253 | } |
| 254 | |
| 255 | /// Feeds `tokens` (at least one) and returns the logits after the last. |
| 256 | fn feed_last(&mut self, tokens: &[u32], st: &mut FeedStats) -> Result<Vec<f32>, String> { |
| 257 | if tokens.is_empty() { |
| 258 | return Err("qwen38 session: nothing to feed".into()); |
| 259 | } |
| 260 | let logits = if tokens.len() >= q::GDN_PF_MIN_T { |
| 261 | let (_, logits, s) = self.model.prefill(tokens, self.chunk)?; |
| 262 | add(&mut st.prefill, &s); |
| 263 | logits |
| 264 | } else { |
| 265 | for &t in tokens { |
| 266 | self.model.step(t)?; |
| 267 | } |
| 268 | st.stepped += tokens.len(); |
| 269 | self.model.logits()? |
| 270 | }; |
| 271 | self.history.extend_from_slice(tokens); |
| 272 | Ok(logits) |
| 273 | } |
| 274 | |
| 275 | /// Feeds one reply token through the decode graph without reading the logits: the graph's |
| 276 | /// greedy token after it (chosen on the chip) and the step's chip time (ns). For greedy |
| 277 | /// replies (L356: no 1 MB logits copy and host argmax per token). |
| 278 | pub fn advance_greedy(&mut self, token: u32) -> Result<(u32, u64), String> { |
| 279 | match self.model.step(token) { |
| 280 | Ok((next, stats)) => { |
| 281 | self.history.push(token); |
| 282 | Ok((next, stats.chip_ns)) |
| 283 | } |
| 284 | Err(e) => { |
| 285 | self.history.clear(); |
| 286 | Err(e) |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// Feeds one reply token through the decode graph: the logits after it and the graph's |
| 292 | /// chip time for the step (ns). |
| 293 | pub fn advance(&mut self, token: u32) -> Result<(Vec<f32>, u64), String> { |
| 294 | let r = self.model.step(token).and_then(|(_, stats)| { |
| 295 | let logits = self.model.logits()?; |
| 296 | Ok((logits, stats.chip_ns)) |
| 297 | }); |
| 298 | match r { |
| 299 | Ok(v) => { |
| 300 | self.history.push(token); |
| 301 | Ok(v) |
| 302 | } |
| 303 | Err(e) => { |
| 304 | self.history.clear(); |
| 305 | Err(e) |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[cfg(test)] |
| 312 | mod tests { |
| 313 | use super::*; |
| 314 | |
| 315 | #[test] |
| 316 | fn reuse_takes_the_longest_strict_prefix() { |
| 317 | let p = [1, 2, 3, 4, 5, 6]; |
| 318 | assert_eq!(plan_reuse(&[], None, &p), Reuse::Cold); |
| 319 | assert_eq!(plan_reuse(&[1, 2, 3], None, &p), Reuse::Live(3)); |
| 320 | assert_eq!( |
| 321 | plan_reuse(&[1, 2], Some(&[1, 2, 3, 4]), &p), |
| 322 | Reuse::Snapshot(4) |
| 323 | ); |
| 324 | assert_eq!( |
| 325 | plan_reuse(&[1, 2, 3, 4, 5], Some(&[1, 2]), &p), |
| 326 | Reuse::Live(5) |
| 327 | ); |
| 328 | // Tie: live (no copy). |
| 329 | assert_eq!(plan_reuse(&[1, 2], Some(&[1, 2]), &p), Reuse::Live(2)); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn reuse_never_takes_a_whole_or_diverging_state() { |
| 334 | let p = [1, 2, 3]; |
| 335 | // Equal to the prompt: nothing left to feed, so not reusable. |
| 336 | assert_eq!(plan_reuse(&[1, 2, 3], None, &p), Reuse::Cold); |
| 337 | // Longer than the prompt, or diverging inside it. |
| 338 | assert_eq!(plan_reuse(&[1, 2, 3, 4], Some(&[1, 9]), &p), Reuse::Cold); |
| 339 | assert_eq!(plan_reuse(&[9], Some(&[1, 2, 3, 4]), &p), Reuse::Cold); |
| 340 | // A diverging live state does not hide a valid snapshot. |
| 341 | assert_eq!( |
| 342 | plan_reuse(&[1, 2, 9], Some(&[1, 2]), &p), |
| 343 | Reuse::Snapshot(2) |
| 344 | ); |
| 345 | } |
| 346 | } |