From d3bd1460f1ff265a0c80d9c63b4db9bccdb1ca7c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 17 Oct 2026 11:18:40 +0200 Subject: [PATCH] perf(serve): online hill-climbing controller of the PCIe share (LELEKA_PCIE_AUTO=on, off by default) Co-Authored-By: Claude Sonnet 5.5 --- .../qwen_forward/original_serve_residency.rs | 98 ++++++++++++++++++- 1 file changed, 97 insertions(+), 1 deletion(-) diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index b8133e30..07b52246 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -393,6 +393,88 @@ impl SpanCache { } } +/// `LELEKA_PCIE_AUTO=on` (claude/decode-parity): a hill-climbing controller of the PCIe share. The static share is a +/// balance between the PCIe leg and the CPU pool of a layer, and the best value moves with the staging mode, the link and +/// the hit rate. Rounds are timed from one `apply_pending` to the next; the cost of a round is its time per +/// (misses + 40) entries (the entries the PCIe/CPU legs carry, plus a floor for the fixed work). Levels are shares in 256ths; +/// every `EXPLORE_EVERY` rounds the neighbours of the incumbent are tried for `TRIAL` rounds each and the cheaper one (by +/// EMA) becomes the incumbent. Only the split changes, never what an expert computes. +#[derive(Debug)] +pub(crate) struct PcieAuto { + levels: Vec, + ema: Vec>, + incumbent: usize, + trying: usize, + left: u32, + since_explore: u32, + next_probe_up: bool, + last: Option, + misses: u64, +} +impl PcieAuto { + const TRIAL: u32 = 6; + const EXPLORE_EVERY: u32 = 30; + pub(crate) fn from_environment(start_num: u32) -> Option { + if !std::env::var("LELEKA_PCIE_AUTO").is_ok_and(|v| v == "on") || start_num == 0 { + return None; + } + let levels: Vec = (2..=10).map(|i| i * 16).collect(); // 0.125 .. 0.625 + let incumbent = levels.iter().enumerate().min_by_key(|(_, &l)| l.abs_diff(start_num)).map_or(0, |(i, _)| i); + Some(Self { + ema: vec![None; levels.len()], + levels, + incumbent, + trying: incumbent, + left: Self::TRIAL, + since_explore: 0, + next_probe_up: false, + last: None, + misses: 0, + }) + } + pub(crate) fn pcie_num(&self) -> u32 { + self.levels[self.trying] + } + pub(crate) fn add_misses(&mut self, n: usize) { + self.misses += n as u64; + } + /// Round boundary: score the round that just ended under `trying`, then pick the level of the next one. + pub(crate) fn round(&mut self) { + let now = std::time::Instant::now(); + let ended = self.last.replace(now); + let misses = std::mem::take(&mut self.misses); + let Some(then) = ended else { return }; + if misses == 0 { + return; + } + let cost = now.duration_since(then).as_secs_f64() * 1e3 / (misses as f64 + 40.0 * 48.0); + let slot = &mut self.ema[self.trying]; + *slot = Some(slot.map_or(cost, |old| 0.7 * old + 0.3 * cost)); + self.left = self.left.saturating_sub(1); + self.since_explore += 1; + if self.trying != self.incumbent { + if self.left == 0 { + // the trial ended: keep the cheaper of the two + let (a, b) = (self.ema[self.trying].unwrap_or(f64::MAX), self.ema[self.incumbent].unwrap_or(f64::MAX)); + if a < b { + self.incumbent = self.trying; + } + self.trying = self.incumbent; + self.left = 0; + } + } else if self.since_explore >= Self::EXPLORE_EVERY { + self.since_explore = 0; + let target = if self.next_probe_up { self.incumbent + 1 } else { self.incumbent.wrapping_sub(1) }; + self.next_probe_up = !self.next_probe_up; + if target < self.levels.len() { + self.ema[target] = None; + self.trying = target; + self.left = Self::TRIAL; + } + } + } +} + /// What survives requests: the routed counts of the adaptive tier (`drive.d.usage`) and the counters. #[derive(Debug, Default)] pub(crate) struct ResidencyState { @@ -402,6 +484,8 @@ pub(crate) struct ResidencyState { /// experts, as `tools/make_profile.py` reads them (layer i32, k i32, k ids i32, k weights f32). routing: Option>, pub(crate) spans: SpanCache, + pub(crate) pcie_auto: Option, + pcie_auto_checked: bool, } impl ResidencyState { pub(crate) fn new(config: &ExpertTierConfig) -> Self { @@ -412,6 +496,8 @@ impl ResidencyState { usage: if config.adaptive() { vec![0.0; LAYERS * EXPERTS] } else { Vec::new() }, stats: ResidencyStats::default(), routing, + pcie_auto: None, + pcie_auto_checked: false, spans: SpanCache::default(), } } @@ -536,9 +622,12 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { TOP_K, sink.plan_capacity(), |e| cache.resident_slot(layer, e as usize), - self.pcie_num, + self.state.pcie_auto.as_ref().map_or(self.pcie_num, PcieAuto::pcie_num), sink.staging_capacity(), )?; + if let Some(auto) = self.state.pcie_auto.as_mut() { + auto.add_misses(split.kinds.iter().filter(|&&k| k != 0).count()); + } super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); drop(profile_split); let profile_spans = super::original_serve_profile::span("pool.spans"); @@ -569,6 +658,13 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { self.cpu.run_entries(rows, sink, Some(&include)) } fn apply_pending(&mut self) -> Result<()> { + if !self.state.pcie_auto_checked { + self.state.pcie_auto_checked = true; + self.state.pcie_auto = PcieAuto::from_environment(self.pcie_num); + } + if let Some(auto) = self.state.pcie_auto.as_mut() { + auto.round(); + } // The swaps issued beside the previous commit land before this window (`apply_pending(true)`): their copies // would otherwise read host memory while the CPU pool streams its experts (job 803: the overlap costs the CPU // share more than the wait), and the resident set no longer depends on when the copies finished.