Merge claude/laptop-vs-vanilla into main
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
//! Start-up report of the CUDA devices and of the kernel set each one runs (operator log only, no behaviour).
|
||||
//!
|
||||
//! Every PTX asset of this crate is sealed for sm_120. A device of compute capability 12.x loads those images as they are; a device of
|
||||
//! 8.6 <= cc < 12.0 loads the pinned sm_86 companions when the build has the `sm86` feature (`arch_ptx`); anything else cannot load them.
|
||||
//! The report goes through the driver API directly (no context needed), so it lists every device of the machine, not only the one in use.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
/// One line per CUDA device, preceded by one line with the driver version. Empty when the driver cannot be loaded.
|
||||
pub fn gpu_kernel_report() -> Vec<String> {
|
||||
imp::report()
|
||||
}
|
||||
|
||||
/// The kernel set a device of compute capability (`major`, `minor`) runs, and the MMQ launch policy that follows from it.
|
||||
fn kernel_set(major: i32, minor: i32, sm86_build: bool) -> (&'static str, &'static str) {
|
||||
if major >= 12 {
|
||||
("sealed sm_120 PTX, native", "stream-K grid")
|
||||
} else if (major, minor) >= (8, 6) {
|
||||
if sm86_build {
|
||||
("pinned sm_86 companion PTX of the sealed sm_120 images", "one block per tile (stream-K off, STRA-235)")
|
||||
} else {
|
||||
("NONE: this build has no sm_86 companions, the sealed sm_120 images cannot load", "-")
|
||||
}
|
||||
} else {
|
||||
("NONE: compute capability below 8.6 is not supported", "-")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
mod imp {
|
||||
use super::kernel_set;
|
||||
use std::ffi::{CStr, c_char, c_int, c_void};
|
||||
|
||||
type Init = unsafe extern "C" fn(u32) -> c_int;
|
||||
type Count = unsafe extern "C" fn(*mut c_int) -> c_int;
|
||||
type Get = unsafe extern "C" fn(*mut c_int, c_int) -> c_int;
|
||||
type Name = unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int;
|
||||
type TotalMem = unsafe extern "C" fn(*mut usize, c_int) -> c_int;
|
||||
type Attr = unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int;
|
||||
type Version = unsafe extern "C" fn(*mut c_int) -> c_int;
|
||||
|
||||
/// # Safety
|
||||
/// `T` must be the exact `extern "C"` signature of the named driver function.
|
||||
unsafe fn symbol<T: Copy>(handle: *mut c_void, name: &CStr) -> Option<T> {
|
||||
debug_assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<*mut c_void>());
|
||||
// SAFETY: valid dlopen handle and a static C name.
|
||||
let address = unsafe { libc::dlsym(handle, name.as_ptr()) };
|
||||
if address.is_null() {
|
||||
None
|
||||
} else {
|
||||
// SAFETY: function pointers and data pointers have the same size on the 64-bit targets; signature per the caller.
|
||||
Some(unsafe { std::mem::transmute_copy::<*mut c_void, T>(&address) })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn report() -> Vec<String> {
|
||||
// SAFETY: fixed library name; the handle is closed below.
|
||||
let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW) };
|
||||
if handle.is_null() {
|
||||
return Vec::new();
|
||||
}
|
||||
let lines = (|| {
|
||||
// SAFETY: fixed driver symbol names, paired with their documented signatures.
|
||||
let (init, count, get, name, total, attr, version) = unsafe {
|
||||
(
|
||||
symbol::<Init>(handle, c"cuInit")?,
|
||||
symbol::<Count>(handle, c"cuDeviceGetCount")?,
|
||||
symbol::<Get>(handle, c"cuDeviceGet")?,
|
||||
symbol::<Name>(handle, c"cuDeviceGetName")?,
|
||||
symbol::<TotalMem>(handle, c"cuDeviceTotalMem_v2")?,
|
||||
symbol::<Attr>(handle, c"cuDeviceGetAttribute")?,
|
||||
symbol::<Version>(handle, c"cuDriverGetVersion")?,
|
||||
)
|
||||
};
|
||||
let sm86_build = cfg!(feature = "sm86");
|
||||
let mut lines = Vec::new();
|
||||
let (mut n, mut v) = (0, 0);
|
||||
// SAFETY: valid writable outputs for every driver call below; devices are queried by ordinals the driver just counted.
|
||||
unsafe {
|
||||
if init(0) != 0 || count(&mut n) != 0 {
|
||||
return None;
|
||||
}
|
||||
let _ = version(&mut v);
|
||||
lines.push(format!(
|
||||
"gpu: CUDA driver {}.{}, {n} device(s), sm_86 companions in this build: {}, chain kernels: {}",
|
||||
v / 1000,
|
||||
v % 1000 / 10,
|
||||
if sm86_build { "yes" } else { "no" },
|
||||
std::env::var("LELEKA_CHAIN").unwrap_or_else(|_| "default".to_owned())
|
||||
));
|
||||
for ordinal in 0..n {
|
||||
let mut dev = 0;
|
||||
if get(&mut dev, ordinal) != 0 {
|
||||
continue;
|
||||
}
|
||||
let mut label = [0 as c_char; 128];
|
||||
let label = if name(label.as_mut_ptr(), 128, dev) == 0 {
|
||||
CStr::from_ptr(label.as_ptr()).to_string_lossy().into_owned()
|
||||
} else {
|
||||
"unknown model".to_owned()
|
||||
};
|
||||
let (mut major, mut minor, mut sms, mut bytes) = (0, 0, 0, 0usize);
|
||||
let _ = attr(&mut major, 75, dev);
|
||||
let _ = attr(&mut minor, 76, dev);
|
||||
let _ = attr(&mut sms, 16, dev);
|
||||
let _ = total(&mut bytes, dev);
|
||||
let (set, mmq) = kernel_set(major, minor, sm86_build);
|
||||
lines.push(format!(
|
||||
"gpu {ordinal}: {label}, cc {major}.{minor}, {sms} SMs, {:.1} GiB; kernels: {set}; MMQ launch: {mmq}",
|
||||
bytes as f64 / f64::from(1u32 << 30)
|
||||
));
|
||||
}
|
||||
}
|
||||
Some(lines)
|
||||
})();
|
||||
// SAFETY: the handle returned above, closed exactly once.
|
||||
unsafe {
|
||||
libc::dlclose(handle);
|
||||
}
|
||||
lines.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))]
|
||||
mod imp {
|
||||
pub(super) fn report() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::kernel_set;
|
||||
|
||||
#[test]
|
||||
fn the_kernel_set_follows_the_compute_capability() {
|
||||
assert_eq!(kernel_set(12, 0, false).0, "sealed sm_120 PTX, native");
|
||||
assert!(kernel_set(8, 6, true).0.contains("sm_86 companion"));
|
||||
assert!(kernel_set(8, 9, true).0.contains("sm_86 companion"));
|
||||
assert!(kernel_set(8, 6, false).0.starts_with("NONE"));
|
||||
assert!(kernel_set(7, 5, true).0.starts_with("NONE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_report_never_panics_without_a_driver() {
|
||||
for line in super::gpu_kernel_report() {
|
||||
eprintln!("{line}");
|
||||
assert!(line.starts_with("gpu"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3233,6 +3233,8 @@ mod original_sampler_params;
|
||||
mod sealed_ptx;
|
||||
#[allow(unsafe_code)]
|
||||
mod arch_ptx;
|
||||
mod gpu_report;
|
||||
pub use gpu_report::gpu_kernel_report;
|
||||
#[cfg(feature = "sm86")]
|
||||
mod sm86_table;
|
||||
#[allow(unsafe_code)]
|
||||
|
||||
@@ -31,6 +31,63 @@ fn verify_enabled() -> bool {
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Job {
|
||||
pub(super) pieces: [(usize, usize, u32); 3],
|
||||
/// Memory priority the helper reads these pages at (Windows; 0: leave the thread's default): see `layer_priority`.
|
||||
pub(super) priority: u8,
|
||||
}
|
||||
|
||||
/// The default memory priority of a thread on Windows.
|
||||
const NORMAL_PRIORITY: u8 = 5;
|
||||
/// The priority of the layers whose experts are not meant to stay cached.
|
||||
const LOW_PRIORITY: u8 = 1;
|
||||
const LAYERS: usize = 48;
|
||||
|
||||
/// Memory priority for the page-cache pages of the experts a layer's helpers read (Windows only, `LELEKA_STAGE_PRIORITY=on|off|<GiB>`).
|
||||
///
|
||||
/// Every chunk of a long prompt reads every expert the GPU does not hold, layer 0 to 47, then starts again at layer 0. The file cache keeps
|
||||
/// the most recently used pages, so a scan longer than the cache finds none of its pages again: with 10 GiB of cache and 40 GiB to read,
|
||||
/// every chunk reads all 40 GiB from the drive. Reading the first layers at a low memory priority makes the memory manager repurpose their
|
||||
/// pages first, so the pages of the last layers stay cached from one chunk to the next (measured with `wsrun-lvv/iobench.ps1`: a cyclic
|
||||
/// scan of 12 GiB through ~7 GiB of cache took 3.0-3.7 s per pass without it and 0.8 s with it). The first `layers - n` layers read at
|
||||
/// low priority, where `n` layers fit the budget: `LELEKA_STAGE_PRIORITY=<GiB>`, or with `on` 90 % of the available RAM less 2 GiB. Only
|
||||
/// which pages the cache keeps changes, never a byte read or its order. Off unless asked for (until measured on the laptop).
|
||||
pub(super) fn layer_priority(layer: usize, per_layer_bytes: usize) -> u8 {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::sync::OnceLock;
|
||||
static MODE: OnceLock<Option<Option<u64>>> = OnceLock::new();
|
||||
let mode = *MODE.get_or_init(|| match std::env::var("LELEKA_STAGE_PRIORITY").ok().as_deref() {
|
||||
Some("on") | Some("auto") | Some("1") => Some(None),
|
||||
Some(other) => other.parse::<f64>().ok().filter(|g| *g > 0.0).map(|g| Some((g * (1u64 << 30) as f64) as u64)),
|
||||
None => None,
|
||||
});
|
||||
let Some(fixed) = mode else { return 0 };
|
||||
let budget = match fixed {
|
||||
Some(bytes) => bytes,
|
||||
None => match libc::physical_memory() {
|
||||
Some((_, available)) => (available.saturating_sub(2 << 30) as f64 * 0.9) as u64,
|
||||
None => return 0,
|
||||
},
|
||||
};
|
||||
let high = (budget / per_layer_bytes.max(1) as u64) as usize;
|
||||
if layer + high < LAYERS { LOW_PRIORITY } else { NORMAL_PRIORITY }
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (layer, per_layer_bytes);
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the calling thread's memory priority (a no-op off Windows).
|
||||
fn apply_priority(priority: u8) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = libc::set_thread_memory_priority(u32::from(priority));
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = priority;
|
||||
}
|
||||
}
|
||||
|
||||
struct Wake {
|
||||
@@ -100,6 +157,7 @@ impl Shared {
|
||||
}
|
||||
fn work(&self) {
|
||||
let mut seen = 0u32;
|
||||
let mut applied = NORMAL_PRIORITY;
|
||||
loop {
|
||||
let jobs = {
|
||||
let mut wake = self.wake.lock().unwrap_or_else(|p| p.into_inner());
|
||||
@@ -134,6 +192,11 @@ impl Shared {
|
||||
cancelled |= self.finished(seen);
|
||||
if !cancelled {
|
||||
let job = jobs[j];
|
||||
let wanted = if job.priority == 0 { NORMAL_PRIORITY } else { job.priority };
|
||||
if wanted != applied {
|
||||
apply_priority(wanted);
|
||||
applied = wanted;
|
||||
}
|
||||
let base = self.buffers[j % ring];
|
||||
let mut offset = 0usize;
|
||||
let mut finite = true;
|
||||
@@ -480,7 +543,7 @@ mod tests {
|
||||
}
|
||||
fn job(bytes: &[u8]) -> Job {
|
||||
let piece = |i: usize| (bytes[i * 18..].as_ptr() as usize, 18, 20);
|
||||
Job { pieces: [piece(0), piece(1), piece(2)] }
|
||||
Job { pieces: [piece(0), piece(1), piece(2)], priority: 0 }
|
||||
}
|
||||
|
||||
/// `wait` hands out `length` bytes of a page-locked buffer that production allocates uninitialised: a length
|
||||
|
||||
@@ -728,7 +728,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
pieces[role] = (bytes.as_ptr() as usize, bytes.len(), span.raw_kind());
|
||||
}
|
||||
source.job = Some(jobs.len());
|
||||
jobs.push(Job { pieces });
|
||||
jobs.push(Job { pieces, priority: 0 });
|
||||
}
|
||||
}
|
||||
if !jobs.is_empty() {
|
||||
let priority = host_stage::layer_priority(layer, jobs.len().saturating_mul(blob));
|
||||
for job in &mut jobs {
|
||||
job.priority = priority;
|
||||
}
|
||||
}
|
||||
let charge = groups * 16;
|
||||
|
||||
@@ -35,7 +35,7 @@ tokio = { version = "1", features = ["rt", "macros", "process", "io-util", "time
|
||||
rustix = { version = "=1.1.5", features = ["fs", "process", "stdio"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Console", "Win32_UI_WindowsAndMessaging"] }
|
||||
leleka-memory = { path = "../leleka-memory" }
|
||||
|
||||
# The workspace forbids unsafe code; this crate denies it and lets exactly one module (`winsys`, Windows only) opt in.
|
||||
|
||||
@@ -52,6 +52,9 @@ pub struct Facts {
|
||||
pub memory: Memory,
|
||||
/// Logical CPUs this process may use (affinity and cgroup quota aware); 0 when unknown.
|
||||
pub cpu_cores: u32,
|
||||
/// Physical cores (SMT siblings counted once) when the platform says so (Windows); 0 when unknown. The CPU expert pool's
|
||||
/// workers spin, so a worker without a core of its own slows the ones that have one (`native-cpu-expert::pool_plan`).
|
||||
pub cpu_physical_cores: u32,
|
||||
/// `memory.max` of the cgroup this process runs in, when limited.
|
||||
pub cgroup_memory_max: Option<u64>,
|
||||
pub wsl: bool,
|
||||
@@ -301,6 +304,7 @@ mod windows {
|
||||
.map(|text| parse_meminfo(&text))
|
||||
.unwrap_or_default();
|
||||
facts.cpu_cores = std::thread::available_parallelism().map_or(0, |n| n.get() as u32);
|
||||
facts.cpu_physical_cores = crate::winsys::physical_cores().unwrap_or(0);
|
||||
|
||||
match nvidia_smi() {
|
||||
None => facts.nvidia_smi_error = Some("nvidia-smi.exe was not found in PATH or System32".into()),
|
||||
|
||||
@@ -162,7 +162,15 @@ pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Pres
|
||||
Preset::Workstation if cores <= 16 => 4,
|
||||
Preset::Workstation => 8,
|
||||
};
|
||||
plan.cpu_workers = Some(cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS));
|
||||
let mut workers = cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS);
|
||||
// The pool's workers spin while they wait: one without a core of its own steals cycles from one that has it, so a
|
||||
// bigger count is slower, not just useless (docs/upstream-port-plan.md row 2.3). Where the platform reports the
|
||||
// physical cores (Windows), the count never exceeds every physical core but the host thread's: 7 on the 8-core
|
||||
// laptop instead of 12 (the workstation preset's logical-core count); the 16-core server is unchanged (15).
|
||||
if facts.cpu_physical_cores > 0 {
|
||||
workers = workers.min(facts.cpu_physical_cores.saturating_sub(1).max(1));
|
||||
}
|
||||
plan.cpu_workers = Some(workers);
|
||||
if preset == Preset::Workstation && cores < leave + 1 {
|
||||
plan.warnings.push(format!(
|
||||
"only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)"
|
||||
@@ -366,6 +374,20 @@ mod tests {
|
||||
Profile::builtin("rtx3080-16g").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workers_never_exceed_the_physical_cores_but_the_hosts_where_those_are_known() {
|
||||
let mut laptop_host = host(16, 48, 36);
|
||||
laptop_host.cpu_physical_cores = 8;
|
||||
assert_eq!(compute(&laptop_host, None, &laptop(), Preset::Workstation).cpu_workers, Some(7), "8c/16t: 12 workers would put 5 of them on SMT siblings");
|
||||
assert_eq!(compute(&host(16, 48, 36), None, &laptop(), Preset::Workstation).cpu_workers, Some(12), "physical cores unknown: unchanged");
|
||||
let mut server_host = host(32, 121, 100);
|
||||
server_host.cpu_physical_cores = 16;
|
||||
assert_eq!(compute(&server_host, Some(&gpu(32607, 32100)), &server(), Preset::Dedicated).cpu_workers, Some(15), "the 16-core server is unchanged");
|
||||
let mut small = host(2, 16, 8);
|
||||
small.cpu_physical_cores = 1;
|
||||
assert_eq!(compute(&small, None, &laptop(), Preset::Dedicated).cpu_workers, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated);
|
||||
|
||||
@@ -10,10 +10,30 @@ use windows_sys::Win32::{
|
||||
UI::WindowsAndMessaging::{SW_HIDE, ShowWindow},
|
||||
System::{
|
||||
Console::{CTRL_BREAK_EVENT, GenerateConsoleCtrlEvent, GetConsoleWindow},
|
||||
SystemInformation::{GetLogicalProcessorInformation, RelationProcessorCore, SYSTEM_LOGICAL_PROCESSOR_INFORMATION},
|
||||
Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION},
|
||||
},
|
||||
};
|
||||
|
||||
/// Physical cores of this machine (SMT siblings counted once), `None` when Windows does not say.
|
||||
pub fn physical_cores() -> Option<u32> {
|
||||
let mut bytes = 0u32;
|
||||
// SAFETY: a size query: a null buffer with a zero length; the call reports the length it needs.
|
||||
unsafe { GetLogicalProcessorInformation(std::ptr::null_mut(), &mut bytes) };
|
||||
let entry = std::mem::size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION>();
|
||||
if bytes == 0 || bytes as usize % entry != 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: an all-zero SYSTEM_LOGICAL_PROCESSOR_INFORMATION is a valid value (integers and a union of integers).
|
||||
let mut buffer: Vec<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> = (0..bytes as usize / entry).map(|_| unsafe { std::mem::zeroed() }).collect();
|
||||
// SAFETY: `buffer` has exactly `bytes` writable bytes.
|
||||
if unsafe { GetLogicalProcessorInformation(buffer.as_mut_ptr(), &mut bytes) } == 0 {
|
||||
return None;
|
||||
}
|
||||
let cores = buffer.iter().filter(|e| e.Relationship == RelationProcessorCore).count() as u32;
|
||||
(cores > 0).then_some(cores)
|
||||
}
|
||||
|
||||
/// `n` bytes from the system-preferred CNG random number generator.
|
||||
pub fn random_bytes(n: usize) -> Result<Vec<u8>, String> {
|
||||
let mut bytes = vec![0u8; n];
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -566,19 +566,26 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
|
||||
if candidate.tail_len != 0 {
|
||||
return Err(Reject::Mismatch);
|
||||
}
|
||||
self.insert(candidate, tokens, state, blocks, None)
|
||||
self.insert(candidate, tokens, state, blocks, None, None)
|
||||
}
|
||||
|
||||
/// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same history that
|
||||
/// end earlier (a token-wise prefix of this one) are superseded: the next request of the session starts from this one.
|
||||
pub fn commit_tail(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B) -> Result<(), Reject> {
|
||||
self.commit_tail_keeping(candidate, tokens, state, blocks, tail, None)
|
||||
}
|
||||
|
||||
/// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a request extends
|
||||
/// the same request's prompt-end checkpoint; when the client resends the history without the reply's reasoning, the next prompt
|
||||
/// shares only the prompt part, so the prompt-end node must survive (the next request's own tails supersede it as usual).
|
||||
pub fn commit_tail_keeping(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B, keep_end: Option<usize>) -> Result<(), Reject> {
|
||||
if candidate.tail_len == 0 {
|
||||
return Err(Reject::Mismatch);
|
||||
}
|
||||
self.insert(candidate, tokens, state, blocks, Some(tail))
|
||||
self.insert(candidate, tokens, state, blocks, Some(tail), keep_end)
|
||||
}
|
||||
|
||||
fn insert(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: Option<B>) -> Result<(), Reject> {
|
||||
fn insert(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: Option<B>, keep_end: Option<usize>) -> Result<(), Reject> {
|
||||
let g = self.cfg.block_tokens;
|
||||
if tokens.len() != candidate.path.len() * g + candidate.tail_len
|
||||
|| blocks.len() != candidate.missing.len()
|
||||
@@ -601,7 +608,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
|
||||
None => return Err(Reject::Mismatch),
|
||||
}
|
||||
}
|
||||
let superseded = if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens) } else { Vec::new() };
|
||||
let superseded = if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() };
|
||||
let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload });
|
||||
let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size());
|
||||
self.node_bytes += bytes;
|
||||
@@ -633,7 +640,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
|
||||
}
|
||||
|
||||
/// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues).
|
||||
fn superseded_tails(&self, path: &[u64], tokens: &[i32]) -> Vec<u64> {
|
||||
fn superseded_tails(&self, path: &[u64], tokens: &[i32], keep_end: Option<usize>) -> Vec<u64> {
|
||||
let g = self.cfg.block_tokens;
|
||||
let mut out = Vec::new();
|
||||
for (j, parent) in path.iter().enumerate() {
|
||||
@@ -641,7 +648,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
|
||||
for key in self.tails.get(parent).into_iter().flatten() {
|
||||
let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue };
|
||||
let end = start + tail.tokens.len();
|
||||
if end < tokens.len() && tokens[start..end] == *tail.tokens {
|
||||
if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens {
|
||||
out.push(*key);
|
||||
}
|
||||
}
|
||||
@@ -882,6 +889,40 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a tail node that leaves the tail ending at `keep` standing (the decode-end checkpoint of a request).
|
||||
fn put_tail_keeping(s: &mut PrefixStore<Payload, Payload>, t: &[i32], len: usize, keep: usize) {
|
||||
let prefix = &t[..len];
|
||||
match s.consider_tail(prefix, true, STATE, BLOCK) {
|
||||
Consider::Admit(c) => {
|
||||
let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect();
|
||||
s.commit_tail_keeping(c, prefix, Payload(STATE), blocks_in, Payload(BLOCK / 2), Some(keep)).unwrap();
|
||||
s.check_invariants();
|
||||
}
|
||||
other => panic!("not admitted: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_end_checkpoint_survives_the_decode_end_checkpoint_of_its_request() {
|
||||
let mut s = store(100_000);
|
||||
let a = tokens(1, 2, 8);
|
||||
put(&mut s, &a, 3, true);
|
||||
// the prompt ended 5 tokens after the third grid point, the decode added 4 more
|
||||
assert_eq!(put_tail(&mut s, &a, 3 * G + 5), Consider::Exists);
|
||||
let before = s.node_count();
|
||||
put_tail_keeping(&mut s, &a, 3 * G + 9, 3 * G + 5);
|
||||
assert_eq!(s.node_count(), before + 1, "the decode end is added and the prompt end stays");
|
||||
// the next prompt resends the prompt but not the reply: it continues from the prompt end
|
||||
let mut next = a[..3 * G + 5].to_vec();
|
||||
next.extend_from_slice(&[900, 901, 902]);
|
||||
let m = s.longest_match(&next, next.len()).unwrap();
|
||||
assert_eq!(m.tokens, 3 * G + 5);
|
||||
// the next request's own prompt-end checkpoint supersedes the earlier prompt end as before
|
||||
assert_eq!(put_tail(&mut s, &next, 3 * G + 7), Consider::Exists);
|
||||
let m = s.longest_match(&next, next.len()).unwrap();
|
||||
assert_eq!(m.tokens, 3 * G + 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_checkpoint_between_two_grid_points_is_matched_exactly_and_supersedes_the_one_before_it() {
|
||||
let mut s = store(100_000);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -464,7 +464,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
return Ok(ChunkOutcome::Nothing);
|
||||
}
|
||||
let end = prompt.len().saturating_sub(1);
|
||||
self.admit_tail(device, &prompt[..end])
|
||||
self.admit_tail(device, &prompt[..end], None)
|
||||
}
|
||||
|
||||
/// The end of the decode: the session stands at `consumed.len()` (the prompt and the committed reply), settled, with the draft
|
||||
@@ -473,7 +473,10 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
if self.cfg.tail != TailMode::Reply || self.bypass || self.req.is_none() {
|
||||
return Ok(ChunkOutcome::Nothing);
|
||||
}
|
||||
let outcome = self.admit_tail(device, consumed)?;
|
||||
// the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning of the reply
|
||||
// continues from the prompt, not from the decode end
|
||||
let keep = self.req.as_ref().map(|r| r.limit);
|
||||
let outcome = self.admit_tail(device, consumed, keep)?;
|
||||
if matches!(outcome, ChunkOutcome::Admitted { .. } | ChunkOutcome::Exists) {
|
||||
// the buffer holds exactly these cells, and the node has a copy of them
|
||||
self.live.clear();
|
||||
@@ -482,7 +485,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn admit_tail<D: PrefixDevice<State = S, Block = B>>(&mut self, device: &mut D, tokens: &[i32]) -> Result<ChunkOutcome, Error> {
|
||||
fn admit_tail<D: PrefixDevice<State = S, Block = B>>(&mut self, device: &mut D, tokens: &[i32], keep_end: Option<usize>) -> Result<ChunkOutcome, Error> {
|
||||
let g = self.block_tokens;
|
||||
// a grid point is a pure checkpoint of its own (and a node below one block has no blocks to hang on)
|
||||
if tokens.len() <= g || tokens.len() % g == 0 || device.position()? != tokens.len() as u64 {
|
||||
@@ -519,7 +522,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
let new_blocks = blocks.len();
|
||||
let bytes = state.byte_size() + tail.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::<usize>();
|
||||
let park_ms = started.elapsed().as_secs_f64() * 1e3;
|
||||
self.store.commit_tail(candidate, tokens, state, blocks, tail).map_err(|_| Error::IdentityMismatch)?;
|
||||
self.store.commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end).map_err(|_| Error::IdentityMismatch)?;
|
||||
self.park_ms_request += park_ms;
|
||||
self.admitted_request += 1;
|
||||
Ok(ChunkOutcome::Admitted { tokens: tokens.len(), new_blocks, bytes, park_ms })
|
||||
|
||||
@@ -484,6 +484,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
};
|
||||
let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) };
|
||||
let residency = ResidencyState::new(&config.expert_tier);
|
||||
report_kernel_selection();
|
||||
vram_note(context, "before expert tier");
|
||||
let mut loan = None;
|
||||
let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?);
|
||||
@@ -1567,6 +1568,17 @@ pub(crate) fn dbg_el() -> f32 {
|
||||
DBG_T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f32()
|
||||
}
|
||||
|
||||
/// One operator line per CPU kind and per CUDA device: which kernel family the process runs on each (logging only).
|
||||
fn report_kernel_selection() {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
for line in leleka_native_cpu_expert::cpu_kernel_report() {
|
||||
operator_note(&line);
|
||||
}
|
||||
for line in leleka_cuda_driver::gpu_kernel_report() {
|
||||
operator_note(&line);
|
||||
}
|
||||
}
|
||||
|
||||
fn operator_note(text: &str) {
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr().lock(), "leleka-serve {text}");
|
||||
|
||||
@@ -12,7 +12,7 @@ path = "src/lib.rs"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
libc = "=0.2.190"
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_SystemInformation", "Win32_Security", "Win32_Storage_FileSystem"] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_Security", "Win32_Storage_FileSystem"] }
|
||||
|
||||
# Unsafe is the point of this crate: every block carries a SAFETY comment.
|
||||
[lints.rust]
|
||||
|
||||
@@ -225,6 +225,38 @@ pub fn physical_memory() -> Option<(u64, u64)> {
|
||||
Some((status.ullTotalPhys, status.ullAvailPhys))
|
||||
}
|
||||
|
||||
/// A new handle on the same file with its own file object (`ReOpenFile`, read access, shared with readers): positional reads through
|
||||
/// two such handles run in parallel, while two `try_clone`s of one synchronous handle share one file object and the I/O manager runs
|
||||
/// their requests one at a time, whatever the thread count.
|
||||
pub fn reopen_file_read(file: &std::fs::File) -> std::io::Result<std::fs::File> {
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle};
|
||||
use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, ReOpenFile};
|
||||
// SAFETY: the raw handle belongs to `file`, which outlives the call; ReOpenFile returns a new handle (or INVALID_HANDLE_VALUE).
|
||||
let handle = unsafe { ReOpenFile(file.as_raw_handle().cast(), GENERIC_READ, FILE_SHARE_READ, 0) };
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: `handle` is a valid, owned file handle that nothing else closes.
|
||||
Ok(unsafe { std::fs::File::from_raw_handle(handle.cast()) })
|
||||
}
|
||||
|
||||
/// Memory priority of the calling thread (1 very low .. 5 normal, the default): the standby-list priority the file pages it faults in
|
||||
/// get, which decides what the memory manager repurposes first when it needs RAM. `false` when the call is refused.
|
||||
pub fn set_thread_memory_priority(priority: u32) -> bool {
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentThread, MEMORY_PRIORITY_INFORMATION, SetThreadInformation, ThreadMemoryPriority};
|
||||
let info = MEMORY_PRIORITY_INFORMATION { MemoryPriority: priority };
|
||||
// SAFETY: the current-thread pseudo handle and a live MEMORY_PRIORITY_INFORMATION of exactly the size passed.
|
||||
unsafe {
|
||||
SetThreadInformation(
|
||||
GetCurrentThread(),
|
||||
ThreadMemoryPriority,
|
||||
std::ptr::from_ref(&info).cast(),
|
||||
std::mem::size_of::<MEMORY_PRIORITY_INFORMATION>() as u32,
|
||||
) != 0
|
||||
}
|
||||
}
|
||||
|
||||
pub const PTHREAD_STACK_MIN: usize = 16384;
|
||||
|
||||
pub const MADV_WILLNEED: c_int = 3;
|
||||
|
||||
+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> {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, no behaviour).
|
||||
//!
|
||||
//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every logical CPU the
|
||||
//! process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a machine with several packages or
|
||||
//! with unlike cores shows each kind on its own line, and a core that cannot run the chosen family is named.
|
||||
use core::arch::x86_64::{__cpuid, __cpuid_count, _xgetbv};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Core {
|
||||
brand: String,
|
||||
avx2: bool,
|
||||
avx512: [bool; 6],
|
||||
}
|
||||
|
||||
const AVX512_NAMES: [&str; 6] = ["F", "BW", "VL", "DQ", "VBMI", "VNNI"];
|
||||
|
||||
/// The features of the core the calling thread runs on. The gates mirror `rust_simd::probe_avx2` / `probe_avx512`.
|
||||
fn probe() -> Core {
|
||||
// SAFETY: CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen.
|
||||
unsafe {
|
||||
let max = __cpuid(0).eax;
|
||||
let ext = __cpuid(0x8000_0000).eax;
|
||||
let mut brand = String::new();
|
||||
if ext >= 0x8000_0004 {
|
||||
let mut raw = Vec::with_capacity(48);
|
||||
for leaf in 0x8000_0002..=0x8000_0004u32 {
|
||||
let r = __cpuid(leaf);
|
||||
for w in [r.eax, r.ebx, r.ecx, r.edx] {
|
||||
raw.extend_from_slice(&w.to_le_bytes());
|
||||
}
|
||||
}
|
||||
brand = String::from_utf8_lossy(&raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned();
|
||||
}
|
||||
if max < 7 {
|
||||
return Core { brand, avx2: false, avx512: [false; 6] };
|
||||
}
|
||||
let c1 = __cpuid(1).ecx;
|
||||
let osxsave = c1 & (1 << 27) != 0;
|
||||
let xcr0 = if osxsave { _xgetbv(0) } else { 0 };
|
||||
let l7 = __cpuid_count(7, 0);
|
||||
let avx2 = [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7.ebx & (1 << 5) != 0;
|
||||
let os512 = osxsave && xcr0 & 0xe6 == 0xe6;
|
||||
let bits = [l7.ebx & (1 << 16) != 0, l7.ebx & (1 << 30) != 0, l7.ebx & (1 << 31) != 0, l7.ebx & (1 << 17) != 0, l7.ecx & (1 << 1) != 0, l7.ecx & (1 << 11) != 0];
|
||||
Core { brand, avx2, avx512: bits.map(|b| b && os512) }
|
||||
}
|
||||
}
|
||||
|
||||
fn avx512_complete(c: &Core) -> bool {
|
||||
c.avx512.iter().all(|b| *b)
|
||||
}
|
||||
|
||||
/// `0-7,12` style list of CPU indexes.
|
||||
fn ranges(cpus: &[usize]) -> String {
|
||||
let mut out = String::new();
|
||||
let mut i = 0;
|
||||
while i < cpus.len() {
|
||||
let mut j = i;
|
||||
while j + 1 < cpus.len() && cpus[j + 1] == cpus[j] + 1 {
|
||||
j += 1;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push(',');
|
||||
}
|
||||
out.push_str(&if i == j { cpus[i].to_string() } else { format!("{}-{}", cpus[i], cpus[j]) });
|
||||
i = j + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that changed it.
|
||||
pub fn cpu_kernel_report() -> Vec<String> {
|
||||
let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256);
|
||||
let mut groups: Vec<(Core, Vec<usize>)> = Vec::new();
|
||||
for cpu in 0..n {
|
||||
// a pinned probe thread per logical CPU; a refused pin probes wherever the thread runs (the line then shows that CPU's kind)
|
||||
let core = std::thread::spawn(move || {
|
||||
let previous = crate::rust_topology::pin_current_thread(cpu as i32);
|
||||
let core = probe();
|
||||
crate::rust_topology::restore_thread_affinity(previous);
|
||||
core
|
||||
})
|
||||
.join();
|
||||
let Ok(core) = core else { continue };
|
||||
match groups.iter_mut().find(|(g, _)| *g == core) {
|
||||
Some((_, cpus)) => cpus.push(cpu),
|
||||
None => groups.push((core, vec![cpu])),
|
||||
}
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
for (core, cpus) in &groups {
|
||||
let have: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| *b).map(|(n, _)| *n).collect();
|
||||
let lacks: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| !*b).map(|(n, _)| *n).collect();
|
||||
let avx512 = if lacks.is_empty() {
|
||||
"AVX-512 F/BW/VL/DQ/VBMI/VNNI: all".to_owned()
|
||||
} else if have.is_empty() {
|
||||
"AVX-512: none".to_owned()
|
||||
} else {
|
||||
format!("AVX-512: has {}, lacks {}", have.join("/"), lacks.join("/"))
|
||||
};
|
||||
lines.push(format!(
|
||||
"cpu: logical {} ({}): {}; AVX2/FMA/F16C: {}; {}; kernel family on this core: {}",
|
||||
ranges(cpus),
|
||||
cpus.len(),
|
||||
if core.brand.is_empty() { "unknown model" } else { &core.brand },
|
||||
if core.avx2 { "yes" } else { "no" },
|
||||
avx512,
|
||||
if avx512_complete(core) { "AVX-512" } else if core.avx2 { "AVX2" } else { "none (unsupported)" }
|
||||
));
|
||||
}
|
||||
let dispatch = crate::rust_simd::dispatch();
|
||||
let mut switches = Vec::new();
|
||||
for name in ["STRATA_FORCE_AVX2", "STRATA_NO_IQ512", "STRATA_NO_IQ256", "STRATA_NO_IQ4NL"] {
|
||||
if std::env::var_os(name).is_some() {
|
||||
switches.push(name);
|
||||
}
|
||||
}
|
||||
lines.push(format!(
|
||||
"cpu: process kernel family {} (IQ rows: 512-bit {}, 256-bit {}; IQ4_NL {}){}",
|
||||
if dispatch.avx512 { "AVX-512" } else { "AVX2" },
|
||||
if dispatch.iq512 { "on" } else { "off" },
|
||||
if dispatch.iq256 { "on" } else { "off" },
|
||||
if dispatch.iq4nl { "on" } else { "off" },
|
||||
if switches.is_empty() { String::new() } else { format!("; overridden by {}", switches.join(", ")) }
|
||||
));
|
||||
if groups.len() > 1 && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) {
|
||||
lines.push("cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; a worker pinned to a core without it would fault or be refused".to_owned());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn the_report_names_every_logical_cpu_once_and_the_process_family() {
|
||||
let lines = super::cpu_kernel_report();
|
||||
eprintln!("{}", lines.join("\n"));
|
||||
assert!(lines.iter().any(|l| l.starts_with("cpu: logical ")));
|
||||
assert!(lines.iter().any(|l| l.starts_with("cpu: process kernel family ")));
|
||||
let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256);
|
||||
let counted: usize = lines
|
||||
.iter()
|
||||
.filter(|l| l.starts_with("cpu: logical "))
|
||||
.map(|l| l.split(['(', ')']).nth(1).and_then(|c| c.parse::<usize>().ok()).unwrap_or(0))
|
||||
.sum();
|
||||
assert_eq!(counted, n, "every probed logical CPU is in exactly one group");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ mod rust_types;
|
||||
#[allow(unsafe_code)]
|
||||
mod rust_simd;
|
||||
#[allow(unsafe_code)]
|
||||
mod cpu_report;
|
||||
pub use cpu_report::cpu_kernel_report;
|
||||
#[allow(unsafe_code)]
|
||||
mod rust_quant;
|
||||
#[allow(unsafe_code)]
|
||||
mod rust_iq;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# Laptop (RTX 3080 16 GB, native Windows): Leleka against vanilla Strata on the 256k agent session
|
||||
|
||||
Branch `claude/laptop-vs-vanilla`, started 2026-10-27 from `main` (3bedec6). Machine: RTX 3080 Laptop 16 GB (driver 617.42), i9-11900H (8 cores / 16 threads, AVX-512, no AVX-VNNI),
|
||||
47.7 GB RAM, Samsung PM9A1 NVMe, Windows 11, WSL shut down for every run. Model Qwen3.8-Flash-Next IQ3_S (the pinned pack, digest `sha256:80d5e333...66a3`).
|
||||
|
||||
Owner's rule: on large-context work our end-to-end speed has to be better than vanilla Strata on the same machine, a 1 % gain counts. The measure is the 5-turn
|
||||
long session (`scripts/e2e/long_session.py --turns 5 --target-tokens 245000 --max-output 300 --context 262144`, source snapshot
|
||||
`C:\Users\pavel\work\wsrun\src-snap\crates`, turn 1 = 45,766 input tokens), nothing shorter.
|
||||
|
||||
## 1. The reference: what vanilla does on this laptop (engine log `wsrun\vanilla\engine-vanilla.log`, `engine/strata` sources, release 0.2.6 / engine 0.1.50)
|
||||
|
||||
| | vanilla Strata | ours before this work (`workstation`, dist build `c40531f`) |
|
||||
| --- | --- | --- |
|
||||
| TTFT per turn (s) | 230 / 260 / 279 / 236 / 243 | 432 / 490 / 707 / 514 / 360 (run 1), 449 / 528 / 743 / 611 / - (run 4) |
|
||||
| prefill tok/s on the tokens actually read | 199.5 / 192.6 / 191.3 / 199.3 / 187.8 | 105-115 |
|
||||
| decode tok/s | 15.8 / 17.5 / 16.1 / 15.0 / 17.1 | 5.9-7.5 |
|
||||
| total wall of the session | 1,341 s | about 2,500 s |
|
||||
| prompt chunk | 8192 (ring 96 slots; the prompt path borrows 1,781 of 2,661 cache slots, 3.41 GiB) | 2048 (borrows 1,154 of 2,234 slots) |
|
||||
| VRAM left for the desktop | 459 MiB free (it warns, and runs) | 2.8 GiB (`workstation`: budget 13 GiB of 16) |
|
||||
| expert cache | 2,661 slots (5.10 GiB), profile fill, adaptive | 2,234 slots (4.29 GiB), same profile (identical file, sha256 `8f59b4aa...`) |
|
||||
| CPU pool | 7 workers pinned to logical processors 2,4,...,14 (one per physical core), host thread on 0, 24 tasks per phase | 12 workers (the preset counts logical cores), 7 pinned, 5 spinning unpinned |
|
||||
| PCIe share | `pcie_frac` auto-balanced 0.20 -> 0.40 -> 0.30 -> 0.35 from the measured CPU-pool speed | 0 (pageable bank) |
|
||||
| route tail skip | **ON by default (`STRATA_ROUTE_TAIL_SKIP=7`, changes the answer)**: 25-30 % of the missed experts are never computed | off (experimental, quality gate failed on the 5090) |
|
||||
| exact sm_86 speed switches | 9 on by default (ADAPT_NOWAIT, ADAPT_LAG=2, CPU_IQ_ALL_EXACT1, SIDE_MIXER=2, ATTN_DAILY, GR_UP75, GU_SWIGLU, QSA_ROWS, B6_MMVQ_ROWS) | none (rows 2.1 / 2.2 of the port plan, other agent) |
|
||||
| experts on disk | one packed `experts.bin` (46.8 GB, one blob per expert, layer-major) mapped, file tier 41.7 GiB | the two GGUF shards mapped, gate/up/down of an expert in three different tensors |
|
||||
| PLE rows | direct (unbuffered, overlapped) reads, 146k rows/s probe, on a worker thread | KAR level-2 PLE: three positional reads of random 4 KiB pages per row, on the prompt's critical path |
|
||||
|
||||
Vanilla's decode is 107 ms per speculation round (300 tokens = 177 rounds, 123 of 227 drafts accepted); ours is 240 ms for the same 1.7 tokens per round.
|
||||
|
||||
## 2. Where the time goes (ours, measured with the engine's own `PREFILL-PROFILE` lines)
|
||||
|
||||
One 2048-token chunk at the old setting (job ab2, 18.9 s): `moe` 14.5 s of which `moe.ring` (the expert stream) 11.8 s, `input` 2.5-5.0 s (all of it `input.ple`),
|
||||
`gdn` 1.1 s, `qsa` 0.5-0.6 s. At 6144 tokens (33 s, steady state): `input.ple` 10.3 s, `moe` 15.6 s (`ring` 14.3), `gdn` 3.8 s, `qsa` 2-2.9 s.
|
||||
|
||||
* PLE: 16 rows per token, derived from the token and the two before it (n-gram hash), almost never in the 64 MiB device cache; each row is three random 4 KiB reads in the KAR archive. The reads are
|
||||
latency-bound, 20-45 k per second, and happen before the chunk starts. That is 13-26 % of every 2048-token chunk and 31 % of a 6144-token one.
|
||||
* MoE ring: every expert the GPU does not hold streams once per chunk, from the page cache or the NVMe. The cost per chunk is nearly constant (11.8 s at 2048 tokens, 14.3 s at 6144), so
|
||||
a bigger chunk divides it.
|
||||
|
||||
## 3. Gaps, ranked by expected gain on the 256k session (about 85 % of a turn is prefill)
|
||||
|
||||
|
||||
| # | Gap | Evidence | Explains | State |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 1 | **Prompt chunk 2048 against 8192.** The prefix grid (`block_tokens`) caps every chunk, and 8192 needs a loan of about 2,450 cache slots while the `workstation` preset (13 GiB budget) leaves 2,234. | `PREFILL-PROFILE`: 108-113 tok/s at 2048, 185-197 at 6144 (same machine, same session). `reconfigure --prefill-capacity 8192` is refused (`original_prefill_arena: InputAllocation`); 6144 borrows 2,016 of 2,234 slots, 4096 borrows 1,585, 3072 1,369, 2048 1,154. | prefill 110 -> 176 tok/s | **done by configuration**: `leleka reconfigure --prefill-capacity 6144 --prefix-cache-block 6144`. It changes the chunk-order rounding, so it is not a default (section 5). 8192 needs about 0.6 GiB more VRAM (`--gpu-budget-gib 14`, not tried) |
|
||||
| 2 | **PLE rows on the prompt's critical path.** 16 rows per token, 3 random 4 KiB reads each, read before every chunk through clones of ONE synchronous handle: the I/O manager runs the requests of one file object one at a time, so 32 threads gave a queue depth of 1 (100 k reads in 10 s). | `input.ple` was 5-12 s of every 6144-token chunk (31 %), 39-77 s per turn. After the change (own file objects through `ReOpenFile`, and the next chunk's rows read on a thread while the chunk computes) it is 0.47-0.9 s per chunk (run d, GPU power-capped). Decode paid 8-10 ms per window for it (`window.ple`, 48 sequential reads per token). | prefill, about 25 % of a chunk | **done** (`ee4cb59`, `3461b86`), default on for Windows |
|
||||
| 3 | **CPU pool: 12 workers on 8 cores** (the preset counts logical processors); 5 spin unpinned and take cycles from the pinned ones. Vanilla: 7, pinned one per physical core. | decode 7.98 / 7.75 tok/s (7 workers, run c turns 1-2) against 7.57 / 6.58 (12 workers, run b): +5 to +18 %, two turns, not a clean A/B (run c also had the PLE read-ahead). | decode, about 10 % | **done** (`449b7a1`): 7 on this laptop, 15 on the 16-core server |
|
||||
| 4 | **Decode is dominated by the CPU misses' page-in, not by their compute.** Per 2-row window (BRINGUP_TRACE): 216 distinct experts, `fetch` (`will_need` on 3 ranges each, then a touching phase) 58.7 ms, compute `join` 35 ms, of 117 ms in the verifier. `cpu.open` is 2.2 ms per layer against 1.3 ms of compute. | run c profile: round 203 ms = GPU chain about 106 ms + `pool.cpu` 3.6 ms x 48 (open 2.2, compute 1.3). Vanilla's 107 ms round has 25-30 % of the misses removed by its default route tail skip. | decode 2.2x | open. Candidates: skip the prefetch pass when the pages are resident, more RAM for the page cache (pinned 8 GiB + about 10 GiB standby against vanilla's 27.5 GiB), `PcieAuto` |
|
||||
| 5 | **Route tail skip is ON by default in vanilla** (`STRATA_ROUTE_TAIL_SKIP=7`): 25-30 % of the missed experts are never computed and the answer differs. Ours stays off (quality gate failed: p99 d_top1 1.005 against a limit of 0.499). | engine-vanilla.log: 25,065 missed experts skipped in turn 1 (168,623 lookups). | part of decode | **not taken**. The fair decode comparison is vanilla with `STRATA_ROUTE_TAIL_SKIP=0`, not yet run |
|
||||
| 6 | Page cache churn of the expert scan: every chunk reads all experts the GPU does not hold (about 37 GiB), layer 0 to 47, through about 10 GiB of cache, so a cyclic LRU scan finds nothing again. | `wsrun-lvv\iobench.ps1`: a cyclic scan of 12 GiB through about 7 GiB of cache took 3.0-3.7 s per pass; with the first half read at memory priority 1 and the second at 5, 0.8 s per pass. | `moe.ring` (14.3 s of 33 s per chunk) | implemented, **opt-in** `LELEKA_STAGE_PRIORITY=on` (`73c67a6`). Run d had it on, but the GPU was capped, so its effect is not measured |
|
||||
| 7 | VRAM left to the desktop: 2.8 GiB (`workstation`) against 459 MiB (vanilla). Cache 2,234 against 2,661 slots. The dGPU shows 0 MiB in use at idle on this Optimus laptop. | engine logs | decode hit rate, the 8192 loan | owner's policy; `--gpu-budget-gib 14` is the knob |
|
||||
| 8 | Experts in one packed layer-major file (vanilla) against three tensors per expert in the GGUF. | disk microbench: page-fault touch with 32 threads reaches 4.2 GB/s on 640 KiB pieces, the same as `PrefetchVirtualMemory` first (4.3) and unbuffered 8 MiB reads (4.9); the ring runs at about 3 GB/s | none measured | not pursued |
|
||||
|
||||
Which gap explains what: **prefill 110 against 199 tok/s** is gap 1 (chunk 2048, about three quarters of it) and gap 2 (PLE, a quarter); **decode 6.5-7.5 against 15-17.6** is mostly gap 4 plus gap 5 (the lossy default), with gap 3 and the sm_86 kernel switches (port plan rows 2.1 / 2.2) behind them.
|
||||
|
||||
## 4. Measurements (5-turn 245k session, `workstation`, native, WSL off)
|
||||
|
||||
Prefill tok/s is tokens read (input minus reused) over the sum of the chunk times in the engine's `PREFILL-PROFILE` lines.
|
||||
|
||||
| run | build / settings | TTFT per turn (s) | decode tok/s | wall (s) |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| vanilla 0.2.6 | defaults (tail skip on) | 230 / 260 / 279 / 236 / 243 | 15.8 / 17.5 / 16.1 / 15.0 / 17.1 | 1,341 |
|
||||
| ours before | `c40531f`, chunk 2048, tail reply | 432-449 / 490-528 / 707-743 / 514-611 / 360 | 5.9-7.5 | about 2,500 |
|
||||
| b | same build, `reconfigure` to chunk 6144 / grid 6144 / tail prompt | 262.6 / 291.8 / 301.2 / 276.7 / 286.3 (sum 1,419) | 7.57 / 6.58 / 7.38 / 7.40 / 8.41 | 1,621 |
|
||||
| c | + PLE read-ahead (shared handle), 7 workers | 244.4 / 277.4 / - | 7.98 / 7.75 | stopped after turn 2 |
|
||||
| d | + own file objects, stage priority on | not a valid run (GPU at a 30 W cap) | - | - |
|
||||
| **A** | `2cb26cc` (= the above + tail-keep `85fd803`), chunk 6144 / grid 6144 / tail prompt, PLE read-ahead on own file objects, 7 workers, stage priority off; 2026-10-27 21:14, AC, P0, max 71 C, max 131 W | **173.7 / 203.8 / 208.4 / 195.9 / 216.5 (sum 998)** | 6.85 / 6.40 / 6.65 / 6.94 / 6.14 | **1,226** (217 / 251 / 254 / 239 / 265) |
|
||||
|
||||
Run A against vanilla: TTFT sum 998 s against 1,248 s (-20 %, every turn faster: 174 / 204 / 208 / 196 / 217 against 230 / 260 / 279 / 236 / 243); total wall 1,226 s against 1,341 s (**-8.6 %**), against 1,621 s for run b and about 2,500 s before this work. Prefill 285 / 260 / 269 / 253 / 222 tok/s on the tokens read (vanilla 199 / 193 / 191 / 199 / 188); `input.ple` 1 s per turn (b: 39-77 s). `cached_tokens` 0 / 45,761 / 95,950 / 149,371 / 196,388 (vanilla reuses 45,761 / 95,828 / 149,192 / 196,189): exact reuse, 45,766 / 50,194 / 53,426 / 47,022 / 45,552 tokens read per turn (vanilla 45,766 / 50,072 / 53,369 / 47,002 / 45,541). **Decode is still 2.4x slower than vanilla** (6.1-6.9 against 15-17.6 tok/s: 45 s against 18 s per 300 tokens, 225 s against 92 s over the session), so ours is ahead by 250 s in prefill and behind by 133 s in decode. The expert tier in the decode windows is 46-48 % VRAM / 52-54 % CPU, 178-210 rounds per 300 tokens (vanilla 177). One run; no repetition yet, and the GPU was in a different state from run b (70-130 W against 40-90 W), so part of the b-to-A step is the machine, not the code (`gdn` and `qsa` per turn are also 2x shorter than in b).
|
||||
|
||||
Run b: prefill 182 / 176 / 183 / 175 / 164 tok/s (vanilla 199 / 193 / 191 / 199 / 188), `input.ple` 75 / 77 / 60 / 47 / 39 s per turn, `moe.ring` 114-132 s, `qsa` 18 -> 82 s from 46k to 240k tokens. The prompt-end checkpoint (`tail prompt`) reuses 45,761 of 45,766 tokens; the old setting re-read about 1.7k tokens per turn.
|
||||
|
||||
**Run d was stopped by the guard at 20:18 and is not a measurement.** The GPU sat at P5, 285-1545 MHz and 25-47 W with `SW Power Cap` and `SW Thermal Slowdown` active at a 30 W power limit (default 115 W), at 52-55 C, while Windows reports the battery as discharging with the power plan on Turbo. The earlier runs drew 70-90 W. Under that cap the same chunks took 47 s instead of 30 s (`gdn` 10.3 s against 3.8, `moe.ring` 24 s against 13), so no comparison with vanilla is valid. The 30 W profile is also the one that blue-screened this laptop (0x19C), so no further GPU run was started. The machine has to be back in its full-power state (charger, OEM performance mode) before the next run.
|
||||
|
||||
## 5. Quality
|
||||
|
||||
* PLE read-ahead and own file objects: non-lossy. A packet is a function of the archive bytes; `LELEKA_PLE_AHEAD_VERIFY=1` compares every packet taken from the read-ahead with a direct read: 605,716 rows (run c, shared handle) and 754,127 rows (run d, own file objects), 0 mismatches. The device sees the same bytes, so the tensors are bit-identical by construction.
|
||||
* CPU workers 7 and the stage priority change no value (thread count; which pages stay cached).
|
||||
* **Chunk 6144 changes the rounding order of the prompt path** (docs/prefill-throughput.md: 16,000 tokens answered identically at 2048, 4096 and 6144 and differently at 8192 on one prompt). It stays an explicit setting and is not the default until `scripts/quality/q_pair.py` (or the `LELEKA_TRACE_PREFILL_R` residual hashes) has been run with 2048 / 6144 arms and a control. Not run.
|
||||
* Run A's settings (chunk 6144, tail prompt) were not checked with q_pair or greedy-id equality: the reply hashes of two runs of the same prompt already differ (turn 1: `e3b0...` empty in runs b-d, `0230c278...` in run A, because the reasoning-only reply varies), the port is not bit-deterministic between processes, and the harness needs a capture that is not on this laptop. The tail mode only moves where a checkpoint is taken (the state after a chunk is a function of the tokens before it), the chunk size changes rounding.
|
||||
* Route tail skip stays off.
|
||||
|
||||
## 6. Not verified / next
|
||||
|
||||
* A paired full run of the final build against vanilla (blocked by the power state); the effect of `LELEKA_STAGE_PRIORITY`; 8192 with `--gpu-budget-gib 14`.
|
||||
* Vanilla with `STRATA_ROUTE_TAIL_SKIP=0` for an exact-for-exact decode comparison.
|
||||
* Next gap: gap 4 (decode page-in: the `will_need` pass, and the working-set trims the governor does every 13 s at the 8 GiB soft floor), then `PcieAuto`.
|
||||
Reference in New Issue
Block a user