use std::sync::OnceLock;
use anyhow::{bail, Context, Result};
use mlx_native::{tensor_kernel_family_available, KernelRegistry, MlxDevice, TensorKernelFamily};
use TensorKernelFamily::{
Dflash2Af4g64Staged, Dflash2RingAttention, GroupedM8Experts, MoeExpertTiles, RepackedGgufMm,
};
const FAMILIES: [TensorKernelFamily; 6] = [
RepackedGgufMm,
Dflash2Af4g64Staged,
Dflash2RingAttention,
GroupedM8Experts,
MoeExpertTiles,
TensorKernelFamily::MmPerm021,
];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Grammar {
One,
OnOffTrue,
WaitLayers,
}
impl Grammar {
pub(crate) fn is_on(self, value: &str) -> bool {
match self {
Self::One => value == "1",
Self::OnOffTrue => matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "on" | "true"
),
Self::WaitLayers => value
.trim()
.parse::<usize>()
.is_ok_and(|layers| (2..=8).contains(&layers)),
}
}
}
pub(crate) struct SwitchRow {
pub(crate) name: &'static str,
pub(crate) grammar: Grammar,
pub(crate) families: &'static [TensorKernelFamily],
}
const fn row(
name: &'static str,
grammar: Grammar,
families: &'static [TensorKernelFamily],
) -> SwitchRow {
SwitchRow {
name,
grammar,
families,
}
}
use Grammar::{OnOffTrue, One, WaitLayers};
#[rustfmt::skip]
pub(crate) const SWITCHES: &[SwitchRow] = &[
row("HF2Q_DFLASH2_DRAFT_AF4_G64", One, &[Dflash2Af4g64Staged]),
row("HF2Q_DFLASH2_DRAFT_STAGED", One, &[Dflash2Af4g64Staged, Dflash2RingAttention, RepackedGgufMm]),
row("HF2Q_DFLASH2_GPU_TARGET_TOKENS", OnOffTrue, &[]),
row("HF2Q_REPACKED_GGUF_M32", One, &[RepackedGgufMm]),
row("HF2Q_REPACKED_GGUF_M32_PROJ", One, &[RepackedGgufMm]),
row("HF2Q_REPACKED_GGUF_M32_HEAD", One, &[RepackedGgufMm]),
row("HF2Q_REPACKED_GGUF_ANY_WIDTH", One, &[RepackedGgufMm]),
row("HF2Q_REPACKED_GGUF_SHARED_HEAD", One, &[RepackedGgufMm]),
row("HF2Q_QWEN_VERIFY_ATTN_TILE", One, &[]),
row("HF2Q_QWEN_PREFILL_PREPARED", OnOffTrue, &[RepackedGgufMm]),
row("HF2Q_QWEN_PREFILL_FOLD_CUE", OnOffTrue, &[]),
row("HF2Q_QWEN_PREFILL_JOINT", OnOffTrue, &[]),
row("HF2Q_QWEN_PREFILL_WAIT_LAYERS", WaitLayers,&[]),
row("HF2Q_QWEN_PREFILL_KEEP_FRESH", OnOffTrue, &[]),
row("HF2Q_QWEN_VERIFY_MIXER_FUSED", One, &[]),
row("HF2Q_QWEN_VERIFY_REPLAY_REUSE", One, &[]),
row("HF2Q_DFLASH2_CONTEXT_FIRST", One, &[]),
row("HF2Q_DFLASH2_DRAFT_PREFETCH", One, &[]),
row("HF2Q_DFLASH2_GPU_DECISIONS", One, &[]),
row("HF2Q_DFLASH2_PROPOSAL_REPETITION", OnOffTrue, &[]),
row("HF2Q_QWEN_MOE_BATCHED", OnOffTrue, &[]),
row("HF2Q_QWEN_MOE_STAGED_M8", OnOffTrue, &[GroupedM8Experts]),
row("HF2Q_QWEN_MOE_LIVE_TILES", OnOffTrue, &[GroupedM8Experts, MoeExpertTiles]),
];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum HostRoute {
Runs,
Unavailable(TensorKernelFamily),
}
impl HostRoute {
pub(crate) fn reason(self) -> Option<String> {
match self {
Self::Runs => None,
Self::Unavailable(family) => Some(format!(
"{} cannot run on this host: {}",
family.name(),
mlx_native::tensor_kernel_family_unavailable_reason()
)),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct HostRoutes {
device: String,
registry_id: u64,
unavailable: Vec<TensorKernelFamily>,
}
impl HostRoutes {
pub(crate) fn ask(device: &MlxDevice, registry: &mut KernelRegistry) -> Result<Self> {
let mut unavailable = Vec::new();
for family in FAMILIES {
let available = tensor_kernel_family_available(registry, device, family)
.with_context(|| format!("probe {} on {}", family.name(), device.name()))?;
if !available {
unavailable.push(family);
}
}
Ok(Self {
device: device.name(),
registry_id: device.registry_id(),
unavailable,
})
}
pub(crate) fn runs(&self, family: TensorKernelFamily) -> bool {
!self.unavailable.contains(&family)
}
pub(crate) fn switch(&self, name: &str) -> Option<HostRoute> {
SWITCHES
.iter()
.find(|row| row.name == name)
.map(|row| self.route(row))
}
fn route(&self, row: &SwitchRow) -> HostRoute {
row.families
.iter()
.find(|family| !self.runs(**family))
.map_or(HostRoute::Runs, |family| HostRoute::Unavailable(*family))
}
pub(crate) fn require_explicit(&self, env: &dyn Fn(&str) -> Option<String>) -> Result<()> {
for row in selected_tensor_only(env) {
if let route @ HostRoute::Unavailable(_) = self.route(row) {
bail!("{}", self.explicit_refusal(row.name, route));
}
}
Ok(())
}
pub(crate) fn explicit_refusal(&self, name: &str, route: HostRoute) -> String {
format!(
"{name} is on, but {} ({}). Unset {name}: the stock route serves this host.",
route
.reason()
.unwrap_or_else(|| "its route runs on this host".to_owned()),
self.device
)
}
pub(crate) fn summary(&self) -> String {
if self.unavailable.is_empty() {
format!("{}: every fast-route kernel family runs", self.device)
} else {
let off = SWITCHES
.iter()
.filter(|row| self.route(row) != HostRoute::Runs)
.map(|row| row.name)
.collect::<Vec<_>>()
.join(", ");
format!(
"{}: {}; these switches cannot run: {off}",
self.device,
mlx_native::tensor_kernel_family_unavailable_reason()
)
}
}
}
fn selected_tensor_only(
env: &dyn Fn(&str) -> Option<String>,
) -> impl Iterator<Item = &'static SwitchRow> + '_ {
SWITCHES.iter().filter(move |row| {
!row.families.is_empty() && env(row.name).is_some_and(|value| row.grammar.is_on(&value))
})
}
fn require_selected(
env: &dyn Fn(&str) -> Option<String>,
probe: impl FnOnce() -> Result<HostRoutes>,
) -> Result<()> {
match probe() {
Ok(host) => host.require_explicit(env),
Err(error) => {
let selected = selected_tensor_only(env)
.map(|row| row.name)
.collect::<Vec<_>>();
if selected.is_empty() {
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
tracing::warn!(
error = format!("{error:#}"),
"fast-route host capability probe failed; no tensor-only switch is \
selected, the stock route is unaffected"
);
});
Ok(())
} else {
Err(error.context(format!(
"{} selected, and the kernel families it needs could not be probed",
selected.join(", ")
)))
}
}
}
}
static HOST: OnceLock<HostRoutes> = OnceLock::new();
#[cfg(test)]
thread_local! {
static TEST_HOST: std::cell::RefCell<Option<HostRoutes>> =
const { std::cell::RefCell::new(None) };
}
#[cfg(test)]
pub(crate) struct HostForTest {
previous: Option<HostRoutes>,
}
#[cfg(test)]
impl HostForTest {
pub(crate) fn set(host: HostRoutes) -> Self {
Self {
previous: TEST_HOST.with(|cell| cell.replace(Some(host))),
}
}
pub(crate) fn with_tensor_api() -> Self {
Self::set(HostRoutes {
device: "host with the Metal tensor API (test)".to_owned(),
registry_id: 0,
unavailable: Vec::new(),
})
}
pub(crate) fn without_tensor_api() -> Self {
Self::set(HostRoutes {
device: "host without the Metal tensor API (test)".to_owned(),
registry_id: 0,
unavailable: FAMILIES.to_vec(),
})
}
}
#[cfg(test)]
impl Drop for HostForTest {
fn drop(&mut self) {
TEST_HOST.with(|cell| *cell.borrow_mut() = self.previous.take());
}
}
#[cfg(test)]
pub(crate) fn simulate_in(registry: &mut KernelRegistry) -> Result<()> {
let simulated = TEST_HOST.with(|cell| {
cell.borrow()
.as_ref()
.is_some_and(|host| host.unavailable.len() == FAMILIES.len())
});
if simulated {
registry
.simulate_missing_tensor_header()
.context("simulate a runtime compiler without <metal_tensor>")?;
}
Ok(())
}
pub(crate) fn probe(device: &MlxDevice) -> Result<HostRoutes> {
#[cfg(test)]
if let Some(host) = TEST_HOST.with(|cell| cell.borrow().clone()) {
return Ok(host);
}
if let Some(host) = HOST.get() {
if host.registry_id != device.registry_id() {
return HostRoutes::ask(device, &mut KernelRegistry::new());
}
return Ok(host.clone());
}
let host = HostRoutes::ask(device, &mut KernelRegistry::new())?;
tracing::info!(host = %host.summary(), "fast-route host capability");
Ok(HOST.get_or_init(|| host).clone())
}
pub(crate) fn require_explicit(device: &MlxDevice) -> Result<()> {
require_selected(&|name| std::env::var(name).ok(), || probe(device))
}
pub(crate) fn runs(family: TensorKernelFamily) -> bool {
#[cfg(test)]
if let Some(runs) = TEST_HOST.with(|cell| cell.borrow().as_ref().map(|host| host.runs(family)))
{
return runs;
}
HOST.get().is_none_or(|host| host.runs(family))
}
#[cfg(test)]
mod tests;