diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index 6bae0de87..be50a5e2f 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -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 diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index e7ef6714e..b8eaa29fe 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -634,6 +634,10 @@ fn serve_local( ) -> Result<(), Box> { 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); diff --git a/flare/src/controller.rs b/flare/src/controller.rs index 448d60154..05c1f6b84 100644 --- a/flare/src/controller.rs +++ b/flare/src/controller.rs @@ -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"); diff --git a/helios/src/cuda.rs b/helios/src/cuda.rs index 721870fce..f468cdace 100644 --- a/helios/src/cuda.rs +++ b/helios/src/cuda.rs @@ -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 { + 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, diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index cb9fb9671..0be72a9be 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -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, _core_files: Vec>, pub(super) server_config: serde_json::Value, @@ -271,6 +272,7 @@ impl NativeModel { progress: &StartupProgress, agree: &mut dyn CacheAgreement, ) -> Result { + 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")); @@ -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, @@ -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 } @@ -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, diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index ef46d7b72..4f13c69dd 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -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 { + 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 { self.costs.get(step) } @@ -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 } } } @@ -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)?; diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index 78ce33053..39e408ac5 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -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)] @@ -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 } } @@ -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(); } @@ -139,6 +142,7 @@ impl ActionCosts { replays: ReplayTimes::default(), observed_at_ns: 0, last_attempt_ns: 0, + seeded: false, }, )); } @@ -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 { + 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; @@ -238,7 +282,7 @@ impl ActionCosts { pub fn observation(&self, key: Key) -> Option<(u64, Option, 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))) } @@ -271,6 +315,7 @@ 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(); } } @@ -278,7 +323,40 @@ impl ActionCosts { #[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() { diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index f980e67be..98d539467 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -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); diff --git a/helios/src/server.rs b/helios/src/server.rs index 7c84af2c5..1c42ee73a 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -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, @@ -223,6 +225,19 @@ impl Server { images: Option, config: ServerConfig, peers: Option, + ) -> std::result::Result { + 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, + config: ServerConfig, + peers: Option, + graph_cost_cache: Option, ) -> std::result::Result { if model.contract.vision.enabled() != images.is_some() { return Err("image processor must match prepared vision capabilities".into()); @@ -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, @@ -260,6 +275,7 @@ impl Server { peers, config.scheduling_policy, config.log_to_stderr, + graph_cost_cache, )? }); let state = Arc::new(HttpState { diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 0988eeb1f..b54b4e577 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -16,6 +16,9 @@ use std::{ use tokio::sync::{mpsc as async_mpsc, oneshot}; +#[cfg(all(feature = "runtime-core", target_os = "linux"))] +mod cost_cache; + use crate::{ AdmissionError, Error, ExecutionError, Failure, Result, Shutdown, cache::ConditioningEvent, @@ -470,6 +473,22 @@ impl ModelRuntime { policy: crate::scheduler::PolicyConfig, log_to_stderr: bool, ) -> std::result::Result { + unsafe { Self::start_with_graph_cost_cache(manifest, config, queue_capacity, event_capacity, frontend, peers, policy, log_to_stderr, None) } + } + + pub(super) unsafe fn start_with_graph_cost_cache( + manifest: ExecutionManifest, + config: ModelConfig, + queue_capacity: usize, + event_capacity: usize, + frontend: Arc, + peers: Option, + policy: crate::scheduler::PolicyConfig, + log_to_stderr: bool, + graph_cost_cache: Option, + ) -> std::result::Result { + #[cfg(not(all(feature = "runtime-core", target_os = "linux")))] + let _ = graph_cost_cache; crate::model::catalog::validate(&config, &manifest)?; super::observation::initialize_clock(); if queue_capacity == 0 || queue_capacity > 1024 || !(2..=4096).contains(&event_capacity) { @@ -527,6 +546,8 @@ impl ModelRuntime { // SAFETY: start's caller retains all prepared resources through // confirmed drain. This thread exclusively owns the executor; // construction binds both streams to the manifest's context. + #[cfg(all(feature = "runtime-core", target_os = "linux"))] + let graph_cost_cache = if peers.is_none() { graph_cost_cache } else { None }; let mut executor = match unsafe { RankExecutor::new(manifest, peers) } { Ok(executor) => executor, Err(error) => { @@ -622,6 +643,23 @@ impl ModelRuntime { shutdown.error = Some(error); return shutdown; } + #[cfg(all(feature = "runtime-core", target_os = "linux"))] + let graph_cost_cache = graph_cost_cache.and_then(|(root, core)| { + match cost_cache::Cache::new(root, core, &worker_config, executor.manifest()) { + Ok(cache) => { + match cache.load(&mut scheduler) { + Ok(n) if n > 0 && log_to_stderr => eprintln!("Scheduler graph costs restored: {n}"), + Err(error) if log_to_stderr => eprintln!("warning: scheduler graph cost cache: {error}"), + _ => {} + } + Some(cache) + } + Err(error) => { + if log_to_stderr { eprintln!("warning: scheduler graph cost cache: {error}"); } + None + } + } + }); // The host prefix store opens its transfer threads on every // rank's context, which the loader prepared for this process. let store = match executor @@ -682,6 +720,16 @@ impl ModelRuntime { let mut shutdown = executor.close(); worker.close_store(&mut shutdown); if shutdown.drained { + #[cfg(all(feature = "runtime-core", target_os = "linux"))] + if error.is_none() && shutdown.error.is_none() { + if let Some(cache) = graph_cost_cache { + match cache.save(&worker.scheduler) { + Ok(n) if n > 0 && log_to_stderr => eprintln!("Scheduler graph costs saved: {n}"), + Err(error) if log_to_stderr => eprintln!("warning: scheduler graph cost cache: {error}"), + _ => {} + } + } + } let _ = worker.scheduler.release_after_shutdown(&shutdown); worker_metrics.scheduler(worker.scheduler.stats()); } diff --git a/helios/src/server/runtime/cost_cache.rs b/helios/src/server/runtime/cost_cache.rs new file mode 100644 index 000000000..345d32abf --- /dev/null +++ b/helios/src/server/runtime/cost_cache.rs @@ -0,0 +1,237 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Persistent, stale graph duration priors for authenticated single-device cores. + +use crate::{execution::ExecutionManifest, model::ModelConfig, scheduler::RequestScheduler}; +use ring::rand::{SecureRandom, SystemRandom}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + os::unix::fs::OpenOptionsExt, + path::PathBuf, +}; + +type CacheResult = std::result::Result>; +const SCHEMA: u32 = 1; +const MAX_BYTES: u64 = 1024 * 1024; + +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Scope { + core: [u8; 32], + gpu: [u8; 16], + executable: [u8; 32], + cuda_driver: i32, + kernel_driver: Option, + abi: u32, + prepared_sequence_tokens: usize, + max_sequence_tokens: usize, + max_active: usize, + prefill_chunk_size: usize, + graphs: Vec, +} + +#[derive(Serialize, Deserialize)] +struct Stored { + schema: u32, + scope: Scope, + costs: Vec<(String, u64)>, +} + +pub(super) struct Cache { + path: PathBuf, + scope: Scope, +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn executable_digest() -> CacheResult<[u8; 32]> { + let mut file = File::open("/proc/self/exe")?; + let mut digest = Sha256::new(); + let mut buffer = [0u8; 64 * 1024]; + loop { + let n = file.read(&mut buffer)?; + if n == 0 { + break; + } + digest.update(&buffer[..n]); + } + Ok(digest.finalize().into()) +} + +impl Cache { + pub(super) fn new( + root: PathBuf, + core: [u8; 32], + model: &ModelConfig, + manifest: &ExecutionManifest, + ) -> CacheResult { + let gpu = crate::cuda::device_uuid(manifest.device)?; + let mut graphs: Vec<_> = manifest.graphs.iter().map(|graph| + format!("{:?}:{}:{}:{}:{}:{}:{:?}:{}", graph.kind, + graph.batch_capacity, graph.draft_tokens, graph.token_capacity, + graph.prefill_capacity, graph.packed_token_capacity, graph.sampling_mode, graph.name) + ).collect(); + graphs.sort_unstable(); + let scope = Scope { + core, + gpu, + executable: executable_digest()?, + cuda_driver: crate::cuda::driver_version()?, + kernel_driver: fs::read_to_string("/proc/driver/nvidia/version").ok(), + abi: manifest.abi_version, + prepared_sequence_tokens: model.prepared_sequence_tokens, + max_sequence_tokens: model.limits.max_sequence_tokens, + max_active: manifest.max_active, + prefill_chunk_size: model.limits.prefill_chunk_size, + graphs, + }; + // A runtime upgrade replaces the incompatible record instead of + // accumulating one file per executable. + let path = root.join(format!("{}-{}.json", hex(&core), hex(&gpu))); + Ok(Self { path, scope }) + } + + fn read_records(&self) -> CacheResult>> { + let file = match File::open(&self.path) { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + let mut bytes = Vec::new(); + file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_BYTES { + return Err("graph cost cache exceeds size limit".into()); + } + let stored: Stored = serde_json::from_slice(&bytes)?; + if stored.schema != SCHEMA || stored.scope != self.scope { + return Ok(None); + } + Ok(Some(stored.costs)) + } + + pub(super) fn load(&self, scheduler: &mut RequestScheduler) -> CacheResult { + match self.read_records()? { + Some(costs) => Ok(scheduler.restore_graph_costs(&costs)?), + None => Ok(0), + } + } + + fn write_records(&self, costs: &[(String, u64)]) -> CacheResult { + let count = costs.iter().filter(|(_, nanos)| *nanos != 0).count(); + if count == 0 { + return Ok(0); + } + let bytes = serde_json::to_vec(&serde_json::json!({ + "schema": SCHEMA, "scope": &self.scope, "costs": costs, + }))?; + if bytes.len() as u64 > MAX_BYTES { + return Err("graph cost cache exceeds size limit".into()); + } + let parent = self.path.parent().ok_or("graph cost cache requires a directory")?; + fs::create_dir_all(parent)?; + // Distinct temporary names allow independent writers to publish + // complete snapshots without truncating a live file. + let mut nonce = [0u8; 16]; + SystemRandom::new().fill(&mut nonce).map_err(|_| "cannot create cache temporary name")?; + let temporary = parent.join(format!(".graph-cost-{}.tmp", hex(&nonce))); + let mut file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&temporary)?; + let result = (|| -> std::io::Result<()> { + file.write_all(&bytes)?; + file.sync_all()?; + drop(file); + fs::rename(&temporary, &self.path)?; + File::open(parent)?.sync_all()?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result?; + Ok(count) + } + + pub(super) fn save(&self, scheduler: &RequestScheduler) -> CacheResult { + self.write_records(&scheduler.retained_graph_costs()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Directory(PathBuf); + impl Drop for Directory { + fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } + } + + fn fixture() -> (Directory, Cache) { + let mut nonce = [0u8; 16]; + SystemRandom::new().fill(&mut nonce).unwrap(); + let directory = Directory(std::env::temp_dir().join(format!("flare-graph-cost-{}", hex(&nonce)))); + let cache = Cache { + path: directory.0.join("costs.json"), + scope: Scope { + core: [1; 32], gpu: [2; 16], executable: [3; 32], + cuda_driver: 13020, kernel_driver: Some("driver".into()), abi: 1, + prepared_sequence_tokens: 262144, max_sequence_tokens: 262144, + max_active: 8, prefill_chunk_size: 4096, graphs: vec!["Decode:1".into()], + }, + }; + (directory, cache) + } + + #[test] + fn graph_cost_cache_round_trips_and_replaces_a_complete_file() { + let (_directory, cache) = fixture(); + assert!(cache.read_records().unwrap().is_none()); + let first = vec![("Decode:1".into(), 100), ("Decode:2".into(), 0)]; + assert_eq!(cache.write_records(&first).unwrap(), 1); + assert_eq!(cache.read_records().unwrap(), Some(first)); + let second = vec![("Decode:1".into(), 200), ("Decode:2".into(), 300)]; + assert_eq!(cache.write_records(&second).unwrap(), 2); + assert_eq!(cache.read_records().unwrap(), Some(second.clone())); + assert_eq!(cache.write_records(&[("Decode:1".into(), 0)]).unwrap(), 0); + assert_eq!(cache.read_records().unwrap(), Some(second)); + assert_eq!(fs::read_dir(cache.path.parent().unwrap()).unwrap().count(), 1); + } + + #[test] + fn graph_cost_cache_rejects_changed_identity_and_corrupt_or_oversized_records() { + let (_directory, mut cache) = fixture(); + let costs = vec![("Decode:1".into(), 100)]; + cache.write_records(&costs).unwrap(); + cache.scope.core[0] ^= 1; + assert!(cache.read_records().unwrap().is_none()); + cache.scope.core[0] ^= 1; + cache.scope.gpu[0] ^= 1; + assert!(cache.read_records().unwrap().is_none()); + cache.scope.gpu[0] ^= 1; + cache.scope.executable[0] ^= 1; + assert!(cache.read_records().unwrap().is_none()); + cache.scope.executable[0] ^= 1; + cache.scope.cuda_driver += 1; + assert!(cache.read_records().unwrap().is_none()); + cache.scope.cuda_driver -= 1; + cache.scope.max_sequence_tokens -= 1; + assert!(cache.read_records().unwrap().is_none()); + cache.scope.max_sequence_tokens += 1; + cache.scope.graphs.push("Prefill:1".into()); + assert!(cache.read_records().unwrap().is_none()); + cache.scope.graphs.pop(); + assert_eq!(cache.read_records().unwrap(), Some(costs.clone())); + let too_large = vec![("x".repeat(MAX_BYTES as usize), 1)]; + assert!(cache.write_records(&too_large).is_err()); + assert_eq!(cache.read_records().unwrap(), Some(costs)); + fs::write(&cache.path, b"{").unwrap(); + assert!(cache.read_records().is_err()); + fs::write(&cache.path, vec![0; MAX_BYTES as usize + 1]).unwrap(); + assert!(cache.read_records().is_err()); + } +} diff --git a/helios/src/server/session.rs b/helios/src/server/session.rs index 20ac715e1..75235d330 100644 --- a/helios/src/server/session.rs +++ b/helios/src/server/session.rs @@ -17,6 +17,7 @@ pub struct LoadedSession { manifest: ExecutionManifest, peers: Option, bootstrap: Bootstrap, + graph_cost_cache: Option, // CUDA contexts outlive all retained manifest/peer bindings, including // registered host storage when a loaded session is dropped before start. owner: NativeModel, @@ -37,10 +38,19 @@ impl LoadedSession { manifest, peers, bootstrap, + graph_cost_cache: None, owner, }) } + /// Supply the application's cache directory for authenticated single-device timings. + #[cfg(target_os = "linux")] + pub fn set_graph_cost_cache_root(&mut self, root: std::path::PathBuf) { + if self.peers.is_none() { + self.graph_cost_cache = Some((root, self.owner.core_envelope_digest())); + } + } + pub fn server_config_mut(&mut self) -> &mut ServerConfig { &mut self.bootstrap.server } @@ -51,6 +61,7 @@ impl LoadedSession { manifest, peers, bootstrap, + graph_cost_cache, } = self; // Assume an unconfirmed drain before entering code that may launch GPU work. // Unwinding also retains the owner rather than freeing referenced storage. @@ -58,13 +69,14 @@ impl LoadedSession { // SAFETY: The session owns the loaded model and grants its worker exclusive // execution. The guard retains the resources when drain is unconfirmed. let server = unsafe { - Server::start( + Server::start_with_graph_cost_cache( manifest, bootstrap.model, bootstrap.frontend, bootstrap.images, bootstrap.server, peers, + graph_cost_cache, ) }; match server {