diff --git a/architecture.json b/architecture.json index 96a4d87a..fa066761 100644 --- a/architecture.json +++ b/architecture.json @@ -173,7 +173,6 @@ {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the binding (lazy PLE reader); the gate pattern matches the type name"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises the instance field `ple_reader` of one ModelBinding; the gate pattern matches the type name"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "kept for now: the adaptive-tier tuning tuple is derived once from the process settings capture and emits the invalid-LELEKA_ADAPT_DECAY line once; it is read from three files (cross_layer_potential, source_spans, this one), so passing it needs a field on the residency state; not moved in this change (STRA-338 follow-up)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "kept: DBG_T0, the epoch of the bring-up trace timestamps (dbg_el()); diagnostics only, called from trace macros in many files that hold no common owner, never read by serving logic"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the session; the gate pattern matches the type name"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises an instance field of one session; the gate pattern matches the type name"}, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs index 39c235fd..daa41b5a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs @@ -104,6 +104,7 @@ pub(crate) struct ExpertTierConfig { /// `--adapt-every` (4) and `--adapt-swaps` (96); either 0 turns the adaptive tier off. pub(crate) adapt_every: u32, pub(crate) adapt_swaps: u32, + pub(crate) adapt_tuning: AdaptTuning, /// `!--no-prefill-borrow` (the loan is taken only with a profile, as in the Original). pub(crate) prefill_borrow: bool, /// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`. @@ -159,9 +160,6 @@ pub(in crate::qwen_forward) struct Swap { pub(in crate::qwen_forward) outgoing: usize, } -/// Default of `LELEKA_ADAPT_DECAY` (generate.cpp's constant). -const ADAPT_DECAY_DEFAULT: f32 = 0.7; - /// Counters of the tier (the Original's `R4 expert-cache hits` / `adaptive tier` report lines). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct ResidencyStats { @@ -261,6 +259,7 @@ pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> { pub(in crate::qwen_forward) pcie_num: u32, pub(in crate::qwen_forward) adapt_every: u32, pub(in crate::qwen_forward) adapt_swaps: usize, + pub(in crate::qwen_forward) adapt_tuning: AdaptTuning, /// The route tail skip rank of this decode phase (0 = off; `effective_tail_rank`). pub(in crate::qwen_forward) tail_rank: u32, /// `layer * 512 + expert` -> the expert's pages are page-locked (`MappedExpertBank::locked_experts`); empty = @@ -282,10 +281,12 @@ pub(crate) use tail_skip_rank::set_tail_skip_arm; pub(in crate::qwen_forward) use tail_skip_rank::split_group; #[cfg(test)] pub(in crate::qwen_forward) use tail_skip_rank::split_group_tail; +mod adapt_tuning; mod split_group_pcie; +pub(crate) use adapt_tuning::AdaptTuning; +pub(in crate::qwen_forward) use adapt_tuning::SwapCap; #[cfg(test)] -use split_group_pcie::adapt_decay; -use split_group_pcie::adapt_tuning; +use adapt_tuning::adapt_decay; #[cfg(test)] use split_group_pcie::choose_swaps_reference; pub(in crate::qwen_forward) use split_group_pcie::pcie_locked_only; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/adapt_tuning.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/adapt_tuning.rs new file mode 100644 index 00000000..39ebef8b --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/adapt_tuning.rs @@ -0,0 +1,58 @@ +//! The experiment knobs of the adaptive tier, parsed once into the tier configuration: the least routed count a +//! missing expert needs, the count lead over the victim, and the decay of the counts per adaptation. + +use super::TieOrder; +use crate::settings::MemorySettings; + +/// Default of `LELEKA_ADAPT_DECAY` (generate.cpp's constant). +const ADAPT_DECAY_DEFAULT: f32 = 0.7; + +/// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in), +/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per +/// adaptation). The defaults are generate.cpp's constants. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct AdaptTuning { + pub(crate) min_count: f32, + pub(crate) margin: f32, + pub(crate) decay: f32, +} + +impl Default for AdaptTuning { + fn default() -> Self { + Self { min_count: 2.0, margin: 1.5, decay: ADAPT_DECAY_DEFAULT } + } +} + +impl AdaptTuning { + /// The tuning the operator chose; an invalid decay is replaced by the default with one line on the operator log. + pub(crate) fn from_settings(memory: &MemorySettings) -> Self { + let (decay, line) = adapt_decay(memory.adapt_decay.as_deref()); + if let Some(line) = line { + eprintln!("leleka-serve {line}"); + } + Self { min_count: memory.adapt_min_count, margin: memory.adapt_margin, decay } + } +} + +/// How many swaps one adaptation may make, in which order equal gains compete for them, and under which tuning. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct SwapCap { + pub(in crate::qwen_forward) max_swaps: usize, + pub(in crate::qwen_forward) ties: TieOrder, + pub(in crate::qwen_forward) tuning: AdaptTuning, +} + +/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a +/// few hundred adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. +/// Anything else (out of range, not a finite number) falls back to the default, with the line to log. Unset gives the +/// default silently. +pub(super) fn adapt_decay(raw: Option<&str>) -> (f32, Option) { + let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) }; + match text.trim().parse::() { + Ok(v) if v.is_finite() && (0.0..=1.0).contains(&v) => (v, None), + _ => ( + ADAPT_DECAY_DEFAULT, + Some(format!("LELEKA_ADAPT_DECAY={text:?} is outside 0..1; using {ADAPT_DECAY_DEFAULT}")), + ), + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/cross_layer_potential.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/cross_layer_potential.rs index dc5394b9..2b8aa5e7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/cross_layer_potential.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/cross_layer_potential.rs @@ -7,7 +7,7 @@ //! mass of the experts that are not resident, and the total gain of the swaps that would be made (a) inside each //! layer (uncapped, the present rule) and (b) over all layers together (a slot may move to another layer). Nothing //! here changes a swap; the profile prints the average per adaptation. -use super::{EXPERTS, LAYERS, adapt_tuning}; +use super::{AdaptTuning, EXPERTS, LAYERS}; type Entry = (f32, usize); @@ -37,12 +37,12 @@ fn pairing(mut cand: Vec, mut vict: Vec, margin: f32) -> (f64, usi } /// Adds the estimate of one adaptation; a no-op unless the profile and its tier-cross switch are on. -pub(super) fn record(usage: &[f32], resident: impl Fn(usize, usize) -> bool) { +pub(super) fn record(usage: &[f32], resident: impl Fn(usize, usize) -> bool, tuning: AdaptTuning) { use super::super::original_serve_profile::{add, enabled}; if !enabled() || !crate::settings::process().diagnostics.profile_tier_cross || usage.len() != LAYERS * EXPERTS { return; } - let (min_count, margin, _) = adapt_tuning(); + let AdaptTuning { min_count, margin, .. } = tuning; let layers = split(usage, &resident, min_count); let (mut within, mut n_within) = (0.0, 0); for (cand, vict) in &layers { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs index 0f0b7f46..631cc985 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans.rs @@ -5,8 +5,7 @@ use super::{ CpuExpertPool, EXPERTS, Error, GpuExpertPool, GroupSplit, LAYERS, MappedExpertBank, ModelBinding, MoeWeightCache, OriginalGpuStream, OriginalServePool, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyPcieSource, PcieAuto, PcieLag, PcieSplitPolicy, Rc, ResidentExpertBankSpan, Result, RoutedGroup, SpanCache, StrataPcieAuto, - Swap, SwapSources, TOP_K, TieOrder, adapt_tuning, choose_swaps_by, driver_error, span_cache_enabled, - split_group_pcie, + Swap, SwapCap, SwapSources, TOP_K, TieOrder, choose_swaps_by, driver_error, span_cache_enabled, split_group_pcie, }; /// The source spans of `experts` of `layer`, in order: from the cache when seen before, else through the CPU @@ -131,7 +130,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { self.cache.arm_swaps().map_err(|e| driver_error(&e))?; drop(p); let _p = super::super::original_serve_profile::span("adapt.decay"); - let decay = adapt_tuning().2; + let decay = self.adapt_tuning.decay; for value in &mut self.state.usage { *value *= decay; } @@ -291,10 +290,11 @@ impl<'ctx> GpuExpertPool<'_, '_, 'ctx> { let cache = &*self.cache; let p = super::super::original_serve_profile::span("adapt.choose"); let ties = self.tie_order(); - let swaps = - choose_swaps_by(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), (self.adapt_swaps, ties)); + let cap = SwapCap { max_swaps: self.adapt_swaps, ties, tuning: self.adapt_tuning }; + let swaps = choose_swaps_by(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), cap); drop(p); - super::cross_layer_potential::record(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some()); + let resident = |l, e| cache.resident_slot(l, e).is_some(); + super::cross_layer_potential::record(&self.state.usage, resident, self.adapt_tuning); let p = super::super::original_serve_profile::span("adapt.queue"); for swap in &swaps { let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs index b390084a..30a526c0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie.rs @@ -3,8 +3,8 @@ //! Pure planning over ids and residency; it touches no device and no source. use super::{ - ADAPT_DECAY_DEFAULT, EXPERTS, Error, GroupSplit, LAYERS, MAX_WINDOW_ENTRIES, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, - OriginalVerifyGpuPlan, ResidencyStats, Result, Swap, TieOrder, + AdaptTuning, EXPERTS, Error, GroupSplit, LAYERS, MAX_WINDOW_ENTRIES, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, + OriginalVerifyGpuPlan, ResidencyStats, Result, Swap, SwapCap, TieOrder, }; /// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged, @@ -203,38 +203,6 @@ pub(in crate::qwen_forward) fn pcie_locked_only() -> bool { crate::settings::process().memory.pcie_locked_only } -/// Experiment knobs of the adaptive tier (claude/decode-parity; the defaults are generate.cpp's constants): -/// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in), -/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per -/// adaptation). -pub(super) fn adapt_tuning() -> (f32, f32, f32) { - static TUNING: std::sync::OnceLock<(f32, f32, f32)> = std::sync::OnceLock::new(); - *TUNING.get_or_init(|| { - let memory = &crate::settings::process().memory; - let decay = adapt_decay(memory.adapt_decay.as_deref()); - if let Some(line) = decay.1 { - eprintln!("leleka-serve {line}"); - } - (memory.adapt_min_count, memory.adapt_margin, decay.0) - }) -} - -/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a -/// few hundred -/// adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. Anything else -/// (out of range, -/// not a finite number) falls back to the default, with the line to log. Unset gives the default silently. -pub(super) fn adapt_decay(raw: Option<&str>) -> (f32, Option) { - let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) }; - match text.trim().parse::() { - Ok(v) if v.is_finite() && (0.0..=1.0).contains(&v) => (v, None), - _ => ( - ADAPT_DECAY_DEFAULT, - Some(format!("LELEKA_ADAPT_DECAY={text:?} is outside 0..1; using {ADAPT_DECAY_DEFAULT}")), - ), - } -} - /// generate.cpp `adapt`'s ranking over `usage[l * 512 + e]`: per layer the non-resident experts routed at /// least twice (most first) against the resident ones (least first), pairwise while /// `cand >= vict + 1.5`; all layers' swaps by gain, the best `max_swaps`. Ties keep ascending expert / layer @@ -243,17 +211,17 @@ pub(in crate::qwen_forward) fn choose_swaps( usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize, + tuning: AdaptTuning, ) -> Vec { - choose_swaps_by(usage, resident, (max_swaps, TieOrder::LowLayerFirst)) + choose_swaps_by(usage, resident, SwapCap { max_swaps, ties: TieOrder::LowLayerFirst, tuning }) } -/// `choose_swaps` with the order in which equal-gain swaps compete for the `max_swaps` cap (`cap`.1). +/// `choose_swaps` with the order in which equal-gain swaps compete for the `max_swaps` cap (`cap.ties`). pub(in crate::qwen_forward) fn choose_swaps_by( usage: &[f32], resident: impl Fn(usize, usize) -> bool, - cap: (usize, TieOrder), + cap: SwapCap, ) -> Vec { - let (max_swaps, ties) = cap; - let (min_count, margin, _) = adapt_tuning(); + let SwapCap { max_swaps, ties, tuning: AdaptTuning { min_count, margin, .. } } = cap; let mut swaps = Vec::new(); if usage.len() != LAYERS * EXPERTS { return swaps; @@ -323,8 +291,9 @@ pub(super) fn choose_swaps_reference( usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize, + tuning: AdaptTuning, ) -> Vec { - let (min_count, margin, _) = adapt_tuning(); + let AdaptTuning { min_count, margin, .. } = tuning; let mut swaps = Vec::new(); if usage.len() != LAYERS * EXPERTS { return swaps; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank.rs index 0124f481..5574461c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank.rs @@ -2,10 +2,11 @@ //! defaults, validation, `LELEKA_ORIGINAL_SERVE_*` switches) and the route tail-skip rank of a decode phase. use super::{ - AtomicU32, EXPERTS, EnvSource, Error, ExpertTierConfig, GroupSplit, LAYERS, Ordering, OriginalExpertCache, PathBuf, - PcieMode, PcieSplitPolicy, Result, RoutedGroup, TAIL_SKIP_RANK, TAIL_UNRESOLVED, TOP_K, VERIFIER_ASSEMBLY_MIB, - split_group_pcie, strata_pcie_auto, + AdaptTuning, AtomicU32, EXPERTS, EnvSource, Error, ExpertTierConfig, GroupSplit, LAYERS, Ordering, + OriginalExpertCache, PathBuf, PcieMode, PcieSplitPolicy, Result, RoutedGroup, TAIL_SKIP_RANK, TAIL_UNRESOLVED, + TOP_K, VERIFIER_ASSEMBLY_MIB, split_group_pcie, strata_pcie_auto, }; +use crate::settings::MemorySettings; /// The tail-skip rank in force (0 = off): the environment, read once, unless a replay arm set it. pub(crate) fn tail_skip_rank() -> u32 { @@ -77,21 +78,14 @@ impl ExpertTierConfig { per_layer: false, profile: None, reserve_mib: 700, - // measured (jobs 989/990/988): the per-request verifier needs ~450 MiB, so 1024 left ~550 MiB idle - // (180k smoke included); 300 gives the auto-sized cache ~+330 slots. 5090, 5 x 245k session - // (speedtrain-ab): with 300 the card never had less than 563 MiB free (vanilla runs down to 315), so - // 130 would be safe on the card (E: +87 slots), but the first slots-footprint A/B showed the Context - // BUDGET is a second ceiling the planner now respects (`usable_room`); 130 stays an opt-in - // (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it. decode_reserve_mib: 300, - // the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling - // (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at auto-sized cache, equal at 2048 slots) pcie_frac: 0.45, pcie_frac_set: false, pcie_mode: PcieMode::Auto, strata_pcie_auto: None, adapt_every: 4, adapt_swaps: 96, + adapt_tuning: AdaptTuning::default(), prefill_borrow: true, resident_budget_gib: 0.0, seed_swaps: 0, @@ -212,6 +206,7 @@ impl ExpertTierConfig { if let Some(v) = serve_var(env, "ADAPT_SWAPS") { self.adapt_swaps = v.parse().map_err(|_| Error::InvalidDimension)?; } + self.adapt_tuning = AdaptTuning::from_settings(&MemorySettings::from_source(env)); if let Some(v) = serve_var(env, "PREFILL_BORROW") { self.prefill_borrow = !matches!(v.as_str(), "no" | "0" | "off"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs index a6556578..f9274cbc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs @@ -2,8 +2,9 @@ //! (residents, PCIe share, tail skip, invalid ids), the lag controller, the PCIe mode and the off-by-default config. use super::{ - EXPERTS, ExpertTierConfig, GroupSplit, LAYERS, PcieLag, PcieMode, PcieSplitPolicy, ResidencyState, RoutedGroup, - VANILLA_FREE_FLOOR_MIB, VERIFIER_ASSEMBLY_MIB, adapt_decay, choose_swaps, split_group_pcie, split_group_tail, + AdaptTuning, EXPERTS, ExpertTierConfig, GroupSplit, LAYERS, PcieLag, PcieMode, PcieSplitPolicy, ResidencyState, + RoutedGroup, VANILLA_FREE_FLOOR_MIB, VERIFIER_ASSEMBLY_MIB, adapt_decay, choose_swaps, split_group_pcie, + split_group_tail, }; #[cfg(test)] use super::{choose_swaps_reference, split_group}; @@ -71,8 +72,8 @@ fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect(); let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; for max_swaps in [1usize, 5, 96, 4096] { - let fast = choose_swaps(&usage, resident, max_swaps); - let slow = choose_swaps_reference(&usage, resident, max_swaps); + let fast = choose_swaps(&usage, resident, max_swaps, AdaptTuning::default()); + let slow = choose_swaps_reference(&usage, resident, max_swaps, AdaptTuning::default()); assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}"); for (a, b) in fast.iter().zip(&slow) { assert_eq!( @@ -108,8 +109,8 @@ fn choose_swaps_timing() { } (t.elapsed().as_secs_f64() * 1e6 / 200.0, n) }; - let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len()); - let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len()); + let (fast, a) = time(&|| choose_swaps(&usage, resident, 96, AdaptTuning::default()).len()); + let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96, AdaptTuning::default()).len()); eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})"); } @@ -280,14 +281,14 @@ fn swaps_take_the_most_routed_misses_over_the_least_routed_residents() { // layer 7: resident 4 (0.0), candidate 30 (2.0: the least count a candidate may have) usage[7 * EXPERTS + 30] = 2.0; let resident = |l: usize, e: usize| (l == 2 && e < 3) || (l == 7 && e == 4); - let swaps = choose_swaps(&usage, resident, 96); + let swaps = choose_swaps(&usage, resident, 96, AdaptTuning::default()); // layer 2 pairs: (10, 1) gain 8.5; (11, 2): 2.5 < 3.0 + 1.5 stops; layer 7: (30, 4) gain 2.0 assert_eq!(swaps.len(), 2); assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (2, 10, 1)); assert_eq!((swaps[1].layer, swaps[1].incoming, swaps[1].outgoing), (7, 30, 4)); - assert_eq!(choose_swaps(&usage, resident, 1).len(), 1); + assert_eq!(choose_swaps(&usage, resident, 1, AdaptTuning::default()).len(), 1); // no resident in a layer: no swap there (a native pack's cache only changes through its profile) - assert!(choose_swaps(&usage, |_, _| false, 96).is_empty()); + assert!(choose_swaps(&usage, |_, _| false, 96, AdaptTuning::default()).is_empty()); } #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs index 975b24d8..93514d45 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs @@ -1,6 +1,6 @@ //! Golden cases of `ExpertTierConfig::from_source`, the strict parser of the `LELEKA_ORIGINAL_SERVE_*` tier //! switches: a value that does not parse (or fails `validate`) is refused, never ignored. -use super::{ExpertTierConfig, PathBuf, PcieMode, ResidencyState, Result}; +use super::{AdaptTuning, ExpertTierConfig, PathBuf, PcieMode, ResidencyState, Result}; use crate::settings::MapEnv; const P: &str = "LELEKA_ORIGINAL_SERVE_"; @@ -142,3 +142,16 @@ fn the_controller_exists_only_for_the_switch_and_the_fixed_share_is_untouched() assert_eq!(ResidencyState::new(&on).strata_pcie_link_gbps, Some(30.0)); assert_eq!(on.pcie_num(), off.pcie_num(), "the start share is the configured one"); } + +#[test] +fn the_adaptive_tuning_travels_with_the_tier_config() { + let tuned = MapEnv::new() + .with("LELEKA_ADAPT_MIN_COUNT", "3") + .with("LELEKA_ADAPT_MARGIN", "0.5") + .with("LELEKA_ADAPT_DECAY", "0.9"); + let tier = ExpertTierConfig::from_source(&tuned).unwrap(); + assert_eq!(tier.adapt_tuning, AdaptTuning { min_count: 3.0, margin: 0.5, decay: 0.9 }); + assert_eq!(read(&[]).map(|c| c.adapt_tuning), Ok(AdaptTuning::default())); + let outside = MapEnv::new().with("LELEKA_ADAPT_DECAY", "1.5"); + assert_eq!(ExpertTierConfig::from_source(&outside).map(|c| c.adapt_tuning.decay), Ok(0.7)); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs index 9929c824..4527b574 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs @@ -18,7 +18,7 @@ use super::{ contract::{Error, Result}, moe_weight_cache::MoeWeightCache, original_serve_pool::CpuExpertPool, - original_serve_residency::{SpanCache, Swap, choose_swaps, source_spans}, + original_serve_residency::{AdaptTuning, SpanCache, Swap, choose_swaps, source_spans}, original_serve_verifier::driver_error, }; use crate::model_binding::weight_binding::ModelBinding; @@ -53,7 +53,12 @@ pub(crate) struct SeedReport { /// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every /// resident expert (the blend with the profile's placement). -pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec { +pub(super) fn plan( + counts: &[f32], + cache: &OriginalExpertCache<'_>, + (max_swaps, keep): (usize, f32), + tuning: AdaptTuning, +) -> Vec { let mut usage: Vec = counts.to_vec(); if keep > 0.0 { for layer in 0..LAYERS { @@ -64,7 +69,7 @@ pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: u } } } - choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) + choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps, tuning) } /// Where the source spans of the incoming experts come from: the binding, the weight cache, the CPU tier and the span @@ -204,7 +209,7 @@ mod tests { usage[3 * EXPERTS + e] = u; } let resident = |l: usize, e: usize| l == 3 && e < 2; - let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS); + let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS, AdaptTuning::default()); // (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops assert_eq!(swaps.len(), 1); assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/decode_phase_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/decode_phase_steps.rs index 5f733c27..62873e4f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/decode_phase_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/decode_phase_steps.rs @@ -222,6 +222,7 @@ pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>( pcie_num, adapt_every: tier.adapt_every, adapt_swaps: tier.adapt_swaps as usize, + adapt_tuning: tier.adapt_tuning, tail_rank, pcie_locked, }) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs index 2e78bde1..660ad01c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs @@ -106,7 +106,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if seed_rows_capped(tier.seed_max_rows, counts) { return Ok(()); } - let swaps = original_serve_seed::plan(counts, cache, max, keep); + let swaps = original_serve_seed::plan(counts, cache, (max, keep), tier.adapt_tuning); let planned = self.config.clock.since(started); let mut report = original_serve_seed::summarize(counts, &swaps); let mut sources = original_serve_seed::SwapSources { diff --git a/crates/engine-qwen35-cuda/src/settings/memory.rs b/crates/engine-qwen35-cuda/src/settings/memory.rs index 524c05a5..e727f6be 100644 --- a/crates/engine-qwen35-cuda/src/settings/memory.rs +++ b/crates/engine-qwen35-cuda/src/settings/memory.rs @@ -65,7 +65,7 @@ pub(crate) struct CpuPoolSettings { } impl MemorySettings { - pub(super) fn from_source(env: &impl EnvSource) -> Self { + pub(crate) fn from_source(env: &impl EnvSource) -> Self { let tuning = |key: &str, default: f32| number::(env, key).filter(|v| v.is_finite()).unwrap_or(default); Self { route_tail_skip: trimmed_number::(env, "LELEKA_ROUTE_TAIL_SKIP"),