use std::cell::{Cell, RefCell};
use std::sync::{Arc, LazyLock};
use super::schema::{DFlash2CheckpointDescriptor, QWEN36_DFLASH2, QWEN38_DFLASH2};
use crate::inference::route_host::{self, Grammar};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PlaneSet {
DenseFfn,
Projections,
Head,
MoeExperts,
MoeShared,
}
pub(crate) struct SwitchRow {
pub(crate) name: &'static str,
pub(crate) requires: Option<&'static str>,
pub(crate) planes: &'static [PlaneSet],
pub(crate) qwen38: Option<&'static str>,
pub(crate) qwen36: Option<&'static str>,
}
const fn row(
name: &'static str,
requires: Option<&'static str>,
planes: &'static [PlaneSet],
qwen38: Option<&'static str>,
qwen36: Option<&'static str>,
) -> SwitchRow {
SwitchRow {
name,
requires,
planes,
qwen38,
qwen36,
}
}
const ON: Option<&str> = Some("1");
const AF4: Option<&str> = Some("HF2Q_DFLASH2_DRAFT_AF4_G64");
const M32: Option<&str> = Some("HF2Q_REPACKED_GGUF_M32");
const PREFILL: Option<&str> = Some("HF2Q_QWEN_PREFILL_PREPARED");
const BATCHED: Option<&str> = Some("HF2Q_QWEN_MOE_BATCHED");
const STAGED_M8: Option<&str> = Some("HF2Q_QWEN_MOE_STAGED_M8");
use PlaneSet::{DenseFfn, Head, MoeExperts, MoeShared, Projections};
#[rustfmt::skip]
pub(crate) const SWITCHES: &[SwitchRow] = &[
row("HF2Q_DFLASH2_DRAFT_AF4_G64", None, &[], ON, ON),
row("HF2Q_DFLASH2_DRAFT_STAGED", AF4, &[Head], ON, ON),
row("HF2Q_DFLASH2_GPU_TARGET_TOKENS", None, &[], ON, ON),
row("HF2Q_DFLASH2_CONTEXT_FIRST", None, &[], ON, ON),
row("HF2Q_DFLASH2_DRAFT_PREFETCH", None, &[], ON, ON),
row("HF2Q_DFLASH2_GPU_DECISIONS", None, &[], ON, ON),
row("HF2Q_DFLASH2_PROPOSAL_REPETITION", None, &[], ON, None),
row("HF2Q_REPACKED_GGUF_M32", None, &[DenseFfn], ON, ON),
row("HF2Q_REPACKED_GGUF_M32_PROJ", M32, &[Projections], ON, ON),
row("HF2Q_REPACKED_GGUF_M32_HEAD", M32, &[Head], ON, ON),
row("HF2Q_REPACKED_GGUF_ANY_WIDTH", M32, &[], ON, ON),
row("HF2Q_REPACKED_GGUF_SHARED_HEAD", None, &[], ON, ON),
row("HF2Q_QWEN_VERIFY_ATTN_TILE", None, &[], ON, ON),
row("HF2Q_QWEN_VERIFY_MIXER_FUSED", None, &[], ON, ON),
row("HF2Q_QWEN_VERIFY_REPLAY_REUSE", None, &[], ON, ON),
row("HF2Q_QWEN_PREFILL_PREPARED", None, &[DenseFfn, Projections], ON, ON),
row("HF2Q_QWEN_PREFILL_FOLD_CUE", PREFILL, &[], ON, ON),
row("HF2Q_QWEN_PREFILL_JOINT", PREFILL, &[], ON, ON),
row("HF2Q_QWEN_PREFILL_WAIT_LAYERS", PREFILL, &[], Some("8"), Some("8")),
row("HF2Q_QWEN_PREFILL_KEEP_FRESH", None, &[], None, ON),
row("HF2Q_QWEN_MOE_BATCHED", None, &[], None, ON),
row("HF2Q_QWEN_MOE_STAGED_M8", BATCHED, &[MoeExperts], None, ON),
row("HF2Q_QWEN_MOE_LIVE_TILES", STAGED_M8, &[MoeShared], None, ON),
];
const SWITCH_COUNT: usize = SWITCHES.len();
const _: () = assert!(SWITCH_COUNT <= u32::BITS as usize);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Switch(usize);
const fn same(left: &str, right: &str) -> bool {
let (left, right) = (left.as_bytes(), right.as_bytes());
if left.len() != right.len() {
return false;
}
let mut index = 0;
while index < left.len() {
if left[index] != right[index] {
return false;
}
index += 1;
}
true
}
pub(crate) const fn switch(name: &str) -> Switch {
let mut index = 0;
while index < SWITCH_COUNT {
if same(SWITCHES[index].name, name) {
return Switch(index);
}
index += 1;
}
panic!("switch is not in the DFlash2 route profile table")
}
const GRAMMARS: [Grammar; SWITCH_COUNT] = {
let mut grammars = [Grammar::One; SWITCH_COUNT];
let mut index = 0;
while index < SWITCH_COUNT {
let mut host = 0;
loop {
assert!(
host < route_host::SWITCHES.len(),
"a route profile switch has no row in the host route table"
);
if same(route_host::SWITCHES[host].name, SWITCHES[index].name) {
grammars[index] = route_host::SWITCHES[host].grammar;
break;
}
host += 1;
}
index += 1;
}
grammars
};
pub(crate) fn turns_on(switch: Switch, value: Option<&str>) -> bool {
value.is_some_and(|value| GRAMMARS[switch.0].is_on(value))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum RouteProfile {
Qwen38,
Qwen36,
}
impl RouteProfile {
pub(crate) fn of(descriptor: &DFlash2CheckpointDescriptor) -> Option<Self> {
if descriptor.id == QWEN38_DFLASH2.id {
Some(Self::Qwen38)
} else if descriptor.id == QWEN36_DFLASH2.id {
Some(Self::Qwen36)
} else {
None
}
}
#[cfg(test)]
pub(crate) fn descriptor(self) -> &'static DFlash2CheckpointDescriptor {
match self {
Self::Qwen38 => &QWEN38_DFLASH2,
Self::Qwen36 => &QWEN36_DFLASH2,
}
}
fn value(self, row: &SwitchRow) -> Option<&'static str> {
match self {
Self::Qwen38 => row.qwen38,
Self::Qwen36 => row.qwen36,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SwitchSource {
Env,
Profile,
Default,
Withheld,
}
impl SwitchSource {
fn label(self) -> &'static str {
match self {
Self::Env => "env",
Self::Profile => "profile",
Self::Default => "default",
Self::Withheld => "withheld",
}
}
}
#[derive(Debug)]
pub(crate) struct ResolvedRoutes {
profile: Option<RouteProfile>,
values: [Option<String>; SWITCH_COUNT],
sources: [SwitchSource; SWITCH_COUNT],
withheld: [Option<String>; SWITCH_COUNT],
ones: u32,
on: u32,
}
impl ResolvedRoutes {
pub(crate) fn resolve(
profile: Option<RouteProfile>,
withhold: &dyn Fn(&SwitchRow) -> Option<String>,
env: &dyn Fn(&str) -> Option<String>,
) -> Self {
let mut values: [Option<String>; SWITCH_COUNT] = std::array::from_fn(|_| None);
let mut sources = [SwitchSource::Default; SWITCH_COUNT];
let mut withheld: [Option<String>; SWITCH_COUNT] = std::array::from_fn(|_| None);
let mut ones = 0;
let mut on = 0_u32;
for (index, row) in SWITCHES.iter().enumerate() {
let explicit = env(row.name).filter(|value| !value.trim().is_empty());
let (value, source) = match (explicit, profile.and_then(|profile| profile.value(row))) {
(Some(value), _) => (Some(value), SwitchSource::Env),
(None, None) => (None, SwitchSource::Default),
(None, Some(value)) => {
let unmet = row
.requires
.filter(|required| on & (1 << switch(required).0) == 0);
let reason = match unmet {
Some(required) => Some(format!("{required} is off")),
None => withhold(row),
};
match reason {
Some(reason) => {
withheld[index] = Some(reason);
(None, SwitchSource::Withheld)
}
None => (Some(value.to_owned()), SwitchSource::Profile),
}
}
};
if value.as_deref() == Some("1") {
ones |= 1 << index;
}
if turns_on(Switch(index), value.as_deref()) {
on |= 1 << index;
}
values[index] = value;
sources[index] = source;
}
Self {
profile,
values,
sources,
withheld,
ones,
on,
}
}
pub(crate) fn from_process_env() -> Self {
Self::resolve(None, &|_| None, &process_value)
}
pub(crate) fn profile(&self) -> Option<RouteProfile> {
self.profile
}
pub(crate) fn any_withheld(&self) -> bool {
self.withheld.iter().any(Option::is_some)
}
pub(crate) fn withheld_audit(&self) -> String {
let reasons: Vec<String> = SWITCHES
.iter()
.zip(&self.withheld)
.filter_map(|(row, reason)| Some(format!("{}: {}", row.name, reason.as_deref()?)))
.collect();
if reasons.is_empty() {
"none".to_owned()
} else {
reasons.join("; ")
}
}
pub(crate) fn value(&self, switch: Switch) -> Option<&str> {
self.values[switch.0].as_deref()
}
#[cfg(test)]
pub(crate) fn source(&self, switch: Switch) -> SwitchSource {
self.sources[switch.0]
}
#[cfg(test)]
pub(crate) fn is_one(&self, switch: Switch) -> bool {
self.ones & (1 << switch.0) != 0
}
pub(crate) fn is_on(&self, switch: Switch) -> bool {
self.on & (1 << switch.0) != 0
}
pub(crate) fn entries(
&self,
) -> impl Iterator<Item = (&'static str, Option<&str>, &'static str, Option<&str>)> {
SWITCHES.iter().enumerate().map(|(index, row)| {
(
row.name,
self.values[index].as_deref(),
self.sources[index].label(),
self.withheld[index].as_deref(),
)
})
}
pub(crate) fn plane_sets(&self) -> Vec<PlaneSet> {
let mut sets = Vec::new();
for (index, row) in SWITCHES.iter().enumerate() {
if self.is_on(Switch(index)) {
for set in row.planes {
if !sets.contains(set) {
sets.push(*set);
}
}
}
}
sets
}
pub(crate) fn audit(&self) -> String {
SWITCHES
.iter()
.enumerate()
.map(|(index, row)| {
format!(
"{}={}({})",
row.name,
self.values[index].as_deref().unwrap_or("unset"),
self.sources[index].label()
)
})
.collect::<Vec<_>>()
.join(" ")
}
}
thread_local! {
static BOUND: RefCell<Option<Arc<ResolvedRoutes>>> = const { RefCell::new(None) };
static BOUND_ONES: Cell<Option<u32>> = const { Cell::new(None) };
static BOUND_ON: Cell<Option<u32>> = const { Cell::new(None) };
}
pub(crate) fn process_value(name: &str) -> Option<String> {
match std::env::var(name) {
Ok(value) => Some(value),
Err(std::env::VarError::NotPresent) => None,
Err(std::env::VarError::NotUnicode(value)) => Some(value.to_string_lossy().into_owned()),
}
}
static PROCESS: LazyLock<Arc<ResolvedRoutes>> =
LazyLock::new(|| Arc::new(ResolvedRoutes::from_process_env()));
pub(crate) fn current() -> Arc<ResolvedRoutes> {
BOUND
.with(|bound| bound.borrow().clone())
.unwrap_or_else(|| Arc::clone(&PROCESS))
}
pub(crate) fn with_value<R>(switch: Switch, read: impl FnOnce(Option<&str>) -> R) -> R {
BOUND.with(|bound| match bound.borrow().as_deref() {
Some(routes) => read(routes.value(switch)),
None => read(PROCESS.value(switch)),
})
}
pub(crate) fn is_one(switch: Switch) -> bool {
let ones = BOUND_ONES.with(Cell::get).unwrap_or_else(|| PROCESS.ones);
ones & (1 << switch.0) != 0
}
pub(crate) fn is_on(switch: Switch) -> bool {
let on = BOUND_ON.with(Cell::get).unwrap_or_else(|| PROCESS.on);
on & (1 << switch.0) != 0
}
fn replace(routes: Option<Arc<ResolvedRoutes>>) -> Option<Arc<ResolvedRoutes>> {
BOUND_ONES.with(|ones| ones.set(routes.as_ref().map(|routes| routes.ones)));
BOUND_ON.with(|on| on.set(routes.as_ref().map(|routes| routes.on)));
BOUND.with(|bound| bound.replace(routes))
}
pub(crate) struct Bound {
previous: Option<Arc<ResolvedRoutes>>,
}
#[must_use]
pub(crate) fn bind(routes: Arc<ResolvedRoutes>) -> Bound {
Bound {
previous: replace(Some(routes)),
}
}
pub(crate) fn bind_thread(routes: Arc<ResolvedRoutes>) {
replace(Some(routes));
}
impl Drop for Bound {
fn drop(&mut self) {
replace(self.previous.take());
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect();
move |name| map.get(name).cloned()
}
const M32: Switch = switch("HF2Q_REPACKED_GGUF_M32");
const PREFILL: Switch = switch("HF2Q_QWEN_PREFILL_PREPARED");
const MOE_BATCHED: Switch = switch("HF2Q_QWEN_MOE_BATCHED");
const MOE_STAGED: Switch = switch("HF2Q_QWEN_MOE_STAGED_M8");
const GPU_TOKENS: Switch = switch("HF2Q_DFLASH2_GPU_TARGET_TOKENS");
const ATTN_TILE: Switch = switch("HF2Q_QWEN_VERIFY_ATTN_TILE");
#[test]
fn table_names_are_unique_hf2q_switches() {
for (index, row) in SWITCHES.iter().enumerate() {
assert!(row.name.starts_with("HF2Q_"), "{}", row.name);
assert_eq!(switch(row.name), Switch(index), "duplicate {}", row.name);
}
}
#[test]
fn without_a_profile_every_switch_is_the_environment_or_unset() {
let none = ResolvedRoutes::resolve(None, &|_| None, &env(&[]));
assert_eq!(none.ones, 0);
for index in 0..SWITCH_COUNT {
assert_eq!(none.value(Switch(index)), None);
assert_eq!(none.source(Switch(index)), SwitchSource::Default);
}
assert!(none.plane_sets().is_empty());
let explicit = ResolvedRoutes::resolve(
None,
&|_| None,
&env(&[
("HF2Q_REPACKED_GGUF_M32", "1"),
("HF2Q_QWEN_MOE_BATCHED", "on"),
]),
);
assert!(explicit.is_one(M32));
assert_eq!(explicit.source(M32), SwitchSource::Env);
assert_eq!(explicit.value(MOE_BATCHED), Some("on"));
assert!(!explicit.is_one(MOE_BATCHED), "`on` is not exactly 1");
assert_eq!(explicit.value(PREFILL), None);
assert_eq!(explicit.plane_sets(), vec![PlaneSet::DenseFfn]);
}
#[test]
fn a_switch_is_on_only_by_the_grammar_of_its_own_reader() {
for (name, value, on) in [
("HF2Q_REPACKED_GGUF_M32", "1", true),
("HF2Q_REPACKED_GGUF_M32", "on", false),
("HF2Q_REPACKED_GGUF_M32", "true", false),
("HF2Q_REPACKED_GGUF_M32", " 1", false),
("HF2Q_REPACKED_GGUF_M32", "0", false),
("HF2Q_QWEN_PREFILL_PREPARED", "1", true),
("HF2Q_QWEN_PREFILL_PREPARED", "on", true),
("HF2Q_QWEN_PREFILL_PREPARED", " TRUE ", true),
("HF2Q_QWEN_PREFILL_PREPARED", "0", false),
("HF2Q_QWEN_MOE_BATCHED", "on", true),
("HF2Q_QWEN_MOE_STAGED_M8", "yes", false),
] {
assert_eq!(turns_on(switch(name), Some(value)), on, "{name}={value:?}");
let routes = ResolvedRoutes::resolve(None, &|_| None, &env(&[(name, value)]));
assert_eq!(routes.is_on(switch(name)), on, "{name}={value:?}");
}
assert!(!turns_on(M32, None));
for (index, row) in SWITCHES.iter().enumerate() {
let host = route_host::SWITCHES
.iter()
.find(|host| host.name == row.name)
.expect("host row");
assert_eq!(GRAMMARS[index], host.grammar, "{}", row.name);
}
let off = ResolvedRoutes::resolve(
Some(RouteProfile::Qwen38),
&|_| None,
&env(&[("HF2Q_REPACKED_GGUF_M32", "on")]),
);
assert!(!off.is_on(M32));
for name in [
"HF2Q_REPACKED_GGUF_M32_PROJ",
"HF2Q_REPACKED_GGUF_M32_HEAD",
"HF2Q_REPACKED_GGUF_ANY_WIDTH",
] {
assert_eq!(off.source(switch(name)), SwitchSource::Withheld, "{name}");
}
let prefill = ResolvedRoutes::resolve(
None,
&|_| None,
&env(&[
("HF2Q_QWEN_PREFILL_PREPARED", "on"),
("HF2Q_REPACKED_GGUF_M32_HEAD", "true"),
]),
);
assert_eq!(
prefill.plane_sets(),
vec![PlaneSet::DenseFfn, PlaneSet::Projections]
);
}
#[test]
fn profile_plane_sets_are_charged_once() {
let moe = ResolvedRoutes::resolve(Some(RouteProfile::Qwen36), &|_| None, &env(&[]));
assert_eq!(
moe.plane_sets(),
vec![
PlaneSet::Head,
PlaneSet::DenseFfn,
PlaneSet::Projections,
PlaneSet::MoeExperts,
PlaneSet::MoeShared
]
);
}
#[test]
fn an_explicit_value_overrides_the_profile_in_both_directions() {
let routes = ResolvedRoutes::resolve(
Some(RouteProfile::Qwen38),
&|_| None,
&env(&[
("HF2Q_QWEN_PREFILL_PREPARED", "0"),
("HF2Q_QWEN_VERIFY_ATTN_TILE", "0"),
("HF2Q_DFLASH2_GPU_TARGET_TOKENS", "0"),
("HF2Q_QWEN_MOE_BATCHED", "1"),
("HF2Q_REPACKED_GGUF_M32", " "),
]),
);
assert_eq!(routes.value(PREFILL), Some("0"));
assert_eq!(routes.source(PREFILL), SwitchSource::Env);
assert!(!routes.is_one(ATTN_TILE));
assert_eq!(routes.value(GPU_TOKENS), Some("0"));
assert!(routes.is_one(MOE_BATCHED));
assert_eq!(routes.source(MOE_BATCHED), SwitchSource::Env);
assert!(routes.is_one(M32));
assert_eq!(routes.source(M32), SwitchSource::Profile);
}
#[test]
fn a_withheld_row_keeps_its_default_and_takes_its_dependents_with_it() {
let routes = ResolvedRoutes::resolve(
Some(RouteProfile::Qwen36),
&|row| {
(row.name == "HF2Q_QWEN_MOE_BATCHED").then(|| "shared expert is Q5_K".to_owned())
},
&env(&[("HF2Q_REPACKED_GGUF_M32", "0")]),
);
for name in [
"HF2Q_QWEN_MOE_BATCHED",
"HF2Q_QWEN_MOE_STAGED_M8",
"HF2Q_QWEN_MOE_LIVE_TILES",
"HF2Q_REPACKED_GGUF_M32_PROJ",
"HF2Q_REPACKED_GGUF_M32_HEAD",
"HF2Q_REPACKED_GGUF_ANY_WIDTH",
] {
assert_eq!(routes.value(switch(name)), None, "{name}");
assert_eq!(
routes.source(switch(name)),
SwitchSource::Withheld,
"{name}"
);
}
assert_eq!(routes.source(M32), SwitchSource::Env);
assert!(
routes.is_one(PREFILL),
"an unrelated row keeps its profile value"
);
assert!(routes.any_withheld());
let audit = routes.withheld_audit();
assert!(
audit.contains("HF2Q_QWEN_MOE_BATCHED: shared expert is Q5_K"),
"{audit}"
);
assert!(
audit.contains("HF2Q_QWEN_MOE_STAGED_M8: HF2Q_QWEN_MOE_BATCHED is off"),
"{audit}"
);
assert!(
audit.contains("HF2Q_REPACKED_GGUF_M32_PROJ: HF2Q_REPACKED_GGUF_M32 is off"),
"{audit}"
);
assert_eq!(
routes.plane_sets(),
vec![PlaneSet::Head, PlaneSet::DenseFfn, PlaneSet::Projections]
);
assert!(routes
.audit()
.contains("HF2Q_QWEN_MOE_BATCHED=unset(withheld)"));
let explicit = ResolvedRoutes::resolve(
Some(RouteProfile::Qwen36),
&|row| (row.name == "HF2Q_QWEN_MOE_BATCHED").then(|| "test".to_owned()),
&env(&[("HF2Q_QWEN_MOE_STAGED_M8", "1")]),
);
assert!(explicit.is_one(MOE_STAGED));
assert_eq!(explicit.source(MOE_STAGED), SwitchSource::Env);
let full = ResolvedRoutes::resolve(Some(RouteProfile::Qwen36), &|_| None, &env(&[]));
assert!(!full.any_withheld());
assert_eq!(full.withheld_audit(), "none");
}
#[test]
fn every_requirement_names_an_earlier_row() {
for (index, row) in SWITCHES.iter().enumerate() {
if let Some(required) = row.requires {
assert!(
switch(required).0 < index,
"{} requires {required}",
row.name
);
}
}
}
#[test]
fn audit_names_every_switch_with_its_value_and_source() {
let routes = ResolvedRoutes::resolve(
Some(RouteProfile::Qwen38),
&|_| None,
&env(&[("HF2Q_QWEN_VERIFY_ATTN_TILE", "0")]),
);
let audit = routes.audit();
assert_eq!(audit.split(' ').count(), SWITCH_COUNT);
assert!(audit.contains("HF2Q_REPACKED_GGUF_M32=1(profile)"));
assert!(audit.contains("HF2Q_QWEN_VERIFY_ATTN_TILE=0(env)"));
assert!(audit.contains("HF2Q_QWEN_MOE_BATCHED=unset(default)"));
}
#[test]
fn a_binding_is_per_thread_and_restored_on_drop() {
let keep_fresh =
crate::inference::models::qwen35::prefill_keep_fresh::QWEN_PREFILL_KEEP_FRESH_ENV;
let enabled = crate::inference::models::qwen35::prefill_keep_fresh::enabled;
let before = enabled();
let bound = Arc::new(ResolvedRoutes::resolve(
Some(RouteProfile::Qwen36),
&|_| None,
&env(&[(keep_fresh, " TrUe ")]),
));
let inner = Arc::new(ResolvedRoutes::resolve(None, &|_| None, &env(&[])));
let unbound = || BOUND.with(|bound| bound.borrow().is_none());
{
let _outer = bind(Arc::clone(&bound));
assert!(is_one(MOE_BATCHED));
assert!(with_value(MOE_BATCHED, |value| value == Some("1")));
assert!(enabled());
assert_eq!(current().profile(), Some(RouteProfile::Qwen36));
{
let _inner = bind(inner);
assert!(!is_one(MOE_BATCHED));
assert!(with_value(MOE_BATCHED, |value| value.is_none()));
assert!(!enabled());
}
assert!(is_one(MOE_BATCHED), "restored");
assert!(enabled(), "grammar-aware reader restored");
assert!(std::thread::spawn(unbound).join().expect("thread"));
}
assert!(unbound());
assert_eq!(BOUND_ONES.with(Cell::get), None);
assert_eq!(enabled(), before, "process binding restored");
}
#[test]
fn every_profile_belongs_to_a_pinned_qwen_descriptor() {
for profile in [RouteProfile::Qwen38, RouteProfile::Qwen36] {
let descriptor = profile.descriptor();
assert_eq!(RouteProfile::of(descriptor), Some(profile));
assert!(descriptor.target_source_sha256.is_some());
}
assert_eq!(
RouteProfile::of(&super::super::schema::GEMMA4_E2B_DFLASH2),
None
);
}
}