interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-inference-abi / src / qwen3_coder.rs

504 lines · 17626 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//! Native end-to-end Qwen3-Coder-30B-A3B inference in Rust, no MAX graph, no Python.
17//!
18//! Loads the official FP8 checkpoint (`Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8`)
19//! through the same validated shard reader as the MoE path, decodes weights to
20//! FP32 once at load, and runs the full 48-layer forward on CPU: embedding,
21//! per-layer GQA attention with QK norms and RoPE, the native MoE experts via
22//! [`crate::qwen3_moe`], final norm, LM head, and sampling. Every GPU kernel in
23//! Phase B plugs into this exact structure, so numerics stay comparable.
24
25use std::collections::HashMap;
26use std::path::{Path, PathBuf};
27
28use rayon::prelude::*;
29
30use crate::moe_plan::MoeBatchPlan;
31use crate::qwen3_moe::{
32 bf16_to_f32, fp8_table, load_qwen3_fp8_moe_layer, reference_moe_forward,
33 reference_router_logits, shard_path, Qwen3MoeError, Qwen3MoeLayer, Shard, FP8_BLOCK,
34 QWEN3_A3B_HIDDEN, QWEN3_A3B_LAYERS,
35};
36use crate::tensor::{apply_rope, rmsnorm, sample_argmax, scaled_dot_product_attention_single};
37
38pub const QWEN3_CODER_LAYERS: usize = QWEN3_A3B_LAYERS;
39pub const QWEN3_CODER_HIDDEN: usize = QWEN3_A3B_HIDDEN;
40pub const QWEN3_CODER_Q_HEADS: usize = 32;
41pub const QWEN3_CODER_KV_HEADS: usize = 4;
42pub const QWEN3_CODER_HEAD_DIM: usize = 128;
43pub const QWEN3_CODER_Q_DIM: usize = QWEN3_CODER_Q_HEADS * QWEN3_CODER_HEAD_DIM;
44pub const QWEN3_CODER_KV_DIM: usize = QWEN3_CODER_KV_HEADS * QWEN3_CODER_HEAD_DIM;
45pub const QWEN3_CODER_VOCAB: usize = 151936;
46pub const QWEN3_CODER_RMS_EPS: f32 = 1e-6;
47pub const QWEN3_CODER_ROPE_THETA: f32 = 10_000_000.0;
48
49#[derive(Debug)]
50pub enum Qwen3CoderError {
51 Io(String),
52 Index(String),
53 Contract(String),
54}
55
56impl std::fmt::Display for Qwen3CoderError {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 match self {
59 Self::Io(d) => write!(f, "io: {d}"),
60 Self::Index(d) => write!(f, "index: {d}"),
61 Self::Contract(d) => write!(f, "contract: {d}"),
62 }
63 }
64}
65
66impl std::error::Error for Qwen3CoderError {}
67
68impl From<Qwen3MoeError> for Qwen3CoderError {
69 fn from(e: Qwen3MoeError) -> Self {
70 Self::Contract(format!("moe layer: {e}"))
71 }
72}
73
74/// One layer's attention weights decoded to FP32 row-major at load.
75#[derive(Debug, Clone)]
76pub struct Qwen3CoderAttention {
77 pub q_proj: Vec<f32>,
78 pub k_proj: Vec<f32>,
79 pub v_proj: Vec<f32>,
80 pub o_proj: Vec<f32>,
81 pub q_norm: Vec<f32>,
82 pub k_norm: Vec<f32>,
83 pub input_norm: Vec<f32>,
84 pub post_norm: Vec<f32>,
85}
86
87/// Full Qwen3-Coder-30B-A3B weights. MoE experts stay in their validated
88/// capsule form; everything else is FP32 decoded once at load.
89pub struct Qwen3CoderWeights {
90 pub embed: Vec<f32>,
91 pub attns: Vec<Qwen3CoderAttention>,
92 pub moes: Vec<Qwen3MoeLayer>,
93 pub final_norm: Vec<f32>,
94 pub lm_head: Vec<f32>,
95}
96
97/// Per-layer KV cache: one (k, v) pair per decoded position.
98#[derive(Debug, Default)]
99pub struct Qwen3CoderLayerKv {
100 pub keys: Vec<Vec<f32>>,
101 pub values: Vec<Vec<f32>>,
102}
103
104#[derive(Debug, Default)]
105pub struct Qwen3CoderState {
106 pub layers: Vec<Qwen3CoderLayerKv>,
107}
108
109impl Qwen3CoderState {
110 pub fn new() -> Self {
111 Self {
112 layers: (0..QWEN3_CODER_LAYERS)
113 .map(|_| Qwen3CoderLayerKv::default())
114 .collect(),
115 }
116 }
117}
118
119/// Parallel FP32 vector-matrix multiply, f32 accumulation for speed on the
120/// wide projections (Q, O, LM head). Narrow norms stay on `tensor::matmul_vec`.
121fn matvec_f32_parallel(x: &[f32], w: &[f32], out: &mut [f32], in_dim: usize, out_dim: usize) {
122 debug_assert_eq!(x.len(), in_dim);
123 debug_assert_eq!(w.len(), in_dim * out_dim);
124 debug_assert_eq!(out.len(), out_dim);
125 out.par_chunks_exact_mut(1)
126 .enumerate()
127 .for_each(|(j, slot)| {
128 let row = &w[j * in_dim..(j + 1) * in_dim];
129 let mut sum = 0.0f32;
130 for i in 0..in_dim {
131 sum += x[i] * row[i];
132 }
133 slot[0] = sum;
134 });
135}
136
137/// Decodes one FP8 block-128 matrix with BF16 inverse scales to FP32 row-major.
138fn decode_fp8_block128(weights: &[u8], scales_inv: &[u16], rows: usize, cols: usize) -> Vec<f32> {
139 let lut = fp8_table();
140 let k_blocks = cols / FP8_BLOCK;
141 assert_eq!(cols % FP8_BLOCK, 0, "cols must split into 128-wide blocks");
142 assert_eq!(
143 scales_inv.len(),
144 rows.div_ceil(FP8_BLOCK) * k_blocks,
145 "scale grid must match 128x128 blocks"
146 );
147 let mut out = vec![0.0f32; rows * cols];
148 out.par_chunks_mut(cols)
149 .enumerate()
150 .for_each(|(r, row_out)| {
151 let row = &weights[r * cols..(r + 1) * cols];
152 for b in 0..k_blocks {
153 let scale = bf16_to_f32(scales_inv[(r / FP8_BLOCK) * k_blocks + b]);
154 let dst = &mut row_out[b * FP8_BLOCK..(b + 1) * FP8_BLOCK];
155 let src = &row[b * FP8_BLOCK..(b + 1) * FP8_BLOCK];
156 for (d, &w) in dst.iter_mut().zip(src.iter()) {
157 *d = lut[w as usize] * scale;
158 }
159 }
160 });
161 out
162}
163
164/// Reinterprets a BF16 payload as u16 words. Panics on odd length or
165/// misalignment rather than silently dropping bytes and shifting every word.
166pub(crate) fn bf16_words(bytes: &[u8]) -> &[u16] {
167 assert_eq!(bytes.len() % 2, 0, "bf16 payload must be even length");
168 // SAFETY: u16 has no invalid bit patterns; prefix/suffix are checked empty.
169 let (prefix, words, suffix) = unsafe { bytes.align_to::<u16>() };
170 assert!(
171 prefix.is_empty() && suffix.is_empty(),
172 "bf16 payload misaligned"
173 );
174 words
175}
176
177fn decode_bf16(bytes: &[u8]) -> Vec<f32> {
178 bf16_words(bytes).iter().map(|&b| bf16_to_f32(b)).collect()
179}
180
181pub(crate) struct CoderShardCache {
182 checkpoint_dir: PathBuf,
183 weight_map: serde_json::Map<String, serde_json::Value>,
184 shards: HashMap<String, Shard>,
185}
186
187impl CoderShardCache {
188 pub(crate) fn open(checkpoint_dir: &Path) -> Result<Self, Qwen3CoderError> {
189 let index_path = checkpoint_dir.join("model.safetensors.index.json");
190 let index: serde_json::Value = serde_json::from_slice(
191 &std::fs::read(&index_path)
192 .map_err(|e| Qwen3CoderError::Io(format!("{}: {e}", index_path.display())))?,
193 )
194 .map_err(|e| Qwen3CoderError::Index(format!("{}: {e}", index_path.display())))?;
195 let weight_map = index
196 .get("weight_map")
197 .and_then(|v| v.as_object())
198 .cloned()
199 .ok_or_else(|| Qwen3CoderError::Index("missing weight_map object".to_string()))?;
200 Ok(Self {
201 checkpoint_dir: checkpoint_dir.to_path_buf(),
202 weight_map,
203 shards: HashMap::new(),
204 })
205 }
206
207 pub(crate) fn read_raw(
208 &mut self,
209 name: &str,
210 dtype: &str,
211 shape: &[usize],
212 elem_bytes: usize,
213 ) -> Result<Vec<u8>, Qwen3CoderError> {
214 let filename = self
215 .weight_map
216 .get(name)
217 .and_then(|v| v.as_str())
218 .ok_or_else(|| Qwen3CoderError::Index(format!("no shard for {name}")))?;
219 if !self.shards.contains_key(filename) {
220 let shard = Shard::open(&shard_path(&self.checkpoint_dir, filename)?)
221 .map_err(|e| Qwen3CoderError::Contract(format!("shard open: {e}")))?;
222 self.shards.insert(filename.to_string(), shard);
223 }
224 let expect_elems: usize = shape.iter().product();
225 let mut dst = vec![0u8; expect_elems * elem_bytes];
226 self.shards[filename]
227 .read(name, dtype, shape, &mut dst)
228 .map_err(|e| Qwen3CoderError::Contract(format!("shard read: {e}")))?;
229 Ok(dst)
230 }
231
232 fn read_bf16_f32(&mut self, name: &str, shape: &[usize]) -> Result<Vec<f32>, Qwen3CoderError> {
233 Ok(decode_bf16(&self.read_raw(name, "BF16", shape, 2)?))
234 }
235
236 fn read_fp8_f32(
237 &mut self,
238 name: &str,
239 rows: usize,
240 cols: usize,
241 ) -> Result<Vec<f32>, Qwen3CoderError> {
242 let scale_name = format!("{name}_scale_inv");
243 let weights = self.read_raw(name, "F8_E4M3", &[rows, cols], 1)?;
244 let scales = self.read_raw(
245 &scale_name,
246 "BF16",
247 &[rows / FP8_BLOCK, cols / FP8_BLOCK],
248 2,
249 )?;
250 Ok(decode_fp8_block128(
251 &weights,
252 bf16_words(&scales),
253 rows,
254 cols,
255 ))
256 }
257}
258
259/// Loads all 48 layers plus embeddings, final norm, and LM head.
260pub fn load_qwen3_coder(checkpoint_dir: &Path) -> Result<Qwen3CoderWeights, Qwen3CoderError> {
261 let h = QWEN3_CODER_HIDDEN;
262 let qd = QWEN3_CODER_Q_DIM;
263 let kvd = QWEN3_CODER_KV_DIM;
264 let hd = QWEN3_CODER_HEAD_DIM;
265 let mut cache = CoderShardCache::open(checkpoint_dir)?;
266
267 let embed = cache.read_bf16_f32("model.embed_tokens.weight", &[QWEN3_CODER_VOCAB, h])?;
268 let final_norm = cache.read_bf16_f32("model.norm.weight", &[h])?;
269 let lm_head = cache.read_bf16_f32("lm_head.weight", &[QWEN3_CODER_VOCAB, h])?;
270
271 let mut attns = Vec::with_capacity(QWEN3_CODER_LAYERS);
272 let mut moes = Vec::with_capacity(QWEN3_CODER_LAYERS);
273 for layer in 0..QWEN3_CODER_LAYERS {
274 let p = format!("model.layers.{layer}");
275 let q_proj = cache.read_fp8_f32(&format!("{p}.self_attn.q_proj.weight"), qd, h)?;
276 let k_proj = cache.read_fp8_f32(&format!("{p}.self_attn.k_proj.weight"), kvd, h)?;
277 let v_proj = cache.read_fp8_f32(&format!("{p}.self_attn.v_proj.weight"), kvd, h)?;
278 let o_proj = cache.read_fp8_f32(&format!("{p}.self_attn.o_proj.weight"), h, qd)?;
279 let q_norm = cache.read_bf16_f32(&format!("{p}.self_attn.q_norm.weight"), &[hd])?;
280 let k_norm = cache.read_bf16_f32(&format!("{p}.self_attn.k_norm.weight"), &[hd])?;
281 let input_norm = cache.read_bf16_f32(&format!("{p}.input_layernorm.weight"), &[h])?;
282 let post_norm =
283 cache.read_bf16_f32(&format!("{p}.post_attention_layernorm.weight"), &[h])?;
284 attns.push(Qwen3CoderAttention {
285 q_proj,
286 k_proj,
287 v_proj,
288 o_proj,
289 q_norm,
290 k_norm,
291 input_norm,
292 post_norm,
293 });
294 moes.push(load_qwen3_fp8_moe_layer(checkpoint_dir, layer)?);
295 }
296
297 Ok(Qwen3CoderWeights {
298 embed,
299 attns,
300 moes,
301 final_norm,
302 lm_head,
303 })
304}
305
306pub(crate) fn rmsnorm_per_head(
307 x: &[f32],
308 weight: &[f32],
309 eps: f32,
310 num_heads: usize,
311 head_dim: usize,
312 out: &mut [f32],
313) {
314 for h in 0..num_heads {
315 rmsnorm(
316 &x[h * head_dim..(h + 1) * head_dim],
317 weight,
318 eps,
319 &mut out[h * head_dim..(h + 1) * head_dim],
320 );
321 }
322}
323
324/// Runs one token through all 48 layers on the CPU (bit-exact reference: attention, norms,
325/// RoPE and the routed experts). Returns the final hidden state.
326pub fn forward_token(
327 weights: &Qwen3CoderWeights,
328 token_id: u32,
329 pos: usize,
330 state: &mut Qwen3CoderState,
331) -> Vec<f32> {
332 let h = QWEN3_CODER_HIDDEN;
333 let qd = QWEN3_CODER_Q_DIM;
334 let kvd = QWEN3_CODER_KV_DIM;
335 let hd = QWEN3_CODER_HEAD_DIM;
336 let eps = QWEN3_CODER_RMS_EPS;
337
338 let token_idx = (token_id as usize) % QWEN3_CODER_VOCAB;
339 let mut x = weights.embed[token_idx * h..(token_idx + 1) * h].to_vec();
340
341 for (layer_idx, (attn, moe)) in weights.attns.iter().zip(weights.moes.iter()).enumerate() {
342 let kv = &mut state.layers[layer_idx];
343
344 let mut x_norm = vec![0.0f32; h];
345 rmsnorm(&x, &attn.input_norm, eps, &mut x_norm);
346
347 let mut q = vec![0.0f32; qd];
348 let mut k = vec![0.0f32; kvd];
349 let mut v = vec![0.0f32; kvd];
350 matvec_f32_parallel(&x_norm, &attn.q_proj, &mut q, h, qd);
351 matvec_f32_parallel(&x_norm, &attn.k_proj, &mut k, h, kvd);
352 matvec_f32_parallel(&x_norm, &attn.v_proj, &mut v, h, kvd);
353
354 let mut qn = vec![0.0f32; qd];
355 let mut kn = vec![0.0f32; kvd];
356 rmsnorm_per_head(&q, &attn.q_norm, eps, QWEN3_CODER_Q_HEADS, hd, &mut qn);
357 rmsnorm_per_head(&k, &attn.k_norm, eps, QWEN3_CODER_KV_HEADS, hd, &mut kn);
358
359 apply_rope(
360 &mut qn,
361 &mut kn,
362 pos,
363 QWEN3_CODER_Q_HEADS,
364 QWEN3_CODER_KV_HEADS,
365 hd,
366 QWEN3_CODER_ROPE_THETA,
367 );
368
369 kv.keys.push(kn);
370 kv.values.push(v);
371
372 let mut attn_out = vec![0.0f32; qd];
373 scaled_dot_product_attention_single(
374 &qn,
375 &kv.keys,
376 &kv.values,
377 QWEN3_CODER_Q_HEADS,
378 QWEN3_CODER_KV_HEADS,
379 hd,
380 &mut attn_out,
381 );
382
383 let mut attn_proj = vec![0.0f32; h];
384 matvec_f32_parallel(&attn_out, &attn.o_proj, &mut attn_proj, qd, h);
385 for i in 0..h {
386 x[i] += attn_proj[i];
387 }
388
389 let mut post = vec![0.0f32; h];
390 rmsnorm(&x, &attn.post_norm, eps, &mut post);
391
392 let router = reference_router_logits(moe, &post, 1);
393 let plan = MoeBatchPlan::qwen3_coder_a3b(&router, 1).expect("routing plan must build");
394 let moe_out = reference_moe_forward(moe, &post, &plan);
395 for i in 0..h {
396 x[i] += moe_out[i];
397 }
398 }
399
400 let mut x_final = vec![0.0f32; h];
401 rmsnorm(&x, &weights.final_norm, eps, &mut x_final);
402 x_final
403}
404
405/// Projects a hidden state to vocabulary logits.
406pub fn compute_logits(weights: &Qwen3CoderWeights, hidden: &[f32]) -> Vec<f32> {
407 let h = QWEN3_CODER_HIDDEN;
408 let mut logits = vec![0.0f32; QWEN3_CODER_VOCAB];
409 matvec_f32_parallel(hidden, &weights.lm_head, &mut logits, h, QWEN3_CODER_VOCAB);
410 logits
411}
412
413/// Prefills prompt tokens, then greedily decodes up to `max_new` tokens,
414/// stopping at any id in `stop_ids`. Returns only the new tokens.
415pub fn generate_greedy(
416 weights: &Qwen3CoderWeights,
417 prompt: &[u32],
418 max_new: usize,
419 stop_ids: &[u32],
420) -> Vec<u32> {
421 let mut state = Qwen3CoderState::new();
422 let mut pos = 0usize;
423 for &tok in prompt {
424 forward_token(weights, tok, pos, &mut state);
425 pos += 1;
426 }
427 let mut out = Vec::new();
428 let mut prev = *prompt.last().unwrap_or(&0);
429 for _ in 0..max_new {
430 let hidden = forward_token(weights, prev, pos, &mut state);
431 let (next, _) = sample_argmax(&compute_logits(weights, &hidden));
432 pos += 1;
433 if stop_ids.contains(&next) {
434 break;
435 }
436 out.push(next);
437 prev = next;
438 }
439 out
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445 use crate::qwen3_moe::{dequant_matvec, QWEN3_A3B_INTERMEDIATE};
446
447 /// 2-aligned storage so the misalignment tests control the offset exactly.
448 fn aligned_bytes(words: &[u16]) -> Vec<u16> {
449 words.to_vec()
450 }
451
452 #[test]
453 fn bf16_words_reads_aligned_payload() {
454 let backing = aligned_bytes(&[0x3f80, 0x4000]);
455 // SAFETY: u16 storage viewed as bytes; lifetime tied to `backing`.
456 let bytes = unsafe { std::slice::from_raw_parts(backing.as_ptr() as *const u8, 4) };
457 assert_eq!(bf16_words(bytes), &[0x3f80, 0x4000]);
458 }
459
460 #[test]
461 #[should_panic(expected = "misaligned")]
462 fn bf16_words_rejects_misaligned_payload() {
463 let backing = aligned_bytes(&[0, 0, 0]);
464 // SAFETY: in-bounds view starting one byte into 2-aligned storage.
465 let bytes =
466 unsafe { std::slice::from_raw_parts((backing.as_ptr() as *const u8).add(1), 4) };
467 let _ = bf16_words(bytes);
468 }
469
470 #[test]
471 #[should_panic(expected = "even length")]
472 fn bf16_words_rejects_odd_length() {
473 let backing = aligned_bytes(&[0, 0]);
474 // SAFETY: in-bounds 3-byte view of 4-byte storage.
475 let bytes = unsafe { std::slice::from_raw_parts(backing.as_ptr() as *const u8, 3) };
476 let _ = bf16_words(bytes);
477 }
478
479 #[test]
480 fn coder_constants_match_official_config() {
481 assert_eq!(QWEN3_CODER_LAYERS, 48);
482 assert_eq!(QWEN3_CODER_HIDDEN, 2048);
483 assert_eq!(QWEN3_CODER_Q_HEADS, 32);
484 assert_eq!(QWEN3_CODER_KV_HEADS, 4);
485 assert_eq!(QWEN3_CODER_HEAD_DIM, 128);
486 assert_eq!(QWEN3_CODER_VOCAB, 151936);
487 assert_eq!(QWEN3_A3B_INTERMEDIATE, 768);
488 }
489
490 #[test]
491 fn fp8_block128_roundtrip_spot_check() {
492 let lut = fp8_table();
493 assert!((lut[0x38] - 1.0).abs() < 1e-6);
494 assert!((lut[0xBC] + 1.5).abs() < 1e-6);
495 let w = vec![0x38u8; 256];
496 // 2x128 is one 128x128 scale block (row blocks round up).
497 let s = vec![crate::qwen3_moe::f32_to_bf16(1.0); 1];
498 let m = decode_fp8_block128(&w, &s, 2, 128);
499 assert!(m.iter().all(|&v| (v - 1.0).abs() < 1e-6));
500 let v = vec![1.0f32; 128];
501 let y = dequant_matvec(&w, &s, 2, 128, &v, &lut);
502 assert!((y[0] - 128.0).abs() < 1e-3);
503 }
504}