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-inference-abi / src / qwen3_moe_omega_prefill.rs
| 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 OWN-30B (Qwen3-30B-A3B FP8) on omega's own prefill kernels |
| 17 | //! (W-L1G-R, 2026-10-14). New file; not wired into the engine or the server yet. |
| 18 | //! |
| 19 | //! One call takes the whole prompt (`m` tokens at consecutive positions `pos0 ..`) through every |
| 20 | //! layer with a fixed number of launches per layer, whatever `m` is: |
| 21 | //! |
| 22 | //! | step | where | launches | |
| 23 | //! |---|---|---| |
| 24 | //! | input RMSNorm | host | | |
| 25 | //! | quantise x (f32, k = hidden) | chip | 1 | |
| 26 | //! | q\|k\|v QMMA GEMM (PLAIN, 1 expert) | chip | 1 | |
| 27 | //! | attention for all m tokens ([`PrefillAttention`]) | chip | 1 call | |
| 28 | //! | quantise attention out (f32, k = 4096) | chip | 1 | |
| 29 | //! | o QMMA GEMM (PLAIN) | chip | 1 | |
| 30 | //! | residual, post RMSNorm, router logits, top-k ([`MoeBatchPlan`]) | host | | |
| 31 | //! | counting sort of the (token, expert) rows by expert ([`MoeBatchPlan`]) | host | | |
| 32 | //! | quantise post (f32, k = hidden) | chip | 1 | |
| 33 | //! | gate\|up QMMA GEMM, SWIGLU_NAT epilogue, rows gathered by token index | chip | 1 | |
| 34 | //! | quantise act (bf16, k = moe_intermediate) | chip | 1 | |
| 35 | //! | down QMMA GEMM (PLAIN, sorted rows) | chip | 1 | |
| 36 | //! | weighted combine + residual | host | | |
| 37 | //! |
| 38 | //! It returns the last token's final-normed hidden state (the lm_head input). |
| 39 | //! |
| 40 | //! Weights: the FP8 tensors the loader made resident ([`AttnWeights::Fp8`], [`ExpertWeights::Fp8`]) |
| 41 | //! are read IN PLACE: the tile tables carry each expert's `(w_va, s_va)` from |
| 42 | //! [`Fp8Gemv::tensor_entry`] (omega_gpu_fp8_tensor_entry), collected once at construction. |
| 43 | //! |
| 44 | //! Reused / reimplemented: routing and the expert sort are [`MoeBatchPlan::from_logits`] (public: |
| 45 | //! softmax, top-k, renormalise, then a stable counting sort by expert). The router logits and the |
| 46 | //! combine are REIMPLEMENTED here (the engine's `router_logits` / `combine_rows` are private), in |
| 47 | //! the same summation order. The tile table is `aien_omega_pf::build_tiles` (a Rust mirror of |
| 48 | //! `omega_gpu_pf_qgemm_tiles_va`, checked equal to the C builder in that crate's tests). |
| 49 | //! |
| 50 | //! Host <-> device traffic. The driver makes NO staging copies of its own: |
| 51 | //! * HOST buffers (GPU-uncached session memory, `omega_gpu_pf_alloc_host`) are written or read by |
| 52 | //! the CPU in place: the quantiser inputs (normed x, post; m x hidden f32 each), the tile tables |
| 53 | //! and the row index (small), and the two GEMM outputs the host needs (o projection m x hidden |
| 54 | //! f32, down rows g x hidden f32 with g = m * top_k). Rule nvos.h:1117: anything the host reads |
| 55 | //! or writes stays GPU-uncached. |
| 56 | //! * DEVICE buffers (GPU-cached, CPU never touches them): quantised activations and scales, the |
| 57 | //! SwiGLU act rows, and on the device-attention path the q|k|v rows and the attention output. |
| 58 | //! * Attention, host entry (`omega_gpu_prefill_attn`): q|k|v is read from and the output written |
| 59 | //! to HOST buffers; omega itself copies them through its staging buffers (inside the call). |
| 60 | //! The device entry (`omega_gpu_prefill_attn_dev`, taken when [`PrefillAttention::has_dev`]) |
| 61 | //! keeps both on the device: no copies. |
| 62 | //! |
| 63 | //! Per layer the CPU therefore touches about (3m + g) x hidden x 4 bytes of uncached memory; the |
| 64 | //! down readback (g x hidden) dominates. A device combine kernel would remove it (not in omega yet). |
| 65 | //! |
| 66 | //! Wiring into `Qwen3MoeOmegaEngine` (NOT done here; owner's steps): |
| 67 | //! 1. `OmegaFusedKv` (qwen3_moe_omega_dattn.rs): add `prefill_attention(&mut self) -> |
| 68 | //! aien_omega_pf::OmegaPrefillAttention<'_>` over its private `cache`, and `mark_filled(&mut |
| 69 | //! self, upto)` setting every layer's private `filled[l] = upto` (the prefill appends K/V for |
| 70 | //! `pos0 .. upto` in all layers, the fused decode step checks `pos == filled[layer]`). |
| 71 | //! 2. `KvAttention`: a way to reach that (e.g. `fn fused(&mut self) -> Option<&mut OmegaFusedKv>`, |
| 72 | //! default `None`), since the engine holds `kv: Box<dyn KvAttention>`. |
| 73 | //! 3. Engine: a field `whole_prompt: Option<WholePromptPrefill<aien_omega_pf::OmegaPfDevice>>`, |
| 74 | //! built in `new()` when `aien_omega_pf::is_native() && aien_omega_pf::has_attention()` and |
| 75 | //! [`layer_entries`] succeeds (FP8 everywhere, `Fp8Gemv::tensor_entry` linked). |
| 76 | //! 4. In `generate_with`, replace the `prompt[reused..].chunks(prefill_chunk)` loop when that |
| 77 | //! field is set and `trace_layers` is empty and `routing_mutant` is off: `pos0 = self.pos` |
| 78 | //! (after `rewind(reused)` / `reset()`), `hidden = wp.run(&self.weights, &mut |
| 79 | //! fused.prefill_attention(), &prompt[reused..], pos0)?`, then `fused.mark_filled(pos0 + m)`, |
| 80 | //! `self.pos = pos0 + m`, `self.history.extend_from_slice(&prompt[reused..])`, and map |
| 81 | //! `wp.stats` into `last_timing`. `pos0 + m < kv.capacity()` is already checked there. |
| 82 | //! 5. Routing here is host routing (no per-token device router launches). |
| 83 | use std::time::Instant; |
| 84 | |
| 85 | use aien_omega_pf::{ |
| 86 | build_tiles, Layout, PfBuffer, PrefillAttention, PrefillDevice, QgemmCall, QuantIn, TILE_BYTES, |
| 87 | }; |
| 88 | use rayon::prelude::*; |
| 89 | |
| 90 | use crate::moe_plan::MoeBatchPlan; |
| 91 | use crate::qwen3_moe_omega::{ |
| 92 | AttnWeights, ExpertWeights, Fp8Gemv, Qwen3MoeConfig, Qwen3MoeOmegaWeights, |
| 93 | }; |
| 94 | use crate::tensor::rmsnorm; |
| 95 | |
| 96 | /// Scale of the attention output (1.0: the quantiser picks its own power-of-two scales). |
| 97 | pub const ATTN_OUT_SCALE: f32 = 1.0; |
| 98 | |
| 99 | /// Device addresses of one layer's FP8 tensors, per expert `(w_va, s_va)`. |
| 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 101 | pub struct LayerEntries { |
| 102 | pub qkv: (u64, u64), |
| 103 | pub o: (u64, u64), |
| 104 | pub gu_w: Vec<u64>, |
| 105 | pub gu_s: Vec<u64>, |
| 106 | pub dn_w: Vec<u64>, |
| 107 | pub dn_s: Vec<u64>, |
| 108 | } |
| 109 | |
| 110 | fn check_tensor( |
| 111 | what: &str, |
| 112 | t: &dyn Fp8Gemv, |
| 113 | experts: usize, |
| 114 | n: usize, |
| 115 | k: usize, |
| 116 | ) -> Result<(), String> { |
| 117 | if t.experts() != experts || t.n() != n || t.k() != k { |
| 118 | return Err(format!( |
| 119 | "{what}: tensor is {} x [{}][{}], the whole-prompt path needs {experts} x [{n}][{k}]", |
| 120 | t.experts(), |
| 121 | t.n(), |
| 122 | t.k() |
| 123 | )); |
| 124 | } |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | /// Collects every layer's in-place weight addresses, checking the shapes the GEMMs assume. |
| 129 | pub fn layer_entries(weights: &Qwen3MoeOmegaWeights) -> Result<Vec<LayerEntries>, String> { |
| 130 | let c = &weights.config; |
| 131 | let (h, qd, e, i) = (c.hidden, c.q_dim(), c.experts, c.moe_intermediate); |
| 132 | if weights.layers.len() != c.layers { |
| 133 | return Err(format!( |
| 134 | "{} layers of weights, config says {}", |
| 135 | weights.layers.len(), |
| 136 | c.layers |
| 137 | )); |
| 138 | } |
| 139 | weights |
| 140 | .layers |
| 141 | .iter() |
| 142 | .enumerate() |
| 143 | .map(|(l, layer)| { |
| 144 | let (AttnWeights::Fp8 { qkv, o }, ExpertWeights::Fp8 { gate_up, down }) = (&layer.attn, &layer.experts) else { |
| 145 | return Err(format!("layer {l}: the whole-prompt path needs FP8 attention and experts (WeightFormat::Fp8All)")); |
| 146 | }; |
| 147 | check_tensor(&format!("layer {l} q|k|v"), qkv.as_ref(), 1, c.qkv_n(), h)?; |
| 148 | check_tensor(&format!("layer {l} o"), o.as_ref(), 1, h, qd)?; |
| 149 | check_tensor(&format!("layer {l} gate|up"), gate_up.as_ref(), e, 2 * i, h)?; |
| 150 | check_tensor(&format!("layer {l} down"), down.as_ref(), e, h, i)?; |
| 151 | let entry = |t: &dyn Fp8Gemv, ex: usize, what: &str| t.tensor_entry(ex).map_err(|err| format!("layer {l} {what} expert {ex} address: {err}")); |
| 152 | let (mut gu_w, mut gu_s, mut dn_w, mut dn_s) = (Vec::with_capacity(e), Vec::with_capacity(e), Vec::with_capacity(e), Vec::with_capacity(e)); |
| 153 | for ex in 0..e { |
| 154 | let (w, s) = entry(gate_up.as_ref(), ex, "gate|up")?; |
| 155 | gu_w.push(w); |
| 156 | gu_s.push(s); |
| 157 | let (w, s) = entry(down.as_ref(), ex, "down")?; |
| 158 | dn_w.push(w); |
| 159 | dn_s.push(s); |
| 160 | } |
| 161 | Ok(LayerEntries { qkv: entry(qkv.as_ref(), 0, "q|k|v")?, o: entry(o.as_ref(), 0, "o")?, gu_w, gu_s, dn_w, dn_s }) |
| 162 | }) |
| 163 | .collect() |
| 164 | } |
| 165 | |
| 166 | /// The (token, expert) rows grouped by expert, from a routing plan. |
| 167 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 168 | pub struct ExpertSort { |
| 169 | /// Rows of each expert, in expert order (the GEMM tile builder's `counts`). |
| 170 | pub counts: Vec<u32>, |
| 171 | /// Token of each sorted row (the gate|up GEMM's row index). |
| 172 | pub rows: Vec<u32>, |
| 173 | /// Sorted row of each token-major assignment `token * top_k + slot`. |
| 174 | pub inv: Vec<u32>, |
| 175 | } |
| 176 | |
| 177 | impl ExpertSort { |
| 178 | pub fn from_plan(plan: &MoeBatchPlan) -> Self { |
| 179 | Self { |
| 180 | counts: plan |
| 181 | .expert_offsets |
| 182 | .windows(2) |
| 183 | .map(|w| w[1] - w[0]) |
| 184 | .collect(), |
| 185 | rows: plan.grouped_token_ids.clone(), |
| 186 | inv: plan.assignment_to_grouped.clone(), |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | /// What a whole-prompt call did. Launch counters count calls into the device / attention. |
| 192 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 193 | pub struct PrefillStats { |
| 194 | pub tokens: usize, |
| 195 | pub layers: usize, |
| 196 | pub quant: usize, |
| 197 | pub qkv: usize, |
| 198 | pub attn: usize, |
| 199 | pub o: usize, |
| 200 | pub gate_up: usize, |
| 201 | pub down: usize, |
| 202 | /// Attention ran through the device-pointer entry. |
| 203 | pub attn_dev: bool, |
| 204 | pub chip_ns: u64, |
| 205 | pub attn_ns: u64, |
| 206 | pub host_ns: u64, |
| 207 | /// Host-time breakdown by phase (W-L1G-D profile), summed over layers. |
| 208 | pub prof: HostProf, |
| 209 | /// Device router-logits and combine launches (W-L1G-D device path; not in [`Self::launches`]). |
| 210 | pub router: usize, |
| 211 | pub combine: usize, |
| 212 | } |
| 213 | |
| 214 | /// Where the whole-prompt wall time goes (W-L1G-D, 2026-10-14): ns per phase, summed over layers. |
| 215 | /// `dev_ns` is the wall time of the device calls (quantiser, GEMMs, attention) including launch |
| 216 | /// overhead; the other fields are host work. `wall_ns` is the whole `run`. |
| 217 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 218 | pub struct HostProf { |
| 219 | pub embed_ns: u64, |
| 220 | pub norm_in_ns: u64, |
| 221 | pub resid_ns: u64, |
| 222 | pub norm_post_ns: u64, |
| 223 | pub router_ns: u64, |
| 224 | pub plan_ns: u64, |
| 225 | pub tiles_ns: u64, |
| 226 | pub combine_ns: u64, |
| 227 | pub final_ns: u64, |
| 228 | pub dev_ns: u64, |
| 229 | pub wall_ns: u64, |
| 230 | } |
| 231 | |
| 232 | impl PrefillStats { |
| 233 | pub fn launches(&self) -> usize { |
| 234 | self.quant + self.qkv + self.attn + self.o + self.gate_up + self.down |
| 235 | } |
| 236 | |
| 237 | /// Adds the counters of one more pass over the same prompt (chunked prefill): counts and |
| 238 | /// times sum, `layers` is the per-pass depth, `attn_dev` holds only if every pass used it. |
| 239 | pub fn absorb(&mut self, p: &PrefillStats) { |
| 240 | let first = self.tokens == 0 && self.layers == 0; |
| 241 | self.tokens += p.tokens; |
| 242 | self.layers = self.layers.max(p.layers); |
| 243 | self.quant += p.quant; |
| 244 | self.qkv += p.qkv; |
| 245 | self.attn += p.attn; |
| 246 | self.o += p.o; |
| 247 | self.gate_up += p.gate_up; |
| 248 | self.down += p.down; |
| 249 | self.attn_dev = if first { |
| 250 | p.attn_dev |
| 251 | } else { |
| 252 | self.attn_dev && p.attn_dev |
| 253 | }; |
| 254 | self.chip_ns += p.chip_ns; |
| 255 | self.attn_ns += p.attn_ns; |
| 256 | self.host_ns += p.host_ns; |
| 257 | let (a, b) = (&mut self.prof, &p.prof); |
| 258 | a.embed_ns += b.embed_ns; |
| 259 | a.norm_in_ns += b.norm_in_ns; |
| 260 | a.resid_ns += b.resid_ns; |
| 261 | a.norm_post_ns += b.norm_post_ns; |
| 262 | a.router_ns += b.router_ns; |
| 263 | a.plan_ns += b.plan_ns; |
| 264 | a.tiles_ns += b.tiles_ns; |
| 265 | a.combine_ns += b.combine_ns; |
| 266 | a.final_ns += b.final_ns; |
| 267 | a.dev_ns += b.dev_ns; |
| 268 | a.wall_ns += b.wall_ns; |
| 269 | self.router += p.router; |
| 270 | self.combine += p.combine; |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | fn as_f32(b: &[u8]) -> Result<&[f32], String> { |
| 275 | // SAFETY: every bit pattern is a valid f32; align_to only yields the aligned middle. |
| 276 | let (pre, mid, post) = unsafe { b.align_to::<f32>() }; |
| 277 | if !pre.is_empty() || !post.is_empty() { |
| 278 | return Err("host buffer not f32-aligned".into()); |
| 279 | } |
| 280 | Ok(mid) |
| 281 | } |
| 282 | |
| 283 | fn as_f32_mut(b: &mut [u8]) -> Result<&mut [f32], String> { |
| 284 | // SAFETY: as as_f32. |
| 285 | let (pre, mid, post) = unsafe { b.align_to_mut::<f32>() }; |
| 286 | if !pre.is_empty() || !post.is_empty() { |
| 287 | return Err("host buffer not f32-aligned".into()); |
| 288 | } |
| 289 | Ok(mid) |
| 290 | } |
| 291 | |
| 292 | fn as_u32_mut(b: &mut [u8]) -> Result<&mut [u32], String> { |
| 293 | // SAFETY: every bit pattern is a valid u32. |
| 294 | let (pre, mid, post) = unsafe { b.align_to_mut::<u32>() }; |
| 295 | if !pre.is_empty() || !post.is_empty() { |
| 296 | return Err("host buffer not u32-aligned".into()); |
| 297 | } |
| 298 | Ok(mid) |
| 299 | } |
| 300 | |
| 301 | fn host<'a, B: PfBuffer>(b: &'a B, what: &str) -> Result<&'a [f32], String> { |
| 302 | as_f32( |
| 303 | b.host() |
| 304 | .ok_or_else(|| format!("{what} is not a host buffer"))?, |
| 305 | ) |
| 306 | } |
| 307 | |
| 308 | fn host_mut<'a, B: PfBuffer>(b: &'a mut B, what: &str) -> Result<&'a mut [f32], String> { |
| 309 | as_f32_mut( |
| 310 | b.host_mut() |
| 311 | .ok_or_else(|| format!("{what} is not a host buffer"))?, |
| 312 | ) |
| 313 | } |
| 314 | |
| 315 | /// Tile-table regions of the shared HOST tile buffer (one per GEMM of a layer). |
| 316 | #[derive(Debug, Clone, Copy)] |
| 317 | enum Region { |
| 318 | Qkv = 0, |
| 319 | O = 1, |
| 320 | GateUp = 2, |
| 321 | Down = 3, |
| 322 | } |
| 323 | |
| 324 | /// The buffers of one sizing (`m` tokens, `bm` rows per tile). Sizes in the field comments. |
| 325 | struct Bufs<B> { |
| 326 | m: usize, |
| 327 | bm: usize, |
| 328 | max_tiles: usize, |
| 329 | /// HOST f32 [m][max(hidden, q_dim)]: quantiser input (normed x, host-path attention out, post). |
| 330 | xin: B, |
| 331 | /// DEV e4m3 [m + bm][max(hidden, q_dim)] and f32 scales [m + bm][max / 128] (GEMM reads tiles to row0 + bm - 1). |
| 332 | xq: B, |
| 333 | xs: B, |
| 334 | /// HOST f32 [m][qkv_n] (host attention entry) or None. |
| 335 | qkv_host: Option<B>, |
| 336 | /// DEV f32 [m][qkv_n] and [m][q_dim] (device attention entry) or None. |
| 337 | qkv_dev: Option<B>, |
| 338 | att_dev: Option<B>, |
| 339 | /// HOST f32 [m][hidden]: o projection. |
| 340 | oproj: B, |
| 341 | /// HOST u32 [g + bm]: token of each sorted row (padding rows read token 0). |
| 342 | rowidx: B, |
| 343 | /// DEV bf16 [g][moe_intermediate]: SwiGLU act rows. |
| 344 | act: B, |
| 345 | /// DEV e4m3 [g + bm][I] and f32 scales [g + bm][I / 128]. |
| 346 | aq: B, |
| 347 | a_s: B, |
| 348 | /// HOST f32 [g][hidden]: down rows (sorted order). |
| 349 | down: B, |
| 350 | /// HOST 4 regions x max_tiles x 32 bytes. |
| 351 | tiles: B, |
| 352 | } |
| 353 | |
| 354 | /// The whole-prompt prefill driver over a [`PrefillDevice`] (real: `aien_omega_pf::OmegaPfDevice`). |
| 355 | pub struct WholePromptPrefill<D: PrefillDevice> { |
| 356 | dev: D, |
| 357 | entries: Vec<LayerEntries>, |
| 358 | bufs: Option<Bufs<D::Buf>>, |
| 359 | pub stats: PrefillStats, |
| 360 | /// GPU-cached copies of the FP8 weights ([`Self::cache_weights`]); empty = read in place. |
| 361 | cached: Vec<D::Buf>, |
| 362 | /// Correctness-gate recorder (W-L1G-C, 2026-10-14): `None` = off. See [`WpTrace`]. |
| 363 | pub trace: Option<WpTrace>, |
| 364 | /// Negative-control mutant (W-L1G-C): `WpMutant::None` in service. |
| 365 | pub mutant: WpMutant, |
| 366 | /// Device router logits + combine (W-L1G-D, [`devhost`]): `None` = host path (the default). |
| 367 | devhost: Option<devhost::DevHost<D::Buf>>, |
| 368 | } |
| 369 | |
| 370 | impl<D: PrefillDevice> std::fmt::Debug for WholePromptPrefill<D> { |
| 371 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 372 | write!( |
| 373 | f, |
| 374 | "WholePromptPrefill {{ layers: {}, sized_for: {:?} }}", |
| 375 | self.entries.len(), |
| 376 | self.bufs.as_ref().map(|b| b.m) |
| 377 | ) |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | impl<D: PrefillDevice> WholePromptPrefill<D> { |
| 382 | /// Collects the in-place weight addresses of every layer (no weight copy). |
| 383 | pub fn new(dev: D, weights: &Qwen3MoeOmegaWeights) -> Result<Self, String> { |
| 384 | Ok(Self { |
| 385 | dev, |
| 386 | entries: layer_entries(weights)?, |
| 387 | bufs: None, |
| 388 | stats: PrefillStats::default(), |
| 389 | cached: Vec::new(), |
| 390 | trace: None, |
| 391 | mutant: WpMutant::None, |
| 392 | devhost: None, |
| 393 | }) |
| 394 | } |
| 395 | |
| 396 | pub fn device(&self) -> &D { |
| 397 | &self.dev |
| 398 | } |
| 399 | |
| 400 | /// Copies every FP8 weight tensor into GPU-cached device memory (one copy kernel per tensor) |
| 401 | /// and points the tile tables at the copies (the in-place GEMV tensors are GPU-uncached; the |
| 402 | /// GEMM reuses each weight tile across row tiles, so it wants L2). Returns the bytes copied. |
| 403 | /// Per expert the omega_gpu_fp8 layout is w `n * k` e4m3 and s `(n / 128) * (k / 128)` f32, |
| 404 | /// experts contiguous (omega_gpu_fp8_tensor_entry); that contiguity is checked here. |
| 405 | pub fn cache_weights(&mut self, c: &Qwen3MoeConfig) -> Result<usize, String> { |
| 406 | if !self.cached.is_empty() { |
| 407 | return Ok(self.cached.iter().map(|b| b.bytes()).sum()); |
| 408 | } |
| 409 | let (h, qd, qkv_n, i) = (c.hidden, c.q_dim(), c.qkv_n(), c.moe_intermediate); |
| 410 | let blk = aien_omega_pf::BLOCK; |
| 411 | let mut total = 0usize; |
| 412 | let mut new_entries = self.entries.clone(); |
| 413 | let mut bufs = Vec::new(); |
| 414 | for (l, ent) in new_entries.iter_mut().enumerate() { |
| 415 | let mut one = |w: &mut [u64], |
| 416 | s: &mut [u64], |
| 417 | n: usize, |
| 418 | k: usize| |
| 419 | -> Result<(), String> { |
| 420 | let (wb, sb) = (n * k, (n / blk) * (k / blk) * 4); |
| 421 | for ex in 0..w.len() { |
| 422 | if w[ex] != w[0] + (ex * wb) as u64 || s[ex] != s[0] + (ex * sb) as u64 { |
| 423 | return Err(format!("layer {l}: expert {ex} weights are not contiguous; cannot copy in one piece")); |
| 424 | } |
| 425 | } |
| 426 | for (v, per) in [(w, wb), (s, sb)] { |
| 427 | let bytes = per * v.len(); |
| 428 | let dst = self.dev.alloc_dev(bytes)?; |
| 429 | self.dev |
| 430 | .copy_va(dst.va(), v[0], bytes) |
| 431 | .map_err(|e| format!("layer {l}: weight copy of {bytes} bytes: {e}"))?; |
| 432 | for (ex, x) in v.iter_mut().enumerate() { |
| 433 | *x = dst.va() + (ex * per) as u64; |
| 434 | } |
| 435 | total += bytes; |
| 436 | bufs.push(dst); |
| 437 | } |
| 438 | Ok(()) |
| 439 | }; |
| 440 | let (mut qw, mut qs) = ([ent.qkv.0], [ent.qkv.1]); |
| 441 | one(&mut qw, &mut qs, qkv_n, h)?; |
| 442 | ent.qkv = (qw[0], qs[0]); |
| 443 | let (mut ow, mut os) = ([ent.o.0], [ent.o.1]); |
| 444 | one(&mut ow, &mut os, h, qd)?; |
| 445 | ent.o = (ow[0], os[0]); |
| 446 | one(&mut ent.gu_w, &mut ent.gu_s, 2 * i, h)?; |
| 447 | one(&mut ent.dn_w, &mut ent.dn_s, h, i)?; |
| 448 | } |
| 449 | self.entries = new_entries; |
| 450 | self.cached = bufs; |
| 451 | Ok(total) |
| 452 | } |
| 453 | |
| 454 | /// Tokens the prompt-sized scratch is sized for (0 before the first pass). The scratch is |
| 455 | /// kept between passes and only regrown, so this is its high-water mark. |
| 456 | pub fn scratch_tokens(&self) -> usize { |
| 457 | self.bufs.as_ref().map_or(0, |b| b.m) |
| 458 | } |
| 459 | |
| 460 | fn ensure(&mut self, c: &Qwen3MoeConfig, m: usize, dev_attn: bool) -> Result<(), String> { |
| 461 | let bm = self.dev.qgemm_bm(); |
| 462 | if let Some(b) = &self.bufs { |
| 463 | let mode_ok = if dev_attn { |
| 464 | b.qkv_dev.is_some() |
| 465 | } else { |
| 466 | b.qkv_host.is_some() |
| 467 | }; |
| 468 | if b.m >= m && b.bm == bm && mode_ok { |
| 469 | return Ok(()); |
| 470 | } |
| 471 | } |
| 472 | self.bufs = None; // free the old sizing before allocating the new one |
| 473 | let (h, qd, qkv_n, i, e) = ( |
| 474 | c.hidden, |
| 475 | c.q_dim(), |
| 476 | c.qkv_n(), |
| 477 | c.moe_intermediate, |
| 478 | c.experts, |
| 479 | ); |
| 480 | let g = m * c.top_k; |
| 481 | let kmax = h.max(qd); |
| 482 | let max_tiles = g.div_ceil(bm) + e; |
| 483 | let d = &mut self.dev; |
| 484 | let (qkv_host, qkv_dev, att_dev) = if dev_attn { |
| 485 | ( |
| 486 | None, |
| 487 | Some(d.alloc_dev(m * qkv_n * 4)?), |
| 488 | Some(d.alloc_dev(m * qd * 4)?), |
| 489 | ) |
| 490 | } else { |
| 491 | (Some(d.alloc_host(m * qkv_n * 4)?), None, None) |
| 492 | }; |
| 493 | let mut b = Bufs { |
| 494 | m, |
| 495 | bm, |
| 496 | max_tiles, |
| 497 | xin: d.alloc_host(m * kmax * 4)?, |
| 498 | xq: d.alloc_dev((m + bm) * kmax)?, |
| 499 | xs: d.alloc_dev((m + bm) * (kmax / aien_omega_pf::BLOCK) * 4)?, |
| 500 | qkv_host, |
| 501 | qkv_dev, |
| 502 | att_dev, |
| 503 | oproj: d.alloc_host(m * h * 4)?, |
| 504 | rowidx: d.alloc_host((g + bm) * 4)?, |
| 505 | act: d.alloc_dev(g * i * 2)?, |
| 506 | aq: d.alloc_dev((g + bm) * i)?, |
| 507 | a_s: d.alloc_dev((g + bm) * (i / aien_omega_pf::BLOCK) * 4)?, |
| 508 | down: d.alloc_host(g * h * 4)?, |
| 509 | tiles: d.alloc_host(4 * max_tiles * TILE_BYTES)?, |
| 510 | }; |
| 511 | // padding rows of the row index read token 0 (a valid row); written once per sizing |
| 512 | as_u32_mut( |
| 513 | b.rowidx |
| 514 | .host_mut() |
| 515 | .ok_or("row index is not a host buffer")?, |
| 516 | )? |
| 517 | .fill(0); |
| 518 | self.bufs = Some(b); |
| 519 | Ok(()) |
| 520 | } |
| 521 | |
| 522 | /// Runs the whole prompt `tokens` at positions `pos0 .. pos0 + m - 1` through every layer. |
| 523 | /// Positions `0 .. pos0 - 1` must already be in `attn`'s KV cache. Returns the last token's |
| 524 | /// final-normed hidden state. |
| 525 | pub fn run( |
| 526 | &mut self, |
| 527 | weights: &Qwen3MoeOmegaWeights, |
| 528 | attn: &mut dyn PrefillAttention, |
| 529 | tokens: &[u32], |
| 530 | pos0: usize, |
| 531 | ) -> Result<Vec<f32>, String> { |
| 532 | if self.devhost.is_some() { |
| 533 | return self.run_dev(weights, attn, tokens, pos0); |
| 534 | } |
| 535 | let c = &weights.config; |
| 536 | let m = tokens.len(); |
| 537 | if m == 0 { |
| 538 | return Err("whole-prompt prefill of 0 tokens".into()); |
| 539 | } |
| 540 | if pos0 + m > u32::MAX as usize { |
| 541 | return Err(format!("positions {pos0} + {m} do not fit u32")); |
| 542 | } |
| 543 | if self.entries.len() != weights.layers.len() { |
| 544 | return Err(format!( |
| 545 | "driver built for {} layers, weights have {}", |
| 546 | self.entries.len(), |
| 547 | weights.layers.len() |
| 548 | )); |
| 549 | } |
| 550 | let (h, qd, qkv_n, e, top_k, i, eps) = ( |
| 551 | c.hidden, |
| 552 | c.q_dim(), |
| 553 | c.qkv_n(), |
| 554 | c.experts, |
| 555 | c.top_k, |
| 556 | c.moe_intermediate, |
| 557 | c.rms_eps, |
| 558 | ); |
| 559 | let g = m * top_k; |
| 560 | let dev_attn = attn.has_dev(); |
| 561 | self.ensure(c, m, dev_attn)?; |
| 562 | let mut st = PrefillStats { |
| 563 | tokens: m, |
| 564 | layers: weights.layers.len(), |
| 565 | attn_dev: dev_attn, |
| 566 | ..Default::default() |
| 567 | }; |
| 568 | let (dev, b) = (&mut self.dev, self.bufs.as_mut().expect("sized")); |
| 569 | let bm = b.bm; |
| 570 | let t_run = Instant::now(); |
| 571 | let mut lap = Instant::now(); |
| 572 | // W-L1G-D profile: adds the time since the last lap to one HostProf field. |
| 573 | macro_rules! lap { |
| 574 | ($f:ident) => {{ |
| 575 | st.prof.$f += lap.elapsed().as_nanos() as u64; |
| 576 | lap = Instant::now(); |
| 577 | }}; |
| 578 | } |
| 579 | |
| 580 | let t = Instant::now(); |
| 581 | let mut x: Vec<f32> = tokens |
| 582 | .iter() |
| 583 | .flat_map(|&tok| weights.embed_row(tok)) |
| 584 | .collect(); |
| 585 | let mut logits = vec![0.0f32; m * e]; |
| 586 | lap!(embed_ns); |
| 587 | st.host_ns += t.elapsed().as_nanos() as u64; |
| 588 | |
| 589 | // Writes a tile table into its region and returns (tiles_va, ntiles). |
| 590 | let put_tiles = |tiles: &mut D::Buf, |
| 591 | max: usize, |
| 592 | region: Region, |
| 593 | w: &[u64], |
| 594 | s: &[u64], |
| 595 | counts: &[u32]| |
| 596 | -> Result<(u64, usize), String> { |
| 597 | let tab = build_tiles(bm, w, s, counts).map_err(|err| err.to_string())?; |
| 598 | if tab.len() > max { |
| 599 | return Err(format!( |
| 600 | "tile table of {} entries > region of {max}", |
| 601 | tab.len() |
| 602 | )); |
| 603 | } |
| 604 | let off = region as usize * max * TILE_BYTES; |
| 605 | let bytes = tiles.host_mut().ok_or("tile table is not a host buffer")?; |
| 606 | for (j, tl) in tab.iter().enumerate() { |
| 607 | bytes[off + j * TILE_BYTES..off + (j + 1) * TILE_BYTES] |
| 608 | .copy_from_slice(&tl.to_bytes()); |
| 609 | } |
| 610 | Ok((tiles.va() + off as u64, tab.len())) |
| 611 | }; |
| 612 | let dense = [m as u32]; |
| 613 | // W-L1G-C gate hooks: the recorder (a field disjoint from dev / bufs) and the mutant switch. |
| 614 | let mutant = self.mutant; |
| 615 | let mut tr = self.trace.as_mut(); |
| 616 | if let Some(t) = tr.as_deref_mut() { |
| 617 | t.note_pass(m, weights.layers.len(), h, top_k); |
| 618 | } |
| 619 | |
| 620 | for (l, layer) in weights.layers.iter().enumerate() { |
| 621 | let ent = &self.entries[l]; |
| 622 | let lu = l as u32; |
| 623 | // --- input RMSNorm straight into the quantiser's HOST input --- |
| 624 | let t = Instant::now(); |
| 625 | { |
| 626 | let xin = host_mut(&mut b.xin, "xin")?; |
| 627 | xin[..m * h] |
| 628 | .par_chunks_mut(h) |
| 629 | .zip(x.par_chunks(h)) |
| 630 | .for_each(|(o, xr)| rmsnorm(xr, &layer.input_norm, eps, o)); |
| 631 | lap!(norm_in_ns); |
| 632 | } |
| 633 | st.host_ns += t.elapsed().as_nanos() as u64; |
| 634 | if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { |
| 635 | let src = host(&b.xin, "xin")?[..m * h].to_vec(); |
| 636 | let t = tr.as_deref_mut().expect("trace"); |
| 637 | WpTrace::store_op(t.row0, &mut t.ops.x_norm, &src); |
| 638 | } |
| 639 | st.chip_ns += dev |
| 640 | .quant(h, QuantIn::F32, m, b.xin.va(), b.xq.va(), b.xs.va()) |
| 641 | .map_err(|err| format!("layer {l} quant x: {err}"))?; |
| 642 | st.quant += 1; |
| 643 | |
| 644 | // --- q|k|v: one GEMM for all m tokens --- |
| 645 | lap!(dev_ns); |
| 646 | let (tv, nt) = put_tiles( |
| 647 | &mut b.tiles, |
| 648 | b.max_tiles, |
| 649 | Region::Qkv, |
| 650 | &[ent.qkv.0], |
| 651 | &[ent.qkv.1], |
| 652 | &dense, |
| 653 | )?; |
| 654 | lap!(tiles_ns); |
| 655 | let qkv_y = match (&b.qkv_dev, &b.qkv_host) { |
| 656 | (Some(d), _) => d.va(), |
| 657 | (None, Some(hb)) => hb.va(), |
| 658 | (None, None) => unreachable!("ensure allocates one q|k|v buffer"), |
| 659 | }; |
| 660 | let call = QgemmCall { |
| 661 | n: qkv_n, |
| 662 | k: h, |
| 663 | layout: Layout::Plain, |
| 664 | tiles_va: tv, |
| 665 | ntiles: nt, |
| 666 | rowidx_va: 0, |
| 667 | xq_va: b.xq.va(), |
| 668 | xs_va: b.xs.va(), |
| 669 | y_va: qkv_y, |
| 670 | }; |
| 671 | st.chip_ns += dev |
| 672 | .qgemm(&call) |
| 673 | .map_err(|err| format!("layer {l} q|k|v gemm x{m}: {err}"))?; |
| 674 | st.qkv += 1; |
| 675 | |
| 676 | // --- attention: ONE call for all m tokens --- |
| 677 | let att_va = if let (Some(qd_buf), Some(ad_buf)) = (&b.qkv_dev, &b.att_dev) { |
| 678 | let ns = attn |
| 679 | .attend_dev( |
| 680 | lu, |
| 681 | pos0 as u32, |
| 682 | m as u32, |
| 683 | qd_buf.va(), |
| 684 | eps, |
| 685 | ATTN_OUT_SCALE, |
| 686 | ad_buf.va(), |
| 687 | ) |
| 688 | .ok_or_else(|| { |
| 689 | format!("layer {l}: attention offered the device entry, then refused it") |
| 690 | })? |
| 691 | .map_err(|err| format!("layer {l} attention (device) x{m}: {err}"))?; |
| 692 | st.attn_ns += ns; |
| 693 | ad_buf.va() |
| 694 | } else { |
| 695 | let qkv = host(b.qkv_host.as_ref().expect("host q|k|v"), "q|k|v")?; |
| 696 | let out = host_mut(&mut b.xin, "xin")?; |
| 697 | let ns = attn |
| 698 | .attend( |
| 699 | lu, |
| 700 | pos0 as u32, |
| 701 | m as u32, |
| 702 | &qkv[..m * qkv_n], |
| 703 | eps, |
| 704 | ATTN_OUT_SCALE, |
| 705 | &mut out[..m * qd], |
| 706 | ) |
| 707 | .map_err(|err| format!("layer {l} attention x{m}: {err}"))?; |
| 708 | st.attn_ns += ns; |
| 709 | b.xin.va() |
| 710 | }; |
| 711 | st.attn += 1; |
| 712 | if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { |
| 713 | let qkv = match (&b.qkv_dev, &b.qkv_host) { |
| 714 | (Some(d), _) => read_dev(&mut *dev, d.va(), m * qkv_n)?, |
| 715 | (None, Some(hb)) => host(hb, "q|k|v")?[..m * qkv_n].to_vec(), |
| 716 | (None, None) => Vec::new(), |
| 717 | }; |
| 718 | let attn = if b.att_dev.is_some() { |
| 719 | read_dev(&mut *dev, att_va, m * qd)? |
| 720 | } else { |
| 721 | host(&b.xin, "xin")?[..m * qd].to_vec() |
| 722 | }; |
| 723 | let t = tr.as_deref_mut().expect("trace"); |
| 724 | let row0 = t.row0; |
| 725 | WpTrace::store_op(row0, &mut t.ops.qkv, &qkv); |
| 726 | WpTrace::store_op(row0, &mut t.ops.attn, &attn); |
| 727 | } |
| 728 | st.chip_ns += dev |
| 729 | .quant(qd, QuantIn::F32, m, att_va, b.xq.va(), b.xs.va()) |
| 730 | .map_err(|err| format!("layer {l} quant attn: {err}"))?; |
| 731 | st.quant += 1; |
| 732 | |
| 733 | // --- o: one GEMM into HOST rows --- |
| 734 | lap!(dev_ns); |
| 735 | let (tv, nt) = put_tiles( |
| 736 | &mut b.tiles, |
| 737 | b.max_tiles, |
| 738 | Region::O, |
| 739 | &[ent.o.0], |
| 740 | &[ent.o.1], |
| 741 | &dense, |
| 742 | )?; |
| 743 | lap!(tiles_ns); |
| 744 | let call = QgemmCall { |
| 745 | n: h, |
| 746 | k: qd, |
| 747 | layout: Layout::Plain, |
| 748 | tiles_va: tv, |
| 749 | ntiles: nt, |
| 750 | rowidx_va: 0, |
| 751 | xq_va: b.xq.va(), |
| 752 | xs_va: b.xs.va(), |
| 753 | y_va: b.oproj.va(), |
| 754 | }; |
| 755 | st.chip_ns += dev |
| 756 | .qgemm(&call) |
| 757 | .map_err(|err| format!("layer {l} o gemm x{m}: {err}"))?; |
| 758 | st.o += 1; |
| 759 | if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { |
| 760 | let src = host(&b.oproj, "o projection")?[..m * h].to_vec(); |
| 761 | let t = tr.as_deref_mut().expect("trace"); |
| 762 | WpTrace::store_op(t.row0, &mut t.ops.oproj, &src); |
| 763 | } |
| 764 | |
| 765 | // --- residual, post norm (into the quantiser input), routing, sort --- |
| 766 | let t = Instant::now(); |
| 767 | let sort = { |
| 768 | lap!(dev_ns); |
| 769 | let oproj = host(&b.oproj, "o projection")?; |
| 770 | x.par_chunks_mut(h) |
| 771 | .zip(oproj[..m * h].par_chunks(h)) |
| 772 | .for_each(|(xr, pr)| { |
| 773 | for (xi, p) in xr.iter_mut().zip(pr) { |
| 774 | *xi += p; |
| 775 | } |
| 776 | }); |
| 777 | if let Some(t) = tr.as_deref_mut() { |
| 778 | let (row0, width) = (t.row0, t.hidden); |
| 779 | WpTrace::copy_f32(row0, &mut t.x_mid[l], &x, width); |
| 780 | } |
| 781 | lap!(resid_ns); |
| 782 | let post = host_mut(&mut b.xin, "xin")?; |
| 783 | post[..m * h] |
| 784 | .par_chunks_mut(h) |
| 785 | .zip(x.par_chunks(h)) |
| 786 | .for_each(|(o, xr)| rmsnorm(xr, &layer.post_norm, eps, o)); |
| 787 | lap!(norm_post_ns); |
| 788 | router_logits(&layer.router, &post[..m * h], h, e, &mut logits); |
| 789 | lap!(router_ns); |
| 790 | if mutant == WpMutant::Routing { |
| 791 | rotate_logits(&mut logits, e); |
| 792 | } |
| 793 | if tr.as_ref().is_some_and(|t| t.ops_layer == Some(l)) { |
| 794 | let post_rows = post[..m * h].to_vec(); |
| 795 | let logits_rows = logits.clone(); |
| 796 | let t = tr.as_deref_mut().expect("trace"); |
| 797 | let row0 = t.row0; |
| 798 | WpTrace::store_op(row0, &mut t.ops.post, &post_rows); |
| 799 | WpTrace::store_op(row0, &mut t.ops.logits, &logits_rows); |
| 800 | } |
| 801 | let plan = MoeBatchPlan::from_logits(&logits, m, e, top_k) |
| 802 | .map_err(|err| format!("layer {l} routing: {err}"))?; |
| 803 | let sort = ExpertSort::from_plan(&plan); |
| 804 | if let Some(t) = tr.as_deref_mut() { |
| 805 | let (row0, k) = (t.row0, t.top_k); |
| 806 | WpTrace::copy_u32(row0, &mut t.experts[l], &plan.topk_experts, k); |
| 807 | } |
| 808 | as_u32_mut( |
| 809 | b.rowidx |
| 810 | .host_mut() |
| 811 | .ok_or("row index is not a host buffer")?, |
| 812 | )?[..g] |
| 813 | .copy_from_slice(&sort.rows); |
| 814 | (sort, plan.topk_weights) |
| 815 | }; |
| 816 | let (sort, wts) = sort; |
| 817 | lap!(plan_ns); |
| 818 | st.host_ns += t.elapsed().as_nanos() as u64; |
| 819 | st.chip_ns += dev |
| 820 | .quant(h, QuantIn::F32, m, b.xin.va(), b.xq.va(), b.xs.va()) |
| 821 | .map_err(|err| format!("layer {l} quant post: {err}"))?; |
| 822 | st.quant += 1; |
| 823 | |
| 824 | // --- experts: gate|up with the SwiGLU epilogue (rows gathered by token), act quantised, down --- |
| 825 | lap!(dev_ns); |
| 826 | let (tv, nt) = put_tiles( |
| 827 | &mut b.tiles, |
| 828 | b.max_tiles, |
| 829 | Region::GateUp, |
| 830 | &ent.gu_w, |
| 831 | &ent.gu_s, |
| 832 | &sort.counts, |
| 833 | )?; |
| 834 | if mutant == WpMutant::GateUpScales { |
| 835 | // GEMM mutant: every expert's weights with the NEXT expert's scale blocks (same table size, same region). |
| 836 | let mut s = ent.gu_s.clone(); |
| 837 | s.rotate_left(1); |
| 838 | put_tiles( |
| 839 | &mut b.tiles, |
| 840 | b.max_tiles, |
| 841 | Region::GateUp, |
| 842 | &ent.gu_w, |
| 843 | &s, |
| 844 | &sort.counts, |
| 845 | )?; |
| 846 | } |
| 847 | lap!(tiles_ns); |
| 848 | let call = QgemmCall { |
| 849 | n: 2 * i, |
| 850 | k: h, |
| 851 | layout: Layout::SwigluNat, |
| 852 | tiles_va: tv, |
| 853 | ntiles: nt, |
| 854 | rowidx_va: b.rowidx.va(), |
| 855 | xq_va: b.xq.va(), |
| 856 | xs_va: b.xs.va(), |
| 857 | y_va: b.act.va(), |
| 858 | }; |
| 859 | st.chip_ns += dev |
| 860 | .qgemm(&call) |
| 861 | .map_err(|err| format!("layer {l} gate|up gemm x{g}: {err}"))?; |
| 862 | st.gate_up += 1; |
| 863 | st.chip_ns += dev |
| 864 | .quant(i, QuantIn::Bf16, g, b.act.va(), b.aq.va(), b.a_s.va()) |
| 865 | .map_err(|err| format!("layer {l} quant act: {err}"))?; |
| 866 | st.quant += 1; |
| 867 | lap!(dev_ns); |
| 868 | let (tv, nt) = put_tiles( |
| 869 | &mut b.tiles, |
| 870 | b.max_tiles, |
| 871 | Region::Down, |
| 872 | &ent.dn_w, |
| 873 | &ent.dn_s, |
| 874 | &sort.counts, |
| 875 | )?; |
| 876 | lap!(tiles_ns); |
| 877 | let call = QgemmCall { |
| 878 | n: h, |
| 879 | k: i, |
| 880 | layout: Layout::Plain, |
| 881 | tiles_va: tv, |
| 882 | ntiles: nt, |
| 883 | rowidx_va: 0, |
| 884 | xq_va: b.aq.va(), |
| 885 | xs_va: b.a_s.va(), |
| 886 | y_va: b.down.va(), |
| 887 | }; |
| 888 | st.chip_ns += dev |
| 889 | .qgemm(&call) |
| 890 | .map_err(|err| format!("layer {l} down gemm x{g}: {err}"))?; |
| 891 | st.down += 1; |
| 892 | |
| 893 | let t = Instant::now(); |
| 894 | lap!(dev_ns); |
| 895 | combine_rows( |
| 896 | &mut x, |
| 897 | &host(&b.down, "down rows")?[..g * h], |
| 898 | &wts, |
| 899 | &sort.inv, |
| 900 | h, |
| 901 | top_k, |
| 902 | ); |
| 903 | lap!(combine_ns); |
| 904 | if let Some(t) = tr.as_deref_mut() { |
| 905 | let (row0, width) = (t.row0, t.hidden); |
| 906 | WpTrace::copy_f32(row0, &mut t.x_out[l], &x, width); |
| 907 | if t.ops_layer == Some(l) { |
| 908 | let off = row0 * width; |
| 909 | let moe: Vec<f32> = x |
| 910 | .iter() |
| 911 | .zip(&t.x_mid[l][off..off + x.len()]) |
| 912 | .map(|(a, b)| a - b) |
| 913 | .collect(); |
| 914 | WpTrace::store_op(row0, &mut t.ops.moe_out, &moe); |
| 915 | } |
| 916 | } |
| 917 | st.host_ns += t.elapsed().as_nanos() as u64; |
| 918 | } |
| 919 | let t = Instant::now(); |
| 920 | let mut hidden = vec![0.0f32; h]; |
| 921 | rmsnorm(&x[(m - 1) * h..], &weights.final_norm, eps, &mut hidden); |
| 922 | lap!(final_ns); |
| 923 | let _ = lap; |
| 924 | st.prof.wall_ns = t_run.elapsed().as_nanos() as u64; |
| 925 | st.host_ns += t.elapsed().as_nanos() as u64; |
| 926 | self.stats = st; |
| 927 | Ok(hidden) |
| 928 | } |
| 929 | } |
| 930 | |
| 931 | /// Router logits for every row of `post` (`m x h`): `logits[r][ex] = dot(router[ex], post[r])`, |
| 932 | /// each dot summed in index order (reimplements the engine's private `router_logits`). |
| 933 | pub fn router_logits(router: &[f32], post: &[f32], h: usize, e: usize, logits: &mut [f32]) { |
| 934 | logits |
| 935 | .par_chunks_mut(e) |
| 936 | .zip(post.par_chunks(h)) |
| 937 | .for_each(|(lr, pr)| { |
| 938 | for (ex, lv) in lr.iter_mut().enumerate() { |
| 939 | *lv = router[ex * h..(ex + 1) * h] |
| 940 | .iter() |
| 941 | .zip(pr) |
| 942 | .map(|(a, b)| a * b) |
| 943 | .sum(); |
| 944 | } |
| 945 | }); |
| 946 | } |
| 947 | |
| 948 | /// `x[r] += sum_slot wts[r * top_k + slot] * down[inv[r * top_k + slot]]`, accumulated in slot |
| 949 | /// order from zero (reimplements the engine's private `combine_rows`). |
| 950 | pub fn combine_rows( |
| 951 | x: &mut [f32], |
| 952 | down_sorted: &[f32], |
| 953 | wts: &[f32], |
| 954 | inv: &[u32], |
| 955 | h: usize, |
| 956 | top_k: usize, |
| 957 | ) { |
| 958 | x.par_chunks_mut(h).enumerate().for_each(|(r, xr)| { |
| 959 | let mut acc = vec![0.0f32; h]; |
| 960 | for slot in 0..top_k { |
| 961 | let gi = r * top_k + slot; |
| 962 | let row = inv[gi] as usize; |
| 963 | for (a, d) in acc.iter_mut().zip(&down_sorted[row * h..(row + 1) * h]) { |
| 964 | *a += wts[gi] * d; |
| 965 | } |
| 966 | } |
| 967 | for (xi, a) in xr.iter_mut().zip(&acc) { |
| 968 | *xi += a; |
| 969 | } |
| 970 | }); |
| 971 | } |
| 972 | |
| 973 | pub mod devhost; |
| 974 | /// Host mirror of the activation quantiser (W-L1G-C). |
| 975 | pub mod fake_quant; |
| 976 | |
| 977 | /// Negative-control mutants of the whole-prompt path (W-L1G-C). Each must be caught by the gate. |
| 978 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 979 | pub enum WpMutant { |
| 980 | #[default] |
| 981 | None, |
| 982 | /// Every chosen expert id becomes its neighbour `(ex + 1) % e`, weights unchanged (the |
| 983 | /// engine's `routing_mutant`, done by rotating each token's router logits by one). |
| 984 | Routing, |
| 985 | /// The gate|up GEMM reads every expert's weights with the next expert's scale blocks. |
| 986 | GateUpScales, |
| 987 | } |
| 988 | |
| 989 | /// One layer's intermediate values for every token (recorded at [`WpTrace::ops_layer`]). |
| 990 | #[derive(Debug, Clone, Default, PartialEq)] |
| 991 | pub struct WpOps { |
| 992 | /// `m x hidden` input RMSNorm output (the q|k|v GEMM input before quantisation). |
| 993 | pub x_norm: Vec<f32>, |
| 994 | /// `m x qkv_n` fused projection rows. |
| 995 | pub qkv: Vec<f32>, |
| 996 | /// `m x q_dim` attention output (the o GEMM input before quantisation). |
| 997 | pub attn: Vec<f32>, |
| 998 | /// `m x hidden` o projection. |
| 999 | pub oproj: Vec<f32>, |
| 1000 | /// `m x hidden` post RMSNorm output (the gate|up GEMM input before quantisation). |
| 1001 | pub post: Vec<f32>, |
| 1002 | /// `m x experts` router logits. |
| 1003 | pub logits: Vec<f32>, |
| 1004 | /// `m x hidden` weighted expert sum (what the experts add to the residual). |
| 1005 | pub moe_out: Vec<f32>, |
| 1006 | } |
| 1007 | |
| 1008 | /// Correctness-gate recorder (W-L1G-C): per layer, every token's residual after the attention |
| 1009 | /// block (`x_mid`), after the experts (`x_out`) and the chosen experts (token-major, slot |
| 1010 | /// order); plus every op of one layer (`ops_layer`). The same shape is filled by the OFF path |
| 1011 | /// and the W8A8 control (`qwen3_moe_omega::w8a8_control`), so the three can be compared per |
| 1012 | /// layer and per op. |
| 1013 | #[derive(Debug, Clone, Default, PartialEq)] |
| 1014 | pub struct WpTrace { |
| 1015 | pub m: usize, |
| 1016 | pub hidden: usize, |
| 1017 | pub top_k: usize, |
| 1018 | /// First token row of the pass being recorded. `0` for a single pass. A chunked prefill |
| 1019 | /// sizes the trace for the whole prompt (`begin`) and sets this to each pass's `from`, so |
| 1020 | /// the W-L1G gate records every token instead of only the last pass. |
| 1021 | pub row0: usize, |
| 1022 | /// Per layer `m x hidden`. |
| 1023 | pub x_mid: Vec<Vec<f32>>, |
| 1024 | pub x_out: Vec<Vec<f32>>, |
| 1025 | /// Per layer `m x top_k` expert ids. |
| 1026 | pub experts: Vec<Vec<u32>>, |
| 1027 | pub ops_layer: Option<usize>, |
| 1028 | pub ops: WpOps, |
| 1029 | } |
| 1030 | |
| 1031 | impl WpTrace { |
| 1032 | /// A recorder of every layer's residuals and the ops of `ops_layer`. |
| 1033 | pub fn new(ops_layer: Option<usize>) -> Self { |
| 1034 | Self { |
| 1035 | ops_layer, |
| 1036 | ..Default::default() |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | /// Sizes the per-layer stores for `m` tokens (called by the run being recorded). |
| 1041 | pub fn begin(&mut self, m: usize, layers: usize, hidden: usize, top_k: usize) { |
| 1042 | self.m = m; |
| 1043 | self.hidden = hidden; |
| 1044 | self.top_k = top_k; |
| 1045 | self.row0 = 0; |
| 1046 | self.x_mid = vec![vec![0.0f32; m * hidden]; layers]; |
| 1047 | self.x_out = vec![vec![0.0f32; m * hidden]; layers]; |
| 1048 | self.experts = vec![vec![0u32; m * top_k]; layers]; |
| 1049 | self.ops = WpOps::default(); |
| 1050 | } |
| 1051 | |
| 1052 | /// Prepares this pass of `m_pass` tokens. A trace already sized (by [`Self::begin`]) for |
| 1053 | /// every row through `row0 + m_pass` keeps those rows. A direct `run` sizes itself to this |
| 1054 | /// pass, which replaces whatever the previous direct call recorded. |
| 1055 | pub fn note_pass(&mut self, m_pass: usize, layers: usize, hidden: usize, top_k: usize) { |
| 1056 | let end = self.row0.saturating_add(m_pass); |
| 1057 | let ready = self.m > 0 |
| 1058 | && end <= self.m |
| 1059 | && self.layers() == layers |
| 1060 | && self.hidden == hidden |
| 1061 | && self.top_k == top_k; |
| 1062 | if !ready { |
| 1063 | self.begin(m_pass, layers, hidden, top_k); |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | /// Copies one pass of `width`-wide rows into `dst` at [`Self::row0`]. |
| 1068 | pub fn copy_f32(row0: usize, dst: &mut [f32], src: &[f32], width: usize) { |
| 1069 | let off = row0.saturating_mul(width); |
| 1070 | let n = src.len(); |
| 1071 | dst[off..off + n].copy_from_slice(src); |
| 1072 | } |
| 1073 | |
| 1074 | /// Copies one pass of `width`-wide rows into `dst` at `row0`. |
| 1075 | pub fn copy_u32(row0: usize, dst: &mut [u32], src: &[u32], width: usize) { |
| 1076 | let off = row0.saturating_mul(width); |
| 1077 | let n = src.len(); |
| 1078 | dst[off..off + n].copy_from_slice(src); |
| 1079 | } |
| 1080 | |
| 1081 | /// Ops of one pass, in pass order. `row0 == 0` starts the vector (a new prompt or a |
| 1082 | /// direct single pass). Later passes append. |
| 1083 | pub fn store_op(row0: usize, dst: &mut Vec<f32>, src: &[f32]) { |
| 1084 | if row0 == 0 { |
| 1085 | dst.clear(); |
| 1086 | } |
| 1087 | dst.extend_from_slice(src); |
| 1088 | } |
| 1089 | |
| 1090 | pub fn layers(&self) -> usize { |
| 1091 | self.x_out.len() |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | /// Rotates every token's router logits right by one, so the top-k ids all move to `(ex + 1) % e` |
| 1096 | /// with the same softmax weights (the routing mutant on a whole-prompt batch). |
| 1097 | pub fn rotate_logits(logits: &mut [f32], e: usize) { |
| 1098 | for row in logits.chunks_mut(e) { |
| 1099 | row.rotate_right(1); |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | /// Reads `n` f32 of a device-private buffer through a temporary HOST buffer (gate recorder only). |
| 1104 | fn read_dev<D: PrefillDevice>(dev: &mut D, va: u64, n: usize) -> Result<Vec<f32>, String> { |
| 1105 | let tmp = dev.alloc_host(n * 4)?; |
| 1106 | dev.copy_va(tmp.va(), va, n * 4) |
| 1107 | .map_err(|e| format!("recorder copy of {n} f32: {e}"))?; |
| 1108 | Ok(host(&tmp, "recorder scratch")?[..n].to_vec()) |
| 1109 | } |
| 1110 | |
| 1111 | #[cfg(test)] |
| 1112 | mod tests; |