From 40fc3eab2b7546d4ffabbc1a4d2f3fbbb756beba Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 2 Nov 2026 20:54:19 +0100 Subject: [PATCH] Fast cold load: large-block, deep-queue reads for the sealed archive copy, the expert bank and the hash passes The cold start of the 5090 server is dominated by reading two things: the 55 GB KAR archive (copied into the sealed memfd) and the 50 GB of routed-expert tensors of shard 0 (copied into the page-locked bank). A plain read() loop asks the NVMe for one 128 KiB readahead window at a time (queue depth 1-2; the drive's max_sectors_kb is 128): 8-35 MB/s after a reboot, 2003.8 s for the first holder (docs/experiments/baseline-pair-5090.md section 9). * model-format/bulk_read.rs (new, no unsafe): N threads each read blocks of 8 MiB. Direct (default): O_DIRECT through the open file's /proc/self/fd entry (no path lookup) into 4 KiB-aligned bounce buffers, so the page cache is never touched and nothing has to be evicted; Advise: buffered pread with POSIX_FADV_WILLNEED ahead and DONTNEED behind (a bounded window); Plain: large pread + DONTNEED. Direct falls back to Advise where O_DIRECT is refused. Memory is threads x 8 MiB. Switches for A/B in one binary: LELEKA_LOAD_READ=direct|advise|plain, LELEKA_LOAD_THREADS, LELEKA_LOAD_CHUNK_MIB, LELEKA_LOAD_AHEAD_MIB; LELEKA_LOAD_READ=legacy keeps the old sequential loop for the bank. * deploy/sealed.rs: the memfd fill uses it (seal_file_report also returns how the file was read; seal_file_with_identity is unchanged). * gguf.rs read_file_span_into: spans of 64 MiB and more (the expert tensors) use it; smaller spans and every failure mode are as before. * readahead.rs (the SHA-256/CRC passes of a first verification): WILLNEED 512 MiB ahead of the reader thread. * examples/bulk_read_bench.rs + bulk_read_digest.py: offline cold-read measurement with a reproducible digest (SHA-256 over the SHA-256 of consecutive blocks), device-level read/write accounting so a shared disk shows. Measured on rnr5090 (Lexar NM610PRO, DRAM-less, HMB; kernel 7.0.0-38; another agent's jobs share the drive, so every figure carries its "other" volume; page cache of the span evicted first with posix_fadvise(DONTNEED), never drop_caches): * whole KAR file, 51.5 GiB, new default (direct, 32 x 8 MiB): 152.9 s (362 MB/s) and 159.8 s (346 MB/s, with the digest), nothing else on the drive; Cached 62 -> 59 GiB (no cache growth). Target < 5 min met. * old patterns, same day: one thread, 16-32 MiB reads (the holder's pattern) 65, 86, 105, 154 MB/s on 2-8 GiB cold slices (55 GB in 6-14 min); 8 threads x 32 MiB buffered (the old sealed.rs pattern) 240 MB/s while sharing the drive; the recorded cold-after-reboot holder 2003.8 s. * strategy matrix (4 rounds x 7 configs, fresh 2 GiB regions, MB/s per round, median of 4): advise 16x16 MiB 230 574 194 1126 (402); direct 32x8 185 554 1133 113 (369); advise 32x8 277 454 229 510 (365); plain 16x16 385 257 979 207 (321); direct 16x8 180 311 351 174 (245); direct 8x32 149 317 271 138 (210); one thread 65 201 123 86 (105). The drive's speed varies 10x between regions and moments whatever the strategy, so the multi-thread configs are indistinguishable here; every one of them beats one thread. Direct is the default because it leaves the page cache untouched (nothing to evict, the machine's free-memory state is not changed), not because it is faster. * identity: an 8 GiB slice read with the new code has the same block-digest chain as a plain sequential pass in Python (8b8b21b830cf938b1f0cec60a5a8127d2489e33e1f853cd792b18497b2b081a6, both); unit tests compare every strategy with the source for aligned and ragged spans. The engine's own SHA-256/CRC check of the sealed memfd and the replay gate are in the GPU run recorded in docs/unattended.md. Co-Authored-By: Claude Sonnet 5.5 --- crates/deploy/src/sealed.rs | 117 ++-- .../model-format/examples/bulk_read_bench.rs | 98 +++ .../model-format/examples/bulk_read_digest.py | 17 + crates/model-format/src/bulk_read.rs | 570 ++++++++++++++++++ crates/model-format/src/gguf.rs | 10 + crates/model-format/src/lib.rs | 1 + crates/model-format/src/readahead.rs | 27 + 7 files changed, 798 insertions(+), 42 deletions(-) create mode 100644 crates/model-format/examples/bulk_read_bench.rs create mode 100644 crates/model-format/examples/bulk_read_digest.py create mode 100644 crates/model-format/src/bulk_read.rs diff --git a/crates/deploy/src/sealed.rs b/crates/deploy/src/sealed.rs index d5661058..921a18a3 100644 --- a/crates/deploy/src/sealed.rs +++ b/crates/deploy/src/sealed.rs @@ -33,6 +33,22 @@ pub fn seal_file_with_identity( Err("sealed memfd archives require Linux".into()) } +#[cfg(not(target_os = "linux"))] +pub fn seal_file_report( + _path: &std::path::Path, + _expect_bytes: Option, + _progress: &mut dyn FnMut(u64, u64), +) -> Result< + ( + std::fs::File, + Option, + leleka_model_format::bulk_read::Report, + ), + String, +> { + Err("sealed memfd archives require Linux".into()) +} + #[cfg(not(target_os = "linux"))] pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> { Err("inherited descriptors require Linux".into()) @@ -73,7 +89,7 @@ mod linux { process::Command, sync::{ Mutex, - atomic::{AtomicU64, AtomicUsize, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, }, }; @@ -83,7 +99,8 @@ mod linux { | SealFlags::SHRINK.bits() | SealFlags::SEAL.bits(), ); - /// Bytes per positional read/write of the parallel fill. + /// Block size the tests use to cover several blocks and a ragged tail. + #[cfg(test)] const COPY_CHUNK: usize = 32 << 20; /// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets @@ -106,6 +123,15 @@ mod linux { expect_bytes: Option, progress: &mut dyn FnMut(u64, u64), ) -> Result<(File, Option), String> { + seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity)) + } + + /// As [`seal_file_with_identity`], also returning how the file was read (strategy, bytes, time) for the log. + pub fn seal_file_report( + path: &Path, + expect_bytes: Option, + progress: &mut dyn FnMut(u64, u64), + ) -> Result<(File, Option, leleka_model_format::bulk_read::Report), String> { let source = File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; let metadata = source @@ -130,55 +156,57 @@ mod linux { .map_err(|e| format!("memfd_create failed: {e}"))?; let memory = File::from(fd); let total = metadata.len(); + let report: Mutex> = Mutex::new(None); // The final size first (before the GROW seal exists), so that workers write disjoint ranges. memory .set_len(total) .map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?; - let workers = std::thread::available_parallelism() - .map_or(4, |n| n.get()) - .clamp(2, 8); - let next = AtomicU64::new(0); + // Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue + // instead of one 128 KiB readahead window at a time, and the 55 GB never enters the page cache. + let plan = leleka_model_format::bulk_read::Plan::from_env(); let copied = AtomicU64::new(0); - let finished = AtomicUsize::new(0); + let finished = AtomicBool::new(false); let failure: Mutex> = Mutex::new(None); std::thread::scope(|scope| { - for _ in 0..workers { - scope.spawn(|| { - let mut buffer = vec![0u8; COPY_CHUNK]; - loop { - if failure.lock().is_ok_and(|f| f.is_some()) { - break; - } - let offset = next.fetch_add(COPY_CHUNK as u64, Ordering::Relaxed); - if offset >= total { - break; - } - let count = (total - offset).min(COPY_CHUNK as u64) as usize; - let step = source - .read_exact_at(&mut buffer[..count], offset) - .map_err(|e| format!("read failed at {offset}: {e}")) - .and_then(|()| { - memory.write_all_at(&buffer[..count], offset).map_err(|e| { - format!("write to memfd failed (out of memory?): {e}") - }) - }); - match step { - Ok(()) => { - copied.fetch_add(count as u64, Ordering::Relaxed); - } - Err(message) => { - if let Ok(mut f) = failure.lock() { - f.get_or_insert(message); - } - break; - } + scope.spawn(|| { + // Set on every exit, a panic included, so that the progress loop below ends. + struct Finished<'a>(&'a AtomicBool); + impl Drop for Finished<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } + } + let _finished = Finished(&finished); + let outcome = leleka_model_format::bulk_read::for_each_chunk( + &source, + 0, + total, + plan, + |offset, data| { + memory.write_all_at(data, offset).map_err(|e| { + std::io::Error::other(format!( + "write to memfd failed (out of memory?): {e}" + )) + })?; + copied.fetch_add(data.len() as u64, Ordering::Relaxed); + Ok(()) + }, + ); + match outcome { + Ok(done) => { + if let Ok(mut slot) = report.lock() { + *slot = Some(done); } } - finished.fetch_add(1, Ordering::Release); - }); - } + Err(e) => { + if let Ok(mut f) = failure.lock() { + f.get_or_insert(format!("read failed: {e}")); + } + } + } + }); let mut reported = 0u64; - while finished.load(Ordering::Acquire) < workers { + while !finished.load(Ordering::Acquire) { std::thread::sleep(std::time::Duration::from_millis(100)); let now = copied.load(Ordering::Relaxed); if now - reported >= 4 << 30 { @@ -205,7 +233,12 @@ mod linux { return Err("the kernel did not apply every seal".into()); } progress(total, total); - Ok((memory, identity_before)) + let report = report + .into_inner() + .ok() + .flatten() + .ok_or("the archive copy did not report")?; + Ok((memory, identity_before, report)) } /// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an diff --git a/crates/model-format/examples/bulk_read_bench.rs b/crates/model-format/examples/bulk_read_bench.rs new file mode 100644 index 00000000..ce864784 --- /dev/null +++ b/crates/model-format/examples/bulk_read_bench.rs @@ -0,0 +1,98 @@ +//! Offline measurement of `leleka_model_format::bulk_read` on a real (cold) file; not part of the product. +//! +//! bulk_read_bench PATH START_MIB LEN_MIB STRATEGY THREADS CHUNK_MIB [--digest] [--no-evict-first] (LEN_MIB 0: to the end of the file) +//! +//! Evicts the span first (`posix_fadvise(DONTNEED)`, never `drop_caches`), reads it with the chosen strategy and prints the rate, +//! the device-level read volume (so a disk shared with another job is visible) and, with `--digest`, a SHA-256 over the +//! SHA-256 digests of the consecutive CHUNK_MIB blocks from START (reproducible by `bulk_read_digest.py`). +use leleka_model_format::bulk_read::{Plan, Strategy, evict, for_each_chunk}; +use sha2::{Digest, Sha256}; +use std::{fs::File, sync::Mutex}; + +/// (bytes read, bytes written) by the whole device so far. +fn device_bytes() -> Option<(u64, u64)> { + let text = std::fs::read_to_string("/sys/block/nvme0n1/stat").ok()?; + let field = |n: usize| -> Option { + Some(text.split_whitespace().nth(n)?.parse::().ok()? * 512) + }; + Some((field(2)?, field(6)?)) +} + +fn main() { + let args: Vec = std::env::args().collect(); + if args.len() < 7 { + eprintln!( + "usage: bulk_read_bench PATH START_MIB LEN_MIB direct|advise|plain THREADS CHUNK_MIB [--digest] [--no-evict-first]" + ); + std::process::exit(2); + } + let file = File::open(&args[1]).expect("open"); + let start = args[2].parse::().expect("START_MIB") << 20; + let len = match args[3].parse::().expect("LEN_MIB") { + 0 => file.metadata().expect("metadata").len() - start, + mib => mib << 20, + }; + let strategy = match args[4].as_str() { + "direct" => Strategy::Direct, + "advise" => Strategy::Advise, + _ => Strategy::Plain, + }; + let chunk = args[6].parse::().expect("CHUNK_MIB") << 20; + let plan = Plan { + strategy, + threads: args[5].parse().expect("THREADS"), + chunk, + ahead: 1 << 30, + }; + let digest = args.iter().any(|a| a == "--digest"); + if !args.iter().any(|a| a == "--no-evict-first") { + evict(&file, start, len); + } + let digests: Mutex> = Mutex::new(Vec::new()); + let before = device_bytes(); + let report = for_each_chunk(&file, start, len, plan, |offset, bytes| { + if digest { + let d: [u8; 32] = Sha256::digest(bytes).into(); + digests.lock().unwrap().push((offset, d)); + } + Ok(()) + }) + .expect("read"); + let after = device_bytes(); + let device = match (before, after) { + (Some(b), Some(a)) => format!( + " device {:.0} MB/s other-read {:.1} GB written {:.2} GB", + (a.0 - b.0) as f64 / report.elapsed.as_secs_f64() / 1e6, + (a.0 - b.0).saturating_sub(len) as f64 / 1e9, + (a.1 - b.1) as f64 / 1e9 + ), + _ => String::new(), + }; + print!( + "{:7} threads {:3} chunk {:3} MiB: {:6.1} s {:7.0} MB/s{}", + report.strategy.as_str(), + plan.threads, + chunk >> 20, + report.elapsed.as_secs_f64(), + report.mb_per_s(), + device + ); + if digest { + let mut list = digests.into_inner().unwrap(); + list.sort(); + let mut outer = Sha256::new(); + for (_, d) in &list { + outer.update(d); + } + print!( + " digest {}", + outer + .finalize() + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ); + } + println!(); + evict(&file, start, len); +} diff --git a/crates/model-format/examples/bulk_read_digest.py b/crates/model-format/examples/bulk_read_digest.py new file mode 100644 index 00000000..5c302507 --- /dev/null +++ b/crates/model-format/examples/bulk_read_digest.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""Reference for bulk_read_bench --digest: sha256 over the sha256 digests of consecutive CHUNK_MIB blocks (one plain sequential pass). +Offline check only. usage: bulk_read_digest.py PATH START_MIB LEN_MIB CHUNK_MIB""" +import hashlib, os, sys +path, start, length, chunk = sys.argv[1], int(sys.argv[2]) << 20, int(sys.argv[3]) << 20, int(sys.argv[4]) << 20 +outer = hashlib.sha256() +fd = os.open(path, os.O_RDONLY) +off = start +while off < start + length: + n = min(chunk, start + length - off) + data = os.pread(fd, n, off) + while len(data) < n: + data += os.pread(fd, n - len(data), off + len(data)) + outer.update(hashlib.sha256(data).digest()) + off += n +os.posix_fadvise(fd, start, length, os.POSIX_FADV_DONTNEED) +print(outer.hexdigest()) diff --git a/crates/model-format/src/bulk_read.rs b/crates/model-format/src/bulk_read.rs new file mode 100644 index 00000000..ade86d4c --- /dev/null +++ b/crates/model-format/src/bulk_read.rs @@ -0,0 +1,570 @@ +//! Large-block, high-queue-depth reads of a cold file, with the page cache kept out of the way. +//! +//! A cold start reads two things that are tens of gigabytes long: the KAR archive (copied once into a sealed memfd) and +//! the routed-expert tensors of shard 0 (copied into the page-locked bank). A plain `read()` loop asks the device for +//! one 128 KiB readahead window at a time (queue depth 1-2); on the 5090 server's NVMe that ran at 8-35 MB/s while +//! the same drive does well over 1 GB/s when many requests are in flight (`docs/unattended.md`, "Fast cold load"). +//! Here several threads each read large aligned blocks, so the device sees a deep queue. +//! +//! Three strategies, one result (the bytes are the file's, in every strategy): +//! +//! * [`Strategy::Direct`]: `O_DIRECT` into 4 KiB-aligned bounce buffers. The page cache is never touched, so nothing +//! has to be evicted afterwards and the machine's free-memory state (huge-page blocks) is left alone. +//! * [`Strategy::Advise`]: buffered `pread` with `posix_fadvise(WILLNEED)` kept ahead of the readers and +//! `posix_fadvise(DONTNEED)` behind them, so the cache holds a bounded window, never the file. +//! * [`Strategy::Plain`]: buffered `pread` of large blocks and eviction behind (the fallback where the other two are +//! refused, and the reference for tests). +//! +//! `Direct` falls back to `Advise` when the file system refuses `O_DIRECT` (tmpfs, some network and FUSE mounts); the +//! fall-back is reported in [`Report::strategy`]. Memory is bounded by `threads * (chunk + 8 KiB)`. No `unsafe`. +//! Nothing here decides what a digest means: a short read that is not the end of the file, or a file that ends early, +//! is an error, as with `read_exact`. +use std::{ + fs::File, + io, + sync::{ + Mutex, + atomic::{AtomicU64, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; + +/// Alignment of `O_DIRECT` offsets, lengths and buffers (the logical block size is never larger on supported devices). +const ALIGN: usize = 4096; + +/// Spans below this are not worth the threads: callers keep their ordinary read for them. +pub const MIN_PARALLEL_BYTES: u64 = 64 << 20; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Strategy { + Direct, + Advise, + Plain, +} + +impl Strategy { + pub fn as_str(self) -> &'static str { + match self { + Strategy::Direct => "direct", + Strategy::Advise => "advise", + Strategy::Plain => "plain", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Plan { + pub strategy: Strategy, + /// Reader threads (each has one block in flight). + pub threads: usize, + /// Bytes per block (a multiple of 4096). + pub chunk: usize, + /// `Advise` only: how far ahead of the readers `WILLNEED` runs. + pub ahead: u64, +} + +impl Plan { + /// The defaults, then the environment (`LELEKA_LOAD_READ=direct|advise|plain`, `LELEKA_LOAD_THREADS=N`, + /// `LELEKA_LOAD_CHUNK_MIB=N`, `LELEKA_LOAD_AHEAD_MIB=N`): the switches that let one binary be measured in each form. + pub fn from_env() -> Plan { + Plan::with_overrides(Plan::default(), |name| std::env::var(name).ok()) + } + + pub fn with_overrides(mut plan: Plan, var: impl Fn(&str) -> Option) -> Plan { + if let Some(text) = var("LELEKA_LOAD_READ") { + plan.strategy = match text.trim() { + "direct" => Strategy::Direct, + "advise" => Strategy::Advise, + "plain" => Strategy::Plain, + _ => plan.strategy, + }; + } + if let Some(n) = var("LELEKA_LOAD_THREADS").and_then(|t| t.trim().parse::().ok()) { + plan.threads = n.clamp(1, 128); + } + if let Some(n) = var("LELEKA_LOAD_CHUNK_MIB").and_then(|t| t.trim().parse::().ok()) { + plan.chunk = (n.clamp(1, 256)) << 20; + } + if let Some(n) = var("LELEKA_LOAD_AHEAD_MIB").and_then(|t| t.trim().parse::().ok()) { + plan.ahead = n.clamp(1, 8192) << 20; + } + plan + } +} + +impl Default for Plan { + fn default() -> Self { + Plan { + strategy: Strategy::Direct, + threads: 32, + chunk: 8 << 20, + ahead: 1 << 30, + } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Report { + /// The strategy that actually ran (`Direct` becomes `Advise` where `O_DIRECT` is refused). + pub strategy: Strategy, + pub bytes: u64, + pub elapsed: Duration, +} + +impl Report { + pub fn mb_per_s(&self) -> f64 { + self.bytes as f64 / self.elapsed.as_secs_f64().max(1e-9) / 1e6 + } +} + +/// A byte buffer whose start is 4 KiB-aligned, without `unsafe`. +struct Aligned { + raw: Vec, + start: usize, + len: usize, +} + +impl Aligned { + fn new(len: usize) -> io::Result { + let mut raw = Vec::new(); + raw.try_reserve_exact(len + ALIGN) + .map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, "read buffer"))?; + raw.resize(len + ALIGN, 0); + let start = (ALIGN - raw.as_ptr() as usize % ALIGN) % ALIGN; + Ok(Aligned { raw, start, len }) + } + fn bytes(&mut self) -> &mut [u8] { + &mut self.raw[self.start..self.start + self.len] + } +} + +/// Reopen the open file (the same inode, no pathname lookup) with `O_DIRECT`. +#[cfg(target_os = "linux")] +fn open_direct(file: &File) -> io::Result { + use std::os::{fd::AsRawFd, unix::fs::OpenOptionsExt}; + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECT) + .open(format!("/proc/self/fd/{}", file.as_raw_fd())) +} + +#[cfg(not(target_os = "linux"))] +fn open_direct(_file: &File) -> io::Result { + Err(io::Error::new(io::ErrorKind::Unsupported, "O_DIRECT")) +} + +#[cfg(unix)] +fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { + use std::os::unix::fs::FileExt; + file.read_at(buffer, offset) +} + +#[cfg(windows)] +fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { + use std::os::windows::fs::FileExt; + file.seek_read(buffer, offset) +} + +/// Fill `buffer` from `offset`; `Ok(n)` with `n < buffer.len()` only at the end of the file. +fn read_full(file: &File, buffer: &mut [u8], offset: u64) -> io::Result { + let mut done = 0; + while done < buffer.len() { + match read_at(file, &mut buffer[done..], offset + done as u64) { + Ok(0) => break, + Ok(n) => done += n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(done) +} + +#[cfg(target_os = "linux")] +fn advise(file: &File, offset: u64, len: u64, advice: rustix::fs::Advice) { + if let Some(len) = std::num::NonZeroU64::new(len) { + let _ = rustix::fs::fadvise(file, offset, Some(len), advice); + } +} + +/// Drop the clean page-cache pages of `file[offset .. offset + len]` (best effort; never `drop_caches`). +pub fn evict(file: &File, offset: u64, len: u64) { + #[cfg(target_os = "linux")] + advise(file, offset, len, rustix::fs::Advice::DontNeed); + #[cfg(not(target_os = "linux"))] + let _ = (file, offset, len); +} + +struct Shared<'a, F> { + file: &'a File, + direct: Option, + strategy: Strategy, + start: u64, + len: u64, + file_len: u64, + chunk: u64, + ahead: u64, + next: AtomicU64, + advised_to: AtomicU64, + failure: Mutex>, + sink: &'a F, +} + +impl io::Result<()> + Sync> Shared<'_, F> { + fn failed(&self) -> bool { + self.failure.lock().is_ok_and(|f| f.is_some()) + } + + fn fail(&self, error: io::Error) { + if let Ok(mut slot) = self.failure.lock() { + slot.get_or_insert(error); + } + } + + fn worker(&self, buffer: &mut Aligned) { + let chunks = self.len.div_ceil(self.chunk); + loop { + if self.failed() { + return; + } + let index = self.next.fetch_add(1, Ordering::Relaxed); + if index >= chunks { + return; + } + let offset = self.start + index * self.chunk; + let count = (self.len - index * self.chunk).min(self.chunk) as usize; + if let Err(error) = self.read_block(buffer, offset, count) { + self.fail(error); + return; + } + } + } + + fn read_block(&self, buffer: &mut Aligned, offset: u64, count: usize) -> io::Result<()> { + match (&self.direct, self.strategy) { + (Some(direct), Strategy::Direct) => { + let aligned = offset - offset % ALIGN as u64; + let lead = (offset - aligned) as usize; + let want = (lead + count).next_multiple_of(ALIGN); + let got = read_full(direct, &mut buffer.bytes()[..want], aligned)?; + if got < lead + count { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the file ended before the span did", + )); + } + (self.sink)(offset, &buffer.bytes()[lead..lead + count]) + } + _ => { + if self.strategy == Strategy::Advise { + self.keep_ahead(offset + count as u64); + } + let got = read_full(self.file, &mut buffer.bytes()[..count], offset)?; + if got < count { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the file ended before the span did", + )); + } + (self.sink)(offset, &buffer.bytes()[..count])?; + evict(self.file, offset, count as u64); + Ok(()) + } + } + } + + /// Make sure `WILLNEED` covers `ahead` bytes beyond `until` (each byte is advised once). + fn keep_ahead(&self, until: u64) { + let target = (until + self.ahead) + .min(self.file_len) + .min(self.start + self.len); + let mut done = self.advised_to.load(Ordering::Relaxed).max(self.start); + while done < target { + match self.advised_to.compare_exchange( + done, + target, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => { + #[cfg(target_os = "linux")] + advise(self.file, done, target - done, rustix::fs::Advice::WillNeed); + return; + } + Err(now) => done = now.max(self.start), + } + } + } +} + +/// Read `file[start .. start + len]` in blocks on several threads and hand each block to `sink(absolute_offset, bytes)`. +/// Blocks arrive in no particular order, from different threads; each covers a distinct range of at most `plan.chunk` +/// bytes. The first error stops the others and is returned. +pub fn for_each_chunk( + file: &File, + start: u64, + len: u64, + plan: Plan, + sink: F, +) -> io::Result +where + F: Fn(u64, &[u8]) -> io::Result<()> + Sync, +{ + let began = Instant::now(); + let file_len = file.metadata()?.len(); + if start.checked_add(len).is_none_or(|end| end > file_len) { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the span is beyond the end of the file", + )); + } + let chunk = (plan.chunk.max(ALIGN) / ALIGN * ALIGN) as u64; + let mut strategy = plan.strategy; + let mut direct = None; + if strategy == Strategy::Direct { + match open_direct(file) { + Ok(handle) => direct = Some(handle), + Err(_) => strategy = Strategy::Advise, + } + } + if len == 0 { + return Ok(Report { + strategy, + bytes: 0, + elapsed: began.elapsed(), + }); + } + // The block that reaches the file's last bytes may be shorter than its aligned length: `read_full` stops at the end. + let threads = plan.threads.clamp(1, len.div_ceil(chunk) as usize); + let buffer_len = chunk as usize + 2 * ALIGN; + let mut buffers = Vec::with_capacity(threads); + for _ in 0..threads { + buffers.push(Aligned::new(buffer_len)?); + } + let mut shared = Shared { + file, + direct, + strategy, + start, + len, + file_len, + chunk, + ahead: plan.ahead, + next: AtomicU64::new(0), + advised_to: AtomicU64::new(start), + failure: Mutex::new(None), + sink: &sink, + }; + if strategy == Strategy::Advise { + // The first window before any reader asks. + shared.keep_ahead(start); + } + // A direct handle that the file system accepted at open but refuses at read (EINVAL): retry the first block + // once with the buffered strategy instead of failing the whole load. + if let (Some(direct), Strategy::Direct) = (&shared.direct, shared.strategy) { + let mut probe = Aligned::new(ALIGN)?; + let aligned = start - start % ALIGN as u64; + if read_full(direct, probe.bytes(), aligned).is_err() { + shared.direct = None; + shared.strategy = Strategy::Advise; + shared.keep_ahead(start); + } + } + let used = shared.strategy; + thread::scope(|scope| { + let shared = &shared; + for buffer in buffers.iter_mut() { + scope.spawn(move || shared.worker(buffer)); + } + }); + if let Some(error) = shared.failure.into_inner().ok().flatten() { + return Err(error); + } + if used != Strategy::Direct { + evict(file, start, len); + } + Ok(Report { + strategy: used, + bytes: len, + elapsed: began.elapsed(), + }) +} + +/// Fill `dest` with `file[start .. start + dest.len()]`. +pub fn read_into(file: &File, start: u64, dest: &mut [u8], plan: Plan) -> io::Result { + let chunk = plan.chunk.max(ALIGN) / ALIGN * ALIGN; + let len = dest.len() as u64; + let pieces: Vec> = dest.chunks_mut(chunk).map(Mutex::new).collect(); + let plan = Plan { chunk, ..plan }; + for_each_chunk(file, start, len, plan, |offset, bytes| { + let index = ((offset - start) / chunk as u64) as usize; + let mut piece = pieces + .get(index) + .ok_or_else(|| io::Error::other("block outside the destination"))? + .lock() + .map_err(|_| io::Error::other("destination lock poisoned"))?; + if piece.len() != bytes.len() { + return Err(io::Error::other( + "block length differs from the destination piece", + )); + } + piece.copy_from_slice(bytes); + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + fn pattern(size: usize) -> Vec { + (0..size) + .map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8) ^ ((n >> 17) as u8)) + .collect() + } + + fn temp(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) { + let path = std::env::temp_dir().join(format!("leleka-bulk-{name}-{}", std::process::id())); + let mut file = File::create(&path).unwrap(); + file.write_all(bytes).unwrap(); + file.sync_all().unwrap(); + drop(file); + let file = File::open(&path).unwrap(); + (path, file) + } + + fn plans() -> Vec { + let mut all = Vec::new(); + for strategy in [Strategy::Direct, Strategy::Advise, Strategy::Plain] { + for (threads, chunk) in [(1, 4096), (3, 8192), (8, 64 << 10), (4, 1 << 20)] { + all.push(Plan { + strategy, + threads, + chunk, + ahead: 256 << 10, + }); + } + } + all + } + + #[test] + fn every_strategy_returns_the_same_bytes_for_aligned_and_ragged_spans() { + let payload = pattern((3 << 20) + 5000); + let (path, file) = temp("same", &payload); + for plan in plans() { + for (start, len) in [ + (0usize, payload.len()), + (1, 100_000), + (4095, 4097), + (4096, 8192), + (12_345, (2 << 20) + 17), + (payload.len() - 1, 1), + (payload.len() - 10_001, 10_001), + ] { + let mut dest = vec![0u8; len]; + let report = read_into(&file, start as u64, &mut dest, plan).unwrap(); + assert_eq!(report.bytes, len as u64); + assert!( + dest == payload[start..start + len], + "{plan:?} start {start} len {len}" + ); + } + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn for_each_chunk_covers_the_span_exactly_once() { + let payload = pattern((1 << 20) + 777); + let (path, file) = temp("cover", &payload); + for plan in plans() { + let seen = Mutex::new(vec![0u8; payload.len()]); + let count = AtomicU64::new(0); + for_each_chunk( + &file, + 100, + payload.len() as u64 - 100, + plan, + |offset, bytes| { + count.fetch_add(bytes.len() as u64, Ordering::Relaxed); + let mut seen = seen.lock().unwrap(); + for (i, b) in bytes.iter().enumerate() { + assert_eq!(seen[offset as usize + i], 0, "byte visited twice"); + assert_eq!(*b, payload[offset as usize + i]); + seen[offset as usize + i] = 1; + } + Ok(()) + }, + ) + .unwrap(); + assert_eq!(count.load(Ordering::Relaxed), payload.len() as u64 - 100); + assert!(seen.lock().unwrap()[100..].iter().all(|&v| v == 1)); + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_span_past_the_end_and_a_sink_error_are_errors() { + let payload = pattern(100_000); + let (path, file) = temp("err", &payload); + let mut dest = vec![0u8; 10]; + assert_eq!( + read_into(&file, 99_995, &mut dest, Plan::default()) + .unwrap_err() + .kind(), + io::ErrorKind::UnexpectedEof + ); + for plan in plans() { + let error = for_each_chunk(&file, 0, 100_000, plan, |_, _| { + Err(io::Error::other("sink refused")) + }) + .unwrap_err(); + assert_eq!(error.to_string(), "sink refused"); + } + let empty = for_each_chunk(&file, 5, 0, Plan::default(), |_, _| Ok(())).unwrap(); + assert_eq!(empty.bytes, 0); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_file_shorter_than_it_was_measured_is_unexpected_eof() { + let payload = pattern(50_000); + let (path, file) = temp("short", &payload); + // Grow the claimed length by truncating after the metadata read: emulate with a span the file cannot serve. + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(20_000) + .unwrap(); + let mut dest = vec![0u8; 50_000]; + for plan in plans() { + assert!(read_into(&file, 0, &mut dest, plan).is_err()); + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn the_environment_overrides_the_defaults() { + let plan = Plan::with_overrides(Plan::default(), |name| match name { + "LELEKA_LOAD_READ" => Some("advise".into()), + "LELEKA_LOAD_THREADS" => Some("7".into()), + "LELEKA_LOAD_CHUNK_MIB" => Some("16".into()), + "LELEKA_LOAD_AHEAD_MIB" => Some("64".into()), + _ => None, + }); + assert_eq!( + plan, + Plan { + strategy: Strategy::Advise, + threads: 7, + chunk: 16 << 20, + ahead: 64 << 20 + } + ); + let kept = Plan::with_overrides(Plan::default(), |_| Some("nonsense".into())); + assert_eq!(kept, Plan::default()); + } +} diff --git a/crates/model-format/src/gguf.rs b/crates/model-format/src/gguf.rs index d2c85919..c3375e56 100644 --- a/crates/model-format/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -473,6 +473,16 @@ fn read_file_span_owned(file: &mut File, absolute: u64, mut bytes: Box<[u8]>) -> Ok(bytes) } fn read_file_span_into(file: &mut File, absolute: u64, bytes: &mut [u8]) -> Result<()> { + // A large span (a routed-expert tensor of hundreds of MB) is read in big blocks on several threads, so the + // device sees a deep queue; the bytes and the failure modes are the same (`bulk_read`). Positional reads leave the + // cursor alone, and every caller seeks before it reads. `LELEKA_LOAD_READ=legacy` keeps the sequential loop below. + #[cfg(target_os = "linux")] + if bytes.len() as u64 >= crate::bulk_read::MIN_PARALLEL_BYTES + && std::env::var("LELEKA_LOAD_READ").as_deref() != Ok("legacy") + { + crate::bulk_read::read_into(file, absolute, bytes, crate::bulk_read::Plan::from_env())?; + return Ok(()); + } file.seek(SeekFrom::Start(absolute))?; for chunk in bytes.chunks_mut(STREAM_BUFFER_BYTES) { file.read_exact(chunk)?; diff --git a/crates/model-format/src/lib.rs b/crates/model-format/src/lib.rs index 32f08474..b1a7ebd3 100644 --- a/crates/model-format/src/lib.rs +++ b/crates/model-format/src/lib.rs @@ -6,6 +6,7 @@ //! callers must keep that file's contents stable throughout its lifetime. //! Its only direct dependency is the Rust SHA-256 implementation in `sha2`. +pub mod bulk_read; pub mod gguf; pub mod huge_pages; pub(crate) mod readahead; diff --git a/crates/model-format/src/readahead.rs b/crates/model-format/src/readahead.rs index ef8119c1..f728980e 100644 --- a/crates/model-format/src/readahead.rs +++ b/crates/model-format/src/readahead.rs @@ -87,6 +87,22 @@ fn advise_sequential(file: &File) { #[cfg(not(target_os = "linux"))] fn advise_sequential(_file: &File) {} +/// How far ahead of the reader the kernel is asked to fetch (`POSIX_FADV_WILLNEED`). A cold NVMe that serves one 128 KiB +/// window at a time reads at tens of MB/s; a few hundred MB of asynchronous readahead keeps its queue full while the +/// hash runs. +#[cfg(target_os = "linux")] +const WILLNEED_AHEAD: u64 = 512 << 20; + +#[cfg(target_os = "linux")] +fn advise_willneed(file: &File, offset: u64, len: u64) { + if let Some(len) = std::num::NonZeroU64::new(len) { + let _ = rustix::fs::fadvise(file, offset, Some(len), rustix::fs::Advice::WillNeed); + } +} + +#[cfg(not(target_os = "linux"))] +fn advise_willneed(_file: &File, _offset: u64, _len: u64) {} + /// Run `body` with `fanout` receivers that each get every chunk of `file[start .. start + bytes]`, in order. /// The reader thread ends when the span is read, when a read fails (the error is the last item) or when every /// receiver is gone. `body` must drain or drop its receivers. @@ -109,8 +125,19 @@ pub(crate) fn with_read_ahead( thread::scope(|scope| { scope.spawn(move || { let mut offset = 0u64; + let mut advised = start; while offset < bytes { let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize; + #[cfg(target_os = "linux")] + { + let target = (start + offset + count as u64 + WILLNEED_AHEAD).min(start + bytes); + if target > advised { + advise_willneed(file, advised, target - advised); + advised = target; + } + } + #[cfg(not(target_os = "linux"))] + let _ = (&mut advised, advise_willneed as fn(&File, u64, u64)); let mut buffer = pool .lock() .ok()