From 7699138a6ef4bcbee960d0aa6dd3ea1a8c95d396 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 21:39:26 +0100 Subject: [PATCH] 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. --- architecture-baseline.json | 1 - crates/leleka-runtime/src/backend.rs | 30 + crates/leleka-runtime/src/backend/config.rs | 31 + crates/leleka-runtime/src/backend/load.rs | 1219 +---------------- .../leleka-runtime/src/backend/load_admit.rs | 243 ++++ .../leleka-runtime/src/backend/load_bind.rs | 136 ++ .../leleka-runtime/src/backend/load_cuda.rs | 127 ++ .../src/backend/load_identity.rs | 132 ++ crates/leleka-runtime/src/backend/load_moe.rs | 103 ++ .../src/backend/load_moe_gates.rs | 139 ++ .../src/backend/load_sources.rs | 303 ++++ .../leleka-runtime/src/backend/load_tests.rs | 171 +++ .../src/backend/load_weights.rs | 199 +++ crates/leleka-runtime/src/backend/owner.rs | 142 +- .../leleka-runtime/src/backend/serve_close.rs | 83 ++ .../src/backend/serve_generate.rs | 227 +++ .../leleka-runtime/src/backend/serve_loop.rs | 126 ++ .../src/backend/serve_report.rs | 166 +++ .../leleka-runtime/src/backend/serve_run.rs | 115 ++ .../src/qwen_forward/moe_weight_cache.rs | 2 + docs/architecture/tech-debt.md | 35 + 21 files changed, 2531 insertions(+), 1199 deletions(-) create mode 100644 crates/leleka-runtime/src/backend/load_admit.rs create mode 100644 crates/leleka-runtime/src/backend/load_bind.rs create mode 100644 crates/leleka-runtime/src/backend/load_cuda.rs create mode 100644 crates/leleka-runtime/src/backend/load_identity.rs create mode 100644 crates/leleka-runtime/src/backend/load_moe.rs create mode 100644 crates/leleka-runtime/src/backend/load_moe_gates.rs create mode 100644 crates/leleka-runtime/src/backend/load_sources.rs create mode 100644 crates/leleka-runtime/src/backend/load_tests.rs create mode 100644 crates/leleka-runtime/src/backend/load_weights.rs create mode 100644 crates/leleka-runtime/src/backend/serve_close.rs create mode 100644 crates/leleka-runtime/src/backend/serve_generate.rs create mode 100644 crates/leleka-runtime/src/backend/serve_loop.rs create mode 100644 crates/leleka-runtime/src/backend/serve_report.rs create mode 100644 crates/leleka-runtime/src/backend/serve_run.rs create mode 100644 docs/architecture/tech-debt.md diff --git a/architecture-baseline.json b/architecture-baseline.json index 1fab2e11..106ee4da 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -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, diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 0712044a..9c0ce81b 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -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 { diff --git a/crates/leleka-runtime/src/backend/config.rs b/crates/leleka-runtime/src/backend/config.rs index 90bf5244..b0a99963 100644 --- a/crates/leleka-runtime/src/backend/config.rs +++ b/crates/leleka-runtime/src/backend/config.rs @@ -75,6 +75,37 @@ pub(super) struct OptimizedBackendConfig { pub(super) ranked_profile: Option, 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, diff --git a/crates/leleka-runtime/src/backend/load.rs b/crates/leleka-runtime/src/backend/load.rs index 162c3370..c75e0bf3 100644 --- a/crates/leleka-runtime/src/backend/load.rs +++ b/crates/leleka-runtime/src/backend/load.rs @@ -1,1170 +1,83 @@ //! The owner-side Load: bind the sources, open CUDA, build the caches, then serve generations until Unload. +//! The phases live in `load_*.rs`; this file fixes the order they run in. use super::*; +use leleka_cuda_driver::Context; + +/// Everything one Load needs from its owner thread. +#[derive(Clone, Copy)] +pub(super) struct LoadEnv<'a> { + pub(super) config: &'a NativeBackendConfig, + pub(super) rx: &'a Receiver, + pub(super) shared: &'a Shared, + pub(super) reply: &'a Reply, + pub(super) instance: u64, + pub(super) serial: u64, + pub(super) observer: Option<&'a EvaluationObserver>, + pub(super) execution: EvaluationExecution, + pub(super) optimized: Option<&'a OptimizedBackendConfig>, + pub(super) original: Option<&'a original_serve::OriginalServeOptions>, +} pub(super) fn serve_load( - config: &NativeBackendConfig, - rx: &Receiver, - shared: &Shared, + env: &LoadEnv<'_>, model: ModelDescriptor, requested: RuntimeConfig, - reply: &Reply, - identity_and_observer: ( - u64, - u64, - Option<&EvaluationObserver>, - EvaluationExecution, - Option<&OptimizedBackendConfig>, - Option<&original_serve::OriginalServeOptions>, - ), ) -> Result<(), BackendError> { - let (instance, serial, observer, execution, optimized, original) = identity_and_observer; - let identity = (instance, serial); crate::load_clock::begin(); - validate_load(&model, &requested).map_err(|e| load_failure(LoadPhase::Config, e))?; - // 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. - 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"), - )); + let experimental_plan = admit_load(env, &model, &requested)?; + let governed = start_governor(env)?; + let (bound, identity) = bind_model(env, &requested, model)?; + let driver = open_driver()?; + let context = open_checked_context(env, &driver, governed, &bound.binding)?; + if let Some(options) = env.original { + return launch_original(env, options, &requested, identity, bound, context); } - // 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. - let experimental_plan = 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 - let gguf_ple_load = 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(); - if original.is_some() - && (observer.is_some() - || optimized.is_some() - || config.kar_expert_source.is_some() - || experimental_plan.is_some() - || !(gguf_ple_load - || matches!(&requested.inference_mode, - InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE))) - { - // booleans only (no model or request data): which of the gate's conditions refused the load - { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load detail: observer={} optimized={} kar_expert={} experimental={} gguf_env={} kar_source={} mode={}", - observer.is_some(), - optimized.is_some(), - config.kar_expert_source.is_some(), - experimental_plan.is_some(), - std::env::var("LELEKA_ORIGINAL_SERVE_GGUF_PLE").is_ok_and(|v| v == "1"), - config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(), - match &requested.inference_mode { - InferenceMode::ExperimentalMtp { profile_id } => profile_id.as_str(), - _ => "other", - } - ); - } - return 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", - ), - )); + probe_experimental_plan(env, &context, experimental_plan.as_ref())?; + match serve_native(env, &requested, identity, &bound, &context)? { + Some(closed) => close_context(env.shared, context, closed), + None => Ok(()), } - if matches!( - execution, - EvaluationExecution::ExperimentalResidentMmq - | EvaluationExecution::ExperimentalNativeResidentMmq - | EvaluationExecution::ExperimentalNativeIntegerIq3Mmq - ) && (!matches!(&requested.inference_mode, - InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE) - || observer.is_none()) - { - return Err(load_failure( - LoadPhase::Selection, - invalid("resident MMQ evaluation requires explicit KAR PLE MTP Load"), - )); - } - if execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - && !gguf_ple_load - && !matches!(&requested.inference_mode, - InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE) - { - return Err(load_failure( - LoadPhase::Selection, - invalid("IQ3 windowed256 retained GR experiment requires explicit KAR PLE MTP Load"), - )); - } - if execution == EvaluationExecution::ExperimentalWindowed256RetainedGr - && (!matches!(&requested.inference_mode, - InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE) - || observer.is_none()) - { - return Err(load_failure( - LoadPhase::Selection, - invalid("windowed256 retained GR evaluation requires explicit KAR PLE MTP Load"), - )); - } - validate_kar_selection( - &requested, - config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(), - ) - .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))?; - 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"), - )); - } - // 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" - ))] - let memory_governor = match original { - Some(options) => { - let g = crate::memory_governor::startup(&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: config - .kar_ple_inherited - .as_ref() - .map(InheritedKarArchive::file_backed), - kar_sparse_bytes: config - .kar_ple_inherited - .as_ref() - .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, - }) - .map_err(|e| load_failure(LoadPhase::Config, e))?; - if let Some(archive) = config.kar_ple_inherited.as_ref() { - crate::memory_governor::guard_archive(g, archive) - .map_err(|e| load_failure(LoadPhase::Config, e))?; - } - Some(g) - } - None => None, - }; - let streamed_spill = optimized.is_some_and(|options| { - matches!( - options.policy, - OptimizedOwnerPolicy::StreamedSpill - | OptimizedOwnerPolicy::RetainedScratch - | OptimizedOwnerPolicy::ResidentOwners - | OptimizedOwnerPolicy::AdaptiveSlots - ) - }); - let retained_scratch = optimized.is_some_and(|options| { - matches!( - options.policy, - OptimizedOwnerPolicy::RetainedScratch - | OptimizedOwnerPolicy::ResidentOwners - | OptimizedOwnerPolicy::AdaptiveSlots - ) - }); - let adaptive_slots = - optimized.is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots); - let resident_owners = optimized.is_some_and(|options| { - matches!( - options.policy, - OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots - ) - }); - // 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. - let parallel_sources = !resident_owners && !streamed_spill; - let archive_wanted = matches!(&requested.inference_mode, InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE); - let mut prefetched = if parallel_sources { - Some(verify_sources_parallel(config, archive_wanted)) - } else { - None - }; - let (shard0, expert_capture) = (if let Some(sources) = prefetched.as_mut() { - std::mem::replace(&mut sources.shard0, Err(String::new())) - .map(|shard| (shard, None)) - .map_err(|_| ()) - } else if resident_owners { - Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental( - &config.shard0, - SHARD0, - config - .kar_ple_inherited - .as_ref() - .map(InheritedKarArchive::expert_capture_observation), - ) - .map(|(shard, capture)| (shard, Some(capture))) - .map_err(|_| ()) - } else if streamed_spill { - // 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. - Qwen4ExpArtifact::open_shard0_with_expert_capture( - &config.shard0, - SHARD0, - config - .kar_ple_inherited - .as_ref() - .map(InheritedKarArchive::expert_capture_observation), - ) - .map(|(shard, capture)| (shard, Some(capture))) - .map_err(|_| ()) - } else { - VerifiedGgufFile::open(&config.shard0, SHARD0) - .map(|shard| (shard, None)) - .map_err(|_| ()) - }) - .map_err(|_| { - load_failure( - LoadPhase::Shard0, - invalid("pinned shard 0 verification failed"), - ) - })?; - crate::load_clock::lap("shard0_result"); - let shard1 = (if let Some(sources) = prefetched.as_mut() { - std::mem::replace(&mut sources.shard1, Err(String::new())).map_err(|_| ()) - } else { - VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| ()) - }) - .map_err(|_| { - load_failure( - LoadPhase::Shard1, - invalid("pinned shard 1 verification failed"), - ) - })?; - crate::load_clock::lap("shard1_result"); - let mut prefetched_kar = prefetched.and_then(|sources| sources.kar); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1) - .map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?; - 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")))?; - crate::load_clock::lap("artifact_bind_and_tokenizer"); - // 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. - 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"), - )); - } - let mut binding = match &requested.inference_mode { - InferenceMode::Native => ModelBinding::from_artifact(artifact), - InferenceMode::ExperimentalKarPle { .. } => { - if let Some(source) = config.kar_ple_inherited.as_ref() { - ModelBinding::from_artifact_with_inherited_kar_ple(artifact, source) - } else { - let (source, staging) = config - .kar_ple_source - .as_ref() - .ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; - ModelBinding::from_artifact_with_pinned_kar_ple(artifact, source, staging) - } - } - InferenceMode::ExperimentalMtp { profile_id } => { - let (source, staging) = config - .mtp_source - .as_ref() - .ok_or_else(|| unsupported("MTP operator source is absent"))?; - if profile_id == KAR_MTP_PROFILE { - if let Some(kar) = config.kar_ple_inherited.as_ref() { - match prefetched_kar.take() { - 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, kar, source, staging, - ), - } - } else { - let (kar, kar_staging) = config - .kar_ple_source - .as_ref() - .ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; - ModelBinding::from_artifact_with_pinned_kar_mtp( - artifact, - kar, - kar_staging, - source, - staging, - ) - } - } else { - ModelBinding::from_artifact_with_pinned_mtp(artifact, source, staging) - } - } - _ => return Err(unsupported("experimental mode is not supported")), - } - .map_err(selected_binding_failure)?; - crate::load_clock::lap("binding_kar_and_mtp_total"); - // Routed experts from a pinned KAR archive: verified whole (SHA-256 and - // every payload CRC), mapped completely, and bound before publication. - if let Some(kar_config) = config.kar_expert_source.as_ref() { - if 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(|error| { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={:?} class={error:?}", - LoadPhase::SelectedBinding - ); - invalid("KAR expert source admission failed") - })?; - binding = binding - .with_kar_expert_source(source) - .map_err(selected_binding_failure)?; - } - let (effective_mode, mode_identity_digest) = - selected_bound_mode(&binding, &requested.inference_mode) - .map_err(|e| load_failure(LoadPhase::EffectiveMode, e))?; - let mode_identity_digest = - if execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr { - execution_mode_digest(&mode_identity_digest) - } else { - mode_identity_digest - }; - // The KAR expert identity changes model outputs, so it changes the mode. - let mode_identity_digest = match binding.kar_expert_source() { - Some(source) => kar_expert_mode_digest(&mode_identity_digest, source.identity_digest()), - None => mode_identity_digest, - }; - // An experimental mode changes model outputs, so it changes the mode (all-off leaves the digest alone). - let mode_identity_digest = - experimental_modes::mode_digest(&mode_identity_digest, &config.experimental); - let mode_identity_digest = if original.is_some() { - original_serve_execution_digest(&mode_identity_digest) - } else { - mode_identity_digest - }; - if shared.shutdown.load(Ordering::Acquire) { - return Err(load_failure( - LoadPhase::Cancellation, - unavailable("native load cancelled"), - )); - } - // Only a bounded, pinned metadata file is read here. Complete source SHA - // admission precedes Driver/Context allocation and cannot change on RPCs. - let ranked_profile = optimized - .and_then(|options| options.ranked_profile.as_ref()) - .map(read_ranked_expert_profile) - .transpose() - .map_err(|e| load_failure(LoadPhase::Selection, e))?; - let queued_owners = - optimized.is_some_and(|options| options.policy != OptimizedOwnerPolicy::Original); - let mode_identity_digest = if let Some(options) = optimized { - if queued_owners { - let source = options.ranked_profile.as_ref().ok_or_else(|| { - load_failure( - LoadPhase::Selection, - invalid("queued owners require ranked profile"), - ) - })?; - if adaptive_slots { - adaptive_slots_execution_digest(&mode_identity_digest, &source.sha256) - } else if resident_owners { - resident_owners_execution_digest(&mode_identity_digest, &source.sha256) - } else if retained_scratch { - retained_scratch_execution_digest(&mode_identity_digest, &source.sha256) - } else if streamed_spill { - streamed_spill_execution_digest(&mode_identity_digest, &source.sha256) - } else { - queued_owners_execution_digest(&mode_identity_digest, &source.sha256) - } - } else { - optimized_execution_digest( - &mode_identity_digest, - options - .ranked_profile - .as_ref() - .map(|source| source.sha256.as_str()), - ) - } - } else { - mode_identity_digest - }; - // 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). - if optimized.is_some() || original.is_some() { - let bank_stage = - crate::memory_governor::begin("expert bank (resident copy or mappings)", None); - (if streamed_spill { - binding.adopt_resident_expert_capture(expert_capture.ok_or_else(|| { - load_failure( - LoadPhase::SelectedBinding, - invalid("streamed expert capture absent"), - ) - })?) - } else if original - .is_some_and(|options| options.expert_source == original_serve::ExpertSource::Mapped) - { - binding.load_mapped_expert_source() - } else { - binding.load_resident_expert_source() - }) - .map_err(|error| { - load_failure( - LoadPhase::SelectedBinding, - match error { - InputBindingError::Allocation => exhausted("resident expert RAM unavailable"), - InputBindingError::Read => unavailable("resident expert source read failed"), - _ => invalid("resident expert source admission failed"), - }, - ) - })?; - crate::memory_governor::end(bank_stage, None); - #[cfg(any(target_os = "linux", target_os = "windows"))] - if original - .is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident) - { - crate::memory_governor::drop_file_cache(&[ - config.shard0.as_path(), - config.shard1.as_path(), - ]); - } - crate::load_clock::lap("expert_bank_admission"); - // 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. - if let Some(report) = leleka_model_format::huge_pages::settle() { - eprintln!("{report}"); - crate::load_clock::lap("expert_bank_huge_pages"); - } - if shared.shutdown.load(Ordering::Acquire) { - return Err(load_failure( - LoadPhase::Cancellation, - unavailable("native load cancelled"), - )); - } - } - let driver = Driver::load() - .map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable")))?; - 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"); - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] - if let Some(g) = memory_governor { - crate::memory_governor::check_vram(g, context.as_ref(), config.gpu_budget_bytes) - .map_err(|e| load_failure(LoadPhase::Context, e))?; - } - 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))?; - } - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] - if let Some(options) = original { - let loaded = LoadedModel { - handle: format!( - "native-{}-{}-{}", - std::process::id(), - identity.0, - identity.1 - ), - descriptor: model, - load_config_version: LOAD_CONFIG_VERSION, - effective_mode, - mode_identity_digest, - }; - loaded - .validate_for_load(&loaded.descriptor, &requested) - .map_err(|_| { - load_failure( - LoadPhase::Identity, - unavailable("native load identity failed"), - ) - })?; - return original_serve::run(original_serve::Run { - context_tokens: config.context_tokens, - rx, - shared, - binding, - context, - tokenizer, - eos, - loaded, - reply, - options, - model_files: vec![config.shard0.clone(), config.shard1.clone()], - }); - } - #[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )))] - if original.is_some() { - return Err(load_failure( - LoadPhase::Selection, - unsupported("Original serve CUDA owners require Linux x86_64"), - )); - } - if let Some(plan) = experimental_plan.as_ref() { - // Fail at Load, not at the first token, if an experimental PTX is unpinned or does not load. - probe_experimental(context.as_ref(), &config.experimental, plan) - .map_err(|e| load_failure(LoadPhase::Context, e))?; - } - let output = if queued_owners { - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] - { - OutputStage::load_compact(&binding, context.as_ref()) - } - #[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )))] - { - return Err(unsupported("queued CUDA owners require Linux x86_64")); - } - } else { - OutputStage::load(&binding, context.as_ref()) - } - .map_err(|e| { - load_forward_failure( - LoadPhase::OutputHead, - e, - exhausted("native output head initialization failed"), - ) - })?; - let mut kar_cache = binding - .kar_ple_binding() - .map(|provider| KarPleCache::new(context.as_ref(), provider)) - .transpose() - .map_err(|e| { - load_forward_failure( - LoadPhase::KarCache, - e, - exhausted("KAR PLE cache initialization failed"), - ) - })?; - // 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. - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] - let mut optimized_dense = if optimized.is_some() { - Some( - (if resident_owners { - DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal( - &binding, - context.as_ref(), - ) - } else if retained_scratch { - DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention( - &binding, - context.as_ref(), - ) - } else if queued_owners { - DenseWeightCache::new_qsa_selected_router_gr_batch(&binding, context.as_ref()) - } else { - DenseWeightCache::new_qsa_selected_router(&binding, context.as_ref()) - }) - .map_err(|e| { - load_forward_failure( - LoadPhase::DenseWeightCache, - e, - exhausted("optimized dense initialization failed"), - ) - })?, - ) - } else { - None - }; - #[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )))] - let mut optimized_dense: Option> = None; - let moe_result = if optimized.is_some() { - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] - { - match ranked_profile.as_deref() { - Some(bytes) if adaptive_slots => { - MoeWeightCache::new_native_strata_adaptive_shared_permanent_mapped(&binding, context.as_ref(), bytes) - .and_then(|cache| { - match cache.strata_adaptive_witness(&binding) { - Ok(w) if w.initial_slots > 0 && w.resident_slots == w.initial_slots - && 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 - && w.preload_upload_bytes == w.raw_slot_bytes as u64 => Ok(cache), - Ok(_) => { let _ = cache.close(); Err(crate::qwen_forward::contract::Error::IdentityMismatch) }, - Err(primary) => { let _ = cache.close(); Err(primary) } - } - }) - } - Some(bytes) if resident_owners => { - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru( - &binding, context.as_ref(), bytes, - ).and_then(|cache| { - match cache.learned_main_witness(&binding) { - Ok(w) => { - let check = (|| { - let s = cache.shared_permanent_witness()?; - if w.shared_matrices != 192 || s.descriptors != w.shared_matrices - || s.bytes != w.shared_bytes || 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 - || w.age < u64::try_from(w.routed_matrices + w.shared_matrices).map_err(|_| crate::qwen_forward::contract::Error::Overflow)? - || s.roles != s.preload_roles - || s.request_roles != [Default::default(); 7] || !s.successful_bytes_reconcile { - return Err(crate::qwen_forward::contract::Error::IdentityMismatch); - } - let totals = 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(crate::qwen_forward::contract::Error::Overflow)?; - } - Ok::<_, crate::qwen_forward::contract::Error>(totals) - })?; - if totals[0] != s.inclusive_hits || totals[1] != s.inclusive_misses - || totals[2] != s.inclusive_source_read_bytes - || totals[3] != s.inclusive_upload_bytes - || totals[4] != s.inclusive_eviction_bytes { - return Err(crate::qwen_forward::contract::Error::IdentityMismatch); - } - Ok(()) - })(); - match check { Ok(()) => Ok(cache), Err(primary) => { let _ = cache.close(); Err(primary) } } - }, - Err(primary) => { let _ = cache.close(); Err(primary) } - } - }) - } - Some(bytes) if streamed_spill => { - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor( - &binding, context.as_ref(), bytes, - ) - } - Some(bytes) if queued_owners => { - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input( - &binding, - context.as_ref(), - bytes, - ) - } - Some(bytes) => { - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile( - &binding, - context.as_ref(), - bytes, - ) - } - None => MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru( - &binding, - context.as_ref(), - ), - } - } - #[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )))] - { - let _ = &ranked_profile; - return Err(unsupported( - "optimized CUDA execution requires Linux x86_64", - )); - } - } else { - match execution { - EvaluationExecution::Native - | EvaluationExecution::ExperimentalWindowed256RetainedGr => { - MoeWeightCache::new(&binding, context.as_ref()) - } - EvaluationExecution::ExperimentalResidentMmq => { - MoeWeightCache::new_mmq(&binding, context.as_ref()) - } - EvaluationExecution::ExperimentalNativeResidentMmq => { - MoeWeightCache::new_native_mmq(&binding, context.as_ref()) - } - EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => { - MoeWeightCache::new_native_integer_iq3_mmq(&binding, context.as_ref()) - } - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr => { - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv( - &binding, - context.as_ref(), - ) - } - } - }; - let mut moe_cache = moe_result.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"), - ) - })?; - // This fixed resident MTP charge never participates in the main LRU. - // Fixed MTP and ranked main-cache preload are reported separately. - 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; - let mtp_resident_bytes = initial_cache_upload_bytes - .checked_sub(profile_preload_bytes) - .ok_or_else(|| { - load_failure( - LoadPhase::MoeWeightCache, - invalid("cache preload accounting mismatch"), - ) - })?; - let dense_cache = if let Some(dense) = optimized_dense.take() { - dense - } else { - DenseWeightCache::new(&binding, context.as_ref()).map_err(|e| { - load_forward_failure( - LoadPhase::DenseWeightCache, - e, - exhausted("dense weight cache initialization failed"), - ) - })? - }; - // The optional staging owner is empty after take; end its Context borrow. - drop(optimized_dense); +} + +/// The native serve path: weights, the published handle, the command loop, the weights closed again. +/// `None` when the caller that asked for the Load had already gone away. +fn serve_native<'d>( + env: &LoadEnv<'_>, + requested: &RuntimeConfig, + identity: Identity, + bound: &Bound, + context: &Rc>, +) -> Result, BackendError> { + let ranked = bound.ranked_profile.as_deref(); + let mut weights = load_weights(env, &bound.binding, context.as_ref(), bound.flags, ranked)?; // Exercise only structural session initialization; no synthetic inference // or repeated model/GPU qualification is performed during load. - let initial_session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); + let initial_session = + QwenSession::for_binding_on_shared_device(&bound.binding, Rc::clone(context)); drop(initial_session); - let loaded = LoadedModel { - handle: format!( - "native-{}-{}-{}", - std::process::id(), - identity.0, - identity.1 - ), - descriptor: model, - load_config_version: LOAD_CONFIG_VERSION, - effective_mode, - mode_identity_digest, - }; - loaded - .validate_for_load(&loaded.descriptor, &requested) - .map_err(|_| { - load_failure( - LoadPhase::Identity, - unavailable("native load identity failed"), - ) - })?; - if shared.shutdown.load(Ordering::Acquire) { - return Err(load_failure( - LoadPhase::Cancellation, - unavailable("native load cancelled"), - )); - } - shared.ready.store(true, Ordering::Release); - if reply.send(Ok(loaded.clone())).is_err() { - shared.ready.store(false, Ordering::Release); - return Ok(()); + let loaded = build_loaded(env, identity, requested)?; + check_not_cancelled(env.shared)?; + if !announce_ready(env, &loaded) { + return Ok(None); } let mut unload_reply = None; - // 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. - let mut conversations = ResidentConversations::>::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() - }), - ); - while !shared.shutdown.load(Ordering::Acquire) { - match rx.recv_timeout(Duration::from_millis(100)) { - Err(mpsc::RecvTimeoutError::Timeout) => continue, - Err(_) => break, - Ok(Command::Load(_, _, reply)) => { - conversations.clear(); - let _ = reply.send(Err(exhausted( - "unload the existing model before another load", - ))); - } - Ok(Command::Reconfigure(_, reply)) => { - let _ = reply.send(Err(unsupported( - "this backend cannot be reconfigured at run time", - ))); - } - Ok(Command::Unload(candidate, reply)) => { - conversations.clear(); - if candidate != loaded { - let _ = reply.send(Err(invalid("unknown loaded model handle"))); - } else { - unload_reply = Some(reply); - break; - } - } - Ok(Command::Generate(candidate, request, cancel, reply)) => { - let _guard = ActiveGuard(shared); - if candidate != loaded { - conversations.clear(); - let _ = reply.send(Err(invalid("unknown loaded model handle"))); - continue; - } - if !shared.ready.load(Ordering::Acquire) { - conversations.clear(); - let _ = reply.send(Err(unavailable("native model is not ready"))); - continue; - } - let prompt = match prepare_prompt(&tokenizer, &request, config.context_tokens) { - Ok(prompt) => prompt, - Err(error) => { - conversations.clear(); - let _ = reply.send(Err(error)); - continue; - } - }; - let (sink, stream) = GenerationSink::bounded_channel(QUEUE) - .map_err(|_| unavailable("generation queue unavailable"))?; - if reply.send(Ok(stream)).is_err() { - conversations.clear(); - continue; - } - // 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. - let old = conversations - .take_for(&prompt, |entry| { - if entry.loaded != loaded - || !append_compatible(&entry.continuation.tokens, &prompt) - { - return false; - } - match entry.continuation.decoder.validate_resume( - &binding, - &entry.session, - &entry.continuation.product, - &entry.continuation.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, - } - }) - .map(|resumed| resumed.session); - let (mut session, resume) = match old { - Some(entry) => (entry.session, Some(entry.continuation)), - None => ( - QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)), - None, - ), - }; - let mut pending_prefix = None; - let before_moe = moe_cache.counters(); - let before_dense = dense_cache.counters(); - let measured = observer.map(|_| { - std::cell::RefCell::new(measurement::Recorder::new( - &prompt, - request.max_output_tokens, - )) - }); - let run = Generation { - measurement: measured.as_ref(), - execution, - binding: &binding, - output: &output, - kar_cache: kar_cache.as_mut(), - moe_cache: &mut moe_cache, - dense_cache: &dense_cache, - session: &mut session, - tokenizer: &tokenizer, - sink: &sink, - cancel: &cancel, - shared, - context_tokens: config.context_tokens, - eos, - mtp: matches!(loaded.effective_mode, InferenceMode::ExperimentalMtp { .. }), - }; - let sampler = request_sampler(&request, clock_seed()); - let result = if !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, - request.max_output_tokens, - resume, - &mut pending_prefix, - ) - } else { - match sampler { - Ok(None) => generate(run, &prompt, request.max_output_tokens), - Ok(Some(params)) => { - match crate::qwen_forward::step_sampler::StepSampler::new( - params, &prompt, - ) - .and_then(|plan| output.arm_sampler(plan)) - { - Ok(()) => { - let result = generate(run, &prompt, request.max_output_tokens); - output.disarm_sampler(); - result - } - Err(_) => Err(GenerationFailure::Backend(unavailable( - "sampling setup failed", - ))), - } - } - Err(_) => Err(GenerationFailure::Backend(invalid( - "unsupported generation request", - ))), - } - }; - { - use std::io::Write; - let after_moe = moe_cache.counters(); - let after_dense = dense_cache.counters(); - let outcome = match &result { - Ok(_) => "completed", - Err(GenerationFailure::Cancelled) => "cancelled", - Err(GenerationFailure::Backend(_)) => "failed", - }; - // 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 _ = writeln!( - std::io::stderr().lock(), - "leleka-weight-cache phase=generation outcome={outcome} hits={} misses={} source_bytes={} upload_bytes={} eviction_bytes={} dense_hits={} dense_source_bytes={} dense_upload_bytes={} resident_main_bytes={} resident_dense_bytes={} resident_mtp_bytes={} context_allocated_bytes={}", - after_moe.hits.saturating_sub(before_moe.hits), - after_moe.misses.saturating_sub(before_moe.misses), - after_moe.read_bytes.saturating_sub(before_moe.read_bytes), - after_moe - .upload_bytes - .saturating_sub(before_moe.upload_bytes), - after_moe - .eviction_bytes - .saturating_sub(before_moe.eviction_bytes), - after_dense.hits.saturating_sub(before_dense.hits), - after_dense - .read_bytes - .saturating_sub(before_dense.read_bytes), - after_dense - .upload_bytes - .saturating_sub(before_dense.upload_bytes), - main_resident, - after_dense.upload_bytes, - mtp_resident_bytes, - context.allocated_bytes() - ); - } - // Length truncation is not admitted as a reusable public result. - let completed = matches!(&result, Ok((FinishReason::Stop, _))); - let measured_usage = match &result { - Ok((_, usage)) => Some(( - usage.input_tokens, - usage.output_tokens, - usage.reused_input_tokens, - )), - Err(_) => None, - }; - let measured_completed = result.is_ok(); - let measured_stopped = completed; - let terminal = match result { - 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, - }, - }; - // Terminal publication is bounded too; after transport loss, - // closing without a terminal is reported as MissingTerminal. - let terminal_published = emit_terminal(&sink, terminal).is_ok(); - let pending_prefix = terminal_admit( - pending_prefix, - completed, - terminal_published, - cancel.load(Ordering::Acquire), - shared.shutdown.load(Ordering::Acquire), - sink.is_closed(), - shared.ready.load(Ordering::Acquire), - ); - if let (Some(observer), Some(measured)) = (observer, measured) { - let snapshot = |m: crate::qwen_forward::moe_weight_cache::WeightCacheCounters, d: crate::qwen_forward::dense_weight_cache::DenseCacheCounters| 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, - }; - let record = measured.into_inner().finish( - snapshot(before_moe, before_dense), - snapshot(moe_cache.counters(), dense_cache.counters()), - measured_completed, - measured_stopped, - terminal_published, - measured_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" - ); - } - } - if let Some(continuation) = pending_prefix { - let committed = continuation.tokens.clone(); - conversations.publish( - &committed, - PrefixSession { - loaded: loaded.clone(), - session, - continuation, - }, - ); - } - { - use std::io::Write; - for event in conversations.take_events() { - let _ = writeln!(std::io::stderr().lock(), "leleka-{event}"); - } - } - } - } + let mut conversations = new_conversations(); + 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, + ))) +} + +/// Publish the handle; `false` (and not ready again) when the requester is gone. +fn announce_ready(env: &LoadEnv<'_>, loaded: &LoadedModel) -> bool { + env.shared.ready.store(true, Ordering::Release); + if env.reply.send(Ok(loaded.clone())).is_err() { + env.shared.ready.store(false, Ordering::Release); + return false; } - shared.ready.store(false, Ordering::Release); - conversations.clear(); - drop(conversations); - { - use std::io::Write; - let moe = moe_cache.counters(); - let dense = 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 - ); - } - let moe_closed = moe_cache.close(); - let dense_closed = dense_cache.close(); - drop(kar_cache); - drop(output); - let closed = Rc::try_unwrap(context) - .map_err(|_| unavailable("native context still borrowed"))? - .close() - .map_err(|_| unavailable("native context cleanup failed")); - let closed = closed.and_then(|()| { - if moe_closed.is_err() || dense_closed.is_err() { - Err(unavailable("weight cache cleanup failed")) - } else { - Ok(()) - } - }); - if closed.is_err() { - shared.shutdown.store(true, Ordering::Release); - } - if let Some(reply) = unload_reply { - let _ = reply.send(closed); - } - Ok(()) + true } diff --git a/crates/leleka-runtime/src/backend/load_admit.rs b/crates/leleka-runtime/src/backend/load_admit.rs new file mode 100644 index 00000000..683f9c4e --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_admit.rs @@ -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, 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, 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 { + 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 { + 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, + } +} diff --git a/crates/leleka-runtime/src/backend/load_bind.rs b/crates/leleka-runtime/src/backend/load_bind.rs new file mode 100644 index 00000000..f01872ce --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_bind.rs @@ -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>, + 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), 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, + 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, + 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"); + } +} diff --git a/crates/leleka-runtime/src/backend/load_cuda.rs b/crates/leleka-runtime/src/backend/load_cuda.rs new file mode 100644 index 00000000..b6289582 --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_cuda.rs @@ -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::load() + .map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable"))) +} + +pub(super) fn open_context<'d>( + config: &NativeBackendConfig, + driver: &'d Driver, +) -> Result>, 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>, 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>, +) -> 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>, +) -> Result<(), BackendError> { + Err(load_failure( + LoadPhase::Selection, + unsupported("Original serve CUDA owners require Linux x86_64"), + )) +} diff --git a/crates/leleka-runtime/src/backend/load_identity.rs b/crates/leleka-runtime/src/backend/load_identity.rs new file mode 100644 index 00000000..002a99ee --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_identity.rs @@ -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>, 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 { + 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 { + 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) +} diff --git a/crates/leleka-runtime/src/backend/load_moe.rs b/crates/leleka-runtime/src/backend/load_moe.rs new file mode 100644 index 00000000..b8b2331f --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_moe.rs @@ -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, 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>, +) -> Result, 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, 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, BackendError> { + let _ = &ranked_profile; + Err(unsupported( + "optimized CUDA execution requires Linux x86_64", + )) +} diff --git a/crates/leleka-runtime/src/backend/load_moe_gates.rs b/crates/leleka-runtime/src/backend/load_moe_gates.rs new file mode 100644 index 00000000..fe2292b3 --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_moe_gates.rs @@ -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, 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, + ] +} diff --git a/crates/leleka-runtime/src/backend/load_sources.rs b/crates/leleka-runtime/src/backend/load_sources.rs new file mode 100644 index 00000000..c72a0aaf --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_sources.rs @@ -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, + pub(super) kar: Option, +} + +type Shard0 = Result<(VerifiedGgufFile, Option), ()>; +type Binding = Result; + +// 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 { + 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 { + 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 { + 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, +) -> Result { + 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 { + 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, +) -> Result { + 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, + (source, staging): (&Path, &Path), +) -> Result { + 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, + (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 { + 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") +} diff --git a/crates/leleka-runtime/src/backend/load_tests.rs b/crates/leleka-runtime/src/backend/load_tests.rs new file mode 100644 index 00000000..f7dbc114 --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_tests.rs @@ -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" + ); +} diff --git a/crates/leleka-runtime/src/backend/load_weights.rs b/crates/leleka-runtime/src/backend/load_weights.rs new file mode 100644 index 00000000..7debb413 --- /dev/null +++ b/crates/leleka-runtime/src/backend/load_weights.rs @@ -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 = Result; + +/// 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>, + 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, 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, 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>, 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>, BackendError> { + Err(unsupported("queued CUDA owners require Linux x86_64")) +} + +fn load_kar_cache<'c>( + binding: &ModelBinding, + context: &'c Context<'_>, +) -> Result>, 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>, +) -> Result, 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, 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>, 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>, 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 { + 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"), + ) + }) +} diff --git a/crates/leleka-runtime/src/backend/owner.rs b/crates/leleka-runtime/src/backend/owner.rs index 9ae87345..8c176e56 100644 --- a/crates/leleka-runtime/src/backend/owner.rs +++ b/crates/leleka-runtime/src/backend/owner.rs @@ -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, + shared: &'a Shared, + instance: u64, + observer: Option<&'a EvaluationObserver>, + selection: &'a OwnerExecution, +} +impl<'a> OwnerCtx<'a> { + fn new( + config: &'a NativeBackendConfig, + rx: &'a Receiver, + 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, + ) { + 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(reply: Reply) { + 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, @@ -64,49 +152,13 @@ pub(super) fn owner( observer: Option, 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(); } diff --git a/crates/leleka-runtime/src/backend/serve_close.rs b/crates/leleka-runtime/src/backend/serve_close.rs new file mode 100644 index 00000000..39f119b0 --- /dev/null +++ b/crates/leleka-runtime/src/backend/serve_close.rs @@ -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>, +} + +/// 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>, +) -> 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>, + 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(()) +} diff --git a/crates/leleka-runtime/src/backend/serve_generate.rs b/crates/leleka-runtime/src/backend/serve_generate.rs new file mode 100644 index 00000000..00f8365c --- /dev/null +++ b/crates/leleka-runtime/src/backend/serve_generate.rs @@ -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, + pub(super) reply: Reply, +} + +impl Job { + pub(super) fn new( + candidate: LoadedModel, + request: GenerationRequest, + cancel: Arc, + reply: Reply, + ) -> 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, + 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>, + pub(super) resume: Option, + pub(super) session: QwenSession<'c>, + pub(super) pending_prefix: Option, + pub(super) before: Counters, +} +impl<'c> Exchange<'c> { + pub(super) fn begin( + sv: &Serving<'_, 'c, '_>, + session: QwenSession<'c>, + resume: Option, + 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, 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, 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) { + 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> { + 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 { + 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, + }, + ); +} diff --git a/crates/leleka-runtime/src/backend/serve_loop.rs b/crates/leleka-runtime/src/backend/serve_loop.rs new file mode 100644 index 00000000..5cc61a09 --- /dev/null +++ b/crates/leleka-runtime/src/backend/serve_loop.rs @@ -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>; + +/// 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>, + 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>, + 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::>::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>, +) -> 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>, + command: Command, +) -> Result { + 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) { + conversations.clear(); + let _ = reply.send(Err(exhausted( + "unload the existing model before another load", + ))); +} + +fn refuse_reconfigure(reply: Reply) { + 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>, +) -> Flow { + if candidate != *loaded { + let _ = reply.send(Err(invalid("unknown loaded model handle"))); + return Flow::Continue; + } + *unload_reply = Some(reply); + Flow::Unload +} diff --git a/crates/leleka-runtime/src/backend/serve_report.rs b/crates/leleka-runtime/src/backend/serve_report.rs new file mode 100644 index 00000000..c66e4755 --- /dev/null +++ b/crates/leleka-runtime/src/backend/serve_report.rs @@ -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}"); + } +} diff --git a/crates/leleka-runtime/src/backend/serve_run.rs b/crates/leleka-runtime/src/backend/serve_run.rs new file mode 100644 index 00000000..01779258 --- /dev/null +++ b/crates/leleka-runtime/src/backend/serve_run.rs @@ -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, 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>, + ), +) -> 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, + pending_prefix: &mut Option, +) -> 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", + ))), + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs index d40131e4..311d3db7 100644 --- a/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/moe_weight_cache.rs @@ -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; diff --git a/docs/architecture/tech-debt.md b/docs/architecture/tech-debt.md new file mode 100644 index 00000000..a658880f --- /dev/null +++ b/docs/architecture/tech-debt.md @@ -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` +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.