merge: claude/laptop-profile (RTX 3080 laptop: mapped experts instead of a 50 GB RAM copy, KAR read-only file source, resident RAM budget, regenerated sm_86 resolver image, paired bench harness, docs/laptop-profile.md)

Laptop numbers (indicative, 3 prompts x 2): Original decode 8.15 tok/s / TTFT 7.2 s (KAR PLE), port 2.70 tok/s / 28.4 s;
both bottlenecks (serial CPU expert preparation, prompt-path expert copies) are being fixed on claude/pool-zero-copy and
claude/prefill-throughput. model-format now denies (instead of forbids) unsafe code for one audited mmap owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 13:10:56 +02:00
co-authored by Claude Opus 5.5
24 changed files with 1743 additions and 560 deletions
Generated
+1
View File
@@ -1036,6 +1036,7 @@ dependencies = [
name = "leleka-model-format"
version = "0.1.0"
dependencies = [
"rustix",
"sha2",
]
+4
View File
@@ -0,0 +1,4 @@
# Laptop profile paired prompts (docs/laptop-profile.md): one user turn per line, thinking off, 128 new tokens.
Write a Python function that converts an ISO-8601 duration string such as P3DT4H12M5S into a total number of seconds. Reject years and months with a clear ValueError, validate the whole input with one regular expression, and add three short doctest examples. After the code, explain in two sentences which edge cases you considered and why.
Explain to a junior engineer how a write-ahead log makes a database safe against crashes. Cover what is written before the data pages change, how recovery replays or discards log records after a power loss, why the order of fsync calls matters, and one common performance trade-off. Use a short numbered list followed by a one-paragraph summary.
You are reviewing a pull request that changes a Rust HTTP server to stream responses as server-sent events. List the five most important things to check for correctness, including client cancellation, backpressure, errors that happen after the first byte was sent, and the terminal event. For each item, describe one concrete test you would write.
+5 -5
View File
@@ -1624,7 +1624,7 @@
"ptxas": "ok",
"recipe": "precise",
"recipe_confidence": "entries+flag-mode",
"retarget_rejected": "ptxas /home/para/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 34613; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas /home/para/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 36077; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas fatal : Ptx assembly aborted due to errors",
"retarget_rejected": "ptxas /home/para/laptop/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 34613; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas /home/para/laptop/sm86-work/build/mtp_original_prefill_quant.sm86.ptx, line 36077; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas fatal : Ptx assembly aborted due to errors",
"rules": [],
"sm120_bytes": 1343875,
"sm120_nvcc": "13.0.88",
@@ -2494,13 +2494,13 @@
"count": 1
}
],
"sm120_bytes": 23782,
"sm120_bytes": 23915,
"sm120_nvcc": "13.2.86",
"sm120_path": "crates/cuda-driver/src/qsa_prompt_resolver.ptx",
"sm120_sha256": "748a2e0d5fcd12a9d49a20fa1556190b22b0630680c7a4ef398d901f47f471b3",
"sm120_sha256": "8d3ecbaecbf28445ba64485bdff3d91a21d87b85d5939a0152ef2f2414480e22",
"sm120_stored_nul": true,
"sm86_bytes": 23781,
"sm86_sha256": "2447167293973383cb42afd73fc280b14f679bae30ad84764ed74bd07d2a6ca8"
"sm86_bytes": 23914,
"sm86_sha256": "32d96ca6a72f40eda21d51d9f4d4d377c373c63783cc422910883bb8d8d8b08d"
},
{
"entries": 5,
File diff suppressed because it is too large Load Diff
+19
View File
@@ -295,6 +295,19 @@ mod enabled {
(self.inner.unregister)(bytes.as_ptr().cast_mut().cast())
})
}
/// Page-lock `len` bytes at page-aligned `start`, inside a read-only file mapping a bank retains
/// (CU_MEMHOSTREGISTER_READ_ONLY = 8; no device mapping): the pages are read in and stay resident, and
/// copies from them are DMA instead of staged.
pub(crate) fn register_read_only(&self, start: usize, len: usize) -> Result<()> {
// SAFETY: the caller passes a page range inside a live mapping it retains until `unregister_at`.
check("cuMemHostRegister_v2", unsafe {
(self.inner.register)(start as *mut c_void, len, 8)
})
}
pub(crate) fn unregister_at(&self, start: usize) -> Result<()> {
// SAFETY: identical live registered base from `register_read_only`; all consumers drained.
check("cuMemHostUnregister", unsafe { (self.inner.unregister)(start as *mut c_void) })
}
pub(crate) fn copy_kernel(
&self,
actual: &mut MappedCopyArguments,
@@ -461,6 +474,12 @@ impl MappedApi {
pub(crate) fn unregister_bank(&self, _: &[u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn register_read_only(&self, _: usize, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn unregister_at(&self, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_kernel(&self, _: &mut MappedCopyArguments, _: Stream) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
+168 -6
View File
@@ -21,6 +21,16 @@ pub struct MappedExpertBank<'ctx> {
api: Option<api::MappedApi>,
page_charge: usize,
closed: bool,
/// The low-RAM source: the banks are read-only shared mappings of the GGUF file
/// (`ResidentExpertBankLease::file_mapped`). They are NOT page-locked (that would read and lock the whole
/// 50 GB file in RAM); every consumer copies from pageable memory (`cache_source` + `cuMemcpyHtoDAsync`,
/// which the driver stages), and the zero-copy device aliases (`retained_span_handle`, `copy_triplet`)
/// are refused. This is the Original's `--mmap-experts` without `--resident-cpu-experts`: unpinned
/// experts are copied, the OS file cache keeps the hot ones.
pageable: bool,
/// The low-RAM RAM budget (`pin_resident`, the Original's `--resident-budget-gib`): page-aligned ranges of
/// the file mappings that are page-locked read-only, hottest experts first. Unregistered at close.
resident: std::cell::RefCell<Vec<(usize, usize)>>,
}
impl Context<'_> {
pub fn mapped_expert_bank<'ctx>(
@@ -32,6 +42,10 @@ impl Context<'_> {
return Err(Error::InvalidSize);
}
let page = api::page_size()?;
let pageable = lease.file_mapped();
if members.iter().any(|m| m.file_mapped() != pageable) {
return Err(Error::InvalidSize);
}
let mut ranges = Vec::new();
ranges
.try_reserve_exact(BANKS)
@@ -110,10 +124,15 @@ impl Context<'_> {
api: None,
page_charge: extra,
closed: false,
pageable,
resident: std::cell::RefCell::new(Vec::new()),
};
let guard = self.enter()?;
let operation = (|| {
owner.api = Some(api::MappedApi::load()?);
if owner.pageable {
return Ok(());
}
for bank in &mut owner.banks {
owner
.api
@@ -146,7 +165,7 @@ impl<'ctx> MappedExpertBank<'ctx> {
/// Validate the retained registered owner before the literal queued H2D
/// cache fill. The device alias is deliberately not exported to runtime.
pub(crate) fn cache_source(&self, span: &ResidentExpertBankSpan) -> Result<&[u8]> {
self.alias(span)?;
self.check(span)?;
let layer = match span.role() {
TensorRole::Layer { layer, .. } => layer,
_ => return Err(Error::InvalidSize),
@@ -189,7 +208,149 @@ impl<'ctx> MappedExpertBank<'ctx> {
+ 2 * size_of::<usize>()
+ self.banks.capacity() * size_of::<RegisteredBank>()
}
/// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field).
pub fn pageable(&self) -> bool {
self.pageable
}
/// The low-RAM resident budget (generate.cpp `--resident-budget-gib` / `--resident-experts`,
/// `FileExpertSource::pin_cache_complement`): keep the experts `ranked` (hottest first, the caller leaves out
/// the ones the VRAM cache holds) resident in RAM, page-locked, while their gate/up/down bytes fit
/// `budget_bytes`. The Original copies them into a page-locked arena; here the bank's own file pages are
/// page-locked in place (read-only registration), which reads them in once and keeps them out of the OS's
/// reclaim, and makes their copies DMA. Answers are unchanged: the bytes are the same file pages. Only for
/// a pageable bank, once. Returns (experts held, bytes registered including page rounding).
pub fn pin_resident(&self, ranked: &[(u8, u32)], budget_bytes: u64) -> Result<(usize, u64)> {
if !self.pageable || self.closed || self.context.is_poisoned() {
return Err(Error::UnsupportedQwenOperation);
}
if !self.resident.borrow().is_empty() {
return Err(Error::InvalidSize);
}
let page = api::page_size()?;
let mut ranges: Vec<(usize, usize)> = Vec::new();
let mut used = 0u64;
let mut held = 0usize;
for &(layer, expert) in ranked {
if layer >= 48 || expert >= 512 {
return Err(Error::InvalidSize);
}
let spans: Vec<(usize, usize)> = (0..3)
.map(|role| {
let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes();
let each = bytes.len() / 512;
(bytes.as_ptr() as usize + expert as usize * each, each)
})
.collect();
let need: u64 = spans.iter().map(|&(_, n)| n as u64).sum();
if used + need > budget_bytes {
continue;
}
used += need;
held += 1;
ranges.extend(spans);
}
// page-round each span inside its own mapping, then merge overlapping/adjacent ranges per mapping
let mut rounded: Vec<(usize, usize)> = Vec::new();
for &(start, len) in &ranges {
let bank = self
.banks
.iter()
.map(|b| b.member.bytes())
.find(|b| {
let s = b.as_ptr() as usize;
start >= s && start + len <= s + b.len()
})
.ok_or(Error::InvalidSize)?;
let lo = (bank.as_ptr() as usize) & !(page - 1);
let hi = (bank.as_ptr() as usize + bank.len()).next_multiple_of(page);
let a = (start & !(page - 1)).max(lo);
let b = (start + len).next_multiple_of(page).min(hi);
rounded.push((a, b));
}
rounded.sort_unstable();
let mut merged: Vec<(usize, usize)> = Vec::new();
for (a, b) in rounded {
match merged.last_mut() {
// only merge inside one mapping: distinct mappings are distinct VMAs (never contiguous by
// assumption), so an overlap or touch can only be the same tensor's pages
Some(last) if a <= last.1 && self.same_mapping(last.0, b - 1) => last.1 = last.1.max(b),
_ => merged.push((a, b)),
}
}
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
let mut registered = 0u64;
let mut result = Ok(());
for &(a, b) in &merged {
match api.register_read_only(a, b - a) {
Ok(()) => {
self.resident.borrow_mut().push((a, b - a));
registered += (b - a) as u64;
}
Err(e) => {
result = Err(e);
break;
}
}
}
let result = combine(result, guard.finish());
if let Err(primary) = result {
// leave nothing half-built: the copies still work from pageable memory
let guard = self.context.enter()?;
let mut cleanup = Ok(());
for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) {
cleanup = combine(cleanup, api.unregister_at(start));
}
return combine(Err(primary), combine(cleanup, guard.finish()));
}
Ok((held, registered))
}
fn same_mapping(&self, a: usize, b: usize) -> bool {
let page = api::page_size().unwrap_or(4096);
self.banks.iter().map(|x| x.member.bytes()).any(|x| {
let lo = (x.as_ptr() as usize) & !(page - 1);
let hi = (x.as_ptr() as usize + x.len()).next_multiple_of(page);
a >= lo && b < hi
})
}
/// `bytes` (a `cache_source` slice) cut at every boundary of a `pin_resident` range, as (offset, length)
/// pieces: one H2D copy must not start in registered pages and run into unregistered ones (the driver
/// refuses it with CUDA_ERROR_INVALID_VALUE), so copy sites issue one copy per piece. One piece when nothing
/// is page-locked.
pub(crate) fn copy_pieces(&self, bytes: &[u8]) -> Vec<(usize, usize)> {
let resident = self.resident.borrow();
let start = bytes.as_ptr() as usize;
let end = start + bytes.len();
let mut cuts = vec![start, end];
for &(a, n) in resident.iter() {
for c in [a, a + n] {
if c > start && c < end {
cuts.push(c);
}
}
}
cuts.sort_unstable();
cuts.dedup();
cuts.windows(2).map(|w| (w[0] - start, w[1] - w[0])).collect()
}
/// Bytes page-locked by `pin_resident`.
pub fn resident_bytes(&self) -> u64 {
self.resident.borrow().iter().map(|&(_, n)| n as u64).sum()
}
/// The device alias of a registered span: refused for pageable banks.
fn alias(&self, span: &ResidentExpertBankSpan) -> Result<u64> {
let n = self.check(span)?;
if self.pageable {
return Err(Error::UnsupportedQwenOperation);
}
self.banks[n]
.alias
.checked_add(span.offset() as u64)
.ok_or(Error::InvalidSize)
}
/// Every check of a span against its retained bank except the device alias; returns the bank index.
fn check(&self, span: &ResidentExpertBankSpan) -> Result<usize> {
if self.closed || self.context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
@@ -206,7 +367,7 @@ impl<'ctx> MappedExpertBank<'ctx> {
_ => return Err(Error::InvalidSize),
};
let bank = &self.banks[n];
if !bank.registered
if (!bank.registered && !self.pageable)
|| !span.belongs_to(&bank.member)
|| span.bytes().is_empty()
|| span
@@ -218,9 +379,7 @@ impl<'ctx> MappedExpertBank<'ctx> {
{
return Err(Error::InvalidSize);
}
bank.alias
.checked_add(span.offset() as u64)
.ok_or(Error::InvalidSize)
Ok(n)
}
pub fn eligible(&self, spans: &[ResidentExpertBankSpan; 3]) -> bool {
let layer = match spans[0].role() {
@@ -235,7 +394,7 @@ impl<'ctx> MappedExpertBank<'ctx> {
};
span.role() == TensorRole::Layer { layer, role }
&& span.expert() == spans[0].expert()
&& self.alias(span).is_ok()
&& self.check(span).is_ok()
})
}
pub fn copy_triplet(
@@ -363,6 +522,9 @@ impl<'ctx> MappedExpertBank<'ctx> {
let guard = self.context.enter()?;
let mut result = Ok(());
if let Some(api) = &self.api {
for (start, _) in std::mem::take(&mut *self.resident.borrow_mut()) {
result = combine(result, api.unregister_at(start));
}
for bank in &mut self.banks {
if bank.registered {
let unregister = api.unregister_bank(bank.member.bytes());
+8 -1
View File
@@ -474,7 +474,14 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
// Physical role-major bank layout requires three H2Ds. Same source
// bytes and literal blob G/U/D layout; no decode/conversion/copy tmp.
for (destination, source) in destinations.into_iter().zip(sources) {
api.copy_registered(destination, source, stream)?;
// one copy per registered/unregistered piece (`MappedExpertBank::copy_pieces`)
for (offset, bytes) in bank.copy_pieces(source) {
api.copy_registered(
destination.checked_subspan(source.len(), offset, bytes)?,
&source[offset..offset + bytes],
stream,
)?;
}
}
Ok(())
})?;
@@ -313,8 +313,10 @@ impl<'ctx> OriginalExpertCache<'ctx> {
let mut offset = 0usize;
for span in spans {
let source = bank.cache_source(span)?;
let destination = handle.checked_subspan(capacity, offset, source.len())?;
api.copy(destination.qwen_address(), source, stream)?;
for (at, bytes) in bank.copy_pieces(source) {
let destination = handle.checked_subspan(capacity, offset + at, bytes)?;
api.copy(destination.qwen_address(), &source[at..at + bytes], stream)?;
}
offset += source.len();
}
Ok(())
@@ -523,13 +525,15 @@ impl<'ctx> OriginalExpertCache<'ctx> {
let mut offset = 0usize;
for span in spans {
let source = bank.cache_source(span)?;
let destination = handle.checked_subspan(capacity, offset, source.len())?;
self.attempted = true;
self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy(
destination.qwen_address(),
source,
api::Stream(0),
)?;
for (at, bytes) in bank.copy_pieces(source) {
let destination = handle.checked_subspan(capacity, offset + at, bytes)?;
self.attempted = true;
self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy(
destination.qwen_address(),
&source[at..at + bytes],
api::Stream(0),
)?;
}
offset += source.len();
}
Ok(())
@@ -244,7 +244,9 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
let mut offset = staging + (q * stride) as u64;
for part in s {
let bytes = source.bank.cache_source(part)?;
copy.enqueue_copy_h2d(offset, bytes)?;
for (at, n) in source.bank.copy_pieces(bytes) {
copy.enqueue_copy_h2d(offset + at as u64, &bytes[at..at + n])?;
}
offset += bytes.len() as u64;
}
}
+7 -7
View File
@@ -440,13 +440,6 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0x36, 0x1d, 0xb3, 0xe8, 0x47, 0x1e, 0x42, 0x77, 0x8a, 0x4b, 0x7d, 0x45, 0x9a, 0xf7, 0x28, 0x9a, 0xa8, 0xe8, 0x01, 0x7b, 0xb3, 0xa7, 0x45, 0x5e, 0x6a, 0xa2, 0xe0, 0x49, 0xb2, 0x2a, 0xd0, 0x93],
ptx: concat!(include_str!("../ptx-sm86/experimental_kv_q4.ptx"), "\0").as_bytes(),
},
Companion {
name: "qsa_prompt_resolver.ptx",
key: [0x74, 0x8a, 0x2e, 0x0d, 0x5f, 0xcd, 0x12, 0xa9, 0xd4, 0x9a, 0x20, 0xfa, 0x15, 0x56, 0x19, 0x0b, 0x22, 0xb0, 0x63, 0x06, 0x80, 0xc7, 0xa4, 0xef, 0x39, 0x8d, 0x90, 0x1f, 0x47, 0xf4, 0x71, 0xb3],
len: 23782,
sha: [0x24, 0x47, 0x16, 0x72, 0x93, 0x97, 0x33, 0x83, 0xcb, 0x42, 0xaf, 0xd7, 0x3f, 0xc2, 0x80, 0xb1, 0x4f, 0x67, 0x9b, 0xae, 0x30, 0xad, 0x84, 0x76, 0x4e, 0xd7, 0x4b, 0xd0, 0x7d, 0x2a, 0x6c, 0xa8],
ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_resolver.ptx"), "\0").as_bytes(),
},
Companion {
name: "qwen_qsa_attention_native.ptx",
key: [0x77, 0x72, 0xe4, 0xe7, 0x5d, 0x78, 0xa9, 0x91, 0x01, 0x44, 0xca, 0x10, 0x85, 0x51, 0x80, 0x0f, 0xd4, 0x29, 0x69, 0x55, 0x78, 0x15, 0x40, 0xaf, 0xb6, 0x5f, 0x53, 0xd6, 0x12, 0xd7, 0xe1, 0xf3],
@@ -545,6 +538,13 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0x51, 0x62, 0x2e, 0x4f, 0x08, 0xa7, 0xe1, 0xfb, 0x52, 0x0f, 0xac, 0x0d, 0x0d, 0x8d, 0x2c, 0x3b, 0x61, 0xdc, 0xa1, 0x22, 0x70, 0x51, 0xaa, 0x14, 0xf6, 0xf7, 0x7d, 0xfc, 0x0a, 0xdf, 0x57, 0xad],
ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_indexer.ptx"), "\0").as_bytes(),
},
Companion {
name: "qsa_prompt_resolver.ptx",
key: [0x8d, 0x3e, 0xcb, 0xae, 0xcb, 0xf2, 0x84, 0x45, 0xba, 0x64, 0x48, 0x5b, 0xdf, 0xf3, 0xd9, 0x1a, 0x21, 0xd8, 0x7b, 0x85, 0xd5, 0x93, 0x9a, 0x01, 0x52, 0xef, 0x2f, 0x24, 0x14, 0x48, 0x0e, 0x22],
len: 23915,
sha: [0x32, 0xd9, 0x6c, 0xa6, 0xa7, 0x2f, 0x40, 0xed, 0xa2, 0x1d, 0x51, 0xd9, 0xf4, 0xd4, 0xd3, 0x77, 0xc3, 0x73, 0xc6, 0x37, 0x83, 0xcc, 0x42, 0x29, 0x10, 0x88, 0x3b, 0xb8, 0xd8, 0xd8, 0xb0, 0x8d],
ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_resolver.ptx"), "\0").as_bytes(),
},
Companion {
name: "q2_0_q8_1.ptx",
key: [0x8e, 0x81, 0xdb, 0xba, 0xa7, 0x6d, 0x85, 0x16, 0x47, 0x63, 0x39, 0xc1, 0x68, 0xf1, 0xd9, 0xc1, 0x72, 0x34, 0x1a, 0x78, 0xcc, 0xec, 0xda, 0x08, 0x71, 0x4a, 0x13, 0xa5, 0x68, 0x7e, 0x3b, 0x6e],
+3
View File
@@ -3470,6 +3470,9 @@ mod singleload_proof;
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "backend_original_serve_smoke.rs"]
mod original_serve_smoke;
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "backend_original_serve_laptop.rs"]
mod original_serve_laptop;
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "resident_mmq_model_proof.rs"]
@@ -0,0 +1,163 @@
//! Opt-in real-model bench of the Original serve stack in the laptop profile (docs/laptop-profile.md): the
//! low-RAM sources instead of the server's resident ones, and fixed pre-tokenized prompts so the Original
//! (`strata generate --serve`, `GEN <max_new> <ids>`) can be run on exactly the same token IDs.
//!
//! * `LELEKA_LAPTOP_BENCH=yes` explicit opt-in (one GPU, one model load);
//! * `LELEKA_STRA169_IQ3S_SHARD0`, `_SHARD1` the pinned GGUF shards;
//! * `LELEKA_LAPTOP_KAR_FILE` (read-only regular file, `InheritedKarArchive::open_read_only_file`) or
//! `LELEKA_STRA169_KAR_FD` (the sealed memfd), and `LELEKA_STRA169_KAR_PROVENANCE`;
//! * `LELEKA_STRA169_MTP_PACK`, `LELEKA_STRA169_MTP_STAGING`;
//! * `LELEKA_LAPTOP_EXPERTS` = `mapped` (default: read-only shared mapping of shard 0, the Original's
//! `--mmap-experts` with the GGUF in place) or `resident` (the 50 GB RAM copy of the server profile);
//! * `LELEKA_LAPTOP_PROMPT_IDS` file, one comma-separated token-ID line per prompt;
//! * optional `LELEKA_LAPTOP_MAX_NEW` (128), `_REPEAT` (2), `_SPEC_MIN_P` (0.5, setup.py's), `_CPU_WORKERS` (7: the Original's default on an
//! 8-core CPU, one core for the host loop), `_MAX_CONTEXT` (8192), `LELEKA_ORIGINAL_SERVE_CAPACITY` (2048),
//! `LELEKA_ORIGINAL_SERVE_BUDGET_GIB` (15), `LELEKA_ORIGINAL_SERVE_KV_RESIDENT` (default window),
//! `LELEKA_ORIGINAL_SERVE_RT_DIR`, and the VRAM expert tier's `LELEKA_ORIGINAL_SERVE_EXPERT_*` switches.
//!
//! Prints one `LAPTOP request` line per request (prompt tokens, TTFT, prompt and decode phase wall time, prefill
//! and decode tok/s) and the output IDs of the first pass. Greedy, no penalties, EOS stops.
//!
//! Run: `cargo test -p leleka-runtime --features cuda-driver[,sm86] --release -- --ignored --nocapture
//! original_serve_laptop_bench`.
use super::*;
use crate::qwen_forward::{
original_serve_request::ServeRequest,
original_serve_stack::{OriginalServeStack, StackConfig},
};
use std::env;
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned bench input {name}"))
}
fn number(name: &str, default: usize) -> usize {
env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default)
}
/// `VmRSS`, `VmHWM`, `RssAnon`, `RssFile`, `RssShmem`, `VmLck`, `VmPin` of this process in MiB.
fn memory_line() -> String {
let text = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
let mut out = Vec::new();
for key in ["VmRSS:", "VmHWM:", "RssAnon:", "RssFile:", "RssShmem:", "VmLck:", "VmPin:"] {
if let Some(line) = text.lines().find(|l| l.starts_with(key)) {
let kib: u64 = line.split_ascii_whitespace().nth(1).and_then(|v| v.parse().ok()).unwrap_or(0);
out.push(format!("{}={}MiB", key.trim_end_matches(':'), kib / 1024));
}
}
out.join(" ")
}
fn elapsed(start: std::time::Instant) -> f64 {
start.elapsed().as_secs_f64()
}
#[test]
#[ignore = "one explicitly scheduled real-model load and GPU (laptop profile)"]
fn original_serve_laptop_bench() {
assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required");
let start = std::time::Instant::now();
let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed");
let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed");
eprintln!("LAPTOP load: shards verified in {:.1} s; {}", elapsed(start), memory_line());
let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed");
let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent");
let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE");
let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") {
Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance).expect("read-only KAR admission failed"),
None => {
let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("LELEKA_LAPTOP_KAR_FILE or LELEKA_STRA169_KAR_FD").parse().expect("invalid descriptor");
InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed")
}
};
let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp(
artifact,
&inherited,
&required_path("LELEKA_STRA169_MTP_PACK"),
&required_path("LELEKA_STRA169_MTP_STAGING"),
)
.expect("actual pinned KAR+MTP binding failed");
eprintln!("LAPTOP load: KAR ({}) + MTP bound at {:.1} s; {}", if inherited.file_backed() { "read-only file" } else { "sealed memfd" }, elapsed(start), memory_line());
let experts = env::var("LELEKA_LAPTOP_EXPERTS").unwrap_or_else(|_| "mapped".to_owned());
let report = match experts.as_str() {
"mapped" => binding.load_mapped_expert_source().expect("mapped expert source load failed"),
"resident" => binding.load_resident_expert_source().expect("resident expert source load failed"),
other => panic!("LELEKA_LAPTOP_EXPERTS must be mapped or resident, not {other}"),
};
eprintln!("LAPTOP load: experts {experts} ({} bytes, file_mapped={}) at {:.1} s; {}", report.source_bytes, report.file_mapped, elapsed(start), memory_line());
// Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by
// --max-context). Unscaled RoPE; must precede the first CUDA context user.
if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") {
let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count");
leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused");
eprintln!("LAPTOP config: process geometry {cells} cells (experimental)");
}
let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15);
let driver = Driver::load().expect("CUDA driver load failed");
let device = driver.device(0).expect("CUDA device 0 unavailable");
let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable"));
let mut config = StackConfig::new(number("LELEKA_LAPTOP_MAX_CONTEXT", 8192) as i64);
config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048);
config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32;
if let Ok(v) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT") {
config.kv_resident = v.parse().expect("LELEKA_ORIGINAL_SERVE_KV_RESIDENT must be a count");
}
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
.expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting");
eprintln!("LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}",
config.capacity, config.cpu_workers, config.max_context, config.kv_resident, config.expert_tier);
let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) {
Ok(stack) => stack,
Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()),
};
eprintln!("LAPTOP load: stack open at {:.1} s; {}", elapsed(start), memory_line());
let prompts: Vec<Vec<i32>> = std::fs::read_to_string(required_path("LELEKA_LAPTOP_PROMPT_IDS"))
.expect("prompt id file unreadable")
.lines()
.filter(|l| !l.trim().is_empty())
.map(|l| l.split(',').map(|t| t.trim().parse().expect("token id")).collect())
.collect();
let max_new = number("LELEKA_LAPTOP_MAX_NEW", 128);
let repeat = number("LELEKA_LAPTOP_REPEAT", 2).max(1);
// setup.py's `--spec-min-p 0.5` (the draft-probability floor; greedy output does not depend on it)
let spec_min_p: f32 = env::var("LELEKA_LAPTOP_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SPEC_MIN_P")).unwrap_or(0.5);
for pass in 0..repeat {
for (index, ids) in prompts.iter().enumerate() {
let request = ServeRequest::new(ids.clone(), max_new, None, 7, spec_min_p, vec![eos as i32]);
let mut out = Vec::new();
let begun = std::time::Instant::now();
let mut first = None;
let served = stack.serve(&request, &mut |round| {
if first.is_none() {
first = Some(begun.elapsed());
}
out.extend_from_slice(round);
Ok(())
}, &mut || false);
let total = begun.elapsed().as_secs_f64() * 1e3;
let ttft = first.map_or(total, |d| d.as_secs_f64() * 1e3);
let (prompt_ms, decode_ms) = stack.last_timing();
match served {
Ok(outcome) => {
let prefill = if prompt_ms > 0.0 { ids.len() as f64 * 1e3 / prompt_ms } else { 0.0 };
let decode = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 };
eprintln!("LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} \
decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2}; {}",
index + 1, ids.len(), out.len(), outcome.rounds, memory_line());
if let Some(stats) = stack.expert_tier_stats() {
eprintln!("LAPTOP tier p{} pass={pass}: {}", index + 1, stats.describe());
}
if pass == 0 {
eprintln!("LAPTOP output p{}: {}", index + 1, out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(","));
}
}
Err(e) => panic!("request p{} pass {pass} failed: {e:?} health={:?}", index + 1, stack.health()),
}
}
}
stack.close().expect("stack cleanup failed");
Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed");
}
@@ -17,6 +17,8 @@ const PINNED_ARCHIVE_BYTES: u64 = 55_295_529_472;
pub struct InheritedKarArchive {
archive: File,
provenance: File,
/// `open_read_only_file`: an ordinary read-only file instead of a sealed memfd (see there).
file_backed: bool,
}
impl InheritedKarArchive {
#[cfg(target_os = "linux")]
@@ -30,9 +32,44 @@ impl InheritedKarArchive {
Ok(Self {
archive,
provenance,
file_backed: false,
})
}
/// The low-RAM form of the same pinned archive: the archive stays an ordinary file on the SSD and only the
/// rows a request reads pass through the OS file cache, like the Original's `PleTable::open_kar` (ngram.cpp:
/// `kar_open` with payload verification, then a read-only mapping of the file). A sealed memfd copy keeps
/// all 55,295,529,472 bytes in shmem for the life of the process, which a 32-48 GB PC cannot hold.
///
/// Weaker than the seal and therefore explicit: the full SHA-256 and every payload CRC are still verified at
/// load (`load_pinned_inherited_archive`), but immutability afterwards rests on the operator: the file must
/// be a regular file owned by this user with no write permission bits (`chmod a-w`) and a single link, and
/// every later row read rechecks its length and inode.
#[cfg(target_os = "linux")]
pub fn open_read_only_file(archive: &Path, provenance: PathBuf) -> Result<Self, &'static str> {
let archive = open_read_only_archive(archive, PINNED_ARCHIVE_BYTES)
.map_err(|_| "KAR archive file is not the pinned read-only archive")?;
let provenance = private_copy::open_regular(&provenance, None)
.map_err(|_| "KAR provenance is not a regular file")?;
verify_open_provenance(&provenance, PROVENANCE_DIGEST)
.map_err(|_| "KAR provenance verification failed")?;
Ok(Self {
archive,
provenance,
file_backed: true,
})
}
#[cfg(not(target_os = "linux"))]
pub fn open_read_only_file(_archive: &Path, _provenance: PathBuf) -> Result<Self, &'static str> {
Err("KAR archive file requires Linux")
}
/// True for `open_read_only_file`.
pub fn file_backed(&self) -> bool {
self.file_backed
}
#[cfg(not(target_os = "linux"))]
pub fn open(_fd: u32, _provenance: PathBuf) -> Result<Self, &'static str> {
Err("inherited KAR archive requires Linux")
@@ -69,6 +106,56 @@ fn open_sealed_archive_fd(fd: u32, expected_bytes: u64) -> InputResult<File> {
Ok(file)
}
/// An ordinary archive file for `InheritedKarArchive::open_read_only_file`: regular, the pinned length, one
/// link, owned by this user, no write permission bits for anyone.
#[cfg(target_os = "linux")]
fn open_read_only_archive(path: &Path, expected_bytes: u64) -> InputResult<File> {
use std::os::unix::fs::OpenOptionsExt;
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(0x800 | 0x20000) // O_NONBLOCK (reject FIFOs), O_NOFOLLOW
.open(path)
.map_err(private_copy::provenance_error)?;
check_read_only_archive(&file, expected_bytes)?;
Ok(file)
}
#[cfg(target_os = "linux")]
fn check_read_only_archive(file: &File, expected_bytes: u64) -> InputResult<()> {
use std::os::unix::fs::MetadataExt;
let meta = file.metadata().map_err(private_copy::provenance_error)?;
if !meta.is_file() || meta.len() != expected_bytes || meta.nlink() != 1 {
return Err(InputBindingError::Range);
}
// /proc/self is owned by this process's effective user
let me = std::fs::metadata("/proc/self").map_err(private_copy::provenance_error)?.uid();
if meta.mode() & 0o222 != 0 || meta.uid() != me {
return Err(InputBindingError::Metadata);
}
Ok(())
}
/// An independent reader of the admitted read-only archive (same inode, rechecked).
#[cfg(target_os = "linux")]
fn reopen_read_only_archive(source: &File, expected_bytes: u64) -> InputResult<File> {
use std::os::fd::AsRawFd;
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(0x800)
.open(format!("/proc/self/fd/{}", source.as_raw_fd()))
.map_err(private_copy::provenance_error)?;
let (a, b) = (
source.metadata().map_err(private_copy::provenance_error)?,
file.metadata().map_err(private_copy::provenance_error)?,
);
if a.dev() != b.dev() || a.ino() != b.ino() {
return Err(InputBindingError::Metadata);
}
check_read_only_archive(&file, expected_bytes)?;
Ok(file)
}
#[cfg(target_os = "linux")]
fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> InputResult<()> {
use sha2::{Digest, Sha256};
@@ -107,9 +194,14 @@ pub(crate) fn load_pinned_inherited_archive(
) -> InputResult<VerifiedKarPleArtifact> {
use std::os::fd::AsRawFd;
let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?;
let fd = u32::try_from(source.archive.as_raw_fd()).map_err(|_| InputBindingError::Range)?;
let reader = open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES)
.map_err(|e| input_failure(LoadPhase::Source, e))?;
let reader = if source.file_backed {
reopen_read_only_archive(&source.archive, PINNED_ARCHIVE_BYTES)
.map_err(|e| input_failure(LoadPhase::Source, e))?
} else {
let fd = u32::try_from(source.archive.as_raw_fd()).map_err(|_| InputBindingError::Range)?;
open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES)
.map_err(|e| input_failure(LoadPhase::Source, e))?
};
verify_open_provenance(&source.provenance, PROVENANCE_DIGEST)
.map_err(|e| input_failure(LoadPhase::Provenance, e))?;
let inspection = leleka_model_format::kar::KarInspection::inspect(reader)
@@ -25,6 +25,27 @@ impl ModelBinding {
ResidentExpertSourceError::Read(_) => InputBindingError::Read,
})
}
/// The low-RAM form of `load_resident_expert_source`: the same banks as read-only shared mappings of shard 0
/// (the Original's `--mmap-experts`, GGUF in place). Same preconditions; no RAM is committed for the experts.
#[cfg(target_os = "linux")]
pub(crate) fn load_mapped_expert_source(
&mut self,
) -> InputResult<ResidentExpertSourceReport> {
if self.kar_ple.is_none() || self.mtp.is_none() {
return Err(InputBindingError::Metadata);
}
self.mtp_weights()?;
self.artifact
.get_mut()
.load_mapped_expert_source()
.map_err(|error| match error {
ResidentExpertSourceError::Geometry => InputBindingError::Geometry,
ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata,
ResidentExpertSourceError::Allocation
| ResidentExpertSourceError::MemoryAdmission => InputBindingError::Allocation,
ResidentExpertSourceError::Read(_) => InputBindingError::Read,
})
}
pub(crate) fn resident_expert_source_report(
&self,
) -> InputResult<Option<ResidentExpertSourceReport>> {
@@ -66,6 +66,8 @@ pub(crate) struct ExpertTierConfig {
pub(crate) adapt_swaps: u32,
/// `!--no-prefill-borrow` (the loan is taken only with a profile, as in the Original).
pub(crate) prefill_borrow: bool,
/// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`.
pub(crate) resident_budget_gib: f64,
}
impl ExpertTierConfig {
pub(crate) fn off() -> Self {
@@ -79,6 +81,7 @@ impl ExpertTierConfig {
adapt_every: 4,
adapt_swaps: 96,
prefill_borrow: true,
resident_budget_gib: 0.0,
}
}
/// The tier is on with a slot count or a profile.
@@ -91,6 +94,7 @@ impl ExpertTierConfig {
}
pub(crate) fn validate(&self) -> Result<()> {
if self.slots < -1 || !self.pcie_frac.is_finite() || !(0.0..=1.0).contains(&self.pcie_frac) || self.adapt_swaps > 4096
|| !self.resident_budget_gib.is_finite() || self.resident_budget_gib < 0.0
{
return Err(Error::InvalidDimension);
}
@@ -137,6 +141,9 @@ impl ExpertTierConfig {
if let Some(v) = var("PREFILL_BORROW") {
config.prefill_borrow = !matches!(v.as_str(), "no" | "0" | "off");
}
if let Some(v) = var("RESIDENT_BUDGET_GIB") {
config.resident_budget_gib = v.parse().map_err(|_| Error::InvalidDimension)?;
}
config.validate()?;
Ok(config)
}
@@ -451,10 +458,55 @@ pub(in crate::qwen_forward) fn open_tier<'ctx>(
let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?;
cache.verify_slot(slot, &bank, &spans).map_err(|e| driver_error(&e))?;
}
if config.resident_budget_gib > 0.0 && bank.pageable() {
pin_resident_complement(&bank, &cache, profile, config.resident_budget_gib)?;
}
}
Ok(Some((cache, filled)))
}
/// generate.cpp `--resident-budget-gib N` over the low-RAM (file-mapped) bank: the experts the VRAM cache does
/// not hold, in profile order, page-locked in RAM while they fit N GiB, clamped like
/// `FileExpertSource::pin_cache_complement` to `MemAvailable` less the 4 GiB headroom and a 0.25 GiB margin.
fn pin_resident_complement(
bank: &leleka_cuda_driver::MappedExpertBank<'_>,
cache: &OriginalExpertCache<'_>,
profile: &OriginalRankedExperts,
budget_gib: f64,
) -> Result<()> {
const GIB: f64 = 1_073_741_824.0;
let available = std::fs::read_to_string("/proc/meminfo")
.ok()
.and_then(|t| {
t.lines()
.find(|l| l.starts_with("MemAvailable:"))
.and_then(|l| l.split_ascii_whitespace().nth(1)?.parse::<u64>().ok())
})
.map_or(0, |kib| kib * 1024);
let room = available.saturating_sub(4 << 30).saturating_sub(256 << 20);
let budget = ((budget_gib * GIB) as u64).min(room);
let ranked: Vec<(u8, u32)> = profile
.pairs()
.iter()
.filter(|&&(layer, expert)| cache.slot_of(usize::from(layer), usize::from(expert)) < 0)
.map(|&(layer, expert)| (layer as u8, u32::from(expert)))
.collect();
let started = std::time::Instant::now();
match bank.pin_resident(&ranked, budget) {
Ok((held, bytes)) => eprintln!(
"leleka-serve: resident RAM budget {:.2} GiB (asked {budget_gib:.2}, {:.2} GiB available): {held} experts the \
VRAM cache does not hold page-locked by profile rank ({:.2} GiB) in {:.1} s; the rest read from the file",
budget as f64 / GIB,
available as f64 / GIB,
bytes as f64 / GIB,
started.elapsed().as_secs_f64()
),
// #403: a budget that cannot be kept is a warning; every miss is read from the file pages instead
Err(e) => eprintln!("leleka-serve: WARNING: the resident RAM budget cannot be kept ({e:?}); experts are read from the file"),
}
Ok(())
}
/// The serve stack's loan test (generate.cpp `fits_one`, fixed chunk): the prompt path's buffers for the
/// configured chunk come from the cache's last `k` slots when `0 < k` and `k + 128 <= slots`. Unlike the
/// Original the chunk is not halved to fit: the prompt executor is built for exactly this capacity.
+11 -2
View File
@@ -10,5 +10,14 @@ autotests = false
[dependencies]
sha2 = "0.11"
[lints]
workspace = true
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "=1.1.5", features = ["mm", "param"] }
# The workspace forbids unsafe code; this crate denies it instead so that exactly one owner, the read-only
# shared mapping of a verified GGUF tensor (gguf_resident.rs `FileSpan`, the low-RAM expert source), can
# `#[allow]` its mmap/munmap/slice. Everything else stays unsafe-free.
[lints.rust]
unsafe_code = "deny"
[lints.clippy]
all = "warn"
+196 -4
View File
@@ -28,7 +28,7 @@ fn next_source_id() -> Result<u64> {
pub(crate) struct ResidentTensor {
source: u64,
tensor_number: usize,
bytes: Box<[u8]>,
bytes: ResidentStorage,
charged_bytes: usize,
}
impl ResidentTensor {
@@ -38,6 +38,64 @@ impl ResidentTensor {
pub(crate) fn len(&self) -> usize {
self.bytes.len()
}
/// True when the bytes are the verified file's own pages (the Original's `--mmap-experts` GGUF-in-place
/// source), false for an owned RAM copy.
pub(crate) fn file_mapped(&self) -> bool {
matches!(self.bytes, ResidentStorage::Mapped(_))
}
}
/// Where a retained tensor's bytes live: an owned copy in RAM (the resident source), or a read-only shared
/// mapping of the verified GGUF file itself (the low-RAM source: the OS file cache holds what is used and
/// can give it back; the bytes are the file's, so the answers are the same).
enum ResidentStorage {
Owned(Box<[u8]>),
Mapped(FileSpan),
}
impl ResidentStorage {
fn as_slice(&self) -> &[u8] {
match self {
Self::Owned(bytes) => bytes,
Self::Mapped(span) => span.as_slice(),
}
}
fn len(&self) -> usize {
self.as_slice().len()
}
}
impl std::ops::Deref for ResidentStorage {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.as_slice()
}
}
/// A `PROT_READ`/`MAP_SHARED` mapping of one tensor's exact byte range of a verified file (rounded out to
/// pages for the kernel, never exposed beyond the tensor). Unmapped on drop.
pub(crate) struct FileSpan {
base: *mut std::ffi::c_void,
map_len: usize,
start: usize,
len: usize,
}
impl FileSpan {
#[allow(unsafe_code)]
fn as_slice(&self) -> &[u8] {
// SAFETY: `base..base+map_len` is a live read-only mapping owned by `self`; `start + len <= map_len`
// was checked at construction. The source file's stability is the `VerifiedGgufFile` contract (its
// contents must not change while the handle and anything retained from it are alive).
unsafe { std::slice::from_raw_parts(self.base.cast::<u8>().add(self.start), self.len) }
}
}
impl Drop for FileSpan {
#[allow(unsafe_code)]
fn drop(&mut self) {
#[cfg(target_os = "linux")]
// SAFETY: exact base/length returned by mmap; no borrow of the slice outlives `self`.
unsafe {
let _ = rustix::mm::munmap(self.base, self.map_len);
}
}
}
impl VerifiedGgufFile {
/// Constructor is source-owned: arbitrary caller bytes cannot become a bank.
@@ -84,10 +142,83 @@ impl VerifiedGgufFile {
Ok(ResidentTensor {
source,
tensor_number,
bytes,
bytes: ResidentStorage::Owned(bytes),
charged_bytes,
})
}
/// The Original's `--mmap-experts` with the GGUF in place (`FileExpertSource::set_gguf`): the tensor's
/// bytes are a read-only shared mapping of this verified file instead of a copy, so no RAM is committed
/// for them; the OS file cache keeps what is read. Same descriptor, same indexed bounds and size checks
/// as `load_resident_tensor`. `charged_bytes` is the mapped length (address space, not RAM).
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
pub(crate) fn map_resident_tensor(
&mut self,
tensor_number: usize,
) -> std::result::Result<ResidentTensor, ResidentLoadError> {
let (tensor_offset, tensor_bytes) = {
let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| {
ResidentLoadError::Source("GGUF tensor index is out of bounds".into())
})?;
(tensor.offset, tensor.bytes)
};
let length =
usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?;
if length == 0 {
return Err(ResidentLoadError::Source("resident tensor is empty".into()));
}
self.stream_tensor(tensor_number, 0, 0, |_| Ok(()))
.map_err(ResidentLoadError::Source)?;
let absolute = self
.index
.summary
.data_start
.checked_add(tensor_offset)
.ok_or_else(|| ResidentLoadError::Source("GGUF tensor offset overflow".into()))?;
if absolute
.checked_add(tensor_bytes)
.is_none_or(|end| end > self.index.summary.file_size)
{
return Err(ResidentLoadError::Source("GGUF tensor exceeds indexed file".into()));
}
let page = rustix::param::page_size() as u64;
let map_offset = absolute & !(page - 1);
let start = usize::try_from(absolute - map_offset)
.map_err(|e| ResidentLoadError::Source(e.into()))?;
let map_len = start
.checked_add(length)
.ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?;
self.check_size().map_err(ResidentLoadError::Source)?;
// SAFETY: a fresh read-only shared mapping of the retained verified descriptor at a page-aligned
// offset inside the indexed file; the kernel picks the address. No existing memory is replaced.
let base = unsafe {
rustix::mm::mmap(
std::ptr::null_mut(),
map_len,
rustix::mm::ProtFlags::READ,
rustix::mm::MapFlags::SHARED,
&self.file,
map_offset,
)
}
.map_err(|e| ResidentLoadError::Source(Box::new(std::io::Error::from(e))))?;
let span = FileSpan { base, map_len, start, len: length };
self.check_size().map_err(ResidentLoadError::Source)?;
let source = match self.resident_source_id {
Some(source) => source,
None => {
let source = next_source_id().map_err(ResidentLoadError::Source)?;
self.resident_source_id = Some(source);
source
}
};
Ok(ResidentTensor {
source,
tensor_number,
bytes: ResidentStorage::Mapped(span),
charged_bytes: length,
})
}
/// Copies a real source-owned bank span, with unchanged indexed bounds and
/// same-FD pre/post size checks. A hit intentionally does not seek/read FD.
pub(crate) fn copy_resident_tensor(
@@ -132,6 +263,7 @@ impl VerifiedGgufFile {
.ok_or("resident tensor offset overflow")?;
let selected = resident
.bytes
.as_slice()
.get(first..end)
.ok_or("resident tensor extent")?;
self.check_size()?;
@@ -186,7 +318,7 @@ impl VerifiedGgufFile {
Ok(ResidentTensor {
source,
tensor_number,
bytes,
bytes: ResidentStorage::Owned(bytes),
charged_bytes,
})
}
@@ -207,7 +339,7 @@ impl ResidentTensor {
std::rc::Rc::new(self)
}
pub(crate) fn retained_bytes(&self) -> &[u8] {
&self.bytes
self.bytes.as_slice()
}
pub(crate) const fn retention_metadata_bytes() -> usize {
std::mem::size_of::<Self>() + 2 * std::mem::size_of::<usize>()
@@ -323,4 +455,64 @@ mod retained_lease_test {
drop(lease);
std::fs::remove_file(path).unwrap();
}
/// The low-RAM source maps the verified file instead of copying it: the same bytes, the same retained-owner
/// checks, and the mapping outlives the source handle like the owned copy does.
#[cfg(target_os = "linux")]
#[test]
fn mapped_tensor_is_the_files_bytes_and_a_retained_owner() {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!(
"strata-bank-map-{}-{nonce}.gguf",
std::process::id()
));
let mut bytes = b"GGUF".to_vec();
bytes.extend(3u32.to_le_bytes());
bytes.extend(1u64.to_le_bytes());
bytes.extend(0u64.to_le_bytes());
let name = b"public.mapped.owner";
bytes.extend((name.len() as u64).to_le_bytes());
bytes.extend(name);
bytes.extend(1u32.to_le_bytes());
bytes.extend(16u64.to_le_bytes());
bytes.extend(0u32.to_le_bytes());
bytes.extend(0u64.to_le_bytes());
bytes.resize(bytes.len().div_ceil(32) * 32, 0);
for word in [0x80000000u32, 0x3f800000, 0xbf800000, 0x40490fdb]
.into_iter()
.cycle()
.take(16)
{
bytes.extend(word.to_le_bytes());
}
std::fs::write(&path, &bytes).unwrap();
let hex = Sha256::digest(&bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>();
let digest = format!("sha256:{hex}");
let mut source = VerifiedGgufFile::open(&path, &digest).unwrap();
let copy = source.load_resident_tensor(0, 64).unwrap();
let mapped = source.map_resident_tensor(0).unwrap();
assert!(mapped.file_mapped() && !copy.file_mapped());
assert_eq!(mapped.len(), 64);
assert_eq!(mapped.charged_bytes(), 64);
let mapped = mapped.into_retained();
assert_eq!(mapped.retained_bytes(), copy.into_retained().retained_bytes());
assert_eq!(mapped.retained_bytes().as_ptr() as usize % 16, 0);
source.validate_retained_tensor(&mapped).unwrap();
let out = source
.copy_resident_tensor(&mapped, 16, vec![0u8; 16].into_boxed_slice())
.unwrap();
assert_eq!(&*out, &mapped.retained_bytes()[16..32]);
let expected = mapped.retained_bytes().to_vec();
drop(source);
// the mapping is its own owner, like the owned copy
assert_eq!(mapped.retained_bytes(), expected);
drop(mapped);
std::fs::remove_file(path).unwrap();
}
}
@@ -392,6 +392,7 @@ impl Qwen4ExpArtifact {
shard0_sha256: self.shards[0].artifact_sha256(),
copied_spans: 0,
copied_bytes: 0,
file_mapped: false,
};
self.resident_experts = Some(ResidentExpertBank {
banks: Rc::new(capture.banks),
@@ -26,6 +26,8 @@ pub struct ResidentExpertSourceReport {
pub shard0_sha256: [u8; 32],
pub copied_spans: u64,
pub copied_bytes: u64,
/// The banks are read-only shared mappings of shard 0 (`load_mapped_expert_source`), not RAM copies.
pub file_mapped: bool,
}
#[derive(Debug)]
pub enum ResidentExpertSourceError {
@@ -329,6 +331,7 @@ impl Qwen4ExpArtifact {
shard0_sha256: self.shards[0].artifact_sha256(),
copied_spans: 0,
copied_bytes: 0,
file_mapped: false,
};
self.resident_experts = Some(ResidentExpertBank {
banks: Rc::new(banks),
@@ -341,6 +344,86 @@ impl Qwen4ExpArtifact {
pub fn resident_expert_source_report(&self) -> Option<ResidentExpertSourceReport> {
self.resident_experts.as_ref().map(|bank| bank.report())
}
/// The low-RAM source (the Original's `--mmap-experts`, GGUF shards in place: generate.cpp
/// `src.set_gguf(o.native_preset)` + `FileExpertSource::open`): the same 144 banks, but each is a read-only
/// shared mapping of shard 0 instead of a RAM copy. Nothing is read at load; the OS file cache holds the
/// experts that are used and can give the memory back. The bytes are the verified file's, so every consumer
/// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM.
#[cfg(target_os = "linux")]
pub fn load_mapped_expert_source(
&mut self,
) -> Result<ResidentExpertSourceReport, ResidentExpertSourceError> {
if self.resident_experts.is_some() {
return Err(ResidentExpertSourceError::AlreadyEnabled);
}
if self.topology.block_count != 48 || self.topology.expert_count != 512 {
return Err(ResidentExpertSourceError::Geometry);
}
let mut banks = Vec::new();
banks
.try_reserve_exact(BANKS)
.map_err(|_| ResidentExpertSourceError::Allocation)?;
let mut source_bytes = 0usize;
for layer in 0..48 {
for role in [
LayerRole::FfnGateExperts,
LayerRole::FfnUpExperts,
LayerRole::FfnDownExperts,
] {
let role = TensorRole::Layer { layer, role };
let tensor = self
.roles
.get(&role)
.ok_or(ResidentExpertSourceError::Geometry)?;
let descriptor = checked_descriptor(role, tensor)?;
source_bytes = source_bytes
.checked_add(descriptor.bytes)
.ok_or(ResidentExpertSourceError::Geometry)?;
if source_bytes as u64 > SOURCE_CAP {
return Err(ResidentExpertSourceError::MemoryAdmission);
}
let mapped = self.shards[0]
.map_resident_tensor(descriptor.tensor_number)
.map_err(|error| match error {
gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation,
gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission,
gguf::ResidentLoadError::Source(error) => {
ResidentExpertSourceError::Read(BindingError::Io(error))
}
})?;
if mapped.len() != descriptor.bytes {
return Err(ResidentExpertSourceError::Geometry);
}
banks.push(Bank {
descriptor,
tensor: mapped.into_retained(),
});
}
}
if banks.len() != BANKS {
return Err(ResidentExpertSourceError::Geometry);
}
let report = ResidentExpertSourceReport {
source_bytes: source_bytes as u64,
charged_bytes: source_bytes as u64,
bank_count: BANKS as u32,
source_cap_bytes: SOURCE_CAP,
observed_mem_available_bytes: 0,
future_headroom_bytes: 0,
shard0_sha256: self.shards[0].artifact_sha256(),
copied_spans: 0,
copied_bytes: 0,
file_mapped: true,
};
self.resident_experts = Some(ResidentExpertBank {
banks: Rc::new(banks),
report,
copied_spans: Cell::new(0),
copied_bytes: Cell::new(0),
});
Ok(report)
}
}
#[path = "qwen4exp_digest_capture.rs"]
@@ -363,6 +446,11 @@ impl ResidentExpertBankLease {
pub fn charged_source_bytes(&self) -> u64 {
self.report.charged_bytes
}
/// The banks are read-only shared mappings of the verified shard (the low-RAM source): page-locking them
/// would read and lock the whole file in RAM, so their consumers copy from pageable memory instead.
pub fn file_mapped(&self) -> bool {
self.report.file_mapped
}
pub fn retention_metadata_bytes(&self) -> usize {
// Complete lease was minted only after this checked closed bound.
BANKS * gguf::ResidentTensor::retention_metadata_bytes()
@@ -392,6 +480,9 @@ impl ResidentExpertBankMember {
pub fn bytes(&self) -> &[u8] {
self.tensor.retained_bytes()
}
pub fn file_mapped(&self) -> bool {
self.tensor.file_mapped()
}
pub fn belongs_to_lease(&self, lease: &ResidentExpertBankLease) -> bool {
slot(self.descriptor.role)
.ok()
+52
View File
@@ -0,0 +1,52 @@
//! Tokenize one user prompt per line into a Qwen chat turn with thinking off (the template's
//! `enable_thinking=false` generation prompt), printing one comma-separated token-ID line per prompt.
//!
//! `cargo run -p leleka-tokenizer --example chat_tokens -- TOKENIZER_DIR PROMPTS.txt`
//!
//! Used to feed the same token IDs to the Original (`strata generate --tokens-file`) and to the port in
//! paired laptop runs (docs/laptop-profile.md). Blank lines and lines starting with `#` are skipped.
use std::{env, fs, path::Path, process::ExitCode};
use leleka_tokenizer::Tokenizer;
fn main() -> ExitCode {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
eprintln!("usage: chat_tokens TOKENIZER_DIR PROMPTS.txt");
return ExitCode::from(2);
}
let tokenizer = match Tokenizer::from_assets(Path::new(&args[1])) {
Ok(t) => t,
Err(e) => {
eprintln!("chat_tokens: tokenizer: {e}");
return ExitCode::FAILURE;
}
};
let text = match fs::read_to_string(&args[2]) {
Ok(t) => t,
Err(e) => {
eprintln!("chat_tokens: {}: {e}", args[2]);
return ExitCode::FAILURE;
}
};
for line in text.lines().map(str::trim) {
if line.is_empty() || line.starts_with('#') {
continue;
}
let turn = format!(
"<|im_start|>user\n{line}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
);
match tokenizer.encode(&turn, true) {
Ok(ids) => {
let ids: Vec<String> = ids.iter().map(u32::to_string).collect();
println!("{}", ids.join(","));
}
Err(e) => {
eprintln!("chat_tokens: encode: {e}");
return ExitCode::FAILURE;
}
}
}
ExitCode::SUCCESS
}
+185
View File
@@ -0,0 +1,185 @@
# Laptop profile: Qwen3.8-Flash-Next IQ3_S on a 16 GB laptop GPU
**Status:** experimental profile, measured on one laptop. Nothing here is a production default or a quality claim.
The target is the one machine below, not the RTX 5090 server: what has to live where, which of the Original's
low-memory modes apply, what the Rust port lacked to run there, and paired numbers on the same prompts.
## Machine
| | |
| --- | --- |
| CPU | Intel i9-11900H, 8 cores / 16 threads, AVX-512 (VNNI, VBMI) |
| RAM | 48 GB (47 GiB usable); WSL2 gets half by default: `MemTotal` 24,447,308 kB |
| GPU | NVIDIA GeForce RTX 3080 Laptop GPU, 16,384 MiB, sm_86, driver 617.42 (WDDM, WSL2 passthrough); 14.89 GiB free to CUDA in WSL with nothing running |
| Disk | NVMe, 1.2 TB free on C:; the WSL ext4 VHDX lives on it |
| Software | Windows 11 Pro 26200, WSL2 Ubuntu 24.04, CUDA 13.2.86 (nvcc), cuBLAS 13.4 (Original) / 12.9.1.4 (port), Rust 1.99, gcc 13.3 |
Pinned host memory under this WSL2: `cudaHostAlloc` of 16 x 512 MiB and `cudaHostRegister` of 1-16 GiB all succeeded
(probe, 2026-10-16). The Original's setup.py comment "the driver pins only about 1 GB" under WSL is not true for this
driver; the limit is the VM's RAM.
## Model components and where they can live
Sizes are from the files (`native_experts.txt`, the MTP pack, the KAR provenance) and the Original's formulas.
| component | size | must be | can be |
| --- | --- | --- | --- |
| routed experts (48 layers x 512, IQ2_S..IQ4_NL) | 50,292,326,400 B (46.84 GiB), blob 1.51-2.66 MB, mean 2.05 MB | read per token for the 10 routed experts of every layer | VRAM cache (hot), RAM (warm), SSD (cold, via the OS file cache or direct reads) |
| dense pack (attention, GDN, shared experts, routers, norms) | `dense.bin` 1,538,035,200 B | VRAM | - |
| native head (Q5_K `output.weight` 248,320 x 2,560) | 521,472,000 B (Original log) | VRAM | - |
| token embedding | ~0.4 GB (Q5_K) | read per token | mapped host memory |
| PLE n-gram table (`per_layer_token_embd`, 320,001,536 rows) | 28,800,138,240 B (90 B/row, GGUF shard 2) or ~16 GB of level-2 KAR parts (50 B/row) | 16 rows per token | SSD (direct reads) + a bounded row cache |
| MTP draft layer (`data/mtp-rt`) | dense 116,099,072 B + experts 707,788,800 B (802 MiB of VRAM loaded) + draft head 212.9 MiB (106,299-token CJK subset) | VRAM | - |
| QSA KV, INT8 | 1,056 B per cell per layer, 12 QSA layers + draft layer = ~13.7 KB per token: 8K 0.11 GB, 32K 0.45 GB, 128K 1.8 GB, 256K 3.6 GB | the attention window in VRAM | the rest in pinned RAM (`--kv-resident`) |
| prompt (prefill) buffers | Original: borrowed from expert-cache slots (`--prefill auto`); port arena 2.0 / 2.8 / 4.3 GiB at chunk 2048 / 4096 / 8192 | VRAM while a prompt is read | - |
The routed experts are the whole problem: 46.84 GiB against 14.9 GiB of usable VRAM and 23 GiB of WSL RAM.
### VRAM budget (16 GiB card, 14.9 GiB free to CUDA)
Measured (logs of the runs below):
| | Original (`--expert-cache auto`, `--max-context 8192`) | port (Original serve stack, 8K ceiling) |
| --- | --- | --- |
| free before the expert cache | 9.67-9.73 GiB (after dense, native Q5_K head 521 MB, MTP 802 MiB, KV, state) | not printed; KV alone 0.391 GiB + 0.258 GiB prompt stage (262,144-cell geometry, 32K window) |
| reserve | `--vram-reserve-mib` 700 + 218 MiB draft head | `_VRAM_RESERVE_MIB` 700 + `_DECODE_RESERVE_MIB` 1024 (per-request verifier assembly) |
| expert slots | 4,597-4,632 slots, 8.76-8.83 GiB, sized per blob by the profile | 3,133 slots, 6.00 GiB |
| prompt path | borrows the last 1,965 slots (3.72 GiB) during a prompt | borrows the last 1,157 slots |
| left free | 459-461 MiB "with everything loaded" | (nvidia-smi peak 14,195 MiB used of 16,384) |
| decode hit rate (per request) | 48-77 % | 40-53 % of window entries on the GPU |
Every GiB of VRAM is ~520 more cached experts (2.05 MB each) out of 24,576.
### RAM budget (48 GB physical, 23.3 GiB in WSL by default)
| | Original low-RAM resident mode | port before this work | port, laptop profile |
| --- | --- | --- | --- |
| experts | `--resident-experts`: the complement of the GPU cache (~36 GiB) does not fit, so the soft path keeps what fits (MemAvailable - 4 GiB headroom), hottest by the profile, page-locked; the rest through the OS file cache from the GGUF in place | 50 GB copied into RAM (`load_resident_expert_source`, needs MemAvailable >= 58 GB) and page-locked whole | read-only shared mapping of shard 0 (`load_mapped_expert_source`): nothing copied, the OS file cache keeps what is used |
| KAR archive | `--ple-kar`: mapped from the file | 55,295,529,472 B sealed memfd (shmem) for the life of the process | read-only file (`open_read_only_file`): file cache only |
| PLE (GGUF) | `--ple-io direct`: never in RAM, 1M-row (90 MB) cache | not used (KAR PLE only) | not used (KAR PLE only) |
| KV host copy | none at 8K (streaming is off below 64K, and setup turns it off under WSL) | 12 x 276,825,088 B = 3.32 GB pinned (always 262,144 cells) | same: 3.094 GiB pinned |
**Under WSL2 the unmodified Original's resident modes do not engage.** `available_memory_bytes()`
(expert_source.cpp:219) requires the cgroup-v2 path of `/proc/self/cgroup` ("0::/init.scope") to exist unde
`/sys/fs/cgroup`; WSL2 mounts cgroup v2 at `/sys/fs/cgroup/unified` (hybrid layout), so it returns false and
`--resident-experts` / `--resident-budget-gib` fall back to plain mmap with "cannot determine available RAM". With
that check relaxed (2 lines, built as a separate labeled arm, not committed to `engine/strata`) the resident mode
works: "RAM budget 16.83 GiB: 8892 of the 38.07 GiB of experts the GPU cache does not hold", page-locked.
### NVMe
* PLE direct reads: 16 rows per token, one 4 KiB read each, ~64 KB/token: negligible at any decode rate.
* Experts: a miss that is neither in VRAM nor in RAM is a 1.5-2.7 MB read. That is the term that decides decode
speed once the RAM cannot hold the complement.
* The shards are verified once per start by the port (SHA-256 of 83.6 GB) and the KAR archive likewise (55.3 GB).
## Files on the laptop and why
| file | size | needed by | why |
| --- | --- | --- | --- |
| `qwen-iq3-s-l2-v4.kar` + provenance | 55.3 GB | port (KAR PLE), Original `--ple-kar` arm | the compressed PLE source; level 2 is lossy (an experimental arm, not the control) |
| `data/iq3_s` (dense.bin, index, native_experts.txt, tokenizer) | 1.5 GB | Original | its native pack |
| `data/mtp-rt` | 0.8 GB | both | the MTP draft layer |
| `data/expert-profile.bin` | 196,632 B, sha256 `8f59b4aa...6388975baf` | both (VRAM tier ranking, resident budget) | upstream `data/expert-profile.bin` at the pinned Strata commit `d9ab8435`; the imported subtree omits it |
| GGUF shard 1 | 54,817,524,224 B | both, strictly | the routed experts (no non-lossy compressed source exists: the KAR archive's level-2 experts have relative L2 ~0.33 and no quality gate), the dense GGUF projections and the native head |
| GGUF shard 2 | 28,800,138,432 B | both, strictly | Original: `--native` opens every shard of the split (`gguf_split_paths`, generate.cpp:1544) and `--ple-io direct` reads the table from it; port: `Qwen4ExpArtifact::bind` and `KarPleBinding::new` verify both shard digests and the PLE descriptor even when the rows come from KAR |
All model files live on the WSL ext4 disk (`~/laptop/model`, `~/laptop/data`): `/mnt/c` is a 9p mount, far slowe
for mapped and direct reads. Nothing of it is in Git.
## The Original's low-memory modes (engine/strata, unmodified)
From `generate.cpp`, `expert_source.cpp`, `setup.py` and `docs/DETAILS.md`:
| mode | flags | experts in RAM | fits this laptop |
| --- | --- | --- | --- |
| resident arena (default) | none | all 50.3 GB, pinned | no |
| low-RAM mapped | `--mmap-experts` (GGUF in place when the pack has no experts.bin) | OS file cache only | yes |
| low-RAM resident | `--resident-experts` = `--mmap-experts --resident-cpu-experts`, page-locked, 4 GiB headroom, soft | the complement of the GPU cache if it fits, else (#467) what fits, hottest by profile | yes (the "what fits" path) |
| RAM budget | `--resident-budget-gib N` | N GiB, hottest by profile, rest mapped; lookahead page prefetch of the next layer's predicted experts | yes |
| PLE | `--ple-io direct` (default) / `--ple-kar` (KAR-enabled build, experimental) | 90 MB row cache / file cache | yes |
| KV | `--kv int8`, `--kv-resident 32768` from 64K (setup turns streaming off under WSL) | none at 8K | yes |
setup.py's argument set for IQ3_S: `--pack --native SHARD1 --ple-gguf SHARD2 --expert-profile data/expert-profile.bin
--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp DIR --max-context N [--kv int8] [--resident-experts |
--mmap-experts]`. setup.py's table lists IQ3_S at 62 GB of RAM (48 GB: IQ2_XS or Q2_0); for a PC whose RAM cannot hold the
experts it picks the low-RAM resident variant, which is what is measured here.
## What the port lacked for this laptop
The Original serve stack of the port (`docs/original-serve.md`) opened only with server-sized sources:
| mechanism | Original | port before | port now (this branch) |
| --- | --- | --- | --- |
| expert source without a 50 GB copy | `--mmap-experts`, GGUF in place | none: `load_resident_expert_source` copies 50 GB and needs MemAvailable >= 58 GB | `load_mapped_expert_source`: read-only shared mapping of shard 0; `MappedExpertBank` pageable mode (copies staged by the driver, no 50 GB `cuMemHostRegister`) |
| RAM budget / resident complement | `--resident-budget-gib`, `--resident-experts` | none | `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB`: hottest non-VRAM experts page-locked in place (read-only registration of the file pages), same clamp |
| KAR PLE without holding the archive in RAM | `PleTable::open_kar` maps the file | 55.3 GB sealed memfd (shmem) | `InheritedKarArchive::open_read_only_file`: regular read-only file, verified at load |
| PLE direct from the GGUF | `--ple-io direct` | not ported (the Original serve stack needs KAR PLE) | not ported |
| VRAM expert tier sized for 16 GB | `--expert-cache auto` + profile | merged from `claude/expert-residency`, never run on a real model | used here, first real-model run |
| MTP | `--spec 4 --mtp` | present (`--mtp-rt-dir` / pack) | unchanged |
| KV sized by `--max-context` | yes | always 262,144 cells: 3.32 GB pinned host copy + 0.42 GB VRAM window at any ceiling | `LELEKA_LAPTOP_CELLS` (bench only, experimental) |
| sm_86 companion of `qsa_prompt_resolver.ptx` | n/a | stale after the kv-streaming reseal (2 arch_ptx tests failed; the 3080 would load the sm_120 image) | regenerated |
| lookahead page prefetch of predicted experts | `STRATA_LOOKAHEAD` | none | none |
| PCIe share of misses | `--pcie-frac 0.55` over the pinned complement | `_PCIE_FRAC` default 0 | 0 (pageable bank) |
## Results, 2026-10-16 (one laptop, WSL2, n = 6 requests per arm)
Workload: `benchmarks/laptop/prompts.txt` (3 user turns, thinking off, 88 / 83 / 78 tokens, tokenized once with
`chat_tokens` and fed as the same IDs to both engines), 128 new tokens, greedy, each prompt served twice in one
process (pass 0, pass 1), conversation cache off, `--max-context 8192` / ceiling 8192, INT8 KV, spec 4 + MTP
(`data/mtp-rt`), `--spec-min-p 0.5`, expert profile sha256 `8f59b4aa...` , 7 CPU expert workers. Cache state: no
root, so page caches could not be dropped; each arm starts with whatever the previous one left (recorded per arm
in `~/laptop/results/*.cache`). Engine: Original `engine/strata` at this branch, built for sm_86 with CUDA 13.2.86
(`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`); port: branch `claude/laptop-profile`, `--features sm86`, release. Model:
the two IQ3_S shards (sha256 `4c1eb2ce...`, `316b46f3...`, verified on copy) and the level-2 KAR archive
(`536d612c...`). TTFT is measured from sending the request to the first emitted token; decode tok/s is produced
tokens over the decode phase; prefill tok/s is prompt tokens over the prompt phase. VRAM is nvidia-smi's peak fo
the whole GPU; RAM is the process's peak RSS (file-backed pages are reclaimable).
| arm | PLE | experts | decode tok/s mean (median, range) | prefill tok/s mean | TTFT mean (range) | load to ready | peak VRAM | peak RSS (anon / file / shmem) |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Original, `--resident-experts` (falls back to mmap under WSL2, see above) | GGUF direct | 4,632 VRAM slots + mmap | 5.64 (5.61, 4.45-7.12) | 8.7 | 10.0 s (8.0-12.0) | 34 s | 15,093 MiB | 22.4 GB (2.3 / 19.8 / 1.1) |
| Original, same, KAR PLE (`--ple-kar ... --ple-kar-gpu-cache-mib 64`) | KAR L2 | same | 8.15 (7.45, 6.75-10.17) | 12.4 | 7.2 s (4.6-9.1) | 150 s | 15,111 MiB | 22.9 GB (2.0 / 22.3 / 1.1) |
| Original + WSL cgroup fix (diagnostic arm), resident 16.83 GiB page-locked, KAR PLE | KAR L2 | 4,597 VRAM + 16.8 GiB RAM + mmap | 10.61 (10.93, 7.00-14.44) | 18.6 | 5.0 s (3.6-8.4) | 161 s | 15,111 MiB | 22.2 GB (1.9 / 15.1 / 18.1); MemAvailable fell to 2.2 GB |
| **port**, mapped experts + VRAM tier (profile, auto) | KAR L2 | 3,133 VRAM slots + mmap | **2.70** (2.63, 2.15-3.68) | **3.1** | **28.4 s** (20.6-36.6) | 212 s | 14,195 MiB | 20.5 GB (2.1 / 17.8 / 3.9) |
| port, adaptive swaps off, decode reserve 512 MiB | KAR L2 | 3,397 VRAM slots + mmap | 2.62 (2.67, 1.81-3.13) | 3.5 | 25.2 s (21.0-30.7) | 193 s | 14,709 MiB | 20.3 GB |
| port, + resident budget 16 GiB (clamped to 11.42 GiB page-locked) | KAR L2 | 3,133 VRAM + 11.4 GiB RAM + mmap | 2.39 (2.27, 1.48-3.44) | 3.1 | 30.2 s (21.2-46.9) | 214 s | 14,195 MiB | 14.0 GB |
The paired comparison is row 2 (unmodified Original, the mode it actually runs in under WSL2) against row 4 (port):
same prompts, same PLE source, same profile, same VRAM-tier policy, greedy. **The port is 3.0x slower in decode
(2.70 vs 8.15 tok/s), 4.0x slower in prefill (3.1 vs 12.4 tok/s) and 3.9x later to the first token (28.4 vs 7.2
s), with 1.5 GB less RAM, 0.9 GB less VRAM and 1,500 fewer VRAM expert slots.** Greedy outputs of the two agree on
the first 47 / 43 / 57 tokens of the three prompts and then diverge (GPU and CPU experts round differently and the
two place different experts on the GPU; the Original itself diverges from its GGUF-PLE run after 44 / 42 / 128
tokens). This is not a quality gate. Rows 1 and 2 differ in the PLE source and in page-cache state at the start;
they are not a PLE A/B.
Where the port's time goes (traced run, `LELEKA_BRINGUP_TRACE=1`, 3 prompts x 48 tokens): every decode millisecond
is inside `run_window` (62 windows, 62.8 s, 1,014 ms mean per verify window; begin_adaptation 13 ms, draft 10 ms,
everything else < 1 ms). The Original spends ~0.35-0.45 s per round on the same prompts. In the window, the
routed-expert CPU tier (`CpuExpertPool::run_entries`) prepares every job on the calling thread
(`prepare_scoped` copies the expert's three matrices out of the bank, i.e. page faults on the mapped shard, serially)
before the workers compute; the Original's pool reads the blobs where they are, fetches a layer's missing experts
on 8 threads and prefetches the next layer's predicted experts. Neither the resident budget nor turning adaptive
swaps off changed the port's rate beyond the run-to-run spread, which points at that path rather than at residency.
The prompt path likewise copies each borrowed expert with a host-blocking pageable `cuMemcpyHtoDAsync` on one
thread, where the Original stages through pinned buffers with helper threads.
## Recommendations and open items
1. Port next (largest measured gap): parallel, zero-copy CPU expert preparation over the mapped bank (literal
`expert_pool_dispatch_multi` + `FileExpertSource` fetch threads and routing lookahead), then pinned staging fo
the prompt copy ring. Re-measure with the same harness.
2. VRAM: the port leaves ~1,500 fewer expert slots than the Original; the 1 GiB per-request verifier reserve, the
262,144-cell KV geometry (3.1 GiB pinned host + 0.65 GiB VRAM at an 8K ceiling) and the verifier being assembled
per request are the candidates (`LELEKA_LAPTOP_CELLS` exists in the bench for an experiment; not run here).
3. WSL memory: with the default 50 % (23.3 GiB) the Original's resident mode (fixed) left 2.2 GB available. A
`%UserProfile%\.wslconfig` with `[wsl2] memory=40GB swap=8GB` would let the complement grow toward ~30 GiB of
the 38 GiB the GPU does not hold. Needs `wsl --shutdown`; not applied.
4. The Original's `available_memory_bytes()` hybrid-cgroup bug (WSL2) is worth an upstream-style fix in the fork;
this branch does not modify `engine/strata`.
5. Native Windows would give the Original the full 47 GiB and its Windows paths (PrefetchVirtualMemory,
working-set trimming); it needs a Windows CUDA toolkit install (not present), so it was not tried.
6. Statistics: n = 6 per arm (2 passes x 3 prompts), single process per arm, uncontrolled page-cache state; the
charter's paired-A/B requirements (>= 30 repeats, CIs) are not met. Treat the ratios as indicative.
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Sample one process's memory and the GPU's VRAM once a second until it exits (laptop profile benches).
# monitor.sh PID OUT.tsv
# Columns: unix time, VRAM used MiB (nvidia-smi, whole GPU), VmRSS, RssAnon, RssFile, RssShmem, VmLck, VmPin (MiB),
# MemAvailable (MiB, whole VM). Prints the peaks when the process is gone.
set -u
pid="$1"; out="$2"
printf 't\tvram\trss\tanon\tfile\tshmem\tlck\tpin\tavail\n' > "$out"
field() { awk -v k="$1:" '$1==k {printf "%d", $2/1024}' "/proc/$pid/status" 2>/dev/null; }
while kill -0 "$pid" 2>/dev/null; do
vram=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | head -1)
avail=$(awk '$1=="MemAvailable:" {printf "%d", $2/1024}' /proc/meminfo)
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%s)" "${vram:-0}" "$(field VmRSS)" "$(field RssAnon)" \
"$(field RssFile)" "$(field RssShmem)" "$(field VmLck)" "$(field VmPin)" "$avail" >> "$out"
sleep 1
done
awk -F'\t' 'NR>1 {for (i=2;i<=9;i++) if ($i+0>m[i]) m[i]=$i+0; if (min==""||$9+0<min) min=$9+0}
END {printf "peak MiB: vram=%d rss=%d anon=%d file=%d shmem=%d lck=%d pin=%d; min MemAvailable=%d\n", m[2],m[3],m[4],m[5],m[6],m[7],m[8],min}' "$out"
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Run the unmodified Original (`strata generate --serve`) on the laptop-profile prompts and record its timings,
# outputs and memory (docs/laptop-profile.md).
# original_bench.sh LABEL [extra engine args...]
# Environment: STRATA (engine binary), MODEL_DIR (the two GGUF shards), PACK (data/iq3_s), MTP (data/mtp-rt),
# PROFILE (expert-profile.bin), PROMPTS (one comma-separated token-ID line per prompt), OUT (results dir),
# MAX_NEW (128), REPEAT (2), MAX_CONTEXT (8192).
# The default arguments are setup.py's for IQ3_S (`--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5
# --mtp`, `--kv int8`), with the conversation cache off so repeats read the whole prompt again (the port's stack
# has it off by default too). The low-RAM mode (`--resident-experts`, `--mmap-experts`, ...) is passed as extra args.
# Requests are sent one at a time; TTFT is measured here from sending `GEN` to the first `T` line.
set -uo pipefail
label="$1"; shift
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
: "${STRATA:?}" "${MODEL_DIR:?}" "${PACK:?}" "${MTP:?}" "${PROFILE:?}" "${PROMPTS:?}" "${OUT:?}"
MAX_NEW="${MAX_NEW:-128}"; REPEAT="${REPEAT:-2}"; MAX_CONTEXT="${MAX_CONTEXT:-8192}"
mkdir -p "$OUT"
shard1="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"
shard2="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"
args=(--serve --pack "$PACK" --native "$shard1" --ple-gguf "$shard2" --expert-profile "$PROFILE"
--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp "$MTP" --max-context "$MAX_CONTEXT"
--kv int8 --prompt-cache 0 "$@")
echo "strata ${args[*]}" > "$OUT/$label.cmd"
mapfile -t prompts < <(grep -v '^[[:space:]]*$' "$PROMPTS")
t_start=$EPOCHREALTIME
coproc ENGINE { exec "$STRATA" "${args[@]}" 2> "$OUT/$label.stderr"; }
pid=$ENGINE_PID
bash "$here/monitor.sh" "$pid" "$OUT/$label.mem.tsv" > "$OUT/$label.mem.peak" &
mon=$!
: > "$OUT/$label.stdout"
ready=""
while IFS= read -r line <&"${ENGINE[0]}"; do
echo "$line" >> "$OUT/$label.stdout"
if [[ "$line" == READY* ]]; then ready=1; break; fi
done
if [[ -z "$ready" ]]; then echo "engine did not become ready"; tail -20 "$OUT/$label.stderr"; exit 1; fi
echo "load_s=$(echo "$EPOCHREALTIME - $t_start" | bc)" > "$OUT/$label.timing"
for ((pass = 0; pass < REPEAT; pass++)); do
for i in "${!prompts[@]}"; do
t0=$EPOCHREALTIME; first=""; toks=()
echo "GEN $MAX_NEW ${prompts[$i]}" >&"${ENGINE[1]}"
while IFS= read -r line <&"${ENGINE[0]}"; do
echo "$line" >> "$OUT/$label.stdout"
case "$line" in
T\ *) [[ -z "$first" ]] && first=$EPOCHREALTIME; toks+=("${line#T }") ;;
DONE*) break ;;
ERR*) echo "p$((i + 1)) pass=$pass: $line"; break ;;
esac
done
t1=$EPOCHREALTIME
ttft=$(echo "(${first:-$t1} - $t0) * 1000" | bc)
total=$(echo "($t1 - $t0) * 1000" | bc)
# DONE produced prompt prompt_ms decode_ms finish accepted offered resume hits look ram_reads file_reads file_MB
read -r _ produced n prompt_ms decode_ms finish acc off resume hits look ram files fmb <<< "$line"
printf 'p%d pass=%d prompt=%s produced=%s ttft_ms=%.1f prompt_ms=%s decode_ms=%s total_ms=%.1f prefill_tok_s=%.1f decode_tok_s=%.2f accept=%s/%s hits=%s/%s ram=%s files=%s file_MB=%s finish=%s\n' \
$((i + 1)) "$pass" "$n" "$produced" "$ttft" "$prompt_ms" "$decode_ms" "$total" \
"$(echo "$n * 1000 / $prompt_ms" | bc -l)" "$(echo "$produced * 1000 / $decode_ms" | bc -l)" \
"$acc" "$off" "$hits" "$look" "$ram" "$files" "$fmb" "$finish" | tee -a "$OUT/$label.timing"
if [[ $pass -eq 0 ]]; then
(IFS=,; echo "output p$((i + 1)): ${toks[*]}") >> "$OUT/$label.outputs"
fi
done
done
echo QUIT >&"${ENGINE[1]}"
wait "$pid"; rc=$?
wait "$mon" || true
echo "exit=$rc" >> "$OUT/$label.mem.peak"
cat "$OUT/$label.mem.peak"
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Run the port's Original serve stack (laptop profile) on the same pre-tokenized prompts as original_bench.sh.
# port_bench.sh LABEL
# Environment: TEST_BIN (the built leleka-runtime test executable, `cargo test --release -p leleka-runtime
# --features sm86 --lib --no-run`), MODEL_DIR (the two GGUF shards), KAR (read-only archive file) and
# KAR_PROVENANCE, MTP (data/mtp-rt), MTP_STAGING (private 0700 dir), PROMPTS, OUT, CUBLAS12_LIB (dir with
# libcublas.so.12). Every LELEKA_* switch of backend_original_serve_laptop.rs passes through (experts mapped or
# resident, the VRAM tier's LELEKA_ORIGINAL_SERVE_EXPERT_*, MAX_NEW, REPEAT, CPU_WORKERS, ...).
set -uo pipefail
label="$1"; shift
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
: "${TEST_BIN:?}" "${MODEL_DIR:?}" "${KAR:?}" "${KAR_PROVENANCE:?}" "${MTP:?}" "${MTP_STAGING:?}" "${PROMPTS:?}" "${OUT:?}"
mkdir -p "$OUT"
mkdir -p -m 700 "$MTP_STAGING"
export LD_LIBRARY_PATH="${CUBLAS12_LIB:-$(ls -d "$HOME"/cublas-12.9.1.4/x/*/lib | head -1)}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export LELEKA_LAPTOP_BENCH=yes
export LELEKA_STRA169_IQ3S_SHARD0="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"
export LELEKA_STRA169_IQ3S_SHARD1="$MODEL_DIR/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"
export LELEKA_LAPTOP_KAR_FILE="$KAR" LELEKA_STRA169_KAR_PROVENANCE="$KAR_PROVENANCE"
export LELEKA_STRA169_MTP_PACK="$MTP" LELEKA_STRA169_MTP_STAGING="$MTP_STAGING"
export LELEKA_LAPTOP_PROMPT_IDS="$PROMPTS"
env | grep -E '^LELEKA_' | sort > "$OUT/$label.env"
"$TEST_BIN" --ignored --exact backend::original_serve_laptop::original_serve_laptop_bench --nocapture --test-threads 1 \
> "$OUT/$label.stdout" 2> "$OUT/$label.stderr" &
pid=$!
bash "$here/monitor.sh" "$pid" "$OUT/$label.mem.tsv" > "$OUT/$label.mem.peak" &
mon=$!
wait "$pid"; rc=$?
wait "$mon" || true
echo "exit=$rc" >> "$OUT/$label.mem.peak"
grep -hE '^LAPTOP (load|config|request|tier)' "$OUT/$label.stderr" "$OUT/$label.stdout" | sed -E 's/ (VmRSS|VmHWM|RssAnon|RssFile|RssShmem|VmLck|VmPin)=/ \1=/g' | tee "$OUT/$label.timing"
grep -hE '^LAPTOP output' "$OUT/$label.stderr" "$OUT/$label.stdout" | sed 's/^LAPTOP //' > "$OUT/$label.outputs"
cat "$OUT/$label.mem.peak"