Skip to content

Retain bounded timing-refresh credit across idle and exclude readiness wait - #540

Open
FujitsuPolycom wants to merge 1 commit into
NVIDIA:mainfrom
FujitsuPolycom:pr/core-helios-sam-copy-drafts-and-cost-refresh
Open

FujitsuPolycom wants to merge 1 commit into
NVIDIA:mainfrom
FujitsuPolycom:pr/core-helios-sam-copy-drafts-and-cost-refresh

Conversation

@FujitsuPolycom

@FujitsuPolycom FujitsuPolycom commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Why

Helios remeasures stale retained graph durations through a funded refresh ledger (helios/src/scheduler/refresh.rs) earning 0.002 / 0.998 of ordinary execution duration up to a 5 ms cap (2,495 ms of ordinary execution for a first refresh) and subtracting the executed refresh duration on completion. Before this change, two defects blocked stale cost recovery under normal serving workloads:

  1. RequestScheduler::idle zeroed positive timing-refresh and acceptance-learning credit while keeping negative debt. Workloads of sequential requests shorter than 2,495 ms separated by idle gaps never reached 5 ms of credit, leaving stale estimates unrefreshed indefinitely even though idle intervals add neither credit nor ordinary execution time and retaining bounded earned credit (<= 5 ms) preserves the aggregate expense bounds P <= (0.002 / 0.998) * O + D (timing refresh) and P <= (0.01 / 0.99) * O + D (acceptance learning).
  2. RefreshState::complete credited and charged raw physical duration (cost::observed_duration_ns), whereas ActionCosts::observe records device execution time less measured embedding-delivery readiness wait (gpu_ns - wait_ns). Disk-backed readiness stalls inflated timing-refresh debt even though retained cost estimates excluded them; subtracting wait_ns without guarding gpu_ns <= wait_ns would charge 0 ns when readiness wait met or exceeded the GPU interval while ActionCosts::observe discarded the 0-ns sample, leaving the target stale with full credit.

ActionCosts::refresh_order remains observed_at_ns.max(last_attempt_ns) so expensive stale shapes (D > ttl_ns / 499 = 60.12 ms at the 30 s TTL) that re-expire during debt refill cannot starve smaller stale shapes.

What changed

  • helios/src/scheduler.rs, helios/src/server/runtime.rs, helios/src/scheduler/refresh.rs:
    • Before: RequestScheduler::idle(&mut self) called RefreshState::idle to clear positive timing-refresh and acceptance-learning credit to zero while preserving negative debt, and RefreshState::complete used cost::observed_duration_ns for both ledgers.
    • After: RefreshState::idle is removed and RequestScheduler::idle is renamed to RequestScheduler::assert_idle(&self) to verify only that no scheduled execution remains in flight; RefreshState::abort continues to discard positive credit and preserve negative debt. Ordinary completions earn timing-refresh credit from cost::observed_compute_duration_ns, and PlanOrigin::RefreshStart completions subtract observed_compute_duration_ns(timing).or_else(|| observed_duration_ns(timing)).unwrap_or(timing.wall_ns). Every validated refresh completion incurs a strictly positive charge because RefreshState::validate_completion rejects non-isolated probes and probes lacking both a positive GPU interval and wall_ns. Acceptance-learning income and PlanOrigin::AcceptanceStart charges continue using raw physical duration.
  • helios/src/scheduler/cost.rs:
    • Before: Only raw physical duration (observed_duration_ns) was exposed for refresh accounting.
    • After: Add observed_compute_duration_ns, returning the device interval (or max(device, wall) when isolated) less measured readiness wait when gpu_ns > wait_ns, and None otherwise (ActionCosts::observe deliberately omits wall_ns).
  • scripts/scheduling_sim/learning_policy.py, scripts/scheduling_sim/learning.py:
    • Before: LearningScheduler.idle unconditionally discarded positive exploration credit.
    • After: Add --retain-idle-credit (PolicyConfig.retain_idle_credit), defaulting to True for retained-refresh so the simulator's qualified policy matches Helios and False for other exploratory policies, while keeping retain_idle_credit=False expressible in --configs / --comparison-configs JSON for reproducing the prior discarding rule.
  • helios/README.md, docs/scheduling-runtime-design.md, docs/scheduling-theory.md, helios/src/scheduler/policy_tests.rs, tests/test_scheduling_learning_{policy,experiments}.py:
    • Update present-state specifications across all three documents, deduplicate prefill-catalog test builders (prefill_catalog_engine) and boolean CLI-flag assertions, and add end-to-end regression tests for idle-separated short-request recovery, D = 145 ms > ttl_ns / 499 non-starvation, and readiness-wait exclusion across gpu > wait, gpu == wait, gpu < wait (wall_ns == 0 and > 0), and absent GPU timing (wall_ns == 0 rejected by validate_completion, wall_ns > 0 charged).
  • Compatibility: No model core format, Protobuf schema, Flare CLI flag, or captured-graph operation contract changes; existing signed cores load without re-export or re-signing.

Claimed benefit and result

  • Expected runtime benefit: Idle-separated request bursts shorter than 2,495 ms accumulate bounded earned credit (<= 5 ms) and recover stale graph cost estimates while preserving aggregate budget bounds and round-robin refresh ordering; measured embedding-delivery readiness stalls no longer inflate timing-refresh debt when gpu_ns > wait_ns, and wait_ns >= gpu_ns completions charge unexcluded physical or wall time. Live GPU serving throughput was not measured in isolation on this PR.
  • 64-seed simulator validation (--preset validate --reference ttl, 62 scenarios, 64 heldout seeds 10000..10063): retained-refresh:funded:cumulative:alpha=0.002 (retain_idle_credit=True default) passed all evaluated gates (41/41 passed, complete_core_suite=true, complete_validation_suite=true):
    • Core stationary vs ttl (35/35 passed): geomean busy useful throughput ratio 1.009886 (worst paired seed-cluster LB 0.999357 >= 0.98), worst p99 decode-gap UB 1.033553 <= 1.05 (worst scenario mean 1.024200), worst p99 TTFT UB 1.047665 <= 1.05, 0/2,240 stationary resets.
    • Core stationary vs retained-refresh:funded:cumulative:alpha=0.002:retain_idle_credit=False (--comparison-configs): 35/35 passed, exact 1.000000 parity (min = max = 1.000000).
    • Core stationary vs known diagnostic reference: 19/35 passed, geomean throughput ratio 0.994760.
    • Recovery & mature-1000 (8/8 scenarios): 64/64 seeds recovered within 60,000 busy ms on every scenario; uncertainty calibration passed (coverage_16 = coverage_1000 = 1.0); idle transients (idle-29s, idle-31s, idle-120s, idle-3600s, idle-short-burst): 0 spurious probes across all 320 seed runs.
  • Scope boundary: Does not change continuous-busy debt refill rates (499 * D for timing refresh, 99 * D for acceptance learning) or acceptance-learning debt after large physical probe episodes.

Supporting evidence and limitations

Tested on git archive cdf1185d69254c58e8ee50dabbab3dc8e43a01ce atop main (ba3afb13a7e9836080c23eadf8e1c17ee96e6e7a) on Linux/WSL2 x86_64 (rustc 1.100.0, plain local ext4 storage):

  • Layer 1 — CPU unit, integration, and CLI tests (--locked --release):
    • pytest across 9 scheduler/prefill suites (test_scheduling_{continuation,oracle,timing,learning_policy,learning_run,learning_experiments,sim,utility}.py, test_prefill_capacities.py), tests/preparation/test_core_boundary.py, tests/test_design_review_hook.py, and tests/cli: 941 passed, 0 failed, 0 skipped.
    • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target -- --test-threads=1 (under 64 MiB RLIMIT_MEMLOCK with FLARE_TEST_TEMPLATE_DIR populated): 1,690 unit + 61 integration = 1,751 passed, 80 ignored (43 + 37), 0 regressions; untouched model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape panics identically on origin/main (ba3afb13a7e9836080c23eadf8e1c17ee96e6e7a and 2bdc8472e492ad392cc795563d5b0f8db47a5a25) at helios/src/model/packed_round_tests.rs:106:9 (missing Speculative batch 2).
    • cargo test --locked --release --manifest-path flare/Cargo.toml --target-dir flare-cli/target: 236 passed (228 + 7 + 1), 4 ignored, 0 failed.
    • cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 225 passed (201 + 7 + 6 + 4 + 7), 3 ignored, 0 failed.
    • cargo test --locked --release --manifest-path heliopause/Cargo.toml --target-dir flare-cli/target: 208 passed, 5 ignored, 0 failed.
    • eos: 2 passed; selene --features test-support: 506 passed (505 + 1), 0 failed.
  • Layer 2 — Scheduling simulator (scripts/scheduling_sim/learning.py):
    • 16-seed --preset screen --policies retained-refresh --alpha 0.002 --credit-cap-ms 5 --reference ttl nominated retained-refresh:funded:cumulative:alpha=0.002 (retain_idle_credit=True), and 64-seed --preset validate with --comparison-configs (retain_idle_credit=False) accepted it across all 62 scenarios.
  • Layer 3 — Formal lifecycle conformance (verification/helios-lifecycle/check.py):
    • Temurin JRE 21.0.13 + tla2tools.jar 1.7.4: all 9 TLA+ models (10 TLC model runs including DispatchRing.tla and Speculation16.cfg) passed with 0 errors and verified 593,660 observed Rust transitions across all 8 conformance suites (Lifecycle 1,342; RankProtocol 1,291; DispatchRing 7,940; OffloadTransfer 8,490; CacheOwnership 195,492; Speculation 13,566; ResponseLifecycle 365,508; CheckpointReservation 31).
  • Limitations and unrun checks:
    • Live GPU and HTTP serving qualification (tests/server/test_scheduler.py, live power-cap cost-refresh recovery, and disk-backed embedding-delivery readiness stalls) was not executed on GPU hardware and remains tracked in docs/TODO.txt (Qualify retained graph costs and funded remeasurement in live Helios).
    • cargo kani, cargo-mutants, and check.py --mutations were not run (no completion-vector validator, state-view extent arithmetic, or lifecycle safety guard was modified).

Discord: Dooner

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 540.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents · Value Proposition · Case File

Recommendation: Changes Requested

One blocker: wide copy-verify graphs are silently relabelled as MTP on the only core-export path, so the feature never runs on an exported core. Commit a85be397 (funded-refresh recovery) is correct, self-contained and could merge on its own today.

Blockers:

  • heliopause/src/export/binding.rs:201 unconditionally writes draft_source = "MTP" while converting the manifest to the wire Execution (capture.rs:3158, the sole export route), so graphs the producer emits with draft_source = 2 (ignition/preparation/execution.py:32,316-319) arrive at load as MTP and are pruned by helios/src/runtime_core/selection.rs:277-298 (copy_wide needs 2; the MTP branch needs draft_tokens <= drafts). Wide copy-verify is dead on every exported core, silently — and the coercion also skips the copy-only contract checks (helios/src/execution/manifest.rs:844-846, helios/src/model/catalog.rs:123-131). Derive the enum name instead of overwriting (2 => "COPY_DRAFT", unknown => invalid(...)) and add one binding::execution round-trip test.

Should fix:

  • docs/cli-design.md:200-202 (and :742, docs/mtp-design.md:22-29) still say --history-drafts "does not change the graphs"; it now retains/prunes copy-only graphs, drops kernels (selection.rs:375-380) and rewrites speculative_widths (:382-396).
  • Fill three documentation gaps, not more: docs/mtp-design.md:31-40 → SAM-first with the ring as fallback (caps, min_match_len = 6); docs/scheduling-runtime-design.md:6-12 module index + a short draft_source/wide-copy section, :249-254 → the new strictly-tighter-batch pruning rule, :396-399 → the copy/MTP packed-duration split; helios/manifest.md:29-53 → draft_source.
  • One authority for the proposal source: cost::Key (cost.rs:151-158) omits draft_source yet prepared() rejects duplicate shapes (:159-161), so an MTP and a copy graph with identical B/D/W/P cannot coexist and is_copy_only_step (:223-232) has to infer the source from the table; has_mtp (:192-196) is an existence scan, so one unmeasured MTP entry suppresses measured copy entries and packed_round_duration returns None for a shape that was measured.
  • Give 0.88, 4.0, 2.0, +3 and 6 a stated derivation (speculation.rs:15-21, rounds.rs:766, sam.rs:22); only the 6 is argued today. Also reject draft_source = 2 on mixed in ignition/preparation/execution.py:104-108, which selection.rs:278-283 does not accept.
  • Evidence: per-commit live numbers (four outcomes bundled into 25 files cannot be attributed or bisected), state that the 13.05 ms / 4.52 MiB SAM build is paid synchronously at admission per request (scheduler.rs:1849-1852), and add one load-and-serve of an already-exported W=8 core plus one preempt→readmit SAM test (server/runtime.rs:2068-2108 re-indexes generated text through the prompt).

Subtract / Simplify:

Could remove ~550–685 of +3,965 added lines:

  • ~150–250 test lines: fold helios/src/model/tests.rs:846-953 into :1861-2075, drop the duplicated legacy-load assertion (:1873-1888), trim helios/src/scheduler/tests.rs:1995-2127 to admission + isolation.
  • ~100 lines: helios/src/scheduler/rounds.rs:755-903 duplicates the ordinary candidate loop at :905-1060; one loop with a per-slot curve provider, which also collapses the curves/copy_curves caches (:747-748).
  • ~150 lines of SAM API with no production caller: propose_conditional_continuations (sam.rs:1112-1189, doc names a "2-deep pipelined execution" that exists nowhere), propose_for_context (:1068-1110), MatchSource/MatchProposal::source, PromptSAM::build, push_slice, unread accessors; re-point the oracle at propose.
  • ~87 lines of duplication: one private helper for helios/src/scheduler.rs:1112-1205 (already drifted on the zero-count ring case), delete the unreachable wide_copy_curve else (rounds.rs:541-548), delete the empty RefreshState::idle and its no-op test calls (refresh.rs:95-99, ~10 call sites), one ProposalSource::from_wire instead of three ladders (serving.rs:58-63, python.rs:225-233, selection.rs:144-148). Do not drop Candidate.expected — it is a real second quantity.

Nits:

4 nits

To opt out, include #autobot:ignore in your post or comment.

@FujitsuPolycom
FujitsuPolycom force-pushed the pr/core-helios-sam-copy-drafts-and-cost-refresh branch from 7ca5430 to 1401971 Compare November 26, 2026 18:02
FujitsuPolycom added a commit to FujitsuPolycom/hyperflare-recipes that referenced this pull request Nov 26, 2026
When Helios dispatches a wide copy-verify round (`draft_source=COPY_DRAFT`,
`W=16` or `W=24`) backed by a long prompt or output match, running the
3-layer `DSpark` drafter, `draft_head`, 7-step `Markov` head,
`confidence_head`, and `PreparedCausalPrefixAllocation` adds wasted
draft latency before verifying host-supplied copy tokens. Skipping the
draft stages while verifying all `W` tokens through the full 40-layer
target decoder and updating `PreparedContext` for every accepted token
preserves exact `0-ULP` target distribution parity and keeps DSpark's
sliding-window context KV exact for subsequent learned-draft rounds.

Before this change, `PreparationConfig` in
`hyperflare_recipes/recipes/deepseek41/bootstrap.py` prepared only
DSpark-backed speculative rounds (`W <= 8`), `SpeculativePreparation`
did not size `copy_token_ids` for wider copy rounds, and
`PreparedParallelDraftRound.verify` always read active lane limits from
`o.inputs.query_lengths`. This commit:
- Adds `copy_draft_tokens` on `SpeculativePreparation`
  (`hyperflare_recipes/components/dspark.py`) to size `copy_token_ids` to
  `max(7, draft_tokens, copy_draft_tokens)` and expose the four copy-proposal
  buffers (`copy_token_ids`, `copy_token_count`, `copy_expected_consumed`,
  `copy_generation`) via `buffers()` (aligned with PR local-inference-lab#48).
- Adds an optional `token_limits` override on
  `PreparedParallelDraftRound.verify` (plus `DraftProposalState.copy_offered_mask`
  and the copy-proposal validation/point-mass overlay helpers shared with
  PR local-inference-lab#48 so this branch compiles and passes tests cleanly atop `main`) and
  introduces `PreparedCopyOnlySpeculativeRound` in
  `hyperflare_recipes/components/parallel_draft.py`, allocating a persistent
  1-element `int64` device tensor `self.local_vocab_start` in `__init__` (so
  vocabulary-parallel TP ranks bind per-rank offsets via `USE_VOCAB_START_PTR`
  without baking a rank-0 Dynamo guard), skipping `DSpark`, `Markov`,
  `confidence_head`, and `PreparedCausalPrefixAllocation`, validating copy
  freshness, grammar gating, and in-vocab contiguity, applying point-mass
  `q = 1.0` proposals without mutating host-uploaded `query_lengths`, running
  target verification (including `vocabulary_parallel` sharded tile masses),
  committing KV pages, SWA rings, and `CompletionOutputs`, and executing
  `PreparedContext` over accepted target hidden states.
- Adds opt-in `copy_verify_shapes: tuple[tuple[int, int], ...] = ()` on
  `PreparationConfig` in `hyperflare_recipes/recipes/deepseek41/bootstrap.py`
  with strict shape validation (`batch` in `batch_capacities(max_active)`,
  `width > max(speculative_widths)`, `width <= 64`,
  `batch * width <= speculative_token_capacity`), wires
  `copy-speculative{B}x{W}` graphs (`draft_source=2`, `confidence_width=0`,
  `draft_tokens=W-1`, no `speculative_prefix_limits`), updates
  `completion_token_capacity`, collective runtimes, verification samples,
  `server_config`, and keeps `prepare_contract(..., rows=max(config.speculative_widths))`
  so `state_rows_per_request` remains 8 with zero extra state-pool storage.
- Adds 16 CPU and `make_fx` unit tests in
  `tests/recipes/test_deepseek41_sam_wide_skip.py`.

Default `copy_verify_shapes=()` leaves catalog graphs, buffer dimensions,
`state_rows_per_request`, and execution behavior 100% identical to the
preceding revision. Enabling `copy_verify_shapes` (for example
`((1, 16), (1, 24), (2, 16), (4, 16))`) exposes copy-only wide graphs
requiring zero extra target scratch memory beyond the existing
`P <= 64` verify arena and zero extra state-pool rows.

Evidence and limits:
- CPU pytest (`CUDA_VISIBLE_DEVICES=""`, atop `main` `24849d9`) against
  `NVIDIA/hyperflare-inference#540` (`GraphSignature.draft_source`):
  `tests/recipes/test_deepseek41_sam_wide_skip.py` (16 passed, 0 failed,
  covering `W=16`/`W=24` full acceptance, 15-bit and 23-bit `copy_offered_mask`,
  `PreparedContext` exact update, partial rejection across positions
  `[0, 1, 7, 14, 15, 22, 23]`, freshness/grammar/contiguity/non-mutation,
  exact stochastic rejection marginal with negative sensitivity check,
  4-rank `vocabulary_parallel` sharded tile verification, persistent
  `local_vocab_start` tensor binding, and `make_fx` tracing for `W=16` and
  `W=24`).
- Default `copy_verify_shapes=()` preserves baseline DeepSeek-V4.1 Flash TP4
  export and `flare run` serving on `4x RTX PRO 6000 Blackwell` (SM120, PCIe
  Gen5). Non-empty `copy_verify_shapes` (`W=16`/`W=24`) has CPU and `make_fx`
  verification only and remains pending live multi-GPU capture, export, and
  serving qualification (matching `NVIDIA/hyperflare-inference#540`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=8fdd
Signed-off-by: FujitsuPolycom <[email protected]>
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents · Value Proposition · Case File

Recommendation: Changes Requested

One blocker; the third commit's feature cannot run on the path it was built for. Commit 1b0db227 (funded-refresh recovery) is correct and self-contained and could merge on its own today.

Blockers:

  • heliopause/src/export/binding.rs:201 overwrites draft_source with "MTP" on the only manifest→wire path (capture.rs:3158 (not opened)), so graphs the producer emits with 2 (ignition/preparation/execution.py:32,316-319) load as MTP and are pruned by helios/src/runtime_core/selection.rs:277-298 (copy_wide requires 2; the MTP branch requires draft_tokens <= drafts). Wide copy-verify is silently dead on every exported core, and the coercion also skips the copy-only contract checks (execution/manifest.rs:844-846 (not opened), model/catalog.rs:93-131 (not opened)). Derive instead of overwrite (2 => "COPY_DRAFT", unknown => invalid(...)) and add one binding::execution round-trip test.

Should fix:

  • Three doc statements now contradict the code: docs/cli-design.md:200-201 (+:741) and docs/mtp-design.md:22-29 say --history-drafts "does not change the graphs", but selection.rs:277-298,375-396 prunes copy graphs, drops kernels and rewrites speculative_widths.
  • Fill the existing docs rather than adding new ones: mtp-design.md:31-40 → SAM-first with the ring as fallback (caps, min match 6); scheduling-runtime-design.md:6-12 module index plus a short draft_source/wide-copy section, :249-254 → the stricter-batch pruning rule, :396-399 → the copy/MTP packed-duration split, scheduling-theory.md:577-579,714-729 → retained idle credit and two-tier order; helios/manifest.md:29-53 → draft_source.
  • One authority for the proposal source, and put it in prepared-shape identity (cost::Key, cost.rs:50-58): today prepared() rejects duplicate shapes (:159-161), so an MTP and a copy graph at identical B/D/W/P cannot coexist; is_copy_only_step (:223-232) must infer the source from the table; and has_mtp (:192-196) is an existence scan, so one unmeasured MTP entry makes packed_round_duration return None for a measured copy shape.
  • Give 0.88, 4.0, 2.0 and +3 (and the changed 6) a stated derivation (speculation.rs:15-21, rounds.rs:766, sam.rs:22); only the 6 is argued, from one repetitive prompt.
  • Evidence: state that PromptSAM::build (13.05 ms / 4.52 MiB) runs synchronously at admission for every request (scheduler.rs:1849-1852), add per-commit live numbers for the padding-dominance and SAM/wide-copy work (four bundled outcomes cannot be attributed), one load-and-serve of an already-exported core, and one preempt→readmit SAM test.
  • ignition/preparation/execution.py:104-108 accepts draft_source = 2 on kind == "mixed", which selection.rs:278-283 then refuses to load — reject it at the producer.
    ... 0 more

Subtract / Simplify:

Could remove ~500–600 of +3,968 added lines:

  • ~150–250 test lines — fold model/tests.rs:846-953 into :1861-2075, drop the duplicate legacy-load assertion, trim scheduler/tests.rs:1995-2127 to admission + isolation.
  • ~112 lines — rounds.rs:755-903 duplicates the ordinary candidate loop at :905-1060; one loop with a per-slot curve provider also collapses curves/copy_curves (:747-748); delete the unreachable wide_copy_curve else (:541-548).
  • ~150 lines of SAM API with no production caller — propose_conditional_continuations (sam.rs:1118-1189), propose_for_context (:1070), MatchSource/source, PromptSAM::build, push_slice, from_shared_prompt, unread accessors, SamConfig; re-point the brute-force oracle at propose first.
  • ~75 lines — one private helper for scheduler.rs:1112-1205 (already drifted on the zero-count ring case), delete the empty RefreshState::idle (refresh.rs:95-99) with its no-op test calls, one ProposalSource::from_wire instead of three ladders (serving.rs:58-63 (not opened), python.rs:225-233 (not opened), selection.rs:144-148). Do not drop Candidate.expected — it is a real second quantity.

Nits:

5 nits

To opt out, include #autobot:ignore in your post or comment.

@shieldstar

Copy link
Copy Markdown

Commit 1b0db22 ("Recover stale Helios graph costs ...") stores a zero-duration expected value on each Candidate for refresh ordering. In add_candidate (Decode lanes) and mixed_candidates (Decode or Speculative lanes), that value comes from a second lane_value(..., 0, ...) call per selected lane per candidate. For those lanes lane_value goes through expected_speculative_tokens -> powered_curve, so every candidate rebuilds the lane's forecast curve a second time, although the token forecast is the one the duration-priced value has just computed; only the time argument of LaneValue::decode differs. This runs on every plan, not only when a refresh can start, because the value is stored on every candidate and read later by compare_refresh. It is the same per-shape curve rebuilding as #547, and it works against the per-lane caching that rounds.rs:746 asks for ("Lane forecasts stay fixed while shapes compete; evaluate each at most once"). Engines with speculative widths and no mixed graphs price their lanes from cached curves elsewhere and do not pay this; engines without speculative widths, or with mixed graphs, do.

Counting powered_curve calls with a test-only counter (the one from #547) at this PR's head, eight-slot engines, four decoding lanes:

36 curve evaluations for 5 mixed shapes and 4 decoding lanes
27 curve evaluations for 4 decode batch capacities and 4 decoding lanes

Before this PR those passes make one evaluation per shape (or batch capacity) and lane; the zero-duration values add the rest.

A suggestion: compute the token forecast once per lane and price it at both durations. This gives the same values bit for bit, since it is the expression lane_value_for_tokens evaluates, and removes the extra evaluations, the duplicated optimistic_tokens call in the acceptance-probe branch included. Other kinds in add_candidate keep your code. Excerpt (mixed_candidates):

@@ -1236,11 +1245,14 @@ impl RequestScheduler {
                         }
                     }
                     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.lane_value(r, decode, width, duration_ns, values[slot]) },
-                        );
+                        // One forecast prices the lane at this duration and at zero duration.
+                        let tokens = if optimistic {
+                            self.optimistic_tokens(r, self.speculative_tokens(r, width))
+                        } else {
+                            self.expected_speculative_tokens(r, self.lane_tokens(r, decode, width))
+                        };
+                        decoders[count] = (slot, values[slot].decode(tokens, duration_ns as f64 / 1e6));
+                        zero_duration[slot] = values[slot].decode(tokens, 0.0);
                         count += 1;
                     }
                     _ => {}
@@ -1266,14 +1278,7 @@ impl RequestScheduler {
                 let mut refresh_expected = decoders[..count]
                     .iter()
                     .filter(|(s, _)| mask & (1 << s) != 0)
-                    .map(|&(slot, _)| {
-                        let r = self.slots[slot].request.as_ref().unwrap();
-                        if optimistic {
-                            values[slot].decode(self.optimistic_tokens(r, self.speculative_tokens(r, width)), 0.0)
-                        } else {
-                            self.lane_value(r, decode, width, 0, values[slot])
-                        }
-                    })
+                    .map(|&(slot, _)| zero_duration[slot])
                     .sum::<f64>();
                 if let Some((slot, value)) = prompt {
                     mask |= 1 << slot;

With it both tests pass, and the helios scheduler:: unit tests pass (386 passed, 5 ignored; release, --features runtime-core,server). A diagnostic test that prints every candidate's rate and stored zero-duration value bits, both mixed_candidates branches and the selected plan (speculative engine with a waiting Init at alpha 1.0 and 0.6, a mixed catalog with and without a prompt, decode only) gave byte-identical output with and without the change.

This is independent of #547. If #547 lands too, the forecast here would come from its per-pass curve cache instead of expected_speculative_tokens; both changes touch these lines, so whichever lands second needs a small rebase. Two smaller spots are left as they are: resize_prefill also prices each mixed lane twice, once per resized plan rather than per candidate, and the zero-duration value of Init, Restore, Snapshot and Vision candidates goes through prerequisite_value, which can build a curve in next_progress for a request that is already decoding.

Full diff against this PR's head (fix, test-only counter, two tests)
diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs
index 9f586503..3e28842e 100644
--- a/helios/src/scheduler/policy.rs
+++ b/helios/src/scheduler/policy.rs
@@ -1010,6 +1010,7 @@ impl RequestScheduler {
             return;
         };
         let mut offers = [(0usize, 0.0); REQUEST_LANES];
+        let mut zero_duration = [0.0; REQUEST_LANES];
         let mut count = 0;
         for slot in bits(mask) {
             let r = self.slots[slot].request.as_ref().unwrap();
@@ -1038,10 +1039,15 @@ impl RequestScheduler {
             if kind == GraphKind::Vision && capacity < r.vision_patches[0] {
                 continue;
             }
-            offers[count] = (
-                slot,
-                self.lane_value(r, kind, capacity, duration_ns, values[slot]),
-            );
+            let value = if matches!(kind, GraphKind::Decode | GraphKind::Speculative) {
+                // One forecast prices the lane at this duration and at zero duration.
+                let tokens = self.expected_speculative_tokens(r, self.lane_tokens(r, kind, capacity));
+                zero_duration[slot] = values[slot].decode(tokens, 0.0);
+                values[slot].decode(tokens, duration_ns as f64 / 1e6)
+            } else {
+                self.lane_value(r, kind, capacity, duration_ns, values[slot])
+            };
+            offers[count] = (slot, value);
             count += 1;
         }
         if count == 0 {
@@ -1082,6 +1088,8 @@ impl RequestScheduler {
             .unwrap_or_else(|| (selected, ValueRate::new(duration_ns, expected, age_price)));
         let expected = if duration_ns == 0 || kind.is_prefill() {
             expected
+        } else if matches!(kind, GraphKind::Decode | GraphKind::Speculative) {
+            bits(selected).map(|slot| zero_duration[slot]).sum()
         } else {
             bits(selected)
                 .map(|slot| {
@@ -1207,6 +1215,7 @@ impl RequestScheduler {
                 continue;
             };
             let mut decoders = [(0usize, 0.0); REQUEST_LANES];
+            let mut zero_duration = [0.0; REQUEST_LANES];
             let mut count = 0;
             let mut prompt: Option<(usize, f64)> = None;
             for (slot, entry) in self.slots.iter().enumerate() {
@@ -1236,11 +1245,14 @@ impl RequestScheduler {
                         }
                     }
                     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.lane_value(r, decode, width, duration_ns, values[slot]) },
-                        );
+                        // One forecast prices the lane at this duration and at zero duration.
+                        let tokens = if optimistic {
+                            self.optimistic_tokens(r, self.speculative_tokens(r, width))
+                        } else {
+                            self.expected_speculative_tokens(r, self.lane_tokens(r, decode, width))
+                        };
+                        decoders[count] = (slot, values[slot].decode(tokens, duration_ns as f64 / 1e6));
+                        zero_duration[slot] = values[slot].decode(tokens, 0.0);
                         count += 1;
                     }
                     _ => {}
@@ -1266,14 +1278,7 @@ impl RequestScheduler {
                 let mut refresh_expected = decoders[..count]
                     .iter()
                     .filter(|(s, _)| mask & (1 << s) != 0)
-                    .map(|&(slot, _)| {
-                        let r = self.slots[slot].request.as_ref().unwrap();
-                        if optimistic {
-                            values[slot].decode(self.optimistic_tokens(r, self.speculative_tokens(r, width)), 0.0)
-                        } else {
-                            self.lane_value(r, decode, width, 0, values[slot])
-                        }
-                    })
+                    .map(|&(slot, _)| zero_duration[slot])
                     .sum::<f64>();
                 if let Some((slot, value)) = prompt {
                     mask |= 1 << slot;
diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs
index b3f2f4dd..d11101cb 100644
--- a/helios/src/scheduler/policy_tests.rs
+++ b/helios/src/scheduler/policy_tests.rs
@@ -6285,3 +6285,45 @@ fn attempted_stale_shapes_rotate_without_starvation_when_timing_is_invalid() {
     // Once all feasible stale shapes are in Tier 1, oldest-attempt rotates back to 8192.
     invalid_probe(&mut s, 8192);
 }
+
+
+#[test]
+fn mixed_refresh_value_reuses_each_decoding_lanes_forecast() {
+    // A decoding lane's zero-duration refresh value uses the token forecast its
+    // duration-priced value already computed, so pricing both adds no curve evaluation.
+    let shapes = [(2, 3, 64, MS), (2, 8, 64, MS), (4, 3, 64, MS), (4, 8, 64, MS), (8, 8, 64, MS)];
+    let mut s = mixed_engine(8, true, &shapes);
+    let decoding = fixed_host_requests(&mut s, &[32, 32, 32, 32]);
+    let (values, age_price, _) = s.lane_values(s.window_remaining().unwrap());
+    let mut candidates = Vec::new();
+    super::rounds::CURVE_EVALUATIONS.set(0);
+    s.mixed_candidates(&mut candidates, &values, age_price, false);
+    let evaluations = super::rounds::CURVE_EVALUATIONS.get();
+    assert!(candidates.iter().any(|c| c.kind == GraphKind::Mixed && c.expected > 0.0));
+    assert!(
+        evaluations <= shapes.len() * decoding.len(),
+        "{evaluations} curve evaluations for {} mixed shapes and {} decoding lanes",
+        shapes.len(),
+        decoding.len(),
+    );
+}
+
+#[test]
+fn decode_refresh_value_reuses_each_decoding_lanes_forecast() {
+    // Without speculative widths, add_candidate prices each decoding lane once per batch
+    // capacity; its zero-duration refresh value must reuse that forecast.
+    let mut s = engine(8, false);
+    let decoding = fixed_host_requests(&mut s, &[32, 32, 32, 32]);
+    let batches = crate::execution::BATCH_CAPACITIES.iter().take_while(|b| **b <= 8).count();
+    let (values, age_price, _) = s.lane_values(s.window_remaining().unwrap());
+    let mut candidates = Vec::new();
+    super::rounds::CURVE_EVALUATIONS.set(0);
+    s.candidates(&mut candidates, &values, age_price);
+    let evaluations = super::rounds::CURVE_EVALUATIONS.get();
+    assert!(candidates.iter().any(|c| c.kind == GraphKind::Decode && c.expected > 0.0));
+    assert!(
+        evaluations <= batches * decoding.len(),
+        "{evaluations} curve evaluations for {batches} decode batch capacities and {} decoding lanes",
+        decoding.len(),
+    );
+}
diff --git a/helios/src/scheduler/rounds.rs b/helios/src/scheduler/rounds.rs
index 65e0493a..4b4324ec 100644
--- a/helios/src/scheduler/rounds.rs
+++ b/helios/src/scheduler/rounds.rs
@@ -19,6 +19,12 @@ const SURPLUS_HISTORY_CAPACITY: usize = 256;
 const SURPLUS_MIN_SAMPLES: usize = 4;
 const SURPLUS_FACTOR_MAX: f64 = 2.0;
 
+#[cfg(test)]
+thread_local! {
+    /// Powered-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) };
+}
+
 #[derive(Clone, Copy)]
 struct DepthCalibration {
     realized: f64,
@@ -535,6 +541,8 @@ impl RequestScheduler {
 
     /// Prefix survival raised to the adaptive verification exponent.
     pub(super) fn powered_curve(&self, request: &LiveRequest, optimistic: bool) -> Vec<f64> {
+        #[cfg(test)]
+        CURVE_EVALUATIONS.set(CURVE_EVALUATIONS.get() + 1);
         self.speculative_curve(request, optimistic).into_iter().map(|p| p.powf(self.policy.adaptive_verification_alpha)).collect()
     }
 

Environment:

  • Commit: 1401971
  • Arch: aarch64
  • OS: Linux 7.0.0-1025-nvidia-64k
  • Toolchain: rustc 1.94.1

Discord: shieldstarx

@voipmonitor

Copy link
Copy Markdown
Collaborator

Tested CPU unit tests and live end-to-end DeepSeek-V4.1-Flash TP4 serving on 4× RTX PRO 6000 Blackwell (SM120, PCIe Gen5) in both the 9-PR and full 12-PR stacks.

Verification Summary

  • Rust scheduler tests (including wide_copy_verify_selects_w24_on_long_sam_match_and_falls_back_to_mtp_otherwise) pass cleanly.
  • Live TP4 serving (--no-history-drafts, default copy_verify_shapes=()) verified with zero regressions across C=1..64 and 16K–128K contexts. (Note: opt-in wide copy-verify W=16/24 live GPU serving was not enabled in this run and remains separately to be qualified, matching the PR description.)

Merge / Follow-up Notes

  • Currently MERGEABLE on main.
  • Clean 3-file merge touchpoint when stacking with #542 in helios/src/scheduler/{cost.rs,rounds.rs,tests.rs}: keep #540's has_mtp copy-skip guard and wide copy-verify candidate block while replacing shape.batch.ilog2() as usize with #542's batch_capacity_index(shape.batch).
  • Also worth picking up @shieldstar's small fix above to avoid redundant powered_curve evaluations in add_candidate / mixed_candidates.

@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

Pushed e5a69669 addressing @shieldstar's finding and all @flare-autobot review items, and updated the PR description. Thank you @shieldstar for the exact patch and tests, and @voipmonitor for the live TP4 verification!

Point-by-point responses (e5a69669)

  1. Blocker — heliopause/src/export/binding.rs:201 overwriting draft_source: Replaced the unconditional "MTP" write with derivation from the manifest field (None | 0 | 1 | "MTP" => "MTP", 2 | "COPY_DRAFT" => "COPY_DRAFT", unknown => Err(invalid(...)), rejecting "COPY_DRAFT" on non-speculative graphs) and added protobuf round-trip test export::binding::tests::execution_preserves_mtp_and_copy_draft_source_and_rejects_unknown (207 passed in heliopause).
  2. @shieldstar — Duplicate powered_curve evaluations in add_candidate / mixed_candidates: Folded your exact byte-identical zero_duration[slot] reuse in helios/src/scheduler/policy.rs along with the #[cfg(test)] CURVE_EVALUATIONS counter in rounds.rs and both unit tests (mixed_refresh_value_reuses_each_decoding_lanes_forecast, decode_refresh_value_reuses_each_decoding_lanes_forecast).
  3. Should-fix — Single authority in cost::Key & removing has_mtp scan: Included canonical draft_source: Option<ProposalSource> in cost::Key, Candidate, and ScheduledStep, split packed_round_durations per source, removed Estimate.draft_source and has_mtp, and added unmeasured_mtp_and_measured_copy_coexist_at_identical_shape_and_preserve_packed_duration.
  4. Should-fix — Producer validation (ignition/preparation/execution.py): Rejected draft_source == 2 on non-speculative graphs (including kind == "mixed") and added test_copy_draft_source_requires_speculative_graph_without_gpu_confidence (71 passed across execution/boundary/speculative contract Python tests).
  5. Should-fix — Docs, constant derivations, and preempt→readmit test: Updated docs/cli-design.md, docs/mtp-design.md, docs/scheduling-runtime-design.md, docs/scheduling-theory.md, and helios/manifest.md (including synchronous admission SAM build cost and --history-drafts graph pruning/rewriting), added derivations for 0.88, 4.0, 2.0, 6, and WIDE_COPY_MIN_EXTRA_DRAFTS = 3, and added preempted_request_reindexes_generated_history_into_sam_on_readmission.
  6. Cleanup: Removed unused SAM APIs (propose_conditional_continuations, propose_for_context, MatchSource, SamConfig, PromptSAM::build, etc.), unified the 3 ProposalSource::from_wire ladders, unified the wide-copy and ordinary candidate loops in rounds.rs, removed unreachable wide_copy_curve else and empty RefreshState::idle, factored resolve_copy_match in scheduler.rs (fixing zero-count ring drift), and trimmed redundant test setup.
  7. Verification (e5a69669): helios --features runtime-core,server 1,712 passed (0 failed); helios default 620 passed; heliopause 207 passed; flare & flare-cli cargo check clean; Python 71 passed. Note: per-commit live GPU A/B on e5a69669 remains unrun on hardware and is disclosed in the PR limits.

@flare-autobot please re-review at e5a69669.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents · Value Proposition · Case File

Recommendation: Ready To Merge

The one previous blocker (export coercing draft_source) is fixed; remaining items are deletions and evidence, not correctness.

Blockers:

None.

Should fix:

  • cost.rs:237-252 — delete the combined packed_round_duration: its (None, Some(0)) arm scans the whole MTP table, so a copy shape's cost depends on unrelated graphs and the code contradicts docs/scheduling-runtime-design.md:429-433. Callers (rounds.rs:588, policy.rs:785) already know their source; pass it.
  • scheduler.rs:1101-1104 — delete test-only history_proposal: it is the prompt-blind path this PR replaces and re-implements clamp_copy_capacity with a panicking - 1. Move the ring assertions to request_history_proposal.
  • Give "speculative defaults to Mtp" one home: move canonical_draft_source (cost.rs:50-59) to speculation.rs, and delete the unreachable "any source" wildcards in catalog.rs:296-299 / packing.rs:48-51.
  • rounds.rs:30-33,565-566 + policy_tests.rs:6289-6331 (not opened) — delete the CURVE_EVALUATIONS counter and its two call-count tests; keep the zero_duration[slot] reuse they guard.
  • Evidence + prose: per-commit live numbers and one load-and-serve of an exported W=16/24 draft_source = 2 core; add sam.rs (not opened) + copy-only wide graphs to docs/mtp-design.md:542-544 and reword docs/api.md:295-296 / docs/cli-design.md:1790.

Subtract / Simplify:

Could remove ~85–90 of +4,306 added lines:

  • rounds.rs:30-33, :565-566, policy_tests.rs:6289-6331 (not opened) — test-only call-count instrumentation and its two tests (~46 lines).
  • cost.rs:237-252 — combined packed-round lookup; delete, pass the source at rounds.rs:588 / policy.rs:785 (~12 lines).
  • scheduler.rs:1101-1104, decoded_history.rs:180-183, catalog.rs:240-245 — entry points this PR orphaned (~14 lines).
  • rounds.rs:785-803 vs :1019-1030 byte-identical cohort preamble (~10) + whole-curve clone at :925 (~2); plus unreachable is_none() arms and the duplicated 6 (speculation.rs:25 vs sam.rs:23 (not opened)) (~10).

Nits:

5 nits (capability tuples omit draft_source — state the invariant, don't add a sixth field; 0/Mixed + COPY_DRAFT normalised differently per layer; idle rename; the 6 rests on one prompt; binding.rs:216 writes the default).

To opt out, include #autobot:ignore in your post or comment.

@lukealonso

Copy link
Copy Markdown
Collaborator

Review of head commit e5a69669 against the repository's scheduler design principles and verification hierarchy. Several scheduler invariants are violated and required verification layers remain unrun.

Scheduler design issues

  1. Two-tier timing-refresh ordering starves smaller stale shapes (helios/src/scheduler/cost.rs:324, helios/src/scheduler/policy.rs):
    ActionCosts::refresh_order assigns every stale entry whose last attempt predates its expiry (last_attempt_ns < observed_at_ns + ttl_ns) the identical Tier 0 key (false, 0) and breaks ties by zero-duration expected useful value (Candidate.expected). Because ordinary execution earns timing-refresh credit at 0.002 / 0.998 (roughly 1 / 499), any probed graph whose duration D exceeds ttl_ns / 499 (about 60.1 ms at the 30-second TTL—such as Prefill(8192) at 145–200 ms) incurs debt requiring 499 * D > 30 s of ordinary compute to repay. By the time refresh credit refills to 5 ms, that same largest shape has expired again (now >= observed_at_ns + 30 s > last_attempt_ns), returns to Tier 0 (false, 0), and wins refresh selection again. Any smaller stale shape—even one that has become the true fastest option—can be starved indefinitely. Ordering by observed_at_ns.max(last_attempt_ns) on main avoided this starvation.

  2. Speculative padding pruning acts as a smallest-fitting-batch filter and omits cohort matching (helios/src/scheduler/policy.rs:144-169, 249-264):
    docs/scheduling-runtime-design.md specifies strict physical Pareto dominance for the same request cohort and logical per-request prefixes (discarding a shape only when all physical capacities are at least as large as an alternative), explicitly forbidding smallest-fitting-shape filters, and docs/scheduling-theory.md notes that a padded larger graph remains eligible if it is actually faster. In PR Retain bounded timing-refresh credit across idle and exclude readiness wait #540, both dominates_padding_with and the second loop in prune_padding prune a wider GPU-allocated batch (for example B = 8, P = 11) whenever a tighter batch satisfies other.packed_token_capacity >= min(ceilings_sum, larger.packed_token_capacity) (for example B = 4, P = 13 or B = 4, P = 32), even when the tighter batch has more physical target rows (13 > 11 or 32 > 11), runs a different prefix allocation, and is measured slower (11 ms vs 7 ms in tight_batch_prunes_wider_padded_ragged_speculative_shapes_for_active_cohort). In addition, the second pass in prune_padding (policy.rs:249-264) checks other.batch >= lanes && other.batch < candidate.batch without checking other.mask == candidate.mask, allowing a candidate serving a different request cohort to prune candidate.

  3. Wide copy-only widths contaminate service-rate normalization, delivery reference intervals, and prerequisite lookahead (helios/src/runtime_core/selection.rs:384-398, helios/src/scheduler/cost.rs:237-252, helios/src/scheduler/service.rs, helios/src/scheduler/policy.rs):
    Retaining copy-only widths (16, 24) in speculative_widths (and therefore RequestScheduler::speculative_catalog) causes service_rates, delivery_reference_intervals, next_progress, and continuation_candidate to look up ActionCosts::packed_round_duration(batch, width) for those widths and pair a copy-only graph's measured duration with the learned MTP powered_curve for every decoding request—including requests without a qualifying copy match that cannot legally execute that graph. That violates the realizable individual-feasibility contract in docs/scheduling-utility.md. Separately, ActionCosts::packed_round_duration merges MTP and copy sources and its (None, Some(0)) branch scans the entire MTP table across all shapes, making one shape's lookup depend on unrelated graphs.

  4. Cross-source leakage in funded acceptance learning and unisolated copy-only cost refreshes (helios/src/scheduler/learning.rs, helios/src/scheduler/rounds.rs, helios/src/scheduler/cost.rs):
    RequestScheduler::acceptance_probe calls packed_round_candidates(..., optimistic = true), which emits wide copy-only candidates (draft_source = Copy). That allows acceptance-learning credit (PlanOrigin::AcceptanceStart) to be spent on a copy-only graph while tie-breaking with speculative_information, which reads learned MTP Forecast or AcceptanceProfile[Mtp] weights (never updated by copy-only rounds) rather than CopyCalibration. Also, contrary to the PR summary stating that copy-only graphs are excluded from baseline cost refreshes, ActionCosts::stale_keys does not filter out Copy entries, so stale wide copy shapes still compete in PlanOrigin::RefreshStart.

  5. Heuristic gating constants and duplicate copy-survival models (helios/src/scheduler/rounds.rs:27, 894-915, helios/src/scheduler/speculation.rs:19-39, 133-220):
    packed_round_candidates hard-gates wide copy graphs behind WIDE_COPY_MIN_EXTRA_DRAFTS = 3, limit > base_mtp_drafts + 1, and WIDE_COPY_MIN_MATCH_LEN = 6, preventing a faster copy-only graph (without learned-drafter compute) from competing on expected useful value per time for shorter continuations. Meanwhile CopyCalibration introduces a second per-request copy-survival model with an empirically unvalidated 0.88 geometric prior (weight 4.0) while LiveRequest::acceptance[Copy] (prior 0.5^d) continues to be updated on completion in scheduler.rs:2862 and ignored by wide copy selection.

  6. Synchronous admission stalls and repeated per-plan lookups (helios/src/scheduler.rs:1846, helios/src/scheduler/rounds.rs:904):
    PromptOutputSAM::new runs synchronously inside RequestScheduler::admit (13.05 ms and 4.52 MiB at 131,072 prompt tokens, outside host memory budgeting), stalling the single-threaded worker loop and delaying GPU submissions for concurrent decoding requests. During planning, packed_round_candidates calls request_copy_match_stats (which queries both PromptOutputSAM and DecodedHistory with heap allocations) inside the loop over every wide copy shape and active lane rather than computing each lane's match once per plan, contributing to the measured +0.25 ms/rd scheduler overhead.


Verification gaps against the testing hierarchy

Per docs/verification.md, verification/helios-lifecycle/README.md, docs/scheduling-runtime-design.md, docs/scheduling-theory.md, docs/mtp-design.md, and docs/core-design.md, the following required verification layers remain unrun at e5a69669:

  1. Crate test suite and CI: No GitHub Actions checks have run on this branch. At e5a69669, flare and flare-cli were only cargo checked rather than tested, helios and heliopause ran without --release, and eos, selene, selene-manager, and tests/cli were not run (cf. .github/workflows/native-serving.yml).
  2. Scheduling simulator (scripts/scheduling_sim/learning): The three timing-refresh policy changes diverge from the simulator's retained-refresh policy and were not validated through the simulator's screening and 64-seed validation catalog (docs/scheduling-theory.md), which covers idle transitions, poisoned observations, missing timings, and recovery fixtures and would expose the starvation issue above.
  3. Formal lifecycle, Kani, and mutation checks: Neither python3 verification/helios-lifecycle/check.py (TLA+/TLC conformance across Lifecycle.tla and Speculation.tla/Speculation16.cfg), cargo kani --manifest-path helios/Cargo.toml --lib, nor --mutations / cargo-mutants was run despite modifying admission, speculation, and readiness handling. In addition, Speculation16.cfg and the Kani completion-vector harnesses cover widths up to 16, leaving the W = 24 wide copy-verify path outside bounded formal coverage.
  4. Native HTTP scheduler integration tests: tests/server/test_scheduler.py (ordinary, fixed-width, and adaptive speculative serving) was not run.
  5. Real GPU execution and core export/replay qualification: Zero GPU checks have run on head commit e5a69669 (which fixed protobuf draft_source export and changed cost::Key, policy.rs, rounds.rs, selection.rs, and runtime.rs). In particular, no wide copy-verify (draft_source = COPY_DRAFT, W = 16/24) core has been exported, loaded, or replayed on GPU; live power-cap cost-refresh recovery and disk-backed readiness stalls have not been run on hardware; and Qwen3.8 Flash (the existing --history-drafts and --mixed-prefill recipe), GLM 5.3 Flash, SM121/GB10, and multi-host RoCE remain untested.
  6. Paired MTP and replay-floor benchmarks: The prior-commit (14019718) live serving numbers are combined-stack rather than per-change isolated, use temperature = 0 only (whereas docs/mtp-design.md and docs/core-design.md require checkpoint stochastic defaults as the primary benchmark, with temperature = 0 reported separately), cover only one synthetic 512-token code-edit prompt and one 256-token stream rather than the required multi-category workload, and omit concurrent TTFT and host-submission-gap checks against the 5% replay-floor target.

lukealonso pushed a commit to local-inference-lab/hyperflare-recipes that referenced this pull request Nov 27, 2026
…verlap, and opt-in wide copy-verify (W=16, W=24) (#49)

* Reduce DeepSeek-V4.1 and GLM-5.3 decode launch and reduction overhead

Why
DeepSeek-V4.1 and GLM-5.3 decode and speculative verify graphs leave
several recipe-level launch, buffer-sizing, and padded-row inefficiencies
on the critical path that require no core runtime or b12x ABI changes:
- DeepSeek-V4.1 decode, verify, and draft layers omitted
  `num_valid_tokens=metadata.live_counts[:1]` when constructing and
  invoking `PreparedRouter`, so padded rows beyond the active batch
  were routed as valid expert assignments instead of masked to `-1`.
- DeepSeek-V4.1 PCIe `OneshotAllReduce` capacity defaulted to
  `all_reduce_tokens` (256 tokens, 2.5 MiB), forcing BF16 Engram
  `PreparedChunkedAllReduce` reductions (`[5 * decode_tokens, 5120]`,
  6.25 MiB at `decode_tokens=128`) to split into three sequential
  reductions per table.
- Fused Markov draft proposal selection (`fuse_markov` and
  `_markov_step_batched8`) stopped at batch size 8, falling back to an
  unfused multi-kernel path at batches 16 and 32, and batch size 1
  recomputed predecessor token resolution across every CTA instead of
  pre-resolving once per step.
- `PreparedContext` launched six separate RMSNorm and rotary kernels
  across the three DeepSeek-V4.1 draft context layers, and ratio-2
  `PreparedCompressor.commit` launched separate gather and `save_hidden`
  operations per pending field on CUDA.
- `PreparedMTP` in GLM-5.3 ran separate `PreparedAllReduce` and
  `rms_norm_add_residual` operations even when a single-channel PCIe
  oneshot runtime supports `PreparedAllReduceRMSNorm`.

What
- `hyperflare_recipes/recipes/deepseek41/decoder.py`: pass
  `num_valid_tokens=metadata.live_counts[:1]` to `PreparedRouter` in
  `decode`, `verify`, and `draft` modes whenever `metadata.live_counts`
  is present. Pinned `b12x` W4A8 compact and materialized MoE kernels
  guard `expert >= 0 and expert < num_experts` and emit exact zeros for
  `-1` routes.
- `hyperflare_recipes/recipes/deepseek41/bootstrap.py`: add
  `PreparationConfig.pcie_all_reduce_tokens` returning
  `max(self.all_reduce_tokens, 5 * self.decode_tokens)` and pass it to
  `create_all_reduce_runtime`, leaving `create_roce_runtime` at
  `config.all_reduce_tokens`.
- `hyperflare_recipes/components/parallel_draft.py` and
  `hyperflare_recipes/components/markov_sampling.py`: generalize
  `fuse_markov` and `_markov_step_batched8` (`row_base = tl.program_id(1) * 8`)
  to all batch sizes `b >= 8` with `b % 8 == 0` (covering batches 16
  and 32), and enable `pre_resolve = True` for batch size 1 so
  `_markov_step` loads the resolved predecessor token directly.
- `hyperflare_recipes/components/dspark.py`: add
  `_context_kv_norm_rope_kernel` on CUDA to fuse the three draft-layer
  KV RMSNorm and rotary stages into one Triton launch using the same
  BF16-exact seam as `deepseek41/attention.py`, retaining the existing
  CPU fallback.
- `hyperflare_recipes/recipes/deepseek41/attention.py`: add
  `_commit_ratio2_pending` on CUDA to fuse each ratio-2 compressor
  layer's pending-value, pending-gate, and pending-position commit into
  one Triton launch per layer, retaining the existing CPU fallback.
- `hyperflare_recipes/recipes/glm53/mtp.py`: select
  `PreparedAllReduceRMSNorm` for `attention_reduce` and `mlp_reduce` in
  `PreparedMTP` when `PreparedAllReduceRMSNorm.fits(runtime, source)` is
  true, falling back to `PreparedAllReduce` plus `rms_norm_add_residual`
  otherwise.

Result
These changes preserve BF16 numerical behavior and compatibility with
the current `uv.lock` `ignition` and `flashinfer-python` pins. On CUDA
graphs, they mask padded decode/verify router rows, eliminate Engram
PCIe reduction chunking at `decode_tokens=128`, keep fused Markov
proposals active at batches 16 and 32, remove redundant batch-1 Markov
predecessor reductions, cut `PreparedContext` norm+RoPE launches from 6
to 1, cut ratio-2 pending commit launches from 15 to 3 per round, and
fuse GLM-5.3 MTP PCIe all-reduce and RMSNorm pairs.

Evidence
- CPU pytest (`CUDA_VISIBLE_DEVICES=""`) across all 6 modified test files
  (`tests/recipes/test_glm53_stack.py`,
  `tests/recipes/test_deepseek41_expert_overlap.py`,
  `tests/recipes/test_deepseek41_scratch.py`,
  `tests/recipes/test_deepseek41_dspark.py`,
  `tests/components/test_parallel_draft_metadata.py`,
  `tests/components/test_markov_sampling_cuda.py`) passed with zero
  failures.
- Verified in combined-stack SM120 TP4 DeepSeek-V4.1 Flash serving (`4x RTX PRO
  6000 Blackwell`, PCIe Gen5); standalone GLM-5.3 MTP GPU serving and SM121
  (GB10) hardware tests remain unverified.

Discord: Dooner

Design-Signed-Off-By: Gemini 4 Neon; design-review=8fdd
Signed-off-by: FujitsuPolycom <[email protected]>

* deepseek41: overlap prefill collectives, fuse FFN gather, and enable KV RoPE/PDL

Why
In row-sharded DeepSeek-V4.1 prefill on 4-GPU PCIe systems, several per-layer
synchronization barriers and redundant device copies stall compute while
leaving PCIe DMA engines or SMs idle:
- `mla_wo` source layers (2, 8, 14) have 2,560 BF16 KV columns instead of 512,
  so decoder preparation fell back to draining `cr_mlp_1` synchronously before
  starting `cr_kv_gather_0`.
- Layers preceding Engram layers (0 -> 1 and 13 -> 14) disabled `defer_mlp_b`,
  forcing a synchronous `mlp_reduce_1` drain and disabling pipelined attention
  hyper-connection and P2P KV gather on layers 1 and 14.
- Row-sharded FFN shards performed two sequential `ConcurrentGatherShards` calls
  per half (`ffn_vals` and `ffn_meta`) and copied immutable inputs inside
  `Concurrent*` collectives and Engram chunk slices.
- Engram prefill exchanged full gathered embeddings over `PreparedAllGather`
  even when each rank owns only its row shard, multiplying wire volume by
  `world_size`.
- DeepSeek-V4.1 prefill attention ran a standalone rotary application on the
  64-dim KV RoPE slice even when `flashinfer` `b12x` `mla_norm_mxfp8` supports
  fused `kv_rope_dim=64`, and MXFP8 linear/norm calls gated SM120 programmatic
  dependent launch (`release_dependents`) to decode batches (`rows <= 8`).

What
- `hyperflare_recipes/recipes/deepseek41/bootstrap.py`: size the shared
  `DcpAllToAll` KV gather runtime to `max_rows = 5 * max_kv_shard_rows` and
  `columns = 512 * world` so one IPC runtime serves both full (`[st, 512]`) and
  `mla_wo` (`[st, 2560]` viewed as `[5 * st, 512]`) layers.
- `hyperflare_recipes/recipes/deepseek41/decoder.py`:
  - Enable `p2p_kv_gather` for `mla_wo` layers when the KV runtime fits `5 * st`
    rows, using a zero-copy `[5 * st, 512]` view and 4D transpose back to
    `[world * st, 2560]` with automatic fallback to narrower runtimes.
  - Enable `defer_mlp_b` across L0 -> L1 and L13 -> L14 by passing the previous
    layer's deferred post-MLP hyper-connection into the Engram layer, running
    `engram.mix_half` on Half A while `cr_mlp_1` stays in flight for Half B,
    joining `cr_mlp_1` before Half B's post + `engram.mix_half`, registering
    `engram.mix_plan` and `incoming_post.plan` with `ScratchArena`, and draining
    `cr_mlp_1` before any synchronous fallback Engram gather.
  - Pack each half's MXFP8 FFN activations, E8M0 scales, and top-k router
    indices/weights into a single `[st, 2664]` BF16 payload via fused Triton
    `_pack_ffn_shard_kernel` and `_unpack_ffn_gathered_kernel` (with bit-exact
    CPU fallbacks and an explicit `rows % 128 == 0` guard in
    `_unpack_ffn_gathered`) so one `ConcurrentGatherShards` call replaces two
    per half; preserve `self.shared(..., residual=routed)` when
    `getattr(self.shared, "supports_residual", False)` is true.
  - Detect `copy_input` support on `Concurrent*` collectives (passing
    `copy_input=False` for unaliased owned buffers) and drop redundant `.clone()`
    calls on immutable Engram gather slices.
  - Support `ConcurrentAllToAll` for owner-row Engram overlap chunks with
    seamless fallback to `ConcurrentAllGather` on unmodified `ignition` runtimes.
- `hyperflare_recipes/recipes/deepseek41/engram.py`: detect `PreparedAllToAll` on
  row-sharded prefill and use owner-row all-to-all (with `prepare_all_to_all_chunk`,
  `slice_exchange_chunk`, and skipping `index_select` in `project_gathered`) when
  `PreparedAllToAll.fits` holds, falling back cleanly to `PreparedAllGather`. Add
  `mix_half` reusing `mix_plan` for per-half execution.
- `hyperflare_recipes/components/mla_norm_quant.py` and
  `hyperflare_recipes/recipes/deepseek41/attention.py`: add
  `PreparedMLANormQuant.supports_kv_rope()`, wire `kv_rope_dim=64` and split
  `(cos, sin)` angles when supported while omitting the kwargs on unmodified
  `b12x`, skip standalone KV RoPE application when fused, and enable
  `release_dependents=True` on prefill MLA norm-quant.
- `hyperflare_recipes/components/linear.py`: enable `release_dependents` whenever
  `rhs_prefetch_ready` holds instead of restricting it to `rows <= 8`.
- `tests/recipes/test_deepseek41_prefill_overlap.py` and
  `tests/recipes/test_deepseek41_row_shard_attention.py`: add 24 unit tests
  covering bit-exact parity, negative sensitivity checks, `rows % 128` guard,
  `supports_residual` preservation, schedule invariants, and legacy/upgraded
  runtime compatibility; update row-shard attention schedule expectations for
  19-layer `p2p_kv_gather` and 5x `kv_runtime` sizing.

Result
All seven changes preserve bit-exact BF16/FP32/MXFP8 outputs on CPU parity
checks while keeping backwards compatibility with both current `main` `ignition`
and `b12x` as well as upgraded `ignition` `PreparedAllToAll`/`copy_input=False`
and `b12x` `mla_norm_mxfp8` `kv_rope_dim=64` builds.

Evidence
- CPU pytest (`CUDA_VISIBLE_DEVICES=""`, atop `main` `24849d9`, paired with
  `NVIDIA/hyperflare-inference#542`) across `test_deepseek41_prefill_overlap.py`,
  `test_deepseek41_row_shard_attention.py`, and sibling DeepSeek-V4.1 / GLM-5.3
  suites passed with zero failures (CUDA-gated tests skipped on CPU).
- Verified in combined-stack SM120 TP4 DeepSeek-V4.1 Flash serving (`4x RTX PRO
  6000 Blackwell`, PCIe Gen5); SM121 (GB10) and multi-host RoCE remain
  unverified.

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=8fdd
Signed-off-by: FujitsuPolycom <[email protected]>

* deepseek41: add opt-in DSpark-skip wide copy-verify rounds (W=16, W=24)

When Helios dispatches a wide copy-verify round (`draft_source=COPY_DRAFT`,
`W=16` or `W=24`) backed by a long prompt or output match, running the
3-layer `DSpark` drafter, `draft_head`, 7-step `Markov` head,
`confidence_head`, and `PreparedCausalPrefixAllocation` adds wasted
draft latency before verifying host-supplied copy tokens. Skipping the
draft stages while verifying all `W` tokens through the full 40-layer
target decoder and updating `PreparedContext` for every accepted token
preserves exact `0-ULP` target distribution parity and keeps DSpark's
sliding-window context KV exact for subsequent learned-draft rounds.

Before this change, `PreparationConfig` in
`hyperflare_recipes/recipes/deepseek41/bootstrap.py` prepared only
DSpark-backed speculative rounds (`W <= 8`), `SpeculativePreparation`
did not size `copy_token_ids` for wider copy rounds, and
`PreparedParallelDraftRound.verify` always read active lane limits from
`o.inputs.query_lengths`. This commit:
- Adds `copy_draft_tokens` on `SpeculativePreparation`
  (`hyperflare_recipes/components/dspark.py`) to size `copy_token_ids` to
  `max(7, draft_tokens, copy_draft_tokens)` and expose the four copy-proposal
  buffers (`copy_token_ids`, `copy_token_count`, `copy_expected_consumed`,
  `copy_generation`) via `buffers()` (aligned with PR #48).
- Adds an optional `token_limits` override on
  `PreparedParallelDraftRound.verify` (plus `DraftProposalState.copy_offered_mask`
  and the copy-proposal validation/point-mass overlay helpers shared with
  PR #48 so this branch compiles and passes tests cleanly atop `main`) and
  introduces `PreparedCopyOnlySpeculativeRound` in
  `hyperflare_recipes/components/parallel_draft.py`, allocating a persistent
  1-element `int64` device tensor `self.local_vocab_start` in `__init__` (so
  vocabulary-parallel TP ranks bind per-rank offsets via `USE_VOCAB_START_PTR`
  without baking a rank-0 Dynamo guard), skipping `DSpark`, `Markov`,
  `confidence_head`, and `PreparedCausalPrefixAllocation`, validating copy
  freshness, grammar gating, and in-vocab contiguity, applying point-mass
  `q = 1.0` proposals without mutating host-uploaded `query_lengths`, running
  target verification (including `vocabulary_parallel` sharded tile masses),
  committing KV pages, SWA rings, and `CompletionOutputs`, and executing
  `PreparedContext` over accepted target hidden states.
- Adds opt-in `copy_verify_shapes: tuple[tuple[int, int], ...] = ()` on
  `PreparationConfig` in `hyperflare_recipes/recipes/deepseek41/bootstrap.py`
  with strict shape validation (`batch` in `batch_capacities(max_active)`,
  `width > max(speculative_widths)`, `width <= 64`,
  `batch * width <= speculative_token_capacity`), wires
  `copy-speculative{B}x{W}` graphs (`draft_source=2`, `confidence_width=0`,
  `draft_tokens=W-1`, no `speculative_prefix_limits`), updates
  `completion_token_capacity`, collective runtimes, verification samples,
  `server_config`, and keeps `prepare_contract(..., rows=max(config.speculative_widths))`
  so `state_rows_per_request` remains 8 with zero extra state-pool storage.
- Adds 16 CPU and `make_fx` unit tests in
  `tests/recipes/test_deepseek41_sam_wide_skip.py`.

Default `copy_verify_shapes=()` leaves catalog graphs, buffer dimensions,
`state_rows_per_request`, and execution behavior 100% identical to the
preceding revision. Enabling `copy_verify_shapes` (for example
`((1, 16), (1, 24), (2, 16), (4, 16))`) exposes copy-only wide graphs
requiring zero extra target scratch memory beyond the existing
`P <= 64` verify arena and zero extra state-pool rows.

Evidence and limits:
- CPU pytest (`CUDA_VISIBLE_DEVICES=""`, atop `main` `24849d9`) against
  `NVIDIA/hyperflare-inference#540` (`GraphSignature.draft_source`):
  `tests/recipes/test_deepseek41_sam_wide_skip.py` (16 passed, 0 failed,
  covering `W=16`/`W=24` full acceptance, 15-bit and 23-bit `copy_offered_mask`,
  `PreparedContext` exact update, partial rejection across positions
  `[0, 1, 7, 14, 15, 22, 23]`, freshness/grammar/contiguity/non-mutation,
  exact stochastic rejection marginal with negative sensitivity check,
  4-rank `vocabulary_parallel` sharded tile verification, persistent
  `local_vocab_start` tensor binding, and `make_fx` tracing for `W=16` and
  `W=24`).
- Default `copy_verify_shapes=()` preserves baseline DeepSeek-V4.1 Flash TP4
  export and `flare run` serving on `4x RTX PRO 6000 Blackwell` (SM120, PCIe
  Gen5). Non-empty `copy_verify_shapes` (`W=16`/`W=24`) has CPU and `make_fx`
  verification only and remains pending live multi-GPU capture, export, and
  serving qualification (matching `NVIDIA/hyperflare-inference#540`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=8fdd
Signed-off-by: FujitsuPolycom <[email protected]>

---------

Signed-off-by: FujitsuPolycom <[email protected]>
Signed-off-by: Martin Vit <[email protected]>
Co-authored-by: Martin Vit <[email protected]>
@FujitsuPolycom
FujitsuPolycom force-pushed the pr/core-helios-sam-copy-drafts-and-cost-refresh branch from e5a6966 to 982a9ce Compare November 28, 2026 04:36
@FujitsuPolycom FujitsuPolycom changed the title helios: cost-refresh recovery, prompt+output SAM copy-drafts, and calibrated wide copy-verify Retain bounded timing-refresh credit across idle and exclude readiness wait Nov 28, 2026
@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

@lukealonso Reworked #540 to 982a9ce3 (rebased onto main 353551e9), narrowed strictly to idle credit retention and readiness-wait exclusion on timing refresh — all SAM/history copy-drafting, wide copy-verify (COPY_DRAFT, W=16/24), and speculative batch-padding pruning changes have been removed.

  1. Starvation when D > ttl_ns / 499 (Scheduler item 1): Restored ActionCosts::refresh_order to main's observed_at_ns.max(last_attempt_ns), removed (false, 0) tiering and Candidate.expected, and added Rust + Python regression tests for a D = 145 ms stale shape yielding to an older stale shape after refill.
  2. Removed SAM, wide copy-verify, and padding pruning (Scheduler items 2–6): Dropped completely from this PR.
  3. Readiness-wait exclusion & positive-charge guard: Added observed_compute_duration_ns and timing_refresh_duration_ns in helios/src/scheduler/cost.rs, excluding readiness wait when gpu_ns > wait_ns and falling back to unexcluded physical/wall duration when gpu_ns <= wait_ns (tested for < and ==, wall_ns == 0 and > 0), while keeping acceptance ledgers on raw physical time.
  4. Verification (Verification items 1–3):
    • 982a9ce3: 804 passed across the 10 Python scheduler, core-boundary, and design-review suites.
    • Byte-identical code tree on 3e2fcd27 (--locked --release): all Rust crates tested (helios 1,705 passed + 1 pre-existing upstream main failure in untouched model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape, eos 1, selene 503, heliopause 208, flare 236, flare-cli 221, untouched selene-manager 414 + 1 concurrent-load wall-clock flake); 16-seed screening + 64-seed 62-scenario simulator validation accepted retain_idle_credit=True (35/35 vs ttl, exact 1.000000 parity vs main, 64/64 recovery, 0 idle spurious probes); verification/helios-lifecycle/check.py passed all 9 TLA+ models (10 TLC runs) and 590,327 Rust transitions.
    • Unrun locally: GPU/HTTP tests (tests/server/test_scheduler.py, live power-cap/readiness stalls), pytest tests/cli (missing local cryptography/rich), and cargo kani/cargo-mutants (completion-vector and state-view arithmetic untouched).

Updated the PR title and body for 982a9ce3 — please take another look when convenient.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Merge After Should-Fix

The runtime change is minimal and verified; one operator doc still states the retired idle rule, and the rest is duplicated tests and repeated prose to delete.

  • Blockers: 0
  • Should fix: 4
  • Subtractive suggestions: 4
  • Nits: 6

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

…s wait

Why:
Helios remeasures stale retained graph durations through a funded refresh
ledger (`helios/src/scheduler/refresh.rs`) that earns `0.002 / 0.998` of
ordinary execution time up to a 5 ms cap (2,495 ms of ordinary execution
for a first refresh) and subtracts the executed refresh duration on
completion. Before this change, two defects prevented stale graph cost
estimates from recovering under ordinary serving workloads:
1. `RequestScheduler::idle` cleared positive timing-refresh and
   acceptance-learning credit to zero while preserving negative debt.
   Workloads of sequential requests shorter than 2,495 ms separated by
   idle gaps never reached 5 ms of credit, leaving stale cost estimates
   unrefreshed indefinitely even though idle intervals add neither credit
   nor ordinary execution time and retaining bounded earned credit
   (`<= 5 ms`) preserves the aggregate expense bounds
   `P <= (0.002 / 0.998) * O + D` (timing refresh) and
   `P <= (0.01 / 0.99) * O + D` (acceptance learning).
2. `RefreshState::complete` credited and charged raw physical execution
   time (`cost::observed_duration_ns`), whereas `ActionCosts::observe`
   records device execution time less measured embedding-delivery
   readiness wait (`gpu_ns - wait_ns`). Disk-backed readiness stalls
   inflated timing-refresh debt even though retained cost estimates
   excluded that wait; subtracting `wait_ns` without guarding
   `gpu_ns <= wait_ns` would charge 0 ns when readiness wait met or
   exceeded the GPU interval while `ActionCosts::observe` discarded the
   0-ns sample, leaving the target stale with full credit.

Keeping `ActionCosts::refresh_order` on `observed_at_ns.max(last_attempt_ns)`
preserves round-robin progress across feasible stale shapes, including
shapes with duration `D > ttl_ns / 499` (60.12 ms at the 30 s TTL) that
re-expire before their refresh debt refills.

What:
- `helios/src/scheduler.rs`, `helios/src/server/runtime.rs`,
  `helios/src/scheduler/refresh.rs`:
  - Before: `RequestScheduler::idle(&mut self)` called `RefreshState::idle`
    to zero positive timing-refresh and acceptance-learning credit while
    retaining negative debt, and `RefreshState::complete` used
    `cost::observed_duration_ns` for both ledgers.
  - After: `RefreshState::idle` is removed and `RequestScheduler::idle` is
    renamed to `RequestScheduler::assert_idle(&self)` to verify only that
    no submission remains in flight; `RefreshState::abort` continues to
    discard positive credit and preserve negative debt. Ordinary
    completions earn timing-refresh credit from
    `cost::observed_compute_duration_ns`, and `PlanOrigin::RefreshStart`
    episodes subtract `observed_compute_duration_ns(timing)` with fallback
    to `observed_duration_ns(timing)` and `timing.wall_ns` (which is
    strictly positive on every validated completion because
    `RefreshState::validate_completion` rejects probes lacking both a
    positive GPU interval and `wall_ns`). Acceptance-learning income and
    `PlanOrigin::AcceptanceStart` charges continue to use raw physical
    duration.
- `helios/src/scheduler/cost.rs`:
  - Add `observed_compute_duration_ns`, returning the device interval (or
    `max(device, wall)` when isolated) less measured readiness wait when
    `gpu_ns > wait_ns`, and `None` otherwise (`ActionCosts::observe`
    deliberately omits `wall_ns`).
- `scripts/scheduling_sim/learning_policy.py`,
  `scripts/scheduling_sim/learning.py`:
  - Add `--retain-idle-credit` (`PolicyConfig.retain_idle_credit`),
    defaulting to `True` for `retained-refresh` so the simulator matches
    Helios and `False` for other exploratory policies (with
    `retain_idle_credit=False` expressible in `--configs` JSON).
- `helios/README.md`, `docs/scheduling-runtime-design.md`,
  `docs/scheduling-theory.md`, `helios/src/scheduler/policy_tests.rs`,
  `tests/test_scheduling_learning_{policy,experiments}.py`:
  - Update present-state specifications, deduplicate prefill-catalog test
    builders and boolean CLI option assertions, and cover idle-separated
    recovery, `D > ttl_ns / 499` non-starvation, and readiness-wait
    exclusion across `gpu > wait`, `gpu == wait`, `gpu < wait`, and absent
    GPU timing (`wall_ns == 0` rejected, `wall_ns > 0` charged).
- Compatibility: No model core format, Protobuf schema, CLI flag in Flare,
  or graph-operation contract changes; existing signed cores load unchanged.

Result:
- Expected runtime benefit: sequential bursts shorter than 2,495 ms
  separated by idle gaps accumulate bounded earned credit (`<= 5 ms`) and
  recover stale graph cost estimates without violating aggregate refresh
  bounds or starving smaller stale shapes behind `D > ttl_ns / 499` shapes,
  and embedding-delivery readiness stalls no longer inflate timing-refresh
  debt. Live GPU serving throughput was not measured in isolation on this
  commit.
- Measured simulator result (64 heldout seeds `10000..10063`, 62 scenarios,
  `--reference ttl`): `retained-refresh:funded:cumulative:alpha=0.002`
  (`retain_idle_credit=True`) was accepted across the complete core and
  validation suites (`41/41` evaluated gates passed): `35/35` core
  stationary scenarios vs `ttl` (geomean throughput ratio `1.009886`, worst
  lower bound `0.999357 >= 0.98`, worst p99 decode-gap upper bound
  `1.033553 <= 1.05`, worst p99 TTFT upper bound `1.047665 <= 1.05`,
  `0/2,240` stationary resets), `35/35` exact `1.000000` core parity vs the
  `retain_idle_credit=False` control, `64/64` seeds recovered within
  `60,000` busy ms across all 8 recovery and `mature-1000` recovery
  scenarios, calibration `coverage_16 = coverage_1000 = 1.0`, and `0`
  spurious probes across all 5 idle-transient scenarios (`320` seed runs).
- Scope boundary: continuous-busy debt refill rates (`499 * D` for timing
  refresh, `99 * D` for acceptance learning) and acceptance-learning debt
  after large physical probe episodes are unchanged.

Evidence:
Verified on Linux/WSL2 x86_64 (`rustc 1.100.0`, plain local `ext4` storage)
atop `origin/main` (`ba3afb13a7e9836080c23eadf8e1c17ee96e6e7a`):
- Layer 1 — CPU unit, integration, and CLI suites (`--locked --release`):
  - `pytest` across 9 scheduler/prefill suites,
    `tests/preparation/test_core_boundary.py`,
    `tests/test_design_review_hook.py`, and `tests/cli`: 941 passed,
    0 failed, 0 skipped.
  - `helios` (`--features runtime-core,server`, `--test-threads=1` under
    64 MiB `RLIMIT_MEMLOCK`): 1,689 unit + 61 integration = 1,750 passed,
    80 ignored (`43 + 37`), 0 failures outside untouched
    `model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape`,
    which panics identically on `origin/main` at
    `helios/src/model/packed_round_tests.rs:106:9` (`missing Speculative
    batch 2`).
  - `flare`: 236 passed, 4 ignored, 0 failed; `flare-cli`: 221 passed,
    3 ignored, 0 failed; `heliopause`: 208 passed, 5 ignored, 0 failed;
    `eos`: 1 passed; `selene` (`--features test-support`): 503 passed.
- Layer 2 — Scheduling simulator (`scripts/scheduling_sim/learning.py`):
  - 16-seed `--preset screen --policies retained-refresh --alpha 0.002
    --credit-cap-ms 5 --reference ttl` nominated
    `retained-refresh:funded:cumulative:alpha=0.002`
    (`retain_idle_credit=True`), and 64-seed `--preset validate` accepted it
    against `ttl` and the `retain_idle_credit=False` control.
- Layer 3 — Formal lifecycle conformance
  (`verification/helios-lifecycle/check.py`, Temurin JRE 21.0.13 +
  `tla2tools.jar` 1.7.4): all 9 TLA+ models (10 TLC model checks including
  `DispatchRing.tla` and `Speculation16.cfg`) passed with 0 errors and
  verified 593,660 observed Rust transitions across all 8 conformance
  suites.
- Limitations / unrun checks: live GPU and HTTP serving qualification
  (`tests/server/test_scheduler.py`, live power-cap cost-refresh recovery,
  and disk-backed embedding-delivery readiness stalls) was not executed on
  GPU hardware and remains tracked in `docs/TODO.txt`; `cargo kani`,
  `cargo-mutants`, and `check.py --mutations` were not run (no
  completion-vector validator, state-view extent arithmetic, or lifecycle
  safety guard was modified).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Carbon); design-review=c3a9
Signed-off-by: FujitsuPolycom <[email protected]>
@FujitsuPolycom
FujitsuPolycom force-pushed the pr/core-helios-sam-copy-drafts-and-cost-refresh branch from 9077913 to cdf1185 Compare November 28, 2026 23:42
@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

Addressed at cdf1185d69254c58e8ee50dabbab3dc8e43a01ce (rebased onto main ba3afb13, 12 files, +621/-173, -152 net lines vs 982a9ce3). The PR description has been updated to stand on its own.

Should Fix (S1–S4)

  • S1 (helios/README.md:432-443): Rewrote the funded timing-refresh paragraph to state that ordinary valid execution earns 0.002 / 0.998 of measured compute duration excluding measured readiness wait (capped at 5 ms, with samples whose device interval does not exceed readiness wait earning nothing), funded refresh pays that same compute duration with an unexcluded physical/wall fallback, and idle retains bounded earned credit (<= 5 ms) and negative debt while abort discards positive credit and preserves debt.
  • S2 (helios/src/scheduler/policy_tests.rs): Consolidated engine_with_terminal_prefill, cold_deepseek_16k_engine, and large_prefill_engine into a single parameterized prefill_catalog_engine helper (152 test-fixture lines reduced by ~74 lines while keeping all existing assertions intact).
  • S3 (tests/test_scheduling_learning_experiments.py): Parametrized test_boolean_cli_options_are_explicit_and_keep_default_ids over ("--partial-blocks", "partial_blocks") and ("--retain-idle-credit", "retain_idle_credit") while retaining the main(["--preset", "validate", "--configs", ..., "--retain-idle-credit"]) exit-code-2 check.
  • S4 (scripts/scheduling_sim/learning_policy.py, scripts/scheduling_sim/learning.py, docs/scheduling-theory.md): Defaulted PolicyConfig.retain_idle_credit to True for retained-refresh so the simulator's qualified policy matches Helios (False for other exploratory policies, with retain_idle_credit=False expressible via --configs / --comparison-configs JSON for reproducing the pre-PR rule), updated configuration_id and simulator unit tests accordingly, and noted in docs/scheduling-theory.md that --preset validate encodes retain_idle_credit in --configs rather than via the CLI flag.

Subtract / Simplify (1–4) & Nits (1, 3, 5)

  • Subtract 1 (helios/src/scheduler/cost.rs, policy_tests.rs): Removed the 60-line helper-level cost.rs test and ensured policy_tests.rs covers all five branches end-to-end through RequestScheduler::complete (gpu > wait, gpu == wait, gpu < wait with wall_ns == 0 and > 0, absent GPU with wall_ns > 0, and absent GPU with wall_ns == 0 rejected by validate_completion).
  • Subtract 2 (helios/src/scheduler.rs, helios/src/server/runtime.rs, policy_tests.rs): Renamed RequestScheduler::idle(&mut self) to RequestScheduler::assert_idle(&self) with a one-line doc comment and updated runtime.rs:1184 and all 10 policy_tests.rs call sites.
  • Subtract 3 (helios/src/scheduler/cost.rs, refresh.rs:87): Removed single-caller cost::timing_refresh_duration_ns and inlined cost::observed_compute_duration_ns(timing).or_else(|| cost::observed_duration_ns(timing)).unwrap_or(timing.wall_ns) in RefreshState::complete.
  • Subtract 4 (docs/scheduling-runtime-design.md, docs/scheduling-theory.md): Eliminated repeated restatements of idle retention and readiness-wait exclusion while preserving every constant, equation, and metric cross-reference.
  • Nit 1 (helios/src/scheduler/cost.rs:21-45): Narrowed the observed_compute_duration_ns docstring to "Device interval (or isolated wall time) less measured readiness wait" and noted on both helpers that ActionCosts::observe deliberately omits wall_ns.
  • Nit 3 (policy_tests.rs, tests/test_scheduling_learning_policy.py): Aligned the Python burst-recovery bound assertion to last_probe (matching policy_tests.rs's last_refresh_ns and the theorem in docs/scheduling-theory.md) and commented both sites.
  • Nit 5 (PR description): Clarified that strictly positive refresh charges rely on RefreshState::validate_completion rejecting zero-duration probes, and cited the exact panic and origin/main reproduction for untouched model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape (helios/src/model/packed_round_tests.rs:106:9, missing Speculative batch 2 on ba3afb13 / 2bdc8472).

Verification on git archive cdf1185d

  • Layer 1 (--locked --release & pytest): pytest 941 passed, 0 failed (including tests/cli, test_core_boundary.py, test_design_review_hook.py, and all 9 scheduler/prefill suites); helios --features runtime-core,server 1,751 passed (1,690 unit + 61 integration), 80 ignored (only untouched packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape failing as on main); flare 236 passed (4 ignored); flare-cli 225 passed (3 ignored); heliopause 208 passed (5 ignored); eos 2 passed; selene --features test-support 506 passed.
  • Layer 2 (scripts/scheduling_sim/learning.py): 16-seed --preset screen nominated retained-refresh:funded:cumulative:alpha=0.002 (retain_idle_credit=True), and 64-seed --preset validate --reference ttl with --comparison-configs (retain_idle_credit=False) accepted it across all 62 scenarios (41/41 gates passed: 35/35 vs ttl at geomean 1.009886, 35/35 exact 1.000000 parity vs retain_idle_credit=False, 64/64 recovery across all 8/8 recovery/mature-1000 scenarios, 0/2,240 stationary resets, and 0 spurious probes across all 320 idle-transient seed runs).
  • Layer 3 (verification/helios-lifecycle/check.py): All 9 TLA+ models (10 TLC runs) passed with 0 errors and verified 593,660 observed Rust transitions across 8 conformance suites.
  • Remaining limits: Live GPU/HTTP serving qualification (tests/server/test_scheduler.py, power-cap recovery, disk-backed readiness stalls) remains unrun on GPU hardware (docs/TODO.txt).

@flare-autobot please re-review at cdf1185d69254c58e8ee50dabbab3dc8e43a01ce.

@flare-autobot flare-autobot added area:scheduling Request scheduling, fairness, batching, and speculative-width selection. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:scheduling Request scheduling, fairness, batching, and speculative-width selection. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants