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

915 lines · 33202 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//! OWN-8B stage 2: the dense Qwen3 forward pass on Omega (design
17//! `~/handoffs/2026-10-15-own8b-design.md`, sections 2.2 to 2.4, stage table row 2).
18//!
19//! [`Qwen3DenseOmegaEngine`] runs a dense Qwen3 checkpoint (Qwen3-8B FP8, Qwen3-4B bf16 with tied
20//! embeddings, any shape the loader accepts) one sequence at a time:
21//!
22//! - decode [`Qwen3DenseOmegaEngine::step`]: host RMSNorm, one projection launch for q|k|v, host
23//! q/k per-head norms and RoPE, the K/V row into the paged bf16 pool, one paged attention launch,
24//! one launch each for o, gate|up and down, host SwiGLU and residuals; final norm on the host.
25//! FP8 projections run omega's block-scaled FP8 GEMV, bf16 projections omega's bf16 streaming
26//! GEMV (the design's kernel map, section 1.4); the lm_head is the bf16 GEMV in both formats
27//! ([`Qwen3DenseOmegaEngine::logits`]).
28//! - prefill [`Qwen3DenseOmegaEngine::step_batch`]: the same layer over `m` rows. An FP8 projection
29//! runs omega's FP8 GEMM in place (`m <= 1024`, "bit-identical to calling the GEMV once per
30//! row", `omega_gpu_fp8gemm_api.h:19-21`), a bf16 projection the GEMV once per row; attention is
31//! the split path, one launch per row.
32//! - [`Qwen3DenseOmegaEngine::generate_with`]: prefix reuse, prefill, sampling through a caller's
33//! sampler, stop ids, cancel; [`Qwen3DenseOmegaEngine::rewind`] and KV export/restore as the 30B.
34//!
35//! The same engine runs on the host ([`HostDenseUploader`] + [`HostPoolKv`]): that is oracle A of
36//! section 2.4 (same code, host GEMVs, same bf16 KV rounding), compared layer by layer through
37//! [`DenseLayerTrace`]. Negative controls: [`MutantUploader`] (k|v row swap, FP8 scale-grid
38//! transpose), the attention mutant ([`Qwen3DenseOmegaEngine::attention_mutant`]) and omega's
39//! kernel mutants (`aien_omega_fp8::test_set_mutant`, `aien_omega_bf16::test_set_mutant`).
40
41use std::path::Path;
42use std::sync::{Arc, Mutex};
43use std::time::Instant;
44
45use super::{
46 load_qwen3_dense_omega, DenseGemv, DenseLoadReport, DenseTensor, DenseUploader, HostFp8Gemv,
47 Qwen3DenseConfig, Qwen3DenseOmegaWeights,
48};
49use crate::qwen3_coder::rmsnorm_per_head;
50use crate::qwen3_moe::FP8_BLOCK;
51use crate::qwen3_moe_omega::{
52 sample_next, FinishReason, GenerateOutcome, GenerateParams, HostPoolKv, KvAttention,
53 KvGeometry, OmegaPagedKv, StepTiming,
54};
55use crate::tensor::{apply_rope, rmsnorm};
56
57// ---------------------------------------------------------------------------
58// Device and host GEMVs.
59// ---------------------------------------------------------------------------
60
61/// omega's bf16 streaming GEMV over one `[n][k]` matrix (projections of a bf16 checkpoint and
62/// every lm_head), behind a lock (`Bf16Tensor` is not `Sync`). The kernel stages x in shared memory
63/// (k * 4 bytes, at most 16384: omega_blackwell_qmd.h `OMEGA_BW_QMD_MAX_SHARED_BYTES`), so a wider
64/// matrix is held as column slices of at most `BF16_MAX_SLICE_K` and their partial sums are added
65/// in slice order (Qwen3-4B down: k 9728 = 4096 + 4096 + 1536).
66#[derive(Debug)]
67pub struct OmegaBf16Gemv(Mutex<Vec<aien_omega_bf16::Bf16Tensor>>, usize, usize);
68
69/// Widest x one bf16 launch stages: 16384 shared bytes / 4.
70pub const BF16_MAX_SLICE_K: usize = 4096;
71
72impl DenseGemv for OmegaBf16Gemv {
73 fn n(&self) -> usize {
74 self.1
75 }
76 fn k(&self) -> usize {
77 self.2
78 }
79 fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result<u64, String> {
80 let slices = self.0.lock().map_err(|_| "bf16 tensor lock poisoned")?;
81 if let [t] = slices.as_slice() {
82 return Ok(t.gemv_f32(x, y).map_err(|e| e.to_string())?.elapsed_ns);
83 }
84 let mut part = vec![0f32; y.len()];
85 let mut ns = 0;
86 for (i, t) in slices.iter().enumerate() {
87 let c0 = i * BF16_MAX_SLICE_K;
88 let c1 = (c0 + BF16_MAX_SLICE_K).min(self.2);
89 let out = if i == 0 { &mut *y } else { &mut part[..] };
90 ns += t
91 .gemv_f32(&x[c0..c1], out)
92 .map_err(|e| e.to_string())?
93 .elapsed_ns;
94 if i > 0 {
95 y.iter_mut().zip(&part).for_each(|(a, b)| *a += b);
96 }
97 }
98 Ok(ns)
99 }
100}
101
102/// omega's FP8 block-scaled GEMV (decode) and FP8 GEMM (prefill) over one `[n][k]` projection
103/// uploaded as a one-expert tensor, behind a lock.
104#[derive(Debug)]
105pub struct OmegaFp8DenseGemv(Mutex<aien_omega_fp8::Fp8Tensor>, usize, usize);
106
107impl DenseGemv for OmegaFp8DenseGemv {
108 fn n(&self) -> usize {
109 self.1
110 }
111 fn k(&self) -> usize {
112 self.2
113 }
114 fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result<u64, String> {
115 let t = self.0.lock().map_err(|_| "fp8 tensor lock poisoned")?;
116 let info = t.gemv_f32(0, x, y).map_err(|e| e.to_string())?;
117 Ok(info.elapsed_ns)
118 }
119 fn rows_f32(&self, m: usize, x: &[f32], y: &mut [f32]) -> Result<(u64, u64), String> {
120 if m <= 1 || !aien_omega_fp8::has_gemm() {
121 return rows_by_gemv(self, m, x, y);
122 }
123 let (n, k) = (self.1, self.2);
124 check_rows(n, k, m, x, y)?;
125 let t = self.0.lock().map_err(|_| "fp8 tensor lock poisoned")?;
126 let (mut ns, mut launches) = (0u64, 0u64);
127 let mut r0 = 0usize;
128 while r0 < m {
129 let rows = (m - r0).min(aien_omega_fp8::GEMM_MAX_ROWS);
130 let ids = vec![0u32; rows];
131 let token_rows: Vec<u32> = (0..rows as u32).collect();
132 let info = t
133 .gemm_f32(
134 &ids,
135 &token_rows,
136 &x[r0 * k..(r0 + rows) * k],
137 &mut y[r0 * n..(r0 + rows) * n],
138 )
139 .map_err(|e| e.to_string())?;
140 ns += info.elapsed_ns;
141 launches += 1;
142 r0 += rows;
143 }
144 Ok((ns, launches))
145 }
146}
147
148fn check_rows(n: usize, k: usize, m: usize, x: &[f32], y: &[f32]) -> Result<(), String> {
149 if x.len() != m * k || y.len() != m * n {
150 return Err(format!(
151 "rows [{n}][{k}] x {m}: given x {} y {}",
152 x.len(),
153 y.len()
154 ));
155 }
156 Ok(())
157}
158
159/// The default multi-row path: the GEMV once per row, in row order.
160pub fn rows_by_gemv<G: DenseGemv + ?Sized>(
161 g: &G,
162 m: usize,
163 x: &[f32],
164 y: &mut [f32],
165) -> Result<(u64, u64), String> {
166 let (n, k) = (g.n(), g.k());
167 check_rows(n, k, m, x, y)?;
168 let mut ns = 0u64;
169 for (xr, yr) in x.chunks_exact(k).zip(y.chunks_exact_mut(n)) {
170 ns += g.gemv_f32(xr, yr)?;
171 }
172 Ok((ns, m as u64))
173}
174
175/// One `[n][k]` bf16 matrix on the host, in the omega bf16 GEMV's f32 schedule (pin `a647b6a9`):
176/// lane chunks of 8, FFMA along the lane, SHFL.DOWN, and slices of 4096 columns added in order.
177/// Rows run in parallel. The kernel was not changed. This is the bf16 half of oracle A.
178#[derive(Debug)]
179pub struct HostBf16Gemv {
180 n: usize,
181 k: usize,
182 bits: Vec<u16>,
183}
184
185impl HostBf16Gemv {
186 pub fn new(n: usize, k: usize, bits: Vec<u16>) -> Result<Self, String> {
187 if bits.len() != n * k {
188 return Err(format!("{} words for [{n}][{k}]", bits.len()));
189 }
190 Ok(Self { n, k, bits })
191 }
192 /// The stored `[n][k]` bf16 words.
193 pub fn bits(&self) -> &[u16] {
194 &self.bits
195 }
196}
197
198impl DenseGemv for HostBf16Gemv {
199 fn n(&self) -> usize {
200 self.n
201 }
202 fn k(&self) -> usize {
203 self.k
204 }
205 fn gemv_f32(&self, x: &[f32], y: &mut [f32]) -> Result<u64, String> {
206 let k = self.k;
207 if x.len() != k || y.len() != self.n {
208 return Err(format!(
209 "gemv [{}][{k}] given x {} y {}",
210 self.n,
211 x.len(),
212 y.len()
213 ));
214 }
215 super::bf16_kernel_gemv(&self.bits, self.n, k, x, y)?;
216 Ok(0)
217 }
218}
219
220/// Keeps every matrix on the host (oracle A): bf16 as [`HostBf16Gemv`], FP8 as [`HostFp8Gemv`]
221/// (the chip's formula).
222#[derive(Debug, Default)]
223pub struct HostDenseUploader;
224
225impl DenseUploader for HostDenseUploader {
226 fn upload_bf16(
227 &self,
228 _layer: Option<usize>,
229 _what: DenseTensor,
230 n: usize,
231 k: usize,
232 bits: &[u16],
233 ) -> Result<Arc<dyn DenseGemv>, String> {
234 Ok(Arc::new(HostBf16Gemv::new(n, k, bits.to_vec())?))
235 }
236 fn upload_fp8(
237 &self,
238 _layer: Option<usize>,
239 _what: DenseTensor,
240 n: usize,
241 k: usize,
242 w: &[u8],
243 scales: &[u16],
244 ) -> Result<Arc<dyn DenseGemv>, String> {
245 Ok(Arc::new(HostFp8Gemv::new(
246 n,
247 k,
248 w.to_vec(),
249 scales.to_vec(),
250 )?))
251 }
252}
253
254/// Makes every matrix resident on the GB10: bf16 through omega's `Bf16Tensor` (NaN/Inf refused at
255/// upload), FP8 through omega's `Fp8Tensor` with one expert (NaN codes refused at upload).
256#[derive(Debug, Default)]
257pub struct OmegaDenseUploader;
258
259impl OmegaDenseUploader {
260 /// Whether this binary links omega's bf16 GEMV and FP8 GEMV (else every upload is refused).
261 pub fn native() -> (bool, bool) {
262 (aien_omega_bf16::is_native(), aien_omega_fp8::is_native())
263 }
264}
265
266impl DenseUploader for OmegaDenseUploader {
267 fn upload_bf16(
268 &self,
269 _layer: Option<usize>,
270 _what: DenseTensor,
271 n: usize,
272 k: usize,
273 bits: &[u16],
274 ) -> Result<Arc<dyn DenseGemv>, String> {
275 if !aien_omega_bf16::is_native() {
276 return Err(
277 "this binary carries no omega bf16 GEMV (built without AIEN_OMEGA_DIR)".into(),
278 );
279 }
280 let mut slices = Vec::new();
281 for c0 in (0..k).step_by(BF16_MAX_SLICE_K) {
282 let w = BF16_MAX_SLICE_K.min(k - c0);
283 let t = if w == k {
284 aien_omega_bf16::Bf16Tensor::upload(n, k, bits)
285 } else {
286 let cols: Vec<u16> = bits
287 .chunks_exact(k)
288 .flat_map(|row| &row[c0..c0 + w])
289 .copied()
290 .collect();
291 aien_omega_bf16::Bf16Tensor::upload(n, w, &cols)
292 };
293 slices.push(t.map_err(|e| e.to_string())?);
294 }
295 Ok(Arc::new(OmegaBf16Gemv(Mutex::new(slices), n, k)))
296 }
297 fn upload_fp8(
298 &self,
299 _layer: Option<usize>,
300 _what: DenseTensor,
301 n: usize,
302 k: usize,
303 w: &[u8],
304 scales: &[u16],
305 ) -> Result<Arc<dyn DenseGemv>, String> {
306 if !aien_omega_fp8::is_native() {
307 return Err(
308 "this binary carries no omega FP8 GEMV (built without AIEN_OMEGA_DIR)".into(),
309 );
310 }
311 let t = aien_omega_fp8::Fp8Tensor::upload(1, n, k, w, scales).map_err(|e| e.to_string())?;
312 Ok(Arc::new(OmegaFp8DenseGemv(Mutex::new(t), n, k)))
313 }
314}
315
316/// A deliberately wrong upload (negative controls of stage 2).
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum DenseUploadMutant {
319 /// q|k|v stored with the k rows and the v rows exchanged (FP8: the bytes and the scale rows).
320 SwapKv,
321 /// FP8 only: every scale grid `[a][b]` stored as the transpose of the grid read as `[b][a]`.
322 TransposeScales,
323}
324
325impl DenseUploadMutant {
326 pub fn parse(s: &str) -> Result<Self, String> {
327 match s {
328 "swap-kv" => Ok(Self::SwapKv),
329 "transpose-scales" => Ok(Self::TransposeScales),
330 other => Err(format!(
331 "unknown upload mutant {other:?} (swap-kv, transpose-scales)"
332 )),
333 }
334 }
335}
336
337/// Wraps an uploader and applies a [`DenseUploadMutant`] to what it uploads.
338pub struct MutantUploader<'a> {
339 pub inner: &'a dyn DenseUploader,
340 pub mutant: DenseUploadMutant,
341 pub q_rows: usize,
342 pub kv_rows: usize,
343 /// The checkpoint is FP8 (its lm_head is still bf16).
344 pub fp8: bool,
345}
346
347impl<'a> MutantUploader<'a> {
348 pub fn new(
349 inner: &'a dyn DenseUploader,
350 mutant: DenseUploadMutant,
351 c: &Qwen3DenseConfig,
352 ) -> Self {
353 Self {
354 inner,
355 mutant,
356 q_rows: c.q_dim(),
357 kv_rows: c.kv_dim(),
358 fp8: c.format == super::DenseWeightFormat::Fp8Block128,
359 }
360 }
361}
362
363/// Exchanges rows `a..a+rows` and `b..b+rows` (`a + rows <= b`) of a row-major `width` matrix.
364fn swap_rows<T>(m: &mut [T], width: usize, a: usize, b: usize, rows: usize) {
365 let (lo, hi) = m.split_at_mut(b * width);
366 lo[a * width..(a + rows) * width].swap_with_slice(&mut hi[..rows * width]);
367}
368
369impl DenseUploader for MutantUploader<'_> {
370 fn upload_bf16(
371 &self,
372 layer: Option<usize>,
373 what: DenseTensor,
374 n: usize,
375 k: usize,
376 bits: &[u16],
377 ) -> Result<Arc<dyn DenseGemv>, String> {
378 if self.mutant == DenseUploadMutant::SwapKv && what == DenseTensor::Qkv {
379 let mut b = bits.to_vec();
380 swap_rows(
381 &mut b,
382 k,
383 self.q_rows,
384 self.q_rows + self.kv_rows,
385 self.kv_rows,
386 );
387 return self.inner.upload_bf16(layer, what, n, k, &b);
388 }
389 if self.mutant == DenseUploadMutant::TransposeScales && !self.fp8 {
390 return Err("the transpose-scales mutant needs an FP8 checkpoint".into());
391 }
392 self.inner.upload_bf16(layer, what, n, k, bits)
393 }
394 fn upload_fp8(
395 &self,
396 layer: Option<usize>,
397 what: DenseTensor,
398 n: usize,
399 k: usize,
400 w: &[u8],
401 scales: &[u16],
402 ) -> Result<Arc<dyn DenseGemv>, String> {
403 let (mut w2, mut s2) = (w.to_vec(), scales.to_vec());
404 let (a, b) = (n / FP8_BLOCK, k / FP8_BLOCK);
405 match self.mutant {
406 DenseUploadMutant::SwapKv if what == DenseTensor::Qkv => {
407 let (q, kv) = (self.q_rows, self.kv_rows);
408 swap_rows(&mut w2, k, q, q + kv, kv);
409 swap_rows(
410 &mut s2,
411 b,
412 q / FP8_BLOCK,
413 (q + kv) / FP8_BLOCK,
414 kv / FP8_BLOCK,
415 );
416 }
417 DenseUploadMutant::SwapKv => {}
418 DenseUploadMutant::TransposeScales => {
419 for r in 0..a {
420 for c in 0..b {
421 s2[r * b + c] = scales[c * a + r];
422 }
423 }
424 }
425 }
426 self.inner.upload_fp8(layer, what, n, k, &w2, &s2)
427 }
428}
429
430// ---------------------------------------------------------------------------
431// The engine.
432// ---------------------------------------------------------------------------
433
434/// What one traced layer did for one position (oracle A compares these between the chip engine
435/// and the host engine).
436#[derive(Debug, Clone, PartialEq)]
437pub struct DenseLayerTrace {
438 pub layer: usize,
439 pub pos: usize,
440 pub x_in: Vec<f32>,
441 /// Attention output before o (`[q_heads x head_dim]`).
442 pub attn: Vec<f32>,
443 /// o projection of `attn`.
444 pub attn_proj: Vec<f32>,
445 /// Post-attention RMSNorm of the residual (the MLP input).
446 pub post: Vec<f32>,
447 /// down(SwiGLU(gate|up(post))).
448 pub mlp_out: Vec<f32>,
449 pub x_out: Vec<f32>,
450}
451
452/// Every run setting of a [`Qwen3DenseOmegaEngine`] that can change a K/V byte (persistent KV
453/// identity, as `OmegaKvSwitches` for the 30B; fail closed).
454#[derive(Debug, Clone, Copy, PartialEq, Eq)]
455pub struct DenseKvSwitches {
456 pub attention_path: &'static str,
457 /// Rows per prefill launch (the FP8 GEMM is bit-equal to the GEMV, listed anyway).
458 pub prefill_chunk: usize,
459 pub attention_mutant: bool,
460 pub trace_layers: bool,
461}
462
463/// Most prompt tokens one [`Qwen3DenseOmegaEngine::step_batch`] layer pass takes by default (one
464/// FP8 GEMM launch per projection, `GEMM_MAX_ROWS`).
465pub const DENSE_PREFILL_CHUNK: usize = aien_omega_fp8::GEMM_MAX_ROWS;
466
467/// The dense Qwen3 engine: one sequence, decode by `step`, prefill by `step_batch`.
468pub struct Qwen3DenseOmegaEngine {
469 weights: Qwen3DenseOmegaWeights,
470 kv: Box<dyn KvAttention>,
471 /// Layers whose activations are recorded into `traces`.
472 pub trace_layers: Vec<usize>,
473 pub traces: Vec<DenseLayerTrace>,
474 /// Negative control: attention over `0..pos` instead of `0..=pos` (the newest position dropped,
475 /// off by one; position 0 still sees itself). Layer parity and tokens must then fail.
476 pub attention_mutant: bool,
477 pub last_timing: StepTiming,
478 /// Prompt tokens per `step_batch` pass inside `generate_with` (1 = token at a time).
479 pub prefill_chunk: usize,
480 pos: usize,
481 history: Vec<u32>,
482}
483
484impl Qwen3DenseOmegaEngine {
485 /// The cache must have the config's geometry.
486 pub fn new(weights: Qwen3DenseOmegaWeights, kv: Box<dyn KvAttention>) -> Result<Self, String> {
487 let want = KvGeometry::from(&weights.config);
488 let have = kv.geometry();
489 if have != want {
490 return Err(format!(
491 "kv cache geometry {have:?} is not the model's {want:?}"
492 ));
493 }
494 Ok(Self {
495 weights,
496 kv,
497 trace_layers: Vec::new(),
498 traces: Vec::new(),
499 attention_mutant: false,
500 last_timing: StepTiming::default(),
501 prefill_chunk: DENSE_PREFILL_CHUNK,
502 pos: 0,
503 history: Vec::new(),
504 })
505 }
506
507 /// Loads `dir` through `uploader` with the chip's paged bf16 KV of `max_context` tokens.
508 pub fn load_omega(
509 dir: &Path,
510 uploader: &dyn DenseUploader,
511 max_context: usize,
512 progress: &mut dyn FnMut(&str),
513 ) -> Result<(Self, DenseLoadReport), String> {
514 let (weights, report) = load_qwen3_dense_omega(dir, uploader, progress)?;
515 let kv = OmegaPagedKv::new(&KvGeometry::from(&weights.config), max_context)?;
516 Ok((Self::new(weights, Box::new(kv))?, report))
517 }
518
519 /// Loads `dir` on the host (oracle A): host GEMVs, the host bf16 pool and its attention.
520 pub fn load_host(
521 dir: &Path,
522 uploader: &dyn DenseUploader,
523 max_context: usize,
524 progress: &mut dyn FnMut(&str),
525 ) -> Result<(Self, DenseLoadReport), String> {
526 let (weights, report) = load_qwen3_dense_omega(dir, uploader, progress)?;
527 let kv = HostPoolKv::new(&KvGeometry::from(&weights.config), max_context)?;
528 Ok((Self::new(weights, Box::new(kv))?, report))
529 }
530
531 pub fn config(&self) -> &Qwen3DenseConfig {
532 &self.weights.config
533 }
534 pub fn weights(&self) -> &Qwen3DenseOmegaWeights {
535 &self.weights
536 }
537 /// "split" (chip paged attention), "host-pool" (oracle) or a test cache's name.
538 pub fn attention_path(&self) -> &'static str {
539 self.kv.path_name()
540 }
541 pub fn max_context_tokens(&self) -> usize {
542 self.kv.capacity()
543 }
544 pub fn kv_resident(&self) -> bool {
545 self.kv.resident()
546 }
547 /// Tokens already in the KV.
548 pub fn position(&self) -> usize {
549 self.pos
550 }
551 /// Tokens whose KV is stored (positions `0..position()`).
552 pub fn history(&self) -> &[u32] {
553 &self.history
554 }
555
556 pub fn reset(&mut self) {
557 self.kv.truncate(0);
558 self.pos = 0;
559 self.history.clear();
560 self.traces.clear();
561 }
562
563 /// Keeps the first `len` stored tokens; the next step is at `len`.
564 pub fn rewind(&mut self, len: usize) {
565 let len = len.min(self.pos);
566 self.kv.truncate(len);
567 self.history.truncate(len);
568 self.pos = len;
569 }
570
571 /// The longest common prefix of the stored history and `prompt`, capped at
572 /// `prompt.len() - 1` (the last prompt token is always stepped).
573 pub fn reusable_prefix(&self, prompt: &[u32]) -> usize {
574 let common = self
575 .history
576 .iter()
577 .zip(prompt)
578 .take_while(|(a, b)| a == b)
579 .count();
580 common.min(prompt.len().saturating_sub(1))
581 }
582
583 /// The K/V of stored positions `start..start + len` as the `kvio` payload.
584 pub fn export_kv(&mut self, start: usize, len: usize) -> Result<Vec<u8>, String> {
585 if start + len > self.pos {
586 return Err(format!(
587 "kv export {start}+{len}: only {} positions stored",
588 self.pos
589 ));
590 }
591 self.kv.export_blocks(start, len).unwrap_or_else(|| {
592 Err(format!(
593 "the {} attention cache cannot export its KV",
594 self.kv.path_name()
595 ))
596 })
597 }
598
599 /// Replaces the stored sequence by `tokens` with the K/V of `payload`; on error the engine
600 /// is reset.
601 pub fn restore_kv(&mut self, tokens: &[u32], payload: &[u8]) -> Result<(), String> {
602 self.reset();
603 if tokens.is_empty() || tokens.len() >= self.kv.capacity() {
604 return Err(format!(
605 "kv restore of {} tokens, context is {}",
606 tokens.len(),
607 self.kv.capacity()
608 ));
609 }
610 let r = self
611 .kv
612 .import_blocks(0, tokens.len(), payload)
613 .unwrap_or_else(|| {
614 Err(format!(
615 "the {} attention cache cannot import KV",
616 self.kv.path_name()
617 ))
618 });
619 match r {
620 Ok(()) => {
621 self.history = tokens.to_vec();
622 self.pos = tokens.len();
623 Ok(())
624 }
625 Err(e) => {
626 self.reset();
627 Err(e)
628 }
629 }
630 }
631
632 pub fn kv_switches(&self) -> DenseKvSwitches {
633 DenseKvSwitches {
634 attention_path: self.kv.path_name(),
635 prefill_chunk: self.prefill_chunk,
636 attention_mutant: self.attention_mutant,
637 trace_layers: !self.trace_layers.is_empty(),
638 }
639 }
640
641 /// Decode: runs `token` at the next position through every layer and returns the final-normed
642 /// hidden state (feed it to [`Self::logits`]). Records `last_timing`.
643 pub fn step(&mut self, token: u32) -> Result<Vec<f32>, String> {
644 self.forward(&[token])
645 }
646
647 /// Prefill: runs `tokens` at the next positions, every layer over all rows at once (FP8: one
648 /// GEMM launch per projection per 1024 rows), and returns the final-normed hidden state of
649 /// the last token. Bit-equal to `step` once per token wherever the multi-row kernel is
650 /// bit-equal to the GEMV (omega's FP8 GEMM, every host path).
651 pub fn step_batch(&mut self, tokens: &[u32]) -> Result<Vec<f32>, String> {
652 if tokens.is_empty() {
653 return Err("step_batch of no tokens".into());
654 }
655 self.forward(tokens)
656 }
657
658 fn forward(&mut self, tokens: &[u32]) -> Result<Vec<f32>, String> {
659 let t_step = Instant::now();
660 let mut timing = StepTiming::default();
661 let c = &self.weights.config;
662 let (h, qd, kvd, hd, eps) = (c.hidden, c.q_dim(), c.kv_dim(), c.head_dim, c.rms_eps);
663 let (inter, qkv_n) = (c.intermediate, c.qkv_n());
664 let (qh, kvh, theta) = (c.q_heads, c.kv_heads, c.rope_theta);
665 let m = tokens.len();
666 let p0 = self.pos;
667 if p0 + m > self.kv.capacity() {
668 return Err(format!(
669 "context full: {p0} + {m} of {}",
670 self.kv.capacity()
671 ));
672 }
673 let mut x = Vec::with_capacity(m * h);
674 for &t in tokens {
675 x.extend(self.weights.embed_row(t)?);
676 }
677 let mut xn = vec![0.0f32; m * h];
678 let mut qkv = vec![0.0f32; m * qkv_n];
679 let mut qn = vec![0.0f32; m * qd];
680 let mut kn = vec![0.0f32; kvd];
681 let mut attn = vec![0.0f32; m * qd];
682 let mut attn_proj = vec![0.0f32; m * h];
683 let mut gu = vec![0.0f32; m * 2 * inter];
684 let mut act = vec![0.0f32; m * inter];
685 let mut mlp = vec![0.0f32; m * h];
686
687 let rows = |g: &Arc<dyn DenseGemv>,
688 x: &[f32],
689 y: &mut [f32],
690 timing: &mut StepTiming|
691 -> Result<(), String> {
692 let (ns, launches) = if m == 1 {
693 (g.gemv_f32(x, y)?, 1)
694 } else {
695 g.rows_f32(m, x, y)?
696 };
697 timing.chip_ns += ns;
698 timing.launches += launches;
699 Ok(())
700 };
701
702 for (li, layer) in self.weights.layers.iter().enumerate() {
703 let traced = self.trace_layers.contains(&li);
704 let x_in = if traced { x.clone() } else { Vec::new() };
705
706 // --- attention ---
707 let t0 = Instant::now();
708 for (xr, or) in x.chunks_exact(h).zip(xn.chunks_exact_mut(h)) {
709 rmsnorm(xr, &layer.input_norm, eps, or);
710 }
711 timing.host_ns += t0.elapsed().as_nanos() as u64;
712 let t1 = Instant::now();
713 rows(&layer.qkv, &xn, &mut qkv, &mut timing)
714 .map_err(|e| format!("layer {li} qkv: {e}"))?;
715 for r in 0..m {
716 let th = Instant::now();
717 let row = &qkv[r * qkv_n..(r + 1) * qkv_n];
718 let q = &mut qn[r * qd..(r + 1) * qd];
719 rmsnorm_per_head(&row[..qd], &layer.q_norm, eps, qh, hd, q);
720 rmsnorm_per_head(&row[qd..qd + kvd], &layer.k_norm, eps, kvh, hd, &mut kn);
721 let pos = p0 + r;
722 apply_rope(q, &mut kn, pos, qh, kvh, hd, theta);
723 self.kv.append(li, pos, &kn, &row[qd + kvd..])?;
724 timing.host_ns += th.elapsed().as_nanos() as u64;
725 }
726 for r in 0..m {
727 // The mutant drops the newest position (off by one), except at position 0.
728 let ctx = if self.attention_mutant {
729 (p0 + r).max(1)
730 } else {
731 p0 + r + 1
732 };
733 timing.chip_ns += self.kv.attend(
734 li,
735 &qn[r * qd..(r + 1) * qd],
736 ctx,
737 &mut attn[r * qd..(r + 1) * qd],
738 )?;
739 timing.launches += 1;
740 }
741 rows(&layer.o, &attn, &mut attn_proj, &mut timing)
742 .map_err(|e| format!("layer {li} o: {e}"))?;
743 timing.attention_ns += t1.elapsed().as_nanos() as u64;
744
745 // --- residual, post norm, MLP ---
746 let t2 = Instant::now();
747 for (xi, p) in x.iter_mut().zip(&attn_proj) {
748 *xi += p;
749 }
750 for (xr, or) in x.chunks_exact(h).zip(xn.chunks_exact_mut(h)) {
751 rmsnorm(xr, &layer.post_norm, eps, or);
752 }
753 timing.host_ns += t2.elapsed().as_nanos() as u64;
754 let t3 = Instant::now();
755 rows(&layer.gate_up, &xn, &mut gu, &mut timing)
756 .map_err(|e| format!("layer {li} gate_up: {e}"))?;
757 let th = Instant::now();
758 for (g, a) in gu.chunks_exact(2 * inter).zip(act.chunks_exact_mut(inter)) {
759 swiglu(g, inter, a);
760 }
761 timing.host_ns += th.elapsed().as_nanos() as u64;
762 rows(&layer.down, &act, &mut mlp, &mut timing)
763 .map_err(|e| format!("layer {li} down: {e}"))?;
764 for (xi, d) in x.iter_mut().zip(&mlp) {
765 *xi += d;
766 }
767 timing.experts_ns += t3.elapsed().as_nanos() as u64;
768
769 if traced {
770 for r in 0..m {
771 let s = |v: &[f32], w: usize| v[r * w..(r + 1) * w].to_vec();
772 self.traces.push(DenseLayerTrace {
773 layer: li,
774 pos: p0 + r,
775 x_in: s(&x_in, h),
776 attn: s(&attn, qd),
777 attn_proj: s(&attn_proj, h),
778 post: s(&xn, h),
779 mlp_out: s(&mlp, h),
780 x_out: s(&x, h),
781 });
782 }
783 }
784 }
785 let t4 = Instant::now();
786 let mut hidden = vec![0.0f32; h];
787 rmsnorm(
788 &x[(m - 1) * h..],
789 &self.weights.final_norm,
790 eps,
791 &mut hidden,
792 );
793 timing.host_ns += t4.elapsed().as_nanos() as u64;
794 self.pos = p0 + m;
795 self.history.extend_from_slice(tokens);
796 timing.total_ns = t_step.elapsed().as_nanos() as u64;
797 self.last_timing = timing;
798 Ok(hidden)
799 }
800
801 /// Vocabulary logits of a final hidden state (one lm_head launch), added to `last_timing`.
802 pub fn logits(&mut self, hidden: &[f32]) -> Result<Vec<f32>, String> {
803 let t0 = Instant::now();
804 let mut logits = vec![0.0f32; self.weights.config.vocab];
805 let ns = self
806 .weights
807 .lm_head
808 .gemv_f32(hidden, &mut logits)
809 .map_err(|e| format!("lm_head: {e}"))?;
810 let dt = t0.elapsed().as_nanos() as u64;
811 self.last_timing.lm_head_ns += dt;
812 self.last_timing.total_ns += dt;
813 self.last_timing.chip_ns += ns;
814 self.last_timing.launches += 1;
815 Ok(logits)
816 }
817
818 /// Prefill `prompt` (reusing the stored prefix) then decode with `sampler(logits, step)`;
819 /// `on_token` gets every emitted token and may return `false` to cancel. Stop ids are
820 /// consumed, never emitted.
821 pub fn generate_with(
822 &mut self,
823 prompt: &[u32],
824 params: &GenerateParams,
825 sampler: &mut dyn FnMut(&[f32], usize) -> u32,
826 on_token: &mut dyn FnMut(u32) -> bool,
827 ) -> Result<GenerateOutcome, String> {
828 if prompt.is_empty() {
829 return Err("empty prompt".into());
830 }
831 if prompt.len() >= self.kv.capacity() {
832 return Err(format!(
833 "prompt of {} tokens, context is {}",
834 prompt.len(),
835 self.kv.capacity()
836 ));
837 }
838 let reused = self.reusable_prefix(prompt);
839 if reused > 0 {
840 self.rewind(reused);
841 } else {
842 self.reset();
843 }
844 let t0 = Instant::now();
845 let mut hidden = Vec::new();
846 let mut prefill_timing = StepTiming::default();
847 for chunk in prompt[reused..].chunks(self.prefill_chunk.max(1)) {
848 hidden = self.step_batch(chunk)?;
849 prefill_timing.add(&self.last_timing);
850 }
851 let prefill_ms = t0.elapsed().as_millis() as u64;
852 self.last_timing = StepTiming::default();
853 let t1 = Instant::now();
854 let mut decode_timing = StepTiming::default();
855 let (mut emitted, mut step) = (0usize, 0usize);
856 let mut finish = FinishReason::Length;
857 while emitted < params.max_new_tokens {
858 let logits = self.logits(&hidden)?;
859 decode_timing.add(&self.last_timing);
860 let next = sampler(&logits, step);
861 step += 1;
862 if params.stop_token_ids.contains(&next) {
863 finish = FinishReason::Stop;
864 break;
865 }
866 emitted += 1;
867 if !on_token(next) {
868 finish = FinishReason::Cancelled;
869 break;
870 }
871 if emitted >= params.max_new_tokens || self.pos >= self.kv.capacity() {
872 break;
873 }
874 hidden = self.step(next)?;
875 }
876 Ok(GenerateOutcome {
877 emitted_tokens: emitted,
878 finish,
879 prefill_ms,
880 decode_ms: t1.elapsed().as_millis() as u64,
881 prompt_tokens: prompt.len(),
882 reused_prompt_tokens: reused,
883 decode_timing,
884 prefill_timing,
885 })
886 }
887
888 /// `generate_with` using [`sample_next`] (the door's sampling rule).
889 pub fn generate(
890 &mut self,
891 prompt: &[u32],
892 params: &GenerateParams,
893 on_token: &mut dyn FnMut(u32) -> bool,
894 ) -> Result<GenerateOutcome, String> {
895 let p = params.clone();
896 self.generate_with(
897 prompt,
898 params,
899 &mut |logits, step| sample_next(logits, &p, step),
900 on_token,
901 )
902 }
903}
904
905/// `act[j] = silu(gu[j]) * gu[i + j]` (gate rows first, then up rows).
906fn swiglu(gu: &[f32], i: usize, act: &mut [f32]) {
907 for j in 0..i {
908 let g = gu[j];
909 act[j] = g / (1.0 + (-g).exp()) * gu[i + j];
910 }
911}
912
913#[cfg(test)]
914#[path = "qwen3_dense_omega_engine_tests.rs"]
915mod tests;