From e81f0950ddbc3a6435d6a5fb27d6bf594cbe05fc Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 13:39:31 +0100 Subject: [PATCH] STRA-338 size: leleka-context + leleka-engine-fake: split resolve_context, rope fill/resolve/validate, plan estimate; wrap strings (context fn_lines 6->0, complexity 6->0, width 9->0; fake width 1->0) --- crates/context/src/context_policy.rs | 120 +++++++----- crates/context/src/geometry.rs | 8 +- .../memory_plan/impl_default_for_geometry.rs | 30 ++- .../src/memory_plan/plan_with_per_token.rs | 64 ++++--- .../src/rope_scaling/fill_rope_table.rs | 177 +++++++++++------- .../src/rope_scaling/impl_fmt_display_for.rs | 14 +- .../src/rope_scaling/impl_ropescalingtype.rs | 55 +++--- crates/context/tests/rope_plan_golden.rs | 3 +- .../every_fixture_case_has.rs | 4 +- crates/engine-fake/src/lib.rs | 5 +- limits-baseline.json | 17 +- 11 files changed, 290 insertions(+), 207 deletions(-) diff --git a/crates/context/src/context_policy.rs b/crates/context/src/context_policy.rs index 18933d30..02b0429a 100644 --- a/crates/context/src/context_policy.rs +++ b/crates/context/src/context_policy.rs @@ -155,8 +155,8 @@ pub struct EffectiveContext { pub notes: Vec, } -/// Derive the effective configuration or refuse. Pure; evaluates the same arithmetic as `strata-plan`. -pub fn resolve_context(req: &ContextRequest) -> Result { +//// 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); } @@ -169,12 +169,19 @@ pub fn resolve_context(req: &ContextRequest) -> Result= 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)?; +/// 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)) => { @@ -187,10 +194,19 @@ pub fn resolve_context(req: &ContextRequest) -> Result) -> Result { + 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 rope_active = rope.kind != RopeScalingType::None; - if rope_active { + let active = rope.kind != RopeScalingType::None; + if active { notes.push(format!( "rope scaling {} factor {} for {} positions per slot (trained {})", rope.kind.name(), @@ -202,62 +218,76 @@ pub fn resolve_context(req: &ContextRequest) -> Result) -> Result { let g = &req.geometry; - let state_per_slot = match req.vram.state_bytes_per_slot { - Some(s) => s, - None => state_bytes(g).map_err(PolicyError::Plan)?, - }; - let total_cells = req.slots.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; - let state_total = req.slots.checked_mul(state_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; + 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(PolicyError::Plan(PlanError::Overflow))?; - let engine_estimate = engine_resident_estimate( - g, - req.kv_format, - req.slots, - req.ctx_per_slot, - rope_active.then_some(ROPE_N_ROT as u64), - ) - .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: 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)" - .into(), - ); + 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 { + 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, + total_cells: a.total_cells, kv_format: req.kv_format, - rope, - rope_active, - rope_table_rows: rope_rows, - rope_table_bytes: rope_bytes, - kv_bytes_per_token: per_token, - kv_bytes_per_slot: per_slot, - state_bytes_per_slot: state_per_slot, - plan, - engine_estimate, - engine_estimate_exceeds_pool: exceeds, + 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)`. +// 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)] diff --git a/crates/context/src/geometry.rs b/crates/context/src/geometry.rs index 08fea84e..230926ad 100644 --- a/crates/context/src/geometry.rs +++ b/crates/context/src/geometry.rs @@ -44,7 +44,8 @@ impl fmt::Display for GeometryError { } Self::Resident(n) => write!( f, - "a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)" + "a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} \ + pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)" ), Self::Overflow => f.write_str("geometry arithmetic overflowed"), } @@ -218,7 +219,10 @@ impl fmt::Display for KvStreamFootprint { let gib = |b: usize| b as f64 / (1u64 << 30) as f64; write!( f, - "kv int8 context={} resident={} cells ({} pages/layer) vram={:.3} GiB (+{:.3} GiB prompt stage) pinned-host={:.3} GiB", + concat!( + "kv int8 context={} resident={} cells ({} pages/layer) vram={:.3} GiB ", + "(+{:.3} GiB prompt stage) pinned-host={:.3} GiB" + ), self.cells, self.resident_pages * PAGE_CELLS, self.resident_pages, diff --git a/crates/context/src/memory_plan/impl_default_for_geometry.rs b/crates/context/src/memory_plan/impl_default_for_geometry.rs index 5f58c92c..7ce6ed1e 100644 --- a/crates/context/src/memory_plan/impl_default_for_geometry.rs +++ b/crates/context/src/memory_plan/impl_default_for_geometry.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Default_for_Geometry, impl Geometry, impl Default_for_Costs, impl fmt_Display_for, impl std_error_Error, fn mul .... +//! Moved out of the parent module by STRA-338: impl Default_for_Geometry, impl Geometry, impl Default_for_Costs, impl +//! fmt_Display_for, impl std_error_Error, fn mul .... #[allow(unused_imports)] use super::*; @@ -136,22 +137,31 @@ pub(super) fn q4_bytes_per_head(head_dim: u64) -> R { mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES) } +fn fp16_bytes_per_cell(s: &KvShapes) -> R { + mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2) +} +fn q4_bytes_per_cell(s: &KvShapes) -> R { + mul(mul(s.n_head_kv, q4_bytes_per_head(s.head_dim)?)?, 2) +} +/// `layer.cpp` hybrid branch: INT8 keys, Q4_0 values. +fn k8v4_bytes_per_cell(s: &KvShapes) -> R { + 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)?)?, + ) +} + /// 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 { s.validate(fmt)?; match fmt { - KvFormat::Fp16 => mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2), + KvFormat::Fp16 => fp16_bytes_per_cell(s), 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::Q4_0 => q4_bytes_per_cell(s), + KvFormat::K8V4 => k8v4_bytes_per_cell(s), KvFormat::Int8Keyless => Ok(q8_bytes_per_cell(s)? / 2), } } diff --git a/crates/context/src/memory_plan/plan_with_per_token.rs b/crates/context/src/memory_plan/plan_with_per_token.rs index e085a4c6..7991fb6f 100644 --- a/crates/context/src/memory_plan/plan_with_per_token.rs +++ b/crates/context/src/memory_plan/plan_with_per_token.rs @@ -1,8 +1,14 @@ -//! Moved out of the parent module by STRA-338: fn plan_with_per_token, fn cli_pool, impl Plan, fn engine_resident_estimate. +//! Moved out of the parent module by STRA-338: fn plan_with_per_token, fn cli_pool, impl Plan, fn +//! engine_resident_estimate. #[allow(unused_imports)] use super::*; +/// The refusal when the KV and fixed bytes of `max_context` exceed the VRAM pool. +fn over_pool(max_context: u64, need: u64, pool: u64) -> R { + does_not_close(format!("max-context {max_context} needs {need} B of the {pool} B VRAM pool; reduce --max-context")) +} + pub(super) fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, pool: u64) -> R { if c.expert_blob == 0 { return Err(PlanError::Geometry("expert_blob must be non-zero")); @@ -12,9 +18,7 @@ pub(super) fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, p 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" - )); + return over_pool(max_context, need, pool); } let cache_bytes = pool - need; let cache_slots = cache_bytes / c.expert_blob; @@ -69,6 +73,35 @@ impl Plan { } } +/// Bytes of the fp32 indexer key store of one layer of one slot. +fn indexer_layer_bytes(g: &Geometry, ctx_per_slot: u64) -> R { + let key = g.indexer_key_dim; + let pooled_rows = ctx_per_slot / g.qsa_block + 2; + let head = mul(mul(g.qsa_block - 1, key)?, 4)?; + let current = mul(key, 4)?; + let pooled = mul(mul(pooled_rows, key)?, 4)?; + add(add(head, current)?, pooled) +} + +/// Bytes of the rope cos/sin table of one slot (0 when the stock model needs none). +fn rope_slot_bytes(ctx_per_slot: u64, rope_n_rot: Option) -> R { + match rope_n_rot { + Some(n) => mul(mul(ctx_per_slot, n / 2)?, 8), + None => Ok(0), + } +} + +/// Per slot: `[KV pools, page tables, indexer stores, rope table]`. +fn per_slot_bytes(g: &Geometry, fmt: KvFormat, ctx_per_slot: u64, rope_n_rot: Option) -> R<[u64; 4]> { + 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 idx_layer = indexer_layer_bytes(g, ctx_per_slot)?; + let rope = rope_slot_bytes(ctx_per_slot, rope_n_rot)?; + Ok([mul(layers, kv_layer)?, mul(layers, mul(pages, 4)?)?, mul(layers, idx_layer)?, rope]) +} + /// `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( @@ -79,26 +112,9 @@ pub fn engine_resident_estimate( rope_n_rot: Option, ) -> R { 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 per_slot = per_slot_bytes(g, fmt, ctx_per_slot, rope_n_rot)?; + let [kv_pools, page_tables, indexer_stores, rope_tables] = + [mul(slots, per_slot[0])?, mul(slots, per_slot[1])?, mul(slots, per_slot[2])?, mul(slots, per_slot[3])?]; let total = add(add(add(kv_pools, page_tables)?, indexer_stores)?, rope_tables)?; Ok(EngineResidentEstimate { kv_pools, page_tables, indexer_stores, rope_tables, total }) } diff --git a/crates/context/src/rope_scaling/fill_rope_table.rs b/crates/context/src/rope_scaling/fill_rope_table.rs index 157c9673..8ed2d6e6 100644 --- a/crates/context/src/rope_scaling/fill_rope_table.rs +++ b/crates/context/src/rope_scaling/fill_rope_table.rs @@ -1,45 +1,46 @@ -//! Moved out of the parent module by STRA-338: fn fill_rope_table, impl RopeTable, fn build_rope_table, impl Default_for_RopeKnobs, impl fmt_Display_for, impl std_error_Error .... +//! Moved out of the parent module by STRA-338: fn fill_rope_table, impl RopeTable, fn build_rope_table, impl +//! Default_for_RopeKnobs, impl fmt_Display_for, impl std_error_Error .... #[allow(unused_imports)] use super::*; -/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out` -/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`). -/// -/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one. -/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply). -pub fn fill_rope_table( - n_rot: usize, - sc: &RopeScaling, +/// The rows being filled: `rows` rows of `half` entries, starting at position `first_pos`. +#[derive(Clone, Copy)] +struct RowSpan { + half: usize, first_pos: usize, - cos_out: &mut [f32], - sin_out: &mut [f32], -) -> Result<(), RopeTableError> { - check_n_rot(n_rot)?; - sc.validate()?; - let half = n_rot / 2; - if cos_out.len() != sin_out.len() || !cos_out.len().is_multiple_of(half) { + rows: usize, +} + +/// The number of rows the output buffers hold, refused when they disagree or reach past `i32` positions. +fn fill_rows(half: usize, first_pos: usize, cos_len: usize, sin_len: usize) -> Result { + if cos_len != sin_len || !cos_len.is_multiple_of(half) { return Err(RopeTableError::BufferLength); } - let rows = cos_out.len() / half; + let rows = cos_len / half; let end = first_pos.checked_add(rows).ok_or(RopeTableError::TooManyPositions(rows))?; if i32::try_from(end).is_err() { return Err(RopeTableError::TooManyPositions(end)); } - // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. - let n_rot_f = n_rot as f64; - let inv: Vec = (0..half).map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)).collect(); - if sc.kind == RopeScalingType::None { - for r in 0..rows { - let p = (first_pos + r) as f64; - for i in 0..half { - let ang = p * inv[i]; - cos_out[r * half + i] = ang.cos() as f32; - sin_out[r * half + i] = ang.sin() as f32; - } + Ok(rows) +} + +/// The unscaled loop of the Original, verbatim (no mscale multiply). +fn fill_unscaled(inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut [f32]) { + let RowSpan { half, first_pos, rows } = span; + for r in 0..rows { + let p = (first_pos + r) as f64; + for i in 0..half { + let ang = p * inv[i]; + cos_out[r * half + i] = ang.cos() as f32; + sin_out[r * half + i] = ang.sin() as f32; } - return Ok(()); } +} + +/// The scaled loop: linear interpolation of the angle, the YaRN ramp blend and the magnitude scale. +fn fill_scaled(sc: &RopeScaling, n_rot: usize, inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut [f32]) { + let RowSpan { half, first_pos, rows } = span; let fs = sc.freq_scale(); let ms = sc.mscale(); let cd = sc.corr_dims(n_rot as i32); @@ -60,6 +61,33 @@ pub fn fill_rope_table( sin_out[r * half + i] = (ang.sin() * ms) as f32; } } +} + +/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out` +/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`). +/// +/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one. +/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply). +pub fn fill_rope_table( + n_rot: usize, + sc: &RopeScaling, + first_pos: usize, + cos_out: &mut [f32], + sin_out: &mut [f32], +) -> Result<(), RopeTableError> { + check_n_rot(n_rot)?; + sc.validate()?; + let half = n_rot / 2; + let rows = fill_rows(half, first_pos, cos_out.len(), sin_out.len())?; + // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. + let n_rot_f = n_rot as f64; + let inv: Vec = (0..half).map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)).collect(); + let span = RowSpan { half, first_pos, rows }; + if sc.kind == RopeScalingType::None { + fill_unscaled(&inv, span, cos_out, sin_out); + } else { + fill_scaled(sc, n_rot, &inv, span, cos_out, sin_out); + } Ok(()) } @@ -105,19 +133,13 @@ impl fmt::Display for RopeKnobError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::NotFinite => f.write_str("a rope scaling knob is not a finite number"), - Self::ScaleBelowOne => { - f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)") - } - Self::FreqBase => { - f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)") - } - Self::Knob => f.write_str( - "invalid rope scaling knob (--yarn-ext-factor < 0 = auto, --yarn-orig-ctx 0 = default, the rest positive)", - ), - Self::ModelType(t) => write!( - f, - "model file carries rope.scaling.type '{t}' - none, linear or yarn only" - ), + Self::ScaleBelowOne => f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)"), + Self::FreqBase => f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)"), + Self::Knob => f.write_str(concat!( + "invalid rope scaling knob (--yarn-ext-factor < 0 = auto, ", + "--yarn-orig-ctx 0 = default, the rest positive)", + )), + Self::ModelType(t) => write!(f, "model file carries rope.scaling.type '{t}' - none, linear or yarn only"), Self::Invalid(e) => write!(f, "invalid rope scaling configuration: {e}"), } } @@ -125,9 +147,8 @@ impl fmt::Display for RopeKnobError { impl std::error::Error for RopeKnobError {} -/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, -/// the `none` reset, and the whole-config validity rule. -pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { +/// The range checks of the `generate.cpp` rope resolution. +fn check_knobs(knobs: &RopeKnobs) -> Result<(), RopeKnobError> { let all = [ knobs.rope_scale, knobs.rope_freq_base, @@ -147,40 +168,49 @@ pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result< if knobs.rope_freq_base != 0.0 && knobs.rope_freq_base <= 1.0 { return Err(RopeKnobError::FreqBase); } - if knobs.rope_freq_scale < 0.0 + if knob_out_of_range(knobs) { + return Err(RopeKnobError::Knob); + } + Ok(()) +} + +fn knob_out_of_range(knobs: &RopeKnobs) -> bool { + knobs.rope_freq_scale < 0.0 || knobs.yarn_orig_ctx < 0.0 || knobs.yarn_ext_factor < -1.0 || knobs.yarn_attn_factor <= 0.0 || knobs.yarn_beta_fast <= 0.0 || knobs.yarn_beta_slow <= 0.0 - { - return Err(RopeKnobError::Knob); - } +} - let mut cfg = RopeScaling::default(); +/// The flag's kind, else the model file's; `None` leaves the default. +fn resolve_kind(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result, RopeKnobError> { if let Some(kind) = knobs.scaling { + return Ok(Some(kind)); + } + match model.scaling_type.as_deref().filter(|t| !t.is_empty()) { + Some(t) => RopeScalingType::parse(t).map(Some).ok_or_else(|| RopeKnobError::ModelType(t.to_owned())), + None => Ok(None), + } +} + +/// Precedence flag > model file > the current value. +fn pick(flag: Option, model: Option, current: f64) -> f64 { + flag.or(model).unwrap_or(current) +} + +/// The configuration the knobs and the model file give before the `none` reset and the validity rule. +fn layered_config(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { + let mut cfg = RopeScaling::default(); + if let Some(kind) = resolve_kind(knobs, model)? { cfg.kind = kind; - } else if let Some(t) = model.scaling_type.as_deref().filter(|t| !t.is_empty()) { - match RopeScalingType::parse(t) { - Some(kind) => cfg.kind = kind, - None => return Err(RopeKnobError::ModelType(t.to_owned())), - } - } - if knobs.rope_scale > 0.0 { - cfg.factor = knobs.rope_scale; - } else if model.factor > 1.0 { - cfg.factor = model.factor; - } - if knobs.rope_freq_base > 0.0 { - cfg.freq_base = knobs.rope_freq_base; - } else if model.freq_base > 1.0 { - cfg.freq_base = model.freq_base; - } - if knobs.yarn_orig_ctx > 0.0 { - cfg.orig_ctx = knobs.yarn_orig_ctx; - } else if model.orig_ctx >= 1.0 { - cfg.orig_ctx = model.orig_ctx; } + let flag_factor = (knobs.rope_scale > 0.0).then_some(knobs.rope_scale); + cfg.factor = pick(flag_factor, (model.factor > 1.0).then_some(model.factor), cfg.factor); + let flag_base = (knobs.rope_freq_base > 0.0).then_some(knobs.rope_freq_base); + cfg.freq_base = pick(flag_base, (model.freq_base > 1.0).then_some(model.freq_base), cfg.freq_base); + let flag_orig = (knobs.yarn_orig_ctx > 0.0).then_some(knobs.yarn_orig_ctx); + cfg.orig_ctx = pick(flag_orig, (model.orig_ctx >= 1.0).then_some(model.orig_ctx), cfg.orig_ctx); cfg.freq_scale_in = knobs.rope_freq_scale; cfg.ext_factor = if knobs.yarn_ext_factor >= 0.0 { knobs.yarn_ext_factor @@ -192,7 +222,14 @@ pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result< cfg.attn_factor = knobs.yarn_attn_factor; cfg.beta_fast = knobs.yarn_beta_fast; cfg.beta_slow = knobs.yarn_beta_slow; + Ok(cfg) +} +/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, +/// the `none` reset, and the whole-config validity rule. +pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { + check_knobs(knobs)?; + let mut cfg = layered_config(knobs, model)?; let mut inert = false; if cfg.kind == RopeScalingType::None { inert = knobs.rope_scale > 1.0 diff --git a/crates/context/src/rope_scaling/impl_fmt_display_for.rs b/crates/context/src/rope_scaling/impl_fmt_display_for.rs index 2622fe36..e04d473f 100644 --- a/crates/context/src/rope_scaling/impl_fmt_display_for.rs +++ b/crates/context/src/rope_scaling/impl_fmt_display_for.rs @@ -6,12 +6,14 @@ use super::*; impl fmt::Display for SetupRopeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::ScaleWithoutMethod => f.write_str( - "--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the trained range, so there is nothing to scale)", - ), - Self::NoneBeyondTrained => f.write_str( - "the context is past the model's trained range and --rope-scaling none keeps the stock angles there; pick yarn or linear, or lower the context", - ), + Self::ScaleWithoutMethod => f.write_str(concat!( + "--rope-scale needs --rope-scaling linear or yarn ", + "(the chosen context fits the trained range, so there is nothing to scale)", + )), + Self::NoneBeyondTrained => f.write_str(concat!( + "the context is past the model's trained range and --rope-scaling none keeps the stock angles there; ", + "pick yarn or linear, or lower the context", + )), } } } diff --git a/crates/context/src/rope_scaling/impl_ropescalingtype.rs b/crates/context/src/rope_scaling/impl_ropescalingtype.rs index a172aada..812107c0 100644 --- a/crates/context/src/rope_scaling/impl_ropescalingtype.rs +++ b/crates/context/src/rope_scaling/impl_ropescalingtype.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl RopeScalingType, impl Default_for_RopeKernelArgs, impl RopeScalingError, impl fmt_Display_for, impl std_error_Error, impl Default_for_RopeScaling .... +//! Moved out of the parent module by STRA-338: impl RopeScalingType, impl Default_for_RopeKernelArgs, impl +//! RopeScalingError, impl fmt_Display_for, impl std_error_Error, impl Default_for_RopeScaling .... #[allow(unused_imports)] use super::*; @@ -115,41 +116,35 @@ impl RopeScaling { /// `rope_scaling_invalid`: the one validity rule. Every value is tested with `is_finite` first so a NaN /// cannot slip through a range comparison. pub fn validate(&self) -> Result<(), RopeScalingError> { - if !self.freq_base.is_finite() || self.freq_base <= 1.0 { + if not_ok(self.freq_base, |x| x > 1.0) { return Err(RopeScalingError::FreqBase); } if self.kind == RopeScalingType::None { return Ok(()); } - if !self.factor.is_finite() || self.factor < 1.0 { - return Err(RopeScalingError::Factor); - } - if !self.freq_scale_in.is_finite() || self.freq_scale_in < 0.0 { - return Err(RopeScalingError::FreqScaleIn); - } - let fs = self.freq_scale(); - if !fs.is_finite() || fs <= 0.0 { - return Err(RopeScalingError::ResolvedFreqScale); - } - if !self.orig_ctx.is_finite() || self.orig_ctx < 1.0 { - return Err(RopeScalingError::OrigCtx); - } - if !self.ext_factor.is_finite() || self.ext_factor < 0.0 { - return Err(RopeScalingError::ExtFactor); - } - if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 { - return Err(RopeScalingError::AttnFactor); - } - if !self.beta_fast.is_finite() || self.beta_fast <= 0.0 || !self.beta_slow.is_finite() || self.beta_slow <= 0.0 - { - return Err(RopeScalingError::Betas); - } - let ms = self.mscale(); - if !ms.is_finite() || ms <= 0.0 { - return Err(RopeScalingError::Mscale); - } - Ok(()) + self.validate_scaled() } + + /// The rules of a scaled configuration, the first miss in the order of the Original. + fn validate_scaled(&self) -> Result<(), RopeScalingError> { + let (fs, ms) = (self.freq_scale(), self.mscale()); + let misses = [ + (not_ok(self.factor, |x| x >= 1.0), RopeScalingError::Factor), + (not_ok(self.freq_scale_in, |x| x >= 0.0), RopeScalingError::FreqScaleIn), + (not_ok(fs, |x| x > 0.0), RopeScalingError::ResolvedFreqScale), + (not_ok(self.orig_ctx, |x| x >= 1.0), RopeScalingError::OrigCtx), + (not_ok(self.ext_factor, |x| x >= 0.0), RopeScalingError::ExtFactor), + (not_ok(self.attn_factor, |x| x > 0.0), RopeScalingError::AttnFactor), + (not_ok(self.beta_fast, |x| x > 0.0) || not_ok(self.beta_slow, |x| x > 0.0), RopeScalingError::Betas), + (not_ok(ms, |x| x > 0.0), RopeScalingError::Mscale), + ]; + misses.into_iter().find(|(missed, _)| *missed).map_or(Ok(()), |(_, error)| Err(error)) + } +} + +/// True when `x` is not finite or fails the range test `ok`. +fn not_ok(x: f64, ok: impl Fn(f64) -> bool) -> bool { + !x.is_finite() || !ok(x) } /// `rope_yarn_ramp`: 1 - clamp(y, 0, 1), float32, taking the PAIR index (ggml's `i0 / 2`). diff --git a/crates/context/tests/rope_plan_golden.rs b/crates/context/tests/rope_plan_golden.rs index 344f9731..64fd891a 100644 --- a/crates/context/tests/rope_plan_golden.rs +++ b/crates/context/tests/rope_plan_golden.rs @@ -189,7 +189,8 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) { 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" + "note: {name}: table hash over {n} rows differs from the macOS fixture (non-macOS libm); \ + sample rows are within tolerance" ); } } diff --git a/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs b/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs index 13ec748f..ce1554ec 100644 --- a/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs +++ b/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs @@ -1,4 +1,6 @@ -//! Tests of rope_plan_golden by topic (moved out of the test file by STRA-338): every_fixture_case_has_a_test, yarn_is_observably_different_from_none, strata_plan_cli_output_is_reproduced_exactly, kv_pool_bytes_match_the_originals_layer_cpp. +//! Tests of rope_plan_golden by topic (moved out of the test file by STRA-338): every_fixture_case_has_a_test, +//! yarn_is_observably_different_from_none, strata_plan_cli_output_is_reproduced_exactly, +//! kv_pool_bytes_match_the_originals_layer_cpp. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-fake/src/lib.rs b/crates/engine-fake/src/lib.rs index 11f37675..24ca1f90 100644 --- a/crates/engine-fake/src/lib.rs +++ b/crates/engine-fake/src/lib.rs @@ -1,5 +1,6 @@ -//! The scripted engine as an [`EngineFamily`], so the composition root starts it exactly as it starts the product engine -//! (`spawn::`) and a test drives everything above the engine without a GPU, a model or a gRPC server. +//! The scripted engine as an [`EngineFamily`], so the composition root starts it exactly as it starts the product +//! engine (`spawn::`) and a test drives everything above the engine without a GPU, a model or a gRPC +//! server. //! //! It computes nothing and makes no statement about any model: what it returns is what the test scripted through the //! [`ScriptedHandle`] it receives at start-up. diff --git a/limits-baseline.json b/limits-baseline.json index 29a1daa5..89d86871 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -13,11 +13,6 @@ "complexity": 2, "fn_lines": 3 }, - "leleka-context": { - "fn_lines": 6, - "complexity": 6, - "width": 9 - }, "leleka-cpu-kernels": { "fn_lines": 1 }, @@ -49,9 +44,6 @@ "complexity": 38, "width": 56 }, - "leleka-engine-fake": { - "width": 1 - }, "leleka-engine-qwen35-cuda": { "fn_lines": 606, "width": 760, @@ -159,12 +151,6 @@ "complexity": 1, "width": 2 }, - "leleka-obs": { - "fn_lines": 5, - "complexity": 4, - "width": 7, - "nesting": 1 - }, "leleka-offline-tools": { "fn_lines": 8, "complexity": 5, @@ -230,8 +216,7 @@ }, "leleka-context": { "fn_lines": 5, - "complexity": 1, - "width": 2 + "complexity": 1 }, "leleka-cpu-kernels": { "fn_lines": 8,