use crate::{Device, Plan, Task};
use std::{
collections::{BTreeSet, HashMap},
sync::mpsc,
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(usize)]
pub enum Backend {
Cpu,
Accelerator,
Storage,
}
impl Backend {
#[allow(non_upper_case_globals)]
pub const Cuda: Self = Self::Accelerator;
}
const BACKENDS: [Backend; 3] = [Backend::Cpu, Backend::Cuda, Backend::Storage];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Memory {
pub ram: usize,
pub vram: usize,
}
impl Memory {
fn fits(self, used: Self, limit: Self) -> bool {
self.ram <= limit.ram - used.ram && self.vram <= limit.vram - used.vram
}
}
#[derive(Clone, Copy, Debug)]
pub struct Route {
pub estimate: Duration,
pub memory: Memory,
}
#[derive(Clone, Debug)]
pub struct Operation {
pub dependencies: Vec<usize>,
pub class: u64,
pub bytes: usize,
pub routes: [Option<Route>; 3],
}
#[derive(Clone, Copy, Debug)]
pub struct Capacity {
pub workers: [usize; 3],
pub memory: Memory,
}
#[derive(Clone, Debug)]
pub struct Hardware {
pub logical_workers: usize,
pub available_ram: Option<u64>,
pub avx2: bool,
pub sse42: bool,
pub sha: bool,
}
pub fn discover_host() -> Hardware {
let mut hardware = Hardware {
logical_workers: std::thread::available_parallelism().map_or(1, usize::from),
available_ram: available_ram(),
avx2: false,
sse42: false,
sha: false,
};
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
hardware.avx2 = std::is_x86_feature_detected!("avx2");
hardware.sse42 = std::is_x86_feature_detected!("sse4.2");
hardware.sha = std::is_x86_feature_detected!("sha");
}
hardware
}
#[cfg(windows)]
fn available_ram() -> Option<u64> {
#[repr(C)]
struct MemoryStatus {
length: u32,
load_percent: u32,
total_physical: u64,
available_physical: u64,
total_page_file: u64,
available_page_file: u64,
total_virtual: u64,
available_virtual: u64,
available_extended_virtual: u64,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GlobalMemoryStatusEx(status: *mut MemoryStatus) -> i32;
}
let mut status = MemoryStatus {
length: std::mem::size_of::<MemoryStatus>() as u32,
load_percent: 0,
total_physical: 0,
available_physical: 0,
total_page_file: 0,
available_page_file: 0,
total_virtual: 0,
available_virtual: 0,
available_extended_virtual: 0,
};
(unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status.available_physical)
}
#[cfg(not(windows))]
fn available_ram() -> Option<u64> {
None
}
#[derive(Clone, Copy, Debug)]
pub struct Sample {
pub task: usize,
pub backend: Backend,
pub ready_at: Duration,
pub dispatched_at: Duration,
pub started_at: Duration,
pub setup: Option<Duration>,
pub elapsed: Duration,
}
#[derive(Debug)]
pub struct Report {
pub elapsed: Duration,
pub dependency_span: Duration,
pub samples: Vec<Sample>,
pub peak: Memory,
pub memory_blocked: Duration,
pub busy: [Duration; 3],
pub fallbacks: Vec<(usize, String)>,
pub model_resets: usize,
pub plan_time: Duration,
pub dispatch_time: Duration,
pub wait_time: Duration,
pub censored_scans: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pressure {
MemoryAdmission,
Dependencies,
Backend(Backend),
Unclassified,
}
impl Report {
pub fn pressure(&self, capacity: Capacity) -> Pressure {
if self.elapsed.is_zero() {
return Pressure::Unclassified;
}
if self.memory_blocked >= self.elapsed / 2 {
return Pressure::MemoryAdmission;
}
if self.dependency_span >= self.elapsed - self.elapsed / 5 {
return Pressure::Dependencies;
}
BACKENDS
.into_iter()
.filter_map(|backend| {
let index = backend as usize;
let workers = capacity.workers[index];
(workers != 0).then(|| {
(
self.busy[index].as_secs_f64()
/ (self.elapsed.as_secs_f64() * workers as f64),
backend,
)
})
})
.max_by(|a, b| a.0.total_cmp(&b.0))
.filter(|(utilization, _)| *utilization >= 0.8)
.map_or(Pressure::Unclassified, |(_, backend)| {
Pressure::Backend(backend)
})
}
}
#[derive(Default)]
pub struct History {
service: HashMap<(u64, u32, Backend), Duration>,
startup: [Option<Duration>; 3],
frozen: bool,
probe_joins: bool,
censor: bool,
deviations: HashMap<(u64, u32, Backend), (bool, Duration)>,
}
fn smooth(prior: Duration, sample: Duration) -> Duration {
(prior - prior / 4).saturating_add(sample / 4)
}
impl History {
pub fn live_probes(&mut self, probe_joins: bool, censor: bool) {
self.probe_joins = probe_joins;
self.censor = censor;
}
pub fn freeze(&mut self) {
self.frozen = true;
}
fn key(class: u64, bytes: usize, backend: Backend) -> (u64, u32, Backend) {
(class, bytes.checked_ilog2().unwrap_or(0), backend)
}
pub fn observe(&mut self, class: u64, bytes: usize, backend: Backend, elapsed: Duration) {
self.update(class, bytes, backend, elapsed);
}
fn update(&mut self, class: u64, bytes: usize, backend: Backend, elapsed: Duration) -> bool {
if self.frozen {
return false;
}
let key = Self::key(class, bytes, backend);
let Some(estimate) = self.service.get_mut(&key) else {
self.service.insert(key, elapsed);
return false;
};
let large_change = elapsed.abs_diff(*estimate) >= Duration::from_micros(25)
&& elapsed.max(*estimate) > elapsed.min(*estimate).saturating_mul(2);
if large_change {
let slower = elapsed > *estimate;
if let Some((direction, previous)) = self.deviations.remove(&key)
&& direction == slower
{
*estimate = elapsed.min(previous) + elapsed.abs_diff(previous) / 2;
return true;
}
self.deviations.insert(key, (slower, elapsed));
} else {
self.deviations.remove(&key);
*estimate = smooth(*estimate, elapsed);
}
false
}
pub fn observe_startup(&mut self, backend: Backend, elapsed: Duration) {
if self.frozen {
return;
}
let slot = &mut self.startup[backend as usize];
*slot = Some(slot.map_or(elapsed, |prior| smooth(prior, elapsed)));
}
fn predict(&self, op: &Operation, backend: Backend) -> Duration {
self.service
.get(&Self::key(op.class, op.bytes, backend))
.copied()
.unwrap_or_else(|| {
op.routes[backend as usize]
.expect("supported route")
.estimate
})
}
}
pub enum Attempt {
Done,
RetryOnCpu(String),
}
#[derive(Clone, Copy)]
struct InFlight {
memory: Memory,
finish: Duration,
task: usize,
dispatched: Duration,
predicted: Duration,
}
pub struct Scheduler {
ops: Vec<Operation>,
plan: Plan,
}
impl Scheduler {
pub fn new(ops: Vec<Operation>) -> Result<Self, &'static str> {
let plan = Plan::new(
ops.iter()
.map(|op| Task {
dependencies: op.dependencies.clone(),
device: Device::Cpu,
memory_bytes: 0,
})
.collect(),
)?;
Ok(Self { ops, plan })
}
pub fn execute<S>(
&self,
capacity: Capacity,
history: &mut History,
initialize: impl Fn(Backend) -> Result<S, String> + Sync,
work: impl Fn(&mut S, usize, Backend) -> Result<(), String> + Sync,
) -> Result<Report, String> {
self.execute_retry(capacity, history, initialize, |session, task, backend| {
work(session, task, backend).map(|()| Attempt::Done)
})
}
pub fn execute_retry<S>(
&self,
capacity: Capacity,
history: &mut History,
initialize: impl Fn(Backend) -> Result<S, String> + Sync,
work: impl Fn(&mut S, usize, Backend) -> Result<Attempt, String> + Sync,
) -> Result<Report, String> {
self.execute_interruptible(capacity, history, initialize, work, None)
}
pub fn execute_interruptible<S>(
&self,
capacity: Capacity,
history: &mut History,
initialize: impl Fn(Backend) -> Result<S, String> + Sync,
work: impl Fn(&mut S, usize, Backend) -> Result<Attempt, String> + Sync,
cancelled: Option<&std::sync::atomic::AtomicBool>,
) -> Result<Report, String> {
let is_cancelled =
|| cancelled.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire));
let start = Instant::now();
let eligible = |op: &Operation, backend: Backend| {
capacity.workers[backend as usize] != 0
&& op.routes[backend as usize]
.is_some_and(|route| route.memory.fits(Memory::default(), capacity.memory))
};
let mut choices: Vec<Vec<Backend>> = self
.ops
.iter()
.map(|op| BACKENDS.into_iter().filter(|&b| eligible(op, b)).collect())
.collect();
if let Some(id) = choices.iter().position(Vec::is_empty) {
return Err(format!("operation {id} has no feasible route"));
}
let mut pending = self.plan.incoming.clone();
let mut order: Vec<_> = (0..self.ops.len()).filter(|&id| pending[id] == 0).collect();
let mut cursor = 0;
while cursor < order.len() {
for &next in &self.plan.successors[order[cursor]] {
pending[next] -= 1;
if pending[next] == 0 {
order.push(next);
}
}
cursor += 1;
}
let mut ranks = vec![Duration::ZERO; self.ops.len()];
let rank = |ranks: &mut [Duration], choices: &[Vec<Backend>], history: &History| {
for &id in order.iter().rev() {
let cost = choices[id]
.iter()
.map(|&b| history.predict(&self.ops[id], b))
.min()
.unwrap();
let tail = self.plan.successors[id]
.iter()
.map(|&next| ranks[next])
.max()
.unwrap_or_default();
ranks[id] = cost.saturating_add(tail);
}
};
rank(&mut ranks, &choices, history);
pending.clone_from(&self.plan.incoming);
let mut ready: BTreeSet<_> = order
.iter()
.copied()
.filter(|&id| pending[id] == 0)
.map(|id| (std::cmp::Reverse(ranks[id]), id))
.collect();
let mut ready_at = vec![Duration::ZERO; self.ops.len()];
let mut finish = vec![Duration::ZERO; self.ops.len()];
let mut peak = Memory::default();
let mut used = Memory::default();
let mut busy = [Duration::ZERO; 3];
let mut memory_blocked = Duration::ZERO;
let mut fallbacks = Vec::new();
let mut model_resets = 0;
let mut censored_scans = 0;
let mut dispatch_time = Duration::ZERO;
let mut wait_time = Duration::ZERO;
let plan_time = start.elapsed();
let mut samples = Vec::with_capacity(self.ops.len());
std::thread::scope(|scope| {
let (completed, events) = mpsc::channel();
let mut workers = Vec::new();
for backend in BACKENDS {
let demand = choices
.iter()
.filter(|routes| routes.contains(&backend))
.count();
for _ in 0..capacity.workers[backend as usize].min(demand) {
let worker_id = workers.len();
let (dispatch, queue) = mpsc::sync_channel::<(usize, Duration)>(1);
workers.push((backend, dispatch, None::<InFlight>, false));
let completed = completed.clone();
let initialize = &initialize;
let work = &work;
scope.spawn(move || {
let mut state = None;
while let Ok((task, dispatched_at)) = queue.recv() {
let started = start.elapsed();
let mut setup = None;
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let state = state.get_or_insert_with(|| {
let init = initialize(backend);
setup = Some(start.elapsed() - started);
init
});
work(state.as_mut().map_err(|e| e.clone())?, task, backend)
}))
.unwrap_or_else(|_| Err("worker panicked".into()));
if completed
.send((
worker_id,
task,
dispatched_at,
started,
setup,
start.elapsed() - started,
result,
))
.is_err()
{
break;
}
}
});
}
}
drop(completed);
while samples.len() < self.ops.len() {
if is_cancelled() {
return Err("execution cancelled".into());
}
let tick = Instant::now();
let mut floor = HashMap::new();
if history.censor {
let now = start.elapsed();
for (backend, _, active, _) in &workers {
if let Some(active) = active {
let age = now.saturating_sub(active.dispatched);
if age
> active
.predicted
.saturating_mul(3)
.saturating_add(Duration::from_micros(100))
{
let op = &self.ops[active.task];
let floor = floor
.entry(History::key(op.class, op.bytes, *backend))
.or_insert(Duration::ZERO);
*floor = (*floor).max(age.saturating_mul(2));
}
}
}
}
censored_scans += usize::from(!floor.is_empty());
let mut waiting_for_memory = false;
for &(_, id) in &ready {
if is_cancelled() {
return Err("execution cancelled".into());
}
let op = &self.ops[id];
let now = start.elapsed();
let candidate = workers
.iter()
.enumerate()
.filter_map(|(index, (backend, _, active, opened))| {
if !choices[id].contains(backend) {
return None;
}
let memory = op.routes[*backend as usize]?.memory;
if active.is_none() && !memory.fits(used, capacity.memory) {
return None;
}
let availability = active.map_or(now, |work| work.finish.max(now));
let cost = history.predict(op, *backend).max(
floor
.get(&History::key(op.class, op.bytes, *backend))
.copied()
.unwrap_or_default(),
);
Some((
availability
.saturating_add(cost)
.saturating_add(if *opened {
Duration::ZERO
} else {
history.startup[*backend as usize].unwrap_or_default()
}),
index,
memory,
))
})
.min_by_key(|&(eta, index, _)| {
let probe = history.probe_joins
&& self.plan.incoming[id] >= 4
&& self.plan.successors[id].len() >= 4
&& choices[id].contains(&Backend::Accelerator);
(
probe && workers[index].0 != Backend::Accelerator,
eta,
workers[index].2.is_some(),
index,
)
});
waiting_for_memory |= workers.iter().any(|(backend, _, active, _)| {
active.is_none()
&& choices[id].contains(backend)
&& !op.routes[*backend as usize]
.unwrap()
.memory
.fits(used, capacity.memory)
});
if let Some((eta, index, memory)) = candidate
&& workers[index].2.is_none()
{
workers[index]
.1
.send((id, now))
.map_err(|_| "worker disconnected")?;
workers[index].2 = Some(InFlight {
memory,
finish: eta,
task: id,
dispatched: now,
predicted: eta.saturating_sub(now),
});
workers[index].3 = true;
used.ram += memory.ram;
used.vram += memory.vram;
peak.ram = peak.ram.max(used.ram);
peak.vram = peak.vram.max(used.vram);
pending[id] = usize::MAX;
}
}
ready.retain(|&(_, id)| pending[id] != usize::MAX);
dispatch_time += tick.elapsed();
let wait = Instant::now();
let message = if history.censor && !ready.is_empty() || cancelled.is_some() {
match events.recv_timeout(Duration::from_micros(300)) {
Ok(event) => Some(event),
Err(mpsc::RecvTimeoutError::Timeout) => None,
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("workers disconnected".into());
}
}
} else {
Some(events.recv().map_err(|_| "workers disconnected")?)
};
wait_time += wait.elapsed();
if waiting_for_memory {
memory_blocked += wait.elapsed();
}
let Some((index, id, dispatched_at, started_at, setup, elapsed, result)) = message
else {
continue;
};
let tick = Instant::now();
let outcome = result.map_err(|e| format!("operation {id}: {e}"))?;
let (backend, _, active, _) = &mut workers[index];
let memory = active.take().unwrap().memory;
used.ram -= memory.ram;
used.vram -= memory.vram;
busy[*backend as usize] += elapsed;
if let Attempt::RetryOnCpu(reason) = outcome {
if *backend != Backend::Accelerator || !choices[id].contains(&Backend::Cpu) {
return Err(format!("operation {id}: {reason}"));
}
choices[id].retain(|backend| *backend == Backend::Cpu);
fallbacks.push((id, reason));
pending[id] = 0;
ready.insert((std::cmp::Reverse(ranks[id]), id));
dispatch_time += tick.elapsed();
continue;
}
let op = &self.ops[id];
if let Some(setup) = setup {
history.observe_startup(*backend, setup);
}
if history.update(
op.class,
op.bytes,
*backend,
elapsed - setup.unwrap_or_default(),
) {
model_resets += 1;
rank(&mut ranks, &choices, history);
ready = ready
.iter()
.map(|&(_, id)| (std::cmp::Reverse(ranks[id]), id))
.collect();
}
finish[id] = elapsed.saturating_add(
op.dependencies
.iter()
.map(|&dep| finish[dep])
.max()
.unwrap_or_default(),
);
samples.push(Sample {
task: id,
backend: *backend,
ready_at: ready_at[id],
dispatched_at,
started_at,
setup,
elapsed,
});
for &next in &self.plan.successors[id] {
pending[next] -= 1;
if pending[next] == 0 {
ready_at[next] = start.elapsed();
ready.insert((std::cmp::Reverse(ranks[next]), next));
}
}
dispatch_time += tick.elapsed();
}
Ok(Report {
elapsed: start.elapsed(),
dependency_span: finish.into_iter().max().unwrap_or_default(),
samples,
peak,
memory_blocked,
busy,
fallbacks,
model_resets,
plan_time,
dispatch_time,
wait_time,
censored_scans,
})
})
}
}
#[derive(Debug)]
pub struct Calibration<T> {
pub policy: T,
samples: Vec<Duration>,
}
impl<T> Calibration<T> {
pub fn samples(&self) -> &[Duration] {
&self.samples
}
pub fn median(&self) -> Duration {
let mut times = self.samples.clone();
times.sort_unstable();
let i = times.len() / 2;
times[(times.len() - 1) / 2] + (times[i] - times[(times.len() - 1) / 2]) / 2
}
}
pub fn calibrate<T: Copy, E>(
policies: &[T],
repeats: std::num::NonZeroUsize,
mut measure: impl FnMut(T) -> Result<Duration, E>,
) -> Result<Vec<Calibration<T>>, E> {
let mut profiles = policies
.iter()
.map(|&policy| Calibration {
policy,
samples: Vec::with_capacity(repeats.get()),
})
.collect::<Vec<_>>();
for pass in 0..repeats.get() {
for offset in 0..profiles.len() {
let index = if pass % 2 == 0 {
offset
} else {
profiles.len() - 1 - offset
};
let row = &mut profiles[index];
row.samples.push(measure(row.policy)?);
}
}
Ok(profiles)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cancellation_stops_before_releasing_dependents() {
use std::sync::atomic::{AtomicBool, Ordering};
let cancel = AtomicBool::new(false);
let route = Some(Route {
estimate: Duration::from_millis(1),
memory: Memory::default(),
});
let node = |dependencies| Operation {
dependencies,
class: 0,
bytes: 32,
routes: [route, None, None],
};
let graph = Scheduler::new(vec![node(vec![]), node(vec![0])]).unwrap();
let result = graph.execute_interruptible(
Capacity {
workers: [1, 0, 0],
memory: Memory::default(),
},
&mut History::default(),
|_| Ok(()),
|_, id, _| {
assert_eq!(id, 0);
cancel.store(true, Ordering::Release);
Ok(Attempt::Done)
},
Some(&cancel),
);
assert_eq!(result.unwrap_err(), "execution cancelled");
}
#[test]
fn detects_consecutive_workload_changes_and_ignores_a_frozen_model() {
let mut history = History::default();
let sample = |ms| Duration::from_millis(ms);
history.observe(7, 64, Backend::Cpu, sample(1));
assert!(!history.update(7, 64, Backend::Cpu, sample(10)));
assert!(history.update(7, 64, Backend::Cpu, sample(12)));
assert_eq!(
history.service[&History::key(7, 64, Backend::Cpu)],
sample(11)
);
history.freeze();
assert!(!history.update(7, 64, Backend::Cpu, sample(150)));
assert_eq!(
history.service[&History::key(7, 64, Backend::Cpu)],
sample(11)
);
}
#[test]
fn critical_chain_precedes_root_and_reuses_worker() {
let route = Some(Route {
estimate: Duration::from_millis(1),
memory: Memory { ram: 8, vram: 0 },
});
let make = |dependencies| Operation {
dependencies,
class: 0,
bytes: 8,
routes: [route, None, None],
};
let graph = Scheduler::new(vec![
make(vec![]),
make(vec![]),
make(vec![1]),
make(vec![2]),
])
.unwrap();
let runs = std::sync::Mutex::new(Vec::new());
let report = graph
.execute(
Capacity {
workers: [2, 0, 0],
memory: Memory { ram: 8, vram: 0 },
},
&mut History::default(),
|_| Ok(0),
|state, id, _| {
*state += 1;
runs.lock().unwrap().push((id, *state));
Ok(())
},
)
.unwrap();
let values = runs.into_inner().unwrap();
assert_eq!(values[0].0, 1);
assert_eq!(values.len(), 4);
assert!(values.iter().any(|&(_, calls)| calls > 1));
assert_eq!(report.peak.ram, 8);
assert!(report.elapsed >= report.dependency_span);
}
#[test]
fn uses_feasible_route_when_gpu_memory_is_too_small() {
let operation = Operation {
dependencies: vec![],
class: 0,
bytes: 8,
routes: [
Some(Route {
estimate: Duration::from_millis(2),
memory: Memory { ram: 8, vram: 0 },
}),
Some(Route {
estimate: Duration::ZERO,
memory: Memory { ram: 8, vram: 16 },
}),
None,
],
};
let scheduler = Scheduler::new(vec![operation]).unwrap();
let report = scheduler
.execute(
Capacity {
workers: [1, 1, 0],
memory: Memory { ram: 8, vram: 8 },
},
&mut History::default(),
Ok,
|backend, _, _| {
assert_eq!(*backend, Backend::Cpu);
Ok(())
},
)
.unwrap();
assert_eq!(report.samples[0].backend, Backend::Cpu);
}
}