aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen3_moe.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-Coder-30B-A3B routed expert layer on GB10. |
| 17 | //! |
| 18 | //! Three pieces share one tensor contract: |
| 19 | //! - sharded FP8 checkpoint ingest into a [`ModelCapsule`] (one layer, no FP32 copy), |
| 20 | //! - the batch routing plan contract shared with the Omega GPU path, |
| 21 | //! - an FP32 CPU oracle that dequantizes only the experts a token selected. |
| 22 | //! |
| 23 | //! Capsule tensors, all row-major: |
| 24 | //! `router` BF16 [128, H]; `gate_up` FP8 E4M3 [128, 2I, H] (gate rows then up rows); |
| 25 | //! `gate_up_scale_inv` BF16 [128, 2I/128, H/128]; `down` FP8 E4M3 [128, H, I]; |
| 26 | //! `down_scale_inv` BF16 [128, H/128, I/128]. |
| 27 | |
| 28 | use std::collections::HashMap; |
| 29 | use std::fmt; |
| 30 | use std::fs::File; |
| 31 | use std::os::unix::fs::FileExt; |
| 32 | use std::path::{Component, Path, PathBuf}; |
| 33 | use std::sync::Arc; |
| 34 | |
| 35 | use rayon::prelude::*; |
| 36 | |
| 37 | use crate::capsule::{ |
| 38 | capsule_digest, row_major_strides, source_digest, CapsuleTensor, ModelCapsule, |
| 39 | QuantizationDescriptor, TensorLayout, WeightDType, |
| 40 | }; |
| 41 | use crate::moe_plan::{MoeBatchPlan, MoePlanError, QWEN3_CODER_A3B_EXPERTS}; |
| 42 | |
| 43 | pub const QWEN3_A3B_HIDDEN: usize = 2048; |
| 44 | pub const QWEN3_A3B_INTERMEDIATE: usize = 768; |
| 45 | pub const QWEN3_A3B_LAYERS: usize = 48; |
| 46 | const BLOCK: usize = 128; |
| 47 | pub(crate) const FP8_BLOCK: usize = BLOCK; |
| 48 | const EXPERTS: usize = QWEN3_CODER_A3B_EXPERTS; |
| 49 | /// Largest safetensors JSON header accepted; real Qwen shards use about 2 MB. |
| 50 | const MAX_HEADER_BYTES: u64 = 256 << 20; |
| 51 | |
| 52 | pub const ROUTER: &str = "router"; |
| 53 | pub const GATE_UP: &str = "gate_up"; |
| 54 | pub const GATE_UP_SCALE_INV: &str = "gate_up_scale_inv"; |
| 55 | pub const DOWN: &str = "down"; |
| 56 | pub const DOWN_SCALE_INV: &str = "down_scale_inv"; |
| 57 | |
| 58 | #[derive(Debug, Clone, PartialEq)] |
| 59 | pub enum Qwen3MoeError { |
| 60 | Io(String), |
| 61 | Index(String), |
| 62 | Contract(String), |
| 63 | Plan(MoePlanError), |
| 64 | } |
| 65 | |
| 66 | impl fmt::Display for Qwen3MoeError { |
| 67 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 68 | match self { |
| 69 | Self::Io(detail) => write!(f, "checkpoint I/O: {detail}"), |
| 70 | Self::Index(detail) => write!(f, "checkpoint index: {detail}"), |
| 71 | Self::Contract(detail) => write!(f, "tensor contract: {detail}"), |
| 72 | Self::Plan(error) => write!(f, "routing plan: {error}"), |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl std::error::Error for Qwen3MoeError {} |
| 78 | |
| 79 | impl From<MoePlanError> for Qwen3MoeError { |
| 80 | fn from(error: MoePlanError) -> Self { |
| 81 | Self::Plan(error) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// One routed expert layer held in a capsule. Accessors borrow typed views of it. |
| 86 | #[derive(Debug, Clone)] |
| 87 | pub struct Qwen3MoeLayer { |
| 88 | pub hidden: usize, |
| 89 | pub intermediate: usize, |
| 90 | pub capsule: ModelCapsule, |
| 91 | } |
| 92 | |
| 93 | fn fp8_block_quant() -> Option<QuantizationDescriptor> { |
| 94 | Some(QuantizationDescriptor { |
| 95 | scheme: "fp8-e4m3fn-block128x128-bf16-scale-inv".to_string(), |
| 96 | axis: 0, |
| 97 | group_size: BLOCK, |
| 98 | scales: Vec::new(), |
| 99 | zero_points: Vec::new(), |
| 100 | packing: "none".to_string(), |
| 101 | }) |
| 102 | } |
| 103 | |
| 104 | /// (name, dtype, shape, element bytes) for every capsule tensor, in payload order. |
| 105 | fn layer_tensor_specs( |
| 106 | hidden: usize, |
| 107 | intermediate: usize, |
| 108 | ) -> [(&'static str, WeightDType, Vec<usize>, usize); 5] { |
| 109 | let (h, i) = (hidden, intermediate); |
| 110 | [ |
| 111 | (ROUTER, WeightDType::Bf16, vec![EXPERTS, h], 2), |
| 112 | (GATE_UP, WeightDType::Fp8E4M3Fn, vec![EXPERTS, 2 * i, h], 1), |
| 113 | ( |
| 114 | GATE_UP_SCALE_INV, |
| 115 | WeightDType::Bf16, |
| 116 | vec![EXPERTS, 2 * i / BLOCK, h / BLOCK], |
| 117 | 2, |
| 118 | ), |
| 119 | (DOWN, WeightDType::Fp8E4M3Fn, vec![EXPERTS, h, i], 1), |
| 120 | ( |
| 121 | DOWN_SCALE_INV, |
| 122 | WeightDType::Bf16, |
| 123 | vec![EXPERTS, h / BLOCK, i / BLOCK], |
| 124 | 2, |
| 125 | ), |
| 126 | ] |
| 127 | } |
| 128 | |
| 129 | fn as_u16(bytes: &[u8]) -> &[u16] { |
| 130 | // SAFETY: u16 has no invalid bit patterns; alignment is checked below. |
| 131 | let (prefix, values, suffix) = unsafe { bytes.align_to::<u16>() }; |
| 132 | assert!( |
| 133 | prefix.is_empty() && suffix.is_empty(), |
| 134 | "BF16 capsule view misaligned" |
| 135 | ); |
| 136 | values |
| 137 | } |
| 138 | |
| 139 | impl Qwen3MoeLayer { |
| 140 | /// Packs raw tensors into a capsule. BF16 tensors are raw bits; FP8 tensors are raw E4M3 bytes. |
| 141 | pub fn from_parts( |
| 142 | hidden: usize, |
| 143 | intermediate: usize, |
| 144 | router: &[u16], |
| 145 | gate_up: &[u8], |
| 146 | gate_up_scale_inv: &[u16], |
| 147 | down: &[u8], |
| 148 | down_scale_inv: &[u16], |
| 149 | ) -> Result<Self, Qwen3MoeError> { |
| 150 | Self::build(hidden, intermediate, |name, dst| { |
| 151 | let src: &[u8] = match name { |
| 152 | ROUTER => bytes_of(router), |
| 153 | GATE_UP => gate_up, |
| 154 | GATE_UP_SCALE_INV => bytes_of(gate_up_scale_inv), |
| 155 | DOWN => down, |
| 156 | _ => bytes_of(down_scale_inv), |
| 157 | }; |
| 158 | if src.len() != dst.len() { |
| 159 | return Err(Qwen3MoeError::Contract(format!( |
| 160 | "{name}: {} bytes supplied, {} expected", |
| 161 | src.len(), |
| 162 | dst.len() |
| 163 | ))); |
| 164 | } |
| 165 | dst.copy_from_slice(src); |
| 166 | Ok(()) |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | /// Allocates the capsule payload once and lets `fill` write each tensor in place. |
| 171 | fn build( |
| 172 | hidden: usize, |
| 173 | intermediate: usize, |
| 174 | mut fill: impl FnMut(&str, &mut [u8]) -> Result<(), Qwen3MoeError>, |
| 175 | ) -> Result<Self, Qwen3MoeError> { |
| 176 | if hidden == 0 |
| 177 | || intermediate == 0 |
| 178 | || !hidden.is_multiple_of(BLOCK) |
| 179 | || !intermediate.is_multiple_of(BLOCK) |
| 180 | { |
| 181 | return Err(Qwen3MoeError::Contract(format!( |
| 182 | "hidden {hidden} and intermediate {intermediate} must be positive multiples of {BLOCK}" |
| 183 | ))); |
| 184 | } |
| 185 | let specs = layer_tensor_specs(hidden, intermediate); |
| 186 | let mut ranges = Vec::with_capacity(specs.len()); |
| 187 | let mut cursor = 0usize; |
| 188 | for (_, _, shape, element_bytes) in &specs { |
| 189 | // 256-byte alignment keeps every view aligned for vector loads. |
| 190 | let start = cursor.div_ceil(256) * 256; |
| 191 | let end = start + shape.iter().product::<usize>() * element_bytes; |
| 192 | ranges.push(start..end); |
| 193 | cursor = end; |
| 194 | } |
| 195 | let mut payload = vec![0u8; cursor]; |
| 196 | for ((name, ..), range) in specs.iter().zip(&ranges) { |
| 197 | fill(name, &mut payload[range.clone()])?; |
| 198 | } |
| 199 | let bytes: Arc<[u8]> = Arc::from(payload); |
| 200 | let mut tensors = HashMap::new(); |
| 201 | for ((name, dtype, shape, _), range) in specs.into_iter().zip(ranges) { |
| 202 | let quant = if dtype == WeightDType::Fp8E4M3Fn { |
| 203 | fp8_block_quant() |
| 204 | } else { |
| 205 | None |
| 206 | }; |
| 207 | tensors.insert( |
| 208 | name.to_string(), |
| 209 | CapsuleTensor { |
| 210 | dtype, |
| 211 | layout: TensorLayout::RowMajor, |
| 212 | logical_strides: row_major_strides(&shape), |
| 213 | shape, |
| 214 | byte_range: range, |
| 215 | quant, |
| 216 | }, |
| 217 | ); |
| 218 | } |
| 219 | Ok(Self { |
| 220 | hidden, |
| 221 | intermediate, |
| 222 | capsule: ModelCapsule { |
| 223 | source_digest: source_digest(&bytes), |
| 224 | capsule_digest: capsule_digest(&bytes, &tensors), |
| 225 | bytes, |
| 226 | tensors, |
| 227 | }, |
| 228 | }) |
| 229 | } |
| 230 | |
| 231 | fn view(&self, name: &str) -> &[u8] { |
| 232 | self.capsule |
| 233 | .tensor_bytes(name) |
| 234 | .expect("Qwen3MoeLayer capsule always holds its five tensors") |
| 235 | } |
| 236 | |
| 237 | pub fn router_bf16(&self) -> &[u16] { |
| 238 | as_u16(self.view(ROUTER)) |
| 239 | } |
| 240 | pub fn gate_up_fp8(&self) -> &[u8] { |
| 241 | self.view(GATE_UP) |
| 242 | } |
| 243 | pub fn gate_up_scale_inv_bf16(&self) -> &[u16] { |
| 244 | as_u16(self.view(GATE_UP_SCALE_INV)) |
| 245 | } |
| 246 | pub fn down_fp8(&self) -> &[u8] { |
| 247 | self.view(DOWN) |
| 248 | } |
| 249 | pub fn down_scale_inv_bf16(&self) -> &[u16] { |
| 250 | as_u16(self.view(DOWN_SCALE_INV)) |
| 251 | } |
| 252 | |
| 253 | /// Bytes resident on the device for this layer's weights. |
| 254 | pub fn resident_weight_bytes(&self) -> usize { |
| 255 | [ROUTER, GATE_UP, GATE_UP_SCALE_INV, DOWN, DOWN_SCALE_INV] |
| 256 | .iter() |
| 257 | .map(|name| self.view(name).len()) |
| 258 | .sum() |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | fn bytes_of(values: &[u16]) -> &[u8] { |
| 263 | // SAFETY: any u16 slice is a valid byte slice of twice the length. |
| 264 | unsafe { std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), values.len() * 2) } |
| 265 | } |
| 266 | |
| 267 | /// Resolves a shard filename from the index. Only a single plain path component |
| 268 | /// is accepted, so an index entry cannot point outside `checkpoint_dir`. |
| 269 | pub(crate) fn shard_path(checkpoint_dir: &Path, filename: &str) -> Result<PathBuf, Qwen3MoeError> { |
| 270 | let mut components = Path::new(filename).components(); |
| 271 | match (components.next(), components.next()) { |
| 272 | (Some(Component::Normal(name)), None) if name == filename => Ok(checkpoint_dir.join(name)), |
| 273 | _ => Err(Qwen3MoeError::Index(format!( |
| 274 | "shard filename {filename:?} is not a plain file name inside the checkpoint directory" |
| 275 | ))), |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | pub(crate) struct Shard { |
| 280 | file: File, |
| 281 | payload_start: u64, |
| 282 | file_len: u64, |
| 283 | header: serde_json::Map<String, serde_json::Value>, |
| 284 | } |
| 285 | |
| 286 | impl Shard { |
| 287 | pub(crate) fn open(path: &Path) -> Result<Self, Qwen3MoeError> { |
| 288 | let io = |e: std::io::Error| Qwen3MoeError::Io(format!("{}: {e}", path.display())); |
| 289 | let file = File::open(path).map_err(io)?; |
| 290 | let file_len = file.metadata().map_err(io)?.len(); |
| 291 | let mut prefix = [0u8; 8]; |
| 292 | file.read_exact_at(&mut prefix, 0).map_err(io)?; |
| 293 | let header_len = u64::from_le_bytes(prefix); |
| 294 | if header_len > MAX_HEADER_BYTES || 8 + header_len > file_len { |
| 295 | return Err(Qwen3MoeError::Contract(format!( |
| 296 | "{}: header length {header_len} is invalid for a {file_len}-byte file", |
| 297 | path.display() |
| 298 | ))); |
| 299 | } |
| 300 | let mut header = vec![0u8; header_len as usize]; |
| 301 | file.read_exact_at(&mut header, 8).map_err(io)?; |
| 302 | let header: serde_json::Value = serde_json::from_slice(&header).map_err(|e| { |
| 303 | Qwen3MoeError::Contract(format!("{}: header JSON: {e}", path.display())) |
| 304 | })?; |
| 305 | let header = match header { |
| 306 | serde_json::Value::Object(map) => map, |
| 307 | _ => { |
| 308 | return Err(Qwen3MoeError::Contract(format!( |
| 309 | "{}: header is not a JSON object", |
| 310 | path.display() |
| 311 | ))) |
| 312 | } |
| 313 | }; |
| 314 | Ok(Self { |
| 315 | file, |
| 316 | payload_start: 8 + header_len, |
| 317 | file_len, |
| 318 | header, |
| 319 | }) |
| 320 | } |
| 321 | |
| 322 | /// The header's dtype of `name`, `None` when this shard does not hold it. |
| 323 | pub(crate) fn dtype(&self, name: &str) -> Option<&str> { |
| 324 | self.header.get(name)?.get("dtype")?.as_str() |
| 325 | } |
| 326 | |
| 327 | /// Reads one tensor into `dst` after checking dtype, shape and byte range. |
| 328 | pub(crate) fn read( |
| 329 | &self, |
| 330 | name: &str, |
| 331 | dtype: &str, |
| 332 | shape: &[usize], |
| 333 | dst: &mut [u8], |
| 334 | ) -> Result<(), Qwen3MoeError> { |
| 335 | let contract = |detail: String| Qwen3MoeError::Contract(format!("{name}: {detail}")); |
| 336 | let entry = self |
| 337 | .header |
| 338 | .get(name) |
| 339 | .ok_or_else(|| contract("missing from shard header".to_string()))?; |
| 340 | if entry.get("dtype").and_then(|v| v.as_str()) != Some(dtype) { |
| 341 | return Err(contract(format!( |
| 342 | "dtype {:?}, expected {dtype}", |
| 343 | entry.get("dtype") |
| 344 | ))); |
| 345 | } |
| 346 | let actual_shape: Option<Vec<usize>> = |
| 347 | entry.get("shape").and_then(|v| v.as_array()).map(|dims| { |
| 348 | dims.iter() |
| 349 | .filter_map(|d| d.as_u64().map(|d| d as usize)) |
| 350 | .collect() |
| 351 | }); |
| 352 | if actual_shape.as_deref() != Some(shape) { |
| 353 | return Err(contract(format!( |
| 354 | "shape {actual_shape:?}, expected {shape:?}" |
| 355 | ))); |
| 356 | } |
| 357 | let offsets: Vec<u64> = entry |
| 358 | .get("data_offsets") |
| 359 | .and_then(|v| v.as_array()) |
| 360 | .map(|o| o.iter().filter_map(|v| v.as_u64()).collect()) |
| 361 | .unwrap_or_default(); |
| 362 | let [start, end] = offsets[..] else { |
| 363 | return Err(contract("data_offsets must hold two integers".to_string())); |
| 364 | }; |
| 365 | if start > end |
| 366 | || end - start != dst.len() as u64 |
| 367 | || self.payload_start + end > self.file_len |
| 368 | { |
| 369 | return Err(contract(format!( |
| 370 | "byte range {start}..{end} does not hold {} bytes inside the shard", |
| 371 | dst.len() |
| 372 | ))); |
| 373 | } |
| 374 | self.file |
| 375 | .read_exact_at(dst, self.payload_start + start) |
| 376 | .map_err(|e| Qwen3MoeError::Io(format!("{name}: {e}"))) |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | /// Loads one official `Qwen3-Coder-30B-A3B-Instruct-FP8` expert layer into a capsule. |
| 381 | /// |
| 382 | /// Only the shards holding that layer are opened, and only the layer's tensors are |
| 383 | /// read. Expert weights stay FP8; nothing is decoded. |
| 384 | pub fn load_qwen3_fp8_moe_layer( |
| 385 | checkpoint_dir: &Path, |
| 386 | layer: usize, |
| 387 | ) -> Result<Qwen3MoeLayer, Qwen3MoeError> { |
| 388 | load_moe_layer( |
| 389 | checkpoint_dir, |
| 390 | layer, |
| 391 | QWEN3_A3B_HIDDEN, |
| 392 | QWEN3_A3B_INTERMEDIATE, |
| 393 | ) |
| 394 | } |
| 395 | |
| 396 | fn load_moe_layer( |
| 397 | checkpoint_dir: &Path, |
| 398 | layer: usize, |
| 399 | h: usize, |
| 400 | i: usize, |
| 401 | ) -> Result<Qwen3MoeLayer, Qwen3MoeError> { |
| 402 | if layer >= QWEN3_A3B_LAYERS { |
| 403 | return Err(Qwen3MoeError::Contract(format!( |
| 404 | "layer {layer} outside [0, {QWEN3_A3B_LAYERS})" |
| 405 | ))); |
| 406 | } |
| 407 | let index_path = checkpoint_dir.join("model.safetensors.index.json"); |
| 408 | let index: serde_json::Value = serde_json::from_slice( |
| 409 | &std::fs::read(&index_path) |
| 410 | .map_err(|e| Qwen3MoeError::Io(format!("{}: {e}", index_path.display())))?, |
| 411 | ) |
| 412 | .map_err(|e| Qwen3MoeError::Index(format!("{}: {e}", index_path.display())))?; |
| 413 | let weight_map = index |
| 414 | .get("weight_map") |
| 415 | .and_then(|v| v.as_object()) |
| 416 | .ok_or_else(|| Qwen3MoeError::Index("missing weight_map object".to_string()))?; |
| 417 | |
| 418 | let prefix = format!("model.layers.{layer}.mlp"); |
| 419 | let mut shards: HashMap<String, Shard> = HashMap::new(); |
| 420 | let mut read = |
| 421 | |name: &str, dtype: &str, shape: &[usize], dst: &mut [u8]| -> Result<(), Qwen3MoeError> { |
| 422 | let filename = weight_map |
| 423 | .get(name) |
| 424 | .and_then(|v| v.as_str()) |
| 425 | .ok_or_else(|| Qwen3MoeError::Index(format!("no shard for {name}")))?; |
| 426 | if !shards.contains_key(filename) { |
| 427 | let shard = Shard::open(&shard_path(checkpoint_dir, filename)?)?; |
| 428 | shards.insert(filename.to_string(), shard); |
| 429 | } |
| 430 | shards[filename].read(name, dtype, shape, dst) |
| 431 | }; |
| 432 | |
| 433 | Qwen3MoeLayer::build(h, i, |tensor, dst| match tensor { |
| 434 | ROUTER => read(&format!("{prefix}.gate.weight"), "BF16", &[EXPERTS, h], dst), |
| 435 | GATE_UP | GATE_UP_SCALE_INV => { |
| 436 | let scales = tensor == GATE_UP_SCALE_INV; |
| 437 | let per_expert = dst.len() / EXPERTS; |
| 438 | for (expert, chunk) in dst.chunks_exact_mut(per_expert).enumerate() { |
| 439 | let (gate, up) = chunk.split_at_mut(per_expert / 2); |
| 440 | for (projection, half) in [("gate_proj", gate), ("up_proj", up)] { |
| 441 | let base = format!("{prefix}.experts.{expert}.{projection}"); |
| 442 | if scales { |
| 443 | read( |
| 444 | &format!("{base}.weight_scale_inv"), |
| 445 | "BF16", |
| 446 | &[i / BLOCK, h / BLOCK], |
| 447 | half, |
| 448 | )?; |
| 449 | } else { |
| 450 | read(&format!("{base}.weight"), "F8_E4M3", &[i, h], half)?; |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | Ok(()) |
| 455 | } |
| 456 | _ => { |
| 457 | let scales = tensor == DOWN_SCALE_INV; |
| 458 | let per_expert = dst.len() / EXPERTS; |
| 459 | for (expert, chunk) in dst.chunks_exact_mut(per_expert).enumerate() { |
| 460 | let base = format!("{prefix}.experts.{expert}.down_proj"); |
| 461 | if scales { |
| 462 | read( |
| 463 | &format!("{base}.weight_scale_inv"), |
| 464 | "BF16", |
| 465 | &[h / BLOCK, i / BLOCK], |
| 466 | chunk, |
| 467 | )?; |
| 468 | } else { |
| 469 | read(&format!("{base}.weight"), "F8_E4M3", &[h, i], chunk)?; |
| 470 | } |
| 471 | } |
| 472 | Ok(()) |
| 473 | } |
| 474 | }) |
| 475 | } |
| 476 | |
| 477 | // --------------------------------------------------------------------------- |
| 478 | // Numeric helpers and the FP32 CPU oracle. |
| 479 | // --------------------------------------------------------------------------- |
| 480 | |
| 481 | pub fn bf16_to_f32(bits: u16) -> f32 { |
| 482 | f32::from_bits((bits as u32) << 16) |
| 483 | } |
| 484 | |
| 485 | /// Round-to-nearest-even FP32 to BF16. NaN stays NaN. |
| 486 | pub fn f32_to_bf16(value: f32) -> u16 { |
| 487 | let bits = value.to_bits(); |
| 488 | if value.is_nan() { |
| 489 | return ((bits >> 16) | 0x40) as u16; |
| 490 | } |
| 491 | let rounding = 0x7fff + ((bits >> 16) & 1); |
| 492 | ((bits + rounding) >> 16) as u16 |
| 493 | } |
| 494 | |
| 495 | /// E4M3FN decode: bias 7, no infinities, 0x7f/0xff are NaN. |
| 496 | pub fn fp8_e4m3fn_to_f32(bits: u8) -> f32 { |
| 497 | let sign = if bits & 0x80 != 0 { -1.0 } else { 1.0 }; |
| 498 | let exponent = ((bits >> 3) & 0x0f) as i32; |
| 499 | let mantissa = (bits & 0x07) as f32; |
| 500 | if exponent == 0x0f && bits & 0x07 == 0x07 { |
| 501 | return f32::NAN; |
| 502 | } |
| 503 | if exponent == 0 { |
| 504 | sign * mantissa * 2f32.powi(-9) |
| 505 | } else { |
| 506 | sign * (1.0 + mantissa / 8.0) * 2f32.powi(exponent - 7) |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | pub(crate) fn fp8_table() -> [f32; 256] { |
| 511 | std::array::from_fn(|bits| fp8_e4m3fn_to_f32(bits as u8)) |
| 512 | } |
| 513 | |
| 514 | /// Round-to-nearest-even FP32 to E4M3FN, saturating at +/-448. NaN maps to 0x7f. |
| 515 | pub fn f32_to_fp8_e4m3fn(value: f32) -> u8 { |
| 516 | if value.is_nan() { |
| 517 | return 0x7f; |
| 518 | } |
| 519 | let sign = if value.is_sign_negative() { 0x80u8 } else { 0 }; |
| 520 | let magnitude = value.abs(); |
| 521 | // Positive codes 0x00..=0x7e are monotonically increasing in value. |
| 522 | let (mut lo, mut hi) = (0u8, 0x7eu8); |
| 523 | if magnitude >= fp8_e4m3fn_to_f32(hi) { |
| 524 | return sign | hi; |
| 525 | } |
| 526 | while hi - lo > 1 { |
| 527 | let mid = lo + (hi - lo) / 2; |
| 528 | if fp8_e4m3fn_to_f32(mid) <= magnitude { |
| 529 | lo = mid; |
| 530 | } else { |
| 531 | hi = mid; |
| 532 | } |
| 533 | } |
| 534 | let (below, above) = (fp8_e4m3fn_to_f32(lo), fp8_e4m3fn_to_f32(hi)); |
| 535 | let code = match (magnitude - below).partial_cmp(&(above - magnitude)) { |
| 536 | Some(std::cmp::Ordering::Less) => lo, |
| 537 | Some(std::cmp::Ordering::Greater) => hi, |
| 538 | _ => { |
| 539 | if lo & 1 == 0 { |
| 540 | lo |
| 541 | } else { |
| 542 | hi |
| 543 | } |
| 544 | } |
| 545 | }; |
| 546 | sign | code |
| 547 | } |
| 548 | |
| 549 | /// How the oracle treats activations entering each expert GEMM. |
| 550 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 551 | pub enum OracleActivations { |
| 552 | /// Exact FP32 activations: measures the device's end-to-end numeric quality. |
| 553 | Fp32, |
| 554 | /// Quantize each row's 128-channel blocks to E4M3 exactly as the device does |
| 555 | /// (scale = max|v| / 448). Isolates indexing and accumulation from rounding. |
| 556 | Fp8Block128, |
| 557 | } |
| 558 | |
| 559 | fn quantize_block128_in_place(values: &mut [f32]) { |
| 560 | for block in values.chunks_mut(BLOCK) { |
| 561 | let maximum = block.iter().fold(0.0f32, |m, v| m.max(v.abs())); |
| 562 | let scale = if maximum > 0.0 { maximum / 448.0 } else { 1.0 }; |
| 563 | for v in block.iter_mut() { |
| 564 | *v = fp8_e4m3fn_to_f32(f32_to_fp8_e4m3fn(*v / scale)) * scale; |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// FP32 router logits [tokens, 128] from BF16-representable inputs. |
| 570 | pub fn reference_router_logits(layer: &Qwen3MoeLayer, x: &[f32], tokens: usize) -> Vec<f32> { |
| 571 | let h = layer.hidden; |
| 572 | let router: Vec<f32> = layer |
| 573 | .router_bf16() |
| 574 | .iter() |
| 575 | .map(|&b| bf16_to_f32(b)) |
| 576 | .collect(); |
| 577 | let mut logits = vec![0.0f32; tokens * EXPERTS]; |
| 578 | logits |
| 579 | .par_chunks_mut(EXPERTS) |
| 580 | .enumerate() |
| 581 | .for_each(|(t, row)| { |
| 582 | let xt = &x[t * h..(t + 1) * h]; |
| 583 | for (e, logit) in row.iter_mut().enumerate() { |
| 584 | *logit = xt |
| 585 | .iter() |
| 586 | .zip(&router[e * h..(e + 1) * h]) |
| 587 | .map(|(a, b)| a * b) |
| 588 | .sum(); |
| 589 | } |
| 590 | }); |
| 591 | logits |
| 592 | } |
| 593 | |
| 594 | /// out[r] = sum_k W[r, k] * v[k] with W an FP8 [rows, cols] matrix and 128x128 BF16 inverse scales. |
| 595 | pub(crate) fn dequant_matvec( |
| 596 | weights: &[u8], |
| 597 | scales: &[u16], |
| 598 | rows: usize, |
| 599 | cols: usize, |
| 600 | v: &[f32], |
| 601 | lut: &[f32; 256], |
| 602 | ) -> Vec<f32> { |
| 603 | let k_blocks = cols / BLOCK; |
| 604 | (0..rows) |
| 605 | .map(|r| { |
| 606 | let row = &weights[r * cols..(r + 1) * cols]; |
| 607 | (0..k_blocks) |
| 608 | .map(|b| { |
| 609 | let dot: f32 = row[b * BLOCK..(b + 1) * BLOCK] |
| 610 | .iter() |
| 611 | .zip(&v[b * BLOCK..(b + 1) * BLOCK]) |
| 612 | .map(|(&w, &x)| lut[w as usize] * x) |
| 613 | .sum(); |
| 614 | dot * bf16_to_f32(scales[(r / BLOCK) * k_blocks + b]) |
| 615 | }) |
| 616 | .sum() |
| 617 | }) |
| 618 | .collect() |
| 619 | } |
| 620 | |
| 621 | /// Independent FP32 layer output [tokens, H] for a routing plan. |
| 622 | /// |
| 623 | /// Weights are dequantized exactly from FP8; activations are not quantized, so the |
| 624 | /// difference to the device measures the device's activation quantization and |
| 625 | /// accumulation order. |
| 626 | pub fn reference_moe_forward(layer: &Qwen3MoeLayer, x: &[f32], plan: &MoeBatchPlan) -> Vec<f32> { |
| 627 | reference_moe_forward_with(layer, x, plan, OracleActivations::Fp32) |
| 628 | } |
| 629 | |
| 630 | pub fn reference_moe_forward_with( |
| 631 | layer: &Qwen3MoeLayer, |
| 632 | x: &[f32], |
| 633 | plan: &MoeBatchPlan, |
| 634 | activations: OracleActivations, |
| 635 | ) -> Vec<f32> { |
| 636 | let quantize = activations == OracleActivations::Fp8Block128; |
| 637 | let (h, i) = (layer.hidden, layer.intermediate); |
| 638 | let lut = fp8_table(); |
| 639 | let gate_up = layer.gate_up_fp8(); |
| 640 | let gate_up_scales = layer.gate_up_scale_inv_bf16(); |
| 641 | let down = layer.down_fp8(); |
| 642 | let down_scales = layer.down_scale_inv_bf16(); |
| 643 | let gu_scale_len = (2 * i / BLOCK) * (h / BLOCK); |
| 644 | let down_scale_len = (h / BLOCK) * (i / BLOCK); |
| 645 | let mut output = vec![0.0f32; plan.tokens * h]; |
| 646 | output.par_chunks_mut(h).enumerate().for_each(|(t, out)| { |
| 647 | let mut xt = x[t * h..(t + 1) * h].to_vec(); |
| 648 | if quantize { |
| 649 | quantize_block128_in_place(&mut xt); |
| 650 | } |
| 651 | for slot in 0..plan.top_k { |
| 652 | let assignment = t * plan.top_k + slot; |
| 653 | let e = plan.topk_experts[assignment] as usize; |
| 654 | let weight = plan.topk_weights[assignment]; |
| 655 | let projected = dequant_matvec( |
| 656 | &gate_up[e * 2 * i * h..(e + 1) * 2 * i * h], |
| 657 | &gate_up_scales[e * gu_scale_len..(e + 1) * gu_scale_len], |
| 658 | 2 * i, |
| 659 | h, |
| 660 | &xt, |
| 661 | &lut, |
| 662 | ); |
| 663 | let mut hidden: Vec<f32> = (0..i) |
| 664 | .map(|j| { |
| 665 | let gate = projected[j]; |
| 666 | gate / (1.0 + (-gate).exp()) * projected[i + j] |
| 667 | }) |
| 668 | .collect(); |
| 669 | if quantize { |
| 670 | quantize_block128_in_place(&mut hidden); |
| 671 | } |
| 672 | let expert_out = dequant_matvec( |
| 673 | &down[e * h * i..(e + 1) * h * i], |
| 674 | &down_scales[e * down_scale_len..(e + 1) * down_scale_len], |
| 675 | h, |
| 676 | i, |
| 677 | &hidden, |
| 678 | &lut, |
| 679 | ); |
| 680 | for (o, v) in out.iter_mut().zip(expert_out) { |
| 681 | *o += weight * v; |
| 682 | } |
| 683 | } |
| 684 | }); |
| 685 | output |
| 686 | } |
| 687 | |
| 688 | /// Agreement between a device output and the oracle. |
| 689 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 690 | pub struct ParityStats { |
| 691 | pub cosine: f64, |
| 692 | pub max_abs: f32, |
| 693 | /// 95th percentile of |a - e| / max(|e|, 0.05). |
| 694 | pub p95_rel: f32, |
| 695 | pub max_abs_expected: f32, |
| 696 | pub non_finite: usize, |
| 697 | } |
| 698 | |
| 699 | pub fn parity_stats(actual: &[f32], expected: &[f32]) -> ParityStats { |
| 700 | assert_eq!(actual.len(), expected.len()); |
| 701 | let (mut dot, mut na, mut ne) = (0.0f64, 0.0f64, 0.0f64); |
| 702 | let mut max_abs = 0.0f32; |
| 703 | let mut max_abs_expected = 0.0f32; |
| 704 | let mut non_finite = 0; |
| 705 | let mut relative = Vec::with_capacity(actual.len()); |
| 706 | for (&a, &e) in actual.iter().zip(expected) { |
| 707 | if !a.is_finite() { |
| 708 | non_finite += 1; |
| 709 | continue; |
| 710 | } |
| 711 | dot += a as f64 * e as f64; |
| 712 | na += a as f64 * a as f64; |
| 713 | ne += e as f64 * e as f64; |
| 714 | let diff = (a - e).abs(); |
| 715 | max_abs = max_abs.max(diff); |
| 716 | max_abs_expected = max_abs_expected.max(e.abs()); |
| 717 | relative.push(diff / e.abs().max(0.05)); |
| 718 | } |
| 719 | relative.sort_by(f32::total_cmp); |
| 720 | let p95_rel = relative |
| 721 | .get((relative.len().saturating_sub(1) * 95).div_ceil(100)) |
| 722 | .copied() |
| 723 | .unwrap_or(f32::NAN); |
| 724 | ParityStats { |
| 725 | cosine: dot / (na.sqrt() * ne.sqrt()), |
| 726 | max_abs, |
| 727 | p95_rel, |
| 728 | max_abs_expected, |
| 729 | non_finite, |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | #[cfg(test)] |
| 734 | mod tests { |
| 735 | use super::*; |
| 736 | |
| 737 | #[test] |
| 738 | fn fp8_e4m3fn_decodes_known_values() { |
| 739 | assert_eq!(fp8_e4m3fn_to_f32(0x38), 1.0); |
| 740 | assert_eq!(fp8_e4m3fn_to_f32(0x30), 0.5); |
| 741 | assert_eq!(fp8_e4m3fn_to_f32(0xc0), -2.0); |
| 742 | assert_eq!(fp8_e4m3fn_to_f32(0x7e), 448.0); |
| 743 | assert_eq!(fp8_e4m3fn_to_f32(0x01), 2f32.powi(-9)); |
| 744 | assert!(fp8_e4m3fn_to_f32(0x7f).is_nan()); |
| 745 | assert!(fp8_e4m3fn_to_f32(0xff).is_nan()); |
| 746 | } |
| 747 | |
| 748 | #[test] |
| 749 | fn fp8_encode_rounds_to_nearest_even_and_saturates() { |
| 750 | for bits in 0u8..=0x7e { |
| 751 | for code in [bits, bits | 0x80] { |
| 752 | assert_eq!( |
| 753 | f32_to_fp8_e4m3fn(fp8_e4m3fn_to_f32(code)), |
| 754 | code, |
| 755 | "exact {code:#x}" |
| 756 | ); |
| 757 | } |
| 758 | } |
| 759 | // 1.0625 lies halfway between 1.0 (0x38, even) and 1.125 (0x39). |
| 760 | assert_eq!(f32_to_fp8_e4m3fn(1.0625), 0x38); |
| 761 | // 1.1875 lies halfway between 1.125 (0x39) and 1.25 (0x3a, even). |
| 762 | assert_eq!(f32_to_fp8_e4m3fn(1.1875), 0x3a); |
| 763 | assert_eq!(f32_to_fp8_e4m3fn(1.07), 0x39); |
| 764 | assert_eq!(f32_to_fp8_e4m3fn(1000.0), 0x7e); |
| 765 | assert_eq!(f32_to_fp8_e4m3fn(-1000.0), 0xfe); |
| 766 | assert_eq!(f32_to_fp8_e4m3fn(-0.0), 0x80); |
| 767 | } |
| 768 | |
| 769 | #[test] |
| 770 | fn bf16_rounds_to_nearest_even() { |
| 771 | assert_eq!(f32_to_bf16(1.0), 0x3f80); |
| 772 | assert_eq!(bf16_to_f32(f32_to_bf16(1.0 + 1.0 / 256.0)), 1.0); |
| 773 | assert_eq!( |
| 774 | bf16_to_f32(f32_to_bf16(1.0 + 3.0 / 256.0)), |
| 775 | 1.0 + 4.0 / 256.0 |
| 776 | ); |
| 777 | assert!(bf16_to_f32(f32_to_bf16(f32::NAN)).is_nan()); |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn shard_names_cannot_escape_the_checkpoint_directory() { |
| 782 | let dir = Path::new("/ckpt"); |
| 783 | assert_eq!( |
| 784 | shard_path(dir, "model-00001-of-00004.safetensors").unwrap(), |
| 785 | PathBuf::from("/ckpt/model-00001-of-00004.safetensors") |
| 786 | ); |
| 787 | for bad in [ |
| 788 | "../secret", |
| 789 | "/etc/passwd", |
| 790 | "sub/model.safetensors", |
| 791 | "..", |
| 792 | ".", |
| 793 | "", |
| 794 | "./x", |
| 795 | ] { |
| 796 | assert!(shard_path(dir, bad).is_err(), "{bad:?} must be rejected"); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | #[test] |
| 801 | fn capsule_views_round_trip_and_digest_covers_payload() { |
| 802 | let (h, i) = (128, 128); |
| 803 | let router: Vec<u16> = (0..EXPERTS * h).map(|v| v as u16).collect(); |
| 804 | let gate_up = vec![0x38u8; EXPERTS * 2 * i * h]; |
| 805 | let gate_up_scales = vec![0x3f80u16; EXPERTS * 2]; |
| 806 | let down = vec![0x30u8; EXPERTS * h * i]; |
| 807 | let down_scales = vec![0x4000u16; EXPERTS]; |
| 808 | let layer = Qwen3MoeLayer::from_parts( |
| 809 | h, |
| 810 | i, |
| 811 | &router, |
| 812 | &gate_up, |
| 813 | &gate_up_scales, |
| 814 | &down, |
| 815 | &down_scales, |
| 816 | ) |
| 817 | .unwrap(); |
| 818 | assert_eq!(layer.router_bf16(), &router[..]); |
| 819 | assert_eq!(layer.gate_up_fp8(), &gate_up[..]); |
| 820 | assert_eq!(layer.gate_up_scale_inv_bf16(), &gate_up_scales[..]); |
| 821 | assert_eq!(layer.down_fp8(), &down[..]); |
| 822 | assert_eq!(layer.down_scale_inv_bf16(), &down_scales[..]); |
| 823 | assert_eq!( |
| 824 | layer.capsule.tensor(GATE_UP).unwrap().dtype, |
| 825 | WeightDType::Fp8E4M3Fn |
| 826 | ); |
| 827 | assert!(layer.capsule.tensor(GATE_UP).unwrap().quant.is_some()); |
| 828 | |
| 829 | let mut changed_down = down.clone(); |
| 830 | changed_down[7] = 0x38; |
| 831 | let changed = Qwen3MoeLayer::from_parts( |
| 832 | h, |
| 833 | i, |
| 834 | &router, |
| 835 | &gate_up, |
| 836 | &gate_up_scales, |
| 837 | &changed_down, |
| 838 | &down_scales, |
| 839 | ) |
| 840 | .unwrap(); |
| 841 | assert_ne!(layer.capsule.capsule_digest, changed.capsule.capsule_digest); |
| 842 | |
| 843 | assert!(Qwen3MoeLayer::from_parts( |
| 844 | h, |
| 845 | i, |
| 846 | &router, |
| 847 | &gate_up, |
| 848 | &gate_up_scales, |
| 849 | &down[1..], |
| 850 | &down_scales |
| 851 | ) |
| 852 | .is_err()); |
| 853 | assert!(Qwen3MoeLayer::from_parts( |
| 854 | 100, |
| 855 | i, |
| 856 | &router, |
| 857 | &gate_up, |
| 858 | &gate_up_scales, |
| 859 | &down, |
| 860 | &down_scales |
| 861 | ) |
| 862 | .is_err()); |
| 863 | } |
| 864 | |
| 865 | #[test] |
| 866 | fn loader_reads_one_layer_from_a_sharded_checkpoint_and_rejects_bad_contracts() { |
| 867 | let dir = std::env::temp_dir().join(format!("aien-qwen3-loader-{}", std::process::id())); |
| 868 | std::fs::create_dir_all(&dir).unwrap(); |
| 869 | let (h, i) = (256, 128); |
| 870 | let prefix = "model.layers.3.mlp"; |
| 871 | // Two shards: router and experts 0..63 in the first, the rest in the second. |
| 872 | // (name, dtype, shape, payload) per shard. |
| 873 | type ShardTensors<'a> = Vec<(String, &'a str, Vec<usize>, Vec<u8>)>; |
| 874 | let mut shard_tensors: [ShardTensors; 2] = [Vec::new(), Vec::new()]; |
| 875 | shard_tensors[0].push(( |
| 876 | format!("{prefix}.gate.weight"), |
| 877 | "BF16", |
| 878 | vec![EXPERTS, h], |
| 879 | vec![0x11; EXPERTS * h * 2], |
| 880 | )); |
| 881 | for expert in 0..EXPERTS { |
| 882 | let shard = usize::from(expert >= 64); |
| 883 | let base = format!("{prefix}.experts.{expert}"); |
| 884 | let tag = expert as u8; |
| 885 | shard_tensors[shard].push(( |
| 886 | format!("{base}.gate_proj.weight"), |
| 887 | "F8_E4M3", |
| 888 | vec![i, h], |
| 889 | vec![tag; i * h], |
| 890 | )); |
| 891 | shard_tensors[shard].push(( |
| 892 | format!("{base}.up_proj.weight"), |
| 893 | "F8_E4M3", |
| 894 | vec![i, h], |
| 895 | vec![tag ^ 0x80; i * h], |
| 896 | )); |
| 897 | shard_tensors[shard].push(( |
| 898 | format!("{base}.down_proj.weight"), |
| 899 | "F8_E4M3", |
| 900 | vec![h, i], |
| 901 | vec![tag ^ 0x40; h * i], |
| 902 | )); |
| 903 | for projection in ["gate_proj", "up_proj"] { |
| 904 | shard_tensors[shard].push(( |
| 905 | format!("{base}.{projection}.weight_scale_inv"), |
| 906 | "BF16", |
| 907 | vec![i / BLOCK, h / BLOCK], |
| 908 | vec![tag; (i / BLOCK) * (h / BLOCK) * 2], |
| 909 | )); |
| 910 | } |
| 911 | shard_tensors[shard].push(( |
| 912 | format!("{base}.down_proj.weight_scale_inv"), |
| 913 | "BF16", |
| 914 | vec![h / BLOCK, i / BLOCK], |
| 915 | vec![tag; (h / BLOCK) * (i / BLOCK) * 2], |
| 916 | )); |
| 917 | } |
| 918 | let mut weight_map = serde_json::Map::new(); |
| 919 | for (index, tensors) in shard_tensors.iter().enumerate() { |
| 920 | let filename = format!("shard-{index}.safetensors"); |
| 921 | let mut header = serde_json::Map::new(); |
| 922 | let mut payload = Vec::new(); |
| 923 | for (name, dtype, shape, bytes) in tensors { |
| 924 | header.insert(name.clone(), serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [payload.len(), payload.len() + bytes.len()]})); |
| 925 | payload.extend_from_slice(bytes); |
| 926 | weight_map.insert(name.clone(), serde_json::json!(filename)); |
| 927 | } |
| 928 | let header = serde_json::to_vec(&header).unwrap(); |
| 929 | let mut file = (header.len() as u64).to_le_bytes().to_vec(); |
| 930 | file.extend_from_slice(&header); |
| 931 | file.extend_from_slice(&payload); |
| 932 | std::fs::write(dir.join(&filename), file).unwrap(); |
| 933 | } |
| 934 | let write_index = |map: &serde_json::Map<String, serde_json::Value>| { |
| 935 | std::fs::write( |
| 936 | dir.join("model.safetensors.index.json"), |
| 937 | serde_json::to_vec(&serde_json::json!({"weight_map": map})).unwrap(), |
| 938 | ) |
| 939 | .unwrap(); |
| 940 | }; |
| 941 | write_index(&weight_map); |
| 942 | |
| 943 | let layer = load_moe_layer(&dir, 3, h, i).unwrap(); |
| 944 | let per_expert = 2 * i * h; |
| 945 | for expert in [0usize, 63, 64, 127] { |
| 946 | let tag = expert as u8; |
| 947 | assert_eq!(layer.gate_up_fp8()[expert * per_expert], tag); |
| 948 | assert_eq!(layer.gate_up_fp8()[expert * per_expert + i * h], tag ^ 0x80); |
| 949 | assert_eq!(layer.down_fp8()[expert * h * i], tag ^ 0x40); |
| 950 | } |
| 951 | assert!(layer.router_bf16().iter().all(|&v| v == 0x1111)); |
| 952 | assert!( |
| 953 | load_moe_layer(&dir, 4, h, i).is_err(), |
| 954 | "layer 4 is not in the checkpoint" |
| 955 | ); |
| 956 | assert!(load_qwen3_fp8_moe_layer(&dir, QWEN3_A3B_LAYERS).is_err()); |
| 957 | |
| 958 | let mut escaping = weight_map.clone(); |
| 959 | escaping.insert( |
| 960 | format!("{prefix}.gate.weight"), |
| 961 | serde_json::json!("../shard-0.safetensors"), |
| 962 | ); |
| 963 | write_index(&escaping); |
| 964 | assert!(matches!( |
| 965 | load_moe_layer(&dir, 3, h, i), |
| 966 | Err(Qwen3MoeError::Index(_)) |
| 967 | )); |
| 968 | |
| 969 | let mut wrong_shard = weight_map.clone(); |
| 970 | wrong_shard.insert( |
| 971 | format!("{prefix}.experts.5.down_proj.weight"), |
| 972 | serde_json::json!("shard-1.safetensors"), |
| 973 | ); |
| 974 | write_index(&wrong_shard); |
| 975 | assert!(matches!( |
| 976 | load_moe_layer(&dir, 3, h, i), |
| 977 | Err(Qwen3MoeError::Contract(_)) |
| 978 | )); |
| 979 | std::fs::remove_dir_all(&dir).unwrap(); |
| 980 | } |
| 981 | |
| 982 | #[test] |
| 983 | fn oracle_matches_hand_computed_identity_expert() { |
| 984 | let (h, i) = (128, 128); |
| 985 | let mut gate_up = vec![0u8; EXPERTS * 2 * i * h]; |
| 986 | let mut down = vec![0u8; EXPERTS * h * i]; |
| 987 | for e in 0..EXPERTS { |
| 988 | for c in 0..128 { |
| 989 | gate_up[e * 2 * i * h + c * h + c] = 0x38; |
| 990 | gate_up[e * 2 * i * h + (i + c) * h + c] = 0x40; // 2.0 |
| 991 | down[e * h * i + c * i + c] = 0x38; |
| 992 | } |
| 993 | } |
| 994 | let layer = Qwen3MoeLayer::from_parts( |
| 995 | h, |
| 996 | i, |
| 997 | &vec![0u16; EXPERTS * h], |
| 998 | &gate_up, |
| 999 | &vec![0x3f80; EXPERTS * 2], |
| 1000 | &down, |
| 1001 | &vec![0x3f80; EXPERTS], |
| 1002 | ) |
| 1003 | .unwrap(); |
| 1004 | let x = vec![1.0f32; h]; |
| 1005 | let plan = |
| 1006 | MoeBatchPlan::qwen3_coder_a3b(&reference_router_logits(&layer, &x, 1), 1).unwrap(); |
| 1007 | let out = reference_moe_forward(&layer, &x, &plan); |
| 1008 | let expected = 2.0 / (1.0 + (-1.0f32).exp()); |
| 1009 | assert!( |
| 1010 | out.iter().all(|v| (v - expected).abs() < 1e-5), |
| 1011 | "{:?}", |
| 1012 | &out[..4] |
| 1013 | ); |
| 1014 | } |
| 1015 | } |