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-serve-http / src / qwen36_batch.rs
| 1 | //! Qwen3.6-35B-A3B behind the door, many conversations at once (sc L354, the port of L129's |
| 2 | //! qwen38-batch scheduler to the 35B). |
| 3 | //! |
| 4 | //! [`Qwen38Door`](crate::qwen38_engine::Qwen38Door) serves one request at a time. This door keeps |
| 5 | //! `slots` conversation rows on the chip (each its own DeltaNet state, KV cache and position over |
| 6 | //! the one upload of the weights, `Qwen38Omega::add_rows`) and one scheduler thread that, every |
| 7 | //! beat, feeds one token of every live conversation through `Qwen38Omega::step_rows`: the token it |
| 8 | //! just sampled, or (while its prompt is still going in) its next prompt tokens. Requests join at |
| 9 | //! the next beat and leave when they stop, hit their length, or their client goes away; the others |
| 10 | //! never notice. Each row's tokens are bit for bit what that request gets alone (the step's |
| 11 | //! contract; the gate checks it, and a row-swap mutant must break it). |
| 12 | //! |
| 13 | //! Next turns: a row keeps the tokens it was fed after its conversation leaves. A new request |
| 14 | //! whose prompt starts with all of a free row's tokens continues that row (only the new tail is |
| 15 | //! fed); otherwise it takes the least recently used free row, emptied. |
| 16 | //! |
| 17 | //! `step_rows` (aien-inference-abi `qwen38_omega/rows.rs`) runs L312's strokes: a beat that feeds |
| 18 | //! two rows or more goes through one stroke graph in chunks of up to `MAX_HEADS` (8) rows, its head |
| 19 | //! slots re-pointed at each chunk's row states; by default (batch v2) every layer is recorded for |
| 20 | //! all heads at once, one weight read per layer, and the bf16 lm_head runs once per group of up to |
| 21 | //! 4 heads (`OMEGA_BF16_MAX_XBATCH`). A lone row, or a chunk of one, takes that row's own one-row |
| 22 | //! graph with the exact two-pass head (greedy rows; rows that read logits take the plain head). |
| 23 | //! `AIEN_Q36_STROKE_V2=0` keeps strokes on v1; `AIEN_Q36_STROKE=0` runs the rows' one-row graphs in |
| 24 | //! turn (stage 1). |
| 25 | //! |
| 26 | //! The server hands out `slots` permits ([`Engine::concurrency`]); the `slots + 1`th request gets |
| 27 | //! 503 `server_busy`. Chip etiquette: `/tmp/aien-gb10.lock` is taken when the first conversation |
| 28 | //! arrives and released when the last one leaves, never held while idle. |
| 29 | use std::path::{Path, PathBuf}; |
| 30 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 31 | use std::sync::{mpsc, Arc, Mutex}; |
| 32 | use std::time::{Duration, Instant}; |
| 33 | |
| 34 | use aien_inference_abi::qwen38::Qwen38Config; |
| 35 | use aien_inference_abi::qwen38_omega::{ |
| 36 | need_bytes, Qwen38Omega, Qwen38Snapshot, RowFeed, RowOut, RowTest, IM_START, |
| 37 | }; |
| 38 | |
| 39 | use crate::engine::{ |
| 40 | Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams, GroupJob, TestSwitches, |
| 41 | }; |
| 42 | use crate::omega_engine::{GpuLock, GPU_LOCK_PATH}; |
| 43 | use crate::qwen38_engine::{ |
| 44 | admit_load, is_moe_dir, rss_bytes, CHIP_GREEDY_ENV, KEEP_FREE, LOAD_LOCK_WAIT, PREFILL_CHUNK, |
| 45 | REQUEST_LOCK_WAIT, |
| 46 | }; |
| 47 | use crate::sampling::SamplingObserver; |
| 48 | |
| 49 | /// Most conversations one door stacks. |
| 50 | pub const MAX_SLOTS: usize = 64; |
| 51 | |
| 52 | /// Prompt tokens a joining row feeds per beat (`AIEN_Q36_PROMPT_PER_BEAT`, default 16): with the |
| 53 | /// rows run in turn this only moves chip time from the rows decoding to the one joining (its |
| 54 | /// time to first token), the total is the same. |
| 55 | pub const PROMPT_PER_BEAT: usize = 16; |
| 56 | |
| 57 | /// L369: prompt tokens per prefill chunk (the chip's most) and the fewest worth a chunk. |
| 58 | pub const Q36_PREFILL_CHUNK: usize = 128; |
| 59 | pub const Q36_PREFILL_MIN: usize = 16; |
| 60 | |
| 61 | fn env_usize(name: &str, default: usize) -> usize { |
| 62 | match std::env::var(name) { |
| 63 | Ok(v) => v.parse().unwrap_or_else(|_| { |
| 64 | eprintln!("aien-serve-http: {name}={v} is not a whole number, using {default}"); |
| 65 | default |
| 66 | }), |
| 67 | Err(_) => default, |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | fn prompt_per_beat() -> Result<usize, String> { |
| 72 | match std::env::var("AIEN_Q36_PROMPT_PER_BEAT") { |
| 73 | Ok(v) => match v.parse::<usize>() { |
| 74 | Ok(n) if n >= 1 => Ok(n), |
| 75 | _ => Err(format!("AIEN_Q36_PROMPT_PER_BEAT={v}: a whole number >= 1")), |
| 76 | }, |
| 77 | Err(_) => Ok(PROMPT_PER_BEAT), |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Memory kept free beyond the load at load time: [`KEEP_FREE`], or `AIEN_SERVE_KEEP_FREE_MIB` for a test server |
| 82 | /// loaded under q36-extra (L366: the kernel takes that one first on out of memory, never 18091). |
| 83 | fn keep_free() -> Result<u64, String> { |
| 84 | match std::env::var("AIEN_SERVE_KEEP_FREE_MIB") { |
| 85 | Ok(v) => v |
| 86 | .parse::<u64>() |
| 87 | .map(|m| m << 20) |
| 88 | .map_err(|_| format!("AIEN_SERVE_KEEP_FREE_MIB={v}: a whole number of MiB")), |
| 89 | Err(_) => Ok(KEEP_FREE), |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | fn mem_available() -> u64 { |
| 94 | (crate::omega_engine::mem_available_gb() * (1u64 << 30) as f64) as u64 |
| 95 | } |
| 96 | |
| 97 | /// The batch door's load admission: the GPU lock (`acquire`), then the free-memory rule (`need` |
| 98 | /// plus `keep`) read under it ([`admit_load`], the single door's rule), then the upload (`open`, |
| 99 | /// given the MemAvailable it was admitted on). The wait for the lock can last up to |
| 100 | /// [`LOAD_LOCK_WAIT`]; a reading taken before it would admit the upload on stale memory. |
| 101 | fn admit_then_open<L, M>( |
| 102 | acquire: impl FnOnce() -> Result<L, String>, |
| 103 | mem_available: impl FnOnce() -> u64, |
| 104 | need: u64, |
| 105 | keep: u64, |
| 106 | open: impl FnOnce(u64) -> Result<M, String>, |
| 107 | ) -> Result<(L, M), String> { |
| 108 | let (lock, avail) = admit_load(acquire, mem_available, need, keep)?; |
| 109 | let model = open(avail)?; |
| 110 | Ok((lock, model)) |
| 111 | } |
| 112 | |
| 113 | /// What the scheduler needs from the model: rows of conversation state and one step over a set |
| 114 | /// of them. `Qwen38Omega` (the chip) and the host tests' fake implement it. |
| 115 | pub trait RowStep: Send + 'static { |
| 116 | fn row_count(&self) -> usize; |
| 117 | /// Empties row `r` (position 0). |
| 118 | fn row_reset(&mut self, r: usize) -> Result<(), String>; |
| 119 | /// One token into each listed row; each row's greedy token and (when asked) logits. |
| 120 | fn step_rows(&mut self, feed: &[RowFeed]) -> Result<Vec<RowOut>, String>; |
| 121 | /// `step_rows` with the merge train's switches per row (`tests[i]` with `feed[i]`). The |
| 122 | /// default refuses a non-plain switch: a stepper that cannot apply it must say so, never |
| 123 | /// step as if it had. |
| 124 | fn step_rows_test( |
| 125 | &mut self, |
| 126 | feed: &[RowFeed], |
| 127 | tests: &[RowTest], |
| 128 | ) -> Result<Vec<RowOut>, String> { |
| 129 | if tests.iter().any(|t| !t.is_plain()) { |
| 130 | return Err("this row stepper has no test switches".into()); |
| 131 | } |
| 132 | self.step_rows(feed) |
| 133 | } |
| 134 | /// L369: a prompt chunk into row `r` in one call (the chip's prefill); the last token's greedy |
| 135 | /// token and (when asked) logits. The state must end as `tokens.len()` single steps leave it; |
| 136 | /// the default is exactly those steps. |
| 137 | fn prefill_row(&mut self, r: usize, tokens: &[u32], logits: bool) -> Result<RowOut, String> { |
| 138 | let mut last = None; |
| 139 | for (i, &token) in tokens.iter().enumerate() { |
| 140 | let feed = [RowFeed { |
| 141 | row: r, |
| 142 | token, |
| 143 | logits: logits && i + 1 == tokens.len(), |
| 144 | }]; |
| 145 | last = self.step_rows(&feed)?.pop(); |
| 146 | } |
| 147 | last.ok_or_else(|| "prefill_row: no tokens".to_string()) |
| 148 | } |
| 149 | /// A host copy of a row's state. |
| 150 | type Snap: Default + Send; |
| 151 | fn row_snapshot(&mut self, r: usize, snap: &mut Self::Snap) -> Result<(), String>; |
| 152 | /// Puts a copy back into row `r` (any row). |
| 153 | fn row_restore(&mut self, r: usize, snap: &Self::Snap) -> Result<(), String>; |
| 154 | } |
| 155 | |
| 156 | impl RowStep for Qwen38Omega { |
| 157 | fn row_count(&self) -> usize { |
| 158 | Qwen38Omega::row_count(self) |
| 159 | } |
| 160 | fn row_reset(&mut self, r: usize) -> Result<(), String> { |
| 161 | Qwen38Omega::row_reset(self, r) |
| 162 | } |
| 163 | fn step_rows(&mut self, feed: &[RowFeed]) -> Result<Vec<RowOut>, String> { |
| 164 | Qwen38Omega::step_rows(self, feed) |
| 165 | } |
| 166 | fn step_rows_test( |
| 167 | &mut self, |
| 168 | feed: &[RowFeed], |
| 169 | tests: &[RowTest], |
| 170 | ) -> Result<Vec<RowOut>, String> { |
| 171 | Qwen38Omega::step_rows_test(self, feed, tests) |
| 172 | } |
| 173 | fn prefill_row(&mut self, r: usize, tokens: &[u32], logits: bool) -> Result<RowOut, String> { |
| 174 | Qwen38Omega::prefill_row(self, r, tokens, logits) |
| 175 | } |
| 176 | type Snap = Qwen38Snapshot; |
| 177 | fn row_snapshot(&mut self, r: usize, snap: &mut Qwen38Snapshot) -> Result<(), String> { |
| 178 | Qwen38Omega::row_snapshot(self, r, snap) |
| 179 | } |
| 180 | fn row_restore(&mut self, r: usize, snap: &Qwen38Snapshot) -> Result<(), String> { |
| 181 | Qwen38Omega::row_restore(self, r, snap) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | /// A request handed to the scheduler. The channel carries a `Vec<Job>`: one request, or a group |
| 186 | /// ([`Engine::generate_group`]) that is seated all in the same beat. |
| 187 | struct Job { |
| 188 | prompt: Vec<u32>, |
| 189 | params: GenerateParams, |
| 190 | /// The job's events go out tagged with its place in its group (0 for a single request). |
| 191 | out: mpsc::SyncSender<(usize, Ev)>, |
| 192 | tag: usize, |
| 193 | /// Set by the request thread when `on_token` says stop (client gone, stop string). |
| 194 | cancel: Arc<AtomicBool>, |
| 195 | /// Set by the scheduler when this job's reader fell behind and an event was dropped: the |
| 196 | /// reply is incomplete whatever the job's last event says. |
| 197 | fell_behind: Arc<AtomicBool>, |
| 198 | t_queued: Instant, |
| 199 | /// The merge train's switches for this request (empty on the served path). |
| 200 | test: TestSwitches, |
| 201 | } |
| 202 | |
| 203 | /// The merge train's switches the batch door applies per request (`Engine::test_switches_honored`). |
| 204 | #[cfg(feature = "aien-test-switches")] |
| 205 | const TEST_SWITCHES_HONORED: &[&str] = &["stroke", "exact_head", "mutant", "row_swap"]; |
| 206 | |
| 207 | /// The per-step row switches of a request (`stroke`, `exact_head`, `mutant`). |
| 208 | fn row_test(t: &TestSwitches) -> RowTest { |
| 209 | RowTest { |
| 210 | stroke: t.stroke.unwrap_or(true), |
| 211 | exact_head: t.exact_head.unwrap_or(true), |
| 212 | mutant: t.mutant.unwrap_or(0), |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Events a request may leave unread before the scheduler drops it (per job of a group). |
| 217 | const EVENTS_PER_JOB: usize = 256; |
| 218 | |
| 219 | impl Job { |
| 220 | /// Never blocks: the scheduler is the only thread stepping every row and it holds the chip |
| 221 | /// lock for the whole spell. A request thread that stops taking events (a streaming client |
| 222 | /// that does not read blocks its `blocking_send`) fills the channel; the job is then cancelled, |
| 223 | /// so its row leaves at the next sample and the others go on. `Err` = not delivered. |
| 224 | fn send(&self, ev: Ev) -> Result<(), ()> { |
| 225 | match self.out.try_send((self.tag, ev)) { |
| 226 | Ok(()) => Ok(()), |
| 227 | Err(mpsc::TrySendError::Full(_)) => { |
| 228 | self.cancel.store(true, Ordering::SeqCst); |
| 229 | if !self.fell_behind.swap(true, Ordering::SeqCst) { |
| 230 | eprintln!( |
| 231 | "aien-serve-http: qwen36-batch: a reply's reader fell behind ({EVENTS_PER_JOB} events unread, job {} of its group, prompt {} tok): dropping it and freeing its row", |
| 232 | self.tag, |
| 233 | self.prompt.len() |
| 234 | ); |
| 235 | } |
| 236 | Err(()) |
| 237 | } |
| 238 | Err(mpsc::TrySendError::Disconnected(_)) => Err(()), |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// What a request whose reader fell behind ends with. |
| 244 | fn fell_behind_error() -> EngineError { |
| 245 | EngineError::Failed(format!( |
| 246 | "qwen36-batch: the reply's reader fell behind ({EVENTS_PER_JOB} events unread); its row was dropped" |
| 247 | )) |
| 248 | } |
| 249 | |
| 250 | /// The request side of [`Qwen36BatchDoor::run_jobs`]: relays every job's tokens to `on_token` |
| 251 | /// until each job has its outcome (or the scheduler let go of them all). |
| 252 | fn relay( |
| 253 | orx: &mpsc::Receiver<(usize, Ev)>, |
| 254 | cancel: &[Arc<AtomicBool>], |
| 255 | fell_behind: &[Arc<AtomicBool>], |
| 256 | on_token: &mut dyn FnMut(usize, u32) -> bool, |
| 257 | ) -> Vec<Result<GenerateOutcome, EngineError>> { |
| 258 | let n = cancel.len(); |
| 259 | let mut res: Vec<Option<Result<GenerateOutcome, EngineError>>> = vec![None; n]; |
| 260 | let mut delivered = vec![0usize; n]; |
| 261 | let mut cancelled = vec![false; n]; |
| 262 | let mut left = n; |
| 263 | while left > 0 { |
| 264 | let Ok((i, ev)) = orx.recv() else { |
| 265 | break; |
| 266 | }; |
| 267 | let r = match ev { |
| 268 | Ev::Token(t) => { |
| 269 | if !cancelled[i] { |
| 270 | delivered[i] += 1; |
| 271 | if !on_token(i, t) { |
| 272 | cancelled[i] = true; |
| 273 | cancel[i].store(true, Ordering::SeqCst); |
| 274 | } |
| 275 | } |
| 276 | continue; |
| 277 | } |
| 278 | // The scheduler dropped an event of this job: whatever its last event says (it can |
| 279 | // fit once the reader resumed), the reply the caller got is incomplete. |
| 280 | Ev::Done(_) if fell_behind[i].load(Ordering::SeqCst) => Err(fell_behind_error()), |
| 281 | Ev::Done(mut o) => { |
| 282 | if cancelled[i] { |
| 283 | o.finish = FinishReason::Cancelled; |
| 284 | o.emitted_tokens = delivered[i]; |
| 285 | } |
| 286 | Ok(o) |
| 287 | } |
| 288 | Ev::Busy(m) => Err(EngineError::Busy(m)), |
| 289 | Ev::Failed(m) => { |
| 290 | // A group fails whole: the others stop rather than read on for nothing. |
| 291 | for c in cancel { |
| 292 | c.store(true, Ordering::SeqCst); |
| 293 | } |
| 294 | Err(EngineError::Failed(m)) |
| 295 | } |
| 296 | }; |
| 297 | if res[i].is_none() { |
| 298 | left -= 1; |
| 299 | } |
| 300 | res[i] = Some(r); |
| 301 | } |
| 302 | res.into_iter() |
| 303 | .enumerate() |
| 304 | .map(|(i, r)| { |
| 305 | r.unwrap_or_else(|| { |
| 306 | // A job whose reader fell behind may have lost its last event too. |
| 307 | Err(if fell_behind[i].load(Ordering::SeqCst) { |
| 308 | fell_behind_error() |
| 309 | } else { |
| 310 | EngineError::Failed("qwen36-batch scheduler gone".into()) |
| 311 | }) |
| 312 | }) |
| 313 | }) |
| 314 | .collect() |
| 315 | } |
| 316 | |
| 317 | enum Ev { |
| 318 | Token(u32), |
| 319 | Done(GenerateOutcome), |
| 320 | Busy(String), |
| 321 | Failed(String), |
| 322 | } |
| 323 | |
| 324 | /// A row between conversations: the tokens its state holds and a host copy of its state at its |
| 325 | /// last prompt's last turn header (the single door's two reuse points, per row). |
| 326 | struct Row<T> { |
| 327 | history: Vec<u32>, |
| 328 | last_used: u64, |
| 329 | /// The tokens `snap` holds (empty: none). |
| 330 | snap_tokens: Vec<u32>, |
| 331 | snap: T, |
| 332 | } |
| 333 | |
| 334 | /// One conversation in flight on the scheduler thread. |
| 335 | struct Active { |
| 336 | job: Job, |
| 337 | row: usize, |
| 338 | /// Prompt tokens in the row's state (the reused ones included). |
| 339 | fed: usize, |
| 340 | reused: usize, |
| 341 | /// Where to copy the state on the way in: the prompt's last turn header (`<|im_start|>`). |
| 342 | snap_at: Option<usize>, |
| 343 | observer: SamplingObserver, |
| 344 | emitted: usize, |
| 345 | /// Logits after the last fed token, until sampled. |
| 346 | logits: Option<Vec<f32>>, |
| 347 | /// The sampled token to feed next. |
| 348 | next: Option<u32>, |
| 349 | /// A greedy reply takes the graph's own token (no logits copy per token, L356's single-door |
| 350 | /// lever); `chip_next` holds it until sampled. |
| 351 | chip_greedy: bool, |
| 352 | chip_next: Option<u32>, |
| 353 | t_admit: Instant, |
| 354 | prefill_ms: u64, |
| 355 | t_decode: Instant, |
| 356 | /// Beats this row decoded in and the rows that rode with it (for the mean batch size). |
| 357 | steps: u64, |
| 358 | rows_sum: u64, |
| 359 | /// The merge train's row swap still owed: at this decode step (from 1), at the first beat |
| 360 | /// from it on with another conversation decoding, the two trade rows (negative control). |
| 361 | swap_due: Option<u64>, |
| 362 | } |
| 363 | |
| 364 | impl Active { |
| 365 | fn prefilling(&self) -> bool { |
| 366 | self.fed < self.job.prompt.len() |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// The door: the server side of the scheduler thread. |
| 371 | pub struct Qwen36BatchDoor { |
| 372 | tx: Mutex<Option<mpsc::Sender<Vec<Job>>>>, |
| 373 | slots: usize, |
| 374 | max_context: usize, |
| 375 | /// Memory the rows took on the box, measured at load (`MemAvailable` before and after). |
| 376 | pub slot_bytes_measured: u64, |
| 377 | /// Memory one row takes on paper (`Qwen38Omega::row_bytes`). |
| 378 | pub slot_bytes_on_paper: usize, |
| 379 | } |
| 380 | |
| 381 | impl Qwen36BatchDoor { |
| 382 | /// Uploads the 35B checkpoint at `dir` once and makes `slots` conversation rows of |
| 383 | /// `max_context` positions each (rounded up to whole 256-position passes), under the GPU lock. |
| 384 | pub fn load(dir: &Path, max_context: usize, slots: usize) -> Result<Self, String> { |
| 385 | if !aien_omega_gpu::is_native() { |
| 386 | return Err("this binary carries the CPU stub of the Omega engine".into()); |
| 387 | } |
| 388 | if !is_moe_dir(dir) { |
| 389 | return Err("the batch door serves the Qwen3.6-35B-A3B (qwen3_5_moe) only".into()); |
| 390 | } |
| 391 | if !aien_omega_q38::q36::is_native() { |
| 392 | return Err( |
| 393 | "this binary has no q36 decode graph linked (build against omega q36/serve)".into(), |
| 394 | ); |
| 395 | } |
| 396 | if slots == 0 || slots > MAX_SLOTS { |
| 397 | return Err(format!("--batch-slots {slots}: 1..={MAX_SLOTS}")); |
| 398 | } |
| 399 | let per_beat = prompt_per_beat()?; |
| 400 | let c = Qwen38Config::from_checkpoint(dir)?; |
| 401 | let max_pos = max_context.next_multiple_of(256); |
| 402 | // The main graph is never stepped here: its own state is one 256-position pass. |
| 403 | let need = need_bytes(&c, 256, PREFILL_CHUNK); |
| 404 | let keep = keep_free()?; |
| 405 | let mut t0 = Instant::now(); |
| 406 | let (lock, mut model) = admit_then_open( |
| 407 | || GpuLock::acquire_queued_at(Path::new(GPU_LOCK_PATH), LOAD_LOCK_WAIT), |
| 408 | mem_available, |
| 409 | need, |
| 410 | keep, |
| 411 | |avail| { |
| 412 | t0 = Instant::now(); |
| 413 | eprintln!( |
| 414 | "aien-serve-http: qwen36-batch: uploading {} layers, {slots} rows of {max_pos} positions (model needs {} MiB, MemAvailable {} MiB)", |
| 415 | c.layers, |
| 416 | need >> 20, |
| 417 | avail >> 20 |
| 418 | ); |
| 419 | Qwen38Omega::open(dir, None, 256) |
| 420 | }, |
| 421 | )?; |
| 422 | let on_paper = model.row_bytes(max_pos); |
| 423 | let rows_need = on_paper as u64 * slots as u64; |
| 424 | let before = mem_available(); |
| 425 | if before < rows_need + keep { |
| 426 | return Err(format!( |
| 427 | "{slots} rows need {} MiB plus {} MiB kept free, MemAvailable {} MiB after the upload; refusing", |
| 428 | rows_need >> 20, |
| 429 | keep >> 20, |
| 430 | before >> 20 |
| 431 | )); |
| 432 | } |
| 433 | model.add_rows(slots, max_pos)?; |
| 434 | let after = mem_available(); |
| 435 | let measured = before.saturating_sub(after); |
| 436 | drop(lock); |
| 437 | eprintln!( |
| 438 | "aien-serve-http: qwen36-batch engine ready in {:.1} s: context {max_context} tokens, {slots} rows, weights {:.2} GB resident, per-row state {:.1} MiB on paper, {:.1} MiB measured (MemAvailable {} MiB -> {} MiB), rss {:.2} GB, prompt tokens per beat {per_beat}", |
| 439 | t0.elapsed().as_secs_f64(), |
| 440 | model.weight_bytes() as f64 / 1e9, |
| 441 | on_paper as f64 / (1u64 << 20) as f64, |
| 442 | measured as f64 / slots as f64 / (1u64 << 20) as f64, |
| 443 | before >> 20, |
| 444 | after >> 20, |
| 445 | rss_bytes() as f64 / 1e9, |
| 446 | ); |
| 447 | let mut door = Self::with_stepper( |
| 448 | model, |
| 449 | max_context, |
| 450 | PathBuf::from(GPU_LOCK_PATH), |
| 451 | REQUEST_LOCK_WAIT, |
| 452 | per_beat, |
| 453 | std::env::var(CHIP_GREEDY_ENV).as_deref() != Ok("0"), |
| 454 | )?; |
| 455 | door.slot_bytes_measured = measured; |
| 456 | door.slot_bytes_on_paper = on_paper; |
| 457 | Ok(door) |
| 458 | } |
| 459 | |
| 460 | /// The door over any [`RowStep`] (every row it has is a slot): the scheduler thread starts |
| 461 | /// here. `lock_path` is the chip lock (tests pass a private file). |
| 462 | pub fn with_stepper<S: RowStep>( |
| 463 | model: S, |
| 464 | max_context: usize, |
| 465 | lock_path: PathBuf, |
| 466 | lock_wait: Duration, |
| 467 | prompt_per_beat: usize, |
| 468 | chip_greedy: bool, |
| 469 | ) -> Result<Self, String> { |
| 470 | let slots = model.row_count(); |
| 471 | if slots == 0 { |
| 472 | return Err("qwen36-batch: no rows".into()); |
| 473 | } |
| 474 | let (tx, rx) = mpsc::channel::<Vec<Job>>(); |
| 475 | let sched = Scheduler { |
| 476 | model, |
| 477 | rows: (0..slots) |
| 478 | .map(|_| Row { |
| 479 | history: Vec::new(), |
| 480 | last_used: 0, |
| 481 | snap_tokens: Vec::new(), |
| 482 | snap: S::Snap::default(), |
| 483 | }) |
| 484 | .collect(), |
| 485 | free: (0..slots).rev().collect(), |
| 486 | waiting: None, |
| 487 | rx, |
| 488 | lock_path, |
| 489 | lock_wait, |
| 490 | max_context, |
| 491 | per_beat: prompt_per_beat.max(1), |
| 492 | pf_chunk: env_usize("AIEN_Q36_PREFILL_CHUNK", Q36_PREFILL_CHUNK).min(Q36_PREFILL_CHUNK), |
| 493 | pf_min: env_usize("AIEN_Q36_PREFILL_MIN", Q36_PREFILL_MIN).max(1), |
| 494 | chip_greedy, |
| 495 | beat: 0, |
| 496 | }; |
| 497 | std::thread::Builder::new() |
| 498 | .name("qwen36-batch".into()) |
| 499 | .spawn(move || sched.run()) |
| 500 | .map_err(|e| format!("scheduler thread: {e}"))?; |
| 501 | Ok(Self { |
| 502 | tx: Mutex::new(Some(tx)), |
| 503 | slots, |
| 504 | max_context, |
| 505 | slot_bytes_measured: 0, |
| 506 | slot_bytes_on_paper: 0, |
| 507 | }) |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | impl Engine for Qwen36BatchDoor { |
| 512 | fn kind(&self) -> &str { |
| 513 | "omega-qwen36-batch" |
| 514 | } |
| 515 | |
| 516 | fn max_context_tokens(&self) -> usize { |
| 517 | self.max_context |
| 518 | } |
| 519 | |
| 520 | fn concurrency(&self) -> usize { |
| 521 | self.slots |
| 522 | } |
| 523 | |
| 524 | fn generate( |
| 525 | &self, |
| 526 | prompt: &[u32], |
| 527 | p: &GenerateParams, |
| 528 | on_token: &mut dyn FnMut(u32) -> bool, |
| 529 | ) -> Result<GenerateOutcome, EngineError> { |
| 530 | self.generate_test(prompt, p, TestSwitches::default(), on_token) |
| 531 | } |
| 532 | |
| 533 | #[cfg(feature = "aien-test-switches")] |
| 534 | fn test_switches_honored(&self) -> &'static [&'static str] { |
| 535 | TEST_SWITCHES_HONORED |
| 536 | } |
| 537 | |
| 538 | #[cfg(feature = "aien-test-switches")] |
| 539 | fn generate_with_test( |
| 540 | &self, |
| 541 | prompt: &[u32], |
| 542 | p: &GenerateParams, |
| 543 | test: &TestSwitches, |
| 544 | on_token: &mut dyn FnMut(u32) -> bool, |
| 545 | ) -> Result<GenerateOutcome, EngineError> { |
| 546 | if let Some(bad) = test |
| 547 | .names() |
| 548 | .into_iter() |
| 549 | .find(|n| !TEST_SWITCHES_HONORED.contains(n)) |
| 550 | { |
| 551 | return Err(EngineError::Failed(format!( |
| 552 | "aien_test.{bad} is not a switch of the batch door (honored: {TEST_SWITCHES_HONORED:?})" |
| 553 | ))); |
| 554 | } |
| 555 | self.generate_test(prompt, p, test.clone(), on_token) |
| 556 | } |
| 557 | |
| 558 | fn generate_group( |
| 559 | &self, |
| 560 | jobs: &[GroupJob], |
| 561 | on_token: &mut dyn FnMut(usize, u32) -> bool, |
| 562 | ) -> Vec<Result<GenerateOutcome, EngineError>> { |
| 563 | self.run_jobs(jobs, on_token) |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | impl Qwen36BatchDoor { |
| 568 | /// The request path; `test` is empty on the served path (`Engine::generate`). |
| 569 | fn generate_test( |
| 570 | &self, |
| 571 | prompt: &[u32], |
| 572 | p: &GenerateParams, |
| 573 | test: TestSwitches, |
| 574 | on_token: &mut dyn FnMut(u32) -> bool, |
| 575 | ) -> Result<GenerateOutcome, EngineError> { |
| 576 | let job = GroupJob { |
| 577 | prompt: prompt.to_vec(), |
| 578 | params: p.clone(), |
| 579 | cancel: None, |
| 580 | test, |
| 581 | }; |
| 582 | self.run_jobs(std::slice::from_ref(&job), &mut |_, t| on_token(t)) |
| 583 | .pop() |
| 584 | .expect("one outcome per job") |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | impl Qwen36BatchDoor { |
| 589 | /// Hands `jobs` to the scheduler as one message (seated together, in the same beat) and |
| 590 | /// relays their tokens until every one is done. |
| 591 | fn run_jobs( |
| 592 | &self, |
| 593 | jobs: &[GroupJob], |
| 594 | on_token: &mut dyn FnMut(usize, u32) -> bool, |
| 595 | ) -> Vec<Result<GenerateOutcome, EngineError>> { |
| 596 | let n = jobs.len(); |
| 597 | if n == 0 { |
| 598 | return Vec::new(); |
| 599 | } |
| 600 | let mut res: Vec<Option<Result<GenerateOutcome, EngineError>>> = vec![None; n]; |
| 601 | for (i, j) in jobs.iter().enumerate() { |
| 602 | if j.prompt.is_empty() { |
| 603 | res[i] = Some(Err(EngineError::Failed("empty prompt".into()))); |
| 604 | } else if j.prompt.len() >= self.max_context { |
| 605 | res[i] = Some(Err(EngineError::PromptTooLong { |
| 606 | len: j.prompt.len(), |
| 607 | max: self.max_context, |
| 608 | })); |
| 609 | } |
| 610 | } |
| 611 | if n > self.slots { |
| 612 | let m = format!( |
| 613 | "a group of {n} needs {n} rows; this door has {}", |
| 614 | self.slots |
| 615 | ); |
| 616 | return vec![Err(EngineError::Failed(m)); n]; |
| 617 | } |
| 618 | if res.iter().any(Option::is_some) { |
| 619 | // A group goes in whole or not at all. |
| 620 | return res |
| 621 | .into_iter() |
| 622 | .map(|r| { |
| 623 | r.unwrap_or_else(|| { |
| 624 | Err(EngineError::Failed( |
| 625 | "another job of the group was refused".into(), |
| 626 | )) |
| 627 | }) |
| 628 | }) |
| 629 | .collect(); |
| 630 | } |
| 631 | let (otx, orx) = mpsc::sync_channel::<(usize, Ev)>(EVENTS_PER_JOB * n.max(1)); |
| 632 | let cancel: Vec<Arc<AtomicBool>> = jobs |
| 633 | .iter() |
| 634 | .map(|j| { |
| 635 | j.cancel |
| 636 | .clone() |
| 637 | .unwrap_or_else(|| Arc::new(AtomicBool::new(false))) |
| 638 | }) |
| 639 | .collect(); |
| 640 | let fell_behind: Vec<Arc<AtomicBool>> = |
| 641 | (0..n).map(|_| Arc::new(AtomicBool::new(false))).collect(); |
| 642 | let t_queued = Instant::now(); |
| 643 | let group: Vec<Job> = jobs |
| 644 | .iter() |
| 645 | .enumerate() |
| 646 | .map(|(i, j)| Job { |
| 647 | prompt: j.prompt.clone(), |
| 648 | params: j.params.clone(), |
| 649 | out: otx.clone(), |
| 650 | tag: i, |
| 651 | cancel: Arc::clone(&cancel[i]), |
| 652 | fell_behind: Arc::clone(&fell_behind[i]), |
| 653 | test: j.test.clone(), |
| 654 | t_queued, |
| 655 | }) |
| 656 | .collect(); |
| 657 | drop(otx); |
| 658 | let sent = match self.tx.lock() { |
| 659 | Err(_) => Err("qwen36-batch door poisoned"), |
| 660 | Ok(tx) => match tx.as_ref() { |
| 661 | None => Err("qwen36-batch scheduler stopped"), |
| 662 | Some(tx) => tx.send(group).map_err(|_| "qwen36-batch scheduler gone"), |
| 663 | }, |
| 664 | }; |
| 665 | if let Err(m) = sent { |
| 666 | return vec![Err(EngineError::Failed(m.into())); n]; |
| 667 | } |
| 668 | relay(&orx, &cancel, &fell_behind, on_token) |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | struct Scheduler<S: RowStep> { |
| 673 | model: S, |
| 674 | rows: Vec<Row<S::Snap>>, |
| 675 | free: Vec<usize>, |
| 676 | rx: mpsc::Receiver<Vec<Job>>, |
| 677 | /// A group that waits for enough free rows; nothing else joins before it. |
| 678 | waiting: Option<Vec<Job>>, |
| 679 | lock_path: PathBuf, |
| 680 | lock_wait: Duration, |
| 681 | max_context: usize, |
| 682 | per_beat: usize, |
| 683 | /// L369 prefill: prompt tokens per chunk (`AIEN_Q36_PREFILL_CHUNK`, 0 = off) and the fewest |
| 684 | /// left before a row reads a chunk instead of single tokens (`AIEN_Q36_PREFILL_MIN`). |
| 685 | pf_chunk: usize, |
| 686 | pf_min: usize, |
| 687 | /// Greedy replies take the graph's token (`AIEN_SERVE_CHIP_GREEDY=0` turns it off). |
| 688 | chip_greedy: bool, |
| 689 | beat: u64, |
| 690 | } |
| 691 | |
| 692 | /// Totals over one busy spell (first arrival to last departure). |
| 693 | #[derive(Default)] |
| 694 | struct Spell { |
| 695 | beats: u64, |
| 696 | steps: u64, |
| 697 | row_tokens: u64, |
| 698 | decode_tokens: u64, |
| 699 | wall_ns: u64, |
| 700 | chip_ns: u64, |
| 701 | } |
| 702 | |
| 703 | impl<S: RowStep> Scheduler<S> { |
| 704 | fn run(mut self) { |
| 705 | let mut active: Vec<Active> = Vec::new(); |
| 706 | let mut lock: Option<GpuLock> = None; |
| 707 | let (mut spell, mut spell_t0) = (Spell::default(), Instant::now()); |
| 708 | loop { |
| 709 | // Idle: wait for a request, then take the chip. |
| 710 | if active.is_empty() { |
| 711 | if lock.take().is_some() { |
| 712 | let s = &spell; |
| 713 | eprintln!( |
| 714 | "aien-serve-http: qwen36-batch: spell over: {} beats, {} steps, {} row tokens ({} decoded), {:.1} ms/step wall, chip {:.1} ms/step, spell {:.1} s", |
| 715 | s.beats, |
| 716 | s.steps, |
| 717 | s.row_tokens, |
| 718 | s.decode_tokens, |
| 719 | s.wall_ns as f64 / 1e6 / s.steps.max(1) as f64, |
| 720 | s.chip_ns as f64 / 1e6 / s.steps.max(1) as f64, |
| 721 | spell_t0.elapsed().as_secs_f64(), |
| 722 | ); |
| 723 | } |
| 724 | let Some(group) = self.waiting.take().or_else(|| self.rx.recv().ok()) else { |
| 725 | return; // the door is gone |
| 726 | }; |
| 727 | let t = Instant::now(); |
| 728 | match GpuLock::acquire_queued_at(&self.lock_path, self.lock_wait) { |
| 729 | Ok(l) => lock = Some(l), |
| 730 | Err(m) => { |
| 731 | for job in &group { |
| 732 | let _ = job.send(Ev::Busy(m.clone())); |
| 733 | } |
| 734 | continue; |
| 735 | } |
| 736 | } |
| 737 | eprintln!( |
| 738 | "aien-serve-http: qwen36-batch: chip lock after {} ms", |
| 739 | t.elapsed().as_millis() |
| 740 | ); |
| 741 | spell = Spell::default(); |
| 742 | spell_t0 = Instant::now(); |
| 743 | self.waiting = Some(group); |
| 744 | } |
| 745 | // Join: every waiting request or group that fits, in arrival order. A group joins whole, |
| 746 | // all its jobs in this beat; while it waits for rows nothing behind it joins. |
| 747 | loop { |
| 748 | let group = match self.waiting.take() { |
| 749 | Some(g) => g, |
| 750 | None => match self.rx.try_recv() { |
| 751 | Ok(g) => g, |
| 752 | Err(_) => break, |
| 753 | }, |
| 754 | }; |
| 755 | if group.len() > self.free.len() { |
| 756 | self.waiting = Some(group); |
| 757 | break; |
| 758 | } |
| 759 | for job in group { |
| 760 | self.admit(job, &mut active); |
| 761 | } |
| 762 | } |
| 763 | // Sample one token for every decoding row from its logits; leave on stop / length / |
| 764 | // cancel (a row still feeding its prompt leaves on cancel only). |
| 765 | let mut i = 0; |
| 766 | while i < active.len() { |
| 767 | let finish = if active[i].prefilling() { |
| 768 | active[i] |
| 769 | .job |
| 770 | .cancel |
| 771 | .load(Ordering::SeqCst) |
| 772 | .then_some(FinishReason::Cancelled) |
| 773 | } else { |
| 774 | Self::sample_one(&mut active[i], self.max_context) |
| 775 | }; |
| 776 | match finish { |
| 777 | Some(f) => { |
| 778 | let a = active.swap_remove(i); |
| 779 | self.finish(a, f, None); |
| 780 | } |
| 781 | None => i += 1, |
| 782 | } |
| 783 | } |
| 784 | if active.is_empty() { |
| 785 | continue; |
| 786 | } |
| 787 | self.beat += 1; |
| 788 | spell.beats += 1; |
| 789 | Self::row_swaps_due(&mut active, &mut self.rows); |
| 790 | // L369: a row with a long stretch of prompt left reads one chunk of it through the chip's |
| 791 | // prefill this beat (its state ends as token by token would leave it). A chunk stops at |
| 792 | // the row's snapshot point, so the copy at the last turn header is taken as before. |
| 793 | // A row with merge-train switches (L384) feeds its prompt token by token through |
| 794 | // `step_rows_test`, so every switch applies to every one of its steps. |
| 795 | let mut chunked = vec![false; active.len()]; |
| 796 | let mut pf_err: Option<String> = None; |
| 797 | if self.pf_chunk > 0 { |
| 798 | for (k, a) in active.iter_mut().enumerate() { |
| 799 | if !a.prefilling() |
| 800 | || a.snap_at == Some(a.fed) |
| 801 | || !row_test(&a.job.test).is_plain() |
| 802 | { |
| 803 | continue; |
| 804 | } |
| 805 | let plen = a.job.prompt.len(); |
| 806 | let stop = match a.snap_at { |
| 807 | Some(s) if s > a.fed => s, |
| 808 | _ => plen, |
| 809 | }; |
| 810 | let n = (stop - a.fed).min(self.pf_chunk); |
| 811 | if n < self.pf_min { |
| 812 | continue; |
| 813 | } |
| 814 | let (from, end) = (a.fed, a.fed + n); |
| 815 | let logits = end == plen; |
| 816 | let t = Instant::now(); |
| 817 | let r = self |
| 818 | .model |
| 819 | .prefill_row(a.row, &a.job.prompt[from..end], logits); |
| 820 | spell.wall_ns += t.elapsed().as_nanos() as u64; |
| 821 | spell.steps += 1; |
| 822 | spell.row_tokens += n as u64; |
| 823 | match r { |
| 824 | Ok(o) => { |
| 825 | spell.chip_ns += o.stats.chip_ns; |
| 826 | self.rows[a.row] |
| 827 | .history |
| 828 | .extend_from_slice(&a.job.prompt[from..end]); |
| 829 | a.fed = end; |
| 830 | if !a.prefilling() { |
| 831 | a.prefill_ms = a.t_admit.elapsed().as_millis() as u64; |
| 832 | a.t_decode = Instant::now(); |
| 833 | } |
| 834 | if logits { |
| 835 | a.logits = o.logits; |
| 836 | } |
| 837 | chunked[k] = true; |
| 838 | } |
| 839 | Err(e) => { |
| 840 | pf_err = Some(format!("prefill of row {} failed: {e}", a.row)); |
| 841 | break; |
| 842 | } |
| 843 | } |
| 844 | } |
| 845 | } |
| 846 | if let Some(e) = pf_err { |
| 847 | eprintln!("aien-serve-http: qwen36-batch: {e}"); |
| 848 | for a in active.drain(..) { |
| 849 | self.finish(a, FinishReason::Length, Some(e.clone())); |
| 850 | } |
| 851 | continue; |
| 852 | } |
| 853 | // One beat: every decoding row feeds its sampled token in the first step; the rows |
| 854 | // still feeding their prompt feed up to `per_beat` prompt tokens, one per step. |
| 855 | for sub in 0..self.per_beat { |
| 856 | // Each joining prompt's state copy at its last turn header, before that token goes in. |
| 857 | for a in active.iter_mut() { |
| 858 | if a.prefilling() && a.snap_at == Some(a.fed) { |
| 859 | a.snap_at = None; |
| 860 | let row = &mut self.rows[a.row]; |
| 861 | match self.model.row_snapshot(a.row, &mut row.snap) { |
| 862 | Ok(()) => row.snap_tokens = a.job.prompt[..a.fed].to_vec(), |
| 863 | Err(e) => { |
| 864 | row.snap_tokens.clear(); |
| 865 | eprintln!( |
| 866 | "aien-serve-http: qwen36-batch: row {} snapshot failed: {e}", |
| 867 | a.row |
| 868 | ); |
| 869 | } |
| 870 | } |
| 871 | } |
| 872 | } |
| 873 | let mut feed = Vec::with_capacity(active.len()); |
| 874 | let mut who = Vec::with_capacity(active.len()); |
| 875 | let mut tests = Vec::with_capacity(active.len()); |
| 876 | for (k, a) in active.iter().enumerate() { |
| 877 | if a.prefilling() && !chunked[k] { |
| 878 | let plen = a.job.prompt.len(); |
| 879 | feed.push(RowFeed { |
| 880 | row: a.row, |
| 881 | token: a.job.prompt[a.fed], |
| 882 | logits: a.fed + 1 == plen, |
| 883 | }); |
| 884 | who.push(k); |
| 885 | tests.push(row_test(&a.job.test)); |
| 886 | } else if sub == 0 && !a.prefilling() { |
| 887 | if let Some(t) = a.next { |
| 888 | feed.push(RowFeed { |
| 889 | row: a.row, |
| 890 | token: t, |
| 891 | logits: !a.chip_greedy, |
| 892 | }); |
| 893 | who.push(k); |
| 894 | tests.push(row_test(&a.job.test)); |
| 895 | } |
| 896 | } |
| 897 | } |
| 898 | if feed.is_empty() { |
| 899 | break; |
| 900 | } |
| 901 | let t = Instant::now(); |
| 902 | // The served path calls `step_rows` exactly as before; only a beat with a |
| 903 | // switched row goes through `step_rows_test`. |
| 904 | let r = if tests.iter().all(RowTest::is_plain) { |
| 905 | self.model.step_rows(&feed) |
| 906 | } else { |
| 907 | self.model.step_rows_test(&feed, &tests) |
| 908 | }; |
| 909 | spell.wall_ns += t.elapsed().as_nanos() as u64; |
| 910 | spell.steps += 1; |
| 911 | spell.row_tokens += feed.len() as u64; |
| 912 | let m = feed.len() as u64; |
| 913 | match r { |
| 914 | Ok(outs) if outs.len() == feed.len() => { |
| 915 | for ((f, &k), o) in feed.iter().zip(&who).zip(outs) { |
| 916 | spell.chip_ns += o.stats.chip_ns; |
| 917 | let a = &mut active[k]; |
| 918 | self.rows[a.row].history.push(f.token); |
| 919 | if a.prefilling() { |
| 920 | a.fed += 1; |
| 921 | if !a.prefilling() { |
| 922 | a.prefill_ms = a.t_admit.elapsed().as_millis() as u64; |
| 923 | a.t_decode = Instant::now(); |
| 924 | } |
| 925 | } else { |
| 926 | a.next = None; |
| 927 | if a.chip_greedy { |
| 928 | a.chip_next = Some(o.token); |
| 929 | } |
| 930 | a.steps += 1; |
| 931 | a.rows_sum += m; |
| 932 | spell.decode_tokens += 1; |
| 933 | } |
| 934 | if f.logits { |
| 935 | a.logits = o.logits; |
| 936 | } |
| 937 | } |
| 938 | } |
| 939 | r => { |
| 940 | let e = match r { |
| 941 | Err(e) => e, |
| 942 | Ok(o) => format!("step_rows gave {} rows for {}", o.len(), feed.len()), |
| 943 | }; |
| 944 | eprintln!("aien-serve-http: qwen36-batch: step over {m} rows failed: {e}"); |
| 945 | for a in active.drain(..) { |
| 946 | self.finish(a, FinishReason::Length, Some(e.clone())); |
| 947 | } |
| 948 | break; |
| 949 | } |
| 950 | } |
| 951 | } |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | /// Seats the request on a free row: the longest state some free row holds that the prompt |
| 956 | /// continues (its live tokens, or its copy at its last turn header), else the least recently |
| 957 | /// used row, emptied. The single door's reuse rule ([`aien_inference_abi::qwen38_omega::plan_reuse`]), per row. |
| 958 | fn admit(&mut self, job: Job, active: &mut Vec<Active>) { |
| 959 | let plen = job.prompt.len(); |
| 960 | let fits = |s: &[u32]| !s.is_empty() && s.len() < plen && job.prompt.starts_with(s); |
| 961 | // (index in `free`, tokens reused, from the copy) |
| 962 | let mut best: Option<(usize, usize, bool)> = None; |
| 963 | for (i, &r) in self.free.iter().enumerate() { |
| 964 | let row = &self.rows[r]; |
| 965 | for (s, from_snap) in [(&row.history, false), (&row.snap_tokens, true)] { |
| 966 | if fits(s) && best.is_none_or(|(_, n, _)| s.len() > n) { |
| 967 | best = Some((i, s.len(), from_snap)); |
| 968 | } |
| 969 | } |
| 970 | } |
| 971 | let (i, reused, from_snap) = best.unwrap_or_else(|| { |
| 972 | let i = (0..self.free.len()) |
| 973 | .min_by_key(|&i| self.rows[self.free[i]].last_used) |
| 974 | .expect("admit is called with a free row"); |
| 975 | (i, 0, false) |
| 976 | }); |
| 977 | let row = self.free.swap_remove(i); |
| 978 | let r = { |
| 979 | let rr = &mut self.rows[row]; |
| 980 | if from_snap { |
| 981 | self.model |
| 982 | .row_restore(row, &rr.snap) |
| 983 | .map(|()| rr.history = rr.snap_tokens.clone()) |
| 984 | } else if reused == 0 { |
| 985 | rr.history.clear(); |
| 986 | self.model.row_reset(row) |
| 987 | } else { |
| 988 | Ok(()) |
| 989 | } |
| 990 | }; |
| 991 | if let Err(e) = r { |
| 992 | eprintln!("aien-serve-http: qwen36-batch: row {row} reset/restore failed: {e}"); |
| 993 | let rr = &mut self.rows[row]; |
| 994 | rr.history.clear(); |
| 995 | rr.snap_tokens.clear(); |
| 996 | let _ = job.send(Ev::Failed(e)); |
| 997 | self.free.push(row); |
| 998 | return; |
| 999 | } |
| 1000 | let snap_at = job |
| 1001 | .prompt |
| 1002 | .iter() |
| 1003 | .rposition(|&t| t == IM_START) |
| 1004 | .filter(|&k| k > 0 && k >= reused && self.rows[row].snap_tokens[..] != job.prompt[..k]); |
| 1005 | eprintln!( |
| 1006 | "aien-serve-http: qwen36-batch: join: prompt {plen} tok, reuse {reused} tok ({}, row {row}), queued {} ms, now {} rows", |
| 1007 | if reused == 0 { "cold" } else if from_snap { "snapshot" } else { "live" }, |
| 1008 | job.t_queued.elapsed().as_millis(), |
| 1009 | active.len() + 1, |
| 1010 | ); |
| 1011 | let observer = SamplingObserver::new(&job.params); |
| 1012 | let job_swap = job.test.row_swap.filter(|&k| k >= 1); |
| 1013 | let chip_greedy = self.chip_greedy && observer.is_greedy(); |
| 1014 | active.push(Active { |
| 1015 | job, |
| 1016 | row, |
| 1017 | fed: reused, |
| 1018 | reused, |
| 1019 | snap_at, |
| 1020 | observer, |
| 1021 | emitted: 0, |
| 1022 | logits: None, |
| 1023 | next: None, |
| 1024 | chip_greedy, |
| 1025 | chip_next: None, |
| 1026 | t_admit: Instant::now(), |
| 1027 | prefill_ms: 0, |
| 1028 | t_decode: Instant::now(), |
| 1029 | steps: 0, |
| 1030 | rows_sum: 0, |
| 1031 | swap_due: job_swap, |
| 1032 | }); |
| 1033 | } |
| 1034 | |
| 1035 | /// The merge train's `row_swap: k` (negative control, per request): a conversation whose |
| 1036 | /// `k`th decode step is up trades rows with the first other conversation that is decoding, |
| 1037 | /// so both continue from each other's state; the per-row identity gate must go red for the |
| 1038 | /// two. Fires once per request; waits while it is the only one decoding. Both rows' kept |
| 1039 | /// tokens are forgotten (their states are no longer what their histories say). |
| 1040 | fn row_swaps_due(active: &mut [Active], rows: &mut [Row<S::Snap>]) { |
| 1041 | for i in 0..active.len() { |
| 1042 | let Some(k) = active[i].swap_due else { |
| 1043 | continue; |
| 1044 | }; |
| 1045 | if active[i].prefilling() || active[i].steps + 1 < k { |
| 1046 | continue; |
| 1047 | } |
| 1048 | let Some(j) = (0..active.len()).find(|&j| j != i && !active[j].prefilling()) else { |
| 1049 | continue; |
| 1050 | }; |
| 1051 | active[i].swap_due = None; |
| 1052 | let (ri, rj) = (active[i].row, active[j].row); |
| 1053 | active[i].row = rj; |
| 1054 | active[j].row = ri; |
| 1055 | for r in [ri, rj] { |
| 1056 | rows[r].history.clear(); |
| 1057 | rows[r].snap_tokens.clear(); |
| 1058 | } |
| 1059 | eprintln!( |
| 1060 | "aien-serve-http: qwen36-batch: TEST ROW SWAP (aien_test.row_swap {k}): rows {ri} and {rj} trade conversations (negative control; never serve this)" |
| 1061 | ); |
| 1062 | } |
| 1063 | } |
| 1064 | |
| 1065 | /// Samples the row's next token from its logits and emits it; `Some(reason)` when the row is |
| 1066 | /// done (the token is not fed). Mirrors the single door's loop exactly. |
| 1067 | fn sample_one(a: &mut Active, max_context: usize) -> Option<FinishReason> { |
| 1068 | let p = &a.job.params; |
| 1069 | let plen = a.job.prompt.len(); |
| 1070 | if a.job.cancel.load(Ordering::SeqCst) { |
| 1071 | return Some(FinishReason::Cancelled); |
| 1072 | } |
| 1073 | if a.chip_next.is_none() && a.logits.is_none() { |
| 1074 | return None; // its sampled token has not been fed yet |
| 1075 | } |
| 1076 | if a.emitted >= p.max_new_tokens || plen + a.emitted >= max_context { |
| 1077 | return Some(FinishReason::Length); |
| 1078 | } |
| 1079 | let tok = match (a.chip_next.take(), a.logits.take()) { |
| 1080 | (Some(t), _) => { |
| 1081 | a.observer.note_greedy(); |
| 1082 | t |
| 1083 | } |
| 1084 | (None, Some(logits)) => a.observer.sample(&logits, a.emitted), |
| 1085 | (None, None) => unreachable!("checked above"), |
| 1086 | }; |
| 1087 | if p.stop_token_ids.contains(&tok) { |
| 1088 | return Some(FinishReason::Stop); |
| 1089 | } |
| 1090 | // Counted only once delivered: a token dropped for a reader that fell behind never |
| 1091 | // reached the caller. |
| 1092 | if a.job.send(Ev::Token(tok)).is_err() { |
| 1093 | return Some(FinishReason::Cancelled); |
| 1094 | } |
| 1095 | a.emitted += 1; |
| 1096 | // The last allowed token is not fed: nothing would read its logits. |
| 1097 | if a.emitted >= p.max_new_tokens || plen + a.emitted >= max_context { |
| 1098 | return Some(FinishReason::Length); |
| 1099 | } |
| 1100 | a.next = Some(tok); |
| 1101 | None |
| 1102 | } |
| 1103 | |
| 1104 | fn finish(&mut self, a: Active, finish: FinishReason, err: Option<String>) { |
| 1105 | let decode_ms = if a.prefilling() { |
| 1106 | 0 |
| 1107 | } else { |
| 1108 | a.t_decode.elapsed().as_millis() as u64 |
| 1109 | }; |
| 1110 | let steps = a.steps.max(1) as f64; |
| 1111 | eprintln!( |
| 1112 | "aien-serve-http: qwen36-batch: leave: row {}, prompt {} tok (reused {}), prefill {} ms, decode {} tok in {decode_ms} ms over {} beats, mean rows {:.2}, wall {:.1} ms/token, {:?}", |
| 1113 | a.row, |
| 1114 | a.job.prompt.len(), |
| 1115 | a.reused, |
| 1116 | a.prefill_ms, |
| 1117 | a.emitted, |
| 1118 | a.steps, |
| 1119 | a.rows_sum as f64 / steps, |
| 1120 | decode_ms as f64 / steps, |
| 1121 | finish, |
| 1122 | ); |
| 1123 | let row = &mut self.rows[a.row]; |
| 1124 | row.last_used = self.beat; |
| 1125 | // The state is unknown after a failed step, and deliberately wrong after a negative |
| 1126 | // control (a mutant, or a traded row): no later request may reuse it, live or copied. |
| 1127 | if err.is_some() |
| 1128 | || a.job.test.mutant.is_some_and(|m| m != 0) |
| 1129 | || a.job.test.row_swap.is_some() |
| 1130 | { |
| 1131 | row.history.clear(); |
| 1132 | row.snap_tokens.clear(); |
| 1133 | } |
| 1134 | let ev = match err { |
| 1135 | Some(e) => Ev::Failed(e), |
| 1136 | None => Ev::Done(GenerateOutcome { |
| 1137 | emitted_tokens: a.emitted, |
| 1138 | finish, |
| 1139 | prefill_ms: a.prefill_ms, |
| 1140 | decode_ms, |
| 1141 | sampling: Some(a.observer.record()), |
| 1142 | }), |
| 1143 | }; |
| 1144 | let _ = a.job.send(ev); |
| 1145 | self.free.push(a.row); |
| 1146 | } |
| 1147 | } |
| 1148 | |
| 1149 | #[cfg(test)] |
| 1150 | mod tests; |