Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions docs/prefix-cache-offload.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,15 @@ tier: `--prefix-cache-memory`, `--prefix-cache-disk`, or `--prefix-cache-pool`):
predictor, 4-lane bit packing, 32-way warp-interleaved 12-bit static rANS,
on-GPU packet assembly, and parallel GPU CRC32 directly on each rank's
lowest-priority CUDA transfer stream using a compact 3-buffer aliased
per-rank GPU workspace budgeted before KV cache sizing. Only compressed bytes
cross PCIe during capture and GPU-decoded restores, while small non-matrix
restores (< 256 KiB) or mutex-contended restores decode on the bounded CPU
worker pool over async HtoD DMA, with zero external runtime libraries beyond
`libcuda.so.1`.
per-rank GPU workspace budgeted before KV cache sizing. On cores that declare
a persistent worker, Helios reserves a third disjoint CUDA Green Context SM
partition for GPU codec execution so codec kernels never share SMs with
cooperative compute graphs, and opens the host prefix store (calling
`cuModuleLoadData`) before starting the persistent worker graph. Only
compressed bytes cross PCIe during capture and GPU-decoded restores, while
small non-matrix restores (< 256 KiB) or mutex-contended restores decode on
the bounded CPU worker pool over async HtoD DMA, with zero external runtime
libraries beyond `libcuda.so.1`.

Both modes compress at the VRAM-to-DRAM boundary and keep compressed bytes
across local DRAM (`MemoryStore`), local disk (`DiskStore`, standalone or
Expand All @@ -82,10 +86,12 @@ emit a standard raw v3 file). Shared-memory, TCP, and RDMA readers advertising
a matching profile can claim packed records from both manager DRAM and NVMe.

Both `cpu` and `gpu` modes advertise `[ZKV1, GKV1]` receive profiles across
single-process local tiers, single-process `selene-manager` pools, and
standalone multi-host `--rank` local disk (the profile handshake rejects
mismatched rank modes at startup, and multi-host `--rank` +
`--prefix-cache-pool` rejects active compression at startup):
single-process local tiers, single-process `selene-manager` pools (including
single-host TP>=2), and standalone multi-host `--rank` local disk (the profile
handshake rejects mismatched rank modes at startup, and multi-host `--rank` +
`--prefix-cache-pool` rejects active compression at startup while
`selene-manager` negotiates raw-only and excludes packed records for
multi-process sessions):

- In `gpu` mode, new captures encode on GPU as `GKV1`, matrix-predictor and
large-page (>= 256 KiB) `GKV1` restores decode on GPU (falling back to the
Expand Down
64 changes: 38 additions & 26 deletions docs/runtime-core-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -644,32 +644,44 @@ When a single-rank core declares an entry in `Execution.persistent_workers`
multi-host cluster cores declaring a persistent worker are rejected),
`NativeResources` resolves the CUDA driver Green Context entrypoints optionally
at driver load (failing load explicitly only when a core requires them on an
unsupported driver), retains the device's primary context, partitions device
SMs with `cuDevSmResourceSplit` into two explicit structured SM resource groups
(a worker green context aligned to the device's co-scheduled SM alignment and a
compute green context preserving co-scheduled SM alignment for multi-CTA
cluster launches), applies the core's recorded CUDA context limits and cache
configuration to the primary context and both green contexts, and opens
non-blocking streams for each. All modules, kernels, and graph executables are
loaded, instantiated under their partition's green context (clamping
cooperative grids to that partition's SM count), and uploaded on their
partition's non-blocking stream before the persistent worker starts; the
executor launches the worker graph once on its worker stream only after startup
completes, while compute graphs replay on the compute green context. When the
entry also declares an optional mapped-host `metrics` reference with positive
`metrics_count`, Helios validates that the range is 8-byte aligned and in bounds
for `metrics_count` 64-bit counters and exposes read-only atomic snapshots of
worker state and counter values to Prometheus `/metrics`, `GET /v1/worker`, and
the serving dashboard without synchronizing GPU streams. Shutdown
drains compute and copy streams first, writes `1u32` (release) to the
mapped-host `stop_flag` reference, and polls `cuStreamQuery` on the worker
stream against a bounded drain timeout with context save/restore (returning
`ExecutionError::Drain` and retaining GPU resources on timeout). Resource
teardown stops any still-running worker, synchronizes the primary context,
drains active telemetry counter readers before unmapping allocations, and
only after context synchronization succeeds destroys worker and compute
streams, executables, modules, mappings, green contexts, virtual-address
reservations, and the primary context.
unsupported driver), retains the device's primary context, and partitions device
SMs with `cuDevSmResourceSplit` into disjoint structured SM resource groups:
two groups (a `worker` green context aligned to the device's co-scheduled SM
alignment and a `compute` backfill green context preserving co-scheduled SM
alignment for multi-CTA cluster launches) when prefix-cache offload does not use
GPU compression, or three groups (`worker`, one minimal aligned `codec` green
context, and `compute` backfill) when prefix-cache offload is enabled with
`--lossless-kv-compression gpu` (failing load explicitly if remaining SMs cannot
form a structured compute partition). Helios applies the core's recorded CUDA
context limits and cache configuration to the primary context and every created
green context (`worker`, `compute`, and `codec` when present), and opens
non-blocking streams for the worker and compute contexts. Offload transfers and
GPU KV-codec kernels bind the `codec` green context when present and the rank's
base context otherwise, while host slab registration remains portable
(`CU_MEMHOSTREGISTER_PORTABLE`) on the base context. All modules, kernels, graph
executables, and host prefix-store GPU codec modules are loaded, instantiated
under their partition's green context (clamping cooperative grids to that
partition's SM count), and uploaded on their partition's non-blocking stream
before the persistent worker starts; `ModelRuntime` opens the host prefix store
before constructing `RankExecutor` so `cuModuleLoadData` for embedded GPU codec
kernels finishes before any worker graph launches. The executor launches the
worker graph once on its worker stream only after startup completes, while
compute graphs replay on the compute green context. When the entry also declares
an optional mapped-host `metrics` reference with positive `metrics_count`,
Helios validates that the range is 8-byte aligned and in bounds for
`metrics_count` 64-bit counters and exposes read-only atomic snapshots of worker
state and counter values to Prometheus `/metrics`, `GET /v1/worker`, and the
serving dashboard without synchronizing GPU streams. Shutdown drains compute and
copy streams first, writes `1u32` (release) to the mapped-host `stop_flag`
reference, and polls `cuStreamQuery` on the worker stream against a bounded
drain timeout with context save/restore (returning `ExecutionError::Drain` and
retaining GPU resources on timeout). Resource teardown stops any still-running
worker, synchronizes the primary context, drains active telemetry counter
readers before unmapping allocations, and only after context synchronization
succeeds destroys worker and compute streams, executables, modules, mappings,
all created green contexts (worker, compute, and optional codec, clearing rather
than restoring the caller's current context if it referred to any destroyed
green context), virtual-address reservations, and the primary context.

Before CUDA initialization or serving worker threads, Flare restricts
`CUDA_VISIBLE_DEVICES` to `--gpus`, resolving indices within an inherited mask.
Expand Down
2 changes: 2 additions & 0 deletions helios/src/offload/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub(crate) mod pool;
mod registrar;
pub mod shard;
pub mod transfer;
#[cfg(test)]
pub(crate) use transfer::GpuRankCodec;

pub use copy_gate::{CopyEngineGate, PeerGraphGuard, PeerGraphLeases};

Expand Down
2 changes: 2 additions & 0 deletions helios/src/offload/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ use flare_selene::{

mod codec;
mod gpu_codec;
#[cfg(test)]
pub(crate) use gpu_codec::GpuRankCodec;
use crate::cuda::{Event, Stream};

pub use crate::cuda::{BATCH_BYTES, BATCH_ENTRIES};
Expand Down
2 changes: 1 addition & 1 deletion helios/src/offload/transfer/gpu_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2664,4 +2664,4 @@ mod imp {
}
}

pub(super) use imp::GpuRankCodec;
pub(crate) use imp::GpuRankCodec;
4 changes: 3 additions & 1 deletion helios/src/runtime_core/event_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ fn disk_cached_and_resident_tables_feed_native_b12x_graphs() {
owner.reserve(&core).unwrap();
owner.allocate(&core, &phase).unwrap();
owner.load_payload(&archive, &core, &phase, 1).unwrap();
owner.prepare_kernels(&archive, &core, &phase, None).unwrap();
owner
.prepare_kernels(&archive, &core, &phase, None, false)
.unwrap();
owner.prepare_graphs(&archive, &core, &phase).unwrap();
}
let failed_source = std::env::temp_dir().join(format!(
Expand Down
2 changes: 1 addition & 1 deletion helios/src/runtime_core/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1007,7 +1007,7 @@ impl NativeModel {
identity: super::model::offload_identity(&self.server_config)?,
geometry: &geometry,
gpu_uuids: uuids,
registration_context: self.ranks[0].execution_context() as usize,
registration_context: self.ranks[0].context as usize,
budget,
peers,
disk: options.prefix_cache.disk.is_some()
Expand Down
32 changes: 28 additions & 4 deletions helios/src/runtime_core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ impl NativeResources {
owner.reserve(&core)?;
owner.allocate(&core, &phase)?;
owner.load_payload(files, &core, &phase, 1)?;
owner.prepare_kernels(files, &core, &phase, None)?;
owner.prepare_kernels(files, &core, &phase, None, false)?;
owner.prepare_graphs(files, &core, &phase)?;
}
phase.finish("");
Expand Down Expand Up @@ -758,6 +758,7 @@ impl NativeResources {
core: &Core,
phase: &Phase,
skip_module: Option<&str>,
reserve_codec_partition: bool,
) -> Result<()> {
let driver = self.driver.clone();
unsafe {
Expand All @@ -774,12 +775,19 @@ impl NativeResources {
&driver,
self.device,
worker.worker_sm_count,
reserve_codec_partition,
)?;
let (worker_context, compute_context) =
(partition.worker_context, partition.compute_context);
let (worker_context, compute_context, codec_context) = (
partition.worker_context,
partition.compute_context,
partition.codec_context,
);
self.green_partition = Some(partition);
apply_context_settings(&driver, worker_context, &core.context)?;
apply_context_settings(&driver, compute_context, &core.context)?;
if !codec_context.is_null() {
apply_context_settings(&driver, codec_context, &core.context)?;
}
}
}
driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?;
Expand Down Expand Up @@ -1405,6 +1413,19 @@ impl NativeResources {
.map_or(self.context, |partition| partition.compute_context)
}

/// CUDA context for host prefix-cache offload streams and GPU codec kernels.
///
/// Persistent-worker cores with GPU compression reserve a disjoint codec green
/// context so codec kernels never contend with cooperative compute SMs. Without
/// a codec partition, offload uses the rank's base context so DMA-only transfers
/// do not bind to the compute green context.
pub(super) fn offload_context(&self) -> Handle {
self.green_partition
.as_ref()
.filter(|partition| !partition.codec_context.is_null())
.map_or(self.context, |partition| partition.codec_context)
}

/// Launch the prepared persistent worker graph once on its green-context worker stream.
/// No-op when the core declares no persistent worker or the worker is already running.
pub fn start_persistent_worker(&self) -> Result<()> {
Expand Down Expand Up @@ -1621,7 +1642,10 @@ impl NativeResources {
}
let mut previous_destroyed = false;
if let Some(mut partition) = self.green_partition.take() {
if previous == partition.worker_context || previous == partition.compute_context {
if previous == partition.worker_context
|| previous == partition.compute_context
|| (!partition.codec_context.is_null() && previous == partition.codec_context)
{
previous_destroyed = true;
}
partition.destroy_green_contexts(&self.driver);
Expand Down
12 changes: 10 additions & 2 deletions helios/src/runtime_core/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -817,8 +817,16 @@ impl NativeModel {
.sum::<u64>();
let modules = cores.iter().map(|p| p.modules.len() as u64).sum::<u64>();
let phase = progress.phase("Prepare kernels", Some(kernels + modules));
let reserve_codec_partition = options.prefix_cache.enabled()
&& options.prefix_cache.compression == crate::offload::KvCompression::Gpu;
model.parallel(&cores, &files, |rank, core, path| {
rank.prepare_kernels(path, core, &phase, codec_gpu_module.as_deref())
rank.prepare_kernels(
path,
core,
&phase,
codec_gpu_module.as_deref(),
reserve_codec_partition,
)
})?;
phase.finish(format!("{kernels} kernels"));
let nodes = cores
Expand Down Expand Up @@ -958,7 +966,7 @@ impl NativeModel {
let contexts: Vec<_> = self
.ranks
.iter()
.map(|rank| (rank.execution_context() as usize, rank.device))
.map(|rank| (rank.offload_context() as usize, rank.device))
.collect();
let contract: crate::model::PreparedContract =
serde_json::from_value(self.server_config["model_contract"].clone())
Expand Down
Loading
Loading