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

295 lines
13 KiB
Rust

//! Pure policy: from a *requested* serving configuration (slots, per-slot context, KV format, rope knobs,
//! VRAM budget) derive the *effective* one, or refuse.
//!
//! Composition of three Original behaviours, none of them new logic:
//! 1. rope selection per `setup.py::resolve_rope` (past the trained 262144 an omitted method becomes YaRN with
//! factor `ctx / 262144`; an explicit `none` is refused there; a stray `--rope-scale` is refused inside the
//! trained range), turned into the full constant set by the `generate.cpp` resolution
//! ([`crate::rope_scaling::resolve_rope_scaling`]);
//! 2. admission per `plan.hpp::make_plan` driven the way `strata-plan` drives it
//! ([`crate::memory_plan::cli_pool`] + [`crate::memory_plan::make_plan_with_format`]);
//! 3. the charter profiles: `1 x 512K` and `2 x 256K` (and the local `1 x 256K`).
//!
//! Slots are an EXTENSION over the Original's planner, which sizes one `max_context`: `S` slots of `C` cells
//! are planned as `max_context = S * C` with `S` copies of the per-sequence recurrent state (the same numbers
//! `strata-plan --max-context S*C --state S*state_bytes` prints). Rope positions restart at 0 in every slot,
//! so the scaling is chosen from the PER-SLOT context: `2 x 256K` needs no scaling, `1 x 512K` needs YaRN 2.
//! The rope table has `ctx_per_slot` rows and is shared by the slots.
//!
//! This module changes no existing behaviour. In particular the runtime still pins serving context at 262144
//! (`backend.rs:91`, `model_binding/qwen4exp_input.rs:133`, ...); see `docs/rope-and-memory-plan.md` for the
//! exact sites a lift must touch. Admission here is `strata-plan`'s arithmetic, which is a planning estimate:
//! the advisory [`EffectiveContext::engine_estimate`] shows what `layer.cpp` would allocate for the KV pools,
//! the fp32 indexer store and the rope table. Nothing here is a performance or quality claim.
use crate::memory_plan::{
Costs, EngineResidentEstimate, Geometry, KvFormat, Plan, PlanError, cli_pool, engine_resident_estimate,
kv_bytes_per_token, make_plan_with_format, state_bytes,
};
use crate::rope_scaling::{
MAX_CHARTER_CONTEXT, ModelRopeKeys, RopeKnobError, RopeKnobs, RopeScaling, RopeScalingType, SetupRopeError,
TRAINED_CONTEXT, resolve_rope_scaling, rope_table_bytes, setup_resolve_rope,
};
use std::fmt;
/// Number of rotated dimensions (`QsaShapes::n_rot`) the rope tables are built for.
pub const ROPE_N_ROT: usize = 64;
/// VRAM inputs, in the terms `strata-plan` takes them (`--vram`, `--dense`, `--embd`, `--workspace`, MTP).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VramBudget {
/// Free VRAM in bytes (`--vram`).
pub free_vram_bytes: u64,
/// Resident dense/embedding/MTP/workspace bytes. `costs.state_bytes` is ignored: it is derived
/// (or overridden by `state_bytes_per_slot`).
pub costs: Costs,
/// Per-sequence recurrent state; `None` = derived from the geometry like the CLI's default.
pub state_bytes_per_slot: Option<u64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ContextRequest {
pub slots: u64,
pub ctx_per_slot: u64,
pub kv_format: KvFormat,
/// Permit experimental KV formats ([`KvFormat::is_experimental`]); off by default per AGENTS.md.
pub allow_experimental: bool,
/// Rope method flag (`--rope-scaling`); `None` = omitted.
pub rope_scaling: Option<RopeScalingType>,
/// Rope factor (`--rope-scale`); `None` = omitted.
pub rope_scale: Option<f64>,
/// Remaining knobs (`scaling` and `rope_scale` of this struct are overwritten by the resolution above).
pub rope_knobs: RopeKnobs,
/// The model file's rope keys (none for the shipped artifact).
pub model_rope: ModelRopeKeys,
pub geometry: Geometry,
pub vram: VramBudget,
}
impl ContextRequest {
/// A request with the Original's defaults for everything except the four things that must be chosen.
pub fn new(slots: u64, ctx_per_slot: u64, kv_format: KvFormat, free_vram_bytes: u64) -> Self {
Self {
slots,
ctx_per_slot,
kv_format,
allow_experimental: false,
rope_scaling: None,
rope_scale: None,
rope_knobs: RopeKnobs::default(),
model_rope: ModelRopeKeys::default(),
geometry: Geometry::default(),
vram: VramBudget { free_vram_bytes, costs: Costs::default(), state_bytes_per_slot: None },
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum PolicyError {
ZeroSlots,
ZeroContext,
/// Per-slot context above the charter/setup ceiling (524288) the tables were verified for.
ContextTooLarge {
requested: u64,
max: u64,
},
ExperimentalKvFormat(KvFormat),
/// `setup.py`'s refusal.
Setup(SetupRopeError),
/// A rope knob or the resolved rope configuration is invalid.
Rope(RopeKnobError),
/// plan.hpp refused (`DoesNotClose`) or the arithmetic could not be evaluated.
Plan(PlanError),
}
impl fmt::Display for PolicyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ZeroSlots => f.write_str("at least one slot is required"),
Self::ZeroContext => f.write_str("the per-slot context must be positive"),
Self::ContextTooLarge { requested, max } => {
write!(f, "per-slot context {requested} exceeds the supported {max}")
}
Self::ExperimentalKvFormat(k) => {
write!(f, "KV format {} is experimental and was not explicitly enabled", k.name())
}
Self::Setup(e) => write!(f, "{e}"),
Self::Rope(e) => write!(f, "{e}"),
Self::Plan(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for PolicyError {}
impl PolicyError {
/// True when the planner (as opposed to a request/rope error) rejected the combination.
pub fn is_planner_rejection(&self) -> bool {
matches!(self, Self::Plan(PlanError::DoesNotClose(_)))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct EffectiveContext {
pub slots: u64,
pub ctx_per_slot: u64,
/// `slots * ctx_per_slot`: the `--max-context` the planner saw.
pub total_cells: u64,
pub kv_format: KvFormat,
/// The resolved rope configuration (identity when `rope_active` is false).
pub rope: RopeScaling,
/// False for the stock model (positions within the trained range, no flags).
pub rope_active: bool,
/// Rows of the shared cos/sin table (one per position of one slot).
pub rope_table_rows: u64,
pub rope_table_bytes: u64,
pub kv_bytes_per_token: u64,
pub kv_bytes_per_slot: u64,
pub state_bytes_per_slot: u64,
pub plan: Plan,
/// Hand-derived estimate of what the engine allocates, ADVISORY only (see `memory_plan`).
pub engine_estimate: EngineResidentEstimate,
/// True when the advisory KV+indexer+rope total alone exceeds the planner's pool: the planner admitted
/// something the engine's own allocation formulas would not fit.
pub engine_estimate_exceeds_pool: bool,
pub notes: Vec<String>,
}
/// Refuse a request that cannot be served before any arithmetic runs.
fn check_request(req: &ContextRequest) -> Result<(), PolicyError> {
if req.slots == 0 {
return Err(PolicyError::ZeroSlots);
}
if req.ctx_per_slot == 0 {
return Err(PolicyError::ZeroContext);
}
if req.ctx_per_slot > MAX_CHARTER_CONTEXT {
return Err(PolicyError::ContextTooLarge { requested: req.ctx_per_slot, max: MAX_CHARTER_CONTEXT });
}
if req.kv_format.is_experimental() && !req.allow_experimental {
return Err(PolicyError::ExperimentalKvFormat(req.kv_format));
}
Ok(())
}
/// The rope configuration chosen for the context actually served, and the size of its shared table.
struct RopeChoice {
rope: RopeScaling,
active: bool,
rows: u64,
bytes: u64,
}
/// The knobs with the method and factor `setup.py` chose written over them.
fn knobs_for(req: &ContextRequest, setup: Option<(RopeScalingType, f64)>) -> RopeKnobs {
let mut knobs = req.rope_knobs;
match setup {
Some((kind, scale)) => {
knobs.scaling = Some(kind);
knobs.rope_scale = scale;
}
None => {
// stock model: leave the type to the model file, scale to the knob family as given
knobs.scaling = None;
knobs.rope_scale = req.rope_scale.unwrap_or(0.0);
}
}
knobs
}
/// setup.py chooses (method, factor) for the context actually served, generate.cpp resolves.
fn choose_rope(req: &ContextRequest, notes: &mut Vec<String>) -> Result<RopeChoice, PolicyError> {
let trained = if req.model_rope.orig_ctx >= 1.0 { req.model_rope.orig_ctx as u64 } else { TRAINED_CONTEXT };
let setup =
setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained).map_err(PolicyError::Setup)?;
let knobs = knobs_for(req, setup);
let resolved = resolve_rope_scaling(&knobs, &req.model_rope).map_err(PolicyError::Rope)?;
let rope = resolved.scaling;
let active = rope.kind != RopeScalingType::None;
if active {
notes.push(format!(
"rope scaling {} factor {} for {} positions per slot (trained {})",
rope.kind.name(),
rope.factor,
req.ctx_per_slot,
trained
));
}
if resolved.inert_knobs_ignored {
notes.push("rope scaling is none: the scaling knobs have no effect".into());
}
let rows = req.ctx_per_slot;
let bytes = rope_table_bytes(ROPE_N_ROT, rows as usize).ok_or(PolicyError::Plan(PlanError::Overflow))?;
Ok(RopeChoice { rope, active, rows, bytes })
}
/// What the planner admitted: the strata-plan arithmetic over `slots * ctx`.
struct Admission {
total_cells: u64,
state_per_slot: u64,
plan: Plan,
per_token: u64,
per_slot: u64,
engine_estimate: EngineResidentEstimate,
exceeds: bool,
}
const ADVISORY_EXCEEDS_POOL: &str = "advisory: the engine's own KV/indexer/rope allocation formulas exceed the planner \
pool even though the planner admitted it (plan.hpp counts the indexer key store at 32 B per token and layer; \
layer.cpp allocates fp32)";
fn admit(req: &ContextRequest, rope_active: bool, notes: &mut Vec<String>) -> Result<Admission, PolicyError> {
let g = &req.geometry;
let overflow = || PolicyError::Plan(PlanError::Overflow);
let state_per_slot = req.vram.state_bytes_per_slot.map_or_else(|| state_bytes(g), Ok).map_err(PolicyError::Plan)?;
let total_cells = req.slots.checked_mul(req.ctx_per_slot).ok_or_else(overflow)?;
let state_total = req.slots.checked_mul(state_per_slot).ok_or_else(overflow)?;
let costs = Costs { state_bytes: state_total, ..req.vram.costs };
let pool = cli_pool(req.vram.free_vram_bytes, &costs).map_err(PolicyError::Plan)?;
let plan = make_plan_with_format(total_cells, g, req.kv_format, &costs, pool).map_err(PolicyError::Plan)?;
let per_token = kv_bytes_per_token(g, req.kv_format).map_err(PolicyError::Plan)?;
let per_slot = per_token.checked_mul(req.ctx_per_slot).ok_or_else(overflow)?;
let rope_rot = rope_active.then_some(ROPE_N_ROT as u64);
let engine_estimate =
engine_resident_estimate(g, req.kv_format, req.slots, req.ctx_per_slot, rope_rot).map_err(PolicyError::Plan)?;
let exceeds = engine_estimate.total > pool;
if exceeds {
notes.push(ADVISORY_EXCEEDS_POOL.into());
}
Ok(Admission { total_cells, state_per_slot, plan, per_token, per_slot, engine_estimate, exceeds })
}
/// Derive the effective configuration or refuse. Pure; evaluates the same arithmetic as `strata-plan`.
pub fn resolve_context(req: &ContextRequest) -> Result<EffectiveContext, PolicyError> {
check_request(req)?;
let mut notes = Vec::new();
let r = choose_rope(req, &mut notes)?;
let a = admit(req, r.active, &mut notes)?;
if req.kv_format.is_experimental() {
notes.push("experimental KV format enabled explicitly; no default and no quality claim".into());
}
Ok(EffectiveContext {
slots: req.slots,
ctx_per_slot: req.ctx_per_slot,
total_cells: a.total_cells,
kv_format: req.kv_format,
rope: r.rope,
rope_active: r.active,
rope_table_rows: r.rows,
rope_table_bytes: r.bytes,
kv_bytes_per_token: a.per_token,
kv_bytes_per_slot: a.per_slot,
state_bytes_per_slot: a.state_per_slot,
plan: a.plan,
engine_estimate: a.engine_estimate,
engine_estimate_exceeds_pool: a.exceeds,
notes,
})
}
/// The two mandatory charter profiles plus the local one: `(slots, ctx_per_slot)`.
pub const CHARTER_PROFILES: [(u64, u64); 3] = [(1, 524_288), (2, 262_144), (1, 262_144)];
#[cfg(test)]
mod tests;