From c9bb433383200308831f6d5940ac40b821356b93 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Tue, 1 Dec 2026 10:07:35 -0800 Subject: [PATCH] perf(helios): alias null continuation row zero onto a single zeroed VMM granule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/runtime-core-design.md | 11 +- helios/src/offload/gpu_tests.rs | 4 +- helios/src/offload/transfer.rs | 38 ++- helios/src/offload/transfer/codec.rs | 79 +++-- helios/src/runtime_core/cache_memory.rs | 424 ++++++++++++++++++++++-- helios/src/runtime_core/memory.rs | 61 +++- 6 files changed, 552 insertions(+), 65 deletions(-) diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 865da8923..3a50c9d71 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -782,7 +782,12 @@ by CUDA's device total. CPU allocations, registered buffers, and GPU allocations share physical DRAM; reclaimable page cache contributes to available memory, while swap does not. Discrete GPUs use CUDA's free device-memory query. Dedicated rows comprise one null row and the selected request capacity times -the recipe's execution rows per request. KV pages receive the remaining budget, +the recipe's execution rows per request. When one continuation row spans more +than one VMM allocation granule (`row_bytes >= 2 * alignment`), Helios aliases +the `floor(row_bytes / alignment)` full leading granules of null row zero onto +one shared zeroed physical granule while keeping row zero's partial tail and +all live rows uniquely backed, saving `(floor(row_bytes / alignment) - 1) * +alignment` physical bytes per rank. KV pages receive the remaining budget, within their virtual maximum. The planner accounts for mapping alignment and requires at least 8,192 cached tokens per active request. @@ -836,8 +841,8 @@ as an enclosing page range. Wider bands can exclude more pages while a snapshot is retained. Both policies keep the planned number of KV pages, snapshot slots and physical bytes. The RM estimate covers the model's VMM objects; other driver objects share the same 524,288-handle range, so deployments near the limit -(such as the 518,232-handle 3,103-page DCP16 layout, leaving 6,056 handles / -1.2%) rely on that remaining headroom. +(such as the 518,504-handle 3,103-page DCP16 layout, leaving 5,784 handles / +1.1%) rely on that remaining headroom. Multi-host cache agreement exchanges page and row counts. Each host uses the same canonical layout and includes its snapshot conflict ranges in the diff --git a/helios/src/offload/gpu_tests.rs b/helios/src/offload/gpu_tests.rs index 8ac9d4f9c..f6123ea42 100644 --- a/helios/src/offload/gpu_tests.rs +++ b/helios/src/offload/gpu_tests.rs @@ -1464,7 +1464,7 @@ mod disk_store { let layout = Layout::new(&geometry).unwrap(); let fingerprint = fingerprint(&geometry); let page_tokens = rank.page_tokens; - assert!(rank.page_capacity >= 400 && rank.row_capacity >= 4); + assert!(rank.page_capacity >= 400 && rank.row_capacity >= 5); const SOURCE: u32 = 100; const RESTORED: u32 = 200; @@ -1475,7 +1475,7 @@ mod disk_store { let extra_pages = pages(SOURCE + PAGES..SOURCE + PAGES + EXTRA); let (source_slot, child_slot, restored_slot, again_slot) = ( StateSlotId(1), - StateSlotId(0), + StateSlotId(4), StateSlotId(2), StateSlotId(3), ); diff --git a/helios/src/offload/transfer.rs b/helios/src/offload/transfer.rs index 1dea740ab..2cbf7a3d5 100644 --- a/helios/src/offload/transfer.rs +++ b/helios/src/offload/transfer.rs @@ -160,9 +160,9 @@ pub(crate) fn expand( } if let Some((slot, slots)) = &job.row { let index = u64::from(slot.0); - if index >= geometry.row_capacity { + if index == 0 || index >= geometry.row_capacity { return Err(invalid(format!( - "state slot {index} is outside the cache's {} rows", + "state slot {index} is outside the cache's live rows 1..{}", geometry.row_capacity ))); } @@ -1168,6 +1168,29 @@ mod tests { ) .is_err() ); + let mut null_slot = job(Direction::Out); + null_slot.row = Some((StateSlotId(0), vec![0x30000])); + assert!( + expand( + &ranks[0], + &layout.ranks[0], + None, + &null_slot, + &mut descriptors + ) + .is_err() + ); + null_slot.direction = Direction::In; + assert!( + expand( + &ranks[0], + &layout.ranks[0], + None, + &null_slot, + &mut descriptors + ) + .is_err() + ); let mut null_slab = job(Direction::In); null_slab.pages[0].1 = 0; assert!( @@ -1692,12 +1715,19 @@ mod tests { "row {target_slot} differs from row {source_slot}" ); - for (id, slot) in [(capacity, 0), (0, rank.row_capacity as u32)] { + for (index, (id, slot)) in [ + (capacity, 1), + (0, 0), + (0, rank.row_capacity as u32), + ] + .into_iter() + .enumerate() + { transfers .submit(Job { codec: None, replication: Default::default(), - id: JobId(3 + u64::from(slot != 0)), + id: JobId(3 + index as u64), window: 0, direction: Direction::Out, pages: vec![(PageId(id), page_slabs[0])], diff --git a/helios/src/offload/transfer/codec.rs b/helios/src/offload/transfer/codec.rs index 30f330655..ad6d961af 100644 --- a/helios/src/offload/transfer/codec.rs +++ b/helios/src/offload/transfer/codec.rs @@ -905,7 +905,7 @@ fn device_spans( } else { geometry.page_capacity }; - if id >= capacity { + if (row && id == 0) || id >= capacity { return Err(invalid("codec destination id outside cache")); } if row { @@ -1052,7 +1052,7 @@ mod tests { let (page_bytes, row_bytes) = (4096usize, 65536usize); let n_pages = 4usize; let mut page_mem = stream.mapped_host_buffer(page_bytes * n_pages * 2).unwrap(); - let mut row_mem = stream.mapped_host_buffer(row_bytes * 2).unwrap(); + let mut row_mem = stream.mapped_host_buffer(row_bytes * 3).unwrap(); let page_addr = stream.mapped_address(&page_mem).unwrap() as u64; let row_addr = stream.mapped_address(&row_mem).unwrap() as u64; let mut geometry = CacheGeometry { @@ -1074,7 +1074,7 @@ mod tests { snapshot_pages: Vec::new(), page_tokens: 64, page_capacity: (n_pages * 2) as u64, - row_capacity: 2, + row_capacity: 3, planes: vec![Plane { name: "kv".into(), address: page_addr, @@ -1087,24 +1087,25 @@ mod tests { }, }; - // Populate source pages 0..n_pages and row 0 in device-visible memory. + // Populate source pages 0..n_pages and row 1 in device-visible memory (row 0 is null). let src_pages: Vec> = (0..n_pages) .map(|p| (0..page_bytes).map(|i| (((i + p * 17) / 7) % 13) as u8).collect()) .collect(); - let mut row0 = vec![0u8; row_bytes]; + let mut row1 = vec![0u8; row_bytes]; for c in 0..128 { for r in 0..128 { let v = ((r as f32 * 0.01).sin() * (c as f32 * 0.02).cos()).to_bits(); let idx = (c * 128 + r) * 4; - row0[idx..idx + 4].copy_from_slice(&v.to_le_bytes()); + row1[idx..idx + 4].copy_from_slice(&v.to_le_bytes()); } } for (p, data) in src_pages.iter().enumerate() { page_mem.bytes_mut()[p * page_bytes..(p + 1) * page_bytes].copy_from_slice(data); } - row_mem.bytes_mut()[..row_bytes].copy_from_slice(&row0); + row_mem.bytes_mut()[..row_bytes].fill(0); + row_mem.bytes_mut()[row_bytes..row_bytes * 2].copy_from_slice(&row1); page_mem.bytes_mut()[n_pages * page_bytes..].fill(0xa5); - row_mem.bytes_mut()[row_bytes..].fill(0xa5); + row_mem.bytes_mut()[row_bytes * 2..].fill(0xa5); let mut transfers = if geometry.placement == KvCompression::Gpu { let path = std::env::var("FLARE_TEST_KV_CODEC_CUBIN") @@ -1128,7 +1129,7 @@ mod tests { window: 0, direction: Direction::Out, pages: (0..n_pages as u32).map(|p| (PageId(p), p as usize)).collect(), - row: Some((StateSlotId(0), vec![0])), + row: Some((StateSlotId(1), vec![0])), replication: Default::default(), codec: Some(cap_win.clone()), }) @@ -1163,7 +1164,7 @@ mod tests { assert_eq!(slots[n_pages].unit.representation, Representation::Packet as i32); assert!(slots[n_pages].bytes.len() < row_bytes); - // 2. Restore packed host -> VRAM pages n_pages..2*n_pages and row 1 (Direction::In) + // 2. Restore packed host -> VRAM pages n_pages..2*n_pages and row 2 (Direction::In) let restore_win = Window::restore_pinned( 0, slots @@ -1184,7 +1185,7 @@ mod tests { pages: (0..n_pages as u32) .map(|p| (PageId(n_pages as u32 + p), p as usize)) .collect(), - row: Some((StateSlotId(1), vec![0])), + row: Some((StateSlotId(2), vec![0])), replication: Default::default(), codec: Some(restore_win), }) @@ -1202,7 +1203,7 @@ mod tests { let dst_off = (n_pages + p) * page_bytes; assert_eq!(&page_mem.bytes()[dst_off..dst_off + page_bytes], data.as_slice()); } - assert_eq!(&row_mem.bytes()[row_bytes..row_bytes * 2], &row0); + assert_eq!(&row_mem.bytes()[row_bytes * 2..row_bytes * 3], &row1); // 3. Corrupt stored CRC must fail cleanly and count a stored verification failure. let mut bad_u = slots[0].unit.clone(); @@ -1296,7 +1297,7 @@ mod tests { let stream = Stream::open_lowest_priority(context, 0).unwrap(); let (page_bytes, row_bytes) = (4096usize, 65536usize); let mut page_mem = stream.mapped_host_buffer(page_bytes * 2).unwrap(); - let mut row_mem = stream.mapped_host_buffer(row_bytes * 2).unwrap(); + let mut row_mem = stream.mapped_host_buffer(row_bytes * 3).unwrap(); let page_addr = stream.mapped_address(&page_mem).unwrap() as u64; let row_addr = stream.mapped_address(&row_mem).unwrap() as u64; let mut base_geo = CacheGeometry { @@ -1318,7 +1319,7 @@ mod tests { snapshot_pages: Vec::new(), page_tokens: 64, page_capacity: 2, - row_capacity: 2, + row_capacity: 3, planes: vec![Plane { name: "kv".into(), address: page_addr, @@ -1331,16 +1332,17 @@ mod tests { }, }; let page0: Vec = (0..page_bytes).map(|i| ((i / 7) % 13) as u8).collect(); - let mut row0 = vec![0u8; row_bytes]; + let mut row1 = vec![0u8; row_bytes]; for c in 0..128 { for r in 0..128 { let v = ((r as f32 * 0.01).sin() * (c as f32 * 0.02).cos()).to_bits(); let idx = (c * 128 + r) * 4; - row0[idx..idx + 4].copy_from_slice(&v.to_le_bytes()); + row1[idx..idx + 4].copy_from_slice(&v.to_le_bytes()); } } page_mem.bytes_mut()[..page_bytes].copy_from_slice(&page0); - row_mem.bytes_mut()[..row_bytes].copy_from_slice(&row0); + row_mem.bytes_mut()[..row_bytes].fill(0); + row_mem.bytes_mut()[row_bytes..row_bytes * 2].copy_from_slice(&row1); let cpu_profile = flare_selene::shared::codec_layout::profile( &base_geo, @@ -1392,7 +1394,7 @@ mod tests { window: 0, direction: Direction::Out, pages: vec![(PageId(0), 0)], - row: Some((StateSlotId(0), vec![0])), + row: Some((StateSlotId(1), vec![0])), replication: Default::default(), codec: Some(cpu_cap.clone()), }, @@ -1402,7 +1404,7 @@ mod tests { // 2. Restore CPU ZKV1 packets using GPU-mode Transfers (decodes on CPU -> VRAM) page_mem.bytes_mut()[page_bytes..].fill(0xaa); - row_mem.bytes_mut()[row_bytes..].fill(0xaa); + row_mem.bytes_mut()[row_bytes * 2..].fill(0xaa); let zkv_win = Window::restore_pinned( 0, cpu_slots @@ -1422,13 +1424,13 @@ mod tests { window: 0, direction: Direction::In, pages: vec![(PageId(1), 0)], - row: Some((StateSlotId(1), vec![0])), + row: Some((StateSlotId(2), vec![0])), replication: Default::default(), codec: Some(zkv_win), }, ); assert_eq!(&page_mem.bytes()[page_bytes..], &page0); - assert_eq!(&row_mem.bytes()[row_bytes..], &row0); + assert_eq!(&row_mem.bytes()[row_bytes * 2..], &row1); // 3. Re-capture in GPU mode (writes GKV1 / gpu_profile) let gpu_cap = Window::capture(0); @@ -1439,7 +1441,7 @@ mod tests { window: 0, direction: Direction::Out, pages: vec![(PageId(1), 0)], - row: Some((StateSlotId(1), vec![0])), + row: Some((StateSlotId(2), vec![0])), replication: Default::default(), codec: Some(gpu_cap.clone()), }, @@ -1449,7 +1451,7 @@ mod tests { // 4. CPU-mode Transfers natively restores GKV1/v2 packets on CPU with zero GPU VRAM! page_mem.bytes_mut()[page_bytes..].fill(0x55); - row_mem.bytes_mut()[row_bytes..].fill(0x55); + row_mem.bytes_mut()[row_bytes * 2..].fill(0x55); let gkv_win = Window::restore_pinned( 0, gpu_slots @@ -1469,15 +1471,42 @@ mod tests { window: 0, direction: Direction::In, pages: vec![(PageId(1), 0)], - row: Some((StateSlotId(1), vec![0])), + row: Some((StateSlotId(2), vec![0])), replication: Default::default(), codec: Some(gkv_win), }, ); assert_eq!(&page_mem.bytes()[page_bytes..], &page0); - assert_eq!(&row_mem.bytes()[row_bytes..], &row0); + assert_eq!(&row_mem.bytes()[row_bytes * 2..], &row1); cpu_xfer.close().unwrap(); gpu_xfer.close().unwrap(); } + + #[test] + fn device_spans_rejects_null_state_slot_zero() { + let geometry = CacheGeometry { + placement: KvCompression::Cpu, + codec_fields: Vec::new(), + snapshot_pages: Vec::new(), + page_tokens: 64, + page_capacity: 4, + row_capacity: 4, + planes: vec![Plane { + name: "kv".into(), + address: 0x1000, + unit_bytes: 4096, + }], + row: Plane { + name: "state".into(), + address: 0x10000, + unit_bytes: 8192, + }, + }; + let layout = flare_selene::Layout::new(std::slice::from_ref(&geometry)).unwrap(); + assert!(device_spans(&geometry, &layout.ranks[0], false, 0).is_ok()); + assert!(device_spans(&geometry, &layout.ranks[0], true, 0).is_err()); + assert!(device_spans(&geometry, &layout.ranks[0], true, 1).is_ok()); + assert!(device_spans(&geometry, &layout.ranks[0], true, 4).is_err()); + } } diff --git a/helios/src/runtime_core/cache_memory.rs b/helios/src/runtime_core/cache_memory.rs index e71e2ab44..112b72e4f 100644 --- a/helios/src/runtime_core/cache_memory.rs +++ b/helios/src/runtime_core/cache_memory.rs @@ -60,10 +60,16 @@ impl Chunk { pub(super) struct Layout { alignment: u64, fixed_bytes: u64, + sentinel_granules: u64, chunks: Vec, pub aliases: Vec>, } +/// Physical bytes saved by aliasing full granules inside null continuation row zero onto one page. +pub(super) fn sentinel_saved_bytes(row_bytes: u64, alignment: u64) -> u64 { + (row_bytes / alignment).saturating_sub(1) * alignment +} + pub(super) fn alias_plane( unit: u64, largest: u64, @@ -120,11 +126,42 @@ pub(super) fn union_aliases(layouts: &[Layout], snapshots: usize) -> Vec 1`, null row zero's leading granules alias one `alignment`-sized + /// physical chunk across `mapping_count` offsets and `tail_bytes` backs the remainder; + /// otherwise one chunk covers `fixed_bytes` with `tail_bytes == 0`. + 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) + } + /// Backing handles and per-device address mappings created by this layout. pub(super) fn handle_charge(&self, row_readers: u64, plane_readers: &[u64]) -> Result { + let (count, granule, tail) = self.fixed_segments(); + let mut fixed_charge = if granule > 0 { + 1u64.checked_add( + count + .checked_mul(row_readers) + .ok_or_else(|| invalid("mapping handle count overflow"))?, + ) + .ok_or_else(|| invalid("mapping handle count overflow"))? + } else { + 0 + }; + if tail > 0 { + fixed_charge = fixed_charge + .checked_add(1) + .and_then(|n| n.checked_add(row_readers)) + .ok_or_else(|| invalid("mapping handle count overflow"))?; + } self.chunks .iter() - .try_fold(1 + row_readers, |total, chunk| { + .try_fold(fixed_charge, |total, chunk| { total .checked_add(1) .and_then(|n| n.checked_add(plane_readers[chunk.plane])) @@ -156,6 +193,18 @@ impl Layout { #[cfg(test)] pub(super) fn verify_physical_invariants(&self, geometry: &CacheGeometry, execution: u64) { + let (count, granule, tail) = self.fixed_segments(); + assert_eq!(count * granule + tail, self.fixed_bytes); + if execution > 0 && geometry.row.unit_bytes / self.alignment > 1 { + assert_eq!( + self.sentinel_granules, + geometry.row.unit_bytes / self.alignment + ); + assert_eq!(granule, self.alignment); + } else { + assert_eq!(self.sentinel_granules, 0); + assert_eq!(tail, 0); + } for (plane, p) in geometry.planes.iter().enumerate() { let mut pieces: Vec<_> = self.chunks.iter().filter(|c| c.plane == plane).collect(); pieces.sort_by_key(|c| c.offset); @@ -358,9 +407,15 @@ impl Layout { return Err(invalid("continuation alias lacks a KV conflict range")); } } + let sentinel_granules = if execution > 0 && row_bytes / row_alignment > 1 { + row_bytes / row_alignment + } else { + 0 + }; Ok(Self { alignment: row_alignment, fixed_bytes, + sentinel_granules, chunks, aliases, }) @@ -581,6 +636,7 @@ impl Layout { Some(Self { alignment: self.alignment, fixed_bytes: self.fixed_bytes, + sentinel_granules: self.sentinel_granules, chunks, aliases, }) @@ -1016,7 +1072,7 @@ mod tests { let readers = [vec![16; 24], vec![1; 24]].concat(); let a = 2 << 20; for (pages, snapshots, fixed, expected) in - [(2304, 116, 20320, 494576), (3103, 157, 3528, 647544)] + [(2304, 116, 20320, 494848), (3103, 157, 3528, 647816)] { let g = geometry(35_122_432, &units, pages, snapshots + 2); let old = Layout::new(&g, 2, &[a; 48], a).unwrap(); @@ -1030,7 +1086,7 @@ mod tests { let candidate = old.pack_prefixes(&g, 2).unwrap(); assert_eq!( fixed + 16 * candidate.handle_charge(1, &readers).unwrap(), - 518232 + 518504 ); assert_eq!(candidate.aliases.len(), snapshots as usize); assert_eq!(candidate.fixed_bytes, old.fixed_bytes); @@ -1360,6 +1416,7 @@ mod tests { } else { vec![alignment / 8, alignment / 4, alignment / 64] }; + let rows = 8u64; let mut geometry = geometry( if equal_planes { 7 * alignment / 2 @@ -1368,10 +1425,10 @@ mod tests { }, &units, 128, - 7, + rows, ); for plane in std::iter::once(&mut geometry.row).chain(&mut geometry.planes) { - let units = if plane.name == "rows" { 7 } else { 128 }; + let units = if plane.name == "rows" { rows } else { 128 }; let bytes = (units * plane.unit_bytes).div_ceil(alignment) * alignment; driver .check( @@ -1407,19 +1464,20 @@ mod tests { owner .allocate_shared_cache(&core, &geometry, &layout) .unwrap(); - // Distinct bytes within each row detect repeated or misplaced - // backing, not just writes crossing snapshot boundaries. - let expected: Vec> = (0..7) + // Row 0 is the null sentinel row (aliased onto one zero granule when spanning + // multiple granules); verify rows 1..rows retain distinct backing and row 0 stays zero. + let mut expected: Vec> = (0..rows) .map(|row| { (0..geometry.row.unit_bytes as usize) .map(|i| { ((i ^ (i >> 8) ^ (i >> 16) ^ (i >> 24)) as u8) - .wrapping_add(row * 31) + .wrapping_add((row as u8).wrapping_mul(31)) }) .collect() }) .collect(); - for (row, bytes) in expected.iter().enumerate() { + expected[0] = vec![0u8; geometry.row.unit_bytes as usize]; + for (row, bytes) in expected.iter().enumerate().skip(1) { driver .check( "cuMemcpyHtoD_v2", @@ -1432,7 +1490,7 @@ mod tests { .unwrap(); } // Release snapshots one at a time, overwriting every page outside the remaining exclusions. - for released in 0..=4 { + for released in 0..=(rows as usize - 3) { for page in 0..geometry.page_capacity { if layout.aliases[released..] .iter() @@ -1456,7 +1514,7 @@ mod tests { driver .check("cuCtxSynchronize", (driver.context_sync)()) .unwrap(); - for row in (0..3).chain(3 + released as u64..7) { + for row in (0..3).chain(3 + released as u64..rows) { let mut contents = vec![0; geometry.row.unit_bytes as usize]; driver .check( @@ -1474,10 +1532,248 @@ mod tests { ); } } + if equal_planes { + // Verify on hardware that row 0's leading granules share one physical page + // while row 0's partial tail [sentinel_bytes, row_bytes) is uniquely backed + // and isolated from both the aliased granule and row 1. + assert_eq!(layout.sentinel_granules, 3); + let sentinel_bytes = layout.sentinel_granules * alignment; + let tail_len = (geometry.row.unit_bytes - sentinel_bytes) as usize; + assert!(tail_len > 0); + let probe = vec![0x5Au8; 4096]; + driver + .check( + "cuMemcpyHtoD_v2", + (driver.upload)( + geometry.row.address, + probe.as_ptr().cast(), + probe.len(), + ), + ) + .unwrap(); + driver + .check("cuCtxSynchronize", (driver.context_sync)()) + .unwrap(); + for granule in 1..layout.sentinel_granules { + let mut seen = vec![0u8; probe.len()]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)( + seen.as_mut_ptr().cast(), + geometry.row.address + granule * alignment, + seen.len(), + ), + ) + .unwrap(); + assert_eq!(seen, probe, "granule {granule} did not alias granule 0"); + } + let mut tail_seen = vec![0xFFu8; tail_len]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)( + tail_seen.as_mut_ptr().cast(), + geometry.row.address + sentinel_bytes, + tail_len, + ), + ) + .unwrap(); + assert!( + tail_seen.iter().all(|&b| b == 0), + "row 0 partial tail was modified by writing aliased granule 0" + ); + let tail_probe = vec![0x3Cu8; tail_len.min(4096)]; + driver + .check( + "cuMemcpyHtoD_v2", + (driver.upload)( + geometry.row.address + sentinel_bytes, + tail_probe.as_ptr().cast(), + tail_probe.len(), + ), + ) + .unwrap(); + driver + .check("cuCtxSynchronize", (driver.context_sync)()) + .unwrap(); + let mut g0_seen = vec![0u8; probe.len()]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)( + g0_seen.as_mut_ptr().cast(), + geometry.row.address, + g0_seen.len(), + ), + ) + .unwrap(); + assert_eq!( + g0_seen, probe, + "writing row 0 partial tail corrupted aliased granule 0" + ); + let mut row1_seen = vec![0u8; geometry.row.unit_bytes as usize]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)( + row1_seen.as_mut_ptr().cast(), + geometry.row.address + geometry.row.unit_bytes, + row1_seen.len(), + ), + ) + .unwrap(); + assert_eq!( + row1_seen, expected[1], + "row 0 writes corrupted row 1 inside the shared boundary granule" + ); + } } } } + #[test] + #[ignore = "requires an assigned CUDA_VISIBLE_DEVICES GPU"] + fn cuda_sentinel_row_with_exact_granule_stride_maps_without_tail() { + use super::super::{ + driver::Driver, + format::{Allocation, Context}, + }; + let driver = Driver::load().unwrap(); + unsafe { + driver.check("cuInit", (driver.init)(0)).unwrap(); + let mut device = 0; + driver + .check("cuDeviceGet", (driver.device)(&mut device, 0)) + .unwrap(); + let mut architecture = [0; 2]; + for (value, attribute) in architecture.iter_mut().zip([75, 76]) { + driver + .check( + "cuDeviceGetAttribute", + (driver.device_attribute)(value, attribute, device), + ) + .unwrap(); + } + let mut core = Core { + resources: Default::default(), + events: vec![], + architecture, + modules: vec![], + functions: vec![], + graphs: vec![], + reservations: vec![], + execution: None, + context: Context::default(), + allocations: vec![], + }; + let mut owner = NativeResources::initialize(&core, 0).unwrap(); + let properties = AllocationProperties { + kind: 1, + handles: 0, + location: Location { kind: 1, device }, + windows: std::ptr::null_mut(), + flags: [0; 8], + }; + let mut alignment = 0; + driver + .check( + "cuMemGetAllocationGranularity", + (driver.granularity)(&mut alignment, &properties, 0), + ) + .unwrap(); + let alignment = alignment as u64; + // execution == 1 with row_bytes == 2 * alignment exercises the tail == 0 path: + // fixed_bytes == sentinel_bytes == 2 * alignment, snapshots start right after row 0. + let mut geometry = geometry(2 * alignment, &vec![alignment / 8; 4], 64, 3); + for plane in std::iter::once(&mut geometry.row).chain(&mut geometry.planes) { + let units = if plane.name == "rows" { 3 } else { 64 }; + let bytes = (units * plane.unit_bytes).div_ceil(alignment) * alignment; + driver + .check( + "cuMemAddressReserve", + (driver.reserve)(&mut plane.address, bytes as usize, 0, 0, 0), + ) + .unwrap(); + owner.reservations.push((plane.address, bytes as usize)); + core.allocations.push(Allocation { + name: plane.name.clone(), + nbytes: bytes as usize, + alignment: alignment as usize, + file: None, + data_spans: vec![], + sources: vec![], + relocations: vec![], + address: Some(plane.address), + memory: Memory::Device, + sizing: None, + }); + } + let alignments = vec![alignment; geometry.planes.len()]; + let layout = Layout::new(&geometry, 1, &alignments, alignment).unwrap(); + assert_eq!(layout.fixed_segments(), (2, alignment, 0)); + layout.verify_physical_invariants(&geometry, 1); + owner + .allocate_shared_cache(&core, &geometry, &layout) + .unwrap(); + + let mut row0 = vec![0xFFu8; geometry.row.unit_bytes as usize]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)(row0.as_mut_ptr().cast(), geometry.row.address, row0.len()), + ) + .unwrap(); + assert!(row0.iter().all(|&b| b == 0)); + + let row1 = vec![0x7Bu8; geometry.row.unit_bytes as usize]; + driver + .check( + "cuMemcpyHtoD_v2", + (driver.upload)( + geometry.row.address + geometry.row.unit_bytes, + row1.as_ptr().cast(), + row1.len(), + ), + ) + .unwrap(); + let probe = vec![0xA3u8; 4096]; + driver + .check( + "cuMemcpyHtoD_v2", + (driver.upload)(geometry.row.address, probe.as_ptr().cast(), probe.len()), + ) + .unwrap(); + driver + .check("cuCtxSynchronize", (driver.context_sync)()) + .unwrap(); + let mut g1_seen = vec![0u8; probe.len()]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)( + g1_seen.as_mut_ptr().cast(), + geometry.row.address + alignment, + g1_seen.len(), + ), + ) + .unwrap(); + assert_eq!(g1_seen, probe); + let mut row1_seen = vec![0u8; row1.len()]; + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)( + row1_seen.as_mut_ptr().cast(), + geometry.row.address + geometry.row.unit_bytes, + row1_seen.len(), + ), + ) + .unwrap(); + assert_eq!(row1_seen, row1); + } + } + #[test] fn unaligned_rows_and_multiplane_pages_have_complete_conflict_ranges() { for (row_bytes, units, pages, alignment) in [ @@ -1684,6 +1980,58 @@ mod tests { layout.verify_physical_invariants(geo, execution); } } + + #[test] + fn sentinel_row_aliases_full_granules_onto_one_page() { + let align = 2 << 20; + let row_bytes = 82_143_488; + assert_eq!(sentinel_saved_bytes(row_bytes, align), 38 * align); + assert_eq!(sentinel_saved_bytes(align, align), 0); + assert_eq!(sentinel_saved_bytes(align - 4096, align), 0); + let g = geometry(row_bytes, &[3_276_800, 204_800], 256, 4); + let layout = Layout::new(&g, 2, &[align, align], align).unwrap(); + assert_eq!(layout.sentinel_granules, 39); + assert_eq!(layout.fixed_bytes, 158 << 20); + assert_eq!(layout.fixed_segments(), (39, align, 80 << 20)); + layout.verify_physical_invariants(&g, 2); + // Handle charge accounts for the 39 aliased sentinel mappings + 1 shared handle + + // 1 handle and 1 mapping for the non-sentinel tail (Row 0 tail + Row 1). + let base_chunks: u64 = layout + .chunks + .iter() + .map(|c| 2 + u64::from(c.row_bytes != 0)) + .sum(); + assert_eq!( + layout.handle_charge(1, &[1, 1]).unwrap(), + (1 + 39) + 2 + base_chunks + ); + + // Exact-granule single execution row: fixed_bytes == sentinel_bytes, tail == 0. + let exact_geo = geometry(2 * align, &[align / 2, align / 4], 64, 3); + let exact_layout = Layout::new(&exact_geo, 1, &[align, align], align).unwrap(); + assert_eq!(exact_layout.fixed_segments(), (2, align, 0)); + exact_layout.verify_physical_invariants(&exact_geo, 1); + let exact_chunks: u64 = exact_layout + .chunks + .iter() + .map(|c| 2 + u64::from(c.row_bytes != 0)) + .sum(); + assert_eq!( + exact_layout.handle_charge(1, &[1, 1]).unwrap(), + (1 + 2) + exact_chunks + ); + + // Zero execution rows: fixed_bytes == 0 must leave sentinel_granules == 0. + let zero_exec = Layout::new(&exact_geo, 0, &[align, align], align).unwrap(); + assert_eq!(zero_exec.fixed_segments(), (1, 0, 0)); + zero_exec.verify_physical_invariants(&exact_geo, 0); + let zero_chunks: u64 = zero_exec + .chunks + .iter() + .map(|c| 2 + u64::from(c.row_bytes != 0)) + .sum(); + assert_eq!(zero_exec.handle_charge(1, &[1, 1]).unwrap(), zero_chunks); + } } impl NativeResources { @@ -1714,14 +2062,30 @@ impl NativeResources { }, ); } - self.map_cache_chunk( - layout.fixed_bytes, - &[( - geometry.row.name.as_str(), - geometry.row.address, - layout.fixed_bytes, - )], - )?; + let (count, granule, tail) = layout.fixed_segments(); + if granule > 0 { + let mappings: Vec<_> = (0..count) + .map(|i| { + ( + geometry.row.name.as_str(), + geometry.row.address + i * granule, + granule, + ) + }) + .collect(); + self.map_cache_chunk(granule, &mappings)?; + } + if tail > 0 { + let tail_offset = count * granule; + self.map_cache_chunk( + tail, + &[( + geometry.row.name.as_str(), + geometry.row.address + tail_offset, + tail, + )], + )?; + } for chunk in &layout.chunks { let plane = &geometry.planes[chunk.plane]; let mut mappings = vec![( @@ -1742,10 +2106,22 @@ impl NativeResources { self.grant_storage_access(&plane.name)?; } // Zero each physical byte once, before any graph or transfer can read an alias. - self.driver.check( - "cuMemsetD8_v2", - (self.driver.zero)(geometry.row.address, 0, layout.fixed_bytes as usize), - )?; + if granule > 0 { + self.driver.check( + "cuMemsetD8_v2", + (self.driver.zero)(geometry.row.address, 0, granule as usize), + )?; + } + if tail > 0 { + self.driver.check( + "cuMemsetD8_v2", + (self.driver.zero)( + geometry.row.address + count * granule, + 0, + tail as usize, + ), + )?; + } for plane in &geometry.planes { let bytes = self.allocations[&plane.name].nbytes; self.driver diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index 120c43509..422d50593 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -380,6 +380,27 @@ fn bytes(core: &Core, capacity: i32, units: u64) -> Result { }) } +/// Physical bytes needed to back `units` continuation rows after aliasing null row zero's full +/// granules onto a single shared granule. +fn row_backing_bytes(core: &Core, units: u64) -> Result { + 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) +} + /// Host memory reserved for post-KV-sizing allocations: offload tiers/index/restore staging plus /// one prepared-input staging window and one decoded-source retention window. fn planned_host_future(offload_host: u64, input_window: u64, source_window: u64) -> Result { @@ -450,7 +471,7 @@ fn capacities( "model requires continuation-row and KV-page allocations", )); } - let fixed = bytes(core, 0, execution)?; + let fixed = row_backing_bytes(core, execution)?; if fixed > budget { return Err(invalid(format!( "selected concurrency and verification width exceed available memory: \ @@ -474,7 +495,7 @@ fn capacities( } let fits = |rows, pages| { cores.iter().zip(available).enumerate().all(|(rank, (p, &budget))| { - bytes(p, 0, rows) + row_backing_bytes(p, rows) .and_then(|n| { n.checked_add(bytes(p, 1, pages)?) .ok_or_else(|| invalid("cache footprint overflow")) @@ -487,7 +508,7 @@ fn capacities( }) }; for (rank, (core, &budget)) in cores.iter().zip(available).enumerate() { - let required = bytes(core, 0, execution)? + let required = row_backing_bytes(core, execution)? .checked_add(bytes(core, 1, minimum_pages)?) .ok_or_else(|| invalid("cache footprint overflow"))?; if required > budget { @@ -972,7 +993,7 @@ impl NativeModel { let minimum = cores .iter() .map(|core| { - bytes(core, 0, 1 + active as u64 * width)? + row_backing_bytes(core, 1 + active as u64 * width)? .checked_add(bytes(core, 1, minimum_pages)?) .ok_or_else(|| invalid("minimum cache footprint overflow")) }) @@ -1218,7 +1239,7 @@ impl NativeModel { } let mut gpu_bytes = 0; for core in cores.iter_mut() { - gpu_bytes += bytes(core, 0, rows - snapshots)? + bytes(core, 1, pages)?; + gpu_bytes += row_backing_bytes(core, rows - snapshots)? + bytes(core, 1, pages)?; for allocation in &mut core.allocations { if let Some(sizing) = allocation.sizing.as_ref() { let units = if sizing.capacity == 0 { rows } else { pages }; @@ -1973,7 +1994,8 @@ mod tests { assert!(full.1 < reduced.1 && reduced.1 < target_only.1); assert_eq!(reduced.0, 1 + 4 * 6 + reduced.2); for (rows, pages, snapshots) in [full, reduced, target_only] { - let used = bytes(&p[0], 0, rows - snapshots).unwrap() + bytes(&p[0], 1, pages).unwrap(); + let used = + row_backing_bytes(&p[0], rows - snapshots).unwrap() + bytes(&p[0], 1, pages).unwrap(); assert!(used <= budget[0] && budget[0] - used < 2 << 20); } // Capture concurrency is deliberately absent from the allocation policy. @@ -1987,7 +2009,10 @@ mod tests { capacities(&p, &[256 << 20, 80 << 20], 4, 3, 256, None, |_, _| Some(0)).unwrap(); assert!(pages <= 1000); for (p, budget) in p.iter().zip([256 << 20, 80 << 20]) { - assert!(bytes(p, 0, rows - snapshots).unwrap() + bytes(p, 1, pages).unwrap() <= budget); + assert!( + row_backing_bytes(p, rows - snapshots).unwrap() + bytes(p, 1, pages).unwrap() + <= budget + ); } assert!(capacities(&p, &[256 << 20, 1 << 20], 4, 3, 256, None, |_, _| Some(0)).is_err()); let (_, pages, _) = @@ -1995,6 +2020,28 @@ mod tests { assert_eq!(pages, 1024); } + #[test] + fn sentinel_row_savings_increase_kv_page_capacity() { + let align = 2 << 20; + let row_bytes = 82_143_488; + let page_bytes = 3_481_600; + let mut p = core(row_bytes, page_bytes, 2048); + for a in &mut p.allocations { + a.alignment = align as usize; + } + // Without sentinel aliasing, 2 rows need 158 MiB; with aliasing, 82 MiB (-76 MiB). + assert_eq!(bytes(&p, 0, 2).unwrap(), 158 << 20); + assert_eq!(row_backing_bytes(&p, 2).unwrap(), 82 << 20); + let budget = 900 << 20; + let (_, pages, _) = + capacities(&[p], &[budget], 1, 1, 128, None, |_, _| Some(0)).unwrap(); + let expected = (budget - (82 << 20)) / page_bytes; + assert!( + pages >= expected - 1 && pages <= expected, + "pages={pages}, expected≈{expected}" + ); + } + #[test] fn capped_pools_can_shrink_below_the_default_floor_without_exceeding_the_ceiling() { let cores = [