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 / tests / qwen3_forward_parity.rs

721 lines · 25458 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 (`Qwen3ForCausalLM`) on the CPU reference path.
17//!
18//! Oracle: transformers 5.17.0 / torch 2.14.0 on CPU, float32 after upcasting the bf16
19//! weights, run by a scratch script outside the repository (provenance in
20//! `fixtures/qwen3-tiny/PROVENANCE.md` and `forward_reference.json`). Our code is never its own
21//! oracle. Tolerance: absolute 1e-4, the ABSOLUTE_TOLERANCE of tinyllama_parity.rs (set before
22//! the first comparison, not tuned).
23//!
24//! The tiny model has `num_heads * head_dim = 64` against `hidden_size = 32`, per-layer
25//! q_norm/k_norm weights that are not 1, tied embeddings, and head_dim read from config.json.
26//! The negative test removes the q/k norm and shows the logits move far outside the tolerance,
27//! so the comparison is not vacuous.
28//!
29//! The ignored test `real_qwen3_4b_instruct_2507_matches_transformers` (run with `--ignored`) runs
30//! the real model in `AIEN_QWEN3_DIR` against
31//! `fixtures/qwen3-4b-instruct-2507-config/real_forward_reference.json` (top-20 logits of the
32//! prompt "The capital of France is", transformers 5.17.0 CPU float32). It fails when
33//! `AIEN_QWEN3_DIR` is unset, so a missing model never reads as a pass. Its
34//! tolerance (5e-3 absolute on 36 layers) was set before the run.
35
36use aien_inference_abi::{
37 load_model_config, model_config_from_hf_json, omega_model_refusal, omega_model_refusal_with,
38 NativeTransformerBackend, ReferenceCpuBackend, SequenceState, TensorBackend,
39 TransformerWeights, GB10_QWEN3_OPT_IN_ENV,
40};
41use serde_json::Value;
42use std::path::PathBuf;
43use std::sync::atomic::{AtomicU64, Ordering};
44use std::sync::Arc;
45
46const ABSOLUTE_TOLERANCE: f32 = 1e-4;
47
48fn fixture(name: &str) -> PathBuf {
49 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
50 .join("fixtures")
51 .join(name)
52}
53
54struct Reference {
55 ids: Vec<u32>,
56 logits: Vec<f32>,
57 argmax: usize,
58}
59
60fn reference(path: PathBuf) -> Reference {
61 let r: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
62 Reference {
63 ids: r["ids"]
64 .as_array()
65 .unwrap()
66 .iter()
67 .map(|v| v.as_u64().unwrap() as u32)
68 .collect(),
69 logits: r["logits"]
70 .as_array()
71 .unwrap()
72 .iter()
73 .map(|v| v.as_f64().unwrap() as f32)
74 .collect(),
75 argmax: r["argmax"].as_u64().unwrap() as usize,
76 }
77}
78
79fn max_abs(a: &[f32], b: &[f32]) -> f32 {
80 assert_eq!(a.len(), b.len());
81 a.iter()
82 .zip(b)
83 .map(|(x, y)| (x - y).abs())
84 .fold(0.0, f32::max)
85}
86
87fn argmax(v: &[f32]) -> usize {
88 v.iter()
89 .enumerate()
90 .max_by(|a, b| a.1.total_cmp(b.1))
91 .unwrap()
92 .0
93}
94
95fn tiny() -> (TransformerWeights, Reference) {
96 let dir = fixture("qwen3-tiny");
97 let config = load_model_config(&dir).expect("config.json");
98 assert!(config.qk_norm);
99 assert_eq!(
100 (config.head_dim, config.num_heads, config.hidden_dim),
101 (16, 4, 32)
102 );
103 let weights = TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config)
104 .expect("weights");
105 (weights, reference(dir.join("forward_reference.json")))
106}
107
108#[test]
109fn qwen3_tiny_sequence_logits_match_transformers() {
110 let (weights, r) = tiny();
111 let got = weights
112 .forward_sequence_with_diagnostics(&r.ids)
113 .activations["last_token_logits"]
114 .clone();
115 let d = max_abs(&got, &r.logits);
116 eprintln!("sequence path max abs diff = {d:e}");
117 assert!(d <= ABSOLUTE_TOLERANCE, "max abs diff {d:e}");
118 assert_eq!(argmax(&got), r.argmax);
119}
120
121#[test]
122fn qwen3_tiny_token_by_token_logits_match_transformers() {
123 let (weights, r) = tiny();
124 let mut state = SequenceState {
125 tokens: Vec::new(),
126 layers: vec![Default::default(); weights.config.num_layers],
127 kv_dtype: Default::default(),
128 };
129 let mut last = Vec::new();
130 for (pos, id) in r.ids.iter().enumerate() {
131 last = weights.forward_token(*id, pos, &mut state);
132 }
133 let got = weights.compute_logits(&last);
134 let d = max_abs(&got, &r.logits);
135 eprintln!("forward_token path max abs diff = {d:e}");
136 assert!(d <= ABSOLUTE_TOLERANCE, "max abs diff {d:e}");
137}
138
139#[test]
140fn qwen3_tiny_backend_prefill_and_decode_match_transformers() {
141 let (weights, r) = tiny();
142 let mut backend = NativeTransformerBackend::new_reference(weights);
143 let got = backend.prefill_sequence(1, &r.ids).expect("prefill");
144 let d = max_abs(&got, &r.logits);
145 eprintln!("backend prefill max abs diff = {d:e}");
146 assert!(d <= ABSOLUTE_TOLERANCE, "prefill max abs diff {d:e}");
147
148 // Prefill all but the last id, then decode the last id: same logits.
149 let mut backend2 = NativeTransformerBackend::new_reference(tiny().0);
150 backend2
151 .prefill_sequence(2, &r.ids[..r.ids.len() - 1])
152 .expect("prefill");
153 let seq = backend2.sequences.get_mut(&2).unwrap();
154 let h = NativeTransformerBackend::forward_token_impl_paged(
155 &backend2.weights,
156 &*backend2.tensor_backend,
157 *r.ids.last().unwrap(),
158 r.ids.len() - 1,
159 seq,
160 2,
161 None,
162 );
163 let got2 = backend2.compute_logits(&h);
164 let d2 = max_abs(&got2, &r.logits);
165 eprintln!("backend decode max abs diff = {d2:e}");
166 assert!(d2 <= ABSOLUTE_TOLERANCE, "decode max abs diff {d2:e}");
167}
168
169/// Negative control: without q_norm/k_norm the logits are far from the reference, so the
170/// parity tests above do exercise the norm.
171#[test]
172fn qwen3_without_qk_norm_is_far_from_reference() {
173 let (mut weights, r) = tiny();
174 for layer in &mut weights.layers {
175 layer.q_norm = None;
176 layer.k_norm = None;
177 }
178 let got = weights
179 .forward_sequence_with_diagnostics(&r.ids)
180 .activations["last_token_logits"]
181 .clone();
182 let d = max_abs(&got, &r.logits);
183 eprintln!("no-norm max abs diff = {d:e}");
184 assert!(
185 d > 100.0 * ABSOLUTE_TOLERANCE,
186 "norm removal changed logits by only {d:e}"
187 );
188}
189
190#[test]
191fn qwen3_checkpoint_missing_q_norm_is_refused() {
192 let dir = fixture("qwen3-tiny");
193 let mut config = load_model_config(&dir).unwrap();
194 config.qk_norm = false; // catalog without norms: file has extra tensors, still loads as Llama-style
195 let llama_style =
196 TransformerWeights::load_from_safetensors(dir.join("model.safetensors"), &config);
197 // The Qwen3 catalog is a strict superset: a Llama-style config must not silently load a
198 // Qwen3 file as correct, so the weights it builds carry no norms.
199 if let Ok(w) = llama_style {
200 assert!(w
201 .layers
202 .iter()
203 .all(|l| l.q_norm.is_none() && l.k_norm.is_none()));
204 }
205 let cat = aien_inference_abi::llama_catalog(&load_model_config(&dir).unwrap());
206 assert!(cat
207 .iter()
208 .any(|(n, s)| n == "model.layers.1.self_attn.q_norm.weight" && s == &vec![16]));
209 assert!(cat
210 .iter()
211 .any(|(n, s)| n == "model.layers.0.self_attn.k_norm.weight" && s == &vec![16]));
212 assert!(cat
213 .iter()
214 .any(|(n, s)| n == "model.layers.0.self_attn.q_proj.weight" && s == &vec![64, 32]));
215}
216
217fn real_config_json() -> String {
218 std::fs::read_to_string(fixture("qwen3-4b-instruct-2507-config").join("config.json")).unwrap()
219}
220
221#[test]
222fn real_qwen3_4b_instruct_2507_config_is_accepted() {
223 let c = model_config_from_hf_json(
224 "Qwen/Qwen3-4B-Instruct-2507",
225 &real_config_json(),
226 Some(
227 &std::fs::read_to_string(
228 fixture("qwen3-4b-instruct-2507-config").join("generation_config.json"),
229 )
230 .unwrap(),
231 ),
232 )
233 .expect("accepted");
234 assert!(c.qk_norm && c.tie_word_embeddings);
235 assert_eq!(
236 (c.num_layers, c.num_heads, c.num_kv_heads, c.head_dim),
237 (36, 32, 8, 128)
238 );
239 assert_eq!(
240 (c.hidden_dim, c.intermediate_dim, c.vocab_size),
241 (2560, 9728, 151936)
242 );
243 assert_eq!(c.rope_theta, 5_000_000.0);
244 assert_eq!(c.max_sequence_length, 262144);
245 assert_eq!(c.eos_token_ids, vec![151645, 151643]);
246 let cat = aien_inference_abi::llama_catalog(&c);
247 // embed + 36 * (norms 2 + qkvo 4 + qk_norm 2 + mlp 3) + final norm, no lm_head (tied).
248 assert_eq!(cat.len(), 1 + 36 * 11 + 1);
249 assert!(cat
250 .iter()
251 .any(|(n, s)| n == "model.layers.35.self_attn.q_proj.weight" && s == &vec![4096, 2560]));
252 assert!(cat
253 .iter()
254 .any(|(n, s)| n == "model.layers.35.self_attn.o_proj.weight" && s == &vec![2560, 4096]));
255 assert!(cat
256 .iter()
257 .any(|(n, s)| n == "model.layers.0.self_attn.q_norm.weight" && s == &vec![128]));
258}
259
260#[test]
261fn qwen3_unsupported_config_fields_are_refused_by_name() {
262 let base: Value = serde_json::from_str(&real_config_json()).unwrap();
263 let refuse = |edit: &dyn Fn(&mut serde_json::Map<String, Value>), needle: &str| {
264 let mut v = base.clone();
265 edit(v.as_object_mut().unwrap());
266 let err = model_config_from_hf_json("m", &v.to_string(), None).unwrap_err();
267 assert!(err.contains(needle), "error {err:?} should name {needle:?}");
268 };
269 refuse(
270 &|m| {
271 m.remove("head_dim");
272 },
273 "head_dim",
274 );
275 refuse(
276 &|m| {
277 m.insert(
278 "rope_parameters".into(),
279 serde_json::json!({"rope_type": "default"}),
280 );
281 },
282 "rope_parameters",
283 );
284 refuse(
285 &|m| {
286 m.insert("some_new_field".into(), Value::Bool(true));
287 },
288 "some_new_field",
289 );
290 refuse(
291 &|m| {
292 m.insert("use_sliding_window".into(), Value::Bool(true));
293 },
294 "use_sliding_window",
295 );
296 refuse(
297 &|m| {
298 m.insert("sliding_window".into(), Value::from(4096));
299 },
300 "sliding_window",
301 );
302 refuse(
303 &|m| {
304 m.insert(
305 "layer_types".into(),
306 serde_json::json!(["linear_attention"]),
307 );
308 },
309 "layer_types",
310 );
311 refuse(
312 &|m| {
313 m.insert("attention_bias".into(), Value::Bool(true));
314 },
315 "attention_bias",
316 );
317 refuse(
318 &|m| {
319 m.insert("hidden_act".into(), Value::from("gelu"));
320 },
321 "hidden_act",
322 );
323 refuse(
324 &|m| {
325 m.insert("model_type".into(), Value::from("qwen2"));
326 },
327 "model_type",
328 );
329 refuse(
330 &|m| {
331 m.insert(
332 "rope_scaling".into(),
333 serde_json::json!({"rope_type": "yarn", "factor": 4.0}),
334 );
335 },
336 "rope_scaling",
337 );
338 refuse(
339 &|m| {
340 m.insert(
341 "architectures".into(),
342 serde_json::json!(["Qwen3MoeForCausalLM"]),
343 );
344 },
345 "architectures",
346 );
347}
348
349#[test]
350fn llama_head_dim_rule_is_unchanged() {
351 // A Llama-architecture config whose heads * head_dim != hidden is still refused.
352 let json = r#"{"architectures":["LlamaForCausalLM"],"hidden_size":32,"intermediate_size":64,
353 "num_hidden_layers":1,"num_attention_heads":4,"num_key_value_heads":2,"head_dim":16,
354 "vocab_size":10,"rms_norm_eps":1e-5,"max_position_embeddings":16,"eos_token_id":2}"#;
355 let err = model_config_from_hf_json("m", json, None).unwrap_err();
356 assert!(err.contains("must equal hidden_size"), "{err}");
357}
358
359#[test]
360fn gb10_backend_refuses_qwen3_and_not_llama() {
361 let q = model_config_from_hf_json(
362 "Qwen/Qwen3-4B-Instruct-2507",
363 &real_config_json(),
364 Some("{\"eos_token_id\":[151645]}"),
365 )
366 .unwrap();
367 // Qwen3-4B (head_dim 128): rmsnorm_heads and attention both run on the engine, and since
368 // sovereign-core#277 (declared attempt 3) the qualified path is the default. Only an
369 // explicit switch-off refuses it, by name.
370 assert_eq!(q.head_dim, 128);
371 let msg = omega_model_refusal_with(&q, false)
372 .expect("Qwen3-4B must be refused on the GB10 engine when switched off");
373 assert!(
374 msg.contains("AIEN_GB10_QWEN3_DECLARED_ATTEMPT") && msg.contains("switched off"),
375 "{msg}"
376 );
377 assert_eq!(omega_model_refusal_with(&q, true), None);
378 // The default is on: unset and 1 enable, 0 and any other value refuse (fail closed).
379 assert!(aien_inference_abi::gb10_qwen3_enabled_from(None, true));
380 assert!(aien_inference_abi::gb10_qwen3_enabled_from(Some("1"), true));
381 // Unset on a non-strict (AIEN_DEV_FALLBACK=1) run is outside the evidence: refused.
382 assert!(!aien_inference_abi::gb10_qwen3_enabled_from(None, false));
383 assert!(aien_inference_abi::gb10_qwen3_enabled_from(
384 Some("1"),
385 false
386 ));
387 for v in ["0", "", "true", "yes", "2", " 1"] {
388 assert!(
389 !aien_inference_abi::gb10_qwen3_enabled_from(Some(v), true),
390 "{v:?}"
391 );
392 }
393 match std::env::var(GB10_QWEN3_OPT_IN_ENV).ok().as_deref() {
394 None if aien_inference_abi::strict::production_strict() => {
395 assert_eq!(omega_model_refusal(&q), None)
396 }
397 None => assert_eq!(omega_model_refusal(&q), Some(msg)),
398 Some("1") => assert_eq!(omega_model_refusal(&q), None),
399 Some(_) => assert_eq!(omega_model_refusal(&q), Some(msg)),
400 }
401 // A Qwen3 shape with head_dim 64 cannot run rmsnorm_heads (head_dim % 128): refused up front.
402 let q64 = model_config_from_hf_json(
403 "qwen3-head-dim-64",
404 &real_config_json().replace("\"head_dim\": 128", "\"head_dim\": 64"),
405 Some("{\"eos_token_id\":[151645]}"),
406 )
407 .unwrap();
408 assert_eq!(q64.head_dim, 64);
409 // Neither setting lifts this one.
410 for opted_in in [false, true] {
411 let msg = omega_model_refusal_with(&q64, opted_in)
412 .expect("Qwen3 with head_dim 64 must be refused on the GB10 engine");
413 assert!(
414 msg.contains("head_dim 64")
415 && msg.contains("Qwen3")
416 && msg.contains("only at head_dim 128"),
417 "{msg}"
418 );
419 }
420 let llama = aien_inference_abi::ModelConfig::tinyllama_1_1b();
421 assert!(omega_model_refusal(&llama).is_none());
422 assert!(omega_model_refusal_with(&llama, false).is_none());
423}
424
425/// Delegates every op to the reference backend and counts `rmsnorm_heads` calls.
426#[derive(Default)]
427struct HeadsSpy {
428 inner: ReferenceCpuBackend,
429 heads_calls: AtomicU64,
430}
431
432impl TensorBackend for HeadsSpy {
433 fn name(&self) -> &'static str {
434 "HeadsSpy"
435 }
436 fn rmsnorm(&self, out: &mut [f32], x: &[f32], weight: &[f32], eps: f32) {
437 self.inner.rmsnorm(out, x, weight, eps)
438 }
439 fn rmsnorm_heads(&self, x: &mut [f32], weight: &[f32], head_dim: usize, eps: f32) {
440 self.heads_calls.fetch_add(1, Ordering::Relaxed);
441 self.inner.rmsnorm_heads(x, weight, head_dim, eps)
442 }
443 fn apply_rope(
444 &self,
445 q: &mut [f32],
446 k: &mut [f32],
447 pos: usize,
448 head_dim: usize,
449 num_q_heads: usize,
450 num_kv_heads: usize,
451 rope: &aien_inference_abi::RopeParams,
452 ) {
453 self.inner
454 .apply_rope(q, k, pos, head_dim, num_q_heads, num_kv_heads, rope)
455 }
456 fn matmul_vec(
457 &self,
458 out: &mut [f32],
459 x: &[f32],
460 weight: &[f32],
461 out_dim: usize,
462 in_dim: usize,
463 ) {
464 self.inner.matmul_vec(out, x, weight, out_dim, in_dim)
465 }
466 fn swiglu(&self, out: &mut [f32], gate: &[f32], up: &[f32]) {
467 self.inner.swiglu(out, gate, up)
468 }
469 fn gqa_attention(
470 &self,
471 out: &mut [f32],
472 q: &[f32],
473 k_cache: &[f32],
474 v_cache: &[f32],
475 seq_len: usize,
476 num_q_heads: usize,
477 num_kv_heads: usize,
478 head_dim: usize,
479 ) {
480 self.inner.gqa_attention(
481 out,
482 q,
483 k_cache,
484 v_cache,
485 seq_len,
486 num_q_heads,
487 num_kv_heads,
488 head_dim,
489 )
490 }
491 fn compute_logits(
492 &self,
493 logits: &mut [f32],
494 hidden: &[f32],
495 embed_weight: &[f32],
496 vocab_size: usize,
497 hidden_dim: usize,
498 ) {
499 self.inner
500 .compute_logits(logits, hidden, embed_weight, vocab_size, hidden_dim)
501 }
502}
503
504/// The q/k norm goes through `TensorBackend::rmsnorm_heads` on every forward path (prefill,
505/// batch decode, single-token decode): two calls (q, k) per layer per token on the decode
506/// paths, and two per layer per chunk on the prompt read (the whole chunk's heads in one run),
507/// and the logits still match transformers. A device backend therefore runs and accounts for
508/// it; before this, the norm was host math outside the backend.
509#[test]
510fn qwen3_qk_norm_runs_through_the_tensor_backend() {
511 let (weights, r) = tiny();
512 let per_token = 2 * weights.config.num_layers as u64;
513 let n = r.ids.len();
514 let spy = Arc::new(HeadsSpy::default());
515 let calls = || spy.heads_calls.load(Ordering::Relaxed);
516 let mut b = NativeTransformerBackend::with_backend(weights, spy.clone());
517
518 // One chunk (the prompt is shorter than a chunk): q and k once per layer.
519 b.prefill_sequence(1, &r.ids[..n - 1]).expect("prefill");
520 assert_eq!(calls(), per_token, "prefill (one chunk)");
521
522 b.pending_prefill_token.insert(1, r.ids[n - 1]);
523 let (_out, logits) = b
524 .forward_decode_batch_with_logits(&[1])
525 .expect("batch decode");
526 assert_eq!(calls(), 2 * per_token, "batch decode");
527 let d = max_abs(&logits[0], &r.logits);
528 assert!(d <= ABSOLUTE_TOLERANCE, "batch decode max abs diff {d:e}");
529
530 b.prefill_sequence(2, &r.ids[..n - 1]).expect("prefill");
531 let before = calls();
532 let seq = b.sequences.get_mut(&2).unwrap();
533 let h = NativeTransformerBackend::forward_token_impl_paged(
534 &b.weights,
535 &*b.tensor_backend,
536 r.ids[n - 1],
537 n - 1,
538 seq,
539 2,
540 None,
541 );
542 assert_eq!(calls(), before + per_token, "single-token decode");
543 let d = max_abs(&b.compute_logits(&h), &r.logits);
544 assert!(
545 d <= ABSOLUTE_TOLERANCE,
546 "single-token decode max abs diff {d:e}"
547 );
548}
549
550#[test]
551#[ignore = "needs the real Qwen3-4B-Instruct-2507 weights in AIEN_QWEN3_DIR"]
552fn real_qwen3_4b_instruct_2507_matches_transformers() {
553 let dir = std::env::var("AIEN_QWEN3_DIR")
554 .expect("AIEN_QWEN3_DIR must name a Qwen3-4B-Instruct-2507 model directory");
555 let dir = PathBuf::from(dir);
556 let r: Value = serde_json::from_str(
557 &std::fs::read_to_string(
558 fixture("qwen3-4b-instruct-2507-config").join("real_forward_reference.json"),
559 )
560 .unwrap(),
561 )
562 .unwrap();
563 let ids: Vec<u32> = r["ids"]
564 .as_array()
565 .unwrap()
566 .iter()
567 .map(|v| v.as_u64().unwrap() as u32)
568 .collect();
569 let top_ids: Vec<usize> = r["top_ids"]
570 .as_array()
571 .unwrap()
572 .iter()
573 .map(|v| v.as_u64().unwrap() as usize)
574 .collect();
575 let top_logits: Vec<f32> = r["top_logits"]
576 .as_array()
577 .unwrap()
578 .iter()
579 .map(|v| v.as_f64().unwrap() as f32)
580 .collect();
581 let config = load_model_config(&dir).expect("config");
582 let weights = TransformerWeights::load_from_safetensors(
583 dir.join("model.safetensors.index.json"),
584 &config,
585 )
586 .expect("weights");
587 let got =
588 weights.forward_sequence_with_diagnostics(&ids).activations["last_token_logits"].clone();
589 assert_eq!(got.len(), r["vocab"].as_u64().unwrap() as usize);
590 let ours: Vec<f32> = top_ids.iter().map(|i| got[*i]).collect();
591 let d = max_abs(&ours, &top_logits);
592 eprintln!(
593 "real model: max abs diff over the reference top-20 = {d:e}, argmax {} vs {}",
594 argmax(&got),
595 top_ids[0]
596 );
597 assert_eq!(argmax(&got), top_ids[0]);
598 assert!(d <= 5e-3, "max abs diff {d:e}");
599}
600
601/// Real Qwen3-4B-Instruct-2507 prefill on the GB10 engine (every op native, q/k norm as
602/// `rmsnorm_heads`) against the same transformers reference. Bound, set before any run: the
603/// project's GB10 logit bound `MAX_ABS_DLOGIT` = 0.15 (aien-inference-runtime tests/drift, from
604/// the Llama cut 3d measurement 0.059) over the reference top-20, the same argmax, no fallback
605/// and no chip error. Chip test: native build, AIEN_QWEN3_DIR, heavy queue / GPU hold only.
606#[test]
607#[ignore = "chip test: needs a native build, the GB10 and AIEN_QWEN3_DIR; run under a GPU hold"]
608fn real_qwen3_4b_instruct_2507_on_gb10_matches_transformers() {
609 let omega = Arc::new(aien_inference_abi::OmegaGb10Backend::new());
610 assert!(omega.is_available(), "native build required");
611 let dir = PathBuf::from(
612 std::env::var("AIEN_QWEN3_DIR").expect("AIEN_QWEN3_DIR must name the model directory"),
613 );
614 let r: Value = serde_json::from_str(
615 &std::fs::read_to_string(
616 fixture("qwen3-4b-instruct-2507-config").join("real_forward_reference.json"),
617 )
618 .unwrap(),
619 )
620 .unwrap();
621 let ids: Vec<u32> = r["ids"]
622 .as_array()
623 .unwrap()
624 .iter()
625 .map(|v| v.as_u64().unwrap() as u32)
626 .collect();
627 let top_ids: Vec<usize> = r["top_ids"]
628 .as_array()
629 .unwrap()
630 .iter()
631 .map(|v| v.as_u64().unwrap() as usize)
632 .collect();
633 let top_logits: Vec<f32> = r["top_logits"]
634 .as_array()
635 .unwrap()
636 .iter()
637 .map(|v| v.as_f64().unwrap() as f32)
638 .collect();
639 let config = load_model_config(&dir).expect("config");
640 omega.check_model(&config).expect(
641 "GB10 engine must accept Qwen3-4B (unset or AIEN_GB10_QWEN3_DECLARED_ATTEMPT=1 enables it)",
642 );
643 let weights = TransformerWeights::load_from_safetensors(
644 dir.join("model.safetensors.index.json"),
645 &config,
646 )
647 .expect("weights");
648 let mut b = NativeTransformerBackend::with_backend(weights, omega.clone());
649 let got = b
650 .prefill_sequence(1, &ids)
651 .expect("prefill on the GB10 engine");
652 let ours: Vec<f32> = top_ids.iter().map(|i| got[*i]).collect();
653 let d = max_abs(&ours, &top_logits);
654 println!(
655 "QWEN3_GB10 max abs diff over the reference top-20 = {d:e} (bound 0.15), argmax {} vs {}, \
656 chip_errors={} fallbacks={} {}",
657 argmax(&got),
658 top_ids[0],
659 omega.chip_errors(),
660 omega.fallback_count(),
661 omega.op_report().line()
662 );
663 assert_eq!(omega.chip_errors(), 0, "{}", omega.last_error());
664 assert_eq!(omega.fallback_count(), 0, "{}", omega.last_error());
665 assert_eq!(argmax(&got), top_ids[0]);
666 assert!(d <= 0.15, "max abs diff {d:e}");
667}
668
669/// Batch decode (`forward_decode_batch_with_logits`, the third q/k-norm site): two sequences
670/// with the reference prompt must reproduce the transformers logits, and a third, different
671/// sequence in the same batch must equal its own single-sequence decode.
672#[test]
673fn qwen3_tiny_batch_decode_matches_transformers_and_single_sequence() {
674 let (weights, r) = tiny();
675 let n = r.ids.len();
676 let other: Vec<u32> = r.ids.iter().rev().copied().collect();
677
678 let mut batch = NativeTransformerBackend::new_reference(weights.clone());
679 for (id, prompt) in [(1u64, &r.ids), (2, &r.ids), (3, &other)] {
680 batch
681 .prefill_sequence(id, &prompt[..n - 1])
682 .expect("prefill");
683 // The decode step consumes the pending token at position n - 1.
684 batch.pending_prefill_token.insert(id, prompt[n - 1]);
685 }
686 let (_out, logits) = batch
687 .forward_decode_batch_with_logits(&[1, 2, 3])
688 .expect("batch decode");
689 assert_eq!(logits.len(), 3);
690 for row in &logits[..2] {
691 let d = max_abs(row, &r.logits);
692 eprintln!("batch decode vs transformers max abs diff = {d:e}");
693 assert!(d <= ABSOLUTE_TOLERANCE, "batch max abs diff {d:e}");
694 }
695
696 let mut single = NativeTransformerBackend::new_reference(weights);
697 single
698 .prefill_sequence(9, &other[..n - 1])
699 .expect("prefill");
700 let seq = single.sequences.get_mut(&9).unwrap();
701 let h = NativeTransformerBackend::forward_token_impl_paged(
702 &single.weights,
703 &*single.tensor_backend,
704 other[n - 1],
705 n - 1,
706 seq,
707 9,
708 None,
709 );
710 let want = single.compute_logits(&h);
711 let d = max_abs(&logits[2], &want);
712 eprintln!("batch row 3 vs single-sequence max abs diff = {d:e}");
713 assert!(
714 d <= ABSOLUTE_TOLERANCE,
715 "batch vs single max abs diff {d:e}"
716 );
717 assert!(
718 max_abs(&logits[2], &logits[0]) > 1e-3,
719 "third sequence must differ from the first"
720 );
721}