Files
leleka/crates/context/src/memory_plan.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 e69c3e66d4 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>
2026-10-14 14:50:09 +02:00

571 lines
19 KiB
Rust

//! Memory-admission arithmetic: literal port of `include/strata/plan/plan.hpp` and the pool derivation in
//! `src/plan/plan_main.cpp` (the `strata-plan` CLI), plus the per-KV-format byte costs the Original defines in
//! `src/core/layer.cpp::kv_pool_bytes`, `kernels/kv_q8.hpp` and `kernels/kv_q4.hpp`.
//!
//! What is literal (golden-tested against the `strata-plan` binary built from the Original):
//! `Geometry`, `Costs`, `state_bytes`, `kv_bytes_per_token_int8`, `make_plan` (INT8 KV), `vram_pool_bytes`,
//! `cli_pool`, `Plan::to_text`, the `DoesNotClose` messages.
//!
//! What is an extension and is labelled as such: `make_plan_with_format` (the same arithmetic with another KV
//! format's per-cell bytes; the per-cell bytes are golden-tested against the Original's own `kv_pool_bytes`),
//! `engine_resident_estimate` (hand-derived from `qsa_state_bytes`; NOT used for admission), and
//! `slots`-aware helpers in `context_policy`.
//!
//! Known quirks of the Original that this port keeps on purpose (so answers are identical to `strata-plan`):
//! - the planner counts the indexer key store as `key_heads * key_dim / qsa_block` = 32 bytes per token and
//! layer, whereas `layer.cpp` allocates an fp32 pooled store (128 bytes per token and layer);
//! - the CLI subtracts the dense and embedding bytes from the free VRAM to form the pool and `make_plan`
//! subtracts them from that pool again (a conservative double count when both are non-zero);
//! - a derived pool of 0 silently becomes the 5.943 GB default pool.
//!
//! Overflow: the Original uses wrapping u64 arithmetic; this port uses checked arithmetic and reports
//! [`PlanError::Overflow`] instead (identical for every non-overflowing input).
//!
//! Pure functions, no I/O, no GPU. No performance or quality claim is made by this module.
use std::fmt;
/// `Geometry` of the real Qwen3.8-Flash-Next artifact (plan.hpp).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Geometry {
pub n_layers: u64,
pub n_qsa_layers: u64,
pub n_kv_heads: u64,
pub head_dim: u64,
pub kv_group: u64,
pub qsa_block: u64,
pub indexer_q_heads: u64,
pub indexer_key_heads: u64,
pub indexer_key_dim: u64,
pub ssm_state_size: u64,
pub ssm_v_heads: u64,
pub ssm_d_conv: u64,
pub ssm_conv_channels: u64,
}
impl Default for Geometry {
fn default() -> Self {
Self {
n_layers: 48,
n_qsa_layers: 12,
n_kv_heads: 2,
head_dim: 256,
kv_group: 64,
qsa_block: 4,
indexer_q_heads: 4,
indexer_key_heads: 1,
indexer_key_dim: 128,
ssm_state_size: 128,
ssm_v_heads: 48,
ssm_d_conv: 4,
ssm_conv_channels: 10240,
}
}
}
impl Geometry {
pub fn n_gdn_layers(&self) -> Result<u64, PlanError> {
self.n_layers
.checked_sub(self.n_qsa_layers)
.ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers"))
}
/// Rejects values that would divide by zero or underflow in the Original's integer arithmetic.
pub fn validate(&self) -> Result<(), PlanError> {
self.n_gdn_layers()?;
if self.kv_group == 0 || self.qsa_block == 0 || self.ssm_d_conv == 0 {
return Err(PlanError::Geometry(
"kv_group, qsa_block and ssm_d_conv must be non-zero",
));
}
Ok(())
}
}
/// Byte costs (plan.hpp `Costs`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Costs {
pub expert_blob: u64,
pub dense_bytes: u64,
pub embd_bytes: u64,
pub mtp_bytes: u64,
pub workspace_bytes: u64,
pub state_bytes: u64,
}
impl Default for Costs {
fn default() -> Self {
Self {
expert_blob: 1_382_400,
dense_bytes: 0,
embd_bytes: 0,
mtp_bytes: 0,
workspace_bytes: 0,
state_bytes: 0,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanError {
/// plan.hpp `DoesNotClose`; the payload is the Original's exact `what()` text.
DoesNotClose(String),
/// Checked arithmetic overflowed (the Original would wrap silently).
Overflow,
Geometry(&'static str),
}
impl fmt::Display for PlanError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DoesNotClose(w) => f.write_str(w),
Self::Overflow => f.write_str("memory-plan arithmetic overflowed u64"),
Self::Geometry(w) => write!(f, "invalid geometry: {w}"),
}
}
}
impl std::error::Error for PlanError {}
type R<T> = Result<T, PlanError>;
fn mul(a: u64, b: u64) -> R<u64> {
a.checked_mul(b).ok_or(PlanError::Overflow)
}
fn add(a: u64, b: u64) -> R<u64> {
a.checked_add(b).ok_or(PlanError::Overflow)
}
/// GDN recurrence + conv history, bytes per sequence (plan.hpp `state_bytes`).
pub fn state_bytes(g: &Geometry) -> R<u64> {
g.validate()?;
let recurrence = mul(
mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?,
4,
)?;
let conv = mul(mul(g.ssm_d_conv - 1, g.ssm_conv_channels)?, 4)?;
mul(g.n_gdn_layers()?, add(recurrence, conv)?)
}
/// INT8 KV + indexer keys, bytes per token (plan.hpp `kv_bytes_per_token`), literal.
pub fn kv_bytes_per_token_int8(g: &Geometry) -> R<u64> {
g.validate()?;
let kv_elems = mul(mul(2, g.n_kv_heads)?, g.head_dim)?;
let kv_scales = mul(kv_elems / g.kv_group, 2)?;
let per_layer = add(kv_elems, kv_scales)?;
let idx_layer = mul(g.indexer_key_heads, g.indexer_key_dim)? / g.qsa_block;
mul(g.n_qsa_layers, add(per_layer, idx_layer)?)
}
/// The VRAM budget the KV cache and the expert cache share (plan.hpp `vram_pool_bytes`).
pub const fn vram_pool_bytes() -> u64 {
5_943_000_000
}
// ---- KV formats ------------------------------------------------------------------------------
/// KV cache storage formats of the Original (`--kv`). `Int8Keyless` is the experimental
/// `STRATA_KEYLESS_ROUTING` mode (`g_without_key`): half of INT8's bytes, no K store; it is not a default
/// and carries its own quality gate (charter: Value-Only Cache).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KvFormat {
Fp16,
Int8,
Q4_0,
K8V4,
Int8Keyless,
}
impl KvFormat {
pub fn name(self) -> &'static str {
match self {
Self::Fp16 => "fp16",
Self::Int8 => "int8",
Self::Q4_0 => "q4_0",
Self::K8V4 => "k8v4",
Self::Int8Keyless => "int8-keyless",
}
}
/// `--kv` spellings of `generate.cpp` (`q4` is accepted as `q4_0`). The keyless mode has no `--kv` name.
pub fn parse_cli(s: &str) -> Option<Self> {
match s {
"fp16" => Some(Self::Fp16),
"int8" => Some(Self::Int8),
"q4_0" | "q4" => Some(Self::Q4_0),
"k8v4" => Some(Self::K8V4),
_ => None,
}
}
pub fn is_experimental(self) -> bool {
self == Self::Int8Keyless
}
}
/// `KV_Q8_GROUP` (kv_q8.hpp) and `QK4_0`/`sizeof(block_q4_0)` (kv_q4.hpp).
pub const KV_Q8_GROUP: u64 = 64;
pub const QK4_0: u64 = 32;
pub const BLOCK_Q4_0_BYTES: u64 = 18;
/// The part of `QsaShapes` that sizes the KV pools.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KvShapes {
pub n_head_kv: u64,
pub head_dim: u64,
/// KV page granule in cells (`qsa_real_shapes().page_size` = 4).
pub page_size: u64,
}
impl KvShapes {
pub fn real() -> Self {
Self {
n_head_kv: 2,
head_dim: 256,
page_size: 4,
}
}
pub fn from_geometry(g: &Geometry) -> Self {
Self {
n_head_kv: g.n_kv_heads,
head_dim: g.head_dim,
page_size: 4,
}
}
fn validate(&self, fmt: KvFormat) -> R<()> {
if self.page_size == 0 {
return Err(PlanError::Geometry("page_size must be non-zero"));
}
if fmt != KvFormat::Fp16 && !self.head_dim.is_multiple_of(KV_Q8_GROUP) {
return Err(PlanError::Geometry(
"quantised KV needs head_dim to be a multiple of 64",
));
}
Ok(())
}
}
fn q8_bytes_per_cell(s: &KvShapes) -> R<u64> {
add(
mul(mul(s.n_head_kv, s.head_dim)?, 2)?,
mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?,
)
}
fn q4_bytes_per_head(head_dim: u64) -> R<u64> {
mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES)
}
/// Bytes per cell (one token, one QSA layer) of the K/V pool in `fmt`, without the pool's constant `+64`.
/// fp16: `n_head_kv * head_dim * 2 * 2`; INT8: kv_q8.hpp; Q4_0: kv_q4.hpp; K8V4: `layer.cpp` hybrid branch
/// (816 B/cell on the real shapes); keyless: INT8 / 2.
pub fn kv_cell_bytes(s: &KvShapes, fmt: KvFormat) -> R<u64> {
s.validate(fmt)?;
match fmt {
KvFormat::Fp16 => mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2),
KvFormat::Int8 => q8_bytes_per_cell(s),
KvFormat::Q4_0 => mul(mul(s.n_head_kv, q4_bytes_per_head(s.head_dim)?)?, 2),
KvFormat::K8V4 => {
let rows = s.n_head_kv;
add(
add(
mul(rows, s.head_dim)?,
mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?,
)?,
mul(rows, q4_bytes_per_head(s.head_dim)?)?,
)
}
KvFormat::Int8Keyless => Ok(q8_bytes_per_cell(s)? / 2),
}
}
/// `layer.cpp::kv_pool_bytes` for one QSA layer: `pages` pages of `page_size` cells, fully resident.
/// Includes the Original's `+64` slack for every format except fp16 (which has none).
pub fn kv_pool_bytes(s: &KvShapes, pages: u64, fmt: KvFormat) -> R<u64> {
let cells = mul(pages, s.page_size)?;
let body = mul(cells, kv_cell_bytes(s, fmt)?)?;
match fmt {
KvFormat::Fp16 => Ok(body),
_ => add(body, 64),
}
}
/// KV + indexer-key bytes per token over all QSA layers for `fmt`, with plan.hpp's indexer term.
/// For [`KvFormat::Int8`] this equals [`kv_bytes_per_token_int8`] (tested).
pub fn kv_bytes_per_token(g: &Geometry, fmt: KvFormat) -> R<u64> {
g.validate()?;
let cell = kv_cell_bytes(&KvShapes::from_geometry(g), fmt)?;
let idx_layer = mul(g.indexer_key_heads, g.indexer_key_dim)? / g.qsa_block;
mul(g.n_qsa_layers, add(cell, idx_layer)?)
}
// ---- the plan --------------------------------------------------------------------------------
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Plan {
pub max_context: u64,
pub kv_bytes: u64,
pub state_bytes: u64,
pub cache_bytes: u64,
pub cache_slots: u64,
pub vram_budget: u64,
pub vram_used: u64,
pub dram_experts: u64,
pub notes: Vec<String>,
}
fn does_not_close<T>(msg: String) -> R<T> {
Err(PlanError::DoesNotClose(msg))
}
/// plan.hpp `make_plan` with INT8 KV, literal. Identical to the `strata-plan` CLI for the same inputs.
pub fn make_plan(max_context: u64, g: &Geometry, c: &Costs, pool: u64) -> R<Plan> {
plan_with_per_token(max_context, kv_bytes_per_token_int8(g)?, c, pool)
}
/// EXTENSION: `make_plan` with another KV format's bytes per token. `Int8` reproduces [`make_plan`].
pub fn make_plan_with_format(
max_context: u64,
g: &Geometry,
fmt: KvFormat,
c: &Costs,
pool: u64,
) -> R<Plan> {
plan_with_per_token(max_context, kv_bytes_per_token(g, fmt)?, c, pool)
}
fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, pool: u64) -> R<Plan> {
if c.expert_blob == 0 {
return Err(PlanError::Geometry("expert_blob must be non-zero"));
}
let kv_bytes = mul(per_token, max_context)?;
let dram_experts = add(c.dense_bytes, c.embd_bytes)?;
let fixed = add(
add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?,
c.state_bytes,
)?;
let need = add(kv_bytes, fixed)?;
if need > pool {
return does_not_close(format!(
"max-context {max_context} needs {need} B of the {pool} B VRAM pool; reduce --max-context"
));
}
let cache_bytes = pool - need;
let cache_slots = cache_bytes / c.expert_blob;
let vram_used = pool - cache_bytes % c.expert_blob;
if cache_slots == 0 {
return does_not_close(format!(
"no room for even one expert cache slot at max-context {max_context}"
));
}
Ok(Plan {
max_context,
kv_bytes,
state_bytes: c.state_bytes,
cache_bytes,
cache_slots,
vram_budget: pool,
vram_used,
dram_experts,
notes: Vec::new(),
})
}
/// The pool derivation of `plan_main.cpp`: free VRAM less the resident dense and embedding bytes, and a
/// derived 0 falls back to [`vram_pool_bytes`] (`pool ? pool : strata::plan::vram_pool_bytes()`).
/// `--pool B` in the CLI assigns `free_vram` and so goes through this too.
pub fn cli_pool(free_vram: u64, c: &Costs) -> R<u64> {
let resident = add(c.dense_bytes, c.embd_bytes)?;
let pool = free_vram.saturating_sub(resident);
Ok(if pool != 0 { pool } else { vram_pool_bytes() })
}
impl Plan {
/// plan.hpp `to_string`, byte for byte (`std::to_string(double)` is `%f`).
pub fn to_text(&self) -> String {
let gb = |b: u64| format!("{:.6}", b as f64 / 1e9);
let mut s = String::new();
s += &format!("memory plan --max-context {}\n", self.max_context);
s += &format!(" KV + indexer keys {} GB\n", gb(self.kv_bytes));
s += &format!(
" recurrent state {} GB (GDN recurrence + conv history, NOT evictable)\n",
gb(self.state_bytes)
);
s += &format!(
" expert cache {} GB ({} slots of 1,382,400 B)\n",
gb(self.cache_bytes),
self.cache_slots
);
s += &format!(" VRAM pool {} GB\n", gb(self.vram_budget));
s += &format!(" expert arena (DRAM) {} GB\n", gb(self.dram_experts));
for n in &self.notes {
s += &format!(" note: {n}\n");
}
s
}
}
// ---- EXTENSION: advisory estimate of what the engine allocates ---------------------------------
/// Hand-derived from `layer.cpp::qsa_state_bytes` for a fully resident state (no `--kv-resident`
/// streaming). NOT golden-tested against the Original as a whole (only its `kv_pool_bytes` part is) and NOT
/// used for admission; it exists to show how far plan.hpp's indexer term is from the fp32 pooled store.
/// Excludes the step/pos state and 16-byte alignment (KiB scale).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EngineResidentEstimate {
pub kv_pools: u64,
pub page_tables: u64,
pub indexer_stores: u64,
pub rope_tables: u64,
pub total: u64,
}
/// `slots` independent sequence states of `ctx_per_slot` cells each; one rope table per state when
/// `rope_table_per_slot` is `Some(n_rot)` (the table is shared across layers by `share_rope`).
pub fn engine_resident_estimate(
g: &Geometry,
fmt: KvFormat,
slots: u64,
ctx_per_slot: u64,
rope_n_rot: Option<u64>,
) -> R<EngineResidentEstimate> {
g.validate()?;
let s = KvShapes::from_geometry(g);
let pages = ctx_per_slot.div_ceil(s.page_size);
let layers = g.n_qsa_layers;
let kv_layer = kv_pool_bytes(&s, pages, fmt)?;
let pooled_rows = ctx_per_slot / g.qsa_block + 2;
let idx_layer = add(
add(
mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?,
mul(g.indexer_key_dim, 4)?,
)?,
mul(mul(pooled_rows, g.indexer_key_dim)?, 4)?,
)?;
let per_slot_kv = mul(layers, kv_layer)?;
let per_slot_pt = mul(layers, mul(pages, 4)?)?;
let per_slot_idx = mul(layers, idx_layer)?;
let per_slot_rope = match rope_n_rot {
Some(n) => mul(mul(ctx_per_slot, n / 2)?, 8)?,
None => 0,
};
let kv_pools = mul(slots, per_slot_kv)?;
let page_tables = mul(slots, per_slot_pt)?;
let indexer_stores = mul(slots, per_slot_idx)?;
let rope_tables = mul(slots, per_slot_rope)?;
let total = add(
add(add(kv_pools, page_tables)?, indexer_stores)?,
rope_tables,
)?;
Ok(EngineResidentEstimate {
kv_pools,
page_tables,
indexer_stores,
rope_tables,
total,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn real_geometry_constants() {
let g = Geometry::default();
assert_eq!(
state_bytes(&g).unwrap(),
36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4)
);
assert_eq!(state_bytes(&g).unwrap(), 117_669_888);
// 12 layers x (1056 + 32)
assert_eq!(kv_bytes_per_token_int8(&g).unwrap(), 13_056);
}
#[test]
fn per_cell_bytes_on_real_shapes() {
let s = KvShapes::real();
assert_eq!(kv_cell_bytes(&s, KvFormat::Fp16).unwrap(), 2048);
assert_eq!(kv_cell_bytes(&s, KvFormat::Int8).unwrap(), 1056);
assert_eq!(kv_cell_bytes(&s, KvFormat::Q4_0).unwrap(), 576);
assert_eq!(kv_cell_bytes(&s, KvFormat::K8V4).unwrap(), 816);
assert_eq!(kv_cell_bytes(&s, KvFormat::Int8Keyless).unwrap(), 528);
}
#[test]
fn int8_generic_equals_literal() {
for g in [
Geometry::default(),
Geometry {
n_kv_heads: 4,
head_dim: 128,
n_qsa_layers: 9,
..Geometry::default()
},
] {
assert_eq!(
kv_bytes_per_token(&g, KvFormat::Int8).unwrap(),
kv_bytes_per_token_int8(&g).unwrap()
);
}
}
#[test]
fn pool_derivation_quirks() {
let c = Costs::default();
assert_eq!(cli_pool(12_000_000_000, &c).unwrap(), 12_000_000_000);
// derived 0 becomes the default pool
let heavy = Costs {
dense_bytes: 13_000_000_000,
..c
};
assert_eq!(cli_pool(12_000_000_000, &heavy).unwrap(), vram_pool_bytes());
assert_eq!(cli_pool(0, &c).unwrap(), vram_pool_bytes());
}
#[test]
fn does_not_close_messages() {
let g = Geometry::default();
let c = Costs::default();
let e = make_plan(524_288, &g, &c, 5_943_000_000).unwrap_err();
assert_eq!(
e.to_string(),
"max-context 524288 needs 6845104128 B of the 5943000000 B VRAM pool; reduce --max-context"
);
// exactly full pool: zero cache slots
let exact = 13_056 * 1000;
let e = make_plan(1000, &g, &c, exact).unwrap_err();
assert_eq!(
e.to_string(),
"no room for even one expert cache slot at max-context 1000"
);
}
#[test]
fn overflow_is_reported_not_wrapped() {
let g = Geometry::default();
assert_eq!(
make_plan(u64::MAX, &g, &Costs::default(), 1),
Err(PlanError::Overflow)
);
}
#[test]
fn q4_makes_both_charter_profiles_close_where_int8_does_not() {
let g = Geometry::default();
let c = Costs {
state_bytes: state_bytes(&g).unwrap(),
..Costs::default()
};
let pool = 5_943_000_000;
assert!(make_plan_with_format(524_288, &g, KvFormat::Int8, &c, pool).is_err());
assert!(make_plan_with_format(524_288, &g, KvFormat::Q4_0, &c, pool).is_ok());
}
#[test]
fn engine_estimate_exposes_fp32_indexer_store() {
let g = Geometry::default();
let e = engine_resident_estimate(&g, KvFormat::Int8, 1, 32_768, None).unwrap();
// 12 layers x (3*128*4 + 128*4 + (32768/4 + 2)*128*4) bytes: the "50 MiB at 32K" of qsa.hpp
assert_eq!(e.indexer_stores, 12 * (1536 + 512 + 8194 * 512));
assert!(e.indexer_stores > 50_000_000 && e.indexer_stores < 51_000_000);
}
}