From 60d1b6bdd15735ba4b2b9f92edc71ad3a184f8b8 Mon Sep 17 00:00:00 2001 From: Jason Cook <1637905+original-el8@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:09:32 -0500 Subject: [PATCH] helios: overlap startup allocation, registration, and setup with runtime-sized zero-copy weight loading MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Model startup previously executed memory allocation, weight loading, kernel and graph preparation, cache allocation, host prefix cache setup, and tokenizer loading strictly in series. On large models—especially host-tiered cores that allocate and register hundreds of gigabytes of mapped host memory—the NVMe storage array sat idle during single-threaded host pre-faulting and `cuMemHostRegister_v2`, while the GPU sat idle during host weight reads and subsequent CPU/CUDA setup. In addition, the payload loader used fixed `SLOTS = 4, READERS = 4, CHUNK = 4 MiB` staging (preventing full double-buffering between `pread` and `cuMemcpyHtoDAsync`) and copied every `MappedHost` weight byte through pinned CUDA staging buffers instead of reading 4 KiB-aligned ranges directly into mapped host memory. What changed: - `helios/src/runtime_core/payload.rs`: replaced fixed staging constants with a runtime `IoPlan` (`choose_io_plan`) derived from CPU count, rank count, Linux block-device `optimal_io_size` (with non-Linux fallback), and available host memory, double-buffering `SLOTS = 2 * READERS` within a bounded staging cap (`<= 128 MiB` across ranks). Added zero-copy `O_DIRECT` reads directly into 4 KiB-aligned `MappedHost` ranges (splitting matching-alignment spans into staged edges and direct interior chunks), separated CUDA-free host payload loading (`load_mapped_host_chunks`) from device payload loading (`load_device`), and added `RegistrationGate` to coordinate chunked host pinning with host `O_DIRECT` readers. - `helios/src/runtime_core/mod.rs` and `helios/src/runtime_core/format.rs`: split `allocate()` into device allocation (`allocate_device`) and coalesced/THP-hinted mapped-host VMA preparation with ordered multi-threaded 2 MiB pre-faulting (`prepare_mapped_host_vmas`, holding no CUDA context locks) so host VMA setup overlaps with device weight uploads. Pipelined `cuMemHostRegister_v2` in `512 MiB`-aligned chunks via `register_pending_mapped_host` (tracked in `host_mmap_spans` and `host_registrations` separately from `host_vmm` `host_mappings`) so host pinning never contends with `cuMemcpyHtoDAsync` while preserving hugepage alignment boundaries and reverse-order teardown. - `helios/src/runtime_core/model.rs`, `helios/src/startup.rs`, `helios/src/server.rs`, `helios/src/server/config.rs`, and `helios/src/server/session.rs`: overlapped `MappedHost` VMA preparation with device weight loading, overlapped chunked `cuMemHostRegister_v2` followed by kernel, graph, embedding-table, KV cache, and host prefix cache setup with `MappedHost` weight loading (replaying completed phase records cleanly in canonical order via `StartupProgress::replay_completed`), and pre-loaded the frontend tokenizer/template on a background CPU thread keyed by immutable frontend config fields for reuse in `LoadedSession::new`. Claimed benefit and result: Measured cold startup for a 552.1 GiB host-tiered signed core (`240.5 GiB` device + `316.6 GiB` mapped host + `64 GiB` host prefix cache) on a 2x PCIe Gen4x4 NVMe RAID0 (`12.78 GiB/s` measured raw `O_DIRECT` ceiling, `43.2 s` physical I/O floor) dropped from `75.0 s` to `45.5 s` (`-29.5 s` / `-39.3%`), sustaining `12.90–13.00 GiB/s` during weight loading with `94.0 GiB` `AnonHugePages` (up from `91.0 GiB`), identical GPU/KV/prefix-cache budgets, and `0.0 s` critical-path cost for allocation, kernel/graph/cache/prefix-cache preparation, and tokenizer loading. Pure-GPU models retain exact serial post-load GPU memory accounting while gaining runtime-sized double-buffered staging and background tokenizer pre-loading. Supporting evidence and material limitations: Validated with `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib` (1919 passed, 0 failed, 49 ignored), `cargo test --locked --release --manifest-path flare/Cargo.toml` (255 passed, 0 failed, 4 ignored), `cargo test --locked --release --manifest-path flare-cli/Cargo.toml` (250 passed, 0 failed, 3 ignored), targeted `runtime-core` tests covering `IoPlan`, zero-copy aligned/unaligned `MappedHost` reads, `RegistrationGate`, `512 MiB` registration chunks, and ordered `2 MiB` pre-fault slices (6 passed, 0 failed), and `cargo build --release --manifest-path flare-cli/Cargo.toml`. Live cold startup (`75.0 s -> 45.5 s`) and streaming serving output were measured via `flare run` on 1x NVIDIA GB300 (`SM103`) on the equivalent `feat/gb300-tiered-runtime` build prior to rebasing cleanly onto `main`. Material limitations: `host_vmm` (Windows and non-identity-mapped Linux GPUs), integrated-GPU `mlock`, `async_transfers`, and multi-rank TP startup overlap paths were not executed on hardware in this change. Design-Signed-Off-By: Jason Cook; design-review=2e5b --- helios/src/runtime_core/format.rs | 2 +- helios/src/runtime_core/mod.rs | 704 ++++++++++++++++++++++---- helios/src/runtime_core/model.rs | 554 +++++++++++++++------ helios/src/runtime_core/payload.rs | 769 ++++++++++++++++++++++++++--- helios/src/server.rs | 2 + helios/src/server/config.rs | 195 +++++--- helios/src/server/session.rs | 6 +- helios/src/startup.rs | 39 +- 8 files changed, 1886 insertions(+), 385 deletions(-) diff --git a/helios/src/runtime_core/format.rs b/helios/src/runtime_core/format.rs index 81adcdefd..cd3fb9491 100644 --- a/helios/src/runtime_core/format.rs +++ b/helios/src/runtime_core/format.rs @@ -48,7 +48,7 @@ pub(super) struct Reservation { pub nbytes: usize, } -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(super) enum Memory { #[default] Device, diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index e794e3732..9adadaff1 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -125,6 +125,10 @@ pub struct NativeResources { events: HashMap, cache: Option, host_mappings: Vec<(u64, usize)>, + #[cfg(unix)] + host_mmap_spans: Vec<(u64, usize)>, + #[cfg(unix)] + host_registrations: Vec, green_partition: Option, persistent_worker: Option>, async_transfers: Vec>, @@ -425,6 +429,10 @@ impl NativeResources { events: HashMap::new(), cache: None, host_mappings: Vec::new(), + #[cfg(unix)] + host_mmap_spans: Vec::new(), + #[cfg(unix)] + host_registrations: Vec::new(), green_partition: None, persistent_worker: None, async_transfers: Vec::new(), @@ -540,10 +548,9 @@ impl NativeResources { Ok(()) } - unsafe fn allocate(&mut self, core: &Core, phase: &Phase) -> Result<()> { - if self.host_vmm && self.host_mappings.is_empty() { - unsafe { self.allocate_host(core)? }; - } + /// Split `allocate()` into device-only allocation so mapped-host VMA preparation and + /// pre-faulting can overlap with device weight loading. + unsafe fn allocate_device(&mut self, core: &Core, phase: &Phase) -> Result<()> { let driver = self.driver.clone(); // SAFETY: Core validation bounds all indexes and relocation fields. // Every CUDA resource is immediately retained by self for error cleanup. @@ -570,10 +577,11 @@ impl NativeResources { ))); } for allocation in &core.allocations { - if self - .allocations - .get(&allocation.name) - .is_some_and(|a| a.nbytes > 0) + if matches!(allocation.memory, Memory::MappedHost) + || self + .allocations + .get(&allocation.name) + .is_some_and(|a| a.nbytes > 0) { continue; } @@ -620,42 +628,7 @@ impl NativeResources { (driver.physical_release)(physical); driver.check("cuMemMap", mapped)?; } - Memory::MappedHost => { - #[cfg(unix)] - if !self.host_vmm { - let mapped = libc::mmap( - address as Handle, - allocation.nbytes, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE - | libc::MAP_ANONYMOUS - | libc::MAP_FIXED_NOREPLACE, - -1, - 0, - ); - if mapped != address as Handle { - return Err(invalid(format!( - "host address collision at {address:#x}: {}", - std::io::Error::last_os_error() - ))); - } - // Registration does not pin host memory for an integrated GPU, and a - // swapped-out page turns each GPU access during replay into a fault. - if self.integrated && libc::mlock(mapped, allocation.nbytes) != 0 { - let error = std::io::Error::last_os_error(); - libc::munmap(mapped, allocation.nbytes); - return Err(invalid(format!( - "cannot lock {} bytes of mapped host storage: {error}; raise RLIMIT_MEMLOCK", - allocation.nbytes - ))); - } - let status = (driver.host_register)(mapped, allocation.nbytes, 2); - if status != 0 { - libc::munmap(mapped, allocation.nbytes); - } - driver.check("cuMemHostRegister_v2", status)?; - } - } + Memory::MappedHost => unreachable!(), // The owning rank maps peer storage and grants this rank access. Memory::Peer => {} } @@ -681,40 +654,16 @@ impl NativeResources { }, }, ); - if allocation.address.is_some() { - match allocation.memory { - Memory::Device => { - self.grant_storage_access(&allocation.name)?; - } - Memory::MappedHost => { - #[cfg(unix)] - if !self.host_vmm { - let mut gpu = 0; - driver.check( - "cuMemHostGetDevicePointer_v2", - (driver.host_device)(&mut gpu, address as Handle, 0), - )?; - if gpu != address { - return Err(invalid( - "mapped host address differs from recorded CUDA address", - )); - } - } - } - Memory::Peer => {} - } + if allocation.address.is_some() && matches!(allocation.memory, Memory::Device) { + self.grant_storage_access(&allocation.name)?; } - if allocation.stored_bytes() < allocation.nbytes { - match allocation.memory { - Memory::MappedHost => { - std::ptr::write_bytes(address as *mut u8, 0, allocation.nbytes) - } - Memory::Device => driver.check( - "cuMemsetD8_v2", - (driver.zero)(address, 0, allocation.nbytes), - )?, - Memory::Peer => {} - } + if allocation.stored_bytes() < allocation.nbytes + && matches!(allocation.memory, Memory::Device) + { + driver.check( + "cuMemsetD8_v2", + (driver.zero)(address, 0, allocation.nbytes), + )?; } phase.advance(allocation.nbytes as u64); } @@ -723,17 +672,243 @@ impl NativeResources { Ok(()) } - unsafe fn load_payload( + unsafe fn allocate_mapped_host_vmm(&mut self, core: &Core, phase: &Phase) -> Result<()> { + if self.host_mappings.is_empty() { + unsafe { self.allocate_host(core)? }; + } + for allocation in &core.allocations { + if allocation.sizing.is_some() + || !matches!(allocation.memory, Memory::MappedHost) + || self + .allocations + .get(&allocation.name) + .is_some_and(|s| s.nbytes > 0) + { + continue; + } + let Some(address) = allocation.address else { + continue; + }; + if allocation.nbytes > 0 && allocation.stored_bytes() < allocation.nbytes { + unsafe { + std::ptr::write_bytes(address as *mut u8, 0, allocation.nbytes); + } + } + self.allocations.insert( + allocation.name.clone(), + Storage { + base: 0, + address, + nbytes: allocation.nbytes, + memory: allocation.memory, + fixed: true, + mappings: Vec::new(), + }, + ); + phase.advance(allocation.nbytes as u64); + } + Ok(()) + } + + /// Map and pre-fault fixed `MappedHost` VMAs (without CUDA context locks) while concurrently + /// streaming `Device` payload bytes into GPU memory. Returns the `512 MiB` registration chunks + /// queued for `cuMemHostRegister_v2` during host payload loading. + unsafe fn load_device_overlapping_mapped_host( + &mut self, + files: &F, + core: &Core, + phase: &Phase, + ranks: usize, + ) -> Result { + if self.host_vmm { + let silent = StartupProgress::silent().phase("Allocate model memory", None); + unsafe { + self.allocate_mapped_host_vmm(core, &silent)?; + self.load_device_payload(files, core, phase, ranks)?; + } + return Ok(PendingHostRegistration::default()); + } + #[cfg(unix)] + { + let cancel = std::sync::atomic::AtomicBool::new(false); + let (device_result, host_result) = std::thread::scope(|scope| { + let integrated = self.integrated; + let peer_readers = &self.peer_readers; + let existing = &self.allocations; + let cancel_ref = &cancel; + let host_worker = std::thread::Builder::new() + .name(format!("flare-host-alloc-{}", self.rank)) + .spawn_scoped(scope, move || unsafe { + prepare_mapped_host_vmas( + integrated, + peer_readers, + existing, + core, + ranks, + cancel_ref, + ) + }); + let device_result = unsafe { self.load_device_payload(files, core, phase, ranks) }; + if device_result.is_err() { + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } + let host_result = match host_worker { + Ok(handle) => match handle.join() { + Ok(result) => result, + Err(_) => Err(invalid("mapped host allocation thread panicked")), + }, + Err(error) => Err(error.to_string().into()), + }; + (device_result, host_result) + }); + let silent = StartupProgress::silent().phase("Allocate model memory", None); + match host_result { + Ok((allocation, pending)) => { + self.attach_mapped_host(allocation, &silent); + device_result?; + Ok(pending) + } + Err(host_error) => { + device_result?; + Err(host_error) + } + } + } + #[cfg(not(unix))] + { + unreachable!("non-unix platforms always set host_vmm = true") + } + } + + /// Pin and GPU-map previously `mmap`-prepared `MappedHost` chunks in `512 MiB` windows, + /// signaling `gate` after each chunk so concurrent `O_DIRECT` readers can stream into + /// registered pages immediately. + unsafe fn register_pending_mapped_host( &mut self, + core: &Core, + pending: PendingHostRegistration, + gate: Option<&payload::RegistrationGate>, + cancel: &std::sync::atomic::AtomicBool, + ) -> Result<()> { + #[cfg(unix)] + { + use std::sync::atomic::Ordering; + + if self.host_vmm || pending.chunks.is_empty() { + if let Some(gate) = gate { + gate.close(); + } + return Ok(()); + } + let driver = self.driver.clone(); + let result = unsafe { + driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; + for (chunk_addr, chunk_bytes, flags) in pending.chunks { + if cancel.load(Ordering::Relaxed) { + break; + } + driver.check( + "cuMemHostRegister_v2", + (driver.host_register)(chunk_addr as Handle, chunk_bytes, flags), + )?; + self.host_registrations.push(chunk_addr); + if let Some(gate) = gate { + gate.advance(); + } + } + if !cancel.load(Ordering::Relaxed) { + for allocation in &core.allocations { + if allocation.sizing.is_some() + || !matches!(allocation.memory, Memory::MappedHost) + || allocation.nbytes == 0 + { + continue; + } + let Some(address) = allocation.address else { + continue; + }; + let mut gpu = 0; + driver.check( + "cuMemHostGetDevicePointer_v2", + (driver.host_device)(&mut gpu, address as Handle, 0), + )?; + if gpu != address { + return Err(invalid( + "mapped host address differs from recorded CUDA address", + )); + } + } + } + Ok(()) + }; + if let Some(gate) = gate { + gate.close(); + } + result + } + #[cfg(not(unix))] + { + let _ = (core, pending, cancel); + if let Some(gate) = gate { + gate.close(); + } + Ok(()) + } + } + + #[cfg(unix)] + fn attach_mapped_host(&mut self, allocation: MappedHostAllocation, phase: &Phase) { + self.host_mmap_spans.extend(allocation.mappings); + for (name, storage) in allocation.storages { + let nbytes = storage.nbytes as u64; + self.allocations.insert(name, storage); + phase.advance(nbytes); + } + } + + unsafe fn allocate(&mut self, core: &Core, phase: &Phase) -> Result<()> { + unsafe { self.allocate_device(core, phase)? }; + if self.host_vmm { + unsafe { self.allocate_mapped_host_vmm(core, phase)? }; + return Ok(()); + } + #[cfg(unix)] + { + let cancel = std::sync::atomic::AtomicBool::new(false); + let (mapped, pending) = unsafe { + prepare_mapped_host_vmas( + self.integrated, + &self.peer_readers, + &self.allocations, + core, + 1, + &cancel, + )? + }; + self.attach_mapped_host(mapped, phase); + unsafe { self.register_pending_mapped_host(core, pending, None, &cancel)? }; + } + Ok(()) + } + + unsafe fn load_device_payload( + &self, files: &F, core: &Core, phase: &Phase, ranks: usize, ) -> Result<()> { + unsafe { + self.driver + .check("cuCtxSetCurrent", (self.driver.context_set)(self.context))?; + payload::load_device(self, files, core, phase, ranks) + } + } + + unsafe fn apply_payload_relocations(&mut self, core: &Core) -> Result<()> { let driver = self.driver.clone(); unsafe { driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; - payload::load(self, files, core, phase, ranks)?; for allocation in &core.allocations { for relocation in &allocation.relocations { let address = @@ -754,6 +929,21 @@ impl NativeResources { Ok(()) } + unsafe fn load_payload( + &mut self, + files: &F, + core: &Core, + phase: &Phase, + ranks: usize, + ) -> Result<()> { + unsafe { + self.driver + .check("cuCtxSetCurrent", (self.driver.context_set)(self.context))?; + payload::load(self, files, core, phase, ranks)?; + self.apply_payload_relocations(core) + } + } + unsafe fn prepare_kernels( &mut self, files: &F, @@ -1835,16 +2025,18 @@ impl NativeResources { (self.driver.unmap)(address, bytes); } } - (Memory::MappedHost, _) => { - #[cfg(unix)] - if !self.host_vmm { - (self.driver.host_unregister)(allocation.address as Handle); - libc::munmap(allocation.address as Handle, allocation.nbytes); - } - } + (Memory::MappedHost, _) => {} (Memory::Peer, _) => {} } } + #[cfg(unix)] + for address in self.host_registrations.drain(..).rev() { + (self.driver.host_unregister)(address as Handle); + } + #[cfg(unix)] + for (address, bytes) in self.host_mmap_spans.drain(..).rev() { + libc::munmap(address as Handle, bytes); + } for (address, bytes) in self.host_mappings.drain(..).rev() { (self.driver.unmap)(address, bytes); } @@ -1936,3 +2128,343 @@ unsafe fn apply_context_settings( configured } } + +#[derive(Default)] +pub(super) struct PendingHostRegistration { + #[cfg(unix)] + chunks: Vec<(u64, usize, u32)>, +} + +impl PendingHostRegistration { + pub(super) fn is_empty(&self) -> bool { + #[cfg(unix)] + { + self.chunks.is_empty() + } + #[cfg(not(unix))] + { + true + } + } + + pub(super) fn chunk_ends(&self) -> Vec { + #[cfg(unix)] + { + self.chunks + .iter() + .map(|&(addr, bytes, _)| addr.saturating_add(bytes as u64)) + .collect() + } + #[cfg(not(unix))] + { + Vec::new() + } + } +} + +#[cfg(any(unix, test))] +#[derive(Default)] +struct MappedHostAllocation { + mappings: Vec<(u64, usize)>, + storages: Vec<(String, Storage)>, +} + +/// Map, hint THP, and parallel-pre-fault coalesced fixed `MappedHost` VMAs without touching any +/// CUDA context or driver locks, returning `512 MiB` registration chunks for subsequent GPU pinning. +#[cfg(unix)] +unsafe fn prepare_mapped_host_vmas( + integrated: bool, + peer_readers: &HashMap>, + existing_allocations: &HashMap, + core: &Core, + ranks: usize, + cancel: &std::sync::atomic::AtomicBool, +) -> Result<(MappedHostAllocation, PendingHostRegistration)> { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let mut outcome = MappedHostAllocation::default(); + let mut pending = PendingHostRegistration::default(); + // SAFETY: Any partial mappings are unmapped before returning on error or cancellation. + unsafe { + // Coalesce contiguous fixed MappedHost allocations into shared VMAs before pinning so + // transparent huge pages can span layer boundaries without losing alignment edges. + let mut spans: Vec<(u64, usize, u32)> = core + .allocations + .iter() + .filter(|a| { + a.sizing.is_none() + && matches!(a.memory, Memory::MappedHost) + && a.nbytes > 0 + && !existing_allocations + .get(&a.name) + .is_some_and(|s| s.nbytes > 0) + }) + .filter_map(|a| { + let addr = a.address?; + let flags = if peer_readers.contains_key(&addr) { + 3 + } else { + 2 + }; + Some((addr, a.nbytes, flags)) + }) + .collect(); + if spans.is_empty() { + return Ok((outcome, pending)); + } + spans.sort_unstable_by_key(|&(addr, _, _)| addr); + let mut merged: Vec<(u64, usize, u32)> = Vec::with_capacity(spans.len()); + for (addr, nbytes, flags) in spans { + if let Some(last) = merged.last_mut() + && last.2 == flags + && last.0.checked_add(last.1 as u64) == Some(addr) + { + last.1 = last + .1 + .checked_add(nbytes) + .ok_or_else(|| invalid("coalesced mapped host size overflow"))?; + } else { + merged.push((addr, nbytes, flags)); + } + } + let cleanup = |outcome: &mut MappedHostAllocation| { + for (addr, bytes) in outcome.mappings.drain(..).rev() { + libc::munmap(addr as Handle, bytes); + } + }; + let mut mapped_spans: Vec<(u64, usize, u32)> = Vec::with_capacity(merged.len()); + for (span_addr, span_bytes, flags) in merged { + if cancel.load(Ordering::Relaxed) { + cleanup(&mut outcome); + return Ok(( + MappedHostAllocation::default(), + PendingHostRegistration::default(), + )); + } + let mapped = libc::mmap( + span_addr as Handle, + span_bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_FIXED_NOREPLACE, + -1, + 0, + ); + if mapped != span_addr as Handle { + let error = std::io::Error::last_os_error(); + cleanup(&mut outcome); + return Err(invalid(format!( + "host address collision at {span_addr:#x}: {error}" + ))); + } + outcome.mappings.push((span_addr, span_bytes)); + #[cfg(target_os = "linux")] + { + // Best-effort transparent huge page hint before pinning so unified-memory + // GPU replay walks fewer TLB entries. + let _ = libc::madvise(mapped, span_bytes, libc::MADV_HUGEPAGE); + } + mapped_spans.push((span_addr, span_bytes, flags)); + } + #[cfg(target_os = "linux")] + { + // Pre-fault at 2 MiB stride in package allocation order across bounded CPU + // threads before cuMemHostRegister_v2 pins the VMA: ordered FIFO slices preserve + // scarce 512 MiB PMDs for the exporter's hot layout priority while parallelizing + // zero-page faulting without holding any CUDA locks. + let slices = prefault_slices( + core.allocations + .iter() + .filter(|a| { + a.sizing.is_none() + && matches!(a.memory, Memory::MappedHost) + && a.nbytes > 0 + && !existing_allocations + .get(&a.name) + .is_some_and(|s| s.nbytes > 0) + }) + .filter_map(|a| a.address.map(|addr| (addr as usize, a.nbytes))), + ); + let cpus = std::thread::available_parallelism().map_or(4, usize::from); + let workers = (cpus / ranks.max(1)).clamp(1, 8).min(slices.len().max(1)); + let fault_slice = |start: usize, end: usize| { + let mut cur = start; + while cur < end { + std::ptr::write_volatile(cur as *mut u8, 0); + cur = match cur.checked_add(PREFAULT_STRIDE) { + Some(next) => next, + None => break, + }; + } + }; + if workers <= 1 { + for &(start, end) in &slices { + if cancel.load(Ordering::Relaxed) { + break; + } + fault_slice(start, end); + } + } else { + let cursor = AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..workers { + let slices = &slices; + let cursor = &cursor; + scope.spawn(move || loop { + if cancel.load(Ordering::Relaxed) { + break; + } + let idx = cursor.fetch_add(1, Ordering::Relaxed); + let Some(&(start, end)) = slices.get(idx) else { + break; + }; + fault_slice(start, end); + }); + } + }); + } + if cancel.load(Ordering::Relaxed) { + cleanup(&mut outcome); + return Ok(( + MappedHostAllocation::default(), + PendingHostRegistration::default(), + )); + } + } + for &(span_addr, span_bytes, flags) in &mapped_spans { + // Registration does not pin host memory for an integrated GPU, and a + // swapped-out page turns each GPU access during replay into a fault. + if integrated && libc::mlock(span_addr as Handle, span_bytes) != 0 { + let error = std::io::Error::last_os_error(); + cleanup(&mut outcome); + return Err(invalid(format!( + "cannot lock {span_bytes} bytes of mapped host storage: {error}; raise RLIMIT_MEMLOCK" + ))); + } + for (chunk_addr, chunk_bytes) in registration_chunks(span_addr, span_bytes) { + pending.chunks.push((chunk_addr, chunk_bytes, flags)); + } + } + for allocation in &core.allocations { + if allocation.sizing.is_some() + || !matches!(allocation.memory, Memory::MappedHost) + || existing_allocations + .get(&allocation.name) + .is_some_and(|s| s.nbytes > 0) + { + continue; + } + let Some(address) = allocation.address else { + continue; + }; + if allocation.nbytes > 0 && allocation.stored_bytes() < allocation.nbytes { + std::ptr::write_bytes(address as *mut u8, 0, allocation.nbytes); + } + outcome.storages.push(( + allocation.name.clone(), + Storage { + base: 0, + address, + nbytes: allocation.nbytes, + memory: allocation.memory, + fixed: true, + mappings: Vec::new(), + }, + )); + } + } + Ok((outcome, pending)) +} + +#[cfg(any(target_os = "linux", test))] +const PREFAULT_STRIDE: usize = 2 * 1024 * 1024; +#[cfg(any(target_os = "linux", test))] +const PREFAULT_SLICE: usize = 32 * 1024 * 1024; +#[cfg(any(unix, test))] +const REGISTER_CHUNK_BYTES: usize = 512 * 1024 * 1024; + +#[cfg(any(target_os = "linux", test))] +fn prefault_slices(allocations: impl Iterator) -> Vec<(usize, usize)> { + let mut slices = Vec::new(); + for (start_addr, nbytes) in allocations { + let Some(end_addr) = start_addr.checked_add(nbytes) else { + continue; + }; + let Some(mut cur) = start_addr + .checked_add(PREFAULT_STRIDE - 1) + .map(|v| v & !(PREFAULT_STRIDE - 1)) + else { + continue; + }; + while cur < end_addr { + let slice_end = cur.saturating_add(PREFAULT_SLICE).min(end_addr); + slices.push((cur, slice_end)); + cur = slice_end; + } + } + slices +} + +#[cfg(any(unix, test))] +fn registration_chunks(span_addr: u64, span_bytes: usize) -> Vec<(u64, usize)> { + let mut chunks = Vec::new(); + let Some(span_end) = span_addr.checked_add(span_bytes as u64) else { + return chunks; + }; + let align = REGISTER_CHUNK_BYTES as u64; + let mut cur = span_addr; + while cur < span_end { + let next_aligned = (cur.saturating_add(align)) & !(align - 1); + let next = if next_aligned > cur { + next_aligned.min(span_end) + } else { + span_end + }; + chunks.push((cur, (next - cur) as usize)); + cur = next; + } + chunks +} + +#[cfg(test)] +mod startup_overlap_tests { + use super::*; + + #[test] + fn registration_chunks_align_to_512mib_boundaries_without_splitting_pmds() { + let align = REGISTER_CHUNK_BYTES as u64; + let start = 4 * align + (128 << 20); + let len = 1280 << 20; + let chunks = registration_chunks(start, len); + assert_eq!( + chunks, + vec![ + (start, 384 << 20), + (5 * align, 512 << 20), + (6 * align, 384 << 20), + ] + ); + assert_eq!( + registration_chunks(2 * align, 2 * REGISTER_CHUNK_BYTES), + vec![ + (2 * align, REGISTER_CHUNK_BYTES), + (3 * align, REGISTER_CHUNK_BYTES), + ] + ); + assert_eq!( + registration_chunks(0x1000_0000, 64 << 20), + vec![(0x1000_0000, 64 << 20)] + ); + } + + #[test] + fn prefault_slices_preserve_allocation_order_and_2mib_alignment() { + let a = 0x2000_0000 + (1 << 20); + let b = 0x4000_0000; + let slices = prefault_slices([(a, 70 << 20), (b, 16 << 20)].into_iter()); + assert_eq!(slices[0], (0x2020_0000, 0x2220_0000)); + assert_eq!(slices[1], (0x2220_0000, 0x2420_0000)); + assert_eq!(slices[2], (0x2420_0000, a + (70 << 20))); + assert_eq!(slices[3], (b, b + (16 << 20))); + assert_eq!(slices.len(), 4); + } +} diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index a996ddfab..b6610b4d2 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -28,6 +28,8 @@ pub struct NativeModel { gpu_codec_cubins: Vec>>, cluster: Option, roce: Vec>, + #[cfg(feature = "server")] + preloaded_frontend: Option, } /// The rank this host serves of a model whose ranks run on separate hosts. @@ -512,7 +514,7 @@ impl NativeModel { .any(|table| table.planes.scales.is_some()); options.validate_embedding_resident_scales(!engram.is_empty(), has_scale_planes)?; let ram = options.embedding_table_storage == Some(crate::engram::Storage::Ram); - let engram_tokens = engram.iter().map(|(_, ranks)| { + let mut engram_tokens = engram.iter().map(|(_, ranks)| { ranks.iter().flat_map(|rank| cores[*rank].execution.as_ref().unwrap().graphs.iter()) .filter(|graph| crate::execution::GraphKind::try_from(graph.kind.as_str()) .is_ok_and(crate::engram::consumes)) @@ -700,7 +702,22 @@ impl NativeModel { gpu_codec_cubins, cluster, roce, + #[cfg(feature = "server")] + preloaded_frontend: None, }; + #[cfg(feature = "server")] + let frontend_preload = model + .cluster + .as_ref() + .is_none_or(|c| c.rank == 0) + .then(|| { + let snapshot = model.server_config.clone(); + thread::Builder::new() + .name("flare-frontend-preload".into()) + .spawn(move || crate::server::preload_frontend(&snapshot).ok()) + .ok() + }) + .flatten(); unsafe { let before_contexts = if matches!( options.memory_limit, @@ -809,180 +826,411 @@ impl NativeModel { .collect::>>()?, }; model.check_memory_limit(&cores, options, &initial, embedding_host_bytes)?; - let (mut gpu_bytes, mut host_bytes, mut payload_bytes) = (0u64, 0u64, 0u64); + let ( + mut gpu_bytes, + mut host_bytes, + mut device_payload_bytes, + mut host_payload_bytes, + ) = (0u64, 0u64, 0u64, 0u64); for allocation in cores.iter().flat_map(|core| &core.allocations) { + let stored = allocation.stored_bytes() as u64; match allocation.memory { - Memory::Device => gpu_bytes += allocation.nbytes as u64, - Memory::MappedHost => host_bytes += allocation.nbytes as u64, + Memory::Device => { + gpu_bytes += allocation.nbytes as u64; + device_payload_bytes += stored; + } + Memory::MappedHost => { + host_bytes += allocation.nbytes as u64; + host_payload_bytes += stored; + } Memory::Peer => {} } - payload_bytes += allocation.stored_bytes() as u64; } - let phase = progress.phase("Allocate model memory", Some(gpu_bytes + host_bytes)); + let payload_bytes = device_payload_bytes + host_payload_bytes; + let overlap_host_alloc = host_bytes > 0 && device_payload_bytes > 0; // Reservations cover all ranks and must exist before parallel mapping. - model.ranks[0].reserve(&cores[0])?; - model.parallel(&cores, &files, |rank, core, _| { - rank.allocate(core, &phase) - })?; - phase.finish(format!( - "{:.1} GiB GPU · {:.1} GiB host", - gpu_bytes as f64 / (1u64 << 30) as f64, - host_bytes as f64 / (1u64 << 30) as f64, - )); + if overlap_host_alloc { + let phase = progress.phase("Allocate model memory", Some(gpu_bytes)); + model.ranks[0].reserve(&cores[0])?; + model.parallel(&cores, &files, |rank, core, _| { + rank.allocate_device(core, &phase) + })?; + phase.finish(format!( + "{:.1} GiB GPU · {:.1} GiB host (overlapping)", + gpu_bytes as f64 / (1u64 << 30) as f64, + host_bytes as f64 / (1u64 << 30) as f64, + )); + } else { + let phase = progress.phase("Allocate model memory", Some(gpu_bytes + host_bytes)); + model.ranks[0].reserve(&cores[0])?; + model.parallel(&cores, &files, |rank, core, _| { + rank.allocate(core, &phase) + })?; + phase.finish(format!( + "{:.1} GiB GPU · {:.1} GiB host", + gpu_bytes as f64 / (1u64 << 30) as f64, + host_bytes as f64 / (1u64 << 30) as f64, + )); + } if let Some(pool) = &options.prefix_cache.pool { let phase = progress.phase("Reach prefix cache pool", None); pool.reach(flare_selene::pool::STARTUP_WAIT)?; phase.finish("manager reached"); } - let phase = progress.phase("Load weights", Some(payload_bytes)); - phase.advance_bytes(0); - model.parallel(&cores, &files, |rank, core, path| { - rank.load_payload(path, core, &phase, devices.len()) - })?; - if model.ranks.iter().any(|rank| rank.integrated) { - Files::release_page_cache(&files); + let load_phase = progress.phase("Load weights", Some(payload_bytes)); + load_phase.advance_bytes(0); + let mut pending_registrations: Vec = (0..devices.len()) + .map(|_| super::PendingHostRegistration::default()) + .collect(); + if overlap_host_alloc { + let collected = std::sync::Mutex::new( + (0..devices.len()) + .map(|_| Option::::None) + .collect::>(), + ); + model.parallel(&cores, &files, |rank, core, path| { + let pending = rank.load_device_overlapping_mapped_host( + path, + core, + &load_phase, + devices.len(), + )?; + collected.lock().unwrap()[rank.rank] = Some(pending); + Ok(()) + })?; + pending_registrations = collected + .into_inner() + .unwrap() + .into_iter() + .map(|p| p.unwrap_or_default()) + .collect(); + } else if device_payload_bytes > 0 { + model.parallel(&cores, &files, |rank, core, path| { + rank.load_device_payload(path, core, &load_phase, devices.len()) + })?; } - phase.finish(format!( - "{:.1} GiB", - payload_bytes as f64 / (1u64 << 30) as f64 - )); - let kernels = cores - .iter() - .map(|p| p.functions.len() as u64) - .sum::(); - let modules = cores.iter().map(|p| p.modules.len() as u64).sum::(); - 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(), - reserve_codec_partition, - ) - })?; - phase.finish(format!("{kernels} kernels")); - let nodes = cores - .iter() - .flat_map(|p| &p.graphs) - .map(|graph| graph.node_count as u64 + 1) - .sum(); - let phase = progress.phase("Prepare execution", Some(nodes)); - model.parallel(&cores, &files, |rank, core, files| { - rank.prepare_graphs(files, core, &phase) - })?; - let has_peer_copy_graphs = model - .ranks - .iter() - .any(NativeResources::has_any_peer_copy_graphs); - validate_async_transfer_peer_copy_compatibility(has_peer_copy_graphs, &cores)?; - model.copy_gate = has_peer_copy_graphs - .then(|| std::sync::Arc::new(crate::offload::CopyEngineGate::new())); - phase.finish(format!("concurrency {active}")); - if !engram.is_empty() { - let phase = progress.phase("Prepare embedding tables", None); - let storage = options.embedding_table_storage.unwrap_or_default(); - let group_budget = embedding_table_cache_bytes / engram.len() as u64; - // Open direct-I/O handles only for containers that actually carry embedding - // planes rather than every weight companion in the deployment. - let mut mapped_files = std::collections::BTreeMap::new(); - let mut direct_files = Vec::new(); - for (index, _) in &mut engram { - for table in &mut index.tables { - for plane in table.planes.iter_mut() { - let target = match mapped_files.entry(plane.file) { - std::collections::btree_map::Entry::Occupied(entry) => { - *entry.get() - } - std::collections::btree_map::Entry::Vacant(slot) => { - let next = direct_files.len(); - direct_files.push(files.direct_file(plane.file)?); - *slot.insert(next) - } - }; - plane.file = target; + let mut prepare_runtime = |model: &mut Self, + cores: &mut [Core], + stage_progress: &StartupProgress| + -> Result> { + let kernels = cores + .iter() + .map(|p| p.functions.len() as u64) + .sum::(); + let modules = cores.iter().map(|p| p.modules.len() as u64).sum::(); + let phase = stage_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(), + reserve_codec_partition, + ) + })?; + phase.finish(format!("{kernels} kernels")); + let nodes = cores + .iter() + .flat_map(|p| &p.graphs) + .map(|graph| graph.node_count as u64 + 1) + .sum(); + let phase = stage_progress.phase("Prepare execution", Some(nodes)); + model.parallel(cores, &files, |rank, core, files| { + rank.prepare_graphs(files, core, &phase) + })?; + let has_peer_copy_graphs = model + .ranks + .iter() + .any(NativeResources::has_any_peer_copy_graphs); + validate_async_transfer_peer_copy_compatibility(has_peer_copy_graphs, cores)?; + model.copy_gate = has_peer_copy_graphs + .then(|| std::sync::Arc::new(crate::offload::CopyEngineGate::new())); + phase.finish(format!("concurrency {active}")); + if !engram.is_empty() { + let phase = stage_progress.phase("Prepare embedding tables", None); + let storage = options.embedding_table_storage.unwrap_or_default(); + let group_budget = embedding_table_cache_bytes / engram.len() as u64; + // Open direct-I/O handles only for containers that actually carry embedding + // planes rather than every weight companion in the deployment. + let mut mapped_files = std::collections::BTreeMap::new(); + let mut direct_files = Vec::new(); + for (index, _) in &mut engram { + for table in &mut index.tables { + for plane in table.planes.iter_mut() { + let target = match mapped_files.entry(plane.file) { + std::collections::btree_map::Entry::Occupied(entry) => { + *entry.get() + } + std::collections::btree_map::Entry::Vacant(slot) => { + let next = direct_files.len(); + direct_files.push(files.direct_file(plane.file)?); + *slot.insert(next) + } + }; + plane.file = target; + } } } - } - let has_prefetch_mailbox = engram - .iter() - .flat_map(|(index, _)| &index.tables) - .any(|table| table.prefetch.is_some()); - let mut bindings = Vec::new(); - for ((index, ranks), tokens) in engram.into_iter().zip(engram_tokens) { - let first = ranks[0]; - let shared = crate::engram::Shared::new( - index, - &direct_files, - ranks.len(), - tokens, - model.ranks[first].context as usize, - devices[first], - storage, - group_budget, - options.embedding_workers(), - embedding_table_resident_scales, - embedding_table_prefetch, - )?; - for (delivery_rank, local) in ranks.into_iter().enumerate() { - bindings.push((local, shared.clone(), delivery_rank)); + let has_prefetch_mailbox = engram + .iter() + .flat_map(|(index, _)| &index.tables) + .any(|table| table.prefetch.is_some()); + let mut bindings = Vec::new(); + for ((index, ranks), tokens) in std::mem::take(&mut engram) + .into_iter() + .zip(std::mem::take(&mut engram_tokens)) + { + let first = ranks[0]; + let shared = crate::engram::Shared::new( + index, + &direct_files, + ranks.len(), + tokens, + model.ranks[first].context as usize, + devices[first], + storage, + group_budget, + options.embedding_workers(), + embedding_table_resident_scales, + embedding_table_prefetch, + )?; + for (delivery_rank, local) in ranks.into_iter().enumerate() { + bindings.push((local, shared.clone(), delivery_rank)); + } } + bindings.sort_by_key(|(local, _, _)| *local); + model.engram = bindings + .into_iter() + .map(|(_, shared, rank)| (shared, rank)) + .collect(); + let label = match storage { + crate::engram::Storage::Disk if embedding_table_resident_scales => { + "disk weights, RAM scales" + } + crate::engram::Storage::Disk => "disk", + crate::engram::Storage::Ram => "RAM", + }; + let cache_bytes: u64 = model + .engram + .iter() + .filter(|(_, rank)| *rank == 0) + .map(|(shared, _)| shared.cache_bytes()) + .sum(); + let prefetch_note = if embedding_table_prefetch && has_prefetch_mailbox { + " · lookahead prefetch" + } else { + "" + }; + phase.finish(if cache_bytes == 0 { + label.to_owned() + } else { + format!( + "{label} · {:.0} MiB row cache{prefetch_note}", + cache_bytes as f64 / (1u64 << 20) as f64 + ) + }); } - bindings.sort_by_key(|(local, _, _)| *local); - model.engram = bindings - .into_iter() - .map(|(_, shared, rank)| (shared, rank)) + Files::release_page_cache(&files); + let planned = model.allocate_caches( + cores, + stage_progress, + active, + agree, + options, + &initial, + embedding_host_bytes, + )?; + model.prepare_offload(options, stage_progress, active, planned.offload_host)?; + Ok(planned.async_transfer_host_caps) + }; + let async_transfer_host_caps = if host_payload_bytes > 0 { + // MappedHost weight loading makes zero CUDA calls and writes only into + // registered 512 MiB windows as `cuMemHostRegister_v2` races ahead of + // NVMe O_DIRECT. Once registration completes, kernel, graph, cache, and + // host prefix cache setup finishes before NVMe I/O ends. + let gates: Vec> = pending_registrations + .iter() + .map(|pending| { + (!pending.is_empty()) + .then(|| super::payload::RegistrationGate::new(pending.chunk_ends())) + }) .collect(); - let label = match storage { - crate::engram::Storage::Disk if embedding_table_resident_scales => { - "disk weights, RAM scales" - } - crate::engram::Storage::Disk => "disk", - crate::engram::Storage::Ram => "RAM", - }; - let cache_bytes: u64 = model - .engram + let rank_chunks: Vec<(Vec, usize)> = model + .ranks .iter() - .filter(|(_, rank)| *rank == 0) - .map(|(shared, _)| shared.cache_bytes()) - .sum(); - let prefetch_note = if embedding_table_prefetch && has_prefetch_mailbox { - " · lookahead prefetch" - } else { - "" - }; - phase.finish(if cache_bytes == 0 { - label.to_owned() - } else { - format!( - "{label} · {:.0} MiB row cache{prefetch_note}", - cache_bytes as f64 / (1u64 << 20) as f64 - ) + .zip(&cores) + .zip(&gates) + .map(|((rank, core), gate)| { + super::payload::collect_mapped_host_chunks( + rank, + &files, + core, + devices.len(), + gate.as_ref(), + ) + }) + .collect::>>()?; + let (bg_progress, bg_observation) = StartupProgress::observed(); + let cancel = std::sync::atomic::AtomicBool::new(false); + let payload_path = files.path().to_path_buf(); + let (host_load_result, runtime_result) = thread::scope(|scope| { + let load_phase_ref = &load_phase; + let cancel_ref = &cancel; + let gates_ref = &gates; + let host_loader = thread::Builder::new() + .name("flare-host-payload".into()) + .spawn_scoped(scope, move || { + thread::scope(|inner| -> Result<()> { + let mut workers = Vec::with_capacity(rank_chunks.len()); + for (rank_idx, (chunks, readers)) in + rank_chunks.iter().enumerate() + { + let path = payload_path.as_path(); + let gate = gates_ref[rank_idx].as_ref(); + workers.push( + thread::Builder::new() + .name(format!("flare-host-rank-{rank_idx}")) + .spawn_scoped(inner, move || { + super::payload::load_mapped_host_chunks( + chunks, + path, + load_phase_ref, + *readers, + cancel_ref, + gate, + ) + }) + .map_err(|e| e.to_string())?, + ); + } + let mut first_err = None; + for worker in workers { + match worker.join() { + Ok(Ok(())) => {} + Ok(Err(error)) => { + cancel_ref.store( + true, + std::sync::atomic::Ordering::Relaxed, + ); + for gate in gates_ref.iter().flatten() { + gate.close(); + } + if first_err.is_none() { + first_err = Some(error); + } + } + Err(_) => { + cancel_ref.store( + true, + std::sync::atomic::Ordering::Relaxed, + ); + for gate in gates_ref.iter().flatten() { + gate.close(); + } + if first_err.is_none() { + first_err = + Some(invalid("host payload loader panicked")); + } + } + } + } + if let Some(error) = first_err { + return Err(error); + } + Ok(()) + }) + }); + let runtime_result = (|| -> Result> { + let pending_slots = std::sync::Mutex::new( + pending_registrations + .into_iter() + .map(Some) + .collect::>(), + ); + model.parallel(&cores, &files, |rank, core, _| { + let pending = pending_slots.lock().unwrap()[rank.rank] + .take() + .unwrap_or_default(); + rank.register_pending_mapped_host( + core, + pending, + gates_ref[rank.rank].as_ref(), + cancel_ref, + ) + })?; + prepare_runtime(&mut model, &mut cores, &bg_progress) + })(); + if runtime_result.is_err() { + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + for gate in gates_ref.iter().flatten() { + gate.close(); + } + } + let host_load_result = match host_loader { + Ok(handle) => match handle.join() { + Ok(result) => result, + Err(_) => Err(invalid("host payload coordinator panicked")), + }, + Err(error) => Err(error.to_string().into()), + }; + (host_load_result, runtime_result) }); - } - Files::release_page_cache(&files); - let planned = model.allocate_caches( - &mut cores, - progress, - active, - agree, - options, - &initial, - embedding_host_bytes, - )?; - model.prepare_offload(options, progress, active, planned.offload_host)?; - model.prepare_async_transfers( - &files, - &cores, - &planned.async_transfer_host_caps, - progress, - )?; + host_load_result?; + let caps = runtime_result?; + model.parallel(&cores, &files, |rank, core, _| { + rank.apply_payload_relocations(core) + })?; + if model.ranks.iter().any(|rank| rank.integrated) { + Files::release_page_cache(&files); + } + load_phase.finish(format!( + "{:.1} GiB", + payload_bytes as f64 / (1u64 << 30) as f64 + )); + progress.replay_completed(&bg_observation.completed_phases()); + caps + } else { + let cancel = std::sync::atomic::AtomicBool::new(false); + let pending_slots = std::sync::Mutex::new( + pending_registrations + .into_iter() + .map(Some) + .collect::>(), + ); + model.parallel(&cores, &files, |rank, core, _| { + let pending = pending_slots.lock().unwrap()[rank.rank] + .take() + .unwrap_or_default(); + rank.register_pending_mapped_host(core, pending, None, &cancel) + })?; + model.parallel(&cores, &files, |rank, core, _| { + rank.apply_payload_relocations(core) + })?; + if model.ranks.iter().any(|rank| rank.integrated) { + Files::release_page_cache(&files); + } + load_phase.finish(format!( + "{:.1} GiB", + payload_bytes as f64 / (1u64 << 30) as f64 + )); + prepare_runtime(&mut model, &mut cores, progress)? + }; + model.prepare_async_transfers(&files, &cores, &async_transfer_host_caps, progress)?; + } + #[cfg(feature = "server")] + if let Some(handle) = frontend_preload { + model.preloaded_frontend = handle.join().ok().flatten(); } Ok(model) } + #[cfg(feature = "server")] + pub(crate) fn take_preloaded_frontend(&mut self) -> Option { + self.preloaded_frontend.take() + } + /// Initialize and start any declared `Execution.async_transfers` channels across local ranks /// so startup tuning graphs observe populated pool geometry and live copy channels. unsafe fn prepare_async_transfers( @@ -1424,6 +1672,8 @@ mod tests { cluster: None, roce: Vec::new(), gpu_codec_cubins: Vec::new(), + #[cfg(feature = "server")] + preloaded_frontend: None, }; for prefix_cache in [ crate::offload::PrefixCacheOffload::default(), diff --git a/helios/src/runtime_core/payload.rs b/helios/src/runtime_core/payload.rs index 4bac0cb31..523691f25 100644 --- a/helios/src/runtime_core/payload.rs +++ b/helios/src/runtime_core/payload.rs @@ -11,8 +11,13 @@ use std::{ collections::VecDeque, fs::File, io, + path::Path, ptr::null_mut, - sync::{Arc, Mutex, mpsc}, + sync::{ + Arc, Condvar, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + mpsc, + }, thread, }; @@ -135,12 +140,142 @@ pub(super) trait Files: Sync { ) -> crate::Result>; } -const CHUNK: usize = 4 << 20; +const MAX_CHUNK: usize = 8 << 20; +const MIN_CHUNK: usize = 1 << 20; const MAX_RECORD: usize = 1 << 20; -const SLOTS: usize = 4; -pub(super) const READERS: usize = 4; +const MIN_READERS: usize = 4; +pub(super) const READERS: usize = 8; +const MAX_STAGING_BYTES: usize = 128 << 20; +const MIN_STAGING_BYTES: usize = 16 << 20; const BLOCK: usize = 4096; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct IoPlan { + chunk_bytes: usize, + readers: usize, + slots: usize, +} + +#[cfg(target_os = "linux")] +fn detect_optimal_io_size(file: &File) -> usize { + use std::os::unix::fs::MetadataExt as _; + + let Ok(meta) = file.metadata() else { + return 0; + }; + let dev = meta.dev(); + let major = libc::major(dev); + let minor = libc::minor(dev); + for suffix in ["queue/optimal_io_size", "../queue/optimal_io_size"] { + let path = format!("/sys/dev/block/{major}:{minor}/{suffix}"); + if let Ok(text) = std::fs::read_to_string(path) + && let Ok(bytes) = text.trim().parse::() + && bytes >= BLOCK + && bytes <= MAX_CHUNK + && bytes % BLOCK == 0 + { + return bytes; + } + } + 0 +} + +#[cfg(not(target_os = "linux"))] +fn detect_optimal_io_size(_file: &File) -> usize { + 0 +} + +#[cfg(target_os = "linux")] +fn available_host_memory_bytes() -> Option { + let info = std::fs::read_to_string("/proc/meminfo").ok()?; + for line in info.lines() { + if let Some(rest) = line.strip_prefix("MemAvailable:") { + let kib = rest.split_whitespace().next()?.parse::().ok()?; + return kib.checked_mul(1024); + } + } + None +} + +#[cfg(not(target_os = "linux"))] +fn available_host_memory_bytes() -> Option { + None +} + +fn choose_io_plan( + ranks: usize, + cpus: usize, + optimal_io_size: usize, + available_host_ram: Option, + payload_bytes: u64, + needs_staging: bool, +) -> IoPlan { + let ranks = ranks.max(1); + let cpus = cpus.max(1); + let readers = (cpus / ranks).clamp(MIN_READERS, READERS); + + let mut chunk_bytes = if ranks == 1 { + MAX_CHUNK + } else { + (MAX_CHUNK / ranks).clamp(MIN_CHUNK, MAX_CHUNK) + }; + if optimal_io_size >= BLOCK && optimal_io_size <= MAX_CHUNK && optimal_io_size % BLOCK == 0 { + chunk_bytes = chunk_bytes + .next_multiple_of(optimal_io_size) + .min(MAX_CHUNK); + } + chunk_bytes = chunk_bytes.next_multiple_of(BLOCK); + if payload_bytes > 0 && (payload_bytes as usize) < chunk_bytes { + chunk_bytes = (payload_bytes as usize) + .next_multiple_of(BLOCK) + .clamp(BLOCK, chunk_bytes); + } + + let slots = if !needs_staging { + 0 + } else { + let total_budget = available_host_ram + .map(|ram| ((ram / 200) as usize).clamp(MIN_STAGING_BYTES, MAX_STAGING_BYTES)) + .unwrap_or(MAX_STAGING_BYTES); + let per_rank_budget = (total_budget / ranks).max(chunk_bytes.saturating_mul(2)); + let staging_slot_bytes = chunk_bytes.saturating_add(2 * BLOCK); + let budget_slots = (per_rank_budget / staging_slot_bytes).max(2); + readers.saturating_mul(2).min(budget_slots) + }; + + IoPlan { + chunk_bytes, + readers, + slots, + } +} + +struct AlignedBuffer { + address: usize, + len: usize, +} + +impl AlignedBuffer { + fn new(len: usize) -> Result { + let len = len.max(BLOCK).next_multiple_of(BLOCK); + let address = crate::os::allocate_aligned(len) + .map_err(|error| invalid(format!("allocate aligned I/O buffer: {error}")))?; + Ok(Self { address, len }) + } + + fn as_mut_slice(&mut self) -> &mut [u8] { + // SAFETY: `address` owns `len` writable bytes until Drop. + unsafe { std::slice::from_raw_parts_mut(self.address as *mut u8, self.len) } + } +} + +impl Drop for AlignedBuffer { + fn drop(&mut self) { + // SAFETY: Matches `allocate_aligned(self.len)`. + unsafe { crate::os::free_aligned(self.address, self.len) }; + } +} + struct Staging<'a> { driver: &'a Driver, buffers: Vec, @@ -199,7 +334,7 @@ impl Drop for Staging<'_> { } } -struct Chunk { +pub(super) struct Chunk { file: Arc, file_offset: u64, destination: u64, @@ -217,56 +352,206 @@ impl Chunk { ) } + fn can_read_direct_into_host(&self) -> bool { + matches!(self.memory, Memory::MappedHost) + && self.nbytes > 0 + && self.file_offset % BLOCK as u64 == 0 + && self.destination % BLOCK as u64 == 0 + && self.nbytes % BLOCK == 0 + } + fn read<'a>(&self, file: &File, buffer: &'a mut [u8]) -> io::Result<&'a [u8]> { let (offset, skip, nbytes) = self.read_range(); - let read = loop { - match file.read_at(&mut buffer[..nbytes], offset) { + let required = skip + self.nbytes; + let mut done = 0usize; + while done < required { + match file.read_at(&mut buffer[done..nbytes], offset + done as u64) { + Ok(0) => { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "short model payload read", + )); + } + Ok(n) => { + done += n; + if done < required && done % BLOCK != 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "short model payload read", + )); + } + } Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, - result => break result?, + Err(error) => return Err(error), } - }; - if read < skip + self.nbytes { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "short model payload read", - )); } Ok(&buffer[skip..skip + self.nbytes]) } + + /// Read a `BLOCK`-aligned `MappedHost` chunk directly into its mapped destination. + /// + /// # Safety + /// `self.destination..self.destination + self.nbytes` must be live, writable, + /// `BLOCK`-aligned host memory disjoint from every concurrent reader. + unsafe fn read_direct_into_host(&self, file: &File) -> io::Result<()> { + let dst = + unsafe { std::slice::from_raw_parts_mut(self.destination as *mut u8, self.nbytes) }; + let mut done = 0usize; + while done < self.nbytes { + match file.read_at(&mut dst[done..], self.file_offset + done as u64) { + Ok(0) => { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "short model payload read", + )); + } + Ok(n) => { + done += n; + if done < self.nbytes && done % BLOCK != 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "short model payload read", + )); + } + } + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + } + } + Ok(()) + } } -/// The owner's mapped allocations must be live and unused by graph execution. -pub(super) unsafe fn load( - owner: &NativeResources, +fn push_span_chunks( + chunks: &mut Vec, + file: &Arc, + mut file_offset: u64, + mut destination: u64, + mut remaining: usize, + chunk_bytes: usize, + memory: Memory, +) { + if matches!(memory, Memory::MappedHost) + && remaining >= BLOCK + && file_offset % BLOCK as u64 == destination % BLOCK as u64 + { + let head = ((BLOCK as u64 - (file_offset % BLOCK as u64)) % BLOCK as u64) as usize; + if head > 0 && head < remaining { + chunks.push(Chunk { + file: file.clone(), + file_offset, + destination, + nbytes: head, + memory, + }); + file_offset += head as u64; + destination += head as u64; + remaining -= head; + } + let aligned_body = remaining - (remaining % BLOCK); + let mut start = 0; + while start < aligned_body { + let nbytes = chunk_bytes.min(aligned_body - start); + chunks.push(Chunk { + file: file.clone(), + file_offset: file_offset + start as u64, + destination: destination + start as u64, + nbytes, + memory, + }); + start += nbytes; + } + file_offset += aligned_body as u64; + destination += aligned_body as u64; + remaining -= aligned_body; + } + let mut start = 0; + while start < remaining { + let nbytes = chunk_bytes.min(remaining - start); + chunks.push(Chunk { + file: file.clone(), + file_offset: file_offset + start as u64, + destination: destination + start as u64, + nbytes, + memory, + }); + start += nbytes; + } +} + +fn tier_io_plan( files: &F, core: &Core, - phase: &Phase, ranks: usize, -) -> Result<()> { - let chunk_bytes = CHUNK / ranks; + memory_filter: Memory, +) -> Result<(IoPlan, u64)> { + let mut payload_bytes = 0u64; + let mut first_file: Option> = None; + for allocation in &core.allocations { + if allocation.memory != memory_filter { + continue; + } + let stored = allocation.stored_bytes() as u64; + if stored == 0 { + continue; + } + payload_bytes += stored; + if first_file.is_none() { + if let Some(source) = allocation.sources.first() { + let span = files.span(core, &source.resource)?; + first_file = Some(files.source(span)?.0.file.clone()); + } else if let Some(file) = &allocation.file { + let span = files.span(core, file)?; + first_file = Some(files.source(span)?.0.file.clone()); + } + } + } + let cpus = thread::available_parallelism().map_or(READERS, usize::from); + let optimal_io_size = first_file + .as_deref() + .map_or(0, detect_optimal_io_size); + let plan = choose_io_plan( + ranks, + cpus, + optimal_io_size, + available_host_memory_bytes(), + payload_bytes, + matches!(memory_filter, Memory::Device), + ); + Ok((plan, payload_bytes)) +} + +fn collect_tier_chunks( + owner: &NativeResources, + files: &F, + core: &Core, + chunk_bytes: usize, + memory_filter: Memory, +) -> Result> { let mut chunks = Vec::new(); for allocation in &core.allocations { + if allocation.memory != memory_filter { + continue; + } if allocation.is_payload_bound() { // Every span names the payload resource that supplies it, so initializations that draw // from several payloads stay exact: no ordering or contiguity is assumed across spans. for (source, [offset, nbytes]) in allocation.sources.iter().zip(allocation.spans()) { let span = files.span(core, &source.resource)?; let (file, base) = files.source(span)?; - let mut file_offset = base + let file_offset = base .checked_add(source.offset) .ok_or_else(|| invalid("allocation source offset overflow"))?; - for start in (0..nbytes).step_by(chunk_bytes) { - let nbytes = chunk_bytes.min(nbytes - start); - chunks.push(Chunk { - file: file.file.clone(), - file_offset, - destination: owner.allocations[&allocation.name].address - + (offset + start) as u64, - nbytes, - memory: allocation.memory, - }); - file_offset += nbytes as u64; - } + let destination = owner.allocations[&allocation.name].address + offset as u64; + push_span_chunks( + &mut chunks, + &file.file, + file_offset, + destination, + nbytes, + chunk_bytes, + allocation.memory, + ); } continue; } @@ -276,24 +561,241 @@ pub(super) unsafe fn load( let span = files.span(core, file)?; let (source, mut file_offset) = files.source(span)?; for [offset, nbytes] in allocation.spans() { - for start in (0..nbytes).step_by(chunk_bytes) { - let nbytes = chunk_bytes.min(nbytes - start); - chunks.push(Chunk { - file: source.file.clone(), - file_offset, - destination: owner.allocations[&allocation.name].address - + (offset + start) as u64, - nbytes, - memory: allocation.memory, - }); - file_offset += nbytes as u64; - } + let destination = owner.allocations[&allocation.name].address + offset as u64; + push_span_chunks( + &mut chunks, + &source.file, + file_offset, + destination, + nbytes, + chunk_bytes, + allocation.memory, + ); + file_offset += nbytes as u64; } } + Ok(chunks) +} + +/// Coordinates pipelined `cuMemHostRegister_v2` chunks with `MappedHost` `O_DIRECT` readers so +/// readers never issue DMA into an unregistered chunk while avoiding CUDA context lock stalls +/// during `Device` weight uploads. +pub(super) struct RegistrationGate { + state: Mutex<(usize, bool)>, + ready: Condvar, + chunk_ends: Vec, +} + +impl RegistrationGate { + pub(super) fn new(chunk_ends: Vec) -> Self { + Self { + state: Mutex::new((0, false)), + ready: Condvar::new(), + chunk_ends, + } + } + + pub(super) fn required_index(&self, destination: u64, nbytes: usize) -> usize { + if self.chunk_ends.is_empty() || nbytes == 0 { + return 0; + } + let last_byte = destination.saturating_add((nbytes - 1) as u64); + self.chunk_ends + .partition_point(|&end| end <= last_byte) + .min(self.chunk_ends.len() - 1) + } + + pub(super) fn advance(&self) { + let mut state = self.state.lock().unwrap(); + state.0 += 1; + self.ready.notify_all(); + } + + pub(super) fn close(&self) { + let mut state = self.state.lock().unwrap(); + state.1 = true; + self.ready.notify_all(); + } + + fn wait_for(&self, required: usize, cancel: &AtomicBool) -> bool { + if self.chunk_ends.is_empty() { + return !cancel.load(Ordering::Relaxed); + } + let mut state = self.state.lock().unwrap(); + while state.0 <= required && !state.1 && !cancel.load(Ordering::Relaxed) { + state = self.ready.wait(state).unwrap(); + } + state.0 > required && !cancel.load(Ordering::Relaxed) + } +} + +/// Collect `MappedHost` payload chunks and their runtime I/O plan for background loading. +pub(super) fn collect_mapped_host_chunks( + owner: &NativeResources, + files: &F, + core: &Core, + ranks: usize, + gate: Option<&RegistrationGate>, +) -> Result<(Vec, usize)> { + let (plan, _) = tier_io_plan(files, core, ranks, Memory::MappedHost)?; + let mut chunks = collect_tier_chunks(owner, files, core, plan.chunk_bytes, Memory::MappedHost)?; + if let Some(gate) = gate { + // Stable sort by registration chunk index so O_DIRECT readers stream chunks in the + // exact order cuMemHostRegister_v2 publishes them, while preserving sequential file + // order within each registration chunk. + chunks.sort_by_key(|chunk| gate.required_index(chunk.destination, chunk.nbytes)); + } + Ok((chunks, plan.readers)) +} + +/// Load `MappedHost` payload chunks without touching CUDA contexts or GPU staging. +/// +/// # Safety +/// Every chunk destination must reference live, writable, disjoint mapped host memory +/// that remains mapped until this function returns. +pub(super) unsafe fn load_mapped_host_chunks( + chunks: &[Chunk], + path: &Path, + phase: &Phase, + readers: usize, + cancel: &AtomicBool, + gate: Option<&RegistrationGate>, +) -> Result<()> { if chunks.is_empty() { return Ok(()); } - let count = SLOTS.min(chunks.len()); + let worker_count = readers.min(chunks.len()).max(1); + let next = AtomicUsize::new(0); + let first_error: Mutex> = Mutex::new(None); + thread::scope(|scope| -> Result<()> { + let mut workers = Vec::with_capacity(worker_count); + for index in 0..worker_count { + let next = &next; + let first_error = &first_error; + let path = path.to_path_buf(); + workers.push( + thread::Builder::new() + .name(format!("flare-host-reader-{index}")) + .spawn_scoped(scope, move || { + let mut direct: Option<(usize, File)> = None; + let mut bounce: Option = None; + loop { + if cancel.load(Ordering::Relaxed) { + break; + } + let idx = next.fetch_add(1, Ordering::Relaxed); + if idx >= chunks.len() { + break; + } + let chunk = &chunks[idx]; + if let Some(gate) = gate { + let required = gate.required_index(chunk.destination, chunk.nbytes); + if !gate.wait_for(required, cancel) { + break; + } + } + let result = (|| -> Result<()> { + let key = Arc::as_ptr(&chunk.file) as usize; + if !matches!(direct, Some((cached, _)) if cached == key) { + direct = None; + let reopened = crate::os::direct_reopen(&chunk.file).map_err( + |error| { + invalid(format!( + "open core payload for direct I/O: {error}" + )) + }, + )?; + direct = Some((key, reopened)); + } + let file = &direct.as_ref().unwrap().1; + if chunk.can_read_direct_into_host() { + // SAFETY: Caller guarantees destination is live, writable, + // BLOCK-aligned, and disjoint across chunks. + unsafe { chunk.read_direct_into_host(file) }.map_err( + |error| { + invalid(format!( + "read {} at {}: {error}", + path.display(), + chunk.file_offset + )) + }, + )?; + } else { + let (_, _, nbytes) = chunk.read_range(); + let needs_alloc = bounce + .as_ref() + .is_none_or(|buf| buf.len < nbytes); + if needs_alloc { + bounce = Some(AlignedBuffer::new(nbytes)?); + } + let buf = bounce.as_mut().unwrap().as_mut_slice(); + let bytes = chunk.read(file, &mut buf[..nbytes]).map_err( + |error| { + invalid(format!( + "read {} at {}: {error}", + path.display(), + chunk.file_offset + )) + }, + )?; + // SAFETY: Caller guarantees destination is live, writable, + // and disjoint across chunks. + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + chunk.destination as *mut u8, + chunk.nbytes, + ); + } + } + phase.advance_bytes(chunk.nbytes as u64); + Ok(()) + })(); + if let Err(error) = result { + cancel.store(true, Ordering::Relaxed); + let mut slot = first_error.lock().unwrap(); + if slot.is_none() { + *slot = Some(error); + } + break; + } + } + }) + .map_err(|e| e.to_string())?, + ); + } + for worker in workers { + worker + .join() + .map_err(|_| invalid("host payload reader panicked"))?; + } + Ok(()) + })?; + if let Some(error) = first_error.into_inner().unwrap() { + return Err(error); + } + Ok(()) +} + +/// Load `Device` payload chunks using double-buffered pinned staging and async GPU uploads. +/// +/// # Safety +/// The owner's mapped device allocations must be live and unused by graph execution, +/// and the owner's CUDA context must be current on the calling thread. +pub(super) unsafe fn load_device( + owner: &NativeResources, + files: &F, + core: &Core, + phase: &Phase, + ranks: usize, +) -> Result<()> { + let (plan, _) = tier_io_plan(files, core, ranks, Memory::Device)?; + let chunks = collect_tier_chunks(owner, files, core, plan.chunk_bytes, Memory::Device)?; + if chunks.is_empty() { + return Ok(()); + } + let count = plan.slots.min(chunks.len()).max(1); + let readers = plan.readers.min(count).max(1); let chunk_size = chunks .iter() .map(|chunk| chunk.read_range().2) @@ -310,7 +812,7 @@ pub(super) unsafe fn load( let (work, available) = mpsc::sync_channel::<(usize, usize)>(count); let available = Arc::new(Mutex::new(available)); let (ready, finished) = mpsc::sync_channel(count); - for index in 0..READERS.min(count) { + for index in 0..readers { let (available, chunks, buffers, ready, path) = ( available.clone(), &chunks, @@ -344,27 +846,17 @@ pub(super) unsafe fn load( let file = &direct.as_ref().unwrap().1; let (_, _, nbytes) = chunk.read_range(); // SAFETY: A slot has one reader and is returned only after - // its upload event completes. Host chunks are disjoint - // validated ranges in mappings retained until scope exit. + // its upload event completes. let destination = unsafe { std::slice::from_raw_parts_mut(buffers[slot] as *mut u8, nbytes) }; - let bytes = chunk.read(file, destination).map_err(|error| { + chunk.read(file, destination).map_err(|error| { invalid(format!( "read {} at {}: {error}", path.display(), chunk.file_offset )) })?; - if matches!(chunk.memory, Memory::MappedHost) { - unsafe { - std::ptr::copy_nonoverlapping( - bytes.as_ptr(), - chunk.destination as *mut u8, - chunk.nbytes, - ); - } - } Ok(()) })(); if ready.send((slot, index, result)).is_err() { @@ -394,28 +886,25 @@ pub(super) unsafe fn load( let (slot, index) = if let Some((slot, index, result)) = read { result?; let chunk = &chunks[index]; - if matches!(chunk.memory, Memory::Device) { - // SAFETY: This slot remains unavailable to readers until its - // event has completed; the owner retains the destination. - unsafe { - owner.driver.check( - "cuMemcpyHtoDAsync_v2", - (owner.driver.upload_async)( - chunk.destination, - staging.buffers[slot].byte_add(chunk.read_range().1), - chunk.nbytes, - staging.stream, - ), - )?; - owner.driver.check( - "cuEventRecord", - (owner.driver.event_record)(staging.events[slot], staging.stream), - )?; - } - inflight.push_back((slot, index)); - continue; + // SAFETY: This slot remains unavailable to readers until its + // event has completed; the owner retains the destination. + unsafe { + owner.driver.check( + "cuMemcpyHtoDAsync_v2", + (owner.driver.upload_async)( + chunk.destination, + staging.buffers[slot].byte_add(chunk.read_range().1), + chunk.nbytes, + staging.stream, + ), + )?; + owner.driver.check( + "cuEventRecord", + (owner.driver.event_record)(staging.events[slot], staging.stream), + )?; } - (slot, index) + inflight.push_back((slot, index)); + continue; } else { let (slot, index) = inflight.pop_front().unwrap(); // SAFETY: Each event follows the upload that owns this slot. @@ -439,9 +928,24 @@ pub(super) unsafe fn load( }) } +/// The owner's mapped allocations must be live and unused by graph execution. +pub(super) unsafe fn load( + owner: &NativeResources, + files: &F, + core: &Core, + phase: &Phase, + ranks: usize, +) -> Result<()> { + unsafe { load_device(owner, files, core, phase, ranks)? }; + let (host_chunks, readers) = collect_mapped_host_chunks(owner, files, core, ranks, None)?; + let cancel = AtomicBool::new(false); + unsafe { load_mapped_host_chunks(&host_chunks, files.path(), phase, readers, &cancel, None) } +} + #[cfg(test)] mod tests { use super::*; + use crate::startup::StartupProgress; use std::fs::OpenOptions; use std::io::{Seek, SeekFrom, Write}; @@ -480,4 +984,109 @@ mod tests { ); } } + + #[test] + fn io_plan_double_buffers_and_respects_memory_and_rank_bounds() { + let big = choose_io_plan(1, 72, 1 << 20, Some(512 << 30), 240 << 30, true); + assert_eq!(big.chunk_bytes, 8 << 20); + assert_eq!(big.readers, 8); + assert_eq!(big.slots, 15); // 128 MiB cap / (8 MiB + 8 KiB) = 15 + + let tp4 = choose_io_plan(4, 32, 1 << 20, Some(128 << 30), 60 << 30, true); + assert_eq!(tp4.chunk_bytes, 2 << 20); + assert_eq!(tp4.readers, 8); + assert!(tp4.slots >= 8 && tp4.slots <= 16); + + let tight = choose_io_plan(1, 16, 0, Some(1 << 30), 10 << 30, true); + assert_eq!(tight.chunk_bytes, 8 << 20); + assert!(tight.slots >= 2); + + let host_only = choose_io_plan(1, 72, 1 << 20, Some(512 << 30), 300 << 30, false); + assert_eq!(host_only.slots, 0); + assert_eq!(host_only.readers, 8); + + let tiny = choose_io_plan(1, 16, 0, Some(64 << 30), 12 * 1024, true); + assert_eq!(tiny.chunk_bytes, 12 * 1024); + } + + #[test] + fn mapped_host_loader_uses_zero_copy_when_aligned_and_preserves_unaligned_edges() { + let path = std::env::temp_dir().join(format!( + "helios-mapped-host-load-{}", + std::process::id() + )); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create_new(true) + .open(&path) + .unwrap(); + let total = 4 * BLOCK + 513; + let data: Vec = (0..total).map(|i| ((i * 31 + 7) % 251) as u8).collect(); + file.write_all(&data).unwrap(); + file.sync_all().unwrap(); + let pinned = Arc::new(File::open(&path).unwrap()); + std::fs::remove_file(&path).unwrap(); + + let cases = [ + // Perfectly aligned: 100% zero-copy direct read. + (0u64, 0usize, 3 * BLOCK, true), + // Matching non-zero mod 4096: staged head + zero-copy body + staged tail. + (137u64, 137usize, 3 * BLOCK + 111, true), + // Mismatched mod 4096: clean staged fallback. + (137u64, 19usize, 2 * BLOCK + 73, false), + ]; + + let phase = StartupProgress::silent().phase("Load weights", None); + for (file_off, dst_off, len, expect_direct_body) in cases { + let mut dest = AlignedBuffer::new(dst_off + len + BLOCK).unwrap(); + dest.as_mut_slice().fill(0x5a); + let dst_addr = dest.address as u64 + dst_off as u64; + let mut chunks = Vec::new(); + push_span_chunks( + &mut chunks, + &pinned, + file_off, + dst_addr, + len, + 2 * BLOCK, + Memory::MappedHost, + ); + assert_eq!( + chunks.iter().any(Chunk::can_read_direct_into_host), + expect_direct_body + ); + let cancel = AtomicBool::new(false); + unsafe { + load_mapped_host_chunks(&chunks, Path::new("fixture"), &phase, 4, &cancel, None) + } + .unwrap(); + let got = &dest.as_mut_slice()[dst_off..dst_off + len]; + let expected = &data[file_off as usize..file_off as usize + len]; + assert_eq!(got, expected); + } + } + + #[test] + fn registration_gate_orders_chunk_indices_and_wakes_on_advance_and_close() { + let gate = RegistrationGate::new(vec![0x2000_0000, 0x4000_0000, 0x6000_0000]); + assert_eq!(gate.required_index(0x1000_0000, 4096), 0); + // Spans boundary between chunk 0 and chunk 1 -> requires chunk 1. + assert_eq!(gate.required_index(0x1FFF_F000, 8192), 1); + assert_eq!(gate.required_index(0x4000_0000, 4096), 2); + + let cancel = AtomicBool::new(false); + thread::scope(|scope| { + let waiter = scope.spawn(|| { + assert!(gate.wait_for(0, &cancel)); + assert!(gate.wait_for(1, &cancel)); + // Chunk 2 will be closed before advancing -> returns false. + assert!(!gate.wait_for(2, &cancel)); + }); + gate.advance(); + gate.advance(); + gate.close(); + waiter.join().unwrap(); + }); + } } diff --git a/helios/src/server.rs b/helios/src/server.rs index 1a2da9c06..067da5a4f 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -29,6 +29,8 @@ mod session; pub use session::{LoadedSession, ServingSession}; pub(crate) mod token_spans; pub use config::Bootstrap; +#[cfg(feature = "runtime-core")] +pub(crate) use config::{PreloadedFrontend, preload_frontend}; pub use dashboard::view; pub use metrics::Snapshot; pub use runtime::{Generation, GenerationEvent, ModelRuntime, Prompt}; diff --git a/helios/src/server/config.rs b/helios/src/server/config.rs index 6b0467379..83e936195 100644 --- a/helios/src/server/config.rs +++ b/helios/src/server/config.rs @@ -17,6 +17,128 @@ use crate::{ }; use serde_json::Value; +pub(crate) struct PreloadedFrontend { + key: serde_json::Value, + frontend: Frontend, +} + +fn frontend_cache_key(object: &serde_json::Map) -> Value { + serde_json::json!({ + "assets": object.get("assets"), + "frontend": object.get("frontend"), + "template_defaults": object.get("template_defaults"), + "contract_frontend": object.get("model_contract").and_then(|c| c.get("frontend")), + }) +} + +fn load_frontend_inner( + object: &serde_json::Map, + frontend_settings: &FrontendSettings, + contract_frontend: &crate::model::contract::FrontendContract, +) -> Result { + let assets = object + .get("assets") + .and_then(Value::as_object) + .ok_or("assets must contain verified frontend descriptors")?; + let jinja = matches!( + frontend_settings.prompt_encoder, + crate::frontend::PromptEncoder::Jinja + ); + let expected = if jinja { + &["tokenizer", "chat_template"][..] + } else { + &["tokenizer"][..] + }; + if assets.len() != expected.len() || expected.iter().any(|name| !assets.contains_key(*name)) { + return Err( + format!("runtime assets must contain exactly {}", expected.join(" and ")).into(), + ); + } + let asset = |name: &str| -> Result { + let descriptor = assets + .get(name) + .ok_or_else(|| format!("missing asset {name}"))?; + Ok(Asset { + range: match (descriptor.get("offset"), descriptor.get("nbytes")) { + (None, None) => None, + (Some(offset), Some(size)) => Some(( + offset.as_u64().ok_or("invalid asset offset")?, + usize::try_from(size.as_u64().ok_or("invalid asset size")?) + .map_err(|_| "asset size exceeds usize")?, + )), + _ => return Err("asset range requires offset and nbytes".into()), + }, + path: descriptor + .get("path") + .and_then(Value::as_str) + .ok_or("asset path must be a string")? + .into(), + sha256: descriptor + .get("sha256") + .and_then(Value::as_str) + .ok_or("asset sha256 must be a string")? + .into(), + }) + }; + let mut defaults = match object.get("template_defaults") { + None => serde_json::Map::new(), + Some(Value::Object(defaults)) => defaults.clone(), + _ => return Err("template_defaults must be an object".into()), + }; + defaults + .entry("add_generation_prompt") + .or_insert(Value::Bool(true)); + let frontend = Frontend::load_with_settings( + FrontendAssets { + tokenizer: asset("tokenizer")?, + tokens: frontend_settings.tokenizer.clone(), + chat_template: jinja.then(|| asset("chat_template")).transpose()?, + }, + defaults, + frontend_settings, + )?; + let declared = crate::model::declared_control_tokens(&frontend, contract_frontend)?; + let frontend = frontend.with_controls(declared); + frontend.prepare_token_bytes()?; + Ok(frontend) +} + +/// Pre-load the tokenizer and chat template from prepared server config on a background CPU thread. +pub(crate) fn preload_frontend(server_config: &Value) -> Result { + let object = server_config + .as_object() + .ok_or("server configuration must be a JSON object")?; + let frontend_settings: FrontendSettings = serde_json::from_value( + object + .get("frontend") + .ok_or("prepared frontend settings are required")? + .clone(), + ) + .map_err(|error| { + crate::ExecutionError::Manifest(crate::Failure::caused_by( + "invalid prepared frontend settings", + error, + )) + })?; + let contract: crate::model::PreparedContract = serde_json::from_value( + object + .get("model_contract") + .ok_or("prepared model contract is required")? + .clone(), + ) + .map_err(|error| { + crate::ExecutionError::Manifest(crate::Failure::caused_by( + "invalid prepared model contract", + error, + )) + })?; + let frontend = load_frontend_inner(object, &frontend_settings, &contract.frontend)?; + Ok(PreloadedFrontend { + key: frontend_cache_key(object), + frontend, + }) +} + pub struct Bootstrap { pub model: ModelConfig, pub frontend: Frontend, @@ -25,7 +147,15 @@ pub struct Bootstrap { } impl Bootstrap { pub fn load(json: &str, manifest: &ExecutionManifest) -> Result { - Self::load_inner(json, manifest).map_err(|error| match error { + Self::load_with_preloaded(json, manifest, None) + } + + pub(crate) fn load_with_preloaded( + json: &str, + manifest: &ExecutionManifest, + preloaded: Option, + ) -> Result { + Self::load_inner(json, manifest, preloaded).map_err(|error| match error { crate::Error::Execution(crate::ExecutionError::State(_)) => { crate::ExecutionError::Manifest(crate::Failure::caused_by(error.to_string(), error)) .into() @@ -34,7 +164,11 @@ impl Bootstrap { }) } - fn load_inner(json: &str, manifest: &ExecutionManifest) -> Result { + fn load_inner( + json: &str, + manifest: &ExecutionManifest, + preloaded: Option, + ) -> Result { let value: Value = serde_json::from_str(json).map_err(|error| { crate::ExecutionError::Manifest(crate::Failure::caused_by( format!("invalid server configuration JSON: {error}"), @@ -212,61 +346,10 @@ impl Bootstrap { .retain(|g| manifest.graphs.iter().any(|m| m.name == g.graph)); model.fit_context(); crate::model::catalog::validate(&model, manifest)?; - let assets = object - .get("assets") - .and_then(Value::as_object) - .ok_or("assets must contain verified frontend descriptors")?; - let jinja = matches!(frontend_settings.prompt_encoder, crate::frontend::PromptEncoder::Jinja); - let expected = if jinja { &["tokenizer", "chat_template"][..] } else { &["tokenizer"][..] }; - if assets.len() != expected.len() || expected.iter().any(|name| !assets.contains_key(*name)) { - return Err(format!("runtime assets must contain exactly {}", expected.join(" and ")).into()); - } - let asset = |name: &str| -> Result { - let descriptor = assets - .get(name) - .ok_or_else(|| format!("missing asset {name}"))?; - Ok(Asset { - range: match (descriptor.get("offset"), descriptor.get("nbytes")) { - (None, None) => None, - (Some(offset), Some(size)) => Some(( - offset.as_u64().ok_or("invalid asset offset")?, - usize::try_from(size.as_u64().ok_or("invalid asset size")?) - .map_err(|_| "asset size exceeds usize")?, - )), - _ => return Err("asset range requires offset and nbytes".into()), - }, - path: descriptor - .get("path") - .and_then(Value::as_str) - .ok_or("asset path must be a string")? - .into(), - sha256: descriptor - .get("sha256") - .and_then(Value::as_str) - .ok_or("asset sha256 must be a string")? - .into(), - }) + let frontend = match preloaded { + Some(preloaded) if preloaded.key == frontend_cache_key(object) => preloaded.frontend, + _ => load_frontend_inner(object, &frontend_settings, &model.contract.frontend)?, }; - let mut defaults = match object.get("template_defaults") { - None => serde_json::Map::new(), - Some(Value::Object(defaults)) => defaults.clone(), - _ => return Err("template_defaults must be an object".into()), - }; - defaults - .entry("add_generation_prompt") - .or_insert(Value::Bool(true)); - let frontend = Frontend::load_with_settings( - FrontendAssets { - tokenizer: asset("tokenizer")?, - tokens: frontend_settings.tokenizer.clone(), - chat_template: jinja.then(|| asset("chat_template")).transpose()?, - }, - defaults, - &frontend_settings, - )?; - let declared = crate::model::declared_control_tokens(&frontend, &model.contract.frontend)?; - let frontend = frontend.with_controls(declared); - frontend.prepare_token_bytes()?; if frontend_settings .image .as_ref() diff --git a/helios/src/server/session.rs b/helios/src/server/session.rs index a54b75aa9..0aed24b11 100644 --- a/helios/src/server/session.rs +++ b/helios/src/server/session.rs @@ -23,7 +23,7 @@ pub struct LoadedSession { } impl LoadedSession { - pub fn new(owner: NativeModel, config: serde_json::Value) -> Result { + pub fn new(mut owner: NativeModel, config: serde_json::Value) -> Result { if owner.cluster().is_some() { return Err("an owned local session requires every model rank in this process".into()); } @@ -31,7 +31,9 @@ impl LoadedSession { let manifest = manifests.next().ok_or("loaded core has no rank")?; let remaining: Vec<_> = manifests.collect(); let peers = (!remaining.is_empty()).then_some(RankPeers::Threads(remaining)); - let mut bootstrap = Bootstrap::load(&config.to_string(), &manifest)?; + let preloaded = owner.take_preloaded_frontend(); + let mut bootstrap = + Bootstrap::load_with_preloaded(&config.to_string(), &manifest, preloaded)?; bootstrap.server.log_to_stderr = false; Ok(Self { manifest, diff --git a/helios/src/startup.rs b/helios/src/startup.rs index 9c39e5249..93486ed17 100644 --- a/helios/src/startup.rs +++ b/helios/src/startup.rs @@ -108,10 +108,7 @@ pub struct StartupSnapshot { #[derive(Clone, Default)] pub struct StartupObservation { latest: Arc>>, - /// The final snapshot of every phase that completed, oldest first. Only - /// unit tests record and read these, to check each phase's reported text - /// and counters; other builds retain the latest snapshot alone. - #[cfg(test)] + /// The final snapshot of every phase that completed, oldest first. completed: Arc>>, } @@ -123,8 +120,7 @@ impl StartupObservation { /// The final snapshots of the phases that completed, in completion order. /// A phase dropped without finishing is absent; `snapshot` shows it as a /// failure. - #[cfg(test)] - pub fn completed_phases(&self) -> Vec { + pub(crate) fn completed_phases(&self) -> Vec { self.completed.lock().unwrap_or_else(|e| e.into_inner()).clone() } @@ -135,9 +131,8 @@ impl StartupObservation { sequence, stage: state.stage, status, label: state.label.chars().take(512).collect(), detail: state.detail.chars().take(512).collect(), - completed: state.completed, total: state.total, elapsed: state.started.elapsed(), + completed: state.completed, total: state.total, elapsed: state.elapsed.unwrap_or_else(|| state.started.elapsed()), }; - #[cfg(test)] if status == StartupStatus::Complete { self.completed.lock().unwrap_or_else(|e| e.into_inner()).push(snapshot.clone()); } @@ -179,6 +174,34 @@ impl StartupProgress { (progress, observation) } + /// Replay phases completed in a background overlapped worker onto this progress sink. + pub(crate) fn replay_completed(&self, snapshots: &[StartupSnapshot]) { + for snapshot in snapshots { + let state = State { + stage: snapshot.stage, + label: snapshot.label.clone(), + detail: if snapshot.detail.is_empty() { + "overlapped".to_owned() + } else { + format!("{} · overlapped", snapshot.detail) + }, + started: Instant::now(), + elapsed: Some(snapshot.elapsed), + completed: snapshot.completed, + total: snapshot.total, + }; + if let Some(observation) = &self.observation { + observation.publish(&state, StartupStatus::Complete); + } + if self.enabled { + self.output + .lock() + .unwrap() + .write(&state, self.terminal, Status::Ok); + } + } + } + /// Whether phases write anything at all. pub fn is_enabled(&self) -> bool { self.enabled