PLE rows: read ahead of the chunk on handles of their own (Windows)
The KAR PLE rows of a chunk (16 per token, three random 4 KiB reads each) were read before the chunk started, through clones of one synchronous handle, which the I/O manager runs one request at a time: 5-12 s of every 6144-token chunk. Rows now read on independent file objects (ReOpenFile) and the next chunk's rows are fetched on a thread while this chunk computes. Packets are a function of the archive bytes only; LELEKA_PLE_AHEAD_VERIFY=1 compares each with a direct read (0 mismatches in 2 live turns). Default on for Windows, LELEKA_PLE_AHEAD=on|off. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
3bedec6107
commit
ee4cb597da
@@ -389,6 +389,7 @@ mod win_archive {
|
||||
#[path = "qwen4exp_inherited_kar_gpu.rs"]
|
||||
mod inherited_kar_tests;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct KarRowPacket {
|
||||
payload: [u8; 50],
|
||||
partition: u16,
|
||||
@@ -401,6 +402,22 @@ impl KarRowPacket {
|
||||
self.partition
|
||||
}
|
||||
}
|
||||
/// `KarPleBinding::row_reader`: the PLE rows read from a thread of its own (a duplicate of the archive handle).
|
||||
pub(crate) struct KarRowReader {
|
||||
reader: leleka_model_format::kar::KarPleRowReader,
|
||||
}
|
||||
impl KarRowReader {
|
||||
pub(crate) fn read_rows(&self, rows: &[u64], max_threads: usize) -> InputResult<Vec<KarRowPacket>> {
|
||||
let packets = self.reader.read_rows(rows, max_threads).map_err(error)?;
|
||||
Ok(packets
|
||||
.into_iter()
|
||||
.map(|p| KarRowPacket {
|
||||
payload: *p.payload(),
|
||||
partition: p.partition(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
pub(crate) struct KarPleBinding {
|
||||
identity: BindingIdentity,
|
||||
archive: RefCell<VerifiedKarPleArtifact>,
|
||||
@@ -461,6 +478,16 @@ impl KarPleBinding {
|
||||
partition: p.partition(),
|
||||
}))
|
||||
}
|
||||
/// An owned reader of the same rows for another thread (the prefill's read-ahead of the next chunk's rows).
|
||||
pub(crate) fn row_reader(&self) -> InputResult<KarRowReader> {
|
||||
let reader = self
|
||||
.archive
|
||||
.try_borrow()
|
||||
.map_err(|_| InputBindingError::Busy)?
|
||||
.row_reader()
|
||||
.map_err(error)?;
|
||||
Ok(KarRowReader { reader })
|
||||
}
|
||||
/// `read_rows` for any number of rows (the batched prefill's cache misses).
|
||||
pub(crate) fn read_rows_batch(&self, rows: &[u64]) -> InputResult<Vec<KarRowPacket>> {
|
||||
let packets = self
|
||||
|
||||
@@ -277,7 +277,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
policy:&OriginalMtpScalarPolicy,mut cancelled:impl FnMut()->bool,
|
||||
)->Result<OriginalPromptPending<'session,'program,'ctx>>{
|
||||
self.validate(binding,dense,session)?;
|
||||
let tokens=source.window(binding,session.target_origin()?.next_position(),count)?;
|
||||
let first_position=session.target_origin()?.next_position();
|
||||
let tokens=source.window(binding,first_position,count)?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={} count={count}",crate::qwen_forward::original_serve_stack::dbg_el(),tokens.len(),self.capacity,arena.capacity());
|
||||
let _launch_sync=leleka_cuda_driver::PromptSyncTrace::enter();
|
||||
if tokens.is_empty()||tokens.len()>self.capacity||arena.capacity()!=self.capacity{return Err(Error::InvalidDimension);}
|
||||
@@ -293,11 +294,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
let input_span=prof::span(PStage::Input,None);
|
||||
// KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device
|
||||
// (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm).
|
||||
let mut staged_input=None;let mut staged_ple=None;
|
||||
let mut staged_input=None;let mut staged_ple=None;let mut first_predecessors:Option<[i32;2]>=None;
|
||||
if binding.kar_ple_binding().is_some()&&staged_input_enabled(){
|
||||
let mut staged=StagedInput::default();
|
||||
for &token in tokens{
|
||||
txn.stage_input(|step|{let pos=step.position();
|
||||
if first_predecessors.is_none(){first_predecessors=Some(step.input_predecessors()?);}
|
||||
match kar.as_deref(){
|
||||
Some(cache)=>InputStage::consume_kar_deferred(binding,cache,token,pos,step,&mut staged),
|
||||
None=>Err(Error::IdentityMismatch),
|
||||
@@ -347,6 +349,18 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
_=>PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,None)?,
|
||||
};
|
||||
drop(upload_span);drop(init_span);
|
||||
// The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes
|
||||
// (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there.
|
||||
if let (Some(cache),Some(kar_binding),Some(mut before))=(kar.as_deref_mut(),binding.kar_ple_binding(),first_predecessors){
|
||||
let next_first=first_position+tokens.len() as u64;
|
||||
let want=self.capacity.min(source.len().saturating_sub(next_first as usize));
|
||||
if want>0{
|
||||
if let Ok(next)=source.window(binding,next_first,want){
|
||||
for &token in tokens{before=[before[1],token.get() as i32];}
|
||||
if let Ok(rows)=InputStage::ple_rows_ahead(binding,before,next){cache.read_ahead(kar_binding,&rows);}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut carrier=Carrier::Plain(rows);
|
||||
for layer in binding.ordered_layers(){
|
||||
let index=layer.index();let role=super::super::gr::GrRole::Attention(index);
|
||||
|
||||
@@ -219,6 +219,19 @@ impl InputStage {
|
||||
deferred: true,
|
||||
})
|
||||
}
|
||||
/// The sixteen PLE rows of each of `tokens` (flattened), where `before` are the two tokens that precede the first
|
||||
/// of them (-1: none): the read-ahead of the chunk after the one being computed. Pure; the same rows
|
||||
/// `consume_kar_deferred` records when that chunk is staged.
|
||||
pub(super) fn ple_rows_ahead(binding: &ModelBinding, mut before: [i32; 2], tokens: &[TokenId]) -> Result<Vec<u64>> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(tokens.len() * 16).map_err(|_| Error::InputAllocation)?;
|
||||
for &token in tokens {
|
||||
let rows = hash::rows(token.get(), before, binding.input_constants())?;
|
||||
out.extend_from_slice(&rows);
|
||||
before = [before[1], token.get() as i32];
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// The PLE input rows of one verifier window: for each input token, the sixteen PLE rows its
|
||||
/// two committed predecessors select (`hash::rows`) gathered from the model's own PLE provider
|
||||
/// (the KAR archive when the model is bound to one, else the native table). Row `i`'s
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
#![allow(dead_code)]
|
||||
use super::contract::{Error, Result};
|
||||
use crate::model_binding::qwen4exp_input::{BindingIdentity, PLE_ROWS};
|
||||
use crate::model_binding::qwen4exp_kar_ple::KarPleBinding;
|
||||
use crate::model_binding::qwen4exp_kar_ple::{KarPleBinding, KarRowPacket, KarRowReader};
|
||||
use leleka_cuda_driver::{Context, DeviceBuffer};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
use std::sync::Arc;
|
||||
use std::thread::JoinHandle;
|
||||
const CACHE_BYTES: usize = 64 * 1024 * 1024;
|
||||
const SLOTS: u32 = (CACHE_BYTES / 64) as u32;
|
||||
const OUTPUT_BYTES: usize = 16 * 160 * 4;
|
||||
@@ -141,7 +143,43 @@ struct Miss {
|
||||
payload: [u8; 50],
|
||||
part: u16,
|
||||
}
|
||||
/// `LELEKA_PLE_AHEAD=on|off` (read once) turns the read-ahead of the next chunk's PLE packets on or off. Unset: on for Windows, where the
|
||||
/// archive is a file the rows are read from at 20-45 k random reads a second (5 to 12 s of every 6144-token chunk); off elsewhere, where
|
||||
/// the server profile keeps the archive in a memfd and its rows are a memory read (not measured, so not changed).
|
||||
fn ahead_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| match std::env::var("LELEKA_PLE_AHEAD").ok().as_deref() {
|
||||
Some("on" | "1" | "yes") => true,
|
||||
Some("off" | "0" | "no") => false,
|
||||
_ => cfg!(windows),
|
||||
})
|
||||
}
|
||||
/// Threads of the read-ahead: the positional reads are latency-bound (three random pages per row), not CPU-bound.
|
||||
const AHEAD_THREADS: usize = 24;
|
||||
/// Packets read ahead and not used yet are dropped past this many (a chunk of 8192 tokens is 131,072 rows).
|
||||
const AHEAD_KEEP: usize = 1 << 20;
|
||||
/// The packets of the rows a chunk about to be read will miss, fetched on a thread of their own while the chunk
|
||||
/// before it computes. A packet is a function of the archive's bytes only, so reading it early changes nothing the
|
||||
/// device sees; a failed read-ahead is dropped and the rows are read at their use, which reports the error as before.
|
||||
#[derive(Default)]
|
||||
struct Ahead {
|
||||
reader: Option<Arc<KarRowReader>>,
|
||||
reader_failed: bool,
|
||||
pending: Option<JoinHandle<Vec<(u64, KarRowPacket)>>>,
|
||||
ready: RowMap<KarRowPacket>,
|
||||
}
|
||||
impl Ahead {
|
||||
/// Wait for the outstanding read-ahead and keep what it read.
|
||||
fn collect(&mut self) {
|
||||
if let Some(handle) = self.pending.take() {
|
||||
if let Ok(rows) = handle.join() {
|
||||
self.ready.extend(rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) struct KarPleCache<'ctx> {
|
||||
ahead: Ahead,
|
||||
context: &'ctx Context<'ctx>,
|
||||
cache: DeviceBuffer<'ctx>,
|
||||
books: DeviceBuffer<'ctx>,
|
||||
@@ -193,6 +231,7 @@ impl<'ctx> KarPleCache<'ctx> {
|
||||
.allocate(OUTPUT_BYTES)
|
||||
.map_err(|_| Error::CudaExecution)?;
|
||||
Ok(Self {
|
||||
ahead: Ahead::default(),
|
||||
context,
|
||||
cache,
|
||||
books,
|
||||
@@ -250,9 +289,58 @@ impl<'ctx> KarPleCache<'ctx> {
|
||||
let packets = if miss_rows.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
binding
|
||||
.read_rows_batch(&miss_rows)
|
||||
.map_err(super::input::binding_error)?
|
||||
self.ahead.collect();
|
||||
// the rows the read-ahead already holds come from it; the others are read now, as before
|
||||
let mut packets = Vec::<Option<KarRowPacket>>::new();
|
||||
packets
|
||||
.try_reserve_exact(miss_rows.len())
|
||||
.map_err(|_| Error::InputAllocation)?;
|
||||
let mut rest_at = Vec::<usize>::new();
|
||||
let mut rest_rows = Vec::<u64>::new();
|
||||
let mut from_ahead = Vec::<(usize, u64)>::new();
|
||||
for (at, row) in miss_rows.iter().enumerate() {
|
||||
match self.ahead.ready.remove(row) {
|
||||
Some(packet) => {
|
||||
from_ahead.push((at, *row));
|
||||
packets.push(Some(packet));
|
||||
}
|
||||
None => {
|
||||
packets.push(None);
|
||||
rest_at.push(at);
|
||||
rest_rows.push(*row);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !rest_rows.is_empty() {
|
||||
let read = binding
|
||||
.read_rows_batch(&rest_rows)
|
||||
.map_err(super::input::binding_error)?;
|
||||
if read.len() != rest_rows.len() {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
for (at, packet) in rest_at.into_iter().zip(read) {
|
||||
packets[at] = Some(packet);
|
||||
}
|
||||
}
|
||||
// LELEKA_PLE_AHEAD_VERIFY=1: every packet taken from the read-ahead is compared with a direct read of its row
|
||||
if !from_ahead.is_empty() && std::env::var("LELEKA_PLE_AHEAD_VERIFY").is_ok_and(|v| v == "1") {
|
||||
let rows: Vec<u64> = from_ahead.iter().map(|(_, row)| *row).collect();
|
||||
let direct = binding
|
||||
.read_rows_batch(&rows)
|
||||
.map_err(super::input::binding_error)?;
|
||||
for ((at, row), direct) in from_ahead.iter().zip(&direct) {
|
||||
let held = packets[*at].as_ref().ok_or(Error::InvalidDimension)?;
|
||||
if held.payload() != direct.payload() || held.partition() != direct.partition() {
|
||||
eprintln!("leleka-ple-ahead: MISMATCH row {row}");
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
eprintln!("leleka-ple-ahead: {} of {} missed rows came from the read-ahead, all equal to a direct read", from_ahead.len(), miss_rows.len());
|
||||
}
|
||||
packets
|
||||
.into_iter()
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or(Error::InvalidDimension)?
|
||||
};
|
||||
let misses = miss_rows.len();
|
||||
let (miss_slot, victims, next_slot) =
|
||||
@@ -282,6 +370,47 @@ impl<'ctx> KarPleCache<'ctx> {
|
||||
stamp,
|
||||
})
|
||||
}
|
||||
/// Start reading, on a thread of its own, the packets of the PLE `rows` (the sixteen rows of each token of the
|
||||
/// chunk after the one being computed) that neither the device cache nor an earlier read-ahead holds. Call it
|
||||
/// after `commit` of the current chunk. The result is used by the next `stage_batch`; nothing here can fail a request.
|
||||
pub(super) fn read_ahead(&mut self, binding: &KarPleBinding, rows: &[u64]) {
|
||||
if self.failed || rows.is_empty() || !ahead_enabled() {
|
||||
return;
|
||||
}
|
||||
self.ahead.collect();
|
||||
if self.ahead.ready.len() > AHEAD_KEEP {
|
||||
self.ahead.ready.clear();
|
||||
}
|
||||
if self.ahead.reader.is_none() && !self.ahead.reader_failed {
|
||||
match binding.row_reader() {
|
||||
Ok(reader) => self.ahead.reader = Some(Arc::new(reader)),
|
||||
Err(_) => self.ahead.reader_failed = true,
|
||||
}
|
||||
}
|
||||
let Some(reader) = self.ahead.reader.clone() else { return };
|
||||
let mut seen = RowMap::<()>::default();
|
||||
let mut wanted = Vec::<u64>::new();
|
||||
for &row in rows {
|
||||
if row >= PLE_ROWS || self.entries.contains_key(&row) || self.ahead.ready.contains_key(&row) {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(row, ()).is_none() {
|
||||
wanted.push(row);
|
||||
}
|
||||
}
|
||||
if wanted.is_empty() {
|
||||
return;
|
||||
}
|
||||
let spawned = std::thread::Builder::new().name("ple-ahead".into()).spawn(move || {
|
||||
match reader.read_rows(&wanted, AHEAD_THREADS) {
|
||||
Ok(packets) if packets.len() == wanted.len() => wanted.into_iter().zip(packets).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
});
|
||||
if let Ok(handle) = spawned {
|
||||
self.ahead.pending = Some(handle);
|
||||
}
|
||||
}
|
||||
/// Publish the mapping of a chunk the device decoded and found finite.
|
||||
pub(super) fn commit(&mut self, staged: KarPleStaged) {
|
||||
for (_, _, victim) in &staged.inserts {
|
||||
|
||||
+169
-133
@@ -1045,6 +1045,7 @@ impl KarPleRowPacket {
|
||||
self.partition
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct VerifiedPart {
|
||||
row_base: u64,
|
||||
row_count: u64,
|
||||
@@ -1068,6 +1069,8 @@ pub struct VerifiedKarPleArtifact {
|
||||
profile: KarPleProfile,
|
||||
parts: Vec<VerifiedPart>,
|
||||
books: Vec<[u16; 4]>,
|
||||
/// Handles with their own file objects for the parallel row reads (`independent_handles`), opened on first use.
|
||||
handles: std::sync::OnceLock<Vec<File>>,
|
||||
}
|
||||
impl VerifiedKarPleArtifact {
|
||||
pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result<Self, KarError> {
|
||||
@@ -1164,6 +1167,7 @@ impl VerifiedKarPleArtifact {
|
||||
profile,
|
||||
parts,
|
||||
books,
|
||||
handles: std::sync::OnceLock::new(),
|
||||
})
|
||||
}
|
||||
pub fn archive_sha256(&self) -> &[u8; 32] {
|
||||
@@ -1192,152 +1196,184 @@ impl VerifiedKarPleArtifact {
|
||||
if self.reader.file.metadata().map_err(KarError::Io)?.len() != self.archive_bytes() {
|
||||
return Err(KarError::Integrity("KAR archive length changed"));
|
||||
}
|
||||
let mut packets = [KarPleRowPacket {
|
||||
// 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each
|
||||
let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 8, 2)?;
|
||||
let mut out = [KarPleRowPacket {
|
||||
payload: [0; 50],
|
||||
partition: 0,
|
||||
}; 16];
|
||||
for (row, packet) in rows.iter().zip(&mut packets) {
|
||||
let index = self
|
||||
.parts
|
||||
.partition_point(|p| p.row_base <= *row)
|
||||
.checked_sub(1)
|
||||
.ok_or(KarError::Range("KAR PLE partition range"))?;
|
||||
let p = &self.parts[index];
|
||||
let local = row - p.row_base;
|
||||
if local >= p.row_count {
|
||||
return Err(KarError::Range("KAR PLE local row range"));
|
||||
}
|
||||
let scale = p
|
||||
.scales
|
||||
.checked_add(
|
||||
local
|
||||
.checked_mul(10)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?,
|
||||
)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?;
|
||||
read_at(&mut self.reader.file, scale, &mut packet.payload[..10])?;
|
||||
for plane in 0..2usize {
|
||||
let at = p
|
||||
.planes
|
||||
.checked_add(
|
||||
(plane as u64)
|
||||
.checked_mul(p.stride)
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?,
|
||||
)
|
||||
.and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n)))
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?;
|
||||
read_at(&mut self.reader.file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?;
|
||||
}
|
||||
if packet.payload[..10]
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00)
|
||||
{
|
||||
return Err(KarError::Profile("KAR PLE nonfinite scale"));
|
||||
}
|
||||
packet.partition =
|
||||
u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?;
|
||||
}
|
||||
Ok(packets)
|
||||
out.copy_from_slice(&packets);
|
||||
Ok(out)
|
||||
}
|
||||
/// Handles with a file object of their own (so reads through two of them can be in flight at once).
|
||||
fn row_handles(&self) -> &[File] {
|
||||
self.handles
|
||||
.get_or_init(|| independent_handles(&self.reader.file, ROW_HANDLES))
|
||||
}
|
||||
/// `read_rows` over any number of rows: the same three region reads per row, the same bounds and non-finite
|
||||
/// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill
|
||||
/// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk).
|
||||
pub fn read_rows_batch(&self, rows: &[u64]) -> Result<Vec<KarPleRowPacket>, KarError> {
|
||||
if rows.iter().any(|r| *r >= PLE_ROWS) {
|
||||
return Err(KarError::Range("KAR PLE row outside table"));
|
||||
}
|
||||
if self.reader.file.metadata().map_err(KarError::Io)?.len() != self.archive_bytes() {
|
||||
return Err(KarError::Integrity("KAR archive length changed"));
|
||||
}
|
||||
let mut packets = Vec::new();
|
||||
packets
|
||||
.try_reserve_exact(rows.len())
|
||||
.map_err(|_| KarError::Allocation)?;
|
||||
packets.resize(
|
||||
rows.len(),
|
||||
KarPleRowPacket {
|
||||
payload: [0; 50],
|
||||
partition: 0,
|
||||
},
|
||||
);
|
||||
// positional reads of a file that is not in the page cache are latency-bound: many in flight
|
||||
let workers = (rows.len() / 512).clamp(1, 32);
|
||||
if workers == 1 {
|
||||
self.read_chunk(rows, &mut packets)?;
|
||||
} else {
|
||||
let per = rows.len().div_ceil(workers);
|
||||
let results: Vec<Result<(), KarError>> = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = rows
|
||||
.chunks(per)
|
||||
.zip(packets.chunks_mut(per))
|
||||
.map(|(rows, out)| scope.spawn(move || self.read_chunk(rows, out)))
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
h.join()
|
||||
.unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
for r in results {
|
||||
r?;
|
||||
}
|
||||
}
|
||||
Ok(packets)
|
||||
read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), rows, 32, 512)
|
||||
}
|
||||
fn read_chunk(&self, rows: &[u64], out: &mut [KarPleRowPacket]) -> Result<(), KarError> {
|
||||
for (row, packet) in rows.iter().zip(out) {
|
||||
let index = self
|
||||
.parts
|
||||
.partition_point(|p| p.row_base <= *row)
|
||||
.checked_sub(1)
|
||||
.ok_or(KarError::Range("KAR PLE partition range"))?;
|
||||
let p = &self.parts[index];
|
||||
let local = row - p.row_base;
|
||||
if local >= p.row_count {
|
||||
return Err(KarError::Range("KAR PLE local row range"));
|
||||
}
|
||||
let scale = p
|
||||
.scales
|
||||
/// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread
|
||||
/// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead.
|
||||
pub fn row_reader(&self) -> Result<KarPleRowReader, KarError> {
|
||||
Ok(KarPleRowReader {
|
||||
files: independent_handles(&self.reader.file, ROW_HANDLES),
|
||||
parts: self.parts.clone(),
|
||||
archive_bytes: self.archive_bytes(),
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Handles a row read spreads its threads over. On Windows each has a file object of its own (a synchronous handle serializes the
|
||||
/// requests made through it, whatever the number of threads: 100,000 random reads of a cold chunk took 10 s that way).
|
||||
const ROW_HANDLES: usize = 16;
|
||||
/// `n` handles on `file` that can serve reads at the same time; the file itself when no more can be had.
|
||||
fn independent_handles(file: &File, n: usize) -> Vec<File> {
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
match reopen_independent(file) {
|
||||
Ok(f) => out.push(f),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
if let Ok(f) = file.try_clone() {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn reopen_independent(file: &File) -> std::io::Result<File> {
|
||||
leleka_libc_shim::reopen_file_read(file)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
fn reopen_independent(file: &File) -> std::io::Result<File> {
|
||||
// positional reads of one descriptor do not queue behind each other
|
||||
file.try_clone()
|
||||
}
|
||||
/// Rows of the PLE table read through an owned handle of the archive (`VerifiedKarPleArtifact::row_reader`): the same
|
||||
/// bytes, bounds and refusals as `read_rows_batch`, usable from a thread of its own.
|
||||
pub struct KarPleRowReader {
|
||||
files: Vec<File>,
|
||||
parts: Vec<VerifiedPart>,
|
||||
archive_bytes: u64,
|
||||
}
|
||||
impl KarPleRowReader {
|
||||
/// `max_threads` positional-read threads at most (one per 512 rows).
|
||||
pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result<Vec<KarPleRowPacket>, KarError> {
|
||||
read_rows_parallel(&self.files, &self.parts, self.archive_bytes, rows, max_threads, 512)
|
||||
}
|
||||
}
|
||||
fn read_rows_parallel(
|
||||
files: &[File],
|
||||
parts: &[VerifiedPart],
|
||||
archive_bytes: u64,
|
||||
rows: &[u64],
|
||||
max_threads: usize,
|
||||
min_rows_per_thread: usize,
|
||||
) -> Result<Vec<KarPleRowPacket>, KarError> {
|
||||
let Some(first) = files.first() else {
|
||||
return Err(KarError::Io(std::io::ErrorKind::NotFound.into()));
|
||||
};
|
||||
if rows.iter().any(|r| *r >= PLE_ROWS) {
|
||||
return Err(KarError::Range("KAR PLE row outside table"));
|
||||
}
|
||||
if first.metadata().map_err(KarError::Io)?.len() != archive_bytes {
|
||||
return Err(KarError::Integrity("KAR archive length changed"));
|
||||
}
|
||||
let mut packets = Vec::new();
|
||||
packets
|
||||
.try_reserve_exact(rows.len())
|
||||
.map_err(|_| KarError::Allocation)?;
|
||||
packets.resize(
|
||||
rows.len(),
|
||||
KarPleRowPacket {
|
||||
payload: [0; 50],
|
||||
partition: 0,
|
||||
},
|
||||
);
|
||||
// positional reads of a file that is not in the page cache are latency-bound: many in flight
|
||||
let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1));
|
||||
if workers == 1 {
|
||||
read_rows_chunk(first, parts, rows, &mut packets)?;
|
||||
} else {
|
||||
let per = rows.len().div_ceil(workers);
|
||||
let results: Vec<Result<(), KarError>> = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = rows
|
||||
.chunks(per)
|
||||
.zip(packets.chunks_mut(per))
|
||||
.enumerate()
|
||||
.map(|(i, (rows, out))| {
|
||||
let file = &files[i % files.len()];
|
||||
scope.spawn(move || read_rows_chunk(file, parts, rows, out))
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
h.join()
|
||||
.unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
for r in results {
|
||||
r?;
|
||||
}
|
||||
}
|
||||
Ok(packets)
|
||||
}
|
||||
fn read_rows_chunk(
|
||||
file: &File,
|
||||
parts: &[VerifiedPart],
|
||||
rows: &[u64],
|
||||
out: &mut [KarPleRowPacket],
|
||||
) -> Result<(), KarError> {
|
||||
for (row, packet) in rows.iter().zip(out) {
|
||||
let index = parts
|
||||
.partition_point(|p| p.row_base <= *row)
|
||||
.checked_sub(1)
|
||||
.ok_or(KarError::Range("KAR PLE partition range"))?;
|
||||
let p = &parts[index];
|
||||
let local = row - p.row_base;
|
||||
if local >= p.row_count {
|
||||
return Err(KarError::Range("KAR PLE local row range"));
|
||||
}
|
||||
let scale = p
|
||||
.scales
|
||||
.checked_add(
|
||||
local
|
||||
.checked_mul(10)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?,
|
||||
)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?;
|
||||
read_at(file, scale, &mut packet.payload[..10])?;
|
||||
for plane in 0..2usize {
|
||||
let at = p
|
||||
.planes
|
||||
.checked_add(
|
||||
local
|
||||
.checked_mul(10)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?,
|
||||
(plane as u64)
|
||||
.checked_mul(p.stride)
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?,
|
||||
)
|
||||
.ok_or(KarError::Range("KAR PLE scale overflow"))?;
|
||||
read_at(&self.reader.file, scale, &mut packet.payload[..10])?;
|
||||
for plane in 0..2usize {
|
||||
let at = p
|
||||
.planes
|
||||
.checked_add(
|
||||
(plane as u64)
|
||||
.checked_mul(p.stride)
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?,
|
||||
)
|
||||
.and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n)))
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?;
|
||||
read_at(
|
||||
&self.reader.file,
|
||||
at,
|
||||
&mut packet.payload[10 + plane * 20..30 + plane * 20],
|
||||
)?;
|
||||
}
|
||||
if packet.payload[..10]
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00)
|
||||
{
|
||||
return Err(KarError::Profile("KAR PLE nonfinite scale"));
|
||||
}
|
||||
packet.partition =
|
||||
u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?;
|
||||
.and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n)))
|
||||
.ok_or(KarError::Range("KAR PLE plane overflow"))?;
|
||||
read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?;
|
||||
}
|
||||
Ok(())
|
||||
if packet.payload[..10]
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00)
|
||||
{
|
||||
return Err(KarError::Profile("KAR PLE nonfinite scale"));
|
||||
}
|
||||
packet.partition =
|
||||
u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(unix)]
|
||||
fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> {
|
||||
|
||||
Reference in New Issue
Block a user