STRA-338 S5b: decompose serve_load into ordered phase functions

serve_load (about 1000 lines, 1170 after rustfmt) becomes load.rs (a 20-line order of
the phases) plus: load_admit (every refusal that needs no model byte, the memory
governor start), load_sources + load_bind (verify, bind, identity digest chain, expert
bank), load_identity, load_cuda (driver, context, probes, hand-over to the Original
serve stack), load_weights + load_moe + load_moe_gates (output head, KAR PLE, dense and
MoE caches; the adaptive and learned-main witness gates), serve_loop + serve_generate +
serve_run + serve_report (the command loop and one Generate), serve_close (teardown).
owner() is split the same way. Each phase takes a small context (LoadEnv, Bound,
Identity, Weights, Serving, Exchange) and returns a typed result.

Order and side effects are kept: the admission checks, the env reads
(LELEKA_ORIGINAL_SERVE_GGUF_PLE is still read in gguf_ple_load and in the refusal
detail line), the log texts (including the load-gate detail line and the
KAR_MTP_PROFILE / NATIVE_MTP_PROFILE logic of the kar-off-ab branch), the cancellation
checks, the lap marks, and the drop order of the CUDA objects (Weights drops dense, MoE,
KAR PLE, output head; the context is closed after the weights and outlives the binding).
The three conditions of the former execution gates are one match, the policy flags one
PolicyFlags::of. No GPU or numerical path was touched.

New tests (backend/load_tests.rs): PolicyFlags against the former expressions, the
execution gates against the former three sequential checks for all 6 executions x 8
boolean combinations, and the weight-cache log line against its exact text and the
saturating subtraction. Test ids: 689 before the S5 work, 694 now (the five added), the
same 2 environment-dependent failures and 58 ignored; cargo check --all-targets for
leleka-runtime and leleka-deploy gives the same warning counts, clippy reports nothing
in backend/. All new and changed functions are within 30 lines, complexity 10, nesting 4,
except one 127-column line that is a 119-character MoeWeightCache constructor name
(docs/architecture/tech-debt.md, which also lists what S5a moved verbatim and still misses
the limits). moe_weight_cache.rs gains three pub(crate) use lines for the witness types.
The architecture baseline loses the transient backend/load.rs entry.
This commit is contained in:
Pavlo Ratushnyi
2026-11-05 21:39:26 +01:00
parent c434a97c7e
commit 7699138a6e
21 changed files with 2531 additions and 1199 deletions
-1
View File
@@ -84,7 +84,6 @@
"crates/igpu/src/lib.rs": 1386,
"crates/igpu/src/shaders.rs": 440,
"crates/leleka-memory/src/lock.rs": 432,
"crates/leleka-runtime/src/backend/load.rs": 1170,
"crates/leleka-runtime/src/backend_original_serve.rs": 1115,
"crates/leleka-runtime/src/conversation/cache/tests.rs": 407,
"crates/leleka-runtime/src/conversation/manager_tests.rs": 1129,
+30
View File
@@ -70,6 +70,34 @@ mod owner;
use owner::*;
mod load;
use load::*;
mod load_admit;
use load_admit::*;
mod load_sources;
use load_sources::*;
mod load_identity;
use load_identity::*;
mod load_bind;
use load_bind::*;
mod load_cuda;
use load_cuda::*;
mod load_weights;
use load_weights::*;
mod load_moe;
use load_moe::*;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
mod load_moe_gates;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use load_moe_gates::*;
mod serve_loop;
use serve_loop::*;
mod serve_generate;
use serve_generate::*;
mod serve_report;
use serve_report::*;
mod serve_run;
use serve_run::*;
mod serve_close;
use serve_close::*;
mod validate;
use validate::*;
mod digests;
@@ -209,6 +237,8 @@ mod native_down_candidate_only;
#[cfg(test)]
mod digests_golden;
#[cfg(test)]
mod load_tests;
#[cfg(test)]
mod streamed_spill_policy_tests {
@@ -75,6 +75,37 @@ pub(super) struct OptimizedBackendConfig {
pub(super) ranked_profile: Option<RankedExpertProfileSource>,
pub(super) policy: OptimizedOwnerPolicy,
}
/// What each optimized owner policy switches on; every flag is false without an optimized selection.
#[derive(Clone, Copy)]
pub(super) struct PolicyFlags {
pub(super) queued_owners: bool,
pub(super) streamed_spill: bool,
pub(super) retained_scratch: bool,
pub(super) resident_owners: bool,
pub(super) adaptive_slots: bool,
}
impl PolicyFlags {
pub(super) fn of(optimized: Option<&OptimizedBackendConfig>) -> Self {
use OptimizedOwnerPolicy::{
AdaptiveSlots, Original, ResidentOwners, RetainedScratch, StreamedSpill,
};
let policy = optimized.map(|options| options.policy);
let one_of =
|set: &[OptimizedOwnerPolicy]| policy.is_some_and(|policy| set.contains(&policy));
Self {
queued_owners: policy.is_some_and(|policy| policy != Original),
streamed_spill: one_of(&[
StreamedSpill,
RetainedScratch,
ResidentOwners,
AdaptiveSlots,
]),
retained_scratch: one_of(&[RetainedScratch, ResidentOwners, AdaptiveSlots]),
resident_owners: one_of(&[ResidentOwners, AdaptiveSlots]),
adaptive_slots: one_of(&[AdaptiveSlots]),
}
}
}
pub(super) struct OwnerExecution {
pub(super) kind: EvaluationExecution,
pub(super) optimized: Option<OptimizedBackendConfig>,
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,243 @@
//! Load admission: every refusal that needs no model byte, and the start of the memory governor.
use super::*;
use std::io::Write;
/// Refuse what cannot be served, before any model byte is read. Returns the experimental plan, if any,
/// that the Load probes once the CUDA context exists.
pub(super) fn admit_load(
env: &LoadEnv<'_>,
model: &ModelDescriptor,
requested: &RuntimeConfig,
) -> Result<Option<experimental_modes::Plan>, BackendError> {
validate_load(model, requested).map_err(|e| load_failure(LoadPhase::Config, e))?;
refuse_kar_experts_with_mtp(env.config, requested)?;
let plan = plan_experimental(env.config)?;
let gguf_ple = gguf_ple_load(env.config, requested);
check_original_gate(env, requested, plan.is_some(), gguf_ple)?;
check_execution_gates(env, requested, gguf_ple)?;
validate_selection(env.config, requested)?;
check_memory_ceiling(env.config, requested)?;
Ok(plan)
}
pub(super) fn kar_mtp_requested(requested: &RuntimeConfig) -> bool {
matches!(&requested.inference_mode,
InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE)
}
// Only the single-token step consults the KAR expert source. The MTP flow
// prefills prompt tiles and verifies draft windows through chunked/grouped
// MoE paths that read the GGUF experts, so combining them would build the
// KV cache from one expert set and decode from another. Refuse, not mix.
fn refuse_kar_experts_with_mtp(
config: &NativeBackendConfig,
requested: &RuntimeConfig,
) -> Result<(), BackendError> {
if config.kar_expert_source.is_some()
&& matches!(
requested.inference_mode,
InferenceMode::ExperimentalMtp { .. }
)
{
return Err(load_failure(
LoadPhase::Selection,
unsupported("KAR expert source does not support the MTP flow"),
));
}
Ok(())
}
// Experimental modes: validate the combination with the Original's selection rules and refuse cheaply,
// before any model byte is read, while nothing in the forward pass consumes them.
fn plan_experimental(
config: &NativeBackendConfig,
) -> Result<Option<experimental_modes::Plan>, BackendError> {
experimental_modes::plan(&config.experimental)
.and_then(|plan| experimental_modes::ensure_consumed(&plan).map(|()| plan))
.map_err(|e| load_failure(LoadPhase::Config, experimental_error(e)))
}
// EXPERIMENTAL (LELEKA_ORIGINAL_SERVE_GGUF_PLE=1, profile rtx5090-32g-gguf-ple): the native-PLE MTP load is a
// valid Original-serve load, only with no KAR source configured
fn gguf_ple_load(config: &NativeBackendConfig, requested: &RuntimeConfig) -> bool {
matches!(&requested.inference_mode,
InferenceMode::ExperimentalMtp { profile_id } if profile_id == NATIVE_MTP_PROFILE)
&& std::env::var("LELEKA_ORIGINAL_SERVE_GGUF_PLE").is_ok_and(|v| v == "1")
&& config.kar_ple_source.is_none()
&& config.kar_ple_inherited.is_none()
}
fn check_original_gate(
env: &LoadEnv<'_>,
requested: &RuntimeConfig,
has_plan: bool,
gguf_ple: bool,
) -> Result<(), BackendError> {
if env.original.is_none() {
return Ok(());
}
let refused = env.observer.is_some()
|| env.optimized.is_some()
|| env.config.kar_expert_source.is_some()
|| has_plan
|| !(gguf_ple || kar_mtp_requested(requested));
if !refused {
return Ok(());
}
log_original_refusal(env, requested, has_plan);
Err(load_failure(
LoadPhase::Selection,
invalid(
"Original serve requires explicit KAR PLE MTP Load without observer, optimized owners, \
a KAR expert source or an experimental mode",
),
))
}
// booleans only (no model or request data): which of the gate's conditions refused the load
fn log_original_refusal(env: &LoadEnv<'_>, requested: &RuntimeConfig, has_plan: bool) {
let _ = writeln!(
std::io::stderr().lock(),
"leleka-load detail: observer={} optimized={} kar_expert={} experimental={} gguf_env={} \
kar_source={} mode={}",
env.observer.is_some(),
env.optimized.is_some(),
env.config.kar_expert_source.is_some(),
has_plan,
std::env::var("LELEKA_ORIGINAL_SERVE_GGUF_PLE").is_ok_and(|v| v == "1"),
env.config.kar_ple_source.is_some() || env.config.kar_ple_inherited.is_some(),
match &requested.inference_mode {
InferenceMode::ExperimentalMtp { profile_id } => profile_id.as_str(),
_ => "other",
}
);
}
/// The evaluation executions each demand an explicit KAR PLE MTP Load (and, for most, an observer).
fn check_execution_gates(
env: &LoadEnv<'_>,
requested: &RuntimeConfig,
gguf_ple: bool,
) -> Result<(), BackendError> {
let kar_mtp = kar_mtp_requested(requested);
match execution_gate_message(env.execution, kar_mtp, env.observer.is_some(), gguf_ple) {
Some(message) => Err(load_failure(LoadPhase::Selection, invalid(message))),
None => Ok(()),
}
}
/// The refusal an execution gets for the Load it was asked to serve, if any.
pub(super) fn execution_gate_message(
execution: EvaluationExecution,
kar_mtp: bool,
observed: bool,
gguf_ple: bool,
) -> Option<&'static str> {
match execution {
EvaluationExecution::ExperimentalResidentMmq
| EvaluationExecution::ExperimentalNativeResidentMmq
| EvaluationExecution::ExperimentalNativeIntegerIq3Mmq
if !kar_mtp || !observed =>
{
Some("resident MMQ evaluation requires explicit KAR PLE MTP Load")
}
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr
if !gguf_ple && !kar_mtp =>
{
Some("IQ3 windowed256 retained GR experiment requires explicit KAR PLE MTP Load")
}
EvaluationExecution::ExperimentalWindowed256RetainedGr if !kar_mtp || !observed => {
Some("windowed256 retained GR evaluation requires explicit KAR PLE MTP Load")
}
_ => None,
}
}
fn validate_selection(
config: &NativeBackendConfig,
requested: &RuntimeConfig,
) -> Result<(), BackendError> {
let kar_present = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some();
validate_kar_selection(requested, kar_present)
.map_err(|e| load_failure(LoadPhase::Selection, e))?;
validate_mtp_selection(requested, config.mtp_source.is_some())
.map_err(|e| load_failure(LoadPhase::Selection, e))
}
fn check_memory_ceiling(
config: &NativeBackendConfig,
requested: &RuntimeConfig,
) -> Result<(), BackendError> {
if requested
.gpu_memory_limit_bytes
.is_some_and(|limit| limit < config.gpu_budget_bytes)
{
return Err(load_failure(
LoadPhase::Config,
exhausted("requested memory ceiling is below native owner budget"),
));
}
Ok(())
}
/// What the memory governor hands back at startup (`docs/memory-safety.md`); nothing off the CUDA platforms.
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
pub(super) type Governed = Option<&'static leleka_memory::Governor>;
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
pub(super) type Governed = ();
// The memory budget, before a single model byte is read: refuse with numbers when the fixed footprint does not fit,
// otherwise size the caches from what is left and keep the sealed KAR memfd resident (`docs/memory-safety.md`).
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
pub(super) fn start_governor(env: &LoadEnv<'_>) -> Result<Governed, BackendError> {
let Some(options) = env.original else {
return Ok(None);
};
let fail = |e| load_failure(LoadPhase::Config, e);
let governor =
crate::memory_governor::startup(&governor_args(env.config, options)).map_err(fail)?;
if let Some(archive) = env.config.kar_ple_inherited.as_ref() {
crate::memory_governor::guard_archive(governor, archive).map_err(fail)?;
}
Ok(Some(governor))
}
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
pub(super) fn start_governor(_: &LoadEnv<'_>) -> Result<Governed, BackendError> {
Ok(())
}
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
fn governor_args(
config: &NativeBackendConfig,
options: &original_serve::OriginalServeOptions,
) -> crate::memory_governor::StartArgs {
let inherited = config.kar_ple_inherited.as_ref();
crate::memory_governor::StartArgs {
kv_resident: options
.kv_resident
.unwrap_or(leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS),
gpu_budget_bytes: config.gpu_budget_bytes,
kar_file_backed: inherited.map(InheritedKarArchive::file_backed),
kar_sparse_bytes: inherited
.and_then(InheritedKarArchive::sparse_extents)
.map(|spans| leleka_memory::lock::spans_bytes(&spans)),
expert_source_mapped: options.expert_source == original_serve::ExpertSource::Mapped,
prefix: options.prefix_cache.as_ref().map(|p| p.budget_bytes),
prompt_cache: options.prompt_cache,
}
}
@@ -0,0 +1,136 @@
//! The first half of a Load, before any CUDA object exists: sources, binding, identity, the expert bank.
use super::*;
use leleka_model_format::qwen4exp::ProvisionalExpertSource;
/// The host-side result of binding: what the CUDA half and the serve loop work on.
pub(super) struct Bound {
pub(super) binding: ModelBinding,
pub(super) tokenizer: Tokenizer,
pub(super) eos: u32,
/// The pinned ranked expert profile, read once, for the optimized owners.
pub(super) ranked_profile: Option<Vec<u8>>,
pub(super) flags: PolicyFlags,
}
pub(super) fn bind_model(
env: &LoadEnv<'_>,
requested: &RuntimeConfig,
model: ModelDescriptor,
) -> Result<(Bound, Identity), BackendError> {
let flags = PolicyFlags::of(env.optimized);
let (mut bound, capture) = bind_providers(env, requested, flags)?;
let (mode, digest) = effective_identity(env, &bound.binding, requested)?;
check_not_cancelled(env.shared)?;
bound.ranked_profile = read_profile(env.optimized)?;
let digest = policy_digest(env.optimized, flags, digest)?;
adopt_bank(env, &mut bound.binding, capture, flags)?;
Ok((
bound,
Identity {
model,
mode,
digest,
},
))
}
/// Verify the sources, bind the artifact to the selected providers and admit the KAR expert source.
fn bind_providers(
env: &LoadEnv<'_>,
requested: &RuntimeConfig,
flags: PolicyFlags,
) -> Result<(Bound, Option<ProvisionalExpertSource>), BackendError> {
let opened = open_sources(env, requested, flags)?;
let parts = bind_artifact(opened.shard0, opened.shard1)?;
check_mtp_context(env.config, requested)?;
let selected = bind_selected(env.config, requested, parts.artifact, opened.kar)?;
let binding = admit_kar_experts(env, selected)?;
let bound = Bound {
binding,
tokenizer: parts.tokenizer,
eos: parts.eos,
ranked_profile: None,
flags,
};
Ok((bound, opened.capture))
}
// Only this fresh unpublished selected binding can gain the raw RAM bank.
// Complete GGUF/KAR/MTP admission already finished; no sessions or Ready exist.
// The Original serve stack reads the same bank (CPU window tier, prompt arena); without it the stack's
// arena fails with InputRead at Load. The operator picks the RAM copy (server) or the mappings (laptop).
fn adopt_bank(
env: &LoadEnv<'_>,
binding: &mut ModelBinding,
capture: Option<ProvisionalExpertSource>,
flags: PolicyFlags,
) -> Result<(), BackendError> {
if env.optimized.is_none() && env.original.is_none() {
return Ok(());
}
let bank_stage = crate::memory_governor::begin("expert bank (resident copy or mappings)", None);
admit_expert_bank(env, binding, capture, flags)?;
crate::memory_governor::end(bank_stage, None);
drop_shard_page_cache(env);
crate::load_clock::lap("expert_bank_admission");
settle_huge_pages();
check_not_cancelled(env.shared)
}
fn admit_expert_bank(
env: &LoadEnv<'_>,
binding: &mut ModelBinding,
capture: Option<ProvisionalExpertSource>,
flags: PolicyFlags,
) -> Result<(), BackendError> {
let mapped = env
.original
.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Mapped);
let adopted = if flags.streamed_spill {
binding.adopt_resident_expert_capture(capture.ok_or_else(|| {
load_failure(
LoadPhase::SelectedBinding,
invalid("streamed expert capture absent"),
)
})?)
} else if mapped {
binding.load_mapped_expert_source()
} else {
binding.load_resident_expert_source()
};
adopted
.map_err(|error| load_failure(LoadPhase::SelectedBinding, expert_bank_refusal(error)))?;
Ok(())
}
fn expert_bank_refusal(error: InputBindingError) -> BackendError {
match error {
InputBindingError::Allocation => exhausted("resident expert RAM unavailable"),
InputBindingError::Read => unavailable("resident expert source read failed"),
_ => invalid("resident expert source admission failed"),
}
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
fn drop_shard_page_cache(env: &LoadEnv<'_>) {
if env
.original
.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident)
{
crate::memory_governor::drop_file_cache(&[
env.config.shard0.as_path(),
env.config.shard1.as_path(),
]);
}
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
fn drop_shard_page_cache(_: &LoadEnv<'_>) {}
// LELEKA_HUGEPAGES (opt-in): coverage of the bank copies and a collapse of the ranges that fell back, now that the
// shard page cache is gone and before the banks are page-locked.
fn settle_huge_pages() {
if let Some(report) = leleka_model_format::huge_pages::settle() {
eprintln!("{report}");
crate::load_clock::lap("expert_bank_huge_pages");
}
}
@@ -0,0 +1,127 @@
//! The CUDA half of a Load: driver, device context, load-time probes and the hand-over to the Original serve stack.
use super::*;
use leleka_cuda_driver::Context;
pub(super) fn open_driver() -> Result<Driver, BackendError> {
Driver::load()
.map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable")))
}
pub(super) fn open_context<'d>(
config: &NativeBackendConfig,
driver: &'d Driver,
) -> Result<Rc<Context<'d>>, BackendError> {
GPU_ORDINAL.store(config.gpu_device_ordinal, Ordering::Relaxed);
let device = driver
.device(config.gpu_device_ordinal as i32)
.map_err(|_| load_failure(LoadPhase::Device, unavailable("CUDA device unavailable")))?;
let context = Rc::new(
device
.create_context(config.gpu_budget_bytes as usize)
.map_err(|_| {
load_failure(
LoadPhase::Context,
exhausted("native CUDA context unavailable"),
)
})?,
);
crate::load_clock::lap("cuda_driver_and_context");
Ok(context)
}
/// The context, checked against the memory governor's VRAM facts, with the KAR level-decode PTX probed
/// when a KAR expert source is bound.
pub(super) fn open_checked_context<'d>(
env: &LoadEnv<'_>,
driver: &'d Driver,
governed: Governed,
binding: &ModelBinding,
) -> Result<Rc<Context<'d>>, BackendError> {
let context = open_context(env.config, driver)?;
check_vram(governed, &context, env.config.gpu_budget_bytes)?;
if binding.kar_expert_source().is_some() {
// Fail at Load, not at the first token, if the KAR level-decode PTX is
// unpinned or does not load on this device.
probe_kar_level_decode(context.as_ref())
.map_err(|e| load_failure(LoadPhase::Context, e))?;
}
Ok(context)
}
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
fn check_vram(governed: Governed, context: &Context<'_>, budget: u64) -> Result<(), BackendError> {
match governed {
Some(g) => crate::memory_governor::check_vram(g, context, budget)
.map_err(|e| load_failure(LoadPhase::Context, e)),
None => Ok(()),
}
}
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
fn check_vram(_: Governed, _: &Context<'_>, _: u64) -> Result<(), BackendError> {
Ok(())
}
/// Fail at Load, not at the first token, if an experimental PTX is unpinned or does not load.
pub(super) fn probe_experimental_plan(
env: &LoadEnv<'_>,
context: &Context<'_>,
plan: Option<&experimental_modes::Plan>,
) -> Result<(), BackendError> {
match plan {
Some(plan) => probe_experimental(context, &env.config.experimental, plan)
.map_err(|e| load_failure(LoadPhase::Context, e)),
None => Ok(()),
}
}
/// Hand the bound model and the context to the Original serve stack, which serves until Unload.
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
pub(super) fn launch_original<'d>(
env: &LoadEnv<'_>,
options: &original_serve::OriginalServeOptions,
requested: &RuntimeConfig,
identity: Identity,
bound: Bound,
context: Rc<Context<'d>>,
) -> Result<(), BackendError> {
let loaded = build_loaded(env, identity, requested)?;
original_serve::run(original_serve::Run {
context_tokens: env.config.context_tokens,
rx: env.rx,
shared: env.shared,
binding: bound.binding,
context,
tokenizer: bound.tokenizer,
eos: bound.eos,
loaded,
reply: env.reply,
options,
model_files: vec![env.config.shard0.clone(), env.config.shard1.clone()],
})
}
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
pub(super) fn launch_original(
_: &LoadEnv<'_>,
_: &original_serve::OriginalServeOptions,
_: &RuntimeConfig,
_: Identity,
_: Bound,
_: Rc<Context<'_>>,
) -> Result<(), BackendError> {
Err(load_failure(
LoadPhase::Selection,
unsupported("Original serve CUDA owners require Linux x86_64"),
))
}
@@ -0,0 +1,132 @@
//! Load phases that fix the identity a Load publishes: the mode digest chain and the loaded-model handle.
use super::*;
/// The model, the effective mode and the digest that identify what this Load publishes.
pub(super) struct Identity {
pub(super) model: ModelDescriptor,
pub(super) mode: InferenceMode,
pub(super) digest: String,
}
/// The mode the binding really implements and the digest of everything that changes the model's outputs.
pub(super) fn effective_identity(
env: &LoadEnv<'_>,
binding: &ModelBinding,
requested: &RuntimeConfig,
) -> Result<(InferenceMode, String), BackendError> {
let (mode, digest) = selected_bound_mode(binding, &requested.inference_mode)
.map_err(|e| load_failure(LoadPhase::EffectiveMode, e))?;
Ok((mode, fold_mode_digest(env, binding, digest)))
}
fn fold_mode_digest(env: &LoadEnv<'_>, binding: &ModelBinding, digest: String) -> String {
let digest = if env.execution
== EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr
{
execution_mode_digest(&digest)
} else {
digest
};
// The KAR expert identity changes model outputs, so it changes the mode.
let digest = match binding.kar_expert_source() {
Some(source) => kar_expert_mode_digest(&digest, source.identity_digest()),
None => digest,
};
// An experimental mode changes model outputs, so it changes the mode (all-off leaves the digest alone).
let digest = experimental_modes::mode_digest(&digest, &env.config.experimental);
if env.original.is_some() {
original_serve_execution_digest(&digest)
} else {
digest
}
}
pub(super) fn check_not_cancelled(shared: &Shared) -> Result<(), BackendError> {
if shared.shutdown.load(Ordering::Acquire) {
return Err(load_failure(
LoadPhase::Cancellation,
unavailable("native load cancelled"),
));
}
Ok(())
}
// Only a bounded, pinned metadata file is read here. Complete source SHA
// admission precedes Driver/Context allocation and cannot change on RPCs.
pub(super) fn read_profile(
optimized: Option<&OptimizedBackendConfig>,
) -> Result<Option<Vec<u8>>, BackendError> {
optimized
.and_then(|options| options.ranked_profile.as_ref())
.map(read_ranked_expert_profile)
.transpose()
.map_err(|e| load_failure(LoadPhase::Selection, e))
}
/// The digest of the optimized owner policy, folded over the digest of the bound mode.
pub(super) fn policy_digest(
optimized: Option<&OptimizedBackendConfig>,
flags: PolicyFlags,
digest: String,
) -> Result<String, BackendError> {
let Some(options) = optimized else {
return Ok(digest);
};
let profile = options.ranked_profile.as_ref();
if !flags.queued_owners {
return Ok(optimized_execution_digest(
&digest,
profile.map(|source| source.sha256.as_str()),
));
}
let source = profile.ok_or_else(|| {
load_failure(
LoadPhase::Selection,
invalid("queued owners require ranked profile"),
)
})?;
Ok(queued_family_digest(flags, &digest, &source.sha256))
}
fn queued_family_digest(flags: PolicyFlags, digest: &str, profile: &str) -> String {
if flags.adaptive_slots {
adaptive_slots_execution_digest(digest, profile)
} else if flags.resident_owners {
resident_owners_execution_digest(digest, profile)
} else if flags.retained_scratch {
retained_scratch_execution_digest(digest, profile)
} else if flags.streamed_spill {
streamed_spill_execution_digest(digest, profile)
} else {
queued_owners_execution_digest(digest, profile)
}
}
/// The handle this Load publishes, checked against the request it answers.
pub(super) fn build_loaded(
env: &LoadEnv<'_>,
identity: Identity,
requested: &RuntimeConfig,
) -> Result<LoadedModel, BackendError> {
let loaded = LoadedModel {
handle: format!(
"native-{}-{}-{}",
std::process::id(),
env.instance,
env.serial
),
descriptor: identity.model,
load_config_version: LOAD_CONFIG_VERSION,
effective_mode: identity.mode,
mode_identity_digest: identity.digest,
};
loaded
.validate_for_load(&loaded.descriptor, requested)
.map_err(|_| {
load_failure(
LoadPhase::Identity,
unavailable("native load identity failed"),
)
})?;
Ok(loaded)
}
@@ -0,0 +1,103 @@
//! The MoE weight cache of a native Load: which constructor each execution selects.
use super::*;
use crate::qwen_forward::contract::Error as ForwardError;
use leleka_cuda_driver::Context;
type Cache<'c> = Result<MoeWeightCache<'c>, ForwardError>;
/// Build the MoE cache. On a refusal the optimized dense cache that was built first is closed.
pub(super) fn load_moe<'c>(
env: &LoadEnv<'_>,
binding: &ModelBinding,
context: &'c Context<'_>,
flags: PolicyFlags,
ranked_profile: Option<&[u8]>,
optimized_dense: &mut Option<DenseWeightCache<'c>>,
) -> Result<MoeWeightCache<'c>, BackendError> {
let built = if env.optimized.is_some() {
optimized_moe(binding, context, flags, ranked_profile)?
} else {
plain_moe(env.execution, binding, context)
};
built.map_err(|e| {
if let Some(dense) = optimized_dense.take() {
let _ = dense.close();
}
load_forward_failure(
LoadPhase::MoeWeightCache,
e,
exhausted("MoE/MTP weight cache initialization failed"),
)
})
}
fn plain_moe<'c>(
execution: EvaluationExecution,
binding: &ModelBinding,
context: &'c Context<'_>,
) -> Cache<'c> {
match execution {
EvaluationExecution::Native | EvaluationExecution::ExperimentalWindowed256RetainedGr => {
MoeWeightCache::new(binding, context)
}
EvaluationExecution::ExperimentalResidentMmq => MoeWeightCache::new_mmq(binding, context),
EvaluationExecution::ExperimentalNativeResidentMmq => {
MoeWeightCache::new_native_mmq(binding, context)
}
EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => {
MoeWeightCache::new_native_integer_iq3_mmq(binding, context)
}
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr => {
MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv(binding, context)
}
}
}
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
fn optimized_moe<'c>(
binding: &ModelBinding,
context: &'c Context<'_>,
flags: PolicyFlags,
ranked_profile: Option<&[u8]>,
) -> Result<Cache<'c>, BackendError> {
Ok(match ranked_profile {
Some(bytes) if flags.adaptive_slots => adaptive_moe(binding, context, bytes),
Some(bytes) if flags.resident_owners => learned_main_moe(binding, context, bytes),
Some(bytes) if flags.streamed_spill => {
MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor(
binding, context, bytes,
)
}
Some(bytes) if flags.queued_owners => {
MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input(
binding, context, bytes,
)
}
Some(bytes) => {
MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile(
binding, context, bytes,
)
}
None => MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(
binding, context,
),
})
}
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
fn optimized_moe<'c>(
_: &ModelBinding,
_: &'c Context<'_>,
_: PolicyFlags,
ranked_profile: Option<&[u8]>,
) -> Result<Cache<'c>, BackendError> {
let _ = &ranked_profile;
Err(unsupported(
"optimized CUDA execution requires Linux x86_64",
))
}
@@ -0,0 +1,139 @@
//! Witness gates of the adaptive-slots and the learned-main MoE caches (CUDA platforms only): a cache is accepted
//! only when its witness shows the state a fresh load must have; otherwise it is closed and refused.
use super::*;
use crate::qwen_forward::contract::Error as ForwardError;
use crate::qwen_forward::moe_weight_cache::{
AdaptiveWitness, LearnedMainWitness, SharedPermanentWitness,
};
use leleka_cuda_driver::Context;
type Cache<'c> = Result<MoeWeightCache<'c>, ForwardError>;
/// A refused cache is closed before the refusal is reported.
fn close_refused<'c>(cache: MoeWeightCache<'c>, error: ForwardError) -> Cache<'c> {
let _ = cache.close();
Err(error)
}
pub(super) fn adaptive_moe<'c>(
binding: &ModelBinding,
context: &'c Context<'_>,
bytes: &[u8],
) -> Cache<'c> {
let cache = MoeWeightCache::new_native_strata_adaptive_shared_permanent_mapped(
binding, context, bytes,
)?;
match cache.strata_adaptive_witness(binding) {
Ok(witness) if adaptive_fresh(&witness) => Ok(cache),
Ok(_) => close_refused(cache, ForwardError::IdentityMismatch),
Err(primary) => close_refused(cache, primary),
}
}
/// A fresh adaptive cache holds its initial slots, all resident, with no swap, window or occurrence yet.
fn adaptive_fresh(w: &AdaptiveWitness) -> bool {
w.initial_slots > 0
&& w.resident_slots == w.initial_slots
&& adaptive_idle(w)
&& w.preload_upload_bytes == w.raw_slot_bytes as u64
}
fn adaptive_idle(w: &AdaptiveWitness) -> bool {
w.pending_swaps == 0
&& w.verified_windows == 0
&& w.routed_occurrences == 0
&& w.resident_occurrences == 0
&& w.cpu_occurrences == 0
&& w.completed_swaps == 0
&& w.completed_swap_upload_bytes == 0
}
pub(super) fn learned_main_moe<'c>(
binding: &ModelBinding,
context: &'c Context<'_>,
bytes: &[u8],
) -> Cache<'c> {
let cache = MoeWeightCache::
new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru(
binding, context, bytes,
)?;
let checked = match cache.learned_main_witness(binding) {
Ok(witness) => learned_main_check(&cache, &witness),
Err(primary) => Err(primary),
};
match checked {
Ok(()) => Ok(cache),
Err(primary) => close_refused(cache, primary),
}
}
fn learned_main_check(
cache: &MoeWeightCache<'_>,
w: &LearnedMainWitness,
) -> Result<(), ForwardError> {
let s = cache.shared_permanent_witness()?;
if learned_shared_mismatch(w, &s) || learned_main_mismatch(w) {
return Err(ForwardError::IdentityMismatch);
}
let demand =
u64::try_from(w.routed_matrices + w.shared_matrices).map_err(|_| ForwardError::Overflow)?;
if w.age < demand || learned_traffic_mismatch(&s) {
return Err(ForwardError::IdentityMismatch);
}
if role_totals(&s)? != inclusive_totals(&s) {
return Err(ForwardError::IdentityMismatch);
}
Ok(())
}
fn learned_shared_mismatch(w: &LearnedMainWitness, s: &SharedPermanentWitness) -> bool {
w.shared_matrices != 192 || s.descriptors != w.shared_matrices || s.bytes != w.shared_bytes
}
fn learned_main_mismatch(w: &LearnedMainWitness) -> bool {
w.routed_matrices == 0
|| w.routed_bytes.checked_add(w.shared_bytes) != Some(w.main_bytes)
|| w.main_bytes > (24usize << 30)
|| w.metadata_bytes > (16usize << 20)
|| w.routed_matrices
.checked_add(w.shared_matrices)
.is_none_or(|n| n > w.main_slot_limit)
|| w.historical_prefix == 0
|| w.historical_routed_preload_bytes != w.routed_bytes
}
fn learned_traffic_mismatch(s: &SharedPermanentWitness) -> bool {
s.roles != s.preload_roles
|| s.request_roles != [Default::default(); 7]
|| !s.successful_bytes_reconcile
}
/// Hits, fills, source-read, upload and eviction bytes summed over the seven roles.
fn role_totals(s: &SharedPermanentWitness) -> Result<[u64; 5], ForwardError> {
s.roles.iter().try_fold([0u64; 5], |mut totals, c| {
for (i, value) in [
c.hits,
c.fills,
c.source_read_bytes,
c.upload_bytes,
c.eviction_bytes,
]
.into_iter()
.enumerate()
{
totals[i] = totals[i].checked_add(value).ok_or(ForwardError::Overflow)?;
}
Ok::<_, ForwardError>(totals)
})
}
/// The inclusive counters the role totals must reconcile with (the fills column is compared with the misses).
fn inclusive_totals(s: &SharedPermanentWitness) -> [u64; 5] {
[
s.inclusive_hits,
s.inclusive_misses,
s.inclusive_source_read_bytes,
s.inclusive_upload_bytes,
s.inclusive_eviction_bytes,
]
}
@@ -0,0 +1,303 @@
//! Load phases that read the pinned sources: verify the shards, bind the artifact and the selected input providers.
use super::*;
use leleka_model_format::qwen4exp::ProvisionalExpertSource;
use std::path::Path;
/// The two verified shards, plus what the capture variants of the optimized modes took from shard 0 and the
/// inherited KAR archive when it was verified at the same time.
pub(super) struct Opened {
pub(super) shard0: VerifiedGgufFile,
pub(super) shard1: VerifiedGgufFile,
pub(super) capture: Option<ProvisionalExpertSource>,
pub(super) kar: Option<InputResultKar>,
}
type Shard0 = Result<(VerifiedGgufFile, Option<ProvisionalExpertSource>), ()>;
type Binding = Result<ModelBinding, InputBindingError>;
// The Original path (no capture variants) verifies shard 0, shard 1 and the inherited archive at once;
// the capture variants of the optimized modes read shard 0 incrementally and keep the sequential order.
pub(super) fn open_sources(
env: &LoadEnv<'_>,
requested: &RuntimeConfig,
flags: PolicyFlags,
) -> Result<Opened, BackendError> {
let parallel_sources = !flags.resident_owners && !flags.streamed_spill;
let archive_wanted = kar_mtp_requested(requested);
let mut prefetched =
parallel_sources.then(|| verify_sources_parallel(env.config, archive_wanted));
let (shard0, capture) =
open_shard0(env.config, prefetched.as_mut(), flags).map_err(shard0_refusal)?;
crate::load_clock::lap("shard0_result");
let shard1 = open_shard1(env.config, prefetched.as_mut()).map_err(shard1_refusal)?;
crate::load_clock::lap("shard1_result");
let kar = prefetched.and_then(|sources| sources.kar);
Ok(Opened {
shard0,
shard1,
capture,
kar,
})
}
fn shard0_refusal(_: ()) -> BackendError {
load_failure(
LoadPhase::Shard0,
invalid("pinned shard 0 verification failed"),
)
}
fn shard1_refusal(_: ()) -> BackendError {
load_failure(
LoadPhase::Shard1,
invalid("pinned shard 1 verification failed"),
)
}
/// The owned KAR file the capture observes (never KAR admission), when an inherited archive is configured.
fn capture_observation(config: &NativeBackendConfig) -> Option<&std::fs::File> {
config
.kar_ple_inherited
.as_ref()
.map(InheritedKarArchive::expert_capture_observation)
}
fn open_shard0(
config: &NativeBackendConfig,
prefetched: Option<&mut VerifiedSources>,
flags: PolicyFlags,
) -> Shard0 {
if let Some(sources) = prefetched {
let shard0 = std::mem::replace(&mut sources.shard0, Err(String::new()));
return shard0.map(|shard| (shard, None)).map_err(|_| ());
}
if flags.resident_owners {
return captured_shard0(config, true);
}
if flags.streamed_spill {
return captured_shard0(config, false);
}
VerifiedGgufFile::open(&config.shard0, SHARD0)
.map(|shard| (shard, None))
.map_err(|_| ())
}
// Borrow metadata only from the operator's actual owned sealed archive.
// Capture's provisional errors remain deferred to the old bank boundary;
// original whole SHA/index failure order still determines model validity.
fn captured_shard0(config: &NativeBackendConfig, incremental: bool) -> Shard0 {
let (path, observation) = (&config.shard0, capture_observation(config));
let opened = if incremental {
Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental(path, SHARD0, observation)
} else {
Qwen4ExpArtifact::open_shard0_with_expert_capture(path, SHARD0, observation)
};
opened
.map(|(shard, capture)| (shard, Some(capture)))
.map_err(|_| ())
}
fn open_shard1(
config: &NativeBackendConfig,
prefetched: Option<&mut VerifiedSources>,
) -> Result<VerifiedGgufFile, ()> {
match prefetched {
Some(sources) => std::mem::replace(&mut sources.shard1, Err(String::new())).map_err(|_| ()),
None => VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| ()),
}
}
/// The bound artifact with the tokenizer and the end-of-sequence id its metadata carries.
pub(super) struct Parts {
pub(super) artifact: Qwen4ExpArtifact,
pub(super) tokenizer: Tokenizer,
pub(super) eos: u32,
}
pub(super) fn bind_artifact(
shard0: VerifiedGgufFile,
shard1: VerifiedGgufFile,
) -> Result<Parts, BackendError> {
let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?;
let (tokenizer, eos) = tokenizer_of(&artifact)?;
crate::load_clock::lap("artifact_bind_and_tokenizer");
Ok(Parts {
artifact,
tokenizer,
eos,
})
}
fn tokenizer_of(artifact: &Qwen4ExpArtifact) -> Result<(Tokenizer, u32), BackendError> {
let metadata = artifact.tokenizer();
let tokenizer = Tokenizer::from_vocabulary(
&metadata.model,
&metadata.pre,
metadata.tokens.clone(),
metadata.merges.clone(),
metadata.token_types.clone(),
)
.map_err(|_| {
load_failure(
LoadPhase::Tokenizer,
invalid("verified tokenizer construction failed"),
)
})?;
let eos = *metadata
.special_ids
.get("tokenizer.ggml.eos_token_id")
.ok_or_else(|| load_failure(LoadPhase::Eos, invalid("verified EOS is absent")))?;
Ok((tokenizer, eos))
}
// The Original-literal MTP drafter bank (mapped host image, page table, ring) is frozen at the trained
// 262144-cell geometry (`MTP_ORIGINAL_MAX_CELLS`); it is refused, not resized, past it.
pub(super) fn check_mtp_context(
config: &NativeBackendConfig,
requested: &RuntimeConfig,
) -> Result<(), BackendError> {
if matches!(
requested.inference_mode,
InferenceMode::ExperimentalMtp { .. }
) && u64::from(config.context_tokens) > leleka_context::rope_scaling::TRAINED_CONTEXT
{
return Err(load_failure(
LoadPhase::EffectiveMode,
unsupported("the MTP drafter bank is frozen at the trained context"),
));
}
Ok(())
}
/// Bind the artifact to the providers the requested mode selects. A refusal of an absent operator source
/// is a plain `BackendError`; a failure inside the binding is mapped to the selected-binding failure.
pub(super) fn bind_selected(
config: &NativeBackendConfig,
requested: &RuntimeConfig,
artifact: Qwen4ExpArtifact,
kar: Option<InputResultKar>,
) -> Result<ModelBinding, BackendError> {
let bound = match &requested.inference_mode {
InferenceMode::Native => ModelBinding::from_artifact(artifact),
InferenceMode::ExperimentalKarPle { .. } => bind_kar_ple(config, artifact)?,
InferenceMode::ExperimentalMtp { profile_id } => {
bind_mtp(config, profile_id, artifact, kar)?
}
_ => return Err(unsupported("experimental mode is not supported")),
};
let binding = bound.map_err(selected_binding_failure)?;
crate::load_clock::lap("binding_kar_and_mtp_total");
Ok(binding)
}
fn bind_kar_ple(
config: &NativeBackendConfig,
artifact: Qwen4ExpArtifact,
) -> Result<Binding, BackendError> {
if let Some(source) = config.kar_ple_inherited.as_ref() {
return Ok(ModelBinding::from_artifact_with_inherited_kar_ple(
artifact, source,
));
}
let (source, staging) = config
.kar_ple_source
.as_ref()
.ok_or_else(|| unsupported("KAR PLE operator source is absent"))?;
Ok(ModelBinding::from_artifact_with_pinned_kar_ple(
artifact, source, staging,
))
}
fn bind_mtp(
config: &NativeBackendConfig,
profile_id: &str,
artifact: Qwen4ExpArtifact,
kar: Option<InputResultKar>,
) -> Result<Binding, BackendError> {
let (source, staging) = config
.mtp_source
.as_ref()
.ok_or_else(|| unsupported("MTP operator source is absent"))?;
if profile_id != KAR_MTP_PROFILE {
return Ok(ModelBinding::from_artifact_with_pinned_mtp(
artifact, source, staging,
));
}
bind_kar_mtp(config, artifact, kar, (source.as_path(), staging.as_path()))
}
fn bind_kar_mtp(
config: &NativeBackendConfig,
artifact: Qwen4ExpArtifact,
kar: Option<InputResultKar>,
(source, staging): (&Path, &Path),
) -> Result<Binding, BackendError> {
if let Some(inherited) = config.kar_ple_inherited.as_ref() {
return Ok(bind_inherited_kar_mtp(
artifact,
inherited,
kar,
(source, staging),
));
}
let (kar_source, kar_staging) = config
.kar_ple_source
.as_ref()
.ok_or_else(|| unsupported("KAR PLE operator source is absent"))?;
Ok(ModelBinding::from_artifact_with_pinned_kar_mtp(
artifact,
kar_source,
kar_staging,
source,
staging,
))
}
/// The archive verified at the same time as the shards when it was, otherwise verified by the binding itself.
fn bind_inherited_kar_mtp(
artifact: Qwen4ExpArtifact,
inherited: &InheritedKarArchive,
prefetched: Option<InputResultKar>,
(source, staging): (&Path, &Path),
) -> Binding {
match prefetched {
Some(verified) => verified.and_then(|verified| {
ModelBinding::from_artifact_with_verified_kar_mtp(artifact, verified, source, staging)
}),
None => {
ModelBinding::from_artifact_with_inherited_kar_mtp(artifact, inherited, source, staging)
}
}
}
// Routed experts from a pinned KAR archive: verified whole (SHA-256 and
// every payload CRC), mapped completely, and bound before publication.
pub(super) fn admit_kar_experts(
env: &LoadEnv<'_>,
binding: ModelBinding,
) -> Result<ModelBinding, BackendError> {
let Some(kar_config) = env.config.kar_expert_source.as_ref() else {
return Ok(binding);
};
if env.optimized.is_some() {
return Err(load_failure(
LoadPhase::Selection,
invalid("KAR expert source is exclusive with the optimized owners"),
));
}
let source = KarExpertSource::open(kar_config).map_err(kar_expert_admission_failure)?;
binding
.with_kar_expert_source(source)
.map_err(selected_binding_failure)
}
fn kar_expert_admission_failure(error: impl std::fmt::Debug) -> BackendError {
use std::io::Write;
let _ = writeln!(
std::io::stderr().lock(),
"leleka-load phase={:?} class={error:?}",
LoadPhase::SelectedBinding
);
invalid("KAR expert source admission failed")
}
@@ -0,0 +1,171 @@
//! What the phase functions of the Load (STRA-338 S5b) must keep from the code they replaced: the policy flags, the
//! execution gates and the weight-cache log line, each compared with the expressions of the former `serve_load`.
use super::*;
use crate::qwen_forward::dense_weight_cache::DenseCacheCounters;
use crate::qwen_forward::moe_weight_cache::WeightCacheCounters;
/// The expressions of the former `serve_load`: queued owners, streamed spill, retained scratch, resident owners,
/// adaptive slots.
fn former_flags(policy: OptimizedOwnerPolicy) -> [bool; 5] {
use OptimizedOwnerPolicy::*;
let config = OptimizedBackendConfig {
ranked_profile: None,
policy,
};
let optimized = Some(&config);
[
optimized.is_some_and(|options| options.policy != Original),
optimized.is_some_and(|options| {
matches!(
options.policy,
StreamedSpill | RetainedScratch | ResidentOwners | AdaptiveSlots
)
}),
optimized.is_some_and(|options| {
matches!(
options.policy,
RetainedScratch | ResidentOwners | AdaptiveSlots
)
}),
optimized.is_some_and(|options| matches!(options.policy, ResidentOwners | AdaptiveSlots)),
optimized.is_some_and(|options| options.policy == AdaptiveSlots),
]
}
#[test]
fn policy_flags_match_the_expressions_of_the_former_serve_load() {
use OptimizedOwnerPolicy::*;
for policy in [
Original,
QueuedOwners,
StreamedSpill,
RetainedScratch,
ResidentOwners,
AdaptiveSlots,
] {
let config = OptimizedBackendConfig {
ranked_profile: None,
policy,
};
let f = PolicyFlags::of(Some(&config));
let flags = [
f.queued_owners,
f.streamed_spill,
f.retained_scratch,
f.resident_owners,
f.adaptive_slots,
];
assert_eq!(flags, former_flags(policy));
}
let none = PolicyFlags::of(None);
assert!(!(none.queued_owners || none.streamed_spill || none.retained_scratch));
assert!(!(none.resident_owners || none.adaptive_slots));
}
/// The three sequential checks of the former `serve_load`, with the booleans they were made of.
fn former_gate(
execution: EvaluationExecution,
kar_mtp: bool,
observed: bool,
gguf_ple: bool,
) -> Option<&'static str> {
use EvaluationExecution::*;
let resident_mmq = matches!(
execution,
ExperimentalResidentMmq | ExperimentalNativeResidentMmq | ExperimentalNativeIntegerIq3Mmq
);
if resident_mmq && (!kar_mtp || !observed) {
return Some("resident MMQ evaluation requires explicit KAR PLE MTP Load");
}
if execution == ExperimentalNativeIntegerIq3Windowed256RetainedGr && !gguf_ple && !kar_mtp {
return Some("IQ3 windowed256 retained GR experiment requires explicit KAR PLE MTP Load");
}
if execution == ExperimentalWindowed256RetainedGr && (!kar_mtp || !observed) {
return Some("windowed256 retained GR evaluation requires explicit KAR PLE MTP Load");
}
None
}
#[test]
fn execution_gates_match_the_former_sequential_checks() {
use EvaluationExecution::*;
let executions = [
Native,
ExperimentalResidentMmq,
ExperimentalNativeResidentMmq,
ExperimentalNativeIntegerIq3Mmq,
ExperimentalWindowed256RetainedGr,
ExperimentalNativeIntegerIq3Windowed256RetainedGr,
];
for execution in executions {
for bits in 0..8u8 {
let (kar_mtp, observed, gguf_ple) = (bits & 1 != 0, bits & 2 != 0, bits & 4 != 0);
assert_eq!(
execution_gate_message(execution, kar_mtp, observed, gguf_ple),
former_gate(execution, kar_mtp, observed, gguf_ple),
"gate differs at bits {bits}"
);
}
}
}
fn moe(
hits: u64,
misses: u64,
read_bytes: u64,
upload_bytes: u64,
eviction_bytes: u64,
) -> WeightCacheCounters {
WeightCacheCounters {
hits,
misses,
read_bytes,
upload_bytes,
eviction_bytes,
}
}
fn dense(hits: u64, read_bytes: u64, upload_bytes: u64) -> DenseCacheCounters {
DenseCacheCounters {
hits,
read_bytes,
upload_bytes,
matrices: 9,
}
}
#[test]
fn generation_cache_line_keeps_its_text() {
let before = Counters {
moe: moe(1, 2, 3, 100, 4),
dense: dense(5, 6, 7),
};
let after = Counters {
moe: moe(11, 5, 30, 250, 9),
dense: dense(8, 6, 70),
};
assert_eq!(
generation_cache_line(before, after, (40, 12345), "completed"),
"leleka-weight-cache phase=generation outcome=completed hits=10 misses=3 source_bytes=27 \
upload_bytes=150 eviction_bytes=5 dense_hits=3 dense_source_bytes=0 dense_upload_bytes=63 \
resident_main_bytes=201 resident_dense_bytes=70 resident_mtp_bytes=40 context_allocated_bytes=12345"
);
}
#[test]
fn generation_cache_line_reads_a_counter_that_went_down_as_zero() {
let before = Counters {
moe: moe(1, 2, 3, 100, 4),
dense: dense(5, 6, 7),
};
let after = Counters {
moe: moe(11, 5, 30, 250, 9),
dense: dense(8, 6, 70),
};
assert_eq!(
generation_cache_line(after, before, (400, 1), "failed"),
"leleka-weight-cache phase=generation outcome=failed hits=0 misses=0 source_bytes=0 \
upload_bytes=0 eviction_bytes=0 dense_hits=0 dense_source_bytes=0 dense_upload_bytes=0 \
resident_main_bytes=0 resident_dense_bytes=7 resident_mtp_bytes=400 context_allocated_bytes=1"
);
}
@@ -0,0 +1,199 @@
//! The weight caches a native Load builds on the CUDA context: output head, KAR PLE cache, dense and MoE weights.
use super::*;
use leleka_cuda_driver::Context;
type ForwardResult<T> = Result<T, crate::qwen_forward::contract::Error>;
/// The caches of one loaded model. Fields are in the order they are dropped: dense, MoE, KAR PLE, output head.
pub(super) struct Weights<'c, 'd> {
pub(super) dense_cache: DenseWeightCache<'c>,
pub(super) moe_cache: MoeWeightCache<'c>,
pub(super) kar_cache: Option<KarPleCache<'c>>,
pub(super) output: OutputStage<'c, 'd>,
/// Fixed resident MTP bytes: never part of the main LRU; the fixed MTP charge and the ranked main-cache
/// preload are reported separately.
pub(super) mtp_resident_bytes: u64,
}
// Immutable weights borrow this actor's stable external Context. MTP pack
// and fixed dense stages are charged before the lazy MoE LRU can grow.
// The ranked cache may preload only after every dense/router eager charge.
pub(super) fn load_weights<'c, 'd>(
env: &LoadEnv<'_>,
binding: &ModelBinding,
context: &'c Context<'d>,
flags: PolicyFlags,
ranked_profile: Option<&[u8]>,
) -> Result<Weights<'c, 'd>, BackendError> {
let output = load_output(binding, context, flags.queued_owners)?;
let kar_cache = load_kar_cache(binding, context)?;
let mut optimized_dense = load_optimized_dense(env, binding, context, flags)?;
let moe_cache = load_moe(
env,
binding,
context,
flags,
ranked_profile,
&mut optimized_dense,
)?;
let mtp_resident_bytes = mtp_resident_bytes(&moe_cache)?;
let dense_cache = staged_or_plain_dense(binding, context, &mut optimized_dense)?;
// The optional staging owner is empty after take; end its Context borrow.
drop(optimized_dense);
Ok(Weights {
dense_cache,
moe_cache,
kar_cache,
output,
mtp_resident_bytes,
})
}
fn load_output<'c, 'd>(
binding: &ModelBinding,
context: &'c Context<'d>,
queued_owners: bool,
) -> Result<OutputStage<'c, 'd>, BackendError> {
let stage = if queued_owners {
load_compact_output(binding, context)?
} else {
OutputStage::load(binding, context)
};
stage.map_err(|e| {
load_forward_failure(
LoadPhase::OutputHead,
e,
exhausted("native output head initialization failed"),
)
})
}
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
fn load_compact_output<'c, 'd>(
binding: &ModelBinding,
context: &'c Context<'d>,
) -> Result<ForwardResult<OutputStage<'c, 'd>>, BackendError> {
Ok(OutputStage::load_compact(binding, context))
}
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
fn load_compact_output<'c, 'd>(
_: &ModelBinding,
_: &'c Context<'d>,
) -> Result<ForwardResult<OutputStage<'c, 'd>>, BackendError> {
Err(unsupported("queued CUDA owners require Linux x86_64"))
}
fn load_kar_cache<'c>(
binding: &ModelBinding,
context: &'c Context<'_>,
) -> Result<Option<KarPleCache<'c>>, BackendError> {
binding
.kar_ple_binding()
.map(|provider| KarPleCache::new(context, provider))
.transpose()
.map_err(|e| {
load_forward_failure(
LoadPhase::KarCache,
e,
exhausted("KAR PLE cache initialization failed"),
)
})
}
fn staged_or_plain_dense<'c>(
binding: &ModelBinding,
context: &'c Context<'_>,
staged: &mut Option<DenseWeightCache<'c>>,
) -> Result<DenseWeightCache<'c>, BackendError> {
match staged.take() {
Some(dense) => Ok(dense),
None => load_plain_dense(binding, context),
}
}
fn load_plain_dense<'c>(
binding: &ModelBinding,
context: &'c Context<'_>,
) -> Result<DenseWeightCache<'c>, BackendError> {
DenseWeightCache::new(binding, context).map_err(|e| {
load_forward_failure(
LoadPhase::DenseWeightCache,
e,
exhausted("dense weight cache initialization failed"),
)
})
}
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
fn load_optimized_dense<'c>(
env: &LoadEnv<'_>,
binding: &ModelBinding,
context: &'c Context<'_>,
flags: PolicyFlags,
) -> Result<Option<DenseWeightCache<'c>>, BackendError> {
if env.optimized.is_none() {
return Ok(None);
}
let built = if flags.resident_owners {
DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(
binding, context,
)
} else if flags.retained_scratch {
DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention(binding, context)
} else if flags.queued_owners {
DenseWeightCache::new_qsa_selected_router_gr_batch(binding, context)
} else {
DenseWeightCache::new_qsa_selected_router(binding, context)
};
built.map(Some).map_err(|e| {
load_forward_failure(
LoadPhase::DenseWeightCache,
e,
exhausted("optimized dense initialization failed"),
)
})
}
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
fn load_optimized_dense<'c>(
_: &LoadEnv<'_>,
_: &ModelBinding,
_: &'c Context<'_>,
_: PolicyFlags,
) -> Result<Option<DenseWeightCache<'c>>, BackendError> {
Ok(None)
}
/// Resident MTP bytes: the upload of the cache build minus the ranked-profile preload.
fn mtp_resident_bytes(moe_cache: &MoeWeightCache<'_>) -> Result<u64, BackendError> {
let initial_cache_upload_bytes = moe_cache.counters().upload_bytes;
#[cfg(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
))]
let profile_preload_bytes = moe_cache.profile_preload_upload_bytes();
#[cfg(not(all(
any(target_os = "linux", target_os = "windows"),
target_arch = "x86_64"
)))]
let profile_preload_bytes = 0;
initial_cache_upload_bytes
.checked_sub(profile_preload_bytes)
.ok_or_else(|| {
load_failure(
LoadPhase::MoeWeightCache,
invalid("cache preload accounting mismatch"),
)
})
}
+97 -45
View File
@@ -56,6 +56,94 @@ pub(super) fn load_forward_failure(
result
}
/// What the owner thread keeps for its whole life; one `LoadEnv` is made from it per Load.
struct OwnerCtx<'a> {
config: &'a NativeBackendConfig,
rx: &'a Receiver<Command>,
shared: &'a Shared,
instance: u64,
observer: Option<&'a EvaluationObserver>,
selection: &'a OwnerExecution,
}
impl<'a> OwnerCtx<'a> {
fn new(
config: &'a NativeBackendConfig,
rx: &'a Receiver<Command>,
shared: &'a Shared,
instance: u64,
observer: Option<&'a EvaluationObserver>,
selection: &'a OwnerExecution,
) -> Self {
Self {
config,
rx,
shared,
instance,
observer,
selection,
}
}
fn run(&self) {
let mut serial = 0_u64;
while !self.shared.shutdown.load(Ordering::Acquire) {
let command = match self.rx.recv_timeout(Duration::from_millis(100)) {
Ok(command) => command,
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(_) => break,
};
match command {
Command::Load(model, requested, reply) => {
let Some(next) = serial.checked_add(1) else {
break;
};
serial = next;
self.load(serial, model, requested, reply);
}
other => refuse_unloaded(self.shared, other),
}
}
}
fn load(
&self,
serial: u64,
model: ModelDescriptor,
requested: RuntimeConfig,
reply: Reply<LoadedModel>,
) {
let env = LoadEnv {
config: self.config,
rx: self.rx,
shared: self.shared,
reply: &reply,
instance: self.instance,
serial,
observer: self.observer,
execution: self.selection.kind,
optimized: self.selection.optimized.as_ref(),
original: self.selection.original.as_ref(),
};
if let Err(error) = serve_load(&env, model, requested) {
let _ = reply.send(Err(error));
}
}
}
fn reply_no_model<T>(reply: Reply<T>) {
let _ = reply.send(Err(invalid("no model is loaded")));
}
/// Every command except Load while nothing is loaded.
fn refuse_unloaded(shared: &Shared, command: Command) {
match command {
Command::Generate(_, _, _, reply) => {
clear_active(shared);
reply_no_model(reply);
}
Command::Unload(_, reply) => reply_no_model(reply),
Command::Reconfigure(_, reply) => reply_no_model(reply),
Command::Load(_, _, reply) => reply_no_model(reply),
}
}
pub(super) fn owner(
config: NativeBackendConfig,
rx: Receiver<Command>,
@@ -64,49 +152,13 @@ pub(super) fn owner(
observer: Option<EvaluationObserver>,
selection: OwnerExecution,
) {
let execution = selection.kind;
let mut serial = 0_u64;
while !shared.shutdown.load(Ordering::Acquire) {
let command = match rx.recv_timeout(Duration::from_millis(100)) {
Ok(command) => command,
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(_) => break,
};
match command {
Command::Load(model, requested, reply) => {
serial = match serial.checked_add(1) {
Some(value) => value,
None => break,
};
if let Err(error) = serve_load(
&config,
&rx,
shared,
model,
requested,
&reply,
(
instance,
serial,
observer.as_ref(),
execution,
selection.optimized.as_ref(),
selection.original.as_ref(),
),
) {
let _ = reply.send(Err(error));
}
}
Command::Generate(_, _, _, reply) => {
clear_active(shared);
let _ = reply.send(Err(invalid("no model is loaded")));
}
Command::Unload(_, reply) => {
let _ = reply.send(Err(invalid("no model is loaded")));
}
Command::Reconfigure(_, reply) => {
let _ = reply.send(Err(invalid("no model is loaded")));
}
}
}
OwnerCtx::new(
&config,
&rx,
shared,
instance,
observer.as_ref(),
&selection,
)
.run();
}
@@ -0,0 +1,83 @@
//! The end of a loaded native model: the weights and the context are closed and the Unload caller is answered.
use super::*;
use leleka_cuda_driver::Context;
/// What closing the weights left to settle with the context.
pub(super) struct Closed {
caches_failed: bool,
unload_reply: Option<Reply<()>>,
}
/// Mark the model not ready, drop the conversations, report the cache counters and close the caches.
pub(super) fn close_weights(
shared: &Shared,
mut conversations: Conversations<'_>,
weights: Weights<'_, '_>,
unload_reply: Option<Reply<()>>,
) -> Closed {
shared.ready.store(false, Ordering::Release);
conversations.clear();
drop(conversations);
log_final_counters(&weights);
let Weights {
dense_cache,
moe_cache,
kar_cache,
output,
..
} = weights;
let moe_closed = moe_cache.close();
let dense_closed = dense_cache.close();
drop(kar_cache);
drop(output);
Closed {
caches_failed: moe_closed.is_err() || dense_closed.is_err(),
unload_reply,
}
}
fn log_final_counters(weights: &Weights<'_, '_>) {
use std::io::Write;
let moe = weights.moe_cache.counters();
let dense = weights.dense_cache.counters();
let _ = writeln!(
std::io::stderr().lock(),
"leleka-weight-cache hits={} misses={} read_bytes={} upload_bytes={} eviction_bytes={} \
dense_hits={} dense_matrices={} dense_read_bytes={} dense_upload_bytes={}",
moe.hits,
moe.misses,
moe.read_bytes,
moe.upload_bytes,
moe.eviction_bytes,
dense.hits,
dense.matrices,
dense.read_bytes,
dense.upload_bytes
);
}
/// Close the context once nothing borrows it, mark the owner shut down on a failure and answer Unload.
pub(super) fn close_context(
shared: &Shared,
context: Rc<Context<'_>>,
closed: Closed,
) -> Result<(), BackendError> {
let context_closed = Rc::try_unwrap(context)
.map_err(|_| unavailable("native context still borrowed"))?
.close()
.map_err(|_| unavailable("native context cleanup failed"));
let result = context_closed.and_then(|()| {
if closed.caches_failed {
Err(unavailable("weight cache cleanup failed"))
} else {
Ok(())
}
});
if result.is_err() {
shared.shutdown.store(true, Ordering::Release);
}
if let Some(reply) = closed.unload_reply {
let _ = reply.send(result);
}
Ok(())
}
@@ -0,0 +1,227 @@
//! One Generate command of the serve loop: admit it, resume or start a session, generate, publish the terminal.
use super::*;
use std::cell::RefCell;
/// One Generate command as it arrived.
pub(super) struct Job {
pub(super) candidate: LoadedModel,
pub(super) request: GenerationRequest,
pub(super) cancel: Arc<AtomicBool>,
pub(super) reply: Reply<GenerationStream>,
}
impl Job {
pub(super) fn new(
candidate: LoadedModel,
request: GenerationRequest,
cancel: Arc<AtomicBool>,
reply: Reply<GenerationStream>,
) -> Self {
Self {
candidate,
request,
cancel,
reply,
}
}
}
/// An admitted job: its prompt tokens and the sink its stream is published on.
pub(super) struct Admitted {
pub(super) prompt: Vec<u32>,
pub(super) sink: GenerationSink,
}
/// What one exchange works on. Fields are in the order they are dropped.
pub(super) struct Exchange<'c> {
pub(super) measured: Option<RefCell<measurement::Recorder>>,
pub(super) resume: Option<MtpContinuation>,
pub(super) session: QwenSession<'c>,
pub(super) pending_prefix: Option<MtpContinuation>,
pub(super) before: Counters,
}
impl<'c> Exchange<'c> {
pub(super) fn begin(
sv: &Serving<'_, 'c, '_>,
session: QwenSession<'c>,
resume: Option<MtpContinuation>,
admitted: &Admitted,
job: &Job,
) -> Self {
let before = Counters::of(sv.weights);
let measured = sv.env.observer.map(|_| {
RefCell::new(measurement::Recorder::new(
&admitted.prompt,
job.request.max_output_tokens,
))
});
Self {
measured,
resume,
session,
pending_prefix: None,
before,
}
}
}
pub(super) fn handle_generate<'c>(
sv: &mut Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
job: Job,
) -> Result<(), BackendError> {
let _guard = ActiveGuard(sv.env.shared);
let Some(admitted) = admit(sv, conversations, &job)? else {
return Ok(());
};
let (session, resume) = start_session(sv, conversations, &admitted.prompt);
let mut exchange = Exchange::begin(sv, session, resume, &admitted, &job);
let outcome = run_generation(sv, &job, &admitted, &mut exchange);
log_generation_cache(sv, exchange.before, &outcome);
if let Some(continuation) = conclude(sv, &job, &admitted, &mut exchange, outcome) {
publish_prefix(sv, conversations, continuation, exchange.session);
}
log_conversation_events(conversations);
Ok(())
}
/// Refusals clear the resident conversations and answer the caller; `None` ends the exchange.
fn admit<'c>(
sv: &Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
job: &Job,
) -> Result<Option<Admitted>, BackendError> {
let prompt = match prompt_for(sv, job) {
Ok(prompt) => prompt,
Err(error) => {
conversations.clear();
let _ = job.reply.send(Err(error));
return Ok(None);
}
};
let (sink, stream) = GenerationSink::bounded_channel(QUEUE)
.map_err(|_| unavailable("generation queue unavailable"))?;
if job.reply.send(Ok(stream)).is_err() {
conversations.clear();
return Ok(None);
}
Ok(Some(Admitted { prompt, sink }))
}
/// The prompt tokens of an acceptable job, or the refusal to answer it with.
fn prompt_for(sv: &Serving<'_, '_, '_>, job: &Job) -> Result<Vec<u32>, BackendError> {
if job.candidate != *sv.loaded {
return Err(invalid("unknown loaded model handle"));
}
if !sv.env.shared.ready.load(Ordering::Acquire) {
return Err(unavailable("native model is not ready"));
}
prepare_prompt(
&sv.bound.tokenizer,
&job.request,
sv.env.config.context_tokens,
)
}
fn start_session<'c>(
sv: &Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
prompt: &[u32],
) -> (QwenSession<'c>, Option<MtpContinuation>) {
match take_resumable(sv, conversations, prompt) {
Some(entry) => (entry.session, Some(entry.continuation)),
None => {
let fresh =
QwenSession::for_binding_on_shared_device(&sv.bound.binding, Rc::clone(sv.context));
(fresh, None)
}
}
}
// Take before attempting any work: no failed/cancelled request
// may leave the entry it consumed behind. A candidate must be
// for this handle, a strict token-prefix of the prompt, and
// still validate against the device; a live session that is
// not the one continuing is parked (when enabled), not lost.
fn take_resumable<'c>(
sv: &Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
prompt: &[u32],
) -> Option<PrefixSession<'c>> {
let (loaded, binding, shared) = (sv.loaded, &sv.bound.binding, sv.env.shared);
conversations
.take_for(prompt, |entry| {
resumable(entry, loaded, binding, shared, prompt)
})
.map(|resumed| resumed.session)
}
fn resumable(
entry: &PrefixSession<'_>,
loaded: &LoadedModel,
binding: &ModelBinding,
shared: &Shared,
prompt: &[u32],
) -> bool {
if entry.loaded != *loaded || !append_compatible(&entry.continuation.tokens, prompt) {
return false;
}
let resume = &entry.continuation;
match resume
.decoder
.validate_resume(binding, &entry.session, &resume.product, &resume.tokens)
{
Ok(()) => true,
Err(crate::qwen_forward::contract::Error::CudaExecution) => {
// Dropping a poisoned session cannot mint a fresh
// healthy session on the same actor/context.
shared.ready.store(false, Ordering::Release);
false
}
Err(_) => false,
}
}
/// Publish the terminal, deliver the measurement, and return the continuation that may be resumed later.
fn conclude(
sv: &Serving<'_, '_, '_>,
job: &Job,
admitted: &Admitted,
x: &mut Exchange<'_>,
outcome: Outcome,
) -> Option<MtpContinuation> {
let verdict = verdict(&outcome);
let shared = sv.env.shared;
// Terminal publication is bounded too; after transport loss,
// closing without a terminal is reported as MissingTerminal.
let published = emit_terminal(&admitted.sink, terminal_of(outcome)).is_ok();
let continuation = terminal_admit(
x.pending_prefix.take(),
verdict.stopped,
published,
job.cancel.load(Ordering::Acquire),
shared.shutdown.load(Ordering::Acquire),
admitted.sink.is_closed(),
shared.ready.load(Ordering::Acquire),
);
deliver_measurement(sv, x, &verdict, published);
continuation
}
fn publish_prefix<'c>(
sv: &Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
continuation: MtpContinuation,
session: QwenSession<'c>,
) {
let committed = continuation.tokens.clone();
let loaded = sv.loaded.clone();
conversations.publish(
&committed,
PrefixSession {
loaded,
session,
continuation,
},
);
}
@@ -0,0 +1,126 @@
//! The command loop of a loaded native model: Load and Reconfigure are refused, Unload ends the loop, Generate runs.
use super::*;
use leleka_cuda_driver::Context;
/// The resident conversations of one loaded model: the live continuation plus (operator opt-in) parked ones.
pub(super) type Conversations<'c> = ResidentConversations<PrefixSession<'c>>;
/// Everything the command loop works on, borrowed from the Load that owns it.
pub(super) struct Serving<'a, 'c, 'd> {
pub(super) env: &'a LoadEnv<'a>,
pub(super) bound: &'a Bound,
pub(super) context: &'a Rc<Context<'d>>,
pub(super) loaded: &'a LoadedModel,
pub(super) weights: &'a mut Weights<'c, 'd>,
}
impl<'a, 'c, 'd> Serving<'a, 'c, 'd> {
pub(super) fn new(
env: &'a LoadEnv<'a>,
bound: &'a Bound,
context: &'a Rc<Context<'d>>,
loaded: &'a LoadedModel,
weights: &'a mut Weights<'c, 'd>,
) -> Self {
Self {
env,
bound,
context,
loaded,
weights,
}
}
}
/// Whether the loop goes on after a command.
#[derive(PartialEq)]
enum Flow {
Continue,
Unload,
}
// 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 serve_commands<'c>(
sv: &mut Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
unload_reply: &mut Option<Reply<()>>,
) -> Result<(), BackendError> {
while !sv.env.shared.shutdown.load(Ordering::Acquire) {
match sv.env.rx.recv_timeout(Duration::from_millis(100)) {
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(_) => break,
Ok(command) => {
if dispatch(sv, conversations, unload_reply, command)? == Flow::Unload {
break;
}
}
}
}
Ok(())
}
fn dispatch<'c>(
sv: &mut Serving<'_, 'c, '_>,
conversations: &mut Conversations<'c>,
unload_reply: &mut Option<Reply<()>>,
command: Command,
) -> Result<Flow, BackendError> {
match command {
Command::Load(_, _, reply) => refuse_load(conversations, reply),
Command::Reconfigure(_, reply) => refuse_reconfigure(reply),
Command::Unload(candidate, reply) => {
conversations.clear();
return Ok(unload(sv.loaded, candidate, reply, unload_reply));
}
Command::Generate(candidate, request, cancel, reply) => {
handle_generate(
sv,
conversations,
Job::new(candidate, request, cancel, reply),
)?;
}
}
Ok(Flow::Continue)
}
fn refuse_load(conversations: &mut Conversations<'_>, reply: Reply<LoadedModel>) {
conversations.clear();
let _ = reply.send(Err(exhausted(
"unload the existing model before another load",
)));
}
fn refuse_reconfigure(reply: Reply<String>) {
let _ = reply.send(Err(unsupported(
"this backend cannot be reconfigured at run time",
)));
}
/// The loop ends when the handle is the loaded one; its reply is kept until the model is closed.
fn unload(
loaded: &LoadedModel,
candidate: LoadedModel,
reply: Reply<()>,
unload_reply: &mut Option<Reply<()>>,
) -> Flow {
if candidate != *loaded {
let _ = reply.send(Err(invalid("unknown loaded model handle")));
return Flow::Continue;
}
*unload_reply = Some(reply);
Flow::Unload
}
@@ -0,0 +1,166 @@
//! What one Generate reports: the weight-cache counters, the terminal verdict and the measurement.
use super::*;
use crate::qwen_forward::dense_weight_cache::DenseCacheCounters;
use crate::qwen_forward::moe_weight_cache::WeightCacheCounters;
/// The weight-cache counters at one moment.
#[derive(Clone, Copy)]
pub(super) struct Counters {
pub(super) moe: WeightCacheCounters,
pub(super) dense: DenseCacheCounters,
}
impl Counters {
pub(super) fn of(weights: &Weights<'_, '_>) -> Self {
Self {
moe: weights.moe_cache.counters(),
dense: weights.dense_cache.counters(),
}
}
pub(super) fn counts(self) -> CacheCounts {
let (m, d) = (self.moe, self.dense);
CacheCounts {
expert_hits: m.hits,
expert_misses: m.misses,
expert_source_bytes: m.read_bytes,
expert_upload_bytes: m.upload_bytes,
expert_eviction_bytes: m.eviction_bytes,
dense_hits: d.hits,
dense_source_bytes: d.read_bytes,
dense_upload_bytes: d.upload_bytes,
}
}
}
/// The weight-cache counters this generation moved, as one stderr line.
pub(super) fn log_generation_cache(sv: &Serving<'_, '_, '_>, before: Counters, outcome: &Outcome) {
use std::io::Write;
let after = Counters::of(sv.weights);
let label = match outcome {
Ok(_) => "completed",
Err(GenerationFailure::Cancelled) => "cancelled",
Err(GenerationFailure::Backend(_)) => "failed",
};
let allocated = sv.context.allocated_bytes();
let line = generation_cache_line(
before,
after,
(sv.weights.mtp_resident_bytes, allocated),
label,
);
let _ = writeln!(std::io::stderr().lock(), "{line}");
}
pub(super) fn generation_cache_line(
before: Counters,
after: Counters,
(mtp_resident_bytes, allocated): (u64, usize),
outcome: &str,
) -> String {
let [hits, misses, source, upload, eviction] = moe_deltas(before.moe, after.moe);
let [dense_hits, dense_source, dense_upload] = dense_deltas(before.dense, after.dense);
// Resident main bytes are successful uploads less successful
// LRU frees; eager MTP/dense weights are never eviction victims.
let main_resident = after
.moe
.upload_bytes
.saturating_sub(mtp_resident_bytes)
.saturating_sub(after.moe.eviction_bytes);
let resident_dense = after.dense.upload_bytes;
format!(
"leleka-weight-cache phase=generation outcome={outcome} hits={hits} misses={misses} \
source_bytes={source} upload_bytes={upload} eviction_bytes={eviction} dense_hits={dense_hits} \
dense_source_bytes={dense_source} dense_upload_bytes={dense_upload} \
resident_main_bytes={main_resident} resident_dense_bytes={resident_dense} \
resident_mtp_bytes={mtp_resident_bytes} context_allocated_bytes={allocated}"
)
}
/// Hits, misses, source, upload and eviction bytes the MoE cache moved between two snapshots.
pub(super) fn moe_deltas(before: WeightCacheCounters, after: WeightCacheCounters) -> [u64; 5] {
[
after.hits.saturating_sub(before.hits),
after.misses.saturating_sub(before.misses),
after.read_bytes.saturating_sub(before.read_bytes),
after.upload_bytes.saturating_sub(before.upload_bytes),
after.eviction_bytes.saturating_sub(before.eviction_bytes),
]
}
/// Hits, source and upload bytes the dense cache moved between two snapshots.
pub(super) fn dense_deltas(before: DenseCacheCounters, after: DenseCacheCounters) -> [u64; 3] {
[
after.hits.saturating_sub(before.hits),
after.read_bytes.saturating_sub(before.read_bytes),
after.upload_bytes.saturating_sub(before.upload_bytes),
]
}
/// What the finished generation says about itself, taken before the result is consumed.
pub(super) struct Verdict {
pub(super) ok: bool,
pub(super) stopped: bool,
pub(super) usage: Option<(u64, u64, u64)>,
}
pub(super) fn verdict(outcome: &Outcome) -> Verdict {
Verdict {
ok: outcome.is_ok(),
// Length truncation is not admitted as a reusable public result.
stopped: matches!(outcome, Ok((FinishReason::Stop, _))),
usage: match outcome {
Ok((_, usage)) => Some((
usage.input_tokens,
usage.output_tokens,
usage.reused_input_tokens,
)),
Err(_) => None,
},
}
}
pub(super) fn terminal_of(outcome: Outcome) -> GenerationTerminal {
match outcome {
Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage },
Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled,
Err(GenerationFailure::Backend(error)) => GenerationTerminal::Failed {
code: error.code,
message: error.message,
retryable: false,
},
}
}
pub(super) fn deliver_measurement(
sv: &Serving<'_, '_, '_>,
x: &mut Exchange<'_>,
verdict: &Verdict,
published: bool,
) {
let (Some(observer), Some(measured)) = (sv.env.observer, x.measured.take()) else {
return;
};
let after = Counters::of(sv.weights).counts();
let record = measured.into_inner().finish(
x.before.counts(),
after,
verdict.ok,
verdict.stopped,
published,
verdict.usage,
);
if !measurement::notify(observer, record) {
use std::io::Write;
// Fixed delivery status only; no request, IDs, paths or data.
let _ = writeln!(
std::io::stderr().lock(),
"leleka-evaluation observation-delivery=failed"
);
}
}
pub(super) fn log_conversation_events(conversations: &mut Conversations<'_>) {
use std::io::Write;
for event in conversations.take_events() {
let _ = writeln!(std::io::stderr().lock(), "leleka-{event}");
}
}
@@ -0,0 +1,115 @@
//! Running one admitted generation: the Generation step context and the choice of the generation loop.
use super::*;
use std::cell::RefCell;
pub(super) type Sampler =
Result<Option<leleka_sampler_ref::SamplerParams>, leleka_sampler_ref::SamplingError>;
pub(super) type Outcome = Result<(FinishReason, Usage), GenerationFailure>;
pub(super) fn run_generation<'c>(
sv: &mut Serving<'_, 'c, '_>,
job: &Job,
admitted: &Admitted,
x: &mut Exchange<'c>,
) -> Outcome {
let run = build_run(sv, job, admitted, (&mut x.session, x.measured.as_ref()));
let sampler = request_sampler(&job.request, clock_seed());
let max = job.request.max_output_tokens;
choose_generation(
run,
sampler,
(&admitted.prompt, max),
&mut x.resume,
&mut x.pending_prefix,
)
}
pub(super) fn build_run<'a, 'c, 'd>(
sv: &'a mut Serving<'_, 'c, 'd>,
job: &'a Job,
admitted: &'a Admitted,
(session, measurement): (
&'a mut QwenSession<'c>,
Option<&'a RefCell<measurement::Recorder>>,
),
) -> Generation<'a, 'c, 'd> {
Generation {
measurement,
execution: sv.env.execution,
binding: &sv.bound.binding,
output: &sv.weights.output,
kar_cache: sv.weights.kar_cache.as_mut(),
moe_cache: &mut sv.weights.moe_cache,
dense_cache: &sv.weights.dense_cache,
session,
tokenizer: &sv.bound.tokenizer,
sink: &admitted.sink,
cancel: &job.cancel,
shared: sv.env.shared,
context_tokens: sv.env.config.context_tokens,
eos: sv.bound.eos,
mtp: matches!(
sv.loaded.effective_mode,
InferenceMode::ExperimentalMtp { .. }
),
}
}
pub(super) fn choose_generation(
run: Generation<'_, '_, '_>,
sampler: Sampler,
(prompt, max): (&[u32], u32),
resume: &mut Option<MtpContinuation>,
pending_prefix: &mut Option<MtpContinuation>,
) -> Outcome {
if !run.shared.ready.load(Ordering::Acquire) {
Err(GenerationFailure::Backend(unavailable(
"resident prefix unavailable",
)))
} else if matches!(sampler, Err(_) | Ok(Some(_))) && run.mtp {
// Sampled drafting/verification (coupled draft sampling) is not wired.
Err(GenerationFailure::Backend(unsupported(
"sampling is unavailable with MTP",
)))
} else if run.mtp {
generate_mtp_resume(run, prompt, max, resume.take(), pending_prefix)
} else {
generate_single(run, sampler, prompt, max)
}
}
pub(super) fn generate_single(
run: Generation<'_, '_, '_>,
sampler: Sampler,
prompt: &[u32],
max: u32,
) -> Outcome {
match sampler {
Ok(None) => generate(run, prompt, max),
Ok(Some(params)) => generate_sampled(run, params, prompt, max),
Err(_) => Err(GenerationFailure::Backend(invalid(
"unsupported generation request",
))),
}
}
pub(super) fn generate_sampled(
run: Generation<'_, '_, '_>,
params: leleka_sampler_ref::SamplerParams,
prompt: &[u32],
max: u32,
) -> Outcome {
let output = run.output;
let armed = crate::qwen_forward::step_sampler::StepSampler::new(params, prompt)
.and_then(|plan| output.arm_sampler(plan));
match armed {
Ok(()) => {
let result = generate(run, prompt, max);
output.disarm_sampler();
result
}
Err(_) => Err(GenerationFailure::Backend(unavailable(
"sampling setup failed",
))),
}
}
@@ -36,6 +36,8 @@ mod cache_strata_adaptive;
mod cache_original_prompt;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) use cache_original_prompt::{PREFILL_STREAM_OVERRIDE, set_span_cache_override};
pub(crate) use cache_profile::{LearnedMainWitness, SharedPermanentWitness};
pub(crate) use cache_strata_adaptive::AdaptiveWitness;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "cache_original_verify.rs"]
mod cache_original_verify;
+35
View File
@@ -0,0 +1,35 @@
# Architecture tech debt (STRA-367)
Debt that a hexagonal step moved but did not remove. A line here names the file, the limit it misses, and what
removes it. The size and ratchet numbers themselves live in `architecture-baseline.json`.
Limits for new and changed code: function at most 30 lines, cyclomatic complexity at most 10, nesting at most 4,
line at most 120 columns, file at most 400 lines.
## crates/leleka-runtime `backend/` (STRA-338 S5a, S5b)
`backend.rs` (3797 lines) is a parent of 258 lines plus responsibility-named children. `serve_load` is decomposed
into `load.rs` (the order of the phases) and `load_admit`, `load_sources`, `load_identity`, `load_bind`, `load_cuda`,
`load_weights`, `load_moe`, `load_moe_gates`, `serve_loop`, `serve_generate`, `serve_run`, `serve_report`,
`serve_close`; all of them are inside the
limits except the one line named first. What was moved verbatim in S5a and is still outside the limits:
| Where | Misses | Removed by |
| --- | --- | --- |
| `load_moe_gates.rs`, the `learned_main_lru` constructor call | one line of 127 columns: the method name of `MoeWeightCache` is 119 characters | renaming the constructor in `qwen_forward/moe_weight_cache` (its own step) |
| `generate_mtp.rs` `generate_mtp_resume` | 250 lines, complexity 44 | splitting the MTP window loop into phases (engine-core step; GPU identity and A/B gates apply) |
| `generate.rs` `prefill_chunk`, `generate`, `step`, `target_step` | 90, 60, 55, 34 lines; complexity 14 and 10 | same step as above |
| `spawn.rs` `spawn_backend_configured` | 100 lines; recomputes the policy flags that `PolicyFlags::of` now owns | use `PolicyFlags::of`, split the owner hand-over |
| `spawn_optimized.rs` | seven factories of 32 to 39 lines repeating one precondition block | one `OptimizedSelection` check shared by the factories |
| `sources.rs` `verify_sources_parallel`, `read_ranked_expert_profile` | 42 and 51 lines | splitting the scoped verification and the profile read |
| `proxy.rs` `start_generation`, `validate.rs` `validate_handle` | 44 lines; 46 lines and complexity 14 | splitting the checks into predicates |
| `config.rs` | the `*_EXECUTION` identity strings are single lines of 120 to 200 columns | string continuation, with the golden digest test as the guard |
Process-wide state and reads that the policy file `architecture.json` counts and that this directory still holds:
`RECONFIGURING`, `INSTANCE` and `GPU_ORDINAL` (process globals, S14), the `LELEKA_ORIGINAL_SERVE_GGUF_PLE`,
`LELEKA_PUBLIC_EVALUATION` and similar environment reads in `load_admit.rs`, `spawn_optimized.rs`, `spawn_original.rs`
(Settings, S13), `Instant::now()` in `generate*.rs`, `utf8.rs` and `sources.rs` (Clock, S14), and the `Box<dyn Backend>`
returned by the factories (startup composition only).
`qwen_forward/moe_weight_cache.rs` gained three `pub(crate) use` lines (`AdaptiveWitness`, `LearnedMainWitness`,
`SharedPermanentWitness`) so the witness gates in `load_moe_gates.rs` can name the types; no code changed there.