frink-cli 0.73.0

llama.cpp-style CLI for the Frink inference engine
//! The architectures `src/llama-quant.cpp` names, and the three rules in
//! `llama_tensor_get_type_impl` that only one architecture takes (pin
//! `ee467158`, `:542-567` and `:745-773`).
//!
//! `llama-quant.cpp` branches on `qs.model.arch` in two places: the
//! keep-list ([`super::policy::allows_quantization`]) and the type
//! choice. Every architecture it names is a variant here, so a rule keyed
//! on one is a `match` arm the compiler sees, not a string compared in
//! two files. An architecture the quantizer never names is
//! [`QuantArch::Other`]: it takes the generic rules.

use frink_gguf::GgmlType;

use super::policy::Target;
use super::recipe::Role;

/// An architecture `llama-quant.cpp` treats differently, spelled as
/// `general.architecture` spells it (`src/llama-arch.cpp`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantArch {
    /// `falcon`: four arms of the mix.
    Falcon,
    /// `glm5-next`: a Q8_0 floor and a keep-list.
    Glm5Next,
    /// `raon1` (`LLM_ARCH_RAON1_MINI`): source precision, floors and a
    /// keep-list.
    Raon1Mini,
    /// `muse-spark`: a Q8_0 bump.
    MuseSpark,
    Limite,
    /// `inkling2` and `inkling2_loop` share one keep-list.
    Inkling2,
    Inkling2Loop,
    Zaya1,
    HyV4Flash,
    Metis16,
    KimiK31,
    Xing40,
    VllmDecision2,
    /// Every architecture `llama-quant.cpp` does not name.
    Other,
}

impl QuantArch {
    pub fn from_name(arch: &str) -> QuantArch {
        match arch {
            "falcon" => QuantArch::Falcon,
            "glm5-next" => QuantArch::Glm5Next,
            "raon1" => QuantArch::Raon1Mini,
            "muse-spark" => QuantArch::MuseSpark,
            "limite" => QuantArch::Limite,
            "inkling2" => QuantArch::Inkling2,
            "inkling2_loop" => QuantArch::Inkling2Loop,
            "zaya1" => QuantArch::Zaya1,
            "hy_v4_flash" => QuantArch::HyV4Flash,
            "metis16" => QuantArch::Metis16,
            "kimi-k31" => QuantArch::KimiK31,
            "xing4_0" => QuantArch::Xing40,
            "vllm-decision2" => QuantArch::VllmDecision2,
            _ => QuantArch::Other,
        }
    }
}

/// ggml's `bits_per_weight` (`8 * type_size / blck_size`) for the types
/// the rules below compare. Exact as a ratio; compared as one.
fn bits_per_weight(t: GgmlType) -> (usize, usize) {
    let (bytes, elems) = t.block_layout();
    (8 * bytes, elems)
}

/// `bits_per_weight(a) < bits_per_weight(b)`, without a float.
fn fewer_bits(a: GgmlType, b: GgmlType) -> bool {
    let (na, da) = bits_per_weight(a);
    let (nb, db) = bits_per_weight(b);
    na * db < nb * da
}

/// What the architecture rules at the top of `llama_tensor_get_type_impl`
/// decide before the generic chain runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Early {
    /// `return` with this type: the chain, its counters and the floors do
    /// not run.
    Return(GgmlType),
    /// Run the chain starting from this type instead of the target's.
    Start(GgmlType),
}

/// The three rules above the output-head arm (`ee467158:src/llama-quant.cpp
/// :542-567`), in their order. `default` is the target's block format and
/// `source` the tensor's own type.
pub fn early(
    arch: QuantArch,
    target: Target,
    role: Role,
    name: &str,
    default: GgmlType,
    source: GgmlType,
) -> Early {
    // GLM5_NEXT: never below Q8_0 for the q latents and the MTP
    // projection. The switch passes the float types through; no target
    // frink writes is one, so every mix returns Q8_0.
    if arch == QuantArch::Glm5Next
        && ["attn_q_a", "attn_q_b", "nextn.eh_proj"]
            .iter()
            .any(|n| name.contains(n))
    {
        return Early::Return(GgmlType::Q8_0);
    }
    // RAON1_MINI at Q6_K and Q8_0: the MLA latents stay at source
    // precision.
    if arch == QuantArch::Raon1Mini
        && matches!(target, Target::Q6_K | Target::Q8_0)
        && ["attn_kv_a_mqa.weight", "attn_k_b.weight", "attn_v_b.weight"]
            .iter()
            .any(|n| name.contains(n))
    {
        return Early::Return(source);
    }
    // MUSE_SPARK: `ffn_latent` and `attn_gate` up to Q8_0, and then the
    // chain (which has no arm for either category).
    if arch == QuantArch::MuseSpark
        && matches!(role, Role::FfnLatent | Role::AttnGate)
        && fewer_bits(default, GgmlType::Q8_0)
    {
        return Early::Start(GgmlType::Q8_0);
    }
    Early::Start(default)
}

/// RAON1_MINI's floors (`:745-773`), applied after the chain and its
/// counters: a type is only ever raised to the floor. The `low` mixes
/// there are IQ and Q2/Q3 tiers frink does not write, so only the
/// `k_4_5` half can fire.
pub fn raon_floor(target: Target, role: Role, name: &str, ty: GgmlType) -> GgmlType {
    let k_4_5 = matches!(
        target,
        Target::Q4_K_S | Target::Q4_K_M | Target::Q5_K_S | Target::Q5_K_M
    );
    // `ggml_is_quantized`: a block of more than one element.
    if !k_4_5 || ty.block_layout().1 <= 1 {
        return ty;
    }
    let floor = if matches!(role, Role::AttnOutput | Role::AttnGate) {
        GgmlType::Q8_0
    } else if [
        "attn_q_a.weight",
        "attn_q_b.weight",
        "attn_k_b.weight",
        "attn_kv_a_mqa.weight",
        "attn_v_b.weight",
        "_shexp.weight",
    ]
    .iter()
    .any(|n| name.contains(n))
        || matches!(role, Role::AttnQ | Role::AttnK | Role::AttnV)
        || name.contains("ssm_g.weight")
    {
        GgmlType::Q6K
    } else {
        return ty;
    };
    if fewer_bits(ty, floor) {
        floor
    } else {
        ty
    }
}

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

    /// The bit counts the floors compare are ggml's: Q4_K 4.5, Q5_K 5.5,
    /// Q6_K 6.5625, Q8_0 8.5.
    #[test]
    fn bits_per_weight_orders_the_writable_types_like_ggml() {
        assert!(fewer_bits(GgmlType::Q4K, GgmlType::Q5K));
        assert!(fewer_bits(GgmlType::Q5K, GgmlType::Q6K));
        assert!(fewer_bits(GgmlType::Q6K, GgmlType::Q8_0));
        assert!(!fewer_bits(GgmlType::Q8_0, GgmlType::Q8_0));
        assert!(!fewer_bits(GgmlType::Q8_0, GgmlType::Q6K));
    }

    #[test]
    fn architecture_names_are_llama_arch_cpps() {
        assert_eq!(QuantArch::from_name("raon1"), QuantArch::Raon1Mini);
        assert_eq!(QuantArch::from_name("glm5-next"), QuantArch::Glm5Next);
        assert_eq!(QuantArch::from_name("xing4_0"), QuantArch::Xing40);
        assert_eq!(QuantArch::from_name("llama"), QuantArch::Other);
    }
}