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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions flare-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions flare/src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
5 changes: 4 additions & 1 deletion helios/src/engram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -612,6 +613,7 @@ impl Shared {
workers: usize,
resident_scales: bool,
prefetch: bool,
progress: Option<&Phase>,
) -> Result<Arc<Self>> {
if storage == Storage::Ram && cache_bytes != 0 {
return Err("embedding row cache requires disk table storage".into());
Expand All @@ -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,
Expand All @@ -643,6 +645,7 @@ impl Shared {
stats.clone(),
workers,
resident_scales,
progress,
)
})
.collect::<Result<Vec<_>>>()?;
Expand Down
124 changes: 114 additions & 10 deletions helios/src/engram/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand All @@ -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> {
Self::load_with_progress(file, plane, None)
}

fn load_with_progress(file: &File, plane: Plane, progress: Option<&Phase>) -> Result<Self> {
Self::initialize(plane, |address, extent, required| {
let skip = (plane.offset % BLOCK as u64) as usize;
let offset = plane.offset - skip as u64;
Expand All @@ -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(())
})
Expand Down Expand Up @@ -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)?;
Expand All @@ -373,7 +441,7 @@ impl Resident {
#[cfg(unix)]
pub(super) fn from_shared(file: File, plane: Plane) -> Result<Self> {
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;
Expand Down Expand Up @@ -1290,6 +1358,30 @@ impl Reader {
stats: Arc<Stats>,
workers: usize,
resident_scales: bool,
) -> Result<Self> {
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<File>],
planes: &[Plane; 2],
resident: bool,
cache_bytes: usize,
max_rows: usize,
stats: Arc<Stats>,
workers: usize,
resident_scales: bool,
progress: Option<&Phase>,
) -> Result<Self> {
if resident && cache_bytes != 0 {
return Err("embedding row cache requires disk table storage".into());
Expand All @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions helios/src/runtime_core/event_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
68 changes: 49 additions & 19 deletions helios/src/runtime_core/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
Loading