feat(runtime): port plan.hpp memory-admission arithmetic with strata-plan golden tests

Literal port of plan.hpp/plan_main.cpp pool derivation (INT8, byte-identical CLI output
on 78 runs) plus per-format KV bytes (fp16/int8/q4_0/k8v4/keyless) tested against the
Original's kv_pool_bytes. Adds the rope+plan golden integration test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:42:42 +02:00
co-authored by Claude Sonnet 5.5
parent c738ab7667
commit 86a9abac72
7 changed files with 2751 additions and 0 deletions
+1
View File
@@ -1,6 +1,7 @@
//! Independent Qwen runtime. CUDA state stays inside its dedicated owner thread.
pub mod backend;
pub mod memory_plan;
pub mod rope_scaling;
pub use backend::spawn_backend_observed_native_integer_iq3_windowed256_retained_gr;
+570
View File
@@ -0,0 +1,570 @@
//! 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);
}
}
@@ -0,0 +1,404 @@
//! Golden tests for `rope_scaling` and `memory_plan` against fixtures produced by the ORIGINAL's host code
//! (see `rope_plan_golden/gen_rope_golden.sh` and `gen_plan_golden.sh`; clang++ on macOS, arm64).
//!
//! Rope: the C++ side links `rope_scaling.hpp` unmodified and the two `build_rope_table` definitions extracted
//! verbatim from `rope.cu`, compiled `-O2 -ffp-contract=off`. Tables are checked bit-for-bit through FNV-1a 64
//! over all 524288 rows (and over the first 262144) plus ten full sample rows. The only libm-dependent
//! operations are pow/cos/sin/log (f64) and cosf/logf/sinf (f32): on macOS both sides call the same system
//! libm, so equality is exact there. On other platforms the hash result is reported but not asserted, and the
//! sample rows and analytic values are allowed 1 and 2 ULP respectively (documented, not measured here).
//!
//! 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::{
Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan,
make_plan_with_format, state_bytes,
};
use leleka_runtime::rope_scaling::{
RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle,
};
use serde_json::Value;
const ROPE_JSON: &str = include_str!("rope_plan_golden/rope_golden.json");
const PLAN_JSON: &str = include_str!("rope_plan_golden/memory_plan_golden.json");
fn bits64(v: &Value) -> f64 {
let s = v.as_str().expect("hex string");
f64::from_bits(u64::from_str_radix(s.trim_start_matches("0x"), 16).unwrap())
}
fn bits32(v: &Value) -> f32 {
let s = v.as_str().expect("hex string");
f32::from_bits(u32::from_str_radix(s.trim_start_matches("0x"), 16).unwrap())
}
fn hex64(v: &Value) -> u64 {
u64::from_str_radix(v.as_str().unwrap().trim_start_matches("0x"), 16).unwrap()
}
fn ulp_diff(a: f32, b: f32) -> u32 {
if a.to_bits() == b.to_bits() {
return 0;
}
let map = |x: f32| {
let u = x.to_bits() as i64;
if u >= 0x8000_0000 {
0x8000_0000 - (u & 0x7fff_ffff)
} else {
u + 0x8000_0000
}
};
(map(a) - map(b)).unsigned_abs() as u32
}
const EXACT: bool = cfg!(target_os = "macos");
fn assert_close(what: &str, got: f32, want: f32, tol_ulp: u32) {
let tol = if EXACT { 0 } else { tol_ulp };
assert!(
ulp_diff(got, want) <= tol,
"{what}: got {:#010x} want {:#010x} ({} ulp, allowed {tol})",
got.to_bits(),
want.to_bits(),
ulp_diff(got, want)
);
}
fn config_of(c: &Value) -> RopeScaling {
RopeScaling {
kind: RopeScalingType::parse(c["type"].as_str().unwrap()).unwrap(),
freq_base: bits64(&c["freq_base"]),
factor: bits64(&c["factor"]),
freq_scale_in: bits64(&c["freq_scale_in"]),
orig_ctx: bits64(&c["orig_ctx"]),
ext_factor: bits64(&c["ext_factor"]),
attn_factor: bits64(&c["attn_factor"]),
beta_fast: bits64(&c["beta_fast"]),
beta_slow: bits64(&c["beta_slow"]),
}
}
struct Fnv(u64);
impl Fnv {
fn new() -> Self {
Self(0xcbf2_9ce4_8422_2325)
}
fn feed(&mut self, xs: &[f32]) {
for x in xs {
for b in x.to_bits().to_le_bytes() {
self.0 ^= u64::from(b);
self.0 = self.0.wrapping_mul(0x100_0000_01b3);
}
}
}
}
fn cases() -> Vec<Value> {
let root: Value = serde_json::from_str(ROPE_JSON).unwrap();
root["cases"].as_array().unwrap().clone()
}
fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) {
let name = c["name"].as_str().unwrap();
// validity message, exactly
let want = c["invalid"].as_str();
assert_eq!(
sc.validate().err().map(|e| e.reason()),
want,
"{name}: validity"
);
// scalar resolutions: libm log is the only dependency
let tol = if EXACT { 0.0 } else { 4.0 * f64::EPSILON };
let near = |a: f64, b: f64| (a - b).abs() <= tol * b.abs().max(1.0);
assert!(
near(sc.freq_scale(), bits64(&c["freq_scale"])),
"{name}: freq_scale"
);
if want.is_none() || sc.freq_scale().is_finite() {
assert!(near(sc.mscale(), bits64(&c["mscale"])), "{name}: mscale");
}
let cd = sc.corr_dims(n_rot);
for k in 0..2 {
let want = bits64(&c["corr_dims"][k]);
// a NaN from log(<0) of an invalid config: any NaN matches (payload/sign are libm detail)
assert!(
cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()),
"{name}: corr_dims[{k}]"
);
}
let a = sc.kernel_args(n_rot);
let w = &c["kernel_args"];
assert_eq!(
a.freq_scale.to_bits(),
bits32(&w["freq_scale"]).to_bits(),
"{name}: args.freq_scale"
);
assert_eq!(
a.corr_low.to_bits(),
bits32(&w["corr_low"]).to_bits(),
"{name}: args.corr_low"
);
assert_eq!(
a.corr_high.to_bits(),
bits32(&w["corr_high"]).to_bits(),
"{name}: args.corr_high"
);
assert_eq!(
a.ext_factor.to_bits(),
bits32(&w["ext_factor"]).to_bits(),
"{name}: args.ext_factor"
);
assert_eq!(
a.attn_factor.to_bits(),
bits32(&w["attn_factor"]).to_bits(),
"{name}: args.attn_factor"
);
// analytic float32 path
for s in c["analytic"].as_array().unwrap() {
let (co, si) = rope_scaled_angle(
bits32(&s["theta_extrap"]),
a.freq_scale,
a.corr_low,
a.corr_high,
a.ext_factor,
a.attn_factor,
s["pair"].as_i64().unwrap() as i32,
);
assert_close(&format!("{name}: analytic cos"), co, bits32(&s["cos"]), 2);
assert_close(&format!("{name}: analytic sin"), si, bits32(&s["sin"]), 2);
}
}
fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) {
let name = c["name"].as_str().unwrap();
let half = n_rot / 2;
const CHUNK: usize = 4096;
const N: usize = 524_288;
let samples = c["rows"].as_array().unwrap();
let mut cos_hash = Fnv::new();
let mut sin_hash = Fnv::new();
let mut at_262144 = (0, 0);
let mut cbuf = vec![0.0f32; CHUNK * half];
let mut sbuf = vec![0.0f32; CHUNK * half];
let mut first = 0;
while first < N {
fill_rope_table(n_rot, sc, first, &mut cbuf, &mut sbuf).unwrap();
if first == 262_144 {
at_262144 = (cos_hash.0, sin_hash.0);
}
for s in samples {
let p = s["pos"].as_u64().unwrap() as usize;
if p >= first && p < first + CHUNK {
let r = p - first;
for i in 0..half {
assert_close(
&format!("{name}: row {p} cos[{i}]"),
cbuf[r * half + i],
bits32(&s["cos"][i]),
1,
);
assert_close(
&format!("{name}: row {p} sin[{i}]"),
sbuf[r * half + i],
bits32(&s["sin"][i]),
1,
);
}
}
}
cos_hash.feed(&cbuf);
sin_hash.feed(&sbuf);
first += CHUNK;
}
let want = c["tables"].as_array().unwrap();
let got = [(at_262144.0, at_262144.1), (cos_hash.0, sin_hash.0)];
for (t, (gc, gs)) in want.iter().zip(got) {
let (wc, ws) = (hex64(&t["cos_fnv1a64"]), hex64(&t["sin_fnv1a64"]));
let n = t["n_pos"].as_u64().unwrap();
if EXACT {
assert_eq!(gc, wc, "{name}: cos table hash over {n} rows");
assert_eq!(gs, ws, "{name}: sin table hash over {n} rows");
} else if (gc, gs) != (wc, ws) {
eprintln!(
"note: {name}: table hash over {n} rows differs from the macOS fixture (non-macOS libm); sample rows are within tolerance"
);
}
}
}
fn run_case(name: &str) {
let c = cases()
.into_iter()
.find(|c| c["name"] == name)
.expect("case in fixture");
let sc = config_of(&c);
let n_rot = c["n_rot"].as_u64().unwrap() as usize;
check_scalars(&c, &sc, n_rot as i32);
if c.get("tables").is_some() {
check_tables(&c, &sc, n_rot);
}
}
macro_rules! rope_cases {
($($n:ident),* $(,)?) => { $( #[test] fn $n() { run_case(stringify!($n)); } )* };
}
rope_cases!(
none_default,
none_junk_knobs,
linear_2,
linear_1_5,
linear_freq_scale_in,
linear_attn_factor,
yarn_2,
yarn_1_5,
yarn_1,
yarn_4,
yarn_2_betas,
yarn_2_ext_half,
yarn_orig_131072,
yarn_ext0,
yarn_n_rot128,
yarn_n_rot4,
bad_factor_below_1,
bad_freq_base_1,
bad_orig_ctx_0,
bad_ext_negative,
bad_attn_0,
bad_beta_fast_0,
bad_beta_slow_neg,
bad_freq_scale_in_neg,
bad_mscale_negative,
);
#[test]
fn every_fixture_case_has_a_test() {
let names: Vec<String> = cases()
.iter()
.map(|c| c["name"].as_str().unwrap().to_owned())
.collect();
assert_eq!(names.len(), 25);
}
#[test]
fn yarn_is_observably_different_from_none() {
// the fixture would be vacuous if the scaled and unscaled tables were indistinguishable
let cs = cases();
let find = |n: &str| cs.iter().find(|c| c["name"] == n).unwrap().clone();
let (a, b) = (find("none_default"), find("yarn_2"));
assert_ne!(a["tables"][1]["cos_fnv1a64"], b["tables"][1]["cos_fnv1a64"]);
assert_ne!(
find("linear_2")["tables"][1]["cos_fnv1a64"],
b["tables"][1]["cos_fnv1a64"]
);
// yarn with ext_factor 0 and a non-unit mscale path differs from linear only by the log term being off
assert_eq!(find("yarn_ext0")["mscale"], find("linear_2")["mscale"]);
}
// ---- memory plan -------------------------------------------------------------------------------
fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> {
let mut ctx: u64 = 20480;
let mut free_vram: u64 = 12_000_000_000;
let mut costs = Costs::default();
let mut state_given = false;
let mut i = 0;
while i < args.len() {
let a = args[i].as_str();
let raw = args.get(i + 1)?;
let next = |i: &mut usize| -> u64 {
*i += 1;
raw.parse().expect("fixture numbers are plain u64")
};
match a {
"--max-context" => ctx = next(&mut i),
"--vram" | "--pool" => free_vram = next(&mut i),
"--dense" => costs.dense_bytes = next(&mut i),
"--embd" => costs.embd_bytes = next(&mut i),
"--workspace" => costs.workspace_bytes = next(&mut i),
"--state" => {
costs.state_bytes = next(&mut i);
state_given = true;
}
_ => return None, // --help / unknown / missing value: argument parsing, not planner arithmetic
}
i += 1;
}
let g = Geometry::default();
if !state_given {
costs.state_bytes = state_bytes(&g).unwrap();
}
let pool = cli_pool(free_vram, &costs).unwrap();
Some(match make_plan(ctx, &g, &costs, pool) {
Ok(p) => {
// the format-generic path with INT8 must be the same plan
assert_eq!(
make_plan_with_format(ctx, &g, KvFormat::Int8, &costs, pool).unwrap(),
p
);
(0, p.to_text(), String::new())
}
Err(e @ PlanError::DoesNotClose(_)) => (1, String::new(), format!("strata-plan: {e}\n")),
Err(e) => panic!("unexpected {e}"),
})
}
#[test]
fn strata_plan_cli_output_is_reproduced_exactly() {
let root: Value = serde_json::from_str(PLAN_JSON).unwrap();
assert_eq!(
root["state_bytes_default"].as_u64().unwrap(),
state_bytes(&Geometry::default()).unwrap()
);
let mut compared = 0;
let mut closed = 0;
let mut refused = 0;
for run in root["cli"].as_array().unwrap() {
let args: Vec<String> = run["args"]
.as_array()
.unwrap()
.iter()
.map(|a| a.as_str().unwrap().to_owned())
.collect();
let Some((exit, out, err)) = interpret_cli(&args) else {
assert!(matches!(run["exit"].as_i64().unwrap(), 0 | 2), "{args:?}");
continue;
};
assert_eq!(
exit as i64,
run["exit"].as_i64().unwrap(),
"{args:?}: exit code"
);
assert_eq!(out, run["stdout"].as_str().unwrap(), "{args:?}: stdout");
assert_eq!(err, run["stderr"].as_str().unwrap(), "{args:?}: stderr");
compared += 1;
if exit == 0 { closed += 1 } else { refused += 1 }
}
// the table must exercise both outcomes, or the comparison is vacuous
assert!(
compared >= 60 && closed >= 30 && refused >= 8,
"{compared} {closed} {refused}"
);
}
#[test]
fn kv_pool_bytes_match_the_originals_layer_cpp() {
let root: Value = serde_json::from_str(PLAN_JSON).unwrap();
let rows = root["kv_pool"].as_array().unwrap();
assert!(rows.len() >= 80);
for r in rows {
let fmt = match r["format"].as_str().unwrap() {
"fp16" => KvFormat::Fp16,
"int8" => KvFormat::Int8,
"q4_0" => KvFormat::Q4_0,
"k8v4" => KvFormat::K8V4,
"int8-keyless" => KvFormat::Int8Keyless,
other => panic!("unknown format {other}"),
};
let s = KvShapes {
n_head_kv: r["n_head_kv"].as_u64().unwrap(),
head_dim: r["head_dim"].as_u64().unwrap(),
page_size: r["page_size"].as_u64().unwrap(),
};
let got = kv_pool_bytes(&s, r["pages"].as_u64().unwrap(), fmt).unwrap();
assert_eq!(got, r["bytes"].as_u64().unwrap(), "{r}");
}
}
@@ -0,0 +1,49 @@
// gen_kv_pool_golden.cpp - prints the Original's `kv_pool_bytes` (src/core/layer.cpp, extracted verbatim by
// gen_plan_golden.py into kv_pool_bytes.inc) for every KV format on several shapes. Output: JSON array.
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/qsa.hpp"
#include <cstdint>
#include <cstdio>
using strata::kernels::QsaShapes;
static bool g_without_key = false; // layer.cpp globals the extracted function reads
static bool g_kv_q4 = false;
#include "kv_pool_bytes.inc"
int main() {
struct Shape { int64_t kv, dim, page; };
const Shape shapes[] = {{2, 256, 4}, {4, 128, 1}, {2, 256, 1}, {1, 64, 8}};
const int64_t pages[] = {1, 7, 131072, 262144};
struct Fmt { const char* name; bool without_key, q4, hybrid, int8; };
// the flag combinations qsa_state_bytes passes: kv_pool_bytes(s, slots, g_kv_hybrid, g_kv_int8 || g_kv_hybrid)
const Fmt fmts[] = {{"fp16", false, false, false, false},
{"int8", false, false, false, true},
{"q4_0", false, true, false, false},
{"k8v4", false, false, true, true},
{"int8-keyless", true, false, false, true}};
std::printf("[");
bool first = true;
for (const Shape& sh : shapes) {
QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head_kv = sh.kv;
s.head_dim = sh.dim;
s.page_size = sh.page;
for (const Fmt& f : fmts) {
g_without_key = f.without_key;
g_kv_q4 = f.q4;
for (int64_t p : pages) {
std::printf("%s\n {\"n_head_kv\": %lld, \"head_dim\": %lld, \"page_size\": %lld, \"format\": \"%s\", "
"\"pages\": %lld, \"bytes\": %llu}",
first ? "" : ",", (long long) sh.kv, (long long) sh.dim, (long long) sh.page, f.name,
(long long) p, (unsigned long long) kv_pool_bytes(s, p, f.hybrid, f.int8));
first = false;
}
}
}
std::printf("\n]\n");
return 0;
}
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Offline fixture generator (Python is allowed for offline tooling, AGENTS.md): builds the Original's
`strata-plan` CLI (header-only) and the `kv_pool_bytes` harness, runs a table of configurations and writes
memory_plan_golden.json. Usage: gen_plan_golden.py <out.json> <engine/strata dir> <work dir>."""
import json, subprocess, sys, os, re
out, strata, work = sys.argv[1:4]
cxx = os.environ.get("CXX", "clang++")
here = os.path.dirname(os.path.abspath(__file__))
flags = ["-std=c++17", "-O2", "-I" + os.path.join(strata, "include"), "-I" + work]
subprocess.check_call([cxx, *flags, os.path.join(strata, "src/plan/plan_main.cpp"), "-o", os.path.join(work, "strata-plan")])
with open(os.path.join(strata, "src/core/layer.cpp")) as f:
src = f.read().split("\n")
start = next(i for i, l in enumerate(src) if l.startswith("uint64_t kv_pool_bytes("))
end = next(i for i in range(start, len(src)) if src[i].startswith("}"))
with open(os.path.join(work, "kv_pool_bytes.inc"), "w") as f:
f.write("\n".join(src[start:end + 1]) + "\n")
subprocess.check_call([cxx, *flags, os.path.join(here, "gen_kv_pool_golden.cpp"), "-o", os.path.join(work, "kvgen")])
kv_pool = json.loads(subprocess.check_output([os.path.join(work, "kvgen")]))
G = 1000 ** 3
GIB = 1024 ** 3
state_default = 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4)
cases = []
def add(*args): cases.append([str(a) for a in args])
for ctx in (20480, 65536, 131072, 262144, 393216, 524288):
for vram in (12 * G, 16 * G, 24 * G, 32 * G, 32 * GIB, 48 * G):
add("--max-context", ctx, "--vram", vram)
# charter profiles with their state (x2 slots for 2x256K), on 32 GiB with and without resident weights
for (ctx, slots) in ((524288, 1), (524288, 2), (262144, 1), (262144, 2)):
st = state_default * slots
for vram in (16 * G, 24 * G, 32 * GIB):
add("--max-context", ctx, "--vram", vram, "--state", st)
add("--max-context", ctx, "--vram", vram, "--state", st, "--dense", 4 * G, "--embd", 500_000_000, "--workspace", 300_000_000)
# small cards: the planner must refuse
for ctx in (262144, 524288):
for vram in (3 * G, 4 * G, 6 * G, 7 * G):
add("--max-context", ctx, "--vram", vram)
# resident weights larger than the card: derived pool 0 falls back to the default pool
add("--max-context", 4096, "--vram", 5 * G, "--dense", 6 * G)
add("--max-context", 20480) # CLI defaults
add("--pool", 5943000000, "--max-context", 20480)
add("--pool", 3 * G, "--max-context", 100000)
add("--pool", 20 * G, "--max-context", 100000, "--dense", 5 * G, "--embd", G) # --pool still subtracts dense/embd
add("--max-context", 1000, "--vram", 1_000_000) # does not close
add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_399) # no room for one slot (default state)
add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_400) # exactly one slot
add("--max-context", 100, "--vram", 10 * G, "--state", 0)
add("--max-context", 100, "--vram", 10 * G, "--workspace", 123456789)
add("--help")
add("--bogus")
add("--max-context")
runs = []
for args in cases:
p = subprocess.run([os.path.join(work, "strata-plan"), *args], capture_output=True, text=True)
runs.append({"args": args, "exit": p.returncode, "stdout": p.stdout, "stderr": p.stderr})
json.dump({"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"state_bytes_default": state_default, "cli": runs, "kv_pool": kv_pool}, open(out, "w"), indent=1)
@@ -0,0 +1,7 @@
#!/bin/sh
# Regenerates memory_plan_golden.json from the Original (macOS or Linux, any C++17 compiler + python3).
set -eu
here=$(cd "$(dirname "$0")" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
python3 -I "$here/gen_plan_golden.py" "$here/memory_plan_golden.json" "$here/../../../../engine/strata" "$work"
File diff suppressed because it is too large Load Diff