engine: the stack configuration, the request, the PLE reader, the conversation cache and the open phases read the settings of their binding (STRA-338)

StackConfig::new, stack_config and options_config take the Settings; RequestToServe carries them to the sampling
path (RequestSampling::path) and the capture directory; the open phases (serve policies, MTP pack experts, footprint
switch, decode graph reuse) and the QSA index key cache read ModelBinding::settings(); ResidentPolicy::from_environment
is gone (the load hands its settings to new_conversations); the PLE policy and the gguf-ple opt-in read the binding's
settings. The backend choice and the public-evaluation check capture the environment at their entry points.
This commit is contained in:
Pavlo Ratushnyi
2026-11-28 09:57:25 +01:00
parent 972cb9542d
commit 2e872c37ce
35 changed files with 185 additions and 118 deletions
@@ -129,7 +129,12 @@ impl Rig {
let generate = original_serve::runner::generate;
let link = original_serve::runner::ClientLink { sink, cancel, shared, clock: &*clock };
let vocabulary = original_serve::runner::TokenVocabulary { tokenizer, eos: eos as u32 };
let to_serve = original_serve::runner::RequestToServe { request, prompt: ids, spec_min_p: 0.0 };
let to_serve = original_serve::runner::RequestToServe {
request,
prompt: ids,
spec_min_p: 0.0,
settings: &crate::settings::Settings::from_environment(),
};
generate(stack, &link, &vocabulary, to_serve)
}
@@ -102,7 +102,7 @@ fn serve_native<'d>(
return Ok(None);
}
let mut unload_reply = None;
let mut conversations = new_conversations();
let mut conversations = new_conversations(env.settings);
let mut serving = Serving::new(env, bound, context, &loaded, &mut weights);
serve_commands(&mut serving, &mut conversations, &mut unload_reply)?;
Ok(Some(close_weights(env.shared, conversations, weights, unload_reply)))
@@ -20,7 +20,7 @@ pub(super) struct LoopCtx<'r, 'a, 'ctx> {
impl<'r> LoopCtx<'r, '_, '_> {
/// What a generate command reads: the loop's facts and the settings in force.
fn generate_env(&self, live: &Live<'_, '_, '_>) -> GenerateEnv<'r> {
fn generate_env(&self, live: &Live<'_, '_, '_>) -> GenerateEnv<'_> {
GenerateEnv {
shared: self.shared,
tokenizer: self.tokenizer,
@@ -30,6 +30,7 @@ impl<'r> LoopCtx<'r, '_, '_> {
spec_min_p: live.options.spec_min_p,
context_tokens: *live.context_tokens,
memory: self.reopen.memory,
settings: self.reopen.binding.settings(),
}
}
}
@@ -31,13 +31,13 @@ pub(super) fn open_run_stack<'a, 'ctx>(
memory: &MemoryServices,
) -> Result<(Stack<'a, 'ctx>, i32), BackendError> {
let RecordedModel { artifact_digest, files: model_files } = model;
let config = stack_config(options, context_tokens, memory)?;
let config = stack_config(options, context_tokens, (memory, binding.settings()))?;
let workers = config.cpu_workers;
// STRA-325: build id, recorded model digest and effective tuning, once, before the stack opens (operator log only;
// reads nothing the stack uses)
crate::serve_meta::emit(&crate::serve_meta::startup_lines(
&crate::serve_meta::BuildInfo::current(),
&crate::serve_meta::ProfileInfo::from_settings(crate::settings::process()),
&crate::serve_meta::ProfileInfo::from_settings(binding.settings()),
&crate::serve_meta::ModelInfo::recorded(artifact_digest, model_files),
&meta_facts(&config, options, context_tokens),
));
@@ -128,6 +128,8 @@ pub(super) struct GenerateEnv<'r> {
pub(super) spec_min_p: f32,
pub(super) context_tokens: u32,
pub(super) memory: &'r MemoryServices,
/// The operator settings of the loaded binding.
pub(super) settings: &'r crate::settings::Settings,
}
impl<'r> GenerateEnv<'r> {
@@ -248,7 +250,7 @@ fn run_generation(
) {
let (sink, cancel) = channel;
let (shared, clock) = (env.shared, env.clock);
let to_serve = RequestToServe { request, prompt, spec_min_p: env.spec_min_p };
let to_serve = RequestToServe { request, prompt, spec_min_p: env.spec_min_p, settings: env.settings };
let result = generate(owner, &env.client_link(sink, cancel), &env.vocabulary(), to_serve);
let terminal = match result {
Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage },
@@ -62,7 +62,7 @@ fn open_stack<'a, 'ctx>(
options: &OriginalServeOptions,
tokens: u32,
) -> Result<(Stack<'a, 'ctx>, i32), BackendError> {
let config = stack_config(options, tokens, env.memory)?;
let config = stack_config(options, tokens, (env.memory, env.binding.settings()))?;
let workers = config.cpu_workers;
let opened = OriginalServeStack::open(env.binding, env.context.as_ref(), Rc::clone(env.context), config)
.map_err(|failure| open_error(&failure))?;
@@ -72,12 +72,16 @@ impl<'x, F: Fn() -> bool, C: Clock> Delivery<'x, F, C> {
/// The request as the stack serves it: the prompt, the budget, the sampler and the stop tokens.
fn serve_request_for(to_serve: RequestToServe<'_>, eos: u32) -> Result<ServeRequest, GenerationFailure> {
let RequestToServe { request, prompt, spec_min_p } = to_serve;
let RequestToServe { request, prompt, spec_min_p, settings } = to_serve;
let sampler = request_sampler(request, clock_seed()).map_err(|_| invalid("unsupported generation request"))?;
Ok(ServeRequest::new(
prompt.iter().map(|&t| t as i32).collect(),
request.max_output_tokens as usize,
RequestSampling { plan: sampler.as_ref(), entropy: clock_seed() },
RequestSampling {
plan: sampler.as_ref(),
entropy: clock_seed(),
path: crate::qwen_forward::original_serve_config::sampler_path_in(settings),
},
spec_min_p,
crate::qwen_forward::original_serve_request::original_stop_tokens(eos),
))
@@ -110,6 +114,8 @@ pub(in super::super::super) struct RequestToServe<'x> {
pub(in super::super::super) request: &'x GenerationRequest,
pub(in super::super::super) prompt: &'x [u32],
pub(in super::super::super) spec_min_p: f32,
/// The operator settings: the sampling kernel and the capture directory of the request.
pub(in super::super::super) settings: &'x crate::settings::Settings,
}
/// One request over the stack; the caller owns the stream/terminal bookkeeping.
@@ -119,7 +125,8 @@ pub(in super::super::super) fn generate<C: Clock>(
vocabulary: &TokenVocabulary<'_>,
to_serve: RequestToServe<'_>,
) -> Result<(FinishReason, Usage), GenerationFailure> {
let RequestToServe { request, prompt, .. } = to_serve;
let RequestToServe { request, prompt, settings, .. } = to_serve;
let capture_dir = settings.serve.capture_dir.as_deref();
let clock = link.clock;
let serve_request = serve_request_for(to_serve, vocabulary.eos)?;
let cancelled = || link.should_stop();
@@ -133,17 +140,17 @@ pub(in super::super::super) fn generate<C: Clock>(
};
let result = stack.serve(&serve_request, &mut |tokens: &[i32]| delivery.deliver(tokens), &mut probe);
let outcome = served_outcome(delivery.captured.take(), timed_out, result)?;
finish_request(stack, link, (prompt, request), (delivery, outcome))
finish_request(stack, link, (prompt, request, capture_dir), (delivery, outcome))
}
/// `LELEKA_CAPTURE_DIR`: the request is written out for the offline replay.
/// The request is written out for the offline replay when the operator named a capture directory.
fn capture_if_configured(
stack: &impl ServeDevice,
ids: (&[u32], &[i32]),
request: &GenerationRequest,
outcome: ServeOutcome,
(outcome, capture_dir): (ServeOutcome, Option<&std::ffi::OsStr>),
) {
if let Some(directory) = crate::settings::process().serve.capture_dir.as_ref() {
if let Some(directory) = capture_dir {
let (prompt, generated) = ids;
let reused = stack.reused_tokens() as u64;
let ids = CapturedIds { prompt, generated };
@@ -155,12 +162,12 @@ fn capture_if_configured(
fn finish_request<F: Fn() -> bool, C: Clock>(
stack: &impl ServeDevice,
link: &ClientLink<'_, C>,
asked: (&[u32], &GenerationRequest),
asked: (&[u32], &GenerationRequest, Option<&std::ffi::OsStr>),
served: (Delivery<'_, F, C>, ServeOutcome),
) -> Result<(FinishReason, Usage), GenerationFailure> {
let ((prompt, request), (mut delivery, outcome)) = (asked, served);
let ((prompt, request, capture_dir), (mut delivery, outcome)) = (asked, served);
let (sink, clock) = (link.sink, link.clock);
capture_if_configured(stack, (prompt, &delivery.generated_ids), request, outcome);
capture_if_configured(stack, (prompt, &delivery.generated_ids), request, (outcome, capture_dir));
let reason = match outcome.stop {
ServeStop::Eos => FinishReason::Stop,
ServeStop::Length | ServeStop::Context => FinishReason::Length,
@@ -32,7 +32,10 @@ pub(super) fn gpu_probe(ordinal: u32) -> Option<GpuProbe> {
}
}
fn prefix_config(prefix: &super::super::PrefixCacheOptions) -> crate::qwen_forward::original_serve_stack::PrefixConfig {
fn prefix_config(
prefix: &super::super::PrefixCacheOptions,
serve: &crate::settings::ServeSettings,
) -> crate::qwen_forward::original_serve_stack::PrefixConfig {
use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig, TailMode};
let mut prefix_config = PrefixConfig {
tail: match prefix.tail {
@@ -46,7 +49,7 @@ fn prefix_config(prefix: &super::super::PrefixCacheOptions) -> crate::qwen_forwa
Some(bytes) => PrefixBudget::Bytes(bytes),
},
block_tokens: prefix.block_tokens,
defer_decode_tail: crate::settings::process().serve.prefix_park_async,
defer_decode_tail: serve.prefix_park_async,
..PrefixConfig::auto()
};
if let Some(seconds) = prefix.retention_s {
@@ -56,17 +59,21 @@ fn prefix_config(prefix: &super::super::PrefixCacheOptions) -> crate::qwen_forwa
}
/// The serve stack's configuration for these settings (everything except the weights, which stay loaded), over the
/// engine's memory services.
/// engine's memory services and the operator settings of the engine.
pub(super) fn stack_config(
options: &OriginalServeOptions,
context_tokens: u32,
memory: &leleka_memory::MemoryServices,
(memory, settings): (&leleka_memory::MemoryServices, &crate::settings::Settings),
) -> Result<StackConfig, BackendError> {
Ok(StackConfig { memory: memory.clone(), ..options_config(options, context_tokens)? })
Ok(StackConfig { memory: memory.clone(), ..options_config(options, context_tokens, settings)? })
}
fn options_config(options: &OriginalServeOptions, context_tokens: u32) -> Result<StackConfig, BackendError> {
let mut config = StackConfig::new(i64::from(context_tokens));
fn options_config(
options: &OriginalServeOptions,
context_tokens: u32,
settings: &crate::settings::Settings,
) -> Result<StackConfig, BackendError> {
let mut config = StackConfig::new(i64::from(context_tokens), settings);
if let Some(capacity) = options.prefill_capacity {
config.capacity = capacity;
}
@@ -82,19 +89,19 @@ fn options_config(options: &OriginalServeOptions, context_tokens: u32) -> Result
}
config.conversation = options.conversation();
if let Some(prefix) = options.prefix_cache.as_ref() {
config.prefix = Some(prefix_config(prefix));
config.prefix = Some(prefix_config(prefix, &settings.serve));
}
// The VRAM expert tier (off unless LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS / _EXPERT_PROFILE select it).
config.expert_tier =
crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment().map_err(|_| {
load_failure(
LoadPhase::OriginalStack,
invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"),
)
})?;
config.expert_tier = expert_tier_config()?;
Ok(config)
}
/// The VRAM expert tier (off unless LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS / _EXPERT_PROFILE select it).
fn expert_tier_config() -> Result<crate::qwen_forward::original_serve_residency::ExpertTierConfig, BackendError> {
crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment().map_err(|_| {
load_failure(LoadPhase::OriginalStack, invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"))
})
}
fn prefix_tail_label(tail: Option<crate::qwen_forward::original_serve_stack::TailMode>) -> &'static str {
use crate::qwen_forward::original_serve_stack::TailMode;
match tail {
@@ -183,7 +183,10 @@ fn print_config(config: &StackConfig, budget_gib: usize) {
}
fn laptop_stack_config() -> StackConfig {
let mut config = StackConfig::new(number("LELEKA_LAPTOP_MAX_CONTEXT", 8192) as i64);
let mut config = StackConfig::new(
number("LELEKA_LAPTOP_MAX_CONTEXT", 8192) as i64,
&crate::settings::Settings::from_environment(),
);
config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048);
config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32;
if let Ok(v) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT") {
@@ -99,7 +99,7 @@ fn start_governor(
prefix: plan.prefix_arg(),
prompt_cache: 6,
},
crate::settings::process(),
&crate::settings::Settings::from_environment(),
)
.unwrap_or_else(|e| panic!("memory plan refused: {}", e.message));
crate::memory_governor::guard_archive(&governor, inherited)
@@ -148,7 +148,7 @@ fn load(plan: &Plan, memory: MemoryServices) -> Loaded {
Loaded { binding, _inherited: inherited, tokenizer, eos, memory, governor, budget_gib }
}
fn stack_config(plan: &Plan) -> StackConfig {
let mut config = StackConfig::new(plan.max_context as i64);
let mut config = StackConfig::new(plan.max_context as i64, &crate::settings::Settings::from_environment());
config.capacity = plan.capacity;
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.kv_resident = plan.resident;
@@ -30,7 +30,8 @@ pub(super) fn run() {
let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE");
let inherited = InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed");
let memory = MemoryServices::new();
let governor = crate::memory_governor::install(&memory, false, crate::settings::process()).expect("governor");
let governor = crate::memory_governor::install(&memory, false, &crate::settings::Settings::from_environment())
.expect("governor");
let started = std::time::Instant::now();
let report = crate::memory_governor::guard_archive(&governor, &inherited);
eprintln!(
@@ -103,7 +103,7 @@ fn set_mode(config: &mut StackConfig, plan: &Plan) {
}
}
fn stack_config(plan: &Plan) -> StackConfig {
let mut config = StackConfig::new(plan.max_context as i64);
let mut config = StackConfig::new(plan.max_context as i64, &crate::settings::Settings::from_environment());
config.capacity = plan.capacity;
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.kv_resident = plan.resident;
@@ -16,7 +16,10 @@ fn tail_mode(arm: &str) -> TailMode {
}
}
fn arm_config(shape: &ArmShape) -> StackConfig {
let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64);
let mut config = StackConfig::new(
number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64,
&crate::settings::Settings::from_environment(),
);
config.capacity = shape.capacity;
if let Some(on) = shape.tiers {
config.loan_tiers = on;
@@ -52,7 +52,13 @@ fn request(
ServeRequest::new(
prompt.iter().map(|&t| t as i32).collect(),
max_new,
RequestSampling { plan: sampler, entropy: 7 },
RequestSampling {
plan: sampler,
entropy: 7,
path: crate::qwen_forward::original_serve_config::sampler_path_in(
&crate::settings::Settings::from_environment(),
),
},
0.0,
crate::qwen_forward::original_serve_request::original_stop_tokens(eos),
)
@@ -222,7 +222,7 @@ impl Resume<'_, '_> {
}
}
fn resume_config(cache: bool) -> StackConfig {
let mut config = StackConfig::new(8192);
let mut config = StackConfig::new(8192, &crate::settings::Settings::from_environment());
config.capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024);
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.conversation = cache.then(crate::qwen_forward::original_serve_stack::ConversationConfig::original);
@@ -208,7 +208,7 @@ impl Cov<'_, '_> {
}
}
fn coverage_config(conversation: Option<crate::qwen_forward::original_serve_stack::ConversationConfig>) -> StackConfig {
let mut config = StackConfig::new(16_384);
let mut config = StackConfig::new(16_384, &crate::settings::Settings::from_environment());
config.capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024);
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.conversation = conversation;
@@ -114,7 +114,7 @@ fn build_prompts(tokenizer: &Tokenizer, plan: &Plan) -> Vec<Vec<u32>> {
.collect()
}
fn long_config(plan: &Plan) -> StackConfig {
let mut config = StackConfig::new(plan.max_context as i64);
let mut config = StackConfig::new(plan.max_context as i64, &crate::settings::Settings::from_environment());
config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048);
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.kv_resident = plan.resident;
@@ -19,7 +19,8 @@ struct Smoke<'a, 'ctx> {
tier_on: bool,
}
fn smoke_config() -> StackConfig {
let mut config = StackConfig::new(env_or("LELEKA_SMOKE_MAX_CONTEXT", 4096));
let mut config =
StackConfig::new(env_or("LELEKA_SMOKE_MAX_CONTEXT", 4096), &crate::settings::Settings::from_environment());
config.capacity = env_or("LELEKA_ORIGINAL_SERVE_CAPACITY", 1024);
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
if let Some(cells) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT").ok().and_then(|v| v.parse().ok()) {
@@ -160,7 +160,13 @@ impl Smoke<'_, '_> {
ServeRequest::new(
ids.iter().map(|&t| t as i32).collect(),
max_new,
RequestSampling { plan: sampled.then_some(&sampler), entropy: 7 },
RequestSampling {
plan: sampled.then_some(&sampler),
entropy: 7,
path: crate::qwen_forward::original_serve_config::sampler_path_in(
&crate::settings::Settings::from_environment(),
),
},
min_p,
original_stop_tokens(self.eos),
)
@@ -87,7 +87,10 @@ fn load_sweep_binding() -> Loaded {
}
fn sweep_stack_config() -> StackConfig {
let mut config = StackConfig::new(count_env("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64);
let mut config = StackConfig::new(
count_env("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64,
&crate::settings::Settings::from_environment(),
);
config.capacity = count_env("LELEKA_REPLAY_CAPACITY", 2048);
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
@@ -40,15 +40,17 @@ enum Flow {
// One live continuation, plus (operator opt-in) parked conversations with
// the Original's best-prefix / slot / byte-budget policy. Disabled (the
// default) this is exactly the former single resident prefix.
pub(super) fn new_conversations<'c>() -> Conversations<'c> {
ResidentConversations::<PrefixSession<'_>>::new(ResidentPolicy::from_environment().unwrap_or_else(|reason| {
use std::io::Write;
let _ = writeln!(
std::io::stderr().lock(),
"leleka-conversation configuration-rejected reason={reason}; parking disabled"
);
ResidentPolicy::disabled()
}))
pub(super) fn new_conversations<'c>(settings: &crate::settings::Settings) -> Conversations<'c> {
ResidentConversations::<PrefixSession<'_>>::new(ResidentPolicy::from_source(settings.env()).unwrap_or_else(
|reason| {
use std::io::Write;
let _ = writeln!(
std::io::stderr().lock(),
"leleka-conversation configuration-rejected reason={reason}; parking disabled"
);
ResidentPolicy::disabled()
},
))
}
pub(super) fn serve_commands<'c>(
@@ -186,7 +186,7 @@ pub fn spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots(
ranked_profile: RankedExpertProfileSource,
observer: EvaluationObserver,
) -> Result<Box<dyn Backend>, BackendError> {
if !crate::settings::process().serve.public_evaluation {
if !crate::settings::Settings::from_environment().serve.public_evaluation {
return Err(invalid("explicit public evaluation required"));
}
check_streamed_spill_inputs(&config, &ranked_profile)?;
@@ -18,7 +18,7 @@ pub fn original_serve_choice(
kar_staged: config.kar_ple_source.is_some(),
mtp: config.mtp_source.is_some(),
kar_expert: config.kar_expert_source.is_some(),
gguf_ple: crate::settings::process().serve.gguf_ple,
gguf_ple: crate::settings::Settings::from_environment().serve.gguf_ple,
experimental: !config.experimental.is_off(),
context_tokens: config.context_tokens,
};
@@ -79,11 +79,6 @@ impl ResidentPolicy {
Ok(policy)
}
/// The process environment's operator knobs.
pub fn from_environment() -> Result<Self, &'static str> {
Self::from_source(crate::settings::process().env())
}
/// The same knobs read from `env`: a value that is set but not valid unicode is refused.
pub(crate) fn from_source(env: &impl EnvSource) -> Result<Self, &'static str> {
let read = |name: &str| match env.get_os(name) {
@@ -68,8 +68,8 @@ impl PlePolicy {
})
}
fn from_environment() -> InputResult<Self> {
Self::from_values(|key| crate::settings::process().env().get(key))
fn from_settings(settings: &crate::settings::Settings) -> InputResult<Self> {
Self::from_values(|key| settings.env().get(key))
}
}
@@ -119,7 +119,7 @@ impl ModelBinding {
if let Some(reader) = self.ple_reader.get() {
return Ok(reader.as_ref());
}
let policy = PlePolicy::from_environment()?;
let policy = PlePolicy::from_settings(&self.settings)?;
let reader = if policy.enabled { self.open_ple_reader(&policy)? } else { None };
Ok(self.ple_reader.get_or_init(|| reader).as_ref())
}
@@ -5,8 +5,8 @@ use leleka_model_format::qwen4exp::{ResidentExpertSourceError, ResidentExpertSou
/// EXPERIMENTAL `LELEKA_ORIGINAL_SERVE_GGUF_PLE=1` (profile `rtx5090-32g-gguf-ple`): a binding without a KAR archive
/// (PLE rows from the GGUF shard, `qwen4exp-native-mtp-v1`) may take the expert bank too. Off by default: without it a
/// binding needs both providers, as before.
fn gguf_ple_opt_in() -> bool {
crate::settings::process().serve.gguf_ple
fn gguf_ple_opt_in(settings: &crate::settings::Settings) -> bool {
settings.serve.gguf_ple
}
impl ModelBinding {
@@ -15,7 +15,7 @@ impl ModelBinding {
/// The mutable loan excludes binding/source loans; fresh session placement
/// remains the selected caller contract (sessions retain an identity Rc).
pub(crate) fn load_resident_expert_source(&mut self) -> InputResult<ResidentExpertSourceReport> {
if (self.kar_ple.is_none() && !gguf_ple_opt_in()) || self.mtp.is_none() {
if (self.kar_ple.is_none() && !gguf_ple_opt_in(&self.settings)) || self.mtp.is_none() {
return Err(InputBindingError::Metadata);
}
self.mtp_weights()?;
@@ -32,7 +32,7 @@ impl ModelBinding {
/// (the Original's `--mmap-experts`, GGUF in place). Same preconditions; no RAM is committed for the experts.
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub(crate) fn load_mapped_expert_source(&mut self) -> InputResult<ResidentExpertSourceReport> {
if (self.kar_ple.is_none() && !gguf_ple_opt_in()) || self.mtp.is_none() {
if (self.kar_ple.is_none() && !gguf_ple_opt_in(&self.settings)) || self.mtp.is_none() {
return Err(InputBindingError::Metadata);
}
self.mtp_weights()?;
@@ -58,7 +58,7 @@ impl ModelBinding {
&mut self,
capture: leleka_model_format::qwen4exp::ProvisionalExpertSource,
) -> InputResult<ResidentExpertSourceReport> {
if (self.kar_ple.is_none() && !gguf_ple_opt_in()) || self.mtp.is_none() {
if (self.kar_ple.is_none() && !gguf_ple_opt_in(&self.settings)) || self.mtp.is_none() {
return Err(InputBindingError::Metadata);
}
self.mtp_weights()?;
@@ -91,8 +91,12 @@ impl<'ctx> DenseWeightCache<'ctx> {
self.workspaces.qsa_selected =
Some(RefCell::new(QsaSelectedCache::new(self.binding.clone(), context, self.mirror_failed.clone())?));
}
self.workspaces.qsa_keys =
Some(RefCell::new(QsaIndexKeyCache::new(self.binding.clone(), context, self.mirror_failed.clone())?));
self.workspaces.qsa_keys = Some(RefCell::new(QsaIndexKeyCache::new(
self.binding.clone(),
context,
self.mirror_failed.clone(),
binding.settings(),
)?));
self.workspaces.qsa_input =
Some(RefCell::new(QsaInputScratch::new(self.binding.clone(), context, self.mirror_failed.clone())?));
// Fixed activation scratch is charged before any lazy MoE growth.
@@ -20,8 +20,8 @@ pub(in crate::qwen_forward) const VERIFY_MAX_T: usize = 8;
/// 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 {
crate::settings::process().kv.footprint_legacy
pub(in crate::qwen_forward) fn legacy_footprint(settings: &crate::settings::Settings) -> bool {
settings.kv.footprint_legacy
}
#[cfg(test)]
fn legacy_footprint_from(value: Option<&str>) -> bool {
@@ -30,8 +30,11 @@ fn legacy_footprint_from(value: Option<&str>) -> bool {
/// 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.
pub(in crate::qwen_forward) fn mtp_pack_experts_needed(rt_directory_set: bool) -> bool {
!rt_directory_set || legacy_footprint()
pub(in crate::qwen_forward) fn mtp_pack_experts_needed(
rt_directory_set: bool,
settings: &crate::settings::Settings,
) -> bool {
!rt_directory_set || legacy_footprint(settings)
}
const VOCABULARY: usize = 248_320;
@@ -209,7 +212,10 @@ impl RopeConstants {
fn mtp_gr_variant() -> OriginalMtpGrVariant {
if leleka_cuda_driver::chain_selects_mtp() { OriginalMtpGrVariant::Staged } else { OriginalMtpGrVariant::Plain }
}
pub(in crate::qwen_forward) fn mtp_full_policy(rope: &RopeConstants) -> OriginalMtpFullPolicy {
pub(in crate::qwen_forward) fn mtp_full_policy(
rope: &RopeConstants,
serve: &crate::settings::ServeSettings,
) -> OriginalMtpFullPolicy {
OriginalMtpFullPolicy {
native_router: true,
legacy_router_mode: 0,
@@ -221,8 +227,8 @@ pub(in crate::qwen_forward) fn mtp_full_policy(rope: &RopeConstants) -> Original
gr: mtp_gr_variant(),
kv: rope.draft_kv(),
coupled_j: None,
chain_pipeline: crate::settings::process().serve.draft_chain_pipeline,
check_merge: crate::settings::process().serve.draft_check_merge,
chain_pipeline: serve.draft_chain_pipeline,
check_merge: serve.draft_check_merge,
}
}
pub(in crate::qwen_forward) fn mtp_scalar_policy(rope: &RopeConstants) -> OriginalMtpScalarPolicy {
@@ -247,8 +253,8 @@ pub(in crate::qwen_forward) fn sampler_path(lookup: impl Fn(&str) -> Option<Stri
SamplerPath::Split
}
}
pub(in crate::qwen_forward) fn sampler_path_from_environment() -> SamplerPath {
sampler_path(|name| crate::settings::process().env().get(name))
pub(crate) fn sampler_path_in(settings: &crate::settings::Settings) -> SamplerPath {
sampler_path(|name| settings.env().get(name))
}
/// The CPU reference `SamplerParams` of a request as the driver sampler takes them (field for field;
@@ -11,10 +11,11 @@ use super::{
#[test]
fn the_pack_expert_bank_is_needed_only_without_an_rt_directory() {
// pack-driven draft (no RT directory): the pack's experts are the draft layer's experts
assert!(mtp_pack_experts_needed(false));
let settings = crate::settings::Settings::from_environment();
assert!(mtp_pack_experts_needed(false, &settings));
// RT-directory draft (the product): it streams its own experts; the default environment holds no second copy
if !legacy_footprint() {
assert!(!mtp_pack_experts_needed(true));
if !legacy_footprint(&settings) {
assert!(!mtp_pack_experts_needed(true, &settings));
}
}
#[test]
@@ -74,7 +75,7 @@ fn theta_scale_is_powf_of_the_frequency_base_over_the_rotation_width() {
#[test]
fn mtp_policies_stay_inside_the_closed_profile_and_share_one_kv_policy() {
let rope = RopeConstants::from_parts(1e7, RopeKernelArgs::default());
let full = mtp_full_policy(&rope);
let full = mtp_full_policy(&rope, &crate::settings::Settings::from_environment().serve);
let scalar = mtp_scalar_policy(&rope);
assert!(full.native_router && full.native_combine && full.native_shared_scalar && full.native_final_gr);
assert!(!full.old_grouped_s2 && !full.fp32_final_gr && full.coupled_j.is_none() && full.legacy_router_mode == 0);
@@ -35,6 +35,8 @@ pub(crate) struct ServeRequest {
pub(crate) struct RequestSampling<'a> {
pub(crate) plan: Option<&'a leleka_sampler_ref::SamplerParams>,
pub(crate) entropy: u64,
/// The sampling kernel the request runs (`STRATA_OLD_SAMPLER`, `STRATA_SAMPLER_ONE_BLOCK`), from the settings.
pub(crate) path: leleka_cuda_driver::SamplerPath,
}
impl ServeRequest {
@@ -50,14 +52,7 @@ impl ServeRequest {
Some(params) => super::original_serve_config::driver_sampler_params(params),
None => super::original_serve_config::greedy_params(sampling.entropy),
};
Self {
prompt,
max_new,
params,
path: super::original_serve_config::sampler_path_from_environment(),
spec_min_p,
eos,
}
Self { prompt, max_new, params, path: sampling.path, spec_min_p, eos }
}
}
@@ -65,7 +60,17 @@ impl ServeRequest {
/// A greedy request (no sampler plan, no penalties) seeded by `entropy`.
#[cfg(test)]
pub(crate) fn greedy(prompt: Vec<i32>, max_new: usize, entropy: u64, spec_min_p: f32, eos: Vec<i32>) -> Self {
Self::new(prompt, max_new, RequestSampling { plan: None, entropy }, spec_min_p, eos)
Self::new(
prompt,
max_new,
RequestSampling {
plan: None,
entropy,
path: super::original_serve_config::sampler_path_in(&crate::settings::Settings::from_environment()),
},
spec_min_p,
eos,
)
}
}
@@ -31,14 +31,14 @@ impl TtftMarks {
}
}
impl StackConfig {
pub(crate) fn new(max_context: i64) -> Self {
let serve = &crate::settings::process().serve;
pub(crate) fn new(max_context: i64, settings: &crate::settings::Settings) -> Self {
let serve = &settings.serve;
Self {
memory: leleka_memory::MemoryServices::new(),
capacity: DEFAULT_CAPACITY,
max_context,
rt_directory: None,
coupled: crate::settings::process().decode.coupled,
coupled: settings.decode.coupled,
// LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15)
// LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan`
// (physical cores but the host's, hybrid and quota aware) instead
@@ -78,8 +78,11 @@ fn check_model_shape(binding: &ModelBinding) -> std::result::Result<(), ServeFai
}
/// The window policies the environment names: the first arm is live, the rest are parked with their controllers.
pub(super) fn serve_policies(config: &StackConfig, serving_cells: u64) -> std::result::Result<Policies, ServeFailure> {
let env = crate::settings::process().env();
pub(super) fn serve_policies(
config: &StackConfig,
(serving_cells, settings): (u64, &crate::settings::Settings),
) -> std::result::Result<Policies, ServeFailure> {
let env = settings.env();
let context = crate::qwen_forward::original_spec_controller::SpecContext::new(config.max_context, serving_cells);
let mut settings = OriginalServeSettings::from_environment(context, VOCABULARY, config.coupled, env);
let mut arm_label = String::from("env");
@@ -165,19 +168,18 @@ fn load_moe<'ctx>(
config: &StackConfig,
layout: PrefillLayoutOptions,
) -> std::result::Result<MoeWeightCache<'ctx>, ServeFailure> {
let pack_experts = super::super::super::original_serve_config::mtp_pack_experts_needed(
config.rt_directory.is_some(),
binding.settings(),
);
let moe = staged!(
&config.memory,
"MoE arena cache",
context,
MoeWeightCache::new_original_prompt_arena(
binding,
context,
layout,
super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some())
)
.map_err(at("MoeWeightCache::new_original_prompt_arena"))?
MoeWeightCache::new_original_prompt_arena(binding, context, layout, pack_experts)
.map_err(at("MoeWeightCache::new_original_prompt_arena"))?
);
if !super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some()) {
if !pack_experts {
operator_note(
"footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from \
the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)",
@@ -241,8 +243,9 @@ pub(super) fn share_rt_dense_roles<'ctx>(
config: &StackConfig,
executor: &OriginalPromptExecutor<'ctx>,
moe: &mut MoeWeightCache<'ctx>,
settings: &crate::settings::Settings,
) -> std::result::Result<(), ServeFailure> {
if config.rt_directory.is_some() && !super::super::super::original_serve_config::legacy_footprint() {
if config.rt_directory.is_some() && !super::super::super::original_serve_config::legacy_footprint(settings) {
if let Some(retained) = executor.retained_mtp_weights() {
let share = moe.share_rt_mtp_dense(retained).map_err(at("share_rt_mtp_dense"))?;
operator_note(&format!(
@@ -34,7 +34,7 @@ pub(super) struct Assembly<'a, 'ctx> {
/// in the order `open` computed them.
pub(super) fn prepare(binding: &ModelBinding, config: &StackConfig) -> std::result::Result<Prepared, ServeFailure> {
let max_cells = usize::try_from(binding.input_constants().bound_cells()).map_err(|_| failure(Error::Overflow))?;
let policies = serve_policies(config, binding.input_constants().bound_cells())?;
let policies = serve_policies(config, (binding.input_constants().bound_cells(), binding.settings()))?;
let rope = RopeConstants::from_serving_context(binding.serving());
let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?;
let formats = expert_formats(binding).map_err(at("expert_formats"))?;
@@ -43,12 +43,12 @@ pub(super) fn prepare(binding: &ModelBinding, config: &StackConfig) -> std::resu
}
/// The policy group of the stack: the MTP policies are derived from the RoPE constants before they move in.
fn serve_policy(prepared: Prepared) -> ServePolicy {
fn serve_policy(prepared: Prepared, serve: &crate::settings::ServeSettings) -> ServePolicy {
let Prepared { max_cells, policies, rope, blobs, formats, .. } = prepared;
ServePolicy {
settings: policies.settings,
max_cells,
full_policy: mtp_full_policy(&rope),
full_policy: mtp_full_policy(&rope, serve),
scalar_policy: mtp_scalar_policy(&rope),
rope,
blobs,
@@ -70,13 +70,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
context,
config,
tier: TierState::new(prepared.layout, tier.loan, tier.loan_tiers, tier.residency, tier.initial_owners),
policy: serve_policy(prepared),
policy: serve_policy(prepared, &binding.settings().serve),
empty_session: buffers.empty_session,
empty_draft: buffers.empty_draft,
conversation: tier.conversation,
prefix: tier.prefix,
state: RequestState::default(),
held: GraphReuse::new(crate::settings::process().serve.decode_graph_reuse),
held: GraphReuse::new(binding.settings().serve.decode_graph_reuse),
history: buffers.history,
ple_history: buffers.ple_history,
ple_scratch: buffers.ple_scratch,
@@ -69,7 +69,7 @@ pub(super) fn load_core<'a, 'ctx>(
let opened = open_executor(binding, context, &opening, &weights, &mut session)?;
let (executor, draft) = opened;
let Weights { output, embedding, kar, dense, mut moe } = weights;
share_rt_dense_roles(config, &executor, &mut moe)?;
share_rt_dense_roles(config, &executor, &mut moe, binding.settings())?;
vram_note(context, "after prompt executor and draft");
crate::memory_governor::end(executor_stage, Some(context));
Ok(Core { executor, draft, session, kar, moe, dense, output, embedding })
@@ -30,7 +30,7 @@ fn a_chunk_borrows_the_smallest_rung_that_holds_it() {
#[test]
fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() {
let config = StackConfig::new(4096);
let config = StackConfig::new(4096, &crate::settings::Settings::from_environment());
assert!(ADMITTED_CAPACITIES.contains(&config.capacity));
for capacity in [256usize, 1024, 8192] {
assert!(StackConfig { capacity, ..config.clone() }.validate(QsaGeometry::TRAINED).is_ok(), "{capacity}");
@@ -46,7 +46,7 @@ fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_
#[test]
fn the_conversation_cache_is_on_by_default_with_the_original_settings() {
let config = StackConfig::new(4096);
let config = StackConfig::new(4096, &crate::settings::Settings::from_environment());
let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original");
assert_eq!(
(conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root),
@@ -62,7 +62,7 @@ fn the_conversation_cache_is_on_by_default_with_the_original_settings() {
#[test]
fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() {
let config = StackConfig::new(4096);
let config = StackConfig::new(4096, &crate::settings::Settings::from_environment());
assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768));
assert_eq!(config.kv_footprint(QsaGeometry::TRAINED).map(|f| f.resident_pages), Some(8192));
for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] {
@@ -86,8 +86,14 @@ impl<'ctx> QsaIndexKeyCache<'ctx> {
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
failed: Rc<Cell<bool>>,
settings: &crate::settings::Settings,
) -> Result<Self> {
Self::with_eager(binding, context, failed, crate::qwen_forward::original_serve_config::legacy_footprint())
Self::with_eager(
binding,
context,
failed,
crate::qwen_forward::original_serve_config::legacy_footprint(settings),
)
}
pub(super) fn with_eager(
binding: BindingIdentity,