Skip to content

perf(helios): alias null continuation row zero onto a single zeroed VMM granule - #659

Merged
lukealonso merged 1 commit into
mainfrom
perf/sentinel-row-aliasing
Dec 3, 2026
Merged

lukealonso merged 1 commit into
mainfrom
perf/sentinel-row-aliasing

Conversation

@lukealonso

@lukealonso lukealonso commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Models with continuation-state storage (sizing.capacity == 0, state_pool) reserve row zero as a permanent null row that is never assigned to any live request or snapshot (StateSlotId allocations start at 1, offload transfers reject slot 0, and inactive lanes must perform no state mutation). Previously, NativeResources::allocate_shared_cache (helios/src/runtime_core/cache_memory.rs) and cache-capacity planning (helios/src/runtime_core/memory.rs) backed row zero with dedicated physical GPU memory across its full row stride. On models whose continuation row spans multiple 2 MiB CUDA VMM granules (for example 35 MiB on DCP16 layouts, 82 MiB on hybrid Mamba models, or 184.88 MiB on Qwen3.8-27B), that consumed tens to hundreds of MiB of physical VRAM per rank solely to hold zeros.

Because CUDA VMM cuMemMap maps one physical allocation handle at multiple aligned virtual offsets—the same mechanism allocate_shared_cache uses for snapshot-to-KV aliasing—aliasing row zero's floor(row_bytes / alignment) full leading granules onto one shared zeroed physical granule reclaims (floor(row_bytes / alignment) - 1) * alignment bytes per rank while preserving row zero's full virtual span, its uniquely backed partial tail (which shares a boundary granule with row one), and distinct backing for every live and snapshot row.

What changed

  • helios/src/runtime_core/cache_memory.rs:
    • Before: Layout tracked only fixed_bytes, handle_charge charged 1 + row_readers for the fixed continuation chunk, and allocate_shared_cache allocated and zeroed one physical chunk of fixed_bytes.
    • After: added sentinel_saved_bytes(row_bytes, alignment), Layout::sentinel_granules (row_bytes / row_alignment when execution > 0 && row_bytes / row_alignment > 1, else 0), and Layout::fixed_segments() describing (mapping_count, chunk_bytes, tail_bytes) once across handle_charge, allocate_shared_cache mapping and zeroing, and verify_physical_invariants. When sentinel_granules > 1, allocate_shared_cache maps one alignment-sized physical handle across sentinel_granules aligned offsets of row zero, maps any remaining tail separately when tail > 0, and zeroes each physical chunk once before replay.
    • RM-handle trade-off: Aliasing row zero's leading granules adds (sentinel_granules - 1) * row_readers per-device mappings plus 1 + row_readers handles when a non-empty tail chunk exists. On the 16-rank DCP16 fixture (35 MiB rows, row_readers == 1), handle usage rises by +17 per rank (518,232 -> 518,504 total handles, shrinking RS_UNIQUE_HANDLE_RANGE headroom from 1.2% to 1.1%), scaling with row_readers if state_pool has peer readers.
    • Added CPU coverage in sentinel_row_aliases_full_granules_onto_one_page (standard partial-tail, tail == 0, and execution == 0 geometries), updated cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten (rows = 8, keeping row zero zeroed and probing hardware aliasing across granules 0..3 plus isolation of row zero's partial tail from granule zero and row one), and added cuda_sentinel_row_with_exact_granule_stride_maps_without_tail for the tail == 0 GPU path.
  • helios/src/runtime_core/memory.rs:
    • Before: capacities, minimum-footprint validation, and gpu_bytes accounting priced continuation rows with bytes(core, 0, units).
    • After: added row_backing_bytes(core, units) delegating validation and aligned span calculation to bytes(core, 0, units) and subtracting sentinel_saved_bytes when units > 0 for physical-backing checks and gpu_bytes reporting, while keeping virtual-span calculations (mapped = bytes(core, 0, execution) + borrowed) on full virtual sizes. Added sentinel_row_savings_increase_kv_page_capacity.
  • helios/src/offload/transfer.rs, helios/src/offload/transfer/codec.rs, helios/src/offload/gpu_tests.rs:
    • Before: offload transfer expansion (transfer::expand) and codec span resolution (codec::device_spans) accepted StateSlotId(0), and staged_store_round_trips_records_through_files_and_a_restart plus two synthetic codec GPU tests read or wrote through StateSlotId(0).
    • After: transfer::expand and codec::device_spans reject StateSlotId(0) for both inbound and outbound transfers, CPU tests verify slot-zero rejection, staged_store_round_trips_records_through_files_and_a_restart uses StateSlotId(4) (row_capacity >= 5), and the two codec GPU tests use a 3-row geometry with StateSlotId(1) and StateSlotId(2).
  • docs/runtime-core-design.md:
    • Documented null-row sentinel granule aliasing in cache sizing and updated the DCP16 RM-handle headroom example (518,504 handles, leaving 5,784 / 1.1% headroom).
  • Compatibility: No core wire format, Protobuf, CLI, or Prometheus metric schema changes; existing prepared cores load and serve without re-export. Pure KV models and models with row_bytes < 2 * alignment are unaffected (sentinel_granules = 0).

Claimed benefit and result

  • Reclaims (floor(row_bytes / alignment) - 1) * alignment bytes of physical VRAM per rank for KV pages, shared snapshots, or reduced footprint across every continuation-state model whose row spans at least two VMM granules (for example 32 MiB/rank on a 35 MiB row, 76 MiB/rank on an 82 MiB row, and 182 MiB/rank on a 184.88 MiB row).
  • Measured on an RTX PRO 6000 Blackwell (SM120) GPU loading an existing Qwen3.8-27B-NVIDIA-NVFP4-QAD-MXFP8 TP1 core (row_bytes = 193,865,984, alignment = 2 MiB, sentinel_granules = 92) with --gpus 0 --max-concurrency 2, compared directly against origin/main (cb191a93):
    • Cap-limited (--kv-cache-limit context): nvidia-smi GPU 0 VRAM used dropped from 39,709 MiB (57,604 MiB free) to 39,527 MiB (57,786 MiB free) — -182 MiB exact, matching (92 - 1) * 2 MiB; Allocate cache dropped 8.5 GiB -> 8.4 GiB with identical 2,048 KV pages (262,144 tokens) and 44 shared snapshot slots.
    • Memory-limited (--memory-limit 40G, 30.23 GiB loaded, 9.77 GiB cache budget): KV capacity increased from 2,352 to 2,400 KV pages (+48 pages / +6,144 KV tokens, 301,056 -> 307,200) and shared snapshot slots increased from 50 to 51.

Supporting evidence and limitations

  • Rust crate release suites on c9bb4333 (--locked --release --target-dir flare-cli/target):
    • eos: 12 passed, 0 failed
    • selene (--features test-support): 585 lib + 1 integration passed, 0 failed
    • selene-manager (--features test-support): 205 lib + 243 integration passed, 0 failed, 1 ignored
    • helios (--features runtime-core,server, with prepared public templates from tests/frontend/prepare_templates.py excluding gated muse_spark): 1,881 lib + 62 integration passed, 0 failed (49 lib / 36 integration ignored)
    • flare: 247 lib + 8 integration passed, 0 failed, 4 ignored
    • flare-cli: 220 bin + 26 integration passed, 0 failed, 3 ignored
  • SM120 GPU execution on RTX PRO 6000 Blackwell:
    • CUDA_VISIBLE_DEVICES=0 cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib runtime_core::cache_memory::tests::cuda_ -- --ignored --test-threads=1: 2 passed, 0 failed (cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten and cuda_sentinel_row_with_exact_granule_stride_maps_without_tail), verifying multi-offset cuMemMap aliasing across granules, split cuMemsetD8_v2 zeroing, partial-tail isolation from granule zero and row one, and the tail == 0 path.
    • CUDA_VISIBLE_DEVICES=1 FLARE_TEST_KV_CODEC_CUBIN=... cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib offload::transfer::codec::tests:: -- --ignored --test-threads=1: 4 passed, 0 failed.
    • CUDA_VISIBLE_DEVICES=0,1 cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib offload::transfer::tests::split_pools_cost_each_device_its_part_and_round_trip_units -- --ignored --exact: 1 passed, 0 failed.
    • Live flare run serving and NVMe disk offload + restart restore on Qwen3.8-27B-NVIDIA-NVFP4-QAD-MXFP8 (--memory-limit 40G --prefix-cache-memory 0 --prefix-cache-disk): cold 4,228-token prompt stored 312.89 MiB (328,093,696 bytes) to NVMe and returned 42; fresh restarted process restored 312.89 MiB (328,085,504 bytes, 4,221 reused tokens) from NVMe and returned 42.
  • Formal verification:
    • python3 verification/helios-lifecycle/check.py (TLC 1.7.4 / Java 21): all 8 TLA+ models and all observed Rust transition checks passed (Lifecycle 1,710, RankProtocol 1,291, DispatchRing 7,940, OffloadTransfer 8,490, CacheOwnership 222,817, Speculation 13,566, ResponseLifecycle 365,508, CheckpointReservation 68).
    • cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib (Kani 0.68.0 / CBMC 6.11.0): 13 verified harnesses, 0 failures.
  • Limitations / unrun checks:
    • offload::gpu_tests::disk_store::staged_store_round_trips_records_through_files_and_a_restart and sibling FLARE_OFFLOAD_TEST_CORE Rust unit tests require a core signed with the synthetic flare-tests fixture key (seed = [42; 32]) and were not run directly against production-signed local cores (live disk offload and restart restore were verified through flare run instead).
    • prepare_templates.py returned 403 Forbidden for the gated meta-models/Muse-Spark-Open-816B-A42B-NVFP4 template; all 9 public template recipes were prepared and all 1,881 helios lib tests passed.
    • Aliasing row zero onto one writable granule relies on the model contract that inactive lanes perform no state mutation.

Discord: lukealonso

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 659.
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:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:validation Proposed implementation needs acceptance evidence; no claim that a reported defect is fixed. labels Dec 1, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The core design and arithmetic are sound, model-agnostic, and well-scoped to shared cache-planning and VMM-allocation code (helios/src/runtime_core/cache_memory.rs, memory.rs). Two issues block merge: the new CUDA VMM multi-aliasing/split-zeroing path has zero executed coverage on a GPU, and an existing GPU offload test writes through StateSlotId(0) and will fail on affected cores — plus two clean subtractive refactors worth ~70 lines.

  • Blockers: 2 · Should fix: 2 · Subtract/Simplify: 2 · Nits: 1
Walkthrough
  • helios/src/runtime_core/cache_memory.rs: Adds sentinel_saved_bytes(row_bytes, alignment) (:69-71) and Layout::sentinel_granules (:63, :259-262, propagated through pack_prefixes at :487). Updates Layout::handle_charge (:81-102) to charge 1 + sentinel_granules * row_readers plus an optional tail chunk (1 + row_readers). Updates NativeResources::allocate_shared_cache (:1416-1488) to map sentinel_granules offsets onto one alignment-sized physical handle, map the remaining fixed_bytes - sentinel_bytes tail separately, and zero each physical chunk once. Re-baselines DCP16 handle-count assertions (:818-834), excludes row 0 from the pattern upload in the ignored GPU test (:1210-1226), and adds CPU unit test sentinel_row_aliases_full_granules_onto_one_page (:1367-1385).
  • helios/src/runtime_core/memory.rs: Adds row_backing_bytes(core, units) (:385-414) subtracting sentinel_saved_bytes when units > 0 for physical-backing checks, capacities (:486, 510, 523), pool minimum footprint (:1003), and gpu_bytes reporting (:1249), while preserving virtual-span calculations (bytes(core, 0, ...), :576-579). Adds CPU unit test sentinel_row_savings_increase_kv_page_capacity (:2031-2050).
  • docs/runtime-core-design.md: Documents null-row sentinel granule aliasing (:773-778) and updates the DCP16 RM-handle headroom example (518,504 handles, 5,784 / 1.1% headroom, :832-833).
Merge Risk: Medium · up to 16e2247
  • CUDA VMM driver path is unexecuted: allocate_shared_cache (helios/src/runtime_core/cache_memory.rs:1416-1488) introduces multi-offset cuMemMap aliasing of a single physical handle across up to 39 adjacent virtual slots inside one reservation, plus split cuMemsetD8_v2 zeroing. This runs once at startup (no serving hot-path, lock, or concurrency impact), but NVIDIA Blackwell drivers have previously shown non-obvious cuMemMap aliasing rejections (documented at cache_memory.rs:218-220), so running this path on real hardware before merge is essential.
  • Silent-corruption blast radius if row zero is written: Aliasing row 0's leading granules onto one writable physical page turns any stray write to StateSlotId(0) into multi-granule corruption across [0, sentinel_bytes). Production scheduling starts live/snapshot slots at 1 (helios/src/scheduler.rs:946-948, 1753), but helios/src/offload/transfer.rs:156-163 does not reject slot 0, and helios/src/offload/gpu_tests.rs:1476-1525 actively writes to it.
  • RM handle budget impact is small on current layouts: On the 16-rank DCP16 layout (row_readers == 1), handle usage rises by +272 (518,232 -> 518,504, shrinking RM_HANDLE_RANGE headroom from 1.2% to 1.1%), already reflected in handle_charge, tests, and docs.
Pre-merge checks: ✅ 3 passed · ⚠️ 1 warnings
  • ✅ Security / malicious screen: No suspicious code, external exfiltration, or prompt-injection content; standard runtime memory optimization.
  • ✅ Charter & value fit: Model-agnostic runtime-only optimization keyed off sizing.capacity == 0 and VMM alignment; no wire/Protobuf/CLI/metric changes, no per-model branches, existing exported cores remain compatible.
  • ✅ Related / duplicate / conflict check: Builds cleanly on Fix native peer-access OOM without reducing cache capacity #286 (multi-address cuMemMap), Fit native KV backing to the Linux GPU mapping handle range #391 (handle_charge / RM_HANDLE_RANGE), and Fix KV plane granule padding conflicts and optimize two-row snapshot selection #473 (granule conflict ranges); no competing or conflicting PRs.
  • ⚠️ Tests & verification evidence: CPU runtime_core:: tests pass and CI is green on 16e2247, and formal TLA+/Kani suites do not cover VMM granule layout; however, the new CUDA VMM allocation/zeroing code has never been executed on a GPU (docs/verification.md:14, docs/design-review.md:106-115), no live VRAM / Plan cache measurement is provided, and helios/src/offload/gpu_tests.rs:1478 breaks on affected cores. (Note: the commit's Design-Signed-Off-By trailer could not be inspected with available tools and should be verified before merge.)
Blockers (2)
  1. New CUDA VMM multi-aliasing and split-zeroing path is completely unexecuted on GPU (helios/src/runtime_core/cache_memory.rs:1106-1283, :1416-1488).
    • Verified behavior/impact: The only code that performs the multi-offset cuMemMap and split cuMemsetD8_v2 lives in NativeResources::allocate_shared_cache (:1416-1488). The new CPU unit tests only verify sentinel_saved_bytes, Layout::new, handle_charge, and capacities. The sole test covering allocate_shared_cache — cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten (:1106-1283, which exercises both sentinel_granules == 0 at 3 * alignment / 2 and sentinel_granules == 3 at 7 * alignment / 2) — was modified and skipped ("all local GPUs were occupied"). Both docs/verification.md:14 (CUDA ordering / inactive rows / allocation stability require real GPU execution) and docs/design-review.md:106-115 (principle 12: validate the real path and back performance/memory claims with actual Helios measurements) apply directly here, especially given prior Blackwell driver cuMemMap aliasing constraints (cache_memory.rs:218-220).
    • Fix: Run cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten on an assigned GPU against 16e2247 (and ideally verify in the equal_planes == true branch that row 0's leading granules stay zero while row 0's partial tail [sentinel_bytes, row_bytes) is independently backed from row 1), and report a before/after Plan cache / Allocate cache (or VRAM) reading from loading a real continuation-state core with row_bytes >= 2 * alignment.
  2. Existing GPU offload test writes and round-trips StateSlotId(0), breaking on affected cores (helios/src/offload/gpu_tests.rs:1476-1525, :1730-1804).
    • Verified behavior/impact: staged_store_round_trips_records_through_files_and_a_restart binds child_slot = StateSlotId(0) (:1478), uploads a distinct pseudo-random pattern across rank.row.unit_bytes into row 0 (:1519-1525), stores it to disk (:1730-1739), restores it into StateSlotId(2) (:1780-1790), and asserts byte-for-byte equality with the original pattern (:1798-1804). On any continuation-state core with row_bytes >= 2 * alignment, uploading to row 0 overwrites the single shared physical granule sentinel_granules times, so granules 0..sentinel_granules - 1 read back as copies of the last aliased granule and the test fails at :1800-1804.
    • Fix: Change child_slot at helios/src/offload/gpu_tests.rs:1478 to a nonzero slot (e.g. StateSlotId(4), adjusting the row_capacity assert at :1467 from >= 4 to >= 5).
Should Fix (2)
  1. Enforce the non-zero row invariant in Helios's offload transfer layer (helios/src/offload/transfer.rs:156-163).
    • Verified behavior/impact: helios/src/offload/transfer.rs:156-163 only checks index >= geometry.row_capacity and accepts StateSlotId(0) for both inbound and outbound transfers. Now that row 0 is aliased onto one shared physical granule, an inbound transfer targeting slot 0 silently corrupts all sentinel_granules offsets simultaneously rather than affecting a single region. Production scheduling never allocates slot 0 (helios/src/scheduler.rs:946-948, 1753).
    • Fix: Reject index == 0 alongside index >= geometry.row_capacity at helios/src/offload/transfer.rs:156-163 (and update the two synthetic unit tests in helios/src/offload/transfer/codec.rs:1098, 1344 that pass StateSlotId(0) over standalone mapped host buffers to use StateSlotId(1) / a 3-row geometry).
  2. Guard Layout::grouped against execution == 0 and note the handle-margin trade-off in the PR description (helios/src/runtime_core/cache_memory.rs:259-262).
    • Verified behavior/impact: In Layout::grouped (:157, 259-262), sentinel_granules is computed solely from row_bytes / row_alignment without checking execution > 0 (or fixed_bytes >= n * row_alignment). While production capacities() guarantees execution >= 2 (memory.rs:459), Layout::new is callable directly and execution == 0 would leave fixed_bytes = 0 < sentinel_bytes. Separately, while the PR description mentions the 518,232 -> 518,504 test update, it omits explaining the handle-headroom cost (+17 handles/rank on DCP16, shrinking RM_HANDLE_RANGE headroom from 1.2% to 1.1%, and scaling by row_readers if state_pool ever has peer readers).
    • Fix: Compute sentinel_granules as if execution > 0 && row_bytes / row_alignment > 1 { row_bytes / row_alignment } else { 0 } (ensuring sentinel_bytes <= fixed_bytes by construction), and add one sentence to the PR description noting the RM-handle trade-off.
Subtract / Simplify (2)
  1. Collapse row_backing_bytes onto bytes(core, 0, units) (helios/src/runtime_core/memory.rs:385-414 vs :357-381).
    • row_backing_bytes duplicates the exact capacity filter, units > s.maximum check, checked multiplication, alignment rounding, overflow errors, and try_fold from bytes. Calling let span = bytes(core, 0, units)?; first guarantees both validation and that sum(sentinel_saved_bytes) <= span (so neither summation overflow nor subtraction underflow is possible):
      fn row_backing_bytes(core: &Core, units: u64) -> Result<u64> {
          let span = bytes(core, 0, units)?;
          if units == 0 {
              return Ok(span);
          }
          let saved: u64 = core
              .allocations
              .iter()
              .filter_map(|a| a.sizing.as_ref().filter(|s| s.capacity == 0).map(|s| (a, s)))
              .map(|(a, s)| super::cache_memory::sentinel_saved_bytes(s.unit_bytes, a.alignment as u64))
              .sum();
          Ok(span - saved)
      }
    • Deletes ~20 lines of verbatim duplication and ensures virtual-span and physical-backing calculations share a single validation/rounding implementation.
  2. Describe the fixed-chunk split once on Layout (helios/src/runtime_core/cache_memory.rs:82-102, :1416-1447, :1468-1488).
    • handle_charge, allocate_shared_cache mapping, and allocate_shared_cache zeroing each repeat the same sentinel_granules > 1 / fixed_bytes > sentinel_bytes branching. A single helper on Layout:
      fn fixed_segments(&self) -> (u64, u64, u64) {
          let count = self.sentinel_granules.max(1);
          let granule = if count > 1 { self.alignment } else { self.fixed_bytes };
          (count, granule, self.fixed_bytes - granule * count)
      }
      eliminates both else branches in allocate_shared_cache (:1438-1447, :1483-1488) and collapses handle_charge (:82-102) into one checked expression (1u64.checked_add(count * row_readers) plus 1 + row_readers when tail > 0), removing ~50 lines of repeated branching and guaranteeing handle accounting, mapping, and zeroing cannot drift.
Nits (1)
  • helios/src/runtime_core/cache_memory.rs:1212-1225: Assigning expected[0] = vec![0u8; geometry.row.unit_bytes as usize]; after the existing pattern-generation closure keeps the test diff smaller and avoids nesting the pattern logic inside an if/else.
Dropped on verification
  • Claimed mock Driver available at cache_memory.rs:1120-1209 (Correctness lens Finding 6): False. cache_memory.rs:1113-1209 loads the real CUDA driver via Driver::load().unwrap() and invokes cuInit/cuDeviceGet; there is no mock Driver in cache_memory.rs. Dropped the mock-test recommendation in favor of running the real GPU test.
  • Proposed fallback clearing sentinel_granules inside plan_mapping_handles when over RM_HANDLE_RANGE (Correctness lens Finding 3b): Unsafe as proposed. capacities() (memory.rs:1068) runs before compact_cache_layouts() (memory.rs:1220) and spends sentinel_saved_bytes on extra KV pages; disabling sentinel aliasing afterward without replanning capacities would silently allocate sentinel_saved_bytes more physical VRAM than budgeted and risk OOM. Also verified that state_pool has row_readers == 1 on DCP16 (only KV planes have 16 peer readers), so the 39×16 peer-reader scenario does not occur on current DCP16 layouts.
  • Claimed undeclared capacity shift (Correctness lens Finding 4): Over-flagged. The PR description explicitly states "Reclaims ... bytes of physical VRAM per rank for KV pages or shared snapshots" and cites sentinel_row_savings_increase_kv_page_capacity verifying the KV page gain.
  • Claimed self-contradictory observability shift where "Allocate cache" GiB drops while pages rise (Correctness lens Finding 5): Mathematically false. gpu_bytes (memory.rs:1249) sums row_backing_bytes + bytes(core, 1, pages): when memory-limited, reclaimed bytes go into extra KV pages so gpu_bytes remains near budget; when cap-limited, pages stays constant while gpu_bytes drops.
  • Claimed duplicated alignment source between memory.rs:398 and cache_memory.rs:259 (Correctness lens minor): False. memory.rs:1201-1217 passes core.allocations[..].alignment as u64 straight into Layout::new, which is the exact same field read by row_backing_bytes at memory.rs:398.
  • Naming drift (sentinel_* vs null_row_*) and Layout::sentinel_granules derived-field note (Subtraction lens section 4): Low-signal; sentinel_granules is needed by handle_charge during compaction without CacheGeometry in scope, and renaming is cosmetic.

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.

…MM granule

Models with continuation-state storage (`sizing.capacity == 0`, `state_pool`)
reserve row zero as a permanent null row that is never assigned to any live
request or snapshot (`StateSlotId` allocations start at `1`, offload transfers
reject slot `0`, and inactive lanes must perform no state mutation). Previously,
`NativeResources::allocate_shared_cache` (`helios/src/runtime_core/cache_memory.rs`)
and cache-capacity planning (`helios/src/runtime_core/memory.rs`) backed row
zero with dedicated physical GPU memory across its full row stride. On models
whose continuation row spans multiple `2 MiB` CUDA VMM granules (for example
`35 MiB` on DCP16 layouts, `82 MiB` on hybrid Mamba models, or `184.88 MiB` on
Qwen3.8-27B), that consumed tens to hundreds of MiB of physical VRAM per rank
solely to store zeros.

Because CUDA VMM `cuMemMap` maps one physical allocation handle at multiple
aligned virtual offsets—the same mechanism `allocate_shared_cache` uses for
snapshot-to-KV aliasing—aliasing row zero's `floor(row_bytes / alignment)` full
leading granules onto one zeroed physical granule reclaims
`(floor(row_bytes / alignment) - 1) * alignment` bytes per rank while
preserving row zero's virtual span, its uniquely backed partial tail (which
shares a boundary granule with row one), and distinct backing for every live
and snapshot row.

What changed:

- `helios/src/runtime_core/cache_memory.rs`:
  - Before: `Layout` tracked only `fixed_bytes`, `handle_charge` charged
    `1 + row_readers` for the fixed continuation chunk, and
    `allocate_shared_cache` created and zeroed one physical chunk of
    `fixed_bytes`.
  - After: added `sentinel_saved_bytes(row_bytes, alignment)`,
    `Layout::sentinel_granules` (`row_bytes / row_alignment` when
    `execution > 0` and `row_bytes / row_alignment > 1`, else `0`), and
    `Layout::fixed_segments()` describing `(mapping_count, chunk_bytes,
    tail_bytes)` once for `handle_charge`, `allocate_shared_cache` mapping and
    zeroing, and `verify_physical_invariants`. When `sentinel_granules > 1`,
    `allocate_shared_cache` maps one `alignment`-sized physical chunk at
    `sentinel_granules` aligned offsets of row zero, maps the remaining tail
    separately when `tail > 0`, and zeroes each physical chunk once before
    replay. `handle_charge` accounts for the extra per-granule mappings
    (`+17` handles per rank on the 16-rank DCP16 layout, moving the 3,103-page
    fixture from `518,232` to `518,504` handles and RM-handle headroom from
    `1.2%` to `1.1%`, scaling by `row_readers` if `state_pool` has peer
    readers).
  - Added CPU coverage in `sentinel_row_aliases_full_granules_onto_one_page`
    (including `tail == 0` and `execution == 0` cases), updated
    `cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten` (`rows = 8`
    so chunk packing merges after midpoint-ordered grouping, keeping row zero
    zeroed and probing hardware aliasing across granules `0..3` plus isolation
    of row zero's partial tail from granule zero and row one), and added
    `cuda_sentinel_row_with_exact_granule_stride_maps_without_tail` covering
    the `tail == 0` GPU path.
- `helios/src/runtime_core/memory.rs`:
  - Before: `capacities`, minimum-footprint validation, and `gpu_bytes`
    accounting priced continuation rows with `bytes(core, 0, units)`.
  - After: added `row_backing_bytes(core, units)` wrapping `bytes(core, 0,
    units)` and subtracting `sentinel_saved_bytes` when `units > 0` for
    physical-backing checks and `gpu_bytes` reporting, while keeping virtual
    span calculations on `bytes(core, 0, ...)`. Added
    `sentinel_row_savings_increase_kv_page_capacity`.
- `helios/src/offload/transfer.rs`, `helios/src/offload/transfer/codec.rs`,
  `helios/src/offload/gpu_tests.rs`:
  - Before: offload transfer expansion (`transfer::expand`) and codec span
    resolution (`codec::device_spans`) accepted `StateSlotId(0)`, and
    `staged_store_round_trips_records_through_files_and_a_restart` plus two
    synthetic codec GPU tests wrote or read through `StateSlotId(0)`.
  - After: `transfer::expand` and `codec::device_spans` reject `StateSlotId(0)`
    for both inbound and outbound transfers, CPU tests verify rejection of slot
    zero, `staged_store_round_trips_records_through_files_and_a_restart` uses
    `StateSlotId(4)` with `row_capacity >= 5`, and the two codec GPU tests use
    a 3-row geometry with `StateSlotId(1)` and `StateSlotId(2)`.
- `docs/runtime-core-design.md`:
  - Documented null-row sentinel granule aliasing in cache sizing and updated
    the DCP16 RM-handle example (`518,504` handles, `5,784` / `1.1%` headroom).
- Compatibility: No core wire format, Protobuf, CLI, or metric schema changes;
  existing prepared cores load and serve without re-export. Pure KV models and
  models with `row_bytes < 2 * alignment` are unaffected (`sentinel_granules = 0`).

Claimed benefit and result:

- Reclaims `(floor(row_bytes / alignment) - 1) * alignment` bytes of physical
  VRAM per rank for KV pages, shared snapshots, or reduced footprint on every
  continuation-state model with `row_bytes >= 2 * alignment`.
- Measured on an RTX PRO 6000 Blackwell (SM120) GPU loading an existing
  `Qwen3.8-27B-NVIDIA-NVFP4-QAD-MXFP8` TP1 core (`row_bytes = 193,865,984`,
  `alignment = 2 MiB`, `sentinel_granules = 92`) compared against `origin/main`
  (`cb191a93`) with `--max-concurrency 2`:
  - Cap-limited (`--kv-cache-limit context`): `nvidia-smi` GPU 0 VRAM dropped
    from `39,709 MiB` to `39,527 MiB` (`-182 MiB` exact, matching `(92 - 1) *
    2 MiB`; `Allocate cache` `8.5 GiB -> 8.4 GiB`, identical `2,048` KV pages
    and `44` shared snapshot slots).
  - Memory-limited (`--memory-limit 40G`): KV capacity increased from `2,352`
    to `2,400` KV pages (`+48` pages / `+6,144` KV tokens, `301,056 -> 307,200`)
    and shared snapshots increased from `50` to `51` within the same `9.77 GiB`
    cache budget.

Supporting evidence and limitations:

- Rust crate release suites (`--locked --release --target-dir flare-cli/target`):
  - `eos`: 12 passed, 0 failed.
  - `selene` (`--features test-support`): 585 lib + 1 integration passed, 0 failed.
  - `selene-manager` (`--features test-support`): 205 lib + 243 integration passed, 0 failed, 1 ignored.
  - `helios` (`--features runtime-core,server`, with prepared public templates):
    1,881 lib + 62 integration passed, 0 failed, 49 lib / 36 integration ignored.
  - `flare`: 247 lib + 8 integration passed, 0 failed, 4 ignored.
  - `flare-cli`: 220 bin + 26 integration passed, 0 failed, 3 ignored.
- SM120 GPU tests (RTX PRO 6000 Blackwell):
  - `runtime_core::cache_memory::tests::cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten`
    and `cuda_sentinel_row_with_exact_granule_stride_maps_without_tail`: 2 passed, 0 failed.
  - `offload::transfer::codec::tests::` (all 4 GPU tests with SM120 `kv_codec_gpu.cubin`):
    4 passed, 0 failed.
  - `offload::transfer::tests::split_pools_cost_each_device_its_part_and_round_trip_units`
    (2 GPUs): 1 passed, 0 failed.
  - Live serving and NVMe disk offload + restart restore on
    `Qwen3.8-27B-NVIDIA-NVFP4-QAD-MXFP8` (`--prefix-cache-memory 0 --prefix-cache-disk`):
    cold turn (`4,228` prompt tokens) stored `312.89 MiB` to disk and returned
    `42`; fresh restarted process restored `312.89 MiB` from NVMe (`4,221`
    reused tokens) and returned `42`.
- Formal verification:
  - `python3 verification/helios-lifecycle/check.py` (TLC 1.7.4 / Java 21):
    all 8 TLA+ models and all observed Rust transition checks passed (Lifecycle
    1,710, RankProtocol 1,291, DispatchRing 7,940, OffloadTransfer 8,490,
    CacheOwnership 222,817, Speculation 13,566, ResponseLifecycle 365,508,
    CheckpointReservation 68).
  - `cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib`
    (Kani 0.68.0 / CBMC 6.11.0): 13 verified harnesses, 0 failures.
- Limitations: `offload::gpu_tests::disk_store::staged_store_round_trips_records_through_files_and_a_restart`
  and sibling `FLARE_OFFLOAD_TEST_CORE` Rust unit tests require a core signed
  with the synthetic `flare-tests` test key and were not run directly against
  production-signed local cores (the disk offload/restart path was exercised
  live through `flare run` instead). Aliasing row zero onto one writable
  granule relies on the model contract that inactive lanes perform no state
  mutation.

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@lukealonso
lukealonso force-pushed the perf/sentinel-row-aliasing branch from 16e2247 to c9bb433 Compare December 3, 2026 20:54
@lukealonso

Copy link
Copy Markdown
Collaborator Author

Rebased onto origin/main (cb191a93) at c9bb4333, resolved the merge conflicts in helios/src/runtime_core/cache_memory.rs, and addressed all review items:

  • Executed SM120 GPU VMM & live-core verification:
    • Ran cuda_aliases_preserve_rows_while_unowned_pages_are_rewritten (updated to rows = 8 after origin/main's midpoint-ordered grouping, with hardware probes verifying physical aliasing across row 0 granules 0..3 and isolation of row 0's partial tail from granule 0 and row 1) and added cuda_sentinel_row_with_exact_granule_stride_maps_without_tail for the tail == 0 path (2 passed, 0 failed on RTX PRO 6000 Blackwell).
    • Measured before/after on a live Qwen3.8-27B-NVIDIA-NVFP4-QAD-MXFP8 TP1 core (row_bytes = 193,865,984, sentinel_granules = 92) vs origin/main (cb191a93): -182 MiB exact GPU VRAM in --kv-cache-limit context mode (39,709 -> 39,527 MiB, Allocate cache 8.5 -> 8.4 GiB) and +48 KV pages / +1 shared snapshot slot (2,352 -> 2,400 pages, 50 -> 51 snapshots) in --memory-limit 40G mode, plus live NVMe disk offload and restart restore (312.89 MiB, 4,221 reused tokens).
  • Enforced non-zero row invariant & fixed tests using StateSlotId(0):
    • Rejected StateSlotId(0) in offload::transfer::expand and offload::transfer::codec::device_spans with CPU rejection tests.
    • Updated staged_store_round_trips_records_through_files_and_a_restart (helios/src/offload/gpu_tests.rs) to use StateSlotId(4) (row_capacity >= 5), and updated the two codec GPU tests in helios/src/offload/transfer/codec.rs to use a 3-row geometry with StateSlotId(1) and StateSlotId(2) (all 4 GPU codec tests passed on SM120).
  • Refactors & edge-case guards:
    • Guarded sentinel_granules in Layout::grouped with execution > 0 && row_bytes / row_alignment > 1 (with CPU coverage for execution == 0 and tail == 0) and noted the RM-handle trade-off in the PR description.
    • Collapsed row_backing_bytes onto bytes(core, 0, units) (helios/src/runtime_core/memory.rs) and unified fixed-chunk accounting/mapping/zeroing/invariant checks via Layout::fixed_segments() (helios/src/runtime_core/cache_memory.rs).
  • Verification: Full release test suites across eos, selene, selene-manager, helios, flare, and flare-cli, TLA+ lifecycle & Rust conformance (check.py), and all 13 Kani proofs passed.

@flare-autobot

@lukealonso
lukealonso merged commit 1cc15c0 into main Dec 3, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:validation Proposed implementation needs acceptance evidence; no claim that a reported defect is fixed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants