Subtraction and simplicity report · NVIDIA/hyperflare-inference #693

Raw Markdown for agents: https://autobot.eidonix.com/p/41cdf155-f674-4495-84a1-0d9ecc8b078a.md

Subtraction, Simplicity & Conventions — PR #693

Key findings

  1. The same optimization is expressed twice. Six near-identical wrappers now surround one computation (lane_value, cached_lane_value, cached_lane_value_within, lane_value_for_tokens, lane_value_for_tokens_within, cached_lane_value_for_tokens_within), and the Option<&mut CurveCache> parameter plus its None => self.expected_speculative_tokens(...) fallback exists to serve exactly one production site, policy.rs:1997. Delete the Option, thread one &mut CurveCache through resize_prefill, and roughly 40 production lines go with no behavioural change (policy.rs:1387-1524).
  2. CurveCache.optimistic is dead state and is already inconsistent at one call site. Delete the field, the optimistic argument of get_or_insert_with, and the debug_assert_eq! rather than patching policy.rs:1714 (policy.rs:98-130 vs policy.rs:1714 and rounds.rs:844).
  3. The tokens <= 1 short-circuit is written twice, in two modules, both encoding f64::from(tokens != 0), which is exactly what forecast_tokens already returns for width ≤ 1 (rounds.rs:626-631 vs policy.rs:1393-1395).
  4. CURVE_EVALUATIONS and three of the four new tests re-add a test-only counter that the review of #540 asked to be deleted, and after this PR's own alpha-1 shortcut the counter no longer measures the powf cost it was introduced to bound (rounds.rs:10-14, :634-636; policy_tests.rs:9489/9517/9545).
  5. Everything else is lean and idiomatic. The alpha-1 shortcut, the limit <= 1 { continue; } skip, and the slot-indexed fixed array all fit existing module conventions; no AGENTS.md structural rule (env var, flag, per-model branch, fallback layer) is violated.

Correction to my working notes: I initially believed the None arm was production-unreachable. That is wrong — policy.rs:1997 reaches it. The finding below is restated on the verified reachability.


1. Option<&mut CurveCache>, its None fallback, and the six-wrapper family — delete the Option, thread the single remaining caller

helios/src/scheduler/policy.rs:1387-1404:

    fn cached_expected_tokens(
        &self,
        r: &LiveRequest,
        tokens: usize,
        curves: Option<&mut CurveCache>,
    ) -> f64 {
        if tokens <= 1 {
            return f64::from(tokens != 0);
        }
        match curves {
            Some(curves) => {
                let curve = curves
                    .get_or_insert_with(r.handle.slot as usize, false, || self.powered_curve(r, false));
                super::rounds::forecast_tokens(curve, tokens)
            }
            None => self.expected_speculative_tokens(r, tokens),
        }
    }

Verified reachability of the None arm (I traced every None producer):

        if mixed {
            let decode = if self.speculative_widths.is_empty() { GraphKind::Decode } else { GraphKind::Speculative };
            expected += bits(candidate.mask & !(1 << slot)).map(|slot| {
                self.lane_value(self.slots[slot].request.as_ref().unwrap(), decode,
                    candidate.capacity, duration_ns, values[slot])
            }).sum::<f64>();
        }

So an entire Option marshalled through cached_expected_tokens, cached_lane_value_for_tokens_within, prerequisite_value (policy.rs:1021) and next_progress (policy.rs:900) exists for one line, and next_progress pays for it with a throwaway allocation on the None path.

Concrete simplification:

2. Delete CurveCache.optimistic — it is dead state, and it is already wrong at one call site

helios/src/scheduler/policy.rs:98-130:

/// Per-slot memoization of powered speculative survival curves within one pricing pass.
/// Each cache instance is bound to one `optimistic` mode so optimistic and ordinary curves never mix.
pub(super) struct CurveCache {
    optimistic: bool,
    entries: [Option<Vec<f64>>; REQUEST_LANES],
}
...
    pub(super) fn get_or_insert_with(
        &mut self,
        slot: usize,
        optimistic: bool,
        build: impl FnOnce() -> Vec<f64>,
    ) -> &[f64] {
        debug_assert_eq!(
            self.optimistic, optimistic,
            "CurveCache cannot mix optimistic and non-optimistic survival curves"
        );
        self.entries[slot].get_or_insert_with(build)
    }

Nothing reads an optimistic curve back out of the cache: the optimistic mixed branch bypasses it outright —

                        Some(kind) if kind == decode => {
                            decoders[count] = (
                                slot,
                                if optimistic { values[slot].decode(self.optimistic_tokens(r, self.speculative_tokens(r, width)), duration_ns as f64 / 1e6) }
                                else { self.cached_lane_value(r, decode, width, duration_ns, values[slot], curves) },
                            );

(policy.rs:1767-1774, bypass at :1770), and the ordinary scheduler path passes a literal false at policy.rs:1399. Meanwhile the two construction sites disagree:

Do not fix policy.rs:1714 to CurveCache::new(optimistic). That keeps a field, a parameter on two public-ish constructors, a per-call bool in every signature, a debug assertion and a latent trap, all guarding a distinction no code observes. Delete optimistic from the struct, new(), and get_or_insert_with(&mut self, slot, build), delete the doc sentence at policy.rs:99 and the debug_assert_eq! at :119-122, and change the call sites to CurveCache::new() / get_or_insert_with(slot, …). This is the "delete the workaround, don't patch it" case: pure subtraction, no behaviour touched, and it removes the only reason the tag inconsistency matters.

3. The tokens <= 1 short-circuit is duplicated across modules — keep it in one place

helios/src/scheduler/rounds.rs:626-631:

    fn proposal_forecast_tokens(&self, request: &LiveRequest, width: usize, optimistic: bool) -> f64 {
        if width <= 1 {
            return f64::from(width != 0);
        }
        forecast_tokens(&self.powered_curve(request, optimistic), width)
    }

is the same rule the PR adds at policy.rs:1393-1395:

        if tokens <= 1 {
            return f64::from(tokens != 0);
        }

Both encode f64::from(tokens != 0), which is exactly what forecast_tokens computes on its own — f64::from(width != 0) + powered[..width.saturating_sub(1)].iter().sum() (rounds.rs:1016-1019), whose sum is empty for width <= 1. So the guard is an optimization tweak, not a distinct rule, and it now exists in two forms in two files with no shared name. After finding 1 there is one expected-tokens function anyway; fold the guard into it and have the width-form (proposal_forecast_tokens) delegate. If you want to keep the guard at both layers for the hot path, at least express it once, e.g. fn forecast_tokens_upto(powered, width) in rounds.rs and call it from policy.rs, so the identity "0/1 tokens ⇒ 0.0/1.0" is stated in one place and cannot drift.

4. CURVE_EVALUATIONS + is_cached + three of the four new tests re-add what #540's review asked to be removed

helios/src/scheduler/rounds.rs:10-14:

#[cfg(test)]
thread_local! {
    /// Powered speculative curve evaluations on this thread, for tests that bound planning work.
    pub(super) static CURVE_EVALUATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

and rounds.rs:634-636: #[cfg(test)] CURVE_EVALUATIONS.set(CURVE_EVALUATIONS.get() + 1);

Per the dossier, this counter and its two call-count tests were introduced in #540 and the review of #540 recommended deleting both ("Subtract/Simplify"); neither exists on main today, so #693 reintroduces them without saying why. It backs three tests — waiting_init_prices_each_decoding_lane_curve_once_per_candidate_pass (policy_tests.rs:9489), mixed_candidates_price_each_decoding_lane_curve_once_per_call (:9517), decode_only_candidate_pass_builds_no_forecast_curve (:9545) — plus the #[cfg(test)] accessor is_cached (policy.rs:126-129), used only at policy_tests.rs:9645-9653.

Two further reasons it is the wrong instrument here:

Recommendation: delete CURVE_EVALUATIONS, is_cached and the three counting tests (~90 test lines plus the thread-local); if a bound is genuinely wanted, assert is_cached inside the equality test, which already loops the shapes. Contrast cost.rs:15-19's ENTRY_LOOKUPS, which is load-bearing for existing checkpoint tests — this counter has no such dependency.

5. Smaller, same-direction deletions

What is already lean — do not touch

Net effect of all five: roughly 40-60 lines of production plumbing (the Option threading, the None arm, three wrapper functions, the mode tag, the expected_speculative_tokens residual) and ~100 lines of test scaffolding (counter, is_cached, three tests) disappear without losing a single behavioural assertion.


Open questions / could not verify

  1. rounds.rs citations (:10-14, :622, :626-631, :634-636, :844, :892-894, :1016-1019) are taken from the PR description and dossier, not re-read in this session; the code quoted above from policy.rs was read directly at head.
  2. Does expected_speculative_tokens (rounds.rs:622) have any caller other than the None arm at policy.rs:1402? If not, finding 1 makes it dead code — worth a grep before deleting.
  3. Is threading a cache into resize_prefill cheap enough to accept? It runs once per resized prefill candidate (policy.rs:1924-1935), so the extra dedup is strictly less work than today's uncached re-pricing at policy.rs:1993-1999, but that is a measurement I did not take.
  4. Why re-add CURVE_EVALUATIONS after #540's review asked for its removal? No rationale in the PR.
  5. The next_progress branch restructure (policy.rs:946-1012) is described only as "reuses cached_expected_tokens"; its equivalence is a correctness question for the Correctness lens, but note that it moved decode pricing inside the else and now early-returns at policy.rs:980 — if that restructure is not in fact needed for the cache, reverting it is the largest available subtraction of all.