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-serve-http / src / qwen38_engine.rs

388 lines · 15686 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//! Qwen3.8-27B behind the door (sc #642 serving): the whole model resident on AIEN's own Omega
17//! kernels (64 layers, fused FP8 projections, bf16 lm_head), prompts through omega's prefill,
18//! replies through the chip-proven decode graph, next turn resumed from the live state or the
19//! snapshot taken before the prompt's last turn header (`aien_inference_abi::qwen38_omega::
20//! Qwen38Session`).
21//!
22//! Chip etiquette as the 30B door ([`crate::omega_engine`]): `/tmp/aien-gb10.lock` is taken for
23//! the upload and around each generation, never while idle. Persistent KV parks
24//! (`AIEN_KV_STORE_DIR`) are not offered: they hold attention KV only, not the DeltaNet state.
25use std::path::{Path, PathBuf};
26use std::sync::Mutex;
27use std::time::{Duration, Instant};
28
29use aien_inference_abi::qwen38::Qwen38Config;
30use aien_inference_abi::qwen38_omega::{need_bytes, Qwen38Omega, Qwen38Session, Reuse};
31
32use crate::engine::{Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams};
33use crate::omega_engine::{GpuLock, GPU_LOCK_PATH};
34use crate::sampling::SamplingObserver;
35
36/// Model id the door answers to unless `--model-id` says otherwise.
37pub const DEFAULT_MODEL_ID: &str = "qwen3.8-27b-fp8";
38/// The same for the sparse sibling, Qwen3.6-35B-A3B (config model_type qwen3_5_moe, sc L306).
39pub const DEFAULT_MODEL_ID_MOE: &str = "qwen3.6-35b-a3b-fp8";
40/// Prefill chunk length (the 2026-10-18 TTFT receipts ran 4096).
41pub const PREFILL_CHUNK: usize = 4096;
42/// How long a request waits in the chip lock's queue before answering busy (the hive's chip
43/// jobs queue with `flock(1)` and run for seconds to minutes each).
44pub const REQUEST_LOCK_WAIT: Duration = Duration::from_secs(300);
45/// How long the upload waits for the chip lock (other jobs' chip runs take minutes; a request
46/// waits [`REQUEST_LOCK_WAIT`]).
47pub const LOAD_LOCK_WAIT: Duration = Duration::from_secs(1800);
48/// Memory kept free beyond [`need_bytes`] at load (other jobs share the box).
49pub const KEEP_FREE: u64 = 8 << 30;
50/// omega's switch for the 35B graph's a|b beside mix overlap (L356: ON unless set).
51pub const Q36_OVERLAP_AB_ENV: &str = "AIEN_OMEGA_Q36_OVERLAP_AB";
52/// 0: greedy replies read the logits and take the host argmax every token (L356: the chip's token otherwise).
53pub const CHIP_GREEDY_ENV: &str = "AIEN_SERVE_CHIP_GREEDY";
54
55fn model_type(dir: &Path) -> Option<String> {
56 crate::read_model_text(&dir.join("config.json"))
57 .ok()
58 .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
59 .and_then(|v| v["model_type"].as_str().map(str::to_owned))
60}
61
62/// `config.json` says `model_type: qwen3_5` (Qwen3.8-27B) or `qwen3_5_moe` (Qwen3.6-35B-A3B):
63/// the family this door serves.
64pub fn is_qwen38_dir(dir: &Path) -> bool {
65 matches!(model_type(dir).as_deref(), Some("qwen3_5" | "qwen3_5_moe"))
66}
67
68/// The sparse member (`qwen3_5_moe`).
69pub fn is_moe_dir(dir: &Path) -> bool {
70 model_type(dir).as_deref() == Some("qwen3_5_moe")
71}
72
73/// The model id a checkpoint answers to by default.
74pub fn default_model_id(dir: &Path) -> &'static str {
75 if is_moe_dir(dir) {
76 DEFAULT_MODEL_ID_MOE
77 } else {
78 DEFAULT_MODEL_ID
79 }
80}
81
82fn mem_available() -> u64 {
83 (crate::omega_engine::mem_available_gb() * (1u64 << 30) as f64) as u64
84}
85
86/// This process's resident set in bytes (0 when unreadable).
87pub fn rss_bytes() -> u64 {
88 std::fs::read_to_string("/proc/self/status")
89 .ok()
90 .and_then(|t| {
91 t.lines()
92 .find_map(|l| l.strip_prefix("VmRSS:"))
93 .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok())
94 })
95 .map_or(0, |kb| kb * 1024)
96}
97
98/// Takes the lock with `acquire`, and only then reads free memory with `mem_available` and checks
99/// it against `need` plus `keep` ([`KEEP_FREE`] here; the batch door's may be set). On a refusal
100/// the lock is released (dropped) before the error returns. The order is the point: a check made
101/// before a long lock wait is stale by the time the upload starts.
102pub(crate) fn admit_load<L>(
103 acquire: impl FnOnce() -> Result<L, String>,
104 mem_available: impl FnOnce() -> u64,
105 need: u64,
106 keep: u64,
107) -> Result<(L, u64), String> {
108 let lock = acquire()?;
109 let avail = mem_available();
110 if avail < need + keep {
111 return Err(format!(
112 "needs {} MiB plus {} MiB kept free ({} MiB in all), MemAvailable {} MiB after taking the GPU lock (another model may be loaded); refusing",
113 need >> 20,
114 keep >> 20,
115 (need + keep) >> 20,
116 avail >> 20
117 ));
118 }
119 Ok((lock, avail))
120}
121
122pub struct Qwen38Door {
123 session: Mutex<Qwen38Session>,
124 max_context: usize,
125 lock_path: PathBuf,
126 lock_wait: Duration,
127}
128
129impl Qwen38Door {
130 /// Uploads the checkpoint at `dir` with a KV cache for `max_context` positions (rounded up
131 /// to whole 256-position passes), under the GPU lock.
132 pub fn load(dir: &Path, max_context: usize) -> Result<Self, String> {
133 if !aien_omega_gpu::is_native() {
134 return Err("this binary carries the CPU stub of the Omega engine".into());
135 }
136 // The 35B runs prompts through its decode graph (no prefill entries needed).
137 if !is_moe_dir(dir) && !aien_omega_q38::has_prefill() {
138 return Err("this binary has no qwen38 prefill entries linked (build against omega qwen38/prefill-graph)".into());
139 }
140 let c = Qwen38Config::from_checkpoint(dir)?;
141 let max_pos = max_context.next_multiple_of(256);
142 let need = need_bytes(&c, max_pos, PREFILL_CHUNK);
143 // Memory is judged only once the lock is ours: the wait can last many minutes and free
144 // memory on a shared box swings by tens of GiB meanwhile (alpha test: 6 to 59 GiB).
145 let t_lock = Instant::now();
146 let (_lock, avail) = admit_load(
147 || GpuLock::acquire_queued_at(Path::new(GPU_LOCK_PATH), LOAD_LOCK_WAIT),
148 mem_available,
149 need,
150 KEEP_FREE,
151 )?;
152 eprintln!(
153 "aien-serve-http: qwen38: lock taken after {:.1} s, memory re-checked after the lock: MemAvailable {} MiB, needs {} MiB plus {} MiB kept free",
154 t_lock.elapsed().as_secs_f64(),
155 avail >> 20,
156 need >> 20,
157 KEEP_FREE >> 20
158 );
159 let t0 = Instant::now();
160 eprintln!(
161 "aien-serve-http: qwen38: uploading {} layers, KV {max_pos} positions (need {} MiB, MemAvailable {} MiB)",
162 c.layers,
163 need >> 20,
164 avail >> 20
165 );
166 if is_moe_dir(dir) && !aien_omega_q38::q36::is_native() {
167 return Err(
168 "this binary has no q36 decode graph linked (build against omega q36/serve)".into(),
169 );
170 }
171 // L356 (Drake 2026-10-21 02:25Z: the quick levers ON): the 35B graph runs each DeltaNet
172 // layer's a|b GEMV beside its mix GEMV (both only read xq and write their own buffers;
173 // the GDN step waits for both), values identical. An explicit AIEN_OMEGA_Q36_OVERLAP_AB
174 // (0 = the old serial order) wins; omega reads it once, at the first token.
175 if std::env::var_os(Q36_OVERLAP_AB_ENV).is_none() {
176 // Set during startup, before the engine or any worker thread reads the environment.
177 std::env::set_var(Q36_OVERLAP_AB_ENV, "1");
178 }
179 let model = Qwen38Omega::open(dir, None, max_pos)?;
180 eprintln!(
181 "aien-serve-http: qwen38: {Q36_OVERLAP_AB_ENV}={}",
182 std::env::var(Q36_OVERLAP_AB_ENV).unwrap_or_default()
183 );
184 eprintln!(
185 "aien-serve-http: qwen38 engine ready in {:.1} s: context {max_context} tokens, weights {:.2} GB resident, KV {:.2} GB, rss {:.2} GB, prefill chunk {PREFILL_CHUNK}, spin_us {:?}",
186 t0.elapsed().as_secs_f64(),
187 model.weight_bytes() as f64 / 1e9,
188 model.kv_bytes() as f64 / 1e9,
189 rss_bytes() as f64 / 1e9,
190 aien_omega_gpu::spin_us(),
191 );
192 Ok(Self {
193 session: Mutex::new(Qwen38Session::new(model, PREFILL_CHUNK)),
194 max_context,
195 lock_path: PathBuf::from(GPU_LOCK_PATH),
196 lock_wait: REQUEST_LOCK_WAIT,
197 })
198 }
199}
200
201impl Engine for Qwen38Door {
202 fn kind(&self) -> &str {
203 "omega-qwen38"
204 }
205
206 fn max_context_tokens(&self) -> usize {
207 self.max_context
208 }
209
210 fn generate(
211 &self,
212 prompt: &[u32],
213 p: &GenerateParams,
214 on_token: &mut dyn FnMut(u32) -> bool,
215 ) -> Result<GenerateOutcome, EngineError> {
216 if prompt.is_empty() {
217 return Err(EngineError::Failed("empty prompt".into()));
218 }
219 if prompt.len() >= self.max_context {
220 return Err(EngineError::PromptTooLong {
221 len: prompt.len(),
222 max: self.max_context,
223 });
224 }
225 let t_lock = Instant::now();
226 let lock = GpuLock::acquire_queued_at(&self.lock_path, self.lock_wait)
227 .map_err(EngineError::Busy)?;
228 let lock_wait_ms = t_lock.elapsed().as_millis();
229 let mut s = self
230 .session
231 .lock()
232 .map_err(|_| EngineError::Failed("qwen38 session poisoned".into()))?;
233 // Greedy requests take the exact two-pass head (the same tokens, the logits read back are
234 // -inf off its candidates); sampled ones need every logit.
235 s.model_mut().set_exact_head_on(p.temperature <= 0.001);
236 let t0 = Instant::now();
237 let (mut logits, fs) = s.start(prompt).map_err(EngineError::Failed)?;
238 let prefill_ms = t0.elapsed().as_millis() as u64;
239 let t1 = Instant::now();
240 let mut observer = SamplingObserver::new(p);
241 // L356: a greedy reply takes the decode graph's own token (argmax on the chip, the
242 // host rule) and skips the logits copy and host argmax per token. The first token comes
243 // from the prefill logits as before. AIEN_SERVE_CHIP_GREEDY=0: the host path throughout.
244 let chip_greedy =
245 observer.is_greedy() && std::env::var(CHIP_GREEDY_ENV).as_deref() != Ok("0");
246 let mut chip_next: Option<u32> = None;
247 let (mut emitted, mut chip_ns) = (0usize, 0u64);
248 let finish = loop {
249 if emitted >= p.max_new_tokens || prompt.len() + emitted >= self.max_context {
250 break FinishReason::Length;
251 }
252 let tok = match chip_next.take() {
253 Some(t) => {
254 observer.note_greedy();
255 t
256 }
257 None => observer.sample(&logits, emitted),
258 };
259 if p.stop_token_ids.contains(&tok) {
260 break FinishReason::Stop;
261 }
262 emitted += 1;
263 if !on_token(tok) {
264 break FinishReason::Cancelled;
265 }
266 // The last allowed token is not fed: nothing would read its logits.
267 if emitted >= p.max_new_tokens || prompt.len() + emitted >= self.max_context {
268 break FinishReason::Length;
269 }
270 if chip_greedy {
271 let (next, ns) = s.advance_greedy(tok).map_err(EngineError::Failed)?;
272 chip_next = Some(next);
273 chip_ns += ns;
274 } else {
275 let (next, ns) = s.advance(tok).map_err(EngineError::Failed)?;
276 logits = next;
277 chip_ns += ns;
278 }
279 };
280 let decode_ms = t1.elapsed().as_millis() as u64;
281 let steps = emitted.saturating_sub(1).max(1) as f64;
282 let reused = fs.reuse.map_or(0, Reuse::tokens);
283 drop(s);
284 drop(lock);
285 let pf = &fs.prefill;
286 eprintln!(
287 "aien-serve-http: qwen38: lock wait {lock_wait_ms} ms, prompt {} tok, reuse {:?} ({reused} tok), fed {} ({} stepped), prefill {prefill_ms} ms (gemm chip {} ms, gdn chip {} ms, attn chip {} ms, host {} ms, restore {} ms, snapshot {} ms), decode {emitted} tok in {decode_ms} ms, graph chip {:.1} ms/token, wall {:.1} ms/token, chip greedy {chip_greedy}",
288 prompt.len(),
289 fs.reuse.unwrap_or(Reuse::Cold),
290 fs.fed,
291 fs.stepped,
292 pf.gemm_chip_ns / 1_000_000,
293 pf.gdn_chip_ns / 1_000_000,
294 pf.attn_chip_ns / 1_000_000,
295 pf.host_ns / 1_000_000,
296 fs.restore_ns / 1_000_000,
297 fs.snapshot_ns / 1_000_000,
298 chip_ns as f64 / 1e6 / steps,
299 decode_ms as f64 / steps,
300 );
301 Ok(GenerateOutcome {
302 emitted_tokens: emitted,
303 finish,
304 prefill_ms,
305 decode_ms,
306 sampling: Some(observer.record()),
307 })
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use std::cell::RefCell;
315
316 struct Guard<'a>(&'a RefCell<Vec<&'static str>>);
317 impl Drop for Guard<'_> {
318 fn drop(&mut self) {
319 self.0.borrow_mut().push("release");
320 }
321 }
322
323 const NEED: u64 = 41_305 << 20;
324
325 #[test]
326 fn memory_is_read_after_the_lock_is_taken() {
327 let log = RefCell::new(Vec::new());
328 let r = admit_load(
329 || {
330 log.borrow_mut().push("lock");
331 Ok(Guard(&log))
332 },
333 || {
334 log.borrow_mut().push("memory");
335 NEED + KEEP_FREE
336 },
337 NEED,
338 KEEP_FREE,
339 );
340 let (g, avail) = r.expect("exactly need plus keep-free is enough");
341 assert_eq!(avail, NEED + KEEP_FREE);
342 assert_eq!(*log.borrow(), ["lock", "memory"]);
343 drop(g);
344 }
345
346 #[test]
347 fn low_memory_after_the_wait_refuses_and_releases_the_lock() {
348 // 59 GiB was free before the wait, 6 GiB after it: only the reading after the lock counts.
349 let log = RefCell::new(Vec::new());
350 let e = admit_load(
351 || Ok(Guard(&log)),
352 || {
353 log.borrow_mut().push("memory");
354 6 << 30
355 },
356 NEED,
357 KEEP_FREE,
358 )
359 .err()
360 .expect("6 GiB must be refused");
361 assert!(
362 e.contains("41305 MiB plus 8192 MiB kept free (49497 MiB in all)"),
363 "{e}"
364 );
365 assert!(
366 e.contains("MemAvailable 6144 MiB after taking the GPU lock"),
367 "{e}"
368 );
369 assert_eq!(*log.borrow(), ["memory", "release"]);
370 }
371
372 #[test]
373 fn one_byte_short_is_refused() {
374 let r = admit_load(|| Ok(()), || NEED + KEEP_FREE - 1, NEED, KEEP_FREE);
375 assert!(r.is_err());
376 }
377
378 #[test]
379 fn no_lock_means_memory_is_never_read() {
380 let r: Result<((), u64), String> = admit_load(
381 || Err("lock wait timed out".into()),
382 || panic!("memory must not be read without the lock"),
383 NEED,
384 KEEP_FREE,
385 );
386 assert_eq!(r.unwrap_err(), "lock wait timed out");
387 }
388}