use std::path::{Path, PathBuf};
use crate::qstar::{BandwidthProfile, MoeBackend, QStarPolicy};
pub const PROFILE_PATH_ENV: &str = "FERROX_BENCHBW_PATH";
pub const PROFILE_SUBDIR: &str = "benchbw";
pub const LEGACY_PROFILE_FILE: &str = "benchbw.json";
pub fn bench_format(quant_format: &str) -> &str {
match quant_format {
"nvfp4" => "nvfp4",
"ds_fp4" => "ds_fp4",
"mxfp4" => "mxfp4_triton",
"bf16" => "bf16",
"fp8_block" => "fp8_block",
other => other,
}
}
pub fn cache_dir() -> PathBuf {
std::env::var("XDG_CACHE_HOME")
.ok()
.filter(|s| !s.is_empty())
.map(PathBuf::from)
.or_else(|| {
std::env::var("HOME")
.ok()
.filter(|s| !s.is_empty())
.map(|h| PathBuf::from(h).join(".cache"))
})
.unwrap_or_else(std::env::temp_dir)
.join("ferrox")
}
pub fn env_profile_path() -> Option<PathBuf> {
std::env::var(PROFILE_PATH_ENV)
.ok()
.filter(|s| !s.is_empty())
.map(PathBuf::from)
}
pub fn default_profile_path_in(cache_dir: &Path, gpu_uuid: Option<&str>) -> PathBuf {
match gpu_uuid.filter(|u| !u.is_empty()) {
Some(uuid) => cache_dir.join(PROFILE_SUBDIR).join(format!("{uuid}.json")),
None => cache_dir.join(LEGACY_PROFILE_FILE),
}
}
pub fn default_profile_path(gpu_uuid: Option<&str>) -> PathBuf {
default_profile_path_in(&cache_dir(), gpu_uuid)
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Measured {
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>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotMeasurable {
OnlyOneSide,
NotPositive,
}
impl std::fmt::Display for NotMeasurable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotMeasurable::OnlyOneSide => write!(
f,
"only one side was measured; the fetch fraction is a ratio of \
the two, so one number alone says nothing about the split"
),
NotMeasurable::NotPositive => {
write!(
f,
"a bandwidth came back at or below zero, which is a failed measurement"
)
}
}
}
}
impl std::error::Error for NotMeasurable {}
pub fn entry_from(
measured: &Measured,
threshold: f64,
) -> Result<crate::qstar::KernelBandwidths, NotMeasurable> {
let positive = |v: Option<f64>| -> Result<Option<f64>, NotMeasurable> {
match v {
Some(x) if x > 0.0 && x.is_finite() => Ok(Some(x)),
Some(_) => Err(NotMeasurable::NotPositive),
None => Ok(None),
}
};
let cpu = positive(measured.cpu_moe_gbs)?;
let pcie = positive(measured.pcie_gather_gbs)?;
let cpu_ov = positive(measured.cpu_moe_overlap_gbs)?;
let pcie_ov = positive(measured.pcie_gather_overlap_gbs)?;
if cpu.is_some() != pcie.is_some() || cpu_ov.is_some() != pcie_ov.is_some() {
return Err(NotMeasurable::OnlyOneSide);
}
let (Some(cpu), Some(pcie)) = (cpu, pcie) else {
return Err(NotMeasurable::OnlyOneSide);
};
let (verdict_cpu, verdict_pcie) = match (cpu_ov, pcie_ov) {
(Some(c), Some(p)) => (c, p),
_ => (cpu, pcie),
};
Ok(crate::qstar::KernelBandwidths {
cpu_moe_gbs: Some(cpu),
pcie_gather_gbs: Some(pcie),
cpu_moe_overlap_gbs: cpu_ov,
pcie_gather_overlap_gbs: pcie_ov,
recommended: Some(crate::qstar::recommend_backend(
verdict_cpu,
verdict_pcie,
threshold,
)),
})
}
pub fn write_profile(path: &Path, profile: &BandwidthProfile) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let body = serde_json::to_vec_pretty(profile)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let tmp = path.with_extension("json.partial");
std::fs::write(&tmp, body)?;
std::fs::rename(&tmp, path)
}
pub fn latest_profile_path_in(cache_dir: &Path) -> Option<PathBuf> {
let mut found: Vec<(std::time::SystemTime, PathBuf)> = Vec::new();
if let Ok(entries) = std::fs::read_dir(cache_dir.join(PROFILE_SUBDIR)) {
for entry in entries.flatten() {
if !entry.file_name().to_string_lossy().ends_with(".json") {
continue;
}
let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
continue;
};
found.push((mtime, entry.path()));
}
}
if let Some((_, path)) = found.into_iter().max() {
return Some(path);
}
let legacy = default_profile_path_in(cache_dir, None);
legacy.is_file().then_some(legacy)
}
pub fn latest_profile_path() -> Option<PathBuf> {
latest_profile_path_in(&cache_dir())
}
pub fn read_profile(path: &Path) -> Option<BandwidthProfile> {
match read_candidate(path) {
Candidate::Profile(profile) => Some(*profile),
_ => None,
}
}
enum Candidate {
Missing,
Corrupt,
Profile(Box<BandwidthProfile>),
}
fn read_candidate(path: &Path) -> Candidate {
let body = match std::fs::read_to_string(path) {
Ok(body) => body,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Candidate::Missing,
Err(_) => return Candidate::Corrupt,
};
match serde_json::from_str::<BandwidthProfile>(&body) {
Ok(profile) => Candidate::Profile(Box::new(profile)),
Err(_) => Candidate::Corrupt,
}
}
fn candidate_paths(cache_dir: &Path, path: Option<&Path>, gpu_uuid: Option<&str>) -> Vec<PathBuf> {
if let Some(explicit) = path {
return vec![explicit.to_path_buf()];
}
let mut candidates = Vec::with_capacity(2);
if gpu_uuid.is_some_and(|u| !u.is_empty()) {
candidates.push(default_profile_path_in(cache_dir, gpu_uuid));
}
candidates.push(default_profile_path_in(cache_dir, None));
candidates
}
pub fn usable_profile_in(
cache_dir: &Path,
gpu_name: Option<&str>,
path: Option<&Path>,
gpu_uuid: Option<&str>,
) -> Option<BandwidthProfile> {
let mut found: Option<BandwidthProfile> = None;
for candidate in candidate_paths(cache_dir, path, gpu_uuid) {
match read_candidate(&candidate) {
Candidate::Profile(profile) => {
found = Some(*profile);
break;
}
Candidate::Corrupt => return None,
Candidate::Missing => continue,
}
}
let profile = found?;
profile.matches_gpu(gpu_name).then_some(profile)
}
pub fn usable_profile(
gpu_name: Option<&str>,
path: Option<&Path>,
gpu_uuid: Option<&str>,
) -> Option<BandwidthProfile> {
let from_env = path.is_none().then(env_profile_path).flatten();
let explicit = path.or(from_env.as_deref());
usable_profile_in(&cache_dir(), gpu_name, explicit, gpu_uuid)
}
pub fn load_backend_recommendation(
quant_format: &str,
gpu_name: Option<&str>,
path: Option<&Path>,
gpu_uuid: Option<&str>,
) -> Option<MoeBackend> {
usable_profile(gpu_name, path, gpu_uuid)?.backend_for(bench_format(quant_format))
}
pub fn load_hybrid_fetch_fraction(
quant_format: &str,
gpu_name: Option<&str>,
path: Option<&Path>,
gpu_uuid: Option<&str>,
) -> Option<f64> {
usable_profile(gpu_name, path, gpu_uuid)?.fetch_fraction_for(bench_format(quant_format))
}
pub fn load_policy(
quant_format: &str,
gpu_name: Option<&str>,
path: Option<&Path>,
gpu_uuid: Option<&str>,
) -> QStarPolicy {
match usable_profile(gpu_name, path, gpu_uuid) {
Some(profile) => profile.policy_for(bench_format(quant_format)),
None => QStarPolicy::fixed_cap(1),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Self {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"ferrox-edge-bench-profile-{}-{tag}-{n}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir is creatable");
TempDir { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn write(path: &Path, body: &str) {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("parent is creatable");
}
std::fs::write(path, body).expect("file is writable");
}
fn set_mtime(path: &Path, epoch_secs: u64) {
let file = std::fs::File::options()
.write(true)
.open(path)
.expect("file is openable");
file.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(epoch_secs))
.expect("mtime is settable");
}
const CARD_PROFILE: &str = r#"{
"version": 4,
"gpu": {"name": "NVIDIA GeForce RTX 4090", "uuid": "GPU-slot0"},
"dtypes": {"nvfp4": "hybrid", "mxfp4_triton": "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},
"mxfp4_triton": {"cpu_moe_gbs": 80.0, "pcie_gather_gbs": 50.0}
}
}"#;
const LEGACY_PROFILE: &str = r#"{
"version": 4,
"gpu": {"name": "NVIDIA GeForce RTX 4090", "uuid": "GPU-other"},
"dtypes": {"nvfp4": "offload"},
"dtype_kernels": {
"nvfp4": {"cpu_moe_overlap_gbs": 80.0, "pcie_gather_overlap_gbs": 20.0}
}
}"#;
#[test]
fn the_quant_name_maps_onto_the_bench_format_key() {
assert_eq!(bench_format("mxfp4"), "mxfp4_triton");
assert_eq!(bench_format("nvfp4"), "nvfp4");
assert_eq!(bench_format("ds_fp4"), "ds_fp4");
assert_eq!(bench_format("bf16"), "bf16");
assert_eq!(bench_format("fp8_block"), "fp8_block");
}
#[test]
fn an_unmapped_quant_name_is_passed_through_and_finds_no_entry() {
assert_eq!(bench_format("q4_k_m"), "q4_k_m");
let dir = TempDir::new("unmapped");
let path = dir.path().join("profile.json");
write(&path, CARD_PROFILE);
assert_eq!(
load_hybrid_fetch_fraction("q4_k_m", None, Some(&path), None),
None
);
assert_eq!(
load_backend_recommendation("q4_k_m", None, Some(&path), None),
None
);
assert_eq!(
load_policy("q4_k_m", None, Some(&path), None),
QStarPolicy::fixed_cap(1)
);
}
#[test]
fn the_profile_path_is_one_file_per_gpu_uuid() {
let root = Path::new("/cache/ferrox");
assert_eq!(
default_profile_path_in(root, Some("GPU-slot0")),
Path::new("/cache/ferrox/benchbw/GPU-slot0.json")
);
assert_eq!(
default_profile_path_in(root, Some("GPU-slot1")),
Path::new("/cache/ferrox/benchbw/GPU-slot1.json")
);
assert_eq!(
default_profile_path_in(root, None),
Path::new("/cache/ferrox/benchbw.json")
);
assert_eq!(
default_profile_path_in(root, Some("")),
Path::new("/cache/ferrox/benchbw.json"),
"an empty uuid is no uuid"
);
}
#[test]
fn the_newest_per_gpu_profile_is_the_latest_one() {
let dir = TempDir::new("latest");
let older = dir.path().join(PROFILE_SUBDIR).join("GPU-slot0.json");
let newer = dir.path().join(PROFILE_SUBDIR).join("GPU-slot1.json");
write(&older, CARD_PROFILE);
write(&newer, CARD_PROFILE);
write(&dir.path().join(LEGACY_PROFILE_FILE), LEGACY_PROFILE);
set_mtime(&older, 1_700_000_000);
set_mtime(&newer, 1_700_000_100);
assert_eq!(latest_profile_path_in(dir.path()), Some(newer.clone()));
set_mtime(&older, 1_700_000_200);
assert_eq!(latest_profile_path_in(dir.path()), Some(older));
}
#[test]
fn the_legacy_file_answers_when_there_is_no_per_gpu_profile() {
let dir = TempDir::new("legacy-latest");
assert_eq!(
latest_profile_path_in(dir.path()),
None,
"an unbenched host has no profile at all"
);
let legacy = dir.path().join(LEGACY_PROFILE_FILE);
write(&legacy, LEGACY_PROFILE);
assert_eq!(latest_profile_path_in(dir.path()), Some(legacy));
}
#[test]
fn a_corrupt_profile_for_this_card_is_not_replaced_by_the_legacy_file() {
let dir = TempDir::new("corrupt");
write(
&dir.path().join(PROFILE_SUBDIR).join("GPU-slot0.json"),
"{\"dtypes\": {\"nvfp4\": \"hyb",
);
write(&dir.path().join(LEGACY_PROFILE_FILE), LEGACY_PROFILE);
assert!(
usable_profile_in(dir.path(), None, None, Some("GPU-slot0")).is_none(),
"a half-written profile for this card must not borrow the legacy file"
);
assert!(usable_profile_in(dir.path(), None, None, None).is_some());
}
#[test]
fn a_json_value_that_is_not_a_profile_counts_as_corrupt() {
let dir = TempDir::new("not-a-document");
write(
&dir.path().join(PROFILE_SUBDIR).join("GPU-slot0.json"),
"[1, 2, 3]",
);
write(&dir.path().join(LEGACY_PROFILE_FILE), LEGACY_PROFILE);
assert!(usable_profile_in(dir.path(), None, None, Some("GPU-slot0")).is_none());
}
#[test]
fn a_missing_per_gpu_profile_falls_through_to_the_legacy_file() {
let dir = TempDir::new("fallthrough");
write(&dir.path().join(LEGACY_PROFILE_FILE), LEGACY_PROFILE);
let profile = usable_profile_in(dir.path(), None, None, Some("GPU-slot0"))
.expect("the legacy file answers for an unbenched card");
assert_eq!(profile.fetch_fraction_for("nvfp4"), Some(0.2));
}
#[test]
fn the_per_gpu_profile_wins_over_the_legacy_file() {
let dir = TempDir::new("per-gpu-wins");
write(
&dir.path().join(PROFILE_SUBDIR).join("GPU-slot0.json"),
CARD_PROFILE,
);
write(&dir.path().join(LEGACY_PROFILE_FILE), LEGACY_PROFILE);
let profile = usable_profile_in(dir.path(), None, None, Some("GPU-slot0"))
.expect("the card's own profile is usable");
assert_eq!(profile.fetch_fraction_for("nvfp4"), Some(0.25));
assert_eq!(profile.backend_for("nvfp4"), Some(MoeBackend::Hybrid));
}
#[test]
fn an_explicit_path_is_the_only_candidate_considered() {
let dir = TempDir::new("explicit");
write(
&dir.path().join(PROFILE_SUBDIR).join("GPU-slot0.json"),
CARD_PROFILE,
);
write(&dir.path().join(LEGACY_PROFILE_FILE), LEGACY_PROFILE);
let absent = dir.path().join("typo.json");
assert!(usable_profile_in(dir.path(), None, Some(&absent), Some("GPU-slot0")).is_none());
let broken = dir.path().join("broken.json");
write(&broken, "not json at all");
assert!(usable_profile_in(dir.path(), None, Some(&broken), Some("GPU-slot0")).is_none());
}
#[test]
fn a_profile_measured_on_another_card_is_ignored() {
let dir = TempDir::new("other-card");
let path = dir.path().join("profile.json");
write(&path, CARD_PROFILE);
assert!(usable_profile_in(
dir.path(),
Some("NVIDIA GeForce RTX 4090"),
Some(&path),
None
)
.is_some());
assert!(
usable_profile_in(
dir.path(),
Some("NVIDIA GeForce RTX 3060 Ti"),
Some(&path),
None
)
.is_none(),
"another card's bandwidths are worse than no bandwidths"
);
}
#[test]
fn the_loaders_resolve_the_quant_name_before_the_lookup() {
let dir = TempDir::new("loaders");
let path = dir.path().join("profile.json");
write(&path, CARD_PROFILE);
assert_eq!(
load_hybrid_fetch_fraction("mxfp4", None, Some(&path), None),
Some(0.625),
"mxfp4 is benched under mxfp4_triton"
);
assert_eq!(
load_backend_recommendation("mxfp4", None, Some(&path), None),
Some(MoeBackend::Hybrid)
);
assert_eq!(
load_hybrid_fetch_fraction("nvfp4", None, Some(&path), None),
Some(0.25)
);
assert_eq!(
load_policy("nvfp4", None, Some(&path), None),
QStarPolicy::from_fraction(0.25)
);
}
#[test]
fn the_loaders_return_none_without_a_usable_profile() {
let dir = TempDir::new("no-profile");
let absent = dir.path().join("nothing.json");
assert_eq!(
load_backend_recommendation("nvfp4", None, Some(&absent), None),
None
);
assert_eq!(
load_hybrid_fetch_fraction("nvfp4", None, Some(&absent), None),
None
);
assert_eq!(
load_policy("nvfp4", None, Some(&absent), None),
QStarPolicy::fixed_cap(1)
);
}
#[test]
fn reading_a_profile_yields_the_document_or_nothing() {
let dir = TempDir::new("read");
let path = dir.path().join("profile.json");
write(&path, CARD_PROFILE);
let profile = read_profile(&path).expect("the fixture parses");
assert_eq!(profile.gpu.uuid.as_deref(), Some("GPU-slot0"));
assert_eq!(read_profile(&dir.path().join("absent.json")), None);
assert_eq!(read_profile(dir.path()), None, "a directory is not a file");
}
#[test]
fn the_cache_directory_is_absolute_and_ends_in_ferrox() {
let dir = cache_dir();
assert!(dir.is_absolute(), "{dir:?}");
assert_eq!(dir.file_name().and_then(|n| n.to_str()), Some("ferrox"));
}
#[test]
fn one_side_measured_is_not_a_measurement() {
assert_eq!(
entry_from(
&Measured {
cpu_moe_gbs: Some(50.0),
..Measured::default()
},
1.0
),
Err(NotMeasurable::OnlyOneSide)
);
assert_eq!(
entry_from(
&Measured {
pcie_gather_gbs: Some(20.0),
..Measured::default()
},
1.0
),
Err(NotMeasurable::OnlyOneSide)
);
assert_eq!(
entry_from(
&Measured {
cpu_moe_gbs: Some(50.0),
pcie_gather_gbs: Some(20.0),
cpu_moe_overlap_gbs: Some(30.0),
pcie_gather_overlap_gbs: None,
},
1.0
),
Err(NotMeasurable::OnlyOneSide)
);
}
#[test]
fn a_bandwidth_at_or_below_zero_is_a_failed_measurement() {
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert_eq!(
entry_from(
&Measured {
cpu_moe_gbs: Some(bad),
pcie_gather_gbs: Some(20.0),
..Measured::default()
},
1.0
),
Err(NotMeasurable::NotPositive),
"{bad} must not become a profile entry"
);
}
}
#[test]
fn the_verdict_and_the_fraction_read_the_same_numbers() {
let measured = Measured {
cpu_moe_gbs: Some(100.0),
pcie_gather_gbs: Some(20.0),
cpu_moe_overlap_gbs: Some(10.0),
pcie_gather_overlap_gbs: Some(19.0),
};
let entry = entry_from(&measured, 1.0).expect("both sides measured");
assert_eq!(
entry.recommended,
Some(crate::qstar::MoeBackend::Offload),
"the contended pair is what the machine actually does"
);
let fraction = entry.fetch_fraction().expect("a pair exists");
let from_pair = crate::qstar::fetch_fraction_from_overlap(10.0, 19.0).unwrap();
assert!((fraction - from_pair).abs() < 1e-9);
let standalone = entry_from(
&Measured {
cpu_moe_gbs: Some(100.0),
pcie_gather_gbs: Some(20.0),
..Measured::default()
},
1.0,
)
.unwrap();
assert_eq!(
standalone.recommended,
Some(crate::qstar::MoeBackend::Hybrid)
);
}
#[test]
fn a_profile_is_written_atomically_and_reads_back() {
let dir = std::env::temp_dir().join(format!(
"ferrox-benchbw-write-{}-{}",
std::process::id(),
line!()
));
let _ = std::fs::remove_dir_all(&dir);
let path = default_profile_path_in(&dir, Some("GPU-abc"));
let mut profile = BandwidthProfile {
threshold: Some(1.0),
..BandwidthProfile::default()
};
profile.gpu.name = Some("NVIDIA GeForce RTX 4090".to_string());
profile.gpu.uuid = Some("GPU-abc".to_string());
profile.dtype_kernels.insert(
"q4_k".to_string(),
entry_from(
&Measured {
cpu_moe_gbs: Some(80.0),
pcie_gather_gbs: Some(20.0),
..Measured::default()
},
1.0,
)
.unwrap(),
);
write_profile(&path, &profile).expect("writes");
let read = read_profile(&path).expect("reads back");
assert_eq!(read.gpu.uuid.as_deref(), Some("GPU-abc"));
assert_eq!(
read.dtype_kernels["q4_k"].recommended,
Some(crate::qstar::MoeBackend::Hybrid)
);
assert!(
std::fs::read_dir(path.parent().unwrap())
.unwrap()
.all(|e| !e
.unwrap()
.file_name()
.to_string_lossy()
.ends_with(".partial")),
"nothing partial may survive a completed write"
);
assert!(read.matches_gpu(Some("NVIDIA GeForce RTX 4090")));
assert!(!read.matches_gpu(Some("NVIDIA GeForce RTX 3060 Ti")));
let _ = std::fs::remove_dir_all(&dir);
}
}