Skip to content
Closed
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
1 change: 1 addition & 0 deletions helios/src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2217,6 +2217,7 @@ impl RequestScheduler {
else if step.lane_kind(row).is_prefill() { lane.tokens as f64 } else { 0.0 }
}));
let participants = self.service_participants();
self.invalidate_checkpoint_selections();
let submitted_timing = SubmittedTiming {
retained_ns: plan.selected_cost.retained_ns,
observed_at_ns: plan.selected_cost.observed_at_ns,
Expand Down
7 changes: 7 additions & 0 deletions helios/src/scheduler/cache_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@

use super::*;

#[cfg(test)]
thread_local! {
pub(super) static STORAGE_SIMULATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct SnapshotQuote {
pub(super) snapshots: Vec<SnapshotId>,
Expand Down Expand Up @@ -250,6 +255,8 @@ impl RequestScheduler {
rank: crate::cache::RetentionRank,
allowed: Option<&BTreeSet<SnapshotId>>,
) -> Option<SnapshotQuote> {
#[cfg(test)]
STORAGE_SIMULATIONS.set(STORAGE_SIMULATIONS.get() + 1);
let keep_pages = keep_pages.max(self.decode_growth_pages());
let mut cache = self.cache.clone();
let mut backing = self.free_backing();
Expand Down
204 changes: 201 additions & 3 deletions helios/src/scheduler/checkpoints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,31 @@ impl LiveRequest {
}

impl RequestScheduler {
pub(super) fn checkpoint_planning_scope(&self) -> PlanningScope<'_> {
*self.checkpoint_selections.borrow_mut() = Some(HashMap::new());
PlanningScope(&self.checkpoint_selections)
pub(super) fn checkpoint_planning_scope(&self) -> Option<PlanningScope<'_>> {
self.begin_checkpoint_planning()
.then(|| PlanningScope(&self.checkpoint_selections))
}

/// If this opens the cache, the caller must call `end_checkpoint_planning`.
/// Once populated, only `advance_to` and `commit` may change checkpoint-selection inputs.
pub(crate) fn begin_checkpoint_planning(&self) -> bool {
let mut cache = self.checkpoint_selections.borrow_mut();
if cache.is_some() {
return false;
}
*cache = Some(HashMap::new());
true
}

#[cfg(any(feature = "server", test))]
pub(crate) fn end_checkpoint_planning(&self) {
*self.checkpoint_selections.borrow_mut() = None;
}

pub(super) fn invalidate_checkpoint_selections(&self) {
if let Some(cache) = self.checkpoint_selections.borrow_mut().as_mut() {
cache.clear();
}
}
pub(super) fn revoke_unused_anchor_guards(&mut self) -> bool {
let handle = self
Expand Down Expand Up @@ -676,6 +698,182 @@ mod tests {
measure(scheduler, GraphKind::Snapshot, 1, 1);
}

fn loaded_scheduler() -> RequestScheduler {
let mut scheduler = super::super::tests::scheduler(16, 2048, 64);
scheduler
.prefill_graphs(&(64..=512).step_by(64).collect::<Vec<_>>())
.unwrap();
linear_costs(&mut scheduler);
for slot in 0..16 {
let mut spec = super::super::tests::spec(1024, 3);
spec.prompt[0] += slot + 100_000;
spec.message_boundaries = vec![128, 256, 512, 896];
scheduler.admit(spec).unwrap();
}
scheduler
}

#[test]
fn checkpoint_selection_preserves_plans_and_prices_over_loaded_trace() {
let trace = |cached: bool| {
let mut scheduler = loaded_scheduler();
let mut trace = Vec::new();
let mut snapshots = 0;
for sequence in 1..=512 {
if cached {
scheduler.begin_checkpoint_planning();
}
let Some(plan) = scheduler.plan() else {
if cached {
scheduler.end_checkpoint_planning();
}
break;
};
trace.push(format!("{plan:?}"));
snapshots += usize::from(plan.kind == GraphKind::Snapshot);
let fence = Fence(sequence);
scheduler
.advance_to(scheduler.now_ns + plan.estimated_duration_ns)
.unwrap();
scheduler.commit(&plan, fence).unwrap();
if cached {
assert!(
scheduler
.checkpoint_selections
.borrow()
.as_ref()
.unwrap()
.is_empty()
);
scheduler.end_checkpoint_planning();
}
let mut records = vec![CompletionRecord::default(); 16];
for (row, lane) in plan.lanes.iter().enumerate() {
let request = scheduler.request(lane.request).unwrap();
let kind = plan.lane_kind(row);
let consumed = if kind.is_prefill() || kind == GraphKind::Decode {
lane.start_position + lane.tokens as u64
} else {
request.consumed_tokens
};
let output = kind == GraphKind::Decode
|| kind == GraphKind::Resume
|| (kind.is_prefill() && consumed == request.prompt_tokens as u64);
records[lane.request.slot as usize] = CompletionRecord {
generation: lane.request.generation as i64,
submission_sequence: sequence as i64,
status: 1,
consumed_tokens: consumed as i64,
generated_tokens: request.generated_tokens as i64 + i64::from(output),
token_id: if output { 42 } else { -1 },
..Default::default()
};
}
let generated = scheduler
.complete(
fence,
&records,
crate::execution::ExecutionTiming {
gpu_ns: [Some(plan.estimated_duration_ns); 16],
..Default::default()
},
)
.unwrap();
for token in generated {
scheduler.published_output(token.request, fence).unwrap();
}
let mut finished = Vec::new();
for request in scheduler.slots.iter().filter_map(|s| s.request.as_ref()) {
let service = request.accounting.service;
trace.push(format!(
"{:?} {:?} {:?}",
request.handle,
service.tokens.map(|p| p.log_price(1.0).to_bits()),
service.deliveries.map(|p| p.log_price(1.0).to_bits())
));
if request.phase == RequestPhase::Finishing {
finished.push(request.handle);
}
}
for handle in finished {
scheduler.finish(handle).unwrap();
}
assert!(scheduler.checkpoint_selections.borrow().is_none());
}
assert!(scheduler.slots.iter().all(|s| s.request.is_none()));
assert!(snapshots >= 16);
trace
};
assert_eq!(trace(false), trace(true));
}

#[test]
fn commit_storage_simulations_do_not_scale_with_prefill_capacities() {
let mut scheduler = loaded_scheduler();
let single_pass: usize = scheduler
.slots
.iter()
.filter_map(|s| s.request.as_ref())
.map(|request| {
cache_memory::STORAGE_SIMULATIONS.set(0);
scheduler.checkpoint_selection_uncached(request);
cache_memory::STORAGE_SIMULATIONS.get()
})
.sum();
assert!(single_pass > 0);
assert!(scheduler.prefill_catalog.len() >= 8);
scheduler.begin_checkpoint_planning();
cache_memory::STORAGE_SIMULATIONS.set(0);
let plan = scheduler.plan().unwrap();
assert_eq!(plan.kind, GraphKind::Init);
assert_eq!(cache_memory::STORAGE_SIMULATIONS.get(), single_pass);
scheduler.advance_to(1).unwrap();
cache_memory::STORAGE_SIMULATIONS.set(0);
scheduler.commit(&plan, Fence(1)).unwrap();
assert_eq!(cache_memory::STORAGE_SIMULATIONS.get(), 0);
assert!(
scheduler
.checkpoint_selections
.borrow()
.as_ref()
.unwrap()
.is_empty()
);
scheduler.end_checkpoint_planning();
assert!(scheduler.checkpoint_selections.borrow().is_none());
}

#[test]
fn checkpoint_selection_recomputes_when_snapshot_cost_expires() {
let mut scheduler = loaded_scheduler();
scheduler.begin_checkpoint_planning();
scheduler.plan().unwrap();
assert!(
!scheduler
.checkpoint_selections
.borrow()
.as_ref()
.unwrap()
.is_empty()
);
scheduler
.advance_to(scheduler.policy.estimate_ttl_ns + 1)
.unwrap();
assert!(
scheduler
.checkpoint_selections
.borrow()
.as_ref()
.unwrap()
.is_empty()
);
let request = scheduler.slots[0].request.as_ref().unwrap();
let selected = scheduler.checkpoint_selection(request);
assert_eq!(selected, scheduler.checkpoint_selection_uncached(request));
assert_eq!(selected.0.cuts.len(), 1);
scheduler.end_checkpoint_planning();
}

#[test]
fn missing_cost_retries_original_uncached_interval_after_progress() {
let mut scheduler = super::super::tests::scheduler(1, 128, 16);
Expand Down
4 changes: 4 additions & 0 deletions helios/src/scheduler/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,12 @@ impl RequestScheduler {
if now_ns < self.now_ns {
return Err("scheduler clock must be monotonic".into());
}
let snapshot_cost = self.costs.fresh_duration(GraphKind::Snapshot, 1);
self.now_ns = now_ns;
self.costs.advance_to(now_ns, self.policy.estimate_ttl_ns);
if snapshot_cost != self.costs.fresh_duration(GraphKind::Snapshot, 1) {
self.invalidate_checkpoint_selections();
}
Ok(())
}

Expand Down
4 changes: 4 additions & 0 deletions helios/src/scheduler/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

use super::*;

pub(crate) fn take_storage_simulations() -> usize {
super::cache_memory::STORAGE_SIMULATIONS.replace(0)
}

pub(super) fn measured_costs(graphs: &[crate::execution::GraphDescriptor]) -> cost::ActionCosts {
let mut costs = cost::ActionCosts::prepared(graphs, 16).unwrap();
for graph in graphs {
Expand Down
20 changes: 15 additions & 5 deletions helios/src/server/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,7 @@ impl ModelRuntime {
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
worker.run(&mut executor)
}));
worker.scheduler.end_checkpoint_planning();
worker_health.store(false, Ordering::Release);
let error = match run {
Ok(Ok(())) => None,
Expand Down Expand Up @@ -1102,11 +1103,20 @@ impl<'a> Worker<'a> {
}
progress |= self.publish()?;
progress |= self.service_store()?;
let (step, planned) = self.plan(executor.outstanding())?;
progress |= planned;
if let Some(step) = step {
progress |= self.submit(executor, &step)?;
}
// The cache is empty through pool retries and copy-proposal updates in
// plan; scheduler.plan() computes the first selections. After that,
// only clock advancement precedes commit, which clears selections
// before changing request or storage state.
self.scheduler.begin_checkpoint_planning();
let planned = (|| -> Result<bool> {
let (step, mut progress) = self.plan(executor.outstanding())?;
if let Some(step) = step {
progress |= self.submit(executor, &step)?;
}
Ok(progress)
})();
self.scheduler.end_checkpoint_planning();
progress |= planned?;
if progress {
self.metrics.scheduler(self.scheduler.stats());
self.metrics
Expand Down
72 changes: 72 additions & 0 deletions helios/src/server/runtime/phase_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,78 @@ fn output_clock_advances_only_after_stop_buffering_releases_tokens() {
);
}

#[test]
fn worker_checkpoint_selections_match_uncached_submission_after_cost_expiry() {
let submit = |cached: bool, expire: bool| {
let fixture = Fixture::new();
let (sender, receiver) = mpsc::channel();
let (mut incoming, _generation) = fixture.incoming(vec![0; 100], 8);
incoming.prompt.message_boundaries = vec![16, 32, 64, 96];
sender.send(vec![incoming]).unwrap();
let mut worker = fixture.worker(receiver);
worker
.scheduler
.configure_policy(crate::scheduler::PolicyConfig {
checkpoint_extra_work_fraction: 1.0,
estimate_ttl_ns: u64::MAX / 4,
..Default::default()
})
.unwrap();
let mut graphs = crate::model::testing::manifest(&fixture.config).graphs;
for graph in &mut graphs {
graph.estimated_duration_ns = if graph.kind == GraphKind::Snapshot {
1
} else {
1000
};
}
worker.scheduler.measured_graph_durations(&graphs).unwrap();
assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true));
if cached {
worker.scheduler.begin_checkpoint_planning();
}
let (step, _) = worker.plan(0).unwrap();
let step = step.unwrap();
assert_eq!(step.kind, GraphKind::Init);
// Submission advances the clock after planning; expiry must discard the
// cached extra captures before commit computes service participants.
let now = super::super::observation::monotonic_ns();
worker
.scheduler
.advance_to(if expire { u64::MAX / 2 } else { now })
.unwrap();
crate::scheduler::tests::take_storage_simulations();
worker.reserve_and_pack(&step, Fence(1)).unwrap();
let simulations = crate::scheduler::tests::take_storage_simulations();
if cached || expire {
assert_eq!(simulations, 0);
} else {
assert!(simulations > 0);
}
worker.scheduler.end_checkpoint_planning();
let mut frame = completion(&worker, &step, 1, None);
frame.timing.gpu_ns[0] = Some(1000);
worker
.scheduler
.complete(Fence(1), &frame.records, frame.timing)
.unwrap();
let following = worker.scheduler.plan().unwrap();
(
(*following).clone(),
following.selection_value_rate().to_bits(),
following.selection_log_scale().to_bits(),
)
};
let fresh = submit(false, false);
let expired = submit(false, true);
assert_ne!(
fresh, expired,
"expiry must change the checkpoint decision or its service price"
);
assert_eq!(submit(true, false), fresh);
assert_eq!(submit(true, true), expired);
}

#[test]
fn packing_sees_reserved_pages_and_pack_failure_retains_submission_until_drain() {
let fixture = Fixture::new();
Expand Down
Loading