diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 87dbc4b09..17ec42965 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -123,7 +123,6 @@ pub struct NativeResources { integrated: bool, events: HashMap, cache: Option, - #[cfg(windows)] host_mappings: Vec<(u64, usize)>, green_partition: Option, persistent_worker: Option>, @@ -421,7 +420,6 @@ impl NativeResources { integrated: integrated != 0, events: HashMap::new(), cache: None, - #[cfg(windows)] host_mappings: Vec::new(), green_partition: None, persistent_worker: None, @@ -547,6 +545,118 @@ impl NativeResources { // Every CUDA resource is immediately retained by self for error cleanup. unsafe { driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; + // Coalesce contiguous fixed MappedHost allocations into shared VMAs before pinning so + // transparent huge pages can span layer boundaries without losing alignment edges. + #[cfg(unix)] + { + let mut spans: Vec<(u64, usize, u32)> = core + .allocations + .iter() + .filter(|a| { + a.sizing.is_none() + && matches!(a.memory, Memory::MappedHost) + && a.nbytes > 0 + && !self.allocations.get(&a.name).is_some_and(|s| s.nbytes > 0) + }) + .filter_map(|a| { + let addr = a.address?; + let flags = if self.peer_readers.contains_key(&addr) { 3 } else { 2 }; + Some((addr, a.nbytes, flags)) + }) + .collect(); + spans.sort_unstable_by_key(|&(addr, _, _)| addr); + let mut merged: Vec<(u64, usize, u32)> = Vec::with_capacity(spans.len()); + for (addr, nbytes, flags) in spans { + if let Some(last) = merged.last_mut() + && last.2 == flags + && last.0.checked_add(last.1 as u64) == Some(addr) + { + last.1 = last + .1 + .checked_add(nbytes) + .ok_or_else(|| invalid("coalesced mapped host size overflow"))?; + } else { + merged.push((addr, nbytes, flags)); + } + } + let mut mapped_spans: Vec<(u64, usize, u32)> = Vec::with_capacity(merged.len()); + let unmap_unregistered = |spans: &[(u64, usize, u32)]| { + for &(addr, bytes, _) in spans { + libc::munmap(addr as Handle, bytes); + } + }; + for (span_addr, span_bytes, flags) in merged { + let mapped = libc::mmap( + span_addr as Handle, + span_bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_FIXED_NOREPLACE, + -1, + 0, + ); + if mapped != span_addr as Handle { + let error = std::io::Error::last_os_error(); + unmap_unregistered(&mapped_spans); + return Err(invalid(format!( + "host address collision at {span_addr:#x}: {error}" + ))); + } + #[cfg(target_os = "linux")] + { + // Best-effort transparent huge page hint before pinning so unified-memory + // GPU replay walks fewer TLB entries. + let _ = libc::madvise(mapped, span_bytes, libc::MADV_HUGEPAGE); + } + mapped_spans.push((span_addr, span_bytes, flags)); + } + #[cfg(target_os = "linux")] + { + // Pre-fault at 2 MiB stride in package allocation order before + // cuMemHostRegister_v2 pins the VMA: the first touch in a 512 MiB PMD faults + // the whole PMD when available, 2 MiB stride also pre-faults sub-PMD mTHP + // folios (2 MiB..256 MiB) when enabled, and preserving allocation order keeps + // scarce PMDs aligned with the exporter's layout priority. + const PREFAULT_STRIDE: usize = 2 * 1024 * 1024; + for a in &core.allocations { + if a.sizing.is_some() + || !matches!(a.memory, Memory::MappedHost) + || a.nbytes == 0 + || self.allocations.get(&a.name).is_some_and(|s| s.nbytes > 0) + { + continue; + } + let Some(addr) = a.address else { continue }; + let start_addr = addr as usize; + let end_addr = start_addr + a.nbytes; + let mut cur = (start_addr + PREFAULT_STRIDE - 1) & !(PREFAULT_STRIDE - 1); + while cur < end_addr { + std::ptr::write_volatile(cur as *mut u8, 0); + cur = match cur.checked_add(PREFAULT_STRIDE) { + Some(next) => next, + None => break, + }; + } + } + } + for (index, &(span_addr, span_bytes, flags)) in mapped_spans.iter().enumerate() { + let mapped = span_addr as Handle; + // Registration does not pin host memory for an integrated GPU, and a + // swapped-out page turns each GPU access during replay into a fault. + if self.integrated && libc::mlock(mapped, span_bytes) != 0 { + let error = std::io::Error::last_os_error(); + unmap_unregistered(&mapped_spans[index..]); + return Err(invalid(format!( + "cannot lock {span_bytes} bytes of mapped host storage: {error}; raise RLIMIT_MEMLOCK" + ))); + } + let status = (driver.host_register)(mapped, span_bytes, flags); + if status != 0 { + unmap_unregistered(&mapped_spans[index..]); + } + driver.check("cuMemHostRegister_v2", status)?; + self.host_mappings.push((span_addr, span_bytes)); + } + } let footprint = core .allocations .iter() @@ -619,40 +729,7 @@ impl NativeResources { driver.check("cuMemMap", mapped)?; } Memory::MappedHost => { - #[cfg(unix)] - { - let mapped = libc::mmap( - address as Handle, - allocation.nbytes, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE - | libc::MAP_ANONYMOUS - | libc::MAP_FIXED_NOREPLACE, - -1, - 0, - ); - if mapped != address as Handle { - return Err(invalid(format!( - "host address collision at {address:#x}: {}", - std::io::Error::last_os_error() - ))); - } - // Registration does not pin host memory for an integrated GPU, and a - // swapped-out page turns each GPU access during replay into a fault. - if self.integrated && libc::mlock(mapped, allocation.nbytes) != 0 { - let error = std::io::Error::last_os_error(); - libc::munmap(mapped, allocation.nbytes); - return Err(invalid(format!( - "cannot lock {} bytes of mapped host storage: {error}; raise RLIMIT_MEMLOCK", - allocation.nbytes - ))); - } - let status = (driver.host_register)(mapped, allocation.nbytes, 2); - if status != 0 { - libc::munmap(mapped, allocation.nbytes); - } - driver.check("cuMemHostRegister_v2", status)?; - } + // Mapped, pre-faulted, and registered in coalesced spans above. } // The owning rank maps peer storage and grants this rank access. Memory::Peer => {} @@ -1583,19 +1660,18 @@ impl NativeResources { (self.driver.unmap)(address, bytes); } } - (Memory::MappedHost, _) => { - #[cfg(unix)] - { - (self.driver.host_unregister)(allocation.address as Handle); - libc::munmap(allocation.address as Handle, allocation.nbytes); - } - } + (Memory::MappedHost, _) => {} (Memory::Peer, _) => {} } } - #[cfg(windows)] for (address, bytes) in self.host_mappings.drain(..).rev() { + #[cfg(windows)] (self.driver.unmap)(address, bytes); + #[cfg(unix)] + { + (self.driver.host_unregister)(address as Handle); + libc::munmap(address as Handle, bytes); + } } self.persistent_worker = None; if had_previous && previous != self.context { diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index 2e7211b17..11744584a 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -481,12 +481,28 @@ fn solve_small_spd(a: &[[f64; 3]; 3], b: &[f64; 3], idx: &[usize]) -> Option<[f6 } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum ObservationState { + /// No valid observation in the current freshness epoch. + #[default] + Unmeasured, + /// One observation in the current freshness epoch; eligible for early staleness if a + /// confirmed warm sibling in the same batch is substantially faster. + SingleSample, + /// Single-sample observation marked stale after a warm sibling contradicted it, + /// keeping its measured cost for ranking until funded refresh re-measures it. + StaleSingleSample, + /// Confirmed by repeated fresh observations, a completed recheck, or test setup. + Confirmed, +} + struct Estimate { nanos: u64, replays: ReplayTimes, prefill: Option, observed_at_ns: u64, last_attempt_ns: u64, + state: ObservationState, } #[derive(Default)] @@ -512,7 +528,9 @@ 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.state != ObservationState::StaleSingleSample + && now_ns.saturating_sub(self.observed_at_ns) < ttl_ns } } @@ -577,6 +595,7 @@ impl ActionCosts { model.reset_with_full(nanos); } estimate.observed_at_ns = self.now_ns; + estimate.state = ObservationState::Confirmed; self.refresh_packed_durations(); if key.kind.is_prefill() { self.refresh_prefill_context_slopes(); @@ -606,6 +625,7 @@ impl ActionCosts { prefill: key.kind.is_prefill().then(|| PrefillCostModel::new(key.tokens)), observed_at_ns: 0, last_attempt_ns: 0, + state: ObservationState::Unmeasured, }, )); } @@ -943,16 +963,76 @@ impl ActionCosts { .first() .map_or((step.token_capacity, 0), |lane| (lane.tokens, lane.start_position)); estimate.nanos = model.observe(sample, work, start_position, fresh); + estimate.state = ObservationState::Confirmed; + } else if key.kind == GraphKind::Speculative { + let (keep_window, next_state) = if estimate.state == ObservationState::StaleSingleSample { + (false, ObservationState::Confirmed) + } else if !fresh { + (false, ObservationState::SingleSample) + } else if estimate.state == ObservationState::SingleSample + && u128::from(sample) * 4 < u128::from(estimate.nanos) * 3 + { + // Discard an unconfirmed cold-start first replay when the follow-up replay + // is substantially faster so the spike does not bias the two-sample median. + (false, ObservationState::Confirmed) + } else { + (true, ObservationState::Confirmed) + }; + estimate.nanos = estimate.replays.observe(sample, keep_window); + estimate.state = next_state; } else { estimate.nanos = estimate.replays.observe(sample, fresh); + estimate.state = ObservationState::Confirmed; } estimate.observed_at_ns = self.now_ns; + let warm_nanos = estimate.nanos; + if estimate.state == ObservationState::Confirmed && key.kind == GraphKind::Speculative { + self.mark_cold_siblings_stale(key, warm_nanos); + } self.refresh_packed_durations(); if key.kind.is_prefill() { self.refresh_prefill_context_slopes(); } } } + + /// Marks unconfirmed single-sample speculative siblings in the same batch stale when a + /// confirmed warm sibling is substantially faster, and also invalidates confirmed strictly + /// narrower siblings that are >10% slower than a confirmed wider sibling in the same batch + /// (e.g., after switching from a heavier routing domain), allowing funded refresh to + /// re-measure them without waiting for the full freshness TTL. + fn mark_cold_siblings_stale(&mut self, warm_key: Key, warm_nanos: u64) { + let now_ns = self.now_ns; + let ttl_ns = self.ttl_ns; + for (other_key, other) in &mut self.entries { + if *other_key == warm_key + || other_key.kind != GraphKind::Speculative + || other_key.batch != warm_key.batch + || !other.fresh(now_ns, ttl_ns) + { + continue; + } + let strictly_narrower = other_key.tokens <= warm_key.tokens + && other_key.packed <= warm_key.packed + && (other_key.tokens < warm_key.tokens || other_key.packed < warm_key.packed); + let anomalous = match other.state { + ObservationState::SingleSample => { + if other_key.tokens <= warm_key.tokens && other_key.packed <= warm_key.packed { + other.nanos > warm_nanos + } else { + u128::from(other.nanos) * 4 > u128::from(warm_nanos) * 5 + } + } + ObservationState::Confirmed if strictly_narrower => { + u128::from(other.nanos) * 10 > u128::from(warm_nanos) * 11 + } + _ => false, + }; + if anomalous { + other.state = ObservationState::StaleSingleSample; + } + } + } } #[cfg(test)] @@ -1586,4 +1666,175 @@ mod tests { Some(expected_spec) ); } + + fn speculative_graph(width: usize) -> GraphDescriptor { + GraphDescriptor { + name: format!("b1w{width}"), + kind: GraphKind::Speculative, + sampling_mode: SamplingMode::General, + confidence_width: width - 1, + draft_tokens: width - 1, + handle: width, + batch_capacity: 1, + token_capacity: width, + packed_token_capacity: width, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + } + + fn speculative_step(width: usize) -> ScheduledStep { + ScheduledStep { + draft_tokens: width - 1, + kind: GraphKind::Speculative, + batch_capacity: 1, + token_capacity: width, + packed_token_capacity: width, + mixed: None, + lanes: vec![], + requires_feedback: false, + } + } + + fn gpu_timing(ns: u64) -> crate::execution::ExecutionTiming { + let mut gpu_ns = [None; 16]; + gpu_ns[0] = Some(ns); + crate::execution::ExecutionTiming { gpu_ns, ..Default::default() } + } + + #[test] + fn cold_start_spike_on_wider_packed_widths_triggers_early_stale_refresh() { + const MS: u64 = 1_000_000; + let graphs: Vec<_> = [1, 2, 4, 8].into_iter().map(speculative_graph).collect(); + let mut costs = ActionCosts::prepared(&graphs, 8).unwrap(); + let ttl = super::super::PolicyConfig::default().estimate_ttl_ns; + let key = |w| super::Key::from_step(&speculative_step(w)); + + // Cold discovery: wider widths execute first while caches and clocks are cold. + costs.advance_to(85 * MS, ttl); + costs.observe(&speculative_step(8), gpu_timing(85 * MS)); + costs.advance_to(140 * MS, ttl); + costs.observe(&speculative_step(4), gpu_timing(55 * MS)); + costs.advance_to(175 * MS, ttl); + costs.observe(&speculative_step(2), gpu_timing(35 * MS)); + costs.advance_to(206 * MS, ttl); + costs.observe(&speculative_step(1), gpu_timing(31 * MS)); + + // Second replay confirms warm width-2 duration and marks cold single-sample + // wider siblings stale immediately while retaining their costs for ranking. + costs.advance_to(239 * MS, ttl); + costs.observe(&speculative_step(2), gpu_timing(33 * MS)); + assert_eq!(costs.get(&speculative_step(2)), Some(34 * MS)); + assert_eq!(costs.get(&speculative_step(1)), Some(31 * MS)); + assert_eq!(costs.get(&speculative_step(4)), Some(55 * MS)); + assert_eq!(costs.get(&speculative_step(8)), Some(85 * MS)); + assert!(costs.is_fresh(key(1))); + assert!(costs.is_fresh(key(2))); + assert!(!costs.is_fresh(key(4))); + assert!(!costs.is_fresh(key(8))); + let stale: Vec<_> = costs.stale_keys().collect(); + assert!(stale.contains(&key(4)) && stale.contains(&key(8))); + + // Warm refresh replaces the stale cold spikes directly without averaging. + costs.advance_to(276 * MS, ttl); + costs.observe(&speculative_step(8), gpu_timing(37 * MS)); + costs.advance_to(310 * MS, ttl); + costs.observe(&speculative_step(4), gpu_timing(34 * MS)); + assert_eq!(costs.get(&speculative_step(8)), Some(37 * MS)); + assert_eq!(costs.get(&speculative_step(4)), Some(34 * MS)); + assert!(costs.is_fresh(key(8))); + assert!(costs.is_fresh(key(4))); + assert_eq!(costs.packed_round_duration(1, 8), Some(37 * MS)); + assert_eq!(costs.packed_round_duration(1, 4), Some(34 * MS)); + + // Direct follow-up on a single-sample cold spike drops the cold sample immediately. + let mut single = ActionCosts::prepared(&[speculative_graph(8)], 8).unwrap(); + single.advance_to(85 * MS, ttl); + single.observe(&speculative_step(8), gpu_timing(85 * MS)); + single.advance_to(122 * MS, ttl); + single.observe(&speculative_step(8), gpu_timing(37 * MS)); + assert_eq!(single.get(&speculative_step(8)), Some(37 * MS)); + } + + #[test] + fn warm_siblings_and_confirmed_slow_widths_stay_stable_without_rechecking() { + const MS: u64 = 1_000_000; + let graphs: Vec<_> = [1, 2, 4, 8].into_iter().map(speculative_graph).collect(); + let ttl = super::super::PolicyConfig::default().estimate_ttl_ns; + let key = |w| super::Key::from_step(&speculative_step(w)); + + // Already-warm widths within 1.25x remain fresh without triggering refresh. + let mut warm = ActionCosts::prepared(&graphs, 8).unwrap(); + warm.advance_to(37 * MS, ttl); + warm.observe(&speculative_step(8), gpu_timing(37 * MS)); + warm.advance_to(71 * MS, ttl); + warm.observe(&speculative_step(4), gpu_timing(34 * MS)); + warm.advance_to(104 * MS, ttl); + warm.observe(&speculative_step(2), gpu_timing(33 * MS)); + warm.advance_to(135 * MS, ttl); + warm.observe(&speculative_step(1), gpu_timing(31 * MS)); + warm.advance_to(168 * MS, ttl); + warm.observe(&speculative_step(2), gpu_timing(33 * MS)); + assert!(warm.is_fresh(key(8))); + assert!(warm.is_fresh(key(4))); + assert_eq!(warm.get(&speculative_step(8)), Some(37 * MS)); + assert_eq!(warm.get(&speculative_step(4)), Some(34 * MS)); + + // A genuinely slow wider width is marked stale at most once per freshness epoch, + // then stays fresh and stable under repeated warm replays of narrower widths. + let mut slow = ActionCosts::prepared(&graphs, 8).unwrap(); + slow.advance_to(85 * MS, ttl); + slow.observe(&speculative_step(8), gpu_timing(85 * MS)); + slow.advance_to(120 * MS, ttl); + slow.observe(&speculative_step(2), gpu_timing(35 * MS)); + slow.advance_to(153 * MS, ttl); + slow.observe(&speculative_step(2), gpu_timing(33 * MS)); + assert!(!slow.is_fresh(key(8))); + assert_eq!(slow.get(&speculative_step(8)), Some(85 * MS)); + + // Refresh confirms 85 ms is genuine; subsequent warm replays keep width 8 fresh. + slow.advance_to(238 * MS, ttl); + slow.observe(&speculative_step(8), gpu_timing(85 * MS)); + assert!(slow.is_fresh(key(8))); + assert_eq!(slow.get(&speculative_step(8)), Some(85 * MS)); + for i in 1..=20u64 { + slow.advance_to((238 + i * 33) * MS, ttl); + slow.observe(&speculative_step(2), gpu_timing(33 * MS)); + assert!(slow.is_fresh(key(8))); + assert_eq!(slow.get(&speculative_step(8)), Some(85 * MS)); + } + } + + #[test] + fn confirmed_narrower_sibling_marked_stale_when_wider_sibling_is_substantially_faster() { + const MS: u64 = 1_000_000; + let graphs: Vec<_> = [1, 2, 4, 8].into_iter().map(speculative_graph).collect(); + let ttl = super::super::PolicyConfig::default().estimate_ttl_ns; + let key = |w| super::Key::from_step(&speculative_step(w)); + + let mut costs = ActionCosts::prepared(&graphs, 8).unwrap(); + // Confirm narrower width 2 at 30 ms on an earlier heavier workload. + costs.advance_to(30 * MS, ttl); + costs.observe(&speculative_step(2), gpu_timing(30 * MS)); + costs.advance_to(60 * MS, ttl); + costs.observe(&speculative_step(2), gpu_timing(30 * MS)); + assert!(costs.is_fresh(key(2))); + assert_eq!(costs.get(&speculative_step(2)), Some(30 * MS)); + + // Wider width 4 confirms at 25 ms (>10% faster than width 2's 30 ms). + costs.advance_to(85 * MS, ttl); + costs.observe(&speculative_step(4), gpu_timing(25 * MS)); + costs.advance_to(110 * MS, ttl); + costs.observe(&speculative_step(4), gpu_timing(25 * MS)); + assert!(!costs.is_fresh(key(2))); + assert_eq!(costs.get(&speculative_step(2)), Some(30 * MS)); + + // Refresh replaces width 2's stale cost with the current 21 ms measurement. + costs.advance_to(131 * MS, ttl); + costs.observe(&speculative_step(2), gpu_timing(21 * MS)); + assert!(costs.is_fresh(key(2))); + assert_eq!(costs.get(&speculative_step(2)), Some(21 * MS)); + } } diff --git a/helios/src/scheduler/planning_tests.rs b/helios/src/scheduler/planning_tests.rs index 1504e6e95..dc793525a 100644 --- a/helios/src/scheduler/planning_tests.rs +++ b/helios/src/scheduler/planning_tests.rs @@ -162,6 +162,86 @@ fn host_cohort_ranking_matches_greedy_reallocation() { } } +#[test] +fn narrow_gpu_confidence_rounds_update_deep_forecasts_without_calibrating_unverified_depths() { + let mut scheduler = planning_scheduler(1, PrefixAllocation::Gpu); + let handle = scheduler.slots[0].request.as_ref().unwrap().handle; + let round = ScheduledStep { + kind: GraphKind::Speculative, + batch_capacity: 1, + draft_tokens: 7, + token_capacity: 2, + packed_token_capacity: 2, + mixed: None, + requires_feedback: false, + lanes: vec![ScheduledLane { + request: handle, + start_position: 80, + tokens: 2, + }], + }; + let mut records = vec![CompletionRecord::default(); scheduler.limits.request_capacity()]; + let confidence = vec![vec![0.95f32; 7]]; + let realized = vec![(0usize, 0usize, 0.5f64), (0usize, 2usize, 0.0f64), (0usize, 4usize, 0.0f64)]; + for step_index in 0..16u32 { + let generated = 18 + step_index as i64; + records[handle.slot as usize] = CompletionRecord { + status: 1, + generated_tokens: generated, + vector: Some(TokenVector { + emitted_count: 1, + offered_drafts: 1, + verification_width: 2, + ..Default::default() + }), + ..Default::default() + }; + scheduler.request_mut(handle).unwrap().generated_tokens = generated as u32; + scheduler.observe_packed_forecasts(&round, &records, &confidence, &realized); + } + + let depth0_global_cal = scheduler.forecasts.calibration_factor(0); + let depth0_request_cal = scheduler.forecasts.request_calibration_factor(handle, 0); + assert!( + depth0_global_cal < 0.75, + "realized depth 0 global calibration should reflect observed 0.5 vs predicted 0.95, got {depth0_global_cal}", + ); + assert!( + depth0_request_cal < 0.75, + "realized depth 0 request calibration should reflect observed 0.5 vs predicted 0.95, got {depth0_request_cal}", + ); + for depth in 2..7 { + let geometric_prior = 0.5f64.powi(depth as i32 + 1); + let prefix_mean = scheduler.forecasts.request_prefix_mean(handle, depth); + assert!( + prefix_mean > geometric_prior + 0.25, + "depth {depth} raw prefix forecast should track observed GPU confidence above geometric prior {geometric_prior}, got {prefix_mean}", + ); + assert!( + f64::from(scheduler.forecasts.population[depth]) > geometric_prior + 0.05, + "depth {depth} population prior should advance from GPU confidence, got {}", + scheduler.forecasts.population[depth], + ); + assert!( + (scheduler.forecasts.calibration_factor(depth) - depth0_global_cal).abs() < 1e-12, + "unverified depth {depth} global calibration must inherit verified depth 0 ({depth0_global_cal}) rather than calibrating against unverified realized zeros, got {}", + scheduler.forecasts.calibration_factor(depth), + ); + assert!( + (scheduler.forecasts.request_calibration_factor(handle, depth) - depth0_request_cal).abs() < 1e-12, + "unverified depth {depth} request calibration must inherit verified depth 0 ({depth0_request_cal}) rather than calibrating against unverified realized zeros, got {}", + scheduler.forecasts.request_calibration_factor(handle, depth), + ); + } + assert!( + scheduler.forecasts.request_calibration_factor(handle, 0) < 0.75, + "realized depth 0 request calibration should reflect observed 0.5 vs predicted 0.95, got {}", + scheduler.forecasts.request_calibration_factor(handle, 0), + ); + assert_eq!(scheduler.forecasts.surplus_depth_one_entries(), 16); + assert_eq!(scheduler.forecasts.surplus_deep_entries(), 0); +} + #[test] #[ignore = "CPU planning benchmark; run in release mode with --ignored --nocapture --test-threads=1"] fn benchmark_packed_planning() { diff --git a/helios/src/scheduler/rounds.rs b/helios/src/scheduler/rounds.rs index cf5aeaceb..e632cb67b 100644 --- a/helios/src/scheduler/rounds.rs +++ b/helios/src/scheduler/rounds.rs @@ -427,6 +427,17 @@ impl Forecasts { ) } + #[cfg(test)] + pub(super) fn request_prefix_mean(&self, request: RequestHandle, depth: usize) -> f64 { + self.requests[request.slot as usize] + .as_ref() + .filter(|forecast| forecast.request == request) + .map_or_else( + || f64::from(self.population[depth]), + |forecast| forecast.prefixes[depth].mean(), + ) + } + pub(super) fn observe_surplus(&mut self, actual: Vec, forecast: Vec) { self.surplus.push(actual, forecast); } @@ -665,10 +676,12 @@ impl RequestScheduler { let mut forecast = self.forecasts.requests[lane.request.slot as usize].take() .filter(|forecast| forecast.request == lane.request) .unwrap_or_else(|| Forecast::new(lane.request, &self.forecasts.population, generated)); - let depth_limit = lane.tokens.saturating_sub(1).min(step.draft_tokens); - let cal_factors = if gpu_confidence && depth_limit >= 1 { + let conf_limit = step.draft_tokens.min(confidence[row].len()).min(forecast.prefixes.len()); + let realized_limit = lane.tokens.saturating_sub(1).min(conf_limit); + let observe_limit = if gpu_confidence { conf_limit } else { realized_limit }; + let cal_factors = if gpu_confidence && realized_limit >= 1 { let mut cumulative_factor = 1.0f64; - (0..depth_limit) + (0..realized_limit) .map(|depth| { cumulative_factor *= forecast.calibration_factor(depth, &self.forecasts.calibration); cumulative_factor @@ -679,7 +692,7 @@ impl RequestScheduler { }; let mut host_pred = if !cal_factors.is_empty() { let mut bound = 1.0f64; - (0..depth_limit).map(|depth| { + (0..realized_limit).map(|depth| { let calibrated = forecast.prefixes[depth].mean() * cal_factors[depth]; bound = bound.min(calibrated.clamp(0.0, 1.0)); bound as f32 @@ -688,21 +701,23 @@ impl RequestScheduler { Vec::new() }; let mut actual_cal = if !host_pred.is_empty() { - Vec::with_capacity(depth_limit) + Vec::with_capacity(realized_limit) } else { Vec::new() }; - let mut step_confidences = Vec::with_capacity(depth_limit); + let mut step_confidences = Vec::with_capacity(realized_limit); let mut prefix = 1.0f32; let mut actual_bound = 1.0f64; - for depth in 0..depth_limit { + for depth in 0..observe_limit { let step_c = confidence[row][depth]; - step_confidences.push(step_c); prefix *= step_c; - if !host_pred.is_empty() { - let calibrated = f64::from(prefix) * cal_factors[depth]; - actual_bound = actual_bound.min(calibrated.clamp(0.0, 1.0)); - actual_cal.push(actual_bound as f32); + if depth < realized_limit { + step_confidences.push(step_c); + if !host_pred.is_empty() { + let calibrated = f64::from(prefix) * cal_factors[depth]; + actual_bound = actual_bound.min(calibrated.clamp(0.0, 1.0)); + actual_cal.push(actual_bound as f32); + } } forecast.prefixes[depth].observe(f64::from(prefix), generated); if gpu_confidence { self.forecasts.observe_population(depth, prefix); } diff --git a/ignition/components/logprobs.py b/ignition/components/logprobs.py index 7efbcb03e..5f1d091ea 100644 --- a/ignition/components/logprobs.py +++ b/ignition/components/logprobs.py @@ -16,6 +16,7 @@ ) _VOCAB_TILE = 1024 +_TILE_GROUP = 16 # A global top-20 token is in its tile's top 20; round up to 32 for the merge sort. _TILE_CANDIDATES = triton.next_power_of_2(MAX_TOP_LOGPROBS) _REDUCTION_WARPS = 4 @@ -55,17 +56,23 @@ def _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, @triton.jit def _statistics(Logits, Records, Frame, Requested, Slots, Epochs, Live, Stats, V: tl.constexpr, WIDTH: tl.constexpr, TILES: tl.constexpr, - SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr): - row, col, tile = tl.program_id(0), tl.program_id(1), tl.program_id(2) + SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr, + TILE_GROUP: tl.constexpr): + row, col, group = tl.program_id(0), tl.program_id(1), tl.program_id(2) _, _, valid = _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, SLOTS, FIELDS) - if valid: - ids = tile * BLOCK + tl.arange(0, BLOCK) - x = tl.load(Logits + (row * WIDTH + col) * V + ids, ids < V, other=-float("inf")).to(tl.float32) - maximum = tl.max(x, 0) - mass = tl.sum(tl.exp(x - tl.where(maximum == -float("inf"), 0., maximum)), 0) - index = (row * WIDTH + col) * TILES + tile - tl.store(Stats + index * 2, maximum) - tl.store(Stats + index * 2 + 1, mass) + if not valid: + return + base_tile = group * TILE_GROUP + for step in tl.static_range(TILE_GROUP): + tile = base_tile + step + if tile < TILES: + ids = tile * BLOCK + tl.arange(0, BLOCK) + x = tl.load(Logits + (row * WIDTH + col) * V + ids, ids < V, other=-float("inf")).to(tl.float32) + maximum = tl.max(x, 0) + mass = tl.sum(tl.exp(x - tl.where(maximum == -float("inf"), 0., maximum)), 0) + index = (row * WIDTH + col) * TILES + tile + tl.store(Stats + index * 2, maximum) + tl.store(Stats + index * 2 + 1, mass) @triton.jit @@ -88,18 +95,24 @@ def _normalization(Records, Frame, Requested, Slots, Epochs, Live, Stats, Lse, def _candidates(Logits, Records, Frame, Requested, Slots, Epochs, Live, Lse, Keys, V: tl.constexpr, WIDTH: tl.constexpr, TILES: tl.constexpr, SLOTS: tl.constexpr, FIELDS: tl.constexpr, BLOCK: tl.constexpr, - CANDIDATES: tl.constexpr): - row, col, tile = tl.program_id(0), tl.program_id(1), tl.program_id(2) + CANDIDATES: tl.constexpr, TILE_GROUP: tl.constexpr): + row, col, group = tl.program_id(0), tl.program_id(1), tl.program_id(2) _, _, valid = _position(Records, Frame, Requested, Slots, Epochs, Live, row, col, SLOTS, FIELDS) - if valid: - ids = tile * BLOCK + tl.arange(0, BLOCK) - x = tl.load(Logits + (row * WIDTH + col) * V + ids, ids < V, other=-float("inf")).to(tl.float32) - x -= tl.load(Lse + row * WIDTH + col) - # Rank the reported FP32 values, including ties introduced by subtraction. - keys = tl.sort(tl.where(ids < V, _sort_key(x, ids), 0), descending=True) - index = (row * WIDTH + col) * TILES + tile - k = tl.arange(0, BLOCK) - tl.store(Keys + index * CANDIDATES + k, keys, k < CANDIDATES) + if not valid: + return + lse = tl.load(Lse + row * WIDTH + col) + base_tile = group * TILE_GROUP + k = tl.arange(0, BLOCK) + for step in tl.static_range(TILE_GROUP): + tile = base_tile + step + if tile < TILES: + ids = tile * BLOCK + tl.arange(0, BLOCK) + x = tl.load(Logits + (row * WIDTH + col) * V + ids, ids < V, other=-float("inf")).to(tl.float32) + x -= lse + # Rank the reported FP32 values, including ties introduced by subtraction. + keys = tl.sort(tl.where(ids < V, _sort_key(x, ids), 0), descending=True) + index = (row * WIDTH + col) * TILES + tile + tl.store(Keys + index * CANDIDATES + k, keys, k < CANDIDATES) @triton.jit @@ -144,6 +157,7 @@ def __init__(self, logits, completion, slots, epochs, live, frame): if not 1 <= width <= completion.token_capacity: raise ValueError("raw logprob width exceeds completion token capacity") tiles = triton.cdiv(vocab, _VOCAB_TILE) + tile_groups = triton.cdiv(tiles, _TILE_GROUP) self.logits = logits self.row_inputs = (slots, epochs, live) self.layout = { @@ -156,11 +170,12 @@ def __init__(self, logits, completion, slots, epochs, live, frame): common = (logits, completion.records, frame, completion.requested, slots, epochs, live) dimensions = (vocab, width, tiles, completion.records.shape[1], completion.records.shape[2]) self._preparation = ( - (_statistics, (*common, self.stats, *dimensions, _VOCAB_TILE), (batch, width, tiles), _REDUCTION_WARPS), + (_statistics, (*common, self.stats, *dimensions, _VOCAB_TILE, _TILE_GROUP), + (batch, width, tile_groups), _REDUCTION_WARPS), (_normalization, (*common[1:], self.stats, self.lse, *dimensions[1:], triton.next_power_of_2(tiles)), (batch, width, 1), _REDUCTION_WARPS), (_candidates, (*common, self.lse, self.keys, *dimensions, _VOCAB_TILE, - _TILE_CANDIDATES), (batch, width, tiles), _REDUCTION_WARPS), + _TILE_CANDIDATES, _TILE_GROUP), (batch, width, tile_groups), _REDUCTION_WARPS), (_finish, (*common, self.lse, self.keys, completion.logprobs, completion.token_ids, completion.token_id_counts, *dimensions, triton.next_power_of_2(tiles * _TILE_CANDIDATES), _TILE_CANDIDATES, diff --git a/ignition/components/readiness.py b/ignition/components/readiness.py index 35658b7ca..db7309e7e 100644 --- a/ignition/components/readiness.py +++ b/ignition/components/readiness.py @@ -25,6 +25,14 @@ def _timestamp(timestamps, frame, STRIDE: tl.constexpr, SLOT: tl.constexpr): tl.store(timestamps + index * STRIDE + SLOT, globaltimer()) +@triton.jit +def _timestamp_pair(timestamps, frame, STRIDE: tl.constexpr, SLOT0: tl.constexpr, SLOT1: tl.constexpr): + index = tl.load(frame) + now = globaltimer() + tl.store(timestamps + index * STRIDE + SLOT0, now) + tl.store(timestamps + index * STRIDE + SLOT1, now) + + def record_timestamp(timestamps, frame, slot): _timestamp[(1,)](timestamps, frame, timestamps.shape[1], slot, num_warps=1) @@ -38,10 +46,12 @@ def wait_for_readiness(source, event, timings, frame, interval, barrier_input, b status, = driver.cuStreamWaitEvent(driver.CUstream(stream.cuda_stream), driver.CUevent(event), flags) if int(status): raise RuntimeError(f"embedding readiness wait failed: {status}") - record_timestamp(timings, frame, 3 * interval + 1) if barrier_handle > 0: + record_timestamp(timings, frame, 3 * interval + 1) _BARRIERS[barrier_handle - 1](barrier_input, barrier_output) - record_timestamp(timings, frame, 3 * interval + 2) + record_timestamp(timings, frame, 3 * interval + 2) + else: + _timestamp_pair[(1,)](timings, frame, timings.shape[1], 3 * interval + 1, 3 * interval + 2, num_warps=1) class ReadinessTimings: diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index de4ce78cd..9d11d19d8 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -909,7 +909,7 @@ def prepare_many(self, functions, signatures, *, progress=None, coordinator=None """ # Compiler workers own parallel compilation; artifact binding needs no second worker pool. lock = nullcontext() if _locked else self._publication_lock(coordinator) - with lock, torch._inductor.config.patch(compile_threads=1): + with lock, torch._inductor.config.patch(compile_threads=min(24, os.cpu_count() or 1)): return self._prepare_many(functions, signatures, progress=progress, coordinator=coordinator, materialize=materialize, warmup=warmup, before_run=before_run, stream=stream) diff --git a/ignition/preparation/capture.py b/ignition/preparation/capture.py index c36a904c5..c1f868f87 100644 --- a/ignition/preparation/capture.py +++ b/ignition/preparation/capture.py @@ -167,6 +167,8 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, warm.synchronize() stage.update(advance=1) stream.wait_stream(warm) + release_unused() + torch.cuda.empty_cache() ordered_names = _capture_order(names, compiled, coordinator) retired = False with phase(progress, label, total=len(names)) as stage: diff --git a/ignition/preparation/compile_pool.py b/ignition/preparation/compile_pool.py index 9310c88f3..57d34496b 100644 --- a/ignition/preparation/compile_pool.py +++ b/ignition/preparation/compile_pool.py @@ -21,8 +21,8 @@ # Device memory one compiler worker can hold: its CUDA context plus Inductor's constant folding. _WORKER_DEVICE_BYTES = 2 << 30 -# A discrete GPU's worker holds only device memory, about 0.7 GiB for Kimi K3's 93-layer forwards. -_DISCRETE_WORKER_DEVICE_BYTES = 1 << 30 +# A discrete GPU's worker holds only device memory, measured at 672 MiB on GB300. +_DISCRETE_WORKER_DEVICE_BYTES = 704 << 20 _DEFAULT_MAX_WORKERS = 8 @@ -46,19 +46,20 @@ def compiler_resources(device, *, headroom_bytes=0, options=None, compile_worker shared = torch.cuda.get_device_properties(device).is_integrated device_bytes = _WORKER_DEVICE_BYTES if shared else _DISCRETE_WORKER_DEVICE_BYTES worker_bytes = host_memory.FORWARD_WORKER_BYTES + (device_bytes if shared else 0) - headroom = max(host_memory._HEADROOM_BYTES, headroom_bytes if shared else 0) + compile_reserve = min(headroom_bytes, 1024 << 20) + headroom = max(host_memory._HEADROOM_BYTES, compile_reserve if shared else 0) max_workers = limit if compile_workers is not None else min(limit, _DEFAULT_MAX_WORKERS) available = host_memory.available_bytes() free = device_memory_info(device)[0] if shared: available = min(available, free) if (available - headroom < max_workers * worker_bytes if shared - else free - headroom_bytes < max_workers * device_bytes): + else free - compile_reserve < max_workers * device_bytes): torch.cuda.empty_cache() free = device_memory_info(device)[0] if shared: available = min(host_memory.available_bytes(), free) - capacity = max(0, (free - headroom_bytes) // device_bytes) + capacity = max(0, (free - compile_reserve) // device_bytes) if compile_workers is None: capacity = min(_DEFAULT_MAX_WORKERS, capacity) return CompilerResources(capacity, available, limit, worker_bytes, headroom) @@ -136,8 +137,11 @@ def __init__(self, device, *, headroom_bytes=0, options=None, compile_workers=No if type(workers) is not int or workers < 1: raise ValueError("forward compiler pool requires a positive admitted worker count") self.workers = workers - # Nested Inductor pools would escape the host's admitted process budget. - self.options = dict(options, compile_threads=1) + # Partition CPU compile threads across workers and force Inductor subprocess workers + # because CompilePool runs inside spawned SubprocPool processes. + cpu_count = os.cpu_count() if hasattr(os, "cpu_count") else None + inner_threads = max(1, min(8, (cpu_count or 1) // max(1, self.workers))) + self.options = dict(options, compile_threads=inner_threads, worker_start_method="subprocess") def submit(self, forward, path): from .forward_metadata import dumps diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 02bcb0b05..68deeb2c0 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -11,6 +11,7 @@ import json import mmap import os +import sys from .runtime_core import _Cuda @@ -446,6 +447,9 @@ def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False): if pointer != address: raise OSError(C.get_errno(), f"cannot reserve native core host address {address:#x}") try: + if sys.platform == "linux": + # Best-effort MADV_HUGEPAGE (14) hint before pinning; ignore errors if THP is unavailable. + self.libc.madvise(C.c_void_p(address), C.c_size_t(extent), C.c_int(14)) if lock and self.libc.mlock(C.c_void_p(address), C.c_size_t(extent)): raise OSError(C.get_errno(), f"cannot lock {extent} bytes of mapped host storage; raise RLIMIT_MEMLOCK") cuda.call("cuMemHostRegister_v2", C.c_void_p(address), C.c_size_t(extent), C.c_uint(2)) diff --git a/tests/preparation/test_forward_compile_options.py b/tests/preparation/test_forward_compile_options.py index 762bf6c7e..a8f602ab2 100644 --- a/tests/preparation/test_forward_compile_options.py +++ b/tests/preparation/test_forward_compile_options.py @@ -6,6 +6,7 @@ from concurrent.futures import Future from contextlib import contextmanager, nullcontext from inspect import signature +import os from pathlib import Path from types import ModuleType, SimpleNamespace import sys @@ -278,7 +279,8 @@ def test_partial_compile_options_merge_over_defaults_across_entry_points(caches, assert pool.options['reorder_for_peak_memory'] is False assert pool.options['memory_planning'] is True assert pool.options['memory_pool'] == 'combined' - assert pool.options['compile_threads'] == 1 + assert pool.options['compile_threads'] == max(1, min(8, (os.cpu_count() or 1) // max(1, pool.workers))) + assert pool.options['worker_start_method'] == 'subprocess' observed = [] original_standalone = torch._inductor.standalone_compile