hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
//! Per-model GGML routing policy for Qwen text models (#729).
//!
//! ADR-044 qualifies the width-four decode route (`dense_decode_mvn = false`,
//! `dense_decode_mv_ext = true`) for Qwen3.8 geometry only. Match the loaded
//! configuration and tensor directory, never a filename or parent directory.
//! Tokenizer identity is a drafter compatibility constraint, not a numeric
//! kernel constraint, and is not read here.
//!
//! The policy is stored on the model and frozen into its kernel registries.
//! Explicit `HF2Q_DECODE_MVN` / `HF2Q_DECODE_MV_EXT` values win independently;
//! resolving one model never changes another model's policy or the environment.

use mlx_native::gguf::GgufFile;
use mlx_native::GgmlRoutingPolicy;

use super::Qwen35Config;
use crate::inference::spec_decode::dflash2::schema::QWEN38_TARGET_GEOMETRY;

/// Operator override for the exact multi-column Q4_K/Q6_K matvec route.
pub(crate) const DECODE_MVN_ENV: &str = "HF2Q_DECODE_MVN";
/// Operator override for the weight-amortized `mul_mv_ext` route.
pub(crate) const DECODE_MV_EXT_ENV: &str = "HF2Q_DECODE_MV_EXT";

/// Why the loaded numeric geometry is outside the qualified Qwen3.8 default.
/// Storage admission remains the native dispatcher's per-product decision.
fn qwen38_refusal(gguf: &GgufFile, config: &Qwen35Config) -> Option<&'static str> {
    let pinned = &QWEN38_TARGET_GEOMETRY;
    if gguf.metadata_string("general.architecture") != Some(pinned.architecture.as_ref())
        || config.variant.key_prefix() != pinned.architecture.as_ref()
    {
        return Some("architecture differs from the qualified Qwen3.8 geometry");
    }
    if config.moe.is_some() {
        return Some("MoE configuration is not the qualified dense Qwen3.8 geometry");
    }
    macro_rules! dimension {
        ($loaded:ident, $qualified:ident) => {
            if config.$loaded != pinned.$qualified {
                return Some(concat!(
                    stringify!($loaded),
                    " differs from the qualified Qwen3.8 geometry"
                ));
            }
        };
    }
    dimension!(hidden_size, hidden_size);
    dimension!(num_hidden_layers, layers);
    dimension!(vocab_size, vocab_size);
    dimension!(num_attention_heads, attention_heads);
    dimension!(num_key_value_heads, attention_kv_heads);
    dimension!(head_dim, head_dim);
    dimension!(linear_num_key_heads, linear_key_heads);
    dimension!(linear_num_value_heads, linear_value_heads);
    dimension!(linear_key_head_dim, linear_key_head_dim);
    dimension!(linear_value_head_dim, linear_value_head_dim);
    dimension!(full_attention_interval, full_attention_interval);
    if config.intermediate_size != Some(pinned.intermediate_size) {
        return Some("intermediate_size differs from the qualified Qwen3.8 geometry");
    }
    let embedding = gguf.tensor_info("token_embd.weight");
    if embedding.map(|tensor| tensor.shape.as_slice()) != Some(pinned.embedding_shape.as_slice()) {
        return Some("embedding shape differs from the qualified Qwen3.8 geometry");
    }
    let head = gguf.tensor_info("output.weight").or(embedding);
    if head.map(|tensor| tensor.shape.as_slice()) != Some(pinned.head_shape.as_slice()) {
        return Some("output head shape differs from the qualified Qwen3.8 geometry");
    }
    None
}

/// Resolve ordinary target routing from the loaded header and parsed config.
/// This default is independent of whether a speculative drafter is selected.
pub fn resolve_qwen_ggml_routing_policy(
    gguf: &GgufFile,
    config: &Qwen35Config,
) -> GgmlRoutingPolicy {
    let refusal = qwen38_refusal(gguf, config);
    let policy = resolve_with(
        refusal.is_none(),
        mlx_native::ggml_routing_policy_from_environment(),
        |key| std::env::var_os(key).is_some(),
    );
    tracing::info!(
        qualified_geometry = refusal.is_none(),
        reason = refusal.unwrap_or("qualified Qwen3.8 numeric geometry"),
        dense_decode_mvn = policy.dense_decode_mvn,
        dense_decode_mv_ext = policy.dense_decode_mv_ext,
        "Qwen ordinary decode default resolved"
    );
    policy
}

fn resolve_with(
    qualified: bool,
    environment: GgmlRoutingPolicy,
    operator_set: impl Fn(&str) -> bool,
) -> GgmlRoutingPolicy {
    let mut policy = environment;
    if qualified {
        if !operator_set(DECODE_MVN_ENV) {
            policy.dense_decode_mvn = false;
        }
        if !operator_set(DECODE_MV_EXT_ENV) {
            policy.dense_decode_mv_ext = true;
        }
    }
    policy
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::gguf::types::MetaValue;
    use crate::backends::gguf::writer::GgufWriter;
    use crate::inference::spec_decode::dflash2::schema::{
        QwenTargetGeometry, QWEN36_TARGET_GEOMETRY,
    };
    use crate::quantize::ggml_quants::GgmlType;
    use crate::serve::dflash2_policy::tests::config_for_geometry;

    /// Header-only fixture: routing reads no payload and needs no tokenizer.
    fn header(
        name: &str,
        geometry: &QwenTargetGeometry,
        tied_head: bool,
    ) -> (tempfile::TempDir, GgufFile) {
        let mut writer = GgufWriter::new(std::io::Cursor::new(Vec::new()));
        writer.write_header(if tied_head { 1 } else { 2 }, 1).unwrap();
        writer
            .write_metadata_kv(
                "general.architecture",
                &MetaValue::String(geometry.architecture.to_string()),
            )
            .unwrap();
        for (tensor, shape) in [
            ("token_embd.weight", geometry.embedding_shape),
            ("output.weight", geometry.head_shape),
        ] {
            if tied_head && tensor == "output.weight" {
                continue;
            }
            writer
                .reserve_tensor_info(
                    tensor,
                    &[shape[1] as u64, shape[0] as u64],
                    GgmlType::Q4_K,
                )
                .unwrap();
        }
        writer.pad_to_alignment().unwrap();
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join(name);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, writer.into_inner().into_inner()).unwrap();
        let gguf = GgufFile::open(&path).unwrap();
        (directory, gguf)
    }

    fn env_default() -> GgmlRoutingPolicy {
        GgmlRoutingPolicy {
            dense_decode_mvn: true,
            dense_decode_mv_ext: false,
            ..GgmlRoutingPolicy::default()
        }
    }

    fn resolve(gguf: &GgufFile, config: &Qwen35Config) -> GgmlRoutingPolicy {
        resolve_with(qwen38_refusal(gguf, config).is_none(), env_default(), |_| false)
    }

    #[test]
    fn renamed_numeric_targets_keep_the_qualified_default_without_a_tokenizer_or_drafter() {
        let config = config_for_geometry(&QWEN38_TARGET_GEOMETRY);
        for name in ["model.gguf", "unrelated/renamed.gguf", "QWEN3.8-27B.gguf"] {
            for tied_head in [false, true] {
                let (_directory, gguf) = header(name, &QWEN38_TARGET_GEOMETRY, tied_head);
                let policy = resolve(&gguf, &config);
                assert!(!policy.dense_decode_mvn, "{name}");
                assert!(policy.dense_decode_mv_ext, "{name}");
                assert_eq!(
                    GgmlRoutingPolicy {
                        dense_decode_mvn: true,
                        dense_decode_mv_ext: false,
                        ..policy
                    },
                    env_default(),
                    "only the qualified fields change"
                );
            }
        }
    }

    #[test]
    fn a_misleading_directory_cannot_grant_the_dense_default_to_moe() {
        let (_directory, gguf) = header("qwen3.8/model.gguf", &QWEN36_TARGET_GEOMETRY, false);
        let config = config_for_geometry(&QWEN36_TARGET_GEOMETRY);
        assert_eq!(resolve(&gguf, &config), env_default());
        assert!(qwen38_refusal(&gguf, &config).unwrap().contains("architecture"));
    }

    #[test]
    fn incompatible_numeric_dimensions_and_tensor_shapes_keep_the_environment_route() {
        let config = config_for_geometry(&QWEN38_TARGET_GEOMETRY);
        let (_directory, gguf) = header("qwen3.8/model.gguf", &QWEN38_TARGET_GEOMETRY, false);
        let mut wrong = config.clone();
        wrong.num_key_value_heads += 1;
        assert_eq!(resolve(&gguf, &wrong), env_default());
        assert!(qwen38_refusal(&gguf, &wrong).unwrap().contains("num_key_value_heads"));
        for head in [false, true] {
            let mut geometry = QWEN38_TARGET_GEOMETRY.clone();
            if head {
                geometry.head_shape[0] += 1;
            } else {
                geometry.embedding_shape[0] += 1;
            }
            let (_directory, wrong) = header("qwen3.8/model.gguf", &geometry, false);
            assert_eq!(resolve(&wrong, &config), env_default());
            let reason = qwen38_refusal(&wrong, &config).unwrap();
            assert!(reason.contains(if head { "output head" } else { "embedding" }), "{reason}");
        }
    }

    #[test]
    fn explicit_operator_env_wins_per_variable() {
        let (_directory, gguf) = header("renamed.gguf", &QWEN38_TARGET_GEOMETRY, false);
        let config = config_for_geometry(&QWEN38_TARGET_GEOMETRY);
        let qualified = qwen38_refusal(&gguf, &config).is_none();
        let operator = env_default();
        assert_eq!(resolve_with(qualified, operator, |_| true), operator);
        let mvn_only = resolve_with(qualified, operator, |key| key == DECODE_MVN_ENV);
        assert!(mvn_only.dense_decode_mvn);
        assert!(mvn_only.dense_decode_mv_ext);
        let mv_ext_only = resolve_with(qualified, operator, |key| key == DECODE_MV_EXT_ENV);
        assert!(!mv_ext_only.dense_decode_mvn);
        assert!(!mv_ext_only.dense_decode_mv_ext);
    }

    #[test]
    fn ordinary_defaults_preserve_the_native_storage_and_width_admission() {
        use mlx_native::{
            ggml_capability, GgmlCapabilityRequest, GgmlInvocation, GgmlKernelRoute,
            GgmlWorkloadClass, GGML_CAPABILITY_SCHEMA_VERSION,
        };
        let (_directory, gguf) = header("renamed.gguf", &QWEN38_TARGET_GEOMETRY, false);
        let config = config_for_geometry(&QWEN38_TARGET_GEOMETRY);
        let routing = resolve(&gguf, &config);
        for (ty, m, expected) in [
            (mlx_native::GgmlType::Q4_K, 4, GgmlKernelRoute::DenseWidthMvExt),
            (mlx_native::GgmlType::Q6_K, 4, GgmlKernelRoute::DenseWidthMvExt),
            (mlx_native::GgmlType::Q8_0, 4, GgmlKernelRoute::DenseWidthMvExt),
            (mlx_native::GgmlType::Q5_K, 4, GgmlKernelRoute::DenseQ5kCanonicalQ4x4),
            (mlx_native::GgmlType::Q4_K, 2, GgmlKernelRoute::DenseMv),
            (mlx_native::GgmlType::F32, 4, GgmlKernelRoute::DenseF32Mm),
        ] {
            let capability = ggml_capability(GgmlCapabilityRequest {
                schema_version: GGML_CAPABILITY_SCHEMA_VERSION,
                invocation: GgmlInvocation::DenseAuto {
                    m,
                    n: QWEN38_TARGET_GEOMETRY.intermediate_size,
                    k: config.hidden_size,
                },
                ggml_type: ty,
                workload: GgmlWorkloadClass::ContinuousWidth,
                routing,
            });
            assert!(capability.executable, "{}", capability.diagnostic);
            assert_eq!(capability.route, Some(expected), "{ty:?} m={m}");
        }
        let unsupported = ggml_capability(GgmlCapabilityRequest {
            schema_version: GGML_CAPABILITY_SCHEMA_VERSION,
            invocation: GgmlInvocation::DenseAuto {
                m: 4,
                n: QWEN38_TARGET_GEOMETRY.intermediate_size,
                k: config.hidden_size,
            },
            ggml_type: mlx_native::GgmlType::I32,
            workload: GgmlWorkloadClass::ContinuousWidth,
            routing,
        });
        assert!(!unsupported.executable, "integer metadata is not a dense weight");
    }

    #[test]
    fn process_resolver_leaves_other_models_and_environment_untouched_in_either_order() {
        if std::env::var_os(DECODE_MVN_ENV).is_some()
            || std::env::var_os(DECODE_MV_EXT_ENV).is_some()
        {
            return;
        }
        let (_dense_directory, dense) = header("renamed.gguf", &QWEN38_TARGET_GEOMETRY, false);
        let (_moe_directory, moe) = header("qwen3.8/model.gguf", &QWEN36_TARGET_GEOMETRY, false);
        let dense_config = config_for_geometry(&QWEN38_TARGET_GEOMETRY);
        let moe_config = config_for_geometry(&QWEN36_TARGET_GEOMETRY);
        let environment = mlx_native::ggml_routing_policy_from_environment();
        let models = [(&dense, &dense_config, true), (&moe, &moe_config, false)];
        for order in [models, [models[1], models[0]]] {
            for (gguf, config, qualified) in order {
                let policy = resolve_qwen_ggml_routing_policy(gguf, config);
                if qualified {
                    assert!(!policy.dense_decode_mvn && policy.dense_decode_mv_ext);
                } else {
                    assert_eq!(policy, environment);
                }
                assert!(std::env::var_os(DECODE_MVN_ENV).is_none());
                assert!(std::env::var_os(DECODE_MV_EXT_ENV).is_none());
            }
        }
        assert_eq!(mlx_native::ggml_routing_policy_from_environment(), environment);
    }
}