frink-cli 0.74.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 seven targets it writes (#750, #768).
//!
//! 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` under every target, on
//!   a llama carrying the key (`shared_kv`) and on the two architectures
//!   that write it, Gemma 3n and Gemma 4 (`gemma3n`, `gemma4`, #768).
//!
//! The recipe tests compare [`Recipe`]'s choice per tensor; the plan test
//! ([`frink_plans_the_pins_type_for_every_tensor`]) writes each golden's
//! checkpoint and compares what `frink quantize`'s planner writes, which
//! is where the shared-KV override lives.

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};
use super::{plan, GgufFile, GgufValue, GgufWriter, TensorPlan};

/// The golden's columns.
const MIXES: [Target; 7] = [
    Target::Q4_K_S,
    Target::Q4_K_M,
    Target::Q5_K_S,
    Target::Q5_K_M,
    Target::Q6_K,
    Target::Q8_0,
    Target::Q4_0,
];

/// Type columns per golden row.
const N: usize = MIXES.len();

/// 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),
    golden!("gemma3n", Rule::Other),
    golden!("gemma4", 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::<N>(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, false, &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::<N>(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, false, &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::<N>(text);
    (0..MIXES.len())
        .flat_map(|col| rows.iter().map(move |r| r.chosen.map(|c| c[col])))
        .collect()
}

/// In each shared-KV golden, the Q4_0 rows under the K-quant and Q8_0
/// targets are exactly the tensors [`unused_kv_type`] names, and those
/// are Q4_0 under every target: the last two layers' `attn_k` and
/// `attn_v`.
#[test]
fn the_shared_kv_goldens_are_q4_0_exactly_where_unused_kv_type_says() {
    for name in ["shared_kv", "gemma3n", "gemma4"] {
        let (_, text, _) = GOLDENS.iter().find(|g| g.0 == name).unwrap();
        let h = header(text);
        let from = first_unused_kv_layer(
            h.key(&format!("{}.block_count", h.arch)),
            h.key(&format!("{}.attention.shared_kv_layers", h.arch)),
        );
        let q4_0_col = MIXES.iter().position(|m| *m == Target::Q4_0).unwrap();
        let mut unused = 0;
        for r in rows::<N>(text) {
            let Some(chosen) = r.chosen else { continue };
            let want = unused_kv_type(r.name, r.shape[0], from);
            let other_q4_0 = chosen
                .iter()
                .enumerate()
                .any(|(c, t)| c != q4_0_col && *t == GgmlType::Q4_0);
            if other_q4_0 {
                assert!(
                    chosen.iter().all(|t| *t == GgmlType::Q4_0),
                    "{name}: {}",
                    r.name
                );
                assert_eq!(want, Some(GgmlType::Q4_0), "{name}: {}", r.name);
                unused += 1;
            } else {
                assert_eq!(want, None, "{name}: {}", r.name);
            }
        }
        assert_eq!(unused, 4, "{name}: two layers' attn_k and attn_v");
    }
}

/// Writes a golden's checkpoint: its architecture, its integer header
/// keys, and every row as an all-zero F32 tensor of the row's shape.
/// The planner reads names, shapes and the header, never the values.
fn golden_checkpoint(name: &str, text: &'static str) -> GgufFile {
    let h = header(text);
    let dir = std::env::temp_dir().join(format!(
        "frink-quant-golden-{name}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("src.gguf");
    let mut metadata = std::collections::BTreeMap::new();
    metadata.insert(
        "general.architecture".to_string(),
        GgufValue::String(h.arch.into()),
    );
    for (k, v) in &h.keys {
        if let Some(v) = v {
            metadata.insert(k.to_string(), GgufValue::U32(*v as u32));
        }
    }
    let rows = rows::<N>(text);
    let bytes = |r: &super::recipe_golden::Row<N>| 4 * r.shape.iter().product::<u64>() as usize;
    let entries = rows
        .iter()
        .map(|r| TensorPlan {
            name: r.name.to_string(),
            shape: r.shape.clone(),
            dtype: GgmlType::F32,
            byte_len: bytes(r),
        })
        .collect();
    let f = std::fs::File::create(&path).unwrap();
    let mut w = GgufWriter::create(std::io::BufWriter::new(f), &metadata, entries).unwrap();
    for r in &rows {
        w.write_tensor(r.name, &vec![0u8; bytes(r)]).unwrap();
    }
    w.finish().unwrap().into_inner().unwrap();
    let file = GgufFile::open(&path).unwrap();
    std::fs::remove_dir_all(&dir).ok();
    file
}

/// What `frink quantize` would WRITE for every tensor of every golden,
/// under every target, is what `llama-quantize` wrote: the mix, the
/// keep-list, and the shared-KV override the recipe tests leave out.
#[test]
fn frink_plans_the_pins_type_for_every_tensor() {
    for (name, text, _) in GOLDENS {
        if header(text).refused.is_some() {
            continue;
        }
        let file = golden_checkpoint(name, text);
        for (col, mix) in MIXES.iter().enumerate() {
            let planned =
                plan(&file, *mix, false, false).unwrap_or_else(|e| panic!("{name} {mix:?}: {e}"));
            for r in rows::<N>(text) {
                let p = planned.iter().find(|p| p.name == r.name).unwrap();
                let want = r.chosen.map_or(GgmlType::F32, |c| c[col]);
                assert_eq!(p.out_dtype, want, "{name} {mix:?}: {}", r.name);
            }
        }
    }
}