Skip to content

helios: gate offload Copy Engine batches during peer-copy graphs - #628

Merged
yatesdr merged 3 commits into
NVIDIA:mainfrom
yatesdr:fix/helios-peer-copy-offload-gate
Dec 1, 2026
Merged

yatesdr merged 3 commits into
NVIDIA:mainfrom
yatesdr:fix/helios-peer-copy-offload-gate

Conversation

@yatesdr

@yatesdr yatesdr commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Fixes #627

Problem and approach

On discrete PCIe SM120 GPUs (RTX PRO 6000, CUDA driver 595.99.02), tensor-parallel CUDA graphs whose collectives execute in-graph peer-to-peer Copy Engine nodes (Node::Copy with a Memory::Peer endpoint, such as b12x PCIeDmaAllReduce paired with FlagLaunch SM spin-waits) deadlock when Helios prefix-cache offload workers issue concurrent host-device Copy Engine batches on the same devices. Node-level frontier probes and controlled copy-path ablations isolated the stall specifically to concurrent Copy Engine DMA submission during peer-copy graph execution.

Coordinating host offload batches against peer-copy graph execution directly in Helios resolves the deadlock for already-exported model packages without changing the package format, Protobuf contract, scheduling policy, or per-model behavior.

Summary of changes

  • Structural peer-copy graph detection (helios/src/runtime_core/mod.rs, helios/src/runtime_core/serving.rs, helios/src/execution/manifest.rs): During CUDA graph reconstruction in NativeResources, record peer_copy_graphs[i] = true whenever any Node::Copy node in graph i has a Memory::Peer source or destination. Expose peer_copy_graphs and has_peer_copies on ExecutionManifest (defaulting absent entries to false for non-core manifests).
  • Per-runtime Copy Engine gate (helios/src/offload/copy_gate.rs, helios/src/offload/mod.rs, helios/src/runtime_core/model.rs, helios/src/server/runtime.rs): Add CopyEngineGate with RAII PeerGraphGuard and OffloadBatchGuard leases. Multiple offload workers hold OffloadBatchGuard concurrently across ranks while no peer-copy graph is waiting or active; waiting peer-copy graphs take priority over new offload batches and wait only for in-flight batches to drain. Share one Arc<CopyEngineGate> per NativeModel across RankExecutor, local offload::Binding / offload::open_with_gate, and NativeModel::attach_offload (Selene pool workers).
  • Execution boundary (helios/src/execution/ranks.rs): Union peer_copy_graphs across local RankPeers::Threads manifests so asymmetric peer copies are covered. Acquire a PeerGraphGuard in RankExecutor::submit only when the submitted graph contains peer copies, release completed leases in RankExecutor::poll, and release remaining leases in RankExecutor::close after inner.close() drains. Graphs without peer-copy nodes do not touch the gate.
  • Offload transfer paths (helios/src/offload/transfer.rs, helios/src/offload/transfer/codec.rs): Acquire OffloadBatchGuard per BATCH_BYTES batch in uncompressed RankWorker::run, CPU-codec copy_spans_batch, and all five GPU-codec capture/restore entry points. Preserve strict lock ordering (gpu.codec before CopyEngineGate) to prevent lock inversion against try_lock, and drain the offload stream before releasing the guard on error.

Resulting behavior

  • Eliminates the TP2 prefill deadlock under concurrent prefix-cache offload while keeping multi-rank offload concurrency outside peer-copy graphs and zero gate overhead on graphs without peer-copy nodes.
  • Preserves compatibility with existing exported model packages without re-export.

Validation

  • Compiler checks (RUSTFLAGS="-D warnings"): cargo check --locked --all-targets passed with 0 warnings on helios --features runtime-core,server, flare, flare-cli, and heliopause --lib.
  • Unit tests:
    • helios offload::copy_gate + execution::ranks: 5/5 passed (multi-rank concurrency, peer-graph wait/drain, priority under continuous offload, panic-unwind release, asymmetric rank union).
    • helios server::runtime + execution::threaded: 162/162 passed.
    • flare: 245/245 passed.
    • flare-cli: 200/201 passed under root and 200/201 passed under non-root (all 201 distinct tests passed across the two permission contexts).
  • SM120 4-GPU CUDA tests (FLARE_RUN_CUDA_TESTS=1): helios offload:: passed 19/19 default tests plus 6/6 ignored offload::transfer:: CPU/GPU KV codec and multi-GPU split-pool tests.
  • Live SM120 TP2 serving (--gpus 0,1, --prefix-cache-memory 4G, 16 GiB disk tier):
    • Qwen3.8-Flash-Next TP2 (--lossless-kv-compression off): cold, warm (0/6 pos0 mismatches, 5.08x speedup), restart + disk restore (0/6 pos0 mismatches, 2.45x speedup), 8-way burst with 2 aborts (8/8, 4.15 s), and 5x 8-way uncached 6,578-token bursts (40/40 HTTP 200, 4.68–4.83 s/burst; unpatched main deadlocked during the first burst).
    • GLM-5.3-Flash TP2 (--lossless-kv-compression gpu): cold, warm (0/96 token mismatches, 3.50x speedup), restart + restore (0/96 token mismatches, 1.55x speedup), and 8-way burst with 2 aborts (8/8, 5.88 s).

Limitations

  • Live serving validation covered single-host threaded TP2 on SM120 (RTX PRO 6000) with local DRAM and disk tiers (uncompressed and GPU KV codec). Multi-host TP, live Selene pool serving, live CPU KV codec serving, and non-SM120 GPUs were not tested end-to-end (pool and CPU codec paths share the same CopyEngineGate wiring and passed unit and CUDA codec tests).

Discord: D-Rock

On discrete PCIe GPUs (observed on SM120 RTX PRO 6000 under CUDA driver
595.99.02), tensor-parallel CUDA graphs whose collectives drive peer-to-peer
transfers through in-graph Copy Engine nodes (`Node::Copy` with a
`Memory::Peer` endpoint, such as `b12x` `PCIeDmaAllReduce`) deadlock when
prefix-cache offload workers issue concurrent host-device Copy Engine
batches on the same devices. Even a single concurrent device-to-host copy
from an unrelated allocation on the offload stream stalls both ranks inside
the graph's peer-copy collectives. Coordinating host offload batches against
peer-copy graph execution directly in Helios eliminates the deadlock for
already-exported model packages without changing the package format,
scheduling policy, or per-model behavior.

Detect peer-copy graphs structurally during CUDA graph reconstruction in
`NativeResources`: record `peer_copy_graphs[i] = true` whenever any
`Node::Copy` node in graph `i` has a `Memory::Peer` source or destination,
carry that vector on `ExecutionManifest`, and union it across local
`RankPeers::Threads` manifests in `RankExecutor`. Share one
`offload::CopyEngineGate` per `NativeModel` across `RankExecutor`, local
`offload::Binding` / `offload::open_with_gate`, and `NativeModel::attach_offload`
(for Selene pool workers). When submitting a graph flagged with peer copies,
`RankExecutor` acquires a `PeerGraphGuard` (blocking until in-flight offload
batches drain and giving waiting peer-copy graphs priority over new batches)
and releases it on `poll` completion or after `close` drains. Offload
workers acquire an `OffloadBatchGuard` per `BATCH_BYTES` batch in
uncompressed `RankWorker::run`, CPU-codec `copy_spans_batch`, and all five
GPU-codec capture/restore entry points (preserving strict `gpu.codec` before
`CopyEngineGate` lock order and draining the CUDA stream before releasing
the guard on error). Graphs without peer-copy nodes incur no gate locking.

Eliminates the TP2 prefill deadlock under concurrent prefix-cache offload
while preserving multi-rank offload concurrency outside peer-copy graphs and
maintaining warm/restore correctness and burst latency.

Validation:
- `RUSTFLAGS="-D warnings" cargo check --locked --all-targets` passed for
  `helios --features runtime-core,server`, `flare`, `flare-cli`, and
  `heliopause --lib` (0 warnings).
- Unit tests passed: `helios` `offload::copy_gate` and `execution::ranks`
  (5/5), `helios` `server::runtime` and `execution::threaded` (162/162),
  `flare` (245/245), and `flare-cli` (200/201 under root and 200/201 under
  non-root, with all 201 distinct tests passing across the two permission
  contexts).
- SM120 4-GPU CUDA `helios` `offload::` tests passed: 19/19 default tests
  plus 6/6 ignored `offload::transfer::` GPU/CPU codec and multi-GPU split
  pool tests (`FLARE_RUN_CUDA_TESTS=1`).
- Live SM120 TP2 (`--gpus 0,1`, `--prefix-cache-memory 4G`, 16 GiB disk
  tier) on `Qwen3.8-Flash-Next` (`--lossless-kv-compression off`): cold,
  warm (0/6 pos0 mismatches, 5.08x speedup), restart + disk restore (0/6
  pos0 mismatches, 2.45x speedup), 8-way burst with 2 aborts (8/8, 4.15s),
  and 5x 8-way uncached 6578-token bursts (40/40 HTTP 200, 4.68-4.83s/burst;
  unpatched `main` deadlocked during the first burst).
- Live SM120 TP2 on `GLM-5.3-Flash` (`--lossless-kv-compression gpu`): cold,
  warm (0/96 token mismatches, 3.50x speedup), restart + restore (0/96
  token mismatches, 1.55x speedup), and 8-way burst with 2 aborts (8/8,
  5.88s).

Limitations:
- Tested on single-host threaded TP2 on SM120 (RTX PRO 6000) with local DRAM
  and disk tiers (uncompressed and GPU KV codec). Multi-host TP, live
  Selene pool serving, CPU KV codec live serving, and non-SM120 GPUs were
  not exercised live (though pool and CPU codec paths share the same
  `CopyEngineGate` wiring and unit/CUDA codec tests).

Fixes NVIDIA#627

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
@flare-autobot flare-autobot added bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P1 High attention: unresolved correctness, serving failure, or model-data deletion risk. labels Nov 30, 2026
@yatesdr
yatesdr marked this pull request as ready for review November 30, 2026 11:42
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 628.
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 flare-autobot added the triage:review Proposed change needs code review; this does not imply merge readiness. label Nov 30, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

Clean engineering of structural peer-copy detection, RAII gate primitives, strict gpu.codec → CopyEngineGate ordering, stream drains, and executor.close()-before-store.close()—but head 1870a27 adds indefinite offload starvation under pipelined TP decode, puts a blocking per-16 MiB event.synchronize() on every prefix-cache deployment without benchmarks, and CI is failing.

  • Blockers: 3 · Should fix: 4 · Subtract/Simplify: 3 · Nits: 2
Walkthrough
  • Structural peer-copy graph detection (runtime_core/mod.rs:119, 919, 1149-1156, 1238, runtime_core/serving.rs:49, 59, 202, execution/manifest.rs:436-449): records peer_copy_graphs[i] = true when any Node::Copy references a Memory::Peer allocation; exposes peer_copy_graphs/has_peer_copies on ExecutionManifest (absent defaults to false), with Vec::new() in non-core manifest literals.
  • Per-model Copy Engine gate (offload/copy_gate.rs:1-263, offload/mod.rs:19-60, 114-130, runtime_core/model.rs:27, 662, 985-991, 1032-1038, server/runtime.rs:715-733): RAII PeerGraphGuard/OffloadBatchGuard leases, one Arc<CopyEngineGate> per NativeModel shared across offload::Binding, offload::open_with_gate, attach_offload, and Selene pool peer workers.
  • Execution boundary (execution/ranks.rs:26-181): RankExecutorInner wrapper, unions peer_copy_graphs across RankPeers::Threads via merge_peer_copy_graphs, acquires PeerGraphGuard in submit only for flagged graphs, releases leases in fence order in poll, clears residuals in close.
  • Offload transfer gating (offload/transfer.rs:293-436, 480-555, 2070-2113, offload/transfer/codec.rs:153-370, 533-795, 958-1031): Option<&CopyEngineGate> threaded into RankWorker::run, CPU-codec copy_spans_batch, and all five GPU-codec entry points, preserving lock order and draining the stream before lease release on success and error.
Merge Risk: High · up to 1870a27
  • Serving & prefix-cache liveness under TP pipelining: enter_offload_batch (offload/copy_gate.rs:60-67) gives strict priority to peer-copy graphs while ThreadedExecutor allows 2-frame decode pipelining (execution/threaded/protocol.rs:28), keeping peer_graphs_active >= 1 for sustained decode and starving inbound store.fetch restores and outbound checkpoint unpins.
  • Hot-path regression for all prefix-cache users: NativeModel attaches Some(copy_gate) unconditionally (runtime_core/model.rs:986-989, 1032-1038), turning every 16 MiB BATCH_BYTES batch (cuda.rs:169) into a blocking record + event.synchronize() on single-GPU and non-peer-copy TP runs, opposing Reduce disk offload restore latency and integrated-memory intake overhead #497 with zero A/B offload measurement.
  • Worker-thread blocking & failing CI: RankExecutor::submit blocks the model worker on an unbounded Condvar::wait outside ThreadedExecutor's 120 s stall detector (execution/threaded.rs:23, 942-952), reversing documented invariants without doc updates; CI failed on head 1870a27.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings

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

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

…ls, and preserve metrics

Address starvation, non-peer-copy overhead, timeout, metrics, multi-host
coverage, and cleanup gaps in `CopyEngineGate`:

- Add bounded fairness to `CopyEngineGate` (`MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4`):
  when offload batches are waiting under sustained 2-frame pipelined peer-copy
  decode, `PeerGraphLeases::should_drain_for_offload()` signals
  `RankExecutor::can_submit()` to pause pipelining for one frame so active
  peer-copy leases drain to zero, then grants one concurrent wave to all waiting
  offload ranks before resuming peer-copy graphs. Only arm an offload wave when
  `peer_graphs_active == 0` so a single-threaded pipelined worker cannot
  self-deadlock.
- Scope `CopyEngineGate` creation in `NativeModel` to models where at least one
  rank reconstructed a graph with `Node::Copy` referencing `Memory::Peer`
  (`NativeResources::has_any_peer_copy_graphs()`). Single-GPU and non-peer-copy
  TP models receive `copy_gate = None` and stay on the ungated single-sync-per-window
  offload fast path.
- Bound `CopyEngineGate::enter_peer_graph` with `PEER_GRAPH_GATE_TIMEOUT`
  (120 s, aligned with `ThreadedExecutor::TIMEOUT`), returning
  `ExecutionError::Drain` instead of parking the model worker thread indefinitely
  if an offload Copy Engine batch fails to drain, and update the invariants in
  `docs/prefix-cache-offload.md` and `helios/src/offload/transfer.rs`.
- Exclude gate-wait pauses from throughput metrics: start the transform timer
  after acquiring the gate in all five GPU-codec call sites in `codec.rs`,
  accumulate per-rank `gate_wait` and subtract `max_gate_wait` from
  `Reply.elapsed` in `Transfers::absorb`, and record `prefill_started` in
  `Worker::submit` after `executor.submit()` succeeds.
- Share `PeerGraphLeases` between `RankExecutor` and multi-host `serve_rank`
  (`execution/parallel.rs`), and wire `owner.copy_gate()` through
  `offload::shard::join_peer_with_gate` (`flare-cli/src/cluster.rs`).
- Deduplicate gated/ungated `stream.copy_batch` and stream-drain helpers into
  `transfer::copy_batch_gated` and `transfer::drain_stream`; remove dead
  `ExecutionManifest::has_peer_copies` and unused `OffloadBatchGuard` re-export;
  move pure delegation matches onto `RankExecutorInner`; validate
  `peer_copy_graphs.len() == graphs.len()` (when non-empty) in
  `ExecutionManifest::validate()`; and add unit and gated CUDA transfer tests.

Validation:
- `RUSTFLAGS="-D warnings" cargo check --locked --all-targets` passed with 0
  warnings on `helios --features runtime-core,server`, `heliopause --lib`,
  `flare`, and `flare-cli`.
- `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server`:
  1,740/1,740 lib tests passed (1,739 with `io_uring` + 1 non-root chmod test)
  and all integration tests passed (excluding the 9 HF-template fixture tests
  requiring `FLARE_TEST_TEMPLATE_DIR`).
- `cargo test --locked --release --manifest-path flare/Cargo.toml`: 245/245 passed.
- `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`: all 201
  unit tests (across root and non-root permission contexts) and all 4
  integration test suites passed.

Limitations:
- New gated CUDA transfer tests (`split_pools_cost_each_device_its_part_and_round_trip_units`
  and `gated_cpu_and_gpu_codec_capture_and_restore_defer_while_peer_graph_holds_gate`)
  and an A/B peer-copy offload latency comparison have not yet been executed on
  this commit because the SM120 host GPUs are currently occupied by another job;
  the earlier SM120 CUDA `offload::` tests and live `Qwen3.8-Flash-Next` TP2 /
  `GLM-5.3-Flash` TP2 runs passed on `1870a27`.

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
@yatesdr

yatesdr commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the Autobot review findings in 76e1813:

  • Anti-starvation under 2-frame pipelined peer-copy decode: Added bounded fairness (MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4) in CopyEngineGate + PeerGraphLeases::should_drain_for_offload() checked in RankExecutor::can_submit(). When offload workers are waiting, pipelining pauses for one frame so active peer-copy leases drain to zero, grants one concurrent wave to all waiting offload ranks, and resumes peer-copy graphs. Added unit test offload_makes_forward_progress_under_pipelined_peer_graphs.
  • Zero overhead on single-GPU and non-peer-copy models: NativeModel now instantiates copy_gate: Option<Arc<CopyEngineGate>> only when at least one rank reconstructed a graph containing Node::Copy referencing Memory::Peer (NativeResources::has_any_peer_copy_graphs()). All single-GPU and non-peer-copy TP models receive None and stay on the ungated single-sync-per-window offload path.
  • Bounded drain timeout & docs: Bounded CopyEngineGate::enter_peer_graph at PEER_GRAPH_GATE_TIMEOUT (120 s, returning ExecutionError::Drain), added enter_peer_graph_times_out_without_stranding_gate, and updated docs/prefix-cache-offload.md and helios/src/offload/transfer.rs.
  • Metrics isolation: Moved GPU-codec transform timers after gate acquisition in all 5 codec.rs sites, subtracted max_gate_wait from Reply.elapsed in Transfers::absorb, and moved prefill_started recording after executor.submit() succeeds.
  • Multi-host peer ranks & cleanups: Shared PeerGraphLeases across RankExecutor and serve_rank (execution/parallel.rs), wired owner.copy_gate() through offload::shard::join_peer_with_gate (flare-cli/src/cluster.rs), deduplicated copy_batch_gated / drain_stream, removed dead ExecutionManifest::has_peer_copies and unused OffloadBatchGuard re-export, moved pure delegation methods onto RankExecutorInner, validated peer_copy_graphs.len() in ExecutionManifest::validate(), and added lease-lifecycle and gated CUDA transfer tests.

Validation on 76e1813:

  • RUSTFLAGS="-D warnings" cargo check --locked --all-targets passed (0 warnings) on helios --features runtime-core,server, heliopause --lib, flare, and flare-cli.
  • Full --locked --release suites passed: helios (1,740/1,740 lib tests + all integration tests, excluding the 9 HF-template fixture tests requiring FLARE_TEST_TEMPLATE_DIR), flare (245/245), and flare-cli (201/201 unit tests + all 4 integration suites).
  • Note on CI: Helios lifecycle (lifecycle and kani) both passed on 1870a27; the only failing check was Python CPU tests / pytest, which is the pre-existing main failure tracked in CI: Python CPU tests permanently red: two stale library-internals assertions (triton 3.7.x text, torch InductorError) #623 / tests: fix two Python CPU test premises about stock Triton and Inductor #624.
  • Pending GPU re-run: the new gated CUDA transfer tests and a peer-copy A/B offload latency measurement have not yet been run on 76e1813 because the SM120 test host's GPUs are currently occupied; I will run and post those numbers once the GPUs are free.

Discord: D-Rock

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

Head 76e1813 cleanly resolves all Round 1 blockers on the in-process threaded TP path and correctly scopes CopyEngineGate to peer-copy models only. But it also gates multi-process peer ranks without wiring should_drain_for_offload() into serve_rank (unbounded offload starvation on RankPeers::Processes), and subtracts max_gate_wait from Reply.elapsed, distorting Selene's admission pricing.

  • Blockers: 1 · Should fix: 2 · Subtract/Simplify: 4 · Nits: 1
Walkthrough
  • Structural peer-copy graph detection (helios/src/runtime_core/mod.rs:119, 919, 1149-1156, 1238, 1347-1349, helios/src/runtime_core/serving.rs:49, 59, 202, helios/src/execution/manifest.rs:838-843): Records peer_copy_graphs[i] = true when any Node::Copy references a Memory::Peer allocation, validates populated lengths in ExecutionManifest::validate(), and only instantiates NativeModel.copy_gate when at least one rank has peer-copy graphs (helios/src/runtime_core/model.rs:827-831).
  • Bounded fairness & timeout gate (helios/src/offload/copy_gate.rs:1-583, helios/src/offload/mod.rs:26, 39-60, 114-130, helios/src/offload/shard.rs:37-61, flare-cli/src/cluster.rs:254-261): Adds CopyEngineGate (with MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4 and PEER_GRAPH_GATE_TIMEOUT = 120 s) and PeerGraphLeases, wired across NativeModel, offload::Binding, open_with_gate, and multi-process peer join_peer_with_gate.
  • Execution boundary (helios/src/execution/ranks.rs:19-196, helios/src/execution/parallel.rs:563-566, 652-665, 692, helios/src/server/runtime.rs:718-733, 2340-2360): Splits RankExecutorInner, merges asymmetric peer_copy_graphs across RankPeers::Threads, checks !self.leases.should_drain_for_offload() in RankExecutor::can_submit, acquires/releases leases in fence order in both RankExecutor and serve_rank, and records prefill_started only after executor.submit() succeeds.
  • Offload transfer & codec gating (helios/src/offload/transfer.rs:292-339, 441-505, 780, 795-799, helios/src/offload/transfer/codec.rs:288-376, 673-700, 760-782, 971-1034): Gates uncompressed batches via copy_batch_gated (preserving single end-of-window sync when copy_gate is None), gates all five GPU-codec sites with gpu.codec locked before CopyEngineGate, moves transform_ns timers after gate acquisition, and threads gate_wait into Reply.elapsed.
  • Documentation & tests (docs/prefix-cache-offload.md:133-138, 917-924, 1025-1029, copy_gate.rs:308-583, ranks.rs:198-227, transfer.rs:2013-2053, codec.rs:1286-1292): Updates offload blocking/queueing invariants and adds unit tests for gate fairness/timeout/lease ordering plus ignored CUDA tests for gated transfer and codec paths.
Merge Risk: Medium · up to 76e1813
  • Multi-process TP liveness regression (RankPeers::Processes): Newly gating peer offload workers (flare-cli/src/cluster.rs:254-261 -> helios/src/offload/shard.rs:47-61) alongside serve_rank (helios/src/execution/parallel.rs:563-566, 652-663) without checking leases.should_drain_for_offload() lets 2-frame pipelined decode starve peer-rank offload workers indefinitely whenever rank 0's local gate has no waiting offload batches.
  • Prefix-cache admission pricing distortion: Subtracting max_gate_wait from Reply.elapsed (helios/src/offload/transfer.rs:780, 795-799) hides real restore wait time from MemoryStore::inbound_rate (selene/src/memory.rs:1455) and worth_fetching / RestoreWait::defer, biasing heavily gate-contended restores to look faster than prefill.
  • Zero blast radius on non-peer-copy models, unverified gated GPU paths on 76e1813: NativeModel.copy_gate is None when no rank reconstructed a peer-copy graph (helios/src/runtime_core/model.rs:827-831), keeping single-GPU and non-peer-copy models untouched, but the new gated CUDA transfer/codec tests and peer-copy A/B measurements have not yet run on 76e1813.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings

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

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

…Gate wiring

Address review findings on CopyEngineGate and offload transfer plumbing:
- Defer READY in execution::parallel::serve_rank when a rank's
  CopyEngineGate reports a waiting offload batch, parking on in-flight
  frames until active peer-copy graphs drain so multi-process TP ranks
  cannot starve offload transfers under continuous traffic. Add unit
  test peer_deferred_ready_drains_active_frames_for_waiting_offload.
- Measure Selene offload Reply.elapsed as real wall-clock completion
  time (including gate wait) so MemoryStore inbound_rate and admission
  pricing reflect actual offload duration, while keeping GPU-codec
  timing scoped after gate acquisition and prefill_started after
  executor.submit(). Remove the gate_wait plumbing from RankReply,
  Pending, RankWorker, RankCodec, and copy helpers.
- Collapse open_with_gate into offload::open and join_peer_with_gate
  into offload::shard::join_peer, deduplicate batch sync/drain into
  GatedCopies in offload::transfer, make enter_peer_graph_timeout
  private, and tighten the drain bound wording in
  docs/prefix-cache-offload.md.
- Add gated SM120 CUDA test
  gated_cpu_and_gpu_codec_capture_and_restore_defer_while_peer_graph_holds_gate.

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
@yatesdr

yatesdr commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Updated in fdd898b to address the review findings:

  • Multi-process offload fairness (execution::parallel::serve_rank): When PREPARE or PREPARE_MORE arrives while leases.should_drain_for_offload() is true, serve_rank defers READY and parks on in-flight frames until active peer-copy graphs drain and the gate is no longer holding back new launches. Covered by unit test peer_deferred_ready_drains_active_frames_for_waiting_offload (live multi-host TCP/RoCE execution was not tested on hardware).
  • Offload transfer pricing and gate_wait removal: Reply.elapsed now retains real wall-clock completion time (including gate wait) so MemoryStore::inbound_rate and admission pricing reflect actual restore latency. Removed the gate_wait plumbing across RankReply, Pending, RankWorker, RankCodec, and copy helpers, while keeping GPU-codec compression/decompression timing scoped after gate acquisition and prefill_started after executor.submit().
  • Cleanup and docs: Collapsed open_with_gate into offload::open and join_peer_with_gate into offload::shard::join_peer, extracted GatedCopies to share batch sync/drain between uncompressed and CPU-codec transfers, narrowed CopyEngineGate::enter_peer_graph_timeout to private, and updated the drain-bound phrasing in docs/prefix-cache-offload.md.

Verification (4× RTX PRO 6000 SM120 PCIe)

  • RUSTFLAGS="-D warnings" cargo check --locked --all-targets passed for helios (runtime-core,server), heliopause, flare, and flare-cli.
  • cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib offload:: and execution:: (134/134) passed.
  • All 8 ignored SM120 CUDA offload::transfer:: tests passed with FLARE_TEST_KV_CODEC_CUBIN (11.91s), including gated_cpu_and_gpu_codec_capture_and_restore_defer_while_peer_graph_holds_gate.
  • Qwen3.8-Flash-Next TP2 (--gpus 0,1, --prefix-cache-memory 4G, --prefix-cache-disk ... --prefix-cache-disk-limit 16G, --lossless-kv-compression off) A/B comparison against main (3801ff1d):
    • cold (6 prompts, 30,797 prompt tokens): 2.676s (main) vs 2.577s (fdd898b, 1.04x), 0 pos-0 token mismatches.
    • warm (6 prompts): 0.552s (main) vs 0.482s (fdd898b, 1.15x), 0 pos-0 token mismatches.
    • restore after restart (6/6 disk hits, 21,159 reused tokens): 1.045s (main) vs 1.062s (fdd898b, 0.98x), 0 pos-0 token mismatches.
    • burst on fdd898b (8 concurrent shared-prefix requests + 2 mid-flight cancellations): 8/8 HTTP 200 in 4.170s, post_health=200, clean SIGTERM shutdown (rc=0).

@flare-autobot please re-review.

Discord: D-Rock

@flare-autobot flare-autobot added the area:scheduling Request scheduling, fairness, batching, and speculative-width selection. label Dec 1, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

Head fdd898b resolves all Round 2 blockers and should-fix items, with the serve_rank deferred-READY path verified as deadlock-free and lock ordering, stream drains, and teardown confirmed sound. Remaining items are optional simplification and polish, not merge gates.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 3 · Nits: 3
Walkthrough
  • Structural peer-copy graph detection (runtime_core/mod.rs:119, 919, 1149-1156, 1238, 1347-1349, runtime_core/serving.rs:49, 59, 202, execution/manifest.rs:436-440, 838-843): Records peer_copy_graphs[i] = true when any Node::Copy endpoint resolves to Memory::Peer, validates length when populated, and instantiates NativeModel.copy_gate only when at least one rank has peer-copy graphs (runtime_core/model.rs:827-831).
  • Bounded fairness & timeout gate (offload/copy_gate.rs:1-645, offload/mod.rs:19-60, 114-123, offload/shard.rs:37-51, flare-cli/src/cluster.rs:254-261): Adds CopyEngineGate (MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4, PEER_GRAPH_GATE_TIMEOUT = 120 s returning ExecutionError::Drain) and fence-ordered PeerGraphLeases, wired through Binding, offload::open, attach_offload, and offload::shard::join_peer.
  • Execution boundary (execution/ranks.rs:19-227, execution/parallel.rs:563-710, server/runtime.rs:714-734, 2340-2360): Splits RankExecutorInner, unions asymmetric peer_copy_graphs across RankPeers::Threads, defers READY via RankExecutor::can_submit / serve_rank while peer-copy frames drain, acquires/releases leases in fence order, clears residual leases after close()/abandon(), and timestamps prefill_started after executor.submit() returns.
  • Offload transfer & codec gating (offload/transfer.rs:290-505, 807-816, offload/transfer/codec.rs:152-373, 530-800, 958-1011): Extracts GatedCopies to share per-batch gating + error stream drain across uncompressed and CPU-codec paths (one end-of-window sync when ungated), gates all five GPU-codec entry points under gpu.codec → CopyEngineGate lock order, and restores wall-clock Reply.elapsed.
  • Documentation & tests (docs/prefix-cache-offload.md:133-138, 917-924, 1025-1029, copy_gate.rs:303-645, ranks.rs:198-227, transfer.rs:2025-2059, codec.rs:1264-1270): Documents bounded drain and fairness behavior, adds 8 copy_gate and 2 ranks unit tests, plus ignored CUDA tests for gated uncompressed, CPU-codec, and GPU-codec transfers.
Merge Risk: Medium · up to fdd898b
  • Zero blast radius on single-GPU and non-peer-copy models: NativeModel.copy_gate is None unless a rank reconstructed a graph with Node::Copy → Memory::Peer (runtime_core/model.rs:827-831), keeping ungated models on the single-sync-per-window path (offload/transfer.rs:347-363) and skipping locks via self.guards.is_empty() (offload/copy_gate.rs:258-264).
  • Core execution and offload hot paths on peer-copy TP models: Touches RankExecutor (execution/ranks.rs:99-196), serve_rank (execution/parallel.rs:563-710), and all uncompressed/CPU/GPU codec transfer paths (offload/transfer.rs:290-498, offload/transfer/codec.rs:288-373, 665-796, 958-1011).
  • Residual verification gaps: Live multi-host TCP/RoCE execution of the deferred-READY path was not exercised on hardware (unit-test simulation only), and the branch predates merged #645 (GraphKind::Prefill now in GraphKind::pipelines()); no textual conflicts with main, and a routine rebase before merge keeps CI (Helios lifecycle + CPU suites) current.
Pre-merge checks: ✅ 3 passed · ⚠️ 1 warning

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

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

@yatesdr
yatesdr merged commit 5d53040 into NVIDIA:main Dec 1, 2026
3 checks passed
FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Dec 1, 2026
…cing with cohort horizon and time-potential

Why

Under concurrent mixed prefill-and-decode workloads where active decode
requests have staggered or tight remaining output budgets, the prefill
coalescing continuation term in helios/src/scheduler/policy.rs and
scripts/scheduling_sim/utility.py exhibits two defects:

1. Scalar minimum peer_budget collapse: clamping the coalescing horizon and
   speculative expected output for all active decoders by
   peer_budget = min_i(rem_i) drops coalescing credit toward zero whenever any
   single active decoder nears completion, stalling decode-batch growth
   (K -> K + m) even while the rest of the cohort retains ample remaining
   output budget.
2. Uniform per-token amortization against non-linear prefill latency: dividing
   the unlocked decode-batch surplus V_unlock uniformly across initial_prefill
   tokens rewards suboptimal bucket-boundary splits (such as 512 + 38 tokens on
   a 550-token prompt) and leaves under 1% of V_unlock on short residual tails
   that actually enter decode, stalling near-complete requests behind active
   decoders while holding concurrency slots and KV pages.

Averaging the bounded horizon across active decoders eliminates single-stream
collapse while preserving coalescing_horizon_tokens (default 64.0). Replacing
uniform per-token amortization with a telescoping potential over the loaded
core's monotone minimal measured GPU prefill time T_min(tokens) at each
request's fixed reference context (admission_reused_tokens) bounds total
coalescing credit to at most 1x V_unlock across any multi-chunk path (including
subset TerminalPrefill catalogs), penalizes tail-creating splits in proportion
to added GPU time, retains 100% of the unlock rate
V_unlock / T_min(initial_prefill) on residual tails, bounds DP work to
O(|catalog| x 512) without coarse-grid quantization cliffs, caches
non-context-scaled DP tables once per PlanningScope for O(1) scoring, and falls
back to uniform per-token amortization on unmeasured cold-start catalogs.

What

- Helios scheduler (helios/src/scheduler.rs, helios/src/scheduler/checkpoints.rs,
  helios/src/scheduler/policy.rs, helios/src/scheduler/utility.rs; +863/-64,
  799 net lines including 32 added lines of #[cfg(test)] helpers -> 767 net
  non-test Rust production LOC):
  - Replaced scalar peer_budget = min_i(rem_i) in
    RequestScheduler::coalescing_prefill_terms with a stack-allocated
    [usize; REQUEST_LANES] cohort average, capping speculative expected output
    per decoder before averaging (matching scripts/scheduling_sim/utility.py)
    and resolving Decode graph durations once per call.
  - Added ResolvedPrefillCatalog, RefCell<Box<CoalescingScopeCache>> (allocated
    once in RequestScheduler::new(); +16 B to size_of::<RequestScheduler>(),
    zero per-select_plan heap allocations, invalidated on PlanningScope
    enter/drop, descending capacity walk retaining the largest capacities when
    > 32 shapes exist), and PrefillTimeModel dynamically over the loaded core's
    Prefill, TerminalPrefill, and constant Mixed catalogs.
  - Evaluated T_min(tokens) via O(1) closed-form affine summation for full
    chunks (PrefillPredictor::full_chunk_affine()) plus a stack-allocated
    strictly monotone 1D DP (MAX_DP_STEPS = 512, conservative downward
    quantization with exact single-launch remainder pricing on coarse grids),
    caching DP tables per scope whenever
    has_context_scaling(requires_terminal) is false.
  - Gated PrefillTimeModel::min_time_ms under #[cfg(test)] so non-test
    --release builds emit zero new compiler warnings.
- Python scheduling simulator (scripts/scheduling_sim/utility.py; +129/-15,
  114 net production LOC): mirrored cohort-averaged horizon and time-potential
  telescoping in UtilityPolicy.
- Docs and tests (docs/scheduling-runtime-design.md +18/-8;
  helios/src/scheduler/policy_tests.rs +1,573/-0;
  tests/test_scheduling_utility.py +304/-3): documented the cohort horizon and
  time-potential formulas and added Rust and Python coverage for cohort
  averaging, telescoping, subset TerminalPrefill catalogs, downward coarse-DP
  quantization, scope-cache invalidation, zero-intercept context-scaled
  predictors, cold-start fallback, and O(|catalog|) lookup scaling.
- Compatibility: zero Protobuf, core-format, ABI, CLI, config, or graph-op
  changes; existing exported cores load and serve unchanged; zero unsafe code
  or new locks.

Result

Live zero-re-export flare run A/B benchmarks on two 4-GPU TP4 clusters
(DeepSeek-V4.1-Flash, identical CLI flags and prompts across arms, zero server
errors or non-finite logprobs; measured on the equivalent scheduler logic atop
571a447 prior to the rebase onto 5d53040 incorporating NVIDIA#656 and NVIDIA#628):

4x RTX PRO 6000 (SM120 TP4, exported core gb202-tp4-202612010626, balanced 4
trials/arm and throughput 2 trials/arm; PolicyConfig::throughput() inherits
coalescing_horizon_tokens = 64.0 from PolicyConfig::default()):

| Policy ∥ Workload | Makespan | Agg Decode | TTFT (p50 ∥ Max) | Max Decode Gap | Mean TPOT |
| --- | --- | --- | --- | --- | --- |
| balanced ∥ Mixed long-prefill + decode | 3.88 -> 3.82 s (-1.5%) | +1.7% | 2K p50: 1,599 -> 1,479 ms (-7.5%) | 408.1 -> 322.4 ms (-21.0%) | 7.20 -> 8.50 ms (+18.2%) |
| balanced ∥ Burst-8 + BG decode | 2.35 -> 2.24 s (-4.6%) | +5.0% | 1,224 -> 992 ms (-19.0%) ∥ 1,782 -> 1,509 ms (-15.3%) | 337.6 -> 201.3 ms (-40.4%) | 6.03 -> 6.80 ms (+12.9%) |
| throughput ∥ Mixed long-prefill + decode | 3.86 -> 3.79 s (-1.8%) | +1.9% | 2K p50: 1,823 -> 1,674 ms (-8.1%) | 584.8 -> 320.7 ms (-45.2%) | 7.55 -> 10.20 ms (+34.9%) |
| throughput ∥ Burst-8 + BG decode | 2.39 -> 2.09 s (-12.8%) | 610.3 -> 698.2 tok/s (+14.4%) | 1,179 -> 983 ms (-16.7%) ∥ 1,729 -> 1,492 ms (-13.7%) | 485.0 -> 452.7 ms (-6.6%) | 6.38 -> 8.23 ms (+29.2%) |

4x DGX Spark GB10 (SM121 TP4, exported core gb10-tp4-202612010243, balanced, 3
trials/arm):

| Workload | Wall / Makespan | Decode Throughput | TTFT | Decode Tail Latency | Mean TPOT |
| --- | --- | --- | --- | --- | --- |
| 12 decoders + 3 ~24.8K prefills | 20.67 -> 18.73 s (-9.4%) | 94.33 -> 103.28 tok/s (+9.5%) | Heavy max: 16,603 -> 14,537 ms (-12.4%) | Max gap: 1,720.5 -> 1,689.2 ms (-1.8%) | 74.77 -> 67.43 ms (-9.8%) |
| 6 decoders + Burst-8 prefills | 12.87 -> 12.41 s (-3.5%) | 104.44 -> 108.28 tok/s (+3.7%) | Burst max: 6,996 -> 6,840 ms (-2.2%) | BG p99 ITL: 266.34 -> 237.94 ms (-10.7%), 0 stalls >500 ms | 40.70 -> 42.10 ms (+3.4%) |

Trade-off: on SM120 under mixed bursts, coalescing prefills earlier into the
decode cohort raises active-decode mean TPOT (+12.9%..+18.2% balanced,
+29.2%..+34.9% throughput) while reducing worst-case decode stalls (-21%..-45%),
TTFT (-7.5%..-19.0%), and makespan (-1.5%..-12.8%).

Deterministic simulator matrix (scripts/scheduling_sim/workloads.py, 21
workloads, seed=0, Value(64), rate_history="service"): mixed=False throughput
and mixed=True balanced are 21/21 bit-identical; mixed=True throughput has
21/21 identical summary metrics; mixed=False balanced is 18/21 identical with
burst_eight makespan 2060 -> 1998 ms (-62 ms, max TTFT -90 ms),
burst_eight_low 7940 -> 7938 ms (-2 ms), and burst_eight_8k 2648 -> 2676 ms
(+28 ms, +1.0%, max TTFT +44 ms). Hot-path release scaling at 16 x 256K warmed
adds +23 ENTRY_LOOKUPS (429 -> 452) and +2.5 us median select_plan latency
(29.9 -> 32.4 us).

Evidence

Verified on a clean git archive extract of this commit atop 5d53040:
- git merge-tree --write-tree 5d53040 HEAD -> 0 conflicts
- cargo check --locked --release on helios (--features runtime-core,server --lib), flare (--lib), flare-cli (--bins), and heliopause -> 0 new non-test warnings
- cargo test --locked --release on helios (--features server --lib and --features runtime-core,server --lib), flare (--lib), and flare-cli
- python3 -m pytest tests/preparation/test_core_boundary.py tests/test_scheduling*.py -q
- ruff==0.12.8 check on scripts/scheduling_sim/utility.py and tests/test_scheduling_utility.py
- Standalone TLA+ model checks (all 10 TLC configs) and Rust trace conformance against all 8 modeled protocols
- Dual-hardware live flare run A/B benchmarks above on 4x RTX PRO 6000 (SM120) and 4x DGX Spark GB10 (SM121) on the equivalent scheduler logic atop 571a447

Material limitations:
- Live GPU serving benchmarks ran on the equivalent scheduler logic atop 571a447 prior to the rebase onto 5d53040 (NVIDIA#656, NVIDIA#628).
- The 62-scenario x 64-seed scripts/scheduling_sim/learning.py --preset validate sweep and cargo-kani were not run (timing estimation, funded refresh, completion-vector validation, and StateView extent arithmetic are unchanged).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
Nepherpitou added a commit to Nepherpitou/hyperflare-inference that referenced this pull request Dec 1, 2026
Upstream NVIDIA#628 records whether a graph moves data through peer memory so
offload Copy Engine batches can be gated around it. That flag was declared
inside the single build loop upstream; our capture split keeps every graph
alive for hooks, so the flag now travels in Captured.

Also passes the empty hooks set in the metadata-only load test, which
predates the hooks argument.
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. priority:P1 High attention: unresolved correctness, serving failure, or model-data deletion risk. 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.

helios: TP2 prefill CUDA graphs using in-graph peer Copy Engine nodes deadlock under concurrent prefix-cache offload on SM120

2 participants