Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GmHhg6k5Hxh8GpVW7od4Di
631 lines
22 KiB
Rust
631 lines
22 KiB
Rust
//! 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>,
|
|
/// Belegt die GPUs immer ganz, auch nach einer Messung (Maya). Sonst
|
|
/// ersetzt der gemessene Wert die Buchung „füllt die GPU“.
|
|
pub exclusive: bool,
|
|
/// 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,
|
|
/// Von einem Administrator entladen.
|
|
Manual,
|
|
/// Verdrängt für eine wartende Anfrage.
|
|
Evicted {
|
|
for_job: JobId,
|
|
for_model: String,
|
|
priority: Priority,
|
|
},
|
|
}
|
|
|
|
/// Warum ein Modell nicht von Hand entladen werden kann.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum UnloadRefusal {
|
|
/// Es gibt keine Instanz des Modells.
|
|
NotLoaded,
|
|
/// Auf der Instanz laufen Anfragen.
|
|
Busy,
|
|
/// Die Instanz lädt gerade oder wird schon entladen.
|
|
InTransition,
|
|
}
|
|
|
|
/// 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,
|
|
exclusive: bool,
|
|
state: InstState,
|
|
active: u32,
|
|
last_used: Instant,
|
|
idle: Option<Duration>,
|
|
/// Nach einem gescheiterten Stopp bis dahin weder verdrängen noch im Leerlauf entladen (#1166).
|
|
unload_blocked_until: Option<Instant>,
|
|
}
|
|
|
|
/// 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.filter(|_| !need.exclusive) {
|
|
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 Some(m) = measured_mb.filter(|m| *m > 0 && !i.exclusive) {
|
|
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)
|
|
}
|
|
|
|
/// Das Beenden der Instanz ist gescheitert und sie läuft nachweislich weiter: Sie bleibt belegt und
|
|
/// bereit, damit ihr Speicher nicht ein zweites Mal vergeben wird. Bis `retry_after` wird sie weder
|
|
/// verdrängt noch im Leerlauf entladen (kein enger Wiederholungskreis); ein Entladen von Hand bleibt möglich.
|
|
pub fn unload_failed(
|
|
&mut self,
|
|
inst: InstId,
|
|
now: Instant,
|
|
retry_after: Duration,
|
|
) -> Vec<Action> {
|
|
if let Some(i) = self.insts.get_mut(&inst) {
|
|
i.state = InstState::Ready;
|
|
i.unload_blocked_until = Some(now + retry_after);
|
|
}
|
|
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)
|
|
}
|
|
|
|
/// Entlädt ein Modell von Hand. Nur möglich, wenn es bereit ist und
|
|
/// keine Anfrage darauf läuft.
|
|
pub fn request_unload(
|
|
&mut self,
|
|
model: &str,
|
|
now: Instant,
|
|
) -> Result<Vec<Action>, UnloadRefusal> {
|
|
let (id, inst) = self
|
|
.insts
|
|
.iter_mut()
|
|
.find(|(_, i)| i.model == model)
|
|
.ok_or(UnloadRefusal::NotLoaded)?;
|
|
if inst.state != InstState::Ready {
|
|
return Err(UnloadRefusal::InTransition);
|
|
}
|
|
if inst.active > 0 {
|
|
return Err(UnloadRefusal::Busy);
|
|
}
|
|
inst.state = InstState::Unloading;
|
|
let mut actions = vec![Action::Unload {
|
|
inst: *id,
|
|
model: model.to_string(),
|
|
reason: UnloadReason::Manual,
|
|
}];
|
|
actions.extend(self.plan(now));
|
|
Ok(actions)
|
|
}
|
|
|
|
/// 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.unload_blocked_until.is_none_or(|t| now >= t)
|
|
&& 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,
|
|
exclusive: job.need.exclusive,
|
|
state: InstState::Loading,
|
|
active: 0,
|
|
last_used: now,
|
|
idle: job.need.idle,
|
|
unload_blocked_until: None,
|
|
},
|
|
);
|
|
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.unload_blocked_until.is_none_or(|t| now >= t)
|
|
&& 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;
|