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 / qwen38_omega.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 | //! Qwen3.8-27B on the Omega GPU engine (sc #642): the checkpoint uploaded once, then one command |
| 17 | //! list per decoded token (`aien_omega_q38::Q38Graph`, omega `src/omega_gpu_q38_graph.h`). |
| 18 | //! |
| 19 | //! What the upload does to the checkpoint (the graph's contract, checked against |
| 20 | //! [`crate::qwen38`], the host reference): |
| 21 | //! |
| 22 | //! - DeltaNet layer: `in_proj_qkv | in_proj_z` -> one FP8 tensor `[16384][5120]` (rows |
| 23 | //! concatenated; both are whole 128-row blocks, so the scale grids concatenate too). |
| 24 | //! `in_proj_a` / `in_proj_b` (bf16 `[48][5120]`) -> one bf16 tensor `[96][5120]`, row `2h` = |
| 25 | //! a_h, `2h + 1` = b_h, every value times 2^-64 (an exact exponent shift: the graph feeds that |
| 26 | //! GEMV the same 2^64-scaled row as the FP8 ones, so its output comes out plain). |
| 27 | //! conv1d, A_log, dt_bias and the gated norm weight go to [`aien_omega_q38::Gdn`] as stored. |
| 28 | //! - Attention layer: `q_proj | k_proj | v_proj` -> one FP8 tensor `[14336][5120]`; q_norm / |
| 29 | //! k_norm to [`aien_omega_q38::Attn256Cache`] (folded to `1 + w` and permuted there). |
| 30 | //! - Every layer: `gate_proj | up_proj` -> `[34816][5120]`; o_proj / out_proj and down_proj as |
| 31 | //! stored; input / post-attention norms folded to `1 + w` (the model's zero-centred RMSNorm). |
| 32 | //! - The final norm folded to `1 + w`; lm_head bf16 `[vocab][5120]` as stored. The embedding |
| 33 | //! stays on the host (one row per token is widened and written before the token). |
| 34 | //! BF16 projections are not supported: a checkpoint without FP8 e4m3 block scales is refused. |
| 35 | //! |
| 36 | //! The decode graph covers one token at a time; prompts run through it token by token until the |
| 37 | //! prefill path lands (sc #642 step 9). |
| 38 | use std::path::Path; |
| 39 | |
| 40 | use aien_omega_bf16::Bf16Tensor; |
| 41 | use aien_omega_fp8::Fp8Tensor; |
| 42 | use aien_omega_gpu::ResidentTensor; |
| 43 | use aien_omega_q38::q36::Q36Graph; |
| 44 | use aien_omega_q38::{Attn256Cache, Gdn, GraphConfig, GraphStats, Q38Graph}; |
| 45 | use aien_omega_router::Router; |
| 46 | |
| 47 | mod moe; |
| 48 | pub use moe::router_probe; |
| 49 | mod prefill; |
| 50 | mod rows; |
| 51 | pub use rows::{RowFeed, RowOut, RowTest}; |
| 52 | mod session; |
| 53 | pub use prefill::PrefillStats; |
| 54 | pub use session::{plan_reuse, FeedStats, Qwen38Session, Reuse, IM_START}; |
| 55 | |
| 56 | use crate::qwen38::{read_bf16_words, read_matrix, read_vec, text_prefix, Matrix, Qwen38Config}; |
| 57 | use crate::qwen3_moe::bf16_to_f32; |
| 58 | use crate::qwen3_moe_omega::{ShardSource, TensorSource}; |
| 59 | |
| 60 | /// l2norm eps of the DeltaNet q/k (the reference's constant). |
| 61 | const EPS_L2: f32 = 1e-6; |
| 62 | |
| 63 | /// One layer's device tensors (kept alive for the graph). Projections are FP8. The DeltaNet a|b |
| 64 | /// tensor stays bf16, which is the graph's existing GEMV, not a bf16 projection path. |
| 65 | struct LayerTensors { |
| 66 | mix: Fp8Tensor, |
| 67 | ab: Option<Bf16Tensor>, |
| 68 | o: Fp8Tensor, |
| 69 | gate_up: Fp8Tensor, |
| 70 | down: Fp8Tensor, |
| 71 | } |
| 72 | |
| 73 | /// The decode graph: the 27B's dense one or the 35B's sparse one (sc L306). |
| 74 | enum Graph { |
| 75 | Dense(Q38Graph), |
| 76 | Moe(Q36Graph), |
| 77 | } |
| 78 | |
| 79 | impl Graph { |
| 80 | fn token( |
| 81 | &mut self, |
| 82 | x: &[f32], |
| 83 | pos: usize, |
| 84 | ) -> Result<(u32, GraphStats), aien_omega_gpu::OmegaGpuError> { |
| 85 | match self { |
| 86 | Graph::Dense(g) => g.token(x, pos), |
| 87 | Graph::Moe(g) => g.token(x, pos), |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | fn read( |
| 92 | &mut self, |
| 93 | x: Option<&mut [f32]>, |
| 94 | hidden: Option<&mut [f32]>, |
| 95 | logits: Option<&mut [f32]>, |
| 96 | ) -> Result<(), aien_omega_gpu::OmegaGpuError> { |
| 97 | match self { |
| 98 | Graph::Dense(g) => g.read(x, hidden, logits), |
| 99 | Graph::Moe(g) => g.read(x, hidden, logits), |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// One stroke of `pos.len()` heads (the 35B graph; the 27B dense graph strokes one). |
| 104 | fn stroke(&mut self, x: &[f32], pos: &[usize]) -> Result<(Vec<u32>, GraphStats), String> { |
| 105 | match self { |
| 106 | Graph::Dense(g) if pos.len() == 1 => g |
| 107 | .token(x, pos[0]) |
| 108 | .map(|(t, s)| (vec![t], s)) |
| 109 | .map_err(gpu("q38 token")), |
| 110 | Graph::Dense(_) => Err("the 27B dense graph strokes one conversation".into()), |
| 111 | Graph::Moe(g) => g.stroke(x, pos).map_err(gpu("q36 stroke")), |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn read_head( |
| 116 | &mut self, |
| 117 | head: usize, |
| 118 | x: Option<&mut [f32]>, |
| 119 | hidden: Option<&mut [f32]>, |
| 120 | logits: Option<&mut [f32]>, |
| 121 | ) -> Result<(), String> { |
| 122 | match self { |
| 123 | Graph::Dense(g) if head == 0 => g.read(x, hidden, logits).map_err(gpu("q38 read")), |
| 124 | Graph::Dense(_) => Err("the 27B dense graph has one head".into()), |
| 125 | Graph::Moe(g) => g |
| 126 | .read_head(head, x, hidden, logits) |
| 127 | .map_err(gpu("q36 read head")), |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// One conversation's state on the chip: what a head slot of the graph points at. |
| 133 | #[derive(Default)] |
| 134 | pub(crate) struct HeadState { |
| 135 | pub(crate) gdn: Option<Gdn>, |
| 136 | pub(crate) attn: Option<Attn256Cache>, |
| 137 | pub(crate) pos: usize, |
| 138 | } |
| 139 | |
| 140 | /// The whole model resident on the device plus the host embedding. |
| 141 | /// |
| 142 | /// Field order is drop order: the graph goes first, then the tensors and state it points at. |
| 143 | pub struct Qwen38Omega { |
| 144 | graph: Graph, |
| 145 | /// The rows' multi-conversation graph (L312's strokes): its head slots are pointed at the rows |
| 146 | /// of each [`Self::step_rows`] chunk; it points at their state, so it drops before them. |
| 147 | row_stroke: Option<Q36Graph>, |
| 148 | /// Extra conversations over the same weights (the 35B only, [`Self::add_rows`]); they point at |
| 149 | /// the router, lm_head and layers below, so they drop right after the main graph. |
| 150 | rows: Vec<rows::Q36Row>, |
| 151 | /// The 35B's router (sparse MLP only); the graph points at it, so it drops after the graph. |
| 152 | #[allow(dead_code)] // owned only |
| 153 | router: Option<Router>, |
| 154 | layers: Vec<LayerTensors>, |
| 155 | lm_head: Bf16Tensor, |
| 156 | /// FP8 copy of lm_head (env `AIEN_Q38_FP8_HEAD=1`, qwen38/decode-speed): the decode graph reads it instead. |
| 157 | #[allow(dead_code)] // owned only: the graph points at it until it is dropped first |
| 158 | lm_head8: Option<Fp8Tensor>, |
| 159 | /// The exact two-pass head screen (35B default; 27B opt-in with `AIEN_Q38_EXACT_HEAD=1`): the fp8b copy |
| 160 | /// of lm_head the graph screens with, for greedy tokens only ([`Self::set_exact_head_on`]). |
| 161 | #[allow(dead_code)] // owned only: the graph points at it until it is dropped first |
| 162 | head_screen: Option<Fp8Tensor>, |
| 163 | gdn: Option<Gdn>, |
| 164 | attn: Option<Attn256Cache>, |
| 165 | /// Heads 1.. of a multi-conversation graph ([`Self::open_window_heads`]): each one's own |
| 166 | /// DeltaNet state and attention cache (the graph points at them: they drop after it) and |
| 167 | /// position. Head 0 is `gdn`, `attn`, `pos` above. |
| 168 | extra_heads: Vec<HeadState>, |
| 169 | pub config: Qwen38Config, |
| 170 | /// bf16 `[vocab][hidden]`. |
| 171 | embed: Vec<u16>, |
| 172 | /// Tokens the state holds (the next token's position). |
| 173 | pub pos: usize, |
| 174 | max_pos: usize, |
| 175 | /// Every layer's (input, post-attention) norm weight and the final norm, folded to `1 + w`: |
| 176 | /// the prefill normalises on the host. |
| 177 | norms: Vec<(Vec<f32>, Vec<f32>)>, |
| 178 | final_norm: Vec<f32>, |
| 179 | /// in_proj_a|b of every DeltaNet layer for the prefill's batched projection, `[5120][96]` |
| 180 | /// (the graph's interleaved rows transposed, plain values) on omega's resident bf16 matmul. |
| 181 | ab_mm: Vec<ResidentTensor>, |
| 182 | /// The prefill's buffers, made by the first [`Self::prefill`]. |
| 183 | pf: Option<prefill::PfState>, |
| 184 | /// What a new row needs (the 35B only). |
| 185 | row_src: Option<rows::RowSource>, |
| 186 | /// Multi-row steps so far (the row-swap negative control counts them). |
| 187 | row_steps: u64, |
| 188 | } |
| 189 | |
| 190 | impl std::fmt::Debug for Qwen38Omega { |
| 191 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 192 | write!( |
| 193 | f, |
| 194 | "Qwen38Omega {{ layers: {}, pos: {}, max_pos: {} }}", |
| 195 | self.config.layers, self.pos, self.max_pos |
| 196 | ) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// The DeltaNet tails and states at a position ([`Qwen38Omega::snapshot`]), in host memory. |
| 201 | #[derive(Debug, Default, Clone)] |
| 202 | pub struct Qwen38Snapshot { |
| 203 | pub pos: usize, |
| 204 | tails: Vec<f32>, |
| 205 | states: Vec<f32>, |
| 206 | } |
| 207 | |
| 208 | impl Qwen38Snapshot { |
| 209 | /// The first f32 (tails, then states) whose bits differ from `o`'s, or the length when one |
| 210 | /// holds more; `None`: the same position and the same bits throughout. |
| 211 | pub fn first_diff(&self, o: &Self) -> Option<usize> { |
| 212 | let a = self.tails.iter().chain(&self.states); |
| 213 | let b = o.tails.iter().chain(&o.states); |
| 214 | if let Some(i) = a.zip(b).position(|(x, y)| x.to_bits() != y.to_bits()) { |
| 215 | return Some(i); |
| 216 | } |
| 217 | let (na, nb) = ( |
| 218 | self.tails.len() + self.states.len(), |
| 219 | o.tails.len() + o.states.len(), |
| 220 | ); |
| 221 | (na != nb || self.pos != o.pos).then_some(na.min(nb)) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Memory the whole model needs with a KV cache of `max_pos` positions and prefill buffers for |
| 226 | /// `chunk` tokens (device and host: the box's memory is one pool). Counted from the config: |
| 227 | /// weights, KV cache, prefill buffers, the host embedding table and one state snapshot, plus |
| 228 | /// `RUNTIME_SLACK` for what the count misses (allocator rounding, the tokenizer, host staging). |
| 229 | /// The 2026-10-18 128k TTFT run measured RSS 39 GiB where the old count said 35.5 GiB; the |
| 230 | /// embedding (2.37 GiB) and the slack close that gap. |
| 231 | pub fn need_bytes(c: &Qwen38Config, max_pos: usize, chunk: usize) -> u64 { |
| 232 | const RUNTIME_SLACK: u64 = 3 << 30; |
| 233 | let h = c.hidden as u64; |
| 234 | if let Some(m) = &c.moe { |
| 235 | // Qwen3.6-35B-A3B (sc L306): FP8 mixers and experts (routed + shared, one byte per weight |
| 236 | // plus a bf16 scale per 128 x 128 block), bf16 a|b, router, lm_head and host embedding; no |
| 237 | // prefill buffers (the prompt runs through the decode graph). |
| 238 | let experts = (m.experts + 1) as u64 * 3 * m.expert_inter as u64 * h; |
| 239 | let o = h * (c.heads * c.head_dim) as u64; |
| 240 | let fp8: u64 = c |
| 241 | .full_attention |
| 242 | .iter() |
| 243 | .map(|&attn| { |
| 244 | let mix = if attn { |
| 245 | (2 * c.heads * c.head_dim + 2 * c.kv_dim()) as u64 * h |
| 246 | } else { |
| 247 | (c.conv_dim() + c.lin_value_dim()) as u64 * h |
| 248 | }; |
| 249 | mix + o + experts |
| 250 | }) |
| 251 | .sum(); |
| 252 | let n_attn = c.full_attention.iter().filter(|&&a| a).count() as u64; |
| 253 | let n_gdn = c.layers as u64 - n_attn; |
| 254 | let ab = n_gdn * 2 * 2 * c.lin_v_heads as u64 * h; |
| 255 | let router = c.layers as u64 * 2 * (m.experts + 1) as u64 * h; |
| 256 | let weights = fp8 + fp8 / 8192 + ab + router + 2 * c.vocab as u64 * h; |
| 257 | let kv = n_attn * 2 * c.kv_heads as u64 * max_pos as u64 * 2 * c.head_dim as u64 |
| 258 | + max_pos as u64 * 1024; |
| 259 | let embed = 2 * c.vocab as u64 * h; |
| 260 | let tail = (c.conv_kernel as u64 - 1) * c.conv_dim() as u64; |
| 261 | let st = (c.lin_v_heads * c.lin_v_dim * c.lin_v_dim) as u64; |
| 262 | let state = n_gdn * 4 * (tail + st); |
| 263 | let _ = chunk; |
| 264 | return weights + kv + embed + 2 * state + RUNTIME_SLACK; |
| 265 | } |
| 266 | let mlp = 3 * c.intermediate as u64 * h; |
| 267 | let o = h * (c.heads * c.head_dim) as u64; |
| 268 | let layers: u64 = c |
| 269 | .full_attention |
| 270 | .iter() |
| 271 | .map(|&attn| { |
| 272 | if attn { |
| 273 | (2 * c.heads * c.head_dim + 2 * c.kv_dim()) as u64 * h + o + mlp |
| 274 | } else { |
| 275 | (c.conv_dim() + c.lin_value_dim()) as u64 * h |
| 276 | + o |
| 277 | + mlp |
| 278 | + 4 * 2 * 2 * c.lin_v_heads as u64 * h |
| 279 | } |
| 280 | }) |
| 281 | .sum(); |
| 282 | // FP8: one byte per weight plus the block scales. BF16 projections are not supported. |
| 283 | let weights = layers + layers / 4096 + 2 * c.vocab as u64 * h; |
| 284 | let n_attn = c.full_attention.iter().filter(|&&a| a).count() as u64; |
| 285 | let n_gdn = c.layers as u64 - n_attn; |
| 286 | let kv = n_attn * 2 * 4 * max_pos as u64 * 512 + max_pos as u64 * 1024; |
| 287 | // xin, xq, xs, mix, act, out, plus the DeltaNet prefill scratch (omega_gpu_gdn_api.h), at |
| 288 | // the 27B widths (the widest the dense graph takes: an upper bound for smaller shapes). |
| 289 | let m = chunk as u64; |
| 290 | let bufs = m * (6144 * 4 + 17408 + 136 * 4 + 16384 * 4 + 17408 * 2 + 5120 * 4) |
| 291 | + m * (40960 + 3 * 24576 + 384) |
| 292 | + m.div_ceil(8) * 8 * 74496; |
| 293 | let embed = 2 * c.vocab as u64 * h; |
| 294 | let state = |
| 295 | n_gdn * 4 * (aien_omega_q38::GDN_TAIL_FLOATS + aien_omega_q38::GDN_STATE_FLOATS) as u64; |
| 296 | // Device state plus one host snapshot. |
| 297 | let extra = if std::env::var("AIEN_Q38_EXACT_HEAD").as_deref() == Ok("1") { |
| 298 | aien_omega_q38::exact_head_extra_bytes() |
| 299 | } else { |
| 300 | 0 |
| 301 | }; |
| 302 | weights + kv + bufs + embed + 2 * state + RUNTIME_SLACK + extra |
| 303 | } |
| 304 | |
| 305 | fn gpu(stage: &str) -> impl Fn(aien_omega_gpu::OmegaGpuError) -> String + '_ { |
| 306 | move |e| format!("{stage}: {e}") |
| 307 | } |
| 308 | |
| 309 | /// The dense graph's shape for a checkpoint, or why it does not fit: 256-wide attention heads, |
| 310 | /// 16 DeltaNet key heads of 128, value heads of 128, conv kernel 4 (Qwen3.8-27B and Qwen3.5-9B), |
| 311 | /// and widths within [`aien_omega_q38::Shape::check`]. |
| 312 | pub fn dense_shape(c: &Qwen38Config) -> Result<aien_omega_q38::Shape, String> { |
| 313 | use aien_omega_q38 as q; |
| 314 | let fixed = c.head_dim == q::HEAD_DIM |
| 315 | && c.lin_k_heads == 16 |
| 316 | && c.lin_k_dim == q::GDN_HEAD_DIM |
| 317 | && c.lin_v_dim == q::GDN_HEAD_DIM |
| 318 | && c.conv_kernel == q::GDN_CONV_KERNEL |
| 319 | && c.kv_heads > 0; |
| 320 | let shape = q::Shape { |
| 321 | hidden: c.hidden, |
| 322 | inter: c.intermediate, |
| 323 | q_heads: c.heads, |
| 324 | kv_heads: c.kv_heads, |
| 325 | gdn_heads: c.lin_v_heads, |
| 326 | }; |
| 327 | if !fixed || shape.check().is_err() { |
| 328 | return Err(format!( |
| 329 | "qwen38 omega: the checkpoint's shape ({shape:?}, head_dim {}, DeltaNet {} key heads of {} / value dim {}, conv {}) is not one the dense graph takes", |
| 330 | c.head_dim, c.lin_k_heads, c.lin_k_dim, c.lin_v_dim, c.conv_kernel |
| 331 | )); |
| 332 | } |
| 333 | Ok(shape) |
| 334 | } |
| 335 | |
| 336 | /// `1 + w`, the zero-centred RMSNorm weight the graph's norms multiply by. |
| 337 | fn fold(w: Vec<f32>) -> Vec<f32> { |
| 338 | w.into_iter().map(|v| 1.0 + v).collect() |
| 339 | } |
| 340 | |
| 341 | fn upload_fp8(name: &str, m: Matrix) -> Result<Fp8Tensor, String> { |
| 342 | fuse_fp8(name, vec![m]) |
| 343 | } |
| 344 | |
| 345 | /// FP8 projections stacked by rows into one tensor (every part `[n_i][k]`, whole 128 blocks). |
| 346 | fn fuse_fp8(name: &str, parts: Vec<Matrix>) -> Result<Fp8Tensor, String> { |
| 347 | let (mut n, mut k0) = (0usize, None); |
| 348 | let (mut w, mut scales) = (Vec::new(), Vec::new()); |
| 349 | for m in parts { |
| 350 | match m { |
| 351 | Matrix::Fp8 { |
| 352 | n: pn, |
| 353 | k, |
| 354 | w: pw, |
| 355 | scales: ps, |
| 356 | } => { |
| 357 | if *k0.get_or_insert(k) != k { |
| 358 | return Err(format!("{name}: parts with different k")); |
| 359 | } |
| 360 | n += pn; |
| 361 | w.extend_from_slice(&pw); |
| 362 | scales.extend_from_slice(&ps); |
| 363 | } |
| 364 | Matrix::Bf16 { .. } => { |
| 365 | return Err(format!( |
| 366 | "{name}: a bf16 part (BF16 projections are not supported; the graph takes FP8)" |
| 367 | )) |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | let k = k0.ok_or_else(|| format!("{name}: no parts"))?; |
| 372 | Fp8Tensor::upload(1, n, k, &w, &scales).map_err(gpu(name)) |
| 373 | } |
| 374 | |
| 375 | /// `in_proj_a` / `in_proj_b` interleaved by rows and scaled by 2^-64 (exact for every normal |
| 376 | /// bf16: only the exponent moves; the checkpoint's values sit far above 2^-62). |
| 377 | fn ab_rows(a: &Matrix, b: &Matrix) -> Result<(usize, usize, Vec<u16>), String> { |
| 378 | let ( |
| 379 | Matrix::Bf16 { n, k, w: wa }, |
| 380 | Matrix::Bf16 { |
| 381 | n: nb, |
| 382 | k: kb, |
| 383 | w: wb, |
| 384 | }, |
| 385 | ) = (a, b) |
| 386 | else { |
| 387 | return Err("in_proj_a / in_proj_b: expected bf16".into()); |
| 388 | }; |
| 389 | if (n, k) != (nb, kb) { |
| 390 | return Err("in_proj_a / in_proj_b: shapes differ".into()); |
| 391 | } |
| 392 | let scale = (2.0f32).powi(-64); |
| 393 | let shift = |v: u16| -> Result<u16, String> { |
| 394 | let x = bf16_to_f32(v) * scale; |
| 395 | let bits = x.to_bits(); |
| 396 | if x != 0.0 && (bits & 0xffff) != 0 { |
| 397 | return Err(format!( |
| 398 | "in_proj_a/b: {} * 2^-64 is not exact in bf16", |
| 399 | bf16_to_f32(v) |
| 400 | )); |
| 401 | } |
| 402 | Ok((bits >> 16) as u16) |
| 403 | }; |
| 404 | let mut out = Vec::with_capacity(2 * n * k); |
| 405 | for h in 0..*n { |
| 406 | for row in [&wa[h * k..(h + 1) * k], &wb[h * k..(h + 1) * k]] { |
| 407 | for &v in row { |
| 408 | out.push(shift(v)?); |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 | Ok((2 * n, *k, out)) |
| 413 | } |
| 414 | |
| 415 | /// [`ab_rows`]' `[n][k]` words back at the checkpoint's values (times 2^64, exact: the reverse |
| 416 | /// exponent shift) and transposed to `[k][n]`, the resident matmul's B layout. |
| 417 | fn ab_plain_transposed(n: usize, k: usize, w: &[u16]) -> Vec<u16> { |
| 418 | let unscale = |v: u16| ((bf16_to_f32(v) * aien_omega_q38::ROW_SCALE).to_bits() >> 16) as u16; |
| 419 | let mut t = vec![0u16; n * k]; |
| 420 | for (j, row) in w.chunks_exact(k).enumerate() { |
| 421 | for (i, &v) in row.iter().enumerate() { |
| 422 | t[i * n + j] = unscale(v); |
| 423 | } |
| 424 | } |
| 425 | t |
| 426 | } |
| 427 | |
| 428 | impl Qwen38Omega { |
| 429 | /// Opens a checkpoint directory and uploads its first `layers` layers (all when `None`) with |
| 430 | /// a KV cache of `max_pos` positions per attention layer. |
| 431 | pub fn open(dir: &Path, layers: Option<usize>, max_pos: usize) -> Result<Self, String> { |
| 432 | let full = Qwen38Config::from_checkpoint(dir)?; |
| 433 | let config = match layers { |
| 434 | None => full, |
| 435 | Some(n) => full |
| 436 | .prefix(n) |
| 437 | .ok_or_else(|| format!("layers {n}: outside 1..={}", full.layers))?, |
| 438 | }; |
| 439 | Self::load(config, &mut ShardSource::open(dir)?, max_pos) |
| 440 | } |
| 441 | |
| 442 | /// Opens a checkpoint directory and uploads model layers `first .. first + count` as a stack |
| 443 | /// of their own (final norm and lm_head on top): a window, fed and read through |
| 444 | /// [`Self::step_residual`] / [`Self::residual`] so a model larger than free device memory is |
| 445 | /// checked one window at a time. |
| 446 | pub fn open_window( |
| 447 | dir: &Path, |
| 448 | first: usize, |
| 449 | count: usize, |
| 450 | max_pos: usize, |
| 451 | ) -> Result<Self, String> { |
| 452 | let full = Qwen38Config::from_checkpoint(dir)?; |
| 453 | let config = full |
| 454 | .window(first, count) |
| 455 | .ok_or_else(|| format!("window {first}+{count}: outside the {} layers", full.layers))?; |
| 456 | Self::load_at(config, first, &mut ShardSource::open(dir)?, max_pos) |
| 457 | } |
| 458 | |
| 459 | /// As [`Self::open_window`] with `heads` conversations resident at once (the 35B graph only, |
| 460 | /// at most [`aien_omega_q38::q36::MAX_HEADS`]): one [`Self::stroke`] advances every head in |
| 461 | /// one command list. Each head has its own DeltaNet state, attention cache and position. |
| 462 | pub fn open_window_heads( |
| 463 | dir: &Path, |
| 464 | first: usize, |
| 465 | count: usize, |
| 466 | max_pos: usize, |
| 467 | heads: usize, |
| 468 | ) -> Result<Self, String> { |
| 469 | let full = Qwen38Config::from_checkpoint(dir)?; |
| 470 | let config = full |
| 471 | .window(first, count) |
| 472 | .ok_or_else(|| format!("window {first}+{count}: outside the {} layers", full.layers))?; |
| 473 | Self::load_at_heads(config, first, &mut ShardSource::open(dir)?, max_pos, heads) |
| 474 | } |
| 475 | |
| 476 | /// Uploads `config.layers` layers from `source`. |
| 477 | pub fn load( |
| 478 | config: Qwen38Config, |
| 479 | source: &mut dyn TensorSource, |
| 480 | max_pos: usize, |
| 481 | ) -> Result<Self, String> { |
| 482 | Self::load_at(config, 0, source, max_pos) |
| 483 | } |
| 484 | |
| 485 | /// Uploads `config.layers` layers from `source`, reading model layer `first + l` for layer `l`. |
| 486 | fn load_at( |
| 487 | config: Qwen38Config, |
| 488 | first: usize, |
| 489 | source: &mut dyn TensorSource, |
| 490 | max_pos: usize, |
| 491 | ) -> Result<Self, String> { |
| 492 | Self::load_at_heads(config, first, source, max_pos, 1) |
| 493 | } |
| 494 | |
| 495 | /// [`Self::load_at`] with `heads` resident conversations (1 for the 27B dense graph). |
| 496 | fn load_at_heads( |
| 497 | config: Qwen38Config, |
| 498 | first: usize, |
| 499 | source: &mut dyn TensorSource, |
| 500 | max_pos: usize, |
| 501 | heads: usize, |
| 502 | ) -> Result<Self, String> { |
| 503 | if config.moe.is_some() { |
| 504 | return Self::load_moe(config, first, source, max_pos, heads); |
| 505 | } |
| 506 | if heads != 1 { |
| 507 | return Err(format!( |
| 508 | "qwen38 omega: {heads} heads (the dense graph strokes one conversation)" |
| 509 | )); |
| 510 | } |
| 511 | use aien_omega_q38 as q; |
| 512 | let c = &config; |
| 513 | let shape = dense_shape(c)?; |
| 514 | if c.layers > q::MAX_LAYERS { |
| 515 | return Err(format!( |
| 516 | "qwen38 omega: {} layers (at most {})", |
| 517 | c.layers, |
| 518 | q::MAX_LAYERS |
| 519 | )); |
| 520 | } |
| 521 | let prefix = text_prefix(source)?; |
| 522 | let (v, h) = (c.vocab, c.hidden); |
| 523 | let embed = read_bf16_words(source, &format!("{prefix}embed_tokens.weight"), &[v, h])?; |
| 524 | let final_norm = fold(read_vec(source, &format!("{prefix}norm.weight"), h)?); |
| 525 | let exact = std::env::var("AIEN_Q38_EXACT_HEAD").as_deref() == Ok("1"); |
| 526 | if exact && aien_omega_q38::exact_head_extra_bytes() == 0 { |
| 527 | return Err("the linked Omega library does not support the 27B exact head".into()); |
| 528 | } |
| 529 | if exact && std::env::var("AIEN_Q38_FP8_HEAD").as_deref() == Ok("1") { |
| 530 | return Err("choose either the exact head or the approximate FP8 head".into()); |
| 531 | } |
| 532 | let (lm_head, lm_head8, head_screen, head_coef) = |
| 533 | match read_matrix(source, "lm_head.weight", v, h)? { |
| 534 | Matrix::Bf16 { n, k, w } => { |
| 535 | let head8 = if std::env::var("AIEN_Q38_FP8_HEAD").as_deref() == Ok("1") { |
| 536 | let (w8, s) = aien_omega_q38::quantize_fp8_bf16(n, k, &w, 16) |
| 537 | .map_err(gpu("lm_head fp8 quantise"))?; |
| 538 | Some(Fp8Tensor::upload(1, n, k, &w8, &s).map_err(gpu("lm_head fp8"))?) |
| 539 | } else { |
| 540 | None |
| 541 | }; |
| 542 | let full = Bf16Tensor::upload(n, k, &w).map_err(gpu("lm_head"))?; |
| 543 | let (screen, coef) = if exact { |
| 544 | let matrix = Matrix::Bf16 { n, k, w }; |
| 545 | // The Omega 5120-wide plan admits this conservative rounding count. |
| 546 | let (codes, scales, coef) = |
| 547 | crate::exact_head::chip_screen_with_roundings(&matrix, 10384)?; |
| 548 | ( |
| 549 | Some( |
| 550 | Fp8Tensor::upload(1, n, k, &codes, &scales) |
| 551 | .map_err(gpu("exact lm_head"))?, |
| 552 | ), |
| 553 | coef, |
| 554 | ) |
| 555 | } else { |
| 556 | (None, Vec::new()) |
| 557 | }; |
| 558 | (full, head8, screen, coef) |
| 559 | } |
| 560 | Matrix::Fp8 { .. } => { |
| 561 | return Err("lm_head: FP8 (the graph takes a bf16 head)".into()) |
| 562 | } |
| 563 | }; |
| 564 | |
| 565 | let n_attn = c.full_attention.iter().filter(|&&a| a).count(); |
| 566 | let n_gdn = c.layers - n_attn; |
| 567 | let mut gdn = if n_gdn > 0 { |
| 568 | Some(Gdn::alloc_ratio(n_gdn, c.lin_v_heads / c.lin_k_heads).map_err(gpu("gdn alloc"))?) |
| 569 | } else { |
| 570 | None |
| 571 | }; |
| 572 | // The 27B keeps omega's default attention shape (zeros); others name their heads. |
| 573 | let (aq, akv, agroup) = if shape == q::Shape::Q38_27B { |
| 574 | (0, 0, 0) |
| 575 | } else { |
| 576 | (c.heads, c.kv_heads, c.heads / c.kv_heads) |
| 577 | }; |
| 578 | let mut attn = if n_attn > 0 { |
| 579 | Some( |
| 580 | Attn256Cache::alloc_shape( |
| 581 | n_attn, |
| 582 | max_pos, |
| 583 | c.rope_theta, |
| 584 | c.rotary_dim, |
| 585 | aq, |
| 586 | akv, |
| 587 | agroup, |
| 588 | ) |
| 589 | .map_err(gpu("attn256 alloc"))?, |
| 590 | ) |
| 591 | } else { |
| 592 | None |
| 593 | }; |
| 594 | let attn_mask = c |
| 595 | .full_attention |
| 596 | .iter() |
| 597 | .enumerate() |
| 598 | .fold(0u64, |m, (l, &a)| if a { m | 1 << l } else { m }); |
| 599 | |
| 600 | let mut layers = Vec::with_capacity(c.layers); |
| 601 | let mut norms = Vec::with_capacity(c.layers); |
| 602 | let mut ab_mm = Vec::with_capacity(n_gdn); |
| 603 | let (mut gi, mut ai) = (0usize, 0usize); |
| 604 | for l in 0..c.layers { |
| 605 | let p = format!("{prefix}layers.{}", first + l); |
| 606 | let rm = |s: &mut dyn TensorSource, name: String, n, k| read_matrix(s, &name, n, k); |
| 607 | let (mix, ab, o) = if c.full_attention[l] { |
| 608 | let a = format!("{p}.self_attn"); |
| 609 | let mix = fuse_fp8( |
| 610 | &format!("{a} q|k|v"), |
| 611 | vec![ |
| 612 | rm( |
| 613 | source, |
| 614 | format!("{a}.q_proj.weight"), |
| 615 | 2 * c.heads * c.head_dim, |
| 616 | h, |
| 617 | )?, |
| 618 | rm(source, format!("{a}.k_proj.weight"), c.kv_dim(), h)?, |
| 619 | rm(source, format!("{a}.v_proj.weight"), c.kv_dim(), h)?, |
| 620 | ], |
| 621 | )?; |
| 622 | let o = upload_fp8( |
| 623 | &format!("{a}.o_proj"), |
| 624 | rm( |
| 625 | source, |
| 626 | format!("{a}.o_proj.weight"), |
| 627 | h, |
| 628 | c.heads * c.head_dim, |
| 629 | )?, |
| 630 | )?; |
| 631 | let q_norm = read_vec(source, &format!("{a}.q_norm.weight"), c.head_dim)?; |
| 632 | let k_norm = read_vec(source, &format!("{a}.k_norm.weight"), c.head_dim)?; |
| 633 | attn.as_mut() |
| 634 | .expect("an attention layer has a cache") |
| 635 | .set_norms(ai, &q_norm, &k_norm) |
| 636 | .map_err(gpu("attn256 set_norms"))?; |
| 637 | ai += 1; |
| 638 | (mix, None, o) |
| 639 | } else { |
| 640 | let a = format!("{p}.linear_attn"); |
| 641 | let mix = fuse_fp8( |
| 642 | &format!("{a} qkv|z"), |
| 643 | vec![ |
| 644 | rm(source, format!("{a}.in_proj_qkv.weight"), c.conv_dim(), h)?, |
| 645 | rm( |
| 646 | source, |
| 647 | format!("{a}.in_proj_z.weight"), |
| 648 | c.lin_value_dim(), |
| 649 | h, |
| 650 | )?, |
| 651 | ], |
| 652 | )?; |
| 653 | let ia = rm(source, format!("{a}.in_proj_a.weight"), c.lin_v_heads, h)?; |
| 654 | let ib = rm(source, format!("{a}.in_proj_b.weight"), c.lin_v_heads, h)?; |
| 655 | let (an, ak, aw) = ab_rows(&ia, &ib).map_err(|e| format!("{a}: {e}"))?; |
| 656 | let ab = Bf16Tensor::upload(an, ak, &aw).map_err(gpu("in_proj_a|b"))?; |
| 657 | ab_mm.push( |
| 658 | ResidentTensor::upload_bf16(ak, an, &ab_plain_transposed(an, ak, &aw)) |
| 659 | .map_err(gpu("in_proj_a|b matmul"))?, |
| 660 | ); |
| 661 | let o = upload_fp8( |
| 662 | &format!("{a}.out_proj"), |
| 663 | rm(source, format!("{a}.out_proj.weight"), h, c.lin_value_dim())?, |
| 664 | )?; |
| 665 | let conv: Vec<f32> = read_bf16_words( |
| 666 | source, |
| 667 | &format!("{a}.conv1d.weight"), |
| 668 | &[c.conv_dim(), 1, c.conv_kernel], |
| 669 | )? |
| 670 | .into_iter() |
| 671 | .map(bf16_to_f32) |
| 672 | .collect(); |
| 673 | let a_log = read_vec(source, &format!("{a}.A_log"), c.lin_v_heads)?; |
| 674 | let dt_bias = read_vec(source, &format!("{a}.dt_bias"), c.lin_v_heads)?; |
| 675 | let norm = read_vec(source, &format!("{a}.norm.weight"), c.lin_v_dim)?; |
| 676 | gdn.as_mut() |
| 677 | .expect("a DeltaNet layer has state") |
| 678 | .set_layer(gi, &conv, &a_log, &dt_bias, &norm) |
| 679 | .map_err(gpu("gdn set_layer"))?; |
| 680 | gi += 1; |
| 681 | (mix, Some(ab), o) |
| 682 | }; |
| 683 | let m = format!("{p}.mlp"); |
| 684 | let gate_up = fuse_fp8( |
| 685 | &format!("{m} gate|up"), |
| 686 | vec![ |
| 687 | rm(source, format!("{m}.gate_proj.weight"), c.intermediate, h)?, |
| 688 | rm(source, format!("{m}.up_proj.weight"), c.intermediate, h)?, |
| 689 | ], |
| 690 | )?; |
| 691 | let down = upload_fp8( |
| 692 | &format!("{m}.down_proj"), |
| 693 | rm(source, format!("{m}.down_proj.weight"), h, c.intermediate)?, |
| 694 | )?; |
| 695 | let in_norm = fold(read_vec(source, &format!("{p}.input_layernorm.weight"), h)?); |
| 696 | let post_norm = fold(read_vec( |
| 697 | source, |
| 698 | &format!("{p}.post_attention_layernorm.weight"), |
| 699 | h, |
| 700 | )?); |
| 701 | layers.push(LayerTensors { |
| 702 | mix, |
| 703 | ab, |
| 704 | o, |
| 705 | gate_up, |
| 706 | down, |
| 707 | }); |
| 708 | norms.push((in_norm, post_norm)); |
| 709 | } |
| 710 | |
| 711 | let mut cfg = GraphConfig { |
| 712 | layers: c.layers as u32, |
| 713 | attn_mask, |
| 714 | vocab: v as u32, |
| 715 | eps: c.eps, |
| 716 | eps_l2: EPS_L2, |
| 717 | gdn: gdn.as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw), |
| 718 | attn: attn |
| 719 | .as_ref() |
| 720 | .map_or(std::ptr::null_mut(), Attn256Cache::as_raw), |
| 721 | lm_head: lm_head.as_raw(), |
| 722 | hidden: 0, |
| 723 | inter: 0, |
| 724 | q_heads: 0, |
| 725 | kv_heads: 0, |
| 726 | gdn_heads: 0, |
| 727 | }; |
| 728 | cfg.set_shape(shape); |
| 729 | // SAFETY: gdn, attn and lm_head are live omega objects owned by the returned value, which |
| 730 | // drops the graph before them (field order). |
| 731 | let mut graph = unsafe { Q38Graph::create(&cfg) }.map_err(gpu("q38 graph create"))?; |
| 732 | for (l, (t, (in_norm, post_norm))) in layers.iter().zip(&norms).enumerate() { |
| 733 | let ab = |
| 734 | t.ab.as_ref() |
| 735 | .map_or(std::ptr::null_mut(), Bf16Tensor::as_raw); |
| 736 | // SAFETY: the tensors live in `layers`, owned by the returned value and dropped after |
| 737 | // the graph. BF16 projections are not supported. |
| 738 | unsafe { |
| 739 | graph.set_layer( |
| 740 | l, |
| 741 | t.mix.as_raw(), |
| 742 | ab, |
| 743 | t.o.as_raw(), |
| 744 | t.gate_up.as_raw(), |
| 745 | t.down.as_raw(), |
| 746 | in_norm, |
| 747 | post_norm, |
| 748 | ) |
| 749 | } |
| 750 | .map_err(gpu("q38 graph set_layer"))?; |
| 751 | } |
| 752 | graph |
| 753 | .set_final_norm(&final_norm) |
| 754 | .map_err(gpu("q38 graph set_final_norm"))?; |
| 755 | if let Some(h8) = &lm_head8 { |
| 756 | // SAFETY: lm_head8 is owned by the returned value and dropped after the graph (field order). |
| 757 | unsafe { graph.set_lm_head_fp8(h8.as_raw()) } |
| 758 | .map_err(gpu("q38 graph set_lm_head_fp8"))?; |
| 759 | } |
| 760 | if let Some(screen) = &head_screen { |
| 761 | // SAFETY: the returned value owns the tensor after the graph in drop order. |
| 762 | unsafe { graph.set_exact_head(screen.as_raw(), &head_coef, 10384) } |
| 763 | .map_err(gpu("q38 graph exact head"))?; |
| 764 | } |
| 765 | Ok(Self { |
| 766 | graph: Graph::Dense(graph), |
| 767 | router: None, |
| 768 | layers, |
| 769 | lm_head, |
| 770 | lm_head8, |
| 771 | head_screen, |
| 772 | gdn, |
| 773 | attn, |
| 774 | extra_heads: Vec::new(), |
| 775 | config, |
| 776 | embed, |
| 777 | pos: 0, |
| 778 | max_pos, |
| 779 | norms, |
| 780 | final_norm, |
| 781 | ab_mm, |
| 782 | pf: None, |
| 783 | row_stroke: None, |
| 784 | rows: Vec::new(), |
| 785 | row_src: None, |
| 786 | row_steps: 0, |
| 787 | }) |
| 788 | } |
| 789 | |
| 790 | /// Bytes resident on the device for the weights (tensors as uploaded, not the KV cache). |
| 791 | pub fn weight_bytes(&self) -> usize { |
| 792 | self.layers |
| 793 | .iter() |
| 794 | .map(|t| { |
| 795 | t.mix.resident_bytes() |
| 796 | + t.o.resident_bytes() |
| 797 | + t.gate_up.resident_bytes() |
| 798 | + t.down.resident_bytes() |
| 799 | + t.ab.as_ref().map_or(0, Bf16Tensor::resident_bytes) |
| 800 | }) |
| 801 | .sum::<usize>() |
| 802 | + self.lm_head.resident_bytes() |
| 803 | } |
| 804 | |
| 805 | /// Bytes the KV cache holds on the device (every attention layer at `max_pos`). |
| 806 | pub fn kv_bytes(&self) -> usize { |
| 807 | self.attn |
| 808 | .as_ref() |
| 809 | .map_or(0, |a| a.layers() * Attn256Cache::layer_bytes(a.max_pos())) |
| 810 | } |
| 811 | |
| 812 | /// A new sequence: DeltaNet state to zero, position 0 (attention rows are overwritten as the |
| 813 | /// new sequence reaches them). |
| 814 | pub fn reset(&mut self) -> Result<(), String> { |
| 815 | for h in 0..self.heads() { |
| 816 | self.reset_head(h)?; |
| 817 | } |
| 818 | Ok(()) |
| 819 | } |
| 820 | |
| 821 | /// Feeds `token` at the next position: the greedy next token and what the step cost. |
| 822 | pub fn step(&mut self, token: u32) -> Result<(u32, GraphStats), String> { |
| 823 | let (t, h) = (token as usize, self.config.hidden); |
| 824 | if t >= self.config.vocab { |
| 825 | return Err(format!( |
| 826 | "step: token {t} outside the vocab {}", |
| 827 | self.config.vocab |
| 828 | )); |
| 829 | } |
| 830 | if self.pos >= self.max_pos { |
| 831 | return Err(format!( |
| 832 | "step: the KV cache holds {} positions", |
| 833 | self.max_pos |
| 834 | )); |
| 835 | } |
| 836 | let x: Vec<f32> = self.embed[t * h..(t + 1) * h] |
| 837 | .iter() |
| 838 | .map(|&b| bf16_to_f32(b)) |
| 839 | .collect(); |
| 840 | let out = self.graph.token(&x, self.pos).map_err(gpu("q38 token"))?; |
| 841 | self.pos += 1; |
| 842 | Ok(out) |
| 843 | } |
| 844 | |
| 845 | /// Feeds the residual stream `x` (`[hidden]`, what enters this stack's first layer: the |
| 846 | /// previous window's [`Self::residual`]) at the next position instead of a token's embedding. |
| 847 | pub fn step_residual(&mut self, x: &[f32]) -> Result<(u32, GraphStats), String> { |
| 848 | if x.len() != self.config.hidden { |
| 849 | return Err(format!( |
| 850 | "step_residual: {} values (hidden {})", |
| 851 | x.len(), |
| 852 | self.config.hidden |
| 853 | )); |
| 854 | } |
| 855 | if self.pos >= self.max_pos { |
| 856 | return Err(format!( |
| 857 | "step: the KV cache holds {} positions", |
| 858 | self.max_pos |
| 859 | )); |
| 860 | } |
| 861 | let out = self.graph.token(x, self.pos).map_err(gpu("q38 token"))?; |
| 862 | self.pos += 1; |
| 863 | Ok(out) |
| 864 | } |
| 865 | |
| 866 | /// The last step's residual stream after this stack's last layer (`[hidden]`, before the |
| 867 | /// final norm). |
| 868 | pub fn residual(&mut self) -> Result<Vec<f32>, String> { |
| 869 | let mut x = vec![0f32; self.config.hidden]; |
| 870 | self.graph |
| 871 | .read(Some(&mut x), None, None) |
| 872 | .map_err(gpu("q38 read residual"))?; |
| 873 | Ok(x) |
| 874 | } |
| 875 | |
| 876 | /// The last step's logits (`[vocab]`). |
| 877 | pub fn logits(&mut self) -> Result<Vec<f32>, String> { |
| 878 | let mut l = vec![0f32; self.config.vocab]; |
| 879 | self.graph |
| 880 | .read(None, None, Some(&mut l)) |
| 881 | .map_err(gpu("q38 read logits"))?; |
| 882 | Ok(l) |
| 883 | } |
| 884 | |
| 885 | /// Positions the KV cache holds (the longest sequence). |
| 886 | pub fn max_pos(&self) -> usize { |
| 887 | self.max_pos |
| 888 | } |
| 889 | |
| 890 | /// Conversations resident at once (head slots of the graph). |
| 891 | pub fn heads(&self) -> usize { |
| 892 | self.extra_heads.len() + 1 |
| 893 | } |
| 894 | |
| 895 | /// Tokens head `head` holds (its next position). |
| 896 | pub fn head_pos(&self, head: usize) -> Result<usize, String> { |
| 897 | match head { |
| 898 | 0 => Ok(self.pos), |
| 899 | h => self |
| 900 | .extra_heads |
| 901 | .get(h - 1) |
| 902 | .map(|s| s.pos) |
| 903 | .ok_or_else(|| format!("head {h} of {}", self.heads())), |
| 904 | } |
| 905 | } |
| 906 | |
| 907 | pub(super) fn head_pos_mut(&mut self, head: usize) -> Result<&mut usize, String> { |
| 908 | let heads = self.heads(); |
| 909 | match head { |
| 910 | 0 => Ok(&mut self.pos), |
| 911 | h => self |
| 912 | .extra_heads |
| 913 | .get_mut(h - 1) |
| 914 | .map(|s| &mut s.pos) |
| 915 | .ok_or_else(|| format!("head {h} of {heads}")), |
| 916 | } |
| 917 | } |
| 918 | |
| 919 | /// One stroke: feeds `tokens[h]` to head `h` (the first `tokens.len()` heads, at most |
| 920 | /// [`Self::heads`]) at each head's next position in ONE command list, one submit. The greedy |
| 921 | /// next token of every head and what the stroke cost (the chip time is the whole stroke). |
| 922 | pub fn stroke(&mut self, tokens: &[u32]) -> Result<(Vec<u32>, GraphStats), String> { |
| 923 | let (heads, h) = (tokens.len(), self.config.hidden); |
| 924 | if heads == 0 || heads > self.heads() { |
| 925 | return Err(format!("stroke: {heads} tokens on {} heads", self.heads())); |
| 926 | } |
| 927 | let mut x = Vec::with_capacity(heads * h); |
| 928 | let mut pos = Vec::with_capacity(heads); |
| 929 | for (head, &t) in tokens.iter().enumerate() { |
| 930 | let t = t as usize; |
| 931 | if t >= self.config.vocab { |
| 932 | return Err(format!( |
| 933 | "stroke: head {head} token {t} outside the vocab {}", |
| 934 | self.config.vocab |
| 935 | )); |
| 936 | } |
| 937 | let p = self.head_pos(head)?; |
| 938 | if p >= self.max_pos { |
| 939 | return Err(format!( |
| 940 | "stroke: head {head} at {p}, the KV cache holds {} positions", |
| 941 | self.max_pos |
| 942 | )); |
| 943 | } |
| 944 | x.extend( |
| 945 | self.embed[t * h..(t + 1) * h] |
| 946 | .iter() |
| 947 | .map(|&b| bf16_to_f32(b)), |
| 948 | ); |
| 949 | pos.push(p); |
| 950 | } |
| 951 | let out = self.graph.stroke(&x, &pos)?; |
| 952 | for head in 0..heads { |
| 953 | *self.head_pos_mut(head)? += 1; |
| 954 | } |
| 955 | Ok(out) |
| 956 | } |
| 957 | |
| 958 | /// The last stroke's residual stream of head `head` (as [`Self::residual`]). |
| 959 | pub fn residual_head(&mut self, head: usize) -> Result<Vec<f32>, String> { |
| 960 | let mut x = vec![0f32; self.config.hidden]; |
| 961 | self.graph.read_head(head, Some(&mut x), None, None)?; |
| 962 | Ok(x) |
| 963 | } |
| 964 | |
| 965 | /// The last stroke's logits of head `head` (as [`Self::logits`]). |
| 966 | pub fn logits_head(&mut self, head: usize) -> Result<Vec<f32>, String> { |
| 967 | let mut l = vec![0f32; self.config.vocab]; |
| 968 | self.graph.read_head(head, None, None, Some(&mut l))?; |
| 969 | Ok(l) |
| 970 | } |
| 971 | |
| 972 | /// Clears head `head`'s conversation (DeltaNet state and position; the attention cache is |
| 973 | /// overwritten from position 0). |
| 974 | pub fn reset_head(&mut self, head: usize) -> Result<(), String> { |
| 975 | let gdn = match head { |
| 976 | 0 => self.gdn.as_mut(), |
| 977 | h => self |
| 978 | .extra_heads |
| 979 | .get_mut(h - 1) |
| 980 | .ok_or_else(|| format!("head {h}"))? |
| 981 | .gdn |
| 982 | .as_mut(), |
| 983 | }; |
| 984 | if let Some(g) = gdn { |
| 985 | g.reset().map_err(gpu("gdn reset"))?; |
| 986 | } |
| 987 | *self.head_pos_mut(head)? = 0; |
| 988 | Ok(()) |
| 989 | } |
| 990 | |
| 991 | fn take_head(&mut self, head: usize) -> HeadState { |
| 992 | match head { |
| 993 | 0 => HeadState { |
| 994 | gdn: self.gdn.take(), |
| 995 | attn: self.attn.take(), |
| 996 | pos: std::mem::take(&mut self.pos), |
| 997 | }, |
| 998 | h => std::mem::take(&mut self.extra_heads[h - 1]), |
| 999 | } |
| 1000 | } |
| 1001 | |
| 1002 | fn put_head(&mut self, head: usize, s: HeadState) { |
| 1003 | match head { |
| 1004 | 0 => { |
| 1005 | self.gdn = s.gdn; |
| 1006 | self.attn = s.attn; |
| 1007 | self.pos = s.pos; |
| 1008 | } |
| 1009 | h => self.extra_heads[h - 1] = s, |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | /// The batch (L312 v2): each layer recorded for every conversation at once, one weight read per |
| 1014 | /// layer for all of them. 35B graph only; pins the GEMM kernels on the session. |
| 1015 | pub fn set_batch(&mut self, on: bool) -> Result<(), String> { |
| 1016 | match &mut self.graph { |
| 1017 | Graph::Moe(g) => g |
| 1018 | .set_batch(on) |
| 1019 | .map_err(|rc| format!("q36 set_batch: rc {rc}")), |
| 1020 | Graph::Dense(_) => Err("set_batch: the 27B dense graph has no batch".into()), |
| 1021 | } |
| 1022 | } |
| 1023 | /// Whether the 35B graph records in the batch (also `AIEN_OMEGA_Q36_BATCH=1` at open). |
| 1024 | pub fn batch(&self) -> bool { |
| 1025 | match &self.graph { |
| 1026 | Graph::Moe(g) => g.batch(), |
| 1027 | Graph::Dense(_) => false, |
| 1028 | } |
| 1029 | } |
| 1030 | /// Chip timestamps around every launch of the next strokes (35B graph only): a timeline per token. |
| 1031 | pub fn set_stamps(&mut self, on: bool) -> Result<(), String> { |
| 1032 | match &mut self.graph { |
| 1033 | Graph::Moe(g) => { |
| 1034 | g.set_stamps(on); |
| 1035 | Ok(()) |
| 1036 | } |
| 1037 | Graph::Dense(_) => Err("set_stamps: the 27B dense graph has no stroke timeline".into()), |
| 1038 | } |
| 1039 | } |
| 1040 | /// The last stroke's timeline: (launch kind name, chip ns) per launch in launch order; needs |
| 1041 | /// [`Self::set_stamps`] before that stroke. |
| 1042 | pub fn timeline(&self) -> Result<Vec<(String, u64)>, String> { |
| 1043 | match &self.graph { |
| 1044 | Graph::Moe(g) => g |
| 1045 | .timeline() |
| 1046 | .map(|v| { |
| 1047 | v.into_iter() |
| 1048 | .map(|(k, ns)| (Q36Graph::kind_name(k), ns)) |
| 1049 | .collect() |
| 1050 | }) |
| 1051 | .map_err(|rc| format!("q36 timeline: rc {rc}")), |
| 1052 | Graph::Dense(_) => Err("timeline: the 27B dense graph has no stroke timeline".into()), |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | /// Head swap: slots `a` and `b` exchange conversations (state objects and positions); the |
| 1057 | /// graph is re-pointed, nothing is copied. After it, the stroke feeding slot `a` continues |
| 1058 | /// the conversation that was in `b`. |
| 1059 | pub fn swap_heads(&mut self, a: usize, b: usize) -> Result<(), String> { |
| 1060 | let heads = self.heads(); |
| 1061 | if a >= heads || b >= heads { |
| 1062 | return Err(format!("swap_heads: {a} and {b} of {heads} heads")); |
| 1063 | } |
| 1064 | if a == b { |
| 1065 | return Ok(()); |
| 1066 | } |
| 1067 | if matches!(self.graph, Graph::Dense(_)) { |
| 1068 | return Err("swap_heads: the 27B dense graph has one head".into()); |
| 1069 | } |
| 1070 | let (sa, sb) = (self.take_head(a), self.take_head(b)); |
| 1071 | let raw = |s: &HeadState| { |
| 1072 | ( |
| 1073 | s.gdn.as_ref().map_or(std::ptr::null_mut(), Gdn::as_raw), |
| 1074 | s.attn |
| 1075 | .as_ref() |
| 1076 | .map_or(std::ptr::null_mut(), Attn256Cache::as_raw), |
| 1077 | ) |
| 1078 | }; |
| 1079 | let ((ga, aa), (gb, ab)) = (raw(&sa), raw(&sb)); |
| 1080 | self.put_head(a, sb); |
| 1081 | self.put_head(b, sa); |
| 1082 | if let Graph::Moe(g) = &mut self.graph { |
| 1083 | // SAFETY: both states are owned by self (just put back) and outlive the graph (field order). |
| 1084 | unsafe { |
| 1085 | g.set_head_state(a, gb, ab) |
| 1086 | .map_err(gpu("q36 set_head_state"))?; |
| 1087 | g.set_head_state(b, ga, aa) |
| 1088 | .map_err(gpu("q36 set_head_state"))?; |
| 1089 | } |
| 1090 | } |
| 1091 | Ok(()) |
| 1092 | } |
| 1093 | |
| 1094 | /// Copies every DeltaNet layer's conv tail and state and the position into `snap` (host |
| 1095 | /// memory, reused between calls): [`Self::restore`] continues the sequence from here. The |
| 1096 | /// attention KV needs no copy: rows past the restored position are rewritten before they |
| 1097 | /// are read. |
| 1098 | pub fn snapshot(&mut self, snap: &mut Qwen38Snapshot) -> Result<(), String> { |
| 1099 | let Some(g) = self.gdn.as_mut() else { |
| 1100 | snap.pos = self.pos; |
| 1101 | return Ok(()); |
| 1102 | }; |
| 1103 | let n = g.layers(); |
| 1104 | let (tf, sf) = (g.tail_floats(), g.state_floats()); |
| 1105 | snap.tails.resize(n * tf, 0.0); |
| 1106 | snap.states.resize(n * sf, 0.0); |
| 1107 | for (l, (t, st)) in snap |
| 1108 | .tails |
| 1109 | .chunks_exact_mut(tf) |
| 1110 | .zip(snap.states.chunks_exact_mut(sf)) |
| 1111 | .enumerate() |
| 1112 | { |
| 1113 | g.get_state(l, t, st).map_err(gpu("gdn get_state"))?; |
| 1114 | } |
| 1115 | snap.pos = self.pos; |
| 1116 | Ok(()) |
| 1117 | } |
| 1118 | |
| 1119 | /// Puts a [`Self::snapshot`] back: the next token goes at `snap.pos`. |
| 1120 | pub fn restore(&mut self, snap: &Qwen38Snapshot) -> Result<(), String> { |
| 1121 | if snap.pos > self.max_pos { |
| 1122 | return Err(format!("restore: position {} past the cache", snap.pos)); |
| 1123 | } |
| 1124 | if let Some(g) = self.gdn.as_mut() { |
| 1125 | let (tf, sf) = (g.tail_floats(), g.state_floats()); |
| 1126 | if snap.tails.len() != g.layers() * tf || snap.states.len() != g.layers() * sf { |
| 1127 | return Err("restore: the snapshot is not of this model".into()); |
| 1128 | } |
| 1129 | for (l, (t, st)) in snap |
| 1130 | .tails |
| 1131 | .chunks_exact(tf) |
| 1132 | .zip(snap.states.chunks_exact(sf)) |
| 1133 | .enumerate() |
| 1134 | { |
| 1135 | g.set_state(l, t, st).map_err(gpu("gdn set_state"))?; |
| 1136 | } |
| 1137 | } |
| 1138 | self.pos = snap.pos; |
| 1139 | Ok(()) |
| 1140 | } |
| 1141 | |
| 1142 | /// The graph, for traces and timelines. |
| 1143 | pub fn graph_mut(&mut self) -> Option<&mut Q38Graph> { |
| 1144 | match &mut self.graph { |
| 1145 | Graph::Dense(g) => Some(g), |
| 1146 | Graph::Moe(_) => None, |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | /// Greedy tokens may use the exact two-pass head when loaded with it: the token is the |
| 1151 | /// full head's, but the logits read back are -inf off the candidates. Sampled requests turn |
| 1152 | /// it off and read every logit. |
| 1153 | pub fn set_exact_head_on(&mut self, on: bool) { |
| 1154 | match &mut self.graph { |
| 1155 | Graph::Moe(g) => g.set_exact_head_on(on), |
| 1156 | Graph::Dense(g) => g.set_exact_head_on(on), |
| 1157 | } |
| 1158 | } |
| 1159 | |
| 1160 | /// True when the next token runs the exact two-pass head. |
| 1161 | pub fn exact_head_active(&self) -> bool { |
| 1162 | match &self.graph { |
| 1163 | Graph::Moe(g) => g.exact_head_active(), |
| 1164 | Graph::Dense(g) => g.exact_head_active(), |
| 1165 | } |
| 1166 | } |
| 1167 | |
| 1168 | /// The 35B graph, for timelines. |
| 1169 | pub fn q36_graph_mut(&mut self) -> Option<&mut Q36Graph> { |
| 1170 | match &mut self.graph { |
| 1171 | Graph::Moe(g) => Some(g), |
| 1172 | Graph::Dense(_) => None, |
| 1173 | } |
| 1174 | } |
| 1175 | |
| 1176 | /// True for the sparse (Qwen3.6-35B-A3B) model. |
| 1177 | pub fn is_moe(&self) -> bool { |
| 1178 | matches!(self.graph, Graph::Moe(_)) |
| 1179 | } |
| 1180 | } |
| 1181 | |
| 1182 | /// Free memory kept for everything else on the box (the resident server shares this pool: |
| 1183 | /// 2026-10-18 16:43:58Z a 32-layer window pushed the kernel into the OOM killer, which took the |
| 1184 | /// server). The gate tools upload a window only when MemAvailable covers it plus this margin. |
| 1185 | pub const KEEP_FREE: u64 = 12 << 30; |
| 1186 | |
| 1187 | /// Device bytes a window takes: its FP8 weights (1 byte each; the 128x128 block scales add 1/4096), |
| 1188 | /// the bf16 a|b rows of its DeltaNet layers, and the bf16 lm_head; from the config, not measured. |
| 1189 | pub fn window_bytes(c: &Qwen38Config, first: usize, count: usize) -> u64 { |
| 1190 | let h = c.hidden as u64; |
| 1191 | // Qwen3.6-35B-A3B (sc L306): every layer holds 257 FP8 experts (256 routed + the shared one) |
| 1192 | // and a bf16 router of 257 rows. |
| 1193 | let mlp = match &c.moe { |
| 1194 | Some(m) => (m.experts as u64 + 1) * (3 * m.expert_inter as u64 * h + 2 * h), |
| 1195 | None => 3 * c.intermediate as u64 * h, |
| 1196 | }; |
| 1197 | let o = h * (c.heads * c.head_dim) as u64; |
| 1198 | let layers: u64 = c.full_attention[first..first + count] |
| 1199 | .iter() |
| 1200 | .map(|&attn| { |
| 1201 | if attn { |
| 1202 | (2 * c.heads * c.head_dim + 2 * c.kv_dim()) as u64 * h + o + mlp |
| 1203 | } else { |
| 1204 | (c.conv_dim() + c.lin_value_dim()) as u64 * h |
| 1205 | + o |
| 1206 | + mlp |
| 1207 | + 2 * 2 * c.lin_v_heads as u64 * h |
| 1208 | } |
| 1209 | }) |
| 1210 | .sum(); |
| 1211 | layers + layers / 4096 + 2 * c.vocab as u64 * h |
| 1212 | } |
| 1213 | |
| 1214 | /// MemAvailable from /proc/meminfo, in bytes. |
| 1215 | pub fn mem_available() -> Result<u64, String> { |
| 1216 | let m = std::fs::read_to_string("/proc/meminfo").map_err(|e| format!("/proc/meminfo: {e}"))?; |
| 1217 | m.lines() |
| 1218 | .find_map(|l| l.strip_prefix("MemAvailable:")) |
| 1219 | .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::<u64>().ok()) |
| 1220 | .map(|kb| kb << 10) |
| 1221 | .ok_or_else(|| "/proc/meminfo: no MemAvailable".into()) |
| 1222 | } |