use mlx_native::ops::quantized_matmul_ggml::GgmlType;
use mlx_native::DType;
pub(crate) const MAX_JOINT_DECODE_ROWS: usize = 8;
pub(crate) const MAX_JOINT_VERIFY_ROWS: usize = 16;
pub(crate) const DFLASH2_VERIFY_WIDTH: usize = 32;
pub(crate) const PADDED_MV_EXT_WIDTH: usize = 4;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum JointRouteMode {
Exact,
PaddedMvExt,
}
impl JointRouteMode {
pub(crate) fn label(self) -> &'static str {
match self {
Self::Exact => "exact",
Self::PaddedMvExt => "padded_mv_ext",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum JointProductRoute {
Batched,
PerRow,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct JointRoutingPolicy {
pub mv_ext: bool,
}
impl JointRoutingPolicy {
pub(crate) fn from_ggml(policy: &mlx_native::GgmlRoutingPolicy) -> Self {
Self {
mv_ext: policy.dense_decode_mv_ext,
}
}
}
pub(crate) fn select_joint_route_mode(
policy: JointRoutingPolicy,
moe: bool,
) -> Result<JointRouteMode, String> {
match (policy.mv_ext, moe) {
(false, _) => Ok(JointRouteMode::Exact),
(true, false) => Ok(JointRouteMode::PaddedMvExt),
(true, true) => Err(
"the mul_mv_ext routing policy routes packed MoE rows through non-exact \
mul_mv_ext and no Q1 gate covers MoE artifacts on that route"
.into(),
),
}
}
pub(crate) fn check_mode_policy(
mode: JointRouteMode,
policy: JointRoutingPolicy,
) -> Result<(), String> {
if mode == JointRouteMode::Exact && policy.mv_ext {
return Err(
"exact joint decode requires a routing policy without mul_mv_ext (it is not bitwise)"
.into(),
);
}
Ok(())
}
pub(crate) fn joint_padded_width(mode: JointRouteMode, rows: usize) -> usize {
match mode {
JointRouteMode::Exact => rows,
JointRouteMode::PaddedMvExt => PADDED_MV_EXT_WIDTH,
}
}
pub(crate) fn joint_mode_max_rows(mode: JointRouteMode, requested: usize) -> usize {
match mode {
JointRouteMode::Exact => requested,
JointRouteMode::PaddedMvExt => requested.min(PADDED_MV_EXT_WIDTH),
}
}
pub(crate) fn joint_verify_padded_width(mode: JointRouteMode, rows: usize) -> usize {
match mode {
JointRouteMode::Exact => rows,
JointRouteMode::PaddedMvExt if rows <= PADDED_MV_EXT_WIDTH => PADDED_MV_EXT_WIDTH,
JointRouteMode::PaddedMvExt if rows <= MAX_JOINT_DECODE_ROWS => MAX_JOINT_DECODE_ROWS,
JointRouteMode::PaddedMvExt => MAX_JOINT_VERIFY_ROWS,
}
}
fn packed_block_type(ggml_type: GgmlType) -> bool {
matches!(
ggml_type,
GgmlType::Q4_0 | GgmlType::Q8_0 | GgmlType::Q4_K | GgmlType::Q5_K | GgmlType::Q6_K
)
}
pub(crate) fn projection_route(
name: &str,
dtype: DType,
ggml_type: GgmlType,
) -> Result<JointProductRoute, String> {
match dtype {
DType::F32 | DType::F16 | DType::BF16 => Ok(JointProductRoute::PerRow),
DType::U8 if packed_block_type(ggml_type) => Ok(JointProductRoute::Batched),
DType::U8 => Err(format!(
"{name} is {ggml_type:?}, which has no proven joint decode route"
)),
other => Err(format!("{name} has unsupported joint storage {other:?}")),
}
}
pub(crate) fn dense_ffn_route(
layer: usize,
gate_up: GgmlType,
down: GgmlType,
) -> Result<(), String> {
for (role, ggml_type) in [("gate/up", gate_up), ("down", down)] {
if !packed_block_type(ggml_type) {
return Err(format!(
"layer {layer} dense FFN {role} is {ggml_type:?}, which has no proven joint decode route"
));
}
}
Ok(())
}
pub(crate) const QWEN_JOINT_FFN_SHARED_ENV: &str = "HF2Q_QWEN_JOINT_FFN_SHARED";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum JointDenseFfnRoute {
SerialBuilder,
SharedWeights,
}
impl JointDenseFfnRoute {
pub(crate) fn label(self) -> &'static str {
match self {
Self::SerialBuilder => "serial_builder",
Self::SharedWeights => "shared_weights",
}
}
}
pub(crate) fn parse_joint_ffn_shared(raw: Option<&str>) -> Result<bool, String> {
let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
return Ok(true);
};
match raw.to_ascii_lowercase().as_str() {
"1" | "on" | "true" => Ok(true),
"0" | "off" | "false" => Ok(false),
_ => Err(format!(
"{QWEN_JOINT_FFN_SHARED_ENV} must be 1/on/true or 0/off/false, got {raw:?}"
)),
}
}
pub(crate) fn joint_ffn_shared_from_process() -> Result<bool, String> {
parse_joint_ffn_shared(std::env::var(QWEN_JOINT_FFN_SHARED_ENV).ok().as_deref())
}
pub(crate) fn select_dense_ffn_route(mode: JointRouteMode, shared: bool) -> JointDenseFfnRoute {
match mode {
JointRouteMode::PaddedMvExt if shared => JointDenseFfnRoute::SharedWeights,
JointRouteMode::Exact | JointRouteMode::PaddedMvExt => JointDenseFfnRoute::SerialBuilder,
}
}
pub(crate) fn check_dense_ffn_route(
mode: JointRouteMode,
route: JointDenseFfnRoute,
) -> Result<(), String> {
if mode == JointRouteMode::Exact && route == JointDenseFfnRoute::SharedWeights {
return Err(
"exact joint decode requires the serial dense FFN builder (the shared gate/up \
route is not bitwise equal to serial decode)"
.into(),
);
}
Ok(())
}
pub(crate) fn joint_decode_env_unavailable_reason() -> Option<String> {
let flag = |name: &str| std::env::var(name).as_deref() == Ok("1");
if flag("HF2Q_LEGACY_PER_LAYER_CB") {
return Some("HF2Q_LEGACY_PER_LAYER_CB=1 selects the legacy serial graph".into());
}
if flag("MLX_UNRETAINED_REFS") {
return Some("MLX_UNRETAINED_REFS=1 requires the serial buffer anchors".into());
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exact_mode_is_selected_unless_mv_ext_is_on() {
let off = JointRoutingPolicy { mv_ext: false };
let on = JointRoutingPolicy { mv_ext: true };
assert_eq!(
select_joint_route_mode(off, false),
Ok(JointRouteMode::Exact)
);
assert_eq!(
select_joint_route_mode(off, true),
Ok(JointRouteMode::Exact)
);
assert_eq!(
select_joint_route_mode(on, false),
Ok(JointRouteMode::PaddedMvExt)
);
assert!(select_joint_route_mode(on, true).is_err());
}
#[test]
fn exact_mode_refuses_mv_ext_policy() {
let on = JointRoutingPolicy { mv_ext: true };
let off = JointRoutingPolicy { mv_ext: false };
assert!(check_mode_policy(JointRouteMode::Exact, on).is_err());
assert!(check_mode_policy(JointRouteMode::Exact, off).is_ok());
assert!(check_mode_policy(JointRouteMode::PaddedMvExt, on).is_ok());
}
#[test]
fn verify_width_covers_the_diagnostic_grid() {
for rows in 1..=MAX_JOINT_VERIFY_ROWS {
assert_eq!(joint_verify_padded_width(JointRouteMode::Exact, rows), rows);
let padded = joint_verify_padded_width(JointRouteMode::PaddedMvExt, rows);
assert!(padded >= rows);
let expected = if rows <= 4 {
4
} else if rows <= 8 {
8
} else {
16
};
assert_eq!(padded, expected);
}
assert_eq!(DFLASH2_VERIFY_WIDTH, 4 * 8);
}
#[test]
fn joint_policy_reads_only_the_model_policy() {
let mut ggml = mlx_native::GgmlRoutingPolicy::default();
ggml.dense_decode_mv_ext = false;
assert_eq!(
JointRoutingPolicy::from_ggml(&ggml),
JointRoutingPolicy { mv_ext: false }
);
ggml.dense_decode_mv_ext = true;
assert_eq!(
JointRoutingPolicy::from_ggml(&ggml),
JointRoutingPolicy { mv_ext: true }
);
}
#[test]
fn padded_width_never_depends_on_tenant_count() {
for rows in 1..=PADDED_MV_EXT_WIDTH {
assert_eq!(joint_padded_width(JointRouteMode::PaddedMvExt, rows), 4);
assert_eq!(joint_padded_width(JointRouteMode::Exact, rows), rows);
}
for requested in 2..=MAX_JOINT_DECODE_ROWS {
let cap = joint_mode_max_rows(JointRouteMode::PaddedMvExt, requested);
assert_eq!(cap, requested.min(4));
assert_eq!(joint_padded_width(JointRouteMode::PaddedMvExt, cap), 4);
assert_eq!(
joint_mode_max_rows(JointRouteMode::Exact, requested),
requested
);
}
}
#[test]
fn float_storage_runs_per_row_and_unproven_blocks_are_refused() {
for dtype in [DType::F32, DType::F16, DType::BF16] {
assert_eq!(
projection_route("router", dtype, GgmlType::F32),
Ok(JointProductRoute::PerRow)
);
}
for ggml_type in [
GgmlType::Q4_0,
GgmlType::Q8_0,
GgmlType::Q4_K,
GgmlType::Q5_K,
GgmlType::Q6_K,
] {
assert_eq!(
projection_route("wq", DType::U8, ggml_type),
Ok(JointProductRoute::Batched)
);
}
for ggml_type in [
GgmlType::Q2_K,
GgmlType::Q3_K,
GgmlType::Q5_0,
GgmlType::IQ4_NL,
GgmlType::IQ4_XS,
] {
let error = projection_route("attn_qkv", DType::U8, ggml_type)
.expect_err("unproven block storage must stay serial");
assert!(error.contains("attn_qkv"), "{error}");
}
}
#[test]
fn dense_ffn_requires_both_roles_admitted() {
assert!(dense_ffn_route(3, GgmlType::Q4_K, GgmlType::Q6_K).is_ok());
let error = dense_ffn_route(3, GgmlType::IQ4_NL, GgmlType::Q6_K)
.expect_err("unproven gate/up storage");
assert!(
error.contains("layer 3") && error.contains("gate/up"),
"{error}"
);
assert!(dense_ffn_route(3, GgmlType::Q4_K, GgmlType::Q2_K).is_err());
}
#[test]
fn shared_ffn_switch_defaults_on_and_parses_explicit_arms() {
for raw in [
None,
Some(""),
Some(" "),
Some("1"),
Some("On"),
Some("true"),
] {
assert_eq!(parse_joint_ffn_shared(raw), Ok(true), "{raw:?}");
}
for raw in ["0", "OFF", "false"] {
assert_eq!(parse_joint_ffn_shared(Some(raw)), Ok(false), "{raw}");
}
let error = parse_joint_ffn_shared(Some("shared")).expect_err("invalid switch value");
assert!(error.contains(QWEN_JOINT_FFN_SHARED_ENV), "{error}");
}
#[test]
fn exact_mode_never_takes_the_shared_ffn_route() {
for shared in [false, true] {
let route = select_dense_ffn_route(JointRouteMode::Exact, shared);
assert_eq!(route, JointDenseFfnRoute::SerialBuilder);
assert!(check_dense_ffn_route(JointRouteMode::Exact, route).is_ok());
}
assert_eq!(
select_dense_ffn_route(JointRouteMode::PaddedMvExt, true),
JointDenseFfnRoute::SharedWeights
);
assert_eq!(
select_dense_ffn_route(JointRouteMode::PaddedMvExt, false),
JointDenseFfnRoute::SerialBuilder
);
assert!(
check_dense_ffn_route(JointRouteMode::Exact, JointDenseFfnRoute::SharedWeights)
.is_err()
);
for route in [
JointDenseFfnRoute::SerialBuilder,
JointDenseFfnRoute::SharedWeights,
] {
assert!(check_dense_ffn_route(JointRouteMode::PaddedMvExt, route).is_ok());
}
}
#[test]
fn shared_ffn_products_read_weights_once_per_padded_step() {
use mlx_native::{
ggml_capability, GgmlCapabilityRequest, GgmlInvocation, GgmlKernelRoute,
GgmlRoutingPolicy, GgmlWorkloadClass, GGML_CAPABILITY_SCHEMA_VERSION,
};
let m = PADDED_MV_EXT_WIDTH as u32;
for dense_decode_mvn in [false, true] {
let routing = GgmlRoutingPolicy {
dense_decode_mvn,
dense_decode_mv_ext: true,
..GgmlRoutingPolicy::default()
};
for ggml_type in [
GgmlType::Q4_0,
GgmlType::Q8_0,
GgmlType::Q4_K,
GgmlType::Q5_K,
GgmlType::Q6_K,
] {
assert!(packed_block_type(ggml_type));
for (n, k) in [(17_408, 5_120), (5_120, 17_408)] {
let capability = ggml_capability(GgmlCapabilityRequest {
schema_version: GGML_CAPABILITY_SCHEMA_VERSION,
invocation: GgmlInvocation::DenseAuto { m, n, k },
ggml_type,
workload: GgmlWorkloadClass::ContinuousWidth,
routing,
});
let at = format!("{ggml_type:?} [{n}, {k}] m={m} mvn={dense_decode_mvn}");
assert!(capability.executable, "{at}: {}", capability.diagnostic);
assert!(
matches!(
capability.route,
Some(
GgmlKernelRoute::DenseWidthMvExt
| GgmlKernelRoute::DenseQ4kWidthMn
| GgmlKernelRoute::DenseQ5kWidthMn
| GgmlKernelRoute::DenseQ6kWidthMn
| GgmlKernelRoute::DenseQ5kCanonicalQ4x4
)
),
"{at}: {:?} is not a multi-column route",
capability.route
);
assert_eq!(capability.dispatches, 1, "{at}: one weight pass");
}
}
}
}
}