Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-inference-abi/src/qwen38.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen38.rs` 1779 lines ยท 71333 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Qwen3.8-27B (`qwen3_5`, the hybrid Gated DeltaNet + attention family) host reference. 17 //! 18 //! Plan: `~/handoffs/2026-10-18-qwen38-27b-on-omega.md` (step 2). Host only: no launch, no chip. 19 //! This is the golden model every later Omega kernel for the 27B is checked against, so it is 20 //! written for clarity and f32 accuracy, not speed. Ground truth for the maths is the model's own 21 //! published code (transformers `modeling_qwen3_5.py`, text path) and its `config.json`: 22 //! 23 //! - 64 layers; `layer_types` marks every 4th (3, 7, ..., 63) `full_attention`, the rest 24 //! `linear_attention` (Gated DeltaNet). Each layer: zero-centred RMSNorm, mixer, residual, then 25 //! zero-centred RMSNorm, dense SiLU MLP, residual. Zero-centred: `x * rsqrt(mean(x^2) + eps) * 26 //! (1 + w)`. 27 //! - Attention: q_proj gives per head `[q | gate]` (2 * head_dim), q_norm / k_norm (zero-centred) 28 //! over head_dim, RoPE on the first `rotary_dim` dims only (rotate-half within them), causal 29 //! softmax with scale `1/sqrt(head_dim)`, grouped kv (`q head h` reads `kv head h / group`), 30 //! output times `sigmoid(gate)`, o_proj. Text positions make the three mRoPE sections equal, so 31 //! they collapse to plain positions. 32 //! - Gated DeltaNet: in_proj_qkv -> depthwise causal conv1d (kernel 4, no bias) -> SiLU, split 33 //! q | k | v; q and k l2-normalised per head (eps 1e-6), q scaled by `1/sqrt(k_dim)`, q and k 34 //! heads repeated to the value heads (`v head h` reads `k head h / ratio`). `beta = 35 //! sigmoid(in_proj_b x)`, `g = -exp(A_log) * softplus(in_proj_a x + dt_bias)`. Per head the f32 36 //! state `S[k_dim][v_dim]`: `S *= exp(g)`, `kv = S^T k`, `delta = (v - kv) * beta`, `S += k 37 //! delta^T`, `o = S^T q`. Then a gated RMSNorm per head (`norm(o) * w * silu(z)`, w used as is) 38 //! and out_proj. Prefill here runs the same recurrence token by token (the chunked form is equal 39 //! to it by algebra). 40 //! - FP8 checkpoint: every projection is `F8_E4M3` with a bf16 `weight_scale_inv` grid 41 //! `[n/128][k/128]`; embedding, lm_head, norms, conv1d, in_proj_a / in_proj_b, A_log and dt_bias 42 //! are bf16. Weights are widened to f32 as `e4m3(w) * scale` and every product accumulates in 43 //! f32. 44 //! 45 //! Memory: the weights are streamed. [`Qwen38Reference::forward`] reads one layer from the shards, 46 //! pushes every new token through it, drops it and reads the next, so the host holds the bf16 47 //! embedding and lm_head plus one layer. A pass costs one read of the checkpoint whatever the 48 //! number of tokens, which is why prompts are scored in one call and not token by token. 49 //! [`Qwen38State`] carries the attention KV (f32) and the DeltaNet conv tails and states between 50 //! calls, so a later call continues the same sequence. 51 52 use std::path::Path; 53 54 use rayon::prelude::*; 55 56 use crate::qwen3_moe::{bf16_to_f32, fp8_table, FP8_BLOCK}; 57 use crate::qwen3_moe_omega::{ShardSource, TensorSource}; 58 59 /// The text model's shape, read from `config.json` (`text_config` of a `qwen3_5` checkpoint). 60 #[derive(Debug, Clone, PartialEq)] 61 pub struct Qwen38Config { 62 pub hidden: usize, 63 pub layers: usize, 64 pub vocab: usize, 65 pub intermediate: usize, 66 /// One entry per layer: `true` for `full_attention`, `false` for `linear_attention`. 67 pub full_attention: Vec, 68 pub heads: usize, 69 pub kv_heads: usize, 70 pub head_dim: usize, 71 /// `head_dim * partial_rotary_factor`: the leading dims RoPE turns. 72 pub rotary_dim: usize, 73 pub rope_theta: f64, 74 pub lin_k_heads: usize, 75 pub lin_v_heads: usize, 76 pub lin_k_dim: usize, 77 pub lin_v_dim: usize, 78 pub conv_kernel: usize, 79 pub eps: f32, 80 pub eos_token_ids: Vec, 81 /// `Some` for the MoE variant (`qwen3_5_moe`, Qwen3.6-35B-A3B): every layer's MLP is a routed 82 /// sparse block plus a gated shared expert, and `intermediate` is unused (0). 83 pub moe: Option, 84 /// `config.json` names an FP8 `quantization_config` (projections FP8 e4m3, 128 x 128 block 85 /// scales); false: the projections are stored bf16 (e.g. the official Qwen3.5-9B). 86 pub fp8: bool, 87 } 88 89 /// The sparse MLP of a `qwen3_5_moe` layer (transformers `Qwen3_5MoeSparseMoeBlock`): router 90 /// logits `W_gate x` (bf16 `[experts][hidden]`), softmax over all experts, the `top_k` largest, 91 /// their probabilities renormalised to sum 1 (always: the router has no `norm_topk_prob` switch); 92 /// each selected expert is a SiLU MLP of width `expert_inter`. Plus a shared expert (width 93 /// `shared_inter`) scaled by `sigmoid(shared_expert_gate x)` (bf16 `[1][hidden]`). 94 #[derive(Debug, Clone, PartialEq)] 95 pub struct MoeShape { 96 pub experts: usize, 97 pub top_k: usize, 98 pub expert_inter: usize, 99 pub shared_inter: usize, 100 } 101 102 fn field<'a>(v: &'a serde_json::Value, key: &str) -> Result<&'a serde_json::Value, String> { 103 v.get(key) 104 .ok_or_else(|| format!("config.json: missing {key}")) 105 } 106 107 fn usize_field(v: &serde_json::Value, key: &str) -> Result { 108 field(v, key)? 109 .as_u64() 110 .map(|x| x as usize) 111 .ok_or_else(|| format!("config.json: {key} is not an unsigned integer")) 112 } 113 114 fn f64_field(v: &serde_json::Value, key: &str) -> Result { 115 field(v, key)? 116 .as_f64() 117 .ok_or_else(|| format!("config.json: {key} is not a number")) 118 } 119 120 impl Qwen38Config { 121 /// Reads `config.json` (and `generation_config.json` for the stop tokens, when present). 122 pub fn from_checkpoint(dir: &Path) -> Result { 123 let read = |name: &str| { 124 std::fs::read_to_string(dir.join(name)) 125 .map_err(|e| format!("{}: {e}", dir.join(name).display())) 126 }; 127 let generation = read("generation_config.json").ok(); 128 Self::from_json(&read("config.json")?, generation.as_deref()) 129 } 130 131 pub fn from_json(config_json: &str, generation_json: Option<&str>) -> Result { 132 let raw: serde_json::Value = 133 serde_json::from_str(config_json).map_err(|e| format!("config.json: {e}"))?; 134 let (text, sparse) = match raw.get("model_type").and_then(|v| v.as_str()) { 135 Some("qwen3_5") => (field(&raw, "text_config")?, false), 136 Some("qwen3_5_text") => (&raw, false), 137 Some("qwen3_5_moe") => (field(&raw, "text_config")?, true), 138 Some("qwen3_5_moe_text") => (&raw, true), 139 other => { 140 return Err(format!( 141 "config.json: model_type {other:?}, this reference runs qwen3_5 and qwen3_5_moe only" 142 )) 143 } 144 }; 145 let moe = if sparse { 146 Some(MoeShape { 147 experts: usize_field(text, "num_experts")?, 148 top_k: usize_field(text, "num_experts_per_tok")?, 149 expert_inter: usize_field(text, "moe_intermediate_size")?, 150 shared_inter: usize_field(text, "shared_expert_intermediate_size")?, 151 }) 152 } else { 153 None 154 }; 155 let tied = text 156 .get("tie_word_embeddings") 157 .or_else(|| raw.get("tie_word_embeddings")) 158 .and_then(|v| v.as_bool()) 159 .unwrap_or(false); 160 if tied { 161 return Err("config.json: tied embeddings are not supported (27B is untied)".into()); 162 } 163 if text.get("attn_output_gate").and_then(|v| v.as_bool()) != Some(true) { 164 return Err("config.json: attn_output_gate must be true".into()); 165 } 166 if text.get("hidden_act").and_then(|v| v.as_str()) != Some("silu") { 167 return Err("config.json: hidden_act must be silu".into()); 168 } 169 if let Some(q) = raw.get("quantization_config") { 170 let s = |k: &str| q.get(k).and_then(|v| v.as_str()); 171 let block = q.get("weight_block_size").and_then(|v| v.as_array()); 172 let block_ok = block.is_none_or(|b| { 173 b.len() == 2 && b.iter().all(|x| x.as_u64() == Some(FP8_BLOCK as u64)) 174 }); 175 if s("quant_method") != Some("fp8") || s("fmt") != Some("e4m3") || !block_ok { 176 return Err(format!( 177 "config.json: quantization_config {q}: only fp8 e4m3 with 128x128 blocks" 178 )); 179 } 180 } 181 let rope = field(text, "rope_parameters")?; 182 let head_dim = usize_field(text, "head_dim")?; 183 let partial = rope 184 .get("partial_rotary_factor") 185 .and_then(|v| v.as_f64()) 186 .unwrap_or(1.0); 187 let rotary_dim = (head_dim as f64 * partial) as usize; 188 let layers = usize_field(text, "num_hidden_layers")?; 189 let full_attention = field(text, "layer_types")? 190 .as_array() 191 .ok_or("config.json: layer_types is not a list")? 192 .iter() 193 .map(|t| match t.as_str() { 194 Some("full_attention") => Ok(true), 195 Some("linear_attention") => Ok(false), 196 other => Err(format!("config.json: layer type {other:?}")), 197 }) 198 .collect::, _>>()?; 199 let mut eos_token_ids = Vec::new(); 200 if let Some(g) = generation_json { 201 let g: serde_json::Value = 202 serde_json::from_str(g).map_err(|e| format!("generation_config.json: {e}"))?; 203 if let Some(ids) = crate::tokenizer::eos_token_ids_from_json(&g) { 204 eos_token_ids = ids; 205 } 206 } 207 if eos_token_ids.is_empty() { 208 eos_token_ids.push(usize_field(text, "eos_token_id")? as u32); 209 } 210 let c = Self { 211 hidden: usize_field(text, "hidden_size")?, 212 layers, 213 vocab: usize_field(text, "vocab_size")?, 214 intermediate: if sparse { 215 0 216 } else { 217 usize_field(text, "intermediate_size")? 218 }, 219 full_attention, 220 heads: usize_field(text, "num_attention_heads")?, 221 kv_heads: usize_field(text, "num_key_value_heads")?, 222 head_dim, 223 rotary_dim, 224 rope_theta: f64_field(rope, "rope_theta")?, 225 lin_k_heads: usize_field(text, "linear_num_key_heads")?, 226 lin_v_heads: usize_field(text, "linear_num_value_heads")?, 227 lin_k_dim: usize_field(text, "linear_key_head_dim")?, 228 lin_v_dim: usize_field(text, "linear_value_head_dim")?, 229 conv_kernel: usize_field(text, "linear_conv_kernel_dim")?, 230 eps: f64_field(text, "rms_norm_eps")? as f32, 231 eos_token_ids, 232 moe, 233 fp8: raw.get("quantization_config").is_some(), 234 }; 235 c.validate()?; 236 Ok(c) 237 } 238 239 pub fn validate(&self) -> Result<(), String> { 240 let bad = |what: &str| Err(format!("qwen3_5 config: {what}")); 241 if self.full_attention.len() != self.layers { 242 return bad("layer_types length differs from num_hidden_layers"); 243 } 244 if !self.heads.is_multiple_of(self.kv_heads) 245 || !self.lin_v_heads.is_multiple_of(self.lin_k_heads) 246 { 247 return bad("head counts do not group evenly"); 248 } 249 if !self.rotary_dim.is_multiple_of(2) || self.rotary_dim > self.head_dim { 250 return bad("rotary_dim must be even and at most head_dim"); 251 } 252 if self.conv_kernel < 1 { 253 return bad("conv kernel must be at least 1"); 254 } 255 if let Some(m) = &self.moe { 256 if m.top_k == 0 || m.top_k > m.experts { 257 return bad("num_experts_per_tok must be 1..=num_experts"); 258 } 259 } 260 Ok(()) 261 } 262 263 /// The first `layers` layers of the model (a truncated stack for parity checks: the final norm 264 /// and lm_head then read layer `layers - 1`'s output). `None` when `layers` is 0 or too many. 265 pub fn prefix(&self, layers: usize) -> Option { 266 if layers == 0 || layers > self.layers { 267 return None; 268 } 269 let mut c = self.clone(); 270 c.layers = layers; 271 c.full_attention.truncate(layers); 272 Some(c) 273 } 274 275 /// Layers `first .. first + count` of the model as a stack of their own (a window for parity 276 /// checks that fit the device one window at a time). `None` when empty or past the end. 277 pub fn window(&self, first: usize, count: usize) -> Option { 278 if count == 0 || first + count > self.layers { 279 return None; 280 } 281 let mut c = self.clone(); 282 c.layers = count; 283 c.full_attention = self.full_attention[first..first + count].to_vec(); 284 Some(c) 285 } 286 287 /// Width of the DeltaNet conv input: q | k | v. 288 pub fn conv_dim(&self) -> usize { 289 2 * self.lin_k_heads * self.lin_k_dim + self.lin_v_heads * self.lin_v_dim 290 } 291 292 pub fn lin_value_dim(&self) -> usize { 293 self.lin_v_heads * self.lin_v_dim 294 } 295 296 pub fn kv_dim(&self) -> usize { 297 self.kv_heads * self.head_dim 298 } 299 } 300 301 // --------------------------------------------------------------------------- 302 // Matrices: the checkpoint's `[n][k]` rows, widened to f32 a block of rows at a time. 303 // --------------------------------------------------------------------------- 304 305 /// One projection as stored: e4m3 with its block scales, or bf16. 306 #[derive(Debug)] 307 pub enum Matrix { 308 Fp8 { 309 n: usize, 310 k: usize, 311 w: Vec, 312 scales: Vec, 313 }, 314 Bf16 { 315 n: usize, 316 k: usize, 317 w: Vec, 318 }, 319 } 320 321 /// Rows per parallel task: one task widens this many rows and runs every token through them. 322 const ROWS_PER_TASK: usize = 16; 323 324 pub(crate) fn dot(a: &[f32], b: &[f32]) -> f32 { 325 // Eight independent lanes so the compiler can keep it in vector registers. 326 let mut acc = [0f32; 8]; 327 let (ca, cb) = (a.chunks_exact(8), b.chunks_exact(8)); 328 let (ra, rb) = (ca.remainder(), cb.remainder()); 329 for (x, y) in ca.zip(cb) { 330 for i in 0..8 { 331 acc[i] += x[i] * y[i]; 332 } 333 } 334 let tail: f32 = ra.iter().zip(rb).map(|(x, y)| x * y).sum(); 335 acc.iter().sum::() + tail 336 } 337 338 impl Matrix { 339 pub fn n(&self) -> usize { 340 match self { 341 Self::Fp8 { n, .. } | Self::Bf16 { n, .. } => *n, 342 } 343 } 344 345 pub fn k(&self) -> usize { 346 match self { 347 Self::Fp8 { k, .. } | Self::Bf16 { k, .. } => *k, 348 } 349 } 350 351 /// Rows `r0..r0 + rows` as f32 into `dst` (`[rows][k]`). 352 fn widen_rows(&self, r0: usize, rows: usize, lut: &[f32; 256], dst: &mut [f32]) { 353 match self { 354 Self::Fp8 { k, w, scales, .. } => { 355 let kb = k / FP8_BLOCK; 356 for r in 0..rows { 357 let row = r0 + r; 358 let src = &w[row * k..(row + 1) * k]; 359 let srow = &scales[(row / FP8_BLOCK) * kb..(row / FP8_BLOCK + 1) * kb]; 360 let out = &mut dst[r * k..(r + 1) * k]; 361 for (b, (o, s)) in out 362 .chunks_exact_mut(FP8_BLOCK) 363 .zip(src.chunks_exact(FP8_BLOCK)) 364 .enumerate() 365 { 366 let scale = bf16_to_f32(srow[b]); 367 for (o, &q) in o.iter_mut().zip(s) { 368 *o = lut[q as usize] * scale; 369 } 370 } 371 } 372 } 373 Self::Bf16 { k, w, .. } => { 374 for (o, &b) in dst[..rows * k].iter_mut().zip(&w[r0 * k..(r0 + rows) * k]) { 375 *o = bf16_to_f32(b); 376 } 377 } 378 } 379 } 380 381 /// Row `r` of a bf16 matrix as stored (`None` for FP8). 382 pub fn bf16_row(&self, r: usize) -> Option<&[u16]> { 383 match self { 384 Self::Bf16 { k, w, .. } => Some(&w[r * k..(r + 1) * k]), 385 Self::Fp8 { .. } => None, 386 } 387 } 388 389 /// `y[t][r] = sum_c W[r][c] * x[t][c]` for `t` rows of `x` (`[t][k]`), returned `[t][n]`. 390 pub fn matmul(&self, x: &[f32], t: usize) -> Vec { 391 let (n, k) = (self.n(), self.k()); 392 assert_eq!( 393 x.len(), 394 t * k, 395 "matmul [{n}][{k}] given {} values for {t} rows", 396 x.len() 397 ); 398 let lut = fp8_table(); 399 // Worked as `[n][t]` so each task owns a contiguous run of output rows. 400 let mut by_row = vec![0f32; n * t]; 401 by_row 402 .par_chunks_mut(ROWS_PER_TASK * t) 403 .enumerate() 404 .for_each_init(Vec::new, |buf: &mut Vec, (task, out)| { 405 let r0 = task * ROWS_PER_TASK; 406 let rows = out.len() / t; 407 buf.resize(rows * k, 0.0); 408 self.widen_rows(r0, rows, &lut, buf); 409 for tt in 0..t { 410 let xv = &x[tt * k..(tt + 1) * k]; 411 for r in 0..rows { 412 out[r * t + tt] = dot(&buf[r * k..(r + 1) * k], xv); 413 } 414 } 415 }); 416 if t == 1 { 417 return by_row; 418 } 419 let mut y = vec![0f32; t * n]; 420 for r in 0..n { 421 for tt in 0..t { 422 y[tt * n + r] = by_row[r * t + tt]; 423 } 424 } 425 y 426 } 427 } 428 429 fn bytes_of_words(words: &mut [u16]) -> &mut [u8] { 430 // SAFETY: u8 has no alignment need and every byte pattern is a valid u16 half; the length is 431 // exactly the slice's size in bytes. The checkpoint's little-endian words match this host 432 // (aarch64 and x86_64 are little-endian). 433 unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::(), words.len() * 2) } 434 } 435 436 pub(crate) fn read_bf16_words( 437 source: &mut dyn TensorSource, 438 name: &str, 439 shape: &[usize], 440 ) -> Result, String> { 441 let mut words = vec![0u16; shape.iter().product()]; 442 source.read_into(name, "BF16", shape, bytes_of_words(&mut words))?; 443 Ok(words) 444 } 445 446 /// Reads the `[len]` vector `name` as f32: bf16 widened, or f32 as stored (Qwen3.5-9B keeps 447 /// `linear_attn.A_log` and `linear_attn.norm.weight` in F32). 448 pub(crate) fn read_vec( 449 source: &mut dyn TensorSource, 450 name: &str, 451 len: usize, 452 ) -> Result, String> { 453 if source.dtype_of(name)?.as_deref() == Some("F32") { 454 let mut bytes = vec![0u8; len * 4]; 455 source.read_into(name, "F32", &[len], &mut bytes)?; 456 return Ok(bytes 457 .chunks_exact(4) 458 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) 459 .collect()); 460 } 461 Ok(read_bf16_words(source, name, &[len])? 462 .into_iter() 463 .map(bf16_to_f32) 464 .collect()) 465 } 466 467 /// Reads `name` as `[n][k]`: e4m3 with `name_scale_inv` when the header says `F8_E4M3`, else 468 /// bf16. An e4m3 weight without its scale grid is refused. 469 pub(crate) fn read_matrix( 470 source: &mut dyn TensorSource, 471 name: &str, 472 n: usize, 473 k: usize, 474 ) -> Result { 475 match source.dtype_of(name)?.as_deref() { 476 Some("F8_E4M3") => { 477 if !n.is_multiple_of(FP8_BLOCK) || !k.is_multiple_of(FP8_BLOCK) { 478 return Err(format!( 479 "{name}: [{n}][{k}] is not a whole number of 128 blocks" 480 )); 481 } 482 let scale_name = format!("{name}_scale_inv"); 483 if source.dtype_of(&scale_name)?.is_none() { 484 return Err(format!("{name}: F8_E4M3 without {scale_name}")); 485 } 486 let mut w = vec![0u8; n * k]; 487 source.read_into(name, "F8_E4M3", &[n, k], &mut w)?; 488 let scales = read_bf16_words(source, &scale_name, &[n / FP8_BLOCK, k / FP8_BLOCK])?; 489 Ok(Matrix::Fp8 { n, k, w, scales }) 490 } 491 Some("BF16") => Ok(Matrix::Bf16 { 492 n, 493 k, 494 w: read_bf16_words(source, name, &[n, k])?, 495 }), 496 Some(other) => Err(format!("{name}: dtype {other} (expected F8_E4M3 or BF16)")), 497 None => Err(format!("{name}: not in the checkpoint")), 498 } 499 } 500 501 /// `{p}.gate_proj` / `up_proj` (`[inter][h]`) and `down_proj` (`[h][inter]`). 502 fn read_ffn(source: &mut dyn TensorSource, p: &str, inter: usize, h: usize) -> Result { 503 Ok(Ffn { 504 gate: read_matrix(source, &format!("{p}.gate_proj.weight"), inter, h)?, 505 up: read_matrix(source, &format!("{p}.up_proj.weight"), inter, h)?, 506 down: read_matrix(source, &format!("{p}.down_proj.weight"), h, inter)?, 507 }) 508 } 509 510 /// The router's choice for one row of logits: softmax over every expert, the `k` largest 511 /// probabilities (larger logit first, the lower id on ties), renormalised to sum 1. `mutant` 512 /// (negative control): 1 swaps the k-th pick for the (k+1)-th; 2 keeps the weights but sends 513 /// every pick to the next expert id (a wrong expert). 514 pub fn route(logits: &[f32], k: usize, mutant: u8) -> Vec<(usize, f32)> { 515 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max); 516 let probs: Vec = logits.iter().map(|&v| (v - max).exp()).collect(); 517 let sum: f32 = probs.iter().sum(); 518 let mut order: Vec = (0..logits.len()).collect(); 519 order.sort_by(|&a, &b| logits[b].total_cmp(&logits[a]).then(a.cmp(&b))); 520 let mut pick: Vec = order[..k].to_vec(); 521 if mutant == 1 && k < order.len() { 522 pick[k - 1] = order[k]; 523 } 524 let sel: f32 = pick.iter().map(|&e| probs[e] / sum).sum(); 525 let n = logits.len(); 526 pick.into_iter() 527 .map(|e| { 528 ( 529 if mutant == 2 { (e + 1) % n } else { e }, 530 probs[e] / sum / sel, 531 ) 532 }) 533 .collect() 534 } 535 536 // --------------------------------------------------------------------------- 537 // One layer's weights, read on demand. 538 // --------------------------------------------------------------------------- 539 540 struct DeltaNetWeights { 541 in_qkv: Matrix, 542 in_z: Matrix, 543 in_a: Matrix, 544 in_b: Matrix, 545 /// `[conv_dim][conv_kernel]`. 546 conv: Vec, 547 a_log: Vec, 548 dt_bias: Vec, 549 norm: Vec, 550 out: Matrix, 551 } 552 553 struct AttentionWeights { 554 q: Matrix, 555 k: Matrix, 556 v: Matrix, 557 o: Matrix, 558 q_norm: Vec, 559 k_norm: Vec, 560 } 561 562 enum Mixer { 563 DeltaNet(DeltaNetWeights), 564 Attention(AttentionWeights), 565 } 566 567 struct LayerWeights { 568 input_norm: Vec, 569 post_norm: Vec, 570 mixer: Mixer, 571 mlp: Mlp, 572 } 573 574 /// One SiLU MLP: `down(silu(gate x) * up x)`. 575 struct Ffn { 576 gate: Matrix, 577 up: Matrix, 578 down: Matrix, 579 } 580 581 impl Ffn { 582 fn run(&self, xn: &[f32], t: usize) -> Vec { 583 let gate = self.gate.matmul(xn, t); 584 let up = self.up.matmul(xn, t); 585 let act: Vec = gate.iter().zip(&up).map(|(&g, &u)| silu(g) * u).collect(); 586 self.down.matmul(&act, t) 587 } 588 } 589 590 /// The sparse block's always-resident part (the experts are read per call, only those routed). 591 struct MoeWeights { 592 /// bf16 `[experts][hidden]`. 593 router: Matrix, 594 /// `shared_expert_gate`, `[hidden]`. 595 shared_gate: Vec, 596 shared: Ffn, 597 } 598 599 enum Mlp { 600 Dense(Ffn), 601 Moe(MoeWeights), 602 } 603 604 /// Per layer state between calls. 605 #[derive(Debug, Clone)] 606 enum LayerState { 607 /// `conv`: the last `conv_kernel - 1` conv inputs, oldest first (`[kernel-1][conv_dim]`); 608 /// `s`: the state, `[v_heads][k_dim][v_dim]`. 609 DeltaNet { conv: Vec, s: Vec }, 610 /// Keys after norm and RoPE, values as projected, `[pos][kv_dim]` each. 611 Attention { k: Vec, v: Vec }, 612 } 613 614 /// Everything a later call needs to continue the sequence. 615 #[derive(Debug, Clone)] 616 pub struct Qwen38State { 617 pub pos: usize, 618 layers: Vec, 619 } 620 621 impl Qwen38State { 622 pub fn new(c: &Qwen38Config) -> Self { 623 let layers = c 624 .full_attention 625 .iter() 626 .map(|&full| { 627 if full { 628 LayerState::Attention { 629 k: Vec::new(), 630 v: Vec::new(), 631 } 632 } else { 633 LayerState::DeltaNet { 634 conv: vec![0.0; (c.conv_kernel - 1) * c.conv_dim()], 635 s: vec![0.0; c.lin_v_heads * c.lin_k_dim * c.lin_v_dim], 636 } 637 } 638 }) 639 .collect(); 640 Self { pos: 0, layers } 641 } 642 } 643 644 // --------------------------------------------------------------------------- 645 // Small pieces of maths. 646 // --------------------------------------------------------------------------- 647 648 /// Zero-centred RMSNorm over each `w.len()` run of `x`: `x * rsqrt(mean(x^2) + eps) * (1 + w)`. 649 fn rms_norm_zc(x: &mut [f32], w: &[f32], eps: f32) { 650 for row in x.chunks_exact_mut(w.len()) { 651 let ms = row.iter().map(|v| v * v).sum::() / w.len() as f32; 652 let inv = 1.0 / (ms + eps).sqrt(); 653 for (v, &g) in row.iter_mut().zip(w) { 654 *v = *v * inv * (1.0 + g); 655 } 656 } 657 } 658 659 pub(crate) fn silu(x: f32) -> f32 { 660 x / (1.0 + (-x).exp()) 661 } 662 663 fn sigmoid(x: f32) -> f32 { 664 1.0 / (1.0 + (-x).exp()) 665 } 666 667 /// PyTorch's `softplus` (beta 1, threshold 20). 668 fn softplus(x: f32) -> f32 { 669 if x > 20.0 { 670 x 671 } else { 672 x.exp().ln_1p() 673 } 674 } 675 676 /// `x / sqrt(sum(x^2) + eps)` in place. 677 fn l2_normalize(x: &mut [f32], eps: f32) { 678 let inv = 1.0 / (x.iter().map(|v| v * v).sum::() + eps).sqrt(); 679 x.iter_mut().for_each(|v| *v *= inv); 680 } 681 682 /// Rotate-half RoPE on the first `rotary` dims of `x` at position `pos`. 683 fn rope(x: &mut [f32], pos: usize, rotary: usize, theta: f64) { 684 let half = rotary / 2; 685 for j in 0..half { 686 let inv_freq = 1.0 / theta.powf((2 * j) as f64 / rotary as f64); 687 let (sin, cos) = (pos as f64 * inv_freq).sin_cos(); 688 let (sin, cos) = (sin as f32, cos as f32); 689 let (x1, x2) = (x[j], x[j + half]); 690 x[j] = x1 * cos - x2 * sin; 691 x[j + half] = x2 * cos + x1 * sin; 692 } 693 } 694 695 // --------------------------------------------------------------------------- 696 // The reference. 697 // --------------------------------------------------------------------------- 698 699 /// Where the logits come from in a [`Qwen38Reference::forward`] call. 700 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 701 pub enum Logits { 702 /// Only the last new token (generation). 703 Last, 704 /// Every new token (scoring a text). 705 All, 706 } 707 708 /// Where the text model's tensors live: the multimodal checkpoint nests it under 709 /// `model.language_model.`, a text-only one under `model.`. 710 pub(crate) fn text_prefix(source: &mut dyn TensorSource) -> Result { 711 ["model.language_model.", "model."] 712 .into_iter() 713 .find(|p| { 714 matches!( 715 source.dtype_of(&format!("{p}embed_tokens.weight")), 716 Ok(Some(_)) 717 ) 718 }) 719 .map(str::to_string) 720 .ok_or_else(|| { 721 "checkpoint: no embed_tokens.weight under model.language_model. or model.".into() 722 }) 723 } 724 725 pub struct Qwen38Reference { 726 pub config: Qwen38Config, 727 source: S, 728 prefix: String, 729 /// bf16 `[vocab][hidden]`, widened per row at lookup. 730 embed: Vec, 731 final_norm: Vec, 732 lm_head: Matrix, 733 /// TEST ONLY negative control for the MoE router, see [`route`]: 0 off (default), 1 the 734 /// `top_k + 1`-th expert in place of the `top_k`-th, 2 every pick sent to the next expert id. 735 pub routing_mutant: u8, 736 /// MoE only: per layer, the routed expert ids of the last call, `[t][top_k]` flattened. 737 pub routes: Vec>, 738 /// MoE only: per layer, the router logit gap between the `top_k`-th and `top_k + 1`-th 739 /// expert of each row of the last call (how close the pick was to flipping). 740 pub route_gaps: Vec>, 741 /// TEST ONLY noise-floor probe (L306): `(where, rel)` multiplies each element of the MoE input 742 /// row by `1 + rel * u` (u in [-1, 1], fixed per layer and index). `where` 0 off (default), 743 /// 1 only the router's input, 2 only the experts' and shared expert's input. 744 pub jitter: (u8, f32), 745 /// TEST ONLY (L306 router probe): when set, [`Self::moe_x`] keeps every MoE layer's input 746 /// residual (before the post-attention norm, `[t][hidden]`) of the last call. 747 pub moe_capture: bool, 748 pub moe_x: Vec>, 749 /// MoE only: per layer, the routed weights `[t][top_k]` and the shared expert gate 750 /// sigmoid(shared_gate . xn) `[t]` of the last call (beside [`Self::routes`]). 751 pub route_wts: Vec>, 752 pub shared_g: Vec>, 753 } 754 755 impl Qwen38Reference { 756 /// Opens a checkpoint directory (`config.json`, `model.safetensors.index.json` and shards). 757 pub fn open(dir: &Path) -> Result { 758 let config = Qwen38Config::from_checkpoint(dir)?; 759 Self::new(config, ShardSource::open(dir)?) 760 } 761 } 762 763 impl Qwen38Reference { 764 /// Reads the embedding, final norm and lm_head; layers are read per call. 765 pub fn new(config: Qwen38Config, mut source: S) -> Result { 766 let prefix = text_prefix(&mut source)?; 767 let (v, h) = (config.vocab, config.hidden); 768 let embed = read_bf16_words( 769 &mut source, 770 &format!("{prefix}embed_tokens.weight"), 771 &[v, h], 772 )?; 773 let final_norm = read_vec(&mut source, &format!("{prefix}norm.weight"), h)?; 774 let lm_head = read_matrix(&mut source, "lm_head.weight", v, h)?; 775 Ok(Self { 776 config, 777 source, 778 prefix, 779 embed, 780 final_norm, 781 lm_head, 782 routing_mutant: 0, 783 routes: Vec::new(), 784 route_gaps: Vec::new(), 785 jitter: (0, 0.0), 786 moe_capture: false, 787 moe_x: Vec::new(), 788 route_wts: Vec::new(), 789 shared_g: Vec::new(), 790 }) 791 } 792 793 /// The bf16 lm_head as read (the exact two-pass head screens it, see [`crate::exact_head`]). 794 pub fn lm_head(&self) -> &Matrix { 795 &self.lm_head 796 } 797 798 /// The final norm over residual rows `x` (`[t][hidden]`): the vector the lm_head multiplies. 799 pub fn final_hidden(&self, x: &[f32]) -> Vec { 800 let mut rows = x.to_vec(); 801 rms_norm_zc(&mut rows, &self.final_norm, self.config.eps); 802 rows 803 } 804 805 pub fn new_state(&self) -> Qwen38State { 806 Qwen38State::new(&self.config) 807 } 808 809 fn read_layer(&mut self, l: usize) -> Result { 810 let c = self.config.clone(); 811 let p = format!("{}layers.{l}", self.prefix); 812 let src: &mut dyn TensorSource = &mut self.source; 813 let h = c.hidden; 814 let mixer = if c.full_attention[l] { 815 let a = format!("{p}.self_attn"); 816 Mixer::Attention(AttentionWeights { 817 q: read_matrix( 818 src, 819 &format!("{a}.q_proj.weight"), 820 2 * c.heads * c.head_dim, 821 h, 822 )?, 823 k: read_matrix(src, &format!("{a}.k_proj.weight"), c.kv_dim(), h)?, 824 v: read_matrix(src, &format!("{a}.v_proj.weight"), c.kv_dim(), h)?, 825 o: read_matrix(src, &format!("{a}.o_proj.weight"), h, c.heads * c.head_dim)?, 826 q_norm: read_vec(src, &format!("{a}.q_norm.weight"), c.head_dim)?, 827 k_norm: read_vec(src, &format!("{a}.k_norm.weight"), c.head_dim)?, 828 }) 829 } else { 830 let a = format!("{p}.linear_attn"); 831 let conv_shape = [c.conv_dim(), 1, c.conv_kernel]; 832 Mixer::DeltaNet(DeltaNetWeights { 833 in_qkv: read_matrix(src, &format!("{a}.in_proj_qkv.weight"), c.conv_dim(), h)?, 834 in_z: read_matrix(src, &format!("{a}.in_proj_z.weight"), c.lin_value_dim(), h)?, 835 in_a: read_matrix(src, &format!("{a}.in_proj_a.weight"), c.lin_v_heads, h)?, 836 in_b: read_matrix(src, &format!("{a}.in_proj_b.weight"), c.lin_v_heads, h)?, 837 conv: read_bf16_words(src, &format!("{a}.conv1d.weight"), &conv_shape)? 838 .into_iter() 839 .map(bf16_to_f32) 840 .collect(), 841 a_log: read_vec(src, &format!("{a}.A_log"), c.lin_v_heads)?, 842 dt_bias: read_vec(src, &format!("{a}.dt_bias"), c.lin_v_heads)?, 843 norm: read_vec(src, &format!("{a}.norm.weight"), c.lin_v_dim)?, 844 out: read_matrix(src, &format!("{a}.out_proj.weight"), h, c.lin_value_dim())?, 845 }) 846 }; 847 let m = format!("{p}.mlp"); 848 let mlp = match &c.moe { 849 None => Mlp::Dense(read_ffn(src, &m, c.intermediate, h)?), 850 Some(s) => Mlp::Moe(MoeWeights { 851 router: read_matrix(src, &format!("{m}.gate.weight"), s.experts, h)?, 852 shared_gate: read_bf16_words( 853 src, 854 &format!("{m}.shared_expert_gate.weight"), 855 &[1, h], 856 )? 857 .into_iter() 858 .map(bf16_to_f32) 859 .collect(), 860 shared: read_ffn(src, &format!("{m}.shared_expert"), s.shared_inter, h)?, 861 }), 862 }; 863 Ok(LayerWeights { 864 input_norm: read_vec(src, &format!("{p}.input_layernorm.weight"), h)?, 865 post_norm: read_vec(src, &format!("{p}.post_attention_layernorm.weight"), h)?, 866 mixer, 867 mlp, 868 }) 869 } 870 871 /// The sparse block over `t` rows of `xn` (post-attention normed): routes every row, reads 872 /// each routed expert of layer `l` once and adds `weight * expert(x)` plus the gated shared 873 /// expert. Records the routed ids in [`Self::routes`]. 874 fn moe(&mut self, l: usize, w: &MoeWeights, xn: &[f32], t: usize) -> Result, String> { 875 let s = self.config.moe.clone().ok_or("moe: dense config")?; 876 let h = self.config.hidden; 877 let (jw, rel) = self.jitter; 878 let jittered: Vec = if jw == 0 { 879 Vec::new() 880 } else { 881 xn.iter() 882 .enumerate() 883 .map(|(i, &v)| { 884 let mut z = 885 ((l as u64) << 32 | (i % h) as u64).wrapping_add(0x9e37_79b9_7f4a_7c15); 886 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); 887 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); 888 z ^= z >> 31; 889 let u = (z >> 40) as f32 / (1u64 << 23) as f32 - 1.0; 890 v * (1.0 + rel * u) 891 }) 892 .collect() 893 }; 894 let (xr, xn) = match jw { 895 1 => (&jittered[..], xn), 896 2 => (xn, &jittered[..]), 897 _ => (xn, xn), 898 }; 899 let logits = w.router.matmul(xr, t); 900 let mut picks: Vec> = Vec::with_capacity(t); 901 let mut gaps = Vec::with_capacity(t); 902 for row in logits.chunks_exact(s.experts) { 903 picks.push(route(row, s.top_k, self.routing_mutant)); 904 let mut v = row.to_vec(); 905 v.sort_by(|a, b| b.total_cmp(a)); 906 gaps.push(if s.top_k < v.len() { 907 v[s.top_k - 1] - v[s.top_k] 908 } else { 909 f32::INFINITY 910 }); 911 } 912 if self.routes.len() <= l { 913 self.routes.resize(l + 1, Vec::new()); 914 self.route_gaps.resize(l + 1, Vec::new()); 915 self.route_wts.resize(l + 1, Vec::new()); 916 self.shared_g.resize(l + 1, Vec::new()); 917 } 918 self.route_wts[l] = picks 919 .iter() 920 .flat_map(|p| p.iter().map(|&(_, wt)| wt)) 921 .collect(); 922 self.route_gaps[l] = gaps; 923 self.routes[l] = picks 924 .iter() 925 .flat_map(|p| p.iter().map(|&(e, _)| e as u16)) 926 .collect(); 927 let mut users: Vec> = vec![Vec::new(); s.experts]; 928 for (i, p) in picks.iter().enumerate() { 929 for &(e, wt) in p { 930 users[e].push((i, wt)); 931 } 932 } 933 let mut out = w.shared.run(xn, t); 934 let mut gates = Vec::with_capacity(t); 935 for (i, row) in out.chunks_exact_mut(h).enumerate() { 936 let g = sigmoid(dot(&w.shared_gate, &xn[i * h..(i + 1) * h])); 937 row.iter_mut().for_each(|v| *v *= g); 938 gates.push(g); 939 } 940 self.shared_g[l] = gates; 941 let p = format!("{}layers.{l}.mlp.experts", self.prefix); 942 for (e, rows) in users.iter().enumerate() { 943 if rows.is_empty() { 944 continue; 945 } 946 let f = read_ffn(&mut self.source, &format!("{p}.{e}"), s.expert_inter, h)?; 947 let mut xs = Vec::with_capacity(rows.len() * h); 948 for &(i, _) in rows { 949 xs.extend_from_slice(&xn[i * h..(i + 1) * h]); 950 } 951 let y = f.run(&xs, rows.len()); 952 for (yr, &(i, wt)) in y.chunks_exact(h).zip(rows) { 953 for (o, &v) in out[i * h..(i + 1) * h].iter_mut().zip(yr) { 954 *o += wt * v; 955 } 956 } 957 } 958 Ok(out) 959 } 960 961 /// Runs `tokens` after what `state` already holds and returns logits, `[rows][vocab]` with 962 /// `rows` 1 for [`Logits::Last`] and `tokens.len()` for [`Logits::All`]. 963 pub fn forward( 964 &mut self, 965 state: &mut Qwen38State, 966 tokens: &[u32], 967 logits: Logits, 968 ) -> Result, String> { 969 self.forward_tapped(state, tokens, logits, &[], &mut Vec::new()) 970 } 971 972 /// [`Self::forward`] that also copies the residual stream entering layer `b` (`[t][hidden]`, 973 /// before its input norm) into `taps` for every `b` in `at` (ascending; `b == layers` is the 974 /// residual before the final norm). The chip checks a model window by window against these. 975 pub fn forward_tapped( 976 &mut self, 977 state: &mut Qwen38State, 978 tokens: &[u32], 979 logits: Logits, 980 at: &[usize], 981 taps: &mut Vec>, 982 ) -> Result, String> { 983 let c = self.config.clone(); 984 let (t, h) = (tokens.len(), c.hidden); 985 if t == 0 { 986 return Err("forward: no tokens".into()); 987 } 988 let mut x = vec![0f32; t * h]; 989 for (row, &tok) in x.chunks_exact_mut(h).zip(tokens) { 990 let tok = tok as usize; 991 if tok >= c.vocab { 992 return Err(format!( 993 "forward: token {tok} outside the vocab {}", 994 c.vocab 995 )); 996 } 997 for (o, &b) in row.iter_mut().zip(&self.embed[tok * h..(tok + 1) * h]) { 998 *o = bf16_to_f32(b); 999 } 1000 } 1001 if at.windows(2).any(|p| p[0] >= p[1]) || at.iter().any(|&b| b > c.layers) { 1002 return Err(format!( 1003 "forward: taps {at:?} not ascending within 0..={}", 1004 c.layers 1005 )); 1006 } 1007 for l in 0..c.layers { 1008 if at.contains(&l) { 1009 taps.push(x.clone()); 1010 } 1011 let w = self.read_layer(l)?; 1012 let mut xn = x.clone(); 1013 rms_norm_zc(&mut xn, &w.input_norm, c.eps); 1014 let mixed = match (&w.mixer, &mut state.layers[l]) { 1015 (Mixer::DeltaNet(d), LayerState::DeltaNet { conv, s }) => { 1016 delta_net(&c, d, &xn, t, conv, s) 1017 } 1018 (Mixer::Attention(a), LayerState::Attention { k, v }) => { 1019 attention(&c, a, &xn, t, state.pos, k, v) 1020 } 1021 _ => return Err(format!("layer {l}: state kind differs from the weights")), 1022 }; 1023 x.iter_mut().zip(&mixed).for_each(|(a, b)| *a += b); 1024 if self.moe_capture && matches!(w.mlp, Mlp::Moe(_)) { 1025 if self.moe_x.len() <= l { 1026 self.moe_x.resize(l + 1, Vec::new()); 1027 } 1028 self.moe_x[l] = x.clone(); 1029 } 1030 let mut xn = x.clone(); 1031 rms_norm_zc(&mut xn, &w.post_norm, c.eps); 1032 let down = match &w.mlp { 1033 Mlp::Dense(f) => f.run(&xn, t), 1034 Mlp::Moe(m) => self.moe(l, m, &xn, t)?, 1035 }; 1036 x.iter_mut().zip(&down).for_each(|(a, b)| *a += b); 1037 } 1038 if at.contains(&c.layers) { 1039 taps.push(x.clone()); 1040 } 1041 state.pos += t; 1042 let rows = match logits { 1043 Logits::Last => &x[(t - 1) * h..], 1044 Logits::All => &x[..], 1045 }; 1046 let mut rows = rows.to_vec(); 1047 rms_norm_zc(&mut rows, &self.final_norm, c.eps); 1048 Ok(self.lm_head.matmul(&rows, rows.len() / h)) 1049 } 1050 } 1051 1052 /// One DeltaNet mixer over `t` new tokens; updates the conv tail and the state. 1053 fn delta_net( 1054 c: &Qwen38Config, 1055 w: &DeltaNetWeights, 1056 xn: &[f32], 1057 t: usize, 1058 conv_tail: &mut [f32], 1059 state: &mut [f32], 1060 ) -> Vec { 1061 let (cd, kern) = (c.conv_dim(), c.conv_kernel); 1062 let qkv = w.in_qkv.matmul(xn, t); 1063 let z = w.in_z.matmul(xn, t); 1064 let a = w.in_a.matmul(xn, t); 1065 let b = w.in_b.matmul(xn, t); 1066 1067 // Causal depthwise conv over [tail | new], then SiLU. 1068 let hist = kern - 1; 1069 let mut seq = conv_tail.to_vec(); 1070 seq.extend_from_slice(&qkv); 1071 let mut mixed = vec![0f32; t * cd]; 1072 for i in 0..t { 1073 for ch in 0..cd { 1074 let taps = &w.conv[ch * kern..(ch + 1) * kern]; 1075 let acc: f32 = (0..kern).map(|j| taps[j] * seq[(i + j) * cd + ch]).sum(); 1076 mixed[i * cd + ch] = silu(acc); 1077 } 1078 } 1079 conv_tail.copy_from_slice(&seq[t * cd..(t + hist) * cd]); 1080 1081 let (kh, vh, kd, vd) = (c.lin_k_heads, c.lin_v_heads, c.lin_k_dim, c.lin_v_dim); 1082 let ratio = vh / kh; 1083 let key_dim = kh * kd; 1084 // Normalised q and k per token and k head. 1085 let mut q = vec![0f32; t * key_dim]; 1086 let mut k = vec![0f32; t * key_dim]; 1087 let q_scale = 1.0 / (kd as f32).sqrt(); 1088 for i in 0..t { 1089 let row = &mixed[i * cd..(i + 1) * cd]; 1090 q[i * key_dim..(i + 1) * key_dim].copy_from_slice(&row[..key_dim]); 1091 k[i * key_dim..(i + 1) * key_dim].copy_from_slice(&row[key_dim..2 * key_dim]); 1092 for hh in 0..kh { 1093 let r = i * key_dim + hh * kd..i * key_dim + (hh + 1) * kd; 1094 l2_normalize(&mut q[r.clone()], 1e-6); 1095 l2_normalize(&mut k[r.clone()], 1e-6); 1096 q[r].iter_mut().for_each(|v| *v *= q_scale); 1097 } 1098 } 1099 1100 // The recurrence, one value head per task. 1101 let mut core = vec![0f32; t * vh * vd]; 1102 let mut per_head: Vec> = vec![Vec::new(); vh]; 1103 state 1104 .par_chunks_mut(kd * vd) 1105 .zip(per_head.par_iter_mut()) 1106 .enumerate() 1107 .for_each(|(hv, (s, out))| { 1108 let hk = hv / ratio; 1109 let decay_rate = -w.a_log[hv].exp(); 1110 out.resize(t * vd, 0.0); 1111 let mut kv = vec![0f32; vd]; 1112 for i in 0..t { 1113 let kt = &k[i * key_dim + hk * kd..i * key_dim + (hk + 1) * kd]; 1114 let qt = &q[i * key_dim + hk * kd..i * key_dim + (hk + 1) * kd]; 1115 let vt = 1116 &mixed[i * cd + 2 * key_dim + hv * vd..i * cd + 2 * key_dim + (hv + 1) * vd]; 1117 let g = decay_rate * softplus(a[i * vh + hv] + w.dt_bias[hv]); 1118 let beta = sigmoid(b[i * vh + hv]); 1119 let decay = g.exp(); 1120 s.iter_mut().for_each(|v| *v *= decay); 1121 kv.iter_mut().for_each(|v| *v = 0.0); 1122 for (r, &kr) in kt.iter().enumerate() { 1123 for (o, &sv) in kv.iter_mut().zip(&s[r * vd..(r + 1) * vd]) { 1124 *o += sv * kr; 1125 } 1126 } 1127 let delta: Vec = vt.iter().zip(&kv).map(|(&v, &m)| (v - m) * beta).collect(); 1128 for (r, &kr) in kt.iter().enumerate() { 1129 for (sv, &d) in s[r * vd..(r + 1) * vd].iter_mut().zip(&delta) { 1130 *sv += kr * d; 1131 } 1132 } 1133 let o = &mut out[i * vd..(i + 1) * vd]; 1134 o.iter_mut().for_each(|v| *v = 0.0); 1135 for (r, &qr) in qt.iter().enumerate() { 1136 for (ov, &sv) in o.iter_mut().zip(&s[r * vd..(r + 1) * vd]) { 1137 *ov += sv * qr; 1138 } 1139 } 1140 } 1141 }); 1142 for (hv, out) in per_head.iter().enumerate() { 1143 for i in 0..t { 1144 core[i * vh * vd + hv * vd..i * vh * vd + (hv + 1) * vd] 1145 .copy_from_slice(&out[i * vd..(i + 1) * vd]); 1146 } 1147 } 1148 1149 // Gated RMSNorm per head (weight used as is), times silu(z). 1150 for (o, zr) in core.chunks_exact_mut(vd).zip(z.chunks_exact(vd)) { 1151 let ms = o.iter().map(|v| v * v).sum::() / vd as f32; 1152 let inv = 1.0 / (ms + c.eps).sqrt(); 1153 for ((v, &g), &zz) in o.iter_mut().zip(&w.norm).zip(zr) { 1154 *v = *v * inv * g * silu(zz); 1155 } 1156 } 1157 w.out.matmul(&core, t) 1158 } 1159 1160 /// One gated full-attention mixer over `t` new tokens starting at position `pos0`; appends their 1161 /// keys and values to the cache. 1162 fn attention( 1163 c: &Qwen38Config, 1164 w: &AttentionWeights, 1165 xn: &[f32], 1166 t: usize, 1167 pos0: usize, 1168 k_cache: &mut Vec, 1169 v_cache: &mut Vec, 1170 ) -> Vec { 1171 let (nh, hd, kvd) = (c.heads, c.head_dim, c.kv_dim()); 1172 let group = nh / c.kv_heads; 1173 let qg = w.q.matmul(xn, t); 1174 let mut k = w.k.matmul(xn, t); 1175 let v = w.v.matmul(xn, t); 1176 // Split per head [q | gate]; norm and turn q and k. 1177 let mut q = vec![0f32; t * nh * hd]; 1178 let mut gate = vec![0f32; t * nh * hd]; 1179 for i in 0..t { 1180 for hh in 0..nh { 1181 let src = &qg[(i * nh + hh) * 2 * hd..(i * nh + hh + 1) * 2 * hd]; 1182 let dq = &mut q[(i * nh + hh) * hd..(i * nh + hh + 1) * hd]; 1183 dq.copy_from_slice(&src[..hd]); 1184 rms_norm_zc(dq, &w.q_norm, c.eps); 1185 rope(dq, pos0 + i, c.rotary_dim, c.rope_theta); 1186 gate[(i * nh + hh) * hd..(i * nh + hh + 1) * hd].copy_from_slice(&src[hd..]); 1187 } 1188 for hh in 0..c.kv_heads { 1189 let dk = &mut k[i * kvd + hh * hd..i * kvd + (hh + 1) * hd]; 1190 rms_norm_zc(dk, &w.k_norm, c.eps); 1191 rope(dk, pos0 + i, c.rotary_dim, c.rope_theta); 1192 } 1193 } 1194 k_cache.extend_from_slice(&k); 1195 v_cache.extend_from_slice(&v); 1196 let (kc, vc) = (&k_cache[..], &v_cache[..]); 1197 let scale = 1.0 / (hd as f32).sqrt(); 1198 let mut out = vec![0f32; t * nh * hd]; 1199 out.par_chunks_mut(hd).enumerate().for_each(|(idx, o)| { 1200 let (i, hh) = (idx / nh, idx % nh); 1201 let kh = hh / group; 1202 let qv = &q[idx * hd..(idx + 1) * hd]; 1203 let span = pos0 + i + 1; 1204 let scores: Vec = (0..span) 1205 .map(|p| dot(qv, &kc[p * kvd + kh * hd..p * kvd + (kh + 1) * hd]) * scale) 1206 .collect(); 1207 let max = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max); 1208 let weights: Vec = scores.iter().map(|s| (s - max).exp()).collect(); 1209 let sum: f32 = weights.iter().sum(); 1210 for (p, &wt) in weights.iter().enumerate() { 1211 let vrow = &vc[p * kvd + kh * hd..p * kvd + (kh + 1) * hd]; 1212 for (ov, &vv) in o.iter_mut().zip(vrow) { 1213 *ov += wt * vv; 1214 } 1215 } 1216 let g = &gate[idx * hd..(idx + 1) * hd]; 1217 for (ov, &gv) in o.iter_mut().zip(g) { 1218 *ov = *ov / sum * sigmoid(gv); 1219 } 1220 }); 1221 w.o.matmul(&out, t) 1222 } 1223 1224 /// `-log softmax(logits)[target]` for one row. 1225 pub fn negative_log_likelihood(logits: &[f32], target: usize) -> f64 { 1226 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max) as f64; 1227 let sum: f64 = logits.iter().map(|&v| (v as f64 - max).exp()).sum(); 1228 max + sum.ln() - logits[target] as f64 1229 } 1230 1231 /// Index of the largest logit (first one on ties). 1232 pub fn argmax(logits: &[f32]) -> usize { 1233 let mut best = 0; 1234 for (i, &v) in logits.iter().enumerate() { 1235 if v > logits[best] { 1236 best = i; 1237 } 1238 } 1239 best 1240 } 1241 1242 #[cfg(test)] 1243 mod tests { 1244 use super::*; 1245 use crate::qwen3_moe::{f32_to_bf16, f32_to_fp8_e4m3fn}; 1246 use std::collections::HashMap; 1247 1248 /// Deterministic pseudo-random values in [-1, 1). 1249 fn prand(seed: u64, idx: usize) -> f32 { 1250 let mut x = seed 1251 .wrapping_mul(0x9E37_79B9_7F4A_7C15) 1252 .wrapping_add(idx as u64 + 1); 1253 x ^= x >> 29; 1254 x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9); 1255 x ^= x >> 32; 1256 ((x & 0xFFFF) as f32 / 32768.0) - 1.0 1257 } 1258 1259 #[derive(Default)] 1260 struct Mem { 1261 tensors: HashMap, Vec)>, 1262 seed: u64, 1263 } 1264 1265 impl TensorSource for Mem { 1266 fn read_into( 1267 &mut self, 1268 name: &str, 1269 dtype: &str, 1270 shape: &[usize], 1271 dst: &mut [u8], 1272 ) -> Result<(), String> { 1273 let (d, s, b) = self.tensors.get(name).ok_or(format!("{name}: missing"))?; 1274 if d != dtype || s != shape || b.len() != dst.len() { 1275 return Err(format!("{name}: {d} {s:?} asked {dtype} {shape:?}")); 1276 } 1277 dst.copy_from_slice(b); 1278 Ok(()) 1279 } 1280 fn dtype_of(&mut self, name: &str) -> Result, String> { 1281 Ok(self.tensors.get(name).map(|t| t.0.clone())) 1282 } 1283 } 1284 1285 impl Mem { 1286 fn bf16(&mut self, name: &str, shape: &[usize], scale: f32, offset: f32) { 1287 self.seed += 1; 1288 let n: usize = shape.iter().product(); 1289 let bytes = (0..n) 1290 .flat_map(|i| f32_to_bf16(offset + prand(self.seed, i) * scale).to_le_bytes()) 1291 .collect(); 1292 self.tensors 1293 .insert(name.into(), ("BF16".into(), shape.to_vec(), bytes)); 1294 } 1295 fn fp8(&mut self, name: &str, n: usize, k: usize) { 1296 self.seed += 1; 1297 let w = (0..n * k) 1298 .map(|i| f32_to_fp8_e4m3fn(prand(self.seed, i) * 8.0)) 1299 .collect(); 1300 self.tensors 1301 .insert(name.into(), ("F8_E4M3".into(), vec![n, k], w)); 1302 let grid = [n / FP8_BLOCK, k / FP8_BLOCK]; 1303 let s = (0..grid[0] * grid[1]) 1304 .flat_map(|i| f32_to_bf16(0.01 + 0.005 * prand(self.seed ^ 7, i)).to_le_bytes()) 1305 .collect(); 1306 self.tensors.insert( 1307 format!("{name}_scale_inv"), 1308 ("BF16".into(), grid.to_vec(), s), 1309 ); 1310 } 1311 } 1312 1313 #[test] 1314 fn read_vec_takes_bf16_and_f32_exactly_and_refuses_other_dtypes() { 1315 let mut m = Mem::default(); 1316 let vals = [1.0f32 / 3.0, -2.5e-7, 7.75]; 1317 let bytes = vals.iter().flat_map(|v| v.to_le_bytes()).collect(); 1318 m.tensors.insert("f".into(), ("F32".into(), vec![3], bytes)); 1319 assert_eq!(read_vec(&mut m, "f", 3).unwrap(), vals); 1320 m.bf16("b", &[3], 0.5, 0.0); 1321 let words = read_bf16_words(&mut m, "b", &[3]).unwrap(); 1322 let want: Vec = words.into_iter().map(bf16_to_f32).collect(); 1323 assert_eq!(read_vec(&mut m, "b", 3).unwrap(), want); 1324 assert!(read_vec(&mut m, "f", 4).is_err()); 1325 m.tensors 1326 .insert("h".into(), ("F16".into(), vec![3], vec![0; 6])); 1327 assert!(read_vec(&mut m, "h", 3).is_err()); 1328 } 1329 1330 fn tiny() -> Qwen38Config { 1331 Qwen38Config { 1332 hidden: 256, 1333 layers: 4, 1334 vocab: 64, 1335 intermediate: 384, 1336 full_attention: vec![false, false, false, true], 1337 heads: 4, 1338 kv_heads: 2, 1339 head_dim: 128, 1340 rotary_dim: 32, 1341 rope_theta: 1e7, 1342 lin_k_heads: 2, 1343 lin_v_heads: 4, 1344 lin_k_dim: 64, 1345 lin_v_dim: 64, 1346 conv_kernel: 4, 1347 eps: 1e-6, 1348 eos_token_ids: vec![1], 1349 moe: None, 1350 fp8: true, 1351 } 1352 } 1353 1354 fn tiny_moe() -> Qwen38Config { 1355 Qwen38Config { 1356 intermediate: 0, 1357 moe: Some(MoeShape { 1358 experts: 8, 1359 top_k: 3, 1360 expert_inter: 128, 1361 shared_inter: 256, 1362 }), 1363 ..tiny() 1364 } 1365 } 1366 1367 fn tiny_source(c: &Qwen38Config) -> Mem { 1368 let mut m = Mem::default(); 1369 let (h, p) = (c.hidden, "model.language_model."); 1370 m.bf16(&format!("{p}embed_tokens.weight"), &[c.vocab, h], 1.0, 0.0); 1371 m.bf16(&format!("{p}norm.weight"), &[h], 0.1, 0.0); 1372 m.bf16("lm_head.weight", &[c.vocab, h], 0.1, 0.0); 1373 for l in 0..c.layers { 1374 let lp = format!("{p}layers.{l}"); 1375 m.bf16(&format!("{lp}.input_layernorm.weight"), &[h], 0.1, 0.0); 1376 m.bf16( 1377 &format!("{lp}.post_attention_layernorm.weight"), 1378 &[h], 1379 0.1, 1380 0.0, 1381 ); 1382 if c.full_attention[l] { 1383 let a = format!("{lp}.self_attn"); 1384 m.fp8(&format!("{a}.q_proj.weight"), 2 * c.heads * c.head_dim, h); 1385 m.fp8(&format!("{a}.k_proj.weight"), c.kv_dim(), h); 1386 m.fp8(&format!("{a}.v_proj.weight"), c.kv_dim(), h); 1387 m.fp8(&format!("{a}.o_proj.weight"), h, c.heads * c.head_dim); 1388 m.bf16(&format!("{a}.q_norm.weight"), &[c.head_dim], 0.1, 0.0); 1389 m.bf16(&format!("{a}.k_norm.weight"), &[c.head_dim], 0.1, 0.0); 1390 } else { 1391 let a = format!("{lp}.linear_attn"); 1392 m.fp8(&format!("{a}.in_proj_qkv.weight"), c.conv_dim(), h); 1393 m.fp8(&format!("{a}.in_proj_z.weight"), c.lin_value_dim(), h); 1394 m.bf16( 1395 &format!("{a}.in_proj_a.weight"), 1396 &[c.lin_v_heads, h], 1397 0.05, 1398 0.0, 1399 ); 1400 m.bf16( 1401 &format!("{a}.in_proj_b.weight"), 1402 &[c.lin_v_heads, h], 1403 0.05, 1404 0.0, 1405 ); 1406 m.bf16( 1407 &format!("{a}.conv1d.weight"), 1408 &[c.conv_dim(), 1, c.conv_kernel], 1409 0.5, 1410 0.0, 1411 ); 1412 m.bf16(&format!("{a}.A_log"), &[c.lin_v_heads], 0.5, 0.0); 1413 m.bf16(&format!("{a}.dt_bias"), &[c.lin_v_heads], 0.5, 0.0); 1414 m.bf16(&format!("{a}.norm.weight"), &[c.lin_v_dim], 0.1, 1.0); 1415 m.fp8(&format!("{a}.out_proj.weight"), h, c.lin_value_dim()); 1416 } 1417 let mp = format!("{lp}.mlp"); 1418 let ffn = |m: &mut Mem, p: &str, inter: usize| { 1419 m.fp8(&format!("{p}.gate_proj.weight"), inter, h); 1420 m.fp8(&format!("{p}.up_proj.weight"), inter, h); 1421 m.fp8(&format!("{p}.down_proj.weight"), h, inter); 1422 }; 1423 match &c.moe { 1424 None => ffn(&mut m, &mp, c.intermediate), 1425 Some(s) => { 1426 m.bf16(&format!("{mp}.gate.weight"), &[s.experts, h], 0.5, 0.0); 1427 m.bf16( 1428 &format!("{mp}.shared_expert_gate.weight"), 1429 &[1, h], 1430 0.2, 1431 0.0, 1432 ); 1433 ffn(&mut m, &format!("{mp}.shared_expert"), s.shared_inter); 1434 for e in 0..s.experts { 1435 ffn(&mut m, &format!("{mp}.experts.{e}"), s.expert_inter); 1436 } 1437 } 1438 } 1439 } 1440 m 1441 } 1442 1443 #[test] 1444 fn reads_the_27b_config() { 1445 let json = r#"{"model_type":"qwen3_5","tie_word_embeddings":false, 1446 "quantization_config":{"quant_method":"fp8","fmt":"e4m3","weight_block_size":[128,128]}, 1447 "text_config":{"attn_output_gate":true,"hidden_act":"silu","hidden_size":5120, 1448 "num_hidden_layers":4,"vocab_size":248320,"intermediate_size":17408, 1449 "layer_types":["linear_attention","linear_attention","linear_attention","full_attention"], 1450 "num_attention_heads":24,"num_key_value_heads":4,"head_dim":256, 1451 "rope_parameters":{"rope_theta":`10000000`,"partial_rotary_factor":0.25}, 1452 "linear_num_key_heads":16,"linear_num_value_heads":48,"linear_key_head_dim":128, 1453 "linear_value_head_dim":128,"linear_conv_kernel_dim":4,"rms_norm_eps":1e-6, 1454 "eos_token_id":248044}}"#; 1455 let c = Qwen38Config::from_json(json, Some(r#"{"eos_token_id":[248046,248044]}"#)).unwrap(); 1456 assert_eq!(c.rotary_dim, 64); 1457 assert_eq!(c.conv_dim(), 10240); 1458 assert_eq!(c.full_attention, vec![false, false, false, true]); 1459 assert_eq!(c.eos_token_ids, vec![248046, 248044]); 1460 assert!(c.fp8); 1461 let tied = json.replace( 1462 "\"tie_word_embeddings\":false", 1463 "\"tie_word_embeddings\":true", 1464 ); 1465 assert!(Qwen38Config::from_json(&tied, None).is_err()); 1466 let int8 = json.replace("\"fp8\"", "\"int8\""); 1467 assert!(Qwen38Config::from_json(&int8, None).is_err()); 1468 } 1469 1470 #[test] 1471 fn the_dense_door_takes_the_27b_and_the_9b_shape() { 1472 let j27 = r#"{"model_type":"qwen3_5","tie_word_embeddings":false, 1473 "quantization_config":{"quant_method":"fp8","fmt":"e4m3","weight_block_size":[128,128]}, 1474 "text_config":{"attn_output_gate":true,"hidden_act":"silu","hidden_size":5120, 1475 "num_hidden_layers":4,"vocab_size":248320,"intermediate_size":17408, 1476 "layer_types":["linear_attention","linear_attention","linear_attention","full_attention"], 1477 "num_attention_heads":24,"num_key_value_heads":4,"head_dim":256, 1478 "rope_parameters":{"rope_theta":`10000000`,"partial_rotary_factor":0.25}, 1479 "linear_num_key_heads":16,"linear_num_value_heads":48,"linear_key_head_dim":128, 1480 "linear_value_head_dim":128,"linear_conv_kernel_dim":4,"rms_norm_eps":1e-6, 1481 "eos_token_id":248044}}"#; 1482 let c27 = Qwen38Config::from_json(j27, None).unwrap(); 1483 let s27 = crate::qwen38_omega::dense_shape(&c27).unwrap(); 1484 assert_eq!(s27, aien_omega_q38::Shape::Q38_27B); 1485 // Qwen3.5-9B (HF Qwen/Qwen3.5-9B config.json text_config) 1486 let j9 = j27 1487 .replace("\"hidden_size\":5120", "\"hidden_size\":4096") 1488 .replace("\"intermediate_size\":17408", "\"intermediate_size\":12288") 1489 .replace("\"num_attention_heads\":24", "\"num_attention_heads\":16") 1490 .replace( 1491 "\"linear_num_value_heads\":48", 1492 "\"linear_num_value_heads\":32", 1493 ); 1494 let c9 = Qwen38Config::from_json(&j9, None).unwrap(); 1495 let s9 = crate::qwen38_omega::dense_shape(&c9).unwrap(); 1496 assert_eq!( 1497 (s9.hidden, s9.inter, s9.q_heads, s9.kv_heads, s9.gdn_heads), 1498 (4096, 12288, 16, 4, 32) 1499 ); 1500 assert_eq!( 1501 (s9.gdn_qkv(), s9.gdn_mix(), s9.att_mix(), s9.mixer_out()), 1502 (8192, 12288, 10240, 4096) 1503 ); 1504 // refused: a head_dim the kernels do not have, and a GDN head count outside {32, 48} 1505 let hd = j9.replace("\"head_dim\":256", "\"head_dim\":128"); 1506 assert!( 1507 crate::qwen38_omega::dense_shape(&Qwen38Config::from_json(&hd, None).unwrap()).is_err() 1508 ); 1509 let gh = j9.replace( 1510 "\"linear_num_value_heads\":32", 1511 "\"linear_num_value_heads\":16", 1512 ); 1513 assert!( 1514 crate::qwen38_omega::dense_shape(&Qwen38Config::from_json(&gh, None).unwrap()).is_err() 1515 ); 1516 } 1517 1518 #[test] 1519 fn fp8_matmul_matches_the_scalar_formula() { 1520 let mut m = Mem::default(); 1521 m.fp8("w", 256, 384); 1522 let w = read_matrix(&mut m, "w", 256, 384).unwrap(); 1523 let x: Vec = (0..3 * 384).map(|i| prand(9, i)).collect(); 1524 let y = w.matmul(&x, 3); 1525 let Matrix::Fp8 { w: q, scales, .. } = &w else { 1526 panic!() 1527 }; 1528 let lut = fp8_table(); 1529 for t in 0..3 { 1530 for r in 0..256 { 1531 let want: f64 = (0..384) 1532 .map(|c| { 1533 let s = bf16_to_f32(scales[(r / 128) * 3 + c / 128]) as f64; 1534 lut[q[r * 384 + c] as usize] as f64 * s * x[t * 384 + c] as f64 1535 }) 1536 .sum(); 1537 let got = y[t * 256 + r] as f64; 1538 assert!( 1539 (got - want).abs() <= 1e-4 * (1.0 + want.abs()), 1540 "{t} {r} {got} {want}" 1541 ); 1542 } 1543 } 1544 } 1545 1546 #[test] 1547 fn rope_turns_only_the_leading_dims() { 1548 let mut x: Vec = (0..8).map(|i| i as f32 + 1.0).collect(); 1549 rope(&mut x, 0, 4, 1e4); 1550 assert_eq!(x, (0..8).map(|i| i as f32 + 1.0).collect::>()); 1551 rope(&mut x, 3, 4, 1e4); 1552 // j = 0: frequency 1, angle 3; pairs (x0, x2). 1553 let (s, c) = 3f32.sin_cos(); 1554 assert!((x[0] - (1.0 * c - 3.0 * s)).abs() < 1e-6); 1555 assert!((x[2] - (3.0 * c + 1.0 * s)).abs() < 1e-6); 1556 assert_eq!(&x[4..], &[5.0, 6.0, 7.0, 8.0]); 1557 } 1558 1559 /// Scoring a sequence in one call and running it token by token through the carried state 1560 /// must give the same logits: the conv tails, DeltaNet states, KV cache and positions all 1561 /// carry over correctly. 1562 #[test] 1563 fn one_call_equals_token_by_token() { 1564 let c = tiny(); 1565 let mut whole = Qwen38Reference::new(c.clone(), tiny_source(&c)).unwrap(); 1566 let mut steps = Qwen38Reference::new(c.clone(), tiny_source(&c)).unwrap(); 1567 let tokens = [5u32, 17, 3, 42, 8, 8, 60]; 1568 let mut s1 = whole.new_state(); 1569 let all = whole.forward(&mut s1, &tokens, Logits::All).unwrap(); 1570 let mut s2 = steps.new_state(); 1571 // A two-token prefix, then single tokens. 1572 let mut rows = steps.forward(&mut s2, &tokens[..2], Logits::All).unwrap(); 1573 for &tok in &tokens[2..] { 1574 rows.extend(steps.forward(&mut s2, &[tok], Logits::Last).unwrap()); 1575 } 1576 assert_eq!(s1.pos, tokens.len()); 1577 assert_eq!(s2.pos, tokens.len()); 1578 let max_diff = all 1579 .iter() 1580 .zip(&rows) 1581 .map(|(a, b)| (a - b).abs()) 1582 .fold(0f32, f32::max); 1583 assert!(max_diff < 1e-4, "max logit difference {max_diff}"); 1584 // And the logits are not degenerate. 1585 let spread = all.iter().cloned().fold(f32::MIN, f32::max) 1586 - all.iter().cloned().fold(f32::MAX, f32::min); 1587 assert!(spread > 1e-3, "logit spread {spread}"); 1588 } 1589 1590 #[test] 1591 fn refuses_an_fp8_weight_without_scales() { 1592 let mut m = Mem::default(); 1593 m.fp8("w", 128, 128); 1594 m.tensors.remove("w_scale_inv"); 1595 assert!(read_matrix(&mut m, "w", 128, 128) 1596 .unwrap_err() 1597 .contains("without")); 1598 } 1599 1600 #[test] 1601 fn nll_and_argmax() { 1602 let l = [0.0f32, 2.0, 1.0]; 1603 assert_eq!(argmax(&l), 1); 1604 let z: f64 = l.iter().map(|&v| (v as f64).exp()).sum(); 1605 assert!((negative_log_likelihood(&l, 2) - (z.ln() - 1.0)).abs() < 1e-12); 1606 } 1607 1608 #[test] 1609 fn reads_the_35b_config() { 1610 let json = r#"{"model_type":"qwen3_5_moe","tie_word_embeddings":false, 1611 "quantization_config":{"quant_method":"fp8","fmt":"e4m3","weight_block_size":[128,128]}, 1612 "text_config":{"attn_output_gate":true,"hidden_act":"silu","hidden_size":2048, 1613 "num_hidden_layers":4,"vocab_size":248320,"moe_intermediate_size":512, 1614 "shared_expert_intermediate_size":512,"num_experts":256,"num_experts_per_tok":8, 1615 "layer_types":["linear_attention","linear_attention","linear_attention","full_attention"], 1616 "num_attention_heads":16,"num_key_value_heads":2,"head_dim":256, 1617 "rope_parameters":{"rope_theta":`10000000`,"partial_rotary_factor":0.25}, 1618 "linear_num_key_heads":16,"linear_num_value_heads":32,"linear_key_head_dim":128, 1619 "linear_value_head_dim":128,"linear_conv_kernel_dim":4,"rms_norm_eps":1e-6, 1620 "eos_token_id":248044}}"#; 1621 let c = Qwen38Config::from_json(json, None).unwrap(); 1622 assert_eq!(c.conv_dim(), 8192); 1623 assert_eq!(c.lin_value_dim(), 4096); 1624 assert_eq!(c.kv_dim(), 512); 1625 assert_eq!(c.intermediate, 0); 1626 assert_eq!( 1627 c.moe, 1628 Some(MoeShape { 1629 experts: 256, 1630 top_k: 8, 1631 expert_inter: 512, 1632 shared_inter: 512 1633 }) 1634 ); 1635 let bad = json.replace("\"num_experts_per_tok\":8", "\"num_experts_per_tok\":300"); 1636 assert!(Qwen38Config::from_json(&bad, None).is_err()); 1637 } 1638 1639 #[test] 1640 fn route_renormalises_and_breaks_ties_low() { 1641 let l = [0.5f32, 2.0, 2.0, -1.0, 1.0]; 1642 let r = route(&l, 3, 0); 1643 assert_eq!(r.iter().map(|p| p.0).collect::>(), vec![1, 2, 4]); 1644 let s: f32 = r.iter().map(|p| p.1).sum(); 1645 assert!((s - 1.0).abs() < 1e-6); 1646 let (e2, e1) = (2f32.exp(), 1f32.exp()); 1647 assert!((r[0].1 - e2 / (2.0 * e2 + e1)).abs() < 1e-6); 1648 let m = route(&l, 3, 1); 1649 assert_eq!(m.iter().map(|p| p.0).collect::>(), vec![1, 2, 0]); 1650 } 1651 1652 #[test] 1653 fn moe_one_call_equals_token_by_token() { 1654 let c = tiny_moe(); 1655 let mut whole = Qwen38Reference::new(c.clone(), tiny_source(&c)).unwrap(); 1656 let mut steps = Qwen38Reference::new(c.clone(), tiny_source(&c)).unwrap(); 1657 let tokens = [5u32, 17, 3, 42, 8, 8, 60]; 1658 let mut s1 = whole.new_state(); 1659 let all = whole.forward(&mut s1, &tokens, Logits::All).unwrap(); 1660 let mut s2 = steps.new_state(); 1661 let mut rows = steps.forward(&mut s2, &tokens[..2], Logits::All).unwrap(); 1662 for &tok in &tokens[2..] { 1663 rows.extend(steps.forward(&mut s2, &[tok], Logits::Last).unwrap()); 1664 } 1665 let max_diff = all 1666 .iter() 1667 .zip(&rows) 1668 .map(|(a, b)| (a - b).abs()) 1669 .fold(0f32, f32::max); 1670 assert!(max_diff < 1e-4, "max logit difference {max_diff}"); 1671 assert_eq!(whole.routes.len(), c.layers); 1672 assert_eq!(whole.routes[0].len(), tokens.len() * 3); 1673 // More than one expert set in use (the router is not degenerate). 1674 let mut sets: Vec> = whole.routes[0].chunks(3).map(|s| s.to_vec()).collect(); 1675 sets.dedup(); 1676 assert!(sets.len() > 1, "{sets:?}"); 1677 // The routing mutant moves the logits. 1678 let mut mutant = Qwen38Reference::new(c.clone(), tiny_source(&c)).unwrap(); 1679 mutant.routing_mutant = 1; 1680 let mut s3 = mutant.new_state(); 1681 let bad = mutant.forward(&mut s3, &tokens, Logits::All).unwrap(); 1682 let moved = all 1683 .iter() 1684 .zip(&bad) 1685 .map(|(a, b)| (a - b).abs()) 1686 .fold(0f32, f32::max); 1687 assert!(moved > 1e-3, "mutant moved the logits by only {moved}"); 1688 } 1689 1690 /// The sparse block against a brute-force f64 evaluation from the raw tensors. 1691 #[test] 1692 fn moe_block_matches_brute_force() { 1693 let c = tiny_moe(); 1694 let s = c.moe.clone().unwrap(); 1695 let mut src = tiny_source(&c); 1696 let mut r = Qwen38Reference::new(c.clone(), tiny_source(&c)).unwrap(); 1697 let h = c.hidden; 1698 let t = 4; 1699 let xn: Vec = (0..t * h).map(|i| prand(77, i)).collect(); 1700 let w = r.read_layer(0).unwrap(); 1701 let Mlp::Moe(m) = &w.mlp else { panic!() }; 1702 let got = r.moe(0, m, &xn, t).unwrap(); 1703 let p = "model.language_model.layers.0.mlp"; 1704 let lut = fp8_table(); 1705 let wide = |src: &mut Mem, name: &str, n: usize, k: usize| -> Vec { 1706 match read_matrix(src, name, n, k).unwrap() { 1707 Matrix::Fp8 { w, scales, .. } => (0..n * k) 1708 .map(|i| { 1709 let (r, c) = (i / k, i % k); 1710 lut[w[i] as usize] as f64 1711 * bf16_to_f32(scales[(r / 128) * (k / 128) + c / 128]) as f64 1712 }) 1713 .collect(), 1714 Matrix::Bf16 { w, .. } => w.iter().map(|&b| bf16_to_f32(b) as f64).collect(), 1715 } 1716 }; 1717 let mv = |w: &[f64], x: &[f64], n: usize| -> Vec { 1718 let k = x.len(); 1719 (0..n) 1720 .map(|r| (0..k).map(|c| w[r * k + c] * x[c]).sum()) 1721 .collect() 1722 }; 1723 let ffn = |src: &mut Mem, q: &str, inter: usize, x: &[f64]| -> Vec { 1724 let g = mv( 1725 &wide(src, &format!("{q}.gate_proj.weight"), inter, h), 1726 x, 1727 inter, 1728 ); 1729 let u = mv( 1730 &wide(src, &format!("{q}.up_proj.weight"), inter, h), 1731 x, 1732 inter, 1733 ); 1734 let a: Vec = g 1735 .iter() 1736 .zip(&u) 1737 .map(|(&g, &u)| g / (1.0 + (-g).exp()) * u) 1738 .collect(); 1739 mv( 1740 &wide(src, &format!("{q}.down_proj.weight"), h, inter), 1741 &a, 1742 h, 1743 ) 1744 }; 1745 let router = wide(&mut src, &format!("{p}.gate.weight"), s.experts, h); 1746 let sg = wide(&mut src, &format!("{p}.shared_expert_gate.weight"), 1, h); 1747 let mut worst = 0f64; 1748 for i in 0..t { 1749 let x: Vec = xn[i * h..(i + 1) * h].iter().map(|&v| v as f64).collect(); 1750 let logits = mv(&router, &x, s.experts); 1751 let mut order: Vec = (0..s.experts).collect(); 1752 order.sort_by(|&a, &b| logits[b].total_cmp(&logits[a])); 1753 let top = &order[..s.top_k]; 1754 let z: f64 = top.iter().map(|&e| logits[e].exp()).sum(); 1755 let gate = 1.0 / (1.0 + (-mv(&sg, &x, 1)[0]).exp()); 1756 let mut want: Vec = 1757 ffn(&mut src, &format!("{p}.shared_expert"), s.shared_inter, &x) 1758 .into_iter() 1759 .map(|v| v * gate) 1760 .collect(); 1761 for &e in top { 1762 let y = ffn(&mut src, &format!("{p}.experts.{e}"), s.expert_inter, &x); 1763 let wt = logits[e].exp() / z; 1764 want.iter_mut().zip(&y).for_each(|(o, v)| *o += wt * v); 1765 } 1766 let ids: Vec = r.routes[0][i * s.top_k..(i + 1) * s.top_k].to_vec(); 1767 assert_eq!( 1768 ids, 1769 top.iter().map(|&e| e as u16).collect::>(), 1770 "row {i}" 1771 ); 1772 for (j, w) in want.iter().enumerate() { 1773 let d = (got[i * h + j] as f64 - w).abs() / (1.0 + w.abs()); 1774 worst = worst.max(d); 1775 } 1776 } 1777 assert!(worst < 1e-4, "worst relative error {worst}"); 1778 } 1779 }