From 2b15114527efca87f5625bc218c649a8aed7abaa Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Mon, 30 Nov 2026 09:34:50 -0800 Subject: [PATCH] fix(helios): per-step speculative calibration and excluded-only waiting/delivery fairness Why: Two independent scheduler biases caused adaptive speculative verification to under-select deeper, higher-throughput verification depths under the default `balanced` policy: 1. Per-depth cumulative calibration in `rounds.rs` defaulted unobserved deeper depths to unity while calibrating shallow depths, letting raw drafter overconfidence persist at unobserved depths and mis-estimating deeper cumulative survival when shallow shapes ran. 2. In `utility.rs`, `service.rs`, `policy.rs`, and `scripts/scheduling_sim/utility.py`, linear decode-age waiting cost `c_i * (A_i * T + T^2 / 2)` was charged to served decoders as well as excluded decoders (giving continuation reference `sigma_i = mu / p_i > 0` even when `p_i = 1`), and delivery fairness priced raw burst frequency `1 / T` (`delivered = 1`, `maximum_rate = 1 / T_min`). On longer-round hardware such as 4x DGX Spark (~35 ms/round), this penalized higher-`tok/s` speculative depths even when every active decoder was served and zero requests were excluded, violating the principle that hardware should only trade throughput for latency to protect an actual excluded/underserved request. What changed: - **Per-step conditional calibration (`helios/src/scheduler/rounds.rs`, `docs/scheduling-runtime-design.md`):** Switched `DepthCalibration` and `RequestCalibration` from cumulative ratios to survival-weighted per-step conditional ratios (`CALIBRATION_FACTOR_MAX = 4.0`, weight `w_d = prev_realized`), multiplied cumulatively across `0..=depth` during pricing. Unobserved deeper depths inherit the deepest observed shallower depth's factor instead of defaulting to `1.0`. - **Excluded-only waiting age (`helios/src/scheduler/utility.rs`, `service.rs`, `policy.rs`, `scripts/scheduling_sim/utility.py`, `docs/scheduling-utility.md`):** Charged linear waiting age only to excluded delivery-bearing streams (`j in D \ S(a)`), yielding the exact Bellman continuation reference `sigma_i = E[T * 1_{i not in S}] / p_i = (K - b_f) * T_f / b_f` (`DeliveryReference::excluded_wait_ms`). Added `LaneValue::decode_within(expected, preceding_ms, horizon_ms)` (and updated `LaneValue::finish`) so served lanes cancel their `-c_i * T / 2` term while preserving additive cohort selection and exact two-stage prerequisite waiting over `[0, preceding_ms]`. - **Served-share delivery fairness (`service.rs`, `utility.rs`, `policy.rs`, `scripts/scheduling_sim/utility.py`, `docs/scheduling-utility.md`):** Replaced burst-frequency delivery service (`delivered = 1`, `maximum_rate = 1 / T_min`) with served wall-time share `s_i in (0, 1]` (`delivered = duration_ms` on visible publication, `0` when excluded, `maximum_rate = 1.0`, initialized at `served_share = b_f / K`). Served decoders earn `+delivery_price_i * service_ms`, which divides by `T` to a duration-independent constant `+g_i / s_i`, protecting skipped requests without taxing deeper speculation on unskipped rounds. - **No core format, Protobuf, or model-specific changes:** Existing cores load and serve unchanged. Claimed benefit and result: - Eliminates artificial depth throttling under `balanced` whenever all active decoders are served (solo `B = 1`, uncontended full `B = 4`, or a decoder taking its turn alongside a waiting prefiller) while preserving prefill chunk shrinking when decoders wait and duration/priority protection for excluded decoders when oversubscribed (`K > b`). - Live 4x DGX Spark TP4 DeepSeek-V4.1-Flash serving (`max_tokens=256`, 5-prompt suite): - On `gb10-tp4-202611301553`, default `balanced` achieves **76.11 tok/s** mean (peaking at **80.89 tok/s** on `greedy_code` with `off/r = 4.80`), matching `throughput` (**76.43 tok/s**, 0.4% difference, within `T=1` sampling variance). - On `gb10-tp4-202611301141`, default `balanced` on `greedy_code` rose from 70.30 tok/s (`off/r = 2.04`) to 75.98 tok/s (`off/r = 3.17`), and on DFly2 (`gb10-tp4-202611301002`), per-step calibration cured the `W=1`/`P=3` collapse (`ctx16k_T1`: 70.94 vs 57.12 tok/s forced `P=6`, +24.2%). Supporting evidence and limitations: - Rust crate tests (`cargo test --locked --release`): `eos` (2/2), `selene` (548/548), `selene-manager`, `helios` scheduler suite (400/400, including `balanced_unexcluded_decoders_maximize_throughput_without_delivery_or_age_penalty` and `oversubscribed_decoders_incur_excluded_wait_and_protect_skipped_lanes`), `flare`, and `flare-cli` (201/201). - Scheduling simulator (`pytest tests/test_scheduling*.py -q`): **786/786** passed, including the updated excluded-only Poisson equation check and unexcluded `B = 1` / `B = 4` peak-throughput depth test. - TLA+ lifecycle models and Rust trace conformance (`python3 verification/helios-lifecycle/check.py --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar --target-dir flare-cli/target`): all 8 models passed with 0 TLC errors (`Lifecycle` 1,342, `RankProtocol` 1,291, `DispatchRing` 7,940, `OffloadTransfer` 8,490, `CacheOwnership` 195,492, `Speculation` 13,566, `ResponseLifecycle` 365,508, `CheckpointReservation` 68 observed transitions). - Limitations / unrun checks: `cargo-kani` is not installed locally (covered by CI; completion-vector and `StateView` validators were not modified). Live GPU multi-concurrency (`B = 4` and `K > 4`) serving benchmarks were not run in this pass (covered by unit and 786 simulator tests). Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b --- docs/scheduling-runtime-design.md | 58 ++++--- docs/scheduling-utility.md | 156 ++++++++++------- helios/src/scheduler/policy.rs | 55 ++++-- helios/src/scheduler/policy_tests.rs | 212 +++++++++++++++++++++-- helios/src/scheduler/rounds.rs | 151 +++++++++++----- helios/src/scheduler/service.rs | 71 +++++--- helios/src/scheduler/utility.rs | 68 ++++++-- scripts/scheduling_sim/utility.py | 54 +++--- tests/test_scheduling_learning_policy.py | 6 +- tests/test_scheduling_utility.py | 48 +++-- 10 files changed, 649 insertions(+), 230 deletions(-) diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index 0b20fa8ba..ea7208073 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -110,29 +110,43 @@ When pricing candidate shapes on a GPU-confidence model, the stored per-request confidence forecast is adjusted by two online corrections derived solely from completed rounds: -1. **Hierarchical per-request, per-depth drafter calibration (`RequestCalibration` - + `DepthCalibration`):** A slow round-level global prior `DepthCalibration` - (`clamp(realized / predicted, 0.0, 2.0)`, defaulting to `1.0` when - `predicted <= 1e-6`, initialized at `realized == predicted == 0.5^d` with - prior weight `4.0`, updated **once per completed round** from the mean - realized and predicted survival across contributing lanes with EWMA cap - `64.0`) provides instant model-wide protection for brand-new requests (e.g., - if a drafter breaks globally) while preventing a single correlated +1. **Hierarchical per-request, per-step drafter calibration (`RequestCalibration` + + `DepthCalibration`):** Calibration models the per-step conditional ratio + `clamp(realized / predicted, 0.0, 4.0)` (`CALIBRATION_FACTOR_MAX = 4.0`, + defaulting to `1.0` when `predicted <= 1e-6`) from offered, determined prefix + outcomes computed once in `complete_inner` (Rao-Blackwellized with + `completion_speculative_survival` when reported, else binary + acceptance/rejection). For each lane at depth `d`, let `w_d` be the preceding + depth's realized prefix survival clamped to `[0, 1]` (with `w_0 = 1.0`). When + `w_d > 1e-6`, the conditional realized step probability + `clamp(realized_d / w_d, 0.0, 1.0)` and raw per-step GPU confidence + `clamp(step_c_d, 0.0, 1.0)` supply an observation of weight `w_d`. A slow + round-level global prior `DepthCalibration` (initialized at + `realized == predicted == 0.5` with prior weight `4.0` and marked unobserved, + updated **once per completed round** from the contributing lanes' + survival-weighted conditional means with round weight + `clamp(sum(w_d) / count, 0.0, 1.0)` and EWMA cap `64.0`) provides immediate + model-wide protection for new requests while preventing a single correlated large-batch dip from overwriting the prior in one step. Each live request - maintains its own aged per-depth `RequestCalibration` (seeded - scale-invariantly at `anchor = max(predicted, 0.05)` with prior weight `2.0` - from the live global factor on its first observation at that depth, EWMA cap - `32.0`, 128-token half-life aging matching `PrefixEstimate`) so sequential - workloads, context lengths, and heterogeneous concurrent lanes do not bleed - calibration across requests, and censored unobserved depths decay their prior - weight so a single funded acceptance probe can escape stale priors. Updates - use the exact offered, determined prefix outcomes computed once in - `complete_inner` (Rao-Blackwellized with `completion_speculative_survival` - when reported, else binary acceptance/rejection). Pricing multiplies each - depth's stored mean by the request's calibration factor, adds the Hoeffding - optimistic margin using the minimum aged weight of the confidence forecast - and verification calibration during funded acceptance learning, clamps to - `[0, 1]`, and enforces nonincreasing prefix survival across depths. + maintains its own aged per-step `RequestCalibration` (seeded + scale-invariantly at `anchor = max(cond_pred, 0.05)` and + `realized = clamp(anchor * prior_factor, 0.0, 1.0)` with decayed prior weight + `2.0` on its first observation at that depth, updated with sample weight + `w_d`, EWMA cap `32.0`, and 128-token half-life aging matching + `PrefixEstimate`) so sequential workloads, context lengths, and heterogeneous + concurrent lanes do not bleed calibration across requests, and unobserved + depths decay their prior weight so a single funded acceptance probe can + escape stale priors. When a depth has no request-local observation, its + per-step factor (and first-observation seed `prior_factor`) uses the global + `DepthCalibration` at that depth if observed; otherwise it inherits the + deepest observed shallower depth (`prev` from `depth - 1` down to `0`, + preferring the request's local factor over the global factor at each depth), + defaulting to `1.0` when no shallower depth has been observed. Pricing + multiplies each depth's stored cumulative prefix mean by the cumulative + product of per-step calibration factors across `0..=depth`, adds the + Hoeffding optimistic margin using the minimum aged weight of the confidence + forecast and verification calibration during funded acceptance learning, + clamps to `[0, 1]`, and enforces nonincreasing prefix survival across depths. 2. **Cross-lane order-statistic allocation surplus (`SurplusHistory`):** Inside a packed GPU-allocated round (`B >= 2`, `P < B * W`, `depth >= 1`), the device allocator observes fresh per-step confidences across all active lanes diff --git a/docs/scheduling-utility.md b/docs/scheduling-utility.md index f4b418c9b..0ebf35c2c 100644 --- a/docs/scheduling-utility.md +++ b/docs/scheduling-utility.md @@ -25,27 +25,31 @@ allocation results below assume a frozen set of backlogged requests. ## Progress and delivery are different services Let `x_i` be request `i`'s useful-token rate, counting consumed prompt tokens and -emitted output tokens. Let `z_i` be its output-delivery rate while decoding. -A burst of eight accepted tokens earns eight output units and one delivery. -Rejected drafts, padding, and inactive rows earn neither service. An unfinished -prefill chunk earns prompt progress and no delivery. +emitted output tokens. Let `s_i in (0, 1]` be its served delivery-time share +while decoding: the fraction of wall time spent in rounds that deliver visible +output to stream `i`. A served decode round of duration `T` that emits eight +tokens earns eight output units and `T` milliseconds of served delivery time +(rate `1`); an excluded round of duration `T` earns zero delivery time +(rate `0`). Rejected drafts, padding, and inactive rows earn neither service. +An unfinished prefill chunk earns prompt progress and no delivery share. The stationary rate utility is ```text F = intrinsic useful work per millisecond + sum_i f_i log(x_i / m_i) - + sum_{i in decode} g_i log(z_i / d_i). + + sum_{i in decode} g_i log(s_i). ``` -Intrinsic work is `sum_i w_i(P_i + beta D_i)`. The constants `m_i` and `d_i` -are maximum individually feasible token and delivery rates from the catalog. -They normalize the logarithms; they do not set intrinsic token values. Holding -the catalog fixed, these normalizations only add constants to `F`. +Intrinsic work is `sum_i w_i(P_i + beta D_i)`. The constant `m_i` is the +maximum individually feasible token rate from the catalog; it normalizes the +token logarithm without setting intrinsic token values. Delivery share `s_i` is +dimensionless with maximum rate `1`. Holding the catalog fixed, normalizations +only add constants to `F`. `beta` prices an output token relative to a prompt token. `f_i` and `g_i` price -token-rate fairness and delivery-rate fairness in value units per millisecond. -The experiment uses `f_i = w_i * token_fairness` and +token-rate fairness and served delivery-share fairness in value units per +millisecond. The experiment uses `f_i = w_i * token_fairness` and `g_i = w_i * delivery_fairness`. A zero coefficient disables its utility term. The gradient prices are @@ -53,13 +57,18 @@ The gradient prices are ```text prompt price_i = w_i + f_i / x_i output price_i = w_i * beta + f_i / x_i -delivery price_i = g_i / z_i. +delivery price_i = g_i / s_i. ``` -Summing these prices times expected service and dividing by expected graph time -gives the supporting-direction calculation for `F`. Decode value remains in -the calculation; it does not cancel as it does in a finite episode where every -request must finish and collect a fixed total reward. +In candidate scoring over a round of duration `T`, a served decoder earns +`delivery price_i * T`, which divides by `T` to a constant `+g_i / s_i` +independent of `T`, while an excluded decoder earns zero. Delivery fairness +therefore prioritizes skipped or underserved decoders against competing work +without penalizing longer, higher-throughput speculative rounds when no stream +is excluded. Summing these prices times expected service and dividing by +expected graph time gives the supporting-direction calculation for `F`. Decode +value remains in the calculation; it does not cancel as it does in a finite +episode where every request must finish and collect a fixed total reward. Gradient scheduling with averaged rates has an asymptotic foundation for fixed service slots and sufficiently slow adaptation. See @@ -78,9 +87,10 @@ r_i <- exp(-T/tau) * r_i + (1 - exp(-T/tau)) * Y_i / (m_i * T). ``` -Delivery history uses the same update with `Y_i` equal to zero or one and -normalizer `d_i`. This estimator spreads service over the occupied interval -for rate accounting. Output-age accounting still places delivery at completion. +Delivery history uses the same update with `Y_i` equal to `T` when stream `i` +publishes visible output during the interval and `0` otherwise, with normalizer +`1`. This estimator tracks served-time share across the occupied interval; +output-age accounting still places delivery at completion. Equal-rate intervals compose consistently when split into different launch durations. A launch-count EMA would not have that property. @@ -90,9 +100,9 @@ service rate and its marginal price. This includes the prefill-to-decode transition, changes in speculative acceptance, and timing updates. Changing a normalization constant inside a logarithm must not itself reprice a token. -The first visible output initializes delivery history to one delivery over its -measured execution interval. A request already decoding without an observed -delivery starts from the batch-feasible delivery reference defined below. +The first visible output initializes delivery history to served share `1`. A +request already decoding without an observed delivery starts from the +batch-feasible served share defined below. Token and delivery histories then persist until the request departs. The implementation stores logarithms of rate fractions. An unserved interval @@ -179,66 +189,79 @@ optimum; neither changes the supplied utility coefficients or graph timings. ## Pricing the delay caused by a graph -Rate utility distinguishes token volume from delivery frequency, but an average -delivery rate alone does not specify individual gaps. Let `A_i` be elapsed time -since request `i`'s last output and `c_i` a price per millisecond squared. Its -linear age cost during a nonpreemptible graph is +Rate utility distinguishes token volume from served delivery share, but an +average service share alone does not specify individual gaps. Let `A_i` be +elapsed time since request `i`'s last output and `c_i` a price per millisecond +squared. A stream incurs waiting cost only while excluded from execution. +During a nonpreemptible graph of duration `T`, an excluded stream `j` pays the +linear age cost ```text -c_i * (A_i*T + T*T/2). +c_j * (A_j*T + T*T/2) ``` -Selected and excluded streams both wait through the graph. A selected stream's -age resets once at completion. Prefill has no decode-age clock. +and advances to `A_j' = A_j + T`. A selected stream makes active progress during +the graph, incurs zero waiting cost, and resets `A_i' = 0` at completion. +Prefill has no decode-age clock. Consider a reference that independently chooses an action each round from a -fixed distribution. Let `p_i` be its probability of serving stream `i`, and -`mu` its mean round duration. Then +fixed distribution with duration `T` and served subset `S`. Let +`p_i = P(i in S)` be its probability of serving stream `i`. Then ```text -sigma_i = mu / p_i +sigma_i = E[T * 1_{i not in S}] / p_i h(A) = -sum_i c_i * sigma_i * A_i ``` is the age-dependent part of its average-reward continuation value. To verify -it, substitute the transition `A_i' = 0` on service and `A_i' = A_i + T` -otherwise. The coefficient of each `A_i` in +it, substitute the excluded-only waiting cost and the transition `A_i' = 0` on +service and `A_i' = A_i + T` otherwise. The coefficient of each `A_i` in `E[reward + h(A') - h(A)]` is -`c_i * (-mu + sigma_i*p_i) = 0`. +`c_i * (-E[T * 1_{i not in S}] + sigma_i*p_i) = 0`. The remaining constant is the reference's net value per time multiplied by -`mu`. This identity holds when graph durations and service indicators are +`E[T]`. This identity holds when graph durations and service indicators are correlated; the derivation does not replace their joint moments with independent -means. +means. When `T` and `1_{i in S}` are independent with mean duration `mu`, +`sigma_i = ((1 - p_i) / p_i) * mu`. For `K` decoding requests sharing a graph family, the reference chooses the -graph minimizing `T/min(batch_capacity,K)`. Each round independently selects a -uniform cohort of that many requests. Every stream then has -`sigma = K*T/min(batch_capacity,K)`. Partially occupied graphs use their actual -occupied row count. Speculation yields one delivery per served stream, so -accepted token count does not multiply this reference rate. +graph minimizing `T/min(batch_capacity,K)` (breaking ties toward larger served +batch `b = min(batch_capacity,K)`). Each round independently selects a uniform +cohort of `b` requests, giving served share `s_i = b/K` and excluded-wait +reference `sigma_i = (K - b) * T / b`. Partially occupied graphs use their +actual occupied row count. When every active decoder fits in one batch (`b = K`), +`s_i = 1` and `sigma_i = 0`. Speculation yields one delivery interval per served +stream, so accepted token count does not multiply this reference. The native selector also has resume and terminal-snapshot families. It assigns each family's wall-time fraction in proportion to its stream count. Within a -family of `k` streams, uniformly sampled cohorts of `b=min(capacity,k)` give -`sigma_i = K*T_family/b`, where `K` counts all delivery-bearing streams. +family of `k` streams, uniformly sampled cohorts of `b = min(capacity,k)` give +`s_i = b/K` and `sigma_i = (K - b) * T_family / b`, where `K` counts all +delivery-bearing streams. The action probabilities are the wall-time fractions divided by their durations, then normalized. This defines a realizable independent reference on frozen ready families. Prefilling requests do not acquire a delivery clock or enlarge `K`; their token service retains its own fairness price. Streams blocked by -additional prerequisite stages use an individual future-delivery reference. -That multistage extension is a scheduling approximation. +additional prerequisite stages use an individual future-delivery reference +(`b = 1`). That multistage extension is a scheduling approximation. Using `h` for one-step policy improvement gives ```text -score(a) = [expected priced token and delivery service - + sum_{served decode i} c_i*sigma_i*(A_i+T)] / T - - T/2 * sum_{active decode i} c_i. +score(a) = [expected priced token service + + sum_{served decode i} (delivery_price_i*T + c_i*sigma_i*A_i)] / T + + sum_{served decode i} c_i*(A_i + sigma_i) + - T/2 * sum_{excluded decode j} c_j. ``` -Terms independent of the chosen action have been removed. The stall-clearing -term is paid once per stream, irrespective of speculative yield. Expected work -and waiting are expressed in the same value units before division by time. +Equivalently, moving `c_i*(A_i*T + sigma_i*T + T*T/2)` into each served lane's +additive numerator leaves the common `-T/2 * sum_{active decode k} c_k` term +outside cohort selection. For a two-stage sequence with prerequisite duration +`t` and total horizon `H = t + d`, an already-ready decoder waits during `[0, t]` +and is served during `[t, H]`, contributing `delivery_price_i * d` and saving +`c_i * d * (A_i + (H + t)/2)` of waiting relative to exclusion over `[0, H]`. +Terms independent of the chosen action have been removed. Expected work and +waiting are expressed in the same value units before division by time. For frozen prices, phases, and a fixed reference, this is an average-reward policy-improvement calculation. A long-run improvement statement additionally @@ -249,9 +272,17 @@ Variable-duration reward and continuation comparisons are instances of the [renewal optimization framework](https://ee.usc.edu/stochastic-nets/docs/renewal-optimization.pdf). With no active decoder, the age terms vanish. Full prefills compete by useful -value per time. With active decoders, a smaller prefill can win when the loss in -prompt throughput is smaller than the reduction in priced waiting. No duration -filter or preferred chunk size is involved. +value per time. Whenever every active decoder is served by a candidate and +`sigma_i = 0` — whether a single solo decoder, an uncontended full decode batch, +or a decoder taking its turn alongside a waiting prefiller — both delivery +fairness (`+delivery_price_i`) and age continuation (`+c_i*A_i`) are independent +of round duration `T`, so candidate selection maximizes priced token throughput +without underutilizing hardware to protect unarrived requests. Duration +trade-offs arise strictly in proportion to active decoders excluded by the +candidate: a prefill shrinks its chunk size when decoders wait, and an +oversubscribed decode batch (`K > b`) trades round duration against the waiting +cost of its excluded peers. No duration filter, preferred chunk size, or +request-count branch is involved. For a fixed physical graph, the excluded-stream cost depends on its duration, not cohort membership. Its best cohort therefore contains the largest additive @@ -263,16 +294,15 @@ enumerate joint speculative outcomes or every subset. Native terminal retirement uses an intrinsic value `v` and linear age-cost coefficient `c`, independently of streaming-delivery fairness and decode age. Its clock `A` starts when termination is observed, including preemption of a -resident request. The snapshot family supplies the batch-feasible reference -interval `sigma`. A terminal row contributes `v + c*sigma*(A+T)` to a snapshot -of duration `T`, and `c` joins the common waiting-cost sum for every candidate. -This is the same age-continuation arithmetic as output delivery, with the +resident request. The snapshot family supplies the batch-feasible excluded-wait +reference `sigma`. Under excluded-only waiting, a terminal row selected for +retirement in a snapshot of duration `T` (or retired during stage one of a +lookahead horizon `H`) incurs zero waiting cost over the horizon, contributing +`v + c*sigma*(A+H) + c*H*(A + H/2)` against the common `-c*H/2` denominator +term. This is the same age-continuation arithmetic as output delivery, with the terminal event's own value and clock. It supplies no token or streaming-delivery credit. There is no additional terminal rate-history coordinate. - -If the row retires at time `t` within a lookahead horizon `H`, its contribution -is `v + c*sigma*(A+H) + c*(H-t)*(A+(H+t)/2)`. The last term removes waiting after -retirement. All contributions use the decision's common positive scale. +All contributions use the decision's common positive scale. The two-stage cohort solver therefore compares terminal retirement and enabled inference without separate priority rules. These terminal terms remain active under throughput policy; the stationary backlogged-stream analysis above does diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index e91689a13..d054396f6 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -424,7 +424,7 @@ impl RequestScheduler { .map(|r| self.service_rates(r)) .unwrap_or_default() }); - let references = self.delivery_reference_intervals(&rates.map(|(_, d)| d)); + let references = self.delivery_references(&rates.map(|(_, d)| d)); let mut scale = 0.0f64 .max(self.policy.output_token_value.ln()) .max(self.policy.decode_age_price.ln()) @@ -445,7 +445,7 @@ impl RequestScheduler { r.accounting.terminal_since_ns.expect("terminal retirement has a start time"), ) as f64 / 1e6; if let Some(reference) = references[slot] { - values[slot].reference_delivery_ms = reference; + values[slot].reference_delivery_ms = reference.excluded_wait_ms; values[slot].age_price = self.policy.terminal_age_price; } continue; @@ -467,9 +467,9 @@ impl RequestScheduler { if let Some(reference) = references[slot].filter(|_| deliveries.is_some()) { delivery_log[slot] = service .deliveries - .unwrap_or_else(|| ServicePrice::initial(1.0 / reference)) + .unwrap_or_else(|| ServicePrice::initial(reference.served_share)) .log_price(self.policy.delivery_fairness); - values[slot].reference_delivery_ms = reference; + values[slot].reference_delivery_ms = reference.excluded_wait_ms; values[slot].age_price = self.policy.decode_age_price; let last_delivery = self.submissions.values().filter(|submission| matches!(submission.kind, GraphKind::Decode | GraphKind::Speculative) @@ -790,9 +790,10 @@ impl RequestScheduler { continue; } } + let preceding = if horizon == 0 { 0 } else { duration_ns }; let offer = ( slot, - self.lane_value(request, role, extent, horizon, values[slot]), + self.lane_value_within(request, role, extent, preceding, horizon, values[slot]), ); if mixed && role == GraphKind::Prefill { let best = &mut prompts[usize::from(promoted)]; @@ -905,8 +906,25 @@ impl RequestScheduler { duration_ns: u64, value: LaneValue, ) -> f64 { - self.lane_value_for_tokens( - r, kind, self.lane_tokens(r, kind, capacity), duration_ns, value, + self.lane_value_within(r, kind, capacity, 0, duration_ns, value) + } + + fn lane_value_within( + &self, + r: &LiveRequest, + kind: GraphKind, + capacity: usize, + preceding_ns: u64, + horizon_ns: u64, + value: LaneValue, + ) -> f64 { + self.lane_value_for_tokens_within( + r, + kind, + self.lane_tokens(r, kind, capacity), + preceding_ns, + horizon_ns, + value, ) } @@ -917,18 +935,33 @@ impl RequestScheduler { tokens: usize, duration_ns: u64, value: LaneValue, + ) -> f64 { + self.lane_value_for_tokens_within(r, kind, tokens, 0, duration_ns, value) + } + + fn lane_value_for_tokens_within( + &self, + r: &LiveRequest, + kind: GraphKind, + tokens: usize, + preceding_ns: u64, + horizon_ns: u64, + value: LaneValue, ) -> f64 { match kind { GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => value.prefill( tokens, r.consumed_tokens + tokens as u64 == r.prompt_tokens as u64, ), - GraphKind::Decode | GraphKind::Speculative => value.decode( + GraphKind::Decode | GraphKind::Speculative => value.decode_within( self.expected_speculative_tokens(r, tokens), - duration_ns as f64 / 1e6, + preceding_ns as f64 / 1e6, + horizon_ns as f64 / 1e6, ), - GraphKind::Resume => value.decode(1.0, duration_ns as f64 / 1e6), - _ => self.prerequisite_value(r, kind, duration_ns, value), + GraphKind::Resume => { + value.decode_within(1.0, preceding_ns as f64 / 1e6, horizon_ns as f64 / 1e6) + } + _ => self.prerequisite_value(r, kind, horizon_ns, value), } } diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 278954f86..e00436fa0 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -839,7 +839,7 @@ fn pipelined_frames_use_ordered_completion_deltas_and_one_delivery_per_frame() { let mut s = engine(1, false); let h = add(&mut s, 1, 65, 32); ready(&mut s, &[h]); - let (token_rate, delivery_rate) = s.service_rates(s.request(h).unwrap()); + let (token_rate, _) = s.service_rates(s.request(h).unwrap()); let first = s.plan().unwrap(); let a = Fence(s.submitted.0 + 1); s.commit(&first, a).unwrap(); @@ -851,12 +851,7 @@ fn pipelined_frames_use_ordered_completion_deltas_and_one_delivery_per_frame() { let mut deliveries = before.service.deliveries.unwrap(); for (plan, fence, ms) in [(&first, a, 2), (&second, b, 3)] { tokens.observe(ms as f64, 1.0, token_rate.unwrap(), s.policy.adaptation_ms); - deliveries.observe( - ms as f64, - 1.0, - delivery_rate.unwrap(), - s.policy.adaptation_ms, - ); + deliveries.observe(ms as f64, ms as f64, 1.0, s.policy.adaptation_ms); complete_timed(&mut s, plan, fence, 0, true, gpu_time(ms * MS)); let after = s.request(h).unwrap().accounting; price_close(after.service.tokens.unwrap(), tokens); @@ -874,7 +869,7 @@ fn speculative_token_volume_and_visible_burst_service_have_separate_prices() { s.fixed_speculative_width(Some(8)).unwrap(); let h = add(&mut s, 1, 65, 64); ready(&mut s, &[h]); - let (token_rate, delivery_rate) = s.service_rates(s.request(h).unwrap()); + let (token_rate, _) = s.service_rates(s.request(h).unwrap()); let plan = s.plan().unwrap(); let fence = Fence(s.submitted.0 + 1); s.commit(&plan, fence).unwrap(); @@ -882,7 +877,7 @@ fn speculative_token_volume_and_visible_burst_service_have_separate_prices() { let mut token_price = before.tokens.unwrap(); token_price.observe(30.0, 8.0, token_rate.unwrap(), s.policy.adaptation_ms); let mut hidden_price = before.deliveries.unwrap(); - hidden_price.observe(30.0, 0.0, delivery_rate.unwrap(), s.policy.adaptation_ms); + hidden_price.observe(30.0, 0.0, 1.0, s.policy.adaptation_ms); complete_timed(&mut s, &plan, fence, 7, false, gpu_time(30 * MS)); price_close( s.request(h).unwrap().accounting.service.tokens.unwrap(), @@ -893,7 +888,7 @@ fn speculative_token_volume_and_visible_burst_service_have_separate_prices() { hidden_price, ); let mut published_price = before.deliveries.unwrap(); - published_price.observe(30.0, 1.0, delivery_rate.unwrap(), s.policy.adaptation_ms); + published_price.observe(30.0, 30.0, 1.0, s.policy.adaptation_ms); for _ in 0..8 { s.published_output(h, fence).unwrap(); price_close( @@ -1117,7 +1112,7 @@ fn first_published_output_initializes_delivery_history_and_preserves_token_price complete_timed(&mut s, &prefill, a, 0, true, gpu_time(3 * MS)); let service = s.request(h).unwrap().accounting.service; price_close(service.tokens.unwrap(), tokens); - let deliveries = utility::ServicePrice::initial(1.0 / 3.0); + let deliveries = utility::ServicePrice::initial(1.0); price_close(service.deliveries.unwrap(), deliveries); let snapshot = s.plan().unwrap(); assert_eq!(snapshot.kind, GraphKind::Snapshot); @@ -1581,15 +1576,44 @@ fn delivery_reference_uses_batch_throughput_and_excludes_prefill_only_requests() .and_then(|s| s.request.as_ref()) .and_then(|r| s.service_rates(r).1) }); - s.delivery_reference_intervals(&rates) + s.delivery_references(&rates) }; - assert_eq!(references(&s)[handles[0].slot as usize], Some(17.0)); + // Both decoders fit in a single batch (b = 2, K = 2): zero excluded wait and full served share. + assert_eq!( + references(&s)[handles[0].slot as usize], + Some(service::DeliveryReference { + excluded_wait_ms: 0.0, + served_share: 1.0, + }) + ); for id in 3..=16 { add(&mut s, id, 32768, 128); } - assert_eq!(references(&s)[handles[0].slot as usize], Some(17.0)); + // Prefill-only requests do not enter the delivery-bearing set K. + assert_eq!( + references(&s)[handles[0].slot as usize], + Some(service::DeliveryReference { + excluded_wait_ms: 0.0, + served_share: 1.0, + }) + ); + // When batch-1 has lower per-delivery cost than batch-2, b = 1 < K = 2 gives positive excluded wait. + set_cost(&mut s, GraphKind::Speculative, 1, 1, 4 * MS); + assert_eq!( + references(&s)[handles[0].slot as usize], + Some(service::DeliveryReference { + excluded_wait_ms: 4.0, + served_share: 0.5, + }) + ); set_cost(&mut s, GraphKind::Speculative, 16, 1, MS); - assert_eq!(references(&s)[handles[0].slot as usize], Some(1.0)); + assert_eq!( + references(&s)[handles[0].slot as usize], + Some(service::DeliveryReference { + excluded_wait_ms: 0.0, + served_share: 1.0, + }) + ); let retained = references(&s); s.advance_to(s.now_ns + s.policy.estimate_ttl_ns).unwrap(); assert_eq!(references(&s), retained); @@ -5233,6 +5257,65 @@ fn gpu_confidence_calibration_isolates_two_lane_observations() { assert!(scheduler.forecasts.calibration_factor(1) < 0.35); } +#[test] +fn gpu_confidence_per_step_calibration_recovers_underconfident_and_unobserved_depths() { + // Case 1: Underconfident per-step proxy (e.g. Simpson index 0.45 vs true conditional 0.80). + // Cumulative ratio at depth 4 is (0.80/0.45)^5 = 17.8, which a cumulative 2x clamp would crush. + let mut scheduler = joined_round_engine(crate::execution::PrefixAllocation::Gpu); + let handle = add(&mut scheduler, 1, 64, 1024); + ready(&mut scheduler, &[handle]); + let slots = scheduler.limits.request_capacity(); + for _ in 0..32 { + let plan = scheduler.plan().unwrap(); + let fence = Fence(scheduler.submitted.0 + 1); + scheduler.commit(&plan, fence).unwrap(); + let mut records = completion_records(&scheduler, &plan, fence, 1); + let offered = plan.lanes[0].tokens.saturating_sub(1).min(plan.packed_token_capacity.saturating_sub(1)); + records[handle.slot as usize].vector.as_mut().unwrap().offered_drafts = offered as i64; + let confidence = vec![vec![0.45f32; 15]; plan.batch_capacity]; + let mut surv = vec![vec![-1.0f32; 15]; slots]; + let mut prefix = 1.0f32; + for d in 0..offered { + prefix *= 0.80; + surv[handle.slot as usize][d] = prefix; + } + scheduler + .complete_packed_round_with_survival(fence, &records, gpu_time(MS), &confidence, Some(&surv)) + .unwrap(); + } + let curve = scheduler.speculative_curve(scheduler.request(handle).unwrap(), false); + assert!(curve[0] > 0.72, "depth 0 should calibrate up to ~0.80, got {:?}", &curve[..5]); + assert!(curve[3] > 0.32, "depth 3 should calibrate up to ~0.41 without cumulative clamp collapse, got {:?}", &curve[..5]); + + // Case 2: Overconfident drafter verified only through depth 1 (offered=2). Unobserved deeper + // steps inherit the deepest verified per-step factor instead of defaulting to unity. + let mut shallow = joined_round_engine(crate::execution::PrefixAllocation::Gpu); + let req = add(&mut shallow, 1, 64, 1024); + ready(&mut shallow, &[req]); + for _ in 0..32 { + let plan = shallow.plan().unwrap(); + let fence = Fence(shallow.submitted.0 + 1); + shallow.commit(&plan, fence).unwrap(); + let mut records = completion_records(&shallow, &plan, fence, 1); + let offered = plan.lanes[0].tokens.saturating_sub(1).min(2); + records[req.slot as usize].vector.as_mut().unwrap().offered_drafts = offered as i64; + let confidence = vec![vec![0.85f32; 15]; plan.batch_capacity]; + let mut surv = vec![vec![-1.0f32; 15]; slots]; + let mut prefix = 1.0f32; + for d in 0..offered { + prefix *= 0.55; + surv[req.slot as usize][d] = prefix; + } + shallow + .complete_packed_round_with_survival(fence, &records, gpu_time(MS), &confidence, Some(&surv)) + .unwrap(); + } + let shallow_curve = shallow.speculative_curve(shallow.request(req).unwrap(), false); + assert!(shallow_curve[1] < 0.36, "verified depth 1 should be ~0.30, got {:?}", &shallow_curve[..5]); + assert!(shallow_curve[2] < 0.22, "unobserved depth 2 must inherit per-step calibration (~0.17), got {:?}", &shallow_curve[..5]); + assert!(shallow_curve[3] < 0.14, "unobserved depth 3 must inherit per-step calibration (~0.09), got {:?}", &shallow_curve[..5]); +} + #[test] fn gpu_allocation_surplus_invariants_and_within_request_variance() { // 1. Pure between-request heterogeneity (zero step-to-step variance): actual == forecast => factor == 1.0. @@ -6429,3 +6512,102 @@ fn expensive_stale_shape_does_not_starve_smaller_stale_shapes_under_credit_refil // Bound P <= (0.002 / 0.998) * O + D uses the most recent refresh episode duration D. assert!(refresh_ns as f64 <= ordinary_ns as f64 * 0.002 / 0.998 + last_refresh_ns as f64); } + +#[test] +fn balanced_unexcluded_decoders_maximize_throughput_without_delivery_or_age_penalty() { + // Without excluded decoders, served-time delivery fairness (+q_i) and excluded-only + // waiting age (sigma_i = 0, zero excluded wait) add no T-dependent penalty against + // deeper speculation that yields higher tok/s (P=6: 2.75/38ms = 72.4 tok/s vs P=3: 2.15/31ms = 69.4 tok/s). + let mut s = interactive_engine(4, true); + set_cost(&mut s, GraphKind::Decode, 1, 1, 22 * MS); + set_cost(&mut s, GraphKind::Speculative, 1, 3, 31 * MS); + set_cost(&mut s, GraphKind::Speculative, 1, 8, 38 * MS); + set_cost(&mut s, GraphKind::Speculative, 4, 3, 34 * MS); + set_cost(&mut s, GraphKind::Speculative, 4, 8, 41 * MS); + + let add_decoder = |s: &mut RequestScheduler, id: u32| { + let h = add(s, id, 64, 512); + let now = s.now_ns; + let r = s.request_mut(h).unwrap(); + r.phase = RequestPhase::Decode; + r.consumed_tokens = 64; + r.scheduled_consumed = 64; + r.generated_tokens = 1; + r.accounting.last_output_ns = Some(now); + // Survival ~ [0.70, 0.45, 0.25, 0.20, 0.15, 0.0, 0.0] -> E(3)=2.15, E(8)=2.75. + for _ in 0..64 { + r.acceptance + .observe(0, 7, 1, true, Some(&[0.70, 0.45, 0.25, 0.20, 0.15, 0.0, 0.0])); + } + h + }; + + // 1) Solo decoder: delivery fairness and age price remain active in lane_values, + // sigma_i = 0, and balanced policy picks max-tok/s width 8. + let h1 = add_decoder(&mut s, 1); + let (values, age_price, _) = s.lane_values(0); + assert!(values[h1.slot as usize].delivery > 0.0); + assert!(age_price > 0.0); + assert_eq!(values[h1.slot as usize].reference_delivery_ms, 0.0); + let solo_plan = s.plan().unwrap(); + assert_eq!(solo_plan.kind, GraphKind::Speculative); + assert_eq!(solo_plan.token_capacity, 8); + + // 2) Full uncontended batch (B=4 decoders all served by batch=4 graph): + // zero excluded decoders -> sigma_i = 0, and balanced policy STILL picks max-tok/s width 8. + let _h2 = add_decoder(&mut s, 2); + let _h3 = add_decoder(&mut s, 3); + let _h4 = add_decoder(&mut s, 4); + let batch_plan = s.plan().unwrap(); + assert_eq!(batch_plan.kind, GraphKind::Speculative); + assert_eq!(batch_plan.batch_capacity, 4); + assert_eq!(batch_plan.token_capacity, 8); +} + +#[test] +fn oversubscribed_decoders_incur_excluded_wait_and_protect_skipped_lanes() { + // With 8 active decoders and max batch 4, 4 decoders are genuinely excluded each round. + // The reference excluded wait is sigma_i = (8 - 4) * (T_ref / 4) > 0, and skipped + // decoders accumulate higher delivery prices and waiting ages than served decoders. + let mut s = interactive_engine(8, true); + set_cost(&mut s, GraphKind::Speculative, 4, 1, 20 * MS); + set_cost(&mut s, GraphKind::Speculative, 4, 8, 40 * MS); + // Disable larger batch shapes so K = 8 genuinely exceeds max batch capacity 4. + s.speculative_catalog.retain(|&(batch, _)| batch <= 4); + + let handles: Vec<_> = (1..=8) + .map(|id| { + let h = add(&mut s, id, 64, 512); + let now = s.now_ns; + let r = s.request_mut(h).unwrap(); + r.phase = RequestPhase::Decode; + r.consumed_tokens = 64; + r.scheduled_consumed = 64; + r.generated_tokens = 1; + r.accounting.last_output_ns = Some(now); + h + }) + .collect(); + + let (values, _, _) = s.lane_values(0); + // Best per-delivery graph is batch=4, T=20ms -> sigma_i = (8 - 4) * (20 / 4) = 20ms. + assert!((values[handles[0].slot as usize].reference_delivery_ms - 20.0).abs() < 1e-9); + + // Execute one round serving 4 decoders; the 4 excluded decoders must be selected next. + let first = s.plan().unwrap(); + assert_eq!(first.lanes.len(), 4); + let served_first: Vec<_> = first.lanes.iter().map(|l| l.request).collect(); + let fence = Fence(s.submitted.0 + 1); + s.commit(&first, fence).unwrap(); + s.advance_to(s.now_ns + 40 * MS).unwrap(); + complete_timed(&mut s, &first, fence, 0, true, gpu_time(40 * MS)); + + let second = s.plan().unwrap(); + assert_eq!(second.lanes.len(), 4); + for lane in &second.lanes { + assert!( + !served_first.contains(&lane.request), + "skipped decoder must be prioritized ahead of just-served cohort" + ); + } +} diff --git a/helios/src/scheduler/rounds.rs b/helios/src/scheduler/rounds.rs index ef4c8027e..b94b698b2 100644 --- a/helios/src/scheduler/rounds.rs +++ b/helios/src/scheduler/rounds.rs @@ -10,7 +10,7 @@ use super::{policy::{Candidate, bits}, utility::{LaneValue, ValueRate, best_coho const POPULATION_WEIGHT: f32 = 1.0 / 64.0; const CALIBRATION_PRIOR_WEIGHT: f64 = 4.0; const POPULATION_CALIBRATION_MAX_WEIGHT: f64 = 64.0; -const CALIBRATION_FACTOR_MAX: f64 = 2.0; +const CALIBRATION_FACTOR_MAX: f64 = 4.0; const REQUEST_CALIBRATION_PRIOR_WEIGHT: f64 = 2.0; const REQUEST_CALIBRATION_MAX_WEIGHT: f64 = 32.0; const REQUEST_CALIBRATION_HALF_LIFE: f64 = 128.0; @@ -24,19 +24,26 @@ struct DepthCalibration { realized: f64, predicted: f64, weight: f64, + observed: bool, } impl DepthCalibration { fn new(prior: f64) -> Self { - Self { realized: prior, predicted: prior, weight: CALIBRATION_PRIOR_WEIGHT } + Self { realized: prior, predicted: prior, weight: CALIBRATION_PRIOR_WEIGHT, observed: false } } - fn observe(&mut self, realized: f64, predicted: f64) { + fn observe_weighted(&mut self, realized: f64, predicted: f64, sample_weight: f64) { debug_assert!(realized.is_finite() && (0.0..=1.0).contains(&realized)); debug_assert!(predicted.is_finite() && (0.0..=1.0).contains(&predicted)); - self.weight = (self.weight + 1.0).min(POPULATION_CALIBRATION_MAX_WEIGHT); - self.realized += (realized - self.realized) / self.weight; - self.predicted += (predicted - self.predicted) / self.weight; + debug_assert!(sample_weight.is_finite() && (0.0..=1.0).contains(&sample_weight)); + if sample_weight <= 1e-6 { + return; + } + self.weight = (self.weight + sample_weight).min(POPULATION_CALIBRATION_MAX_WEIGHT); + let alpha = sample_weight / self.weight; + self.realized += alpha * (realized - self.realized); + self.predicted += alpha * (predicted - self.predicted); + self.observed = true; } fn factor(self) -> f64 { @@ -48,7 +55,7 @@ impl DepthCalibration { } } -/// Request-local aged per-depth verification calibration shrunk toward the global prior. +/// Request-local aged per-step verification calibration shrunk toward the global prior. #[derive(Clone, Copy)] struct RequestCalibration { realized: f64, @@ -75,30 +82,35 @@ impl RequestCalibration { base * Self::decay(generated, self.observed_at) } - fn factor(self, global: DepthCalibration) -> f64 { + fn local_factor(self) -> Option { if self.weight == 0.0 { - global.factor() + None } else if self.predicted > 1e-6 { - (self.realized / self.predicted).clamp(0.0, CALIBRATION_FACTOR_MAX) + Some((self.realized / self.predicted).clamp(0.0, CALIBRATION_FACTOR_MAX)) } else { - 1.0 + Some(1.0) } } - fn observe(&mut self, realized: f64, predicted: f64, generated: u32, global: DepthCalibration) { + fn observe(&mut self, realized: f64, predicted: f64, sample_weight: f64, generated: u32, prior_factor: f64) { debug_assert!(realized.is_finite() && (0.0..=1.0).contains(&realized)); debug_assert!(predicted.is_finite() && (0.0..=1.0).contains(&predicted)); + debug_assert!(sample_weight.is_finite() && (0.0..=1.0).contains(&sample_weight)); + if sample_weight <= 1e-6 { + return; + } let aged = if self.weight == 0.0 { let anchor = predicted.max(REQUEST_CALIBRATION_ANCHOR_FLOOR); self.predicted = anchor; - self.realized = (anchor * global.factor()).clamp(0.0, 1.0); + self.realized = (anchor * prior_factor).clamp(0.0, 1.0); REQUEST_CALIBRATION_PRIOR_WEIGHT * Self::decay(generated, self.observed_at) } else { self.weight_at(generated) }; - self.weight = (aged + 1.0).min(REQUEST_CALIBRATION_MAX_WEIGHT); - self.realized += (realized - self.realized) / self.weight; - self.predicted += (predicted - self.predicted) / self.weight; + self.weight = (aged + sample_weight).min(REQUEST_CALIBRATION_MAX_WEIGHT); + let alpha = sample_weight / self.weight; + self.realized += alpha * (realized - self.realized); + self.predicted += alpha * (predicted - self.predicted); self.observed_at = generated; } } @@ -275,19 +287,38 @@ impl Forecast { } } + fn prior_calibration_factor(&self, depth: usize, global: &[DepthCalibration]) -> f64 { + if let Some(entry) = global.get(depth).filter(|entry| entry.observed) { + return entry.factor(); + } + // Unobserved deeper prefixes inherit the deepest verified step's calibration + // rather than defaulting to unity, preventing upward drift when shallow shapes run. + for prev in (0..depth).rev() { + if let Some(factor) = self.calibration.get(prev).and_then(|entry| entry.local_factor()) { + return factor; + } + if let Some(entry) = global.get(prev).filter(|entry| entry.observed) { + return entry.factor(); + } + } + global.get(depth).map_or(1.0, |entry| entry.factor()) + } + fn calibration_factor(&self, depth: usize, global: &[DepthCalibration]) -> f64 { - let global_entry = global.get(depth).copied().unwrap_or(DepthCalibration::new(1.0)); - self.calibration.get(depth).map_or_else(|| global_entry.factor(), |entry| entry.factor(global_entry)) + if let Some(factor) = self.calibration.get(depth).and_then(|entry| entry.local_factor()) { + return factor; + } + self.prior_calibration_factor(depth, global) } fn calibration_information(&self, depth: usize, generated: u32) -> f64 { self.calibration.get(depth).map_or(REQUEST_CALIBRATION_PRIOR_WEIGHT, |entry| entry.information_at(generated)) } - fn observe_calibration(&mut self, depth: usize, realized: f64, predicted: f64, generated: u32, global: &[DepthCalibration]) { + fn observe_calibration(&mut self, depth: usize, realized: f64, predicted: f64, sample_weight: f64, generated: u32, global: &[DepthCalibration]) { + let prior = self.prior_calibration_factor(depth, global); if let Some(entry) = self.calibration.get_mut(depth) { - let global_entry = global.get(depth).copied().unwrap_or(DepthCalibration::new(1.0)); - entry.observe(realized, predicted, generated, global_entry); + entry.observe(realized, predicted, sample_weight, generated, prior); } } } @@ -303,7 +334,7 @@ impl Forecasts { pub(super) fn new(token_capacity: usize) -> Self { let population: Vec = (0..token_capacity - 1) .map(|i| 0.5f32.powi(i as i32 + 1)).collect(); - let calibration = population.iter().map(|&p| DepthCalibration::new(f64::from(p))).collect(); + let calibration = vec![DepthCalibration::new(0.5); token_capacity - 1]; Self { requests: std::array::from_fn(|_| None), population, @@ -318,15 +349,28 @@ impl Forecasts { self.population[depth] += POPULATION_WEIGHT * (prefix - self.population[depth]); } - /// Calibrates raw GPU prefix confidence against realized verification outcomes at `depth`. + /// Calibrates raw per-step GPU confidence against realized conditional survival at `depth`. + #[cfg(test)] pub(super) fn observe_calibration(&mut self, depth: usize, realized: f64, predicted: f64) { + self.observe_calibration_weighted(depth, realized, predicted, 1.0); + } + + pub(super) fn observe_calibration_weighted(&mut self, depth: usize, realized: f64, predicted: f64, sample_weight: f64) { if let Some(entry) = self.calibration.get_mut(depth) { - entry.observe(realized, predicted); + entry.observe_weighted(realized, predicted, sample_weight); } } #[cfg(test)] pub(super) fn calibration_factor(&self, depth: usize) -> f64 { + if let Some(entry) = self.calibration.get(depth).filter(|entry| entry.observed) { + return entry.factor(); + } + for prev in (0..depth).rev() { + if let Some(entry) = self.calibration.get(prev).filter(|entry| entry.observed) { + return entry.factor(); + } + } self.calibration.get(depth).map_or(1.0, |entry| entry.factor()) } @@ -404,9 +448,11 @@ impl RequestScheduler { let forecast = self.forecasts.requests[request.handle.slot as usize].as_ref() .filter(|forecast| forecast.request == request.handle) .cloned().unwrap_or_else(|| Forecast::new(request.handle, &self.forecasts.population, request.generated_tokens)); + let mut cumulative_factor = 1.0f64; let mut bound = 1.0f64; forecast.prefixes.iter().enumerate().map(|(depth, estimate)| { - let calibrated = estimate.mean() * forecast.calibration_factor(depth, &self.forecasts.calibration); + cumulative_factor *= forecast.calibration_factor(depth, &self.forecasts.calibration); + let calibrated = estimate.mean() * cumulative_factor; let value = if optimistic { let info = estimate.weight_at(request.generated_tokens) .min(forecast.calibration_information(depth, request.generated_tokens)); @@ -555,7 +601,7 @@ impl RequestScheduler { // A model that does not report GPU confidence feeds the population from host estimates instead. let gpu_confidence = self.gpu_confidence(); let mut round_cal = if gpu_confidence { - vec![(0.0f64, 0.0f64, 0usize); self.forecasts.calibration.len()] + vec![(0.0f64, 0.0f64, 0.0f64, 0usize); self.forecasts.calibration.len()] } else { Vec::new() }; @@ -579,8 +625,12 @@ impl RequestScheduler { .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 mut cumulative_factor = 1.0f64; (0..depth_limit) - .map(|depth| forecast.calibration_factor(depth, &self.forecasts.calibration)) + .map(|depth| { + cumulative_factor *= forecast.calibration_factor(depth, &self.forecasts.calibration); + cumulative_factor + }) .collect::>() } else { Vec::new() @@ -600,12 +650,13 @@ impl RequestScheduler { } else { Vec::new() }; - let mut predicted_prefixes = Vec::with_capacity(depth_limit); + let mut step_confidences = Vec::with_capacity(depth_limit); let mut prefix = 1.0f32; let mut actual_bound = 1.0f64; for depth in 0..depth_limit { - prefix *= confidence[row][depth]; - predicted_prefixes.push(prefix); + 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)); @@ -618,28 +669,42 @@ impl RequestScheduler { self.forecasts.observe_surplus(actual_cal, std::mem::take(&mut host_pred)); } if gpu_confidence { + let mut prev_realized = 1.0f64; for &(_, depth, realized) in row_realized { - if let Some(&predicted) = predicted_prefixes.get(depth) { - let pred = f64::from(predicted); - forecast.observe_calibration(depth, realized, pred, generated, &self.forecasts.calibration); - if let Some(acc) = round_cal.get_mut(depth) { - acc.0 += realized; - acc.1 += pred; - acc.2 += 1; + if let Some(&step_c) = step_confidences.get(depth) { + let sample_weight = prev_realized.clamp(0.0, 1.0); + if sample_weight > 1e-6 { + let cond_realized = (realized / sample_weight).clamp(0.0, 1.0); + let cond_pred = f64::from(step_c).clamp(0.0, 1.0); + forecast.observe_calibration( + depth, cond_realized, cond_pred, sample_weight, generated, &self.forecasts.calibration, + ); + if let Some(acc) = round_cal.get_mut(depth) { + acc.0 += sample_weight * cond_realized; + acc.1 += sample_weight * cond_pred; + acc.2 += sample_weight; + acc.3 += 1; + } } + prev_realized = realized; } } } self.forecasts.requests[lane.request.slot as usize] = Some(forecast); } // Update the global calibration prior once per completed round using the round's - // mean realized and predicted survival across contributing lanes, so a single - // correlated large-batch dip cannot overwrite the population prior in one step. + // survival-weighted conditional realized and predicted probabilities across contributing + // lanes, so a single correlated large-batch dip cannot overwrite the prior in one step. if gpu_confidence { - for (depth, (sum_real, sum_pred, count)) in round_cal.into_iter().enumerate() { - if count > 0 { - let denom = count as f64; - self.forecasts.observe_calibration(depth, sum_real / denom, sum_pred / denom); + for (depth, (sum_real, sum_pred, sum_w, count)) in round_cal.into_iter().enumerate() { + if count > 0 && sum_w > 1e-6 { + let round_w = (sum_w / count as f64).clamp(0.0, 1.0); + self.forecasts.observe_calibration_weighted( + depth, + (sum_real / sum_w).clamp(0.0, 1.0), + (sum_pred / sum_w).clamp(0.0, 1.0), + round_w, + ); } } } diff --git a/helios/src/scheduler/service.rs b/helios/src/scheduler/service.rs index a2b1ff80b..c00f506ed 100644 --- a/helios/src/scheduler/service.rs +++ b/helios/src/scheduler/service.rs @@ -22,7 +22,14 @@ struct DeliveryObservation { fence: Fence, before: ServicePrice, duration_ms: f64, - maximum_rate: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct DeliveryReference { + /// Expected excluded wait per served round under the batch-feasible reference: `(K - b) * T / b`. + pub excluded_wait_ms: f64, + /// Fraction of wall time served under the batch-feasible reference: `b / K`. + pub served_share: f64, } #[derive(Clone, Copy)] @@ -38,9 +45,9 @@ impl ServiceAccounting { debug_assert_eq!(observation.fence, fence); let mut price = observation.before; price.observe( + observation.duration_ms, observation.duration_ms, 1.0, - observation.maximum_rate, adaptation_ms, ); self.deliveries = Some(price); @@ -49,12 +56,17 @@ impl ServiceAccounting { } impl RequestScheduler { - pub(super) fn delivery_reference_intervals( + pub(super) fn delivery_references( &self, rates: &[Option; REQUEST_LANES], - ) -> [Option; REQUEST_LANES] { + ) -> [Option; REQUEST_LANES] { let count = rates.iter().flatten().count() as f64; - let mut references = rates.map(|r| r.map(|r| count / r)); + let mut references = rates.map(|r| { + r.map(|r| DeliveryReference { + excluded_wait_ms: (count - 1.0).max(0.0) / r, + served_share: (1.0 / count).min(1.0), + }) + }); let family = |r: &LiveRequest| match r.phase { RequestPhase::Decode if self.speculative_widths.is_empty() => Some(GraphKind::Decode), RequestPhase::Decode => Some(GraphKind::Speculative), @@ -84,12 +96,17 @@ impl RequestScheduler { if streams == 0 { continue; } - let mut per_delivery_ms = [f64::INFINITY; REQUEST_LANES]; + let mut best = [(f64::INFINITY, 0.0f64); REQUEST_LANES]; let mut consider = |nanos: u64, batch: usize, eligible: u64| { - if nanos == 0 || eligible == 0 { return; } - let cost = nanos as f64 / 1e6 / batch.min(eligible.count_ones() as usize) as f64; + if nanos == 0 || eligible == 0 { + return; + } + let served = batch.min(eligible.count_ones() as usize) as f64; + let cost = nanos as f64 / 1e6 / served; for slot in policy::bits(eligible) { - per_delivery_ms[slot] = per_delivery_ms[slot].min(cost); + if cost < best[slot].0 || (cost == best[slot].0 && served > best[slot].1) { + best[slot] = (cost, served); + } } }; if matches!(kind, GraphKind::Speculative) { @@ -99,12 +116,17 @@ impl RequestScheduler { let mut nanos = None; for slot in policy::bits(mask) { if let Some(ns) = self.speculative_duration( - self.slots[slot].request.as_ref().unwrap(), batch, width) { + self.slots[slot].request.as_ref().unwrap(), + batch, + width, + ) { eligible |= 1 << slot; nanos = Some(ns); } } - if let Some(ns) = nanos { consider(ns, batch, eligible); } + if let Some(ns) = nanos { + consider(ns, batch, eligible); + } } } } else { @@ -126,8 +148,12 @@ impl RequestScheduler { } } for (slot, reference) in references.iter_mut().enumerate() { - if mask & (1 << slot) != 0 && per_delivery_ms[slot].is_finite() { - *reference = Some(count * per_delivery_ms[slot]); + let (per_delivery_ms, served) = best[slot]; + if mask & (1 << slot) != 0 && per_delivery_ms.is_finite() { + *reference = Some(DeliveryReference { + excluded_wait_ms: (count - served).max(0.0) * per_delivery_ms, + served_share: (served / count).min(1.0), + }); } } } @@ -278,15 +304,15 @@ impl RequestScheduler { let (tokens, delivery) = match (submission.kind, lane) { (GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill, Some(l)) => (l.tokens as f64, 0.0), (GraphKind::Decode | GraphKind::Speculative, Some(_)) => - (submission.expected_tokens[request.handle.slot as usize], 1.0), + (submission.expected_tokens[request.handle.slot as usize], dt), _ => (0.0, 0.0), }; if let (Some(price), Some(rate)) = (&mut service.tokens, participant.token_rate) { price.observe(dt, tokens, rate, self.policy.adaptation_ms); } - if let (Some(price), Some(rate)) = (&mut service.deliveries, participant.delivery_rate) + if let (Some(price), Some(_)) = (&mut service.deliveries, participant.delivery_rate) { - price.observe(dt, delivery, rate, self.policy.adaptation_ms); + price.observe(dt, delivery, 1.0, self.policy.adaptation_ms); } } service @@ -312,7 +338,7 @@ impl RequestScheduler { }); } let references = self - .delivery_reference_intervals(&participants.map(|p| p.and_then(|p| p.delivery_rate))); + .delivery_references(&participants.map(|p| p.and_then(|p| p.delivery_rate))); for (slot, participant) in participants .iter() .enumerate() @@ -342,7 +368,7 @@ impl RequestScheduler { if let Some(reference) = references[slot] { service .deliveries - .get_or_insert_with(|| ServicePrice::initial(1.0 / reference)); + .get_or_insert_with(|| ServicePrice::initial(reference.served_share)); } } participants @@ -382,24 +408,21 @@ impl RequestScheduler { adaptation_ms, ); } - if let (Some(price), Some(rate)) = (&mut service.deliveries, participant.delivery_rate) + if let (Some(price), Some(_)) = (&mut service.deliveries, participant.delivery_rate) { if output { service.pending_delivery = Some(DeliveryObservation { fence, before: *price, duration_ms, - maximum_rate: rate, }); } - price.observe(duration_ms, 0.0, rate, adaptation_ms); + price.observe(duration_ms, 0.0, 1.0, adaptation_ms); } else if output && service.deliveries.is_none() { - let rate = 1.0 / duration_ms; service.pending_delivery = Some(DeliveryObservation { fence, - before: ServicePrice::initial(rate), + before: ServicePrice::initial(1.0), duration_ms, - maximum_rate: rate, }); } } diff --git a/helios/src/scheduler/utility.rs b/helios/src/scheduler/utility.rs index fc87db901..30f80c96b 100644 --- a/helios/src/scheduler/utility.rs +++ b/helios/src/scheduler/utility.rs @@ -74,6 +74,8 @@ impl ServicePrice { } /// Values share one positive scaling factor across all candidates in a plan. +/// `delivery` is a served-time fairness price (value per served millisecond); +/// `reference_delivery_ms` is the expected excluded wait per served round `sigma_i`. #[derive(Clone, Copy, Debug, Default)] pub(super) struct LaneValue { pub prefill_token: f64, @@ -91,9 +93,29 @@ impl LaneValue { } pub fn decode(&self, expected_output: f64, duration_ms: f64) -> f64 { - self.output_token * expected_output - + self.delivery - + self.age_price * self.reference_delivery_ms * (self.age_ms + duration_ms) + self.decode_within(expected_output, 0.0, duration_ms) + } + + /// Decode value when the lane waits during `[0, preceding_ms]` and is served + /// during `[preceding_ms, horizon_ms]`. + pub fn decode_within( + &self, + expected_output: f64, + preceding_ms: f64, + horizon_ms: f64, + ) -> f64 { + debug_assert!(horizon_ms == 0.0 || preceding_ms <= horizon_ms); + let service_ms = (horizon_ms - preceding_ms).max(0.0); + let mut value = self.output_token * expected_output + + self.delivery * service_ms + + self.age_price * self.reference_delivery_ms * (self.age_ms + horizon_ms); + if service_ms > 0.0 { + // Only excluded lanes pay waiting age; serving removes waiting during service_ms. + value += self.age_price + * service_ms + * (self.age_ms + (horizon_ms + preceding_ms) / 2.0); + } + value } pub fn finish(&self, completion_ms: f64, horizon_ms: f64) -> f64 { @@ -101,10 +123,8 @@ impl LaneValue { let mut value = self.terminal + self.age_price * self.reference_delivery_ms * (self.age_ms + horizon_ms); if horizon_ms > 0.0 { - // A terminal delivery stops its age clock before the sequence ends. - value += self.age_price - * (horizon_ms - completion_ms) - * (self.age_ms + (horizon_ms + completion_ms) / 2.0); + // A selected terminal row is being retired and then absent, so it is never excluded. + value += self.age_price * horizon_ms * (self.age_ms + horizon_ms / 2.0); } value } @@ -332,18 +352,32 @@ mod tests { reference_delivery_ms: 27.0, ..Default::default() }; + let excluded = LaneValue { + age_price: 0.4, + age_ms: 17.0, + reference_delivery_ms: 19.0, + ..Default::default() + }; let total = 6.0; - for finish in [1.0, 3.0, 6.0] { - let value = terminal.finish(finish, total) + continuing.decode(8.0, total); - let selected = ValueRate::new(6_000_000, value, 0.5).score; - let mut reward = 256.0 + 6.0 + 8.0 * 64.0; + let total_age_price = terminal.age_price + continuing.age_price + excluded.age_price; + for finish in [0.0, 1.0, 3.0, 6.0] { + let value = + terminal.finish(finish, total) + continuing.decode_within(8.0, finish, total); + let selected = ValueRate::new(6_000_000, value, total_age_price).score; + let mut reward = 256.0 + 6.0 * (total - finish) + 8.0 * 64.0; let mut potential = 0.0; - let mut common = 0.0; - for (lane, until) in [(terminal, finish), (continuing, total)] { - reward -= lane.age_price * (lane.age_ms * until + until * until / 2.0); - potential += lane.age_price * lane.reference_delivery_ms * lane.age_ms; - common += lane.age_price * (lane.age_ms + lane.reference_delivery_ms); - } + // Selected terminal lane is never excluded; continuing lane waits only during [0, finish]. + potential += terminal.age_price * terminal.reference_delivery_ms * terminal.age_ms; + reward -= continuing.age_price * (continuing.age_ms * finish + finish * finish / 2.0); + potential += + continuing.age_price * continuing.reference_delivery_ms * continuing.age_ms; + // Excluded lane waits for the full horizon and advances its continuation age by total. + reward -= excluded.age_price * (excluded.age_ms * total + total * total / 2.0); + potential -= excluded.age_price * excluded.reference_delivery_ms * total; + let common: f64 = [terminal, continuing, excluded] + .into_iter() + .map(|lane| lane.age_price * (lane.age_ms + lane.reference_delivery_ms)) + .sum(); assert!((selected - (reward + potential) / total - common).abs() < 1e-12); } } diff --git a/scripts/scheduling_sim/utility.py b/scripts/scheduling_sim/utility.py index a93033044..72bb0dab4 100644 --- a/scripts/scheduling_sim/utility.py +++ b/scripts/scheduling_sim/utility.py @@ -133,8 +133,11 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = self.ages.clear() measured = catalog if known_graphs is None else tuple(g for g in catalog if g.name in known_graphs) decoding = sum(not view.remaining_prefill for view in views) - reference_ms = min((decoding * graph.duration_ms / min(decoding, graph.decode_capacity) - for graph in measured if decoding and graph.decode_capacity), default=0.0) + reference = min( + ((graph.duration_ms / min(decoding, graph.decode_capacity), -min(decoding, graph.decode_capacity)) + for graph in measured if decoding and graph.decode_capacity), + default=None, + ) for view in views: actions = candidates([view], catalog, self.value) if not actions: @@ -142,7 +145,7 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = observed = [a for a in actions if known_graphs is None or a.graph.name in known_graphs] token_rate = max(((a.lanes[0].prefill + a.lanes[0].expected_output) / a.graph.duration_ms for a in observed), default=0.0) - delivery_rate = max((1 / a.graph.duration_ms for a in observed), default=0.0) if not view.remaining_prefill else 0 + has_delivery = (not view.remaining_prefill and any(a.graph.duration_ms > 0 for a in observed)) if view.name not in self.prices: self.prices[view.name] = RequestPrices(None, None, view.weight) prices = self.prices[view.name] @@ -152,19 +155,22 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = prices.tokens = ServicePrice.initial( self.config.token_fairness * view.weight, token_rate, len(views)) prices.tokens.rebase(token_rate) - if delivery_rate: + if has_delivery and reference is not None: + per_delivery_ms, neg_served = reference + served = -neg_served + served_share = served / decoding + excluded_wait_ms = (decoding - served) * per_delivery_ms self._delivery_normalizers.add(view.name) if prices.deliveries is None: prices.deliveries = ServicePrice.initial( - self.config.delivery_fairness * view.weight, delivery_rate, 1) - prices.deliveries.log_fraction = -log(reference_ms * delivery_rate) - prices.deliveries.rebase(delivery_rate) - self._references[view.name] = reference_ms - reference = self._references.get(view.name) - if not view.remaining_prefill and reference is not None and ( - delivery_rate or not mask_unknown_prices): + self.config.delivery_fairness * view.weight, 1.0, 1) + prices.deliveries.log_fraction = log(served_share) + self._references[view.name] = excluded_wait_ms + reference_wait = self._references.get(view.name) + if not view.remaining_prefill and reference_wait is not None and ( + has_delivery or not mask_unknown_prices): self.ages[view.name] = (now_ms - view.last_service_ms, - reference, view.weight) + reference_wait, view.weight) self.log_scale = max([0.0, log(self.value.decode_value), log(self.config.age_price) if self.config.age_price else float("-inf"), *(price.log_price - log(price.maximum_rate) @@ -176,9 +182,6 @@ def lane_value(self, lane: Lane) -> float: work = exp(-self.log_scale) * lane.useful_work(self.value) if prices.tokens is not None and (not self._mask_unknown_prices or lane.name in self._token_normalizers): work += prices.tokens.value(lane.prefill + lane.expected_output, self.log_scale) - if prices.deliveries is not None and lane.expected_output > 0 and ( - not self._mask_unknown_prices or lane.name in self._delivery_normalizers): - work += prices.deliveries.value(1, self.log_scale) return work def score(self, action: Action, *, preceding_ms: float = 0.0) -> float: @@ -187,17 +190,23 @@ def score(self, action: Action, *, preceding_ms: float = 0.0) -> float: raise ValueError("prerequisite duration must be finite and nonnegative") duration = preceding_ms + action.graph.duration_ms graph = replace(action.graph, duration_ms=duration) - reward = sum(self.action_lane_value(lane, graph) for lane in action.lanes) + reward = sum(self.action_lane_value(lane, graph, preceding_ms=preceding_ms) for lane in action.lanes) reward -= (exp(-self.log_scale) * self.config.age_price * duration * duration / 2 * sum(w for _, _, w in self.ages.values())) return reward / duration - def action_lane_value(self, lane: Lane, graph: Graph) -> float: + def action_lane_value(self, lane: Lane, graph: Graph, *, preceding_ms: float = 0.0) -> float: reward = self.lane_value(lane) + horizon = graph.duration_ms + service = max(0.0, horizon - preceding_ms) + prices = self.prices[lane.name] + if prices.deliveries is not None and lane.expected_output > 0 and service > 0 and ( + not self._mask_unknown_prices or lane.name in self._delivery_normalizers): + reward += prices.deliveries.value(service, self.log_scale) if lane.name in self.ages and lane.expected_output > 0: - age, reference, weight = self.ages[lane.name] - reward += (exp(-self.log_scale) * self.config.age_price * weight * reference - * (age + graph.duration_ms)) + age, excluded_wait, weight = self.ages[lane.name] + reward += exp(-self.log_scale) * self.config.age_price * weight * ( + excluded_wait * (age + horizon) + service * (age + (horizon + preceding_ms) / 2)) return reward def choose(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = 0.0) -> Action: @@ -219,8 +228,9 @@ def observe(self, duration_ms: float, committed: list[dict]): self.config.adaptation_ms, history=self.config.rate_history) if prices.deliveries is not None and (not self._mask_unknown_prices or name in self._delivery_normalizers): - prices.deliveries.observe(duration_ms, float(output > 0), self.config.adaptation_ms, + prices.deliveries.observe(duration_ms, duration_ms if output > 0 else 0.0, + self.config.adaptation_ms, history=self.config.rate_history) elif output and prices.deliveries is None: prices.deliveries = ServicePrice.initial( - self.config.delivery_fairness * prices.weight, 1 / duration_ms, 1) + self.config.delivery_fairness * prices.weight, 1.0, 1) diff --git a/tests/test_scheduling_learning_policy.py b/tests/test_scheduling_learning_policy.py index 2312782c1..c4fa7deaf 100644 --- a/tests/test_scheduling_learning_policy.py +++ b/tests/test_scheduling_learning_policy.py @@ -209,8 +209,8 @@ def test_invalid_gpu_sample_still_accounts_for_published_decode_service(policy): decision = s.choose([view(remaining=0)], 0) expected_token = replace(s.utility.prices["p"].tokens) expected_delivery = replace(s.utility.prices["p"].deliveries) - for price in (expected_token, expected_delivery): - price.observe(100, 1, UTILITY.adaptation_ms, history="service") + expected_token.observe(100, 1, UTILITY.adaptation_ms, history="service") + expected_delivery.observe(100, 100, UTILITY.adaptation_ms, history="service") finish(s, decision, 100, valid=False) prices = s.utility.prices["p"] assert prices.tokens.log_fraction == pytest.approx(expected_token.log_fraction) @@ -347,7 +347,7 @@ def sample(rng, name=name): decision = s.choose(views, 0) assert calls == {"one": 1, "two": 1} assert s.utility.prices["d0"].tokens.maximum_rate == pytest.approx(0.1) - assert s.utility.ages["d0"][1] == pytest.approx(15) + assert s.utility.ages["d0"][1] == pytest.approx(0.0) assert decision.metadata["sampled_costs_ms"] == {"one": 0.01, "two": 1000} diff --git a/tests/test_scheduling_utility.py b/tests/test_scheduling_utility.py index e5ae9705c..b6969ebec 100644 --- a/tests/test_scheduling_utility.py +++ b/tests/test_scheduling_utility.py @@ -176,16 +176,37 @@ def test_normalizer_changes_preserve_the_marginal_service_price(history): def test_delivery_reference_and_initial_price_use_feasible_batch_service(count): graphs = catalog() streams = [View(f"d{i}", 0, 4096, (1.0,) * 7) for i in range(count)] - expected = min(count * g.duration_ms / min(count, g.decode_capacity) - for g in graphs if g.decode_capacity) + per_delivery_ms, neg_served = min( + (g.duration_ms / min(count, g.decode_capacity), -min(count, g.decode_capacity)) + for g in graphs if g.decode_capacity) + served = -neg_served + expected_wait = (count - served) * per_delivery_ms + expected_share = served / count for extra_prefills in (0, 7): policy = scheduler(age=0.1) policy.prepare(streams + [View(f"p{i}", 32768, 4096, ()) for i in range(extra_prefills)], graphs) assert len(policy.ages) == count for stream in streams: - assert policy.ages[stream.name][1] == pytest.approx(expected) - assert policy.prices[stream.name].deliveries.value(1, 0) == pytest.approx(4 * expected) + assert policy.ages[stream.name][1] == pytest.approx(expected_wait) + assert policy.prices[stream.name].deliveries.value(1, 0) == pytest.approx(4 / expected_share) + + +def test_unexcluded_decoders_pick_peak_throughput_speculation_depth(): + graphs = ( + Graph("d1_w3", 31, decode_capacity=1, width=3), + Graph("d1_w6", 38, decode_capacity=1, width=6), + Graph("d4_w3", 34, decode_capacity=4, width=3), + Graph("d4_w6", 41, decode_capacity=4, width=6), + ) + # Conditional per-step acceptance giving cumulative survival [0.70, 0.45, 0.25, 0.20, 0.15]: + # E(3)=2.15 (69.4 tok/s at 31ms), E(6)=2.75 (72.4 tok/s at 38ms). + acceptance = (0.70, 0.45 / 0.70, 0.25 / 0.45, 0.20 / 0.25, 0.15 / 0.20) + policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + solo = [View("d0", 0, 512, acceptance)] + assert policy.choose(solo, graphs, 0).graph.name == "d1_w6" + batch = [View(f"d{i}", 0, 512, acceptance) for i in range(4)] + assert policy.choose(batch, graphs, 0).graph.name == "d4_w6" @pytest.mark.parametrize("count", [5, 16]) @@ -309,17 +330,24 @@ def test_age_continuation_satisfies_the_reference_poisson_equation(): values = (3., 7., 11.) cost = (0.2, 0.7) mean = sum(p * t for p, t in zip(probabilities, durations)) - second = sum(p * t * t for p, t in zip(probabilities, durations)) - references = [mean / sum(p * s[i] for p, s in zip(probabilities, served)) for i in range(2)] + references = [ + sum(p * t for p, t, s in zip(probabilities, durations, served) if not s[i]) + / sum(p for p, s in zip(probabilities, served) if s[i]) + for i in range(2) + ] expected_rate = sum(p * v for p, v in zip(probabilities, values)) / mean - expected_rate -= sum(c * (second / (2 * mean) + ref / mean * sum( - p * t for p, t, s in zip(probabilities, durations, served) if not s[i])) - for i, (c, ref) in enumerate(zip(cost, references))) + expected_rate -= sum( + c * sum(p * (t * t / 2 + ref * t) for p, t, s in zip(probabilities, durations, served) if not s[i]) / mean + for i, (c, ref) in enumerate(zip(cost, references)) + ) for ages in ((0., 0.), (0., 1000.), (53., 7.)): before = -sum(c * ref * age for c, ref, age in zip(cost, references, ages)) reward = 0 for p, t, s, v in zip(probabilities, durations, served, values): - immediate = v - sum(c * (age * t + t * t / 2) for c, age in zip(cost, ages)) + immediate = v - sum( + c * (age * t + t * t / 2) + for c, age, selected in zip(cost, ages, s) if not selected + ) after = -sum(c * ref * (0 if selected else age + t) for c, ref, age, selected in zip(cost, references, ages, s)) reward += p * (immediate + after - before)