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 / rows.rs

703 lines · 28058 bytes Raw Blame History
1//! Many conversations on one 35B upload (sc L354, server batching): each row is one conversation's
2//! own state (DeltaNet tails and states, the attention KV cache, its position) with its own
3//! Qwen3.6-35B-A3B decode graph pointed at the SAME resident weights, router and lm_head.
4//!
5//! [`Qwen38Omega::step_rows`] feeds one token into each listed row and returns each row's greedy
6//! token and logits. With L312's strokes linked it feeds up to `MAX_HEADS` rows per command
7//! list (one stroke graph whose head slots are re-pointed at each chunk's rows, nothing copied);
8//! `AIEN_Q36_STROKE=0` runs each row's own one-row graph in turn (the first cut). Either way every
9//! row's bits must be exactly what that conversation gets alone (the gate checks it).
10//!
11//! Negative control (TEST ONLY): `AIEN_Q36_TEST_ROW_SWAP=<k>` swaps the states of the first two
12//! fed rows once, at the first multi-row step from the `k`th on (counted from 1) that feeds two or
13//! more rows, so two conversations continue
14//! from each other's state: the per-row identity gate must go red.
15use aien_omega_q38::q36::{self as q, Q36Config, Q36Graph};
16use aien_omega_q38::{Attn256Cache, Gdn, GraphStats};
17
18use super::{gpu, Qwen38Omega, Qwen38Snapshot};
19use crate::qwen3_moe::bf16_to_f32;
20
21/// One DeltaNet layer's parameters as the upload set them (host copy, for each new row's state).
22pub(super) struct GdnParams {
23 pub conv: Vec<f32>,
24 pub a_log: Vec<f32>,
25 pub dt_bias: Vec<f32>,
26 pub norm: Vec<f32>,
27}
28
29/// What a new row needs besides the shared device tensors (the 35B only).
30pub(super) struct RowSource {
31 pub layers: usize,
32 pub attn_mask: u64,
33 pub vocab: usize,
34 pub eps: f32,
35 pub rope_theta: f64,
36 pub rotary_dim: usize,
37 pub gdn_params: Vec<GdnParams>,
38 /// Every attention layer's (q_norm, k_norm) as the checkpoint stores them.
39 pub attn_norms: Vec<(Vec<f32>, Vec<f32>)>,
40 pub mutant: Option<i32>,
41 /// The exact two-pass head's Row coefficients (HUM L314), when the screen was built: every row
42 /// graph and the stroke graph screen with the door's `head_screen`.
43 pub head_coef: Option<Vec<f32>>,
44}
45
46/// One conversation's state and graph. Field order is drop order: the graph before the state it
47/// points at.
48pub(super) struct Q36Row {
49 graph: Q36Graph,
50 gdn: Option<Gdn>,
51 #[allow(dead_code)] // owned only: the graph points at it
52 attn: Option<Attn256Cache>,
53 pos: usize,
54 max_pos: usize,
55}
56
57/// One row's share of a [`Qwen38Omega::step_rows`] call.
58#[derive(Debug, Clone, Copy)]
59pub struct RowFeed {
60 /// The row ([`Qwen38Omega::add_rows`]).
61 pub row: usize,
62 /// The token it takes at its next position.
63 pub token: u32,
64 /// Copy the row's logits back (a row still feeding its prompt needs only the last ones).
65 pub logits: bool,
66}
67
68/// The merge train's switches for one row of a [`Qwen38Omega::step_rows_test`] call (L384):
69/// which path this row's token takes this step. The default is the plain served path.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct RowTest {
72 /// Ride a stroke with the other plain rows (`false`: this row's own one-row graph).
73 pub stroke: bool,
74 /// The exact two-pass head for this row's greedy token (`false`: the plain head).
75 pub exact_head: bool,
76 /// `AIEN_Q36_TEST_MUTANT` number for this row's step only (`0`: none). Set on the row's
77 /// own graph before its token is recorded and cleared after: the command list is recorded
78 /// afresh every token, so the mutant kernels are chosen for this step and no other.
79 pub mutant: i32,
80}
81
82impl Default for RowTest {
83 fn default() -> Self {
84 Self {
85 stroke: true,
86 exact_head: true,
87 mutant: 0,
88 }
89 }
90}
91
92impl RowTest {
93 /// The served path: nothing to apply.
94 pub fn is_plain(&self) -> bool {
95 *self == Self::default()
96 }
97}
98
99/// What one row got from a step.
100#[derive(Debug, Clone)]
101pub struct RowOut {
102 /// The graph's greedy token.
103 pub token: u32,
104 /// `[vocab]` when asked for.
105 pub logits: Option<Vec<f32>>,
106 pub stats: GraphStats,
107}
108
109impl Qwen38Omega {
110 /// Makes `n` more conversation rows of `max_pos` positions each (rounded up to whole
111 /// 256-position passes) over this upload's weights; returns the first new row's index.
112 /// The 35B only. Rows start empty (position 0).
113 pub fn add_rows(&mut self, n: usize, max_pos: usize) -> Result<usize, String> {
114 let first = self.rows.len();
115 let src = self
116 .row_src
117 .as_ref()
118 .ok_or("rows: the 35B (qwen3_5_moe) only")?;
119 let max_pos = max_pos.next_multiple_of(256);
120 let router = self.router.as_ref().ok_or("rows: no router")?.as_raw();
121 let lm_head = self.lm_head.as_raw();
122 for _ in 0..n {
123 let mut gdn = if src.gdn_params.is_empty() {
124 None
125 } else {
126 Some(
127 Gdn::alloc_ratio(src.gdn_params.len(), q::GDN_RATIO)
128 .map_err(gpu("row gdn alloc"))?,
129 )
130 };
131 if let Some(g) = gdn.as_mut() {
132 for (i, p) in src.gdn_params.iter().enumerate() {
133 g.set_layer(i, &p.conv, &p.a_log, &p.dt_bias, &p.norm)
134 .map_err(gpu("row gdn set_layer"))?;
135 }
136 }
137 let mut attn = if src.attn_norms.is_empty() {
138 None
139 } else {
140 Some(
141 Attn256Cache::alloc_shape(
142 src.attn_norms.len(),
143 max_pos,
144 src.rope_theta,
145 src.rotary_dim,
146 q::Q_HEADS,
147 q::KV_HEADS,
148 q::Q_PER_CTA,
149 )
150 .map_err(gpu("row attn256 alloc"))?,
151 )
152 };
153 if let Some(a) = attn.as_mut() {
154 for (i, (qn, kn)) in src.attn_norms.iter().enumerate() {
155 a.set_norms(i, qn, kn)
156 .map_err(gpu("row attn256 set_norms"))?;
157 }
158 }
159 let cfg = Q36Config {
160 layers: src.layers as u32,
161 attn_mask: src.attn_mask,
162 vocab: src.vocab as u32,
163 eps: src.eps,
164 eps_l2: super::EPS_L2,
165 gdn: gdn.as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw),
166 attn: attn
167 .as_ref()
168 .map_or(std::ptr::null_mut(), Attn256Cache::as_raw),
169 router,
170 lm_head,
171 };
172 // SAFETY: the state handles live in the row (dropped after its graph); the router and
173 // lm_head live in `self`, which drops `rows` first (field order).
174 let mut graph =
175 unsafe { Q36Graph::create(&cfg) }.map_err(gpu("row q36 graph create"))?;
176 self.wire(&mut graph)?;
177 self.rows.push(Q36Row {
178 graph,
179 gdn,
180 attn,
181 pos: 0,
182 max_pos,
183 });
184 }
185 // The strokes' graph (L312): MAX_HEADS head slots, pointed at each chunk's rows per step.
186 if self.row_stroke.is_none() && stroke_on() && !self.rows.is_empty() {
187 let r0 = &self.rows[0];
188 let cfg = Q36Config {
189 layers: src.layers as u32,
190 attn_mask: src.attn_mask,
191 vocab: src.vocab as u32,
192 eps: src.eps,
193 eps_l2: super::EPS_L2,
194 gdn: r0.gdn.as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw),
195 attn: r0
196 .attn
197 .as_ref()
198 .map_or(std::ptr::null_mut(), Attn256Cache::as_raw),
199 router,
200 lm_head,
201 };
202 // SAFETY: as the rows' graphs; `row_stroke` drops before `rows` (field order).
203 let mut g = unsafe { Q36Graph::create_heads(&cfg, q::MAX_HEADS) }
204 .map_err(gpu("rows stroke graph create"))?;
205 self.wire(&mut g)?;
206 // L312 v2 (the batch): every layer recorded for all heads at once, one weight read per layer;
207 // its final reads the lm_head once per group of heads (the exact head is left out there).
208 let batch = batch_on();
209 if batch {
210 g.set_batch(true)
211 .map_err(|rc| format!("rows stroke set_batch: rc {rc}"))?;
212 }
213 eprintln!(
214 "qwen36 omega: rows ride strokes of up to {} ({}; AIEN_Q36_STROKE=0 rows in turn)",
215 q::MAX_HEADS,
216 if batch {
217 "batch v2, AIEN_Q36_STROKE_V2=0 for v1"
218 } else {
219 "v1 (AIEN_Q36_STROKE_V2=0)"
220 }
221 );
222 self.row_stroke = Some(g);
223 }
224 Ok(first)
225 }
226
227 /// Points a new graph at this upload's layers and final norm (and the test mutant).
228 fn wire(&self, graph: &mut Q36Graph) -> Result<(), String> {
229 for (l, (t, (in_norm, _))) in self.layers.iter().zip(&self.norms).enumerate() {
230 let ab = t.ab.as_ref().map_or(std::ptr::null_mut(), |b| b.as_raw());
231 // SAFETY: the tensors live in `self.layers`, which outlive the rows and the stroke
232 // graph (field order).
233 unsafe {
234 graph.set_layer(
235 l,
236 t.mix.as_raw(),
237 ab,
238 t.o.as_raw(),
239 t.gate_up.as_raw(),
240 t.down.as_raw(),
241 in_norm,
242 )
243 }
244 .map_err(gpu("row q36 graph set_layer"))?;
245 }
246 graph
247 .set_final_norm(&self.final_norm)
248 .map_err(gpu("row q36 graph set_final_norm"))?;
249 if let Some(m) = self.row_src.as_ref().and_then(|s| s.mutant) {
250 graph.test_set_mutant(m);
251 }
252 if let (Some(screen), Some(coef)) = (
253 self.head_screen.as_ref(),
254 self.row_src.as_ref().and_then(|s| s.head_coef.as_ref()),
255 ) {
256 // SAFETY: the screen lives in `self.head_screen`, which outlives the rows and the stroke
257 // graph (field order); the coefficients are copied.
258 unsafe { graph.set_exact_head(screen.as_raw(), coef) }
259 .map_err(gpu("row q36 graph set_exact_head"))?;
260 }
261 Ok(())
262 }
263
264 /// Rows made so far.
265 pub fn row_count(&self) -> usize {
266 self.rows.len()
267 }
268
269 /// Device bytes one row's state takes on paper at `max_pos` (DeltaNet state and tails, KV).
270 pub fn row_bytes(&self, max_pos: usize) -> usize {
271 let Some(src) = self.row_src.as_ref() else {
272 return 0;
273 };
274 let max_pos = max_pos.next_multiple_of(256);
275 let gdn = self.gdn.as_ref().map_or(0, |g| {
276 src.gdn_params.len() * (g.tail_floats() + g.state_floats()) * 4
277 });
278 gdn + src.attn_norms.len() * Attn256Cache::layer_bytes(max_pos)
279 }
280
281 /// Empties row `r` for a new conversation (DeltaNet state to zero, position 0; KV rows are
282 /// overwritten as the new conversation reaches them).
283 pub fn row_reset(&mut self, r: usize) -> Result<(), String> {
284 let n = self.rows.len();
285 let row = self
286 .rows
287 .get_mut(r)
288 .ok_or_else(|| format!("row {r} of {n}"))?;
289 if let Some(g) = row.gdn.as_mut() {
290 g.reset().map_err(gpu("row gdn reset"))?;
291 }
292 row.pos = 0;
293 Ok(())
294 }
295
296 /// Copies row `r`'s DeltaNet tails and states and its position into `snap` (host memory,
297 /// reused between calls), as [`Self::snapshot`] does for the main state.
298 pub fn row_snapshot(&mut self, r: usize, snap: &mut Qwen38Snapshot) -> Result<(), String> {
299 let n = self.rows.len();
300 let row = self
301 .rows
302 .get_mut(r)
303 .ok_or_else(|| format!("row {r} of {n}"))?;
304 snap.pos = row.pos;
305 let Some(g) = row.gdn.as_mut() else {
306 return Ok(());
307 };
308 let (tf, sf) = (g.tail_floats(), g.state_floats());
309 snap.tails.resize(g.layers() * tf, 0.0);
310 snap.states.resize(g.layers() * sf, 0.0);
311 for (l, (t, st)) in snap
312 .tails
313 .chunks_exact_mut(tf)
314 .zip(snap.states.chunks_exact_mut(sf))
315 .enumerate()
316 {
317 g.get_state(l, t, st).map_err(gpu("row gdn get_state"))?;
318 }
319 Ok(())
320 }
321
322 /// Puts a [`Self::row_snapshot`] back into row `r` (any row: the copy is plain host memory).
323 pub fn row_restore(&mut self, r: usize, snap: &Qwen38Snapshot) -> Result<(), String> {
324 let n = self.rows.len();
325 let row = self
326 .rows
327 .get_mut(r)
328 .ok_or_else(|| format!("row {r} of {n}"))?;
329 if snap.pos > row.max_pos {
330 return Err(format!(
331 "row_restore: position {} past the row's {}",
332 snap.pos, row.max_pos
333 ));
334 }
335 if let Some(g) = row.gdn.as_mut() {
336 let (tf, sf) = (g.tail_floats(), g.state_floats());
337 if snap.tails.len() != g.layers() * tf || snap.states.len() != g.layers() * sf {
338 return Err("row_restore: the snapshot is not of this model".into());
339 }
340 for (l, (t, st)) in snap
341 .tails
342 .chunks_exact(tf)
343 .zip(snap.states.chunks_exact(sf))
344 .enumerate()
345 {
346 g.set_state(l, t, st).map_err(gpu("row gdn set_state"))?;
347 }
348 }
349 row.pos = snap.pos;
350 Ok(())
351 }
352
353 /// Tokens row `r` holds (its next position) and the most it holds.
354 pub fn row_pos(&self, r: usize) -> Option<(usize, usize)> {
355 self.rows.get(r).map(|row| (row.pos, row.max_pos))
356 }
357
358 /// [`Self::step_rows`] with the merge train's switches per row (`tests[i]` goes with
359 /// `feed[i]`; shorter or empty = plain). Plain rows ride strokes together as in `step_rows`;
360 /// a row that turns strokes off, turns the exact head off or asks for a mutant takes its own
361 /// one-row graph for this step with those settings, so no other row's bits can change.
362 /// Outputs are in feed order.
363 pub fn step_rows_test(
364 &mut self,
365 feed: &[RowFeed],
366 tests: &[RowTest],
367 ) -> Result<Vec<RowOut>, String> {
368 if tests.iter().all(RowTest::is_plain) {
369 return self.step_rows(feed);
370 }
371 self.check_feed(feed)?;
372 self.row_steps += 1;
373 let test = |i: usize| tests.get(i).copied().unwrap_or_default();
374 let plain: Vec<usize> = (0..feed.len()).filter(|&i| test(i).is_plain()).collect();
375 let mut outs: Vec<Option<RowOut>> = vec![None; feed.len()];
376 if !plain.is_empty() {
377 let sub: Vec<RowFeed> = plain.iter().map(|&i| feed[i]).collect();
378 let mut got = Vec::with_capacity(sub.len());
379 if sub.len() >= 2 && self.row_stroke.is_some() {
380 let mut sg = self.row_stroke.take().expect("checked above");
381 let r = self.stroke_chunks(&mut sg, &sub, &mut got);
382 self.row_stroke = Some(sg);
383 r?;
384 } else {
385 for f in &sub {
386 got.push(self.row_token(f)?);
387 }
388 }
389 for (i, o) in plain.into_iter().zip(got) {
390 outs[i] = Some(o);
391 }
392 }
393 for (i, f) in feed.iter().enumerate() {
394 let t = test(i);
395 if t.is_plain() {
396 continue;
397 }
398 outs[i] = Some(self.row_token_test(f, t)?);
399 }
400 Ok(outs
401 .into_iter()
402 .map(|o| o.expect("every row answered"))
403 .collect())
404 }
405
406 /// One row's token through its own graph with the row's switches: the mutant set for this
407 /// record only (the graph's standing mutant, if the process has one, is put back after).
408 fn row_token_test(&mut self, f: &RowFeed, t: RowTest) -> Result<RowOut, String> {
409 let standing = self.row_src.as_ref().and_then(|s| s.mutant).unwrap_or(0);
410 if t.mutant != 0 {
411 self.rows[f.row].graph.test_set_mutant(t.mutant);
412 }
413 let r = self.row_token_with_head(f, t.exact_head);
414 if t.mutant != 0 {
415 self.rows[f.row].graph.test_set_mutant(standing);
416 }
417 r
418 }
419
420 /// Argument checks shared by [`Self::step_rows`] and [`Self::step_rows_test`].
421 fn check_feed(&self, feed: &[RowFeed]) -> Result<(), String> {
422 let v = self.config.vocab;
423 for (i, f) in feed.iter().enumerate() {
424 if f.row >= self.rows.len() {
425 return Err(format!("step_rows: row {} of {}", f.row, self.rows.len()));
426 }
427 if feed[..i].iter().any(|g| g.row == f.row) {
428 return Err(format!("step_rows: row {} fed twice", f.row));
429 }
430 if f.token as usize >= v {
431 return Err(format!(
432 "step_rows: token {} outside the vocab {v}",
433 f.token
434 ));
435 }
436 }
437 Ok(())
438 }
439
440 /// One token into each listed row (each row at most once): each row's greedy token, and its
441 /// logits when asked. On an error no position has moved past the failing row.
442 pub fn step_rows(&mut self, feed: &[RowFeed]) -> Result<Vec<RowOut>, String> {
443 let v = self.config.vocab;
444 for (i, f) in feed.iter().enumerate() {
445 if f.row >= self.rows.len() {
446 return Err(format!("step_rows: row {} of {}", f.row, self.rows.len()));
447 }
448 if feed[..i].iter().any(|g| g.row == f.row) {
449 return Err(format!("step_rows: row {} fed twice", f.row));
450 }
451 if f.token as usize >= v {
452 return Err(format!(
453 "step_rows: token {} outside the vocab {v}",
454 f.token
455 ));
456 }
457 }
458 self.row_steps += 1;
459 if feed.len() >= 2
460 && row_swap_step().is_some_and(|k| self.row_steps >= k)
461 && !ROW_SWAPPED.swap(true, std::sync::atomic::Ordering::SeqCst)
462 {
463 eprintln!(
464 "qwen36 omega: TEST ROW SWAP at step {}: rows {} and {} trade state (negative control; never serve this)",
465 self.row_steps, feed[0].row, feed[1].row
466 );
467 let (a, b) = (feed[0].row.min(feed[1].row), feed[0].row.max(feed[1].row));
468 let (lo, hi) = self.rows.split_at_mut(b);
469 std::mem::swap(&mut lo[a], &mut hi[0]);
470 }
471 for f in feed {
472 let row = &self.rows[f.row];
473 if row.pos >= row.max_pos {
474 return Err(format!(
475 "step_rows: row {} holds {} positions",
476 f.row, row.max_pos
477 ));
478 }
479 }
480 let mut outs = Vec::with_capacity(feed.len());
481 // Strokes (L312) for two rows or more; a lone row takes its own one-row graph (with the exact
482 // head): one head costs more in a stroke (L312: N=1 v2 27.3 ms vs 24.4 ms v1).
483 if feed.len() >= 2 && self.row_stroke.is_some() {
484 let mut sg = self.row_stroke.take().expect("checked above");
485 let r = self.stroke_chunks(&mut sg, feed, &mut outs);
486 self.row_stroke = Some(sg);
487 r?;
488 return Ok(outs);
489 }
490 for f in feed {
491 outs.push(self.row_token(f)?);
492 }
493 Ok(outs)
494 }
495
496 /// Up to MAX_HEADS rows per command list, the head slots pointed at them; a chunk of one row
497 /// takes the row's own graph.
498 fn stroke_chunks(
499 &mut self,
500 sg: &mut Q36Graph,
501 feed: &[RowFeed],
502 outs: &mut Vec<RowOut>,
503 ) -> Result<(), String> {
504 let (v, h) = (self.config.vocab, self.config.hidden);
505 {
506 for chunk in feed.chunks(q::MAX_HEADS) {
507 if let [f] = chunk {
508 outs.push(self.row_token(f)?);
509 continue;
510 }
511 // The exact head (when built) makes off-candidate logits -inf: on per head slot, for the
512 // rows that read no logits (sampled rows need every one).
513 for (hd, f) in chunk.iter().enumerate() {
514 sg.set_head_exact_head_on(hd, !f.logits);
515 }
516 let mut x = Vec::with_capacity(chunk.len() * h);
517 let mut pos = Vec::with_capacity(chunk.len());
518 for (hd, f) in chunk.iter().enumerate() {
519 let t = f.token as usize;
520 x.extend(
521 self.embed[t * h..(t + 1) * h]
522 .iter()
523 .map(|&b| bf16_to_f32(b)),
524 );
525 let row = &self.rows[f.row];
526 let (g, a) = (
527 row.gdn.as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw),
528 row.attn
529 .as_ref()
530 .map_or(std::ptr::null_mut(), Attn256Cache::as_raw),
531 );
532 // SAFETY: the row's state lives in `self.rows`, which outlives the stroke
533 // graph (field order); a re-point copies nothing.
534 unsafe { sg.set_head_state(hd, g, a) }
535 .map_err(gpu("rows stroke set_head_state"))?;
536 pos.push(row.pos);
537 }
538 let (tokens, stats) = sg.stroke(&x, &pos).map_err(gpu("rows stroke"))?;
539 for (hd, (f, token)) in chunk.iter().zip(tokens).enumerate() {
540 self.rows[f.row].pos += 1;
541 let logits = if f.logits {
542 let mut l = vec![0f32; v];
543 sg.read_head(hd, None, None, Some(&mut l))
544 .map_err(gpu("rows stroke read logits"))?;
545 Some(l)
546 } else {
547 None
548 };
549 outs.push(RowOut {
550 token,
551 logits,
552 // The chip time is the whole stroke's: counted once, on its first head.
553 stats: if hd == 0 {
554 stats
555 } else {
556 GraphStats::default()
557 },
558 });
559 }
560 }
561 }
562 Ok(())
563 }
564
565 /// One row's token through its own one-row graph.
566 fn row_token(&mut self, f: &RowFeed) -> Result<RowOut, String> {
567 self.row_token_with_head(f, true)
568 }
569
570 /// [`Self::row_token`]; `exact_head` false keeps the plain head for this token (the merge
571 /// train's `exact_head: false` arm; the words must not change).
572 fn row_token_with_head(&mut self, f: &RowFeed, exact_head: bool) -> Result<RowOut, String> {
573 let (v, h) = (self.config.vocab, self.config.hidden);
574 let t = f.token as usize;
575 let x: Vec<f32> = self.embed[t * h..(t + 1) * h]
576 .iter()
577 .map(|&b| bf16_to_f32(b))
578 .collect();
579 let row = &mut self.rows[f.row];
580 if row.pos >= row.max_pos {
581 return Err(format!(
582 "step_rows: row {} holds {} positions",
583 f.row, row.max_pos
584 ));
585 }
586 row.graph.set_exact_head_on(exact_head && !f.logits);
587 let (token, stats) = row.graph.token(&x, row.pos).map_err(gpu("row q36 token"))?;
588 row.pos += 1;
589 let logits = if f.logits {
590 let mut l = vec![0f32; v];
591 row.graph
592 .read(None, None, Some(&mut l))
593 .map_err(gpu("row q36 read logits"))?;
594 Some(l)
595 } else {
596 None
597 };
598 Ok(RowOut {
599 token,
600 logits,
601 stats,
602 })
603 }
604}
605
606impl Qwen38Omega {
607 /// L369: `tokens` (a prompt chunk, at most [`q::PREFILL_MAX_ROWS`]) into row `r` at its next
608 /// positions through the chip's prefill: the state ends bit for bit as `tokens.len()` steps of
609 /// [`Self::step_rows`] would leave it. The last token's greedy token, and its logits when asked
610 /// (then the exact head is off for that token, as in a stroke with a row reading logits).
611 pub fn prefill_row(
612 &mut self,
613 r: usize,
614 tokens: &[u32],
615 logits: bool,
616 ) -> Result<RowOut, String> {
617 let (v, h) = (self.config.vocab, self.config.hidden);
618 let n = tokens.len();
619 if r >= self.rows.len() {
620 return Err(format!("prefill_row: row {r} of {}", self.rows.len()));
621 }
622 if n == 0 || n > q::PREFILL_MAX_ROWS {
623 return Err(format!(
624 "prefill_row: {n} tokens (1..={})",
625 q::PREFILL_MAX_ROWS
626 ));
627 }
628 if let Some(&t) = tokens.iter().find(|&&t| t as usize >= v) {
629 return Err(format!("prefill_row: token {t} outside the vocab {v}"));
630 }
631 let (pos, max_pos) = (self.rows[r].pos, self.rows[r].max_pos);
632 if pos + n > max_pos {
633 return Err(format!(
634 "prefill_row: row {r} holds {max_pos} positions, {pos} + {n} asked"
635 ));
636 }
637 let mut x = Vec::with_capacity(n * h);
638 for &t in tokens {
639 let t = t as usize;
640 x.extend(
641 self.embed[t * h..(t + 1) * h]
642 .iter()
643 .map(|&b| bf16_to_f32(b)),
644 );
645 }
646 // The stroke graph's head slot 0 pointed at the row (its prefill buffers serve every row), or
647 // the row's own graph when the strokes are off.
648 let row = &mut self.rows[r];
649 let g: &mut Q36Graph = match self.row_stroke.as_mut() {
650 Some(sg) => {
651 let (gd, a) = (
652 row.gdn.as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw),
653 row.attn
654 .as_ref()
655 .map_or(std::ptr::null_mut(), Attn256Cache::as_raw),
656 );
657 // SAFETY: the row's state lives in `self.rows`, which outlives the stroke graph.
658 unsafe { sg.set_head_state(0, gd, a) }
659 .map_err(gpu("prefill_row set_head_state"))?;
660 sg
661 }
662 None => &mut row.graph,
663 };
664 if g.prefill_cap() < n {
665 g.prefill_alloc(q::PREFILL_MAX_ROWS)
666 .map_err(gpu("prefill_row alloc"))?;
667 }
668 g.set_exact_head_on(!logits);
669 let (token, stats) = g.prefill(0, &x, pos, true).map_err(gpu("prefill_row"))?;
670 let out_logits = if logits {
671 let mut l = vec![0f32; v];
672 g.read_head(0, None, None, Some(&mut l))
673 .map_err(gpu("prefill_row read logits"))?;
674 Some(l)
675 } else {
676 None
677 };
678 self.rows[r].pos += n;
679 Ok(RowOut {
680 token: token.ok_or("prefill_row: no token")?,
681 logits: out_logits,
682 stats,
683 })
684 }
685}
686
687/// The row-swap negative control fires once per process.
688static ROW_SWAPPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
689
690fn row_swap_step() -> Option<u64> {
691 std::env::var("AIEN_Q36_TEST_ROW_SWAP")
692 .ok()
693 .and_then(|v| v.parse::<u64>().ok())
694}
695
696/// Strokes for the rows (`AIEN_Q36_STROKE=0`: each row's own one-row graph, in turn).
697fn stroke_on() -> bool {
698 std::env::var("AIEN_Q36_STROKE").as_deref() != Ok("0")
699}
700
701fn batch_on() -> bool {
702 std::env::var("AIEN_Q36_STROKE_V2").as_deref() != Ok("0")
703}