Files
leleka/crates/context/src/geometry.rs
T
Pavlo RatushnyiandClaude Opus 5.5 70f057578f feat(serve): --kv / --kv-resident on the Original serve stack, KV footprint, long-context smoke
StackConfig gains kv_format (int8 only; fp16, q4_0, k8v4 and keyless are
refused: no sealed owners) and kv_resident (default 32768 = the window every
earlier build used; raised to 20480; 0 = the whole context). open() fixes the
process window (qsa_set_kv_resident) before any QSA owner and prints the
streamed KV footprint (leleka-context KvStreamFootprint: VRAM, prompt stage,
pinned host). leleka-inference takes --kv and --kv-resident.
original_serve_long_context_streamed_kv_smoke (ignored, env-gated): one greedy
request over a 40K-token passcode prompt with a 20480-cell window.
serving_context cross-checks resident pages against the Original kv_plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:47:16 +02:00

410 lines
18 KiB
Rust

//! Byte geometry of the fixed native QSA stack as a function of the context cell count.
//!
//! The Original sizes every context-dependent buffer from `max_cells` (`qsa_state_bytes`,
//! `session_bytes`). The Rust source-port froze those sizes as literals for `262144` cells
//! (`QSA_PROMPT_*`, `qsa_prompt_host_ffi::BYTES`, `NativeQsaResources::CELLS`, ...). Every one of those
//! literals is linear in the cell count; this module derives them from it. At [`TRAINED_CELLS`] each value
//! equals the frozen literal (asserted in the tests below with the literal numbers copied from the sources),
//! so the default configuration is unchanged. Nothing here claims a layout is *qualified* at a larger size:
//! only the arithmetic is.
//!
//! One QSA page is [`PAGE_CELLS`] cells. Per cell and QSA layer the INT8 KV store is
//! `K codes 512 B + V codes 512 B + K scales 16 B + V scales 16 B = 1056 B` (`kv_q8_bytes_per_cell`).
use std::fmt;
/// The context the model was trained over and the frozen default geometry.
pub const TRAINED_CELLS: usize = 262_144;
/// The largest context the charter requires (`1 x 512K`).
pub const MAX_CELLS: usize = 524_288;
/// Cells per KV page (`qsa_real_shapes().page_size`).
pub const PAGE_CELLS: usize = 4;
/// INT8 KV bytes per cell and layer: codes for K and V (2 heads x 256) plus four f16 scales per head pair.
pub const KV_CELL_BYTES: usize = 1056;
/// Bytes per cell of each of the four staged runs: K codes, V codes, K scales, V scales.
pub const RUN_CELL_BYTES: [usize; 4] = [512, 512, 16, 16];
/// Four 256 byte cursor alignment allowances of the mapped host allocation.
pub const MAPPED_ALIGNMENT_BYTES: usize = 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GeometryError {
/// `cells` must be a positive multiple of [`PAGE_CELLS`] no larger than [`MAX_CELLS`].
Cells(usize),
/// A `--kv-resident` cell count that gives fewer resident pages than the resolve block
/// ([`RESOLVE_BLOCK`]) or more cells than [`MAX_CELLS`].
Resident(usize),
Overflow,
}
impl fmt::Display for GeometryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Cells(n) => write!(
f,
"context of {n} cells must be a positive multiple of {PAGE_CELLS} and at most {MAX_CELLS}"
),
Self::Resident(n) => write!(
f,
"a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)"
),
Self::Overflow => f.write_str("geometry arithmetic overflowed"),
}
}
}
impl std::error::Error for GeometryError {}
type R<T> = Result<T, GeometryError>;
fn mul(a: usize, b: usize) -> R<usize> {
a.checked_mul(b).ok_or(GeometryError::Overflow)
}
fn add(a: usize, b: usize) -> R<usize> {
a.checked_add(b).ok_or(GeometryError::Overflow)
}
/// Sizes derived from one context cell count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QsaGeometry {
cells: usize,
}
impl QsaGeometry {
/// The frozen default (`262144` cells).
pub const TRAINED: Self = Self {
cells: TRAINED_CELLS,
};
pub fn new(cells: usize) -> R<Self> {
if cells == 0 || !cells.is_multiple_of(PAGE_CELLS) || cells > MAX_CELLS {
return Err(GeometryError::Cells(cells));
}
Ok(Self { cells })
}
pub const fn cells(self) -> usize {
self.cells
}
/// KV pages (and page-table entries): `cells / 4` (`65536` at the trained size).
pub const fn pages(self) -> usize {
self.cells / PAGE_CELLS
}
/// Pooled index key rows kept per layer: one per 4-cell block plus the spare (`65537`).
pub const fn pooled_rows(self) -> usize {
self.pages() + 1
}
/// Score row stride of the index selection: blocks plus the tail and spare (`65538`).
pub const fn max_blocks(self) -> usize {
self.pages() + 2
}
/// The identity page table, one `i32` per page: `4 * pages == cells` bytes (`262144`).
pub const fn page_table_bytes(self) -> usize {
self.pages() * 4
}
/// Complete KV payload of one layer in the canonical host image (`276_824_064` at the trained size).
pub fn host_payload_bytes(self) -> R<usize> {
mul(self.cells, KV_CELL_BYTES)
}
/// Mapped host allocation of one layer: payload plus alignment allowances (`276_825_088`).
pub fn mapped_host_bytes(self) -> R<usize> {
add(self.host_payload_bytes()?, MAPPED_ALIGNMENT_BYTES)
}
/// Byte length of the four runs of the full staging pool (`[134217728, 134217728, 4194304, 4194304]`).
pub fn stage_runs(self) -> R<[usize; 4]> {
Ok([
mul(self.cells, RUN_CELL_BYTES[0])?,
mul(self.cells, RUN_CELL_BYTES[1])?,
mul(self.cells, RUN_CELL_BYTES[2])?,
mul(self.cells, RUN_CELL_BYTES[3])?,
])
}
/// Run offsets inside the mapped allocation (`[0, 134217728, 268435456, 272629760]`).
pub fn stage_offsets(self) -> R<[usize; 4]> {
let r = self.stage_runs()?;
Ok([0, r[0], add(r[0], r[1])?, add(add(r[0], r[1])?, r[2])?])
}
/// Device staging pool: four runs, identity table and a 4 byte status word (`277_086_212`).
pub fn stage_bytes(self) -> R<usize> {
let r = self.stage_runs()?;
add(
add(
add(add(r[0], r[1])?, add(r[2], r[3])?)?,
self.page_table_bytes(),
)?,
4,
)
}
/// Device bytes of one layer's resident pool: the fixed 8192-page resident runs, the page table and
/// `map_bytes` of resolver state. `34_865_152 + map_bytes` at the trained size.
pub fn resident_bytes(self, map_bytes: usize) -> R<usize> {
add(
add(RESIDENT_RUNS_BYTES, self.page_table_bytes())?,
map_bytes,
)
}
/// Resident pages (VRAM slots) of one streamed QSA layer for `--kv-resident resident_cells`
/// (`layer.cpp::kv_plan`, `mode == 1`): `ceil(max(resident_cells, 20480) / 4)`. `0` keeps every page of
/// the context resident (the Original's `mode == 0`; here the streaming machinery stays on and simply
/// never evicts). Unlike the Original a window at least as large as the context is not clamped to it:
/// the slots past the context stay unused (the default 32768 cells at a small context).
pub fn resident_pages_for(self, resident_cells: usize) -> R<usize> {
if resident_cells > MAX_CELLS {
return Err(GeometryError::Resident(resident_cells));
}
let pages = if resident_cells == 0 {
self.pages()
} else {
resident_cells.max(KV_RESIDENT_MIN_CELLS).div_ceil(PAGE_CELLS)
};
if pages < RESOLVE_BLOCK {
return Err(GeometryError::Resident(resident_cells));
}
Ok(pages)
}
/// Device bytes of one layer's resident pool with `slots` resident pages: the four resident runs, the
/// context page table and `map_bytes` of resolver state.
pub fn resident_bytes_with(self, slots: usize, map_bytes: usize) -> R<usize> {
let runs = resident_runs(slots)?;
add(
add(add(add(runs[0], runs[1])?, add(runs[2], runs[3])?)?, self.page_table_bytes())?,
map_bytes,
)
}
/// Canonical host metadata bound of one layer (`NativeQsaResources::CANONICAL_METADATA`).
pub fn canonical_metadata_bytes(self) -> R<usize> {
add(mul(self.pages(), 160)?, 4096)
}
/// Index key and tail image of one layer (`NativeQsaResources::INDEX_IMAGE`).
pub fn index_image_bytes(self) -> R<usize> {
add(mul(mul(add(self.pages(), 1)?, 128)?, 4)?, 2048)
}
/// Bytes of the host cos plus sin table for `n_rot` rotated dimensions.
pub fn rope_table_bytes(self, n_rot: usize) -> R<usize> {
mul(mul(self.cells, n_rot / 2)?, 8)
}
/// Whether `end` positions fit (`end <= cells`).
pub const fn admits_end(self, end: usize) -> bool {
end <= self.cells
}
}
/// What the INT8 KV of the twelve streamed QSA layers costs for one context and resident window (the Rust
/// owners' actual sizes: `QsaPromptKv` resident pools, page table and resolver state in VRAM, the pinned
/// mapped host copy, and the one model-owned staging pool of the prompt path). A Leleka extension next to
/// `memory_plan` (whose plan.hpp arithmetic charges the whole KV to VRAM and stays the admission rule).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KvStreamFootprint {
pub cells: usize,
pub resident_cells: usize,
/// Resident pages (VRAM slots) of each layer.
pub resident_pages: usize,
/// VRAM of one layer: resident runs + page table + resolver state.
pub layer_vram_bytes: usize,
/// VRAM of the twelve layers.
pub vram_bytes: usize,
/// Pinned, device-mapped host memory of the twelve host copies.
pub pinned_host_bytes: usize,
/// The prompt path's staging pool (one per model, VRAM).
pub stage_bytes: usize,
}
/// QSA layers of the served model.
pub const QSA_LAYERS: usize = 12;
impl QsaGeometry {
/// [`KvStreamFootprint`] of this context with `--kv-resident resident_cells`.
pub fn kv_stream_footprint(self, resident_cells: usize) -> R<KvStreamFootprint> {
let resident_pages = self.resident_pages_for(resident_cells)?;
let layer_vram_bytes = self.resident_bytes_with(resident_pages, stream_map_bytes(resident_pages)?)?;
Ok(KvStreamFootprint {
cells: self.cells,
resident_cells,
resident_pages,
layer_vram_bytes,
vram_bytes: mul(layer_vram_bytes, QSA_LAYERS)?,
pinned_host_bytes: mul(self.mapped_host_bytes()?, QSA_LAYERS)?,
stage_bytes: self.stage_bytes()?,
})
}
}
impl fmt::Display for KvStreamFootprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let gib = |b: usize| b as f64 / (1u64 << 30) as f64;
write!(
f,
"kv int8 context={} resident={} cells ({} pages/layer) vram={:.3} GiB (+{:.3} GiB prompt stage) pinned-host={:.3} GiB",
self.cells,
self.resident_pages * PAGE_CELLS,
self.resident_pages,
gib(self.vram_bytes),
gib(self.stage_bytes),
gib(self.pinned_host_bytes)
)
}
}
/// The default resident device runs hold `RESIDENT_PAGES` pages regardless of the context (the "actual 32K
/// resident pool", `--kv-resident 32768`): `[16777216, 16777216, 524288, 524288]` bytes.
pub const RESIDENT_PAGES: usize = 8192;
/// `qsa_kv_resident_min()`: the smallest resident window the Original streams with (one verify window's
/// selections must fit at once).
pub const KV_RESIDENT_MIN_CELLS: usize = 20_480;
/// The resident window of the default configuration (and of the production profile `--kv-resident 32768`).
pub const KV_RESIDENT_DEFAULT_CELLS: usize = RESIDENT_PAGES * PAGE_CELLS;
/// Threads of `kv_stream.cu`'s resolve block: with fewer slots one clock-sweep step could take a slot twice.
pub const RESOLVE_BLOCK: usize = 1024;
/// `kKvCtlInts` of `kv_stream.hpp`.
pub const KV_CTL_INTS: usize = 16;
/// The four resident runs (K codes, V codes, K scales, V scales) of `slots` resident pages.
pub fn resident_runs(slots: usize) -> R<[usize; 4]> {
let page = |run: usize| mul(slots, mul(RUN_CELL_BYTES[run], PAGE_CELLS)?);
Ok([page(0)?, page(1)?, page(2)?, page(3)?])
}
/// `kv_stream_map_bytes(n_slots)`: five per-slot `i32` arrays (slot block, stamp, reference bit, miss block,
/// miss slot) and the control block (`163_904` at 8192 slots).
pub fn stream_map_bytes(slots: usize) -> R<usize> {
add(mul(mul(slots, 4)?, 5)?, KV_CTL_INTS * 4)
}
pub const RESIDENT_RUNS: [usize; 4] = [16_777_216, 16_777_216, 524_288, 524_288];
pub const RESIDENT_RUNS_BYTES: usize = 34_603_008;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trained_geometry_reproduces_every_frozen_literal() {
let g = QsaGeometry::TRAINED;
assert_eq!(g.cells(), 262_144);
assert_eq!(g.pages(), 65_536);
assert_eq!(g.page_table_bytes(), 262_144);
assert_eq!(g.pooled_rows(), 65_537); // qsa_prompt_index SIZES[0] = 65537 * 128 * 4
assert_eq!(g.max_blocks(), 65_538); // qsa_prompt_index MAX_BLOCKS
assert_eq!(g.host_payload_bytes(), Ok(276_824_064)); // QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES
assert_eq!(g.mapped_host_bytes(), Ok(276_825_088)); // QSA_PROMPT_MAPPED_HOST_BYTES, host BYTES
assert_eq!(
g.stage_runs(),
Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304])
);
assert_eq!(
g.stage_offsets(),
Ok([0, 134_217_728, 268_435_456, 272_629_760])
);
assert_eq!(g.stage_bytes(), Ok(277_086_212)); // QSA_PROMPT_STAGE_BYTES
assert_eq!(g.resident_bytes(0), Ok(34_865_152)); // QSA_PROMPT_RESIDENT_BYTES - MAP_BYTES
assert_eq!(g.canonical_metadata_bytes(), Ok(65_536 * 160 + 4096));
assert_eq!(g.index_image_bytes(), Ok((65_536 + 1) * 128 * 4 + 2048));
assert_eq!(RESIDENT_RUNS.iter().sum::<usize>(), RESIDENT_RUNS_BYTES);
assert_eq!(RESIDENT_RUNS[0], RESIDENT_PAGES * 2048);
assert_eq!(RESIDENT_RUNS[2], RESIDENT_PAGES * 64);
assert_eq!(g.rope_table_bytes(64), Ok(67_108_864));
}
#[test]
fn resident_window_follows_kv_plan_and_reproduces_the_frozen_pool_at_the_default() {
let g = QsaGeometry::TRAINED;
assert_eq!(g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), Ok(RESIDENT_PAGES));
assert_eq!(resident_runs(RESIDENT_PAGES), Ok(RESIDENT_RUNS));
assert_eq!(stream_map_bytes(RESIDENT_PAGES), Ok(163_904));
assert_eq!(
g.resident_bytes_with(RESIDENT_PAGES, 163_904),
g.resident_bytes(163_904)
);
// max(resident, qsa_kv_resident_min()) rounded up to whole pages
assert_eq!(g.resident_pages_for(1), Ok(5120));
assert_eq!(g.resident_pages_for(20_480), Ok(5120));
assert_eq!(g.resident_pages_for(20_481), Ok(5121));
// 0: the whole context resident
assert_eq!(g.resident_pages_for(0), Ok(65_536));
assert_eq!(
QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0),
Ok(131_072)
);
// a tiny context cannot be fully resident with fewer slots than the resolve block
assert_eq!(
QsaGeometry::new(1024).unwrap().resident_pages_for(0),
Err(GeometryError::Resident(0))
);
assert_eq!(
g.resident_pages_for(MAX_CELLS + 4),
Err(GeometryError::Resident(MAX_CELLS + 4))
);
// production profile: 12 layers x (32768 cells x 1056 B) of VRAM KV
assert_eq!(
resident_runs(RESIDENT_PAGES).unwrap().iter().sum::<usize>(),
32_768 * KV_CELL_BYTES
);
}
#[test]
fn production_profile_footprint() {
// --max-context 262144 --kv int8 --kv-resident 32768 (the default here)
let f = QsaGeometry::TRAINED.kv_stream_footprint(32_768).unwrap();
assert_eq!(f.resident_pages, 8192);
assert_eq!(f.layer_vram_bytes, 34_603_008 + 262_144 + 163_904);
assert_eq!(f.vram_bytes, 12 * 35_029_056);
assert_eq!(f.pinned_host_bytes, 12 * 276_825_088);
assert_eq!(f.stage_bytes, 277_086_212);
// the smallest window frees 12 x 3072 pages x 4224 B of VRAM for expert slots
let small = QsaGeometry::TRAINED.kv_stream_footprint(20_480).unwrap();
assert_eq!(f.vram_bytes - small.vram_bytes, 12 * 3072 * (4224 + 20));
assert!(f.to_string().starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)"));
}
#[test]
fn run_cell_bytes_are_the_original_kv_cell() {
assert_eq!(RUN_CELL_BYTES.iter().sum::<usize>(), KV_CELL_BYTES);
// PAGE bytes of the host image: a page of 4 cells
assert_eq!(PAGE_CELLS * KV_CELL_BYTES, 4224);
}
#[test]
fn charter_512k_scales_every_cell_linear_size_by_exactly_two() {
let a = QsaGeometry::TRAINED;
let b = QsaGeometry::new(MAX_CELLS).unwrap();
assert_eq!(b.pages(), 131_072);
assert_eq!(b.page_table_bytes(), 524_288);
assert_eq!(
b.host_payload_bytes().unwrap(),
2 * a.host_payload_bytes().unwrap()
);
assert_eq!(b.mapped_host_bytes(), Ok(553_649_152));
assert_eq!(
b.stage_runs(),
Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608])
);
assert_eq!(
b.stage_offsets(),
Ok([0, 268_435_456, 536_870_912, 545_259_520])
);
// staging pool: runs + table + status
assert_eq!(b.stage_bytes(), Ok(2 * 276_824_064 + 524_288 + 4));
// the resident runs do not grow, only the table does
assert_eq!(b.resident_bytes(0), Ok(RESIDENT_RUNS_BYTES + 524_288));
assert_eq!(b.rope_table_bytes(64), Ok(134_217_728));
// 12 layers of mapped host memory (NativeQsaResources::mapped)
assert_eq!(12 * b.mapped_host_bytes().unwrap(), 6_643_789_824);
}
#[test]
fn invalid_cell_counts_are_refused() {
for n in [0, 1, 3, 262_145, MAX_CELLS + 4] {
assert_eq!(QsaGeometry::new(n), Err(GeometryError::Cells(n)));
}
assert!(QsaGeometry::new(4).is_ok());
assert!(QsaGeometry::new(393_216).is_ok());
}
#[test]
fn boundary_positions_against_the_cell_count() {
for (cells, last, one_past) in [(262_144, 262_143, 262_144), (524_288, 524_287, 524_288)] {
let g = QsaGeometry::new(cells).unwrap();
assert!(g.admits_end(last + 1), "position {last} is the last cell");
assert!(!g.admits_end(one_past + 1), "position {one_past} is out");
}
}
}