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
65 changes: 43 additions & 22 deletions docs/runtime-core-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,28 +699,49 @@ Before CUDA initialization or serving worker threads, Flare restricts
`CUDA_VISIBLE_DEVICES` to `--gpus`, resolving indices within an inherited mask.

When a core declares `Capacity::DEVICE_POOL` allocations and
`Execution.async_transfers` channels, `allocate_caches` first reserves
`pinned_bytes.div_ceil(512) + 256 MiB` of VRAM per rank for `cuMemHostRegister_v2`
GPU MMU page tables and worker streams (covering each channel's planned pinned
`HOST_POOL` and bounded internal bounce pool, which is disabled when channel
alignment exceeds 32 MiB), then sizes and maps each `DEVICE_POOL` at its fixed
reserved CUDA virtual address before computing KV page capacity (leaving space
for execution state rows and the minimum KV cache requirement, bounded by
`--pool-vram-memory` / `[memory] pool_vram`). Across tensor-parallel ranks,
`DEVICE_POOL` physical byte capacity is agreed as the minimum across ranks, and
`Execution.buffers` views backed by that allocation are rewritten to
`floor(agreed_bytes / row_bytes)` leading rows (truncating any partial trailing
row). `NativeResources::prepare_async_transfers` authenticates and opens the
4 KiB-aligned `RankBody.external_extents` payload segments directly (`O_DIRECT`
on Linux), allocates each channel's runtime-sized pinned `HOST_POOL` (clamped to
the planned per-rank host ceiling from `allocate_caches`, with an internal
pinned bounce pool when enabled), writes immutable startup geometry into the
mapped-host `ControlHeader`, and starts the channel workers before executing
`Execution.tuning_graphs`. Shutdown stops and drains all async transfer
channels after compute streams drain and before unmapping device or mapped-host
storage; unconfirmed drain transitions the channel to `FailedDrain` and retains
pinned memory and CUDA handles until process exit. Cores without
`Execution.async_transfers` channels bypass this path completely.
`Execution.async_transfers` channels, `NativeModel` rejects cores whose graphs
also contain Copy Engine `Memory::Peer` copy nodes at load time, preventing
unbounded Copy Engine deadlocks when in-graph demand transfers cannot yield to
`CopyEngineGate`. During `allocate_caches`, discrete-GPU ranks reserve host RAM
after subtracting planned prefix-cache offload and vision input windows
(`host_future`), reserve `pinned_bytes.div_ceil(512) + 256 MiB` of VRAM per
rank for `cuMemHostRegister_v2` GPU MMU page tables and worker streams
(covering each channel's planned pinned `HOST_POOL` and bounded internal bounce
pool, which is disabled when channel alignment exceeds 32 MiB), and deduct the
pinned host reservation from prefix-cache capture growth. On integrated
unified-DRAM GPUs (such as GB10 and Jetson), `HOST_POOL`, `bounce_pool`,
`DEVICE_POOL`, and KV caches draw from the same physical DRAM: `HOST_POOL`
defaults to zero unless `--pool-ram-memory` is explicitly configured, explicit
host-pool limits are bounded above the minimum KV cache requirement, and the
full `pinned_bytes + pinned_bytes.div_ceil(512) + 256 MiB` is deducted from the
unified cache budget before sizing `DEVICE_POOL`. Helios then sizes each
`DEVICE_POOL` (leaving room for execution state rows and the minimum KV cache
requirement, bounded by `--pool-vram-memory` / `[memory] pool_vram`), agrees on
the elementwise minimum across local ranks and across multi-host cluster ranks
through `CacheAgreement::device_pools`, maps each pool at its fixed reserved
CUDA virtual address, and rewrites `Execution.buffers` views backed by that
allocation to `floor(agreed_bytes / row_bytes)` leading rows (truncating any
partial trailing row). `NativeResources::prepare_async_transfers` authenticates
and opens the 4 KiB-aligned `RankBody.external_extents` payload segments
directly (`O_DIRECT` on Linux), allocates each channel's runtime-sized pinned
`HOST_POOL` (clamped to the planned per-rank host ceiling from
`allocate_caches`, with an internal pinned bounce pool when enabled), writes
immutable startup geometry into the mapped-host `ControlHeader`, and blocks in
`start()` until each channel worker binds its CUDA context, allocates its event
pool, and publishes `ControlHeader.worker_state = Running` before executing
`Execution.tuning_graphs`. All device completion writes serialize on the
channel's single Copy Engine stream, host completion mirrors advance
monotonically via `fetch_max`, and storage or CUDA transfer failures publish
the bit-63 fault sentinel (`COMPLETION_ERROR_BIT | error_code`) rather than the
caller's requested success cookie. Partial DMA submission failures after
`cuMemcpyHtoDAsync_v2` retain their in-flight and bounce-slot ownership until
hardware stream drain is confirmed. Shutdown stops and drains all async
transfer channels after compute streams drain (bounding Linux `io_uring` waits
with a kernel timespec), invalidates mapped-host control telemetry before
unmapping device or mapped-host storage, and on unconfirmed drain transitions
the channel to `FailedDrain` while retaining pinned memory, storage handles,
and CUDA handles until process exit. Cores without `Execution.async_transfers`
channels bypass this path completely.
When omitted, the list contains the first N visible GPUs for the core's N
local ranks, or one GPU per host for a multi-host core. Core loading finishes
its progress threads before setting visibility. Hub revision detection queries
Expand Down
26 changes: 26 additions & 0 deletions flare-cli/src/cluster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,14 @@ impl flare_helios::runtime_core::CacheAgreement for Membership {
}
}

fn device_pools(&mut self, local: &[u64]) -> flare_helios::Result<Vec<u64>> {
use flare_helios::execution::rendezvous;
match self {
Membership::Zero(peers) => rendezvous::agree_device_pools(peers, local),
Membership::Peer(stream) => rendezvous::propose_device_pools(stream, local),
}
}

fn pool(
&mut self,
offer: flare_helios::offload::shard::PoolOffer,
Expand Down Expand Up @@ -309,6 +317,24 @@ mod pool_tests {
assert_eq!(zero.join().unwrap(), peer_approved);
}
}

#[test]
fn device_pools_agreement_exchanges_cluster_minimum() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let peer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let zero = listener.accept().unwrap().0;
let zero_handle = std::thread::spawn(move || {
Membership::Zero(vec![RankStream::Tcp(zero)])
.device_pools(&[80 << 30, 16 << 30])
.unwrap()
});
let peer_agreed = Membership::Peer(RankStream::Tcp(peer))
.device_pools(&[64 << 30, 24 << 30])
.unwrap();
let expected = vec![64 << 30, 16 << 30];
assert_eq!(peer_agreed, expected);
assert_eq!(zero_handle.join().unwrap(), expected);
}
}

#[cfg(all(
Expand Down
35 changes: 24 additions & 11 deletions helios/manifest.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,13 @@ Each `AsyncTransfer` entry declares:
completion words.
- `device_completions` (optional): 8-byte-aligned `Reference` inside a fixed
`Memory::Device` allocation holding `completion_slots` 64-bit completion
words written in stream order by `cuStreamWriteValue64_v2` (when device
attribute `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is
supported) after Copy Engine DMA completes.
words written in stream order on the channel's single Copy Engine stream by
`cuStreamWriteValue64_v2` (when device attribute
`CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is supported) after
Copy Engine DMA completes, with monotonic `fetch_max` host completion mirrors
so deferred DMA mirrors cannot regress reused completion slots.
- `max_host_pool_bytes`: optional ceiling on the channel's pinned host pool
(`0` allows up to the runtime `--pool-ram-memory` budget).
(`0` disables the host pool).
- `alignment`: power-of-two direct-I/O and offset alignment (`>= 4096`).

Supported command opcodes are `DISK_TO_HOST` (`1`), `HOST_TO_DEV` (`2`),
Expand All @@ -190,13 +192,24 @@ Supported command opcodes are `DISK_TO_HOST` (`1`), `HOST_TO_DEV` (`2`),
`CANCEL_EPOCH` (`4`). Priorities `DEMAND` (`0`), `PREFETCH` (`1`), and `WARM`
(`2`) feed a preemptible host queue with bounded background I/O and DMA depth;
`CANCEL_EPOCH` and `ControlHeader.active_epoch` drop queued non-demand commands
from older epochs while preserving `DEMAND`. Helios starts prepared channels
before launching `Execution.tuning_graphs` so startup tuning kernels can read
`device_pool_bytes` and `host_pool_bytes` from `ControlHeader` and partition or
pre-warm pools. Teardown drains serving streams, cancels queued background
transfers, drains in-flight storage I/O and the Copy Engine stream within a
bounded timeout, and retains pinned host memory and CUDA handles until process
exit if drain is not confirmed.
from older epochs while preserving `DEMAND`. Caller-supplied `signal_value`
cookies occupy the lower 63 bits (`(signal_value & (1 << 63)) == 0`); bit 63
(`COMPLETION_ERROR_BIT`) is reserved for fault sentinels
(`COMPLETION_ERROR_BIT | error_code`) emitted on `IoFailure` or `CudaFailure`
instead of the requested success value. Helios waits for each channel worker to
bind its CUDA context, create its event pool, and publish
`ControlHeader.worker_state = Running` before launching
`Execution.tuning_graphs` so startup tuning kernels read populated
`device_pool_bytes` and `host_pool_bytes` from `ControlHeader` and observe a
live channel. Cores that combine `Execution.async_transfers` with graphs
containing Copy Engine `Memory::Peer` copy nodes are rejected at load time,
because in-graph demand waits cannot serialize behind `CopyEngineGate` without
deadlocking the Copy Engine. Teardown drains serving streams, cancels queued
background transfers, drains in-flight storage I/O (bounded by a kernel timespec
on `io_uring`) and the Copy Engine stream within a bounded timeout, invalidates
mapped-host control telemetry before unmapping allocations, and retains pinned
host memory, storage handles, and CUDA handles until process exit if drain is
not confirmed.

Helios implements no model-specific routing, eviction, prefetch policy, or
cache directory layout inside `AsyncTransfer`; captured graphs own all slot
Expand Down
91 changes: 89 additions & 2 deletions helios/src/async_transfer/io_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ pub mod linux_uring {
self.queued_sqes += 1;
Ok(())
}

#[cfg(test)]
pub(super) fn insert_synthetic_inflight_for_test(&mut self, op_id: OpId, nbytes: u64) {
self.expected.insert(op_id, nbytes);
}
}

impl IoBackend for IoUringBackend {
Expand Down Expand Up @@ -201,10 +206,33 @@ pub mod linux_uring {
if self.expected.is_empty() {
break;
}
if Instant::now() >= deadline {
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
return false;
};
if remaining.is_zero() {
return false;
}
let _ = self.ring.submit_and_wait(1);
let ts = types::Timespec::from(remaining);
let args = types::SubmitArgs::new().timespec(&ts);
match self.ring.submitter().submit_with_args(1, &args) {
Ok(_) => {}
Err(err) if err.raw_os_error() == Some(libc::ETIME) => {
let _ = self.poll_completions(out);
return self.expected.is_empty();
}
Err(err) if err.raw_os_error() == Some(libc::EINTR) => continue,
Err(_) => {
let _ = self.ring.submit();
let _ = self.poll_completions(out);
if self.expected.is_empty() {
break;
}
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
return false;
};
std::thread::sleep(Duration::from_millis(1).min(left));
}
}
}
true
}
Expand Down Expand Up @@ -290,3 +318,62 @@ pub fn from_direct_files(files: Vec<File>) -> io::Result<Box<dyn IoBackend>> {
Ok(Box::new(PreadBackend::new(files)))
}
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::{IoBackend, IoCompletion, linux_uring::IoUringBackend};
use std::{
fs::File,
os::fd::FromRawFd,
time::{Duration, Instant},
};

#[test]
fn uring_cancel_and_drain_bounds_wait_with_timespec() {
let mut pipe_fds = [0i32; 2];
assert_eq!(unsafe { libc::pipe(pipe_fds.as_mut_ptr()) }, 0);
let read_end = unsafe { File::from_raw_fd(pipe_fds[0]) };
let write_end = unsafe { File::from_raw_fd(pipe_fds[1]) };

let mut pipe_backend = IoUringBackend::new(vec![read_end]).expect("create pipe io_uring");
let mut buf = [0u8; 64];
unsafe {
pipe_backend
.submit_read(7, 0, 0, buf.as_mut_ptr(), 64)
.expect("submit pipe read");
}
pipe_backend.flush().expect("flush pipe read");
let mut out: Vec<IoCompletion> = Vec::new();
let start = Instant::now();
// Cancelable pipe read must drain promptly and return true.
assert!(pipe_backend.cancel_and_drain(Duration::from_secs(1), &mut out));
assert!(start.elapsed() < Duration::from_secs(1));
assert_eq!(pipe_backend.in_flight(), 0);
assert_eq!(out.len(), 1);
assert_eq!(out[0].op_id, 7);
assert!(!out[0].ok);
drop(write_end);

// Verify timeout expiry via submit_with_args + Timespec when an expected op never
// completes (AsyncCancel emits -ENOENT with user_data 0, then wait hits ETIME).
let mut uncompletable_fds = [0i32; 2];
assert_eq!(unsafe { libc::pipe(uncompletable_fds.as_mut_ptr()) }, 0);
let r2 = unsafe { File::from_raw_fd(uncompletable_fds[0]) };
let w2 = unsafe { File::from_raw_fd(uncompletable_fds[1]) };
let mut stuck = IoUringBackend::new(vec![r2]).expect("create second io_uring");
stuck.insert_synthetic_inflight_for_test(99, 64);
out.clear();
let timeout = Duration::from_millis(50);
let t0 = Instant::now();
let drained = stuck.cancel_and_drain(timeout, &mut out);
let elapsed = t0.elapsed();
assert!(!drained, "uncompleted op must return false on drain timeout");
assert!(
elapsed >= Duration::from_millis(35) && elapsed < Duration::from_secs(1),
"cancel_and_drain elapsed {:?} outside bounded timeout window",
elapsed
);
assert_eq!(stuck.in_flight(), 1);
drop(w2);
}
}
27 changes: 22 additions & 5 deletions helios/src/async_transfer/kani_proofs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
//! and command bounds/alignment validators.
use super::ring::{
BOUNCE_HOST_OFFSET, COMMAND_BYTES, ErrorCode, ExtentEntry, HEADER_BYTES, MAX_RING_CAPACITY,
MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority, TransferCommand,
ValidatedCommand, resolve_pool_bytes, validate_command, validate_control_layout,
validate_extent_entry,
BOUNCE_HOST_OFFSET, COMMAND_BYTES, COMPLETION_ERROR_BIT, ErrorCode, ExtentEntry, HEADER_BYTES,
MAX_RING_CAPACITY, MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority,
TransferCommand, ValidatedCommand, completion_error_sentinel, resolve_pool_bytes,
validate_command, validate_control_layout, validate_extent_entry,
};

#[kani::proof]
Expand Down Expand Up @@ -136,11 +136,22 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
bounce_slot_bytes,
) {
Ok(ValidatedCommand::CancelEpoch {
completion_slot, ..
completion_slot,
signal_value,
..
}) => {
assert_eq!(cmd.opcode, Opcode::CancelEpoch as u32);
if let Some(slot) = completion_slot {
assert!(slot < completion_slots);
assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0);
assert_ne!(
signal_value,
completion_error_sentinel(ErrorCode::IoFailure)
);
assert_ne!(
signal_value,
completion_error_sentinel(ErrorCode::CudaFailure)
);
} else {
assert_eq!(cmd.completion_slot, NO_COMPLETION_SLOT);
}
Expand All @@ -150,6 +161,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
extent,
host_offset,
completion_slot,
signal_value,
..
}) => {
assert_eq!(cmd.opcode, Opcode::DiskToHost as u32);
Expand All @@ -162,6 +174,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
assert!((host_offset as u128) + (extent.nbytes as u128) <= (host_pool_bytes as u128));
if let Some(slot) = completion_slot {
assert!(slot < completion_slots);
assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0);
}
}
Ok(ValidatedCommand::HostToDev {
Expand All @@ -170,6 +183,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
device_offset,
nbytes,
completion_slot,
signal_value,
..
}) => {
assert_eq!(cmd.opcode, Opcode::HostToDev as u32);
Expand All @@ -179,6 +193,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
assert!((device_offset as u128) + (nbytes as u128) <= (device_pool_bytes as u128));
if let Some(slot) = completion_slot {
assert!(slot < completion_slots);
assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0);
}
}
Ok(ValidatedCommand::DiskToDev {
Expand All @@ -187,6 +202,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
host_offset,
device_offset,
completion_slot,
signal_value,
..
}) => {
assert_eq!(cmd.opcode, Opcode::DiskToDev as u32);
Expand All @@ -208,6 +224,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() {
assert!((device_offset as u128) + (extent.nbytes as u128) <= (device_pool_bytes as u128));
if let Some(slot) = completion_slot {
assert!(slot < completion_slots);
assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0);
}
}
Err(code) => {
Expand Down
Loading
Loading