Add LELEKA_ORIGINAL_SERVE_PCIE_AUTO: Strata's PcieAuto share controller (opt-in, default off)

Port of generate.cpp PcieAuto (0.2.6) as a pure policy (strata_pcie_auto.rs): the PCIe share of the
missed experts is link / (link + 1.85 x CPU-pool byte rate), read from the pool's wall time per
CPU-computed expert over windows of 48 then 96 and 96 decode rounds, rounded to 0.05, kept in
0.10..0.60, dead band 0.025, at most three updates. Wired into GpuExpertPool: the share of
split_group comes from the controller instead of the constant; the pool time is the worker pool's
dispatch of each direct group (group-open clock, no new Instant::now). With the switch off the
plan is unchanged. Placement-class change: CPU and GPU round differently.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-11 17:13:27 +01:00
co-authored by Claude Sonnet 5.5
parent 0cb24b840c
commit 2f8379ecd4
13 changed files with 512 additions and 23 deletions
@@ -170,6 +170,14 @@ pub(in crate::qwen_forward) struct CpuExpertPool<'a> {
direct: Option<DirectTier>,
legacy: Option<CpuMissWorkspace>,
crosscheck: CrosscheckCounts,
/// What the last direct group spent in the worker pool (read by the PCIe share controller).
last_group: ComputeSample,
}
/// The worker pool's wall time in one group and the distinct experts it computed (Strata's `ms_run` / `multi_misses`).
#[derive(Clone, Copy, Default)]
pub(in crate::qwen_forward) struct ComputeSample {
pub(in crate::qwen_forward) elapsed: std::time::Duration,
pub(in crate::qwen_forward) experts: usize,
}
#[derive(Default)]
struct CrosscheckCounts {
@@ -199,7 +207,7 @@ use prefetch_off_file_exists::same_spans;
#[allow(unused_imports)]
pub(in crate::qwen_forward) use prefetch_off_file_exists::scatter;
mod direct_parts;
use direct_parts::{borrow_experts, compute_into_sink, group_formats, plan_expert_ids, prefetch_group};
use direct_parts::{GroupWork, borrow_experts, compute_into_sink, group_formats, plan_expert_ids, prefetch_group};
mod cpu_expert_pool;
mod direct_tier;
mod direct_tier_drop;
@@ -81,7 +81,9 @@ impl CpuExpertPool<'_> {
window_trace::add(window_trace::PREPARE, -group.fetch_ms);
window_trace::add(window_trace::FETCH, group.fetch_ms);
let sink_span = super::super::original_serve_profile::span("cpu.sink");
let (written, failure) = compute_into_sink(&mut tier.pool, sink, rows, include, (&experts, formats));
let work = GroupWork { experts: &experts, formats, opened_at: group.started };
let (written, failure, pool_time) = compute_into_sink(&mut tier.pool, sink, rows, include, work);
self.last_group = ComputeSample { elapsed: pool_time, experts: plan.len() };
window_trace::lap(window_trace::JOIN, clock);
drop(sink_span);
let record = (group.any_mapped && failure.is_none() && !plan.is_empty()).then_some(group.use_pass);
@@ -89,6 +91,11 @@ impl CpuExpertPool<'_> {
sink_result(written, failure)
}
/// The worker pool's time and expert count of the last direct group (zero before one ran).
pub(in crate::qwen_forward) fn last_group_sample(&self) -> ComputeSample {
self.last_group
}
/// The VRAM tier tells the router lookahead which experts of `layer` it holds (before each group).
pub(in crate::qwen_forward) fn set_next_resident(&mut self, resident: impl Fn(usize) -> bool) {
if let Some(tier) = self.direct.as_mut().filter(|t| t.lookahead.is_some()) {
@@ -62,18 +62,26 @@ pub(super) fn borrow_experts<'p>(plan: &'p [ExpertJob], opened: &'p [Opened]) ->
Ok(experts)
}
/// Zero the entries the GPU tier owns and compute the rest of the group in place; the sink's result and the failure it
/// saw.
/// One group's work for the worker pool: its experts, their one format, and the instant the group was opened (the
/// clock the pool's time is read from).
pub(super) struct GroupWork<'e, 'b> {
pub(super) experts: &'e [BorrowedExpert<'b>],
pub(super) formats: Option<(GateUpFormat, DownFormat)>,
pub(super) opened_at: std::time::Instant,
}
/// Zero the entries the GPU tier owns and compute the rest of the group in place; the sink's result, the failure it
/// saw and the wall time of the worker pool's dispatch (without the zeroing).
pub(super) fn compute_into_sink(
pool: &mut DirectCpuPool,
sink: &mut OriginalVerifyCpuSink<'_, '_>,
rows: &OriginalVerifyCpuRows<'_>,
include: Option<&[bool]>,
work: (&[BorrowedExpert<'_>], Option<(GateUpFormat, DownFormat)>),
) -> (leleka_cuda_driver::Result<()>, Option<Error>) {
let (experts, formats) = work;
work: GroupWork<'_, '_>,
) -> (leleka_cuda_driver::Result<()>, Option<Error>, std::time::Duration) {
let count = rows.ids.len() / TOP_K;
let mut failure = None;
let mut pool_time = std::time::Duration::ZERO;
let written = sink.with_output(|out| {
if out.len() != count * TOP_K * HIDDEN {
failure = Some(Error::InvalidDimension);
@@ -83,15 +91,27 @@ pub(super) fn compute_into_sink(
zero_unselected(out, include);
drop(zero_span);
let _compute_span = super::super::original_serve_profile::span("cpu.compute");
if let Some(formats) = formats {
if let Err(error) = compute_chunks(pool, (rows, experts), formats, out) {
failure = Some(error);
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
}
let (computed, took) = compute_timed(pool, (rows, &work), out);
pool_time = took;
if let Err(error) = computed {
failure = Some(error);
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
}
Ok(())
});
(written, failure)
(written, failure, pool_time)
}
/// `compute_chunks` over the group's experts and the wall time it took (zero when the group holds none).
fn compute_timed(
pool: &mut DirectCpuPool,
(rows, work): (&OriginalVerifyCpuRows<'_>, &GroupWork<'_, '_>),
out: &mut [f32],
) -> (std::result::Result<(), Error>, std::time::Duration) {
let Some(formats) = work.formats else { return (Ok(()), std::time::Duration::ZERO) };
let before = work.opened_at.elapsed();
let computed = compute_chunks(pool, (rows, work.experts), formats, out);
(computed, work.opened_at.elapsed().saturating_sub(before))
}
/// The entries the GPU tier owns (`include` false) read as zeros.
@@ -331,7 +331,8 @@ impl<'a> CpuExpertPool<'a> {
if path != PoolPath::Direct {
eprintln!("leleka-serve cpu expert pool: {path:?} path (LELEKA_CPU_POOL)");
}
Ok(Self { binding, direct, legacy, crosscheck: CrosscheckCounts::default() })
let (crosscheck, last_group) = (CrosscheckCounts::default(), ComputeSample::default());
Ok(Self { binding, direct, legacy, crosscheck, last_group })
}
}
impl<'ctx> OriginalServePool<'ctx> for CpuExpertPool<'_> {
@@ -96,6 +96,11 @@ pub(crate) struct ExpertTierConfig {
pub(crate) pcie_frac_set: bool,
/// `--pcie-mode` (auto).
pub(crate) pcie_mode: PcieMode,
/// EXPERIMENTAL, opt-in (`LELEKA_ORIGINAL_SERVE_PCIE_AUTO=on`, default `None` = off; placement class): Strata's
/// `PcieAuto` moves the PCIe share from the CPU pool's measured speed after the first decode windows, with
/// `pcie_frac` as its start value. `Some(link GB/s)` (`_PCIE_LINK_GBPS`, default 47.5) is the host-to-device
/// bandwidth it balances the pool against. See `strata_pcie_auto`.
pub(crate) strata_pcie_auto: Option<f64>,
/// `--adapt-every` (4) and `--adapt-swaps` (96); either 0 turns the adaptive tier off.
pub(crate) adapt_every: u32,
pub(crate) adapt_swaps: u32,
@@ -237,6 +242,10 @@ pub(crate) struct ResidencyState {
pub(crate) spans: SpanCache,
pub(crate) pcie_auto: Option<PcieAuto>,
pub(crate) pcie_lag: Option<PcieLag>,
/// `LELEKA_ORIGINAL_SERVE_PCIE_AUTO`: the link bandwidth when the switch is on, and the controller started from it
/// at the first round (`start_strata_pcie_auto`).
strata_pcie_link_gbps: Option<f64>,
pub(crate) strata_pcie_auto: Option<StrataPcieAuto>,
pcie_auto_checked: bool,
}
@@ -295,6 +304,11 @@ pub(in crate::qwen_forward) use split_group_pcie::split_group_pcie;
pub(in crate::qwen_forward) use split_group_pcie::{PcieSplitPolicy, RoutedGroup};
mod swap_tie_order;
pub(in crate::qwen_forward) use swap_tie_order::TieOrder;
mod strata_pcie_auto;
use strata_pcie_auto::StrataPcieAuto;
mod strata_pcie_auto_glue;
#[cfg(test)]
mod strata_pcie_auto_tests;
mod span_cache_and_pcie_lag;
#[allow(unused_imports)]
use span_cache_and_pcie_lag::span_cache_enabled;
@@ -82,6 +82,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
let ran = self.cpu.run_entries(rows, sink, Some(&include));
if ran.is_ok() {
self.measure_pcie_lag(sink, &split);
self.note_cpu_pool_work();
}
ran
}
@@ -90,6 +91,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
self.state.pcie_auto_checked = true;
self.state.pcie_auto = PcieAuto::from_environment(self.pcie_num);
self.state.pcie_lag = PcieLag::from_environment(self.pcie_num);
self.start_strata_pcie_auto();
}
if let Some(auto) = self.state.pcie_auto.as_mut() {
auto.round();
@@ -97,6 +99,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
if let Some(lag) = self.state.pcie_lag.as_mut() {
lag.round();
}
self.end_strata_pcie_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.
@@ -184,13 +187,16 @@ impl<'ctx> GpuExpertPool<'_, '_, 'ctx> {
drop(profile_split);
Ok(split)
}
/// The PCIe share in 256ths: the lag controller's, else the auto controller's, else the configured one.
/// The PCIe share in 256ths: Strata's `PcieAuto` (`LELEKA_ORIGINAL_SERVE_PCIE_AUTO`), else the lag controller's,
/// else the hill climber's, else the configured one.
fn current_pcie_num(&self) -> u32 {
self.state
.pcie_lag
let state = &*self.state;
state
.strata_pcie_auto
.as_ref()
.map(PcieLag::pcie_num)
.or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num))
.map(StrataPcieAuto::pcie_num)
.or_else(|| state.pcie_lag.as_ref().map(PcieLag::pcie_num))
.or_else(|| state.pcie_auto.as_ref().map(PcieAuto::pcie_num))
.unwrap_or(self.pcie_num)
}
fn fetch_pcie_spans(
@@ -159,6 +159,8 @@ impl ResidencyState {
routing,
pcie_auto: None,
pcie_lag: None,
strata_pcie_link_gbps: config.strata_pcie_auto,
strata_pcie_auto: None,
pcie_auto_checked: false,
marks: Vec::new(),
mark_base: [0; 3],
@@ -0,0 +1,169 @@
//! Strata's `PcieAuto` (generate.cpp `struct PcieAuto`, 0.2.6) as a pure policy: no clock, no device, no environment.
//!
//! What it decides: the PCIe share of a group's missed experts (the rest of the misses run on the CPU pool). The
//! balance share is `link / (link + 1.85 x pool rate)`: `link` is the host-to-device bandwidth, the pool rate is the
//! routed-expert bytes over the pool's wall time per CPU-computed expert. The policy reads that pool time over a
//! window of decode rounds and moves the share to the balance, rounded to steps of 0.05 and kept inside 0.10..0.60.
//! At most three updates are made (after 48, then 96 and 96 more rounds), then the share stays where it is; a
//! reading of fewer than 300 CPU experts is not enough and the policy looks again (it gives up after 2000 rounds).
//! A new share must differ from the current one by 0.025 or more to be taken.
//!
//! Opt-in `LELEKA_ORIGINAL_SERVE_PCIE_AUTO`. The share decides which misses a CPU computes and which a GPU computes,
//! and the two round differently (docs/original-serve.md), so this is a placement-class change.
/// Strata's `PcieAuto::kPoolFactor`: how many times the CPU pool's byte rate the balance counts for.
pub(crate) const POOL_FACTOR: f64 = 1.85;
/// Rounds in the first window, and in each later one.
pub(crate) const FIRST_WINDOW_ROUNDS: u32 = 48;
pub(crate) const LATER_WINDOW_ROUNDS: u32 = 96;
/// Fewest CPU-computed experts a window must hold for its pool time to be read.
pub(crate) const MIN_WINDOW_EXPERTS: u64 = 300;
/// A window that never holds enough experts stops the policy after this many rounds.
pub(crate) const GIVE_UP_ROUNDS: u32 = 2000;
/// Updates made at most.
pub(crate) const MAX_UPDATES: u32 = 3;
/// The share is kept inside these bounds and on steps of `1 / SHARE_STEPS_PER_UNIT`.
pub(crate) const MIN_SHARE: f64 = 0.10;
pub(crate) const MAX_SHARE: f64 = 0.60;
const SHARE_STEPS_PER_UNIT: f64 = 20.0;
/// A share closer than this to the current one is left alone.
pub(crate) const DEAD_BAND: f64 = 0.025;
/// Host-to-device bandwidth Strata's start-up probe read on the RTX 5090 server (parity-audit-5090.md, row 5).
pub(crate) const DEFAULT_LINK_GBPS: f64 = 47.5;
/// What the policy needs to know about the machine, fixed for the life of the process.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PcieAutoInputs {
/// Host-to-device bandwidth in GB/s (Strata probes it at start-up; here it is configured).
pub(crate) link_gbps: f64,
/// Mean routed-expert blob size over the layers, in bytes.
pub(crate) blob_bytes: f64,
}
/// What the CPU pool did: wall microseconds spent computing, and the distinct experts it computed.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct PoolWork {
pub(crate) micros: f64,
pub(crate) experts: u64,
}
impl PoolWork {
fn add(&mut self, other: PoolWork) {
self.micros += other.micros;
self.experts += other.experts;
}
}
/// A new share and the reading it came from (for the operator line).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ShareChange {
pub(crate) pcie_num: u32,
pub(crate) fraction: f64,
pub(crate) micros_per_expert: f64,
pub(crate) pool_gbps: f64,
}
/// The controller: the current share in 256ths and the pool time read so far.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct StrataPcieAuto {
inputs: PcieAutoInputs,
pcie_num: u32,
live: bool,
round: Option<PoolWork>,
window: PoolWork,
rounds: u32,
updates: u32,
}
/// `pcie_num = clamp(round(share * 256), 0, 256)`, as `ExpertTierConfig::pcie_num`.
fn num_of(share: f64) -> u32 {
(share * 256.0 + 0.5).clamp(0.0, 256.0) as u32
}
/// The balance share for a link and a pool rate, on the 0.05 grid inside the bounds.
pub(crate) fn balanced_share(link_gbps: f64, pool_gbps: f64) -> f64 {
let balance = link_gbps / (link_gbps + POOL_FACTOR * pool_gbps);
((balance * SHARE_STEPS_PER_UNIT).round() / SHARE_STEPS_PER_UNIT).clamp(MIN_SHARE, MAX_SHARE)
}
impl StrataPcieAuto {
pub(crate) fn new(inputs: PcieAutoInputs, start_num: u32) -> Self {
Self {
inputs,
pcie_num: start_num,
live: true,
round: None,
window: PoolWork::default(),
rounds: 0,
updates: 0,
}
}
/// The PCIe share in 256ths the next group is split with.
pub(crate) fn pcie_num(&self) -> u32 {
self.pcie_num
}
/// Whether the policy can still move the share.
pub(crate) fn live(&self) -> bool {
self.live
}
/// One group's CPU work (the pool's wall time and experts), added to the round that is running.
pub(crate) fn note_group(&mut self, work: PoolWork) {
if self.live {
self.round.get_or_insert_with(PoolWork::default).add(work);
}
}
/// A round boundary: the round that ended joins the window; at the window's size the share may move. A round in
/// which the pool ran no group (the boundary before a request's first round) is not a round.
pub(crate) fn end_round(&mut self) -> Option<ShareChange> {
let work = self.round.take()?;
self.window.add(work);
self.rounds += 1;
let needed = if self.updates == 0 { FIRST_WINDOW_ROUNDS } else { LATER_WINDOW_ROUNDS };
if self.rounds < needed {
return None;
}
if self.window.experts < MIN_WINDOW_EXPERTS {
self.live = self.rounds < GIVE_UP_ROUNDS;
return None;
}
let read = std::mem::take(&mut self.window);
self.rounds = 0;
self.updates += 1;
self.live = self.updates < MAX_UPDATES;
self.retarget(read)
}
fn retarget(&mut self, read: PoolWork) -> Option<ShareChange> {
let PcieAutoInputs { link_gbps, blob_bytes } = self.inputs;
let micros_per_expert = read.micros / read.experts as f64;
let readable = micros_per_expert > 1.0 && blob_bytes > 0.0 && link_gbps > 0.0;
if !readable {
return None;
}
let pool_gbps = blob_bytes / (micros_per_expert * 1e-6) / 1e9;
let fraction = balanced_share(link_gbps, pool_gbps);
if (fraction - f64::from(self.pcie_num) / 256.0).abs() < DEAD_BAND {
return None;
}
self.pcie_num = num_of(fraction);
Some(ShareChange { pcie_num: self.pcie_num, fraction, micros_per_expert, pool_gbps })
}
}
impl ShareChange {
/// The operator line of an update: what the pool took, what the link is, the share it was and the share it is.
pub(crate) fn operator_line(&self, (was_num, link_gbps): (u32, f64), last: bool) -> String {
format!(
"leleka-serve PCIe share (LELEKA_ORIGINAL_SERVE_PCIE_AUTO): the CPU pool takes {:.0} us per computed \
expert ({:.1} GB/s of expert bytes), the link {:.1} GB/s -> pcie_frac {:.2} (pcie_num {} -> {}, was \
{:.2}){}",
self.micros_per_expert,
self.pool_gbps,
link_gbps,
self.fraction,
was_num,
self.pcie_num,
f64::from(was_num) / 256.0,
if last { "; last update" } else { "" },
)
}
}
@@ -0,0 +1,56 @@
//! `StrataPcieAuto` on the window pool (`LELEKA_ORIGINAL_SERVE_PCIE_AUTO`): started at the first round, fed with the
//! CPU pool's time after every group, moved at the round boundary. The policy is `strata_pcie_auto`; nothing here
//! runs with the switch off.
use super::super::original_serve_config::ExpertBlobSizes;
use super::strata_pcie_auto::{PcieAutoInputs, PoolWork};
#[allow(unused_imports)]
use super::*;
/// The mean routed-expert blob size over the layers (Strata: the sum of `blob_bytes(l)` over `n_layers`); 0 when the
/// layout cannot be read.
fn mean_blob_bytes(binding: &ModelBinding) -> f64 {
let Ok(blobs) = ExpertBlobSizes::from_binding(binding) else { return 0.0 };
let total: usize = (0..LAYERS).filter_map(|layer| blobs.blob_bytes(layer)).sum();
total as f64 / LAYERS as f64
}
impl GpuExpertPool<'_, '_, '_> {
/// Once, at the first round: the controller, when the switch is on and the tier stages anything over PCIe.
pub(super) fn start_strata_pcie_auto(&mut self) {
let Some(link_gbps) = self.state.strata_pcie_link_gbps else { return };
if self.pcie_num == 0 {
eprintln!("leleka-serve PCIe share: PCIE_AUTO is on but the tier stages nothing over PCIe (pcie_num 0)");
return;
}
let inputs = PcieAutoInputs { link_gbps, blob_bytes: mean_blob_bytes(self.binding) };
eprintln!(
"leleka-serve PCIe share: LELEKA_ORIGINAL_SERVE_PCIE_AUTO on, start pcie_frac {:.2} (pcie_num {}), \
link {:.1} GB/s, expert blob {:.0} bytes (mean); first update after {} decode rounds",
f64::from(self.pcie_num) / 256.0,
self.pcie_num,
inputs.link_gbps,
inputs.blob_bytes,
strata_pcie_auto::FIRST_WINDOW_ROUNDS,
);
if self.state.pcie_lag.is_some() || self.state.pcie_auto.is_some() {
eprintln!("leleka-serve PCIe share: LELEKA_PCIE_AUTO is shadowed by LELEKA_ORIGINAL_SERVE_PCIE_AUTO");
}
self.state.strata_pcie_auto = Some(StrataPcieAuto::new(inputs, self.pcie_num));
}
/// After a group the CPU pool computed: its dispatch time and expert count join the running round.
pub(super) fn note_cpu_pool_work(&mut self) {
let Some(auto) = self.state.strata_pcie_auto.as_mut() else { return };
let sample = self.cpu.last_group_sample();
auto.note_group(PoolWork { micros: sample.elapsed.as_secs_f64() * 1e6, experts: sample.experts as u64 });
}
/// A round boundary: the controller may move the share; the move is printed.
pub(super) fn end_strata_pcie_round(&mut self) {
let link_gbps = self.state.strata_pcie_link_gbps.unwrap_or_default();
let Some(auto) = self.state.strata_pcie_auto.as_mut() else { return };
let was = auto.pcie_num();
if let Some(change) = auto.end_round() {
eprintln!("{}", change.operator_line((was, link_gbps), !auto.live()));
}
}
}
@@ -0,0 +1,156 @@
//! `StrataPcieAuto`: the policy's numbers against Strata's `PcieAuto` (generate.cpp:2196), no device.
use super::strata_pcie_auto::*;
/// An expert blob of 2.05 MB: with the 47.5 GB/s link, 43 us per expert is Strata's 0.35 on the RTX 5090 server
/// (parity-audit-5090.md row 5), 53 us its 0.40.
const BLOB: f64 = 2.05e6;
const INPUTS: PcieAutoInputs = PcieAutoInputs { link_gbps: DEFAULT_LINK_GBPS, blob_bytes: BLOB };
const START_055: u32 = 141;
fn controller() -> StrataPcieAuto {
StrataPcieAuto::new(INPUTS, START_055)
}
/// `rounds` rounds of one group each, `experts_per_round` experts at `micros_per_expert`; the last change, if any.
fn run_rounds(
auto: &mut StrataPcieAuto,
rounds: u32,
(experts_per_round, micros_per_expert): (u64, f64),
) -> Option<ShareChange> {
let mut last = None;
for _ in 0..rounds {
auto.note_group(PoolWork { micros: micros_per_expert * experts_per_round as f64, experts: experts_per_round });
last = auto.end_round().or(last);
}
last
}
#[test]
fn the_balance_share_is_link_over_link_plus_pool_on_the_005_grid() {
let pool_43us = BLOB / 43e-6 / 1e9;
let pool_53us = BLOB / 53e-6 / 1e9;
assert_eq!(balanced_share(47.5, pool_43us), 0.35);
assert_eq!(balanced_share(47.5, pool_53us), 0.40);
// a link as fast as the pool takes 1 / 2.85 of the misses
assert_eq!(balanced_share(40.0, 40.0), 0.35);
}
#[test]
fn the_share_stays_inside_the_bounds() {
assert_eq!(balanced_share(47.5, 1000.0), MIN_SHARE);
assert_eq!(balanced_share(47.5, 1.0), MAX_SHARE);
}
#[test]
fn nothing_moves_before_the_first_window_of_48_rounds() {
let mut auto = controller();
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS - 1, (40, 43.0)), None);
assert_eq!(auto.pcie_num(), START_055);
let change = run_rounds(&mut auto, 1, (40, 43.0)).expect("48th round");
assert_eq!((change.pcie_num, change.fraction), (90, 0.35));
assert!((change.micros_per_expert - 43.0).abs() < 1e-9);
assert!((change.pool_gbps - BLOB / 43e-6 / 1e9).abs() < 1e-6);
assert_eq!(auto.pcie_num(), 90);
}
#[test]
fn the_share_follows_a_slower_pool_down_in_steps_like_the_vanilla_replay() {
// Strata's replay went 0.55 -> 0.40 -> 0.35: 48 rounds, then 96 more, then 96 more
let mut auto = controller();
let first = run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 53.0)).expect("first update");
assert_eq!((first.pcie_num, first.fraction), (102, 0.40));
assert_eq!(run_rounds(&mut auto, LATER_WINDOW_ROUNDS - 1, (40, 43.0)), None);
let second = run_rounds(&mut auto, 1, (40, 43.0)).expect("second update");
assert_eq!((second.pcie_num, second.fraction), (90, 0.35));
assert!(auto.live(), "two updates made, the third is still to come");
}
#[test]
fn a_reading_within_the_dead_band_changes_nothing_but_uses_the_update() {
let mut auto = StrataPcieAuto::new(INPUTS, 90);
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 43.0)), None);
assert_eq!(auto.pcie_num(), 90);
// the next window is the 96-round one
assert_eq!(run_rounds(&mut auto, LATER_WINDOW_ROUNDS - 1, (40, 53.0)), None);
assert!(run_rounds(&mut auto, 1, (40, 53.0)).is_some());
}
#[test]
fn the_third_update_is_the_last_and_still_applies() {
let mut auto = controller();
run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 53.0));
run_rounds(&mut auto, LATER_WINDOW_ROUNDS, (40, 43.0));
assert!(auto.live());
let third = run_rounds(&mut auto, LATER_WINDOW_ROUNDS, (40, 120.0)).expect("third update");
assert!(third.fraction > 0.40, "a slow pool takes fewer misses, so the PCIe share rises: {third:?}");
assert!(!auto.live());
let kept = auto.pcie_num();
assert_eq!(run_rounds(&mut auto, 500, (40, 10.0)), None);
assert_eq!(auto.pcie_num(), kept);
}
#[test]
fn a_window_with_too_few_cpu_experts_is_looked_at_again_and_then_given_up() {
let mut auto = controller();
// 48 rounds x 6 experts = 288 < 300: not enough, the window grows
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (6, 43.0)), None);
assert!(auto.live());
assert_eq!(run_rounds(&mut auto, 1, (6, 43.0)), None, "49 rounds hold 294 experts");
let change = run_rounds(&mut auto, 1, (6, 43.0)).expect("50 rounds hold 300 experts");
assert_eq!(change.fraction, 0.35);
let mut starved = controller();
assert_eq!(run_rounds(&mut starved, GIVE_UP_ROUNDS - 1, (0, 0.0)), None);
assert!(starved.live());
assert_eq!(run_rounds(&mut starved, 1, (0, 0.0)), None);
assert!(!starved.live());
assert_eq!(starved.pcie_num(), START_055);
}
#[test]
fn a_boundary_without_a_group_is_not_a_round() {
let mut auto = controller();
for _ in 0..200 {
assert_eq!(auto.end_round(), None);
}
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS - 1, (40, 43.0)), None);
assert!(run_rounds(&mut auto, 1, (40, 43.0)).is_some());
}
#[test]
fn a_reading_that_cannot_be_used_leaves_the_share() {
// 1 us per expert or less is a clock artefact, not a pool speed
let mut auto = controller();
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 0.5)), None);
assert_eq!(auto.pcie_num(), START_055);
let no_blob = PcieAutoInputs { blob_bytes: 0.0, ..INPUTS };
let mut blind = StrataPcieAuto::new(no_blob, START_055);
assert_eq!(run_rounds(&mut blind, FIRST_WINDOW_ROUNDS, (40, 43.0)), None);
let no_link = PcieAutoInputs { link_gbps: 0.0, ..INPUTS };
let mut unlinked = StrataPcieAuto::new(no_link, START_055);
assert_eq!(run_rounds(&mut unlinked, FIRST_WINDOW_ROUNDS, (40, 43.0)), None);
}
#[test]
fn a_fast_pool_lowers_the_share_to_the_floor() {
let mut auto = controller();
let change = run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 2.0)).expect("update");
assert_eq!((change.fraction, change.pcie_num), (MIN_SHARE, 26));
}
#[test]
fn the_operator_line_names_the_reading_the_old_and_the_new_share() {
let change = ShareChange { pcie_num: 90, fraction: 0.35, micros_per_expert: 43.2, pool_gbps: 47.4 };
let line = change.operator_line((141, 47.5), false);
for want in ["pcie_frac 0.35", "pcie_num 141 -> 90", "was 0.55", "43 us", "47.4 GB/s", "link 47.5 GB/s"] {
assert!(line.contains(want), "{want:?} in {line:?}");
}
assert!(!line.contains("last update"));
assert!(change.operator_line((141, 47.5), true).ends_with("last update"));
}
#[test]
fn the_start_share_is_kept_until_the_first_window_and_the_inputs_are_read_back() {
let auto = controller();
assert_eq!((auto.pcie_num(), auto.live()), (START_055, true));
}
@@ -82,11 +82,11 @@ impl ExpertTierConfig {
// (`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 the auto-sized cache, equal at
// 2048 slots)
// (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,
prefill_borrow: true,
@@ -152,6 +152,7 @@ impl ExpertTierConfig {
let mut config = Self::off();
config.read_placement(env)?;
config.read_pcie(env)?;
config.read_strata_pcie_auto(env)?;
config.read_adaptation(env)?;
config.read_seed(env)?;
config.read_seed_shape(env)?;
@@ -184,6 +185,23 @@ impl ExpertTierConfig {
}
Ok(())
}
/// `_PCIE_AUTO` (`on` | `off`, also `yes`/`1` and `no`/`0`; anything else is refused) with `_PCIE_LINK_GBPS`
/// (a bandwidth above 0 and up to 1000, checked even while the switch is off).
fn read_strata_pcie_auto(&mut self, env: &impl EnvSource) -> Result<()> {
let link = match serve_var(env, "PCIE_LINK_GBPS") {
Some(v) => v.parse::<f64>().map_err(|_| Error::InvalidDimension)?,
None => strata_pcie_auto::DEFAULT_LINK_GBPS,
};
if !(link > 0.0 && link <= 1000.0) {
return Err(Error::InvalidDimension);
}
self.strata_pcie_auto = match serve_var(env, "PCIE_AUTO").as_deref() {
None | Some("off" | "no" | "0") => None,
Some("on" | "yes" | "1") => Some(link),
Some(_) => return Err(Error::InvalidDimension),
};
Ok(())
}
fn read_adaptation(&mut self, env: &impl EnvSource) -> Result<()> {
if let Some(v) = serve_var(env, "ADAPT_EVERY") {
self.adapt_every = v.parse().map_err(|_| Error::InvalidDimension)?;
@@ -111,3 +111,34 @@ fn the_profile_path_is_kept_as_set_without_a_check() {
assert_eq!(read(&[("EXPERT_PROFILE", "/p/x.strp")]).unwrap().profile, Some(PathBuf::from("/p/x.strp")));
assert_eq!(read(&[("EXPERT_PROFILE", "")]).unwrap().profile, Some(PathBuf::from("")));
}
#[test]
fn strata_pcie_auto_is_off_unless_asked_and_its_link_has_a_default() {
assert_eq!(read(&[]).unwrap().strata_pcie_auto, None);
let link = Some(super::strata_pcie_auto::DEFAULT_LINK_GBPS);
for (value, want) in [("on", link), ("yes", link), ("1", link), ("off", None), ("no", None), ("0", None)] {
assert_eq!(read(&[("PCIE_AUTO", value)]).map(|c| c.strata_pcie_auto), Ok(want), "{value:?}");
}
for value in ["", "ON", "true", "lag", "2"] {
assert!(read(&[("PCIE_AUTO", value)]).is_err(), "{value:?}");
}
}
#[test]
fn the_pcie_link_is_a_positive_bandwidth_up_to_a_thousand() {
assert_eq!(read(&[("PCIE_AUTO", "on"), ("PCIE_LINK_GBPS", "26.5")]).map(|c| c.strata_pcie_auto), Ok(Some(26.5)));
assert_eq!(read(&[("PCIE_LINK_GBPS", "26.5")]).map(|c| c.strata_pcie_auto), Ok(None), "no switch, no controller");
for value in ["0", "-1", "1000.5", "NaN", "inf", "x", ""] {
assert!(read(&[("PCIE_LINK_GBPS", value)]).is_err(), "{value:?}");
assert!(read(&[("PCIE_AUTO", "on"), ("PCIE_LINK_GBPS", value)]).is_err(), "{value:?}");
}
}
#[test]
fn the_controller_exists_only_for_the_switch_and_the_fixed_share_is_untouched() {
let off = ExpertTierConfig::off();
assert!(ResidencyState::new(&off).strata_pcie_link_gbps.is_none());
let on = ExpertTierConfig { strata_pcie_auto: Some(30.0), ..off.clone() };
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");
}
@@ -249,9 +249,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
fn pcie_num_for_report(&self) -> u32 {
self.tier
.residency
.pcie_lag
.strata_pcie_auto
.as_ref()
.map(|l| l.pcie_num())
.map(|s| s.pcie_num())
.or_else(|| self.tier.residency.pcie_lag.as_ref().map(|l| l.pcie_num()))
.or_else(|| self.tier.residency.pcie_auto.as_ref().map(|a| a.pcie_num()))
.unwrap_or(self.config.expert_tier.pcie_num())
}