diff --git a/Cargo.lock b/Cargo.lock index c417adb5..ddc52870 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index 9eb80476..79d30f55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/crates/context/Cargo.toml b/crates/context/Cargo.toml new file mode 100644 index 00000000..9f2295e6 --- /dev/null +++ b/crates/context/Cargo.toml @@ -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 diff --git a/crates/leleka-runtime/src/context_policy.rs b/crates/context/src/context_policy.rs similarity index 100% rename from crates/leleka-runtime/src/context_policy.rs rename to crates/context/src/context_policy.rs diff --git a/crates/context/src/geometry.rs b/crates/context/src/geometry.rs new file mode 100644 index 00000000..6e75277d --- /dev/null +++ b/crates/context/src/geometry.rs @@ -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 = Result; + +fn mul(a: usize, b: usize) -> R { + a.checked_mul(b).ok_or(GeometryError::Overflow) +} +fn add(a: usize, b: usize) -> R { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + add(mul(self.pages(), 160)?, 4096) + } + /// Index key and tail image of one layer (`NativeQsaResources::INDEX_IMAGE`). + pub fn index_image_bytes(self) -> R { + 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 { + 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::(), 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::(), 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"); + } + } +} diff --git a/crates/context/src/lib.rs b/crates/context/src/lib.rs new file mode 100644 index 00000000..9cf6ffb3 --- /dev/null +++ b/crates/context/src/lib.rs @@ -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; diff --git a/crates/leleka-runtime/src/memory_plan.rs b/crates/context/src/memory_plan.rs similarity index 100% rename from crates/leleka-runtime/src/memory_plan.rs rename to crates/context/src/memory_plan.rs diff --git a/crates/leleka-runtime/src/rope_scaling.rs b/crates/context/src/rope_scaling.rs similarity index 100% rename from crates/leleka-runtime/src/rope_scaling.rs rename to crates/context/src/rope_scaling.rs diff --git a/crates/leleka-runtime/tests/rope_plan_golden.rs b/crates/context/tests/rope_plan_golden.rs similarity index 99% rename from crates/leleka-runtime/tests/rope_plan_golden.rs rename to crates/context/tests/rope_plan_golden.rs index 53e351c4..22a8db59 100644 --- a/crates/leleka-runtime/tests/rope_plan_golden.rs +++ b/crates/context/tests/rope_plan_golden.rs @@ -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; diff --git a/crates/leleka-runtime/tests/rope_plan_golden/gen_kv_pool_golden.cpp b/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/gen_kv_pool_golden.cpp rename to crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp diff --git a/crates/leleka-runtime/tests/rope_plan_golden/gen_plan_golden.py b/crates/context/tests/rope_plan_golden/gen_plan_golden.py similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/gen_plan_golden.py rename to crates/context/tests/rope_plan_golden/gen_plan_golden.py diff --git a/crates/leleka-runtime/tests/rope_plan_golden/gen_plan_golden.sh b/crates/context/tests/rope_plan_golden/gen_plan_golden.sh similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/gen_plan_golden.sh rename to crates/context/tests/rope_plan_golden/gen_plan_golden.sh diff --git a/crates/leleka-runtime/tests/rope_plan_golden/gen_rope_golden.cpp b/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/gen_rope_golden.cpp rename to crates/context/tests/rope_plan_golden/gen_rope_golden.cpp diff --git a/crates/leleka-runtime/tests/rope_plan_golden/gen_rope_golden.sh b/crates/context/tests/rope_plan_golden/gen_rope_golden.sh similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/gen_rope_golden.sh rename to crates/context/tests/rope_plan_golden/gen_rope_golden.sh diff --git a/crates/leleka-runtime/tests/rope_plan_golden/memory_plan_golden.json b/crates/context/tests/rope_plan_golden/memory_plan_golden.json similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/memory_plan_golden.json rename to crates/context/tests/rope_plan_golden/memory_plan_golden.json diff --git a/crates/leleka-runtime/tests/rope_plan_golden/rope_golden.json b/crates/context/tests/rope_plan_golden/rope_golden.json similarity index 100% rename from crates/leleka-runtime/tests/rope_plan_golden/rope_golden.json rename to crates/context/tests/rope_plan_golden/rope_golden.json diff --git a/crates/leleka-runtime/Cargo.toml b/crates/leleka-runtime/Cargo.toml index 175cdfda..460508a0 100644 --- a/crates/leleka-runtime/Cargo.toml +++ b/crates/leleka-runtime/Cargo.toml @@ -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] diff --git a/crates/leleka-runtime/src/lib.rs b/crates/leleka-runtime/src/lib.rs index 1f782ce1..3feb3bb8 100644 --- a/crates/leleka-runtime/src/lib.rs +++ b/crates/leleka-runtime/src/lib.rs @@ -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;