Skip to content

fix(helios): zero reclaimed VMM-aliased snapshot KV pages before reuse to prevent SM103 FP8 V-cache tail NaNs - #736

Open
ebfio wants to merge 8 commits into
NVIDIA:mainfrom
ebfio:fix/zero-reclaimed-snapshot-kv-pages
Open

ebfio wants to merge 8 commits into
NVIDIA:mainfrom
ebfio:fix/zero-reclaimed-snapshot-kv-pages

Conversation

@ebfio

@ebfio ebfio commented Dec 5, 2026 •

Copy link
Copy Markdown

Summary

When continuation snapshot rows share physical GPU memory with KV cache pages via CUDA VMM aliasing (share_snapshot_pages), evicting a snapshot returns its backing pages to free_pages without clearing them. If those snapshots stored non-FP8 state (such as BF16 draft-model rings or recurrent state), raw bytes matching 0x7F or 0xFF remain in unwritten KV page tails and are interpreted as FP8 E4M3FN NaN by SM103 FP8 paged attention (0.0 * NaN = NaN in BMM2), poisoning attention outputs and failing sampling with INVALID_DISTRIBUTION (device error 1).

This PR tracks reclaimed snapshot-backing KV pages whenever page_snapshot_refs transitions 1 -> 0 and zeros them via coalesced cuMemsetD8Async on a dedicated CU_STREAM_NON_BLOCKING stream across all cache-owning ranks before any kernel submission or host-to-GPU prefix-cache DMA restore (store.fetch) touches them.

Root Cause (Blackwell SM103 FP8 V-Cache Tail NaN Isolation)

  1. Shared physical backing: allocate_shared_cache maps continuation snapshot virtual rows onto physical pages shared with KV cache pages, and RequestScheduler::share_snapshot_pages / release_snapshot refcount those pages in page_snapshot_refs.
  2. Stale non-FP8 payload bytes in unwritten page tails: A snapshot row holding BF16 (or other non-FP8) state routinely contains 0x7F and 0xFF bytes. When the snapshot is evicted (page_snapshot_refs drops 1 -> 0) and a new request allocates one of those pages, KV-write kernels only populate tokens 0..seq_len. Any unwritten tail slots in a partial page (seq_len % page_size != 0) retain stale snapshot bytes.
  3. Unmasked 0.0 * NaN = NaN in SM103 TRT-LLM FP8 FMHA BMM2: Under FP8 E4M3FN, both 0x7F and 0xFF encode NaN. On Blackwell SM103 (NVIDIA GB300, compute capability 10.3), FlashInfer's TRT-LLM FP8 FMHA kernels mask out-of-range K-cache scores to -inf before softmax (exp(-inf) = 0.0), so NaN bytes in unwritten k_cache tails do not propagate. In BMM2 (P @ V), however, 0.0 attention weights still multiply unwritten tail elements of v_cache across the tile, producing 0.0 * NaN = NaN and cascading into INVALID_DISTRIBUTION (device error 1) during sampling.

Standalone SM103 GPU Isolation Matrix

Device: NVIDIA GB300 (CC 10.3), batch=1, Hq=64, Hkv=8, D=128, page_size=128, NHD, FP8 E4M3FN KV, swept across window_left ∈ {-1, 511}, seq_len ∈ {17, 64, 127, 129, 202, 536}, packed ∈ {1, 4, 9}, eager and CUDA graph:

  • A_zero (virgin zeroed tail): 0 NaN, 0 Inf across all combinations.
  • B_k_nan (k_cache tail = 0x7F only): 0 NaN, 0 Inf across all combinations (softmax masks out-of-range K scores to -inf → 0.0).
  • B_v_nan (v_cache tail = 0x7F only): 100% NaN across every backend, mode, window, and seq_len (0 Inf).
  • B_kv_nan (k_cache=0x7F, v_cache=0xFF): 100% NaN across every backend, mode, window, and seq_len (0 Inf).
  • C_bf16_bytes (evicted BF16 randn * 10.0 raw bytes in K+V tail): NaN > 0 on every combination (8,215,432 total poison NaNs vs 0 total control NaNs; 0 Inf).

Representative rows (all inf_count = 0):

Case window_left packed seq_len Backend Mode nan_count
A_zero -1 1 17 trtllm_decode_rag eager 0
A_zero -1 9 129 trtllm_decode_rag eager 0
A_zero 511 9 536 trtllm_context eager 0
B_k_nan -1 9 129 trtllm_decode_rag eager 0
B_k_nan 511 9 536 trtllm_context eager 0
B_v_nan -1 1 17 trtllm_decode_rag eager / graph 8,192 / 8,192
B_v_nan -1 9 17 trtllm_decode_rag eager / graph 73,728 / 73,728
B_v_nan -1 1 129 trtllm_decode_uni eager / graph 8,192 / 8,192
B_v_nan -1 9 536 trtllm_context eager / graph 73,728 / 73,728
B_v_nan 511 9 536 trtllm_decode_rag eager / graph 73,728 / 73,728
C_bf16_bytes -1 1 17 trtllm_decode_rag eager / graph 2,312 / 2,312
C_bf16_bytes -1 9 17 trtllm_decode_rag eager / graph 20,808 / 20,808
C_bf16_bytes -1 1 127 trtllm_decode_uni eager 24
C_bf16_bytes -1 9 536 trtllm_context eager / graph 19,584 / 19,584
C_bf16_bytes 511 9 536 trtllm_decode_rag eager / graph 19,008 / 19,008

Fix Design & Race-Free Selene DMA Ordering

  • Scheduler reclaimed-page queue (helios/src/scheduler.rs, helios/src/scheduler/cache_memory.rs):
    • Track reclaimed_snapshot_pages: Vec<u32> on RequestScheduler.
    • Push page in release_snapshot strictly when page_snapshot_refs[page] drops 1 -> 0 (shared pages with refcount >= 1 are not queued until their last snapshot reference releases them).
    • Expose RequestScheduler::take_reclaimed_snapshot_pages(&mut self) -> Vec<u32>.
  • Dedicated non-blocking zeroing across all executor topologies (helios/src/cuda.rs, helios/src/execution/{transport,threaded,parallel,parallel/wire,ranks}.rs):
    • Add Stream::with_context wrapping Driver::with_context (fast-path no-op when the context is already current; save/restore otherwise).
    • Open a dedicated CU_STREAM_NON_BLOCKING zero: Stream per GraphExecutor (drained in close()) and per cache-owning peer rank in ThreadedExecutor (guarded by WatchdogCallGuard, drained on clean close(), and forgotten on poisoned teardown so cuStreamDestroy_v2 is never called on a wedged context).
    • Coalesce sorted, deduplicated, bounds-checked reclaimed page IDs into contiguous (start, count) runs (coalesce_page_runs), issue cuMemsetD8Async(dst, 0, nbytes) across all cache planes (overlapped across local and peer GPUs in ThreadedExecutor), and synchronize each enqueued zero stream before returning.
    • Wire ZERO_KV_PAGES / ZEROED_KV_PAGES control packets in TensorParallelExecutor (parallel.rs / parallel/wire.rs / serve_rank) so multi-process / multi-node TP peers also zero reclaimed KV pages concurrently with rank zero while preserving in-flight READY/COMPLETE peer message ordering.
  • Race-free flush points in Worker (helios/src/server/runtime.rs):
    • Add Worker::zero_reclaimed_kv_pages and flush after active cancels, at the end of admit_with_executor, after complete, publish, service_store, and plan, and in submit immediately after reserve_and_pack before executor.submit.
    • Race-free host-cache DMA ordering: inside admit_with_host_store, drain scheduler.take_reclaimed_snapshot_pages() and execute zero_kv_pages(&reclaimed) strictly before store.fetch(hit, ticket). This guarantees reclaimed pages are zeroed and synchronized before Selene initiates any asynchronous host-to-GPU DMA restore into those pages. Any executor failure from zero_kv_pages propagates out of admit_with_executor as a fatal worker error rather than being swallowed as a per-request admission rejection.

Overhead

  • Zeroing runs only when a VMM-aliased continuation snapshot is evicted and its last page reference drops 1 -> 0 — never during steady-state KV page allocation or reuse between requests.
  • Coalescing contiguous backing page ranges reduces an evicted snapshot's KV backing (e.g., ~212 MiB of KV planes) to a handful of cuMemsetD8Async calls executing on a dedicated non-blocking stream at HBM3e bandwidth (~8 TB/s on GB300), completing in ~27 µs.

Verification

  • Clean upstream apply & feature-matrix compile (be4092d7e1f0efe8a16049568c12ec7b841a2e8e):
    • git diff --check and clean-checkout git apply --check + git apply: passed with zero warnings.
    • cargo check --locked --manifest-path helios/Cargo.toml (default features), --features runtime-core, and --features server,runtime-core: 0 new warnings, 0 errors.
  • Unit & regression tests (CUDA_VISIBLE_DEVICES=""):
    • 4 new CPU unit tests (4 passed, 0 failed):
      • scheduler::cache_memory::tests::release_snapshot_records_only_reclaimed_pages_and_drains
      • execution::transport::confidence_tests::coalesce_page_runs_sorts_dedups_merges_and_bounds_checks
      • execution::parallel::tests::zero_kv_pages_wire_roundtrip_and_truncation
      • server::runtime::phase_tests::admit_with_host_store_zeros_reclaimed_snapshot_pages_before_fetch (proves zero_kv_pages runs strictly before store.fetch on evicted aliased snapshot pages and suppresses store.fetch on error)
    • Full affected-subsystem suite (cargo test --locked --manifest-path helios/Cargo.toml --features server,runtime-core --lib -- cuda:: scheduler:: execution:: server::runtime::): 802 passed, 0 failed, 10 ignored (CUDA-device-gated).
  • End-to-end SM103 GPU stress & soak verification (NVIDIA GB300, FP8 E4M3FN KV + VMM-aliased continuation snapshots + speculative decoding with adaptive verification + Selene host prefix cache):
    • Saturation stress suite: 75/75 HTTP 200 requests (0 failed, 0 device errors), driving 98 snapshot evictions (154 snapshot publications), peak 3,008 / 3,184 snapshot-backing pages, minimum 10 free KV pages, and 4,579 speculative graph launches across batch sizes 1..16 and widths {1, 9} (5,493 verification request rounds, 30,157 offered / 10,976 accepted drafts).
    • Extended mixed-workload soak & host-cache verification: 152/152 completed requests (0 failed, 0 cancelled, 0 runtime errors), 280 snapshot evictions, 100,108 generated tokens, 402,718 prefill tokens, 258 host-cache stores (0 store failures), and 4 DRAM host-cache restores (0 fetch failures, 4,805 reused tokens).
  • Submitting agent verification commands:
    git clone -4 --branch main https://github.com/NVIDIA/hyperflare-inference.git
    cd hyperflare-inference
    git checkout -b fix/zero-reclaimed-snapshot-kv-pages origin/main
    git apply --check <pack-dir>/01-hyperflare-inference-zero-reclaimed-snapshot-kv-pages/01-hyperflare-inference-zero-reclaimed-snapshot-kv-pages.patch
    git apply <pack-dir>/01-hyperflare-inference-zero-reclaimed-snapshot-kv-pages/01-hyperflare-inference-zero-reclaimed-snapshot-kv-pages.patch
    
    CUDA_VISIBLE_DEVICES="" cargo check --locked --manifest-path helios/Cargo.toml
    CUDA_VISIBLE_DEVICES="" cargo check --locked --manifest-path helios/Cargo.toml --features runtime-core
    CUDA_VISIBLE_DEVICES="" cargo test --locked --manifest-path helios/Cargo.toml --features server,runtime-core --lib -- cuda:: scheduler:: execution:: server::runtime::

Validation limits

The targeted lib suite is green (802 passed; 0 failed; 10 ignored), but the full
cargo test --lib run is not: 6 tests fail both before and after this patch, all
from a missing fixture that is generated separately (FLARE_TEST_TEMPLATE_DIR,
via python tests/frontend/prepare_templates.py), none in files this patch
touches. Feature-matrix cargo check warning counts are identical to clean
main (5 / 7 / 2). The SM103 isolation and soak numbers above come from one
GB300 and were not re-run for this submission.

Discord: ebfio

Review follow-up (2026-12-05)

The automated review requested changes; all four code items are addressed and the
mandated gate now runs and passes.

  1. Rank-control protocol version bumped 6 to 7. ZERO_KV_PAGES (14) and
    ZEROED_KV_PAGES (15) were added without changing wire::layout(), so a patched
    rank and an unpatched peer passed HELLO and then failed mid-serving with
    "unexpected rank command" on the first snapshot eviction.
  2. GraphExecutor is poisoned when zeroing fails. enqueue_zero_kv_pages and
    zero_kv_pages checked self.poison on entry but never set it, unlike submit
    and poll; on the local rank a failed memset left the executor usable and
    dropped the cause from Shutdown.error.
  3. A CPU test for the reply/control interleaving: the ZEROED_KV_PAGES wait now
    provably consumes interleaved READY/COMPLETE frames into the pending queue.
  4. An ignored CUDA test for the memset path: fills two planes with 0x7F,
    zeroes one page through enqueue_zero_cache_pages, asserts the reclaimed page is
    zero and the live page byte-identical. Gated on runtime-core, because Driver
    does not exist under server alone.

Verification (Linux, py check.py --mutations, exit 0):

  • TLA+ lifecycle models: 11/11 Model checking completed. No error has been found.
  • Observed-edge conformance: 9/9, run before and after the mutation pass with
    identical transition counts.
  • Auxiliary conformance tests: 12/12.
  • Fault injection: 60/60 injected mutations detected (41 Rust, 19 TLA+), 0 survivors.

A defect found while running the gate, worth flagging for anyone rebasing this
branch: cargo check does not compile #[cfg(test)] code, so a test target can be
broken while check is green. Two such errors were present after rebasing onto
cfb72093 (a call to RequestSpec::spec written against its pre-#729 signature,
and a KvCompression path) and only surfaced when the test target was built.

Why. Continuation snapshot rows share physical pages with KV cache rows through
CUDA VMM aliasing (share_snapshot_pages). Before this change, evicting a snapshot
returned those pages to free_pages without clearing them, so a request that later
allocated one inherited the evicted snapshot's bytes wherever the KV write kernels
did not reach, meaning any tail beyond seq_len % page_size. On SM103 those bytes
are read as FP8 E4M3FN, where 0x7F and 0xFF both decode as NaN, and TRT-LLM FP8
FMHA BMM2 multiplies zero attention weights by them (0.0 * NaN), so one stale
tail poisons the attention output and sampling fails with INVALID_DISTRIBUTION
(device error 1). Zeroing at reclaim was chosen over zeroing at allocation
because reclaim is the one point every cache scheme passes through and it keeps
the cost off the allocation fast path.

What changed. RequestScheduler now records pages whose page_snapshot_refs falls
1 -> 0 and zeroes them with coalesced cuMemsetD8Async on a dedicated
CU_STREAM_NON_BLOCKING stream, strictly before any kernel submission or
host-to-GPU prefix-cache DMA restore (store.fetch) can observe them. The same
reclaim path is wired through the local, threaded-TP and multi-process TP
executors, plus the page-id wire encoding exchanged between ranks. Eleven files:
cuda.rs, execution/{parallel,parallel/tests,parallel/wire,ranks,threaded,
transport}.rs, scheduler.rs, scheduler/cache_memory.rs, server/runtime.rs and
server/runtime/phase_tests.rs.

Benefit. Expected: removes a class of nondeterministic sampling failure on SM103
long-context continuation snapshots, at the cost of one asynchronous memset per
reclaimed page. Measured: the four new regression tests pass and the targeted
suite moves from 798 to 802 passing tests with zero failures.

Evidence. cargo check exits 0 for the default, runtime-core and
server,runtime-core feature sets with warning counts identical to clean HEAD
(5 / 7 / 2), so the change adds no warnings. The targeted lib suite reports
"802 passed; 0 failed; 10 ignored". The PR carries the GPU isolation evidence
from a GB300: a poisoned v_cache tail yields 100% NaN while a poisoned k_cache
tail yields none, and evicted BF16 bytes produced 8.2M NaN against 0 in the
control.

Limitations. The full lib suite is not green on the authoring host: 6 failures
both before and after the patch, all from a missing fixture
(FLARE_TEST_TEMPLATE_DIR), none in touched files. The GPU measurements come from
one GB300 and were not re-run for this submission.

Signed-off-by: ebfio <ebfio@users.noreply.github.com>
Design-Signed-Off-By: Iris (deepseek-v4.1-unlimited via litellm); design-review=2e5b
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 736.
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 area:caching Prefix/KV reuse, cache retention, and model or payload cache behavior. area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. 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. labels Dec 5, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The core mechanism—recording VMM-aliased KV pages on the 1 -> 0 page_snapshot_refs transition and zeroing coalesced runs via cuMemsetD8Async across all KV planes before kernel submission or store.fetch—is technically sound and correctly fence-ordered across all release_snapshot call sites. However, the PR omits mandatory verification gates (verification/helios-lifecycle/check.py, a GPU test for enqueue_zero_cache_pages, --release tests, multi-GPU TP verification), extends the rank-control wire protocol without bumping its handshake version, and omits poisoning GraphExecutor on zeroing failures.

  • Blockers: 2 · Should fix: 2 · Subtract/Simplify: 3 · Nits: 4
Walkthrough
  • Scheduler reclaimed-page tracking (helios/src/scheduler.rs:669,772, helios/src/scheduler/cache_memory.rs:822-846): Adds reclaimed_snapshot_pages: Vec<u32> populated inside release_snapshot strictly when page_snapshot_refs[page] drops 1 -> 0 (leaving shared pages with refcount >= 1 untouched), plus take_reclaimed_snapshot_pages() drain accessor and a CPU unit test (cache_memory.rs:2856-2883).
  • CUDA context helper & coalesced memset (helios/src/cuda.rs:1128-1131, helios/src/execution/transport.rs:573,626,1357-1433,1442-1508): Adds Stream::with_context, a dedicated CU_STREAM_NON_BLOCKING zero: Stream on GraphExecutor::Resources (synchronized in close()), coalesce_page_runs (sort/dedup/merge/bounds-check), and enqueue_zero_cache_pages issuing cuMemsetD8Async across CacheGeometry::planes, with a CPU unit test for coalesce_page_runs (transport.rs:2163-2180).
  • Multi-rank executors (helios/src/execution/ranks.rs:90-97,200-203, helios/src/execution/threaded.rs:833,873-885,1217-1258,1273-1308, helios/src/execution/parallel.rs:99-147,288-328,418-429,747-751, helios/src/execution/parallel/wire.rs:27-28,501-524): Dispatches zero_kv_pages across Local, Threaded (overlapping local and per-peer zero streams under WatchdogCallGuard, draining on clean close and mem::forgeting on poisoned teardown), and Parallel (sending ZERO_KV_PAGES = 14, awaiting ZEROED_KV_PAGES = 15 while processing in-flight READY/COMPLETE via extracted apply_peer_message, and handling ZERO_KV_PAGES in serve_rank), plus a wire round-trip/truncation test (parallel/tests.rs:837-854).
  • Worker flush barriers & admission ordering (helios/src/server/runtime.rs:1610-1627,1788-1804,1857-1859,1939-1987,2164-2166,3220,3859,3998-4001, helios/src/server/runtime/phase_tests.rs:12250-12396): Adds Worker::zero_reclaimed_kv_pages, flushes reclaimed pages across the worker loop and immediately before executor.submit (:3220) and store.fetch (:3998-4001), propagates zeroing failures out of admit_with_executor as fatal worker errors, and adds a CPU ordering test asserting ["zero", "fetch"] and fetch suppression on error.
Merge Risk: Medium · up to 500b774
  • Adds synchronous cross-rank ZERO_KV_PAGES / ZEROED_KV_PAGES RPCs (parallel.rs) and cross-context peer zero streams with new teardown/drain logic (threaded.rs) that have zero automated test or multi-GPU execution coverage.
  • Extends the multi-host rank-control wire tag set without bumping wire::layout()'s version (6), allowing mismatched serving builds to pass HELLO handshake and fail mid-serving on the first snapshot eviction.
  • Touches helios/src/server/runtime.rs's main worker loop with six extra flush calls in a heavily contended area (e.g. open PR fix(selene,helios): stop service_store and CompositeStore Retry(Slabs) CPU storm #705), though no core format, API, or dependency boundaries are altered.
Pre-merge checks: ✅ 1 passed · ⚠️ 3 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.

ebfio added 7 commits December 4, 2026 22:10
…lure

Bumps the rank-control layout version 6 -> 7 so a patched rank cannot pass HELLO
against an unpatched peer and then fail mid-serving with an unexpected rank
command on the first snapshot eviction, and records poison on coalesce, memset
and sync failures in enqueue_zero_kv_pages/zero_kv_pages so close() reports the
cause instead of a clean shutdown.
Adds the two tests the review asked for: a CPU test that drives the ZEROED_KV_PAGES wait with interleaved READY/COMPLETE control frames and asserts they survive into the pending queue, and an ignored CUDA test that fills two planes with 0x7F, zeroes one page through enqueue_zero_cache_pages, and asserts the reclaimed page is zero while the live page stays byte-identical.
…mission test

The rebase onto main carried a call written against the pre-NVIDIA#729 signature. Host admission is a non-speculative path, matching runtime.rs:3758, so the test passes false. cargo check never caught this because #[cfg(test)] code is only built by cargo test.
flare_selene re-exports CacheGeometry and Plane at the crate root but not KvCompression, so the new CUDA test must name flare_selene::offload::KvCompression. Found by building the test target, which cargo check does not cover.
… the CUDA test under server tests

The interleaving test fed a READY for a fence rank 0 had never submitted, so record_ready rejected it with 'unexpected rank readiness fence'; it now seeds the pending queue with the draining frame and a committed frame that the COMPLETE belongs to. The CUDA zero-page test lived in the runtime-core-gated confidence_tests module, which the gate's --features server build never compiles; it now sits in its own #[cfg(test)] module so it is compiled and listed as ignored.
The test drives Driver::load and Stream directly, and Driver lives in runtime_core, which the server feature does not enable. check.py builds --features server, so an ungated module broke that build; the lifecycle workflow builds runtime-core,server, where the test is now compiled and listed as ignored.
record_peer_completion selects the first frame with a free completion slot for that rank and only then validates committed/fence/graph, so a COMPLETE for the committed frame is rejected when an uncommitted frame sits ahead of it in the queue. The fixture now orders the committed frame first; READY stays fence-addressed and lands on the draining frame.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:caching Prefix/KV reuse, cache retention, and model or payload cache behavior. area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. 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.

2 participants