From 5021b7a3030c877395c1a8c0b283654d5b99520e Mon Sep 17 00:00:00 2001 From: fakoli Date: Sat, 5 Dec 2026 00:35:59 -0800 Subject: [PATCH] selene,helios: bound pool-only capture buffer to max_sequence_pages Why Pool-only prefix-cache offload (`--prefix-cache-pool` with zero `--prefix-cache-memory` and no local disk tier, added in PR #455) registers a CPU-readable capture buffer sized to hold one full checkpoint chain plus one row of slots. Currently `headroom_inner`, `capture_growth`, and `planned_offload_host` pass the entire GPU KV page capacity as that chain length. On large-VRAM GPUs or long-context quantized models where the GPU cache holds several full-context sequences, sizing the capture buffer to total GPU page capacity multiplies host RAM demand by the KV-to-context ratio and either throttles allocated GPU KV pages or triggers the startup error `host budget cannot hold a full pool capture` noted in PR #455's review. Because no single captured sequence chain can exceed `max_sequence_tokens`, bounding the chain to `min(GPU page capacity, ceil(max_sequence_tokens / page_tokens))` suffices while preserving the existing `intake_slots` floor for concurrent transfer bursts. What changed 1. Add `pub max_sequence_pages: Option` to `PrepareInputs` in `selene/src/offload.rs` (keeping `None` uncapped for callers that omit a sequence limit) and clamp `headroom_inner`'s `chain_pages` via `max_sequence_pages.map_or(pages, |limit| pages.min(limit.get()))`. 2. In `helios/src/runtime_core/memory.rs`, enforce both a positive `max_sequence_tokens` ceiling and a positive `contract.cache.page_tokens` size (via `max_sequence_pages(context, page_tokens)`) before dividing under all `--kv-cache-limit` modes (including `memory`, where `page_ceiling` returns early), compute `max_sequence_pages: NonZeroU64`, pass it into `headroom_with_inputs_for_budget`, share `capture_chain_pages(pages, max_sequence_pages)` between `capture_growth` and `planned_offload_host`, and return `max_sequence_pages` through `PlannedHostBudgets`. 3. Accept `max_sequence_pages: NonZeroU64` in private `NativeModel::prepare_offload` (`helios/src/runtime_core/model.rs`) from `PlannedHostBudgets` instead of recomputing from `server_config`, keeping planning and attach paths consistent. 4. Update the pool-only sizing specification in `docs/prefix-cache-offload.md` to document the single-sequence ceiling. 5. Thread `max_sequence_pages: None` through existing `PrepareInputs` test fixtures and `NonZeroU64::MIN` through `prepare_offload` test callers, add capped coverage inside `pool_only_sizes_registered_capture_and_headroom_for_local_ranks` (`selene`), and add `pool_capture_growth_caps_at_max_sequence_pages_without_throttling_gpu_pages` (`helios`) covering zero-input validation, ceiling rounding, capture exhaustion without clamping, shared `capture_chain_pages` clamping, and exact parity with uncapped `capacities`. Claimed benefit In pool-only mode (`--prefix-cache-memory 0`), the capture chain term stays bounded to one `max_sequence_tokens` chain plus one row's slots instead of scaling with total GPU KV page capacity. For a 1,048,576-token context core on a 96 GiB SM120 workstation GPU (`99,008` KV pages, `~748 KiB`/page record, `91` row slots, `64` tokens/page), the capture buffer drops from `99,099` slots (`~70.7 GiB`) to `16,475` slots (`11.8 GiB`, a `6.0x` reduction) while preserving all `99,008` GPU KV pages (`70.9 GiB`). Evidence All six workspace crates pass in release mode under `RUSTFLAGS="-D warnings"` inside `rust:1.94.1-slim-trixie` at this tree (`eos -- --test-threads=1`: 12 passed; `selene --features test-support`: 649 passed; `selene-manager --features test-support`: 448 passed, 1 ignored across 15 binaries including `rank_processes`; `helios --features runtime-core,server`: 2,041 passed, 88 ignored with 7 CI recipe templates prepared; `flare`: 255 passed, 4 ignored; `flare-cli`: 254 passed, 3 ignored). Hardware CUDA tests (`FLARE_RUN_CUDA_TESTS=1`), integrated-memory hosts, multi-host suites, Windows native tests, and Kani/TLA+ runs were not executed against this tree; live Qwen4-35B-A3B `11.8 GiB` startup and container RSS measurements were observed on a `v0.6.0` (`f705086`) build carrying this sizing rule. Signed-off-by: fakoli Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b --- docs/prefix-cache-offload.md | 27 +++++++------ helios/src/offload/pool/tests.rs | 1 + helios/src/runtime_core/memory.rs | 62 +++++++++++++++++++++++++++-- helios/src/runtime_core/model.rs | 17 ++++++-- selene-manager/tests/client.rs | 2 + selene-manager/tests/offload.rs | 1 + selene/src/offload.rs | 11 ++++- selene/src/offload/sharded/tests.rs | 4 ++ selene/src/offload/tests.rs | 22 ++++++++-- 9 files changed, 123 insertions(+), 24 deletions(-) diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index cd819cfaa..2d1e518e7 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -1592,18 +1592,21 @@ local disks, the manager can restore records it retained before shutdown. With only a pool configured and all ranks in one process, Flare registers a CPU-readable capture buffer. Its slot count is the larger of automatic intake -and the largest GPU page capacity plus one row's slots, bounded by the host -budget. All slots are available for capture. For GLM-5.3-Flash NVFP4 at TP4 -with 32 concurrent requests, automatic intake sets it to 11.0 GiB (1,664 slots); -the full-chain floor is 7.1 GiB. Helios limits GPU page capacity so the buffer -fits the host budget. If even the minimum page capacity plus one row does not -fit, startup fails with `host budget cannot hold a full pool capture`. Configure `--prefix-cache-memory` to choose -the host memory explicitly. While the manager can accept -records, each poll selects completed leaves for retirement, with up to four -selected at once. If a capture has no resident ancestor, it copies the full -GPU chain and offers its ancestors for linking at the manager. While the manager -is unavailable, the buffer retains records under the normal DRAM eviction policy. -With separate rank processes, a pool without a local disk tier only restores. +and one full single-sequence capture chain +(`min(GPU page capacity, ceil(max_sequence_tokens / page_tokens))` plus one +row's slots), bounded by the host budget. All slots are available for capture. +For GLM-5.3-Flash NVFP4 at TP4 with 32 concurrent requests, automatic intake +sets it to 11.0 GiB (1,664 slots); the full-chain floor is 7.1 GiB. Helios +limits GPU page capacity so one sequence chain plus one row fits the host +budget. If even the capped minimum page capacity plus one row does not fit, +startup fails with `host budget cannot hold a full pool capture`. Configure +`--prefix-cache-memory` to choose the host memory explicitly. While the manager +can accept records, each poll selects completed leaves for retirement, with up +to four selected at once. If a capture has no resident ancestor, it copies the +full GPU chain and offers its ancestors for linking at the manager. While the +manager is unavailable, the buffer retains records under the normal DRAM +eviction policy. With separate rank processes, a pool without a local disk tier +only restores. When DRAM feeds the pool directly, the shutdown drain continues copying, checksumming and retiring records that have not yet completed pool handover at diff --git a/helios/src/offload/pool/tests.rs b/helios/src/offload/pool/tests.rs index b79dbdc5d..c56f8831c 100644 --- a/helios/src/offload/pool/tests.rs +++ b/helios/src/offload/pool/tests.rs @@ -131,6 +131,7 @@ fn peer_registration_budget_fails_startup() { input_staging: 0, shard: Some((1, 2)), integrated: false, + max_sequence_pages: None, }, ) .unwrap(); diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index c629f4b29..9f9e02799 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -7,6 +7,7 @@ //! Choose physical cache capacities within reserved virtual address ranges. use std::collections::HashMap; +use std::num::NonZeroU64; use crate::model::contract::CodecLayout; use flare_selene::{CacheGeometry, Plane, geometry::CodecField}; @@ -31,6 +32,7 @@ const ASYNC_TRANSFER_DEVICE_MARGIN_BYTES: u64 = 256 << 20; /// never exceed the device page-table headroom reserved for them. pub(super) struct PlannedHostBudgets { pub offload_host: Option, + pub max_sequence_pages: NonZeroU64, pub async_transfer_host_caps: Vec, } @@ -558,6 +560,13 @@ struct PageLimit { maximum: u64, } +fn max_sequence_pages(context: NonZeroU64, page_tokens: usize) -> Result { + let page_tokens = NonZeroU64::new(page_tokens as u64) + .ok_or_else(|| invalid("model requires a positive cache page size"))?; + Ok(NonZeroU64::new(context.get().div_ceil(page_tokens.get())) + .expect("positive context divided by positive page size is non-zero")) +} + fn page_ceiling( mode: KvCacheLimit, context: u64, @@ -663,6 +672,11 @@ fn planned_host_future(offload_host: u64, input_window: u64, source_window: u64) .ok_or_else(|| invalid("CPU image input windows overflow host memory")) } +/// Effective chain page count for pool-only host capture sizing. +fn capture_chain_pages(pages: u64, max_sequence_pages: NonZeroU64) -> u64 { + pages.min(max_sequence_pages.get()) +} + /// Additional per-GPU cost above the capture buffer reserved before pool registration. fn capture_growth( layout: &flare_selene::Layout, @@ -989,10 +1003,13 @@ impl NativeModel { .find(|buffer| buffer.name == name) .map(|buffer| buffer.nbytes) })?; - let context = self.server_config["max_sequence_tokens"] + let context_limit = self.server_config["max_sequence_tokens"] .as_u64() + .and_then(NonZeroU64::new) .ok_or_else(|| invalid("model requires a prepared context ceiling"))?; + let context = context_limit.get(); let ceiling = page_ceiling(options.kv_cache_limit, context, active as u64, &contract)?; + let max_sequence_pages = max_sequence_pages(context_limit, contract.cache.page_tokens)?; let minimum_pages = ceiling.map_or(active as u64 * 8192u64.div_ceil(page_tokens), |limit| limit.minimum); let capture = options.prefix_cache.pool_only() && self.cluster().is_none(); let cfg = &options.prefix_cache; @@ -1126,6 +1143,7 @@ impl NativeModel { input_staging: staging, shard: self.cluster().map(|cluster| (cluster.rank, cluster.world)), integrated: integrated > 0, + max_sequence_pages: Some(max_sequence_pages), }, capture.then_some(minimum_pages), initial_budget, @@ -1481,7 +1499,7 @@ impl NativeModel { return Some(0); }; let shared = if self.ranks[rank].integrated { integrated } else { 0 }; - capture_growth(layout, pages, tier_host, host_growth, shared) + capture_growth(layout, capture_chain_pages(pages, max_sequence_pages), tier_host, host_growth, shared) }, )?; // Fewer pages only shrink KV, and fewer rows only the snapshot slots aliased into it, so @@ -1547,7 +1565,7 @@ impl NativeModel { } let planned_offload_host = if capture { let layout = capture_layout.as_ref().unwrap(); - let chain_bytes = pages + let chain_bytes = capture_chain_pages(pages, max_sequence_pages) .saturating_add(layout.row_slots() as u64) .saturating_mul(layout.page_record_bytes); Some(tier_host.max(chain_bytes)) @@ -1585,6 +1603,7 @@ impl NativeModel { } Ok(PlannedHostBudgets { offload_host: planned_offload_host, + max_sequence_pages, async_transfer_host_caps, }) } @@ -2025,6 +2044,7 @@ mod tests { input_staging: 0, shard: None, integrated: true, + max_sequence_pages: None, }; let disk_only = crate::offload::PrefixCacheOffload { memory_bytes: Some(0), @@ -2433,6 +2453,42 @@ mod tests { assert_eq!(pages, 131); } + #[test] + fn pool_capture_growth_caps_at_max_sequence_pages_without_throttling_gpu_pages() { + assert!(max_sequence_pages(NonZeroU64::new(1024).unwrap(), 0).is_err()); + assert_eq!( + max_sequence_pages(NonZeroU64::new(1025).unwrap(), 64) + .unwrap() + .get(), + 17 + ); + assert_eq!( + max_sequence_pages(NonZeroU64::new(1_048_576).unwrap(), 64) + .unwrap() + .get(), + 16_384 + ); + let layout = + flare_selene::Layout::new(&[flare_selene::testing::geometry(64, &[("kv", 4096)], 4096)]) + .unwrap(); + let max_pages = NonZeroU64::new(128).unwrap(); + let reserved = (max_pages.get() + layout.row_slots() as u64) * layout.page_record_bytes; + assert_eq!(capture_growth(&layout, 512, reserved, 0, 1), None); + assert_eq!( + capture_growth(&layout, capture_chain_pages(512, max_pages), reserved, 0, 1), + Some(0) + ); + let cores = [core(4096, 4096, 1024)]; + let (_, uncapped_pages, _) = + capacities(&cores, &[1 << 30], 1, 1, 64, None, |_, _| Some(0)).unwrap(); + let (_, pages, _) = capacities(&cores, &[1 << 30], 1, 1, 64, None, |_, pages| { + capture_growth(&layout, capture_chain_pages(pages, max_pages), reserved, 0, 1) + }) + .unwrap(); + assert_eq!(pages, uncapped_pages); + assert!(pages > max_pages.get()); + } + #[test] fn lower_concurrency_and_verification_move_physical_budget_to_kv() { let p = [core(100 << 20, 2 << 20, 100000)]; diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index 6dcffc45c..be77bf7dc 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -16,7 +16,7 @@ use super::{ }; use crate::{Result, execution::ExecutionManifest, startup::StartupProgress}; use blake2::{Blake2b, Digest, digest::consts::U32}; -use std::{collections::HashSet, thread}; +use std::{collections::HashSet, num::NonZeroU64, thread}; pub struct NativeModel { pub(super) ranks: Vec, @@ -1044,7 +1044,13 @@ impl NativeModel { &initial, embedding_host_bytes, )?; - model.prepare_offload(options, progress, active, planned.offload_host)?; + model.prepare_offload( + options, + progress, + active, + planned.offload_host, + planned.max_sequence_pages, + )?; model.prepare_async_transfers( &files, &cores, @@ -1116,6 +1122,7 @@ impl NativeModel { progress: &StartupProgress, max_active: usize, planned_host_budget: Option, + max_sequence_pages: NonZeroU64, ) -> Result<()> { if !options.prefix_cache.enabled() { return Ok(()); @@ -1162,6 +1169,7 @@ impl NativeModel { input_staging: staging, shard, integrated, + max_sequence_pages: Some(max_sequence_pages), }, planned_host_budget, |step| phase.detail(step), @@ -1551,7 +1559,7 @@ mod tests { ..Default::default() }; unsafe { - model.prepare_offload(&options, &progress, 1, None).unwrap(); + model.prepare_offload(&options, &progress, 1, None, NonZeroU64::MIN).unwrap(); } assert!(model.offload.shared().is_none()); } @@ -1562,7 +1570,8 @@ mod tests { }, ..Default::default() }; - let error = unsafe { model.prepare_offload(&options, &progress, 1, None) }.unwrap_err(); + let error = + unsafe { model.prepare_offload(&options, &progress, 1, None, NonZeroU64::MIN) }.unwrap_err(); assert!(error.to_string().contains("lacks an identity")); } diff --git a/selene-manager/tests/client.rs b/selene-manager/tests/client.rs index b26a24459..fa1b807eb 100644 --- a/selene-manager/tests/client.rs +++ b/selene-manager/tests/client.rs @@ -3252,6 +3252,7 @@ fn offload_startup_and_restore_cover_every_tier_combination() { input_staging: 0, shard: None, integrated: false, + max_sequence_pages: None, }, registrar.as_ref(), ) @@ -3505,6 +3506,7 @@ fn prepared_pool_store_with_geometry( input_staging: 0, shard: None, integrated: false, + max_sequence_pages: None, }, &OkRegistrar, ) diff --git a/selene-manager/tests/offload.rs b/selene-manager/tests/offload.rs index 92680554f..c8628d236 100644 --- a/selene-manager/tests/offload.rs +++ b/selene-manager/tests/offload.rs @@ -136,6 +136,7 @@ fn startup_keeps_registration_through_attachment_and_store_drain() { input_staging: 0, shard: None, integrated: false, + max_sequence_pages: None, }, &flare_selene::testing::IdentityRegistrar, ) diff --git a/selene/src/offload.rs b/selene/src/offload.rs index 835ab9563..e2ae18c35 100644 --- a/selene/src/offload.rs +++ b/selene/src/offload.rs @@ -11,6 +11,7 @@ use crate::{ pool, pool::PoolOptions, record, shard, slab, }; use std::{ + num::NonZeroU64, path::PathBuf, time::{Duration, Instant}, }; @@ -162,7 +163,10 @@ impl PrefixCacheOffload { let disk = self.disk_enabled(); let capture = local_pages.filter(|_| self.pool_only()); let intake = if let Some(pages) = capture { - let chain = pages + let chain_pages = inputs + .max_sequence_pages + .map_or(pages, |limit| pages.min(limit.get())); + let chain = chain_pages .checked_add(layout.row_slots() as u64) .ok_or("pool capture slot count overflow")?; let budget = match budget_override { @@ -336,6 +340,10 @@ pub struct PrepareInputs { /// Whether any local rank's device reports integrated memory (`CU_DEVICE_ATTRIBUTE_INTEGRATED`); /// bounds disk-only intake on shared-memory GPUs. pub integrated: bool, + /// Optional single-sequence page ceiling (`max_sequence_tokens.div_ceil(page_tokens)`). + /// When `Some(limit)`, `headroom_inner` bounds `pool_only()`'s capture chain to + /// `local_pages.min(limit.get())` because no single sequence chain exceeds `limit` pages. + pub max_sequence_pages: Option, } /// Elapsed durations for host prefix-cache startup sub-steps. @@ -617,6 +625,7 @@ pub fn prepare_with_inputs_budget_with_progress( input_staging, shard, integrated, + .. } = inputs; options.validate_compression()?; if !options.enabled() { diff --git a/selene/src/offload/sharded/tests.rs b/selene/src/offload/sharded/tests.rs index 7c820ba5c..eb8322c59 100644 --- a/selene/src/offload/sharded/tests.rs +++ b/selene/src/offload/sharded/tests.rs @@ -115,6 +115,7 @@ fn sharded_export_and_restore_use_each_ranks_real_record_file() { input_staging: 0, shard: Some((rank, 2)), integrated: false, + max_sequence_pages: None, }, &IdentityRegistrar, ) @@ -257,6 +258,7 @@ fn sharded_join_rejects_mismatched_compression_modes() { input_staging: 0, shard: Some((rank, 2)), integrated: false, + max_sequence_pages: None, }, &IdentityRegistrar, ) @@ -387,6 +389,7 @@ fn sharded_compressed_v4_store_fetch_truncate_and_restart_agree() { input_staging: 0, shard: Some((rank, 2)), integrated: false, + max_sequence_pages: None, }, &IdentityRegistrar, ) @@ -552,6 +555,7 @@ fn sharded_pool_with_compression_rejected_at_startup() { input_staging: 0, shard: Some((0, 2)), integrated: false, + max_sequence_pages: None, }, &IdentityRegistrar, ) diff --git a/selene/src/offload/tests.rs b/selene/src/offload/tests.rs index 8e657290d..bce14f021 100644 --- a/selene/src/offload/tests.rs +++ b/selene/src/offload/tests.rs @@ -11,6 +11,7 @@ fn inputs(max_active: usize) -> PrepareInputs { input_staging: 0, shard: None, integrated: false, + max_sequence_pages: None, } } @@ -47,6 +48,7 @@ fn prepare_with_inputs( input_staging, shard, integrated: false, + max_sequence_pages: None, }, &crate::testing::IdentityRegistrar, ) @@ -526,24 +528,36 @@ fn pool_only_sizes_registered_capture_and_headroom_for_local_ranks() { pool: Some(pool("unix:/run/selene.sock")), ..Default::default() }; - for pages in [10, 512] { + for (pages, max_sequence_pages) in [ + (10, None), + (512, None), + (512, std::num::NonZeroU64::new(64)), + ] { let mut ranks = vec![crate::testing::geometry(64, &[("kv", 4096)], 8192); 2]; ranks[0].page_capacity = 8; ranks[1].page_capacity = pages; let registrar = crate::testing::TrackingRegistrar::default(); + let test_inputs = PrepareInputs { + max_sequence_pages, + ..inputs(4) + }; let Preparation::Store(prepared) = super::prepare_with_inputs( &options, [0; 32], ranks, vec![(0, 0), (1, 1)], - inputs(4), + test_inputs, ®istrar, ) .unwrap() else { panic!("missing capture buffer"); }; let layout = &prepared.layout; - let slots = intake_slots(layout, 4).max(pages as usize + layout.row_slots()); + let chain_pages = max_sequence_pages.map_or(pages, |limit| pages.min(limit.get())); + let slots = intake_slots(layout, 4).max(chain_pages as usize + layout.row_slots()); + if max_sequence_pages.is_some() { + assert!(slots < intake_slots(layout, 4).max(pages as usize + layout.row_slots())); + } let bytes = slots as u64 * layout.page_record_bytes; let buffer = prepared.memory_pool.as_ref().unwrap(); assert_eq!((buffer.slot_count(), buffer.intake_slots()), (slots, 0)); @@ -554,7 +568,7 @@ fn pool_only_sizes_registered_capture_and_headroom_for_local_ranks() { assert!(prepared.summary().contains(&format!("pool only: capture buffer {}", gibibytes(bytes)))); assert_eq!( options - .headroom_with_inputs(2, layout, inputs(4), Some(pages)) + .headroom_with_inputs(2, layout, test_inputs, Some(pages)) .unwrap(), (2 * STORE_DEVICE_MARGIN_BYTES + bytes.div_ceil(512), bytes) );