use serde::{Deserialize, Serialize};
pub const FRACTION_ONE: u64 = 1 << 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MoeBackend {
Offload,
Hybrid,
Cpu,
Fused,
}
pub const DEFAULT_RECOMMEND_THRESHOLD: f64 = 2.0;
pub fn recommend_backend(cpu_bw_gbs: f64, pcie_bw_gbs: f64, threshold: f64) -> MoeBackend {
if cpu_bw_gbs > threshold * pcie_bw_gbs {
MoeBackend::Hybrid
} else {
MoeBackend::Offload
}
}
pub fn fetch_fraction_from_bandwidths(cpu_gbs: f64, pcie_gbs: f64) -> Option<f64> {
if cpu_gbs <= 0.0 || pcie_gbs <= 0.0 {
return None;
}
Some((pcie_gbs / cpu_gbs).min(1.0))
}
pub fn fetch_fraction_from_overlap(cpu_overlap_gbs: f64, pcie_overlap_gbs: f64) -> Option<f64> {
if cpu_overlap_gbs <= 0.0 || pcie_overlap_gbs <= 0.0 {
return None;
}
Some((pcie_overlap_gbs / (pcie_overlap_gbs + cpu_overlap_gbs)).min(1.0))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QStarSplit {
pub fetch: usize,
pub cpu: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QStarPolicy {
fraction_q16: u64,
max_fetch: usize,
}
impl QStarPolicy {
pub fn fixed_cap(max_fetch: usize) -> Self {
QStarPolicy {
fraction_q16: 0,
max_fetch,
}
}
pub fn from_fraction(fraction: f64) -> Self {
let scaled = (fraction * FRACTION_ONE as f64).round();
let clamped = scaled.clamp(0.0, FRACTION_ONE as f64) as u64;
QStarPolicy {
fraction_q16: clamped,
max_fetch: usize::MAX,
}
}
pub fn fraction_q16(&self) -> u64 {
self.fraction_q16
}
pub fn fraction(&self) -> Option<f64> {
if self.fraction_q16 == 0 {
None
} else {
Some(self.fraction_q16 as f64 / FRACTION_ONE as f64)
}
}
pub fn split(&self, missing: usize) -> QStarSplit {
let fetch = if self.fraction_q16 > 0 {
balanced_fetch(missing, self.fraction_q16).min(missing)
} else {
self.max_fetch.min(missing)
};
QStarSplit {
fetch,
cpu: missing - fetch,
}
}
}
pub fn balanced_fetch(missing: usize, fraction_q16: u64) -> usize {
if fraction_q16 == 0 || missing == 0 {
return 0;
}
let m = missing as i128;
let f = fraction_q16 as i128;
let q = FRACTION_ONE as i128;
let cost = |fetched: i128| -> i128 { (fetched * (q - f)).max((m - fetched) * f) };
let lo = (m * f) >> 16;
let best = if cost(lo) <= cost(lo + 1) { lo } else { lo + 1 };
best.clamp(0, m) as usize
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct KernelBandwidths {
pub cpu_moe_gbs: Option<f64>,
pub pcie_gather_gbs: Option<f64>,
pub cpu_moe_overlap_gbs: Option<f64>,
pub pcie_gather_overlap_gbs: Option<f64>,
pub recommended: Option<MoeBackend>,
}
impl KernelBandwidths {
pub fn fetch_fraction(&self) -> Option<f64> {
if let (Some(cpu), Some(pcie)) = (self.cpu_moe_overlap_gbs, self.pcie_gather_overlap_gbs) {
if let Some(fraction) = fetch_fraction_from_overlap(cpu, pcie) {
return Some(fraction);
}
}
if let (Some(cpu), Some(pcie)) = (self.cpu_moe_gbs, self.pcie_gather_gbs) {
return fetch_fraction_from_bandwidths(cpu, pcie);
}
None
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ProfileGpu {
pub index: Option<u32>,
pub name: Option<String>,
pub uuid: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BandwidthProfile {
pub version: Option<u32>,
pub threshold: Option<f64>,
pub gpu: ProfileGpu,
pub dtypes: std::collections::BTreeMap<String, MoeBackend>,
pub dtype_kernels: std::collections::BTreeMap<String, KernelBandwidths>,
pub workloads: std::collections::BTreeMap<String, Workload>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Workload {
pub kernels: std::collections::BTreeMap<String, KernelBandwidths>,
}
impl BandwidthProfile {
pub fn matches_gpu(&self, gpu_name: Option<&str>) -> bool {
match (self.gpu.name.as_deref(), gpu_name) {
(Some(recorded), Some(actual)) => recorded == actual,
_ => true,
}
}
pub fn backend_for(&self, format: &str) -> Option<MoeBackend> {
if let Some(verdict) = self.dtypes.get(format) {
return Some(*verdict);
}
let picks: Vec<MoeBackend> = self
.workloads
.values()
.filter_map(|w| w.kernels.get(format))
.filter_map(|k| k.recommended)
.collect();
if picks.is_empty() {
return None;
}
Some(if picks.iter().all(|p| *p == MoeBackend::Hybrid) {
MoeBackend::Hybrid
} else {
MoeBackend::Offload
})
}
pub fn fetch_fraction_for(&self, format: &str) -> Option<f64> {
if let Some(fraction) = self
.dtype_kernels
.get(format)
.and_then(KernelBandwidths::fetch_fraction)
{
return Some(fraction);
}
self.workloads
.values()
.filter_map(|w| w.kernels.get(format))
.find_map(KernelBandwidths::fetch_fraction)
}
pub fn policy_for(&self, format: &str) -> QStarPolicy {
match self.fetch_fraction_for(format) {
Some(fraction) => QStarPolicy::from_fraction(fraction),
None => QStarPolicy::fixed_cap(1),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hybrid_has_to_beat_the_link_by_a_real_margin() {
assert_eq!(
recommend_backend(100.0, 40.0, DEFAULT_RECOMMEND_THRESHOLD),
MoeBackend::Hybrid
);
assert_eq!(
recommend_backend(60.0, 40.0, DEFAULT_RECOMMEND_THRESHOLD),
MoeBackend::Offload
);
}
#[test]
fn the_fraction_comes_from_the_two_bandwidths() {
assert_eq!(fetch_fraction_from_bandwidths(100.0, 40.0), Some(0.4));
assert_eq!(fetch_fraction_from_overlap(90.0, 30.0), Some(0.25));
assert_eq!(fetch_fraction_from_bandwidths(10.0, 40.0), Some(1.0));
assert_eq!(fetch_fraction_from_bandwidths(0.0, 40.0), None);
}
#[test]
fn the_split_minimizes_the_slower_side_rather_than_rounding() {
let policy = QStarPolicy::from_fraction(0.415);
assert_eq!(policy.split(3).fetch, 1, "1.24 ideal -> 1, not ceil 2");
assert_eq!(policy.split(4).fetch, 2, "1.66 ideal -> 2");
}
#[test]
fn the_split_tracks_the_fraction_within_one_expert() {
for fraction in [0.1, 0.415, 0.454, 0.7, 1.0] {
let policy = QStarPolicy::from_fraction(fraction);
for missing in 0..=64usize {
let split = policy.split(missing);
assert_eq!(split.fetch + split.cpu, missing, "every miss is assigned");
let ideal = fraction * missing as f64;
assert!(
(split.fetch as f64 - ideal).abs() <= 1.0,
"fraction={fraction} missing={missing} fetch={}",
split.fetch
);
}
}
}
#[test]
fn a_full_fraction_fetches_everything_and_a_zero_cap_fetches_nothing() {
assert_eq!(QStarPolicy::from_fraction(1.0).split(9).fetch, 9);
assert_eq!(QStarPolicy::fixed_cap(0).split(9).fetch, 0);
assert_eq!(QStarPolicy::fixed_cap(0).split(9).cpu, 9);
}
#[test]
fn the_fixed_cap_bounds_fetches_per_step() {
let policy = QStarPolicy::fixed_cap(1);
assert_eq!(policy.split(8), QStarSplit { fetch: 1, cpu: 7 });
assert_eq!(policy.split(0), QStarSplit { fetch: 0, cpu: 0 });
assert_eq!(policy.fraction(), None);
}
fn profile() -> BandwidthProfile {
let json = serde_json::json!({
"version": 4,
"gpu": {"name": "NVIDIA GeForce RTX 4090", "uuid": "GPU-abc"},
"dtypes": {"nvfp4": "hybrid"},
"dtype_kernels": {
"nvfp4": {"cpu_moe_gbs": 100.0, "pcie_gather_gbs": 40.0,
"cpu_moe_overlap_gbs": 90.0, "pcie_gather_overlap_gbs": 30.0},
"bf16": {"cpu_moe_gbs": 100.0, "pcie_gather_gbs": 40.0}
},
"workloads": {
"qwen": {"kernels": {"mxfp4_triton": {"cpu_moe_gbs": 80.0, "pcie_gather_gbs": 50.0,
"recommended": "hybrid"}}}
}
});
serde_json::from_value(json).expect("profile parses")
}
#[test]
fn the_overlapped_measurement_wins_over_the_standalone_ratio() {
let profile = profile();
assert_eq!(profile.fetch_fraction_for("nvfp4"), Some(0.25));
assert_eq!(profile.fetch_fraction_for("bf16"), Some(0.4));
}
#[test]
fn a_per_model_entry_fills_in_for_a_missing_per_format_one() {
let profile = profile();
assert_eq!(profile.fetch_fraction_for("mxfp4_triton"), Some(0.625));
assert_eq!(
profile.backend_for("mxfp4_triton"),
Some(MoeBackend::Hybrid)
);
assert_eq!(profile.backend_for("nvfp4"), Some(MoeBackend::Hybrid));
assert_eq!(profile.backend_for("q4_0"), None);
}
#[test]
fn a_profile_from_another_card_is_refused() {
let profile = profile();
assert!(profile.matches_gpu(Some("NVIDIA GeForce RTX 4090")));
assert!(!profile.matches_gpu(Some("NVIDIA GeForce RTX 3060 Ti")));
assert!(
profile.matches_gpu(None),
"an unnamed card is not a mismatch"
);
}
#[test]
fn an_unmeasured_format_falls_back_to_the_one_fetch_default() {
let profile = profile();
assert_eq!(profile.policy_for("q4_0"), QStarPolicy::fixed_cap(1));
assert_eq!(
profile.policy_for("nvfp4"),
QStarPolicy::from_fraction(0.25)
);
}
}