frink-cli 0.74.0

llama.cpp-style CLI for the Frink inference engine
//! The bits of a checkpoint's header the mix reads, as llama.cpp's loader
//! derives them (pin `ee467158`), and the `blk.%d.` scan both the mix and
//! the tensor order use.

use anyhow::{bail, Result};
use frink_gguf::GgufFile;

use super::arch::QuantArch;

/// What [`super::recipe::Recipe`] reads from the header.
///
/// A struct rather than five arguments, and built in ONE place
/// ([`ModelShape::from_metadata`]), so a field added here has to be
/// filled in by whoever adds it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModelShape {
    pub arch: QuantArch,
    /// `hparams.n_layer_all`, the denominator of every `ffn_down` /
    /// `ffn_gate` / `ffn_up` fraction (`init_quantize_state_counters`).
    /// It is `block_count` except where an architecture's
    /// `load_arch_hparams` widens it; see [`ModelShape::from_metadata`].
    pub n_layer: usize,
    /// `<arch>.expert_count`. `8` is a magic number upstream: Mixtral's
    /// `attn_v` and `attn_k` go to Q8_0.
    pub n_expert: usize,
    /// llama.cpp's `LLM_TYPE_70B`, which is a per-architecture layer
    /// count, not a parameter count.
    pub is_70b: bool,
}

impl ModelShape {
    pub fn from_header(file: &GgufFile) -> Result<ModelShape> {
        let arch = file.metadata_str("general.architecture").unwrap_or("");
        ModelShape::from_metadata(arch, |k| file.metadata_u64(k))
    }

    /// Reads the shape the way llama.cpp's loader does, from
    /// `general.architecture` and a lookup of the integer keys (`None`
    /// for an absent or non-scalar key).
    ///
    /// * `n_layer_all` is `block_count` (`llama-model.cpp:1622`), widened
    ///   by three architectures before the quantizer reads it:
    ///   `graniteswitch` adds its router layer (`granite-switch.cpp:62`),
    ///   `nanbeige` multiplies by `num_loops` (`nanbeige.cpp:31`) and
    ///   `inkling2_loop` counts its cache slots (`inkling2-loop.cpp:24`).
    /// * `LLM_TYPE_70B` is assigned from `hparams.n_layer()`, which is
    ///   `block_count - nextn_predict_layers`: 80 layers on `llama`
    ///   (`llama-embed` inherits it) when not 8 experts and `n_head !=
    ///   n_head_kv`, 80 on `deci`, `qwen2`, `olmo` and `apertus`, 68 on
    ///   `jais2`. The only thing the quantizer does with it is bump a
    ///   Q3_K / Q4_K `attn_v` to Q5_K.
    pub fn from_metadata(arch: &str, key: impl Fn(&str) -> Option<u64>) -> Result<ModelShape> {
        let k = |suffix: &str| key(&format!("{arch}.{suffix}")).map(|v| v as usize);
        let block_count = k("block_count").unwrap_or(0);
        let nextn = k("nextn_predict_layers").unwrap_or(0);
        // `n_layer()`; the loader asserts `n_layer_nextn <= n_layer_all`.
        let n_layer = block_count.saturating_sub(nextn);
        let n_expert = k("expert_count").unwrap_or(0);
        let n_head = k("attention.head_count").unwrap_or(0);
        let n_head_kv = k("attention.head_count_kv").unwrap_or(n_head);
        let n_layer_all = match arch {
            "graniteswitch" => n_layer + 1,
            "nanbeige" => match k("num_loops").unwrap_or(1) {
                0 => bail!("nanbeige.num_loops is 0; llama.cpp asserts it is at least 1"),
                1 => block_count,
                loops => n_layer * loops,
            },
            "inkling2_loop" => {
                let (Some(start), Some(end), Some(passes)) =
                    (k("loop.start"), k("loop.end"), k("loop.count"))
                else {
                    bail!(
                        "inkling2_loop needs loop.start, loop.end and loop.count to size its \
                         layers; llama.cpp does not load this file"
                    );
                };
                if passes == 0 || start >= end || end > n_layer || nextn != 0 {
                    bail!(
                        "inkling2_loop: loop core [{start}, {end}) with {passes} passes over \
                         {n_layer} layers is one llama.cpp refuses"
                    );
                }
                n_layer + (passes - 1) * (end - start)
            }
            _ => block_count,
        };
        let is_70b = match arch {
            "llama" | "llama-embed" => n_layer == 80 && n_expert != 8 && n_head != n_head_kv,
            "deci" | "qwen2" | "olmo" | "apertus" => n_layer == 80,
            "jais2" => n_layer == 68,
            _ => false,
        };
        Ok(ModelShape {
            arch: QuantArch::from_name(arch),
            n_layer: n_layer_all,
            n_expert,
            is_70b,
        })
    }
}

/// C's `sscanf(name, "<prefix>%d.", &i) == 1`: the literal prefix, then
/// `%d` (leading whitespace, an optional sign, at least one digit). The
/// trailing `.` is not needed for the conversion to count.
pub fn scan_layer(name: &str, prefix: &str) -> Option<i64> {
    let rest = name.strip_prefix(prefix)?.trim_start();
    let (sign, digits) = match rest.as_bytes().first()? {
        b'-' => (-1, &rest[1..]),
        b'+' => (1, &rest[1..]),
        _ => (1, rest),
    };
    let end = digits
        .bytes()
        .position(|b| !b.is_ascii_digit())
        .unwrap_or(digits.len());
    if end == 0 {
        return None;
    }
    digits[..end].parse::<i64>().ok().map(|v| sign * v)
}

/// llama.cpp's `weight_name_comparer` (`llama-model-loader.h:52`): the
/// order `llama_model_loader::weights_map` puts tensors in, which is the
/// order the quantizer walks them.
///
/// Layer number scanned out of `blk.%d.` first, then the whole name. The
/// layer stays at its initialiser of `-1` when the prefix does not match,
/// so every non-`blk.` tensor sorts BEFORE layer 0, in name order. It is
/// a numeric sort: `blk.10` comes after `blk.9`.
pub fn llama_cpp_weight_order(a: &str, b: &str) -> std::cmp::Ordering {
    let layer = |n: &str| scan_layer(n, "blk.").unwrap_or(-1);
    layer(a).cmp(&layer(b)).then_with(|| a.cmp(b))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn shape(arch: &str, keys: &[(&str, u64)]) -> ModelShape {
        ModelShape::from_metadata(arch, |k| {
            keys.iter()
                .find(|(n, _)| format!("{arch}.{n}") == k)
                .map(|(_, v)| *v)
        })
        .unwrap()
    }

    /// The three architectures that widen `n_layer_all`, each with the
    /// count its `load_arch_hparams` arrives at.
    #[test]
    fn n_layer_all_is_block_count_except_where_the_loader_widens_it() {
        assert_eq!(shape("llama", &[("block_count", 8)]).n_layer, 8);
        assert_eq!(shape("graniteswitch", &[("block_count", 8)]).n_layer, 9);
        assert_eq!(
            shape("nanbeige", &[("block_count", 8), ("num_loops", 2)]).n_layer,
            16
        );
        assert_eq!(shape("nanbeige", &[("block_count", 8)]).n_layer, 8);
        let loop_keys = [
            ("block_count", 8),
            ("loop.start", 2),
            ("loop.end", 6),
            ("loop.count", 3),
        ];
        assert_eq!(shape("inkling2_loop", &loop_keys).n_layer, 16);
        assert!(ModelShape::from_metadata("inkling2_loop", |_| None).is_err());
    }

    /// `LLM_TYPE_70B` per architecture, and the two llama exceptions.
    #[test]
    fn the_70b_type_follows_each_architectures_layer_switch() {
        let llama = [
            ("block_count", 80),
            ("attention.head_count", 64),
            ("attention.head_count_kv", 8),
        ];
        assert!(shape("llama", &llama).is_70b);
        assert!(shape("llama-embed", &llama).is_70b);
        let mut mha = llama;
        mha[2].1 = 64;
        assert!(!shape("llama", &mha).is_70b, "n_head == n_head_kv is 65B");
        let moe = [
            ("block_count", 80),
            ("attention.head_count", 64),
            ("attention.head_count_kv", 8),
            ("expert_count", 8),
        ];
        assert!(!shape("llama", &moe).is_70b, "8 experts take the 8x switch");
        assert!(shape("apertus", &[("block_count", 80)]).is_70b);
        assert!(shape("jais2", &[("block_count", 68)]).is_70b);
        assert!(!shape("jais2", &[("block_count", 80)]).is_70b);
        // `n_layer()` excludes the MTP layers.
        assert!(!shape("qwen2", &[("block_count", 80), ("nextn_predict_layers", 1)]).is_70b);
        assert!(shape("qwen2", &[("block_count", 81), ("nextn_predict_layers", 1)]).is_70b);
    }

    #[test]
    fn scan_layer_is_sscanf_percent_d() {
        assert_eq!(scan_layer("blk.12.attn_v.weight", "blk."), Some(12));
        assert_eq!(scan_layer("blk.12", "blk."), Some(12));
        assert_eq!(scan_layer("blk.7x.attn", "blk."), Some(7));
        assert_eq!(scan_layer("blk.-3.x", "blk."), Some(-3));
        assert_eq!(scan_layer("blk.x.attn", "blk."), None);
        assert_eq!(scan_layer("dec.blk.1.ffn", "blk."), None);
        assert_eq!(scan_layer("dec.blk.1.ffn", "dec.blk."), Some(1));
    }

    /// The numeric layer sort: plain string ordering puts `blk.10`
    /// before `blk.2`, which is invisible on a model with fewer than ten
    /// layers and wrong on every real one.
    #[test]
    fn tensors_are_walked_in_llama_cpps_weights_map_order_not_the_files() {
        let mut names = vec![
            "blk.10.ffn_down.weight",
            "token_embd.weight",
            "blk.2.attn_v.weight",
            "output_norm.weight",
            "blk.2.attn_k.weight",
            "blk.1.ffn_down.weight",
        ];
        names.sort_by(|a, b| llama_cpp_weight_order(a, b));
        assert_eq!(
            names,
            vec![
                "output_norm.weight",
                "token_embd.weight",
                "blk.1.ffn_down.weight",
                "blk.2.attn_k.weight",
                "blk.2.attn_v.weight",
                "blk.10.ffn_down.weight",
            ]
        );
    }
}