refactor: move pure rope/plan/policy modules into leleka-context, add cell geometry

The source-port runtime no longer builds on macOS, so the pure arithmetic and its
golden tests live in a platform-independent crate shared by the driver and runtime.
leleka_runtime::{rope_scaling,memory_plan,context_policy} stay as re-exports.
geometry.rs derives every frozen 262144-cell byte literal from the cell count.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:50:09 +02:00
co-authored by Claude Sonnet 5.5
parent 9d581c441b
commit e69c3e66d4
18 changed files with 277 additions and 7 deletions
Generated
+8
View File
@@ -1007,6 +1007,13 @@ dependencies = [
name = "leleka-backend-api"
version = "0.1.0"
[[package]]
name = "leleka-context"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "leleka-cuda-driver"
version = "0.1.0"
@@ -1042,6 +1049,7 @@ name = "leleka-runtime"
version = "0.1.0"
dependencies = [
"leleka-backend-api",
"leleka-context",
"leleka-cuda-driver",
"leleka-model-format",
"leleka-native-cpu-expert",
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "control-plane", "desktop-core"]
[workspace.package]
edition = "2024"
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "leleka-context"
version = "0.1.0"
description = "Pure serving-context policy: RoPE scaling tables, memory admission arithmetic, cell geometry"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
+236
View File
@@ -0,0 +1,236 @@
//! 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),
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::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
}
/// 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,
)
}
/// 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
}
}
/// The resident device runs hold `RESIDENT_PAGES` pages regardless of the context (the "actual 32K resident
/// pool"): `[16777216, 16777216, 524288, 524288]` bytes.
pub const RESIDENT_PAGES: usize = 8192;
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.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 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");
}
}
}
+14
View File
@@ -0,0 +1,14 @@
//! Pure (no I/O, no unsafe, no GPU) serving-context policy shared by the CUDA driver and the runtime.
//!
//! - [`rope_scaling`]: linear/YaRN scaling and the host cos/sin table builder (port of `rope_scaling.hpp`,
//! `rope.cu`).
//! - [`memory_plan`]: port of `plan.hpp` memory admission and the per-format KV byte costs.
//! - [`context_policy`]: effective context/slot/rope configuration from a request, or a refusal.
//! - [`geometry`]: every byte size of the fixed native QSA stack as a function of the context cell count.
//!
//! The crate builds on every platform so the arithmetic can be tested on a machine without CUDA.
pub mod context_policy;
pub mod geometry;
pub mod memory_plan;
pub mod rope_scaling;
@@ -11,11 +11,11 @@
//! Memory plan: the C++ side is the unmodified `strata-plan` CLI; stdout/stderr text is compared exactly.
#![allow(clippy::too_many_lines)]
use leleka_runtime::memory_plan::{
use leleka_context::memory_plan::{
Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan,
make_plan_with_format, state_bytes,
};
use leleka_runtime::rope_scaling::{
use leleka_context::rope_scaling::{
RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle,
};
use serde_json::Value;
+1
View File
@@ -12,6 +12,7 @@ leleka-backend-api = { path = "../backend-api" }
leleka-tokenizer = { path = "../tokenizer" }
leleka-model-format = { path = "../model-format" }
leleka-quant-core = { path = "../quant-core" }
leleka-context = { path = "../context" }
leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver"] }
[target.'cfg(target_os = "linux")'.dependencies]
+1 -3
View File
@@ -1,9 +1,7 @@
//! Independent Qwen runtime. CUDA state stays inside its dedicated owner thread.
pub mod backend;
pub mod context_policy;
pub mod memory_plan;
pub mod rope_scaling;
pub use leleka_context::{context_policy, memory_plan, rope_scaling};
pub use backend::spawn_backend_observed_native_integer_iq3_windowed256_retained_gr;
pub use backend::spawn_backend_observed_native_resident_mmq;