Rust comments that named scripts/offline/*, gen_goldens.py, oracle/gen_*.{sh,cpp,py}, build_oracle.sh and similar retired generators now say where the data
came from (the Original's code, Strata 41cf05a0) or drop the sentence. The path/generator text of seven generated fixtures (sampler_oracle.json, sampling_keys.json,
memory_plan_golden.json, rope_golden.json, cvec_oracle.json, stra161 fixtures.json, commentary-tool-prompt.json) is reworded; no test reads those fields and no pin
covers their bytes. cmd_time/doc.rs: the two path texts in the format string; its lines are re-broken so they stay within 120 columns (the string is unchanged
otherwise). Comment-only except those data/string spots; no behaviour change.
260 lines
10 KiB
Rust
260 lines
10 KiB
Rust
//! Unit tests of the native pack: the refusal of NVFP4 experts, the expert tables reproduced from the Python golden,
|
|
//! the native PLE key encodings and the F16 and BF16 rounding against numpy and gguf-py.
|
|
|
|
use super::*;
|
|
|
|
fn index_summary() -> gguf::Summary {
|
|
gguf::Summary {
|
|
tensors: 4,
|
|
metadata: 0,
|
|
architecture: None,
|
|
split_no: None,
|
|
split_count: None,
|
|
split_tensors_count: None,
|
|
data_start: 0,
|
|
file_size: 0,
|
|
types: Default::default(),
|
|
}
|
|
}
|
|
|
|
/// One layer of expert tensors of `kind`, the way a GGUF index lists them (no file behind it).
|
|
fn one_layer(kind: u32) -> Vec<Shard> {
|
|
let tensor = |name: &str, dimensions: Vec<u64>, bytes: u64, kind: u32| gguf::TensorInfo {
|
|
name: name.to_owned(),
|
|
dimensions,
|
|
kind,
|
|
offset: 0,
|
|
bytes,
|
|
};
|
|
vec![Shard {
|
|
path: PathBuf::from("m.gguf"),
|
|
index: gguf::TensorIndex {
|
|
summary: index_summary(),
|
|
tensors: vec![
|
|
tensor("blk.0.ffn_gate_inp.weight", vec![64, 4], 1024, 0),
|
|
tensor("blk.0.ffn_gate_exps.weight", vec![64, 64, 4], 4096, kind),
|
|
tensor("blk.0.ffn_up_exps.weight", vec![64, 64, 4], 4096, kind),
|
|
tensor("blk.0.ffn_down_exps.weight", vec![64, 64, 4], 4096, kind),
|
|
],
|
|
},
|
|
}]
|
|
}
|
|
|
|
/// Strata 0.1.50 packs NVFP4 experts with a scale tail this packer does not write: it refuses them instead of
|
|
/// writing a pack
|
|
/// whose experts the engine would read without their scales.
|
|
#[test]
|
|
fn nvfp4_experts_are_refused_and_other_experts_are_laid_out() {
|
|
let error = expert_layout(&one_layer(40)).err().expect("NVFP4 is refused");
|
|
assert!(error.to_string().contains("NVFP4 experts"), "{error}");
|
|
let shards = one_layer(21);
|
|
let layout = expert_layout(&shards).expect("IQ3_S experts");
|
|
assert_eq!(layout.n_expert, 4);
|
|
assert!(layout.text.starts_with("# strata native experts v3:"));
|
|
}
|
|
|
|
/// `iq_pack.py` `NATIVE_PLE_KEY` = {Q2_0, Q8_0, IQ3_XXS, IQ4_XS} (Strata 0.1.50, #381); any other quantized key is
|
|
/// converted.
|
|
#[test]
|
|
fn the_native_ple_key_encodings_are_the_originals() {
|
|
for (kind, native) in
|
|
[(42, true), (8, true), (18, true), (23, true), (21, false), (14, false), (12, false), (16, false)]
|
|
{
|
|
assert_eq!(native_ple_key(kind), native, "kind {kind}");
|
|
}
|
|
}
|
|
|
|
/// Numpy (`astype(float16)`) and gguf-py (`BF16.quantize_blocks`) answers for 4096 f32 bit patterns, from
|
|
/// the Original's offline tooling (Strata 41cf05a0). The packer's F32 -> F16 / BF16 helpers must match bit for bit.
|
|
#[test]
|
|
fn f16_and_bf16_rounding_match_numpy_and_gguf_py() {
|
|
let vectors = include_bytes!("../../tests/fixtures/offline/f16_bf16_vectors.golden");
|
|
assert_eq!(vectors.len() % 8, 0);
|
|
let mut checked = 0;
|
|
for record in vectors.as_chunks::<8>().0 {
|
|
let bits = u32::from_le_bytes(record[0..4].try_into().unwrap());
|
|
let f16 = u16::from_le_bytes(record[4..6].try_into().unwrap());
|
|
let bf16 = u16::from_le_bytes(record[6..8].try_into().unwrap());
|
|
let value = f32::from_bits(bits);
|
|
if value.is_finite() {
|
|
// the packer refuses non-finite inputs before rounding; NaN payloads are not compared
|
|
assert_eq!(kar_codec::f32_to_f16_bits(value), f16, "f16 of {bits:#010x}");
|
|
}
|
|
assert_eq!(bf16_round_nearest_even(value), bf16, "bf16 of {bits:#010x}");
|
|
checked += 1;
|
|
}
|
|
assert!(checked >= 4000);
|
|
}
|
|
|
|
struct Golden {
|
|
header: String,
|
|
name: String,
|
|
experts: u64,
|
|
total: u64,
|
|
rows: Vec<Vec<String>>,
|
|
}
|
|
|
|
fn parse_golden(text: &str) -> Golden {
|
|
let header = text.lines().next().unwrap().to_owned();
|
|
let after = |marker: &str| {
|
|
header
|
|
.split(marker)
|
|
.nth(1)
|
|
.unwrap()
|
|
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.' && c != '-')
|
|
.next()
|
|
.unwrap()
|
|
.to_owned()
|
|
};
|
|
Golden {
|
|
name: after("offsets in "),
|
|
experts: after("n_expert ").parse().unwrap(),
|
|
total: after("total ").parse().unwrap(),
|
|
rows: text.lines().skip(1).map(|l| l.split(' ').map(str::to_owned).collect()).collect(),
|
|
header,
|
|
}
|
|
}
|
|
|
|
const HIDDEN: u64 = 2560;
|
|
|
|
/// The shard files (name and tensors) of the rebuilt model; shard 0 is the golden's own file.
|
|
struct Files {
|
|
names: Vec<String>,
|
|
tensors: Vec<Vec<gguf::TensorInfo>>,
|
|
}
|
|
|
|
impl Files {
|
|
/// The index of the shard file `name`, added when new.
|
|
fn at(&mut self, name: &str) -> usize {
|
|
if let Some(i) = self.names.iter().position(|n| n == name) {
|
|
return i;
|
|
}
|
|
self.names.push(name.to_owned());
|
|
self.tensors.push(Vec::new());
|
|
self.names.len() - 1
|
|
}
|
|
|
|
fn into_shards(self) -> Vec<Shard> {
|
|
self.names
|
|
.into_iter()
|
|
.zip(self.tensors)
|
|
.map(|(name, tensors)| Shard {
|
|
path: PathBuf::from(name),
|
|
index: gguf::TensorIndex {
|
|
summary: gguf::Summary {
|
|
tensors: tensors.len() as u64,
|
|
metadata: 0,
|
|
architecture: Some("qwen4exp".into()),
|
|
split_no: None,
|
|
split_count: None,
|
|
split_tensors_count: None,
|
|
data_start: 0,
|
|
file_size: 0,
|
|
types: BTreeMap::new(),
|
|
},
|
|
tensors,
|
|
},
|
|
})
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
/// The three expert roles of a layer as `(role, kind, dimensions, bytes)`, from the elements per expert `x`.
|
|
fn role_shapes(row: &[String], x: u64, experts: u64) -> [(&'static str, u32, Vec<u64>, u64); 3] {
|
|
let (gu, d): (u32, u32) = (row[1].parse().unwrap(), row[2].parse().unwrap());
|
|
let (ge, gb) = gguf::block_geometry(gu).unwrap();
|
|
let (de, db) = gguf::block_geometry(d).unwrap();
|
|
let ff = x / HIDDEN;
|
|
[
|
|
("gate", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts),
|
|
("up", gu, vec![HIDDEN, ff, experts], x / ge * gb * experts),
|
|
("down", d, vec![ff, HIDDEN, experts], x / de * db * experts),
|
|
]
|
|
}
|
|
|
|
/// The elements per expert (`HIDDEN * FF`) that make a blob of `blob` bytes for the gu/d kinds of `row`.
|
|
fn elements_per_expert(row: &[String], layer: u64, blob: u64) -> u64 {
|
|
let (gu, d): (u32, u32) = (row[1].parse().unwrap(), row[2].parse().unwrap());
|
|
let (ge, gb) = gguf::block_geometry(gu).unwrap();
|
|
let (de, db) = gguf::block_geometry(d).unwrap();
|
|
// blob = 2 * X * gb/ge + X * db/de for X = HIDDEN * FF elements per expert
|
|
let numerator = blob * ge * de;
|
|
let denominator = 2 * gb * de + db * ge;
|
|
assert_eq!(numerator % denominator, 0, "layer {layer}");
|
|
let x = numerator / denominator;
|
|
assert_eq!(x % HIDDEN, 0);
|
|
x
|
|
}
|
|
|
|
/// The shard files of the three roles of a row: its shard column, one name for all or `gate,up,down`.
|
|
fn role_files(row: &[String]) -> Vec<String> {
|
|
let column = row.get(8).cloned().unwrap_or_default();
|
|
if column.contains(',') { column.split(',').map(str::to_owned).collect() } else { vec![column; 3] }
|
|
}
|
|
|
|
/// Add the router and the three expert tensors of one golden row to the shard files.
|
|
fn add_golden_layer(files: &mut Files, experts: u64, row: &[String]) {
|
|
let layer: u64 = row[0].parse().unwrap();
|
|
let blob: u64 = row[4].parse().unwrap();
|
|
let offsets: Vec<u64> = row[5..8].iter().map(|v| v.parse().unwrap()).collect();
|
|
let names = role_files(row);
|
|
let x = elements_per_expert(row, layer, blob);
|
|
files.tensors[0].push(gguf::TensorInfo {
|
|
name: format!("blk.{layer}.ffn_gate_inp.weight"),
|
|
dimensions: vec![HIDDEN, experts],
|
|
kind: 0,
|
|
offset: 0,
|
|
bytes: HIDDEN * experts * 4,
|
|
});
|
|
for (i, (role, kind, dimensions, bytes)) in role_shapes(row, x, experts).into_iter().enumerate() {
|
|
let s = if names[i].is_empty() { 0 } else { files.at(&names[i]) };
|
|
files.tensors[s].push(gguf::TensorInfo {
|
|
name: format!("blk.{layer}.ffn_{role}_exps.weight"),
|
|
dimensions,
|
|
kind,
|
|
offset: offsets[i],
|
|
bytes,
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Rebuild the tensor directories that produce a real layer table, then run the packer's own layout code.
|
|
/// Gate/up/down element counts follow from the blob size and the two quantization geometries; the hidden size
|
|
/// is the model's 2560.
|
|
fn shards_for(golden: &Golden) -> Vec<Shard> {
|
|
let mut files = Files { names: vec![golden.name.clone()], tensors: vec![Vec::new()] };
|
|
for row in &golden.rows {
|
|
add_golden_layer(&mut files, golden.experts, row);
|
|
}
|
|
files.into_shards()
|
|
}
|
|
|
|
/// The six real per-layer expert tables shipped with Strata (IQ3_S, IQ3_XXS, IQ2_XS, Q2_0 packs, the coder
|
|
/// IQ1_M pack, and Swift's IQ2_XS whose layers 13-47 live in the second shard): the Rust layout reproduces
|
|
/// every row byte for byte. The v2 files predate the shard column; their header wording differs, their rows
|
|
/// and totals do not.
|
|
#[test]
|
|
fn real_golden_expert_tables_are_reproduced() {
|
|
let goldens = [
|
|
include_str!("../../../third_party/strata/tests/data/native_experts/iq3_s.txt"),
|
|
include_str!("../../../third_party/strata/tests/data/native_experts/iq3_xxs.txt"),
|
|
include_str!("../../../third_party/strata/tests/data/native_experts/iq2_xs.txt"),
|
|
include_str!("../../../third_party/strata/tests/data/native_experts/q2_0.txt"),
|
|
include_str!("../../../third_party/strata/tests/data/native_experts/coder-iq1_m.txt"),
|
|
include_str!("../../../third_party/strata/tests/data/native_experts/swift-iq2_xs.txt"),
|
|
];
|
|
for text in goldens {
|
|
let golden = parse_golden(text);
|
|
let shards = shards_for(&golden);
|
|
let layout = expert_layout(&shards).unwrap();
|
|
assert_eq!(layout.n_expert, golden.experts);
|
|
assert_eq!(layout.total, golden.total, "{}", golden.name);
|
|
let produced = layout.text.lines().skip(1).collect::<Vec<_>>();
|
|
let wanted = text.lines().skip(1).collect::<Vec<_>>();
|
|
assert_eq!(produced, wanted, "{}", golden.name);
|
|
if golden.header.contains("native experts v3") || golden.header.contains("native experts v4") {
|
|
assert_eq!(layout.text, text, "{}", golden.name);
|
|
}
|
|
}
|
|
}
|