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

1151 lines · 42528 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
16use super::test_support::*;
17use super::*;
18use crate::qwen3_moe::f32_to_bf16;
19use crate::qwen3_moe_omega::test_support::MemorySource;
20
21/// `~/models/BitNet-b1.58-2B-4T-bf16/config.json` (sha256 9dbdfeeb..., revision 2766813), verbatim.
22const BITNET_2B4T_CONFIG: &str = r#"{
23 "architectures": [
24 "BitNetForCausalLM"
25 ],
26 "auto_map": {
27 "AutoConfig": "configuration_bitnet.BitNetConfig",
28 "AutoModelForCausalLM": "modeling_bitnet.BitNetForCausalLM"
29 },
30 "bos_token_id": 128000,
31 "eos_token_id": 128001,
32 "hidden_act": "relu2",
33 "hidden_size": 2560,
34 "initializer_range": 0.02,
35 "intermediate_size": 6912,
36 "max_position_embeddings": 4096,
37 "model_type": "bitnet",
38 "rms_norm_eps": 1e-05,
39 "num_attention_heads": 20,
40 "num_hidden_layers": 30,
41 "num_key_value_heads": 5,
42 "rope_theta": 500000.0,
43 "tie_word_embeddings": true,
44 "torch_dtype": "bfloat16",
45 "use_cache": true,
46 "vocab_size": 128256,
47 "quantization_config": {
48 "quant_method": "bitnet",
49 "linear_class": "autobitlinear",
50 "quantization_mode": "online"
51 }
52}"#;
53
54/// Its `generation_config.json`, verbatim.
55const BITNET_2B4T_GENERATION: &str = r#"{
56 "bos_token_id": 128000,
57 "eos_token_id": [
58 128001,
59 128009
60 ],
61 "do_sample": true,
62 "temperature": 0.6,
63 "max_length": 4096,
64 "top_p": 0.9,
65 "transformers_version": "4.40.0.dev0"
66}"#;
67
68fn real_config() -> BitNetConfig {
69 BitNetConfig::from_json(BITNET_2B4T_CONFIG, Some(BITNET_2B4T_GENERATION)).unwrap()
70}
71
72fn variant(
73 edit: impl FnOnce(&mut serde_json::Map<String, serde_json::Value>),
74) -> Result<BitNetConfig, String> {
75 let mut v: serde_json::Value = serde_json::from_str(BITNET_2B4T_CONFIG).unwrap();
76 edit(v.as_object_mut().unwrap());
77 BitNetConfig::from_json(&v.to_string(), None)
78}
79
80fn assert_refused(r: Result<BitNetConfig, String>, needles: &[&str]) {
81 let e = r.expect_err("must be refused");
82 assert!(e.starts_with("config refused"), "{e}");
83 for n in needles {
84 assert!(e.contains(n), "refusal {e:?} does not name {n:?}");
85 }
86}
87
88fn load_tiny(up: &RecordingTernUploader) -> Result<(BitNetOmegaWeights, BitNetLoadReport), String> {
89 let c = tiny_config();
90 load_bitnet_omega_from(&c, &mut memory_source(&c), up, &mut |_| {})
91}
92
93/// The full byte test: every upload against the checkpoint, then the norms the host keeps.
94fn byte_test(up: &RecordingTernUploader, w: &BitNetOmegaWeights) -> Result<(), String> {
95 let c = tiny_config();
96 let recs = up.records.lock().unwrap();
97 check_upload_bytes(&c, &mut memory_source(&c), &recs)?;
98 check_host_norms(&c, &mut memory_source(&c), w)
99}
100
101fn scratch(name: &str) -> std::path::PathBuf {
102 let d = std::env::temp_dir().join(format!("aien-bitnet-{name}-{}", std::process::id()));
103 let _ = std::fs::remove_dir_all(&d);
104 d
105}
106
107// -------------------------------------------------------------------------------------------
108// Config.
109// -------------------------------------------------------------------------------------------
110
111#[test]
112fn reads_the_bitnet_2b4t_config() {
113 let c = real_config();
114 assert_eq!(
115 (
116 c.layers,
117 c.hidden,
118 c.q_heads,
119 c.kv_heads,
120 c.head_dim,
121 c.intermediate,
122 c.vocab
123 ),
124 (30, 2560, 20, 5, 128, 6912, 128256)
125 );
126 assert_eq!(
127 (c.rms_eps, c.rope_theta, c.max_position),
128 (1e-5, 500000.0, 4096)
129 );
130 assert_eq!(
131 (c.bos_token_id, c.eos_token_ids.clone()),
132 (128000, vec![128001, 128009])
133 );
134 assert_eq!(c.shape(TernTensor::Qkv), (3840, 2560));
135 assert_eq!(c.shape(TernTensor::O), (2560, 2560));
136 assert_eq!(c.shape(TernTensor::GateUp), (13824, 2560));
137 assert_eq!(c.shape(TernTensor::Down), (2560, 6912));
138 let g = KvGeometry::from(&c);
139 assert_eq!(
140 (g.layers, g.q_heads, g.kv_heads, g.head_dim, g.rope_theta),
141 (30, 20, 5, 128, 500000.0)
142 );
143 // Device bytes: trits 2,084,044,800 / 4 = 521,011,200 (spec 5) + 210 bf16 scales (420) +
144 // e4m3 table 328,335,360 + its 1002 x 20 bf16 scales (40,080): 849,387,060
145 // (calc:f379a7e8).
146 assert_eq!(c.model_resident_bytes(), 849_387_060);
147}
148
149#[test]
150fn refuses_other_families_by_name() {
151 assert_refused(
152 variant(|o| {
153 o.insert("model_type".into(), "llama".into());
154 }),
155 &["model_type", "\"llama\"", "bitnet"],
156 );
157 assert_refused(
158 variant(|o| {
159 o.insert("hidden_act".into(), "silu".into());
160 }),
161 &["hidden_act", "\"silu\"", "relu2"],
162 );
163 assert_refused(
164 variant(|o| {
165 o.insert("tie_word_embeddings".into(), false.into());
166 }),
167 &["tie_word_embeddings", "false"],
168 );
169 assert_refused(
170 variant(|o| {
171 o.remove("tie_word_embeddings");
172 }),
173 &["tie_word_embeddings", "absent"],
174 );
175 assert_refused(
176 variant(|o| {
177 o.insert("torch_dtype".into(), "float16".into());
178 }),
179 &["torch_dtype", "\"float16\"", "bfloat16"],
180 );
181 assert_refused(
182 variant(|o| {
183 o["quantization_config"]["quantization_mode"] = "offline".into();
184 }),
185 &["quantization_config", "offline"],
186 );
187 assert_refused(
188 variant(|o| {
189 o["quantization_config"]["quant_method"] = "gptq".into();
190 }),
191 &["quantization_config", "gptq"],
192 );
193 assert_refused(
194 variant(|o| {
195 o.remove("quantization_config");
196 }),
197 &["quantization_config", "absent"],
198 );
199 assert_refused(
200 variant(|o| {
201 o.insert(
202 "architectures".into(),
203 serde_json::json!(["LlamaForCausalLM"]),
204 );
205 }),
206 &["architectures", "LlamaForCausalLM"],
207 );
208}
209
210#[test]
211fn refuses_what_the_engine_does_not_implement() {
212 assert_refused(
213 variant(|o| {
214 o.insert("sliding_window".into(), 4096.into());
215 }),
216 &["\"sliding_window\"", "not implemented"],
217 );
218 assert_refused(
219 variant(|o| {
220 o.insert(
221 "rope_scaling".into(),
222 serde_json::json!({"type": "linear", "factor": 2.0}),
223 );
224 }),
225 &["rope_scaling"],
226 );
227 assert_refused(
228 variant(|o| {
229 o.insert("attention_bias".into(), true.into());
230 }),
231 &["attention_bias"],
232 );
233 assert_refused(
234 variant(|o| {
235 o.insert("head_dim".into(), 64.into());
236 }),
237 &["head_dim"],
238 );
239 assert_refused(
240 variant(|o| {
241 o.insert("num_key_value_heads".into(), 3.into());
242 }),
243 &["GQA"],
244 );
245 assert_refused(
246 variant(|o| {
247 o.insert("vocab_size".into(), 128255.into());
248 }),
249 &["word table"],
250 );
251 assert_refused(
252 variant(|o| {
253 o.insert("intermediate_size".into(), 6920.into());
254 }),
255 &["intermediate_size", "16"],
256 );
257 // Neutral values of the optional keys are taken.
258 variant(|o| {
259 o.insert("rope_scaling".into(), serde_json::Value::Null);
260 o.insert("attention_bias".into(), false.into());
261 o.insert("head_dim".into(), 128.into());
262 })
263 .unwrap();
264}
265
266// -------------------------------------------------------------------------------------------
267// The ternariser.
268// -------------------------------------------------------------------------------------------
269
270fn bf(v: &[f32]) -> Vec<u16> {
271 v.iter().map(|&x| f32_to_bf16(x)).collect()
272}
273
274#[test]
275fn ternariser_is_pytorch_bf16_absmean() {
276 // mean |w| = 1: s = 1, w_scale = 1. 0.5 is a tie and rounds to even (0); 1.5 rounds to 2,
277 // clamped to 1; -0.5 to 0; -0.75 to -1.
278 let w = bf(&[0.5, 1.5, -0.5, -0.75, 1.25, 0.25, 2.0, -1.25]);
279 let mut t = vec![0i8; w.len()];
280 let s = absmean_ternarise(&w, &mut t).unwrap();
281 assert_eq!((s.mean, s.s, s.w_scale), (1.0, 1.0, 1.0));
282 assert_eq!(t, [0, 1, 0, -1, 1, 0, 1, -1]);
283
284 // mean 0.3 is not a bf16 value: every step rounds. bf16(0.3) = 0.30078125,
285 // s = bf16(1 / 0.30078125) = 3.328125, w_scale = bf16(1 / 3.328125) = 0.30078125.
286 let w = bf(&[0.3, -0.3, 0.3, -0.3]);
287 let s = absmean_ternarise(&w, &mut [0i8; 4]).unwrap();
288 assert_eq!((s.mean, s.s, s.w_scale), (0.30078125, 3.328125, 0.30078125));
289 assert_eq!(s.w_scale_bf16(), f32_to_bf16(0.30078125));
290
291 // The clamp: an all-zero projection has mean bf16(1e-5), trits 0.
292 let mut t = vec![5i8; 4];
293 let s = absmean_ternarise(&[0u16; 4], &mut t).unwrap();
294 assert_eq!(s.mean, bf16_to_f32(f32_to_bf16(1e-5)));
295 assert_eq!(t, [0; 4]);
296
297 // NaN and infinity are refused by index; lengths must agree.
298 let mut w = bf(&[1.0, 2.0, 3.0]);
299 w[2] = 0x7fc0;
300 assert!(absmean_ternarise(&w, &mut [0; 3])
301 .unwrap_err()
302 .contains("weight 2"));
303 w[2] = 0x7f80;
304 assert!(absmean_ternarise(&w, &mut [0; 3])
305 .unwrap_err()
306 .contains("weight 2"));
307 assert!(absmean_ternarise(&bf(&[1.0]), &mut [0; 2]).is_err());
308}
309
310/// The trit of `bf16(w * s)` decides at the bf16 product, not at the exact product: with
311/// mean 3 (bf16 exact), s = bf16(1/3) = 0.333984375; w = 1.5 gives 0.5009765625 exactly in
312/// f32, which bf16 rounds to 0.5, a tie, so the trit is 0 although the exact |w|/mean is 0.5.
313#[test]
314fn ternariser_rounds_the_product_to_bf16_first() {
315 let s = bf16_to_f32(f32_to_bf16(1.0 / 3.0));
316 assert_eq!(s, 171.0 / 512.0);
317 assert_eq!(bf16_to_f32(f32_to_bf16(1.5 * s)), 0.5);
318 assert_eq!(trit_of(f32_to_bf16(1.5), s), 0);
319 assert_eq!(trit_of(f32_to_bf16(1.5078125), s), 1);
320 assert_eq!(trit_of(f32_to_bf16(-1.5078125), s), -1);
321 // The test's own reference agrees on a sweep of every bf16 in [-4, 4] at three scales.
322 for s in [171.0f32 / 512.0, 1.0, 3.328125] {
323 for b in 0u16..=0xffff {
324 let v = bf16_to_f32(b);
325 if v.is_finite() && v.abs() <= 4.0 {
326 assert_eq!(trit_of(b, s), reference_trit(b, s), "w {v} s {s}");
327 }
328 }
329 }
330}
331
332/// omega's `oma_quant_absmean` (`omega/src/algebra/oma_quant.c:6-33` at origin/main 6c1827ba),
333/// ported line for line: f32 input, double mean, `scale = (float)mean`, `q = round(w / scale)`
334/// half away from zero, clamped.
335fn oma_quant_absmean(w: &[f32]) -> (Vec<i8>, f32) {
336 let sum: f64 = w.iter().map(|&x| (x as f64).abs()).sum();
337 if sum == 0.0 {
338 return (vec![0; w.len()], 0.0);
339 }
340 let s = (sum / w.len() as f64) as f32;
341 let q = w
342 .iter()
343 .map(|&x| ((x as f64) / (s as f64)).round().clamp(-1.0, 1.0) as i8)
344 .collect();
345 (q, s)
346}
347
348/// Where the rules coincide, the trits and the scale equal omega's: the mean is a power of two
349/// (so the three bf16 roundings are exact) and no weight sits on the |w| = mean/2 boundary.
350/// Where they do not, the difference is pinned: (1) on the boundary omega rounds away from
351/// zero, PyTorch (and we) to even, so 0; (2) a mean that is not a bf16 value gives a different
352/// scale (omega keeps the f32 mean; we store bf16(1 / bf16(1 / bf16(mean))) as the reference
353/// checkpoint does).
354#[test]
355fn equals_oma_quant_absmean_where_the_rules_coincide() {
356 use crate::qwen3_moe_omega::test_support::prand;
357 for seed in 0..20u64 {
358 // Pairs (a, 4 - a) with a = 2 + m/64, m in 0..128, each with its own random sign: both
359 // are bf16 values, |a| + |4 - a| = 4, so the mean is exactly 2 (a power of two). The
360 // mean/2 boundary |w| = 1 is a = 3, m = 64: skipped.
361 let mut w = Vec::new();
362 for i in 0..2048 {
363 let m = ((prand(seed, 3 * i) + 1.0) * 64.0) as u32 % 128;
364 if m == 64 {
365 continue;
366 }
367 let a = 2.0 + m as f32 / 64.0;
368 let sign = |j| if prand(seed, j) < 0.0 { -1.0f32 } else { 1.0 };
369 w.push(sign(3 * i + 1) * a);
370 w.push(sign(3 * i + 2) * (4.0 - a));
371 }
372 let bits = bf(&w);
373 assert!(
374 bits.iter().zip(&w).all(|(&b, &x)| bf16_to_f32(b) == x),
375 "the pairs are on the bf16 grid"
376 );
377 let mut ours = vec![0i8; w.len()];
378 let s = absmean_ternarise(&bits, &mut ours).unwrap();
379 let (theirs, oma_scale) = oma_quant_absmean(&w);
380 assert_eq!(
381 (s.mean, s.w_scale, oma_scale),
382 (2.0, 2.0, 2.0),
383 "seed {seed}"
384 );
385 assert_eq!(ours, theirs, "seed {seed}");
386 assert!(ours.contains(&0) && ours.contains(&1) && ours.contains(&-1));
387 }
388 // (1) The boundary: mean 2, w = 1 is |w| = mean/2.
389 let w = [1.0f32, 3.0, -1.0, -3.0];
390 let mut ours = [0i8; 4];
391 absmean_ternarise(&bf(&w), &mut ours).unwrap();
392 let (theirs, _) = oma_quant_absmean(&w);
393 assert_eq!(ours, [0, 1, 0, -1]);
394 assert_eq!(theirs, [1, 1, -1, -1]);
395 // (2) A mean that is not a bf16 value.
396 let w = [0.3f32, -0.3, 0.3, -0.3];
397 let s = absmean_ternarise(&bf(&w), &mut [0i8; 4]).unwrap();
398 let (_, oma_scale) =
399 oma_quant_absmean(&bf(&w).iter().map(|&b| bf16_to_f32(b)).collect::<Vec<_>>());
400 assert_eq!(oma_scale, 0.30078125);
401 assert_eq!(s.w_scale, 0.30078125);
402 let w = [0.1f32, -0.2, 0.3, -0.45];
403 let s = absmean_ternarise(&bf(&w), &mut [0i8; 4]).unwrap();
404 let wf: Vec<f32> = bf(&w).iter().map(|&b| bf16_to_f32(b)).collect();
405 let (_, oma_scale) = oma_quant_absmean(&wf);
406 assert_ne!(s.w_scale, oma_scale, "bf16 steps change the scale here");
407}
408
409// -------------------------------------------------------------------------------------------
410// The packer.
411// -------------------------------------------------------------------------------------------
412
413#[test]
414fn packs_omegas_trit_code_sixteen_per_word() {
415 let mut trits = vec![0i8; 32];
416 trits[0] = 1; // bits 0..1 = 0b01
417 trits[1] = -1; // bits 2..3 = 0b10
418 trits[15] = -1; // bits 30..31 = 0b10
419 trits[16] = 1; // second word, bits 0..1
420 let mut words = [0u32; 2];
421 pack_trits(&trits, 32, &mut words).unwrap();
422 assert_eq!(words, [0b1001 | (0b10 << 30), 0b01]);
423 // Every word decodes back.
424 let m = HostTernMatrix::new(
425 1,
426 32,
427 words.to_vec(),
428 vec![TernSegment {
429 part: TernPart::O,
430 rows: 1,
431 scale_bf16: f32_to_bf16(1.0),
432 }],
433 )
434 .unwrap();
435 assert_eq!(m.row(0), trits);
436 assert_eq!(stored_row(&m, 0), trits);
437 assert!(pack_trits(&trits, 24, &mut words).is_err());
438 assert!(pack_trits(&trits, 32, &mut [0u32; 3]).is_err());
439}
440
441#[test]
442fn trit_grid_is_validated_no_0b11() {
443 assert_eq!(
444 find_invalid_code(&[0x9999_9999, 0x5555_5555, 0xaaaa_aaaa]),
445 None
446 );
447 assert_eq!(find_invalid_code(&[0, 0b11 << 6]), Some((1, 3)));
448 let seg = |rows| TernSegment {
449 part: TernPart::O,
450 rows,
451 scale_bf16: f32_to_bf16(0.5),
452 };
453 // 2 rows of 32 trits = 4 words; word 3 trit 5 is row 1 column 21.
454 let mut words = vec![0u32; 4];
455 check_ternary_upload(2, 32, &words, &[seg(2)]).unwrap();
456 words[3] = 0b11 << 10;
457 let e = check_ternary_upload(2, 32, &words, &[seg(2)]).unwrap_err();
458 assert!(e.contains("row 1 column 21") && e.contains("0b11"), "{e}");
459 words[3] = 0;
460 assert!(check_ternary_upload(2, 32, &words[..3], &[seg(2)]).is_err());
461 assert!(check_ternary_upload(2, 32, &words, &[seg(1)])
462 .unwrap_err()
463 .contains("cover 1 rows"));
464 let zero = TernSegment {
465 scale_bf16: 0,
466 ..seg(2)
467 };
468 assert!(check_ternary_upload(2, 32, &words, &[zero])
469 .unwrap_err()
470 .contains("finite and positive"));
471 let nan = TernSegment {
472 scale_bf16: 0x7fc0,
473 ..seg(2)
474 };
475 assert!(check_ternary_upload(2, 32, &words, &[nan]).is_err());
476 // The host matrix refuses the same way.
477 words[0] = 0b11;
478 assert!(HostTernMatrix::new(2, 32, words, vec![seg(2)]).is_err());
479}
480
481#[test]
482fn host_gemv_is_the_exact_ternary_sum() {
483 use crate::qwen3_moe_omega::test_support::prand;
484 let (n, k) = (48, 64);
485 let trits: Vec<i8> = (0..n * k)
486 .map(|i| (prand(7, i) * 1.5).round() as i8)
487 .collect();
488 let mut words = vec![0u32; n * k / 16];
489 pack_trits(&trits, k, &mut words).unwrap();
490 let m = HostTernMatrix::new(
491 n,
492 k,
493 words,
494 vec![TernSegment {
495 part: TernPart::Down,
496 rows: n,
497 scale_bf16: f32_to_bf16(1.0),
498 }],
499 )
500 .unwrap();
501 let x: Vec<i8> = (0..k).map(|i| (prand(8, i) * 127.0) as i8).collect();
502 let mut acc = vec![0i32; n];
503 m.gemv_i8(&x, &mut acc).unwrap();
504 for r in 0..n {
505 let want: i32 = (0..k).map(|c| trits[r * k + c] as i32 * x[c] as i32).sum();
506 assert_eq!(acc[r], want, "row {r}");
507 }
508 assert!(m.gemv_i8(&x[..k - 1], &mut acc).is_err());
509}
510
511// -------------------------------------------------------------------------------------------
512// The 8-bit word table.
513// -------------------------------------------------------------------------------------------
514
515#[test]
516fn fp8_table_is_the_omega_study_rule() {
517 let (n, k) = (128, 256);
518 let mut t = vec![0u16; n * k];
519 // Block (0, 0): amax 448 -> scale 1.0; values land on e4m3 codes directly.
520 t[0] = f32_to_bf16(448.0);
521 t[1] = f32_to_bf16(-1.0);
522 t[2] = f32_to_bf16(-0.0);
523 t[3] = f32_to_bf16(1.0625); // between 1.0 and 1.125: a tie, to the even code (1.0)
524 // Block (0, 1) stays all zero: scale 1.0, codes 0.
525 let (mut w, mut s) = (vec![0xffu8; n * k], vec![0u16; 2]);
526 build_fp8_table(&t, n, k, &mut w, &mut s).unwrap();
527 assert_eq!(s, [f32_to_bf16(1.0), f32_to_bf16(1.0)]);
528 assert_eq!(&w[..4], &[0x7e, 0xb8, 0x00, 0x38]);
529 assert!(w[128..256].iter().all(|&b| b == 0));
530 // amax 1.0: scale bf16(1/448) = 0.002227783203125; 1.0 / scale = 448.88 saturates at 448.
531 let mut t2 = vec![0u16; n * k];
532 t2[0] = f32_to_bf16(1.0);
533 build_fp8_table(&t2, n, k, &mut w, &mut s).unwrap();
534 assert_eq!(bf16_to_f32(s[0]), 73.0 / 32768.0);
535 assert_eq!(w[0], 0x7e);
536 // Shape and NaN refusals.
537 assert!(build_fp8_table(&t, n, k + 1, &mut w, &mut s).is_err());
538 t[5] = 0x7fc0;
539 assert!(build_fp8_table(&t, n, k, &mut w, &mut s)
540 .unwrap_err()
541 .contains("element 5"));
542}
543
544// -------------------------------------------------------------------------------------------
545// The loader on the tiny model.
546// -------------------------------------------------------------------------------------------
547
548#[test]
549fn tiny_load_shapes_byte_counts_and_order() {
550 let up = RecordingTernUploader::keeping();
551 let (w, report) = load_tiny(&up).unwrap();
552 let c = tiny_config();
553 assert_eq!(report.uploads, 4 * c.layers + 1);
554 assert_eq!(report.resident_bytes, c.model_resident_bytes());
555 // 2 layers x (qkv 512x256 + o 256x256 + gate_up 768x256 + down 256x384) / 4 + 7 scales x 2,
556 // plus the 256x256 e4m3 table and its 2x2 scales.
557 let per_layer = (512 * 256 + 256 * 256 + 768 * 256 + 256 * 384) / 4 + 14;
558 assert_eq!(report.resident_bytes, 2 * per_layer + 256 * 256 + 8);
559 assert_eq!(
560 report.host_bytes,
561 2 * 256 * 256 + 4 * 256 + 2 * 4 * (256 + 256 + 256 + 384)
562 );
563 assert_eq!(w.host_bytes(), report.host_bytes);
564 assert_eq!(report.scales.len(), 2);
565 let recs = up.records.lock().unwrap();
566 let order: Vec<_> = recs.iter().map(|r| (r.layer, r.what, r.n, r.k)).collect();
567 use TernTensor::*;
568 assert_eq!(
569 order,
570 [
571 (Some(0), Some(Qkv), 512, 256),
572 (Some(0), Some(O), 256, 256),
573 (Some(0), Some(GateUp), 768, 256),
574 (Some(0), Some(Down), 256, 384),
575 (Some(1), Some(Qkv), 512, 256),
576 (Some(1), Some(O), 256, 256),
577 (Some(1), Some(GateUp), 768, 256),
578 (Some(1), Some(Down), 256, 384),
579 (None, None, 256, 256),
580 ]
581 );
582 assert_eq!(w.embed_row(5).unwrap().len(), 256);
583 assert!(w.embed_row(256).is_err());
584}
585
586#[test]
587fn byte_test_passes_and_stacks_trits_and_scales_q_k_v_and_gate_up() {
588 let up = RecordingTernUploader::keeping();
589 let (w, report) = load_tiny(&up).unwrap();
590 byte_test(&up, &w).unwrap();
591 // One scale per projection, in stacking order, each its own value.
592 let segs = w.layers[0].qkv.segments();
593 let parts: Vec<_> = segs.iter().map(|s| (s.part, s.rows)).collect();
594 assert_eq!(
595 parts,
596 [(TernPart::Q, 256), (TernPart::K, 128), (TernPart::V, 128)]
597 );
598 let gu: Vec<_> = w.layers[0]
599 .gate_up
600 .segments()
601 .iter()
602 .map(|s| (s.part, s.rows))
603 .collect();
604 assert_eq!(gu, [(TernPart::Gate, 384), (TernPart::Up, 384)]);
605 let sc = report.scales[0];
606 assert!(sc[0].w_scale != sc[1].w_scale && sc[1].w_scale != sc[2].w_scale);
607 assert!(sc[4].w_scale != sc[5].w_scale);
608 for (seg, s) in segs.iter().zip(&sc[..3]) {
609 assert_eq!(seg.scale_bf16, s.w_scale_bf16());
610 }
611}
612
613#[test]
614fn negative_control_kv_row_swap_fails_the_byte_test() {
615 let up = RecordingTernUploader::swapping_kv_rows(&tiny_config());
616 let (w, _) = load_tiny(&up).unwrap();
617 let e = byte_test(&up, &w).unwrap_err();
618 assert!(e.contains("qkv") && e.contains("stored row 256"), "{e}");
619}
620
621#[test]
622fn negative_control_plane_swap_fails_the_byte_test() {
623 let up = RecordingTernUploader::with(TernMutant::PlaneSwap);
624 let (w, _) = load_tiny(&up).unwrap();
625 let e = byte_test(&up, &w).unwrap_err();
626 assert!(e.contains("stored row 0"), "{e}");
627}
628
629#[test]
630fn negative_control_kv_scale_swap_fails_the_byte_test() {
631 let up = RecordingTernUploader::with(TernMutant::SwapKvScales);
632 let (w, _) = load_tiny(&up).unwrap();
633 let e = byte_test(&up, &w).unwrap_err();
634 assert!(e.contains("segment K") && e.contains("scale"), "{e}");
635}
636
637#[test]
638fn negative_control_word_table_byte_flip_fails_the_byte_test() {
639 let up = RecordingTernUploader::with(TernMutant::FlipTableByte);
640 let (w, _) = load_tiny(&up).unwrap();
641 let e = byte_test(&up, &w).unwrap_err();
642 assert!(e.contains("table"), "{e}");
643}
644
645#[test]
646fn negative_control_input_post_norm_swap_fails_the_byte_test() {
647 let up = RecordingTernUploader::keeping();
648 let (mut w, _) = load_tiny(&up).unwrap();
649 byte_test(&up, &w).unwrap();
650 let l = &mut w.layers[1];
651 std::mem::swap(&mut l.input_norm, &mut l.post_norm);
652 let e = byte_test(&up, &w).unwrap_err();
653 assert!(e.contains("model.layers.1.input_layernorm.weight"), "{e}");
654}
655
656#[test]
657fn malformed_or_empty_eos_lists_are_refused_by_name() {
658 let gen = |eos: serde_json::Value| {
659 let mut g: serde_json::Value = serde_json::from_str(BITNET_2B4T_GENERATION).unwrap();
660 g["eos_token_id"] = eos;
661 BitNetConfig::from_json(BITNET_2B4T_CONFIG, Some(&g.to_string()))
662 };
663 assert_refused(
664 gen(serde_json::json!(["128001"])),
665 &["generation_config.json eos_token_id", "128001"],
666 );
667 assert_refused(
668 gen(serde_json::json!("eot")),
669 &["generation_config.json eos_token_id"],
670 );
671 assert_refused(gen(serde_json::json!([])), &["eos_token_id", "empty"]);
672 assert_refused(
673 variant(|o| {
674 o.insert("eos_token_id".into(), serde_json::json!(-1));
675 }),
676 &["eos_token_id", "-1"],
677 );
678 assert_eq!(
679 gen(serde_json::json!(128009)).unwrap().eos_token_ids,
680 [128009]
681 );
682}
683
684#[test]
685fn unexpected_or_missing_tensors_are_refused_by_name() {
686 let c = tiny_config();
687 assert_eq!(real_config().tensor_names().len(), 332);
688 let base = tensors(&c);
689 for (label, edit, needle) in [
690 ("bias", 0, "model.layers.0.self_attn.q_proj.bias"),
691 ("scale", 1, "model.layers.1.mlp.down_proj.weight_scale"),
692 (
693 "missing",
694 2,
695 "model.layers.1.self_attn.attn_sub_norm.weight",
696 ),
697 ] {
698 let dir = scratch(&format!("names-{label}"));
699 let mut all = base.clone();
700 match edit {
701 0 | 1 => {
702 let last = all[all.len() - 1].clone();
703 all.push((needle.to_string(), last.1, last.2, last.3));
704 }
705 _ => all.retain(|t| t.0 != needle),
706 }
707 write_checkpoint_of(&dir, &c, all).unwrap();
708 let e = load_bitnet_omega(&dir, &RecordingTernUploader::record_only(), &mut |_| {})
709 .unwrap_err();
710 assert!(
711 e.contains("checkpoint tensors refused") && e.contains(needle),
712 "{label}: {e}"
713 );
714 std::fs::remove_dir_all(&dir).unwrap();
715 }
716}
717
718#[test]
719fn tiny_round_trip_from_disk_equals_memory() {
720 let c = tiny_config();
721 let dir = scratch("roundtrip");
722 write_checkpoint(&dir, &c).unwrap();
723 assert_eq!(BitNetConfig::from_checkpoint(&dir).unwrap(), c);
724 let disk_up = RecordingTernUploader::keeping();
725 let (disk, _) = load_bitnet_omega(&dir, &disk_up, &mut |_| {}).unwrap();
726 let mem_up = RecordingTernUploader::keeping();
727 let (mem, _) = load_tiny(&mem_up).unwrap();
728 // The disk load passes the byte test against the file itself.
729 let mut file = SafetensorsFile::open(&dir.join("model.safetensors")).unwrap();
730 check_upload_bytes(&c, &mut file, &disk_up.records.lock().unwrap()).unwrap();
731 assert_eq!(disk.embed_bf16, mem.embed_bf16);
732 assert_eq!(disk.final_norm, mem.final_norm);
733 let (dr, mr) = (
734 disk_up.records.lock().unwrap(),
735 mem_up.records.lock().unwrap(),
736 );
737 for (a, b) in dr.iter().zip(mr.iter()) {
738 assert_eq!(a.segments, b.segments);
739 match (&a.matrix, &b.matrix) {
740 (Some(x), Some(y)) => assert_eq!(x.words(), y.words()),
741 _ => {
742 let (x, y) = (a.table.as_ref().unwrap(), b.table.as_ref().unwrap());
743 assert_eq!((x.weights(), x.scales()), (y.weights(), y.scales()));
744 }
745 }
746 }
747 std::fs::remove_dir_all(&dir).unwrap();
748}
749
750fn load_err(edit: impl FnOnce(&mut MemorySource)) -> String {
751 let c = tiny_config();
752 let mut m = memory_source(&c);
753 edit(&mut m);
754 load_bitnet_omega_from(&c, &mut m, &RecordingTernUploader::keeping(), &mut |_| {}).unwrap_err()
755}
756
757#[test]
758fn bad_checkpoints_are_refused_by_name() {
759 let q = TernPart::K.tensor_name(1);
760 // A tensor stored in another dtype.
761 let e = load_err(|m| {
762 let t = m.tensors.get_mut(&q).unwrap();
763 t.0 = "F16".into();
764 });
765 assert!(e.contains(&q) && e.contains("F16"), "{e}");
766 // A NaN weight.
767 let e = load_err(|m| {
768 let t = m.tensors.get_mut(&q).unwrap();
769 t.2[6] = 0xc0;
770 t.2[7] = 0x7f;
771 });
772 assert!(e.contains(&q) && e.contains("weight 3"), "{e}");
773 // A missing sub-norm.
774 let sub = "model.layers.0.mlp.ffn_sub_norm.weight";
775 let e = load_err(|m| {
776 m.tensors.remove(sub);
777 });
778 assert!(e.contains(sub), "{e}");
779 // An untied head in a tied checkpoint.
780 let e = load_err(|m| {
781 let embed = m.tensors["model.embed_tokens.weight"].clone();
782 m.tensors.insert("lm_head.weight".into(), embed);
783 });
784 assert!(e.contains("lm_head.weight"), "{e}");
785 // A wrong shape.
786 let e = load_err(|m| {
787 m.tensors.get_mut(&q).unwrap().1 = vec![256, 128];
788 });
789 assert!(e.contains(&q), "{e}");
790}
791
792// -------------------------------------------------------------------------------------------
793// Memory: the RSS gate, measured.
794// -------------------------------------------------------------------------------------------
795
796/// Fills every read with a finite pattern (0x3c bytes: bf16 0x3c3c, about 0.0115), so a
797/// full-width layer loads without a checkpoint on disk.
798struct PatternSource;
799
800impl TensorSource for PatternSource {
801 fn read_into(
802 &mut self,
803 _: &str,
804 dtype: &str,
805 _: &[usize],
806 dst: &mut [u8],
807 ) -> Result<(), String> {
808 assert_eq!(dtype, "BF16");
809 dst.fill(0x3c);
810 Ok(())
811 }
812 fn dtype_of(&mut self, name: &str) -> Result<Option<String>, String> {
813 Ok((name != "lm_head.weight").then(|| "BF16".into()))
814 }
815}
816
817/// Three layers at the 2B-4T widths with a 16k vocabulary (embedding 84 MB).
818fn rss_config() -> BitNetConfig {
819 let mut c = real_config();
820 c.layers = 3;
821 c.vocab = 16384;
822 (c.bos_token_id, c.eos_token_ids) = (1, vec![2]);
823 c
824}
825
826const RSS_CHILD_ENV: &str = "AIEN_BITNET_RSS_CHILD";
827const RSS_CHILD_TEST: &str = "bitnet_omega::tests::rss_probe_child";
828
829/// The child side of [`measured_peak_growth_in_child`]; does nothing unless
830/// `AIEN_BITNET_RSS_CHILD=<streaming|f32image|f32qkv>` is set, then prints `BITNET-RSS-GROWTH <bytes>`.
831#[test]
832#[ignore = "child process of the measured peak RSS gate; started by it"]
833fn rss_probe_child() {
834 let Ok(case) = std::env::var(RSS_CHILD_ENV) else {
835 return;
836 };
837 let up = match case.as_str() {
838 "streaming" => RecordingTernUploader::record_only(),
839 "f32image" => RecordingTernUploader::keeping_f32_image(),
840 "f32qkv" => RecordingTernUploader {
841 keep: Keep::F32CopyOf(TernTensor::Qkv),
842 ..Default::default()
843 },
844 other => panic!("unknown case {other}"),
845 };
846 if std::fs::write("/proc/self/clear_refs", "5").is_err() {
847 println!("BITNET-RSS-GROWTH skipped");
848 return;
849 }
850 let before = crate::qwen3_moe_omega::current_rss_bytes().unwrap();
851 let (w, report) =
852 load_bitnet_omega_from(&rss_config(), &mut PatternSource, &up, &mut |_| {}).unwrap();
853 drop(w);
854 println!(
855 "BITNET-RSS-GROWTH {}",
856 report.peak_rss_bytes.unwrap().saturating_sub(before)
857 );
858}
859
860fn measured_peak_growth_in_child(case: &str) -> Option<u64> {
861 let out = std::process::Command::new(std::env::current_exe().unwrap())
862 .args([
863 RSS_CHILD_TEST,
864 "--ignored",
865 "--exact",
866 "--nocapture",
867 "--test-threads=1",
868 ])
869 .env(RSS_CHILD_ENV, case)
870 .output()
871 .unwrap();
872 let stdout = String::from_utf8_lossy(&out.stdout);
873 assert!(
874 out.status.success(),
875 "RSS child {case} failed:\n{stdout}\n{}",
876 String::from_utf8_lossy(&out.stderr)
877 );
878 let value = stdout
879 .lines()
880 .find_map(|l| l.split_once("BITNET-RSS-GROWTH ").map(|(_, v)| v.trim()))
881 .unwrap_or_else(|| panic!("RSS child {case} printed no measurement:\n{stdout}"));
882 (value != "skipped").then(|| value.parse().unwrap())
883}
884
885/// The memory gate measured: three full-width layers must raise peak RSS by at most the
886/// embedding plus the larger loader phase ([`bitnet_loader_transient_bytes`]) plus 24 MB, so a
887/// per-layer leak or one stray f32 copy of a matrix shows. Controls, each must break the same
888/// bound: an uploader that keeps an f32 image of every matrix and of the table (what a naive
889/// host reference would hold), and one that keeps an f32 copy of layer 0's qkv only (39 MB).
890#[test]
891fn measured_peak_rss_is_the_embedding_plus_the_buffers() {
892 let c = rss_config();
893 // Slack 24 MB: below the 39 MB of one stray f32 copy of qkv, the second-smallest matrix.
894 let bound = (c.embed_host_bytes() + bitnet_loader_transient_bytes(&c) + (24 << 20)) as u64;
895 let Some(streaming) = measured_peak_growth_in_child("streaming") else {
896 assert!(
897 std::env::var_os("CI").is_none(),
898 "no /proc/self/clear_refs under CI: the measured peak RSS gate cannot run"
899 );
900 println!("no /proc/self/clear_refs: measured peak RSS check skipped");
901 return;
902 };
903 println!("BITNET-RSS streaming growth {streaming} bound {bound}");
904 assert!(
905 streaming <= bound,
906 "streaming load grew peak RSS by {streaming}, bound {bound}"
907 );
908 for case in ["f32image", "f32qkv"] {
909 let grown = measured_peak_growth_in_child(case).unwrap();
910 println!("BITNET-RSS {case} control growth {grown} bound {bound}");
911 assert!(
912 grown > bound,
913 "control {case}: grew peak RSS by only {grown}, bound {bound}"
914 );
915 }
916}
917
918// -------------------------------------------------------------------------------------------
919// The real checkpoint (host only, ignored by default).
920// -------------------------------------------------------------------------------------------
921
922fn real_dir() -> std::path::PathBuf {
923 std::env::var_os("AIEN_BITNET_DIR")
924 .map(std::path::PathBuf::from)
925 .unwrap_or_else(|| Path::new(env!("HOME")).join("models/BitNet-b1.58-2B-4T-bf16"))
926}
927
928/// The reference int2 checkpoint's stored scales (spec 6 step 2, read from
929/// `converted/model_state_int2.pt`; printed there rounded to 6 decimals from exact bf16):
930/// `[layer][q, k, v, o, gate, up, down]`.
931const SPEC_SCALES: [(usize, [f32; 7]); 3] = [
932 (
933 0,
934 [
935 1.21875, 1.804688, 2.296875, 0.960938, 1.554688, 1.828125, 2.15625,
936 ],
937 ),
938 (
939 15,
940 [1.6875, 2.71875, 4.5, 2.8125, 2.171875, 2.125, 2.609375],
941 ),
942 (
943 29,
944 [
945 1.125, 1.648438, 1.78125, 0.957031, 2.828125, 2.609375, 2.28125,
946 ],
947 ),
948];
949
950/// The real BitNet 2B-4T master through the streaming loader and the record-only fake: sha256
951/// pinned, per-tensor bytes, total resident, peak RSS, wall time, and the 21 scales the spec
952/// lists from the reference int2 checkpoint. Run with
953/// `cargo test -p aien-inference-abi --release --lib bitnet_omega::tests::real_bitnet -- --ignored --nocapture --test-threads=1`
954/// (`AIEN_BITNET_DIR` overrides `~/models/BitNet-b1.58-2B-4T-bf16`).
955#[test]
956#[ignore = "reads the 4.8 GB BitNet 2B-4T master"]
957fn real_bitnet_streaming_load_host_only() {
958 let dir = real_dir();
959 let sha = sha256_file(&dir.join("model.safetensors")).unwrap();
960 assert_eq!(sha, BITNET_2B4T_SAFETENSORS_SHA256, "not the pinned master");
961 println!("BITNET-LOAD safetensors_sha256={sha}");
962 assert_eq!(
963 checkpoint_tensor_names(&dir).unwrap().len(),
964 332,
965 "spec 1.1: 332 tensors"
966 );
967 let rss_before = crate::qwen3_moe_omega::current_rss_bytes().unwrap();
968 let up = RecordingTernUploader::record_only();
969 let (w, report) = load_bitnet_omega(&dir, &up, &mut |_| {}).unwrap();
970 let c = &w.config;
971 assert_eq!(*c, real_config());
972 for what in TernTensor::ALL {
973 let (n, k) = c.shape(what);
974 println!(
975 "BITNET-LOAD tensor {:<8} [{n}][{k}] bytes_each={} count={}",
976 what.name(),
977 c.ternary_bytes(what),
978 c.layers
979 );
980 }
981 let peak = report.peak_rss_bytes.unwrap();
982 println!(
983 "BITNET-LOAD layout={TERN_LAYOUT_ID} resident_bytes={} uploads={} host_bytes={} embed_bytes={} \
984 transient_bytes={} rss_before={rss_before} peak_rss={peak} peak_over_start={} seconds={:.2}",
985 report.resident_bytes,
986 report.uploads,
987 report.host_bytes,
988 c.embed_host_bytes(),
989 report.transient_bytes,
990 peak - rss_before,
991 report.seconds
992 );
993 for (l, s) in report.scales.iter().enumerate() {
994 let v: Vec<String> = s.iter().map(|x| format!("{}", x.w_scale)).collect();
995 println!(
996 "BITNET-SCALES layer {l} q,k,v,o,gate,up,down = {}",
997 v.join(",")
998 );
999 }
1000 // About 0.85 GB on the device (design calc:f4fe034c; exact count calc:f379a7e8).
1001 assert_eq!(report.resident_bytes, 849_387_060);
1002 assert_eq!(report.uploads, 4 * 30 + 1);
1003 assert!(
1004 (peak - rss_before) as usize
1005 <= c.embed_host_bytes() + bitnet_loader_transient_bytes(c) + (64 << 20),
1006 "peak RSS grew {} bytes",
1007 peak - rss_before
1008 );
1009 for (layer, want) in SPEC_SCALES {
1010 for (j, (got, want)) in report.scales[layer].iter().zip(want).enumerate() {
1011 assert!(
1012 (got.w_scale - want).abs() <= 1e-6,
1013 "layer {layer} part {j}: our scale {} is not the reference {want}",
1014 got.w_scale
1015 );
1016 }
1017 }
1018}
1019
1020/// Informational, test tool only: how many of our trits agree with Microsoft's I2_S gguf
1021/// (parsed here, nothing of theirs is run). Prints `BITNET-GGUF` lines per projection kind and
1022/// in total, for Q and K both in checkpoint row order and in the interleaved-RoPE row order,
1023/// with the gguf block size that decodes (128 or 64). Run like the test above
1024/// (`AIEN_BITNET_GGUF` overrides `~/models/BitNet-b1.58-2B-4T/ggml-model-i2_s.gguf`).
1025#[test]
1026#[ignore = "reads the 4.8 GB master and the 1.2 GB gguf"]
1027fn real_gguf_trit_agreement() {
1028 let gguf = std::env::var_os("AIEN_BITNET_GGUF")
1029 .map(std::path::PathBuf::from)
1030 .unwrap_or_else(|| {
1031 Path::new(env!("HOME")).join("models/BitNet-b1.58-2B-4T/ggml-model-i2_s.gguf")
1032 });
1033 let sha = sha256_file(&gguf).unwrap();
1034 println!("BITNET-GGUF sha256={sha}");
1035 let header = super::gguf_ref::read_header(&gguf).unwrap();
1036 let up = RecordingTernUploader::keeping();
1037 let (w, report) = load_bitnet_omega(&real_dir(), &up, &mut |_| {}).unwrap();
1038 let c = &w.config;
1039 let hd = c.head_dim;
1040 let gguf_name = |part: TernPart, l: usize| {
1041 let n = match part {
1042 TernPart::Q => "attn_q",
1043 TernPart::K => "attn_k",
1044 TernPart::V => "attn_v",
1045 TernPart::O => "attn_output",
1046 TernPart::Gate => "ffn_gate",
1047 TernPart::Up => "ffn_up",
1048 TernPart::Down => "ffn_down",
1049 };
1050 format!("blk.{l}.{n}.weight")
1051 };
1052 // Block size: whichever decodes layer 0 q closer to ours.
1053 let mut totals: std::collections::BTreeMap<&str, (u64, u64, u64)> = Default::default();
1054 let mut block = 0usize;
1055 for l in 0..c.layers {
1056 for what in TernTensor::ALL {
1057 let m = w.layers[l].matrix(what);
1058 let rec_words = up.records.lock().unwrap()[l * 4 + what as usize]
1059 .matrix
1060 .clone()
1061 .unwrap();
1062 let k = m.k();
1063 let mut row0 = 0;
1064 for (si, (part, rows)) in c.parts(what).into_iter().enumerate() {
1065 let t = &header[&gguf_name(part, l)];
1066 let ours: Vec<i8> = (0..rows).flat_map(|r| rec_words.row(row0 + r)).collect();
1067 if block == 0 {
1068 let agree = |b| {
1069 let (g, _) = super::gguf_ref::read_i2s(&gguf, t, b).unwrap();
1070 g.iter().zip(&ours).filter(|(a, b)| a == b).count()
1071 };
1072 let (a128, a64) = (agree(128), agree(64));
1073 println!(
1074 "BITNET-GGUF block choice: agree@128={a128} agree@64={a64} of {}",
1075 ours.len()
1076 );
1077 block = if a128 >= a64 { 128 } else { 64 };
1078 }
1079 let (g, gscale) = super::gguf_ref::read_i2s(&gguf, t, block).unwrap();
1080 let count = |perm: bool| {
1081 let mut same = 0u64;
1082 for r in 0..rows {
1083 // Interleaved order: gguf row j of a head is HF row (j % 2) * hd/2 + j / 2.
1084 let src = if perm {
1085 let (h, j) = (r / hd, r % hd);
1086 h * hd + (j % 2) * (hd / 2) + j / 2
1087 } else {
1088 r
1089 };
1090 same += g[r * k..(r + 1) * k]
1091 .iter()
1092 .zip(&ours[src * k..(src + 1) * k])
1093 .filter(|(a, b)| a == b)
1094 .count() as u64;
1095 }
1096 same
1097 };
1098 let plain = count(false);
1099 let permuted = if matches!(part, TernPart::Q | TernPart::K) {
1100 count(true)
1101 } else {
1102 plain
1103 };
1104 let e = totals.entry(part.name()).or_default();
1105 e.0 += plain;
1106 e.1 += permuted;
1107 e.2 += (rows * k) as u64;
1108 if l == 0 {
1109 println!(
1110 "BITNET-GGUF layer 0 {} gguf_scale={gscale} our_w_scale={} plain={plain} rope_interleaved={permuted} of {}",
1111 part.name(),
1112 report.scales[0][[0, 1, 2, 3, 4, 5, 6][match what {
1113 TernTensor::Qkv => si,
1114 TernTensor::O => 3,
1115 TernTensor::GateUp => 4 + si,
1116 TernTensor::Down => 6,
1117 }]]
1118 .w_scale,
1119 rows * k
1120 );
1121 }
1122 row0 += rows;
1123 }
1124 }
1125 }
1126 let (mut best, mut all) = (0u64, 0u64);
1127 for (part, (plain, permuted, n)) in &totals {
1128 println!("BITNET-GGUF {part}: plain={plain} rope_interleaved={permuted} of {n}");
1129 best += plain.max(permuted);
1130 all += n;
1131 }
1132 println!(
1133 "BITNET-GGUF block={block} total_agree={best} of {all} disagree={}",
1134 all - best
1135 );
1136 // What NOTES.md states from this run: at least 97 % agree overall (measured 97.2514 %,
1137 // calc:736bea70), the I2_S block is 128, and Q and K agree in checkpoint row order, not in
1138 // the interleaved-RoPE order (the gguf keeps the Hugging Face rows).
1139 assert_eq!(block, 128);
1140 assert!(
1141 best * 100 >= all * 97,
1142 "agreement {best} of {all} is under 97 %"
1143 );
1144 for part in ["q", "k"] {
1145 let (plain, permuted, _) = totals[part];
1146 assert!(
1147 plain > permuted,
1148 "{part}: plain {plain} not above interleaved {permuted}"
1149 );
1150 }
1151}