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;
pub(crate) const QWEN_JOINT_MMA_ENV: &str = "HF2Q_QWEN_JOINT_MMA";
const MMA_K_STEP: u32 = 64;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) enum JointProjectionKernel {
#[default]
Canonical,
ColumnInvariantMma,
}
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! {
static MMA_SCOPE_WIDTH: Cell<Option<u32>> = const { Cell::new(None) };
static JOINT_SCOPE_WIDTH: Cell<Option<u32>> = const { Cell::new(None) };
static DFLASH2_VERIFY_SCOPE: Cell<bool> = const { Cell::new(false) };
}
pub(crate) struct JointProjectionScope {
previous: Option<u32>,
previous_joint: Option<u32>,
previous_dflash2_verify: bool,
}
impl JointProjectionScope {
#[cfg(test)]
pub(crate) fn enter(kernel: JointProjectionKernel, width: u32) -> Self {
Self::enter_step(kernel, width, false)
}
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));
}
}
pub(crate) fn active_width(width: u32) -> bool {
JOINT_SCOPE_WIDTH.with(Cell::get) == Some(width)
}
pub(crate) fn dflash2_verify_scope() -> bool {
DFLASH2_VERIFY_SCOPE.with(Cell::get)
}
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
}
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, ¶ms(4, GgmlType::Q4_K, 5120)));
assert!(!active_width(4));
{
let _scope = JointProjectionScope::enter(JointProjectionKernel::ColumnInvariantMma, 4);
assert!(admits(&input, ¶ms(4, GgmlType::Q4_K, 5120)));
assert!(active_width(4));
assert!(!active_width(8));
assert!(admits(&input, ¶ms(4, GgmlType::Q6_K, 17408)));
assert!(!admits(&input, ¶ms(1, GgmlType::Q4_K, 5120)));
assert!(!admits(&input, ¶ms(4, GgmlType::Q8_0, 5120)));
assert!(!admits(&input, ¶ms(4, GgmlType::Q4_K, 5120 + 32)));
{
let _inner = JointProjectionScope::enter(JointProjectionKernel::Canonical, 4);
assert!(!admits(&input, ¶ms(4, GgmlType::Q4_K, 5120)));
}
assert!(admits(&input, ¶ms(4, GgmlType::Q4_K, 5120)));
assert!(active_width(4));
}
assert!(!admits(&input, ¶ms(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());
}
}