frink-cli 0.72.0

llama.cpp-style CLI for the Frink inference engine
//! What the pin's `llama-quantize` chose for one synthetic checkpoint per
//! architecture-specific rule of `src/llama-quant.cpp`, and the test that
//! frink chooses the same under all six mixes it writes (#750).
//!
//! The tables in `goldens/` are `llama-quantize --dry-run`'s printout,
//! written by `scripts/quant_recipe_goldens.py` against a `llama-quantize`
//! built from `tools/llama_cpp_pin` (the script's doc has the command).
//! Each file starts with the checkpoint's architecture and integer header
//! keys, which is what [`ModelShape::from_metadata`] reads here, so the
//! shape the test uses is derived the way `frink quantize` derives it
//! from a real file rather than spelled out by hand.
//!
//! What each golden pins, and the rule the test removes to show the
//! golden can tell it apart ([`Rule`]):
//!
//! * the keep-list's architecture blocks: `limite`, `inkling2`,
//!   `inkling2_loop`, `zaya1`, `hy_v4_flash`, `metis16`, `kimi_k31`,
//!   `glm5_next`, `xing4_0`, `raon1`, `vllm_decision2`, and the
//!   arch-independent entries new since b7650 (`keep_list`);
//! * the type rules: GLM5_NEXT's Q8_0 floor, RAON1_MINI's source
//!   precision and floors, MUSE_SPARK's Q8_0 bump, Falcon's arms;
//! * `n_layer_all`: `graniteswitch`, `nanbeige`, `inkling2_loop`;
//! * `LLM_TYPE_70B`: `llama_70b`, `apertus_70b`, `jais2_70b`, and the
//!   the llama checkpoint that is not 70B (`llama_65b`); `llama_8x80`,
//!   whose 8 experts send `attn_v` and `attn_k` to Q8_0 whatever the
//!   layer count says;
//! * `layer_info`'s `dec.blk.%d.` (`vllm_decision2`) and its refusal
//!   (`moe_bad_layer`);
//! * a shared-KV layer's Q4_0 `attn_k` / `attn_v` (`shared_kv`).

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};

/// The golden's columns.
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,
];

/// The rule a golden exists for, which the test takes away again to
/// show that the golden disagrees with frink without it.
#[derive(Clone, Copy)]
enum Rule {
    /// The architecture's keep-list block or type rules.
    Arch,
    /// `n_layer_all` widened past `block_count`.
    NLayerAll,
    /// `LLM_TYPE_70B`, or its absence on a checkpoint that looks like one.
    Is70b,
    /// A refusal or a planner override: checked on its own.
    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),
];

/// A golden's `# arch` and `# key value` header lines.
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")
    }
}

/// Every tensor of every golden gets `llama-quantize`'s type under each
/// mix, the keep-list agrees on the rest, and frink refuses the file
/// `llama-quantize` refused.
#[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");
            // The refused checkpoint's tensors are the generator's; the
            // one that trips `layer_info` is the point.
            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");
    }
}

/// Each golden disagrees with frink once the rule it was made for is
/// taken away, so it is evidence for that rule and not only for the
/// generic mix.
#[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}");
    }
}

/// frink's answer per (tensor, mix): `None` for a kept tensor.
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
}

/// The golden's answer in [`choices`]' layout.
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()
}

/// The shared-KV golden's Q4_0 rows are exactly the tensors
/// [`unused_kv_type`] names, under every mix, and the planner refuses
/// them by name because frink has no Q4_0 encoder.
#[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");
}