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 / qwen38_omega / prefill.rs

813 lines · 30996 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//! Whole-prompt prefill for Qwen3.8-27B on omega's own prefill kernels (sc #642 step 9).
17//!
18//! The prompt goes through the model in chunks of at most `chunk` tokens; every layer of a chunk
19//! costs a fixed number of chip calls, whatever the chunk length. The DeltaNet tails and states
20//! and the KV cache end exactly where the decode graph ([`Qwen38Omega::step`]) continues.
21//!
22//! Per layer of a chunk of `m` tokens:
23//!
24//! | step | where |
25//! |---|---|
26//! | input RMSNorm (zero-centred, weights folded to `1 + w`) | host |
27//! | quantise x (f32, k 5120) | chip, `omega_gpu_pf_quant` |
28//! | mixer projection, one FP8 GEMM: qkv \| z (DeltaNet) or q \| gate \| k \| v (attention) | chip, `omega_gpu_pf_qgemm` |
29//! | DeltaNet: a \| b, bf16 `[m][5120] x [5120][96]` | chip, `omega_gpu_matmul_resident_f32` |
30//! | DeltaNet: conv, delta rule and gated norm for all `m` tokens | chip, `omega_gpu_gdn_prefill` |
31//! | attention: rows gathered to the kernel's layout ([`aien_omega_q38::gather_table`]) | host |
32//! | attention: q/k norm, RoPE, KV append, causal attention | chip, `omega_gpu_prefill_attn256` |
33//! | attention: output gate, `* sigmoid(gate)` | host |
34//! | quantise the mixer output (f32, k 6144), o_proj FP8 GEMM | chip |
35//! | residual add, post-attention RMSNorm | host |
36//! | quantise, gate \| up FP8 GEMM with the SwiGLU epilogue (bf16 act rows) | chip |
37//! | quantise act (bf16, k 17408), down FP8 GEMM | chip |
38//! | residual add | host |
39//!
40//! After the last chunk: the last token's final norm, the bf16 lm_head GEMV and a host argmax
41//! give the first generated token.
42//!
43//! This first cut moves every mixer input and output through host memory: the GEMM outputs land
44//! in GPU-uncached HOST buffers (nvos.h:1117 rule, as in the OWN-30B driver) and the omega host
45//! entries copy through their own staging. The device-pointer entries are the speed follow-up.
46use std::time::Instant;
47
48use aien_omega_fp8::Fp8Tensor;
49use aien_omega_pf::{
50 build_tiles, Layout, PfBuffer, PfMem, PrefillDevice, QgemmCall, QuantIn, ScopedPfDevice, BLOCK,
51 TILE_BYTES,
52};
53use aien_omega_q38 as q;
54use rayon::prelude::*;
55
56use super::{dense_shape, gpu, Graph, Qwen38Omega, EPS_L2};
57use crate::qwen3_moe::bf16_to_f32;
58use crate::tensor::rmsnorm;
59
60/// What one [`Qwen38Omega::prefill`] call cost. Chip times are the omega info records' launch
61/// times; call times are whole calls including omega's host copies.
62#[derive(Debug, Clone, Default, PartialEq, Eq)]
63pub struct PrefillStats {
64 pub tokens: usize,
65 pub chunks: usize,
66 /// The whole call: for a fresh sequence, the time to first token.
67 pub wall_ns: u64,
68 /// Quantisers and FP8 GEMMs: chip time, wall time of their calls, launches.
69 pub gemm_chip_ns: u64,
70 pub gemm_call_ns: u64,
71 pub gemm_launches: u64,
72 /// DeltaNet a|b resident bf16 matmul (wall time of the calls).
73 pub ab_call_ns: u64,
74 /// DeltaNet prefill calls.
75 pub gdn_chip_ns: u64,
76 pub gdn_call_ns: u64,
77 /// Attention prefill calls.
78 pub attn_chip_ns: u64,
79 pub attn_call_ns: u64,
80 /// Host work: embedding, norms, residual adds, copies out of the HOST buffers, row splits,
81 /// gathers and the output gate.
82 pub host_ns: u64,
83 /// Final norm, lm_head and argmax.
84 pub head_ns: u64,
85}
86
87/// The prefill's buffers for chunks of up to `m` tokens (sizes in the field comments).
88pub(super) struct PfState {
89 dev: ScopedPfDevice,
90 m: usize,
91 bm: usize,
92 max_tiles: usize,
93 padded_rows: usize,
94 /// HOST f32 `[m][max(mixer_out, hidden)]` (6144 for the 27B): quantiser input (normed x,
95 /// mixer output, post-normed x).
96 xin: PfMem,
97 /// DEV e4m3 `[m + bm][inter]` and f32 scales `[m + bm][inter / 128]` (a GEMM tile reads
98 /// activation rows up to `row0 + bm - 1`).
99 xq: PfMem,
100 xs: PfMem,
101 /// HOST f32 `[m][max(gdn_mix, att_mix)]`: the mixer projection (row stride = that GEMM's `n`).
102 mix: PfMem,
103 /// DEV bf16 `[m][inter]`: SwiGLU act rows.
104 act: PfMem,
105 /// HOST f32 `[m][hidden]`: o_proj and down outputs.
106 out: PfMem,
107 /// HOST `max_tiles` x 32 bytes: one GEMM's tile table (every call is synchronous).
108 tiles: PfMem,
109 /// [`q::gather_table`] for the model's rotary width and heads.
110 gather: Vec<u32>,
111 /// The model's widths.
112 shape: q::Shape,
113}
114
115fn ns(t: Instant) -> u64 {
116 t.elapsed().as_nanos() as u64
117}
118
119fn as_f32(b: &[u8]) -> Result<&[f32], String> {
120 // SAFETY: every bit pattern is a valid f32.
121 let (pre, mid, post) = unsafe { b.align_to::<f32>() };
122 if !pre.is_empty() || !post.is_empty() {
123 return Err("host buffer not f32-aligned".into());
124 }
125 Ok(mid)
126}
127
128fn as_f32_mut(b: &mut [u8]) -> Result<&mut [f32], String> {
129 // SAFETY: every bit pattern is a valid f32.
130 let (pre, mid, post) = unsafe { b.align_to_mut::<f32>() };
131 if !pre.is_empty() || !post.is_empty() {
132 return Err("host buffer not f32-aligned".into());
133 }
134 Ok(mid)
135}
136
137fn host<'a>(b: &'a PfMem, what: &str) -> Result<&'a [f32], String> {
138 as_f32(
139 b.host()
140 .ok_or_else(|| format!("{what} is not a host buffer"))?,
141 )
142}
143
144fn host_mut<'a>(b: &'a mut PfMem, what: &str) -> Result<&'a mut [f32], String> {
145 as_f32_mut(
146 b.host_mut()
147 .ok_or_else(|| format!("{what} is not a host buffer"))?,
148 )
149}
150
151/// HOST values copied into the caller's reusable cached scratch (one parallel pass).
152fn copy_out(b: &PfMem, what: &str, dst: &mut [f32]) -> Result<(), String> {
153 let src = &host(b, what)?[..dst.len()];
154 dst.par_chunks_mut(1 << 16)
155 .zip(src.par_chunks(1 << 16))
156 .for_each(|(d, s)| d.copy_from_slice(s));
157 Ok(())
158}
159
160/// `src` written into the start of a HOST buffer (in parallel).
161fn copy_in(b: &mut PfMem, what: &str, src: &[f32]) -> Result<(), String> {
162 let dst = &mut host_mut(b, what)?[..src.len()];
163 dst.par_chunks_mut(1 << 16)
164 .zip(src.par_chunks(1 << 16))
165 .for_each(|(d, s)| d.copy_from_slice(s));
166 Ok(())
167}
168
169/// Index of the largest logit (the first one on a tie).
170fn argmax(v: &[f32]) -> u32 {
171 let mut best = 0usize;
172 for (i, &x) in v.iter().enumerate() {
173 if x > v[best] {
174 best = i;
175 }
176 }
177 best as u32
178}
179
180/// Chunk lengths for `n` tokens: at most `chunk` each, none shorter than the DeltaNet prefill's
181/// minimum (the second to last chunk gives up tokens when the remainder would be too short).
182pub(super) fn chunk_lengths(n: usize, chunk: usize) -> Vec<usize> {
183 let min = q::GDN_PF_MIN_T;
184 let mut out = Vec::with_capacity(n.div_ceil(chunk.max(1)));
185 let mut rem = n;
186 while rem > 0 {
187 let m = if rem <= chunk {
188 rem
189 } else if rem - chunk < min {
190 rem - min
191 } else {
192 chunk
193 };
194 out.push(m);
195 rem -= m;
196 }
197 out
198}
199
200fn reading_fast_setting(value: Option<&str>) -> Result<bool, String> {
201 match value {
202 None | Some("0") => Ok(false),
203 Some("1") => Ok(true),
204 Some(_) => Err("AIEN_Q38_READING_FAST must be 0 or 1".into()),
205 }
206}
207
208fn attention_mirror_setting(value: Option<&str>) -> Result<bool, String> {
209 match value {
210 None | Some("0") => Ok(false),
211 Some("1") => Ok(true),
212 Some(_) => Err("AIEN_Q38_ATTENTION_MIRROR must be 0 or 1".into()),
213 }
214}
215
216fn attention_mirror_selected() -> Result<bool, String> {
217 let value = match std::env::var("AIEN_Q38_ATTENTION_MIRROR") {
218 Ok(value) => Some(value),
219 Err(std::env::VarError::NotPresent) => None,
220 Err(_) => return Err("AIEN_Q38_ATTENTION_MIRROR must be 0 or 1".into()),
221 };
222 let selected = attention_mirror_setting(value.as_deref())?;
223 if selected && !q::has_attention_mirror() {
224 return Err("qwen38 attention mirror: scoped Omega entry is not linked".into());
225 }
226 Ok(selected)
227}
228
229fn reading_device(rows: usize) -> Result<ScopedPfDevice, String> {
230 let setting = match std::env::var("AIEN_Q38_READING_FAST") {
231 Ok(value) => Some(value),
232 Err(std::env::VarError::NotPresent) => None,
233 Err(_) => return Err("AIEN_Q38_READING_FAST must be 0 or 1".into()),
234 };
235 if reading_fast_setting(setting.as_deref())? {
236 ScopedPfDevice::reading_fast(rows)
237 } else {
238 Ok(ScopedPfDevice::default())
239 }
240}
241
242impl PfState {
243 fn new(
244 m: usize,
245 rotary: usize,
246 shape: q::Shape,
247 mut dev: ScopedPfDevice,
248 ) -> Result<Self, String> {
249 let bm = dev.qgemm_bm();
250 let kq = shape.inter.max(shape.hidden).max(shape.mixer_out()); // widest quantiser input
251 let max_tiles = m.div_ceil(bm) + 1;
252 Ok(Self {
253 xin: dev.alloc_host(m * shape.mixer_out().max(shape.hidden) * 4)?,
254 xq: dev.alloc_dev((m + bm) * kq)?,
255 xs: dev.alloc_dev((m + bm) * (kq / BLOCK) * 4)?,
256 mix: dev.alloc_host(m * shape.gdn_mix().max(shape.att_mix()) * 4)?,
257 act: dev.alloc_dev(m * shape.inter * 2)?,
258 out: dev.alloc_host(m * shape.hidden * 4)?,
259 tiles: dev.alloc_host(max_tiles * TILE_BYTES)?,
260 gather: q::gather_table(rotary, shape),
261 shape,
262 dev,
263 m,
264 bm,
265 max_tiles,
266 padded_rows: m + bm,
267 })
268 }
269
270 /// Quantises `m` rows of `k` at `x_va` into `xq` / `xs`.
271 fn quant(
272 &mut self,
273 k: usize,
274 input: QuantIn,
275 x_va: u64,
276 m: usize,
277 st: &mut PrefillStats,
278 ) -> Result<(), String> {
279 let t = Instant::now();
280 st.gemm_chip_ns += self
281 .dev
282 .quant(k, input, m, x_va, self.xq.va(), self.xs.va())?;
283 st.gemm_call_ns += ns(t);
284 st.gemm_launches += 1;
285 Ok(())
286 }
287
288 /// `y[m][n] = xq . W^T` for one FP8 tensor `[n][k]` (or the SwiGLU act rows of `n / 2`).
289 #[allow(clippy::too_many_arguments)]
290 fn gemm(
291 &mut self,
292 w: &Fp8Tensor,
293 n: usize,
294 k: usize,
295 layout: Layout,
296 y_va: u64,
297 m: usize,
298 st: &mut PrefillStats,
299 ) -> Result<(), String> {
300 let t = Instant::now();
301 let (w_va, s_va) = w.entry(0).map_err(|e| e.to_string())?;
302 let tab = build_tiles(self.bm, &[w_va], &[s_va], &[m as u32]).map_err(|e| e.to_string())?;
303 if tab.len() > self.max_tiles {
304 return Err(format!(
305 "tile table of {} entries > {}",
306 tab.len(),
307 self.max_tiles
308 ));
309 }
310 let bytes = self
311 .tiles
312 .host_mut()
313 .ok_or("tile table is not a host buffer")?;
314 for (j, tl) in tab.iter().enumerate() {
315 bytes[j * TILE_BYTES..(j + 1) * TILE_BYTES].copy_from_slice(&tl.to_bytes());
316 }
317 let call = QgemmCall {
318 n,
319 k,
320 layout,
321 tiles_va: self.tiles.va(),
322 ntiles: tab.len(),
323 rowidx_va: 0,
324 xq_va: self.xq.va(),
325 xs_va: self.xs.va(),
326 y_va,
327 };
328 st.gemm_chip_ns += self.dev.qgemm(&call)?;
329 st.gemm_call_ns += ns(t);
330 st.gemm_launches += 1;
331 Ok(())
332 }
333}
334
335impl Qwen38Omega {
336 /// Feeds `tokens` at the next positions in chunks of at most `chunk` tokens and returns the
337 /// greedy next token (the first generated token), its logits and what the call cost. At
338 /// least [`q::GDN_PF_MIN_T`] tokens; `chunk` in `6 ..= 32768`.
339 pub fn prefill(
340 &mut self,
341 tokens: &[u32],
342 chunk: usize,
343 ) -> Result<(u32, Vec<f32>, PrefillStats), String> {
344 let t0 = Instant::now();
345 if self.is_moe() {
346 // The 35B: chunks of the prompt through the chip as rows (L369, the decode step's kernels,
347 // the state bit for bit as token by token); AIEN_Q36_PREFILL_CHUNK=0 feeds the decode
348 // graph token by token (the old path).
349 let chunk = q36_prefill_chunk()?;
350 let mut next = 0u32;
351 if chunk == 0 {
352 for &t in tokens {
353 next = self.step(t)?.0;
354 }
355 } else {
356 let (n, chunks) = self.prefill_moe(tokens, chunk)?;
357 next = n;
358 let logits = self.logits()?;
359 let st = PrefillStats {
360 tokens: tokens.len(),
361 chunks,
362 wall_ns: ns(t0),
363 ..Default::default()
364 };
365 return Ok((next, logits, st));
366 }
367 let logits = self.logits()?;
368 let st = PrefillStats {
369 tokens: tokens.len(),
370 wall_ns: ns(t0),
371 ..Default::default()
372 };
373 return Ok((next, logits, st));
374 }
375 let (last, mut st) = self.prefill_rows(tokens, chunk, false)?;
376 let t = Instant::now();
377 let logits = self.head_logits(&last)?;
378 let next = argmax(&logits);
379 st.head_ns = ns(t);
380 st.wall_ns = ns(t0);
381 Ok((next, logits, st))
382 }
383
384 /// The final norm and the bf16 lm_head on one residual row (`[hidden]`): `[vocab]` logits.
385 pub fn head_logits(&mut self, residual: &[f32]) -> Result<Vec<f32>, String> {
386 let h = self.config.hidden;
387 if residual.len() != h {
388 return Err(format!(
389 "head_logits: {} values (hidden {h})",
390 residual.len()
391 ));
392 }
393 let mut hidden = vec![0f32; h];
394 rmsnorm(residual, &self.final_norm, self.config.eps, &mut hidden);
395 let mut logits = vec![0f32; self.config.vocab];
396 self.lm_head
397 .gemv_f32(&hidden, &mut logits)
398 .map_err(gpu("lm_head"))?;
399 Ok(logits)
400 }
401
402 /// As [`Self::prefill`] without the head: the residual stream after the last layer of every
403 /// token (`all`, `[n][hidden]`) or of the last token only (`[hidden]`). `wall_ns` covers the
404 /// layers only.
405 pub fn prefill_rows(
406 &mut self,
407 tokens: &[u32],
408 chunk: usize,
409 all: bool,
410 ) -> Result<(Vec<f32>, PrefillStats), String> {
411 let t0 = Instant::now();
412 let n = tokens.len();
413 let (h, v) = (self.config.hidden, self.config.vocab);
414 if self.is_moe() {
415 // As prefill: token by token through the decode graph; the rows are its residual x.
416 let mut rows = Vec::with_capacity(if all { n * h } else { h });
417 for (i, &t) in tokens.iter().enumerate() {
418 self.step(t)?;
419 if all || i + 1 == n {
420 rows.extend(self.residual()?);
421 }
422 }
423 let _ = (chunk, v);
424 return Ok((
425 rows,
426 PrefillStats {
427 tokens: n,
428 wall_ns: ns(t0),
429 ..Default::default()
430 },
431 ));
432 }
433 if !q::has_prefill() {
434 return Err("qwen38 prefill: omega's prefill entries are not linked".into());
435 }
436 let attention_mirror = attention_mirror_selected()?;
437 if n < q::GDN_PF_MIN_T {
438 return Err(format!(
439 "qwen38 prefill: {n} tokens (at least {})",
440 q::GDN_PF_MIN_T
441 ));
442 }
443 if !(2 * q::GDN_PF_MIN_T..=q::PATTN_MAX_M).contains(&chunk) {
444 return Err(format!(
445 "qwen38 prefill: chunk {chunk} (6..={})",
446 q::PATTN_MAX_M
447 ));
448 }
449 if self.pos + n > self.max_pos {
450 return Err(format!(
451 "qwen38 prefill: positions {} + {n} > KV cache of {}",
452 self.pos, self.max_pos
453 ));
454 }
455 if let Some(&t) = tokens.iter().find(|&&t| t as usize >= v) {
456 return Err(format!("qwen38 prefill: token {t} outside the vocab {v}"));
457 }
458 let want = chunk.min(n);
459 let shape = dense_shape(&self.config)?;
460 let dev = reading_device(want)?;
461 let reusable = self.pf.as_ref().is_some_and(|p| {
462 p.shape == shape
463 && dev
464 .workspace_fits(p.m, p.padded_rows, p.max_tiles, want)
465 .unwrap_or(p.m >= want && p.bm == dev.qgemm_bm() && p.dev.same_profile(&dev))
466 });
467 if !reusable {
468 self.pf = None; // free incompatible storage before allocating
469 self.pf = Some(PfState::new(want, self.config.rotary_dim, shape, dev)?);
470 } else {
471 let pf = self.pf.as_mut().expect("workspace admitted");
472 // Every matrix call rebuilds its tile table using this selected height.
473 pf.bm = dev.qgemm_bm();
474 pf.dev = dev;
475 }
476 let mut st = PrefillStats {
477 tokens: n,
478 ..Default::default()
479 };
480 let mut rows = Vec::with_capacity(if all { n * h } else { h });
481 let mut done = 0;
482 for m in chunk_lengths(n, chunk) {
483 let x = self.prefill_chunk(&tokens[done..done + m], &mut st, attention_mirror)?;
484 if all {
485 rows.extend_from_slice(&x);
486 } else if done + m == n {
487 rows.extend_from_slice(&x[(m - 1) * h..]);
488 }
489 done += m;
490 st.chunks += 1;
491 }
492 st.wall_ns = ns(t0);
493 Ok((rows, st))
494 }
495
496 /// One chunk through every layer at positions `self.pos ..`: the residual stream after the
497 /// last layer, `[m][hidden]`.
498 fn prefill_chunk(
499 &mut self,
500 toks: &[u32],
501 st: &mut PrefillStats,
502 attention_mirror: bool,
503 ) -> Result<Vec<f32>, String> {
504 let m = toks.len();
505 let pos0 = self.pos;
506 let (h, eps, layers) = (self.config.hidden, self.config.eps, self.config.layers);
507 let pf = self.pf.as_mut().expect("prefill buffers sized");
508 let sh = pf.shape;
509 let (mo, inter) = (sh.mixer_out(), sh.inter);
510 let (att_qkv, gdn_qkv) = (sh.att_qkv(), sh.gdn_qkv());
511
512 let t = Instant::now();
513 let mut x: Vec<f32> = toks
514 .iter()
515 .flat_map(|&tk| {
516 let r = tk as usize * h;
517 self.embed[r..r + h].iter().map(|&b| bf16_to_f32(b))
518 })
519 .collect();
520 let mut xn = vec![0f32; m * h];
521 let mut att = vec![0f32; m * mo];
522 // Reuse the same cached temporaries across layers. After the mixer consumes
523 // qkv, that scratch also holds o/down output; no second output copy is live.
524 // The largest live set is the existing DeltaNet mix/split/a|b stage.
525 let mut mix_scratch = vec![0f32; m * sh.gdn_mix().max(sh.att_mix())];
526 let mut split_scratch = vec![0f32; m * gdn_qkv.max(att_qkv).max(h)];
527 let mut side_scratch = vec![0f32; m * mo];
528 let mut ab = vec![0f32; m * sh.ab()];
529 st.host_ns += ns(t);
530
531 let (mut gi, mut ai) = (0usize, 0usize);
532 for l in 0..layers {
533 let lt = &self.layers[l];
534 let (in_norm, post_norm) = &self.norms[l];
535 let attention = self.config.full_attention[l];
536
537 let t = Instant::now();
538 xn.par_chunks_mut(h)
539 .zip(x.par_chunks(h))
540 .for_each(|(o, r)| rmsnorm(r, in_norm, eps, o));
541 copy_in(&mut pf.xin, "xin", &xn)?;
542 st.host_ns += ns(t);
543 let xin_va = pf.xin.va();
544 pf.quant(h, QuantIn::F32, xin_va, m, st)
545 .map_err(|e| format!("layer {l} quant x: {e}"))?;
546 let mix_n = if attention {
547 sh.att_mix()
548 } else {
549 sh.gdn_mix()
550 };
551 let mix_va = pf.mix.va();
552 pf.gemm(&lt.mix, mix_n, h, Layout::Plain, mix_va, m, st)
553 .map_err(|e| format!("layer {l} mixer gemm x{m}: {e}"))?;
554
555 let t = Instant::now();
556 copy_out(&pf.mix, "mix", &mut mix_scratch[..m * mix_n])?;
557 let mix = &mix_scratch[..m * mix_n];
558 st.host_ns += ns(t);
559 if attention {
560 let t = Instant::now();
561 let qkv = &mut split_scratch[..m * att_qkv];
562 let gate = &mut side_scratch[..m * mo];
563 let (gq, gg) = pf.gather.split_at(att_qkv);
564 qkv.par_chunks_mut(att_qkv)
565 .zip(gate.par_chunks_mut(mo))
566 .zip(mix.par_chunks(mix_n))
567 .for_each(|((a, g), r)| {
568 for (o, &s) in a.iter_mut().zip(gq) {
569 *o = r[s as usize];
570 }
571 for (o, &s) in g.iter_mut().zip(gg) {
572 *o = r[s as usize];
573 }
574 });
575 st.host_ns += ns(t);
576 let cost = self
577 .attn
578 .as_mut()
579 .expect("an attention layer has a cache")
580 .prefill_scoped(
581 ai,
582 pos0,
583 m,
584 qkv,
585 &mut att,
586 q::Attn256PrefillOptions {
587 eps,
588 cached_history: attention_mirror,
589 },
590 )
591 .map_err(|e| format!("layer {l} attention x{m}: {e}"))?;
592 st.attn_chip_ns += cost.chip_ns;
593 st.attn_call_ns += cost.call_ns;
594 ai += 1;
595 let t = Instant::now();
596 att.par_chunks_mut(mo)
597 .zip(gate.par_chunks(mo))
598 .for_each(|(a, g)| {
599 for (v, &gv) in a.iter_mut().zip(g) {
600 *v /= 1.0 + (-gv).exp();
601 }
602 });
603 st.host_ns += ns(t);
604 } else {
605 let t = Instant::now();
606 let qkv = &mut split_scratch[..m * gdn_qkv];
607 let z = &mut side_scratch[..m * mo];
608 qkv.par_chunks_mut(gdn_qkv)
609 .zip(z.par_chunks_mut(mo))
610 .zip(mix.par_chunks(mix_n))
611 .for_each(|((a, b), r)| {
612 a.copy_from_slice(&r[..gdn_qkv]);
613 b.copy_from_slice(&r[gdn_qkv..]);
614 });
615 st.host_ns += ns(t);
616 let t = Instant::now();
617 self.ab_mm[gi]
618 .matmul_f32(m, &xn, &mut ab)
619 .map_err(|e| format!("layer {l} a|b matmul x{m}: {e}"))?;
620 st.ab_call_ns += ns(t);
621 let cost = self
622 .gdn
623 .as_mut()
624 .expect("a DeltaNet layer has state")
625 .prefill(gi, m, qkv, z, &ab, EPS_L2, eps, &mut att)
626 .map_err(|e| format!("layer {l} gdn prefill x{m}: {e}"))?;
627 st.gdn_chip_ns += cost.chip_ns;
628 st.gdn_call_ns += cost.call_ns;
629 gi += 1;
630 }
631
632 // o_proj, residual, post norm
633 let t = Instant::now();
634 copy_in(&mut pf.xin, "xin", &att)?;
635 st.host_ns += ns(t);
636 pf.quant(mo, QuantIn::F32, xin_va, m, st)
637 .map_err(|e| format!("layer {l} quant mixer out: {e}"))?;
638 let out_va = pf.out.va();
639 pf.gemm(&lt.o, h, mo, Layout::Plain, out_va, m, st)
640 .map_err(|e| format!("layer {l} o gemm x{m}: {e}"))?;
641 let t = Instant::now();
642 copy_out(&pf.out, "out", &mut split_scratch[..m * h])?;
643 let o = &split_scratch[..m * h];
644 x.par_chunks_mut(1 << 14)
645 .zip(o.par_chunks(1 << 14))
646 .for_each(|(a, b)| a.iter_mut().zip(b).for_each(|(a, b)| *a += b));
647 xn.par_chunks_mut(h)
648 .zip(x.par_chunks(h))
649 .for_each(|(o, r)| rmsnorm(r, post_norm, eps, o));
650 copy_in(&mut pf.xin, "xin", &xn)?;
651 st.host_ns += ns(t);
652
653 // MLP
654 pf.quant(h, QuantIn::F32, xin_va, m, st)
655 .map_err(|e| format!("layer {l} quant post: {e}"))?;
656 let act_va = pf.act.va();
657 pf.gemm(&lt.gate_up, 2 * inter, h, Layout::SwigluNat, act_va, m, st)
658 .map_err(|e| format!("layer {l} gate|up gemm x{m}: {e}"))?;
659 pf.quant(inter, QuantIn::Bf16, act_va, m, st)
660 .map_err(|e| format!("layer {l} quant act: {e}"))?;
661 pf.gemm(&lt.down, h, inter, Layout::Plain, out_va, m, st)
662 .map_err(|e| format!("layer {l} down gemm x{m}: {e}"))?;
663 let t = Instant::now();
664 copy_out(&pf.out, "out", &mut split_scratch[..m * h])?;
665 let d = &split_scratch[..m * h];
666 x.par_chunks_mut(1 << 14)
667 .zip(d.par_chunks(1 << 14))
668 .for_each(|(a, b)| a.iter_mut().zip(b).for_each(|(a, b)| *a += b));
669 st.host_ns += ns(t);
670 }
671 self.pos += m;
672 Ok(x)
673 }
674}
675
676/// Prompt tokens per 35B prefill chunk (`AIEN_Q36_PREFILL_CHUNK`, default the graph's most,
677/// [`q::q36::PREFILL_MAX_ROWS`]); 0 = token by token through the decode graph.
678pub fn q36_prefill_chunk() -> Result<usize, String> {
679 match std::env::var("AIEN_Q36_PREFILL_CHUNK") {
680 Ok(v) => match v.parse::<usize>() {
681 Ok(n) if n <= q::q36::PREFILL_MAX_ROWS => Ok(n),
682 _ => Err(format!(
683 "AIEN_Q36_PREFILL_CHUNK={v}: 0 (off) ..= {}",
684 q::q36::PREFILL_MAX_ROWS
685 )),
686 },
687 Err(_) => Ok(q::q36::PREFILL_MAX_ROWS),
688 }
689}
690
691impl Qwen38Omega {
692 /// L369: fp8 GEMM weight bytes the 35B prefill has streamed so far on this graph (0 for other
693 /// models); see `Graph::prefill_streamed`.
694 pub fn q36_prefill_streamed(&self) -> u64 {
695 match &self.graph {
696 Graph::Moe(g) => g.prefill_streamed(),
697 _ => 0,
698 }
699 }
700
701 /// The 35B prefill (L369): `tokens` at the next positions of head 0 in chunks of at most
702 /// `chunk` (1..=[`q::q36::PREFILL_MAX_ROWS`]); returns the last token's greedy token and the
703 /// chunk count. The graph's logits / [`Self::logits`] are the last token's, as after `step`.
704 pub fn prefill_moe(&mut self, tokens: &[u32], chunk: usize) -> Result<(u32, usize), String> {
705 let (next, chunks) = self.prefill_moe_head(0, tokens, chunk, true)?;
706 Ok((next.unwrap_or(0), chunks))
707 }
708
709 /// As [`Self::prefill_moe`] for graph head slot `head` at its next position (which moves on by
710 /// `tokens.len()`); `want_token`: the last token's head and argmax.
711 pub fn prefill_moe_head(
712 &mut self,
713 head: usize,
714 tokens: &[u32],
715 chunk: usize,
716 want_token: bool,
717 ) -> Result<(Option<u32>, usize), String> {
718 let (h, v) = (self.config.hidden, self.config.vocab);
719 let pos0 = self.head_pos(head)?;
720 if tokens.is_empty() || chunk == 0 || chunk > q::q36::PREFILL_MAX_ROWS {
721 return Err(format!(
722 "q36 prefill: {} tokens in chunks of {chunk}",
723 tokens.len()
724 ));
725 }
726 if pos0 + tokens.len() > self.max_pos {
727 return Err(format!(
728 "q36 prefill: positions {pos0}..{} past the KV cache's {}",
729 pos0 + tokens.len(),
730 self.max_pos
731 ));
732 }
733 if let Some(&t) = tokens.iter().find(|&&t| t as usize >= v) {
734 return Err(format!("q36 prefill: token {t} outside the vocab {v}"));
735 }
736 let embed = &self.embed;
737 let Graph::Moe(g) = &mut self.graph else {
738 return Err("q36 prefill: not the 35B graph".into());
739 };
740 if g.prefill_cap() < chunk {
741 g.prefill_alloc(chunk).map_err(gpu("q36 prefill_alloc"))?;
742 }
743 let mut next = None;
744 let mut pos = pos0;
745 let n_chunks = tokens.len().div_ceil(chunk);
746 for (i, c) in tokens.chunks(chunk).enumerate() {
747 let mut x = vec![0f32; c.len() * h];
748 for (row, &t) in x.chunks_mut(h).zip(c) {
749 let t = t as usize;
750 for (d, &b) in row.iter_mut().zip(&embed[t * h..(t + 1) * h]) {
751 *d = bf16_to_f32(b);
752 }
753 }
754 let last = i + 1 == n_chunks;
755 let (tok, _) = g
756 .prefill(head, &x, pos, last && want_token)
757 .map_err(gpu("q36 prefill"))?;
758 if last {
759 next = tok;
760 }
761 pos += c.len();
762 }
763 *self.head_pos_mut(head)? = pos;
764 Ok((next, n_chunks))
765 }
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771
772 #[test]
773 fn attention_mirror_setting_is_explicit() {
774 assert!(!attention_mirror_setting(None).unwrap());
775 assert!(!attention_mirror_setting(Some("0")).unwrap());
776 assert!(attention_mirror_setting(Some("1")).unwrap());
777 for bad in ["", "true", "2", " 1", "1 "] {
778 assert!(attention_mirror_setting(Some(bad)).is_err());
779 }
780 }
781
782 #[test]
783 fn reading_fast_setting_is_explicit() {
784 assert!(!reading_fast_setting(None).unwrap());
785 assert!(!reading_fast_setting(Some("0")).unwrap());
786 assert!(reading_fast_setting(Some("1")).unwrap());
787 for bad in ["", "true", "2", " 1", "1 "] {
788 assert!(reading_fast_setting(Some(bad)).is_err());
789 }
790 }
791
792 #[test]
793 fn chunk_lengths_cover_and_respect_the_minimum() {
794 for n in 3..200 {
795 for chunk in [6, 7, 16, 64] {
796 let c = chunk_lengths(n, chunk);
797 assert_eq!(c.iter().sum::<usize>(), n, "n {n} chunk {chunk}");
798 assert!(
799 c.iter().all(|&m| (q::GDN_PF_MIN_T..=chunk).contains(&m)),
800 "n {n} chunk {chunk}: {c:?}"
801 );
802 }
803 }
804 assert_eq!(chunk_lengths(130, 64), vec![64, 63, 3]);
805 assert_eq!(chunk_lengths(129, 64), vec![64, 62, 3]);
806 assert_eq!(chunk_lengths(131_072, 4096).len(), 32);
807 }
808
809 #[test]
810 fn argmax_takes_the_first_maximum() {
811 assert_eq!(argmax(&[0.0, 2.0, 1.0, 2.0]), 1);
812 }
813}