STRA-338 S13: prefill, cache and prefix settings

Kv topic of Settings: the prefill switches (stream, stream threshold, MoE span cache, GDN pool and mirror,
staged input), the dense slab, the prompt embedding alias, the legacy footprint, the PLE read-ahead and its
verification, the prefix retention and the checkpoint re-read. Every on-by-default switch keeps its own
spelling: on unless exactly 0 for the prefill group, packed unless 0 or off for the dense slab, trimmed
words for the footprint, an explicit word or the platform default for the read-ahead.

alias_requested, legacy_footprint_from and the draft-after-commit check remain as test-only helpers over
the same spelling tables that Settings uses, so the tests that exist for them still pin the production
spellings. The OnceLock readers of these keys are gone.
This commit is contained in:
Pavlo Ratushnyi
2026-11-05 22:23:05 +01:00
parent 4e6a9c6c24
commit dd584a09d6
16 changed files with 308 additions and 29 deletions
+2 -2
View File
@@ -165,7 +165,7 @@
"env-read:leleka-npu-service": 1,
"env-read:leleka-npu-worker": 1,
"env-read:leleka-obs": 2,
"env-read:leleka-runtime": 37,
"env-read:leleka-runtime": 24,
"env-read:leleka-tokenizer": 2,
"env-read:strata-control": 19,
"env-read:strata-desktop-core": 15,
@@ -198,7 +198,7 @@
"process-global:leleka-model-format": 8,
"process-global:leleka-native-cpu-expert": 32,
"process-global:leleka-obs": 7,
"process-global:leleka-runtime": 81,
"process-global:leleka-runtime": 69,
"process-global:leleka-tokenizer": 4,
"process-global:strata-control": 14
}
@@ -20,13 +20,12 @@ fn prompt_stream_settings() -> Option<(usize, f64)> {
let on = match PREFILL_STREAM_OVERRIDE.load(Ordering::Relaxed) {
0 => false,
1 => true,
_ => std::env::var("LELEKA_PREFILL_STREAM").map_or(true, |v| v != "0"),
_ => crate::settings::process().kv.prefill_stream,
};
if !on {
return None;
}
let number = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default);
Some((number("STRATA_PREFILL_STREAM_MIN", 4096), 45e9))
Some((crate::settings::process().kv.prefill_stream_min, 45e9))
}
/// Test harness switch for in-process paired A/B (`LELEKA_PREFILL_STREAM_SEQ`): -1 = the environment, 0 off, 1 on.
pub static PREFILL_STREAM_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
@@ -48,8 +47,7 @@ pub(crate) fn span_cache_enabled() -> bool {
1 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_MOE_SPAN_CACHE").map_or(true, |v| v != "0"))
crate::settings::process().kv.prefill_moe_span_cache
}
static SPAN_CACHE_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
/// Per-arm override for the replay harness: 1 on, 0 off, -1 follow the environment.
@@ -6,7 +6,7 @@ use super::*;
/// `LELEKA_DENSE_SLAB=0` keeps one allocation per weight (the A/B arm and the rollback); otherwise the dense weights are packed
/// into 64 MiB slabs. Both place the same bytes: only buffer addresses move.
pub(super) fn dense_slab_policy() -> SlabPolicy {
if std::env::var("LELEKA_DENSE_SLAB").is_ok_and(|v| v == "0" || v == "off") {
if !crate::settings::process().kv.dense_slab {
// every request above one byte exceeds the direct limit: no slab is ever opened
SlabPolicy { direct_above: 1, ..SlabPolicy::DENSE }
} else {
@@ -5,6 +5,5 @@ use super::*;
/// `LELEKA_PREFILL_STAGED_INPUT=0` keeps the per-token host path of the KAR inputs (the A/B arm).
pub(super) fn staged_input_enabled()->bool{
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
*ON.get_or_init(||std::env::var("LELEKA_PREFILL_STAGED_INPUT").map_or(true,|v|v!="0"))
crate::settings::process().kv.prefill_staged_input
}
@@ -146,8 +146,7 @@ pub(in super::super) fn pool_enabled() -> bool {
1 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_GDN_POOL").map_or(true, |v| v != "0"))
crate::settings::process().kv.prefill_gdn_pool
}
/// Per-arm override of the pool switch for the replay harness: 1 on, 0 off, -1 follow the environment.
pub(crate) fn set_pool_override(value: i8) {
@@ -5,8 +5,7 @@ use super::*;
pub(super) fn mirror_reuse_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_GDN_MIRROR").map_or(true, |v| v != "0"))
crate::settings::process().kv.prefill_gdn_mirror
}
impl ChunkEdge {
pub(in crate::qwen_forward) fn into_parts(self) -> (GdnChunkRow, Option<Rc<super::super::verification::VerifiedRow>>) { (self.row, self.verified) }
@@ -145,7 +145,7 @@ impl<'ctx> KarPleCache<'ctx> {
}
}
// LELEKA_PLE_AHEAD_VERIFY=1: every packet taken from the read-ahead is compared with a direct read of its row
if !from_ahead.is_empty() && std::env::var("LELEKA_PLE_AHEAD_VERIFY").is_ok_and(|v| v == "1") {
if !from_ahead.is_empty() && crate::settings::process().kv.ple_ahead_verify {
let rows: Vec<u64> = from_ahead.iter().map(|(_, row)| *row).collect();
let direct = binding
.read_rows_batch(&rows)
@@ -22,12 +22,7 @@ pub(super) fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], ro
/// archive is a file the rows are read from at 20-45 k random reads a second (5 to 12 s of every 6144-token chunk); off elsewhere, where
/// the server profile keeps the archive in a memfd and its rows are a memory read (not measured, so not changed).
pub(super) fn ahead_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| match std::env::var("LELEKA_PLE_AHEAD").ok().as_deref() {
Some("on" | "1" | "yes") => true,
Some("off" | "0" | "no") => false,
_ => cfg!(windows),
})
crate::settings::process().kv.ple_ahead
}
impl Ahead {
/// Wait for the outstanding read-ahead and keep what it read.
@@ -30,7 +30,7 @@ impl<'ctx> OriginalPromptEmbedding<'ctx>{
/// host copy the native embedding already holds, instead of a second 324 MiB copy in VRAM (and a second 322 MiB read at load).
/// Prefill gathers 8192 rows of 1,360 B per chunk (11 MB over PCIe); the MTP drafter's per-round row is one more.
pub(in crate::qwen_forward) fn alias_enabled()->bool{
alias_requested(std::env::var("LELEKA_PROMPT_EMBED_ALIAS").ok().as_deref())
crate::settings::process().kv.prompt_embed_alias
}
/// The same table, aliased onto `native` (its mapped host copy or device fallback). Identity is checked against the binding's own
/// layout so a different tensor can never be aliased. `native` must outlive every use: close this owner first.
@@ -63,7 +63,10 @@ impl<'ctx> OriginalPromptEmbedding<'ctx>{
impl Drop for OriginalPromptEmbedding<'_>{fn drop(&mut self){let _=self.close_inner();}}
/// The switch's reading: only an explicit yes turns the alias on.
fn alias_requested(value:Option<&str>)->bool{matches!(value,Some("1"|"on"|"yes"))}
#[cfg(test)]
fn alias_requested(value:Option<&str>)->bool{
crate::settings::text_is_one_of(value,&crate::settings::PROMPT_EMBED_ALIAS_ON)
}
#[cfg(test)]
mod tests{
use super::alias_requested;
@@ -18,11 +18,11 @@ pub(in crate::qwen_forward) const VERIFY_MAX_T: usize = 8;
/// the pinned MTP pack's expert bank next to the RT-directory copy (675 MiB, `MoeWeightCache::new_with_mtp_experts`) and the legacy host-canonical
/// QSA index-key mirror (12 x 32 MiB, `QsaIndexKeyCache`). The switch exists as the A/B baseline and as a rollback; the default is OFF (not held).
pub(in crate::qwen_forward) fn legacy_footprint() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| legacy_footprint_from(std::env::var("LELEKA_FOOTPRINT_LEGACY").ok().as_deref()))
crate::settings::process().kv.footprint_legacy
}
#[cfg(test)]
fn legacy_footprint_from(value: Option<&str>) -> bool {
matches!(value.map(str::trim), Some("1" | "on" | "yes" | "true"))
crate::settings::trimmed_text_is_one_of(value, &crate::settings::FOOTPRINT_LEGACY_ON)
}
/// Whether the MoE cache uploads the pinned MTP pack's expert bank: only when the draft layer is NOT loaded from an RT directory (the pack-driven draft
/// reads it) or the legacy footprint is asked for.
@@ -56,7 +56,7 @@ impl ConversationConfig {
prompt_cache_every: 16_384,
prompt_cache_root: 2048,
turn_token: Some(TURN_TOKEN),
reread_checkpoints: std::env::var_os("STRATA_CKPT_REREAD").is_some(),
reread_checkpoints: crate::settings::process().kv.ckpt_reread,
}
}
pub(crate) fn validate(&self) -> Result<(), Error> {
@@ -15,7 +15,7 @@ impl PrefixConfig {
// LELEKA_PREFIX_RETENTION_S: session retention in seconds (default 3600 = 60 minutes; 0 = no time limit); a
// diagnostic knob so the expiry path can be exercised in minutes
let mut policy = PolicyParams::default();
if let Some(seconds) = std::env::var("LELEKA_PREFIX_RETENTION_S").ok().and_then(|v| v.trim().parse::<u64>().ok()) {
if let Some(seconds) = crate::settings::process().kv.prefix_retention_s {
policy.retention_ms = seconds.saturating_mul(1000);
}
policy
+9 -1
View File
@@ -6,6 +6,7 @@
//! read the captured namespace through [`Settings::env`] where they always did. Every field keeps the default, the
//! spelling and the fallback of the call site it replaced; the tests of each topic pin them with a `MapEnv`.
mod decode;
mod kv;
mod memory;
mod parse;
mod serve;
@@ -16,6 +17,8 @@ mod capture_tests;
#[cfg(test)]
mod decode_tests;
#[cfg(test)]
mod kv_tests;
#[cfg(test)]
mod memory_tests;
#[cfg(test)]
mod serve_tests;
@@ -23,9 +26,12 @@ mod serve_tests;
#[cfg(test)]
pub(crate) use decode::DRAFT_AFTER_COMMIT_ON;
pub(crate) use decode::DecodeSettings;
pub(crate) use kv::KvSettings;
#[cfg(test)]
pub(crate) use kv::{FOOTPRINT_LEGACY_ON, PROMPT_EMBED_ALIAS_ON};
pub(crate) use memory::MemorySettings;
#[cfg(test)]
pub(crate) use parse::text_is_one_of;
pub(crate) use parse::{text_is_one_of, trimmed_text_is_one_of};
pub(crate) use serve::ServeSettings;
pub(crate) use source::{EnvSource, MapEnv, ProcessEnv};
@@ -39,6 +45,7 @@ pub(crate) struct Settings {
pub(crate) serve: ServeSettings,
pub(crate) decode: DecodeSettings,
pub(crate) memory: MemorySettings,
pub(crate) kv: KvSettings,
}
impl Settings {
@@ -49,6 +56,7 @@ impl Settings {
serve: ServeSettings::from_source(&env),
decode: DecodeSettings::from_source(&env),
memory: MemorySettings::from_source(&env),
kv: KvSettings::from_source(&env),
env,
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Settings of the prompt path and the caches around it: prefill streaming, the weight and K/V footprint switches, the
//! PLE read-ahead and the cross-session prefix cache.
use super::parse::{
equals, on_unless_zero, one_of, text_is_one_of, trimmed_number, trimmed_text_is_one_of,
};
use super::source::EnvSource;
/// The spellings that turn `LELEKA_PROMPT_EMBED_ALIAS` on.
pub(crate) const PROMPT_EMBED_ALIAS_ON: [&str; 3] = ["1", "on", "yes"];
/// The spellings (after trimming) that turn `LELEKA_FOOTPRINT_LEGACY` on.
pub(crate) const FOOTPRINT_LEGACY_ON: [&str; 4] = ["1", "on", "yes", "true"];
/// What the operator chose for prefill, the weight caches and the prefix cache.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct KvSettings {
/// `LELEKA_PREFILL_STREAM`: on unless exactly `0` (the per-layer copy ring is the alternative).
pub(crate) prefill_stream: bool,
/// `STRATA_PREFILL_STREAM_MIN`: the smallest chunk that streams, a trimmed `usize`, 4096 otherwise.
pub(crate) prefill_stream_min: usize,
/// `LELEKA_PREFILL_MOE_SPAN_CACHE`: on unless exactly `0`.
pub(crate) prefill_moe_span_cache: bool,
/// `LELEKA_PREFILL_GDN_POOL`: on unless exactly `0`.
pub(crate) prefill_gdn_pool: bool,
/// `LELEKA_PREFILL_GDN_MIRROR`: on unless exactly `0`.
pub(crate) prefill_gdn_mirror: bool,
/// `LELEKA_PREFILL_STAGED_INPUT`: on unless exactly `0`.
pub(crate) prefill_staged_input: bool,
/// `LELEKA_DENSE_SLAB`: the dense weights are packed into slabs unless the value is exactly `0` or `off`.
pub(crate) dense_slab: bool,
/// `LELEKA_PROMPT_EMBED_ALIAS` is `1`, `on` or `yes`.
pub(crate) prompt_embed_alias: bool,
/// `LELEKA_FOOTPRINT_LEGACY` is `1`, `on`, `yes` or `true` (trimmed).
pub(crate) footprint_legacy: bool,
/// `LELEKA_PLE_AHEAD`: `on|1|yes` and `off|0|no` decide, anything else follows the platform default (Windows on).
pub(crate) ple_ahead: bool,
/// `LELEKA_PLE_AHEAD_VERIFY=1`.
pub(crate) ple_ahead_verify: bool,
/// `LELEKA_PREFIX_RETENTION_S`: session retention in seconds, a trimmed `u64`.
pub(crate) prefix_retention_s: Option<u64>,
/// `STRATA_CKPT_REREAD` is set (to anything).
pub(crate) ckpt_reread: bool,
}
impl KvSettings {
pub(super) fn from_source(env: &impl EnvSource) -> Self {
Self {
prefill_stream: on_unless_zero(env, "LELEKA_PREFILL_STREAM"),
prefill_stream_min: trimmed_number::<usize>(env, "STRATA_PREFILL_STREAM_MIN")
.unwrap_or(4096),
prefill_moe_span_cache: on_unless_zero(env, "LELEKA_PREFILL_MOE_SPAN_CACHE"),
prefill_gdn_pool: on_unless_zero(env, "LELEKA_PREFILL_GDN_POOL"),
prefill_gdn_mirror: on_unless_zero(env, "LELEKA_PREFILL_GDN_MIRROR"),
prefill_staged_input: on_unless_zero(env, "LELEKA_PREFILL_STAGED_INPUT"),
dense_slab: !one_of(env, "LELEKA_DENSE_SLAB", &["0", "off"]),
prompt_embed_alias: text_is_one_of(
env.get("LELEKA_PROMPT_EMBED_ALIAS").as_deref(),
&PROMPT_EMBED_ALIAS_ON,
),
footprint_legacy: trimmed_text_is_one_of(
env.get("LELEKA_FOOTPRINT_LEGACY").as_deref(),
&FOOTPRINT_LEGACY_ON,
),
ple_ahead: ple_ahead(env.get("LELEKA_PLE_AHEAD").as_deref()),
ple_ahead_verify: equals(env, "LELEKA_PLE_AHEAD_VERIFY", "1"),
prefix_retention_s: trimmed_number::<u64>(env, "LELEKA_PREFIX_RETENTION_S"),
ckpt_reread: env.is_set("STRATA_CKPT_REREAD"),
}
}
}
/// The read-ahead switch: an explicit word wins, otherwise the platform default (the archive is a file on Windows).
fn ple_ahead(value: Option<&str>) -> bool {
match value {
Some("on" | "1" | "yes") => true,
Some("off" | "0" | "no") => false,
_ => cfg!(windows),
}
}
@@ -0,0 +1,195 @@
//! Golden cases of the kv topic: each row is what the call site this field replaced returned for that value.
use super::*;
fn kv(pairs: &[(&str, &str)]) -> KvSettings {
KvSettings::from_source(&MapEnv::of(pairs))
}
fn rows(key: &str, field: fn(&KvSettings) -> bool, unset: bool, values: &[(&str, bool)]) {
assert_eq!(field(&kv(&[])), unset, "{key} unset");
for (value, want) in values {
assert_eq!(field(&kv(&[(key, value)])), *want, "{key}={value:?}");
}
}
#[test]
fn the_prefill_switches_are_on_unless_exactly_zero() {
let spellings = [
("0", false),
("off", true),
("1", true),
("", true),
("00", true),
(" 0", true),
];
rows(
"LELEKA_PREFILL_STREAM",
|k| k.prefill_stream,
true,
&spellings,
);
rows(
"LELEKA_PREFILL_MOE_SPAN_CACHE",
|k| k.prefill_moe_span_cache,
true,
&spellings,
);
rows(
"LELEKA_PREFILL_GDN_POOL",
|k| k.prefill_gdn_pool,
true,
&spellings,
);
rows(
"LELEKA_PREFILL_GDN_MIRROR",
|k| k.prefill_gdn_mirror,
true,
&spellings,
);
rows(
"LELEKA_PREFILL_STAGED_INPUT",
|k| k.prefill_staged_input,
true,
&spellings,
);
}
#[test]
fn the_stream_threshold_is_a_trimmed_usize_with_a_default() {
assert_eq!(kv(&[]).prefill_stream_min, 4096);
for (value, want) in [
("2048", 2048),
(" 8192 ", 8192),
("0", 0),
("-1", 4096),
("x", 4096),
("", 4096),
("1.5", 4096),
] {
assert_eq!(
kv(&[("STRATA_PREFILL_STREAM_MIN", value)]).prefill_stream_min,
want,
"{value:?}"
);
}
}
#[test]
fn dense_slab_is_packed_unless_zero_or_off() {
let spellings = [
("0", false),
("off", false),
("1", true),
("on", true),
("OFF", true),
("", true),
];
rows("LELEKA_DENSE_SLAB", |k| k.dense_slab, true, &spellings);
}
#[test]
fn the_prompt_embedding_alias_spellings_are_exact() {
let spellings = [
("1", true),
("on", true),
("yes", true),
("", false),
("0", false),
("off", false),
("no", false),
("true", false),
("2", false),
(" 1", false),
];
rows(
"LELEKA_PROMPT_EMBED_ALIAS",
|k| k.prompt_embed_alias,
false,
&spellings,
);
}
#[test]
fn the_legacy_footprint_spellings_are_trimmed() {
let spellings = [
("1", true),
("on", true),
("yes", true),
("true", true),
(" on ", true),
("", false),
("0", false),
("off", false),
("ON", false),
];
rows(
"LELEKA_FOOTPRINT_LEGACY",
|k| k.footprint_legacy,
false,
&spellings,
);
}
#[test]
fn the_ple_read_ahead_follows_a_word_or_the_platform() {
let platform = cfg!(windows);
assert_eq!(kv(&[]).ple_ahead, platform);
for (value, want) in [
("on", true),
("1", true),
("yes", true),
("off", false),
("0", false),
("no", false),
] {
assert_eq!(
kv(&[("LELEKA_PLE_AHEAD", value)]).ple_ahead,
want,
"{value:?}"
);
}
for value in ["", "auto", "ON", "true", " on"] {
assert_eq!(
kv(&[("LELEKA_PLE_AHEAD", value)]).ple_ahead,
platform,
"{value:?}"
);
}
let verify = [("1", true), ("on", false), ("0", false), ("", false)];
rows(
"LELEKA_PLE_AHEAD_VERIFY",
|k| k.ple_ahead_verify,
false,
&verify,
);
}
#[test]
fn the_prefix_retention_is_a_trimmed_u64() {
assert_eq!(kv(&[]).prefix_retention_s, None);
for (value, want) in [
("3600", Some(3600)),
(" 60 ", Some(60)),
("0", Some(0)),
("-1", None),
("1.5", None),
("x", None),
("", None),
] {
assert_eq!(
kv(&[("LELEKA_PREFIX_RETENTION_S", value)]).prefix_retention_s,
want,
"{value:?}"
);
}
}
#[test]
fn the_checkpoint_reread_switch_is_set_ness() {
rows(
"STRATA_CKPT_REREAD",
|k| k.ckpt_reread,
false,
&[("1", true), ("0", true), ("", true)],
);
}
@@ -47,3 +47,8 @@ pub(super) fn positive_gib(env: &impl EnvSource, key: &str) -> Option<f64> {
pub(crate) fn text_is_one_of(value: Option<&str>, wants: &[&str]) -> bool {
value.is_some_and(|v| wants.contains(&v))
}
/// [`text_is_one_of`] after trimming the value.
pub(crate) fn trimmed_text_is_one_of(value: Option<&str>, wants: &[&str]) -> bool {
text_is_one_of(value.map(str::trim), wants)
}