diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index 0261de211..8182d2750 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -665,6 +665,7 @@ fn serve( "http://{} ยท {context_tokens} tokens/request", server.address() )); + progress.complete(); #[cfg(unix)] unsafe { libc::signal(libc::SIGINT, stop as *const () as libc::sighandler_t); @@ -733,6 +734,7 @@ fn serve_local( let session = loaded.start().map_err(|failure| failure.message)?; let server = session.server(); phase.finish(format!("http://{}", server.address())); + progress.complete(); #[cfg(unix)] unsafe { libc::signal(libc::SIGINT, stop as *const () as libc::sighandler_t); diff --git a/flare/src/controller.rs b/flare/src/controller.rs index 7c44e012f..9b637c70b 100644 --- a/flare/src/controller.rs +++ b/flare/src/controller.rs @@ -2911,6 +2911,7 @@ impl Worker { } }; phase.finish(format!("http://{}", session.server().address())); + progress.complete(); // A failed advertisement leaves the session serving; the Ready detail reports it. let (advertisement, advertisement_error) = match self.settings.advertise { true => match crate::mdns::Advertisement::start(session.server()) { diff --git a/helios/src/engram.rs b/helios/src/engram.rs index 8dc7b959f..e201f151f 100644 --- a/helios/src/engram.rs +++ b/helios/src/engram.rs @@ -14,6 +14,7 @@ use crate::{ Error, Result, cuda::{Event, PinnedHost, Stream}, execution::{ExecutionManifest, GraphKind, Upload}, + startup::Phase, }; #[cfg(unix)] pub use prepared::{PlaneSource, PreparedTables, SourceSegment, TableSource}; @@ -612,6 +613,7 @@ impl Shared { workers: usize, resident_scales: bool, prefetch: bool, + progress: Option<&Phase>, ) -> Result> { if storage == Storage::Ram && cache_bytes != 0 { return Err("embedding row cache requires disk table storage".into()); @@ -634,7 +636,7 @@ impl Shared { let rows = max_tokens .checked_mul(table.heads) .ok_or("embedding row capacity exceeds host range")?; - reader::Reader::from_files( + reader::Reader::from_files_with_progress( files, &table.planes, storage == Storage::Ram, @@ -643,6 +645,7 @@ impl Shared { stats.clone(), workers, resident_scales, + progress, ) }) .collect::>>()?; diff --git a/helios/src/engram/reader.rs b/helios/src/engram/reader.rs index 69a06e71a..908d9c845 100644 --- a/helios/src/engram/reader.rs +++ b/helios/src/engram/reader.rs @@ -7,7 +7,7 @@ //! Bounded, direct-I/O row gathering into the same buffers used by resident tables. use super::{Stats, cache::RowCache}; -use crate::Result; +use crate::{Result, startup::Phase}; #[cfg(unix)] use io_uring::{EnterFlags, IoUring, opcode, types}; use std::{ @@ -181,6 +181,15 @@ impl ResidentMapping { format!("map resident embedding table: {error}") })?; let mapping = Self { address, nbytes }; + // Ask shmem to back the resident tables with transparent huge pages. + // This is only a hint: kernels or host policies that do not enable shmem + // THP, including `shmem_enabled=never`, keep the existing 4 KiB backing. + #[cfg(target_os = "linux")] + if writable { + unsafe { + libc::madvise(address as *mut libc::c_void, nbytes, libc::MADV_HUGEPAGE); + } + } // The sealed read-only remap has its own page tables, even after loading // populated the backing RAM. Prepare them before row delivery starts. if !writable @@ -210,13 +219,19 @@ impl Drop for ResidentMapping { const RESIDENT_SEALS: i32 = libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL; +// F_SEAL_FUTURE_WRITE requires Linux 5.1+. The read-only resident mapping also +// uses MADV_POPULATE_READ (Linux 5.14), so this does not raise the existing +// minimum kernel dependency. +#[cfg(target_os = "linux")] +const RESIDENT_FUTURE_SEALS: i32 = + libc::F_SEAL_FUTURE_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL; + #[cfg(unix)] -fn seal_resident(file: &File) -> Result<()> { - // The loading threads have joined and their writable mapping is gone. - // Kernel-held page references can still make F_SEAL_WRITE temporarily busy. +fn seal_resident_seals(file: &File, seals: i32) -> Result<()> { + // Kernel-held page references can still make the write seal temporarily busy. // Publish only after every required seal succeeds; persistent busy state fails. for attempt in 0..4 { - if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, RESIDENT_SEALS) } == 0 { + if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) } == 0 { return Ok(()); } let error = std::io::Error::last_os_error(); @@ -228,8 +243,37 @@ fn seal_resident(file: &File) -> Result<()> { unreachable!() } +#[cfg(unix)] +fn seal_resident(file: &File) -> Result<()> { + seal_resident_seals(file, RESIDENT_SEALS) +} + +#[cfg(target_os = "linux")] +fn seal_resident_future(file: &File) -> Result<()> { + seal_resident_seals(file, RESIDENT_FUTURE_SEALS) +} + +#[cfg(unix)] +fn has_resident_seals(seals: i32) -> bool { + if seals & RESIDENT_SEALS == RESIDENT_SEALS { + return true; + } + #[cfg(target_os = "linux")] + { + seals & RESIDENT_FUTURE_SEALS == RESIDENT_FUTURE_SEALS + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + impl Resident { pub(super) fn load(file: &File, plane: Plane) -> Result { + Self::load_with_progress(file, plane, None) + } + + fn load_with_progress(file: &File, plane: Plane, progress: Option<&Phase>) -> Result { Self::initialize(plane, |address, extent, required| { let skip = (plane.offset % BLOCK as u64) as usize; let offset = plane.offset - skip as u64; @@ -256,6 +300,9 @@ impl Resident { "resident Engram read at {source} returned {count}, requires {needed} bytes" ).into()); } + if let Some(phase) = progress { + phase.advance_bytes(nbytes as u64); + } } Ok(()) }) @@ -354,7 +401,28 @@ impl Resident { #[cfg(windows)] let address = storage.0; fill(address, extent, required)?; - #[cfg(unix)] + #[cfg(target_os = "linux")] + { + // Keep the populated mapping and make it read-only before sealing. + // Remapping a sealed file would discard every populated page table, + // requiring a second full populate pass over the resident tables. + if unsafe { libc::mprotect(address as *mut libc::c_void, extent, libc::PROT_READ) } != 0 + { + return Err(format!( + "make resident embedding table read-only: {}", + std::io::Error::last_os_error() + ) + .into()); + } + seal_resident_future(&backing)?; + Ok(Self { + storage, + file: backing, + skip, + nbytes: plane.nbytes, + }) + } + #[cfg(all(unix, not(target_os = "linux")))] { drop(storage); seal_resident(&backing)?; @@ -373,7 +441,7 @@ impl Resident { #[cfg(unix)] pub(super) fn from_shared(file: File, plane: Plane) -> Result { let seals = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GET_SEALS) }; - if seals < 0 || seals & RESIDENT_SEALS != RESIDENT_SEALS { + if seals < 0 || !has_resident_seals(seals) { return Err("resident embedding table must have immutable size and contents".into()); } let skip = (plane.offset % BLOCK as u64) as usize; @@ -1290,6 +1358,30 @@ impl Reader { stats: Arc, workers: usize, resident_scales: bool, + ) -> Result { + Self::from_files_with_progress( + files, + planes, + resident, + cache_bytes, + max_rows, + stats, + workers, + resident_scales, + None, + ) + } + + pub(super) fn from_files_with_progress( + files: &[Arc], + planes: &[Plane; 2], + resident: bool, + cache_bytes: usize, + max_rows: usize, + stats: Arc, + workers: usize, + resident_scales: bool, + progress: Option<&Phase>, ) -> Result { if resident && cache_bytes != 0 { return Err("embedding row cache requires disk table storage".into()); @@ -1299,13 +1391,25 @@ impl Reader { } let data = if resident { Data::Ram([ - Arc::new(Resident::load(&files[planes[0].file], planes[0])?), - Arc::new(Resident::load(&files[planes[1].file], planes[1])?), + Arc::new(Resident::load_with_progress( + &files[planes[0].file], + planes[0], + progress, + )?), + Arc::new(Resident::load_with_progress( + &files[planes[1].file], + planes[1], + progress, + )?), ]) } else { let mut disk = DiskReader::from_files(files, stats.clone(), workers)?; if resident_scales { - disk.resident_scales = Some(Resident::load(&files[planes[1].file], planes[1])?); + disk.resident_scales = Some(Resident::load_with_progress( + &files[planes[1].file], + planes[1], + progress, + )?); stats.resident_scale_bytes.fetch_add(planes[1].resident_bytes()? as u64, Ordering::Relaxed); } if cache_bytes != 0 { diff --git a/helios/src/runtime_core/event_tests.rs b/helios/src/runtime_core/event_tests.rs index a4d753c28..cb88f28a0 100644 --- a/helios/src/runtime_core/event_tests.rs +++ b/helios/src/runtime_core/event_tests.rs @@ -154,6 +154,7 @@ fn disk_cached_and_resident_tables_feed_native_b12x_graphs() { 1, resident_scales, true, + None, ) .unwrap(); assert!(shared.cache_bytes() <= cache_bytes); diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index 0796c7ffa..09c4ca307 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -837,7 +837,9 @@ impl NativeModel { .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 progress_total = (resident_bytes != 0).then_some(resident_bytes); + let phase = progress.phase("Prepare embedding tables", progress_total); + phase.advance_bytes(0); 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 @@ -865,26 +867,54 @@ impl NativeModel { .iter() .flat_map(|(index, _)| &index.tables) .any(|table| table.prefetch.is_some()); + // Shard groups are independent. Load them concurrently, then join in + // group order so binding order and final state remain deterministic. 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 groups: Vec<_> = engram.into_iter().zip(engram_tokens).collect(); + let direct_files = &direct_files; + let embedding_workers = options.embedding_workers(); + let phase_ref = &phase; + thread::scope(|scope| -> Result<()> { + let mut handles = Vec::with_capacity(groups.len()); + for (group, ((index, ranks), tokens)) in groups.into_iter().enumerate() { + let first = ranks[0]; + let context = model.ranks[first].context as usize; + let device = devices[first]; + handles.push( + thread::Builder::new() + .name(format!("flare-engram-rank-{group}")) + .spawn_scoped(scope, move || { + crate::engram::Shared::new( + index, + direct_files, + ranks.len(), + tokens, + context, + device, + storage, + group_budget, + embedding_workers, + embedding_table_resident_scales, + embedding_table_prefetch, + Some(phase_ref), + ) + .map(|shared| (ranks, shared)) + }) + .map_err(|error| { + invalid(format!("start Engram rank loader: {error}")) + })?, + ); } - } + for handle in handles { + let (ranks, shared) = handle + .join() + .map_err(|_| invalid("Engram rank loader panicked"))??; + for (delivery_rank, local) in ranks.into_iter().enumerate() { + bindings.push((local, shared.clone(), delivery_rank)); + } + } + Ok(()) + })?; bindings.sort_by_key(|(local, _, _)| *local); model.engram = bindings .into_iter() diff --git a/helios/src/startup.rs b/helios/src/startup.rs index 9c39e5249..384829d19 100644 --- a/helios/src/startup.rs +++ b/helios/src/startup.rs @@ -21,6 +21,7 @@ pub struct StartupProgress { terminal: bool, output: Arc>, observation: Option, + started: Instant, } /// Stable identifiers for core loading stages; labels are presentation text. @@ -159,6 +160,7 @@ impl StartupProgress { terminal: std::io::stderr().is_terminal(), output: Arc::new(Mutex::new(Output)), observation: None, + started: Instant::now(), } } @@ -168,6 +170,7 @@ impl StartupProgress { terminal: false, output: Arc::new(Mutex::new(Output)), observation: None, + started: Instant::now(), } } @@ -209,6 +212,29 @@ impl StartupProgress { /// The startup banner is static, so no background worker needs to settle. pub fn finish_animation(&mut self) {} + /// Emit the final wall-clock startup row after the server is ready. + pub fn complete(&self) { + let elapsed = self.started.elapsed(); + let state = State { + stage: StartupStage::Other, + label: "Startup complete".into(), + detail: String::new(), + started: self.started, + elapsed: Some(elapsed), + completed: 0, + total: None, + }; + if let Some(observation) = &self.observation { + observation.publish(&state, StartupStatus::Complete); + } + if self.enabled { + self.output + .lock() + .unwrap() + .write(&state, self.terminal, Status::Ok); + } + } + pub fn phase(&self, label: &str, total: Option) -> Phase { self.phase_named(StartupStage::from_label(label), label, total) } @@ -536,6 +562,18 @@ mod observation_tests { assert_eq!(snapshot.detail.chars().count(), 512); assert_eq!(snapshot.completed, 100); } + + #[test] + fn complete_publishes_the_final_startup_total() { + let (progress, observation) = StartupProgress::observed(); + progress.phase("Start server", None).finish("ready"); + progress.complete(); + let snapshot = observation.snapshot().unwrap(); + assert_eq!(snapshot.stage, StartupStage::Other); + assert_eq!(snapshot.status, StartupStatus::Complete); + assert_eq!(snapshot.label, "Startup complete"); + assert!(snapshot.detail.is_empty()); + } } #[cfg(all(test, unix))]