Files
leleka/crates/model-format/tests/kar_kernel_model/mod.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 c969796616 test(kar): windows beyond 2^32 elements decode against a direct u64 format oracle
A virtual 8.6e9-element expert bank (group 96, section above 4 GiB) is never
allocated: archive bytes are a hash of the absolute offset, the planner and
kernel model decode first/middle/last-expert windows and the final partial
group, and every element is compared bit for bit with a per-element decode
written straight from the format definition. No defect found.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 16:57:38 +02:00

943 lines
36 KiB
Rust

//! Randomized proof that the kernel's index math reproduces the CPU decode
//! oracle (a literal transcription of `kar_codec::decode_range` fed by the
//! inspector's `decode_record_range` byte arithmetic) on synthetic records.
//! Nothing here touches a GPU, a physical archive, or the model-quality gate.
use super::*;
// ------------------------------------------------------------------ rng
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
// xorshift64*; deterministic, fixed seeds only.
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn range(&mut self, lo: u64, hi_inclusive: u64) -> u64 {
lo + self.below(hi_inclusive - lo + 1)
}
fn finite_f16(&mut self) -> u16 {
loop {
let bits = (self.next() >> 20) as u16;
if !nonfinite_f16(bits) {
return bits;
}
}
}
}
// -------------------------------------------------------------- fixture
const SECTION_OFFSET: u64 = 256;
struct Fixture {
archive: Vec<u8>,
record: KarNestedRecord,
n_padded: usize,
}
fn round16(value: u64) -> u64 {
round_up(value, 16)
}
/// Build a section laid out exactly as the inspector's formulas require, with
/// random finite scales/books/planes and random garbage in every padding gap.
fn fixture(
rng: &mut Rng,
name: &str,
dims: &[u64],
group: u32,
stored: u8,
min: u8,
max: u8,
) -> Fixture {
let n_elements: u64 = dims.iter().product();
let n_padded = n_elements.div_ceil(u64::from(group)) * u64::from(group);
let scales_bytes = n_padded / u64::from(group) * 2;
let books_offset = round16(SECTION_OFFSET + scales_bytes);
let books_bytes = (1u64 << (u32::from(stored) + 2)) - 4;
let planes_offset = round16(books_offset + books_bytes);
let stride = round16(n_padded / 32 * 4);
let section_end = planes_offset + u64::from(stored) * stride;
let mut archive: Vec<u8> = (0..section_end).map(|_| rng.next() as u8).collect();
for s in 0..(scales_bytes / 2) as usize {
let at = SECTION_OFFSET as usize + 2 * s;
archive[at..at + 2].copy_from_slice(&rng.finite_f16().to_le_bytes());
}
for e in 0..(books_bytes / 2) as usize {
let at = books_offset as usize + 2 * e;
archive[at..at + 2].copy_from_slice(&rng.finite_f16().to_le_bytes());
}
// Plane words stay random, padding bytes after them stay garbage.
let record = KarNestedRecord {
name: name.into(),
dimensions: dims.to_vec(),
n_elements,
n_padded,
group,
planes_stored: stored,
planes_min: min,
planes_max: max,
nesting: 0,
section_offset: SECTION_OFFSET,
section_bytes: section_end - SECTION_OFFSET,
scales_offset: SECTION_OFFSET,
scales_bytes,
books_offset,
books_bytes,
planes_offset,
plane_stride_bytes: stride as u32,
};
record.validate().unwrap();
Fixture {
archive,
record,
n_padded: n_padded as usize,
}
}
// --------------------------------------------------------------- oracle
/// `control-plane/src/kar_codec.rs::decode_range`, transcribed.
fn oracle_decode_range(
scales: &[u16],
book: &[u16],
planes: &[&[u32]],
group: u16,
start: usize,
output: &mut [f32],
) -> std::result::Result<(), String> {
let group = usize::from(group);
if group == 0
|| group > 1024
|| group % 32 != 0
|| !(1..=16).contains(&planes.len())
|| book.len() != 1usize << planes.len()
{
return Err("invalid KAR decoder geometry or book".into());
}
let padded = scales.len() * group;
let end = start + output.len();
if end > padded || planes.iter().any(|plane| plane.len() != padded / 32) {
return Err("KAR decoder range or plane length is invalid".into());
}
if scales[start / group..end.div_ceil(group)]
.iter()
.any(|bits| bits & 0x7c00 == 0x7c00)
|| book.iter().any(|bits| bits & 0x7c00 == 0x7c00)
{
return Err("KAR decoder received non-finite f16 data".into());
}
for (relative, value) in output.iter_mut().enumerate() {
let position = start + relative;
let mut index = 0usize;
for plane in planes {
let bit = (plane[position / 32] >> (position % 32)) & 1;
index = (index << 1) | bit as usize;
}
*value = f16_to_f32(book[index]) * f16_to_f32(scales[position / group]);
}
Ok(())
}
/// `model-format/src/kar.rs::decode_record_range` byte arithmetic, over an
/// in-memory archive instead of a file.
fn oracle(
archive: &[u8],
r: &KarNestedRecord,
level: u8,
start: usize,
count: usize,
) -> std::result::Result<Vec<f32>, String> {
let group_size = r.group as usize;
let end = start + count;
let padded = r.n_padded as usize;
let base_group = start / group_size;
let end_group = end.div_ceil(group_size);
let base_element = base_group * group_size;
let local_padded = (end_group - base_group) * group_size;
assert!(base_element + local_padded <= padded);
let region = |offset: u64, len: usize| &archive[offset as usize..offset as usize + len];
let scales: Vec<u16> = region(
r.scales_offset + base_group as u64 * 2,
(end_group - base_group) * 2,
)
.as_chunks::<2>()
.0
.iter()
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect();
let book_offset = r.books_offset + (1u64 << (u32::from(level) + 1)) - 4;
let book: Vec<u16> = region(book_offset, (1usize << level) * 2)
.as_chunks::<2>()
.0
.iter()
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect();
let plane_bytes = local_padded / 32 * 4;
let plane_base = (base_element / 32 * 4) as u64;
let planes: Vec<Vec<u32>> = (0..u64::from(level))
.map(|plane| {
region(
r.planes_offset + plane * u64::from(r.plane_stride_bytes) + plane_base,
plane_bytes,
)
.as_chunks::<4>()
.0
.iter()
.map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect()
})
.collect();
let refs: Vec<&[u32]> = planes.iter().map(Vec::as_slice).collect();
let mut out = vec![0f32; count];
oracle_decode_range(
&scales,
&book,
&refs,
r.group as u16,
start - base_element,
&mut out,
)?;
Ok(out)
}
fn run_kernel(f: &Fixture, level: u8, start: u64, count: u64) -> (WindowPlan, Vec<f32>, u32) {
let plan = plan_window(&f.record, level, start, count).unwrap();
let packet = stage_packet(&plan, &f.archive).unwrap();
let mut out = vec![f32::from_bits(0xdead_beef); plan.count as usize];
let status = kernel_decode(&plan.params, &packet, &mut out);
(plan, out, status)
}
fn assert_bits_eq(actual: &[f32], expected: &[f32], context: &str) {
assert_eq!(actual.len(), expected.len(), "{context}");
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
assert_eq!(a.to_bits(), e.to_bits(), "{context}: element {i}");
}
}
// ---------------------------------------------------------------- tests
#[test]
fn f16_widening_matches_exact_reference_for_every_bit_pattern() {
for bits in 0..=u16::MAX {
let sign = if bits & 0x8000 != 0 { -1.0f64 } else { 1.0 };
let exponent = i32::from((bits >> 10) & 0x1f);
let mantissa = f64::from(bits & 0x3ff);
let got = f16_to_f32(bits);
if exponent == 31 {
assert_eq!(got.is_nan(), mantissa != 0.0, "{bits:#06x}");
assert_eq!(got.is_infinite(), mantissa == 0.0, "{bits:#06x}");
assert_eq!(got.is_sign_negative(), sign < 0.0);
continue;
}
let reference = if exponent == 0 {
mantissa * 2f64.powi(-24)
} else {
(1024.0 + mantissa) * 2f64.powi(exponent - 25)
};
let want = (sign * reference) as f32; // exact: every f16 is an f32
assert_eq!(got.to_bits(), want.to_bits(), "{bits:#06x}");
}
}
#[test]
fn kernel_matches_cpu_oracle_over_random_records_levels_2_to_5() {
let mut rng = Rng(0x5eed_0001_cafe_f00d);
let groups = [32u32, 64, 96, 128, 256, 1024];
let mut cases = 0usize;
for level in MIN_LEVEL..=MAX_LEVEL {
for round in 0..60 {
let group = groups[rng.below(groups.len() as u64) as usize];
// Mix tiny, group-straddling and multi-block tensors.
let n = match round % 4 {
0 => rng.range(1, 70),
1 => rng.range(1, 3 * u64::from(group) + 5),
2 => rng.range(300, 2600),
_ => rng.range(700, 6000),
};
let stored = rng.range(u64::from(level), 5) as u8;
let min = rng.range(2, u64::from(level)) as u8;
let max = rng.range(u64::from(level), u64::from(stored)) as u8;
let f = fixture(&mut rng, "t", &[n], group, stored, min, max);
for _ in 0..12 {
let start = rng.below(n);
let count = rng.range(1, n - start);
let (plan, got, status) = run_kernel(&f, level, start, count);
assert_eq!(status, 0);
let want =
oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap();
assert_bits_eq(
&got,
&want,
&format!("L{level} g{group} n{n} start{start} count{count}"),
);
assert_eq!(plan.params.level, u32::from(level));
cases += 1;
}
}
}
assert_eq!(cases, 4 * 60 * 12);
}
#[test]
fn kernel_matches_oracle_on_alignment_edges_and_partial_last_group() {
let mut rng = Rng(0x000e_d9e5);
// n = 200 with group 96: groups of 96, 96, and a last group holding 8.
let f = fixture(&mut rng, "edge", &[200], 96, 5, 2, 5);
let n = 200u64;
let mut edges = vec![
(0, 1),
(0, 32),
(0, 33),
(31, 1),
(31, 2),
(32, 1),
(33, 63),
(63, 1),
(64, 32),
(95, 2),
(96, 96),
(191, 9),
(192, 8),
(199, 1),
(n - 1, 1),
(0, n),
];
for start in 0..n {
edges.push((start, (n - start).min(1 + start % 7)));
}
for level in MIN_LEVEL..=MAX_LEVEL {
for &(start, count) in &edges {
let (_, got, status) = run_kernel(&f, level, start, count);
assert_eq!(status, 0);
let want =
oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap();
assert_bits_eq(&got, &want, &format!("L{level} start{start} count{count}"));
}
}
}
#[test]
fn multi_block_ranges_cross_block_boundaries_exactly() {
let mut rng = Rng(0xb10c_b10c);
let n = 5 * u64::from(BLOCK_THREADS) + 77;
let f = fixture(&mut rng, "blocks", &[n], 64, 4, 2, 4);
for level in [2u8, 3, 4] {
for (start, count) in [(0u64, n), (13, n - 13), (255, 258), (256, 256), (511, 3)] {
let (plan, got, status) = run_kernel(&f, level, start, count);
assert_eq!(status, 0);
assert_eq!(plan.grid_blocks(), decode_grid(count as u32));
let want =
oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap();
assert_bits_eq(&got, &want, &format!("L{level} {start}+{count}"));
}
}
}
#[test]
fn overlay_selected_levels_decode_from_their_own_archive() {
let mut rng = Rng(0x0e71_a7e5);
// Base stores 2 planes (dial 2..=2); overlay re-encodes the same tensor
// at 4 planes (dial 3..=4). A loader picks (archive, level) per tensor.
let base = fixture(&mut rng, "w", &[777], 32, 2, 2, 2);
let overlay = fixture(&mut rng, "w", &[777], 32, 4, 3, 4);
let (_, base_out, s0) = run_kernel(&base, 2, 100, 400);
assert_eq!(s0, 0);
assert_bits_eq(
&base_out,
&oracle(&base.archive, &base.record, 2, 100, 400).unwrap(),
"base L2",
);
for level in [3u8, 4] {
let (_, out, status) = run_kernel(&overlay, level, 100, 400);
assert_eq!(status, 0);
assert_bits_eq(
&out,
&oracle(&overlay.archive, &overlay.record, level, 100, 400).unwrap(),
&format!("overlay L{level}"),
);
}
// The same level request means different things per archive's dial.
assert!(plan_window(&base.record, 3, 0, 8).is_err());
assert!(plan_window(&overlay.record, 2, 0, 8).is_err());
assert!(plan_window(&overlay.record, 5, 0, 8).is_err());
}
#[test]
fn level_bounds_dial_and_stored_planes_are_enforced() {
let mut rng = Rng(7);
let f = fixture(&mut rng, "t", &[100], 32, 4, 3, 4);
for level in [0u8, 1, 6, 8, 16, 255] {
assert_eq!(
plan_window(&f.record, level, 0, 8).unwrap_err(),
KernelModelError::Rejected("KAR GPU level must be 2..=5")
);
}
// Inside 2..=5 but below the certified dial.
assert!(plan_window(&f.record, 2, 0, 8).is_err());
// Above the planes physically stored (dial lies about max: invalid record).
let mut lying = f.record.clone();
lying.planes_max = 5;
assert!(plan_window(&lying, 5, 0, 8).is_err());
// A well-formed record whose dial allows 5 but stores only 4 is impossible;
// a stored-4 record asked for 5 is rejected before the dial check.
let mut four = fixture(&mut rng, "t", &[100], 32, 4, 2, 4);
assert_eq!(
plan_window(&four.record, 5, 0, 8).unwrap_err(),
KernelModelError::Rejected("KAR level exceeds the planes stored in the record")
);
four.record.nesting = 1;
assert_eq!(
plan_window(&four.record, 3, 0, 8).unwrap_err(),
KernelModelError::Rejected("KAR GPU decode supports top-down nesting only")
);
for level in 2..=4 {
assert!(plan_window(&f.record, level.max(3), 0, 8).is_ok());
}
}
#[test]
fn range_bounds_are_enforced_without_overflow() {
let mut rng = Rng(8);
let f = fixture(&mut rng, "t", &[100], 32, 3, 2, 3);
assert!(plan_window(&f.record, 2, 0, 100).is_ok());
assert!(plan_window(&f.record, 2, 99, 1).is_ok());
for (start, count) in [
(0u64, 0u64),
(0, 101),
(100, 1),
(99, 2),
(u64::MAX, 1),
(1, u64::MAX),
(u64::MAX - 3, 8),
(0, MAX_RANGE_ELEMENTS + 1),
] {
assert!(
plan_window(&f.record, 2, start, count).is_err(),
"{start}+{count}"
);
}
}
#[test]
fn oversize_count_is_rejected_even_when_the_tensor_is_larger() {
let mut rng = Rng(9);
// Synthetic metadata-only record: layout validates, no payload needed.
let n = MAX_RANGE_ELEMENTS + 4096;
let f = Fixture {
archive: Vec::new(),
n_padded: n as usize,
record: {
let scales_bytes = n / 32 * 2;
let books_offset = round16(SECTION_OFFSET + scales_bytes);
let books_bytes = (1u64 << 4) - 4;
let planes_offset = round16(books_offset + books_bytes);
let stride = round16(n / 32 * 4);
KarNestedRecord {
name: "big".into(),
dimensions: vec![n],
n_elements: n,
n_padded: n,
group: 32,
planes_stored: 2,
planes_min: 2,
planes_max: 2,
nesting: 0,
section_offset: SECTION_OFFSET,
section_bytes: planes_offset - SECTION_OFFSET + 2 * stride,
scales_offset: SECTION_OFFSET,
scales_bytes,
books_offset,
books_bytes,
planes_offset,
plane_stride_bytes: stride as u32,
}
},
};
let _ = (&mut rng, f.n_padded);
f.record.validate().unwrap();
assert!(plan_window(&f.record, 2, 0, MAX_RANGE_ELEMENTS).is_ok());
assert!(plan_window(&f.record, 2, 0, MAX_RANGE_ELEMENTS + 1).is_err());
// Far offsets of a >4G-element tensor stay in 64-bit until head values.
let plan = plan_window(&f.record, 2, MAX_RANGE_ELEMENTS - 100, 100).unwrap();
assert_eq!(plan.params.head32, ((MAX_RANGE_ELEMENTS - 100) % 32) as u32);
}
#[test]
fn plan_ranges_are_in_bounds_aligned_disjoint_and_minimal() {
let mut rng = Rng(0x91a7);
for level in MIN_LEVEL..=MAX_LEVEL {
for _ in 0..80 {
let group = [32u32, 64, 96, 256][rng.below(4) as usize];
let n = rng.range(1, 4000);
let f = fixture(&mut rng, "t", &[n], group, level, 2, level);
let start = rng.below(n);
let count = rng.range(1, n - start);
let plan = plan_window(&f.record, level, start, count).unwrap();
let r = &f.record;
let section_end = r.section_offset + r.section_bytes;
let mut spans: Vec<(u64, u64)> = Vec::new();
for range in plan.ranges() {
// Source lies inside this record's section and inside the image.
assert!(range.archive_offset >= r.section_offset);
assert!(range.archive_offset + range.len <= section_end);
assert!(range.archive_offset + range.len <= f.archive.len() as u64);
// Destination lies inside the packet; regions are 16-byte aligned.
assert!(range.packet_offset + range.len <= plan.packet_bytes());
assert_eq!(range.packet_offset % 16, 0);
spans.push((range.packet_offset, range.packet_offset + range.len));
}
spans.sort_unstable();
assert!(spans.windows(2).all(|w| w[0].1 <= w[1].0), "overlap");
assert_eq!(plan.planes.len(), usize::from(level));
assert!(decode_params_valid(&plan.params));
// Only what the range touches is staged.
let words = (start + count).div_ceil(32) - start / 32;
let groups = (start + count).div_ceil(u64::from(group)) - start / u64::from(group);
assert_eq!(plan.params.window_words as u64, words);
assert_eq!(plan.params.window_groups as u64, groups);
assert_eq!(
plan.staged_source_bytes(),
(1u64 << level) * 2 + groups * 2 + u64::from(level) * words * 4
);
}
}
}
#[test]
fn corrupt_launch_parameters_fail_closed_before_any_write() {
let mut rng = Rng(0xbad);
let f = fixture(&mut rng, "t", &[500], 64, 3, 2, 3);
let plan = plan_window(&f.record, 3, 37, 301).unwrap();
let packet = stage_packet(&plan, &f.archive).unwrap();
let good = plan.params;
let mutations: Vec<(&str, DecodeParams)> = vec![
("level 1", DecodeParams { level: 1, ..good }),
("level 6", DecodeParams { level: 6, ..good }),
(
"level above staged",
DecodeParams {
staged_planes: 2,
..good
},
),
("count 0", DecodeParams { count: 0, ..good }),
(
"count too big",
DecodeParams {
count: (MAX_RANGE_ELEMENTS + 1) as u32,
..good
},
),
("group 0", DecodeParams { group: 0, ..good }),
("group 33", DecodeParams { group: 33, ..good }),
("head32 32", DecodeParams { head32: 32, ..good }),
(
"head_group",
DecodeParams {
head_group: good.group,
..good
},
),
(
"too few words",
DecodeParams {
window_words: good.window_words - 1,
..good
},
),
(
"too few groups",
DecodeParams {
window_groups: good.window_groups - 1,
..good
},
),
(
"stride < words",
DecodeParams {
plane_stride_words: 4,
..good
},
),
(
"misaligned planes",
DecodeParams {
planes_offset: good.planes_offset + 2,
..good
},
),
(
"packet too small",
DecodeParams {
packet_bytes: good.packet_bytes - 4,
..good
},
),
(
"scales outside",
DecodeParams {
scales_offset: good.packet_bytes,
..good
},
),
];
for (name, bad) in mutations {
let mut out = vec![f32::from_bits(0xdead_beef); good.count.max(1) as usize + 8];
let before = out.clone();
let short_packet = &packet[..(bad.packet_bytes.min(good.packet_bytes)) as usize];
let status = kernel_decode(&bad, short_packet, &mut out);
assert_eq!(status, STATUS_BAD_ARGUMENT, "{name}");
assert_eq!(
out.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
before.iter().map(|v| v.to_bits()).collect::<Vec<_>>(),
"{name} wrote output"
);
}
// The unmodified parameters pass.
let mut out = vec![0f32; good.count as usize];
assert_eq!(kernel_decode(&good, &packet, &mut out), 0);
}
#[test]
fn nonfinite_scales_and_books_flag_exactly_when_the_oracle_rejects() {
let mut rng = Rng(0xf1f1);
let mut f = fixture(&mut rng, "t", &[256], 32, 3, 2, 3);
let r = f.record.clone();
// Poison group 5 (elements 160..192) with an Inf scale.
let at = (r.scales_offset + 5 * 2) as usize;
f.archive[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes());
// Ranges avoiding group 5 are clean and match the oracle.
for (start, count) in [(0u64, 160u64), (192, 64), (100, 60)] {
let (_, out, status) = run_kernel(&f, 3, start, count);
assert_eq!(status, 0, "{start}+{count}");
let want = oracle(&f.archive, &r, 3, start as usize, count as usize).unwrap();
assert_bits_eq(&out, &want, "clean range");
}
// Any range touching group 5 is flagged, and the oracle errors too.
for (start, count) in [(160u64, 32u64), (159, 2), (0, 256), (191, 1)] {
let (_, out, status) = run_kernel(&f, 3, start, count);
assert_eq!(status, STATUS_NONFINITE_INPUT, "{start}+{count}");
assert!(oracle(&f.archive, &r, 3, start as usize, count as usize).is_err());
assert!(out.iter().any(|v| v.is_nan()));
}
// A NaN in the level-2 table flags a level-2 decode of any range, but a
// level-3 decode (different table) is unaffected.
let mut g = fixture(&mut rng, "t", &[256], 32, 3, 2, 3);
let gr = g.record.clone();
let at = gr.books_offset as usize; // first entry of the level-1 table
let level2 = gr.books_offset as usize + 2 * 2; // first entry of level-2 table
g.archive[level2..level2 + 2].copy_from_slice(&0x7e01u16.to_le_bytes());
let _ = at;
let (_, _, status) = run_kernel(&g, 2, 0, 8);
assert_eq!(status, STATUS_NONFINITE_INPUT);
assert!(oracle(&g.archive, &gr, 2, 0, 8).is_err());
let (_, out, status) = run_kernel(&g, 3, 0, 8);
assert_eq!(status, 0);
assert_bits_eq(&out, &oracle(&g.archive, &gr, 3, 0, 8).unwrap(), "L3 clean");
}
#[test]
fn rows_and_experts_decode_like_flat_ranges_for_unaligned_row_lengths() {
let mut rng = Rng(0xe4e4);
// [cols=20, rows=7, experts=5]: rows are not word aligned.
let f = fixture(&mut rng, "experts", &[20, 7, 5], 32, 5, 2, 5);
for level in MIN_LEVEL..=MAX_LEVEL {
for expert in 0..5u64 {
let (first_row, rows) = expert_rows(&f.record, expert).unwrap();
assert_eq!((first_row, rows), (expert * 7, 7));
let plan = plan_rows(&f.record, level, first_row, rows).unwrap();
assert_eq!((plan.columns, plan.rows), (20, 7));
let packet = stage_packet(&plan.window, &f.archive).unwrap();
let mut out = vec![0f32; 140];
assert_eq!(kernel_decode(&plan.window.params, &packet, &mut out), 0);
let want = oracle(&f.archive, &f.record, level, (expert * 140) as usize, 140).unwrap();
assert_bits_eq(&out, &want, &format!("L{level} expert {expert}"));
}
}
assert!(expert_rows(&f.record, 5).is_err());
assert!(plan_rows(&f.record, 2, 34, 2).is_err()); // rows 34,35 -> 35 rows total
assert!(plan_rows(&f.record, 2, 0, 0).is_err());
assert!(plan_rows(&f.record, 2, u64::MAX, 2).is_err());
let two_d = fixture(&mut rng, "m", &[20, 7], 32, 2, 2, 2);
assert!(expert_rows(&two_d.record, 0).is_err());
}
#[test]
fn multiply_model_is_exact_for_integer_data_and_close_to_f64_otherwise() {
// Exactly representable small integers: any summation order is exact.
let (cols, rows, tokens) = (700u32, 5u32, 3u32);
let weights: Vec<f32> = (0..cols * rows).map(|i| (i % 7) as f32 - 3.0).collect();
let input: Vec<f32> = (0..cols * tokens).map(|i| (i % 5) as f32 - 2.0).collect();
let mut out = vec![0f32; (rows * tokens) as usize];
assert_eq!(
kernel_multiply(&weights, &input, cols, rows, tokens, &mut out),
0
);
for t in 0..tokens as usize {
for r in 0..rows as usize {
let exact: i64 = (0..cols as usize)
.map(|c| {
(weights[r * cols as usize + c] as i64) * (input[t * cols as usize + c] as i64)
})
.sum();
assert_eq!(out[t * rows as usize + r], exact as f32);
}
}
// Non-integer data: tolerance against an f64 reference (documented bound:
// 256-lane tree of binary32 sums stays within cols * 2^-24 relative to
// the L1 mass; this is a sanity bound, not a parity claim).
let mut rng = Rng(0x77);
let (cols, rows) = (1000u32, 4u32);
let w: Vec<f32> = (0..cols * rows)
.map(|_| (rng.below(2001) as f32 - 1000.0) / 640.0)
.collect();
let x: Vec<f32> = (0..cols)
.map(|_| (rng.below(2001) as f32 - 1000.0) / 512.0)
.collect();
let mut y = vec![0f32; rows as usize];
assert_eq!(kernel_multiply(&w, &x, cols, rows, 1, &mut y), 0);
for r in 0..rows as usize {
let (mut reference, mut mass) = (0f64, 0f64);
for c in 0..cols as usize {
let term = f64::from(w[r * cols as usize + c]) * f64::from(x[c]);
reference += term;
mass += term.abs();
}
assert!((f64::from(y[r]) - reference).abs() <= mass * f64::from(cols) * 2f64.powi(-24));
}
}
#[test]
fn multiply_model_order_is_lane_strided_then_fixed_tree() {
let big = 16_777_216.0f32; // 2^24: spacing above it is 2
// Lanes 0,1,2 hold 2^24, 2, 1. Tree: (p0 + p2) + p1 = (2^24 + 1 -> 2^24) + 2.
// Left-to-right over lanes would give (2^24 + 2) + 1 -> 2^24 + 4.
let mut out = [0f32];
assert_eq!(
kernel_multiply(&[big, 2.0, 1.0], &[1f32; 3], 3, 1, 1, &mut out),
0
);
assert_eq!(out[0], big + 2.0);
// Columns stride by 256 within a lane: lane 0 sums columns 0, 256, 512 in
// order, so 2^24 absorbs the two trailing 1.0 terms one at a time.
let mut weights = vec![0f32; 513];
weights[0] = big;
weights[256] = 1.0;
weights[512] = 1.0;
let mut out = [0f32];
assert_eq!(
kernel_multiply(&weights, &vec![1f32; 513], 513, 1, 1, &mut out),
0
);
assert_eq!(out[0], big);
}
#[test]
fn multiply_model_flags_nonfinite_and_bad_shapes() {
let mut out = [0f32; 2];
let weights = [f32::NAN, 1.0, 1.0, 1.0];
let input = [1.0, 1.0];
assert_eq!(
kernel_multiply(&weights, &input, 2, 2, 1, &mut out),
STATUS_NONFINITE_OUTPUT
);
for (cols, rows, tokens) in [(0, 2, 1), (2, 0, 1), (2, 2, 0), (2, 2, MAX_TOKENS + 1)] {
assert_eq!(
kernel_multiply(&weights, &input, cols, rows, tokens, &mut out),
STATUS_BAD_ARGUMENT
);
}
// Buffers shorter than the declared geometry are refused, not read.
assert_eq!(
kernel_multiply(&weights[..3], &input, 2, 2, 1, &mut out),
STATUS_BAD_ARGUMENT
);
}
#[test]
fn decode_then_multiply_matches_oracle_decode_then_multiply() {
let mut rng = Rng(0xd0d0);
let f = fixture(&mut rng, "ffn", &[48, 10, 3], 32, 4, 2, 4);
let x: Vec<f32> = (0..48 * 2)
.map(|_| (rng.below(65) as f32 - 32.0) / 16.0)
.collect();
for level in [2u8, 3, 4] {
let (first, rows) = expert_rows(&f.record, 2).unwrap();
let plan = plan_rows(&f.record, level, first, rows).unwrap();
let packet = stage_packet(&plan.window, &f.archive).unwrap();
let mut weights = vec![0f32; 480];
assert_eq!(kernel_decode(&plan.window.params, &packet, &mut weights), 0);
let mut got = vec![0f32; 20];
assert_eq!(kernel_multiply(&weights, &x, 48, 10, 2, &mut got), 0);
let oracle_weights = oracle(&f.archive, &f.record, level, 2 * 480, 480).unwrap();
let mut want = vec![0f32; 20];
kernel_multiply(&oracle_weights, &x, 48, 10, 2, &mut want);
assert_bits_eq(&got, &want, &format!("L{level}"));
}
}
#[test]
fn swiglu_model_matches_silu_times_up_and_flags_nonfinite() {
let gate = [0.0f32, 1.0, -1.0, 2.5, -30.0, 8.0];
let up = [3.0f32, 0.5, 2.0, -1.0, 4.0, 0.25];
let mut act = [0f32; 6];
assert_eq!(kernel_swiglu(&gate, &up, &mut act), 0);
for ((a, g), u) in act.iter().zip(gate).zip(up) {
let silu = f64::from(g) / (1.0 + (-f64::from(g)).exp());
let want = silu * f64::from(u);
assert!(
(f64::from(*a) - want).abs() <= want.abs() * 1e-6 + 1e-30,
"{g} {u}"
);
}
assert_eq!(act[0], 0.0); // silu(0) = 0
let mut one = [0f32];
assert_eq!(
kernel_swiglu(&[f32::NAN], &[1.0], &mut one),
STATUS_NONFINITE_OUTPUT
);
assert_eq!(kernel_swiglu(&[], &[], &mut one), STATUS_BAD_ARGUMENT);
assert_eq!(
kernel_swiglu(&[1.0], &[1.0, 2.0], &mut one),
STATUS_BAD_ARGUMENT
);
}
// ------------------------------------------------- records beyond 2^32 elements
/// Deterministic archive bytes for a record far too large to allocate. Scale
/// and book regions are forced finite; everything else is hash noise.
struct VirtualArchive<'a> {
r: &'a KarNestedRecord,
}
impl VirtualArchive<'_> {
fn byte(&self, offset: u64) -> u8 {
let mut h = offset.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ 0x1234_5678_9abc_def0;
h ^= h >> 29;
h = h.wrapping_mul(0xbf58_476d_1ce4_e5b9);
h ^= h >> 32;
let r = self.r;
let in_f16 = (r.scales_offset..r.scales_offset + r.scales_bytes).contains(&offset)
|| (r.books_offset..r.books_offset + r.books_bytes).contains(&offset);
let byte = h as u8;
// f16 little endian: odd offsets (relative to the region) hold the
// exponent's top bits; clearing bit 2 keeps the exponent below 31.
let relative = if offset >= r.books_offset {
offset - r.books_offset
} else {
offset - r.scales_offset
};
if in_f16 && relative % 2 == 1 {
byte & 0xbb
} else {
byte
}
}
}
impl crate::kar_levels::RangeSource for VirtualArchive<'_> {
fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> std::result::Result<(), crate::kar::KarError> {
let end = offset + out.len() as u64;
let r = self.r;
if end > r.section_offset + r.section_bytes {
return Err(crate::kar::KarError::Range("virtual read escapes the section"));
}
for (i, b) in out.iter_mut().enumerate() {
*b = self.byte(offset + i as u64);
}
Ok(())
}
}
/// Direct per-element decode from the format definition, in u64/u128 only.
fn direct_element(v: &VirtualArchive<'_>, level: u8, element: u64) -> f32 {
let r = v.r;
let mut code = 0usize;
for plane in 0..u64::from(level) {
let at = r.planes_offset
+ plane * u64::from(r.plane_stride_bytes)
+ (element / 32) * 4
+ (element % 32) / 8;
code = (code << 1) | usize::from((v.byte(at) >> (element % 8)) & 1);
}
let scale_at = r.scales_offset + 2 * (element / u64::from(r.group));
let scale = u16::from_le_bytes([v.byte(scale_at), v.byte(scale_at + 1)]);
let book_at = r.books_offset + ((1u64 << level) - 2) * 2 + 2 * code as u64;
let book = u16::from_le_bytes([v.byte(book_at), v.byte(book_at + 1)]);
f16_to_f32(book) * f16_to_f32(scale)
}
#[test]
fn windows_beyond_four_gib_elements_use_exact_u64_addressing() {
use crate::kar_levels::stage_window;
// 3-D expert bank of 4096*4096*512 = 8.6e9 elements (> 2^32), group 96 so
// group boundaries never line up with the 32-element words.
let dims = [4096u64, 4096, 512];
let n: u64 = dims.iter().product();
let group = 96u64;
let n_padded = n.div_ceil(group) * group;
let stored = 5u8;
let scales_bytes = n_padded / group * 2;
let books_offset = round_up(0x1_0000_0000 + scales_bytes, 16);
let books_bytes = (1u64 << (u32::from(stored) + 2)) - 4;
let planes_offset = round_up(books_offset + books_bytes, 16);
let stride = round_up(n_padded / 32 * 4, 16);
assert!(stride < u64::from(u32::MAX));
let record = KarNestedRecord {
name: "huge".into(),
dimensions: dims.to_vec(),
n_elements: n,
n_padded,
group: group as u32,
planes_stored: stored,
planes_min: 2,
planes_max: stored,
nesting: 0,
section_offset: 0x1_0000_0000,
section_bytes: planes_offset + u64::from(stored) * stride - 0x1_0000_0000,
scales_offset: 0x1_0000_0000,
scales_bytes,
books_offset,
books_bytes,
planes_offset,
plane_stride_bytes: stride as u32,
};
record.validate().unwrap();
assert!(n > u64::from(u32::MAX) && record.section_offset + record.section_bytes > 1 << 33);
let v = VirtualArchive { r: &record };
let mut rng = Rng(0x4b1d_f00d_0007);
let (rows, columns) = (dims[1], dims[0]);
for level in MIN_LEVEL..=MAX_LEVEL {
// First, a middle and the last expert, whole matrices are 16.7M elements
// (the launch bound), so check bounded sub-windows inside each too.
for expert in [0u64, 255, 511] {
let base = expert * rows * columns;
for _ in 0..6 {
let start = base + rng.below(rows * columns - 700);
let count = rng.range(1, 700);
let plan = plan_window(&record, level, start, count).unwrap();
assert_eq!(u64::from(plan.params.head32), start % 32);
assert_eq!(u64::from(plan.params.head_group), start % group);
assert_eq!(plan.first_word, start / 32);
assert!(plan.planes.iter().all(|p| p.archive_offset >= planes_offset));
let packet = stage_window(&v, &plan).unwrap();
let mut out = vec![f32::from_bits(0xdead_beef); count as usize];
assert_eq!(kernel_decode(&plan.params, &packet, &mut out), 0, "L{level}");
let want: Vec<f32> = (start..start + count)
.map(|e| direct_element(&v, level, e))
.collect();
assert_bits_eq(&out, &want, &format!("L{level} expert {expert} {start}+{count}"));
}
}
// The very last elements of the record (partial final group).
let plan = plan_window(&record, level, n - 5, 5).unwrap();
let packet = stage_window(&v, &plan).unwrap();
let mut out = vec![0f32; 5];
assert_eq!(kernel_decode(&plan.params, &packet, &mut out), 0);
let want: Vec<f32> = (n - 5..n).map(|e| direct_element(&v, level, e)).collect();
assert_bits_eq(&out, &want, &format!("L{level} tail"));
}
}