feat(scheduler): Entscheidungslogik für Ressourcen, Warteschlange, Prioritäten und Verdrängung (#1012)

Neues Crate nexus-scheduler: reine Logik ohne Prozesse und Uhr, 22 Tests.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 14:24:42 +01:00
parent 52d6c5642f
commit 1e79d1e8f7
6 changed files with 1061 additions and 1 deletions

7
Cargo.lock generated
View File

@ -654,6 +654,13 @@ dependencies = [
"toml", "toml",
] ]
[[package]]
name = "nexus-scheduler"
version = "0.1.4"
dependencies = [
"nexus-core",
]
[[package]] [[package]]
name = "nexus-store" name = "nexus-store"
version = "0.1.4" version = "0.1.4"

View File

@ -1,6 +1,6 @@
[workspace] [workspace]
resolver = "3" resolver = "3"
members = ["crates/nexus-core", "crates/nexus-store", "crates/nexus-adapter", "crates/nexus-api", "crates/nexus"] members = ["crates/nexus-core", "crates/nexus-scheduler", "crates/nexus-store", "crates/nexus-adapter", "crates/nexus-api", "crates/nexus"]
[workspace.package] [workspace.package]
version = "0.1.4" version = "0.1.4"
@ -13,6 +13,7 @@ nexus-core = { path = "crates/nexus-core" }
nexus-store = { path = "crates/nexus-store" } nexus-store = { path = "crates/nexus-store" }
nexus-adapter = { path = "crates/nexus-adapter" } nexus-adapter = { path = "crates/nexus-adapter" }
nexus-api = { path = "crates/nexus-api" } nexus-api = { path = "crates/nexus-api" }
nexus-scheduler = { path = "crates/nexus-scheduler" }
async-trait = "0.1" async-trait = "0.1"
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] } axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] }
reqwest = { version = "0.12", default-features = false, features = ["stream"] } reqwest = { version = "0.12", default-features = false, features = ["stream"] }

View File

@ -0,0 +1,9 @@
[package]
name = "nexus-scheduler"
description = "Nexus: Entscheidungslogik für Ressourcen, Warteschlange, Prioritäten und Verdrängung"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
nexus-core.workspace = true

View File

@ -0,0 +1,10 @@
# nexus-scheduler
Entscheidungslogik des Schedulers (Spezifikation, Abschnitt 6): Ressourcen je GPU, Warteschlange,
Prioritäten mit Aging, Verdrängung und Leerlauf.
Das Crate rechnet nur. Es startet keine Prozesse, kennt keine Uhr und kein Netzwerk: Der Aufrufer
(`nexus-api`, Modul `runtime`) meldet Ereignisse mit der aktuellen Zeit und führt die zurückgegebenen
Aktionen aus. Dadurch lassen sich alle Regeln ohne GPU und ohne Wartezeiten testen.
Die Regeln stehen in `docs/scheduler.md`.

View File

@ -0,0 +1,563 @@
//! Entscheidungslogik des Schedulers (Spezifikation, Abschnitt 6).
//!
//! [`Planner`] besitzt den Ressourcenzustand (GPUs, Instanzen, Warteschlange)
//! und trifft alle Entscheidungen. Er rechnet nur: Der Aufrufer meldet
//! Ereignisse mit der aktuellen Zeit und führt die zurückgegebenen
//! [`Action`]s aus (laden, entladen, Anfrage zuteilen oder ablehnen).
//!
//! Regeln in Kürze (Einzelheiten in `docs/scheduler.md`):
//! - Je Modell höchstens eine Instanz; weitere Anfragen hängen sich an einen
//! laufenden Ladevorgang an.
//! - Eine Instanz belegt auf jeder ihrer GPUs einen Anteil. Ohne bekannten
//! Bedarf füllt sie die GPU ([`Need::vram_mb`] = `None`).
//! - Instanzen mit laufenden Anfragen werden nie entladen.
//! - Passt ein Modell nicht, werden unbenutzte Instanzen entladen, die am
//! längsten unbenutzte zuerst. `High` darf das sofort, `Normal` und `Low`
//! erst nach einer Schonfrist.
//! - Wartende Anfragen werden nach Priorität und Alter bedient. Wer nicht
//! bedient werden kann, sperrt seine GPUs für alle, die nach ihm kommen:
//! Freigemachter Speicher bleibt dem, für den er freigemacht wurde.
//! - Aging hebt `Low` nach einer Wartezeit-Stufe auf `Normal`, nie höher.
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, Instant};
use nexus_core::Priority;
pub type JobId = u64;
pub type InstId = u64;
/// Einstellungen des Schedulers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
/// Speicher, der je GPU frei bleibt (MB).
pub reserve_mb: u64,
/// Wie viele Anfragen höchstens warten dürfen.
pub max_waiting: usize,
/// Wie lange eine Anfrage höchstens wartet.
pub max_wait: Duration,
/// Wartezeit, nach der `Low` als `Normal` zählt (`0` = kein Aging).
pub aging_step: Duration,
/// Wie lange eine Instanz unbenutzt sein muss, bevor `Normal` und `Low`
/// sie verdrängen dürfen. `High` wartet nicht.
pub evict_min_idle: Duration,
}
impl Default for Settings {
fn default() -> Self {
Self {
reserve_mb: 512,
max_waiting: 32,
max_wait: Duration::from_secs(300),
aging_step: Duration::from_secs(60),
evict_min_idle: Duration::from_secs(60),
}
}
}
/// Was ein Modell zum Laufen braucht.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Need {
pub model: String,
pub gpus: Vec<u32>,
/// Gesamter VRAM-Bedarf in MB, gleichmäßig auf die GPUs verteilt.
/// `None`: unbekannt, das Modell füllt seine GPUs (exklusiv).
pub vram_mb: Option<u64>,
/// Leerlauf, nach dem entladen wird. `None`: nie.
pub idle: Option<Duration>,
}
/// Eine wartende Anfrage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
pub id: JobId,
pub need: Need,
pub priority: Priority,
/// Beginn der Wartezeit (bleibt beim erneuten Einreihen erhalten).
pub enqueued: Instant,
}
/// Warum eine Instanz entladen wird.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnloadReason {
/// Leerlaufzeit abgelaufen.
Idle,
/// Verdrängt für eine wartende Anfrage.
Evicted {
for_job: JobId,
for_model: String,
priority: Priority,
},
}
/// Was der Aufrufer tun soll.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
/// Die Anfrage darf die (bereite) Instanz nutzen.
Grant { job: JobId, inst: InstId },
/// Instanz für das Modell starten; danach [`Planner::load_done`] melden.
Load { inst: InstId, model: String },
/// Instanz beenden; danach [`Planner::unload_done`] melden.
Unload {
inst: InstId,
model: String,
reason: UnloadReason,
},
/// Die Anfrage hat zu lange gewartet.
Expire { job: JobId },
/// Der Ladevorgang, auf den die Anfrage wartete, ist gescheitert.
Fail { job: JobId },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstState {
Loading,
Ready,
Unloading,
}
/// Belegung je GPU.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Claim {
Mb(u64),
All,
}
#[derive(Debug, Clone)]
struct Inst {
model: String,
gpus: Vec<u32>,
claim: Claim,
state: InstState,
active: u32,
last_used: Instant,
idle: Option<Duration>,
}
/// Sicht auf eine Instanz (für Status und Tests).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstView {
pub id: InstId,
pub model: String,
pub gpus: Vec<u32>,
pub state: InstState,
pub active: u32,
/// Gebuchter VRAM je GPU in MB; `None`: füllt die GPU.
pub booked_mb_per_gpu: Option<u64>,
}
/// Sicht auf eine wartende Anfrage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WaitingView {
pub job: JobId,
pub model: String,
pub priority: Priority,
/// Priorität nach Aging.
pub effective: Priority,
pub waited: Duration,
}
fn claim_of(need: &Need) -> Claim {
match need.vram_mb {
Some(total) => Claim::Mb(total.div_ceil(need.gpus.len().max(1) as u64)),
None => Claim::All,
}
}
pub struct Planner {
settings: Settings,
/// Gesamtspeicher je GPU in MB. Eine GPU ohne Eintrag hat unbekannte
/// Größe: MB-Belegungen werden dort nicht begrenzt, „füllt die GPU“ gilt.
gpus: BTreeMap<u32, u64>,
insts: BTreeMap<InstId, Inst>,
queue: Vec<Job>,
next_inst: InstId,
}
impl Planner {
pub fn new(settings: Settings) -> Self {
Self {
settings,
gpus: BTreeMap::new(),
insts: BTreeMap::new(),
queue: Vec::new(),
next_inst: 1,
}
}
/// Setzt den Gesamtspeicher der GPUs (ersetzt den alten Stand).
pub fn set_gpus(&mut self, totals: impl IntoIterator<Item = (u32, u64)>) {
self.gpus = totals.into_iter().collect();
}
pub fn gpus_known(&self) -> bool {
!self.gpus.is_empty()
}
/// Reiht eine Anfrage ein und plant. `false`: Die Warteschlange ist voll,
/// die Anfrage wurde nicht angenommen.
pub fn submit(&mut self, job: Job, now: Instant) -> (Vec<Action>, bool) {
let id = job.id;
self.queue.push(job);
let actions = self.plan(now);
let still_waiting = self.queue.iter().any(|j| j.id == id);
if still_waiting && self.queue.len() > self.settings.max_waiting {
self.queue.retain(|j| j.id != id);
return (actions, false);
}
(actions, true)
}
/// Nimmt eine wartende Anfrage zurück (Client getrennt).
pub fn cancel(&mut self, job: JobId, now: Instant) -> Vec<Action> {
let before = self.queue.len();
self.queue.retain(|j| j.id != job);
if self.queue.len() == before {
return Vec::new();
}
self.plan(now)
}
/// Eine Anfrage auf der Instanz ist zu Ende.
pub fn release(&mut self, inst: InstId, now: Instant) -> Vec<Action> {
let Some(i) = self.insts.get_mut(&inst) else {
return Vec::new();
};
i.active = i.active.saturating_sub(1);
i.last_used = now;
self.plan(now)
}
/// Ergebnis eines Ladevorgangs. `measured_mb` ist der gemessene gesamte
/// VRAM-Verbrauch; er ersetzt die Buchung, außer das Modell füllt die GPU.
pub fn load_done(
&mut self,
inst: InstId,
ok: bool,
measured_mb: Option<u64>,
now: Instant,
) -> Vec<Action> {
let mut actions = Vec::new();
if ok {
if let Some(i) = self.insts.get_mut(&inst) {
i.state = InstState::Ready;
i.last_used = now;
if let (Claim::Mb(_), Some(m)) = (i.claim, measured_mb.filter(|m| *m > 0)) {
i.claim = Claim::Mb(m.div_ceil(i.gpus.len().max(1) as u64));
}
// Wer auf diesen Ladevorgang gewartet hat, wird zuerst bedient,
// auch wenn inzwischen eine höhere Priorität auf dieselbe GPU
// wartet: Sonst würde das eben geladene Modell ungenutzt
// wieder verdrängt.
let model = i.model.clone();
let attached: Vec<JobId> = self
.order(now)
.into_iter()
.filter(|j| j.need.model == model)
.map(|j| j.id)
.collect();
let i = self.insts.get_mut(&inst).expect("eben gefunden");
i.active += attached.len() as u32;
self.queue.retain(|j| !attached.contains(&j.id));
actions.extend(attached.into_iter().map(|job| Action::Grant { job, inst }));
}
} else if let Some(i) = self.insts.remove(&inst) {
let failed: Vec<JobId> = self
.queue
.iter()
.filter(|j| j.need.model == i.model)
.map(|j| j.id)
.collect();
self.queue.retain(|j| j.need.model != i.model);
actions.extend(failed.into_iter().map(|job| Action::Fail { job }));
}
actions.extend(self.plan(now));
actions
}
/// Die Instanz ist beendet, ihr Speicher ist frei.
pub fn unload_done(&mut self, inst: InstId, now: Instant) -> Vec<Action> {
self.insts.remove(&inst);
self.plan(now)
}
/// Die Instanz ist ohne Zutun des Schedulers verschwunden (Absturz).
pub fn lost(&mut self, inst: InstId, now: Instant) -> Vec<Action> {
if self.insts.remove(&inst).is_none() {
return Vec::new();
}
self.plan(now)
}
/// Regelmäßig aufrufen: Zeitlimit der Wartenden, Leerlauf, Schonfrist
/// und Aging hängen an der Zeit.
pub fn tick(&mut self, now: Instant) -> Vec<Action> {
let mut actions = Vec::new();
let max_wait = self.settings.max_wait;
let expired: Vec<JobId> = self
.queue
.iter()
.filter(|j| now.saturating_duration_since(j.enqueued) >= max_wait)
.map(|j| j.id)
.collect();
self.queue.retain(|j| !expired.contains(&j.id));
actions.extend(expired.into_iter().map(|job| Action::Expire { job }));
actions.extend(self.plan(now));
let idle: Vec<InstId> = self
.insts
.iter()
.filter(|(_, i)| {
i.state == InstState::Ready
&& i.active == 0
&& i.idle
.is_some_and(|d| now.saturating_duration_since(i.last_used) >= d)
&& !self.queue.iter().any(|j| j.need.model == i.model)
})
.map(|(id, _)| *id)
.collect();
for id in idle {
let i = self.insts.get_mut(&id).expect("eben gefunden");
i.state = InstState::Unloading;
actions.push(Action::Unload {
inst: id,
model: i.model.clone(),
reason: UnloadReason::Idle,
});
}
actions
}
/// Alle Instanzen, die der Scheduler kennt.
pub fn instances(&self) -> Vec<InstView> {
self.insts
.iter()
.map(|(id, i)| InstView {
id: *id,
model: i.model.clone(),
gpus: i.gpus.clone(),
state: i.state,
active: i.active,
booked_mb_per_gpu: match i.claim {
Claim::Mb(mb) => Some(mb),
Claim::All => None,
},
})
.collect()
}
/// Wartende Anfragen in der Reihenfolge, in der sie bedient werden.
pub fn waiting(&self, now: Instant) -> Vec<WaitingView> {
self.order(now)
.into_iter()
.map(|j| WaitingView {
job: j.id,
model: j.need.model.clone(),
priority: j.priority,
effective: self.effective(&j, now),
waited: now.saturating_duration_since(j.enqueued),
})
.collect()
}
pub fn waiting_count(&self) -> usize {
self.queue.len()
}
/// Nimmt alle Wartenden aus der Schlange (Herunterfahren).
pub fn drain_queue(&mut self) -> Vec<JobId> {
self.queue.drain(..).map(|j| j.id).collect()
}
/// Entfernt alle Instanzen aus dem Zustand (Herunterfahren).
pub fn clear_instances(&mut self) {
self.insts.clear();
}
/// Läuft gerade ein Lade- oder Entladevorgang?
pub fn in_transition(&self) -> bool {
self.insts.values().any(|i| i.state != InstState::Ready)
}
fn effective(&self, job: &Job, now: Instant) -> Priority {
let step = self.settings.aging_step;
if job.priority == Priority::Low
&& !step.is_zero()
&& now.saturating_duration_since(job.enqueued) >= step
{
Priority::Normal
} else {
job.priority
}
}
fn order(&self, now: Instant) -> Vec<Job> {
let mut jobs = self.queue.clone();
jobs.sort_by_key(|j| (std::cmp::Reverse(self.effective(j, now)), j.enqueued, j.id));
jobs
}
/// Passt `claim` auf alle `gpus`, wenn die Instanzen, für die `ignore`
/// zutrifft, nicht mitzählen?
fn fits(&self, gpus: &[u32], claim: Claim, ignore: &dyn Fn(InstId, &Inst) -> bool) -> bool {
gpus.iter().all(|gpu| {
let mut used_mb = 0u64;
let mut occupied = false;
let mut full = false;
for (id, i) in &self.insts {
if ignore(*id, i) || !i.gpus.contains(gpu) {
continue;
}
occupied = true;
match i.claim {
Claim::All => full = true,
Claim::Mb(mb) => used_mb += mb,
}
}
if !occupied {
// Eine leere GPU nimmt jedes Modell an; ist es zu groß,
// scheitert der Start der Engine mit einem klaren Fehler.
return true;
}
if full {
return false;
}
match (claim, self.gpus.get(gpu)) {
(Claim::All, _) => false,
(Claim::Mb(_), None) => true,
(Claim::Mb(mb), Some(total)) => {
used_mb + mb <= total.saturating_sub(self.settings.reserve_mb)
}
}
})
}
fn plan(&mut self, now: Instant) -> Vec<Action> {
let mut actions = Vec::new();
let mut blocked: BTreeSet<u32> = BTreeSet::new();
for job in self.order(now) {
let gpus = &job.need.gpus;
if gpus.iter().any(|g| blocked.contains(g)) {
blocked.extend(gpus.iter().copied());
continue;
}
let existing = self
.insts
.iter()
.find(|(_, i)| i.model == job.need.model)
.map(|(id, i)| (*id, i.state));
match existing {
Some((id, InstState::Ready)) => {
let i = self.insts.get_mut(&id).expect("eben gefunden");
i.active += 1;
i.last_used = now;
self.queue.retain(|j| j.id != job.id);
actions.push(Action::Grant {
job: job.id,
inst: id,
});
}
// Hängt sich an den laufenden Ladevorgang an.
Some((_, InstState::Loading)) => {}
// Wird gerade entladen: danach neu laden.
Some((_, InstState::Unloading)) => blocked.extend(gpus.iter().copied()),
None => {
let claim = claim_of(&job.need);
if self.fits(gpus, claim, &|_, _| false) {
let id = self.next_inst;
self.next_inst += 1;
self.insts.insert(
id,
Inst {
model: job.need.model.clone(),
gpus: gpus.clone(),
claim,
state: InstState::Loading,
active: 0,
last_used: now,
idle: job.need.idle,
},
);
actions.push(Action::Load {
inst: id,
model: job.need.model.clone(),
});
continue;
}
let priority = self.effective(&job, now);
for id in self.victims(&job, claim, priority, now) {
let i = self.insts.get_mut(&id).expect("eben gewählt");
i.state = InstState::Unloading;
actions.push(Action::Unload {
inst: id,
model: i.model.clone(),
reason: UnloadReason::Evicted {
for_job: job.id,
for_model: job.need.model.clone(),
priority,
},
});
}
blocked.extend(gpus.iter().copied());
}
}
}
actions
}
/// Wählt die Instanzen, die für `job` weichen müssen: nur unbenutzte, die
/// am längsten unbenutzte zuerst, und nur, wenn es danach wirklich passt.
/// Leer, wenn schon genug entladen wird oder Verdrängen nicht reicht.
fn victims(&self, job: &Job, claim: Claim, priority: Priority, now: Instant) -> Vec<InstId> {
let gpus = &job.need.gpus;
let unloading = |i: &Inst| i.state == InstState::Unloading;
if self.fits(gpus, claim, &|_, i| unloading(i)) {
return Vec::new();
}
let mut candidates: Vec<(Instant, InstId)> = self
.insts
.iter()
.filter(|(_, i)| {
i.state == InstState::Ready
&& i.active == 0
&& i.gpus.iter().any(|g| gpus.contains(g))
&& (priority == Priority::High
|| now.saturating_duration_since(i.last_used)
>= self.settings.evict_min_idle)
})
.map(|(id, i)| (i.last_used, *id))
.collect();
candidates.sort();
let mut chosen: Vec<InstId> = Vec::new();
let mut enough = false;
for (_, id) in candidates {
chosen.push(id);
if self.fits(gpus, claim, &|id, i| unloading(i) || chosen.contains(&id)) {
enough = true;
break;
}
}
if !enough {
return Vec::new();
}
// Wer nicht weichen muss, bleibt.
let mut index = 0;
while index < chosen.len() {
let without: Vec<InstId> = chosen
.iter()
.copied()
.filter(|id| *id != chosen[index])
.collect();
if self.fits(gpus, claim, &|id, i| unloading(i) || without.contains(&id)) {
chosen = without;
} else {
index += 1;
}
}
chosen
}
}
#[cfg(test)]
mod tests;

View File

@ -0,0 +1,470 @@
use super::*;
const GPU_MB: u64 = 12288;
struct Bench {
p: Planner,
t0: Instant,
next_job: JobId,
}
fn need(model: &str, gpus: &[u32], vram_mb: Option<u64>) -> Need {
Need {
model: model.to_string(),
gpus: gpus.to_vec(),
vram_mb,
idle: Some(Duration::from_secs(1800)),
}
}
impl Bench {
fn new() -> Self {
Self::with(Settings::default())
}
fn with(settings: Settings) -> Self {
let mut p = Planner::new(settings);
p.set_gpus([(0, GPU_MB), (1, GPU_MB)]);
Self {
p,
t0: Instant::now(),
next_job: 1,
}
}
fn at(&self, secs: u64) -> Instant {
self.t0 + Duration::from_secs(secs)
}
fn submit(&mut self, need: Need, priority: Priority, secs: u64) -> (JobId, Vec<Action>) {
let id = self.next_job;
self.next_job += 1;
let now = self.at(secs);
let (actions, accepted) = self.p.submit(
Job {
id,
need,
priority,
enqueued: now,
},
now,
);
assert!(accepted, "Anfrage {id} wurde nicht angenommen");
(id, actions)
}
/// Lädt ein Modell und gibt die Instanz wieder frei (unbenutzt seit `secs`).
fn loaded_idle(&mut self, need: Need, secs: u64) -> InstId {
let (job, actions) = self.submit(need, Priority::Normal, secs);
let inst = load_of(&actions).expect("Ladevorgang");
let actions = self.p.load_done(inst, true, None, self.at(secs));
assert_eq!(actions, vec![Action::Grant { job, inst }]);
assert!(self.p.release(inst, self.at(secs)).is_empty());
inst
}
fn state(&self, inst: InstId) -> Option<InstState> {
self.p
.instances()
.into_iter()
.find(|i| i.id == inst)
.map(|i| i.state)
}
}
fn load_of(actions: &[Action]) -> Option<InstId> {
actions.iter().find_map(|a| match a {
Action::Load { inst, .. } => Some(*inst),
_ => None,
})
}
fn unloads(actions: &[Action]) -> Vec<InstId> {
actions
.iter()
.filter_map(|a| match a {
Action::Unload { inst, .. } => Some(*inst),
_ => None,
})
.collect()
}
fn grants(actions: &[Action]) -> Vec<JobId> {
actions
.iter()
.filter_map(|a| match a {
Action::Grant { job, .. } => Some(*job),
_ => None,
})
.collect()
}
#[test]
fn zwei_anfragen_fuer_dasselbe_modell_laden_nur_einmal() {
let mut b = Bench::new();
let (j1, a1) = b.submit(need("a", &[0], Some(4000)), Priority::Normal, 0);
let (j2, a2) = b.submit(need("a", &[0], Some(4000)), Priority::Normal, 0);
let inst = load_of(&a1).unwrap();
assert!(a2.is_empty(), "zweite Anfrage hängt sich an: {a2:?}");
let done = b.p.load_done(inst, true, None, b.at(3));
assert_eq!(grants(&done), vec![j1, j2]);
assert_eq!(b.p.instances()[0].active, 2);
}
#[test]
fn zwei_modelle_die_zusammen_passen_laufen_nebeneinander() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], Some(5000)), Priority::Normal, 0);
let (_, c) = b.submit(need("b", &[0], Some(6000)), Priority::Normal, 0);
assert!(load_of(&a).is_some() && load_of(&c).is_some());
}
#[test]
fn reserve_bleibt_frei_und_es_wird_nicht_ueberbucht() {
let mut b = Bench::new();
// 12288 - 512 Reserve = 11776 nutzbar: 6000 + 5776 passt, 6000 + 5777 nicht.
let (_, a) = b.submit(need("a", &[0], Some(6000)), Priority::Normal, 0);
let (_, c) = b.submit(need("b", &[0], Some(5777)), Priority::Normal, 0);
assert!(load_of(&a).is_some());
assert!(c.is_empty(), "b darf nicht laden: {c:?}");
let (_, d) = b.submit(need("c", &[1], Some(5776)), Priority::Normal, 0);
assert!(load_of(&d).is_some(), "andere GPU ist frei");
}
#[test]
fn instanz_mit_laufender_anfrage_wird_nie_verdraengt_auch_nicht_von_high() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], Some(8000)), Priority::Normal, 0);
let inst = load_of(&a).unwrap();
b.p.load_done(inst, true, None, b.at(1));
let (high, c) = b.submit(need("b", &[0], Some(8000)), Priority::High, 2);
assert!(c.is_empty(), "{c:?}");
assert!(b.p.tick(b.at(200)).is_empty());
// Erst wenn die Anfrage zu Ende ist, weicht die Instanz, für High sofort.
let after = b.p.release(inst, b.at(201));
assert_eq!(unloads(&after), vec![inst]);
let loaded = b.p.unload_done(inst, b.at(202));
let new = load_of(&loaded).unwrap();
assert_eq!(
grants(&b.p.load_done(new, true, None, b.at(203))),
vec![high]
);
}
#[test]
fn high_verdraengt_sofort_normal_erst_nach_der_schonfrist() {
let mut b = Bench::new();
let inst = b.loaded_idle(need("a", &[0], Some(8000)), 0);
let (_, n) = b.submit(need("b", &[0], Some(8000)), Priority::Normal, 10);
assert!(n.is_empty(), "Normal wartet die Schonfrist ab: {n:?}");
assert!(b.p.tick(b.at(59)).is_empty());
let t = b.p.tick(b.at(60));
assert_eq!(unloads(&t), vec![inst]);
assert!(matches!(
&t[0],
Action::Unload {
reason: UnloadReason::Evicted { for_model, priority: Priority::Normal, .. },
..
} if for_model == "b"
));
let mut b = Bench::new();
let inst = b.loaded_idle(need("a", &[0], Some(8000)), 0);
let (_, h) = b.submit(need("b", &[0], Some(8000)), Priority::High, 1);
assert_eq!(unloads(&h), vec![inst]);
}
#[test]
fn verdraengt_wird_die_am_laengsten_unbenutzte_und_nur_so_viel_wie_noetig() {
let mut b = Bench::new();
let alt = b.loaded_idle(need("alt", &[0], Some(4000)), 0);
let neu = b.loaded_idle(need("neu", &[0], Some(4000)), 50);
let andere_gpu = b.loaded_idle(need("fern", &[1], Some(4000)), 0);
let (_, a) = b.submit(need("x", &[0], Some(6000)), Priority::High, 100);
assert_eq!(unloads(&a), vec![alt]);
assert_eq!(b.state(neu), Some(InstState::Ready));
assert_eq!(b.state(andere_gpu), Some(InstState::Ready));
}
#[test]
fn nur_wer_weichen_muss_wird_entladen() {
let mut b = Bench::new();
// Die älteste Instanz ist klein; erst die zweite macht genug frei.
let klein = b.loaded_idle(need("klein", &[0], Some(1000)), 0);
let gross = b.loaded_idle(need("gross", &[0], Some(9000)), 10);
let (_, a) = b.submit(need("x", &[0], Some(9000)), Priority::High, 100);
assert_eq!(unloads(&a), vec![gross]);
assert_eq!(b.state(klein), Some(InstState::Ready));
}
#[test]
fn reicht_verdraengen_nicht_wird_nichts_entladen() {
let mut b = Bench::new();
let idle = b.loaded_idle(need("idle", &[0], Some(3000)), 0);
let (_, a) = b.submit(need("busy", &[0], Some(6000)), Priority::Normal, 0);
b.p.load_done(load_of(&a).unwrap(), true, None, b.at(1));
let (_, x) = b.submit(need("x", &[0], Some(9000)), Priority::High, 100);
assert!(x.is_empty(), "{x:?}");
assert_eq!(b.state(idle), Some(InstState::Ready));
}
#[test]
fn modell_ohne_angabe_fuellt_die_gpu_und_exklusives_modell_raeumt_beide() {
let mut b = Bench::new();
let (_, a) = b.submit(need("unbekannt", &[0], None), Priority::Normal, 0);
let u = load_of(&a).unwrap();
b.p.load_done(u, true, Some(700), b.at(1));
let (_, c) = b.submit(need("klein", &[0], Some(100)), Priority::Normal, 1);
assert!(
c.is_empty(),
"neben einem füllenden Modell passt nichts: {c:?}"
);
assert_eq!(b.p.instances()[0].booked_mb_per_gpu, None);
let mut b = Bench::new();
let a = b.loaded_idle(need("a", &[0], Some(2000)), 0);
let c = b.loaded_idle(need("c", &[1], Some(2000)), 0);
let (maya, x) = b.submit(need("maya", &[0, 1], None), Priority::High, 5);
assert_eq!(unloads(&x), vec![a, c]);
assert!(
b.p.unload_done(a, b.at(6)).is_empty(),
"eine GPU ist noch belegt"
);
let l = b.p.unload_done(c, b.at(7));
let inst = load_of(&l).unwrap();
assert_eq!(
grants(&b.p.load_done(inst, true, None, b.at(80))),
vec![maya]
);
// Solange das exklusive Modell benutzt wird, startet nichts daneben.
let (_, y) = b.submit(need("a", &[0], Some(2000)), Priority::High, 81);
assert!(y.is_empty(), "{y:?}");
}
#[test]
fn gemessener_wert_ersetzt_die_buchung() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0, 1], Some(20000)), Priority::Normal, 0);
let inst = load_of(&a).unwrap();
assert_eq!(b.p.instances()[0].booked_mb_per_gpu, Some(10000));
b.p.load_done(inst, true, Some(8001), b.at(1));
assert_eq!(b.p.instances()[0].booked_mb_per_gpu, Some(4001));
}
#[test]
fn freigemachter_speicher_bleibt_dem_wartenden_und_spaetere_stellen_sich_an() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], Some(8000)), Priority::Normal, 0);
let a_inst = load_of(&a).unwrap();
b.p.load_done(a_inst, true, None, b.at(1));
// High wartet auf GPU 0 (a ist benutzt).
let (high, h) = b.submit(need("b", &[0], Some(8000)), Priority::High, 2);
assert!(h.is_empty());
// Ein kleines Modell würde noch passen, darf dem Wartenden aber nichts wegnehmen.
let (_, k) = b.submit(need("klein", &[0], Some(3000)), Priority::Low, 3);
assert!(k.is_empty(), "{k:?}");
// Eine weitere Anfrage für das geladene Modell stellt sich hinten an.
let (spaeter, s) = b.submit(need("a", &[0], Some(8000)), Priority::Normal, 4);
assert!(s.is_empty(), "{s:?}");
// Die andere GPU ist nicht betroffen.
let (_, o) = b.submit(need("fern", &[1], Some(3000)), Priority::Low, 4);
assert!(load_of(&o).is_some());
let r = b.p.release(a_inst, b.at(5));
assert_eq!(unloads(&r), vec![a_inst]);
let l = b.p.unload_done(a_inst, b.at(6));
assert_eq!(l.len(), 1, "nur b lädt: {l:?}");
let b_inst = load_of(&l).unwrap();
assert_eq!(
grants(&b.p.load_done(b_inst, true, None, b.at(7))),
vec![high]
);
assert!(b.p.waiting(b.at(7)).iter().any(|w| w.job == spaeter));
}
#[test]
fn high_wird_vor_normal_und_low_bedient_bei_gleicher_prioritaet_die_aeltere() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], None), Priority::Normal, 0);
let inst = load_of(&a).unwrap();
b.submit(need("l", &[0], None), Priority::Low, 1);
b.submit(need("n1", &[0], None), Priority::Normal, 2);
b.submit(need("n2", &[0], None), Priority::Normal, 3);
b.submit(need("h", &[0], None), Priority::High, 4);
b.p.load_done(inst, true, None, b.at(5));
let order: Vec<String> = b.p.waiting(b.at(5)).into_iter().map(|w| w.model).collect();
assert_eq!(order, ["h", "n1", "n2", "l"]);
}
#[test]
fn aging_hebt_low_auf_normal_aber_nie_auf_high() {
let mut b = Bench::new();
let inst = b.loaded_idle(need("a", &[0], Some(8000)), 0);
let (low, _) = b.submit(need("b", &[0], Some(8000)), Priority::Low, 0);
// Nach 60 s zählt Low als Normal und steht vor einer jüngeren Normal-Anfrage.
let (_, _) = b.submit(need("c", &[0], Some(8000)), Priority::Normal, 30);
let w = b.p.waiting(b.at(59));
assert_eq!(w[0].model, "c");
let w = b.p.waiting(b.at(60));
assert_eq!((w[0].job, w[0].effective), (low, Priority::Normal));
assert_eq!(b.p.waiting(b.at(299))[0].effective, Priority::Normal);
// Wie High verdrängt die gealterte Anfrage nicht: Die Schonfrist gilt weiter.
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], Some(8000)), Priority::Normal, 0);
let inst2 = load_of(&a).unwrap();
b.p.load_done(inst2, true, None, b.at(0));
let (_, _) = b.submit(need("b", &[0], Some(8000)), Priority::Low, 0);
let r = b.p.release(inst2, b.at(100));
assert!(
r.is_empty(),
"gealtertes Low wartet die Schonfrist ab: {r:?}"
);
assert_eq!(unloads(&b.p.tick(b.at(160))), vec![inst2]);
let _ = inst;
}
#[test]
fn volle_warteschlange_lehnt_ab_ohne_bediente_anfragen_zu_zaehlen() {
let mut b = Bench::with(Settings {
max_waiting: 2,
..Settings::default()
});
let (_, a) = b.submit(need("a", &[0], None), Priority::Normal, 0);
let inst = load_of(&a).unwrap();
b.submit(need("a", &[0], None), Priority::Normal, 0);
// Zwei warten (auf den Ladevorgang); die dritte wird abgelehnt.
let now = b.at(1);
let job = |id| Job {
id,
need: need("a", &[0], None),
priority: Priority::Normal,
enqueued: now,
};
let (_, accepted) = b.p.submit(job(90), now);
assert!(!accepted);
assert_eq!(b.p.waiting_count(), 2);
// Ist das Modell bereit, wird sofort bedient und nichts abgelehnt.
b.p.load_done(inst, true, None, now);
for id in 91..95 {
let (actions, accepted) = b.p.submit(job(id), now);
assert!(accepted);
assert_eq!(grants(&actions), vec![id]);
}
}
#[test]
fn wartezeit_laeuft_ab() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], None), Priority::Normal, 0);
b.p.load_done(load_of(&a).unwrap(), true, None, b.at(0));
let (job, _) = b.submit(need("b", &[0], None), Priority::Normal, 10);
assert!(b.p.tick(b.at(309)).is_empty());
assert_eq!(b.p.tick(b.at(310)), vec![Action::Expire { job }]);
assert_eq!(b.p.waiting_count(), 0);
}
#[test]
fn leerlauf_entlaedt_nach_der_frist_nie_bei_nie_und_nicht_wenn_jemand_wartet() {
let mut b = Bench::new();
let inst = b.loaded_idle(need("a", &[0], Some(1000)), 0);
let mut nie = need("haus", &[1], Some(1000));
nie.idle = None;
let haus = b.loaded_idle(nie, 0);
assert!(b.p.tick(b.at(1799)).is_empty());
let t = b.p.tick(b.at(1800));
assert_eq!(
t,
vec![Action::Unload {
inst,
model: "a".to_string(),
reason: UnloadReason::Idle
}]
);
assert!(b.p.tick(b.at(1801)).is_empty(), "nicht zweimal entladen");
assert_eq!(b.state(haus), Some(InstState::Ready));
assert!(b.p.tick(b.at(100_000)).is_empty());
// Kommt während des Entladens eine Anfrage, wird danach neu geladen.
let (job, a) = b.submit(need("a", &[0], Some(1000)), Priority::Normal, 1802);
assert!(a.is_empty());
let l = b.p.unload_done(inst, b.at(1803));
let neu = load_of(&l).unwrap();
assert_eq!(
grants(&b.p.load_done(neu, true, None, b.at(1804))),
vec![job]
);
}
#[test]
fn gescheiterter_ladevorgang_laesst_alle_wartenden_dieses_modells_scheitern() {
let mut b = Bench::new();
let (j1, a) = b.submit(need("a", &[0], None), Priority::Normal, 0);
let (j2, _) = b.submit(need("a", &[0], None), Priority::Normal, 0);
let (j3, _) = b.submit(need("b", &[0], None), Priority::Normal, 0);
let done = b.p.load_done(load_of(&a).unwrap(), false, None, b.at(1));
assert_eq!(
done[..2],
[Action::Fail { job: j1 }, Action::Fail { job: j2 }]
);
// Der Speicher ist wieder frei: Das andere Modell lädt.
assert!(load_of(&done).is_some());
assert_eq!(b.p.waiting(b.at(1))[0].job, j3);
}
#[test]
fn abbruch_einer_wartenden_gibt_die_gesperrten_gpus_frei() {
let mut b = Bench::new();
let (_, a) = b.submit(need("a", &[0], Some(8000)), Priority::Normal, 0);
b.p.load_done(load_of(&a).unwrap(), true, None, b.at(0));
let (gross, _) = b.submit(need("b", &[0], Some(8000)), Priority::Normal, 1);
let (_, k) = b.submit(need("klein", &[0], Some(3000)), Priority::Normal, 2);
assert!(k.is_empty());
let c = b.p.cancel(gross, b.at(3));
assert!(load_of(&c).is_some(), "klein lädt jetzt: {c:?}");
assert!(b.p.cancel(gross, b.at(4)).is_empty());
}
#[test]
fn verschwundene_instanz_wird_neu_geladen() {
let mut b = Bench::new();
let inst = b.loaded_idle(need("a", &[0], Some(1000)), 0);
assert!(b.p.lost(inst, b.at(1)).is_empty());
let (_, a) = b.submit(need("a", &[0], Some(1000)), Priority::Normal, 2);
assert!(load_of(&a).is_some_and(|neu| neu != inst));
// Eine Freigabe für die alte Instanz stört nicht.
assert!(b.p.release(inst, b.at(3)).is_empty());
}
#[test]
fn ohne_bekannte_gpu_groesse_wird_nach_mb_nicht_begrenzt_aber_exklusiv_bleibt_exklusiv() {
let mut b = Bench::new();
b.p.set_gpus([]);
assert!(!b.p.gpus_known());
for (i, model) in ["a", "b", "c"].iter().enumerate() {
let (_, a) = b.submit(need(model, &[0], Some(50_000)), Priority::Normal, i as u64);
assert!(load_of(&a).is_some());
}
let (_, x) = b.submit(need("voll", &[0], None), Priority::Normal, 5);
assert!(x.is_empty(), "{x:?}");
}
#[test]
fn zu_grosses_modell_darf_auf_die_leere_gpu() {
let mut b = Bench::new();
let (_, a) = b.submit(need("riese", &[0], Some(50_000)), Priority::Normal, 0);
assert!(load_of(&a).is_some());
}
#[test]
fn wer_auf_den_ladevorgang_wartet_wird_vor_einer_hoeheren_prioritaet_bedient() {
let mut b = Bench::new();
let (normal, a) = b.submit(need("a", &[0], None), Priority::Normal, 0);
let inst = load_of(&a).unwrap();
let (_, h) = b.submit(need("h", &[0], None), Priority::High, 1);
assert!(h.is_empty());
// Das eben geladene Modell wird nicht ungenutzt wieder verdrängt.
let done = b.p.load_done(inst, true, None, b.at(5));
assert_eq!(done, vec![Action::Grant { job: normal, inst }]);
assert_eq!(unloads(&b.p.release(inst, b.at(6))), vec![inst]);
}