Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #632

Raw Markdown for agents: https://autobot.eidonix.com/p/2e3ecb58-65d5-4e38-b8ba-c385c58aaa9c.md

#1 [high] Lens verdict: diff is lean; 3 concrete simplifications

PR #632 (hels/src/scheduler/rounds.rs +15/-10, policy_tests.rs +165, 2 docs). Lens: subtraction, simplicity, conventions.

Verdict: production change is lean and idiomatic — 6 net lines, no flags/knobs/env/config/ABI, no dead code, no speculative generality. Depth threading through 6 functions is genuinely required by the signature change (all call sites updated; search_code shows no missed caller). [0,1] clamp and running-min monotone bound untouched (rounds.rs:412-424). Nothing to delete in the docs but a long parenthetical.

Three concrete simplifications (full detail in follow-up notes): S1. rounds.rs:15-18 — i32::try_from(depth.saturating_add(1)).unwrap_or(30) is an unreachable fallback; .min(30) already bounds the value before/after the cast. Collapse to one line of safe arithmetic. Also the fn is spliced into the middle of the const block (:13 const, :15 fn, :19 const) — move below :25. S2. rounds.rs:47-53 vs 83-91 — the PR writes the identical if predicted > 1e-6 { ratio.clamp(0.0, calibration_factor_max(depth)) } else { 1.0 } twice. The PR touched both; extract one calibration_ratio(realized, predicted, depth) so the ceiling has one definition. Duplication pre-existing (#515/#522) but aggravated here. S3. policy_tests.rs:6449-6511 — new single_lane_packed_calibration_engine() re-plumbs a speculative graph catalogue that already exists twice (single_lane_packed_engine at :4300-4313; cost.rs:369-383 uses the in-repo make closure pattern for repetitive GraphDescriptor literals). 5 identical 13-field literals can be one iterator + struct update (~15 lines).

Also noted: policy_tests.rs:6513-6538 observe_single_lane_packed_round re-derives offered_drafts where packed_completion_records (:4315-4323) already does it.

Explicitly NOT a simplification (defer to Correctness lens): depth>=4 ceiling saturation (prior 0.5^(d+1) x ceiling 2^(d+1) = 1.0). Recommend not "simplifying" the helper to remove the ceiling, but the reviewer should ask whether an unbinding bound is intended — it is a semantics question, not a deletion.

#2 [high] S1 detail — rounds.rs:15-18 calibration_factor_max

FILE: helios/src/scheduler/rounds.rs

Verbatim, lines 10-26 (current head):

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;

fn calibration_factor_max(depth: usize) -> f64 {
    let steps = i32::try_from(depth.saturating_add(1)).unwrap_or(30).min(30);
    CALIBRATION_FACTOR_MAX.powi(steps)
}
const REQUEST_CALIBRATION_PRIOR_WEIGHT: f64 = 2.0;

Problems: (a) Function spliced INTO the const block: :19 const REQUEST_CALIBRATION_PRIOR_WEIGHT follows a fn. Every other const (:10-13, :19-25) groups together. Convention: const REQUEST_CALIBRATION_HALF_LIFE etc. all sit contiguously; the new fn should follow :25 const SURPLUS_FACTOR_MAX. (b) i32::try_from(depth.saturating_add(1)).unwrap_or(30) — the unwrap_or(30) arm is unreachable-as-intended and redundant with the following .min(30). On a 32-bit target usize can't exceed i32::MAX through saturating_add... actually it can (usize::MAX > i32::MAX on 64-bit), so try_from can fail; but then unwrap_or(30) gives 30, and .min(30) gives 30 — same result as clamping depth first. So the two error/overflow paths are already handled by one .min(30). (c) CALIBRATION_FACTOR_MAX.powi(steps) where steps is i32 — requires the cast dance only because powi takes i32 and depth is usize.

Simplification (net -3 lines, one min, no cast on the value path):

const CALIBRATION_FACTOR_STEPS_MAX: u32 = 30;

fn calibration_factor_max(depth: usize) -> f64 {
    let steps = u32::try_from(depth + 1).unwrap_or(u32::MAX);
    CALIBRATION_FACTOR_MAX.powi(steps.min(CALIBRATION_FACTOR_STEPS_MAX) as i32)
}

or, simplest and provably total:

fn calibration_factor_max(depth: usize) -> f64 {
    CALIBRATION_FACTOR_MAX.powi(depth.min(29) as i32 + 1)
}

(depth.min(29) + 1 == (depth+1).min(30) for all depth, no overflow, no conversion failure). Note: 2.0^30 is finite so no overflow concern; f64 magnitude is irrelevant either way.

Evidence that the cap value itself is duplicated: docs/scheduling-runtime-design.md:116-117 "exponent depth + 1 capped at 30" and helios/README.md:450 "with depth + 1 capped at 30". A named constant (CALIBRATION_FACTOR_STEPS_MAX) would give the docs a symbol to cite instead of a bare magic 30 in three places (rounds.rs:16, doc:117, README:450).

Also rounds.rs:13 CALIBRATION_FACTOR_MAX is now only read inside the helper (:17) — still fine, keep it, since docs:122 cite it by name.

#3 [high] S2 detail — duplicated clamp block, rounds.rs:47-53 / 83-91

FILE: helios/src/scheduler/rounds.rs

DepthCalibration::factor, :47-53 (the PR edited the clamp expression on :49):

    fn factor(self, depth: usize) -> f64 {
        if self.predicted > 1e-6 {
            (self.realized / self.predicted).clamp(0.0, calibration_factor_max(depth))
        } else {
            1.0
        }
    }

RequestCalibration::factor, :83-91 (the PR edited the clamp expression on :87):

    fn factor(self, depth: usize, global: DepthCalibration) -> f64 {
        if self.weight == 0.0 {
            global.factor(depth)
        } else if self.predicted > 1e-6 {
            (self.realized / self.predicted).clamp(0.0, calibration_factor_max(depth))
        } else {
            1.0
        }
    }

The six-line if predicted > 1e-6 { ratio.clamp(0.0, ceiling) } else { 1.0 } block is byte-identical between the two sites. This duplication predates the PR (#515 introduced it, #522 extended it), but #632 touches exactly these two lines — it is the natural moment to collapse them, and it is the kind of thing a reviewer should ask for now because the PR is only about the ceiling formula.

Concrete simplification (one definition of the ceiling, one epsilon policy):

fn calibration_ratio(realized: f64, predicted: f64, depth: usize) -> f64 {
    if predicted > 1e-6 {
        (realized / predicted).clamp(0.0, calibration_factor_max(depth))
    } else {
        1.0
    }
}

then DepthCalibration::factor body becomes calibration_ratio(self.realized, self.predicted, depth) and RequestCalibration::factor becomes:

    fn factor(self, depth: usize, global: DepthCalibration) -> f64 {
        if self.weight == 0.0 {
            global.factor(depth)
        } else {
            calibration_ratio(self.realized, self.predicted, depth)
        }
    }

Net: -4 lines and the 1e-6 guard + the clamp appear once each. Cite rounds.rs:47-53 and :83-91.

Verify no third site: search_code CALIBRATION_FACTOR_MAX|calibration_factor_max returns only rounds.rs:13, :17 (plus SURPLUS_FACTOR_MAX :25/:256 which is a different, flat bound and must not be folded in).

#4 [high] S3 detail — policy_tests.rs:6449-6511 catalogue duplication

FILE: helios/src/scheduler/policy_tests.rs, new helper :6449-6511.

Verbatim, :6466-6503 (the repeated part):

    graphs.push(crate::execution::GraphDescriptor {
        name: "speculative-b1-d0-w1".into(),
        kind: GraphKind::Speculative,
        sampling_mode: SamplingMode::General,
        handle: 100,
        batch_capacity: 1,
        draft_tokens: 0,
        token_capacity: 1,
        packed_token_capacity: 0,
        prefill_capacity: 0,
        estimated_duration_ns: 28 * MS,
        confidence_width: 0,
        tuned_bindings: vec![],
        input_bindings: vec![],
    });
    for (packed, nanos) in [
        (2usize, 29_500_000u64),
        (3, 31_200_000),
        (4, 35_000_000),
        (5, 37_000_000),
        (6, 38_800_000),
    ] {
        graphs.push(crate::execution::GraphDescriptor {
            name: format!("speculative-b1-d5-w6-p{packed}"),
            kind: GraphKind::Speculative,
            sampling_mode: SamplingMode::General,
            handle: 100 + packed,
            batch_capacity: 1,
            draft_tokens: 5,
            token_capacity: 6,
            packed_token_capacity: packed,
            prefill_capacity: 0,
            estimated_duration_ns: nanos,
            confidence_width: 5,
            tuned_bindings: vec![],
            input_bindings: vec![],
        });
    }

Two concrete simplifications:

(A) The (draft_tokens / token_capacity / confidence_width / batch_capacity / prefill_capacity / sampling_mode) fields are shared by all six literals and by the sibling helper. GraphDescriptor is a plain pub struct with public fields (helios/src/execution/manifest.rs:185) and the file already uses the spread pattern elsewhere (policy_tests.rs:1789-1792, 3783-3789 ..Default::default()), and cost.rs:369-383 wraps a repetitive literal in a local closure. Use one closure:

let spec = |name: String, handle: u64, drafts: usize, width: usize, packed, nanos| GraphDescriptor {
    name, kind: GraphKind::Speculative, sampling_mode: SamplingMode::General,
    handle, batch_capacity: 1, draft_tokens: drafts, token_capacity: width,
    packed_token_capacity: packed, prefill_capacity: 0, estimated_duration_ns: nanos,
    confidence_width: drafts, tuned_bindings: vec![], input_bindings: vec![],
};
graphs.push(spec("speculative-b1-d0-w1".into(), 100, 0, 1, 0, 28 * MS));
graphs.extend([(2usize, 29_500_000u64), (3, 31_200_000), (4, 35_000_000), (5, 37_000_000), (6, 38_800_000)]
    .into_iter().map(|(packed, nanos)| spec(format!("speculative-b1-d5-w6-p{packed}"), 100 + packed as u64, 5, 6, packed, nanos)));

~15 lines instead of 38, and confidence_width: drafts matches the invariant enforced at manifest.rs:850 (confidence_width != draft_tokens is rejected) — for the d0/w1 graph that yields 0, for the d5/w6 graphs 5, i.e. exactly the current values.

(B) The whole helper nearly duplicates the pre-existing single_lane_packed_engine(page_tokens) at :4300-4313, which already builds a confidence_width: 7 GPU packed shape on a b1 catalogue. Only difference: the new test needs capacities 2..6 with distinct measured durations and draft_tokens = 5. Parameterising the existing helper (single_lane_packed_engine(page_tokens, &[(packed, nanos)])) and deleting the new one removes ~60 lines of duplicated catalogue plumbing. If parameterising is judged too invasive for policy_tests.rs, at minimum (A) applies.

Overlap evidence: search_code single_lane_packed_engine → definition :4300, uses :4327, :4364, :4383. single_lane_packed_calibration_engine → definition :6449, uses :6544, :6583.

(C) Minor: observe_single_lane_packed_round (:6523-6524) recomputes the offered-draft count:

    let remaining = plan.packed_token_capacity.saturating_sub(plan.lanes.len());
    let offered = plan.lanes[0].tokens.saturating_sub(1).min(remaining).min(5);

packed_completion_records at :4315-4323 already sets offered_drafts from the same quantities for every lane (lane.tokens.min(plan.packed_token_capacity).saturating_sub(1)); reusing it and reading records[slot].vector.offered_drafts would remove the re-derivation. Note the existing helper also exists in lifecycle_tests.rs:28 — test-only duplication is tolerated in this repo, so (C) is a nit, not a should-fix.

(D) s.refresh.acceptance_credit_ns = 0.0; appears twice in a row at :6547 and :6553 with a plan() between them; the second is redundant with the first unless plan() mutates it (it does not — :6547 already zeroes it before the first plan()). Deleting :6553 changes nothing. (Correctness check: refresh.credit_ns is separately zeroed at :6548.)

#6 [high] Research summary

Subtraction, Simplicity & Conventions lens — PR #632

Verdict: the production diff is already lean and idiomatic. The rounds.rs change is +15/−10, adding one 4-line helper and threading depth through six functions. That threading is genuinely required by the signature change, every parameter is read, every caller is updated, and there is no flag, knob, env var, config key, manifest/Protobuf/ABI change, dead code, #[allow], TODO, or new pub surface. SURPLUS_FACTOR_MAX = 2.0 (rounds.rs:25) is correctly left flat and must not be merged with this ceiling. So my findings are three targeted cleanups, not a redesign — and I have explicitly not treated the depth ≥ 4 saturation effect as a simplification, since removing the ceiling is a semantics decision for the Correctness lens, not a deletion.

S1 — calibration_factor_max (rounds.rs:15-18). i32::try_from(depth.saturating_add(1)).unwrap_or(30).min(30) has an unreachable-by-design fallback: both the unwrap_or(30) arm and the trailing .min(30) produce the same value, so the conversion dance exists only to satisfy powi's i32. CALIBRATION_FACTOR_MAX.powi(depth.min(29) as i32 + 1) is provably total and identical, with no overflow and no conversion failure. Separately, the function is spliced into the middle of the const block — const REQUEST_CALIBRATION_PRIOR_WEIGHT at :19 follows a fn — whereas every other const groups at :10-13 and :19-25; it belongs after :25. Suggesting a named CALIBRATION_FACTOR_STEPS_MAX: u32 = 30 also gives the docs a symbol to cite instead of a bare 30 occurring in three places (rounds.rs:16, docs/scheduling-runtime-design.md:117, helios/README.md:450).

S2 — the clamp block is written twice (rounds.rs:47-53 and :83-91). This PR edits exactly the duplicated line in both places: if self.predicted > 1e-6 { (self.realized / self.predicted).clamp(0.0, calibration_factor_max(depth)) } else { 1.0 }. The duplication predates #515/#522, but since the PR's entire subject is that clamp expression, this is the moment to extract one calibration_ratio(realized, predicted, depth) so the ceiling and the 1e-6 epsilon policy have one definition. Net −4 lines, and RequestCalibration::factor reduces to an if weight == 0.0 delegation.

S3 — the new test fixture duplicates an existing one (policy_tests.rs:6449-6511). single_lane_packed_calibration_engine() re-plumbs a GPU-confidence single-lane packed catalogue that already exists as single_lane_packed_engine at :4300-4313, using six near-identical 13-field GraphDescriptor literals. Parameterising the existing helper (page_tokens, plus a &[(packed, nanos)] slice) and deleting the new one removes ~60 lines; if that is judged too invasive, a local builder closure in the cost.rs:369-383 idiom collapses the 38 literal lines to ~15 and lets confidence_width: drafts carry the invariant already enforced at manifest.rs:850 (not opened). Two nits inside the same test: observe_single_lane_packed_round re-derives offered_drafts where packed_completion_records (:4315-4323) already does it, and s.refresh.acceptance_credit_ns = 0.0 is set twice at :6547 and :6553 with only a non-mutating plan() between them, so :6553 is removable.

One low-severity doc cut: the helios/README.md:449-453 parenthetical (...capped at 30 so a per-step ceiling of 2 compounds across the cumulative depth + 1-step Rényi-2 collision survival product ...) is now longer than the sentence it modifies, while the same derivation is already specified at docs/scheduling-runtime-design.md:113-123. Keep README at clamped to [0, 2^(depth+1)]. Everything else in both docs is a clean one-for-one replacement with no stale text left behind, and docs/mtp-design.md:173-180 (not opened) remains accurate.

Full verbatim quotes, replacement code and per-point evidence are in scratchpad notes 1-5.

#7 [high] Final-report exact quotes + caveats on nits C/D

Two items the final report quotes or relies on that are not verbatim in notes 1-5.

(1) EXACT README text for the low-severity doc cut — helios/README.md:446-453 as it now reads:

outcomes. When pricing GPU-confidence shapes, stored per-depth forecasts are
scaled by a request-local aged per-depth verification calibration ratio (seeded
scale-invariantly with prior weight `2` from a once-per-round population prior
capped at weight `64`, 128-token half-life, request EWMA cap `32`, clamped to
`[0, 2^(depth + 1)]` with `depth + 1` capped at `30` so a per-step ceiling of
`2` compounds across the cumulative `depth + 1`-step Rényi-2 collision
survival product `prod_{j=0..depth} sum_i q_{j,i}^2`), and crowded

The parenthetical opens at (seeded and closes after q_{j,i}^2``) — 6.5 lines of parentheses inside a 3-line sentence. Suggested README form: clamped to [0, 2^(depth + 1)])` and let docs/scheduling-runtime-design.md:113-123 carry the Rényi-2 derivation, where it already reads:

   + `DepthCalibration`):** Both calibration levels clamp `realized / predicted`
   to `[0.0, calibration_factor_max(depth)]` (defaulting to `1.0` when
   `predicted <= 1e-6`), where `calibration_factor_max(depth) = 2.0^(depth + 1)`
   with exponent `depth + 1` capped at `30`.

Note the design doc names the helper calibration_factor_max(depth), i.e. docs already cite the code identifier — which is the reason to keep CALIBRATION_FACTOR_MAX and to name the cap constant (S1).

(2) CAVEAT on nit (D) in entry 4. I claim policy_tests.rs:6553 s.refresh.acceptance_credit_ns = 0.0; is redundant because :6547 sets the same field and only a plan() call sits between them. The "plan() does not mutate acceptance_credit_ns" half is INFERRED from reading plan() at a high level, not proven by tracing every mutation site in refresh. The final report must phrase this as "appears redundant — confirm plan() does not write acceptance_credit_ns before deleting", not as a deletion instruction. Note the test deliberately re-zeroes the field in the loop at :6558 to defeat CREDIT_CAP_NS accrual, so the field is definitely written elsewhere; that makes the :6553 claim specifically about the single pre-loop plan() at :6550. Similarly nit (C) is safe as stated: packed_completion_records :4315-4323 sets offered_drafts from lane.tokens.min(plan.packed_token_capacity).saturating_sub(1), whereas the new helper uses lane.tokens.saturating_sub(1).min(packed - lanes.len()).min(5) — these are NOT identical expressions (the new one subtracts lane count and caps at 5). So (C) is a reuse-shaped observation, not an exact-equivalent substitution; the final report should say "reuse or consolidate" rather than "replace with the existing helper", or a correctness regression could be introduced for multi-lane plans. Flag as nit only.

#5 [medium] Negative findings + doc parenthetical

Checked for removables that are NOT there (so the report can say so plainly):

Convention note (not a violation of AGENTS.md, but of local idiom): rounds.rs groups its consts at :10-25; the new fn at :15-18 splits them. Also helios/Cargo.toml sets no clippy pedantic deny, and the repo's only clippy allowances are too_many_arguments (21 sites) — RequestCalibration::observe now takes 6 args (rounds.rs:93), under the threshold, so no allowance is needed. Good.