Files
leleka/crates/context/src/geometry.rs
T

265 lines
12 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,
concat!(
"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;