use frink_gguf::GgmlType;
use super::arch::QuantArch;
use super::model_shape::ModelShape;
use super::policy::{allows_quantization, first_unused_kv_layer, unused_kv_type, Target};
use super::recipe::Recipe;
use super::recipe_golden::{assert_frink_chooses_what_llama_quantize_chose, rows};
const MIXES: [Target; 6] = [
Target::Q4_K_S,
Target::Q4_K_M,
Target::Q5_K_S,
Target::Q5_K_M,
Target::Q6_K,
Target::Q8_0,
];
#[derive(Clone, Copy)]
enum Rule {
Arch,
NLayerAll,
Is70b,
Other,
}
macro_rules! golden {
($name:literal, $rule:expr) => {
(
$name,
include_str!(concat!("goldens/", $name, ".golden")),
$rule,
)
};
}
const GOLDENS: &[(&str, &str, Rule)] = &[
golden!("keep_list", Rule::Other),
golden!("glm5_next", Rule::Arch),
golden!("raon1", Rule::Arch),
golden!("muse_spark", Rule::Arch),
golden!("limite", Rule::Arch),
golden!("inkling2", Rule::Arch),
golden!("zaya1", Rule::Arch),
golden!("hy_v4_flash", Rule::Arch),
golden!("metis16", Rule::Arch),
golden!("kimi_k31", Rule::Arch),
golden!("xing4_0", Rule::Arch),
golden!("vllm_decision2", Rule::Arch),
golden!("falcon", Rule::Arch),
golden!("graniteswitch", Rule::NLayerAll),
golden!("nanbeige", Rule::NLayerAll),
golden!("inkling2_loop", Rule::NLayerAll),
golden!("llama_70b", Rule::Is70b),
golden!("llama_65b", Rule::Is70b),
golden!("llama_8x80", Rule::Other),
golden!("apertus_70b", Rule::Is70b),
golden!("jais2_70b", Rule::Is70b),
golden!("moe_bad_layer", Rule::Other),
golden!("shared_kv", Rule::Other),
];
struct Header {
arch: &'static str,
keys: Vec<(&'static str, Option<u64>)>,
refused: Option<&'static str>,
}
fn header(text: &'static str) -> Header {
let mut h = Header {
arch: "",
keys: Vec::new(),
refused: None,
};
for line in text.lines().filter_map(|l| l.strip_prefix("# ")) {
let (k, v) = line.split_once(' ').expect("header line");
match k {
"arch" => h.arch = v,
"refused" => h.refused = Some(v),
_ => h.keys.push((k, v.parse().ok())),
}
}
h
}
impl Header {
fn key(&self, k: &str) -> Option<u64> {
self.keys
.iter()
.find(|(n, _)| *n == k)
.and_then(|(_, v)| *v)
}
fn shape(&self) -> ModelShape {
ModelShape::from_metadata(self.arch, |k| self.key(k)).expect("a shape llama.cpp loads")
}
}
#[test]
fn frink_chooses_the_pins_type_for_every_architecture_rule() {
for (name, text, _) in GOLDENS {
let h = header(text);
let shape = h.shape();
if let Some(why) = h.refused {
let tensors: Vec<(String, Vec<u64>, GgmlType)> = rows::<6>(text)
.into_iter()
.map(|r| (r.name.to_string(), r.shape, GgmlType::F32))
.collect();
assert!(tensors.is_empty(), "{name}: a refused golden has no rows");
let tensors = vec![(
"blk.5.ffn_down.weight".to_string(),
vec![512, 32],
GgmlType::F32,
)];
let err = Recipe::resolve_all(Target::Q4_K_M, shape, &tensors, |_, _| true)
.expect_err(name)
.to_string();
assert!(err.contains(why), "{name}: {err} does not quote {why}");
continue;
}
let n = assert_frink_chooses_what_llama_quantize_chose(text, MIXES, shape, GgmlType::F32);
assert!(n > 0, "{name}: nothing quantized");
}
}
#[test]
fn each_golden_turns_red_without_its_rule() {
for (name, text, rule) in GOLDENS {
let h = header(text);
let real = h.shape();
let without = match rule {
Rule::Arch => ModelShape {
arch: QuantArch::Other,
..real
},
Rule::NLayerAll => ModelShape {
n_layer: h.key(&format!("{}.block_count", h.arch)).unwrap() as usize,
..real
},
Rule::Is70b => ModelShape {
is_70b: !real.is_70b,
..real
},
Rule::Other => continue,
};
assert_ne!(
choices(text, real),
choices(text, without),
"{name}: the golden cannot tell the rule apart"
);
assert_eq!(choices(text, real), golden_choices(text), "{name}");
}
}
fn choices(text: &'static str, shape: ModelShape) -> Vec<Option<GgmlType>> {
let rows = rows::<6>(text);
let tensors: Vec<(String, Vec<u64>, GgmlType)> = rows
.iter()
.map(|r| (r.name.to_string(), r.shape.clone(), GgmlType::F32))
.collect();
let mut out = Vec::new();
for mix in MIXES {
let got = Recipe::resolve_all(mix, shape, &tensors, |n, s| {
allows_quantization(shape.arch, n, s).is_none()
})
.unwrap();
out.extend(rows.iter().map(|r| got.get(r.name).copied()));
}
out
}
fn golden_choices(text: &'static str) -> Vec<Option<GgmlType>> {
let rows = rows::<6>(text);
(0..MIXES.len())
.flat_map(|col| rows.iter().map(move |r| r.chosen.map(|c| c[col])))
.collect()
}
#[test]
fn the_shared_kv_golden_is_q4_0_where_frink_refuses() {
let (_, text, _) = GOLDENS.iter().find(|g| g.0 == "shared_kv").unwrap();
let h = header(text);
let from = first_unused_kv_layer(
h.key("llama.block_count"),
h.key("llama.attention.shared_kv_layers"),
);
let mut q4_0 = 0;
for r in rows::<6>(text) {
let Some(chosen) = r.chosen else { continue };
let want = unused_kv_type(r.name, r.shape[0], from);
if chosen.contains(&GgmlType::Q4_0) {
assert!(chosen.iter().all(|t| *t == GgmlType::Q4_0), "{}", r.name);
assert_eq!(want, Some(GgmlType::Q4_0), "{}", r.name);
q4_0 += 1;
} else {
assert_eq!(want, None, "{}", r.name);
}
}
assert_eq!(q4_0, 4, "two layers' attn_k and attn_v");
}