diff --git a/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs b/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs index 4fbd1b1f..4564caba 100644 --- a/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/kar_ple_cache.rs @@ -1,870 +1,872 @@ -//! One explicit experimental loaded provider, on its CUDA owner thread. -//! Cache mappings publish only after synchronized scatter + decode + finite readback. -#![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, 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; -#[derive(Clone, Copy)] -struct Entry { - slot: u32, - age: u64, -} -/// Row numbers are dense small integers: SipHash costs more than the rest of a chunk's lookups together. -#[derive(Default)] -struct RowHasher(u64); -impl Hasher for RowHasher { - fn finish(&self) -> u64 { - self.0 - } - fn write(&mut self, bytes: &[u8]) { - for b in bytes { - self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100000001b3); - } - } - fn write_u64(&mut self, value: u64) { - let mut x = value.wrapping_add(0x9e3779b97f4a7c15); - x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb); - self.0 = x ^ (x >> 31); - } -} -type RowMap = HashMap>; -/// A chunk's PLE rows resolved to cache slots (`KarPleCache::stage_batch`): the update records the device must -/// scatter and the slot of every row, plus the mapping changes `commit` publishes once the device has accepted them. -pub(super) struct KarPleStaged { - updates: Vec, - slots: Vec, - inserts: Vec<(u64, u32, Option)>, - next_slot: u32, - stamp: u64, -} -impl KarPleStaged { - pub(super) fn updates(&self) -> &[u8] { - &self.updates - } - pub(super) fn slots(&self) -> &[u32] { - &self.slots - } -} -/// Rows of a chunk against the cache map: the slot of every row the cache holds (its age refreshed to `stamp`), and -/// the distinct rows it lacks with, per position, which of them the position names (`u32::MAX` placeholder in `slots`). -struct Lookup { - slots: Vec, - miss_rows: Vec, - pending: Vec<(u32, u32)>, -} -fn lookup_rows(entries: &mut RowMap, rows: &[[u64; 16]], stamp: u64) -> Result { - let total = rows.len().checked_mul(16).ok_or(Error::Overflow)?; - let mut slots = Vec::new(); - slots - .try_reserve_exact(total) - .map_err(|_| Error::InputAllocation)?; - let mut miss_rows = Vec::::new(); - let mut miss_of = RowMap::::default(); - let mut pending = Vec::<(u32, u32)>::new(); - for (at, row) in rows.iter().flatten().enumerate() { - if let Some(entry) = entries.get_mut(row) { - entry.age = stamp; - slots.push(entry.slot); - continue; - } - let miss = match miss_of.get(row) { - Some(&m) => m, - None => { - let m = u32::try_from(miss_rows.len()).map_err(|_| Error::Overflow)?; - miss_rows.push(*row); - miss_of.insert(*row, m); - m - } - }; - slots.push(u32::MAX); - pending.push((at as u32, miss)); - } - Ok(Lookup { - slots, - miss_rows, - pending, - }) -} -/// A slot for each missing row: free slots first (`next_slot..capacity`), then the least recently used rows the chunk -/// did not touch (age below `stamp`). Returns the slot and the evicted row (if any) per miss, and the new `next_slot`. -#[allow(clippy::type_complexity)] -fn assign_slots( - entries: &RowMap, - next_slot: u32, - capacity: u32, - stamp: u64, - misses: usize, -) -> Result<(Vec, Vec>, u32)> { - let free = (capacity - next_slot) as usize; - let from_free = free.min(misses); - let mut miss_slot = Vec::::new(); - miss_slot - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; - let mut victims = Vec::>::new(); - victims - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; - for i in 0..from_free { - miss_slot.push(next_slot + i as u32); - victims.push(None); - } - let need = misses - from_free; - if need > 0 { - let mut candidates: Vec<(u64, u64, u32)> = entries - .iter() - .filter(|(_, e)| e.age < stamp) - .map(|(r, e)| (e.age, *r, e.slot)) - .collect(); - if candidates.len() < need { - return Err(Error::InvalidDimension); - } - candidates.select_nth_unstable_by_key(need - 1, |c| (c.0, c.1)); - for c in &candidates[..need] { - miss_slot.push(c.2); - victims.push(Some(c.1)); - } - } - Ok((miss_slot, victims, next_slot + from_free as u32)) -} -struct Miss { - row: u64, - slot: u32, - victim: Option, - 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 = 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>, - reader_failed: bool, - pending: Option>>, - ready: RowMap, -} -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>, - slots: DeviceBuffer<'ctx>, - output: DeviceBuffer<'ctx>, - binding: BindingIdentity, - archive: [u8; 32], - profile: [u8; 32], - entries: RowMap, - next_slot: u32, - age: u64, - failed: bool, -} -impl<'ctx> KarPleCache<'ctx> { - pub(crate) fn new(context: &'ctx Context<'ctx>, binding: &KarPleBinding) -> Result { - let book_bytes = binding - .books() - .len() - .checked_mul(8) - .ok_or(Error::Overflow)?; - let needed = CACHE_BYTES - .checked_add(book_bytes) - .and_then(|n| n.checked_add(64 + OUTPUT_BYTES + 16 * 56)) - .ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > context.budget_bytes()) - { - return Err(Error::InputAllocation); - } - let mut data = Vec::new(); - data.try_reserve_exact(book_bytes) - .map_err(|_| Error::InputAllocation)?; - for book in binding.books() { - for value in book { - data.extend_from_slice(&value.to_le_bytes()); - } - } - let cache = context - .allocate(CACHE_BYTES) - .map_err(|_| Error::CudaExecution)?; - let mut books = context - .allocate(book_bytes) - .map_err(|_| Error::CudaExecution)?; - books.copy_from(&data).map_err(|_| Error::CudaExecution)?; - let slots = context.allocate(64).map_err(|_| Error::CudaExecution)?; - let output = context - .allocate(OUTPUT_BYTES) - .map_err(|_| Error::CudaExecution)?; - Ok(Self { - ahead: Ahead::default(), - context, - cache, - books, - slots, - output, - binding: binding.identity(), - archive: *binding.archive_digest(), - profile: *binding.profile_digest(), - entries: RowMap::default(), - next_slot: 0, - age: 0, - failed: false, - }) - } - pub(super) fn context_matches(&self, context: &Context<'_>) -> bool { - std::ptr::eq(self.context, context) - } - /// The device cache and the partition books, for `OriginalPromptDevice::initialize_staged`. - pub(super) fn device_parts(&mut self) -> (&mut DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>) { - (&mut self.cache, &self.books) - } - /// A device failure after `stage_batch` may have scattered into the cache: no mapping is trusted again. - pub(super) fn invalidate(&mut self) { - self.failed = true; - } - /// `gather` for every PLE row of a chunk at once, on the device. Nothing is gathered here: this resolves each of - /// the `rows.len() * 16` rows to a cache slot (reading the archive packets of the rows the cache lacks, in - /// parallel), assigns slots to the misses (free slots first, then the least recently used rows the chunk does - /// not use) and returns the update records and slot table the driver scatters and decodes with. The decoded - /// value of a row depends only on its packet, so the placement never changes a value. The mapping changes - /// (`commit`) happen only after the device accepted the chunk. - pub(super) fn stage_batch( - &mut self, - binding: &KarPleBinding, - rows: &[[u64; 16]], - ) -> Result { - if self.failed { - return Err(Error::CudaExecution); - } - if !binding.matches(&self.binding) - || &self.archive != binding.archive_digest() - || &self.profile != binding.profile_digest() - { - return Err(Error::IdentityMismatch); - } - if rows.is_empty() || rows.iter().flatten().any(|r| *r >= PLE_ROWS) { - return Err(Error::InvalidDimension); - } - let stamp = self.age.checked_add(1).ok_or(Error::Overflow)?; - let Lookup { - mut slots, - miss_rows, - pending, - } = lookup_rows(&mut self.entries, rows, stamp)?; - let packets = if miss_rows.is_empty() { - Vec::new() - } else { - self.ahead.collect(); - // the rows the read-ahead already holds come from it; the others are read now, as before - let mut packets = Vec::>::new(); - packets - .try_reserve_exact(miss_rows.len()) - .map_err(|_| Error::InputAllocation)?; - let mut rest_at = Vec::::new(); - let mut rest_rows = Vec::::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 = 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::>>() - .ok_or(Error::InvalidDimension)? - }; - let misses = miss_rows.len(); - let (miss_slot, victims, next_slot) = - assign_slots(&self.entries, self.next_slot, SLOTS, stamp, misses)?; - for (at, miss) in pending { - slots[at as usize] = miss_slot[miss as usize]; - } - let mut updates = Vec::new(); - updates - .try_reserve_exact(misses * 56) - .map_err(|_| Error::InputAllocation)?; - let mut inserts = Vec::new(); - inserts - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; - for (i, packet) in packets.iter().enumerate() { - updates.extend_from_slice(&miss_slot[i].to_le_bytes()); - updates.extend_from_slice(packet.payload()); - updates.extend_from_slice(&packet.partition().to_le_bytes()); - inserts.push((miss_rows[i], miss_slot[i], victims[i])); - } - Ok(KarPleStaged { - updates, - slots, - inserts, - next_slot, - 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::::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 { - if let Some(victim) = victim { - self.entries.remove(victim); - } - } - for (row, slot, _) in staged.inserts { - self.entries.insert( - row, - Entry { - slot, - age: staged.stamp, - }, - ); - } - self.next_slot = staged.next_slot; - self.age = staged.stamp; - } - pub(super) fn gather( - &mut self, - binding: &KarPleBinding, - rows: &[u64; 16], - ) -> Result> { - if self.failed { - return Err(Error::CudaExecution); - } - if !binding.matches(&self.binding) - || &self.archive != binding.archive_digest() - || &self.profile != binding.profile_digest() - { - return Err(Error::IdentityMismatch); - } - let final_age = self.age.checked_add(16).ok_or(Error::Overflow)?; - // Read/validate every packet before any cache/device mutation. The FD stays in model_binding. - if rows.iter().any(|r| *r >= PLE_ROWS) { - return Err(Error::InvalidDimension); - } - let packets = if rows.iter().any(|r| !self.entries.contains_key(r)) { - Some( - binding - .read_rows(rows) - .map_err(super::input::binding_error)?, - ) - } else { - None - }; - let mut misses = Vec::::new(); - misses - .try_reserve_exact(16) - .map_err(|_| Error::InputAllocation)?; - let mut selected = [0u32; 16]; - let mut next_slot = self.next_slot; - for (i, row) in rows.iter().enumerate() { - if let Some(entry) = self.entries.get(row) { - selected[i] = entry.slot; - continue; - } - if let Some(miss) = misses.iter().find(|m| m.row == *row) { - selected[i] = miss.slot; - continue; - } - let (slot, victim) = if next_slot < SLOTS { - let slot = next_slot; - next_slot += 1; - (slot, None) - } else { - let (victim, entry) = self - .entries - .iter() - .filter(|(r, _)| { - !rows.contains(r) && !misses.iter().any(|m| m.victim == Some(**r)) - }) - .min_by_key(|(_, e)| e.age) - .ok_or(Error::InvalidDimension)?; - (entry.slot, Some(*victim)) - }; - selected[i] = slot; - let packet = &packets.as_ref().expect("missing rows require packets")[i]; - misses.push(Miss { - row: *row, - slot, - victim, - payload: *packet.payload(), - part: packet.partition(), - }); - } - let growth = misses.iter().filter(|m| m.victim.is_none()).count(); - self.entries - .try_reserve(growth) - .map_err(|_| Error::InputAllocation)?; - let mut updates = Vec::new(); - updates - .try_reserve_exact(misses.len() * 56) - .map_err(|_| Error::InputAllocation)?; - for m in &misses { - updates.extend_from_slice(&m.slot.to_le_bytes()); - updates.extend_from_slice(&m.payload); - updates.extend_from_slice(&m.part.to_le_bytes()); - } - let mut slot_bytes = [0u8; 64]; - for (i, slot) in selected.iter().enumerate() { - slot_bytes[i * 4..i * 4 + 4].copy_from_slice(&slot.to_le_bytes()); - } - let mut output = Vec::new(); - output - .try_reserve_exact(OUTPUT_BYTES) - .map_err(|_| Error::InputAllocation)?; - output.resize(OUTPUT_BYTES, 0); - let mut values = Vec::new(); - values - .try_reserve_exact(2560) - .map_err(|_| Error::InputAllocation)?; - // From the first mutating operation onward, any failure permanently invalidates - // this cache, including a partial scatter; no stale success mapping is reusable. - let completed = (|| { - if !updates.is_empty() { - let mut device = self - .context - .allocate(updates.len()) - .map_err(|_| Error::CudaExecution)?; - device - .copy_from(&updates) - .map_err(|_| Error::CudaExecution)?; - self.context - .kar_ple_scatter(&mut self.cache, &device, misses.len() as u32) - .map_err(|_| Error::CudaExecution)?; - device.release().map_err(|_| Error::CudaExecution)?; - } - self.slots - .copy_from(&slot_bytes) - .map_err(|_| Error::CudaExecution)?; - self.context - .kar_ple_decode(&self.cache, &self.slots, &self.books, &mut self.output) - .map_err(|_| Error::CudaExecution)?; - self.output - .copy_to(&mut output) - .map_err(|_| Error::CudaExecution)?; - for word in output.as_chunks::<4>().0 { - let v = f32::from_le_bytes(*word); - if !v.is_finite() { - return Err(Error::NonFinite); - } - values.push(v); - } - Ok(()) - })(); - if let Err(error) = completed { - self.failed = true; - return Err(error); - } - for m in misses { - if let Some(victim) = m.victim { - self.entries.remove(&victim); - } - self.entries.insert( - m.row, - Entry { - slot: m.slot, - age: 0, - }, - ); - } - for (i, row) in rows.iter().enumerate() { - self.entries - .get_mut(row) - .expect("completed batch mapping") - .age = self.age + i as u64 + 1; - } - self.next_slot = next_slot; - self.age = final_age; - Ok(values.into_boxed_slice()) - } -} - -/// Row-level parity probe against the Original's `strata_next_kar_ple_probe` -/// (gpu/kar/src/kar_ple_cpu_probe.cpp). Test-only: it admits a plain file path -/// through the same `VerifiedKarPleArtifact::verify` + pinned profile as -/// production, but does not touch the sealed-fd admission. -#[cfg(all(test, any(target_os = "linux", target_os = "windows")))] -mod row_parity_probe { - use super::*; - use crate::model_binding::qwen4exp_kar_ple::pinned_profile; - use leleka_cuda_driver::Driver; - use leleka_model_format::kar::{KarInspection, VerifiedKarPleArtifact}; - use std::io::Write; - - fn fnv(values: &[f32]) -> u64 { - let mut hash = 0xcbf29ce484222325u64; - for v in values { - for b in v.to_le_bytes() { - hash ^= u64::from(b); - hash = hash.wrapping_mul(0x100000001b3); - } - } - hash - } - - #[test] - #[ignore = "reads the real 55 GB KAR archive and uses the GPU; set LELEKA_PLE_PROBE_ARCHIVE and LELEKA_PLE_PROBE_ROWS"] - fn dump_decoded_rows_for_original_comparison() { - let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); - let rows_path = std::env::var("LELEKA_PLE_PROBE_ROWS").expect("rows file"); - let mut rows: Vec = std::fs::read_to_string(rows_path) - .expect("rows file readable") - .split_whitespace() - .map(|t| t.parse().expect("row number")) - .collect(); - let wanted = rows.len(); - while rows.len() % 16 != 0 { - rows.push(*rows.last().unwrap()); - } - let file = std::fs::File::open(archive).expect("archive opens"); - let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); - let identity = BindingIdentity::test_identity(); - let binding = KarPleBinding::new(&identity, artifact).expect("binding"); - let driver = Driver::load().expect("driver"); - let device = driver.device(0).expect("device0"); - let context = device.create_context(2usize << 30).expect("context"); - let mut cache = KarPleCache::new(&context, &binding).expect("cache"); - let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") - .ok() - .map(|p| std::fs::File::create(p).expect("dump file")); - let mut done = 0; - for chunk in rows.chunks_exact(16) { - let batch: [u64; 16] = chunk.try_into().unwrap(); - let values = cache.gather(&binding, &batch).expect("gather"); - for (i, row) in batch.iter().enumerate() { - if done + i < wanted { - println!("row={} fnv1a64={:016x}", row, fnv(&values[i * 160..(i + 1) * 160])); - } - } - if let Some(dump) = dump.as_mut() { - for v in values.iter() { - dump.write_all(&v.to_le_bytes()).unwrap(); - } - } - done += 16; - } - } - - #[test] - #[ignore = "reads the real 55 GB KAR archive (full payload verification); set LELEKA_PLE_PROBE_ARCHIVE"] - fn batch_read_equals_the_sixteen_row_reads() { - let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); - let file = std::fs::File::open(archive).expect("archive opens"); - let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); - let identity = BindingIdentity::test_identity(); - let binding = KarPleBinding::new(&identity, artifact).expect("binding"); - // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share - let mut state = 0x9e3779b97f4a7c15u64; - let mut rows: Vec = (0..40_000) - .map(|_| { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state % PLE_ROWS - }) - .collect(); - rows[0] = 0; - rows[1] = PLE_ROWS - 1; - while rows.len() % 16 != 0 { - rows.push(7); - } - let batch = binding.read_rows_batch(&rows).expect("batch read"); - assert_eq!(batch.len(), rows.len()); - for (i, chunk) in rows.chunks_exact(16).enumerate() { - let sixteen = binding.read_rows(chunk.try_into().unwrap()).expect("16-row read"); - for (j, packet) in sixteen.iter().enumerate() { - assert_eq!(packet.payload(), batch[i * 16 + j].payload(), "row {}", chunk[j]); - assert_eq!(packet.partition(), batch[i * 16 + j].partition(), "row {}", chunk[j]); - } - } - println!("batch read equals the 16-row reads for {} rows", rows.len()); - } -} - - -#[cfg(test)] -mod slot_tests { - use super::*; - - /// What `KarPleCache::commit` does to the map, over the pure parts. - fn apply( - entries: &mut RowMap, - lookup: &Lookup, - miss_slot: &[u32], - victims: &[Option], - stamp: u64, - ) { - for victim in victims.iter().flatten() { - entries.remove(victim); - } - for (i, row) in lookup.miss_rows.iter().enumerate() { - entries.insert( - *row, - Entry { - slot: miss_slot[i], - age: stamp, - }, - ); - } - } - fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { - rows.chunks(16) - .map(|c| std::array::from_fn(|i| c[i % c.len()])) - .collect() - } - /// Every row maps to one slot and no slot serves two rows. - fn consistent(entries: &RowMap) { - let mut seen = std::collections::HashSet::new(); - for entry in entries.values() { - assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); - } - } - - #[test] - fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { - let mut entries = RowMap::::default(); - let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); - let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); - assert_eq!(lookup.miss_rows.len(), 14); - let (miss_slot, victims, next) = assign_slots(&entries, 0, 100, 1, lookup.miss_rows.len()).unwrap(); - assert_eq!(next, 14); - assert!(victims.iter().all(Option::is_none)); - let mut slots = lookup.slots.clone(); - for (at, miss) in &lookup.pending { - slots[*at as usize] = miss_slot[*miss as usize]; - } - assert!(slots.iter().all(|s| *s < 14)); - assert_eq!(slots[0], slots[2]); - assert_eq!(slots[1], slots[4]); - apply(&mut entries, &lookup, &miss_slot, &victims, 1); - consistent(&entries); - assert_eq!(entries.len(), 14); - } - - #[test] - fn hits_keep_their_slots_and_refresh_their_age() { - let mut entries = RowMap::::default(); - let first = chunk(&[1, 2, 3, 4]); - let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); - let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries[r].slot)).collect(); - let second = chunk(&[3, 4, 5, 6]); - let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); - assert_eq!(lookup.miss_rows, vec![5, 6]); - assert_eq!(entries[&3].age, 2); - assert_eq!(entries[&1].age, 1); - for (row, slot) in before { - assert_eq!(entries[&row].slot, slot); - } - } - - #[test] - fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { - let mut entries = RowMap::::default(); - let capacity = 12u32; - let mut next = 0u32; - // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) - let rows1: Vec = (100..112).collect(); - let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap(); - let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - next = n; - assert_eq!(next, capacity); - let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap(); - assert!(lookup.miss_rows.is_empty()); - // chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1) - let rows3 = [100u64, 101, 500, 501, 502, 503]; - let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap(); - assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]); - let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap(); - assert_eq!(n, capacity); - let evicted: Vec = victims.iter().map(|v| v.expect("eviction")).collect(); - assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}"); - let distinct: std::collections::HashSet<_> = slot.iter().collect(); - assert_eq!(distinct.len(), 4); - // the evicted rows' slots are the ones handed out - for (i, v) in evicted.iter().enumerate() { - assert_eq!(entries[v].slot, slot[i]); - } - apply(&mut entries, &lookup, &slot, &victims, 3); - consistent(&entries); - assert_eq!(entries.len(), capacity as usize); - for r in [100u64, 101, 102, 103, 500, 501, 502, 503] { - assert!(entries.contains_key(&r), "row {r}"); - } - } - - /// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row - /// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. - #[test] - fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { - let mut entries = RowMap::::default(); - let first: Vec = (1..=32).map(|r| r * 1000).collect(); - let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); - let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - let given: std::collections::HashMap = entries.iter().map(|(r, e)| (*r, e.slot)).collect(); - let slot_of = |row: u64| given[&row]; - let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; - let flat = |lookup: &Lookup| lookup.slots.clone(); - // a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset - let mut swapped = first.clone(); - swapped.rotate_left(16); - let mut reversed = first.clone(); - reversed.reverse(); - let mut shifted = first.clone(); - shifted.rotate_left(1); - for (name, rows) in [ - ("swapped", swapped), - ("reversed", reversed), - ("shifted", shifted), - ("one row repeated", vec![first[5]; 16]), - ("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()), - ] { - let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap(); - assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss"); - assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot"); - } - // a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats - let mixed: Vec = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002]; - let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap(); - assert_eq!(lookup.miss_rows, vec![77_001, 77_002]); - for (at, &row) in mixed.iter().enumerate() { - let want = if row >= 77_000 { u32::MAX } else { slot_of(row) }; - // `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves - assert_eq!(lookup.slots[at], want, "mixed position {at}"); - } - // 77_001 stands at 2 of the 8 rows and 77_002 at 2: with the padding of the chunk, 4 positions name each - let named = |m: u32| lookup.pending.iter().filter(|(_, miss)| *miss == m).count(); - assert_eq!((named(0), named(1)), (4, 4)); - } - - #[test] - fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { - let mut entries = RowMap::::default(); - let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); - let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); - apply(&mut entries, &lookup, &slot, &victims, 1); - // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable - let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); - assert_eq!(lookup.miss_rows.len(), 4); - assert_eq!( - assign_slots(&entries, next, 8, 2, 4).err(), - Some(Error::InvalidDimension) - ); - } -} +//! One explicit experimental loaded provider, on its CUDA owner thread. +//! Cache mappings publish only after synchronized scatter + decode + finite readback. +#![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, 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; +#[derive(Clone, Copy)] +struct Entry { + slot: u32, + age: u64, +} +/// Row numbers are dense small integers: SipHash costs more than the rest of a chunk's lookups together. +#[derive(Default)] +struct RowHasher(u64); +impl Hasher for RowHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100000001b3); + } + } + fn write_u64(&mut self, value: u64) { + let mut x = value.wrapping_add(0x9e3779b97f4a7c15); + x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb); + self.0 = x ^ (x >> 31); + } +} +type RowMap = HashMap>; +/// A chunk's PLE rows resolved to cache slots (`KarPleCache::stage_batch`): the update records the device must +/// scatter and the slot of every row, plus the mapping changes `commit` publishes once the device has accepted them. +pub(super) struct KarPleStaged { + updates: Vec, + slots: Vec, + inserts: Vec<(u64, u32, Option)>, + next_slot: u32, + stamp: u64, +} +impl KarPleStaged { + pub(super) fn updates(&self) -> &[u8] { + &self.updates + } + pub(super) fn slots(&self) -> &[u32] { + &self.slots + } +} +/// Rows of a chunk against the cache map: the slot of every row the cache holds (its age refreshed to `stamp`), and +/// the distinct rows it lacks with, per position, which of them the position names (`u32::MAX` placeholder in `slots`). +struct Lookup { + slots: Vec, + miss_rows: Vec, + pending: Vec<(u32, u32)>, +} +fn lookup_rows(entries: &mut RowMap, rows: &[[u64; 16]], stamp: u64) -> Result { + let total = rows.len().checked_mul(16).ok_or(Error::Overflow)?; + let mut slots = Vec::new(); + slots + .try_reserve_exact(total) + .map_err(|_| Error::InputAllocation)?; + let mut miss_rows = Vec::::new(); + let mut miss_of = RowMap::::default(); + let mut pending = Vec::<(u32, u32)>::new(); + for (at, row) in rows.iter().flatten().enumerate() { + if let Some(entry) = entries.get_mut(row) { + entry.age = stamp; + slots.push(entry.slot); + continue; + } + let miss = match miss_of.get(row) { + Some(&m) => m, + None => { + let m = u32::try_from(miss_rows.len()).map_err(|_| Error::Overflow)?; + miss_rows.push(*row); + miss_of.insert(*row, m); + m + } + }; + slots.push(u32::MAX); + pending.push((at as u32, miss)); + } + Ok(Lookup { + slots, + miss_rows, + pending, + }) +} +/// A slot for each missing row: free slots first (`next_slot..capacity`), then the least recently used rows the chunk +/// did not touch (age below `stamp`). Returns the slot and the evicted row (if any) per miss, and the new `next_slot`. +#[allow(clippy::type_complexity)] +fn assign_slots( + entries: &RowMap, + next_slot: u32, + capacity: u32, + stamp: u64, + misses: usize, +) -> Result<(Vec, Vec>, u32)> { + let free = (capacity - next_slot) as usize; + let from_free = free.min(misses); + let mut miss_slot = Vec::::new(); + miss_slot + .try_reserve_exact(misses) + .map_err(|_| Error::InputAllocation)?; + let mut victims = Vec::>::new(); + victims + .try_reserve_exact(misses) + .map_err(|_| Error::InputAllocation)?; + for i in 0..from_free { + miss_slot.push(next_slot + i as u32); + victims.push(None); + } + let need = misses - from_free; + if need > 0 { + let mut candidates: Vec<(u64, u64, u32)> = entries + .iter() + .filter(|(_, e)| e.age < stamp) + .map(|(r, e)| (e.age, *r, e.slot)) + .collect(); + if candidates.len() < need { + return Err(Error::InvalidDimension); + } + candidates.select_nth_unstable_by_key(need - 1, |c| (c.0, c.1)); + for c in &candidates[..need] { + miss_slot.push(c.2); + victims.push(Some(c.1)); + } + } + Ok((miss_slot, victims, next_slot + from_free as u32)) +} +struct Miss { + row: u64, + slot: u32, + victim: Option, + 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 = 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>, + reader_failed: bool, + pending: Option>>, + ready: RowMap, +} +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>, + slots: DeviceBuffer<'ctx>, + output: DeviceBuffer<'ctx>, + binding: BindingIdentity, + archive: [u8; 32], + profile: [u8; 32], + entries: RowMap, + next_slot: u32, + age: u64, + failed: bool, +} +impl<'ctx> KarPleCache<'ctx> { + pub(crate) fn new(context: &'ctx Context<'ctx>, binding: &KarPleBinding) -> Result { + let book_bytes = binding + .books() + .len() + .checked_mul(8) + .ok_or(Error::Overflow)?; + let needed = CACHE_BYTES + .checked_add(book_bytes) + .and_then(|n| n.checked_add(64 + OUTPUT_BYTES + 16 * 56)) + .ok_or(Error::Overflow)?; + if context + .allocated_bytes() + .checked_add(needed) + .is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::InputAllocation); + } + let mut data = Vec::new(); + data.try_reserve_exact(book_bytes) + .map_err(|_| Error::InputAllocation)?; + for book in binding.books() { + for value in book { + data.extend_from_slice(&value.to_le_bytes()); + } + } + let cache = context + .allocate(CACHE_BYTES) + .map_err(|_| Error::CudaExecution)?; + let mut books = context + .allocate(book_bytes) + .map_err(|_| Error::CudaExecution)?; + books.copy_from(&data).map_err(|_| Error::CudaExecution)?; + let slots = context.allocate(64).map_err(|_| Error::CudaExecution)?; + let output = context + .allocate(OUTPUT_BYTES) + .map_err(|_| Error::CudaExecution)?; + Ok(Self { + ahead: Ahead::default(), + context, + cache, + books, + slots, + output, + binding: binding.identity(), + archive: *binding.archive_digest(), + profile: *binding.profile_digest(), + entries: RowMap::default(), + next_slot: 0, + age: 0, + failed: false, + }) + } + pub(super) fn context_matches(&self, context: &Context<'_>) -> bool { + std::ptr::eq(self.context, context) + } + /// The device cache and the partition books, for `OriginalPromptDevice::initialize_staged`. + pub(super) fn device_parts(&mut self) -> (&mut DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>) { + (&mut self.cache, &self.books) + } + /// A device failure after `stage_batch` may have scattered into the cache: no mapping is trusted again. + pub(super) fn invalidate(&mut self) { + self.failed = true; + } + /// `gather` for every PLE row of a chunk at once, on the device. Nothing is gathered here: this resolves each of + /// the `rows.len() * 16` rows to a cache slot (reading the archive packets of the rows the cache lacks, in + /// parallel), assigns slots to the misses (free slots first, then the least recently used rows the chunk does + /// not use) and returns the update records and slot table the driver scatters and decodes with. The decoded + /// value of a row depends only on its packet, so the placement never changes a value. The mapping changes + /// (`commit`) happen only after the device accepted the chunk. + pub(super) fn stage_batch( + &mut self, + binding: &KarPleBinding, + rows: &[[u64; 16]], + ) -> Result { + if self.failed { + return Err(Error::CudaExecution); + } + if !binding.matches(&self.binding) + || &self.archive != binding.archive_digest() + || &self.profile != binding.profile_digest() + { + return Err(Error::IdentityMismatch); + } + if rows.is_empty() || rows.iter().flatten().any(|r| *r >= PLE_ROWS) { + return Err(Error::InvalidDimension); + } + let stamp = self.age.checked_add(1).ok_or(Error::Overflow)?; + let Lookup { + mut slots, + miss_rows, + pending, + } = lookup_rows(&mut self.entries, rows, stamp)?; + let packets = if miss_rows.is_empty() { + Vec::new() + } else { + self.ahead.collect(); + // the rows the read-ahead already holds come from it; the others are read now, as before + let mut packets = Vec::>::new(); + packets + .try_reserve_exact(miss_rows.len()) + .map_err(|_| Error::InputAllocation)?; + let mut rest_at = Vec::::new(); + let mut rest_rows = Vec::::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 = 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::>>() + .ok_or(Error::InvalidDimension)? + }; + let misses = miss_rows.len(); + let (miss_slot, victims, next_slot) = + assign_slots(&self.entries, self.next_slot, SLOTS, stamp, misses)?; + for (at, miss) in pending { + slots[at as usize] = miss_slot[miss as usize]; + } + let mut updates = Vec::new(); + updates + .try_reserve_exact(misses * 56) + .map_err(|_| Error::InputAllocation)?; + let mut inserts = Vec::new(); + inserts + .try_reserve_exact(misses) + .map_err(|_| Error::InputAllocation)?; + for (i, packet) in packets.iter().enumerate() { + updates.extend_from_slice(&miss_slot[i].to_le_bytes()); + updates.extend_from_slice(packet.payload()); + updates.extend_from_slice(&packet.partition().to_le_bytes()); + inserts.push((miss_rows[i], miss_slot[i], victims[i])); + } + Ok(KarPleStaged { + updates, + slots, + inserts, + next_slot, + 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::::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 { + if let Some(victim) = victim { + self.entries.remove(victim); + } + } + for (row, slot, _) in staged.inserts { + self.entries.insert( + row, + Entry { + slot, + age: staged.stamp, + }, + ); + } + self.next_slot = staged.next_slot; + self.age = staged.stamp; + } + pub(super) fn gather( + &mut self, + binding: &KarPleBinding, + rows: &[u64; 16], + ) -> Result> { + if self.failed { + return Err(Error::CudaExecution); + } + if !binding.matches(&self.binding) + || &self.archive != binding.archive_digest() + || &self.profile != binding.profile_digest() + { + return Err(Error::IdentityMismatch); + } + let final_age = self.age.checked_add(16).ok_or(Error::Overflow)?; + // Read/validate every packet before any cache/device mutation. The FD stays in model_binding. + if rows.iter().any(|r| *r >= PLE_ROWS) { + return Err(Error::InvalidDimension); + } + let packets = if rows.iter().any(|r| !self.entries.contains_key(r)) { + let _p = super::original_serve_profile::span("ple.read_rows"); + Some( + binding + .read_rows(rows) + .map_err(super::input::binding_error)?, + ) + } else { + None + }; + let mut misses = Vec::::new(); + misses + .try_reserve_exact(16) + .map_err(|_| Error::InputAllocation)?; + let mut selected = [0u32; 16]; + let mut next_slot = self.next_slot; + for (i, row) in rows.iter().enumerate() { + if let Some(entry) = self.entries.get(row) { + selected[i] = entry.slot; + continue; + } + if let Some(miss) = misses.iter().find(|m| m.row == *row) { + selected[i] = miss.slot; + continue; + } + let (slot, victim) = if next_slot < SLOTS { + let slot = next_slot; + next_slot += 1; + (slot, None) + } else { + let (victim, entry) = self + .entries + .iter() + .filter(|(r, _)| { + !rows.contains(r) && !misses.iter().any(|m| m.victim == Some(**r)) + }) + .min_by_key(|(_, e)| e.age) + .ok_or(Error::InvalidDimension)?; + (entry.slot, Some(*victim)) + }; + selected[i] = slot; + let packet = &packets.as_ref().expect("missing rows require packets")[i]; + misses.push(Miss { + row: *row, + slot, + victim, + payload: *packet.payload(), + part: packet.partition(), + }); + } + let growth = misses.iter().filter(|m| m.victim.is_none()).count(); + self.entries + .try_reserve(growth) + .map_err(|_| Error::InputAllocation)?; + let mut updates = Vec::new(); + updates + .try_reserve_exact(misses.len() * 56) + .map_err(|_| Error::InputAllocation)?; + for m in &misses { + updates.extend_from_slice(&m.slot.to_le_bytes()); + updates.extend_from_slice(&m.payload); + updates.extend_from_slice(&m.part.to_le_bytes()); + } + let mut slot_bytes = [0u8; 64]; + for (i, slot) in selected.iter().enumerate() { + slot_bytes[i * 4..i * 4 + 4].copy_from_slice(&slot.to_le_bytes()); + } + let mut output = Vec::new(); + output + .try_reserve_exact(OUTPUT_BYTES) + .map_err(|_| Error::InputAllocation)?; + output.resize(OUTPUT_BYTES, 0); + let mut values = Vec::new(); + values + .try_reserve_exact(2560) + .map_err(|_| Error::InputAllocation)?; + // From the first mutating operation onward, any failure permanently invalidates + // this cache, including a partial scatter; no stale success mapping is reusable. + let _device_span = super::original_serve_profile::span("ple.device"); + let completed = (|| { + if !updates.is_empty() { + let mut device = self + .context + .allocate(updates.len()) + .map_err(|_| Error::CudaExecution)?; + device + .copy_from(&updates) + .map_err(|_| Error::CudaExecution)?; + self.context + .kar_ple_scatter(&mut self.cache, &device, misses.len() as u32) + .map_err(|_| Error::CudaExecution)?; + device.release().map_err(|_| Error::CudaExecution)?; + } + self.slots + .copy_from(&slot_bytes) + .map_err(|_| Error::CudaExecution)?; + self.context + .kar_ple_decode(&self.cache, &self.slots, &self.books, &mut self.output) + .map_err(|_| Error::CudaExecution)?; + self.output + .copy_to(&mut output) + .map_err(|_| Error::CudaExecution)?; + for word in output.as_chunks::<4>().0 { + let v = f32::from_le_bytes(*word); + if !v.is_finite() { + return Err(Error::NonFinite); + } + values.push(v); + } + Ok(()) + })(); + if let Err(error) = completed { + self.failed = true; + return Err(error); + } + for m in misses { + if let Some(victim) = m.victim { + self.entries.remove(&victim); + } + self.entries.insert( + m.row, + Entry { + slot: m.slot, + age: 0, + }, + ); + } + for (i, row) in rows.iter().enumerate() { + self.entries + .get_mut(row) + .expect("completed batch mapping") + .age = self.age + i as u64 + 1; + } + self.next_slot = next_slot; + self.age = final_age; + Ok(values.into_boxed_slice()) + } +} + +/// Row-level parity probe against the Original's `strata_next_kar_ple_probe` +/// (gpu/kar/src/kar_ple_cpu_probe.cpp). Test-only: it admits a plain file path +/// through the same `VerifiedKarPleArtifact::verify` + pinned profile as +/// production, but does not touch the sealed-fd admission. +#[cfg(all(test, any(target_os = "linux", target_os = "windows")))] +mod row_parity_probe { + use super::*; + use crate::model_binding::qwen4exp_kar_ple::pinned_profile; + use leleka_cuda_driver::Driver; + use leleka_model_format::kar::{KarInspection, VerifiedKarPleArtifact}; + use std::io::Write; + + fn fnv(values: &[f32]) -> u64 { + let mut hash = 0xcbf29ce484222325u64; + for v in values { + for b in v.to_le_bytes() { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x100000001b3); + } + } + hash + } + + #[test] + #[ignore = "reads the real 55 GB KAR archive and uses the GPU; set LELEKA_PLE_PROBE_ARCHIVE and LELEKA_PLE_PROBE_ROWS"] + fn dump_decoded_rows_for_original_comparison() { + let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); + let rows_path = std::env::var("LELEKA_PLE_PROBE_ROWS").expect("rows file"); + let mut rows: Vec = std::fs::read_to_string(rows_path) + .expect("rows file readable") + .split_whitespace() + .map(|t| t.parse().expect("row number")) + .collect(); + let wanted = rows.len(); + while rows.len() % 16 != 0 { + rows.push(*rows.last().unwrap()); + } + let file = std::fs::File::open(archive).expect("archive opens"); + let inspection = KarInspection::inspect(file).expect("inspect"); + let artifact = + VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); + let identity = BindingIdentity::test_identity(); + let binding = KarPleBinding::new(&identity, artifact).expect("binding"); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device0"); + let context = device.create_context(2usize << 30).expect("context"); + let mut cache = KarPleCache::new(&context, &binding).expect("cache"); + let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") + .ok() + .map(|p| std::fs::File::create(p).expect("dump file")); + let mut done = 0; + for chunk in rows.chunks_exact(16) { + let batch: [u64; 16] = chunk.try_into().unwrap(); + let values = cache.gather(&binding, &batch).expect("gather"); + for (i, row) in batch.iter().enumerate() { + if done + i < wanted { + println!("row={} fnv1a64={:016x}", row, fnv(&values[i * 160..(i + 1) * 160])); + } + } + if let Some(dump) = dump.as_mut() { + for v in values.iter() { + dump.write_all(&v.to_le_bytes()).unwrap(); + } + } + done += 16; + } + } + + #[test] + #[ignore = "reads the real 55 GB KAR archive (full payload verification); set LELEKA_PLE_PROBE_ARCHIVE"] + fn batch_read_equals_the_sixteen_row_reads() { + let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); + let file = std::fs::File::open(archive).expect("archive opens"); + let inspection = KarInspection::inspect(file).expect("inspect"); + let artifact = + VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); + let identity = BindingIdentity::test_identity(); + let binding = KarPleBinding::new(&identity, artifact).expect("binding"); + // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share + let mut state = 0x9e3779b97f4a7c15u64; + let mut rows: Vec = (0..40_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % PLE_ROWS + }) + .collect(); + rows[0] = 0; + rows[1] = PLE_ROWS - 1; + while rows.len() % 16 != 0 { + rows.push(7); + } + let batch = binding.read_rows_batch(&rows).expect("batch read"); + assert_eq!(batch.len(), rows.len()); + for (i, chunk) in rows.chunks_exact(16).enumerate() { + let sixteen = binding.read_rows(chunk.try_into().unwrap()).expect("16-row read"); + for (j, packet) in sixteen.iter().enumerate() { + assert_eq!(packet.payload(), batch[i * 16 + j].payload(), "row {}", chunk[j]); + assert_eq!(packet.partition(), batch[i * 16 + j].partition(), "row {}", chunk[j]); + } + } + println!("batch read equals the 16-row reads for {} rows", rows.len()); + } +} + + +#[cfg(test)] +mod slot_tests { + use super::*; + + /// What `KarPleCache::commit` does to the map, over the pure parts. + fn apply( + entries: &mut RowMap, + lookup: &Lookup, + miss_slot: &[u32], + victims: &[Option], + stamp: u64, + ) { + for victim in victims.iter().flatten() { + entries.remove(victim); + } + for (i, row) in lookup.miss_rows.iter().enumerate() { + entries.insert( + *row, + Entry { + slot: miss_slot[i], + age: stamp, + }, + ); + } + } + fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { + rows.chunks(16) + .map(|c| std::array::from_fn(|i| c[i % c.len()])) + .collect() + } + /// Every row maps to one slot and no slot serves two rows. + fn consistent(entries: &RowMap) { + let mut seen = std::collections::HashSet::new(); + for entry in entries.values() { + assert!(seen.insert(entry.slot), "slot {} serves two rows", entry.slot); + } + } + + #[test] + fn a_fresh_chunk_gets_distinct_free_slots_and_duplicates_share_one() { + let mut entries = RowMap::::default(); + let rows = chunk(&[10, 20, 10, 30, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]); + let lookup = lookup_rows(&mut entries, &rows, 1).unwrap(); + assert_eq!(lookup.miss_rows.len(), 14); + let (miss_slot, victims, next) = assign_slots(&entries, 0, 100, 1, lookup.miss_rows.len()).unwrap(); + assert_eq!(next, 14); + assert!(victims.iter().all(Option::is_none)); + let mut slots = lookup.slots.clone(); + for (at, miss) in &lookup.pending { + slots[*at as usize] = miss_slot[*miss as usize]; + } + assert!(slots.iter().all(|s| *s < 14)); + assert_eq!(slots[0], slots[2]); + assert_eq!(slots[1], slots[4]); + apply(&mut entries, &lookup, &miss_slot, &victims, 1); + consistent(&entries); + assert_eq!(entries.len(), 14); + } + + #[test] + fn hits_keep_their_slots_and_refresh_their_age() { + let mut entries = RowMap::::default(); + let first = chunk(&[1, 2, 3, 4]); + let lookup = lookup_rows(&mut entries, &first, 1).unwrap(); + let (slot, victims, _) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + let before: Vec<(u64, u32)> = [1u64, 2, 3, 4].iter().map(|r| (*r, entries[r].slot)).collect(); + let second = chunk(&[3, 4, 5, 6]); + let lookup = lookup_rows(&mut entries, &second, 2).unwrap(); + assert_eq!(lookup.miss_rows, vec![5, 6]); + assert_eq!(entries[&3].age, 2); + assert_eq!(entries[&1].age, 1); + for (row, slot) in before { + assert_eq!(entries[&row].slot, slot); + } + } + + #[test] + fn a_full_cache_evicts_the_oldest_rows_the_chunk_does_not_touch() { + let mut entries = RowMap::::default(); + let capacity = 12u32; + let mut next = 0u32; + // chunk 1 fills 12 slots with rows 100..112 (stamp 1), chunk 2 refreshes 100..104 (stamp 2) + let rows1: Vec = (100..112).collect(); + let lookup = lookup_rows(&mut entries, &chunk(&rows1), 1).unwrap(); + let (slot, victims, n) = assign_slots(&entries, next, capacity, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + next = n; + assert_eq!(next, capacity); + let lookup = lookup_rows(&mut entries, &chunk(&[100, 101, 102, 103]), 2).unwrap(); + assert!(lookup.miss_rows.is_empty()); + // chunk 3 touches 100, 101 and needs four new rows: the victims are the four oldest of 104..112 (age 1) + let rows3 = [100u64, 101, 500, 501, 502, 503]; + let lookup = lookup_rows(&mut entries, &chunk(&rows3), 3).unwrap(); + assert_eq!(lookup.miss_rows, vec![500, 501, 502, 503]); + let (slot, victims, n) = assign_slots(&entries, next, capacity, 3, lookup.miss_rows.len()).unwrap(); + assert_eq!(n, capacity); + let evicted: Vec = victims.iter().map(|v| v.expect("eviction")).collect(); + assert!(evicted.iter().all(|r| (104..112).contains(r)), "{evicted:?}"); + let distinct: std::collections::HashSet<_> = slot.iter().collect(); + assert_eq!(distinct.len(), 4); + // the evicted rows' slots are the ones handed out + for (i, v) in evicted.iter().enumerate() { + assert_eq!(entries[v].slot, slot[i]); + } + apply(&mut entries, &lookup, &slot, &victims, 3); + consistent(&entries); + assert_eq!(entries.len(), capacity as usize); + for r in [100u64, 101, 102, 103, 500, 501, 502, 503] { + assert!(entries.contains_key(&r), "row {r}"); + } + } + + /// Upstream 41cf05a0 `36381540` (`gather_batch` matched the prefetched rows by position): here rows are looked up by row + /// id, so a reordered, shifted, repeated or partly new chunk finds each row in the slot it was given, and a hit never moves. + #[test] + fn rows_are_matched_by_row_id_never_by_position_in_the_chunk() { + let mut entries = RowMap::::default(); + let first: Vec = (1..=32).map(|r| r * 1000).collect(); + let lookup = lookup_rows(&mut entries, &chunk(&first), 1).unwrap(); + let (slot, victims, _) = assign_slots(&entries, 0, 64, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + let given: std::collections::HashMap = entries.iter().map(|(r, e)| (*r, e.slot)).collect(); + let slot_of = |row: u64| given[&row]; + let expect = |rows: &[u64]| -> Vec { rows.iter().map(|&r| slot_of(r)).collect() }; + let flat = |lookup: &Lookup| lookup.slots.clone(); + // a permutation (halves swapped), a reversal, a shift by one position, a repeat of one row and a subset + let mut swapped = first.clone(); + swapped.rotate_left(16); + let mut reversed = first.clone(); + reversed.reverse(); + let mut shifted = first.clone(); + shifted.rotate_left(1); + for (name, rows) in [ + ("swapped", swapped), + ("reversed", reversed), + ("shifted", shifted), + ("one row repeated", vec![first[5]; 16]), + ("subset", (0..16).map(|i| first[(i * 7) % 32]).collect()), + ] { + let lookup = lookup_rows(&mut entries, &chunk(&rows), 2).unwrap(); + assert!(lookup.miss_rows.is_empty() && lookup.pending.is_empty(), "{name}: a cached row is a miss"); + assert_eq!(flat(&lookup), expect(&rows), "{name}: a position got another row's slot"); + } + // a chunk of known and new rows: the known keep their slots wherever they stand, each new row is one miss however often it repeats + let mixed: Vec = vec![first[3], 77_001, first[0], 77_001, 77_002, first[3], first[31], 77_002]; + let lookup = lookup_rows(&mut entries, &chunk(&mixed), 3).unwrap(); + assert_eq!(lookup.miss_rows, vec![77_001, 77_002]); + for (at, &row) in mixed.iter().enumerate() { + let want = if row >= 77_000 { u32::MAX } else { slot_of(row) }; + // `chunk` pads a short chunk by repeating its rows: the first `mixed.len()` positions are the rows themselves + assert_eq!(lookup.slots[at], want, "mixed position {at}"); + } + // 77_001 stands at 2 of the 8 rows and 77_002 at 2: with the padding of the chunk, 4 positions name each + let named = |m: u32| lookup.pending.iter().filter(|(_, miss)| *miss == m).count(); + assert_eq!((named(0), named(1)), (4, 4)); + } + + #[test] + fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { + let mut entries = RowMap::::default(); + let lookup = lookup_rows(&mut entries, &chunk(&(0..8).collect::>()), 1).unwrap(); + let (slot, victims, next) = assign_slots(&entries, 0, 8, 1, lookup.miss_rows.len()).unwrap(); + apply(&mut entries, &lookup, &slot, &victims, 1); + // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable + let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); + assert_eq!(lookup.miss_rows.len(), 4); + assert_eq!( + assign_slots(&entries, next, 8, 2, 4).err(), + Some(Error::InvalidDimension) + ); + } +}