Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b00a25e2f5
|
||
|
|
b22474c0a5
|
@@ -1367,5 +1367,40 @@ than upstream's own bf16 (0.32). A 180 s vocal song with the 0.6B
|
||||
planner takes 44 s on a 3060 (q8, 7.1 GB peak). The 0.6B planner is a
|
||||
separate repo, so name it by id: `planner = "ACE-Step/acestep-5Hz-lm-0.6B"`.
|
||||
|
||||
**Rigs: replicas and power schedules (#397).** A mining rig's cards sit
|
||||
on PCIe x1 risers, where tensor parallelism floods the bus, so a rig
|
||||
serves one independent copy of a music model per card.
|
||||
`[harness.candle.audio] replicas = "per-device"` (or a device list, or a
|
||||
model's own `replicas` in its load spec) loads a copy on each card behind
|
||||
one model id; cortex keeps seeing one model per host. Design choices:
|
||||
|
||||
- **Neuron-internal dispatch, one admission controller per model** with a
|
||||
slot per copy, then an idle copy from a round-robin `ReplicaPool`
|
||||
(`harness/replica.rs`). Queue, fair share and the anonymous ceiling see
|
||||
the whole capacity, and `/health` sums naturally: `max_in_flight` is the
|
||||
copy count, with a per-copy `replicas` breakdown; `/models` reports
|
||||
`replicas`. A copy whose device worker is poisoned is retired and never
|
||||
handed out again; otherwise it would fail requests fastest and attract
|
||||
them. One card failing to load leaves the others serving.
|
||||
- **cortex weighs load as a share of capacity**, `(in_flight + queue) /
|
||||
max_in_flight`, so an 8-copy rig with two renders running counts as
|
||||
less busy than a single card with one.
|
||||
- **The audio job gate follows the fleet**: `[audio_jobs] max_concurrent
|
||||
= 0` (now the default) sums the in-flight capacity of loaded music
|
||||
models on hosts taking work, minimum 1. A fixed number would leave most
|
||||
of an 18-card rig idle.
|
||||
|
||||
Solar hosts go dark daily. `[availability] online = ["06:30-18:45"]`
|
||||
(UTC) makes `/health` announce `next_dark {drain_at, starts_at,
|
||||
ends_at}`. The host sets `drain_at` (`drain_secs`, default 900) because it
|
||||
knows how long its jobs run. cortex stops routing and cold-loading there
|
||||
from `drain_at` (`NodeState::takes_work`), marks it unhealthy at once
|
||||
when it goes silent inside the window, logs the departure and return once
|
||||
each at `info` instead of warning every poll, and reports
|
||||
`nodes.scheduled_dark` on its `/health` (gauge
|
||||
`cortex_node_scheduled_dark`). An unannounced outage is still debounced
|
||||
and warned about as before. Component placement across cards (HeartMuLa's
|
||||
LM on one card and codec on another) is not built yet.
|
||||
|
||||
**Next:** the Pascal epic #380 (rig work waits until rigs are named; the fallback if
|
||||
ACE-Step cannot run on Pascal is Stable Audio and/or EzAudio).
|
||||
|
||||
+3
-1
@@ -124,7 +124,9 @@ enabled = false
|
||||
# Finished jobs and their audio are deleted after this many hours.
|
||||
# retention_hours = 72
|
||||
# Renders running at once across the fleet; the rest queue in cortex.
|
||||
# max_concurrent = 4
|
||||
# 0 follows the fleet: the in-flight capacity its loaded music models
|
||||
# advertise, counting every replica on a multi-card host (minimum 1).
|
||||
# max_concurrent = 0
|
||||
# Dispatch attempts per job; a busy (429/503) model does not use one up.
|
||||
# max_attempts = 2
|
||||
# How long a job may wait on a busy model before failing, in seconds.
|
||||
|
||||
@@ -48,6 +48,11 @@ pub struct AudioJobsConfig {
|
||||
/// How many renders cortex runs at once across the fleet. Each one
|
||||
/// occupies a neuron device for its whole duration; queued jobs wait
|
||||
/// in cortex rather than piling onto neuron admission queues.
|
||||
///
|
||||
/// `0` (the default) follows the fleet (#397): the summed in-flight
|
||||
/// capacity of the music models loaded on hosts taking work, which
|
||||
/// counts every replica of a model on a multi-card host, and at least
|
||||
/// one so a cold model can still be loaded.
|
||||
#[serde(default = "default_audio_max_concurrent")]
|
||||
pub max_concurrent: usize,
|
||||
/// Dispatch attempts per job before it fails. A busy neuron (429/503)
|
||||
@@ -85,7 +90,7 @@ fn default_audio_retention_hours() -> u64 {
|
||||
72
|
||||
}
|
||||
fn default_audio_max_concurrent() -> usize {
|
||||
4
|
||||
0
|
||||
}
|
||||
fn default_audio_max_attempts() -> u32 {
|
||||
2
|
||||
|
||||
@@ -75,6 +75,10 @@ pub struct HealthResponse {
|
||||
/// interoperable (absent → empty → treated as no load info).
|
||||
#[serde(default)]
|
||||
pub models: Vec<ModelLoad>,
|
||||
/// This host's next scheduled absence (#397), or the one it is in.
|
||||
/// Absent for a host with no schedule.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub next_dark: Option<DarkWindow>,
|
||||
}
|
||||
|
||||
/// Live admission load for one loaded model (#53).
|
||||
@@ -153,6 +157,48 @@ pub struct ModelLoad {
|
||||
/// sample. `#[serde(default)]` for back-compat.
|
||||
#[serde(default)]
|
||||
pub tok_s_decode: f64,
|
||||
/// Per-replica load for a model with copies on several devices (#397).
|
||||
/// The model-level fields above are their sums; this says how the
|
||||
/// work is spread. Empty for an unreplicated model.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub replicas: Vec<ReplicaLoad>,
|
||||
}
|
||||
|
||||
/// One replica of a replicated model (#397).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ReplicaLoad {
|
||||
pub device: u32,
|
||||
/// Requests this replica is running.
|
||||
pub in_flight: usize,
|
||||
/// `false` once its device has failed; it takes no more work.
|
||||
pub healthy: bool,
|
||||
}
|
||||
|
||||
/// A window in which a host is expected to be off (#397), in unix
|
||||
/// seconds. Solar-powered hosts leave the mesh on a schedule; announcing
|
||||
/// it lets cortex stop sending work before the host goes, and treat its
|
||||
/// absence as planned rather than as a fault.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DarkWindow {
|
||||
/// From here on the host takes no new work, so what it is running can
|
||||
/// finish before it goes. The host sets it: it knows how long its work
|
||||
/// takes.
|
||||
pub drain_at: u64,
|
||||
pub starts_at: u64,
|
||||
pub ends_at: u64,
|
||||
}
|
||||
|
||||
impl DarkWindow {
|
||||
/// Whether a host announcing this window should be sent new work at
|
||||
/// `now`.
|
||||
pub fn takes_work_at(&self, now: u64) -> bool {
|
||||
now < self.drain_at || now >= self.ends_at
|
||||
}
|
||||
|
||||
/// Whether `now` falls in the planned absence, draining included.
|
||||
pub fn expects_absence_at(&self, now: u64) -> bool {
|
||||
now >= self.drain_at && now < self.ends_at
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -193,7 +239,9 @@ mod health_load_tests {
|
||||
rejected_anon_yield: 0,
|
||||
tok_s_prefill: 0.0,
|
||||
tok_s_decode: 0.0,
|
||||
replicas: vec![],
|
||||
}],
|
||||
next_dark: None,
|
||||
};
|
||||
let s = serde_json::to_string(&resp).unwrap();
|
||||
let back: HealthResponse = serde_json::from_str(&s).unwrap();
|
||||
|
||||
@@ -216,6 +216,60 @@ pub struct ModelSpec {
|
||||
/// `None` takes the host's setting, which is every model today.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_in_flight: Option<usize>,
|
||||
|
||||
/// Run an independent copy of this model on each of several devices
|
||||
/// (#397), overriding the host's own setting.
|
||||
///
|
||||
/// Each replica has its own weights and device worker; the neuron
|
||||
/// hands each admitted request to an idle one. cortex keeps seeing one
|
||||
/// model per host whose capacity is the replicas' sum. Only music
|
||||
/// models replicate today; anything else refuses a spec that asks.
|
||||
///
|
||||
/// `None` takes the host's setting.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub replicas: Option<Replicas>,
|
||||
}
|
||||
|
||||
/// Which devices carry a copy of a replicated model (#397).
|
||||
///
|
||||
/// Written `"per-device"` (every device the model may use: its `devices`
|
||||
/// when given, else every CUDA device on the host) or as an explicit list
|
||||
/// of device indices.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "ReplicasRepr", into = "ReplicasRepr")]
|
||||
pub enum Replicas {
|
||||
PerDevice,
|
||||
Devices(Vec<u32>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum ReplicasRepr {
|
||||
Word(String),
|
||||
List(Vec<u32>),
|
||||
}
|
||||
|
||||
impl TryFrom<ReplicasRepr> for Replicas {
|
||||
type Error = String;
|
||||
fn try_from(r: ReplicasRepr) -> Result<Self, String> {
|
||||
match r {
|
||||
ReplicasRepr::Word(w) if w == "per-device" => Ok(Replicas::PerDevice),
|
||||
ReplicasRepr::Word(w) => Err(format!(
|
||||
"replicas must be \"per-device\" or a list of device indices, got \"{w}\""
|
||||
)),
|
||||
ReplicasRepr::List(d) if d.is_empty() => Err("replicas lists no devices".to_string()),
|
||||
ReplicasRepr::List(d) => Ok(Replicas::Devices(d)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Replicas> for ReplicasRepr {
|
||||
fn from(r: Replicas) -> Self {
|
||||
match r {
|
||||
Replicas::PerDevice => ReplicasRepr::Word("per-device".into()),
|
||||
Replicas::Devices(d) => ReplicasRepr::List(d),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a sparse MoE's routed experts are held (#318).
|
||||
@@ -435,6 +489,10 @@ pub struct ModelInfo {
|
||||
/// budget to offer.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub reasoning_budget: Vec<ReasoningBudgetRung>,
|
||||
/// How many independent copies of the model this host runs (#397).
|
||||
/// Absent for an unreplicated model.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub replicas: Option<usize>,
|
||||
}
|
||||
|
||||
/// Why a loaded model can or cannot be served right now (#245).
|
||||
|
||||
@@ -50,6 +50,34 @@ pub struct NodeState {
|
||||
/// neuron reports the same rungs — and duplicating it onto each
|
||||
/// model entry would invite the two to disagree.
|
||||
pub reasoning_budget: Vec<crate::harness::ReasoningBudgetRung>,
|
||||
/// The neuron's last-announced scheduled absence (#397), from
|
||||
/// `/health`. Kept while the neuron is unreachable: that is when it
|
||||
/// says the silence is planned.
|
||||
pub next_dark: Option<crate::discovery::DarkWindow>,
|
||||
/// Whether the neuron is currently away inside its announced dark
|
||||
/// window, so the poller logs the departure and return once each
|
||||
/// rather than every failed poll.
|
||||
pub in_scheduled_absence: bool,
|
||||
}
|
||||
|
||||
impl NodeState {
|
||||
/// Whether new work may be sent here at `now` (unix seconds): the node
|
||||
/// is healthy and not draining ahead of a scheduled absence (#397).
|
||||
pub fn takes_work_at(&self, now: u64) -> bool {
|
||||
self.healthy && self.next_dark.is_none_or(|d| d.takes_work_at(now))
|
||||
}
|
||||
|
||||
/// [`Self::takes_work_at`] the current time.
|
||||
pub fn takes_work(&self) -> bool {
|
||||
self.takes_work_at(unix_now())
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds since the unix epoch.
|
||||
pub fn unix_now() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
/// A model registered on a node, with its runtime status.
|
||||
|
||||
@@ -42,7 +42,7 @@ use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::{RwLock, Semaphore};
|
||||
use tokio::sync::{Notify, RwLock};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
/// Path of the job collection; `{id}` and `{id}/content` hang off it.
|
||||
@@ -82,8 +82,10 @@ pub struct AudioJobs {
|
||||
jobs: RwLock<HashMap<String, JobRecord>>,
|
||||
/// Worker tasks for jobs that are queued or running, for cancellation.
|
||||
workers: Mutex<HashMap<String, JoinHandle<()>>>,
|
||||
/// Bounds concurrent renders across the fleet.
|
||||
slots: Arc<Semaphore>,
|
||||
/// Renders running now, bounded by [`AudioJobs::render_capacity`].
|
||||
running: Mutex<usize>,
|
||||
/// Signalled whenever a render ends.
|
||||
render_ended: Notify,
|
||||
/// Rendered audio, when there is no job directory to write it to.
|
||||
memory_audio: Mutex<HashMap<String, Bytes>>,
|
||||
/// Client for neuron dispatches. A neuron sends nothing until the render
|
||||
@@ -102,7 +104,8 @@ impl AudioJobs {
|
||||
dir: std::sync::OnceLock::new(),
|
||||
jobs: RwLock::new(HashMap::new()),
|
||||
workers: Mutex::new(HashMap::new()),
|
||||
slots: Arc::new(Semaphore::new(config.max_concurrent.max(1))),
|
||||
running: Mutex::new(0),
|
||||
render_ended: Notify::new(),
|
||||
memory_audio: Mutex::new(HashMap::new()),
|
||||
http,
|
||||
}
|
||||
@@ -647,9 +650,7 @@ enum Dispatch {
|
||||
|
||||
async fn run_job(fleet: &Arc<CortexState>, id: &str, guard: ReservationGuard) {
|
||||
let jobs = &fleet.audio_jobs;
|
||||
let Ok(_slot) = Arc::clone(&jobs.slots).acquire_owned().await else {
|
||||
return;
|
||||
};
|
||||
let _slot = render_slot(fleet).await;
|
||||
let Some(record) = jobs
|
||||
.update(id, |r| {
|
||||
if !r.job.status.is_terminal() {
|
||||
@@ -710,6 +711,79 @@ async fn run_job(fleet: &Arc<CortexState>, id: &str, guard: ReservationGuard) {
|
||||
fail(fleet, id, last_error).await;
|
||||
}
|
||||
|
||||
/// A render's place in the fleet-wide bound; dropping it frees the place.
|
||||
struct RenderSlot<'a>(&'a AudioJobs);
|
||||
|
||||
impl Drop for RenderSlot<'_> {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut running) = self.0.running.lock() {
|
||||
*running = running.saturating_sub(1);
|
||||
}
|
||||
self.0.render_ended.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
/// How often a job waiting for a render slot re-reads the fleet's
|
||||
/// capacity, which changes as hosts come and go and models load.
|
||||
const CAPACITY_RECHECK: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Wait for a place among the renders the fleet can run at once.
|
||||
async fn render_slot(fleet: &CortexState) -> RenderSlot<'_> {
|
||||
let jobs = &fleet.audio_jobs;
|
||||
loop {
|
||||
let ended = jobs.render_ended.notified();
|
||||
tokio::pin!(ended);
|
||||
// Registered before the check, so a render ending in between
|
||||
// still wakes this waiter.
|
||||
ended.as_mut().enable();
|
||||
let capacity = match jobs.config.max_concurrent {
|
||||
0 => {
|
||||
let nodes = fleet.nodes.read().await;
|
||||
fleet_render_capacity(nodes.values(), cortex_core::node::unix_now())
|
||||
}
|
||||
n => n,
|
||||
};
|
||||
{
|
||||
let mut running = jobs.running.lock().expect("render count poisoned");
|
||||
if *running < capacity {
|
||||
*running += 1;
|
||||
return RenderSlot(jobs);
|
||||
}
|
||||
}
|
||||
let _ = tokio::time::timeout(CAPACITY_RECHECK, ended).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the fleet can run at once (#397): the in-flight capacity of
|
||||
/// every music model loaded on a host taking work. A host with a copy of a
|
||||
/// model on each of its cards advertises one slot per copy. At least one,
|
||||
/// so a job for a model nobody has loaded can still cold-load it.
|
||||
pub fn fleet_render_capacity<'a>(
|
||||
nodes: impl Iterator<Item = &'a cortex_core::node::NodeState>,
|
||||
now: u64,
|
||||
) -> usize {
|
||||
use cortex_core::node::ModelStatus;
|
||||
nodes
|
||||
.filter(|n| n.takes_work_at(now))
|
||||
.flat_map(|n| {
|
||||
n.models
|
||||
.values()
|
||||
.filter(|m| {
|
||||
matches!(m.status, ModelStatus::Loaded | ModelStatus::Reloading)
|
||||
&& m.capabilities
|
||||
.iter()
|
||||
.any(|c| c == cortex_core::audio::CAPABILITY)
|
||||
})
|
||||
.map(|m| {
|
||||
n.model_load
|
||||
.get(&m.id)
|
||||
.map_or(1, |l| l.max_in_flight.max(1))
|
||||
})
|
||||
})
|
||||
.sum::<usize>()
|
||||
.max(1)
|
||||
}
|
||||
|
||||
async fn dispatch_once(fleet: &Arc<CortexState>, record: &JobRecord) -> Dispatch {
|
||||
let route = match crate::router::resolve(fleet, &record.job.model).await {
|
||||
Ok(r) => r,
|
||||
|
||||
@@ -933,7 +933,9 @@ async fn list_models(State(fleet): State<Arc<CortexState>>) -> Json<Value> {
|
||||
for profile in &catalogue.models {
|
||||
let mut feasible_on = Vec::new();
|
||||
for node in nodes.values() {
|
||||
if !node.healthy {
|
||||
// A host draining ahead of its dark window (#397) offers no
|
||||
// new capacity.
|
||||
if !node.takes_work() {
|
||||
continue;
|
||||
}
|
||||
let Some(disc) = node.discovery.as_ref() else {
|
||||
@@ -1244,6 +1246,9 @@ async fn health(State(fleet): State<Arc<CortexState>>) -> Json<Value> {
|
||||
let nodes = fleet.nodes.read().await;
|
||||
let healthy_count = nodes.values().filter(|n| n.healthy).count();
|
||||
let total_count = nodes.len();
|
||||
// Away inside a dark window they announced (#397): reduced capacity,
|
||||
// not a fault, so monitoring can tell the two apart.
|
||||
let scheduled_dark = nodes.values().filter(|n| n.in_scheduled_absence).count();
|
||||
|
||||
// Models resident on a node that cannot currently serve them. Worth
|
||||
// surfacing even when another node can pick the work up, because it
|
||||
@@ -1277,7 +1282,11 @@ async fn health(State(fleet): State<Arc<CortexState>>) -> Json<Value> {
|
||||
|
||||
let mut body = json!({
|
||||
"status": status,
|
||||
"nodes": { "healthy": healthy_count, "total": total_count },
|
||||
"nodes": {
|
||||
"healthy": healthy_count,
|
||||
"total": total_count,
|
||||
"scheduled_dark": scheduled_dark,
|
||||
},
|
||||
});
|
||||
if !unservable.is_empty() {
|
||||
body["unservable"] = Value::Array(unservable);
|
||||
|
||||
@@ -28,8 +28,31 @@ const CAPABILITY_RETRY: Duration = Duration::from_secs(600);
|
||||
/// reach [`POLL_FAILURE_THRESHOLD`]. Below the threshold the node keeps its
|
||||
/// last-known health, riding over transient misses. A successful poll resets
|
||||
/// the counter (see the success arm in `poll_once`).
|
||||
fn record_poll_failure(node: &mut NodeState) {
|
||||
///
|
||||
/// A node that is away inside the dark window it announced (#397) is a
|
||||
/// planned absence, not a fault: it is marked unhealthy at once, with
|
||||
/// nothing to debounce, and the departure is logged once at `info` instead
|
||||
/// of a warning every poll for the length of the night.
|
||||
fn record_poll_failure(node: &mut NodeState, error: &dyn std::fmt::Display) {
|
||||
node.consecutive_poll_failures = node.consecutive_poll_failures.saturating_add(1);
|
||||
if let Some(dark) = node
|
||||
.next_dark
|
||||
.filter(|d| d.expects_absence_at(cortex_core::node::unix_now()))
|
||||
{
|
||||
node.healthy = false;
|
||||
if !node.in_scheduled_absence {
|
||||
node.in_scheduled_absence = true;
|
||||
tracing::info!(
|
||||
node = %node.name,
|
||||
until = dark.ends_at,
|
||||
"neuron is away for its scheduled dark window"
|
||||
);
|
||||
gauge!("cortex_node_scheduled_dark", "node" => node.name.clone()).set(1.0);
|
||||
}
|
||||
tracing::debug!(node = %node.name, error = %error, "poll failed during scheduled dark window");
|
||||
return;
|
||||
}
|
||||
tracing::warn!(node = %node.name, error = %error, "neuron poll failed");
|
||||
if node.consecutive_poll_failures >= POLL_FAILURE_THRESHOLD {
|
||||
node.healthy = false;
|
||||
}
|
||||
@@ -180,26 +203,27 @@ async fn poll_neuron(fleet: &CortexState, name: &str, endpoint: &str) {
|
||||
|
||||
node.consecutive_poll_failures = 0;
|
||||
node.healthy = true;
|
||||
if node.in_scheduled_absence {
|
||||
node.in_scheduled_absence = false;
|
||||
tracing::info!(
|
||||
node = name,
|
||||
"neuron is back from its scheduled dark window"
|
||||
);
|
||||
gauge!("cortex_node_scheduled_dark", "node" => name.to_string()).set(0.0);
|
||||
}
|
||||
node.last_poll = Some(Utc::now());
|
||||
tracing::debug!(node = name, models = models.len(), "poll ok");
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(node = name, error = %e, "failed to parse /models response");
|
||||
record_poll_failure(node);
|
||||
record_poll_failure(node, &format_args!("unparseable /models response: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(resp) => {
|
||||
tracing::warn!(
|
||||
node = name,
|
||||
status = %resp.status(),
|
||||
"neuron returned non-success status"
|
||||
);
|
||||
record_poll_failure(node);
|
||||
record_poll_failure(node, &format_args!("/models answered {}", resp.status()));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(node = name, error = %e, "failed to reach neuron");
|
||||
record_poll_failure(node);
|
||||
record_poll_failure(node, &format_args!("unreachable: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,6 +370,9 @@ pub async fn poll_health(fleet: &CortexState, name: &str, endpoint: &str) {
|
||||
// Per-device VRAM readings (#203) for free-fit
|
||||
// cold-load placement.
|
||||
node.device_health = h.devices.clone();
|
||||
// The host's power schedule (#397): when to stop sending
|
||||
// it work, and when its silence is planned.
|
||||
node.next_dark = h.next_dark;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -152,12 +152,16 @@ pub async fn resolve(
|
||||
let nodes = fleet.nodes.read().await;
|
||||
// All healthy nodes with the model loaded, each with its current
|
||||
// admission load (#53) so we can pick the least-busy replica (#55).
|
||||
let mut loaded_candidates: Vec<(String, String, usize)> = Vec::new();
|
||||
let mut loaded_candidates: Vec<(String, String, f64)> = Vec::new();
|
||||
let mut unloaded_route = None;
|
||||
let mut recovering_node = None;
|
||||
let mut any_healthy = false;
|
||||
let now = cortex_core::node::unix_now();
|
||||
for node in nodes.values() {
|
||||
if !node.healthy {
|
||||
// A node draining ahead of its scheduled dark window (#397) is
|
||||
// healthy but takes nothing new: what it is running finishes,
|
||||
// and the work it would have got goes elsewhere.
|
||||
if !node.takes_work_at(now) {
|
||||
continue;
|
||||
}
|
||||
any_healthy = true;
|
||||
@@ -186,13 +190,20 @@ pub async fn resolve(
|
||||
continue;
|
||||
}
|
||||
// Least-busy score: in-flight + queued from the
|
||||
// neuron's last /health (#53). Unknown load (no poll
|
||||
// yet) scores 0 so the replica stays eligible.
|
||||
// neuron's last /health (#53), as a share of the
|
||||
// model's in-flight capacity there, so a host with
|
||||
// eight replicas (#397) and two renders running
|
||||
// counts as less busy than a single card with one.
|
||||
// Unknown load (no poll yet) scores 0 so the
|
||||
// replica stays eligible; unknown capacity (0, an
|
||||
// older neuron) counts as one slot.
|
||||
let score = node
|
||||
.model_load
|
||||
.get(model_id)
|
||||
.map(|l| l.in_flight + l.queue_depth)
|
||||
.unwrap_or(0);
|
||||
.map(|l| {
|
||||
(l.in_flight + l.queue_depth) as f64 / l.max_in_flight.max(1) as f64
|
||||
})
|
||||
.unwrap_or(0.0);
|
||||
loaded_candidates.push((node.name.clone(), node.endpoint.clone(), score));
|
||||
}
|
||||
ModelStatus::Unloaded => {
|
||||
@@ -229,7 +240,7 @@ pub async fn resolve(
|
||||
// deterministic routing. `false` = not a cold start.
|
||||
let loaded_route = loaded_candidates
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.2.cmp(&b.2).then_with(|| a.0.cmp(&b.0)))
|
||||
.min_by(|a, b| a.2.total_cmp(&b.2).then_with(|| a.0.cmp(&b.0)))
|
||||
.map(|(name, endpoint, _score)| (name, endpoint, false));
|
||||
(loaded_route, unloaded_route, recovering_node, any_healthy)
|
||||
};
|
||||
@@ -330,7 +341,7 @@ async fn loaded_location(fleet: &Arc<CortexState>, model_id: &str) -> Option<(St
|
||||
let nodes = fleet.nodes.read().await;
|
||||
nodes
|
||||
.values()
|
||||
.filter(|n| n.healthy)
|
||||
.filter(|n| n.takes_work())
|
||||
.find(|n| {
|
||||
n.models.get(model_id).is_some_and(|m| {
|
||||
matches!(m.status, ModelStatus::Loaded | ModelStatus::Reloading) && m.is_servable()
|
||||
@@ -424,7 +435,8 @@ async fn pick_feasible_neuron(
|
||||
let nodes = fleet.nodes.read().await;
|
||||
let mut candidates: Vec<(String, String, bool, bool, bool, u64)> = Vec::new();
|
||||
for node in nodes.values() {
|
||||
if !node.healthy {
|
||||
// Never cold-load onto a host about to go dark (#397).
|
||||
if !node.takes_work() {
|
||||
continue;
|
||||
}
|
||||
let Some(disc) = node.discovery.as_ref() else {
|
||||
@@ -492,7 +504,7 @@ async fn pick_feasible_neuron(
|
||||
// and retries instead of treating a 404 as a hard failure. Only when no
|
||||
// neuron could *ever* satisfy the topology is it a permanent 404.
|
||||
let feasible_but_unhealthy = nodes.values().any(|node| {
|
||||
!node.healthy
|
||||
!node.takes_work()
|
||||
&& node
|
||||
.discovery
|
||||
.as_ref()
|
||||
@@ -660,6 +672,9 @@ async fn profile_to_spec(
|
||||
// decides from its own config.
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
// Like expert residency, how many cards carry a copy is the
|
||||
// host's decision (#397).
|
||||
replicas: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,8 @@ impl CortexState {
|
||||
activation: None,
|
||||
model_load: HashMap::new(),
|
||||
consecutive_poll_failures: 0,
|
||||
next_dark: None,
|
||||
in_scheduled_absence: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ async fn seed_loaded(fleet: &CortexState, node: &str, in_flight: usize, queue_de
|
||||
rejected_anon_yield: 0,
|
||||
tok_s_prefill: 0.0,
|
||||
tok_s_decode: 0.0,
|
||||
replicas: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
//! Hosts that leave the mesh on a schedule (#397).
|
||||
//!
|
||||
//! A solar-powered rig goes dark every evening. It announces the window
|
||||
//! on `/health`, including when it stops taking new work so what it is
|
||||
//! running can finish. cortex must stop routing there at that moment,
|
||||
//! treat the silence that follows as planned, and pick the host up again
|
||||
//! when it returns. Across the whole cycle a client sees only reduced
|
||||
//! capacity, never a failed request.
|
||||
//!
|
||||
//! Also here: a host carrying several replicas of a model (#397) counts as
|
||||
//! that much capacity, both for routing and for the audio job gate.
|
||||
|
||||
mod common;
|
||||
|
||||
use axum::Json;
|
||||
use axum::Router;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use cortex_core::node::unix_now;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
const MODEL: &str = "test-model";
|
||||
|
||||
/// A neuron whose announced schedule, load and presence the test controls.
|
||||
#[derive(Default)]
|
||||
struct Rig {
|
||||
/// Answers 502 to everything, as a host whose power is off would fail
|
||||
/// to answer at all.
|
||||
gone: bool,
|
||||
next_dark: Option<Value>,
|
||||
in_flight: usize,
|
||||
max_in_flight: usize,
|
||||
/// Inference requests that reached this neuron.
|
||||
served: usize,
|
||||
}
|
||||
|
||||
type Shared = Arc<Mutex<Rig>>;
|
||||
|
||||
async fn spawn_rig(rig: Shared) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let endpoint = base.clone();
|
||||
let app = Router::new()
|
||||
.route("/models", get(models))
|
||||
.route("/health", get(health))
|
||||
.route(
|
||||
"/models/{id}/endpoint",
|
||||
get(move |State(rig): State<Shared>, Path(_): Path<String>| {
|
||||
let url = endpoint.clone();
|
||||
async move {
|
||||
if rig.lock().unwrap().gone {
|
||||
return StatusCode::BAD_GATEWAY.into_response();
|
||||
}
|
||||
Json(json!({ "url": url })).into_response()
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route("/v1/chat/completions", post(chat))
|
||||
.with_state(rig);
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
base
|
||||
}
|
||||
|
||||
async fn models(State(rig): State<Shared>) -> Response {
|
||||
if rig.lock().unwrap().gone {
|
||||
return StatusCode::BAD_GATEWAY.into_response();
|
||||
}
|
||||
Json(json!([{
|
||||
"id": MODEL, "harness": "candle", "status": "loaded", "devices": [0],
|
||||
"vram_used_mb": null
|
||||
}]))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn health(State(rig): State<Shared>) -> Response {
|
||||
let r = rig.lock().unwrap();
|
||||
if r.gone {
|
||||
return StatusCode::BAD_GATEWAY.into_response();
|
||||
}
|
||||
let mut body = json!({
|
||||
"uptime_secs": 1,
|
||||
"devices": [],
|
||||
"models": [{
|
||||
"id": MODEL,
|
||||
"in_flight": r.in_flight,
|
||||
"queue_depth": 0,
|
||||
"max_in_flight": r.max_in_flight,
|
||||
}],
|
||||
});
|
||||
if let Some(d) = &r.next_dark {
|
||||
body["next_dark"] = d.clone();
|
||||
}
|
||||
Json(body).into_response()
|
||||
}
|
||||
|
||||
async fn chat(State(rig): State<Shared>) -> Response {
|
||||
let mut r = rig.lock().unwrap();
|
||||
if r.gone {
|
||||
return StatusCode::BAD_GATEWAY.into_response();
|
||||
}
|
||||
r.served += 1;
|
||||
Json(json!({
|
||||
"id": "chatcmpl-rig", "object": "chat.completion", "created": 1, "model": MODEL,
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"},
|
||||
"finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
|
||||
}))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn dark(drain_at: u64, starts_at: u64, ends_at: u64) -> Option<Value> {
|
||||
Some(json!({ "drain_at": drain_at, "starts_at": starts_at, "ends_at": ends_at }))
|
||||
}
|
||||
|
||||
/// Send `n` requests through the gateway; every one must succeed.
|
||||
async fn all_succeed(gateway: &str, n: usize) {
|
||||
let client = reqwest::Client::new();
|
||||
for i in 0..n {
|
||||
let resp = client
|
||||
.post(format!("{gateway}/v1/chat/completions"))
|
||||
.json(&json!({"model": MODEL, "messages": [{"role": "user", "content": "hi"}]}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), 200, "request {i} failed");
|
||||
}
|
||||
}
|
||||
|
||||
fn served(rig: &Shared) -> usize {
|
||||
rig.lock().unwrap().served
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_host_leaving_and_returning_on_schedule_fails_no_request() {
|
||||
let now = unix_now();
|
||||
// The rig: eight replicas, idle, dark from tonight.
|
||||
let rig: Shared = Arc::new(Mutex::new(Rig {
|
||||
max_in_flight: 8,
|
||||
next_dark: dark(now + 3600, now + 4500, now + 40_000),
|
||||
..Default::default()
|
||||
}));
|
||||
// An always-on single card that is already busy.
|
||||
let card: Shared = Arc::new(Mutex::new(Rig {
|
||||
max_in_flight: 1,
|
||||
in_flight: 1,
|
||||
..Default::default()
|
||||
}));
|
||||
let fleet = common::two_neuron_fleet(
|
||||
&spawn_rig(Arc::clone(&rig)).await,
|
||||
&spawn_rig(Arc::clone(&card)).await,
|
||||
)
|
||||
.await;
|
||||
let app = cortex_gateway::build_app(Arc::clone(&fleet));
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let gateway = format!("http://{}", listener.local_addr().unwrap());
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
|
||||
// Daytime: the idle rig takes the work.
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
all_succeed(&gateway, 10).await;
|
||||
assert_eq!(served(&rig), 10, "the idle rig should take the work");
|
||||
|
||||
// Draining: still up and polling fine, but its announced drain time has
|
||||
// passed. Nothing new goes there.
|
||||
rig.lock().unwrap().next_dark = dark(now - 1, now + 60, now + 40_000);
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
all_succeed(&gateway, 10).await;
|
||||
assert_eq!(served(&rig), 10, "a draining host must get no new work");
|
||||
assert_eq!(served(&card), 10);
|
||||
|
||||
// Dark: the rig stops answering. Its absence is planned, so it leaves
|
||||
// routing at once and the gateway reports it as scheduled, not failed.
|
||||
rig.lock().unwrap().gone = true;
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
{
|
||||
let nodes = fleet.nodes.read().await;
|
||||
let a = &nodes["node-a"];
|
||||
assert!(!a.healthy, "a host away on schedule is out of routing");
|
||||
assert!(a.in_scheduled_absence);
|
||||
}
|
||||
all_succeed(&gateway, 10).await;
|
||||
let health: Value = reqwest::get(format!("{gateway}/health"))
|
||||
.await
|
||||
.unwrap()
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(health["nodes"]["scheduled_dark"], 1);
|
||||
|
||||
// Morning: the rig is back with tomorrow's window, and takes work again.
|
||||
{
|
||||
let mut r = rig.lock().unwrap();
|
||||
r.gone = false;
|
||||
r.next_dark = dark(now + 86_400, now + 87_300, now + 126_000);
|
||||
}
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
{
|
||||
let nodes = fleet.nodes.read().await;
|
||||
assert!(nodes["node-a"].healthy);
|
||||
assert!(!nodes["node-a"].in_scheduled_absence);
|
||||
}
|
||||
all_succeed(&gateway, 10).await;
|
||||
assert_eq!(served(&rig), 20, "the returned rig takes work again");
|
||||
assert_eq!(served(&card), 20);
|
||||
}
|
||||
|
||||
/// An unannounced outage is still a fault: debounced, not quietly accepted.
|
||||
#[tokio::test]
|
||||
async fn an_unannounced_absence_is_not_treated_as_scheduled() {
|
||||
let rig: Shared = Arc::new(Mutex::new(Rig {
|
||||
max_in_flight: 1,
|
||||
..Default::default()
|
||||
}));
|
||||
let card: Shared = Arc::new(Mutex::new(Rig {
|
||||
max_in_flight: 1,
|
||||
..Default::default()
|
||||
}));
|
||||
let fleet = common::two_neuron_fleet(
|
||||
&spawn_rig(Arc::clone(&rig)).await,
|
||||
&spawn_rig(Arc::clone(&card)).await,
|
||||
)
|
||||
.await;
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
rig.lock().unwrap().gone = true;
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
let nodes = fleet.nodes.read().await;
|
||||
let a = &nodes["node-a"];
|
||||
assert!(a.healthy, "one missed poll rides the debounce");
|
||||
assert!(!a.in_scheduled_absence);
|
||||
}
|
||||
|
||||
/// Busy-ness is a share of capacity: a rig with eight replicas and two
|
||||
/// renders running is less busy than a single card running one.
|
||||
#[tokio::test]
|
||||
async fn routing_weighs_load_against_replica_capacity() {
|
||||
let rig: Shared = Arc::new(Mutex::new(Rig {
|
||||
max_in_flight: 8,
|
||||
in_flight: 2,
|
||||
..Default::default()
|
||||
}));
|
||||
let card: Shared = Arc::new(Mutex::new(Rig {
|
||||
max_in_flight: 1,
|
||||
in_flight: 1,
|
||||
..Default::default()
|
||||
}));
|
||||
let fleet = common::two_neuron_fleet(
|
||||
&spawn_rig(Arc::clone(&rig)).await,
|
||||
&spawn_rig(Arc::clone(&card)).await,
|
||||
)
|
||||
.await;
|
||||
cortex_gateway::poller::poll_once(&fleet).await;
|
||||
let route = cortex_gateway::router::resolve(&fleet, MODEL)
|
||||
.await
|
||||
.expect("loaded on both");
|
||||
assert_eq!(route.node_name, "node-a");
|
||||
}
|
||||
|
||||
/// The audio job gate follows the fleet: every replica of a loaded music
|
||||
/// model is a render slot, and a draining host's are not.
|
||||
#[tokio::test]
|
||||
async fn render_capacity_counts_replicas_on_hosts_taking_work() {
|
||||
use cortex_core::discovery::{DarkWindow, ModelLoad};
|
||||
use cortex_core::node::{ModelEntry, ModelStatus};
|
||||
use cortex_gateway::audio_jobs::fleet_render_capacity;
|
||||
|
||||
let fleet = common::two_neuron_fleet("http://127.0.0.1:1", "http://127.0.0.1:2").await;
|
||||
let now = unix_now();
|
||||
{
|
||||
let mut nodes = fleet.nodes.write().await;
|
||||
for (name, slots) in [("node-a", 8), ("node-b", 1)] {
|
||||
let n = nodes.get_mut(name).unwrap();
|
||||
n.healthy = true;
|
||||
n.models.insert(
|
||||
"ACE-Step/Ace-Step1.5".into(),
|
||||
ModelEntry {
|
||||
id: "ACE-Step/Ace-Step1.5".into(),
|
||||
status: ModelStatus::Loaded,
|
||||
last_accessed: None,
|
||||
vram_estimate_mb: None,
|
||||
capabilities: vec![cortex_core::audio::CAPABILITY.into()],
|
||||
tool_call: false,
|
||||
reasoning: false,
|
||||
limit: None,
|
||||
servable: None,
|
||||
reasoning_budget: Vec::new(),
|
||||
},
|
||||
);
|
||||
let load: ModelLoad = serde_json::from_value(json!({
|
||||
"id": "ACE-Step/Ace-Step1.5", "in_flight": 0, "queue_depth": 0,
|
||||
"max_in_flight": slots
|
||||
}))
|
||||
.unwrap();
|
||||
n.model_load.insert(load.id.clone(), load);
|
||||
}
|
||||
}
|
||||
let nodes = fleet.nodes.read().await;
|
||||
assert_eq!(fleet_render_capacity(nodes.values(), now), 9);
|
||||
drop(nodes);
|
||||
|
||||
fleet
|
||||
.nodes
|
||||
.write()
|
||||
.await
|
||||
.get_mut("node-a")
|
||||
.unwrap()
|
||||
.next_dark = Some(DarkWindow {
|
||||
drain_at: now - 1,
|
||||
starts_at: now + 60,
|
||||
ends_at: now + 600,
|
||||
});
|
||||
let nodes = fleet.nodes.read().await;
|
||||
assert_eq!(fleet_render_capacity(nodes.values(), now), 1);
|
||||
}
|
||||
@@ -223,6 +223,7 @@ impl TargetClient {
|
||||
// reconstructed spec cannot carry it either.
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -292,6 +293,7 @@ impl TargetClient {
|
||||
// serviceability, and absent means "no opinion".
|
||||
servable: None,
|
||||
reasoning_budget: Vec::new(),
|
||||
replicas: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
//! A host's power schedule (#397).
|
||||
//!
|
||||
//! Solar-powered hosts leave the mesh on a daily schedule. The operator
|
||||
//! lists the windows in which the host is powered; `/health` announces the
|
||||
//! next window in which it is not, so cortex can stop sending new work
|
||||
//! before the host goes and treat its absence as planned.
|
||||
//!
|
||||
//! ```toml
|
||||
//! [availability]
|
||||
//! # UTC. A window may wrap past midnight ("22:00-06:00").
|
||||
//! online = ["06:30-18:45"]
|
||||
//! # Take no new work this long before each dark window, so running work
|
||||
//! # can finish. Longer than this host's longest job.
|
||||
//! drain_secs = 900
|
||||
//! ```
|
||||
//!
|
||||
//! With no `online` windows the host is always on and announces nothing.
|
||||
|
||||
use cortex_core::discovery::DarkWindow;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DAY: u64 = 24 * 60 * 60;
|
||||
|
||||
/// `[availability]` in neuron.toml.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AvailabilityConfig {
|
||||
/// Daily windows, in UTC, in which this host is powered:
|
||||
/// `"HH:MM-HH:MM"`. Empty means always on.
|
||||
#[serde(default)]
|
||||
pub online: Vec<String>,
|
||||
/// How long before each dark window the host stops taking new work,
|
||||
/// in seconds. It should exceed the host's longest job.
|
||||
#[serde(default = "default_drain_secs")]
|
||||
pub drain_secs: u64,
|
||||
}
|
||||
|
||||
impl Default for AvailabilityConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
online: Vec::new(),
|
||||
drain_secs: default_drain_secs(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fifteen minutes: a 600 s song on the slowest card that serves one.
|
||||
fn default_drain_secs() -> u64 {
|
||||
900
|
||||
}
|
||||
|
||||
/// Parsed online windows, as `[start, end)` seconds past UTC midnight.
|
||||
/// A window that wraps past midnight is split in two.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Schedule {
|
||||
online: Vec<(u64, u64)>,
|
||||
drain_secs: u64,
|
||||
}
|
||||
|
||||
impl Schedule {
|
||||
/// `None` when the config lists no windows: an always-on host.
|
||||
pub fn from_config(cfg: &AvailabilityConfig) -> anyhow::Result<Option<Self>> {
|
||||
if cfg.online.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut online = Vec::new();
|
||||
for w in &cfg.online {
|
||||
let (a, b) = w
|
||||
.split_once('-')
|
||||
.ok_or_else(|| anyhow::anyhow!("availability window '{w}' is not HH:MM-HH:MM"))?;
|
||||
let (start, end) = (time_of_day(a.trim(), w)?, time_of_day(b.trim(), w)?);
|
||||
anyhow::ensure!(start != end, "availability window '{w}' is empty");
|
||||
if start < end {
|
||||
online.push((start, end));
|
||||
} else {
|
||||
online.push((start, DAY));
|
||||
online.push((0, end));
|
||||
}
|
||||
}
|
||||
Ok(Some(Self {
|
||||
online,
|
||||
drain_secs: cfg.drain_secs,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The dark window in progress at `now`, or else the next one; `None`
|
||||
/// when the windows cover the whole day.
|
||||
pub fn next_dark(&self, now: u64) -> Option<DarkWindow> {
|
||||
// Lay the online windows out over yesterday, today and the next
|
||||
// two days; the gaps between them are the dark windows. Three days
|
||||
// ahead is enough because a dark window is shorter than a day.
|
||||
let midnight = now - now % DAY;
|
||||
let mut on: Vec<(u64, u64)> = (0..4)
|
||||
.flat_map(|d| {
|
||||
let base = midnight - DAY + d * DAY;
|
||||
self.online.iter().map(move |&(s, e)| (base + s, base + e))
|
||||
})
|
||||
.collect();
|
||||
on.sort_unstable();
|
||||
let mut merged: Vec<(u64, u64)> = Vec::new();
|
||||
for (s, e) in on {
|
||||
match merged.last_mut() {
|
||||
Some(last) if s <= last.1 => last.1 = last.1.max(e),
|
||||
_ => merged.push((s, e)),
|
||||
}
|
||||
}
|
||||
merged
|
||||
.windows(2)
|
||||
.map(|w| DarkWindow {
|
||||
drain_at: w[0].1.saturating_sub(self.drain_secs),
|
||||
starts_at: w[0].1,
|
||||
ends_at: w[1].0,
|
||||
})
|
||||
.find(|d| d.ends_at > now)
|
||||
}
|
||||
}
|
||||
|
||||
fn time_of_day(hhmm: &str, window: &str) -> anyhow::Result<u64> {
|
||||
let bad = || anyhow::anyhow!("availability window '{window}' has a bad time '{hhmm}'");
|
||||
let (h, m) = hhmm.split_once(':').ok_or_else(bad)?;
|
||||
let (h, m): (u64, u64) = (h.parse().map_err(|_| bad())?, m.parse().map_err(|_| bad())?);
|
||||
// 24:00 is the end of the day, so a window can run to midnight.
|
||||
anyhow::ensure!(m < 60 && (h < 24 || (h == 24 && m == 0)), bad());
|
||||
Ok(h * 3600 + m * 60)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn schedule(windows: &[&str]) -> Schedule {
|
||||
Schedule::from_config(&AvailabilityConfig {
|
||||
online: windows.iter().map(|w| w.to_string()).collect(),
|
||||
drain_secs: 600,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// 2026-10-21 00:00 UTC.
|
||||
const MIDNIGHT: u64 = 1_792_540_800;
|
||||
const fn at(h: u64, m: u64) -> u64 {
|
||||
MIDNIGHT + h * 3600 + m * 60
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_day_host_announces_tonight_while_it_is_up() {
|
||||
let s = schedule(&["06:30-18:45"]);
|
||||
let dark = s.next_dark(at(12, 0)).unwrap();
|
||||
assert_eq!(dark.starts_at, at(18, 45));
|
||||
assert_eq!(dark.ends_at, at(24 + 6, 30));
|
||||
assert_eq!(dark.drain_at, at(18, 35));
|
||||
assert!(dark.takes_work_at(at(18, 34)));
|
||||
assert!(!dark.takes_work_at(at(18, 35)));
|
||||
assert!(dark.takes_work_at(at(24 + 6, 30)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_the_dark_window_it_reports_the_one_in_progress() {
|
||||
let s = schedule(&["06:30-18:45"]);
|
||||
// Before dawn: the window that began yesterday evening.
|
||||
let dark = s.next_dark(at(3, 0)).unwrap();
|
||||
assert_eq!(dark.starts_at, at(18, 45) - DAY);
|
||||
assert_eq!(dark.ends_at, at(6, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_may_wrap_past_midnight() {
|
||||
let s = schedule(&["22:00-06:00"]);
|
||||
let dark = s.next_dark(at(23, 0)).unwrap();
|
||||
assert_eq!(
|
||||
(dark.starts_at, dark.ends_at),
|
||||
(at(24 + 6, 0), at(24 + 22, 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_adjacent_windows_merge() {
|
||||
let s = schedule(&["06:00-12:00", "11:00-14:00", "14:00-18:00"]);
|
||||
let dark = s.next_dark(at(9, 0)).unwrap();
|
||||
assert_eq!((dark.starts_at, dark.ends_at), (at(18, 0), at(24 + 6, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_day_is_never_dark() {
|
||||
assert_eq!(schedule(&["00:00-24:00"]).next_dark(at(5, 0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_windows_is_an_always_on_host() {
|
||||
assert_eq!(
|
||||
Schedule::from_config(&AvailabilityConfig::default()).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_windows_are_config_errors() {
|
||||
for w in [
|
||||
"0630-1845",
|
||||
"06:30",
|
||||
"25:00-26:00",
|
||||
"06:60-07:00",
|
||||
"08:00-08:00",
|
||||
] {
|
||||
let cfg = AvailabilityConfig {
|
||||
online: vec![w.into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(Schedule::from_config(&cfg).is_err(), "{w} accepted");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,10 @@ pub struct NeuronConfig {
|
||||
/// don't prevent the rest of the fleet from starting.
|
||||
#[serde(default)]
|
||||
pub default_models: Vec<ModelSpec>,
|
||||
/// When this host is powered (#397), for hosts that leave the mesh
|
||||
/// on a schedule.
|
||||
#[serde(default)]
|
||||
pub availability: crate::availability::AvailabilityConfig,
|
||||
}
|
||||
|
||||
/// Settings for individual harness implementations. Each harness owns
|
||||
@@ -184,6 +188,13 @@ pub struct AudioConfig {
|
||||
/// the model's own limit.
|
||||
#[serde(default)]
|
||||
pub max_duration_secs: Option<f64>,
|
||||
/// Load a copy of each music model on several devices (#397):
|
||||
/// `"per-device"` for every card, or a list of device indices. One
|
||||
/// render runs on each copy at once, so a rig of identical cards
|
||||
/// serves as many songs in parallel as it has cards. A model's own
|
||||
/// `replicas` in its load spec wins.
|
||||
#[serde(default)]
|
||||
pub replicas: Option<cortex_core::harness::Replicas>,
|
||||
}
|
||||
|
||||
/// Per-component placement (#385): `"gpu"` (the model's device, the
|
||||
@@ -594,6 +605,7 @@ impl Default for NeuronConfig {
|
||||
harnesses: vec![],
|
||||
harness: HarnessSettings::default(),
|
||||
default_models: vec![],
|
||||
availability: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -663,27 +663,98 @@ impl LoadedImageModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded ACE-Step music pipeline (#383). Every component lives in the
|
||||
/// device worker's audio slab, addressed via [`Self::handle`]; this
|
||||
/// async-side struct holds admission bookkeeping and the model's limits.
|
||||
/// A render is one `Job::GenerateAudio` round-trip.
|
||||
/// A loaded music pipeline (#383): one copy per replica device (#397).
|
||||
/// Every component of a copy lives in its device worker's audio slab,
|
||||
/// addressed via [`AudioReplica::handle`]; this async-side struct holds
|
||||
/// admission bookkeeping and the model's limits. A render is one
|
||||
/// `Job::GenerateAudio` round-trip on one replica.
|
||||
pub struct LoadedAudioModel {
|
||||
pub model_id: String,
|
||||
pub spec: ModelSpec,
|
||||
/// Every device a copy lives on.
|
||||
pub devices: Vec<u32>,
|
||||
pub worker: Arc<super::device_worker::DeviceWorkerHandle>,
|
||||
pub handle: super::device_worker::AudioHandle,
|
||||
pub replicas: Vec<AudioReplica>,
|
||||
/// Which copies are idle; a render holds one for its whole duration.
|
||||
pub pool: Arc<super::replica::ReplicaPool>,
|
||||
/// Whether the snapshot carried a song planner.
|
||||
pub has_planner: bool,
|
||||
/// What a request may ask of this model; validated before admission.
|
||||
pub limits: cortex_core::audio::AudioLimits,
|
||||
/// Set when a render fails at the driver level: subsequent requests
|
||||
/// fast-reject and `/models` reports `poisoned`.
|
||||
/// Set once every replica's device has failed: requests fast-reject
|
||||
/// and `/models` reports `poisoned`.
|
||||
pub poisoned: Arc<AtomicBool>,
|
||||
/// Admission control (#53) with `max_in_flight` forced to 1 — a render
|
||||
/// saturates the device. The cortex job queue is the real backlog.
|
||||
/// Admission control (#53) with one in-flight slot per replica — a
|
||||
/// render saturates its device. The cortex job queue is the real
|
||||
/// backlog.
|
||||
pub admission: super::admission::AdmissionController,
|
||||
pub inference_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
}
|
||||
|
||||
/// One copy of a music pipeline (#397).
|
||||
pub struct AudioReplica {
|
||||
pub device: u32,
|
||||
pub worker: Arc<super::device_worker::DeviceWorkerHandle>,
|
||||
pub handle: super::device_worker::AudioHandle,
|
||||
}
|
||||
|
||||
impl LoadedAudioModel {
|
||||
/// Per-replica load for `/health`; empty for a single copy, whose
|
||||
/// load the model-level numbers already say.
|
||||
pub fn replica_loads(&self) -> Vec<cortex_core::discovery::ReplicaLoad> {
|
||||
if self.replicas.len() < 2 {
|
||||
return Vec::new();
|
||||
}
|
||||
self.replicas
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, r)| cortex_core::discovery::ReplicaLoad {
|
||||
device: r.device,
|
||||
in_flight: self.pool.in_flight(i),
|
||||
healthy: self.pool.is_healthy(i),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The devices a music model's copies go on (#397): one per entry of
|
||||
/// `replicas`, or the model's single device when it is not replicated.
|
||||
///
|
||||
/// `"per-device"` means every device the model may use: its `devices` when
|
||||
/// the spec names them, else every CUDA device on the host.
|
||||
fn replica_devices(
|
||||
replicas: Option<&cortex_core::harness::Replicas>,
|
||||
devices: Option<&[u32]>,
|
||||
device_count: fn() -> usize,
|
||||
) -> Result<Vec<u32>> {
|
||||
use cortex_core::harness::Replicas;
|
||||
let picked = match replicas {
|
||||
None => vec![devices.and_then(|d| d.first().copied()).unwrap_or(0)],
|
||||
Some(Replicas::Devices(list)) => list.clone(),
|
||||
Some(Replicas::PerDevice) => match devices {
|
||||
Some(d) if !d.is_empty() => d.to_vec(),
|
||||
_ => (0..device_count() as u32).collect(),
|
||||
},
|
||||
};
|
||||
anyhow::ensure!(
|
||||
!picked.is_empty(),
|
||||
"replicas = \"per-device\" found no CUDA devices"
|
||||
);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for d in &picked {
|
||||
anyhow::ensure!(seen.insert(*d), "replicas lists device {d} twice");
|
||||
}
|
||||
Ok(picked)
|
||||
}
|
||||
|
||||
/// CUDA devices on this host; 0 without CUDA.
|
||||
fn cuda_device_count() -> usize {
|
||||
#[cfg(feature = "cuda")]
|
||||
{
|
||||
cudarc::driver::CudaContext::device_count().map_or(0, |n| n.max(0) as usize)
|
||||
}
|
||||
#[cfg(not(feature = "cuda"))]
|
||||
{
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded model with its tokenizer, device placement, and architecture-
|
||||
@@ -3825,6 +3896,10 @@ impl CandleHarness {
|
||||
kv_available_mb,
|
||||
tok_s_prefill,
|
||||
tok_s_decode,
|
||||
replicas: match handle {
|
||||
LoadedHandle::Audio(a) => a.replica_loads(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
@@ -3955,6 +4030,10 @@ impl Harness for CandleHarness {
|
||||
reasoning: h.has_reasoning(),
|
||||
preserve_thinking: h.preserve_thinking(),
|
||||
servable: h.servability(&self.context_limit_cfg),
|
||||
replicas: match h {
|
||||
LoadedHandle::Audio(a) if a.replicas.len() > 1 => Some(a.replicas.len()),
|
||||
_ => None,
|
||||
},
|
||||
// The rungs this model's own template accepts (#290),
|
||||
// discovered at load rather than invented. Advertising a
|
||||
// rung the template rejects hands callers a name that
|
||||
@@ -4015,6 +4094,7 @@ impl Harness for CandleHarness {
|
||||
// A recovering model is a trigger-time snapshot; it
|
||||
// is not serving, so it advertises no controls.
|
||||
reasoning_budget: Vec::new(),
|
||||
replicas: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4476,14 +4556,17 @@ impl Harness for CandleHarness {
|
||||
dm.release().await;
|
||||
}
|
||||
LoadedHandle::Audio(audio) => {
|
||||
// Drop the pipeline on the worker thread so its CUDA
|
||||
// tensors release on the context that allocated them.
|
||||
if let Err(e) = audio.worker.drop_audio(audio.handle).await {
|
||||
tracing::warn!(
|
||||
model = %model_id,
|
||||
error = %e,
|
||||
"audio unload: DropAudio RPC failed (pipeline may leak in worker slab)"
|
||||
);
|
||||
// Drop each copy on its worker thread so its CUDA tensors
|
||||
// release on the context that allocated them.
|
||||
for r in &audio.replicas {
|
||||
if let Err(e) = r.worker.drop_audio(r.handle).await {
|
||||
tracing::warn!(
|
||||
model = %model_id,
|
||||
device = r.device,
|
||||
error = %e,
|
||||
"audio unload: DropAudio RPC failed (pipeline may leak in worker slab)"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "cuda")]
|
||||
@@ -4670,18 +4753,20 @@ impl CandleHarness {
|
||||
files: super::audio::AudioFiles,
|
||||
limits: cortex_core::audio::AudioLimits,
|
||||
) -> Result<()> {
|
||||
let devices = spec.devices.clone().unwrap_or_else(|| vec![0]);
|
||||
let devices = replica_devices(
|
||||
spec.replicas.as_ref().or(self.audio_cfg.replicas.as_ref()),
|
||||
spec.devices.as_deref(),
|
||||
cuda_device_count,
|
||||
)?;
|
||||
let device = Self::pick_device(&devices)?;
|
||||
let worker: Arc<super::device_worker::DeviceWorkerHandle> = match &device {
|
||||
#[cfg(feature = "cuda")]
|
||||
Device::Cuda(_) => self.ensure_device_worker(devices[0]).await?,
|
||||
// On CPU builds this arm is the whole match: a song on the CPU
|
||||
// takes many minutes and is not a serving target.
|
||||
_ => anyhow::bail!(
|
||||
if !matches!(device, Device::Cuda(_)) {
|
||||
// A song on the CPU takes many minutes and is not a serving
|
||||
// target.
|
||||
anyhow::bail!(
|
||||
"music generation requires a CUDA device; '{}' resolved to a CPU device",
|
||||
spec.model_id
|
||||
),
|
||||
};
|
||||
);
|
||||
}
|
||||
|
||||
let has_planner =
|
||||
matches!(&files, super::audio::AudioFiles::AceStep(f) if f.planner.is_some());
|
||||
@@ -4699,32 +4784,62 @@ impl CandleHarness {
|
||||
limits.max_duration = limits.max_duration.min(max);
|
||||
limits.default_duration = limits.default_duration.min(limits.max_duration);
|
||||
}
|
||||
let handle = worker
|
||||
.load_audio(files, spec.model_id.clone())
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("worker load_audio: {e:#}"))?;
|
||||
// Every copy loads at once: each device has its own worker thread,
|
||||
// and on a rig the slow part is each card's own riser.
|
||||
let loads = devices.iter().map(|&d| {
|
||||
let files = files.clone();
|
||||
let model_id = spec.model_id.clone();
|
||||
async move {
|
||||
let worker = self.ensure_device_worker(d).await?;
|
||||
let handle = worker
|
||||
.load_audio(files, model_id)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("worker load_audio on device {d}: {e:#}"))?;
|
||||
anyhow::Ok(AudioReplica {
|
||||
device: d,
|
||||
worker,
|
||||
handle,
|
||||
})
|
||||
}
|
||||
});
|
||||
let mut replicas = Vec::with_capacity(devices.len());
|
||||
let mut first_error = None;
|
||||
for (device, outcome) in devices.iter().zip(futures::future::join_all(loads).await) {
|
||||
match outcome {
|
||||
Ok(r) => replicas.push(r),
|
||||
// One bad card must not take the rig's other copies down
|
||||
// with it. The replica count on `/models` shows the loss.
|
||||
Err(e) => {
|
||||
tracing::warn!(model = %spec.model_id, device, error = %e, "audio replica failed to load");
|
||||
first_error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if replicas.is_empty() {
|
||||
return Err(first_error.unwrap_or_else(|| anyhow::anyhow!("no devices to load on")));
|
||||
}
|
||||
|
||||
// Admission (#53) with the in-flight ceiling forced to 1: a render
|
||||
// saturates the device. cortex queues jobs ahead of this.
|
||||
// Admission (#53) with one in-flight slot per replica: a render
|
||||
// saturates its device. cortex queues jobs ahead of this.
|
||||
let admission_cfg = crate::config::AdmissionConfig {
|
||||
max_in_flight: 1,
|
||||
max_in_flight: replicas.len(),
|
||||
..self.admission_cfg.clone()
|
||||
};
|
||||
let loaded = LoadedAudioModel {
|
||||
model_id: spec.model_id.clone(),
|
||||
spec: spec.clone(),
|
||||
devices,
|
||||
worker,
|
||||
handle,
|
||||
devices: replicas.iter().map(|r| r.device).collect(),
|
||||
pool: super::replica::ReplicaPool::new(replicas.len()),
|
||||
replicas,
|
||||
has_planner,
|
||||
limits,
|
||||
poisoned: Arc::new(AtomicBool::new(false)),
|
||||
admission: crate::harness::admission::AdmissionController::new(&admission_cfg),
|
||||
inference_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
};
|
||||
let copies = loaded.replicas.len();
|
||||
let mut models = self.models.write().await;
|
||||
models.insert(spec.model_id.clone(), LoadedHandle::Audio(Arc::new(loaded)));
|
||||
tracing::info!(model = %spec.model_id, planner = has_planner, "audio pipeline loaded");
|
||||
tracing::info!(model = %spec.model_id, planner = has_planner, replicas = copies, "audio pipeline loaded");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5367,11 +5482,28 @@ impl CandleHarness {
|
||||
};
|
||||
|
||||
let _permit = audio.admission.enter(principal).await?;
|
||||
let _guard = audio.inference_lock.lock().await;
|
||||
let result = audio
|
||||
.worker
|
||||
.generate_audio(audio.handle, params)
|
||||
.await
|
||||
// Admission lets in no more renders than there are copies, so one
|
||||
// is idle here unless a device has failed.
|
||||
let Some(lease) = audio.pool.checkout().await else {
|
||||
audio.poisoned.store(true, Ordering::Release);
|
||||
return Err(InferenceError::Other(anyhow::anyhow!(
|
||||
"every replica of audio model '{}' has failed; unload and reload it",
|
||||
request.model
|
||||
)));
|
||||
};
|
||||
let replica = &audio.replicas[lease.index()];
|
||||
let outcome = replica.worker.generate_audio(replica.handle, params).await;
|
||||
if replica.worker.is_poisoned() {
|
||||
// The device is gone for good: stop handing this copy work,
|
||||
// or it becomes the fastest way to fail a request.
|
||||
tracing::error!(model = %request.model, device = replica.device, "audio replica's device failed; retiring it");
|
||||
lease.mark_failed();
|
||||
if audio.pool.healthy_count() == 0 {
|
||||
audio.poisoned.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
drop(lease);
|
||||
let result = outcome
|
||||
.map_err(|e| InferenceError::Other(anyhow::anyhow!("audio generation: {e:#}")))?;
|
||||
|
||||
let duration = result.duration_secs();
|
||||
@@ -8664,6 +8796,34 @@ mod tests {
|
||||
/// admission controller. Those are separate readers of the same
|
||||
/// number, and a model bounded at 1 while an engine starts with 8
|
||||
/// slots is the failure this function exists to prevent.
|
||||
#[test]
|
||||
fn replica_devices_follow_the_spec_then_the_host() {
|
||||
use cortex_core::harness::Replicas;
|
||||
fn four() -> usize {
|
||||
4
|
||||
}
|
||||
// Unreplicated: the model's first device, as before #397.
|
||||
assert_eq!(replica_devices(None, None, four).unwrap(), [0]);
|
||||
assert_eq!(replica_devices(None, Some(&[2, 3]), four).unwrap(), [2]);
|
||||
// Per-device: the spec's devices when it names them, else every card.
|
||||
let per = Some(&Replicas::PerDevice);
|
||||
assert_eq!(replica_devices(per, None, four).unwrap(), [0, 1, 2, 3]);
|
||||
assert_eq!(replica_devices(per, Some(&[1, 3]), four).unwrap(), [1, 3]);
|
||||
// An explicit list wins over the spec's devices.
|
||||
let list = Replicas::Devices(vec![5, 6]);
|
||||
assert_eq!(
|
||||
replica_devices(Some(&list), Some(&[0]), four).unwrap(),
|
||||
[5, 6]
|
||||
);
|
||||
// Nothing to load on, or a card named twice, is a config error.
|
||||
fn none() -> usize {
|
||||
0
|
||||
}
|
||||
assert!(replica_devices(per, None, none).is_err());
|
||||
let twice = Replicas::Devices(vec![1, 1]);
|
||||
assert!(replica_devices(Some(&twice), None, four).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_may_lower_max_in_flight_below_the_host() {
|
||||
let host = crate::config::AdmissionConfig {
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod preprocess;
|
||||
pub(crate) mod quant;
|
||||
pub mod reasoning_budget;
|
||||
pub mod reasoning_effort;
|
||||
pub mod replica;
|
||||
pub mod sampling;
|
||||
pub mod speculative;
|
||||
pub mod tp;
|
||||
|
||||
@@ -490,6 +490,7 @@ mod tests {
|
||||
preserve_thinking: None,
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//! Copies of one model on several devices (#397).
|
||||
//!
|
||||
//! A mining rig carries many identical small cards on PCIe x1 risers,
|
||||
//! where tensor parallelism is not viable: the throughput shape is one
|
||||
//! independent copy of the model per card. The neuron keeps those copies
|
||||
//! behind one model id, so cortex sees a single model whose capacity is
|
||||
//! their sum.
|
||||
//!
|
||||
//! Admission stays per *model*: one [`AdmissionController`] with an
|
||||
//! in-flight slot per replica, so the queue, the per-principal fair share
|
||||
//! and the anonymous ceiling all see the model's whole capacity. An
|
||||
//! admitted request then takes an idle replica from a [`ReplicaPool`].
|
||||
//! Admission never lets in more requests than there are replicas, so a
|
||||
//! replica is free whenever a request reaches the pool, unless one has
|
||||
//! failed.
|
||||
//!
|
||||
//! Idle replicas are handed out round-robin (a returned replica goes to
|
||||
//! the back of the line), which spreads heat and wear across the cards
|
||||
//! instead of working the first one hardest.
|
||||
//!
|
||||
//! [`AdmissionController`]: super::admission::AdmissionController
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
/// The idle set of a replicated model's copies.
|
||||
pub struct ReplicaPool {
|
||||
idle: Mutex<VecDeque<usize>>,
|
||||
/// One permit per idle, healthy replica.
|
||||
available: Semaphore,
|
||||
healthy: Vec<AtomicBool>,
|
||||
busy: Vec<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl ReplicaPool {
|
||||
pub fn new(replicas: usize) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
idle: Mutex::new((0..replicas).collect()),
|
||||
available: Semaphore::new(replicas),
|
||||
healthy: (0..replicas).map(|_| AtomicBool::new(true)).collect(),
|
||||
busy: (0..replicas).map(|_| AtomicUsize::new(0)).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.healthy.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.healthy.is_empty()
|
||||
}
|
||||
|
||||
/// Wait for an idle replica. `None` once every replica has failed.
|
||||
pub async fn checkout(self: &Arc<Self>) -> Option<ReplicaLease> {
|
||||
let permit = self.available.acquire().await.ok()?;
|
||||
permit.forget();
|
||||
let index = self
|
||||
.idle
|
||||
.lock()
|
||||
.expect("replica pool poisoned")
|
||||
.pop_front()?;
|
||||
self.busy[index].fetch_add(1, Ordering::AcqRel);
|
||||
Some(ReplicaLease {
|
||||
pool: Arc::clone(self),
|
||||
index,
|
||||
})
|
||||
}
|
||||
|
||||
/// Requests replica `index` is running.
|
||||
pub fn in_flight(&self, index: usize) -> usize {
|
||||
self.busy[index].load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn is_healthy(&self, index: usize) -> bool {
|
||||
self.healthy[index].load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn healthy_count(&self) -> usize {
|
||||
self.healthy
|
||||
.iter()
|
||||
.filter(|h| h.load(Ordering::Acquire))
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Take a replica out of service for good. It is not handed out again;
|
||||
/// when it was the last one, waiters are woken with `None`.
|
||||
fn retire(&self, index: usize) {
|
||||
self.healthy[index].store(false, Ordering::Release);
|
||||
if self.healthy_count() == 0 {
|
||||
self.available.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A replica held for one request. Dropping it returns the replica to the
|
||||
/// pool, unless it was marked failed.
|
||||
pub struct ReplicaLease {
|
||||
pool: Arc<ReplicaPool>,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl ReplicaLease {
|
||||
pub fn index(&self) -> usize {
|
||||
self.index
|
||||
}
|
||||
|
||||
/// The replica's device failed: never hand it out again.
|
||||
pub fn mark_failed(&self) {
|
||||
self.pool.retire(self.index);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReplicaLease {
|
||||
fn drop(&mut self) {
|
||||
self.pool.busy[self.index].fetch_sub(1, Ordering::AcqRel);
|
||||
if self.pool.is_healthy(self.index) {
|
||||
self.pool
|
||||
.idle
|
||||
.lock()
|
||||
.expect("replica pool poisoned")
|
||||
.push_back(self.index);
|
||||
self.pool.available.add_permits(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::AdmissionConfig;
|
||||
use crate::harness::admission::AdmissionController;
|
||||
use std::time::Duration;
|
||||
|
||||
/// #397's acceptance: eight replicas, sixteen concurrent requests. Every
|
||||
/// replica works, none ever runs two at once, and nothing is refused.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn sixteen_requests_spread_over_eight_replicas_one_at_a_time() {
|
||||
const REPLICAS: usize = 8;
|
||||
let pool = ReplicaPool::new(REPLICAS);
|
||||
let admission = Arc::new(AdmissionController::new(&AdmissionConfig {
|
||||
max_in_flight: REPLICAS,
|
||||
max_queue_depth: 16,
|
||||
max_per_principal: 0,
|
||||
..AdmissionConfig::default()
|
||||
}));
|
||||
let peak: Arc<Vec<AtomicUsize>> =
|
||||
Arc::new((0..REPLICAS).map(|_| AtomicUsize::new(0)).collect());
|
||||
let served: Arc<Vec<AtomicUsize>> =
|
||||
Arc::new((0..REPLICAS).map(|_| AtomicUsize::new(0)).collect());
|
||||
|
||||
let tasks: Vec<_> = (0..16)
|
||||
.map(|i| {
|
||||
let (pool, admission) = (Arc::clone(&pool), Arc::clone(&admission));
|
||||
let (peak, served) = (Arc::clone(&peak), Arc::clone(&served));
|
||||
tokio::spawn(async move {
|
||||
let principal = format!("caller-{i}");
|
||||
let _permit = admission.enter(Some(&principal)).await.expect("admitted");
|
||||
let lease = pool.checkout().await.expect("a replica");
|
||||
let running = pool.in_flight(lease.index());
|
||||
peak[lease.index()].fetch_max(running, Ordering::AcqRel);
|
||||
served[lease.index()].fetch_add(1, Ordering::AcqRel);
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for t in tasks {
|
||||
t.await.expect("request task");
|
||||
}
|
||||
|
||||
for r in 0..REPLICAS {
|
||||
assert_eq!(peak[r].load(Ordering::Acquire), 1, "replica {r} peak");
|
||||
assert!(
|
||||
served[r].load(Ordering::Acquire) >= 1,
|
||||
"replica {r} never served"
|
||||
);
|
||||
}
|
||||
let total: usize = served.iter().map(|s| s.load(Ordering::Acquire)).sum();
|
||||
assert_eq!(total, 16);
|
||||
assert_eq!(admission.in_flight(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn idle_replicas_are_handed_out_round_robin() {
|
||||
let pool = ReplicaPool::new(3);
|
||||
let mut order = Vec::new();
|
||||
for _ in 0..6 {
|
||||
let lease = pool.checkout().await.expect("a replica");
|
||||
order.push(lease.index());
|
||||
}
|
||||
assert_eq!(order, [0, 1, 2, 0, 1, 2]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_replica_is_never_handed_out_again() {
|
||||
let pool = ReplicaPool::new(2);
|
||||
let lease = pool.checkout().await.expect("a replica");
|
||||
assert_eq!(lease.index(), 0);
|
||||
lease.mark_failed();
|
||||
drop(lease);
|
||||
for _ in 0..4 {
|
||||
assert_eq!(pool.checkout().await.expect("a replica").index(), 1);
|
||||
}
|
||||
assert_eq!(pool.healthy_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waiters_wake_when_the_last_replica_fails() {
|
||||
let pool = ReplicaPool::new(1);
|
||||
let lease = pool.checkout().await.expect("a replica");
|
||||
let waiter = {
|
||||
let pool = Arc::clone(&pool);
|
||||
tokio::spawn(async move { pool.checkout().await.is_none() })
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
lease.mark_failed();
|
||||
drop(lease);
|
||||
let woke_empty = tokio::time::timeout(Duration::from_secs(2), waiter)
|
||||
.await
|
||||
.expect("waiter woke")
|
||||
.expect("waiter task");
|
||||
assert!(woke_empty);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ const POLL_INTERVAL: Duration = Duration::from_secs(5);
|
||||
pub struct HealthCache {
|
||||
inner: RwLock<HealthResponse>,
|
||||
has_gpus: RwLock<bool>,
|
||||
/// This host's power schedule (#397); unset for an always-on host.
|
||||
schedule: std::sync::OnceLock<crate::availability::Schedule>,
|
||||
}
|
||||
|
||||
impl Default for HealthCache {
|
||||
@@ -33,8 +35,11 @@ impl HealthCache {
|
||||
// Per-model admission load is overlaid by the api handler
|
||||
// from the candle harness (#53); the cache doesn't own it.
|
||||
models: Vec::new(),
|
||||
// Overlaid by the api handler from `[availability]`.
|
||||
next_dark: None,
|
||||
}),
|
||||
has_gpus: RwLock::new(false),
|
||||
schedule: std::sync::OnceLock::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +50,20 @@ impl HealthCache {
|
||||
|
||||
/// Get a snapshot of the current health state.
|
||||
pub async fn snapshot(&self) -> HealthResponse {
|
||||
self.inner.read().await.clone()
|
||||
let mut snapshot = self.inner.read().await.clone();
|
||||
if let Some(schedule) = self.schedule.get() {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
snapshot.next_dark = schedule.next_dark(now);
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// Announce this host's power schedule on `/health` (#397). Set once,
|
||||
/// at startup.
|
||||
pub fn set_schedule(&self, schedule: crate::availability::Schedule) {
|
||||
let _ = self.schedule.set(schedule);
|
||||
}
|
||||
|
||||
/// Run forever, polling nvidia-smi every 5 seconds and updating the cache.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod activation;
|
||||
pub mod api;
|
||||
pub mod availability;
|
||||
pub mod config;
|
||||
pub mod cuda;
|
||||
pub mod discovery;
|
||||
|
||||
@@ -191,6 +191,10 @@ async fn daemon(args: Args) -> Result<()> {
|
||||
let shutdown_candle = candle.clone();
|
||||
|
||||
let health_cache = Arc::new(health::HealthCache::new());
|
||||
if let Some(schedule) = neuron::availability::Schedule::from_config(&cfg.availability)? {
|
||||
tracing::info!(online = ?cfg.availability.online, "power schedule (UTC)");
|
||||
health_cache.set_schedule(schedule);
|
||||
}
|
||||
health_cache
|
||||
.set_has_gpus(!discovery_result.devices.is_empty())
|
||||
.await;
|
||||
|
||||
@@ -33,6 +33,7 @@ async fn test_load_default_models_skips_unknown_harness() {
|
||||
preserve_thinking: None,
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
},
|
||||
ModelSpec {
|
||||
model_id: "model-b".into(),
|
||||
@@ -44,6 +45,7 @@ async fn test_load_default_models_skips_unknown_harness() {
|
||||
preserve_thinking: None,
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -107,6 +109,7 @@ async fn test_load_default_models_skipped_on_driver_mismatch() {
|
||||
preserve_thinking: None,
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
}];
|
||||
let activation = ActivationTracker::new(&specs);
|
||||
let reason = "host NVIDIA driver/library mismatch (userspace NVML 580.159 vs loaded \
|
||||
@@ -212,6 +215,7 @@ fn qwen_spec() -> ModelSpec {
|
||||
preserve_thinking: None,
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ fn spec(model_id: &str, tp: Option<u32>, quant: Option<&str>) -> ModelSpec {
|
||||
preserve_thinking: None,
|
||||
expert_residency: None,
|
||||
max_in_flight: None,
|
||||
replicas: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -190,9 +190,24 @@ name = "candle"
|
||||
# Hold the rest of the card's free memory so a large card behaves like
|
||||
# one of the budget's size. For rehearsing a small card; never in serving.
|
||||
#enforce_vram_budget = false
|
||||
# A copy of each music model on several cards, for a rig of identical
|
||||
# cards: "per-device" (every card) or a list of device indices. Each copy
|
||||
# renders one song at a time; cortex sees one model whose capacity is the
|
||||
# number of copies. A model's own `replicas` in [[default_models]] wins.
|
||||
#replicas = "per-device"
|
||||
# Where each component runs: "gpu" (default) or "cpu".
|
||||
#[harness.candle.audio.placement]
|
||||
#text_encoder = "gpu"
|
||||
#planner = "gpu"
|
||||
#dit = "gpu"
|
||||
#vae = "gpu"
|
||||
|
||||
# When this host is powered, for hosts that leave the mesh on a schedule
|
||||
# (solar). /health announces the next dark window; cortex stops sending
|
||||
# new work at its drain time and treats the absence as planned.
|
||||
#[availability]
|
||||
# UTC windows; one may wrap past midnight ("22:00-06:00").
|
||||
#online = ["06:30-18:45"]
|
||||
# Stop taking new work this long before each dark window (seconds). Make
|
||||
# it longer than this host's longest job.
|
||||
#drain_secs = 900
|
||||
|
||||
Reference in New Issue
Block a user