use serde_json::{Map, Value, json};
pub const NEVER: u64 = 1_000_000_000;
pub const MARGIN: f64 = 1.1;
pub const DIP: f64 = 0.8;
pub const DEFAULTS: [(&str, u64); 6] = [
("cpu_below", 2),
("gpu_list_from", 1000),
("cpu_list_from", NEVER),
("cpu_blas_from", NEVER),
("graph_from", NEVER),
("cpu_ivf_from", 1),
];
pub type Rate = (String, u64, f64);
fn rate(rates: &[Rate], path: &str, b: u64) -> Option<f64> {
rates
.iter()
.find(|(p, bb, _)| p == path && *bb == b)
.map(|r| r.2)
}
fn has(rates: &[Rate], path: &str) -> bool {
rates.iter().any(|(p, _, _)| p == path)
}
fn need(rates: &[Rate], path: &str, b: u64) -> Result<f64, String> {
rate(rates, path, b).ok_or_else(|| format!("no rate measured for {path} at {b} queries"))
}
pub fn crossover_with_margin(a: &[(u64, f64)], b: &[(u64, f64)], default: u64) -> u64 {
let mut batches: Vec<u64> = a.iter().map(|x| x.0).collect();
batches.sort_unstable();
let at = |s: &[(u64, f64)], x: u64| s.iter().find(|v| v.0 == x).map_or(0.0, |v| v.1);
let wins = |x: u64| {
let (ra, rb) = (at(a, x), at(b, x));
if x >= default {
rb * MARGIN >= ra
} else {
rb >= MARGIN * ra
}
};
let i = (0..batches.len())
.find(|&i| batches[i..].iter().all(|&y| wins(y)))
.unwrap_or(batches.len());
if i == 0 {
return batches.first().copied().unwrap_or(default);
}
let upper = if i < batches.len() { batches[i] } else { NEVER };
(batches[i - 1] + 1).max(upper.min(default))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Thresholds {
pub cpu_below: u64,
pub gpu_list_from: u64,
pub cpu_list_from: u64,
pub cpu_blas_from: u64,
pub graph_from: u64,
pub cpu_ivf_from: u64,
pub exact_from: u64,
}
impl Thresholds {
fn from(r: &Map<String, Value>) -> Thresholds {
let get = |k: &str, default: u64| r.get(k).and_then(Value::as_u64).unwrap_or(default);
let d = |k: &str| DEFAULTS.iter().find(|x| x.0 == k).map_or(NEVER, |x| x.1);
Thresholds {
cpu_below: get("cpu_below", d("cpu_below")),
gpu_list_from: get("gpu_list_from", d("gpu_list_from")),
cpu_list_from: get("cpu_list_from", d("cpu_list_from")),
cpu_blas_from: get("cpu_blas_from", d("cpu_blas_from")),
graph_from: get("graph_from", d("graph_from")),
cpu_ivf_from: get("cpu_ivf_from", d("cpu_ivf_from")),
exact_from: get("exact_from", NEVER),
}
}
}
pub fn routed_path(t: &Thresholds, b: u64, graph_gpu: bool, graph_cpu: bool) -> &'static str {
if b >= t.exact_from {
return if b >= t.cpu_below {
"gpu-exact"
} else {
"cpu-exact"
};
}
if b >= t.cpu_below {
if graph_gpu && b >= t.graph_from {
return "gpu-graph";
}
return if b >= t.gpu_list_from {
"gpu-list"
} else {
"gpu-query"
};
}
if graph_cpu && b < t.cpu_ivf_from {
return "cpu-graph";
}
if b == 1 {
return "cpu-split";
}
if b >= t.cpu_list_from {
return "cpu-list";
}
if b >= t.cpu_blas_from {
"cpu-query-blas"
} else {
"cpu-query"
}
}
fn defaults() -> Thresholds {
Thresholds::from(&Map::new())
}
pub fn route_table(
rates: &[Rate],
batches: &[u64],
graph_gpu: bool,
graph_cpu: bool,
) -> Vec<(u64, Vec<String>)> {
let mut table = Vec::new();
for &b in batches {
let here: Vec<(&str, f64)> = rates
.iter()
.filter(|r| r.1 == b)
.map(|r| (r.0.as_str(), r.2))
.collect();
if here.is_empty() {
continue;
}
let mut order: Vec<(&str, f64)> = here.clone();
order.sort_by(|x, y| y.1.total_cmp(&x.1));
let default = routed_path(&defaults(), b, graph_gpu, graph_cpu);
if let Some(&(_, dr)) = here.iter().find(|x| x.0 == default)
&& order[0].1 < MARGIN * dr
{
order.retain(|x| x.0 != default);
order.insert(0, (default, dr));
}
table.push((b, order.into_iter().map(|x| x.0.to_string()).collect()));
}
table
}
pub fn dips(rates: &[Rate]) -> Vec<(String, u64)> {
let mut out: Vec<(bool, u64, String)> = Vec::new();
for (p, b, r) in rates {
let lo = rate(rates, p, b / 2);
let hi = rate(rates, p, b * 2);
if let (Some(lo), Some(hi)) = (lo, hi)
&& lo != 0.0
&& hi != 0.0
&& *r < DIP * (lo * hi).sqrt()
{
out.push((!p.starts_with("gpu"), *b, p.clone()));
}
}
out.sort();
out.into_iter().map(|(_, b, p)| (p, b)).collect()
}
pub fn from_rates(rates: &[Rate], batches: &[u64], gpu: bool) -> Result<Value, String> {
let mut cpu_batches: Vec<u64> = rates
.iter()
.filter(|r| r.0.starts_with("cpu") && r.0 != "cpu-exact")
.map(|r| r.1)
.collect();
cpu_batches.sort_unstable();
cpu_batches.dedup();
let many: Vec<u64> = cpu_batches.iter().copied().filter(|&b| b > 1).collect();
let series = |path: &str, at: &[u64]| -> Result<Vec<(u64, f64)>, String> {
at.iter().map(|&b| Ok((b, need(rates, path, b)?))).collect()
};
let mut cq = series("cpu-query", &many)?;
let cl = series("cpu-list", &many)?;
let mut t = defaults();
t.cpu_blas_from = NEVER;
if has(rates, "cpu-query-blas") && !cq.is_empty() {
let cqb = series("cpu-query-blas", &many)?;
t.cpu_blas_from = crossover_with_margin(&cq, &cqb, NEVER);
cq = cq
.iter()
.zip(&cqb)
.map(|(q, bq)| if q.0 >= t.cpu_blas_from { *bq } else { *q })
.collect();
}
t.cpu_list_from = if cq.is_empty() {
NEVER
} else {
crossover_with_margin(&cq, &cl, NEVER)
};
let mut cpu: Vec<(u64, f64)> = Vec::new();
for &b in &cpu_batches {
let r = if b == 1 {
need(rates, "cpu-split", b)?
} else {
let q = cq.iter().find(|x| x.0 == b).map_or(0.0, |x| x.1);
let l = cl.iter().find(|x| x.0 == b).map_or(0.0, |x| x.1);
q.max(l)
};
cpu.push((b, r));
}
t.cpu_ivf_from = 1;
let cpu_graph = has(rates, "cpu-graph");
if cpu_graph {
let cg = series("cpu-graph", &cpu_batches)?;
t.cpu_ivf_from = crossover_with_margin(&cg, &cpu, 1);
cpu = cpu
.iter()
.zip(&cg)
.map(|(c, g)| if c.0 >= t.cpu_ivf_from { *c } else { *g })
.collect();
}
let mut gpu_paths: Vec<&str> = vec!["gpu-query"];
let list_major = has(rates, "gpu-list");
if list_major {
gpu_paths.push("gpu-list");
}
let graph_gpu = has(rates, "gpu-graph");
if graph_gpu {
gpu_paths.push("gpu-graph");
}
if has(rates, "gpu-plugin-graph") {
gpu_paths.push("gpu-plugin-graph");
}
if gpu {
let gq = series("gpu-query", batches)?;
let mut ivf_gpu = gq.clone();
t.gpu_list_from = NEVER;
if list_major {
let gl = series("gpu-list", batches)?;
t.gpu_list_from = crossover_with_margin(&gq, &gl, 1000);
ivf_gpu = gq
.iter()
.zip(&gl)
.map(|(q, l)| if q.0 >= t.gpu_list_from { *l } else { *q })
.collect();
}
t.graph_from = NEVER;
if graph_gpu {
let gg = series("gpu-graph", batches)?;
t.graph_from = crossover_with_margin(&ivf_gpu, &gg, NEVER);
}
let mut best_gpu = Vec::new();
for &b in &cpu_batches {
let mut best = f64::NEG_INFINITY;
for p in &gpu_paths {
best = best.max(need(rates, p, b)?);
}
best_gpu.push((b, best));
}
t.cpu_below = crossover_with_margin(&cpu, &best_gpu, 2);
} else {
t.cpu_below = NEVER;
t.gpu_list_from = NEVER;
t.graph_from = NEVER;
}
t.exact_from = NEVER;
if has(rates, "cpu-exact") || has(rates, "gpu-exact") {
let (mut ex, mut ap) = (Vec::new(), Vec::new());
for &b in batches {
let e: Vec<f64> = ["gpu-exact", "cpu-exact"]
.iter()
.filter_map(|p| rate(rates, p, b))
.collect();
let a = rate(rates, routed_path(&t, b, graph_gpu, cpu_graph), b);
if let Some(a) = a
&& !e.is_empty()
&& a != 0.0
{
ex.push((b, e.iter().copied().fold(f64::NEG_INFINITY, f64::max)));
ap.push((b, a));
}
}
if !ex.is_empty() {
t.exact_from = crossover_with_margin(&ap, &ex, NEVER);
}
}
let table = route_table(rates, batches, graph_gpu, cpu_graph);
let mut out = json!({
"cpu_blas_from": t.cpu_blas_from,
"cpu_list_from": t.cpu_list_from,
"cpu_ivf_from": t.cpu_ivf_from,
"gpu_list_from": t.gpu_list_from,
"graph_from": t.graph_from,
"cpu_below": t.cpu_below,
"exact_from": t.exact_from,
"table": table.iter().map(|(b, p)| json!([b, p])).collect::<Vec<_>>(),
});
let one: Vec<(&str, f64)> = rates
.iter()
.filter(|r| r.1 == 1)
.map(|r| (r.0.as_str(), r.2))
.collect();
let given = routed_path(&t, 1, graph_gpu, cpu_graph);
let mut best: Option<(&str, f64)> = None;
for &(p, r) in &one {
if best.is_none_or(|b| r > b.1) {
best = Some((p, r));
}
}
if let (Some(best), Some(&(_, g))) = (best, one.iter().find(|x| x.0 == given))
&& best.0 != given
&& best.1 >= MARGIN * g
{
out["single"] = json!(best.0);
}
Ok(out)
}
#[derive(Clone, Copy, Debug)]
pub struct Can {
pub device: Option<&'static str>,
pub approximate: bool,
pub gpu: bool,
pub graph: bool,
pub graph_gpu: bool,
pub plugin_graph: bool,
}
#[derive(Clone, Debug)]
pub struct Routes {
t: Thresholds,
single: Option<String>,
table: Vec<(u64, Vec<String>)>,
}
impl Routes {
pub fn parse(v: &Value) -> Routes {
let empty = Map::new();
let r = v.as_object().unwrap_or(&empty);
let table = r
.get("table")
.and_then(Value::as_array)
.map(|t| {
t.iter()
.filter_map(|e| {
let b = e.get(0)?.as_u64()?;
let paths = e
.get(1)?
.as_array()?
.iter()
.filter_map(|p| p.as_str().map(String::from))
.collect();
Some((b, paths))
})
.collect()
})
.unwrap_or_default();
Routes {
t: Thresholds::from(r),
single: r.get("single").and_then(Value::as_str).map(String::from),
table,
}
}
fn usable(path: &str, can: &Can) -> bool {
if can.approximate && path.ends_with("exact") {
return false;
}
if let Some(d) = can.device
&& !path.starts_with(d)
{
return false;
}
if path.starts_with("gpu") && !can.gpu {
return false;
}
if path.ends_with("graph")
&& (!can.graph
|| (path.starts_with("gpu") && !can.graph_gpu)
|| (path == "gpu-plugin-graph" && !can.plugin_graph))
{
return false;
}
true
}
pub fn path(&self, batch: u64, can: &Can) -> String {
let mut t = self.t;
let mut single = self.single.clone();
if can.approximate {
t.exact_from = NEVER;
if single.as_deref().is_some_and(|s| s.ends_with("exact")) {
single = None;
}
}
if !self.table.is_empty() {
let mut entry = &self.table[0].1;
for (b, paths) in &self.table {
if *b > batch {
break;
}
entry = paths;
}
if let Some(p) = entry.iter().find(|p| Self::usable(p, can)) {
return p.clone();
}
t.exact_from = NEVER;
single = None;
}
if batch >= t.exact_from {
let dev = can.device.unwrap_or(if can.gpu && batch >= t.cpu_below {
"gpu"
} else {
"cpu"
});
if dev == "cpu" || can.gpu {
return format!("{dev}-exact");
}
}
if batch == 1
&& let Some(s) = &single
{
let ok = (!s.ends_with("graph") || can.graph)
&& (s.starts_with("cpu")
|| (can.gpu
&& (!s.ends_with("graph") || can.graph_gpu)
&& (s != "gpu-plugin-graph" || can.plugin_graph)));
if ok && can.device.is_none_or(|d| s.starts_with(d)) {
return s.clone();
}
}
let dev = can
.device
.unwrap_or(if batch < t.cpu_below { "cpu" } else { "gpu" });
if dev == "gpu" {
if can.graph && can.graph_gpu && batch >= t.graph_from {
return "gpu-graph".into();
}
return if batch >= t.gpu_list_from {
"gpu-list"
} else {
"gpu-query"
}
.into();
}
if can.graph && batch < t.cpu_ivf_from {
return "cpu-graph".into();
}
if batch == 1 {
return "cpu-split".into();
}
if batch >= t.cpu_list_from {
return "cpu-list".into();
}
if batch >= t.cpu_blas_from {
"cpu-query-blas"
} else {
"cpu-query"
}
.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crossovers() {
let a = [(1, 100.0), (16, 100.0), (64, 100.0), (256, 100.0)];
let b = [(1, 50.0), (16, 50.0), (64, 200.0), (256, 300.0)];
assert_eq!(crossover_with_margin(&a, &b, NEVER), 64);
assert_eq!(crossover_with_margin(&a, &b, 32), 32);
assert_eq!(
crossover_with_margin(
&a,
&[(1, 500.0), (16, 500.0), (64, 500.0), (256, 500.0)],
NEVER
),
1
);
assert_eq!(
crossover_with_margin(&a, &[(1, 10.0), (16, 10.0), (64, 10.0), (256, 10.0)], NEVER),
NEVER
);
}
#[test]
fn paths_from_the_table_then_the_thresholds() {
let r = Routes::parse(&json!({
"cpu_below": 100, "graph_from": 1, "cpu_ivf_from": 8,
"table": [[1, ["cpu-graph", "gpu-graph"]], [64, ["gpu-graph", "cpu-query"]], [512, ["gpu-graph"]]]
}));
let can = Can {
device: None,
approximate: false,
gpu: true,
graph: true,
graph_gpu: true,
plugin_graph: false,
};
assert_eq!(r.path(1, &can), "cpu-graph");
assert_eq!(r.path(100, &can), "gpu-graph");
let cpu = Can {
device: Some("cpu"),
..can
};
assert_eq!(r.path(100, &cpu), "cpu-query");
assert_eq!(r.path(1000, &cpu), "cpu-query");
assert_eq!(r.path(4, &cpu), "cpu-graph");
let no_gpu = Can { gpu: false, ..can };
assert_eq!(r.path(100, &no_gpu), "cpu-query");
}
fn thresholds(v: Value) -> Thresholds {
Thresholds::from(v.as_object().unwrap())
}
#[test]
fn the_thresholds_route() {
let r = thresholds(json!({"cpu_below": 64, "gpu_list_from": 1000, "exact_from": 4096}));
assert_eq!(routed_path(&r, 1, false, false), "cpu-split");
assert_eq!(routed_path(&r, 10, false, false), "cpu-query");
assert_eq!(routed_path(&r, 100, false, false), "gpu-query");
assert_eq!(routed_path(&r, 2000, false, false), "gpu-list");
assert_eq!(routed_path(&r, 5000, false, false), "gpu-exact");
let g = thresholds(json!({"cpu_below": 64, "graph_from": 128}));
assert_eq!(routed_path(&g, 200, true, true), "gpu-graph");
let c = thresholds(json!({"cpu_below": 64, "cpu_ivf_from": 32}));
assert_eq!(routed_path(&c, 10, true, true), "cpu-graph");
let d = defaults();
assert_eq!(routed_path(&d, 1, false, false), "cpu-split");
assert_eq!(
routed_path(&thresholds(json!({"cpu_ivf_from": 8})), 1, false, true),
"cpu-graph"
);
assert_eq!(
routed_path(&thresholds(json!({"cpu_below": 1})), 1, false, false),
"gpu-query"
);
let gl = thresholds(json!({"cpu_below": 1, "gpu_list_from": 1, "graph_from": NEVER}));
assert_eq!(routed_path(&gl, 1, true, true), "gpu-list");
}
#[test]
fn the_table_takes_each_batch_to_its_measured_path() {
let rates: Vec<Rate> = [
("cpu-split", 1, 100.0),
("cpu-graph", 1, 50.0),
("cpu-graph", 8, 900.0),
("gpu-graph", 8, 600.0),
("gpu-query", 8, 300.0),
("gpu-graph", 64, 9000.0),
("gpu-query", 64, 3000.0),
("gpu-list", 64, 4000.0),
("gpu-graph", 512, 20000.0),
("gpu-list", 512, 30000.0),
("gpu-query", 512, 21000.0),
]
.iter()
.map(|&(p, b, r)| (p.to_string(), b, r))
.collect();
let table = route_table(&rates, &[1, 8, 64, 512], true, true);
let firsts: Vec<&str> = table.iter().map(|(_, p)| p[0].as_str()).collect();
assert_eq!(firsts, ["cpu-split", "cpu-graph", "gpu-graph", "gpu-list"]);
let close: Vec<Rate> = vec![
("gpu-query".into(), 64, 1000.0),
("gpu-graph".into(), 64, 1050.0),
];
assert_eq!(route_table(&close, &[64], true, true)[0].1[0], "gpu-query");
let json_table =
json!({"table": table.iter().map(|(b, p)| json!([b, p])).collect::<Vec<_>>()});
let r = Routes::parse(&json_table);
let can = Can {
device: None,
approximate: false,
gpu: true,
graph: true,
graph_gpu: true,
plugin_graph: false,
};
assert_eq!(r.path(1, &can), "cpu-split");
assert_eq!(r.path(7, &can), "cpu-split");
assert_eq!(r.path(8, &can), "cpu-graph");
assert_eq!(r.path(100, &can), "gpu-graph");
assert_eq!(r.path(10_000, &can), "gpu-list");
}
#[test]
fn dips_and_routes_from_rates() {
let rates: Vec<Rate> = vec![
("cpu-split".into(), 1, 9000.0),
("cpu-query".into(), 1, 5000.0),
("cpu-query".into(), 2, 9000.0),
("cpu-list".into(), 2, 4000.0),
("cpu-query".into(), 4, 1000.0),
("cpu-list".into(), 4, 8000.0),
("cpu-query".into(), 8, 30000.0),
("cpu-list".into(), 8, 9000.0),
];
assert_eq!(dips(&rates), vec![("cpu-query".to_string(), 4)]);
let r = from_rates(&rates, &[1, 2, 4, 8], false).unwrap();
assert_eq!(r["cpu_below"], NEVER);
assert_eq!(r["table"][0], json!([1, ["cpu-split", "cpu-query"]]));
}
}