git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table. Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe). limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines, the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
217 lines
6.5 KiB
Rust
217 lines
6.5 KiB
Rust
//! Asynchronous row reader for the per-layer n-gram (PLE) table, port of
|
|
//! `ngram/ple_reader.{hpp,cpp}` over `std` positional reads.
|
|
//!
|
|
//! The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) and never
|
|
//! lives in RAM. A token needs 16 rows on 16 different pages, all derived from
|
|
//! the token itself, so the only time to hide the reads is the embedding plus
|
|
//! layer 0; hence the split API:
|
|
//!
|
|
//! ```text
|
|
//! let ticket = reader.issue(&rows); // as soon as the token id is known
|
|
//! ... // embedding, layer 0
|
|
//! let bytes = reader.collect(ticket)?; // before layer 1 reads the rows
|
|
//! ```
|
|
//!
|
|
//! `issue` also serves prefill: pass all `16 x N` rows of a chunk. Rows are
|
|
//! served from the row cache when possible, the rest are grouped by 4 KiB page
|
|
//! (rows sharing a page share one read; a row straddling a page boundary reads
|
|
//! two pages), the reads are sorted by offset so a chunk reads the SSD in
|
|
//! near-sequential order, and a pool of I/O threads keeps at most
|
|
//! `max_inflight` of them outstanding.
|
|
//!
|
|
//! The row cache is not the table. It keeps rows this process already fetched
|
|
//! (8-way set associative, round-robin inside a set, bounded by construction;
|
|
//! capacity 0 disables it).
|
|
//!
|
|
//! Safety properties kept from the original: an out-of-range row reads as zero
|
|
//! bytes (the mmap path's behaviour); a short read inside the table, a failed
|
|
//! read or a source whose size changed is an error that sticks to the reader
|
|
//! (every later `collect` fails). Unsafe code is forbidden workspace-wide, so
|
|
//! reads go through [`PageSource`] (`pread` via `std`), and O_DIRECT, when
|
|
//! wanted, is the source's business: the reader always reads 4 KiB-aligned
|
|
//! offsets and lengths into 4 KiB-aligned buffers, as an unbuffered file
|
|
//! requires.
|
|
|
|
use std::collections::{HashMap, VecDeque};
|
|
use std::fmt;
|
|
use std::fs::File;
|
|
use std::io;
|
|
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
|
use std::thread::{self, JoinHandle};
|
|
use std::time::{Duration, Instant};
|
|
|
|
/// An IQ4_NL row; `open` takes the table's own row size.
|
|
pub const ROW_BYTES: usize = 90;
|
|
pub const PAGE: usize = 4096;
|
|
const WAYS: usize = 8;
|
|
const EMPTY: u32 = 0xFFFF_FFFF;
|
|
const LATENCY_RING: usize = 65536;
|
|
const DEFAULT_IO_THREADS: usize = 16;
|
|
|
|
/// A positional-read file. Reads may be short only at end of file.
|
|
pub trait PageSource: Send + Sync + 'static {
|
|
fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;
|
|
/// Current length of the underlying file, for the size-unchanged check.
|
|
fn len(&self) -> io::Result<u64>;
|
|
fn is_empty(&self) -> io::Result<bool> {
|
|
Ok(self.len()? == 0)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct PleError(pub String);
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct PleReaderConfig {
|
|
/// Byte offset of row 0 in the file.
|
|
pub table_offset: u64,
|
|
pub n_rows: u64,
|
|
/// One row's size in the file (90 IQ4_NL, 160 FP8), at most one page.
|
|
pub row_bytes: usize,
|
|
/// Reads outstanding at once, 1..=1024.
|
|
pub max_inflight: usize,
|
|
/// Row cache capacity in rows (rounded down to whole 8-row sets); 0 disables.
|
|
pub cache_rows: u64,
|
|
/// I/O threads; `None` picks `min(max_inflight, 16)`, `Some(0)` runs every
|
|
/// read on the thread that calls `collect` (no workers, no keep-alive).
|
|
pub io_threads: Option<usize>,
|
|
/// Required length of the source; a different length at `collect` is an error.
|
|
pub expected_len: Option<u64>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct ReaderStats {
|
|
/// Rows asked for.
|
|
pub requests: u64,
|
|
/// Rows served from the row cache.
|
|
pub cache_hits: u64,
|
|
/// Rows that shared a page already being read in the same ticket.
|
|
pub dedup_rows: u64,
|
|
/// SSD read requests issued.
|
|
pub reads: u64,
|
|
/// Bytes read from the SSD.
|
|
pub bytes: u64,
|
|
/// Time `collect` spent blocked, microseconds.
|
|
pub wait_us: f64,
|
|
/// Sum of per-read latencies (issue to completion), microseconds.
|
|
pub read_us_sum: f64,
|
|
/// Reads delayed by fault injection.
|
|
pub late_injected: u64,
|
|
/// Pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies).
|
|
pub keepalive_reads: u64,
|
|
/// The slowest of them, microseconds.
|
|
pub keepalive_us_max: f64,
|
|
/// Last <= 65,536 read latencies, for percentiles.
|
|
pub read_us: Vec<f32>,
|
|
}
|
|
|
|
/// Set-associative row cache: 8 ways per set, round-robin replacement inside a
|
|
/// set. Bounded by construction.
|
|
#[derive(Debug, Default)]
|
|
pub struct RowCache {
|
|
sets: u64,
|
|
rb: usize,
|
|
keys: Vec<u32>,
|
|
data: Vec<u8>,
|
|
next: Vec<u8>,
|
|
used: u64,
|
|
}
|
|
|
|
/// One row inside a read.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct Use {
|
|
pub row: u32,
|
|
/// Byte offset of the row inside the read buffer.
|
|
pub in_page: usize,
|
|
/// Row slot in the ticket's output.
|
|
pub slot: usize,
|
|
}
|
|
|
|
/// One read: an aligned file offset and one or two pages.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct PlannedRead {
|
|
pub offset: u64,
|
|
pub length: usize,
|
|
pub uses: Vec<Use>,
|
|
}
|
|
|
|
struct Job {
|
|
read: PlannedRead,
|
|
ticket: u32,
|
|
keepalive: bool,
|
|
}
|
|
|
|
struct TicketState {
|
|
pending: usize,
|
|
out: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct KeepAlive {
|
|
period: Duration,
|
|
window: Duration,
|
|
last_issue: Option<Instant>,
|
|
last_read: Option<Instant>,
|
|
rng: u64,
|
|
}
|
|
|
|
struct State {
|
|
queue: VecDeque<Job>,
|
|
tickets: HashMap<u32, TicketState>,
|
|
next_ticket: u32,
|
|
cache: RowCache,
|
|
stats: ReaderStats,
|
|
ring_pos: usize,
|
|
delay: Duration,
|
|
error: Option<PleError>,
|
|
stop: bool,
|
|
inflight: usize,
|
|
keep: KeepAlive,
|
|
}
|
|
|
|
struct Shared {
|
|
source: Arc<dyn PageSource>,
|
|
cfg: PleReaderConfig,
|
|
inline: bool,
|
|
state: Mutex<State>,
|
|
work: Condvar,
|
|
done: Condvar,
|
|
keep_cv: Condvar,
|
|
}
|
|
|
|
/// Heap buffer whose usable window starts on a 4 KiB boundary, for unbuffered sources.
|
|
struct AlignedBuf {
|
|
raw: Vec<u8>,
|
|
start: usize,
|
|
len: usize,
|
|
}
|
|
|
|
/// Handle to a ticket issued by [`PleReader::issue`]. Dropping it without
|
|
/// collecting abandons the rows (reads in flight still warm the cache).
|
|
pub struct Ticket {
|
|
id: u32,
|
|
shared: Arc<Shared>,
|
|
}
|
|
|
|
pub struct PleReader {
|
|
shared: Arc<Shared>,
|
|
workers: Vec<JoinHandle<()>>,
|
|
keepalive: Option<JoinHandle<()>>,
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|
|
|
|
mod file_page_source;
|
|
#[allow(unused_imports)]
|
|
pub use file_page_source::*;
|
|
mod state;
|
|
#[allow(unused_imports)]
|
|
pub use state::*;
|
|
mod ple_reader_methods;
|
|
#[allow(unused_imports)]
|
|
pub use ple_reader_methods::*;
|
|
mod ple_reader_debug_drop;
|
|
#[allow(unused_imports)]
|
|
pub use ple_reader_debug_drop::*;
|