hf2q 0.1.31

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
//! Projection kernel for the packed products of a padded Qwen joint step.
//!
//! [`JointRouteMode::PaddedMvExt`] runs every packed Q4_K / Q6_K product at a
//! fixed width of [`PADDED_MV_EXT_WIDTH`] rows, so a step always pays the
//! width-4 cost, including 1-lane steps. Under
//! [`JointProjectionKernel::ColumnInvariantMma`] (switch
//! [`QWEN_JOINT_MMA_ENV`]) those products use mlx-native's few-row MMA
//! kernel ([`quantized_matmul_ggml_column_invariant_mma`]): one pipeline for
//! every width, and each row's result is independent of the width, of its
//! packed position and of the other rows. Against the `mul_mv_ext` route this
//! is a different accumulation order (Q1 Class B); cohort invariance holds by
//! construction.
//!
//! The kernel applies inside [`JointProjectionScope`] only: joint layer
//! chains retain it through the output head. Joint MTP drafting and accepted
//! target-row catch-up open the same selected scope at their own row widths;
//! ordinary prompt catch-up and serial graphs keep the canonical dispatcher.
//!
//! [`JointRouteMode::PaddedMvExt`]: super::joint_decode_routes::JointRouteMode::PaddedMvExt
//! [`PADDED_MV_EXT_WIDTH`]: super::joint_decode_routes::PADDED_MV_EXT_WIDTH

use std::cell::Cell;

use mlx_native::ops::quantized_matmul_ggml::{GgmlQuantizedMatmulParams, GgmlType};
use mlx_native::{
    quantized_matmul_ggml_column_invariant_mma, CommandEncoder, KernelRegistry, MlxBuffer,
    MlxDevice,
};

use super::joint_decode_routes::JointRouteMode;

/// Diagnostic override for [`JointProjectionKernel::ColumnInvariantMma`]:
/// `1`/`on`/`true` selects it in padded mode and `0`/`off`/`false` disables
/// it. Unset or blank follows the joint-MTP candidate switch.
pub(crate) const QWEN_JOINT_MMA_ENV: &str = "HF2Q_QWEN_JOINT_MMA";

/// K step of the MMA kernel's generic (Q4_K / Q6_K) kind.
const MMA_K_STEP: u32 = 64;

/// Kernel for the packed K-quant products of a joint step.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum JointProjectionKernel {
    /// The canonical dispatcher (`mul_mv_ext` at the padded width).
    #[default]
    Canonical,
    /// [`quantized_matmul_ggml_column_invariant_mma`].
    ColumnInvariantMma,
}

/// Kernel for `mode` under the switch. Exact mode keeps the canonical
/// dispatcher: its rows must stay bitwise equal to serial decode.
pub(crate) fn select_joint_projection_kernel(
    mode: JointRouteMode,
    mma: bool,
) -> JointProjectionKernel {
    match mode {
        JointRouteMode::PaddedMvExt if mma => JointProjectionKernel::ColumnInvariantMma,
        JointRouteMode::Exact | JointRouteMode::PaddedMvExt => JointProjectionKernel::Canonical,
    }
}

thread_local! {
    /// Packed width of the open MMA scope, if any.
    static MMA_SCOPE_WIDTH: Cell<Option<u32>> = const { Cell::new(None) };
    /// Packed width of the open joint layer chain, independent of its kernel.
    static JOINT_SCOPE_WIDTH: Cell<Option<u32>> = const { Cell::new(None) };
    /// Whether the open joint layer chain is a DFlash2 target verify step.
    static DFLASH2_VERIFY_SCOPE: Cell<bool> = const { Cell::new(false) };
}

/// Marks this thread's packed joint products until dropped.
pub(crate) struct JointProjectionScope {
    previous: Option<u32>,
    previous_joint: Option<u32>,
    previous_dflash2_verify: bool,
}

impl JointProjectionScope {
    /// [`Self::enter_step`] for a plain joint decode or joint MTP verify
    /// step.
    #[cfg(test)]
    pub(crate) fn enter(kernel: JointProjectionKernel, width: u32) -> Self {
        Self::enter_step(kernel, width, false)
    }

    /// Open a scope for products of exactly `width` rows. Only
    /// [`JointProjectionKernel::ColumnInvariantMma`] changes MMA routing;
    /// both kernels expose the joint width to other joint-only projections.
    /// `dflash2_verify` marks a DFlash2 target verify step: the only step
    /// whose rows are not held to the serial one-token forward's bits, and
    /// so the only one the prepared routes may serve at widths below 32
    /// ([`dflash2_verify_scope`]).
    pub(crate) fn enter_step(
        kernel: JointProjectionKernel,
        width: u32,
        dflash2_verify: bool,
    ) -> Self {
        let scoped = (kernel == JointProjectionKernel::ColumnInvariantMma).then_some(width);
        Self {
            previous: MMA_SCOPE_WIDTH.with(|cell| cell.replace(scoped)),
            previous_joint: JOINT_SCOPE_WIDTH.with(|cell| cell.replace(Some(width))),
            previous_dflash2_verify: DFLASH2_VERIFY_SCOPE.with(|cell| cell.replace(dflash2_verify)),
        }
    }
}

impl Drop for JointProjectionScope {
    fn drop(&mut self) {
        MMA_SCOPE_WIDTH.with(|cell| cell.set(self.previous));
        JOINT_SCOPE_WIDTH.with(|cell| cell.set(self.previous_joint));
        DFLASH2_VERIFY_SCOPE.with(|cell| cell.set(self.previous_dflash2_verify));
    }
}

/// Whether this thread is encoding the layer chain for this packed width.
pub(crate) fn active_width(width: u32) -> bool {
    JOINT_SCOPE_WIDTH.with(Cell::get) == Some(width)
}

/// Whether this thread is encoding the layer chain of a DFlash2 target
/// verify step.
pub(crate) fn dflash2_verify_scope() -> bool {
    DFLASH2_VERIFY_SCOPE.with(Cell::get)
}

/// Whether the open scope takes this product: the packed width, a Q4_K /
/// Q6_K weight, `K` a multiple of the kernel's K step and a 16-byte aligned
/// input.
fn admits(input: &MlxBuffer, params: &GgmlQuantizedMatmulParams) -> bool {
    MMA_SCOPE_WIDTH.with(Cell::get) == Some(params.m)
        && matches!(params.ggml_type, GgmlType::Q4_K | GgmlType::Q6_K)
        && params.k % MMA_K_STEP == 0
        && input.byte_offset() % 16 == 0
}

/// Dispatch an admitted product on the MMA kernel; `None` when the open
/// scope does not take it (the caller runs the canonical dispatcher).
pub(crate) fn dispatch_in_scope(
    encoder: &mut CommandEncoder,
    registry: &mut KernelRegistry,
    device: &MlxDevice,
    input: &MlxBuffer,
    weight: &MlxBuffer,
    output: &MlxBuffer,
    params: &GgmlQuantizedMatmulParams,
) -> Option<mlx_native::Result<()>> {
    admits(input, params).then(|| {
        quantized_matmul_ggml_column_invariant_mma(
            encoder, registry, device, input, weight, output, params,
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::inference::models::qwen35::joint_step_options::parse_switch;

    #[test]
    fn switch_parses_on_off_and_rejects_other_values() {
        let parse = |raw| parse_switch(QWEN_JOINT_MMA_ENV, raw);
        assert_eq!(parse(None), Ok(false));
        assert_eq!(parse(Some("  ")), Ok(false));
        for on in ["1", "on", "TRUE"] {
            assert_eq!(parse(Some(on)), Ok(true));
        }
        for off in ["0", "off", "False"] {
            assert_eq!(parse(Some(off)), Ok(false));
        }
        assert!(parse(Some("mma")).is_err());
    }

    #[test]
    fn exact_mode_never_selects_mma() {
        assert_eq!(
            select_joint_projection_kernel(JointRouteMode::Exact, true),
            JointProjectionKernel::Canonical
        );
        assert_eq!(
            select_joint_projection_kernel(JointRouteMode::PaddedMvExt, true),
            JointProjectionKernel::ColumnInvariantMma
        );
        assert_eq!(
            select_joint_projection_kernel(JointRouteMode::PaddedMvExt, false),
            JointProjectionKernel::Canonical
        );
    }

    #[test]
    fn scope_admits_only_its_width_and_k_quants_and_restores_on_drop() {
        let params = |m, ggml_type, k| GgmlQuantizedMatmulParams {
            m,
            n: 64,
            k,
            ggml_type,
        };
        let device = MlxDevice::new().expect("device");
        let input = device
            .alloc_buffer(4 * 5120 * 4, mlx_native::DType::F32, vec![4, 5120])
            .expect("input");
        assert!(!admits(&input, &params(4, GgmlType::Q4_K, 5120)));
        assert!(!active_width(4));
        {
            let _scope = JointProjectionScope::enter(JointProjectionKernel::ColumnInvariantMma, 4);
            assert!(admits(&input, &params(4, GgmlType::Q4_K, 5120)));
            assert!(active_width(4));
            assert!(!active_width(8));
            assert!(admits(&input, &params(4, GgmlType::Q6_K, 17408)));
            assert!(!admits(&input, &params(1, GgmlType::Q4_K, 5120)));
            assert!(!admits(&input, &params(4, GgmlType::Q8_0, 5120)));
            assert!(!admits(&input, &params(4, GgmlType::Q4_K, 5120 + 32)));
            {
                let _inner = JointProjectionScope::enter(JointProjectionKernel::Canonical, 4);
                assert!(!admits(&input, &params(4, GgmlType::Q4_K, 5120)));
            }
            assert!(admits(&input, &params(4, GgmlType::Q4_K, 5120)));
            assert!(active_width(4));
        }
        assert!(!admits(&input, &params(4, GgmlType::Q4_K, 5120)));
        assert!(!active_width(4));
    }

    #[test]
    fn only_a_dflash2_verify_step_marks_its_scope_and_the_mark_is_restored() {
        assert!(!dflash2_verify_scope());
        {
            let _plain = JointProjectionScope::enter(JointProjectionKernel::Canonical, 8);
            assert!(!dflash2_verify_scope());
            {
                let _verify =
                    JointProjectionScope::enter_step(JointProjectionKernel::Canonical, 8, true);
                assert!(dflash2_verify_scope() && active_width(8));
            }
            assert!(!dflash2_verify_scope() && active_width(8));
        }
        assert!(!dflash2_verify_scope());
    }
}