Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/scheduling-runtime-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,30 @@ Stale physical dispatches also require an empty queue and completion feedback,
while retaining their measured costs for ranking. Commit rechecks freshness
because a saved plan can outlive the estimate's freshness interval.

## Retained graph durations across serving sessions

The Flare application supplies a local scheduler-cost directory under
`~/.cache/flare/scheduler-costs/` when starting an authenticated Linux
single-device core. The file is scoped by the signed core envelope, GPU UUID,
runtime executable digest, driver versions, selected sequence limits and
physical graph catalog. Missing or incompatible files leave the catalog
unmeasured. The store contains only physical graph duration estimates, not
request state or token histories.

A restored nonzero duration is known but stale: it participates in ordinary
ranking and receives live feedback under the same stale-estimate rules as
an expired observation. Zero still denotes an unmeasured shape. The first
valid live timing replaces the retained prior; monotonic timestamps, replay
windows, learning credits and request-local acceptance estimates are not
carried across sessions.

The worker reads before readiness and writes a bounded snapshot on clean
drained shutdown. Atomic replacement prevents readers from observing a
partially written file. Cache errors do not prevent serving. There is no file
I/O in the scheduling loop. Multi-device and remote-rank timings are not
restored by the single-device cache because they depend on the participating
devices and communication topology.

## Funded timing refresh

Ordinary valid completions earn `0.002 / 0.998` times their measured execution
Expand Down
4 changes: 4 additions & 0 deletions flare-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,10 @@ fn serve_local(
) -> Result<(), Box<dyn std::error::Error>> {
let phase = progress.phase("Load tokenizer", None);
let mut loaded = flare_helios::server::LoadedSession::new(owner, config)?;
#[cfg(target_os = "linux")]
if let Ok(home) = environment::home_directory() {
loaded.set_graph_cost_cache_root(home.join(".cache/flare/scheduler-costs"));
}
loaded.server_config_mut().log_to_stderr = true;
phase.finish("tokenizer ready");
let phase = progress.phase("Start server", None);
Expand Down
4 changes: 4 additions & 0 deletions flare/src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2206,6 +2206,10 @@ impl Worker {
return Err(error.to_string());
}
};
#[cfg(target_os = "linux")]
if let Ok(home) = crate::environment::home_directory() {
loaded.set_graph_cost_cache_root(home.join(".cache/flare/scheduler-costs"));
}
loaded.server_config_mut().bind = self.settings.runtime.bind()?;
loaded.server_config_mut().api_key = self.settings.api_key.clone();
phase.finish("Tokenizer loaded");
Expand Down
14 changes: 14 additions & 0 deletions helios/src/cuda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,20 @@ pub(crate) fn device_uuid(device: i32) -> Result<[u8; 16]> {
Ok(uuid)
}

/// CUDA driver API version used for graph timing cache compatibility.
#[cfg(all(feature = "server", feature = "runtime-core", target_os = "linux"))]
pub(crate) fn driver_version() -> Result<i32> {
let driver = Driver::load()?;
// SAFETY: CUDA exports this signature and Driver retains the library.
let version: libloading::Symbol<'_, unsafe extern "C" fn(*mut c_int) -> c_int> = unsafe {
driver._library.get(b"cuDriverGetVersion\0")
}.map_err(|_| Error::from("cannot resolve cuDriverGetVersion"))?;
let mut value = 0;
// SAFETY: value is a valid writable int.
driver.check("cuDriverGetVersion", unsafe { version(&mut value) })?;
Ok(value)
}

/// Page-locked registration of process memory, released on drop.
pub(crate) struct HostRegistration {
driver: Arc<Driver>,
Expand Down
9 changes: 9 additions & 0 deletions helios/src/runtime_core/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use blake2::{Blake2b, Digest, digest::consts::U32};
use std::{collections::HashSet, path::Path, thread};

pub struct NativeModel {
core_envelope_digest: [u8; 32],
pub(super) ranks: Vec<NativeResources>,
_core_files: Vec<std::sync::Arc<std::fs::File>>,
pub(super) server_config: serde_json::Value,
Expand Down Expand Up @@ -271,6 +272,7 @@ impl NativeModel {
progress: &StartupProgress,
agree: &mut dyn CacheAgreement,
) -> Result<Self> {
let core_envelope_digest = authorized.envelope_digest();
let device_labels = options.device_labels.as_deref().unwrap_or(devices);
if device_labels.len() != devices.len() {
return Err(invalid("GPU label count must match selected devices"));
Expand Down Expand Up @@ -593,6 +595,7 @@ impl NativeModel {
// the buffered startup readers close when loading returns.
let core_files = files.retained_files()?;
let mut model = Self {
core_envelope_digest,
_core_files: core_files,
ranks: Vec::new(),
server_config,
Expand Down Expand Up @@ -925,6 +928,11 @@ impl NativeModel {
.collect()
}

/// Digest of the authenticated core envelope used to load this model.
pub fn core_envelope_digest(&self) -> [u8; 32] {
self.core_envelope_digest
}

pub fn server_config(&self) -> &serde_json::Value {
&self.server_config
}
Expand Down Expand Up @@ -1148,6 +1156,7 @@ mod tests {
fn disabled_offload_needs_no_model_metadata_or_cuda_resources() {
let progress = StartupProgress::silent();
let mut model = NativeModel {
core_envelope_digest: [0; 32],
_core_files: Vec::new(),
ranks: Vec::new(),
server_config: serde_json::Value::Null,
Expand Down
18 changes: 15 additions & 3 deletions helios/src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,19 @@ impl RequestScheduler {
Ok(())
}

#[cfg(all(feature = "server", feature = "runtime-core", target_os = "linux"))]
pub(crate) fn retained_graph_costs(&self) -> Vec<(String, u64)> {
self.costs.retained_durations()
}

#[cfg(all(feature = "server", feature = "runtime-core", target_os = "linux"))]
pub(crate) fn restore_graph_costs(&mut self, records: &[(String, u64)]) -> Result<usize> {
if self.submitted != Fence(0) || self.slots.iter().any(|s| s.request.is_some()) {
return Err("scheduler costs must be restored before admission".into());
}
self.costs.restore_durations(records)
}

pub fn estimated_duration_ns(&self, step: &ScheduledStep) -> Option<u64> {
self.costs.get(step)
}
Expand Down Expand Up @@ -1073,7 +1086,7 @@ impl RequestScheduler {
fn selected_cost(&self, key: cost::Key) -> SelectedCost {
let (retained_ns, observed_at_ns, fresh) = self.costs.observation(key).unwrap_or((0, None, false));
SelectedCost { retained_ns, observed_at_ns, selected_at_ns: self.now_ns,
freshness: if observed_at_ns.is_none() { CostFreshness::Unknown }
freshness: if retained_ns == 0 { CostFreshness::Unknown }
else if fresh { CostFreshness::Fresh } else { CostFreshness::Stale } }
}

Expand Down Expand Up @@ -2142,9 +2155,8 @@ impl RequestScheduler {
return Err("submission fences must increase within int64 range".into());
}
let key = cost::Key::from_step(step);
let observed_at_ns = self.costs.observation(key).and_then(|(_, observed, _)| observed);
let origin = match plan.origin {
PlanOrigin::Ordinary if observed_at_ns.is_none() => PlanOrigin::Discovery,
PlanOrigin::Ordinary if self.costs.duration_key(key).unwrap_or(0) == 0 => PlanOrigin::Discovery,
origin => origin,
};
self.refresh.validate(origin)?;
Expand Down
84 changes: 81 additions & 3 deletions helios/src/scheduler/cost.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ struct Estimate {
replays: ReplayTimes,
observed_at_ns: u64,
last_attempt_ns: u64,
// A restored timing is a prior, not a live observation.
seeded: bool,
}

#[derive(Default)]
Expand Down Expand Up @@ -82,7 +84,7 @@ impl ReplayTimes {

impl Estimate {
fn fresh(&self, now_ns: u64, ttl_ns: u64) -> bool {
self.nanos != 0 && now_ns.saturating_sub(self.observed_at_ns) < ttl_ns
self.nanos != 0 && !self.seeded && now_ns.saturating_sub(self.observed_at_ns) < ttl_ns
}
}

Expand Down Expand Up @@ -114,6 +116,7 @@ impl ActionCosts {
estimate.nanos = nanos;
estimate.replays.observe(nanos, false);
estimate.observed_at_ns = self.now_ns;
estimate.seeded = false;
self.refresh_packed_durations();
}

Expand All @@ -139,6 +142,7 @@ impl ActionCosts {
replays: ReplayTimes::default(),
observed_at_ns: 0,
last_attempt_ns: 0,
seeded: false,
},
));
}
Expand All @@ -150,6 +154,46 @@ impl ActionCosts {
Ok(costs)
}

#[cfg(any(test, all(feature = "server", feature = "runtime-core", target_os = "linux")))]
fn persistent_key(key: Key) -> String {
format!("{:?}:{}:{}:{}:{}:{}", key.kind, key.batch, key.drafts,
key.tokens, key.prefill, key.packed)
}

#[cfg(any(test, all(feature = "server", feature = "runtime-core", target_os = "linux")))]
pub(super) fn retained_durations(&self) -> Vec<(String, u64)> {
let mut records: Vec<_> = self.entries.iter()
.map(|(key, estimate)| (Self::persistent_key(*key), estimate.nanos))
.collect();
records.sort_unstable_by(|a, b| a.0.cmp(&b.0));
records
}

/// Load only a complete, matching physical catalog. Zero remains unknown;
/// nonzero priors rank normally but require fresh live execution feedback.
#[cfg(any(test, all(feature = "server", feature = "runtime-core", target_os = "linux")))]
pub(super) fn restore_durations(&mut self, records: &[(String, u64)]) -> Result<usize> {
let expected = self.retained_durations();
if records.len() != expected.len() || records.iter().zip(&expected).any(|(a, b)|
a.0 != b.0 || a.1 > 600_000_000_000 || b.1 != 0)
{
return Err("scheduler cost cache does not match the unmeasured graph catalog".into());
}
let by_key: std::collections::HashMap<_, _> = records.iter()
.map(|(key, nanos)| (key.as_str(), *nanos)).collect();
let mut restored = 0;
for (key, estimate) in &mut self.entries {
let nanos = by_key[Self::persistent_key(*key).as_str()];
if nanos != 0 {
estimate.nanos = nanos;
estimate.seeded = true;
restored += 1;
}
}
self.refresh_packed_durations();
Ok(restored)
}

pub fn advance_to(&mut self, now_ns: u64, ttl_ns: u64) {
self.now_ns = now_ns;
self.ttl_ns = ttl_ns;
Expand Down Expand Up @@ -238,7 +282,7 @@ impl ActionCosts {

pub fn observation(&self, key: Key) -> Option<(u64, Option<u64>, bool)> {
self.entry(key).map(|estimate| (estimate.nanos,
(estimate.nanos != 0).then_some(estimate.observed_at_ns),
(estimate.nanos != 0 && !estimate.seeded).then_some(estimate.observed_at_ns),
estimate.fresh(self.now_ns, self.ttl_ns)))
}

Expand Down Expand Up @@ -271,14 +315,48 @@ impl ActionCosts {
let fresh = estimate.fresh(self.now_ns, self.ttl_ns);
estimate.nanos = estimate.replays.observe(sample, fresh);
estimate.observed_at_ns = self.now_ns;
estimate.seeded = false;
self.refresh_packed_durations();
}
}
}

#[cfg(test)]
mod tests {
use super::ReplayTimes;
use super::{ActionCosts, ReplayTimes};

#[test]
fn restored_costs_are_known_but_not_fresh() {
let graphs = super::super::tests::duration_graphs(1);
let mut source = ActionCosts::prepared(&graphs, 8).unwrap();
let key = source.entries[0].0;
source.entries[0].1.nanos = 12_000_000;
let records = source.retained_durations();
let mut destination = ActionCosts::prepared(&graphs, 8).unwrap();
assert_eq!(destination.restore_durations(&records).unwrap(), 1);
assert_eq!(destination.duration_key(key), Some(12_000_000));
assert_eq!(destination.observation(key), Some((12_000_000, None, false)));
assert!(!destination.is_fresh(key));
assert!(destination.stale_keys().any(|candidate| candidate == key));
assert_eq!(destination.retained_durations(), records);
assert!(destination.restore_durations(&records).is_err());
}

#[test]
fn mismatched_or_invalid_records_do_not_modify_costs() {
let graphs = super::super::tests::duration_graphs(1);
let mut destination = ActionCosts::prepared(&graphs, 8).unwrap();
let original = destination.retained_durations();
let mut records = original.clone();
records[0].1 = 123;
records[1].0.push_str("-wrong");
assert!(destination.restore_durations(&records).is_err());
assert_eq!(destination.retained_durations(), original);
let mut records = original.clone();
records[0].1 = u64::MAX;
assert!(destination.restore_durations(&records).is_err());
assert_eq!(destination.retained_durations(), original);
}

#[test]
fn isolated_slow_replay_does_not_displace_the_steady_cost() {
Expand Down
28 changes: 28 additions & 0 deletions helios/src/scheduler/policy_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,34 @@ fn padding_pruning_keeps_three_requests_on_batch_four_and_two_requests_on_batch_
assert!(!candidates.iter().any(|c| c.kind == GraphKind::Decode && c.batch == 8));
}

#[test]
fn restored_decode_cost_is_stale_ordinary_work_and_live_feedback_replaces_it() {
let mut source = engine(1, false);
set_cost(&mut source, GraphKind::Decode, 1, 1, 12 * MS);
let records = source.costs.retained_durations();
let mut s = engine(1, false);
s.graph_durations(&super::tests::duration_graphs(1)).unwrap();
assert!(s.costs.restore_durations(&records).unwrap() > 0);
let h = add(&mut s, 1, 64, 128);
ready(&mut s, &[h]);

let plan = s.phase_plan(GraphKind::Decode, Some(h));
let key = cost::Key::from_step(&plan);
assert_eq!(plan.selected_cost.freshness, CostFreshness::Stale);
assert_eq!(plan.selected_cost.observed_at_ns, None);
assert_eq!(plan.origin, PlanOrigin::Ordinary);
assert!(s.plan_requires_feedback(&plan));
let fence = Fence(s.submitted.0 + 1);
s.commit(&plan, fence).unwrap();
assert_eq!(s.submitted_timing(fence).unwrap().origin, TimingOrigin::Ordinary);

let mut timing = ExecutionTiming { wall_ns: 2 * MS, ..Default::default() };
timing.gpu_ns[0] = Some(2 * MS);
s.advance_to(s.now_ns + timing.wall_ns).unwrap();
complete_timed(&mut s, &plan, fence, 0, true, timing);
assert_eq!(s.costs.observation(key), Some((2 * MS, Some(s.now_ns), true)));
}

#[test]
fn faster_padded_estimates_do_not_displace_equivalent_unpadded_work() {
let mut s = engine(8, false);
Expand Down
18 changes: 17 additions & 1 deletion helios/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ use std::{
};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, oneshot};

type GraphCostCacheLocation = (std::path::PathBuf, [u8; 32]);

pub struct ServerConfig {
/// Write operational diagnostics to stderr for command-line callers.
pub log_to_stderr: bool,
Expand Down Expand Up @@ -223,6 +225,19 @@ impl Server {
images: Option<ImageProcessor>,
config: ServerConfig,
peers: Option<crate::execution::RankPeers>,
) -> std::result::Result<Self, StartFailure> {
unsafe { Self::start_with_graph_cost_cache(manifest, model, frontend, images, config, peers, None) }
}

/// The same exclusive resource and drain contract as `start` applies.
unsafe fn start_with_graph_cost_cache(
manifest: ExecutionManifest,
model: ModelConfig,
frontend: Frontend,
images: Option<ImageProcessor>,
config: ServerConfig,
peers: Option<crate::execution::RankPeers>,
graph_cost_cache: Option<GraphCostCacheLocation>,
) -> std::result::Result<Self, StartFailure> {
if model.contract.vision.enabled() != images.is_some() {
return Err("image processor must match prepared vision capabilities".into());
Expand Down Expand Up @@ -251,7 +266,7 @@ impl Server {
// their owners until drain. This server propagates that obligation to the
// model worker and reports uncertain drain through StartFailure or close.
let model = Arc::new(unsafe {
ModelRuntime::start_retaining_drain(
ModelRuntime::start_with_graph_cost_cache(
manifest,
model,
config.queue_capacity,
Expand All @@ -260,6 +275,7 @@ impl Server {
peers,
config.scheduling_policy,
config.log_to_stderr,
graph_cost_cache,
)?
});
let state = Arc::new(HttpState {
Expand Down
Loading