From 957ffdaa79f7f52d50b9deab3ff2dbad0c6d4cda Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 21:12:56 +0100 Subject: [PATCH] STRA-338 S5a: split backend.rs into responsibility-named child modules backend.rs (3797 lines) becomes a 258-line parent that keeps the imports, the #[path] children (original serve, measurement, prompt, GPU proofs) and the two policy test modules, plus backend/{config, spawn, spawn_optimized, spawn_original, sources, proxy, owner, load, validate, digests, probes, request, session, generate, generate_mtp, utf8, errors, tests}.rs. Every public path stays: the children are re-exported with `use child::*`, so leleka_runtime::backend::* and crate::backend::* resolve as before, and the code that used `super::name` from the #[path] children still finds its names. Items moved verbatim by the lexer-based item parser of scripts/dev/rustsplit; only visibility changed (pub(super) on moved private items, struct fields and inherent methods) and the new files were run through rustfmt. Two lints of the moved code (a needless borrow of `config` in serve_load, a useless `.into()` in the context admission error) were removed; both are value-neutral. Test ids: 689 before, 690 after (the one added is the digest golden test of the previous commit); the same 2 tests fail before and after in this WSL setup (model_binding::qwen4exp_input::mtp::backing, unrelated), 58 ignored both times. cargo check --all-targets -p leleka-runtime -p leleka-deploy: same warning counts (runtime lib 80, lib test 64), none in backend files. Architecture gate: the baseline entry of backend.rs (3770) is replaced by one for the new child backend/load.rs (1170 lines). load.rs holds serve_load unchanged and is decomposed in the S5b commits that follow, which remove the entry again. The 8 remaining gate errors are not from this change (deploy file sizes, backend_original_serve.rs, env-read ratchet 261 vs 256, all introduced by the kar-off-ab integration). --- architecture-baseline.json | 2 +- crates/leleka-runtime/src/backend.rs | 3844 +---------------- crates/leleka-runtime/src/backend/config.rs | 131 + crates/leleka-runtime/src/backend/digests.rs | 290 ++ crates/leleka-runtime/src/backend/errors.rs | 36 + crates/leleka-runtime/src/backend/generate.rs | 332 ++ .../src/backend/generate_mtp.rs | 261 ++ crates/leleka-runtime/src/backend/load.rs | 1170 +++++ crates/leleka-runtime/src/backend/owner.rs | 112 + crates/leleka-runtime/src/backend/probes.rs | 68 + crates/leleka-runtime/src/backend/proxy.rs | 287 ++ crates/leleka-runtime/src/backend/request.rs | 74 + crates/leleka-runtime/src/backend/session.rs | 36 + crates/leleka-runtime/src/backend/sources.rs | 145 + crates/leleka-runtime/src/backend/spawn.rs | 249 ++ .../src/backend/spawn_optimized.rs | 259 ++ .../src/backend/spawn_original.rs | 87 + crates/leleka-runtime/src/backend/tests.rs | 373 ++ crates/leleka-runtime/src/backend/utf8.rs | 74 + crates/leleka-runtime/src/backend/validate.rs | 115 + 20 files changed, 4251 insertions(+), 3694 deletions(-) create mode 100644 crates/leleka-runtime/src/backend/config.rs create mode 100644 crates/leleka-runtime/src/backend/digests.rs create mode 100644 crates/leleka-runtime/src/backend/errors.rs create mode 100644 crates/leleka-runtime/src/backend/generate.rs create mode 100644 crates/leleka-runtime/src/backend/generate_mtp.rs create mode 100644 crates/leleka-runtime/src/backend/load.rs create mode 100644 crates/leleka-runtime/src/backend/owner.rs create mode 100644 crates/leleka-runtime/src/backend/probes.rs create mode 100644 crates/leleka-runtime/src/backend/proxy.rs create mode 100644 crates/leleka-runtime/src/backend/request.rs create mode 100644 crates/leleka-runtime/src/backend/session.rs create mode 100644 crates/leleka-runtime/src/backend/sources.rs create mode 100644 crates/leleka-runtime/src/backend/spawn.rs create mode 100644 crates/leleka-runtime/src/backend/spawn_optimized.rs create mode 100644 crates/leleka-runtime/src/backend/spawn_original.rs create mode 100644 crates/leleka-runtime/src/backend/tests.rs create mode 100644 crates/leleka-runtime/src/backend/utf8.rs create mode 100644 crates/leleka-runtime/src/backend/validate.rs diff --git a/architecture-baseline.json b/architecture-baseline.json index cdc2229c..1fab2e11 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -84,7 +84,7 @@ "crates/igpu/src/lib.rs": 1386, "crates/igpu/src/shaders.rs": 440, "crates/leleka-memory/src/lock.rs": 432, - "crates/leleka-runtime/src/backend.rs": 3770, + "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 1475cf13..0712044a 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -4,13 +4,16 @@ pub(crate) mod original_prompt; #[path = "backend_original_serve.rs"] mod original_serve; -pub use original_serve::{ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions, PrefixTail}; use crate::experimental::{self as experimental_modes, ExperimentalConfig}; use crate::model_binding::kar_expert_source::KarExpertSource; pub use crate::model_binding::kar_expert_source::{ KarArchiveRef, KarExpertLevels, KarExpertSourceConfig, }; pub use crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive; +pub use original_serve::{ + ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions, + PrefixTail, +}; #[path = "backend_measurement.rs"] mod measurement; use crate::{ @@ -51,3712 +54,148 @@ use std::{ thread, time::{Duration, Instant}, }; - -const SHARD0: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; -const SHARD1: &str = "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; -// SHA256(raw32 shard0 digest || raw32 shard1 digest), independently computed. -const MODEL_DIGEST: &str = - "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; -// SHA256 of the newline-terminated profile declaration documented below. -// leleka-native-v1\nmodel=\nqsa=fp16\nmtp=none\ngreedy=ordered-finite-logits\n -const MODE_DIGEST: &str = "sha256:82b774f9c0daaf4290ae96b079224efea7da49dae74770cb32db3da69e4e3eb5"; -const KAR_PROFILE: &str = "qwen-iq3-s-l2-v4-ple"; -const NATIVE_MTP_PROFILE: &str = "qwen4exp-native-mtp-v1"; -const KAR_MTP_PROFILE: &str = "qwen4exp-kar-ple-mtp-v1"; -const INTEGER_WINDOWED_EXECUTION: &str = - "experimental-native-integer-iq3-native-down-windowed256-retained-gr-native-t1"; -const PROMPT_LIMIT: usize = 1024 * 1024; -const FRAME_LIMIT: usize = 64 * 1024; -const OUTPUT_LIMIT: u32 = leleka_backend_api::MAX_OUTPUT_TOKENS; -const QUEUE: usize = 16; -const REPLY_TIMEOUT: Duration = Duration::from_secs(1200); -/// A reconfigure reopens the serve stack (about 25 s on the server; the weights stay loaded). -/// A reconfigure is reopening the serve stack (one engine per process): new generations are refused, retryable, meanwhile. -static RECONFIGURING: AtomicBool = AtomicBool::new(false); -const RECONFIGURE_TIMEOUT: Duration = Duration::from_secs(900); -// Explicit KAR/MTP files require private copies and complete pinned admission -// after the base GGUF hashes. Their cold physical load has a separate finite -// budget; ordinary controls and Native stay unchanged. -const KAR_LOAD_REPLY_TIMEOUT: Duration = Duration::from_secs(7200); -const BACKPRESSURE_TIMEOUT: Duration = Duration::from_secs(30); -const GENERATION_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60); -static INSTANCE: AtomicU64 = AtomicU64::new(1); - -/// Operator-owned files must remain immutable until explicit unload. -pub struct NativeBackendConfig { - pub shard0: PathBuf, - pub shard1: PathBuf, - pub gpu_device_ordinal: u32, - pub gpu_budget_bytes: u64, - pub context_tokens: u32, - /// Local archive and private staging parent; never sourced from RPCs. - pub kar_ple_source: Option<(PathBuf, PathBuf)>, - /// Explicit presealed operator handle; mutually exclusive with kar_ple_source. - pub kar_ple_inherited: Option, - /// Fixed draft pack and its private staging parent, operator supplied only. - pub mtp_source: Option<(PathBuf, PathBuf)>, - /// Optional KAR archive (+overlay) that supplies the routed experts at a - /// runtime level 2..=5 instead of the GGUF/MMQ expert path. Operator - /// supplied and SHA-256 pinned; exclusive with the optimized owners. - pub kar_expert_source: Option, - /// EXPERIMENTAL Strata modes (Q4_0 / K8V4 / rotated KV, keyless V-only, KV streaming, control vectors). - /// `Default` is all-off and changes nothing; an enabled mode is admitted, digest-mixed and probed, and is - /// refused at Load until the forward pass consumes it (`experimental::FORWARD_CONSUMER_WIRED`). - pub experimental: ExperimentalConfig, -} - -/// Operator-owned immutable metadata; no file path or policy enters RPCs. -pub struct RankedExpertProfileSource { - pub path: PathBuf, - pub sha256: String, -} -#[derive(Clone, Copy, PartialEq, Eq)] -enum OptimizedOwnerPolicy { - Original, - QueuedOwners, - StreamedSpill, - RetainedScratch, - ResidentOwners, - AdaptiveSlots, -} -struct OptimizedBackendConfig { - ranked_profile: Option, - policy: OptimizedOwnerPolicy, -} -struct OwnerExecution { - kind: EvaluationExecution, - optimized: Option, - /// The Original verified-window serve path (`backend_original_serve.rs`); exclusive with `optimized`. - original: Option, -} -const OPTIMIZED_EXECUTION: &str = - "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-v1"; -const QUEUED_OWNERS_EXECUTION: &str = - "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-pinned-profile-queued-input-compact-head-gr-batch-v1"; -const ADAPTIVE_SLOTS_EXECUTION: &str = "experimental-iq3-window256-mtp-strata-adapt4-96-shared192-cpu-miss-event-refill-gdn-journal-incremental-prompt-gpu-seed-singleton-original-group16-v6"; -const RESIDENT_OWNERS_EXECUTION: &str = "experimental-iq3-window256-mtp-learned-main-shared192-gdn-device-journal-incremental-capture-original-v2"; -const RETAINED_SCRATCH_EXECUTION: &str = - "experimental-iq3-window256-mtp-streamed-spill-retained-gdn-qk-qsa-attention-v1"; -const STREAMED_SPILL_EXECUTION: &str = - "experimental-iq3-window256-mtp-queued-input-compact-head-gr-batch-digest-capture-spill-floor-1gib-v1"; -const ORIGINAL_SERVE_EXECUTION: &str = - "experimental-original-mode17-verified-window-batched-prefill-mtp-cpu-expert-tier-v1"; -const RANKED_EXPERT_PROFILE_SHA: &str = - "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; -const RANKED_EXPERT_PROFILE_BYTES: usize = 196632; - -/// Provenance only: this descriptor does not attest a successful load. -pub fn pinned_model_descriptor() -> ModelDescriptor { - ModelDescriptor { - family: "qwen4exp".into(), - architecture: "qwen4exp".into(), - artifact_digest: MODEL_DIGEST.into(), - weight_format: "gguf:iq3_s".into(), - } -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum EvaluationExecution { - Native, - ExperimentalResidentMmq, - ExperimentalNativeResidentMmq, - ExperimentalNativeIntegerIq3Mmq, - ExperimentalWindowed256RetainedGr, - ExperimentalNativeIntegerIq3Windowed256RetainedGr, -} -impl EvaluationExecution { - fn prefill_tile_cap(self) -> usize { - match self { - Self::ExperimentalWindowed256RetainedGr - | Self::ExperimentalNativeIntegerIq3Windowed256RetainedGr => 256, - _ => 64, - } - } -} - -pub fn spawn_backend(config: NativeBackendConfig) -> Result, BackendError> { - spawn_backend_inner(config, None, EvaluationExecution::Native) -} -/// Explicit operator-selected experiment. Selection is fixed for this owner -/// lifetime and does not certify quality, speed or long-context completion. -/// The existing typed KAR PLE MTP Load remains mandatory; no observer is needed. -pub fn spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr( - config: NativeBackendConfig, -) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "IQ3 windowed256 retained GR experiment requires KAR PLE and MTP sources", - )); - } - spawn_backend_inner( - config, - None, - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - ) -} -/// Separately selected optimized experiment. Default and earlier experiment -/// factories remain unchanged; this selection certifies neither speed nor quality. -pub fn spawn_backend_experimental_optimized_windowed256( - config: NativeBackendConfig, - ranked_profile: Option, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported( - "optimized CUDA execution requires Linux x86_64", - )); - } - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - || ranked_profile.as_ref().is_some_and(|source| { - source.path.as_os_str().is_empty() || source.sha256 != RANKED_EXPERT_PROFILE_SHA - }) - { - return Err(invalid("invalid optimized KAR PLE MTP profile selection")); - } - spawn_backend_configured( - config, - None, - OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { ranked_profile, policy: OptimizedOwnerPolicy::Original }), - }, - ) -} -/// Separately opt-in pinned-profile owner. This prepares the configured candidate -/// factories for serving; selection does not certify quality or performance. -/// The earlier optimized route and Native defaults remain unchanged. -pub fn spawn_backend_experimental_optimized_windowed256_queued_owners( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("queued CUDA owners require Linux x86_64")); - } - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - || ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid("invalid queued-owner KAR PLE MTP profile selection")); - } - spawn_backend_configured( - config, - None, - OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile: Some(ranked_profile), - policy: OptimizedOwnerPolicy::QueuedOwners, - }), - }, - ) -} -/// Explicit inherited-KAR operator experiment. Original and queued-owner -/// factories preserve their previous meanings. Qualification is separate. -pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); - } - if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() - || config.mtp_source.is_none() || ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); - } - spawn_backend_configured(config, None, OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile: Some(ranked_profile), policy: OptimizedOwnerPolicy::StreamedSpill, - }), - }) -} -/// What the three source verifications returned. Errors are reduced to text because the verifying threads hand -/// them over; the callers map each to the same fixed refusal as before. -struct VerifiedSources { - shard0: Result, - shard1: Result, - /// `None` when no inherited archive is configured. - kar: Option, -} - -type InputResultKar = Result; - -/// Verify shard 0, shard 1 and the inherited KAR archive at the same time. They are independent files; the -/// SHA-256 of each is sequential, so the wall time is the slowest one instead of their sum. Each verification -/// is the very function the sequential load used (full hash, strict index, pinned profile), and the results are -/// consumed in the original order, so every refusal is the same as before. -fn verify_sources_parallel(config: &NativeBackendConfig, want_kar: bool) -> VerifiedSources { - use std::time::Instant; - let begun = Instant::now(); - let result = std::thread::scope(|scope| { - let shard1 = scope.spawn(|| { - let started = Instant::now(); - let result = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|e| e.to_string()); - crate::load_clock::span("shard1_sha256_and_index", started); - result - }); - let kar = config.kar_ple_inherited.as_ref().filter(|_| want_kar).map(|archive| { - scope.spawn(move || { - let started = Instant::now(); - let result = crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive(archive); - crate::load_clock::span("kar_inspect_verify", started); - result - }) - }); - let started = Instant::now(); - let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string()); - crate::load_clock::span("shard0_sha256_and_index", started); - VerifiedSources { - shard0, - shard1: shard1.join().unwrap_or_else(|_| Err("verification thread failed".into())), - kar: kar.map(|handle| handle.join().unwrap_or(Err(InputBindingError::Busy))), - } - }); - crate::load_clock::span("sources_verified_in_parallel_wall", begun); - result -} - -/// `leleka-inference --verify-only`: the load-time verification of the sources (both shards, the KAR archive) -/// and nothing else: no CUDA, no GPU, no model state. Prints the `leleka-load-time` lines and returns. -/// It uses exactly the functions of `serve_load`, so what it measures is what a start spends. -pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> { - crate::load_clock::begin(); - let sources = verify_sources_parallel(&config, true); - sources.shard0.map_err(|_| invalid("pinned shard 0 verification failed"))?; - sources.shard1.map_err(|_| invalid("pinned shard 1 verification failed"))?; - if let Some(kar) = sources.kar { - kar.map_err(|_| invalid("pinned KAR archive verification failed"))?; - } - crate::load_clock::lap("all_sources_verified"); - Ok(()) -} - -/// `leleka-inference --kar-attested-by-stamp`: the parent copied the sealed archive from a file whose verification -/// stamp matched and was unchanged while it was copied; skip hashing the memfd again. Never implied. -pub fn set_archive_attested() { - leleka_model_format::verify_stamp::set_attested_archive(); -} - -/// Operator switch of `leleka-inference --verify-stamps DIR [--verify-rehash]`: a file that matched its pinned -/// digest before and is unchanged (device, inode, size, mtime, ctime) is not hashed again. Set once, before Load. -pub fn set_verify_stamps(directory: PathBuf, rehash: bool) -> bool { - leleka_model_format::verify_stamp::set_global(leleka_model_format::verify_stamp::VerifyStamps::new(directory, rehash)) -} - -/// The path an operator configuration resolves to for `mode` (see `OriginalServeMode`): pure over the -/// configuration and the build's asset probe. `Auto` picks the Original path only when it can start; -/// `Original` returns a precise refusal instead of falling back; `Preview` never starts it. The caller -/// spawns the matching backend (`spawn_backend_original_serve`, or its own preview chain). -pub fn original_serve_choice( - mode: OriginalServeMode, - config: &NativeBackendConfig, -) -> Result { - let facts = original_serve::ConfigFacts { - kar_inherited: config.kar_ple_inherited.is_some(), - kar_staged: config.kar_ple_source.is_some(), - mtp: config.mtp_source.is_some(), - kar_expert: config.kar_expert_source.is_some(), - gguf_ple: std::env::var("LELEKA_ORIGINAL_SERVE_GGUF_PLE").is_ok_and(|v| v == "1"), - experimental: !config.experimental.is_off(), - context_tokens: config.context_tokens, - }; - // The probe is only consulted when the mode could select the Original path. - let unsealed = if mode == OriginalServeMode::Preview { Vec::new() } else { original_serve::current_unsealed() }; - original_serve::choose(mode, &facts, &unsealed) -} -/// The Original-literal mode17 serve backend: the generate.cpp serve loop (`OriginalSpecController` over -/// `OriginalServeEngine` and the native Verifier) with the Original batched prompt read and MTP drafting, -/// instead of the Rust-native preview decoder. `options.mode` is resolved with `original_serve_choice`; -/// a mode that resolves to the preview path is refused here (spawn that backend instead). The expert tier -/// is the all-CPU pool over the pinned model's mapped routed weights; selection certifies neither -/// quality nor speed. -pub fn spawn_backend_original_serve( - config: NativeBackendConfig, - options: OriginalServeOptions, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("Original serve CUDA owners require Linux x86_64")); - } - options.validate()?; - match original_serve_choice(options.mode, &config)? { - OriginalServeChoice::Original => {} - OriginalServeChoice::Preview { reason } => { - return Err(invalid_dynamic(format!( - "the selected backend mode resolves to the preview path ({reason}); spawn the preview backend" - ))); - } - } - spawn_backend_configured( - config, - None, - OwnerExecution { - original: Some(options), - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: None, - }, - ) -} -/// Explicit Original-literal mode17 serve (the earlier factory name, kept for its callers): the pinned -/// ranked profile is still validated as before but is not consumed (the Original expert tier here has no -/// GPU residency to rank). Equivalent to `spawn_backend_original_serve` with `OriginalServeMode::Original`. -pub fn spawn_backend_experimental_original_serve( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, -) -> Result, BackendError> { - if ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid("Original serve requires the pinned ranked profile selection")); - } - spawn_backend_original_serve( - config, - OriginalServeOptions { mode: OriginalServeMode::Original, ..OriginalServeOptions::default() }, - ) -} -/// Additional retained whole-buffer owners; distinct unadopted operator mode. -pub fn spawn_backend_experimental_optimized_windowed256_retained_scratch( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); - } - if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() - || config.mtp_source.is_none() || ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); - } - spawn_backend_configured(config, None, OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile: Some(ranked_profile), policy: OptimizedOwnerPolicy::RetainedScratch, - }), - }) -} -/// Separate experimental owner policy; actual model qualification required. -pub fn spawn_backend_experimental_optimized_windowed256_resident_owners( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); - } - if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() - || config.mtp_source.is_none() || ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); - } - spawn_backend_configured(config, None, OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile: Some(ranked_profile), policy: OptimizedOwnerPolicy::ResidentOwners, - }), - }) -} -/// Authentic adaptive slot policy; experimental until paired quality/time gates. -pub fn spawn_backend_experimental_optimized_windowed256_adaptive_slots( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, -) -> Result, BackendError> { - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); - } - if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() - || config.mtp_source.is_none() || ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); - } - spawn_backend_configured(config, None, OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile: Some(ranked_profile), policy: OptimizedOwnerPolicy::AdaptiveSlots, - }), - }) -} -/// Explicit PUBLIC-FIXTURE attachment to the identical adaptive policy. -/// No token IDs enter the public RPC schema; only the operator observer sees them. -pub fn spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots( - config: NativeBackendConfig, - ranked_profile: RankedExpertProfileSource, - observer: EvaluationObserver, -) -> Result, BackendError> { - if std::env::var("LELEKA_PUBLIC_EVALUATION").as_deref() != Ok("yes") { - return Err(invalid("explicit public evaluation required")); - } - if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { - return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); - } - if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() - || config.mtp_source.is_none() || ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); - } - spawn_backend_configured(config, Some(observer), OwnerExecution { - original: None, - kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile: Some(ranked_profile), policy: OptimizedOwnerPolicy::AdaptiveSlots, - }), - }) -} -/// Explicit public evaluation only. Normal serving has no observer and never -/// exposes token IDs; this does not change the RPC or backend protocol. -pub fn spawn_backend_observed( - config: NativeBackendConfig, - observer: EvaluationObserver, -) -> Result, BackendError> { - spawn_backend_inner(config, Some(observer), EvaluationExecution::Native) -} -/// Private evaluation candidate only: fixed operator selection for subsequent -/// typed model Load. Neither RPCs nor normal spawns can choose this policy. -/// Still experimental; selection is not a quality/performance certificate. -pub fn spawn_backend_observed_resident_mmq( - config: NativeBackendConfig, - observer: EvaluationObserver, -) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "resident MMQ evaluation requires KAR PLE and MTP sources", - )); - } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalResidentMmq, - ) -} -/// Explicit evaluation-only native-certified activation policy. This retains -/// original MMQ tensor kernels and does not certify model quality or speed. -pub fn spawn_backend_observed_native_resident_mmq( - config: NativeBackendConfig, - observer: EvaluationObserver, -) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "native-certified resident MMQ evaluation requires KAR PLE and MTP sources", - )); - } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalNativeResidentMmq, - ) -} -/// Explicit operator evaluation candidate only: IQ3 GU integer MMA with native -/// integer truncation/order. Ineligible GU layers use actual native execution. -/// Down retains existing candidate arithmetic; no quality/performance admission. -/// Normal spawns, RPCs, configuration and production defaults cannot select it. -pub fn spawn_backend_observed_native_integer_iq3_mmq( - config: NativeBackendConfig, - observer: EvaluationObserver, -) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "IQ3 integer MMA evaluation requires KAR PLE and MTP sources", - )); - } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalNativeIntegerIq3Mmq, - ) -} -/// Explicit private evaluation: real outer256 with bounded64 kernels and -/// retained GR transport. Native MoE arithmetic and normal serving are kept. -/// This selection is experimental, not a quality or performance certificate. -pub fn spawn_backend_observed_windowed256_retained_gr( - config: NativeBackendConfig, - observer: EvaluationObserver, -) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "windowed256 retained GR evaluation requires KAR PLE and MTP sources", - )); - } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalWindowed256RetainedGr, - ) -} -/// Explicit private evaluation composition: outer256 retained GR transport, -/// IQ3-only native-order integer GU, and native whole-layer fallback for other GU. -/// Down keeps existing candidate arithmetic. No quality/performance admission; -/// normal spawns, RPCs and production configuration cannot select this policy. -pub fn spawn_backend_observed_native_integer_iq3_windowed256_retained_gr( - config: NativeBackendConfig, - observer: EvaluationObserver, -) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "IQ3 windowed256 retained GR evaluation requires KAR PLE and MTP sources", - )); - } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - ) -} -fn spawn_backend_inner( - config: NativeBackendConfig, - observer: Option, - execution: EvaluationExecution, -) -> Result, BackendError> { - spawn_backend_configured( - config, - observer, - OwnerExecution { - original: None, - kind: execution, - optimized: None, - }, - ) -} -fn spawn_backend_configured( - config: NativeBackendConfig, - observer: Option, - selection: OwnerExecution, -) -> Result, BackendError> { - let execution = selection.kind; - let optimized_execution = selection.optimized.is_some(); - let queued_owners = selection.optimized.as_ref().is_some_and(|options| { - options.policy != OptimizedOwnerPolicy::Original - }); - let streamed_spill = selection.optimized.as_ref().is_some_and(|options| { - matches!(options.policy, OptimizedOwnerPolicy::StreamedSpill | OptimizedOwnerPolicy::RetainedScratch | OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots) - }); - let retained_scratch = selection.optimized.as_ref().is_some_and(|options| { - matches!(options.policy, OptimizedOwnerPolicy::RetainedScratch | OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots) - }); - let adaptive_slots = selection.optimized.as_ref().is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots); - let resident_owners = selection.optimized.as_ref().is_some_and(|options| matches!(options.policy, OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots)); - let original_serve = selection.original.is_some(); - if config.context_tokens == 0 - || u64::from(config.context_tokens) > leleka_context::rope_scaling::MAX_CHARTER_CONTEXT - || config.gpu_budget_bytes == 0 - || usize::try_from(config.gpu_budget_bytes).is_err() - || i32::try_from(config.gpu_device_ordinal).is_err() - || (config.kar_ple_source.is_some() && config.kar_ple_inherited.is_some()) - { - return Err(invalid("invalid native resource configuration")); - } - // The serving context (cells, RoPE scaling) is fixed once per process before any CUDA owner exists. - crate::serving::admit_context_tokens(config.context_tokens, config.gpu_budget_bytes) - .map_err(|e| BackendError { - code: ErrorCode::InvalidRequest, - message: format!("native context not servable: {e}").into(), - retryable: false, - })?; - let (tx, rx) = mpsc::sync_channel(QUEUE); - let shared = Arc::new(Shared { - ready: AtomicBool::new(false), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }); - let kar_configured = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(); - let mtp_configured = config.mtp_source.is_some(); - let kar_experts_configured = config.kar_expert_source.is_some(); - // The Native handle a KAR-expert Load will publish: the base Native digest - // mixed with the source identity (pure function of the operator config). - let kar_expert_native_digest = config.kar_expert_source.as_ref().map(|source| { - kar_expert_mode_digest(MODE_DIGEST, &crate::model_binding::kar_expert_source::config_identity_digest(source)) - }); - let worker_shared = Arc::clone(&shared); - let instance = INSTANCE.fetch_add(1, Ordering::Relaxed); - thread::Builder::new() - .name("leleka-cuda-owner".into()) - .spawn(move || { - let _guard = OwnerGuard(Arc::clone(&worker_shared)); - owner(config, rx, &worker_shared, instance, observer, selection); - }) - .map_err(|_| unavailable("native owner thread unavailable"))?; - Ok(Box::new(Proxy { - tx, - shared, - seen: RecentIds::default(), - kar_configured, - mtp_configured, - kar_experts_configured, - kar_expert_native_digest, - execution, - optimized_execution, - queued_owners, - streamed_spill, - retained_scratch, - resident_owners, - adaptive_slots, - original_serve, - })) -} - -struct Active { - id: String, - cancel: Arc, -} -struct Shared { - ready: AtomicBool, - shutdown: AtomicBool, - active: Mutex>, -} -struct Proxy { - tx: SyncSender, - shared: Arc, - seen: RecentIds, - kar_configured: bool, - mtp_configured: bool, - kar_experts_configured: bool, - kar_expert_native_digest: Option, - execution: EvaluationExecution, - optimized_execution: bool, - queued_owners: bool, - streamed_spill: bool, - retained_scratch: bool, - resident_owners: bool, - adaptive_slots: bool, - original_serve: bool, -} -type Reply = SyncSender>; -enum Command { - Load(ModelDescriptor, RuntimeConfig, Reply), - Generate( - LoadedModel, - GenerationRequest, - Arc, - Reply, - ), - Unload(LoadedModel, Reply<()>), - /// New inference settings as a JSON document (`serve_tuning.rs`); the reply is the effective settings. - Reconfigure(String, Reply), -} -impl Proxy { - fn idle(&self) -> Result<(), BackendError> { - if self.shared.shutdown.load(Ordering::Acquire) { - return Err(unavailable("native owner stopped")); - } - if self - .shared - .active - .lock() - .map_err(|_| unavailable("native owner state unavailable"))? - .is_some() - { - return Err(exhausted("native generation is active")); - } - Ok(()) - } - fn send(&self, command: Command) -> Result<(), BackendError> { - self.tx.try_send(command).map_err(|error| match error { - mpsc::TrySendError::Full(_) => exhausted("native control queue is full"), - mpsc::TrySendError::Disconnected(_) => unavailable("native owner stopped"), - }) - } - fn wait(&self, reply: Receiver>) -> Result { - self.wait_with_timeout(reply, REPLY_TIMEOUT) - } - fn wait_with_timeout( - &self, - reply: Receiver>, - timeout: Duration, - ) -> Result { - match reply.recv_timeout(timeout) { - Ok(result) => result, - Err(_) => { - // A late/uncertain operation is never retried on this owner. - self.shared.shutdown.store(true, Ordering::Release); - cancel_active(&self.shared); - Err(unavailable("native operation outcome unavailable")) - } - } - } -} -impl Backend for Proxy { - fn identity(&self) -> BackendIdentity { - BackendIdentity { - name: "leleka-native".into(), - implementation_version: if self.original_serve { - ORIGINAL_SERVE_EXECUTION.into() - } else if self.adaptive_slots { - ADAPTIVE_SLOTS_EXECUTION.into() - } else if self.resident_owners { - RESIDENT_OWNERS_EXECUTION.into() - } else if self.retained_scratch { - RETAINED_SCRATCH_EXECUTION.into() - } else if self.streamed_spill { - STREAMED_SPILL_EXECUTION.into() - } else if self.queued_owners { - QUEUED_OWNERS_EXECUTION.into() - } else if self.optimized_execution { - OPTIMIZED_EXECUTION.into() - } else if self.execution - == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { - INTEGER_WINDOWED_EXECUTION.into() - } else { - "0.1.0-fp16-qsa-explicit-modes".into() - }, - api_version: BACKEND_API_VERSION, - } - } - fn capabilities(&self) -> BackendCapabilities { - let models = if self.shared.ready.load(Ordering::Acquire) - && !self.shared.shutdown.load(Ordering::Acquire) - { - vec![SupportedModelTuple { - family: "qwen4exp".into(), - architecture: "qwen4exp".into(), - weight_format: "gguf:iq3_s".into(), - }] - } else { - Vec::new() - }; - BackendCapabilities { - supported_models: models, - max_concurrent_generations: 1, - supports_cancellation: true, - supports_tool_call_streaming: false, - } - } - fn prefix_cache_summary(&self) -> Option { - if !self.shared.ready.load(Ordering::Acquire) || self.shared.shutdown.load(Ordering::Acquire) { - return None; - } - original_serve::published_prefix_summary() - } - fn memory_report(&self) -> Option { - if self.shared.shutdown.load(Ordering::Acquire) { - return None; - } - leleka_memory::published_report() - } - fn telemetry_report(&self) -> Option { - if self.shared.shutdown.load(Ordering::Acquire) { - return None; - } - leleka_memory::telemetry::published_telemetry() - } - fn load( - &mut self, - model: ModelDescriptor, - config: RuntimeConfig, - ) -> Result { - validate_load(&model, &config)?; - validate_kar_selection(&config, self.kar_configured)?; - validate_mtp_selection(&config, self.mtp_configured)?; - self.idle()?; - // A KAR expert archive (and overlay) is hashed whole during Load, after - // the base shards, so it gets the same cold-load budget as KAR/MTP files. - let timeout = load_reply_timeout(&config.inference_mode, self.kar_experts_configured); - let (tx, rx) = mpsc::sync_channel(1); - self.send(Command::Load(model, config, tx))?; - self.wait_with_timeout(rx, timeout) - } - fn start_generation( - &mut self, - model: &LoadedModel, - request: GenerationRequest, - ) -> Result { - validate_request(&request)?; - validate_handle(model, self.kar_expert_native_digest.as_deref())?; - if RECONFIGURING.load(Ordering::Acquire) { - return Err(BackendError { - code: ErrorCode::ResourceExhausted, - message: "reconfiguring: retry_after=30: the engine is being reconfigured".into(), - retryable: true, - }); - } - self.idle()?; - if !self.shared.ready.load(Ordering::Acquire) { - return Err(unavailable("native model is not ready")); - } - if self.seen.contains(&request.request_id) { - return Err(invalid("generation request was already accepted")); - } - let cancel = Arc::new(AtomicBool::new(false)); - *self - .shared - .active - .lock() - .map_err(|_| unavailable("native owner state unavailable"))? = Some(Active { - id: request.request_id.clone(), - cancel: Arc::clone(&cancel), - }); - let id = request.request_id.clone(); - let (tx, rx) = mpsc::sync_channel(1); - if let Err(error) = self.send(Command::Generate(model.clone(), request, cancel, tx)) { - clear_active(&self.shared); - return Err(error); - } - let result = self.wait(rx); - if result.is_ok() { - self.seen.insert(&id); - } else { - clear_active(&self.shared); - } - result - } - fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> { - let active = self - .shared - .active - .lock() - .map_err(|_| unavailable("native owner state unavailable"))?; - match active.as_ref() { - Some(active) if active.id == request_id => { - active.cancel.store(true, Ordering::Release); - Ok(()) - } - _ => Err(invalid("generation is not active")), - } - } - fn reconfigure(&mut self, settings_json: &str) -> Result { - if !self.original_serve { - return Err(unsupported("only the Original serve path can be reconfigured at run time")); - } - self.idle()?; - if !self.shared.ready.load(Ordering::Acquire) { - return Err(unavailable("native model is not ready")); - } - if RECONFIGURING.swap(true, Ordering::AcqRel) { - return Err(exhausted("a reconfiguration is already running")); - } - let (tx, rx) = mpsc::sync_channel(1); - let result = self - .send(Command::Reconfigure(settings_json.to_owned(), tx)) - .and_then(|()| self.wait_with_timeout(rx, RECONFIGURE_TIMEOUT)); - RECONFIGURING.store(false, Ordering::Release); - result - } - fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> { - validate_handle(&model, self.kar_expert_native_digest.as_deref())?; - self.idle()?; - let (tx, rx) = mpsc::sync_channel(1); - self.send(Command::Unload(model, tx))?; - self.wait(rx) - } -} -impl Drop for Proxy { - fn drop(&mut self) { - self.shared.shutdown.store(true, Ordering::Release); - cancel_active(&self.shared); - } -} -struct OwnerGuard(Arc); -impl Drop for OwnerGuard { - fn drop(&mut self) { - self.0.ready.store(false, Ordering::Release); - self.0.shutdown.store(true, Ordering::Release); - cancel_active(&self.0); - } -} -struct ActiveGuard<'a>(&'a Shared); -impl Drop for ActiveGuard<'_> { - fn drop(&mut self) { - clear_active(self.0); - } -} -fn cancel_active(shared: &Shared) { - if let Ok(active) = shared.active.lock() - && let Some(active) = active.as_ref() - { - active.cancel.store(true, Ordering::Release); - } -} -fn clear_active(shared: &Shared) { - if let Ok(mut active) = shared.active.lock() { - *active = None; - } -} - -#[derive(Clone, Copy, Debug)] -enum LoadPhase { - Config, - Selection, - Shard0, - Shard1, - Artifact, - Tokenizer, - Eos, - SelectedBinding, - EffectiveMode, - Cancellation, - Driver, - Device, - Context, - OutputHead, - KarCache, - MoeWeightCache, - DenseWeightCache, - OriginalStack, - Identity, -} - -fn load_failure(phase: LoadPhase, error: BackendError) -> BackendError { - use std::io::Write; - // BackendError.message is deliberately excluded from operator diagnostics. - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={phase:?} class={:?}", - error.code - ); - error -} -fn selected_binding_failure(error: InputBindingError) -> BackendError { - use std::io::Write; - let phase = LoadPhase::SelectedBinding; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={phase:?} class={error:?}" - ); - invalid("selected input binding failed") -} -fn load_forward_failure( - phase: LoadPhase, - error: crate::qwen_forward::contract::Error, - result: BackendError, -) -> BackendError { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={phase:?} class={error:?}" - ); - result -} - -fn owner( - config: NativeBackendConfig, - rx: Receiver, - shared: &Shared, - instance: u64, - 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"))); - } - } - } -} - -fn serve_load( - config: &NativeBackendConfig, - rx: &Receiver, - shared: &Shared, - 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"), - )); - } - // 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"), - )); - } - 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); - // 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)); - 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 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}"); - } - } - } - } - } - 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(()) -} - -fn validate_load(model: &ModelDescriptor, config: &RuntimeConfig) -> Result<(), BackendError> { - config - .validate() - .map_err(|_| invalid("invalid load configuration"))?; - if model != &pinned_model_descriptor() { - return Err(unsupported("unsupported pinned model identity")); - } - match &config.inference_mode { - InferenceMode::Native => {} - InferenceMode::ExperimentalKarPle { profile_id } if profile_id == KAR_PROFILE => {} - InferenceMode::ExperimentalMtp { profile_id } - if profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE => {} - _ => return Err(unsupported("experimental mode is not supported")), - } - Ok(()) -} -fn load_reply_timeout(mode: &InferenceMode, kar_experts_configured: bool) -> Duration { - if requires_kar(mode) - || kar_experts_configured - || matches!(mode, InferenceMode::ExperimentalMtp { .. }) - { - KAR_LOAD_REPLY_TIMEOUT - } else { - REPLY_TIMEOUT - } -} -fn validate_kar_selection( - config: &RuntimeConfig, - source_present: bool, -) -> Result<(), BackendError> { - if requires_kar(&config.inference_mode) && !source_present { - return Err(unsupported("KAR PLE operator source is absent")); - } - Ok(()) -} - -fn requires_kar(mode: &InferenceMode) -> bool { - matches!(mode, InferenceMode::ExperimentalKarPle { .. }) - || matches!(mode, InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE) -} -fn validate_mtp_selection(config: &RuntimeConfig, present: bool) -> Result<(), BackendError> { - if matches!(config.inference_mode, InferenceMode::ExperimentalMtp { .. }) && !present { - return Err(unsupported("MTP operator source is absent")); - } - Ok(()) -} -fn selected_bound_mode( - binding: &ModelBinding, - mode: &InferenceMode, -) -> Result<(InferenceMode, String), BackendError> { - let (base, base_digest) = bound_mode(binding); - match mode { - InferenceMode::ExperimentalMtp { profile_id } => { - if requires_kar(mode) != matches!(base, InferenceMode::ExperimentalKarPle { .. }) { - return Err(invalid("MTP input provider mismatch")); - } - let pins = binding - .mtp_pack_identity() - .map_err(|_| invalid("MTP pack identity absent"))?; - Ok(( - mode.clone(), - mtp_mode_digest(&base_digest, profile_id, pins), - )) - } - _ => Ok((base, base_digest)), - } -} -fn read_ranked_expert_profile(source: &RankedExpertProfileSource) -> Result, BackendError> { - use std::io::Read; - if source.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid("unrecognized ranked expert profile")); - } - let file = std::fs::File::open(&source.path) - .map_err(|_| invalid("ranked expert profile unavailable"))?; - if file - .metadata() - .map_err(|_| invalid("ranked expert profile unavailable"))? - .len() - != RANKED_EXPERT_PROFILE_BYTES as u64 - { - return Err(invalid("ranked expert profile extent mismatch")); - } - let mut bytes = Vec::new(); - bytes - .try_reserve_exact(RANKED_EXPERT_PROFILE_BYTES + 1) - .map_err(|_| exhausted("ranked expert profile metadata unavailable"))?; - file.take((RANKED_EXPERT_PROFILE_BYTES + 1) as u64) - .read_to_end(&mut bytes) - .map_err(|_| invalid("ranked expert profile read failed"))?; - let mut actual_digest = String::with_capacity(64); - for value in Sha256::digest(&bytes) { - use std::fmt::Write; - let _ = write!(actual_digest, "{value:02x}"); - } - if bytes.len() != RANKED_EXPERT_PROFILE_BYTES || actual_digest != source.sha256 { - return Err(invalid("ranked expert profile digest mismatch")); - } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { - crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&bytes) - .map_err(|_| invalid("ranked expert profile domain mismatch"))?; - Ok(bytes) - } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - { - Err(unsupported( - "optimized CUDA execution requires Linux x86_64", - )) - } -} -fn optimized_execution_digest(bound_digest: &str, ranked_profile: Option<&str>) -> String { - let mut digest = Sha256::new(); - for field in [ - "leleka-optimized-execution-v2", - "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", - "complete-routed-gpu-finite-guard-v1", - bound_digest, - OPTIMIZED_EXECUTION, - if ranked_profile.is_some() { - "ranked-pinned-prefix-bounded-spill-v1" - } else { - "original-matrix-lru-index-v1" - }, - ranked_profile.unwrap_or("none"), - ] { - digest.update(field.as_bytes()); - digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -// Fixed actor policy and profile identity; no caller-controlled mode field. -fn queued_owners_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { - let mut digest = Sha256::new(); - for field in [ - "leleka-optimized-queued-owners-execution-v1", - "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", - "complete-routed-gpu-finite-guard-v1", - bound_digest, - QUEUED_OWNERS_EXECUTION, - "ranked-pinned-prefix-bounded-spill-v1", - ranked_profile, - "compact-head-finite-greedy-v1", - "gr-batch-inject-t1-t3-v1", - "mtp-admitted-input-prefix-v1", - ] { - digest.update(field.as_bytes()); - digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -fn adaptive_slots_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { - let mut digest = Sha256::new(); - for field in ["leleka-strata-adaptive-slots-v6-original-group16-prompt", &retained_scratch_execution_digest(bound_digest, ranked_profile), - ADAPTIVE_SLOTS_EXECUTION, "adapt4-max96-gain1.5-decay0.7-whole-raw-triplet-event-completed", - "shared192-raw24g-reserve128m-three-allocations-all-host-bank", - "prompt-all-used-nonresident-gpu-ascending-expert-id-single16-real-whole-triplets", - "verification-private-first-occurrence-last-floor-nmiss-times141-div256-single16-owner-real-whole-triplets", - "first-window-real-current-source-seed-reuse-coupled-target-draft-rollback", - "adaptive-final-singleton-joint-chunk-fresh-tail-one-shortens-prior-tile-final-pair", - "ephemeral-host16m-actual-preparation-owned-capacities-and-metadata", - "whole-output-t1-to64-four-roles-256owners37273600-plus-working-reserve128m", - "request-host512m-cpu48m-ephemeral16m-real-dynamic-prefix-and-journal-charge", - "native-cpu-original-3cf03257-upto8-rows-concurrent-owned-jobs", - "model-pool160m-source52g-real8g-headroom-request16jobs48m-outer64-native-qsa-ledger", - "gdn-journal18350596-all36-accepted-prefix-replay-t3-host512m", - "original-moe-prompt-gu1280-group16-down2560-actual-maxr-tile-streamk-bounds-d4-down20-42", - "original-mmq-group-bank-explicit-admitted-model-prompt-capacity1-to8192", - "native-qsa-page4-int8-clock-original-decode-fastmath-norm256-rope-text", - "original-fused-gdn-t1-native-bf16-conv-ab-stepnorm-precise", - "incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication"] { - digest.update(field.as_bytes()); digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { use std::fmt::Write; let _ = write!(result, "{value:02x}"); } - result -} -fn resident_owners_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { - let mut digest = Sha256::new(); - for field in ["leleka-resident-owners-v2-original-prompt", &retained_scratch_execution_digest(bound_digest, ranked_profile), - RESIDENT_OWNERS_EXECUTION, "shared192-main-lru24g-preload-floor1g-reserve128m-metadata16m", - "gdn-journal18350596-all36-accepted-prefix-replay-t3-host512m", - "original-moe-prompt-gu1280-group16-down2560-actual-maxr-tile-streamk-bounds-d4-down20-42", - "original-mmq-group-bank-explicit-admitted-model-prompt-capacity1-to8192", - "native-qsa-page4-int8-clock-original-decode-fastmath-norm256-rope-text", - "original-fused-gdn-t1-native-bf16-conv-ab-stepnorm-precise", - "incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication"] { - digest.update(field.as_bytes()); digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { use std::fmt::Write; let _ = write!(result, "{value:02x}"); } - result -} -fn retained_scratch_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { - let mut digest = Sha256::new(); - for field in ["leleka-retained-gdn-qk-qsa-scratch-v1", &streamed_spill_execution_digest(bound_digest, ranked_profile), - RETAINED_SCRATCH_EXECUTION, "whole-qk40960-tail6144-positive-zero-fullfinite-v1", - "qsa-five-actual-owners108544-three-fullfinite-v1", "eager149504-before-profile-128mib-guard-v1"] { - digest.update(field.as_bytes()); digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { use std::fmt::Write; let _ = write!(result, "{value:02x}"); } - result -} -fn streamed_spill_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { - let mut digest = Sha256::new(); - for field in ["leleka-streamed-spill-queued-owners-execution-v1", bound_digest, - STREAMED_SPILL_EXECUTION, "same-fd-full-sha-opaque-capture-adopt-v1", - "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", - "complete-routed-gpu-finite-guard-v1", "ranked-prefix-spill-floor-1073741824-v1", - ranked_profile, "compact-head-finite-greedy-v1", "gr-batch-inject-t1-t3-v1", - "mtp-admitted-input-prefix-v1"] { - digest.update(field.as_bytes()); digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -fn original_serve_execution_digest(bound_digest: &str) -> String { - let mut digest = Sha256::new(); - for field in [ - "leleka-original-serve-execution-v1", - bound_digest, - ORIGINAL_SERVE_EXECUTION, - "original-generate-cpp-mode17-spec4-suffix3-verify-t6-mtp-t4", - "original-batched-prefill-fused-gr-high-only-bf16-mixed-force-batched", - "native-verifier-window-gdn-journal-qsa-journal-accepted-prefix-commit", - "routed-experts-all-cpu-tier-empty-gpu-plan", - "request-reset-to-empty-prompt-no-conversation-cache", - ] { - digest.update(field.as_bytes()); - digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -fn kar_expert_mode_digest(bound_digest: &str, identity: &[u8; 32]) -> String { - let mut digest = Sha256::new(); - digest.update(b"leleka-kar-expert-mode-v1\n"); - digest.update(bound_digest.as_bytes()); - digest.update(b"\n"); - digest.update(identity); - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -fn experimental_error(error: experimental_modes::ExperimentalError) -> BackendError { - match error { - experimental_modes::ExperimentalError::Invalid(message) => invalid(message), - experimental_modes::ExperimentalError::Unsupported(message) => unsupported(message), - } -} -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -fn probe_experimental( - context: &leleka_cuda_driver::Context<'_>, - config: &ExperimentalConfig, - plan: &experimental_modes::Plan, -) -> Result<(), BackendError> { - use leleka_cuda_driver::experimental::ExperimentalError; - for program in &plan.programs { - leleka_cuda_driver::experimental_gpu::Experimental::open(context, *program, &config.opt_in) - .and_then(|opened| opened.close()) - .map_err(|error| match error { - ExperimentalError::Unpinned(_) => unsupported("experimental PTX is not pinned"), - ExperimentalError::NotEnabled(_) | ExperimentalError::Invalid(_) => { - invalid("experimental program is not enabled for this configuration") - } - ExperimentalError::Driver(_) => unavailable("experimental program failed to load"), - })?; - } - Ok(()) -} -#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] -fn probe_experimental( - _: &leleka_cuda_driver::Context<'_>, - _: &ExperimentalConfig, - _: &experimental_modes::Plan, -) -> Result<(), BackendError> { - Err(unsupported("experimental modes require Linux CUDA")) -} -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -fn probe_kar_level_decode(context: &leleka_cuda_driver::Context<'_>) -> Result<(), BackendError> { - leleka_cuda_driver::kar_decode_levels_gpu::KarDecodeLevels::open(context) - .map(|_| ()) - .map_err(|error| match error { - leleka_cuda_driver::kar_decode_levels::KarDecodeError::Unpinned => { - unsupported("KAR level-decode PTX is not pinned") - } - _ => unavailable("KAR level-decode program failed to load"), - }) -} -#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] -fn probe_kar_level_decode(_: &leleka_cuda_driver::Context<'_>) -> Result<(), BackendError> { - Err(unsupported("KAR expert source requires Linux CUDA")) -} -fn execution_mode_digest(bound_digest: &str) -> String { - let mut digest = Sha256::new(); - for field in [ - "leleka-execution-v1", - bound_digest, - INTEGER_WINDOWED_EXECUTION, - ] { - digest.update(field.as_bytes()); - digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -fn mtp_mode_digest(base: &str, profile: &str, pins: [&str; 3]) -> String { - let mut digest = Sha256::new(); - for field in [ - "leleka-mtp-v1", - base, - profile, - "depth=4", - "attention=fp16-dense", - "experts=s2-greedy", - ] - .into_iter() - .chain(pins) - { - digest.update(field.as_bytes()); - digest.update(b"\n"); - } - let mut result = String::from("sha256:"); - for value in digest.finalize() { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} - -// The mode identity binds actual verified archive/profile bytes and the native -// FP16-QSA/no-MTP implementation, independently of the requested mode label. -fn bound_mode(binding: &ModelBinding) -> (InferenceMode, String) { - match binding.kar_ple_binding() { - None => (InferenceMode::Native, MODE_DIGEST.into()), - Some(provider) => ( - InferenceMode::ExperimentalKarPle { - profile_id: KAR_PROFILE.into(), - }, - kar_mode_digest(provider.archive_digest(), provider.profile_digest()), - ), - } -} -fn kar_mode_digest(archive: &[u8; 32], profile: &[u8; 32]) -> String { - let mut digest = Sha256::new(); - digest.update(b"leleka-kar-ple-v1\n"); - digest.update(MODE_DIGEST.as_bytes()); - digest.update(b"\n"); - digest.update(KAR_PROFILE.as_bytes()); - digest.update(b"\n"); - digest.update(archive); - digest.update(profile); - let bytes = digest.finalize(); - let mut result = String::with_capacity(71); - result.push_str("sha256:"); - for value in bytes { - use std::fmt::Write; - let _ = write!(result, "{value:02x}"); - } - result -} -fn validate_handle( - model: &LoadedModel, - kar_expert_native_digest: Option<&str>, -) -> Result<(), BackendError> { - if model.handle.is_empty() - || model.handle.len() > 128 - || model.handle.chars().any(char::is_control) - || model.descriptor != pinned_model_descriptor() - || model.load_config_version != LOAD_CONFIG_VERSION - || !match &model.effective_mode { - // With a KAR expert source the Native handle carries the source - // identity; it must equal the digest this owner would publish. - InferenceMode::Native => { - model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST) - } - InferenceMode::ExperimentalKarPle { profile_id } => { - profile_id == KAR_PROFILE - && model - .mode_identity_digest - .strip_prefix("sha256:") - .is_some_and(|hex| { - hex.len() == 64 - && hex - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) - }) - } - InferenceMode::ExperimentalMtp { profile_id } => { - (profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE) - && model - .mode_identity_digest - .strip_prefix("sha256:") - .is_some_and(|hex| { - hex.len() == 64 - && hex - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) - }) - } - _ => false, - } - { - return Err(invalid("invalid loaded model identity")); - } - Ok(()) -} - -fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> { - if request.request_id.is_empty() - || request.request_id.len() > 128 - || request.request_id.chars().any(char::is_control) - || request.prompt.len() > PROMPT_LIMIT - || request.max_output_tokens == 0 - || request.max_output_tokens > OUTPUT_LIMIT - || request_sampler(request, 1).is_err() - { - return Err(invalid("unsupported generation request")); - } - Ok(()) -} - -/// Validated sampling plan of a request: `None` keeps the ordinary greedy path -/// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for -/// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`). -/// The CUDA ordinal of the loaded device, for the telemetry sampler (NVML indexes the same physical order). -pub(crate) static GPU_ORDINAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - -fn request_sampler( - request: &GenerationRequest, - entropy: u64, -) -> Result, leleka_sampler_ref::SamplingError> { - let s = &request.sampling; - let raw = leleka_sampler_ref::RequestSampling::from_fixed_point(&leleka_sampler_ref::FixedPoint { - temperature_milli: request.temperature_milli, - top_p_micro: s.top_p_micro, - top_k: s.top_k, - min_p_micro: s.min_p_micro, - repetition_penalty_micro: s.repetition_penalty_micro, - frequency_penalty_micro: s.frequency_penalty_micro, - presence_penalty_micro: s.presence_penalty_micro, - penalty_last_n: s.penalty_last_n, - seed: s.seed, - }); - let params = leleka_sampler_ref::SamplingParams::resolve(&raw)?; - Ok(params.needs_sampler().then(|| params.to_sampler_params(entropy))) -} - -/// The steady-clock tick the Original takes as the seed of a request without one. -fn clock_seed() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(1, |d| d.as_nanos() as u64) - .max(1) -} -fn prepare_prompt( - tokenizer: &Tokenizer, - request: &GenerationRequest, - context: u32, -) -> Result, BackendError> { - validate_request(request)?; - // The prompt may carry marks (`LiteralMarks`) for control-token text that was inside a message: that text is encoded as - // ordinary text, the template's own literals as special tokens. A prompt without marks encodes as before. - let tokens = tokenizer - .encode_marked(&request.prompt) - .map_err(|_| invalid("prompt tokenization failed"))?; - if tokens.is_empty() - || tokens - .len() - .checked_add(request.max_output_tokens as usize) - .is_none_or(|total| total > context as usize) - { - return Err(exhausted("prompt and output exceed configured context")); - } - Ok(tokens) -} - -/// The operator ceiling governs admission, while the opaque Position carries -/// the verified model dimension used by every stage's identity validation. -fn native_position( - constants: &InputConstants, - configured: u32, - value: usize, -) -> Result { - let model_context = constants.context_length(); - if configured == 0 || configured > model_context { - return Err(invalid("native context configuration invalid")); - } - let value = u64::try_from(value).map_err(|_| exhausted("native context exhausted"))?; - if value >= u64::from(configured) { - return Err(exhausted("native configured context exhausted")); - } - let bound = Dimension::new(u64::from(model_context)) - .map_err(|_| invalid("verified native context invalid"))?; - Position::new(value, bound).map_err(|_| exhausted("native model context exhausted")) -} - -/// One actual successful resident numeric prefix. Actor/model lifetime is -/// the lifecycle fence; LoadedModel adds handle/mode/config identity. -struct PrefixSession<'driver> { - loaded: LoadedModel, - session: QwenSession<'driver>, - continuation: MtpContinuation, -} -struct MtpContinuation { - decoder: MtpDecoder, - product: TargetStepProduct, - /// Exactly target-committed IDs, never a speculative or merely emitted ID. - tokens: Vec, -} -fn append_compatible(committed: &[u32], incoming: &[u32]) -> bool { - !committed.is_empty() - && committed.len() as u64 <= crate::qwen_forward::contract::serving_cells() - && incoming.len() as u64 <= crate::qwen_forward::contract::serving_cells() - && incoming.starts_with(committed) -} - -/// Completion is the conjunction of numeric success, bounded terminal queue -/// publication and a still-live serving lifecycle. Failed gates drop ownership. -fn terminal_admit( - candidate: Option, - completed: bool, - published: bool, - cancelled: bool, - shutdown: bool, - closed: bool, - ready: bool, -) -> Option { - candidate.filter(|_| completed && published && !cancelled && !shutdown && !closed && ready) -} - -struct Generation<'a, 'context, 'driver> { - execution: EvaluationExecution, - measurement: Option<&'a std::cell::RefCell>, - binding: &'a ModelBinding, - output: &'a OutputStage<'context, 'driver>, - kar_cache: Option<&'a mut KarPleCache<'context>>, - moe_cache: &'a mut MoeWeightCache<'context>, - dense_cache: &'a DenseWeightCache<'context>, - // The cache and session share the actual actor Context lifetime. Driver - // ownership remains separate in OutputStage; no reference is extended. - session: &'a mut QwenSession<'context>, - tokenizer: &'a Tokenizer, - sink: &'a GenerationSink, - cancel: &'a AtomicBool, - shared: &'a Shared, - context_tokens: u32, - eos: u32, - mtp: bool, -} -enum GenerationFailure { - Cancelled, - Backend(BackendError), -} -impl From for GenerationFailure { - fn from(error: BackendError) -> Self { - Self::Backend(error) - } -} -impl Generation<'_, '_, '_> { - fn observe(&self, f: impl FnOnce(&mut measurement::Recorder)) { - if let Some(recorder) = self.measurement { - f(&mut recorder.borrow_mut()); - } - } - fn cancelled(&self) -> bool { - self.cancel.load(Ordering::Acquire) - || self.shared.shutdown.load(Ordering::Acquire) - || self.sink.is_closed() - } - fn step(&mut self, token: u32, position: usize) -> Result { - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - let vocabulary = - Dimension::new(248_320).map_err(|_| invalid("native vocabulary invalid"))?; - - let token = TokenId::new(u64::from(token), vocabulary) - .map_err(|_| invalid("native token invalid"))?; - let position = native_position( - self.binding.input_constants(), - self.context_tokens, - position, - )?; - let forwarded = QwenForward::step_cached( - self.binding, - token, - position, - self.session, - self.output, - self.kar_cache.as_deref_mut(), - self.moe_cache, - self.dense_cache, - ); - let token = forwarded.map_err(|failure| { - // Fixed enums and numeric position only; no token/prompt/path - // diagnostics. A stderr failure cannot replace the real error. - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-native phase=forward position={} error={failure:?}", - position.get() - ); - // A failed full step never commits its session. Keep the retained - // owners for explicit unload, but withdraw serving readiness. - self.shared.ready.store(false, Ordering::Release); - match failure { - crate::qwen_forward::contract::Error::InputAllocation => { - exhausted("native step allocation failed") - } - crate::qwen_forward::contract::Error::Unsupported(_) => { - unsupported("native forward operator unavailable") - } - crate::qwen_forward::contract::Error::NonFinite => error( - ErrorCode::Internal, - "native forward produced invalid values", - ), - _ => unavailable("native forward failed"), - } - })?; - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - Ok(token.get()) - } - fn mtp_error(&self, failure: crate::qwen_forward::contract::Error) -> GenerationFailure { - use crate::qwen_forward::contract::Error; - #[cfg(test)] - eprintln!("PUBLIC MTP contract failure={failure:?}"); - self.shared.ready.store(false, Ordering::Release); - let error = match failure { - Error::InputAllocation => exhausted("MTP allocation failed"), - Error::Unsupported(_) => unsupported("MTP operator unavailable"), - Error::NonFinite => error(ErrorCode::Internal, "MTP produced invalid values"), - _ => unavailable("MTP forward failed"), - }; - GenerationFailure::Backend(error) - } - fn target_step( - &mut self, - token: u32, - position: usize, - ) -> Result { - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - let token = TokenId::new( - u64::from(token), - Dimension::new(248320).map_err(|e| self.mtp_error(e))?, - ) - .map_err(|e| self.mtp_error(e))?; - let position = native_position( - self.binding.input_constants(), - self.context_tokens, - position, - )?; - let result = QwenForward::step_for_mtp_cached( - self.binding, - token, - position, - self.session, - self.output, - self.kar_cache.as_deref_mut(), - Some(self.moe_cache), - Some(self.dense_cache), - ); - let product = result.map_err(|e| self.mtp_error(e))?; - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - Ok(product) - } - fn prefill_tile_cap(&self) -> usize { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - // The selected native prompt admits its actual simultaneous index, - // INT8 KV and FFN owners under the unchanged request host ceiling. - if self.moe_cache.uses_strata_adaptive_experts() { return 64; } - self.execution.prefill_tile_cap() - } - fn prefill_chunk( - &mut self, - tokens: &[u32], - position: usize, - known_next: Option, - draft: &mut MtpDecoder, - started: Instant, - ) -> Result, GenerationFailure> { - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - if started.elapsed() > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - if tokens.is_empty() || tokens.len() > self.prefill_tile_cap() { - return Err(invalid("invalid prefill tile").into()); - } - let vocabulary = Dimension::new(248320).map_err(|e| self.mtp_error(e))?; - let mut typed = Vec::new(); - typed - .try_reserve_exact(tokens.len()) - .map_err(|_| exhausted("prefill tile allocation failed"))?; - for (offset, &token) in tokens.iter().enumerate() { - let actual = position - .checked_add(offset) - .ok_or_else(|| exhausted("MTP context exhausted"))?; - let _ = native_position(self.binding.input_constants(), self.context_tokens, actual)?; - typed.push(TokenId::new(u64::from(token), vocabulary).map_err(|e| self.mtp_error(e))?); - } - let next = known_next - .map(|token| TokenId::new(u64::from(token), vocabulary)) - .transpose() - .map_err(|e| self.mtp_error(e))?; - let cancel = self.cancel; - let shared = self.shared; - let sink = self.sink; - let stopped = || { - cancel.load(Ordering::Acquire) - || shared.shutdown.load(Ordering::Acquire) - || sink.is_closed() - || started.elapsed() > GENERATION_TIMEOUT - }; - // This is an incremental transaction cap, not an unbounded host pool. - // Verified model and already committed KV/cache owners stay outside it. - let forward = match self.execution { - EvaluationExecution::Native => QwenForward::prefill_chunk_cached_joint, - EvaluationExecution::ExperimentalWindowed256RetainedGr => { - QwenForward::prefill_chunk_windowed256_retained_gr_joint - } - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr => { - QwenForward::prefill_chunk_native_integer_iq3_windowed256_retained_gr_joint - } - EvaluationExecution::ExperimentalResidentMmq - | EvaluationExecution::ExperimentalNativeResidentMmq - | EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => { - QwenForward::prefill_chunk_mmq_joint - } - }; - let host_remaining = draft - .prefill_host_remaining(512 * 1024 * 1024) - .map_err(|e| self.mtp_error(e))?; - let result = forward( - self.binding, - &typed, - next, - self.session, - draft, - self.output, - self.kar_cache.as_deref_mut(), - self.moe_cache, - self.dense_cache, - host_remaining, - stopped, - ); - let product = match result { - Err(crate::qwen_forward::contract::Error::Unsupported( - crate::qwen_forward::contract::Stage::Executor, - )) if stopped() => { - if started.elapsed() > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - return Err(GenerationFailure::Cancelled); - } - other => other.map_err(|e| self.mtp_error(e))?, - }; - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - Ok(product) - } - fn emit(&self, event: GenerationEvent) -> Result<(), GenerationFailure> { - let start = Instant::now(); - loop { - if self.cancelled() { - return Err(GenerationFailure::Cancelled); - } - match self.sink.try_emit(event.clone()) { - Ok(()) => return Ok(()), - Err(ContractError::GenerationBackpressure) - if start.elapsed() < BACKPRESSURE_TIMEOUT => - { - thread::sleep(Duration::from_millis(5)) - } - Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled), - _ => { - return Err( - exhausted("generation output backpressure deadline exceeded").into(), - ); - } - } - } - } -} -fn generate( - mut run: Generation<'_, '_, '_>, - prompt: &[u32], - max: u32, -) -> Result<(FinishReason, Usage), GenerationFailure> { - if run.mtp { - return generate_mtp(run, prompt, max); - } - let start = Instant::now(); - let mut next = 0; - for (position, &token) in prompt.iter().enumerate() { - if start.elapsed() > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - next = run.step(token, position)?; - } - run.observe(|r| r.prefilled()); - let mut utf8 = Utf8Pending::default(); - let mut count = 0; - for index in 0..max { - if start.elapsed() > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - if run.cancelled() { - return Err(GenerationFailure::Cancelled); - } - run.observe(|r| r.token(next)); - if next == run.eos { - utf8.finish()?; - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count + 1, - reused_input_tokens: 0, - }; - run.emit(GenerationEvent::Usage(usage.clone()))?; - run.observe(|r| r.decoded()); - return Ok((FinishReason::Stop, usage)); - } - let bytes = run - .tokenizer - .decode_bytes(&[next]) - .map_err(|_| unavailable("native token decoding failed"))?; - if let Some(text) = utf8.push(&bytes)? { - run.emit(GenerationEvent::TextDelta { text })?; - } - count += 1; - if index + 1 < max { - next = run.step(next, prompt.len() + index as usize)?; - } - } - utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?; - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count, - reused_input_tokens: 0, - }; - run.emit(GenerationEvent::Usage(usage.clone()))?; - run.observe(|r| r.decoded()); - Ok((FinishReason::Length, usage)) -} - -fn generate_mtp( - run: Generation<'_, '_, '_>, - prompt: &[u32], - max: u32, -) -> Result<(FinishReason, Usage), GenerationFailure> { - generate_mtp_resume(run, prompt, max, None, &mut None) -} - -fn generate_mtp_resume( - mut run: Generation<'_, '_, '_>, - prompt: &[u32], - max: u32, - resume: Option, - publish: &mut Option, -) -> Result<(FinishReason, Usage), GenerationFailure> { - *publish = None; - let start = Instant::now(); - let (mut decoder, mut latest, reused, mut committed) = match resume { - Some(old) => { - if !append_compatible(&old.tokens, prompt) { - return Err(invalid("resident MTP prefix mismatch").into()); - } - old.decoder - .validate_resume(run.binding, run.session, &old.product, &old.tokens) - .map_err(|e| run.mtp_error(e))?; - let reused = old.tokens.len(); - (old.decoder, Some(old.product), reused, old.tokens) - } - None => ( - if run.execution - == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { - MtpDecoder::new_kv_prefill(run.binding, run.session, prompt) - } else { - MtpDecoder::new(run.binding) - } - .map_err(|e| run.mtp_error(e))?, - None, - 0, - Vec::new(), - ), - }; - run.observe(|r| r.retained(reused)); - let vocabulary = Dimension::new(248320).map_err(|e| run.mtp_error(e))?; - let eos = TokenId::new(u64::from(run.eos), vocabulary).map_err(|e| run.mtp_error(e))?; - let capacity = prompt - .len() - .checked_add(max as usize) - .filter(|n| *n <= run.context_tokens as usize) - .ok_or_else(|| exhausted("resident MTP prefix exceeds context"))?; - committed - .try_reserve(capacity.saturating_sub(committed.len())) - .map_err(|_| exhausted("resident MTP prefix allocation failed"))?; - // The retained draft ends immediately before the retained last target - // cell. Its known-next edge must be warmed before advancing that target. - if let Some(&next) = prompt.get(reused) - && let Some(product) = latest.as_ref() - { - if run.cancelled() { - return Err(GenerationFailure::Cancelled); - } - let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?; - decoder - .warm_retained(run.binding, run.session, product, next, run.moe_cache) - .map_err(|e| run.mtp_error(e))?; - } - // Each tile preserves the genuine last-known-next edge. A final tile - // obtains its actual head product; no intermediate greedy IDs are minted. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let adaptive_prefill = false; - let mut position = reused; - while position < prompt.len() { - if start.elapsed() > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - let mut end = position - .saturating_add(run.prefill_tile_cap()) - .min(prompt.len()); - // Keep the last known-next edge and final head in one joint tile. - // A completed fresh KV warmer cannot admit a second final tile. - if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 { - end -= 1; - } - let next = prompt.get(end).copied(); - let product = if end - position == 1 && next.is_none() && !adaptive_prefill { - // Other policies keep the original lone-row actual-head producer. - Some(run.target_step(prompt[position], position)?) - } else { - run.prefill_chunk(&prompt[position..end], position, next, &mut decoder, start)? - }; - if next.is_none() { - latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?); - } else if product.is_some() { - return Err(invalid("unexpected intermediate prefill head").into()); - } - committed.extend_from_slice(&prompt[position..end]); - position = end; - } - let mut product = latest.ok_or_else(|| invalid("empty MTP prompt"))?; - if reused == 0 - && run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { - decoder - .finish_kv_prefill(run.binding, run.session, &product, &committed) - .map_err(|e| run.mtp_error(e))?; - } - run.observe(|r| r.prefilled()); - let mut utf8 = Utf8Pending::default(); - let mut count = 0_u64; - let reason = loop { - if start.elapsed() > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - if run.cancelled() { - return Err(GenerationFailure::Cancelled); - } - if count == u64::from(max) { - break FinishReason::Length; - } - let authoritative = product - .predicted(run.session) - .map_err(|e| run.mtp_error(e))?; - if authoritative == eos { - run.observe(|r| r.token(eos.get())); - count += 1; - break FinishReason::Stop; - } - if count + 1 == u64::from(max) { - run.observe(|r| r.token(authoritative.get())); - // The last public token is already authoritative. As in Native, - // no draft or unused next-position target step runs at max output. - let bytes = run - .tokenizer - .decode_bytes(&[authoritative.get()]) - .map_err(|_| unavailable("MTP token decoding failed"))?; - if let Some(text) = utf8.push(&bytes)? { - run.emit(GenerationEvent::TextDelta { text })?; - } - count += 1; - break FinishReason::Length; - } - // Bound the target advances by the operator's context, independently - // of the verified model's larger Position dimension. - let position = prompt - .len() - .checked_add(count as usize) - .ok_or_else(|| exhausted("MTP context exhausted"))?; - let _ = native_position(run.binding.input_constants(), run.context_tokens, position)?; - let remaining = - (max as usize - count as usize - 1).min(run.context_tokens as usize - position); - let spec = MtpWindowSpec::new(4, remaining, Some(eos)).map_err(|e| run.mtp_error(e))?; - let cancel = run.cancel; - let shared = run.shared; - let sink = run.sink; - let window = decoder - .window( - run.binding, - product, - run.session, - run.output, - run.kar_cache.as_deref_mut(), - run.moe_cache, - run.dense_cache, - spec, - || { - cancel.load(Ordering::Acquire) - || shared.shutdown.load(Ordering::Acquire) - || sink.is_closed() - || start.elapsed() > GENERATION_TIMEOUT - }, - ) - .map_err(|e| match e { - MtpWindowError::Cancelled if start.elapsed() > GENERATION_TIMEOUT => { - GenerationFailure::Backend(unavailable("generation deadline exceeded")) - } - MtpWindowError::Cancelled => GenerationFailure::Cancelled, - MtpWindowError::Forward(error) => run.mtp_error(error), - })?; - { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-mtp phase=verified-window draft_steps={} accepted={}", - window.draft_steps(), - window.tokens().len() - ); - } - let draft_steps = window.draft_steps(); - let (tokens, next, stopped) = window.into_parts(); - run.observe(|r| { - let mut ids = [0; 4]; - if tokens.len() <= ids.len() { - for (slot, token) in ids.iter_mut().zip(&tokens) { - *slot = token.get(); - } - r.window(draft_steps, &ids[..tokens.len()], stopped); - } else { - r.window(draft_steps, &[u32::MAX; 5], stopped); - } - }); - if tokens.is_empty() && !stopped { - return Err(run.mtp_error(crate::qwen_forward::contract::Error::IdentityMismatch)); - } - for token in tokens { - run.observe(|r| r.token(token.get())); - committed.push(token.get()); - let bytes = run - .tokenizer - .decode_bytes(&[token.get()]) - .map_err(|_| unavailable("MTP token decoding failed"))?; - if let Some(text) = utf8.push(&bytes)? { - run.emit(GenerationEvent::TextDelta { text })?; - } - count += 1; - } - product = next; - if count == u64::from(max) { - break FinishReason::Length; - } - if stopped { - run.observe(|r| r.token(eos.get())); - count += 1; // Authoritative EOS, as in the ordinary mode. - break FinishReason::Stop; - } - }; - if matches!(reason, FinishReason::Length) { - utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?; - } else { - utf8.finish()?; - } - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count, - reused_input_tokens: reused as u64, - }; - run.emit(GenerationEvent::Usage(usage.clone()))?; - decoder - .validate_resume(run.binding, run.session, &product, &committed) - .map_err(|e| run.mtp_error(e))?; - if run.cancelled() { - return Err(GenerationFailure::Cancelled); - } - run.observe(|r| r.decoded()); - *publish = Some(MtpContinuation { - decoder, - product, - tokens: committed, - }); - Ok((reason, usage)) -} -#[derive(Default)] -struct Utf8Pending(Vec); -impl Utf8Pending { - fn push(&mut self, bytes: &[u8]) -> Result, BackendError> { - if self - .0 - .len() - .checked_add(bytes.len()) - .is_none_or(|len| len > FRAME_LIMIT) - { - return Err(exhausted("decoded token exceeds output frame limit")); - } - self.0 - .try_reserve(bytes.len()) - .map_err(|_| exhausted("token decoding allocation failed"))?; - self.0.extend_from_slice(bytes); - let valid = match std::str::from_utf8(&self.0) { - Ok(_) => self.0.len(), - Err(error) if error.error_len().is_none() => error.valid_up_to(), - Err(_) => return Err(unavailable("native token contains invalid UTF8")), - }; - if valid == 0 { - return Ok(None); - } - let text = std::str::from_utf8(&self.0[..valid]) - .map_err(|_| unavailable("native UTF8 prefix invalid"))? - .to_owned(); - self.0.drain(..valid); - Ok(Some(text)) - } - /// Length may cut a valid code point between tokens. Match the existing - /// tokenizer/daemon terminal replacement without advancing model state. - fn finish_length( - &mut self, - emit: impl FnOnce(String) -> Result<(), GenerationFailure>, - ) -> Result<(), GenerationFailure> { - if self.0.is_empty() { - return Ok(()); - } - match std::str::from_utf8(&self.0) { - Err(error) if error.error_len().is_none() && error.valid_up_to() == 0 => {} - _ => return Err(unavailable("native token contains invalid UTF8").into()), - } - emit("\u{fffd}".to_owned())?; - self.0.clear(); - Ok(()) - } - fn finish(&self) -> Result<(), BackendError> { - if self.0.is_empty() { - Ok(()) - } else { - Err(unavailable("generation ended with incomplete UTF8")) - } - } -} -fn emit_terminal(sink: &GenerationSink, terminal: GenerationTerminal) -> Result<(), ContractError> { - let start = Instant::now(); - loop { - match sink.try_emit(GenerationEvent::Terminal(terminal.clone())) { - Err(ContractError::GenerationBackpressure) - if start.elapsed() < BACKPRESSURE_TIMEOUT => - { - thread::sleep(Duration::from_millis(5)) - } - result => return result, - } - } -} -fn error(code: ErrorCode, message: &'static str) -> BackendError { - BackendError { - code, - message: message.into(), - retryable: false, - } -} -fn invalid(message: &'static str) -> BackendError { - error(ErrorCode::InvalidRequest, message) -} -fn invalid_dynamic(message: String) -> BackendError { - BackendError { code: ErrorCode::InvalidRequest, message, retryable: false } -} -fn unsupported_dynamic(message: String) -> BackendError { - BackendError { code: ErrorCode::UnsupportedModel, message, retryable: false } -} -fn unsupported(message: &'static str) -> BackendError { - error(ErrorCode::UnsupportedModel, message) -} -fn exhausted(message: &'static str) -> BackendError { - error(ErrorCode::ResourceExhausted, message) -} -fn unavailable(message: &'static str) -> BackendError { - error(ErrorCode::BackendUnavailable, message) -} +mod config; +pub use config::*; +mod spawn; +pub use spawn::*; +mod spawn_optimized; +pub use spawn_optimized::*; +mod spawn_original; +pub use spawn_original::*; +mod sources; +pub use sources::*; +mod proxy; +use proxy::*; +mod owner; +use owner::*; +mod load; +use load::*; +mod validate; +use validate::*; +mod digests; +use digests::*; +mod probes; +use probes::*; +mod request; +use request::*; +mod session; +use session::*; +mod generate; +use generate::*; +mod generate_mtp; +use generate_mtp::*; +mod utf8; +use utf8::*; +mod errors; +use errors::*; #[cfg(test)] -mod tests { - use super::*; - #[test] - fn queued_owner_identity_is_distinct_and_binds_profile_and_actual_bound_mode() { - let old_fields = [ - "leleka-optimized-execution-v2", - "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", - "complete-routed-gpu-finite-guard-v1", - "sanitized-bound-mode", - OPTIMIZED_EXECUTION, - "ranked-pinned-prefix-bounded-spill-v1", - RANKED_EXPERT_PROFILE_SHA, - ]; - let mut oracle = Sha256::new(); - for field in old_fields { - oracle.update(field.as_bytes()); - oracle.update(b"\n"); - } - let mut expected_old = String::from("sha256:"); - for byte in oracle.finalize() { - use std::fmt::Write; - let _ = write!(expected_old, "{byte:02x}"); - } - let original = optimized_execution_digest("sanitized-bound-mode", Some(RANKED_EXPERT_PROFILE_SHA)); - assert_eq!(original, expected_old); - let queued = queued_owners_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); - assert_ne!(queued, original); - assert_ne!(queued, optimized_execution_digest("sanitized-bound-mode", None)); - assert_ne!(queued, queued_owners_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA)); - assert_ne!(queued, queued_owners_execution_digest("sanitized-bound-mode", "different-profile")); - assert_ne!(QUEUED_OWNERS_EXECUTION, OPTIMIZED_EXECUTION); - } - - fn native_config() -> RuntimeConfig { - RuntimeConfig { - load_config_version: LOAD_CONFIG_VERSION, - inference_mode: InferenceMode::Native, - gpu_memory_limit_bytes: None, - allow_experimental: false, - } - } - fn request() -> GenerationRequest { - GenerationRequest { - request_id: "synthetic-1".into(), - prompt: "x".into(), - max_output_tokens: 1, - temperature_milli: 0, sampling: Default::default(), - } - } - #[test] - fn explicit_kar_selection_requires_source_and_binds_actual_digests() { - let model = pinned_model_descriptor(); - let mut requested = native_config(); - // Availability/permission alone never selects KAR. - requested.allow_experimental = true; - assert!(validate_load(&model, &requested).is_ok()); - assert!(validate_kar_selection(&requested, false).is_ok()); - requested.inference_mode = InferenceMode::ExperimentalKarPle { - profile_id: KAR_PROFILE.into(), - }; - assert!(validate_load(&model, &requested).is_ok()); - assert_eq!( - validate_kar_selection(&requested, false).unwrap_err().code, - ErrorCode::UnsupportedModel - ); - assert!(validate_kar_selection(&requested, true).is_ok()); - requested.allow_experimental = false; - assert!(validate_load(&model, &requested).is_err()); - requested.allow_experimental = true; - requested.inference_mode = InferenceMode::ExperimentalKarPle { - profile_id: "wrong".into(), - }; - assert!(validate_load(&model, &requested).is_err()); - let digest = kar_mode_digest(&[1; 32], &[2; 32]); - assert_ne!(digest, MODE_DIGEST); - assert_ne!(digest, kar_mode_digest(&[2; 32], &[1; 32])); - assert_ne!(digest, kar_mode_digest(&[1; 32], &[3; 32])); - let mut loaded = LoadedModel { - handle: "synthetic-kar".into(), - descriptor: model, - load_config_version: LOAD_CONFIG_VERSION, - effective_mode: InferenceMode::ExperimentalKarPle { - profile_id: KAR_PROFILE.into(), - }, - mode_identity_digest: digest, - }; - assert!(validate_handle(&loaded, None).is_ok()); - loaded.mode_identity_digest = "sha256:bad".into(); - assert!(validate_handle(&loaded, None).is_err()); - } - - #[test] - fn configured_context_admission_preserves_verified_position_identity() { - let constants = InputConstants::test_fixture(); - let model_bound = Dimension::new(u64::from(constants.context_length())).unwrap(); - let configured_bound = Dimension::new(128).unwrap(); - for value in [0, 127] { - let position = native_position(&constants, 128, value).unwrap(); - assert_eq!(position, Position::new(value as u64, model_bound).unwrap()); - assert_ne!( - position, - Position::new(value as u64, configured_bound).unwrap() - ); - } - assert_eq!( - native_position(&constants, 128, 128).unwrap_err().code, - ErrorCode::ResourceExhausted - ); - assert!(native_position(&constants, 0, 0).is_err()); - assert!(native_position(&constants, constants.context_length() + 1, 0).is_err()); - } - - #[test] - fn fixed_identity_and_native_refusal_precede_artifact_access() { - let model = pinned_model_descriptor(); - assert_eq!(model.artifact_digest, MODEL_DIGEST); - assert!(validate_load(&model, &native_config()).is_ok()); - let mut config = native_config(); - config.allow_experimental = true; - assert!(validate_load(&model, &config).is_ok()); - config.inference_mode = InferenceMode::ExperimentalKarPle { - profile_id: "synthetic".into(), - }; - assert_eq!( - validate_load(&model, &config).unwrap_err().code, - ErrorCode::UnsupportedModel - ); - let mut loaded = LoadedModel { - handle: "synthetic-handle".into(), - descriptor: model.clone(), - load_config_version: LOAD_CONFIG_VERSION, - effective_mode: InferenceMode::Native, - mode_identity_digest: MODE_DIGEST.into(), - }; - assert!(validate_handle(&loaded, None).is_ok()); - // A KAR-expert Native Load publishes the source-bound digest, never the - // plain Native one; each owner accepts only its own. - let kar_native = kar_expert_mode_digest(MODE_DIGEST, &[7; 32]); - assert_ne!(kar_native, MODE_DIGEST); - assert!(validate_handle(&loaded, Some(&kar_native)).is_err()); - loaded.mode_identity_digest = kar_native.clone(); - assert!(validate_handle(&loaded, Some(&kar_native)).is_ok()); - assert!(validate_handle(&loaded, None).is_err()); - assert!( - validate_handle(&loaded, Some(&kar_expert_mode_digest(MODE_DIGEST, &[8; 32]))).is_err() - ); - loaded.mode_identity_digest = MODE_DIGEST.into(); - // The cold KAR archive hash needs the long budget even in Native mode. - assert_eq!(load_reply_timeout(&InferenceMode::Native, false), REPLY_TIMEOUT); - assert_eq!(load_reply_timeout(&InferenceMode::Native, true), KAR_LOAD_REPLY_TIMEOUT); - loaded.handle = "x".repeat(129); - assert!(validate_handle(&loaded, None).is_err()); - let mut wrong = model; - wrong.artifact_digest = SHARD0.into(); - assert!(validate_load(&wrong, &native_config()).is_err()); - } - #[test] - fn request_caps_are_checked_before_acceptance() { - let mut r = request(); - assert!(validate_request(&r).is_ok()); - r.max_output_tokens = OUTPUT_LIMIT + 1; - assert!(validate_request(&r).is_err()); - r.max_output_tokens = 1; - r.temperature_milli = 2001; - assert!(validate_request(&r).is_err()); - r.temperature_milli = 700; - assert!(validate_request(&r).is_ok()); - r.temperature_milli = 0; - r.prompt = "x".repeat(PROMPT_LIMIT + 1); - assert!(validate_request(&r).is_err()); - } - #[test] - fn sampling_requests_are_planned_instead_of_refused() { - let mut r = request(); - // plain greedy: no sampler, the ordinary compact path - assert!(matches!(request_sampler(&r, 5), Ok(None))); - // temperature: a sampler with the request's seed or the supplied entropy - r.temperature_milli = 700; - r.sampling.top_p_micro = Some(950_000); - r.sampling.top_k = Some(40); - let p = request_sampler(&r, 5).unwrap().expect("sampler"); - assert!(!p.greedy && p.seed == 5 && p.top_k == 40 && p.counter == 0); - r.sampling.seed = Some(77); - assert_eq!(request_sampler(&r, 5).unwrap().unwrap().seed, 77); - // greedy plus a penalty still needs the penalised argmax - r.temperature_milli = 0; - r.sampling = Default::default(); - r.sampling.presence_penalty_micro = Some(500_000); - let p = request_sampler(&r, 5).unwrap().expect("penalised greedy"); - assert!(p.greedy && p.penalty_last_n == 64); - // out-of-contract fields are refused before acceptance - for bad in [ - |r: &mut GenerationRequest| r.sampling.top_p_micro = Some(1_000_001), - |r: &mut GenerationRequest| r.sampling.repetition_penalty_micro = Some(0), - |r: &mut GenerationRequest| r.sampling.min_p_micro = Some(2_000_000), - |r: &mut GenerationRequest| r.sampling.frequency_penalty_micro = Some(3_000_000), - ] { - let mut r = request(); - bad(&mut r); - assert!(validate_request(&r).is_err()); - } - } - #[test] - fn utf8_split_tokens_publish_only_complete_prefix() { - let mut pending = Utf8Pending::default(); - assert_eq!(pending.push(&[b'a', 0xf0]).unwrap(), Some("a".into())); - assert!(pending.finish().is_err()); - assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None); - assert_eq!(pending.push(&[0x80]).unwrap(), Some("😀".into())); - assert!(pending.finish().is_ok()); - assert!(pending.push(&[0xff]).is_err()); - } - #[test] - fn utf8_length_replaces_incomplete_unicode_suffix_once() { - for suffix in [&[0xe2][..], &[0xf0, 0x9f, 0x98][..]] { - let mut pending = Utf8Pending::default(); - let mut deltas = vec![pending.push(b"a").unwrap().unwrap()]; - assert_eq!(pending.push(suffix).unwrap(), None); - assert!( - pending - .finish_length(|text| { - deltas.push(text); - Ok(()) - }) - .is_ok() - ); - let mut original = b"a".to_vec(); - original.extend_from_slice(suffix); - assert_eq!(deltas.concat(), String::from_utf8_lossy(&original)); - assert!(pending.finish().is_ok()); - assert!( - pending - .finish_length(|_| panic!("completed suffix emitted twice")) - .is_ok() - ); - } - } - #[test] - fn utf8_length_preserves_completed_split_unicode() { - let mut pending = Utf8Pending::default(); - let first = pending.push(&[b'a', 0xf0]).unwrap().unwrap(); - assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None); - let last = pending.push(&[0x80]).unwrap().unwrap(); - assert!( - pending - .finish_length(|_| panic!("complete Unicode emitted a replacement")) - .is_ok() - ); - assert_eq!(first + &last, "a😀"); - assert!(pending.finish().is_ok()); - } - #[test] - fn utf8_stop_keeps_incomplete_unicode_refusal() { - for suffix in [&[0xe2][..], &[0xf0, 0x9f, 0x98][..]] { - let mut pending = Utf8Pending::default(); - assert_eq!(pending.push(suffix).unwrap(), None); - assert!(pending.finish().is_err()); - assert_eq!(pending.0, suffix); - } - } - #[test] - fn utf8_interior_invalid_remains_refused_at_push() { - let mut pending = Utf8Pending::default(); - assert!(pending.push(&[b'a', 0xff, b'b']).is_err()); - assert!( - pending - .finish_length(|_| panic!("invalid interior bytes emitted a replacement")) - .is_err() - ); - } - #[test] - fn utf8_frame_bound_refuses_before_growth() { - let mut pending = Utf8Pending::default(); - assert!(pending.push(&vec![b'x'; FRAME_LIMIT + 1]).is_err()); - assert!(pending.0.is_empty()); - } - #[test] - fn cancel_is_independent_of_full_control_queue() { - let (tx, _rx) = mpsc::sync_channel(1); - let cancel = Arc::new(AtomicBool::new(false)); - let shared = Arc::new(Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(Some(Active { - id: "synthetic-1".into(), - cancel: Arc::clone(&cancel), - })), - }); - let mut proxy = Proxy { - tx, - shared, - seen: RecentIds::default(), - kar_configured: false, - mtp_configured: false, - kar_experts_configured: false, - kar_expert_native_digest: None, - execution: EvaluationExecution::Native, - optimized_execution: false, - queued_owners: false, - streamed_spill: false, - retained_scratch: false, - resident_owners: false, - adaptive_slots: false, - original_serve: false, - }; - let (reply, _) = mpsc::sync_channel(1); - proxy - .send(Command::Load( - pinned_model_descriptor(), - native_config(), - reply, - )) - .unwrap(); - proxy.cancel("synthetic-1").unwrap(); - assert!(cancel.load(Ordering::Acquire)); - assert!(proxy.cancel("unknown").is_err()); - assert!(proxy.idle().is_err()); - } - #[test] - fn prompt_context_admission_is_before_forward() { - let tokenizer = - Tokenizer::from_vocabulary("gpt2", "qwen35", vec!["x".into()], vec![], None).unwrap(); - assert_eq!(prepare_prompt(&tokenizer, &request(), 2).unwrap(), vec![0]); - assert!(prepare_prompt(&tokenizer, &request(), 1).is_err()); - let mut r = request(); - r.prompt.clear(); - assert!(prepare_prompt(&tokenizer, &r, 2).is_err()); - } - #[test] - fn marked_control_token_text_is_encoded_as_text_and_the_templates_own_literals_stay_special() { - let (alphabet, _) = leleka_tokenizer::byte_alphabet(); - let mut tokens: Vec = alphabet.iter().map(char::to_string).collect(); - tokens.push("".into()); - tokens.push("".into()); - let mut types = vec![1u32; 256]; - types.extend([4, 4]); - let tokenizer = - Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, vec![], Some(types)).unwrap(); - let mut r = request(); - r.max_output_tokens = 1; - // The template's own `` and a quoted `` in the message. - r.prompt = format!("\n{}", tokenizer.marks().mark("a")); - let ids = prepare_prompt(&tokenizer, &r, 100).unwrap(); - assert_eq!(ids.iter().filter(|&&id| id == 256).count(), 1); - assert_eq!(ids.iter().filter(|&&id| id == 257).count(), 0); - assert_eq!(tokenizer.decode(&ids).unwrap(), "\na"); - // A prompt without marks is encoded as before. - r.prompt = "\na".into(); - assert_eq!( - prepare_prompt(&tokenizer, &r, 100).unwrap(), - tokenizer.encode(&r.prompt, true).unwrap() - ); - } -} +mod tests; #[cfg(test)] #[path = "gpu_proofs/backend_measurement_sdet.rs"] mod backend_measurement_sdet; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/combined_prefix_numeric.rs"] mod combined_prefix_numeric; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/combined_prefix_numeric_sdet.rs"] mod combined_prefix_numeric_sdet; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gpu_proofs/singleload_proof.rs"] -mod singleload_proof; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gpu_proofs/backend_original_serve_smoke.rs"] -mod original_serve_smoke; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gpu_proofs/backend_original_serve_prefix_smoke.rs"] -mod original_serve_prefix_smoke; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "backend_original_serve_replay.rs"] -mod original_serve_replay; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gpu_proofs/backend_original_serve_ttft.rs"] -mod original_serve_ttft; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gpu_proofs/backend_original_serve_memory_smoke.rs"] -mod original_serve_memory_smoke; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gpu_proofs/backend_original_serve_laptop.rs"] -mod original_serve_laptop; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/backend_original_serve_arms.rs"] mod original_serve_arms; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "gpu_proofs/backend_original_serve_laptop.rs"] +mod original_serve_laptop; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "gpu_proofs/backend_original_serve_memory_smoke.rs"] +mod original_serve_memory_smoke; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "gpu_proofs/backend_original_serve_prefix_smoke.rs"] +mod original_serve_prefix_smoke; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "backend_original_serve_replay.rs"] +mod original_serve_replay; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "gpu_proofs/backend_original_serve_smoke.rs"] +mod original_serve_smoke; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "gpu_proofs/backend_original_serve_ttft.rs"] +mod original_serve_ttft; +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] +#[path = "gpu_proofs/singleload_proof.rs"] +mod singleload_proof; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/resident_mmq_model_proof.rs"] mod resident_mmq_model_proof; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/native_resident_mmq_model_proof.rs"] mod native_resident_mmq_model_proof; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/layer0_native_mmq_proof.rs"] mod layer0_native_mmq_proof; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[cfg(all( + test, + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" +))] #[path = "gpu_proofs/combined_changed_boundary_proof.rs"] mod combined_changed_boundary_proof; @@ -3777,11 +216,21 @@ mod streamed_spill_policy_tests { #[test] fn streamed_spill_identity_is_distinct_and_binds_actual_mode_and_profile() { let old = queued_owners_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); - let new = streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); + let new = + streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); assert_ne!(old, new); - assert_ne!(new, streamed_spill_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA)); - assert_ne!(new, streamed_spill_execution_digest("sanitized-bound-mode", "different-profile")); - assert_eq!(new, streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA)); + assert_ne!( + new, + streamed_spill_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA) + ); + assert_ne!( + new, + streamed_spill_execution_digest("sanitized-bound-mode", "different-profile") + ); + assert_eq!( + new, + streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA) + ); assert_ne!(STREAMED_SPILL_EXECUTION, QUEUED_OWNERS_EXECUTION); } } @@ -3791,10 +240,19 @@ mod retained_scratch_policy_tests { use super::*; #[test] fn retained_scratch_identity_distinctly_binds_bound_mode_profile_and_eager_owners() { - let new=retained_scratch_execution_digest("sanitized",RANKED_EXPERT_PROFILE_SHA); - assert_ne!(new,streamed_spill_execution_digest("sanitized",RANKED_EXPERT_PROFILE_SHA)); - assert_ne!(new,retained_scratch_execution_digest("other",RANKED_EXPERT_PROFILE_SHA)); - assert_ne!(new,retained_scratch_execution_digest("sanitized","other")); - assert_eq!(new,retained_scratch_execution_digest("sanitized",RANKED_EXPERT_PROFILE_SHA)); + let new = retained_scratch_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA); + assert_ne!( + new, + streamed_spill_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA) + ); + assert_ne!( + new, + retained_scratch_execution_digest("other", RANKED_EXPERT_PROFILE_SHA) + ); + assert_ne!(new, retained_scratch_execution_digest("sanitized", "other")); + assert_eq!( + new, + retained_scratch_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA) + ); } } diff --git a/crates/leleka-runtime/src/backend/config.rs b/crates/leleka-runtime/src/backend/config.rs new file mode 100644 index 00000000..90bf5244 --- /dev/null +++ b/crates/leleka-runtime/src/backend/config.rs @@ -0,0 +1,131 @@ +//! Pinned model identity, resource limits and the operator-facing configuration types of the CUDA owner. +use super::*; + +pub(super) const SHARD0: &str = + "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; +pub(super) const SHARD1: &str = + "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; +// SHA256(raw32 shard0 digest || raw32 shard1 digest), independently computed. +pub(super) const MODEL_DIGEST: &str = + "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; +// SHA256 of the newline-terminated profile declaration documented below. +// leleka-native-v1\nmodel=\nqsa=fp16\nmtp=none\ngreedy=ordered-finite-logits\n +pub(super) const MODE_DIGEST: &str = + "sha256:82b774f9c0daaf4290ae96b079224efea7da49dae74770cb32db3da69e4e3eb5"; +pub(super) const KAR_PROFILE: &str = "qwen-iq3-s-l2-v4-ple"; +pub(super) const NATIVE_MTP_PROFILE: &str = "qwen4exp-native-mtp-v1"; +pub(super) const KAR_MTP_PROFILE: &str = "qwen4exp-kar-ple-mtp-v1"; +pub(super) const INTEGER_WINDOWED_EXECUTION: &str = + "experimental-native-integer-iq3-native-down-windowed256-retained-gr-native-t1"; +pub(super) const PROMPT_LIMIT: usize = 1024 * 1024; +pub(super) const FRAME_LIMIT: usize = 64 * 1024; +pub(super) const OUTPUT_LIMIT: u32 = leleka_backend_api::MAX_OUTPUT_TOKENS; +pub(super) const QUEUE: usize = 16; +pub(super) const REPLY_TIMEOUT: Duration = Duration::from_secs(1200); +/// A reconfigure reopens the serve stack (about 25 s on the server; the weights stay loaded). +/// A reconfigure is reopening the serve stack (one engine per process): new generations are refused, retryable, meanwhile. +pub(super) static RECONFIGURING: AtomicBool = AtomicBool::new(false); +pub(super) const RECONFIGURE_TIMEOUT: Duration = Duration::from_secs(900); +// Explicit KAR/MTP files require private copies and complete pinned admission +// after the base GGUF hashes. Their cold physical load has a separate finite +// budget; ordinary controls and Native stay unchanged. +pub(super) const KAR_LOAD_REPLY_TIMEOUT: Duration = Duration::from_secs(7200); +pub(super) const BACKPRESSURE_TIMEOUT: Duration = Duration::from_secs(30); +pub(super) const GENERATION_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60); +pub(super) static INSTANCE: AtomicU64 = AtomicU64::new(1); + +/// Operator-owned files must remain immutable until explicit unload. +pub struct NativeBackendConfig { + pub shard0: PathBuf, + pub shard1: PathBuf, + pub gpu_device_ordinal: u32, + pub gpu_budget_bytes: u64, + pub context_tokens: u32, + /// Local archive and private staging parent; never sourced from RPCs. + pub kar_ple_source: Option<(PathBuf, PathBuf)>, + /// Explicit presealed operator handle; mutually exclusive with kar_ple_source. + pub kar_ple_inherited: Option, + /// Fixed draft pack and its private staging parent, operator supplied only. + pub mtp_source: Option<(PathBuf, PathBuf)>, + /// Optional KAR archive (+overlay) that supplies the routed experts at a + /// runtime level 2..=5 instead of the GGUF/MMQ expert path. Operator + /// supplied and SHA-256 pinned; exclusive with the optimized owners. + pub kar_expert_source: Option, + /// EXPERIMENTAL Strata modes (Q4_0 / K8V4 / rotated KV, keyless V-only, KV streaming, control vectors). + /// `Default` is all-off and changes nothing; an enabled mode is admitted, digest-mixed and probed, and is + /// refused at Load until the forward pass consumes it (`experimental::FORWARD_CONSUMER_WIRED`). + pub experimental: ExperimentalConfig, +} + +/// Operator-owned immutable metadata; no file path or policy enters RPCs. +pub struct RankedExpertProfileSource { + pub path: PathBuf, + pub sha256: String, +} +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum OptimizedOwnerPolicy { + Original, + QueuedOwners, + StreamedSpill, + RetainedScratch, + ResidentOwners, + AdaptiveSlots, +} +pub(super) struct OptimizedBackendConfig { + pub(super) ranked_profile: Option, + pub(super) policy: OptimizedOwnerPolicy, +} +pub(super) struct OwnerExecution { + pub(super) kind: EvaluationExecution, + pub(super) optimized: Option, + /// The Original verified-window serve path (`backend_original_serve.rs`); exclusive with `optimized`. + pub(super) original: Option, +} +pub(super) const OPTIMIZED_EXECUTION: &str = + "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-v1"; +pub(super) const QUEUED_OWNERS_EXECUTION: &str = "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-pinned-profile-queued-input-compact-head-gr-batch-v1"; +pub(super) const ADAPTIVE_SLOTS_EXECUTION: &str = "experimental-iq3-window256-mtp-strata-adapt4-96-shared192-cpu-miss-event-refill-gdn-journal-incremental-prompt-gpu-seed-singleton-original-group16-v6"; +pub(super) const RESIDENT_OWNERS_EXECUTION: &str = "experimental-iq3-window256-mtp-learned-main-shared192-gdn-device-journal-incremental-capture-original-v2"; +pub(super) const RETAINED_SCRATCH_EXECUTION: &str = + "experimental-iq3-window256-mtp-streamed-spill-retained-gdn-qk-qsa-attention-v1"; +pub(super) const STREAMED_SPILL_EXECUTION: &str = "experimental-iq3-window256-mtp-queued-input-compact-head-gr-batch-digest-capture-spill-floor-1gib-v1"; +pub(super) const ORIGINAL_SERVE_EXECUTION: &str = + "experimental-original-mode17-verified-window-batched-prefill-mtp-cpu-expert-tier-v1"; +pub(super) const RANKED_EXPERT_PROFILE_SHA: &str = + "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; +pub(super) const RANKED_EXPERT_PROFILE_BYTES: usize = 196632; + +/// Provenance only: this descriptor does not attest a successful load. +pub fn pinned_model_descriptor() -> ModelDescriptor { + ModelDescriptor { + family: "qwen4exp".into(), + architecture: "qwen4exp".into(), + artifact_digest: MODEL_DIGEST.into(), + weight_format: "gguf:iq3_s".into(), + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum EvaluationExecution { + Native, + ExperimentalResidentMmq, + ExperimentalNativeResidentMmq, + ExperimentalNativeIntegerIq3Mmq, + ExperimentalWindowed256RetainedGr, + ExperimentalNativeIntegerIq3Windowed256RetainedGr, +} +impl EvaluationExecution { + pub(super) fn prefill_tile_cap(self) -> usize { + match self { + Self::ExperimentalWindowed256RetainedGr + | Self::ExperimentalNativeIntegerIq3Windowed256RetainedGr => 256, + _ => 64, + } + } +} + +/// Validated sampling plan of a request: `None` keeps the ordinary greedy path +/// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for +/// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`). +/// The CUDA ordinal of the loaded device, for the telemetry sampler (NVML indexes the same physical order). +pub(crate) static GPU_ORDINAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); diff --git a/crates/leleka-runtime/src/backend/digests.rs b/crates/leleka-runtime/src/backend/digests.rs new file mode 100644 index 00000000..a20f6c1a --- /dev/null +++ b/crates/leleka-runtime/src/backend/digests.rs @@ -0,0 +1,290 @@ +//! Identity digests of the mode a load publishes (mode, execution policy, KAR expert source). +use super::*; + +pub(super) fn selected_bound_mode( + binding: &ModelBinding, + mode: &InferenceMode, +) -> Result<(InferenceMode, String), BackendError> { + let (base, base_digest) = bound_mode(binding); + match mode { + InferenceMode::ExperimentalMtp { profile_id } => { + if requires_kar(mode) != matches!(base, InferenceMode::ExperimentalKarPle { .. }) { + return Err(invalid("MTP input provider mismatch")); + } + let pins = binding + .mtp_pack_identity() + .map_err(|_| invalid("MTP pack identity absent"))?; + Ok(( + mode.clone(), + mtp_mode_digest(&base_digest, profile_id, pins), + )) + } + _ => Ok((base, base_digest)), + } +} +pub(super) fn optimized_execution_digest( + bound_digest: &str, + ranked_profile: Option<&str>, +) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-optimized-execution-v2", + "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", + "complete-routed-gpu-finite-guard-v1", + bound_digest, + OPTIMIZED_EXECUTION, + if ranked_profile.is_some() { + "ranked-pinned-prefix-bounded-spill-v1" + } else { + "original-matrix-lru-index-v1" + }, + ranked_profile.unwrap_or("none"), + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +// Fixed actor policy and profile identity; no caller-controlled mode field. +pub(super) fn queued_owners_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-optimized-queued-owners-execution-v1", + "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", + "complete-routed-gpu-finite-guard-v1", + bound_digest, + QUEUED_OWNERS_EXECUTION, + "ranked-pinned-prefix-bounded-spill-v1", + ranked_profile, + "compact-head-finite-greedy-v1", + "gr-batch-inject-t1-t3-v1", + "mtp-admitted-input-prefix-v1", + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn adaptive_slots_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-strata-adaptive-slots-v6-original-group16-prompt", + &retained_scratch_execution_digest(bound_digest, ranked_profile), + ADAPTIVE_SLOTS_EXECUTION, + "adapt4-max96-gain1.5-decay0.7-whole-raw-triplet-event-completed", + "shared192-raw24g-reserve128m-three-allocations-all-host-bank", + "prompt-all-used-nonresident-gpu-ascending-expert-id-single16-real-whole-triplets", + "verification-private-first-occurrence-last-floor-nmiss-times141-div256-single16-owner-real-whole-triplets", + "first-window-real-current-source-seed-reuse-coupled-target-draft-rollback", + "adaptive-final-singleton-joint-chunk-fresh-tail-one-shortens-prior-tile-final-pair", + "ephemeral-host16m-actual-preparation-owned-capacities-and-metadata", + "whole-output-t1-to64-four-roles-256owners37273600-plus-working-reserve128m", + "request-host512m-cpu48m-ephemeral16m-real-dynamic-prefix-and-journal-charge", + "native-cpu-original-3cf03257-upto8-rows-concurrent-owned-jobs", + "model-pool160m-source52g-real8g-headroom-request16jobs48m-outer64-native-qsa-ledger", + "gdn-journal18350596-all36-accepted-prefix-replay-t3-host512m", + "original-moe-prompt-gu1280-group16-down2560-actual-maxr-tile-streamk-bounds-d4-down20-42", + "original-mmq-group-bank-explicit-admitted-model-prompt-capacity1-to8192", + "native-qsa-page4-int8-clock-original-decode-fastmath-norm256-rope-text", + "original-fused-gdn-t1-native-bf16-conv-ab-stepnorm-precise", + "incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication", + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn resident_owners_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-resident-owners-v2-original-prompt", + &retained_scratch_execution_digest(bound_digest, ranked_profile), + RESIDENT_OWNERS_EXECUTION, + "shared192-main-lru24g-preload-floor1g-reserve128m-metadata16m", + "gdn-journal18350596-all36-accepted-prefix-replay-t3-host512m", + "original-moe-prompt-gu1280-group16-down2560-actual-maxr-tile-streamk-bounds-d4-down20-42", + "original-mmq-group-bank-explicit-admitted-model-prompt-capacity1-to8192", + "native-qsa-page4-int8-clock-original-decode-fastmath-norm256-rope-text", + "original-fused-gdn-t1-native-bf16-conv-ab-stepnorm-precise", + "incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication", + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn retained_scratch_execution_digest( + bound_digest: &str, + ranked_profile: &str, +) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-retained-gdn-qk-qsa-scratch-v1", + &streamed_spill_execution_digest(bound_digest, ranked_profile), + RETAINED_SCRATCH_EXECUTION, + "whole-qk40960-tail6144-positive-zero-fullfinite-v1", + "qsa-five-actual-owners108544-three-fullfinite-v1", + "eager149504-before-profile-128mib-guard-v1", + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn streamed_spill_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-streamed-spill-queued-owners-execution-v1", + bound_digest, + STREAMED_SPILL_EXECUTION, + "same-fd-full-sha-opaque-capture-adopt-v1", + "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", + "complete-routed-gpu-finite-guard-v1", + "ranked-prefix-spill-floor-1073741824-v1", + ranked_profile, + "compact-head-finite-greedy-v1", + "gr-batch-inject-t1-t3-v1", + "mtp-admitted-input-prefix-v1", + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn original_serve_execution_digest(bound_digest: &str) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-original-serve-execution-v1", + bound_digest, + ORIGINAL_SERVE_EXECUTION, + "original-generate-cpp-mode17-spec4-suffix3-verify-t6-mtp-t4", + "original-batched-prefill-fused-gr-high-only-bf16-mixed-force-batched", + "native-verifier-window-gdn-journal-qsa-journal-accepted-prefix-commit", + "routed-experts-all-cpu-tier-empty-gpu-plan", + "request-reset-to-empty-prompt-no-conversation-cache", + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn kar_expert_mode_digest(bound_digest: &str, identity: &[u8; 32]) -> String { + let mut digest = Sha256::new(); + digest.update(b"leleka-kar-expert-mode-v1\n"); + digest.update(bound_digest.as_bytes()); + digest.update(b"\n"); + digest.update(identity); + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn execution_mode_digest(bound_digest: &str) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-execution-v1", + bound_digest, + INTEGER_WINDOWED_EXECUTION, + ] { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} +pub(super) fn mtp_mode_digest(base: &str, profile: &str, pins: [&str; 3]) -> String { + let mut digest = Sha256::new(); + for field in [ + "leleka-mtp-v1", + base, + profile, + "depth=4", + "attention=fp16-dense", + "experts=s2-greedy", + ] + .into_iter() + .chain(pins) + { + digest.update(field.as_bytes()); + digest.update(b"\n"); + } + let mut result = String::from("sha256:"); + for value in digest.finalize() { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} + +// The mode identity binds actual verified archive/profile bytes and the native +// FP16-QSA/no-MTP implementation, independently of the requested mode label. +pub(super) fn bound_mode(binding: &ModelBinding) -> (InferenceMode, String) { + match binding.kar_ple_binding() { + None => (InferenceMode::Native, MODE_DIGEST.into()), + Some(provider) => ( + InferenceMode::ExperimentalKarPle { + profile_id: KAR_PROFILE.into(), + }, + kar_mode_digest(provider.archive_digest(), provider.profile_digest()), + ), + } +} +pub(super) fn kar_mode_digest(archive: &[u8; 32], profile: &[u8; 32]) -> String { + let mut digest = Sha256::new(); + digest.update(b"leleka-kar-ple-v1\n"); + digest.update(MODE_DIGEST.as_bytes()); + digest.update(b"\n"); + digest.update(KAR_PROFILE.as_bytes()); + digest.update(b"\n"); + digest.update(archive); + digest.update(profile); + let bytes = digest.finalize(); + let mut result = String::with_capacity(71); + result.push_str("sha256:"); + for value in bytes { + use std::fmt::Write; + let _ = write!(result, "{value:02x}"); + } + result +} diff --git a/crates/leleka-runtime/src/backend/errors.rs b/crates/leleka-runtime/src/backend/errors.rs new file mode 100644 index 00000000..b0c4217c --- /dev/null +++ b/crates/leleka-runtime/src/backend/errors.rs @@ -0,0 +1,36 @@ +//! Constructors of the fixed `BackendError` refusals. +use super::*; + +pub(super) fn error(code: ErrorCode, message: &'static str) -> BackendError { + BackendError { + code, + message: message.into(), + retryable: false, + } +} +pub(super) fn invalid(message: &'static str) -> BackendError { + error(ErrorCode::InvalidRequest, message) +} +pub(super) fn invalid_dynamic(message: String) -> BackendError { + BackendError { + code: ErrorCode::InvalidRequest, + message, + retryable: false, + } +} +pub(super) fn unsupported_dynamic(message: String) -> BackendError { + BackendError { + code: ErrorCode::UnsupportedModel, + message, + retryable: false, + } +} +pub(super) fn unsupported(message: &'static str) -> BackendError { + error(ErrorCode::UnsupportedModel, message) +} +pub(super) fn exhausted(message: &'static str) -> BackendError { + error(ErrorCode::ResourceExhausted, message) +} +pub(super) fn unavailable(message: &'static str) -> BackendError { + error(ErrorCode::BackendUnavailable, message) +} diff --git a/crates/leleka-runtime/src/backend/generate.rs b/crates/leleka-runtime/src/backend/generate.rs new file mode 100644 index 00000000..da05d727 --- /dev/null +++ b/crates/leleka-runtime/src/backend/generate.rs @@ -0,0 +1,332 @@ +//! The single-token generation step loop. +use super::*; + +pub(super) struct Generation<'a, 'context, 'driver> { + pub(super) execution: EvaluationExecution, + pub(super) measurement: Option<&'a std::cell::RefCell>, + pub(super) binding: &'a ModelBinding, + pub(super) output: &'a OutputStage<'context, 'driver>, + pub(super) kar_cache: Option<&'a mut KarPleCache<'context>>, + pub(super) moe_cache: &'a mut MoeWeightCache<'context>, + pub(super) dense_cache: &'a DenseWeightCache<'context>, + // The cache and session share the actual actor Context lifetime. Driver + // ownership remains separate in OutputStage; no reference is extended. + pub(super) session: &'a mut QwenSession<'context>, + pub(super) tokenizer: &'a Tokenizer, + pub(super) sink: &'a GenerationSink, + pub(super) cancel: &'a AtomicBool, + pub(super) shared: &'a Shared, + pub(super) context_tokens: u32, + pub(super) eos: u32, + pub(super) mtp: bool, +} +pub(super) enum GenerationFailure { + Cancelled, + Backend(BackendError), +} +impl From for GenerationFailure { + fn from(error: BackendError) -> Self { + Self::Backend(error) + } +} +impl Generation<'_, '_, '_> { + pub(super) fn observe(&self, f: impl FnOnce(&mut measurement::Recorder)) { + if let Some(recorder) = self.measurement { + f(&mut recorder.borrow_mut()); + } + } + pub(super) fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Acquire) + || self.shared.shutdown.load(Ordering::Acquire) + || self.sink.is_closed() + } + pub(super) fn step(&mut self, token: u32, position: usize) -> Result { + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + let vocabulary = + Dimension::new(248_320).map_err(|_| invalid("native vocabulary invalid"))?; + + let token = TokenId::new(u64::from(token), vocabulary) + .map_err(|_| invalid("native token invalid"))?; + let position = native_position( + self.binding.input_constants(), + self.context_tokens, + position, + )?; + let forwarded = QwenForward::step_cached( + self.binding, + token, + position, + self.session, + self.output, + self.kar_cache.as_deref_mut(), + self.moe_cache, + self.dense_cache, + ); + let token = forwarded.map_err(|failure| { + // Fixed enums and numeric position only; no token/prompt/path + // diagnostics. A stderr failure cannot replace the real error. + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-native phase=forward position={} error={failure:?}", + position.get() + ); + // A failed full step never commits its session. Keep the retained + // owners for explicit unload, but withdraw serving readiness. + self.shared.ready.store(false, Ordering::Release); + match failure { + crate::qwen_forward::contract::Error::InputAllocation => { + exhausted("native step allocation failed") + } + crate::qwen_forward::contract::Error::Unsupported(_) => { + unsupported("native forward operator unavailable") + } + crate::qwen_forward::contract::Error::NonFinite => error( + ErrorCode::Internal, + "native forward produced invalid values", + ), + _ => unavailable("native forward failed"), + } + })?; + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + Ok(token.get()) + } + pub(super) fn mtp_error( + &self, + failure: crate::qwen_forward::contract::Error, + ) -> GenerationFailure { + use crate::qwen_forward::contract::Error; + #[cfg(test)] + eprintln!("PUBLIC MTP contract failure={failure:?}"); + self.shared.ready.store(false, Ordering::Release); + let error = match failure { + Error::InputAllocation => exhausted("MTP allocation failed"), + Error::Unsupported(_) => unsupported("MTP operator unavailable"), + Error::NonFinite => error(ErrorCode::Internal, "MTP produced invalid values"), + _ => unavailable("MTP forward failed"), + }; + GenerationFailure::Backend(error) + } + pub(super) fn target_step( + &mut self, + token: u32, + position: usize, + ) -> Result { + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + let token = TokenId::new( + u64::from(token), + Dimension::new(248320).map_err(|e| self.mtp_error(e))?, + ) + .map_err(|e| self.mtp_error(e))?; + let position = native_position( + self.binding.input_constants(), + self.context_tokens, + position, + )?; + let result = QwenForward::step_for_mtp_cached( + self.binding, + token, + position, + self.session, + self.output, + self.kar_cache.as_deref_mut(), + Some(self.moe_cache), + Some(self.dense_cache), + ); + let product = result.map_err(|e| self.mtp_error(e))?; + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + Ok(product) + } + pub(super) fn prefill_tile_cap(&self) -> usize { + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + ))] + // The selected native prompt admits its actual simultaneous index, + // INT8 KV and FFN owners under the unchanged request host ceiling. + if self.moe_cache.uses_strata_adaptive_experts() { + return 64; + } + self.execution.prefill_tile_cap() + } + pub(super) fn prefill_chunk( + &mut self, + tokens: &[u32], + position: usize, + known_next: Option, + draft: &mut MtpDecoder, + started: Instant, + ) -> Result, GenerationFailure> { + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + if started.elapsed() > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + if tokens.is_empty() || tokens.len() > self.prefill_tile_cap() { + return Err(invalid("invalid prefill tile").into()); + } + let vocabulary = Dimension::new(248320).map_err(|e| self.mtp_error(e))?; + let mut typed = Vec::new(); + typed + .try_reserve_exact(tokens.len()) + .map_err(|_| exhausted("prefill tile allocation failed"))?; + for (offset, &token) in tokens.iter().enumerate() { + let actual = position + .checked_add(offset) + .ok_or_else(|| exhausted("MTP context exhausted"))?; + let _ = native_position(self.binding.input_constants(), self.context_tokens, actual)?; + typed.push(TokenId::new(u64::from(token), vocabulary).map_err(|e| self.mtp_error(e))?); + } + let next = known_next + .map(|token| TokenId::new(u64::from(token), vocabulary)) + .transpose() + .map_err(|e| self.mtp_error(e))?; + let cancel = self.cancel; + let shared = self.shared; + let sink = self.sink; + let stopped = || { + cancel.load(Ordering::Acquire) + || shared.shutdown.load(Ordering::Acquire) + || sink.is_closed() + || started.elapsed() > GENERATION_TIMEOUT + }; + // This is an incremental transaction cap, not an unbounded host pool. + // Verified model and already committed KV/cache owners stay outside it. + let forward = match self.execution { + EvaluationExecution::Native => QwenForward::prefill_chunk_cached_joint, + EvaluationExecution::ExperimentalWindowed256RetainedGr => { + QwenForward::prefill_chunk_windowed256_retained_gr_joint + } + EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr => { + QwenForward::prefill_chunk_native_integer_iq3_windowed256_retained_gr_joint + } + EvaluationExecution::ExperimentalResidentMmq + | EvaluationExecution::ExperimentalNativeResidentMmq + | EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => { + QwenForward::prefill_chunk_mmq_joint + } + }; + let host_remaining = draft + .prefill_host_remaining(512 * 1024 * 1024) + .map_err(|e| self.mtp_error(e))?; + let result = forward( + self.binding, + &typed, + next, + self.session, + draft, + self.output, + self.kar_cache.as_deref_mut(), + self.moe_cache, + self.dense_cache, + host_remaining, + stopped, + ); + let product = match result { + Err(crate::qwen_forward::contract::Error::Unsupported( + crate::qwen_forward::contract::Stage::Executor, + )) if stopped() => { + if started.elapsed() > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + return Err(GenerationFailure::Cancelled); + } + other => other.map_err(|e| self.mtp_error(e))?, + }; + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + Ok(product) + } + pub(super) fn emit(&self, event: GenerationEvent) -> Result<(), GenerationFailure> { + let start = Instant::now(); + loop { + if self.cancelled() { + return Err(GenerationFailure::Cancelled); + } + match self.sink.try_emit(event.clone()) { + Ok(()) => return Ok(()), + Err(ContractError::GenerationBackpressure) + if start.elapsed() < BACKPRESSURE_TIMEOUT => + { + thread::sleep(Duration::from_millis(5)) + } + Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled), + _ => { + return Err( + exhausted("generation output backpressure deadline exceeded").into(), + ); + } + } + } + } +} +pub(super) fn generate( + mut run: Generation<'_, '_, '_>, + prompt: &[u32], + max: u32, +) -> Result<(FinishReason, Usage), GenerationFailure> { + if run.mtp { + return generate_mtp(run, prompt, max); + } + let start = Instant::now(); + let mut next = 0; + for (position, &token) in prompt.iter().enumerate() { + if start.elapsed() > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + next = run.step(token, position)?; + } + run.observe(|r| r.prefilled()); + let mut utf8 = Utf8Pending::default(); + let mut count = 0; + for index in 0..max { + if start.elapsed() > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + if run.cancelled() { + return Err(GenerationFailure::Cancelled); + } + run.observe(|r| r.token(next)); + if next == run.eos { + utf8.finish()?; + let usage = Usage { + input_tokens: prompt.len() as u64, + output_tokens: count + 1, + reused_input_tokens: 0, + }; + run.emit(GenerationEvent::Usage(usage.clone()))?; + run.observe(|r| r.decoded()); + return Ok((FinishReason::Stop, usage)); + } + let bytes = run + .tokenizer + .decode_bytes(&[next]) + .map_err(|_| unavailable("native token decoding failed"))?; + if let Some(text) = utf8.push(&bytes)? { + run.emit(GenerationEvent::TextDelta { text })?; + } + count += 1; + if index + 1 < max { + next = run.step(next, prompt.len() + index as usize)?; + } + } + utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?; + let usage = Usage { + input_tokens: prompt.len() as u64, + output_tokens: count, + reused_input_tokens: 0, + }; + run.emit(GenerationEvent::Usage(usage.clone()))?; + run.observe(|r| r.decoded()); + Ok((FinishReason::Length, usage)) +} diff --git a/crates/leleka-runtime/src/backend/generate_mtp.rs b/crates/leleka-runtime/src/backend/generate_mtp.rs new file mode 100644 index 00000000..57230eb3 --- /dev/null +++ b/crates/leleka-runtime/src/backend/generate_mtp.rs @@ -0,0 +1,261 @@ +//! The MTP speculative generation loop. +use super::*; + +pub(super) fn generate_mtp( + run: Generation<'_, '_, '_>, + prompt: &[u32], + max: u32, +) -> Result<(FinishReason, Usage), GenerationFailure> { + generate_mtp_resume(run, prompt, max, None, &mut None) +} + +pub(super) fn generate_mtp_resume( + mut run: Generation<'_, '_, '_>, + prompt: &[u32], + max: u32, + resume: Option, + publish: &mut Option, +) -> Result<(FinishReason, Usage), GenerationFailure> { + *publish = None; + let start = Instant::now(); + let (mut decoder, mut latest, reused, mut committed) = match resume { + Some(old) => { + if !append_compatible(&old.tokens, prompt) { + return Err(invalid("resident MTP prefix mismatch").into()); + } + old.decoder + .validate_resume(run.binding, run.session, &old.product, &old.tokens) + .map_err(|e| run.mtp_error(e))?; + let reused = old.tokens.len(); + (old.decoder, Some(old.product), reused, old.tokens) + } + None => ( + if run.execution + == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr + { + MtpDecoder::new_kv_prefill(run.binding, run.session, prompt) + } else { + MtpDecoder::new(run.binding) + } + .map_err(|e| run.mtp_error(e))?, + None, + 0, + Vec::new(), + ), + }; + run.observe(|r| r.retained(reused)); + let vocabulary = Dimension::new(248320).map_err(|e| run.mtp_error(e))?; + let eos = TokenId::new(u64::from(run.eos), vocabulary).map_err(|e| run.mtp_error(e))?; + let capacity = prompt + .len() + .checked_add(max as usize) + .filter(|n| *n <= run.context_tokens as usize) + .ok_or_else(|| exhausted("resident MTP prefix exceeds context"))?; + committed + .try_reserve(capacity.saturating_sub(committed.len())) + .map_err(|_| exhausted("resident MTP prefix allocation failed"))?; + // The retained draft ends immediately before the retained last target + // cell. Its known-next edge must be warmed before advancing that target. + if let Some(&next) = prompt.get(reused) + && let Some(product) = latest.as_ref() + { + if run.cancelled() { + return Err(GenerationFailure::Cancelled); + } + let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?; + decoder + .warm_retained(run.binding, run.session, product, next, run.moe_cache) + .map_err(|e| run.mtp_error(e))?; + } + // Each tile preserves the genuine last-known-next edge. A final tile + // obtains its actual head product; no intermediate greedy IDs are minted. + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + ))] + let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts(); + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )))] + let adaptive_prefill = false; + let mut position = reused; + while position < prompt.len() { + if start.elapsed() > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + let mut end = position + .saturating_add(run.prefill_tile_cap()) + .min(prompt.len()); + // Keep the last known-next edge and final head in one joint tile. + // A completed fresh KV warmer cannot admit a second final tile. + if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 { + end -= 1; + } + let next = prompt.get(end).copied(); + let product = if end - position == 1 && next.is_none() && !adaptive_prefill { + // Other policies keep the original lone-row actual-head producer. + Some(run.target_step(prompt[position], position)?) + } else { + run.prefill_chunk(&prompt[position..end], position, next, &mut decoder, start)? + }; + if next.is_none() { + latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?); + } else if product.is_some() { + return Err(invalid("unexpected intermediate prefill head").into()); + } + committed.extend_from_slice(&prompt[position..end]); + position = end; + } + let mut product = latest.ok_or_else(|| invalid("empty MTP prompt"))?; + if reused == 0 + && run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr + { + decoder + .finish_kv_prefill(run.binding, run.session, &product, &committed) + .map_err(|e| run.mtp_error(e))?; + } + run.observe(|r| r.prefilled()); + let mut utf8 = Utf8Pending::default(); + let mut count = 0_u64; + let reason = loop { + if start.elapsed() > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + if run.cancelled() { + return Err(GenerationFailure::Cancelled); + } + if count == u64::from(max) { + break FinishReason::Length; + } + let authoritative = product + .predicted(run.session) + .map_err(|e| run.mtp_error(e))?; + if authoritative == eos { + run.observe(|r| r.token(eos.get())); + count += 1; + break FinishReason::Stop; + } + if count + 1 == u64::from(max) { + run.observe(|r| r.token(authoritative.get())); + // The last public token is already authoritative. As in Native, + // no draft or unused next-position target step runs at max output. + let bytes = run + .tokenizer + .decode_bytes(&[authoritative.get()]) + .map_err(|_| unavailable("MTP token decoding failed"))?; + if let Some(text) = utf8.push(&bytes)? { + run.emit(GenerationEvent::TextDelta { text })?; + } + count += 1; + break FinishReason::Length; + } + // Bound the target advances by the operator's context, independently + // of the verified model's larger Position dimension. + let position = prompt + .len() + .checked_add(count as usize) + .ok_or_else(|| exhausted("MTP context exhausted"))?; + let _ = native_position(run.binding.input_constants(), run.context_tokens, position)?; + let remaining = + (max as usize - count as usize - 1).min(run.context_tokens as usize - position); + let spec = MtpWindowSpec::new(4, remaining, Some(eos)).map_err(|e| run.mtp_error(e))?; + let cancel = run.cancel; + let shared = run.shared; + let sink = run.sink; + let window = decoder + .window( + run.binding, + product, + run.session, + run.output, + run.kar_cache.as_deref_mut(), + run.moe_cache, + run.dense_cache, + spec, + || { + cancel.load(Ordering::Acquire) + || shared.shutdown.load(Ordering::Acquire) + || sink.is_closed() + || start.elapsed() > GENERATION_TIMEOUT + }, + ) + .map_err(|e| match e { + MtpWindowError::Cancelled if start.elapsed() > GENERATION_TIMEOUT => { + GenerationFailure::Backend(unavailable("generation deadline exceeded")) + } + MtpWindowError::Cancelled => GenerationFailure::Cancelled, + MtpWindowError::Forward(error) => run.mtp_error(error), + })?; + { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-mtp phase=verified-window draft_steps={} accepted={}", + window.draft_steps(), + window.tokens().len() + ); + } + let draft_steps = window.draft_steps(); + let (tokens, next, stopped) = window.into_parts(); + run.observe(|r| { + let mut ids = [0; 4]; + if tokens.len() <= ids.len() { + for (slot, token) in ids.iter_mut().zip(&tokens) { + *slot = token.get(); + } + r.window(draft_steps, &ids[..tokens.len()], stopped); + } else { + r.window(draft_steps, &[u32::MAX; 5], stopped); + } + }); + if tokens.is_empty() && !stopped { + return Err(run.mtp_error(crate::qwen_forward::contract::Error::IdentityMismatch)); + } + for token in tokens { + run.observe(|r| r.token(token.get())); + committed.push(token.get()); + let bytes = run + .tokenizer + .decode_bytes(&[token.get()]) + .map_err(|_| unavailable("MTP token decoding failed"))?; + if let Some(text) = utf8.push(&bytes)? { + run.emit(GenerationEvent::TextDelta { text })?; + } + count += 1; + } + product = next; + if count == u64::from(max) { + break FinishReason::Length; + } + if stopped { + run.observe(|r| r.token(eos.get())); + count += 1; // Authoritative EOS, as in the ordinary mode. + break FinishReason::Stop; + } + }; + if matches!(reason, FinishReason::Length) { + utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?; + } else { + utf8.finish()?; + } + let usage = Usage { + input_tokens: prompt.len() as u64, + output_tokens: count, + reused_input_tokens: reused as u64, + }; + run.emit(GenerationEvent::Usage(usage.clone()))?; + decoder + .validate_resume(run.binding, run.session, &product, &committed) + .map_err(|e| run.mtp_error(e))?; + if run.cancelled() { + return Err(GenerationFailure::Cancelled); + } + run.observe(|r| r.decoded()); + *publish = Some(MtpContinuation { + decoder, + product, + tokens: committed, + }); + Ok((reason, usage)) +} diff --git a/crates/leleka-runtime/src/backend/load.rs b/crates/leleka-runtime/src/backend/load.rs new file mode 100644 index 00000000..162c3370 --- /dev/null +++ b/crates/leleka-runtime/src/backend/load.rs @@ -0,0 +1,1170 @@ +//! The owner-side Load: bind the sources, open CUDA, build the caches, then serve generations until Unload. +use super::*; + +pub(super) fn serve_load( + config: &NativeBackendConfig, + rx: &Receiver, + shared: &Shared, + 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"), + )); + } + // 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", + ), + )); + } + 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); + // 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)); + 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 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}"); + } + } + } + } + } + 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(()) +} diff --git a/crates/leleka-runtime/src/backend/owner.rs b/crates/leleka-runtime/src/backend/owner.rs new file mode 100644 index 00000000..9ae87345 --- /dev/null +++ b/crates/leleka-runtime/src/backend/owner.rs @@ -0,0 +1,112 @@ +//! The owner thread loop and the load-failure diagnostics. +use super::*; + +#[derive(Clone, Copy, Debug)] +pub(super) enum LoadPhase { + Config, + Selection, + Shard0, + Shard1, + Artifact, + Tokenizer, + Eos, + SelectedBinding, + EffectiveMode, + Cancellation, + Driver, + Device, + Context, + OutputHead, + KarCache, + MoeWeightCache, + DenseWeightCache, + OriginalStack, + Identity, +} + +pub(super) fn load_failure(phase: LoadPhase, error: BackendError) -> BackendError { + use std::io::Write; + // BackendError.message is deliberately excluded from operator diagnostics. + let _ = writeln!( + std::io::stderr().lock(), + "leleka-load phase={phase:?} class={:?}", + error.code + ); + error +} +pub(super) fn selected_binding_failure(error: InputBindingError) -> BackendError { + use std::io::Write; + let phase = LoadPhase::SelectedBinding; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-load phase={phase:?} class={error:?}" + ); + invalid("selected input binding failed") +} +pub(super) fn load_forward_failure( + phase: LoadPhase, + error: crate::qwen_forward::contract::Error, + result: BackendError, +) -> BackendError { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-load phase={phase:?} class={error:?}" + ); + result +} + +pub(super) fn owner( + config: NativeBackendConfig, + rx: Receiver, + shared: &Shared, + instance: u64, + 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"))); + } + } + } +} diff --git a/crates/leleka-runtime/src/backend/probes.rs b/crates/leleka-runtime/src/backend/probes.rs new file mode 100644 index 00000000..5e7bafb1 --- /dev/null +++ b/crates/leleka-runtime/src/backend/probes.rs @@ -0,0 +1,68 @@ +//! Load-time probes of the experimental and KAR level-decode PTX. +use super::*; + +pub(super) fn experimental_error(error: experimental_modes::ExperimentalError) -> BackendError { + match error { + experimental_modes::ExperimentalError::Invalid(message) => invalid(message), + experimental_modes::ExperimentalError::Unsupported(message) => unsupported(message), + } +} +#[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub(super) fn probe_experimental( + context: &leleka_cuda_driver::Context<'_>, + config: &ExperimentalConfig, + plan: &experimental_modes::Plan, +) -> Result<(), BackendError> { + use leleka_cuda_driver::experimental::ExperimentalError; + for program in &plan.programs { + leleka_cuda_driver::experimental_gpu::Experimental::open(context, *program, &config.opt_in) + .and_then(|opened| opened.close()) + .map_err(|error| match error { + ExperimentalError::Unpinned(_) => unsupported("experimental PTX is not pinned"), + ExperimentalError::NotEnabled(_) | ExperimentalError::Invalid(_) => { + invalid("experimental program is not enabled for this configuration") + } + ExperimentalError::Driver(_) => unavailable("experimental program failed to load"), + })?; + } + Ok(()) +} +#[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +pub(super) fn probe_experimental( + _: &leleka_cuda_driver::Context<'_>, + _: &ExperimentalConfig, + _: &experimental_modes::Plan, +) -> Result<(), BackendError> { + Err(unsupported("experimental modes require Linux CUDA")) +} +#[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] +pub(super) fn probe_kar_level_decode( + context: &leleka_cuda_driver::Context<'_>, +) -> Result<(), BackendError> { + leleka_cuda_driver::kar_decode_levels_gpu::KarDecodeLevels::open(context) + .map(|_| ()) + .map_err(|error| match error { + leleka_cuda_driver::kar_decode_levels::KarDecodeError::Unpinned => { + unsupported("KAR level-decode PTX is not pinned") + } + _ => unavailable("KAR level-decode program failed to load"), + }) +} +#[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +pub(super) fn probe_kar_level_decode( + _: &leleka_cuda_driver::Context<'_>, +) -> Result<(), BackendError> { + Err(unsupported("KAR expert source requires Linux CUDA")) +} diff --git a/crates/leleka-runtime/src/backend/proxy.rs b/crates/leleka-runtime/src/backend/proxy.rs new file mode 100644 index 00000000..767863fc --- /dev/null +++ b/crates/leleka-runtime/src/backend/proxy.rs @@ -0,0 +1,287 @@ +//! The caller-side handle of the owner actor: shared state, commands and the `Backend` implementation. +use super::*; + +pub(super) struct Active { + pub(super) id: String, + pub(super) cancel: Arc, +} +pub(super) struct Shared { + pub(super) ready: AtomicBool, + pub(super) shutdown: AtomicBool, + pub(super) active: Mutex>, +} +pub(super) struct Proxy { + pub(super) tx: SyncSender, + pub(super) shared: Arc, + pub(super) seen: RecentIds, + pub(super) kar_configured: bool, + pub(super) mtp_configured: bool, + pub(super) kar_experts_configured: bool, + pub(super) kar_expert_native_digest: Option, + pub(super) execution: EvaluationExecution, + pub(super) optimized_execution: bool, + 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, + pub(super) original_serve: bool, +} +pub(super) type Reply = SyncSender>; +pub(super) enum Command { + Load(ModelDescriptor, RuntimeConfig, Reply), + Generate( + LoadedModel, + GenerationRequest, + Arc, + Reply, + ), + Unload(LoadedModel, Reply<()>), + /// New inference settings as a JSON document (`serve_tuning.rs`); the reply is the effective settings. + Reconfigure(String, Reply), +} +impl Proxy { + pub(super) fn idle(&self) -> Result<(), BackendError> { + if self.shared.shutdown.load(Ordering::Acquire) { + return Err(unavailable("native owner stopped")); + } + if self + .shared + .active + .lock() + .map_err(|_| unavailable("native owner state unavailable"))? + .is_some() + { + return Err(exhausted("native generation is active")); + } + Ok(()) + } + pub(super) fn send(&self, command: Command) -> Result<(), BackendError> { + self.tx.try_send(command).map_err(|error| match error { + mpsc::TrySendError::Full(_) => exhausted("native control queue is full"), + mpsc::TrySendError::Disconnected(_) => unavailable("native owner stopped"), + }) + } + pub(super) fn wait( + &self, + reply: Receiver>, + ) -> Result { + self.wait_with_timeout(reply, REPLY_TIMEOUT) + } + pub(super) fn wait_with_timeout( + &self, + reply: Receiver>, + timeout: Duration, + ) -> Result { + match reply.recv_timeout(timeout) { + Ok(result) => result, + Err(_) => { + // A late/uncertain operation is never retried on this owner. + self.shared.shutdown.store(true, Ordering::Release); + cancel_active(&self.shared); + Err(unavailable("native operation outcome unavailable")) + } + } + } +} +impl Backend for Proxy { + fn identity(&self) -> BackendIdentity { + BackendIdentity { + name: "leleka-native".into(), + implementation_version: if self.original_serve { + ORIGINAL_SERVE_EXECUTION.into() + } else if self.adaptive_slots { + ADAPTIVE_SLOTS_EXECUTION.into() + } else if self.resident_owners { + RESIDENT_OWNERS_EXECUTION.into() + } else if self.retained_scratch { + RETAINED_SCRATCH_EXECUTION.into() + } else if self.streamed_spill { + STREAMED_SPILL_EXECUTION.into() + } else if self.queued_owners { + QUEUED_OWNERS_EXECUTION.into() + } else if self.optimized_execution { + OPTIMIZED_EXECUTION.into() + } else if self.execution + == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr + { + INTEGER_WINDOWED_EXECUTION.into() + } else { + "0.1.0-fp16-qsa-explicit-modes".into() + }, + api_version: BACKEND_API_VERSION, + } + } + fn capabilities(&self) -> BackendCapabilities { + let models = if self.shared.ready.load(Ordering::Acquire) + && !self.shared.shutdown.load(Ordering::Acquire) + { + vec![SupportedModelTuple { + family: "qwen4exp".into(), + architecture: "qwen4exp".into(), + weight_format: "gguf:iq3_s".into(), + }] + } else { + Vec::new() + }; + BackendCapabilities { + supported_models: models, + max_concurrent_generations: 1, + supports_cancellation: true, + supports_tool_call_streaming: false, + } + } + fn prefix_cache_summary(&self) -> Option { + if !self.shared.ready.load(Ordering::Acquire) + || self.shared.shutdown.load(Ordering::Acquire) + { + return None; + } + original_serve::published_prefix_summary() + } + fn memory_report(&self) -> Option { + if self.shared.shutdown.load(Ordering::Acquire) { + return None; + } + leleka_memory::published_report() + } + fn telemetry_report(&self) -> Option { + if self.shared.shutdown.load(Ordering::Acquire) { + return None; + } + leleka_memory::telemetry::published_telemetry() + } + fn load( + &mut self, + model: ModelDescriptor, + config: RuntimeConfig, + ) -> Result { + validate_load(&model, &config)?; + validate_kar_selection(&config, self.kar_configured)?; + validate_mtp_selection(&config, self.mtp_configured)?; + self.idle()?; + // A KAR expert archive (and overlay) is hashed whole during Load, after + // the base shards, so it gets the same cold-load budget as KAR/MTP files. + let timeout = load_reply_timeout(&config.inference_mode, self.kar_experts_configured); + let (tx, rx) = mpsc::sync_channel(1); + self.send(Command::Load(model, config, tx))?; + self.wait_with_timeout(rx, timeout) + } + fn start_generation( + &mut self, + model: &LoadedModel, + request: GenerationRequest, + ) -> Result { + validate_request(&request)?; + validate_handle(model, self.kar_expert_native_digest.as_deref())?; + if RECONFIGURING.load(Ordering::Acquire) { + return Err(BackendError { + code: ErrorCode::ResourceExhausted, + message: "reconfiguring: retry_after=30: the engine is being reconfigured".into(), + retryable: true, + }); + } + self.idle()?; + if !self.shared.ready.load(Ordering::Acquire) { + return Err(unavailable("native model is not ready")); + } + if self.seen.contains(&request.request_id) { + return Err(invalid("generation request was already accepted")); + } + let cancel = Arc::new(AtomicBool::new(false)); + *self + .shared + .active + .lock() + .map_err(|_| unavailable("native owner state unavailable"))? = Some(Active { + id: request.request_id.clone(), + cancel: Arc::clone(&cancel), + }); + let id = request.request_id.clone(); + let (tx, rx) = mpsc::sync_channel(1); + if let Err(error) = self.send(Command::Generate(model.clone(), request, cancel, tx)) { + clear_active(&self.shared); + return Err(error); + } + let result = self.wait(rx); + if result.is_ok() { + self.seen.insert(&id); + } else { + clear_active(&self.shared); + } + result + } + fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> { + let active = self + .shared + .active + .lock() + .map_err(|_| unavailable("native owner state unavailable"))?; + match active.as_ref() { + Some(active) if active.id == request_id => { + active.cancel.store(true, Ordering::Release); + Ok(()) + } + _ => Err(invalid("generation is not active")), + } + } + fn reconfigure(&mut self, settings_json: &str) -> Result { + if !self.original_serve { + return Err(unsupported( + "only the Original serve path can be reconfigured at run time", + )); + } + self.idle()?; + if !self.shared.ready.load(Ordering::Acquire) { + return Err(unavailable("native model is not ready")); + } + if RECONFIGURING.swap(true, Ordering::AcqRel) { + return Err(exhausted("a reconfiguration is already running")); + } + let (tx, rx) = mpsc::sync_channel(1); + let result = self + .send(Command::Reconfigure(settings_json.to_owned(), tx)) + .and_then(|()| self.wait_with_timeout(rx, RECONFIGURE_TIMEOUT)); + RECONFIGURING.store(false, Ordering::Release); + result + } + fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> { + validate_handle(&model, self.kar_expert_native_digest.as_deref())?; + self.idle()?; + let (tx, rx) = mpsc::sync_channel(1); + self.send(Command::Unload(model, tx))?; + self.wait(rx) + } +} +impl Drop for Proxy { + fn drop(&mut self) { + self.shared.shutdown.store(true, Ordering::Release); + cancel_active(&self.shared); + } +} +pub(super) struct OwnerGuard(pub(super) Arc); +impl Drop for OwnerGuard { + fn drop(&mut self) { + self.0.ready.store(false, Ordering::Release); + self.0.shutdown.store(true, Ordering::Release); + cancel_active(&self.0); + } +} +pub(super) struct ActiveGuard<'a>(pub(super) &'a Shared); +impl Drop for ActiveGuard<'_> { + fn drop(&mut self) { + clear_active(self.0); + } +} +pub(super) fn cancel_active(shared: &Shared) { + if let Ok(active) = shared.active.lock() + && let Some(active) = active.as_ref() + { + active.cancel.store(true, Ordering::Release); + } +} +pub(super) fn clear_active(shared: &Shared) { + if let Ok(mut active) = shared.active.lock() { + *active = None; + } +} diff --git a/crates/leleka-runtime/src/backend/request.rs b/crates/leleka-runtime/src/backend/request.rs new file mode 100644 index 00000000..fe5ab2da --- /dev/null +++ b/crates/leleka-runtime/src/backend/request.rs @@ -0,0 +1,74 @@ +//! Request preparation: sampler plan, prompt tokens, positions. +use super::*; + +pub(super) fn request_sampler( + request: &GenerationRequest, + entropy: u64, +) -> Result, leleka_sampler_ref::SamplingError> { + let s = &request.sampling; + let raw = + leleka_sampler_ref::RequestSampling::from_fixed_point(&leleka_sampler_ref::FixedPoint { + temperature_milli: request.temperature_milli, + top_p_micro: s.top_p_micro, + top_k: s.top_k, + min_p_micro: s.min_p_micro, + repetition_penalty_micro: s.repetition_penalty_micro, + frequency_penalty_micro: s.frequency_penalty_micro, + presence_penalty_micro: s.presence_penalty_micro, + penalty_last_n: s.penalty_last_n, + seed: s.seed, + }); + let params = leleka_sampler_ref::SamplingParams::resolve(&raw)?; + Ok(params + .needs_sampler() + .then(|| params.to_sampler_params(entropy))) +} + +/// The steady-clock tick the Original takes as the seed of a request without one. +pub(super) fn clock_seed() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(1, |d| d.as_nanos() as u64) + .max(1) +} +pub(super) fn prepare_prompt( + tokenizer: &Tokenizer, + request: &GenerationRequest, + context: u32, +) -> Result, BackendError> { + validate_request(request)?; + // The prompt may carry marks (`LiteralMarks`) for control-token text that was inside a message: that text is encoded as + // ordinary text, the template's own literals as special tokens. A prompt without marks encodes as before. + let tokens = tokenizer + .encode_marked(&request.prompt) + .map_err(|_| invalid("prompt tokenization failed"))?; + if tokens.is_empty() + || tokens + .len() + .checked_add(request.max_output_tokens as usize) + .is_none_or(|total| total > context as usize) + { + return Err(exhausted("prompt and output exceed configured context")); + } + Ok(tokens) +} + +/// The operator ceiling governs admission, while the opaque Position carries +/// the verified model dimension used by every stage's identity validation. +pub(super) fn native_position( + constants: &InputConstants, + configured: u32, + value: usize, +) -> Result { + let model_context = constants.context_length(); + if configured == 0 || configured > model_context { + return Err(invalid("native context configuration invalid")); + } + let value = u64::try_from(value).map_err(|_| exhausted("native context exhausted"))?; + if value >= u64::from(configured) { + return Err(exhausted("native configured context exhausted")); + } + let bound = Dimension::new(u64::from(model_context)) + .map_err(|_| invalid("verified native context invalid"))?; + Position::new(value, bound).map_err(|_| exhausted("native model context exhausted")) +} diff --git a/crates/leleka-runtime/src/backend/session.rs b/crates/leleka-runtime/src/backend/session.rs new file mode 100644 index 00000000..daeac864 --- /dev/null +++ b/crates/leleka-runtime/src/backend/session.rs @@ -0,0 +1,36 @@ +//! The resident numeric prefix kept between generations. +use super::*; + +/// One actual successful resident numeric prefix. Actor/model lifetime is +/// the lifecycle fence; LoadedModel adds handle/mode/config identity. +pub(super) struct PrefixSession<'driver> { + pub(super) loaded: LoadedModel, + pub(super) session: QwenSession<'driver>, + pub(super) continuation: MtpContinuation, +} +pub(super) struct MtpContinuation { + pub(super) decoder: MtpDecoder, + pub(super) product: TargetStepProduct, + /// Exactly target-committed IDs, never a speculative or merely emitted ID. + pub(super) tokens: Vec, +} +pub(super) fn append_compatible(committed: &[u32], incoming: &[u32]) -> bool { + !committed.is_empty() + && committed.len() as u64 <= crate::qwen_forward::contract::serving_cells() + && incoming.len() as u64 <= crate::qwen_forward::contract::serving_cells() + && incoming.starts_with(committed) +} + +/// Completion is the conjunction of numeric success, bounded terminal queue +/// publication and a still-live serving lifecycle. Failed gates drop ownership. +pub(super) fn terminal_admit( + candidate: Option, + completed: bool, + published: bool, + cancelled: bool, + shutdown: bool, + closed: bool, + ready: bool, +) -> Option { + candidate.filter(|_| completed && published && !cancelled && !shutdown && !closed && ready) +} diff --git a/crates/leleka-runtime/src/backend/sources.rs b/crates/leleka-runtime/src/backend/sources.rs new file mode 100644 index 00000000..8e97afc9 --- /dev/null +++ b/crates/leleka-runtime/src/backend/sources.rs @@ -0,0 +1,145 @@ +//! Verification of the pinned sources (shards, KAR archive, ranked profile) at load time. +use super::*; + +/// What the three source verifications returned. Errors are reduced to text because the verifying threads hand +/// them over; the callers map each to the same fixed refusal as before. +pub(super) struct VerifiedSources { + pub(super) shard0: Result, + pub(super) shard1: Result, + /// `None` when no inherited archive is configured. + pub(super) kar: Option, +} + +pub(super) type InputResultKar = + Result; + +/// Verify shard 0, shard 1 and the inherited KAR archive at the same time. They are independent files; the +/// SHA-256 of each is sequential, so the wall time is the slowest one instead of their sum. Each verification +/// is the very function the sequential load used (full hash, strict index, pinned profile), and the results are +/// consumed in the original order, so every refusal is the same as before. +pub(super) fn verify_sources_parallel( + config: &NativeBackendConfig, + want_kar: bool, +) -> VerifiedSources { + use std::time::Instant; + let begun = Instant::now(); + let result = std::thread::scope(|scope| { + let shard1 = scope.spawn(|| { + let started = Instant::now(); + let result = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|e| e.to_string()); + crate::load_clock::span("shard1_sha256_and_index", started); + result + }); + let kar = config + .kar_ple_inherited + .as_ref() + .filter(|_| want_kar) + .map(|archive| { + scope.spawn(move || { + let started = Instant::now(); + let result = + crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive( + archive, + ); + crate::load_clock::span("kar_inspect_verify", started); + result + }) + }); + let started = Instant::now(); + let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string()); + crate::load_clock::span("shard0_sha256_and_index", started); + VerifiedSources { + shard0, + shard1: shard1 + .join() + .unwrap_or_else(|_| Err("verification thread failed".into())), + kar: kar.map(|handle| handle.join().unwrap_or(Err(InputBindingError::Busy))), + } + }); + crate::load_clock::span("sources_verified_in_parallel_wall", begun); + result +} + +/// `leleka-inference --verify-only`: the load-time verification of the sources (both shards, the KAR archive) +/// and nothing else: no CUDA, no GPU, no model state. Prints the `leleka-load-time` lines and returns. +/// It uses exactly the functions of `serve_load`, so what it measures is what a start spends. +pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> { + crate::load_clock::begin(); + let sources = verify_sources_parallel(&config, true); + sources + .shard0 + .map_err(|_| invalid("pinned shard 0 verification failed"))?; + sources + .shard1 + .map_err(|_| invalid("pinned shard 1 verification failed"))?; + if let Some(kar) = sources.kar { + kar.map_err(|_| invalid("pinned KAR archive verification failed"))?; + } + crate::load_clock::lap("all_sources_verified"); + Ok(()) +} + +/// `leleka-inference --kar-attested-by-stamp`: the parent copied the sealed archive from a file whose verification +/// stamp matched and was unchanged while it was copied; skip hashing the memfd again. Never implied. +pub fn set_archive_attested() { + leleka_model_format::verify_stamp::set_attested_archive(); +} + +/// Operator switch of `leleka-inference --verify-stamps DIR [--verify-rehash]`: a file that matched its pinned +/// digest before and is unchanged (device, inode, size, mtime, ctime) is not hashed again. Set once, before Load. +pub fn set_verify_stamps(directory: PathBuf, rehash: bool) -> bool { + leleka_model_format::verify_stamp::set_global( + leleka_model_format::verify_stamp::VerifyStamps::new(directory, rehash), + ) +} +pub(super) fn read_ranked_expert_profile( + source: &RankedExpertProfileSource, +) -> Result, BackendError> { + use std::io::Read; + if source.sha256 != RANKED_EXPERT_PROFILE_SHA { + return Err(invalid("unrecognized ranked expert profile")); + } + let file = std::fs::File::open(&source.path) + .map_err(|_| invalid("ranked expert profile unavailable"))?; + if file + .metadata() + .map_err(|_| invalid("ranked expert profile unavailable"))? + .len() + != RANKED_EXPERT_PROFILE_BYTES as u64 + { + return Err(invalid("ranked expert profile extent mismatch")); + } + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(RANKED_EXPERT_PROFILE_BYTES + 1) + .map_err(|_| exhausted("ranked expert profile metadata unavailable"))?; + file.take((RANKED_EXPERT_PROFILE_BYTES + 1) as u64) + .read_to_end(&mut bytes) + .map_err(|_| invalid("ranked expert profile read failed"))?; + let mut actual_digest = String::with_capacity(64); + for value in Sha256::digest(&bytes) { + use std::fmt::Write; + let _ = write!(actual_digest, "{value:02x}"); + } + if bytes.len() != RANKED_EXPERT_PROFILE_BYTES || actual_digest != source.sha256 { + return Err(invalid("ranked expert profile digest mismatch")); + } + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + ))] + { + crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&bytes) + .map_err(|_| invalid("ranked expert profile domain mismatch"))?; + Ok(bytes) + } + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )))] + { + Err(unsupported( + "optimized CUDA execution requires Linux x86_64", + )) + } +} diff --git a/crates/leleka-runtime/src/backend/spawn.rs b/crates/leleka-runtime/src/backend/spawn.rs new file mode 100644 index 00000000..57b78d0a --- /dev/null +++ b/crates/leleka-runtime/src/backend/spawn.rs @@ -0,0 +1,249 @@ +//! Factories of the Native and the evaluation-only backends, and the common owner-thread spawn. +use super::*; + +pub fn spawn_backend(config: NativeBackendConfig) -> Result, BackendError> { + spawn_backend_inner(config, None, EvaluationExecution::Native) +} +/// Explicit operator-selected experiment. Selection is fixed for this owner +/// lifetime and does not certify quality, speed or long-context completion. +/// The existing typed KAR PLE MTP Load remains mandatory; no observer is needed. +pub fn spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr( + config: NativeBackendConfig, +) -> Result, BackendError> { + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + { + return Err(invalid( + "IQ3 windowed256 retained GR experiment requires KAR PLE and MTP sources", + )); + } + spawn_backend_inner( + config, + None, + EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + ) +} +/// Explicit public evaluation only. Normal serving has no observer and never +/// exposes token IDs; this does not change the RPC or backend protocol. +pub fn spawn_backend_observed( + config: NativeBackendConfig, + observer: EvaluationObserver, +) -> Result, BackendError> { + spawn_backend_inner(config, Some(observer), EvaluationExecution::Native) +} +/// Private evaluation candidate only: fixed operator selection for subsequent +/// typed model Load. Neither RPCs nor normal spawns can choose this policy. +/// Still experimental; selection is not a quality/performance certificate. +pub fn spawn_backend_observed_resident_mmq( + config: NativeBackendConfig, + observer: EvaluationObserver, +) -> Result, BackendError> { + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + { + return Err(invalid( + "resident MMQ evaluation requires KAR PLE and MTP sources", + )); + } + spawn_backend_inner( + config, + Some(observer), + EvaluationExecution::ExperimentalResidentMmq, + ) +} +/// Explicit evaluation-only native-certified activation policy. This retains +/// original MMQ tensor kernels and does not certify model quality or speed. +pub fn spawn_backend_observed_native_resident_mmq( + config: NativeBackendConfig, + observer: EvaluationObserver, +) -> Result, BackendError> { + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + { + return Err(invalid( + "native-certified resident MMQ evaluation requires KAR PLE and MTP sources", + )); + } + spawn_backend_inner( + config, + Some(observer), + EvaluationExecution::ExperimentalNativeResidentMmq, + ) +} +/// Explicit operator evaluation candidate only: IQ3 GU integer MMA with native +/// integer truncation/order. Ineligible GU layers use actual native execution. +/// Down retains existing candidate arithmetic; no quality/performance admission. +/// Normal spawns, RPCs, configuration and production defaults cannot select it. +pub fn spawn_backend_observed_native_integer_iq3_mmq( + config: NativeBackendConfig, + observer: EvaluationObserver, +) -> Result, BackendError> { + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + { + return Err(invalid( + "IQ3 integer MMA evaluation requires KAR PLE and MTP sources", + )); + } + spawn_backend_inner( + config, + Some(observer), + EvaluationExecution::ExperimentalNativeIntegerIq3Mmq, + ) +} +/// Explicit private evaluation: real outer256 with bounded64 kernels and +/// retained GR transport. Native MoE arithmetic and normal serving are kept. +/// This selection is experimental, not a quality or performance certificate. +pub fn spawn_backend_observed_windowed256_retained_gr( + config: NativeBackendConfig, + observer: EvaluationObserver, +) -> Result, BackendError> { + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + { + return Err(invalid( + "windowed256 retained GR evaluation requires KAR PLE and MTP sources", + )); + } + spawn_backend_inner( + config, + Some(observer), + EvaluationExecution::ExperimentalWindowed256RetainedGr, + ) +} +/// Explicit private evaluation composition: outer256 retained GR transport, +/// IQ3-only native-order integer GU, and native whole-layer fallback for other GU. +/// Down keeps existing candidate arithmetic. No quality/performance admission; +/// normal spawns, RPCs and production configuration cannot select this policy. +pub fn spawn_backend_observed_native_integer_iq3_windowed256_retained_gr( + config: NativeBackendConfig, + observer: EvaluationObserver, +) -> Result, BackendError> { + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + { + return Err(invalid( + "IQ3 windowed256 retained GR evaluation requires KAR PLE and MTP sources", + )); + } + spawn_backend_inner( + config, + Some(observer), + EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + ) +} +pub(super) fn spawn_backend_inner( + config: NativeBackendConfig, + observer: Option, + execution: EvaluationExecution, +) -> Result, BackendError> { + spawn_backend_configured( + config, + observer, + OwnerExecution { + original: None, + kind: execution, + optimized: None, + }, + ) +} +pub(super) fn spawn_backend_configured( + config: NativeBackendConfig, + observer: Option, + selection: OwnerExecution, +) -> Result, BackendError> { + let execution = selection.kind; + let optimized_execution = selection.optimized.is_some(); + let queued_owners = selection + .optimized + .as_ref() + .is_some_and(|options| options.policy != OptimizedOwnerPolicy::Original); + let streamed_spill = selection.optimized.as_ref().is_some_and(|options| { + matches!( + options.policy, + OptimizedOwnerPolicy::StreamedSpill + | OptimizedOwnerPolicy::RetainedScratch + | OptimizedOwnerPolicy::ResidentOwners + | OptimizedOwnerPolicy::AdaptiveSlots + ) + }); + let retained_scratch = selection.optimized.as_ref().is_some_and(|options| { + matches!( + options.policy, + OptimizedOwnerPolicy::RetainedScratch + | OptimizedOwnerPolicy::ResidentOwners + | OptimizedOwnerPolicy::AdaptiveSlots + ) + }); + let adaptive_slots = selection + .optimized + .as_ref() + .is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots); + let resident_owners = selection.optimized.as_ref().is_some_and(|options| { + matches!( + options.policy, + OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots + ) + }); + let original_serve = selection.original.is_some(); + if config.context_tokens == 0 + || u64::from(config.context_tokens) > leleka_context::rope_scaling::MAX_CHARTER_CONTEXT + || config.gpu_budget_bytes == 0 + || usize::try_from(config.gpu_budget_bytes).is_err() + || i32::try_from(config.gpu_device_ordinal).is_err() + || (config.kar_ple_source.is_some() && config.kar_ple_inherited.is_some()) + { + return Err(invalid("invalid native resource configuration")); + } + // The serving context (cells, RoPE scaling) is fixed once per process before any CUDA owner exists. + crate::serving::admit_context_tokens(config.context_tokens, config.gpu_budget_bytes).map_err( + |e| BackendError { + code: ErrorCode::InvalidRequest, + message: format!("native context not servable: {e}"), + retryable: false, + }, + )?; + let (tx, rx) = mpsc::sync_channel(QUEUE); + let shared = Arc::new(Shared { + ready: AtomicBool::new(false), + shutdown: AtomicBool::new(false), + active: Mutex::new(None), + }); + let kar_configured = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(); + let mtp_configured = config.mtp_source.is_some(); + let kar_experts_configured = config.kar_expert_source.is_some(); + // The Native handle a KAR-expert Load will publish: the base Native digest + // mixed with the source identity (pure function of the operator config). + let kar_expert_native_digest = config.kar_expert_source.as_ref().map(|source| { + kar_expert_mode_digest( + MODE_DIGEST, + &crate::model_binding::kar_expert_source::config_identity_digest(source), + ) + }); + let worker_shared = Arc::clone(&shared); + let instance = INSTANCE.fetch_add(1, Ordering::Relaxed); + thread::Builder::new() + .name("leleka-cuda-owner".into()) + .spawn(move || { + let _guard = OwnerGuard(Arc::clone(&worker_shared)); + owner(config, rx, &worker_shared, instance, observer, selection); + }) + .map_err(|_| unavailable("native owner thread unavailable"))?; + Ok(Box::new(Proxy { + tx, + shared, + seen: RecentIds::default(), + kar_configured, + mtp_configured, + kar_experts_configured, + kar_expert_native_digest, + execution, + optimized_execution, + queued_owners, + streamed_spill, + retained_scratch, + resident_owners, + adaptive_slots, + original_serve, + })) +} diff --git a/crates/leleka-runtime/src/backend/spawn_optimized.rs b/crates/leleka-runtime/src/backend/spawn_optimized.rs new file mode 100644 index 00000000..e78958bf --- /dev/null +++ b/crates/leleka-runtime/src/backend/spawn_optimized.rs @@ -0,0 +1,259 @@ +//! Factories of the optimized windowed256 experiments (queued owners .. adaptive slots). +use super::*; + +/// Separately selected optimized experiment. Default and earlier experiment +/// factories remain unchanged; this selection certifies neither speed nor quality. +pub fn spawn_backend_experimental_optimized_windowed256( + config: NativeBackendConfig, + ranked_profile: Option, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "optimized CUDA execution requires Linux x86_64", + )); + } + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + || ranked_profile.as_ref().is_some_and(|source| { + source.path.as_os_str().is_empty() || source.sha256 != RANKED_EXPERT_PROFILE_SHA + }) + { + return Err(invalid("invalid optimized KAR PLE MTP profile selection")); + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile, + policy: OptimizedOwnerPolicy::Original, + }), + }, + ) +} +/// Separately opt-in pinned-profile owner. This prepares the configured candidate +/// factories for serving; selection does not certify quality or performance. +/// The earlier optimized route and Native defaults remain unchanged. +pub fn spawn_backend_experimental_optimized_windowed256_queued_owners( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported("queued CUDA owners require Linux x86_64")); + } + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) + || config.mtp_source.is_none() + || ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "invalid queued-owner KAR PLE MTP profile selection", + )); + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile: Some(ranked_profile), + policy: OptimizedOwnerPolicy::QueuedOwners, + }), + }, + ) +} +/// Explicit inherited-KAR operator experiment. Original and queued-owner +/// factories preserve their previous meanings. Qualification is separate. +pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "streamed spill CUDA owners require Linux x86_64", + )); + } + if config.kar_ple_inherited.is_none() + || config.kar_ple_source.is_some() + || config.mtp_source.is_none() + || ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "streamed spill requires inherited sealed KAR, MTP and pinned profile", + )); + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile: Some(ranked_profile), + policy: OptimizedOwnerPolicy::StreamedSpill, + }), + }, + ) +} +/// Additional retained whole-buffer owners; distinct unadopted operator mode. +pub fn spawn_backend_experimental_optimized_windowed256_retained_scratch( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "streamed spill CUDA owners require Linux x86_64", + )); + } + if config.kar_ple_inherited.is_none() + || config.kar_ple_source.is_some() + || config.mtp_source.is_none() + || ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "streamed spill requires inherited sealed KAR, MTP and pinned profile", + )); + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile: Some(ranked_profile), + policy: OptimizedOwnerPolicy::RetainedScratch, + }), + }, + ) +} +/// Separate experimental owner policy; actual model qualification required. +pub fn spawn_backend_experimental_optimized_windowed256_resident_owners( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "streamed spill CUDA owners require Linux x86_64", + )); + } + if config.kar_ple_inherited.is_none() + || config.kar_ple_source.is_some() + || config.mtp_source.is_none() + || ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "streamed spill requires inherited sealed KAR, MTP and pinned profile", + )); + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile: Some(ranked_profile), + policy: OptimizedOwnerPolicy::ResidentOwners, + }), + }, + ) +} +/// Authentic adaptive slot policy; experimental until paired quality/time gates. +pub fn spawn_backend_experimental_optimized_windowed256_adaptive_slots( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "streamed spill CUDA owners require Linux x86_64", + )); + } + if config.kar_ple_inherited.is_none() + || config.kar_ple_source.is_some() + || config.mtp_source.is_none() + || ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "streamed spill requires inherited sealed KAR, MTP and pinned profile", + )); + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile: Some(ranked_profile), + policy: OptimizedOwnerPolicy::AdaptiveSlots, + }), + }, + ) +} +/// Explicit PUBLIC-FIXTURE attachment to the identical adaptive policy. +/// No token IDs enter the public RPC schema; only the operator observer sees them. +pub fn spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, + observer: EvaluationObserver, +) -> Result, BackendError> { + if std::env::var("LELEKA_PUBLIC_EVALUATION").as_deref() != Ok("yes") { + return Err(invalid("explicit public evaluation required")); + } + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "streamed spill CUDA owners require Linux x86_64", + )); + } + if config.kar_ple_inherited.is_none() + || config.kar_ple_source.is_some() + || config.mtp_source.is_none() + || ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "streamed spill requires inherited sealed KAR, MTP and pinned profile", + )); + } + spawn_backend_configured( + config, + Some(observer), + OwnerExecution { + original: None, + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: Some(OptimizedBackendConfig { + ranked_profile: Some(ranked_profile), + policy: OptimizedOwnerPolicy::AdaptiveSlots, + }), + }, + ) +} diff --git a/crates/leleka-runtime/src/backend/spawn_original.rs b/crates/leleka-runtime/src/backend/spawn_original.rs new file mode 100644 index 00000000..e8cf69be --- /dev/null +++ b/crates/leleka-runtime/src/backend/spawn_original.rs @@ -0,0 +1,87 @@ +//! Choice of the Original-literal mode17 serve path and its factories. +use super::*; + +/// The path an operator configuration resolves to for `mode` (see `OriginalServeMode`): pure over the +/// configuration and the build's asset probe. `Auto` picks the Original path only when it can start; +/// `Original` returns a precise refusal instead of falling back; `Preview` never starts it. The caller +/// spawns the matching backend (`spawn_backend_original_serve`, or its own preview chain). +pub fn original_serve_choice( + mode: OriginalServeMode, + config: &NativeBackendConfig, +) -> Result { + let facts = original_serve::ConfigFacts { + kar_inherited: config.kar_ple_inherited.is_some(), + kar_staged: config.kar_ple_source.is_some(), + mtp: config.mtp_source.is_some(), + kar_expert: config.kar_expert_source.is_some(), + gguf_ple: std::env::var("LELEKA_ORIGINAL_SERVE_GGUF_PLE").is_ok_and(|v| v == "1"), + experimental: !config.experimental.is_off(), + context_tokens: config.context_tokens, + }; + // The probe is only consulted when the mode could select the Original path. + let unsealed = if mode == OriginalServeMode::Preview { + Vec::new() + } else { + original_serve::current_unsealed() + }; + original_serve::choose(mode, &facts, &unsealed) +} +/// The Original-literal mode17 serve backend: the generate.cpp serve loop (`OriginalSpecController` over +/// `OriginalServeEngine` and the native Verifier) with the Original batched prompt read and MTP drafting, +/// instead of the Rust-native preview decoder. `options.mode` is resolved with `original_serve_choice`; +/// a mode that resolves to the preview path is refused here (spawn that backend instead). The expert tier +/// is the all-CPU pool over the pinned model's mapped routed weights; selection certifies neither +/// quality nor speed. +pub fn spawn_backend_original_serve( + config: NativeBackendConfig, + options: OriginalServeOptions, +) -> Result, BackendError> { + if !cfg!(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )) { + return Err(unsupported( + "Original serve CUDA owners require Linux x86_64", + )); + } + options.validate()?; + match original_serve_choice(options.mode, &config)? { + OriginalServeChoice::Original => {} + OriginalServeChoice::Preview { reason } => { + return Err(invalid_dynamic(format!( + "the selected backend mode resolves to the preview path ({reason}); spawn the preview backend" + ))); + } + } + spawn_backend_configured( + config, + None, + OwnerExecution { + original: Some(options), + kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + optimized: None, + }, + ) +} +/// Explicit Original-literal mode17 serve (the earlier factory name, kept for its callers): the pinned +/// ranked profile is still validated as before but is not consumed (the Original expert tier here has no +/// GPU residency to rank). Equivalent to `spawn_backend_original_serve` with `OriginalServeMode::Original`. +pub fn spawn_backend_experimental_original_serve( + config: NativeBackendConfig, + ranked_profile: RankedExpertProfileSource, +) -> Result, BackendError> { + if ranked_profile.path.as_os_str().is_empty() + || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA + { + return Err(invalid( + "Original serve requires the pinned ranked profile selection", + )); + } + spawn_backend_original_serve( + config, + OriginalServeOptions { + mode: OriginalServeMode::Original, + ..OriginalServeOptions::default() + }, + ) +} diff --git a/crates/leleka-runtime/src/backend/tests.rs b/crates/leleka-runtime/src/backend/tests.rs new file mode 100644 index 00000000..1d594b8f --- /dev/null +++ b/crates/leleka-runtime/src/backend/tests.rs @@ -0,0 +1,373 @@ +use super::*; +#[test] +fn queued_owner_identity_is_distinct_and_binds_profile_and_actual_bound_mode() { + let old_fields = [ + "leleka-optimized-execution-v2", + "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", + "complete-routed-gpu-finite-guard-v1", + "sanitized-bound-mode", + OPTIMIZED_EXECUTION, + "ranked-pinned-prefix-bounded-spill-v1", + RANKED_EXPERT_PROFILE_SHA, + ]; + let mut oracle = Sha256::new(); + for field in old_fields { + oracle.update(field.as_bytes()); + oracle.update(b"\n"); + } + let mut expected_old = String::from("sha256:"); + for byte in oracle.finalize() { + use std::fmt::Write; + let _ = write!(expected_old, "{byte:02x}"); + } + let original = + optimized_execution_digest("sanitized-bound-mode", Some(RANKED_EXPERT_PROFILE_SHA)); + assert_eq!(original, expected_old); + let queued = queued_owners_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); + assert_ne!(queued, original); + assert_ne!( + queued, + optimized_execution_digest("sanitized-bound-mode", None) + ); + assert_ne!( + queued, + queued_owners_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA) + ); + assert_ne!( + queued, + queued_owners_execution_digest("sanitized-bound-mode", "different-profile") + ); + assert_ne!(QUEUED_OWNERS_EXECUTION, OPTIMIZED_EXECUTION); +} + +fn native_config() -> RuntimeConfig { + RuntimeConfig { + load_config_version: LOAD_CONFIG_VERSION, + inference_mode: InferenceMode::Native, + gpu_memory_limit_bytes: None, + allow_experimental: false, + } +} +fn request() -> GenerationRequest { + GenerationRequest { + request_id: "synthetic-1".into(), + prompt: "x".into(), + max_output_tokens: 1, + temperature_milli: 0, + sampling: Default::default(), + } +} +#[test] +fn explicit_kar_selection_requires_source_and_binds_actual_digests() { + let model = pinned_model_descriptor(); + let mut requested = native_config(); + // Availability/permission alone never selects KAR. + requested.allow_experimental = true; + assert!(validate_load(&model, &requested).is_ok()); + assert!(validate_kar_selection(&requested, false).is_ok()); + requested.inference_mode = InferenceMode::ExperimentalKarPle { + profile_id: KAR_PROFILE.into(), + }; + assert!(validate_load(&model, &requested).is_ok()); + assert_eq!( + validate_kar_selection(&requested, false).unwrap_err().code, + ErrorCode::UnsupportedModel + ); + assert!(validate_kar_selection(&requested, true).is_ok()); + requested.allow_experimental = false; + assert!(validate_load(&model, &requested).is_err()); + requested.allow_experimental = true; + requested.inference_mode = InferenceMode::ExperimentalKarPle { + profile_id: "wrong".into(), + }; + assert!(validate_load(&model, &requested).is_err()); + let digest = kar_mode_digest(&[1; 32], &[2; 32]); + assert_ne!(digest, MODE_DIGEST); + assert_ne!(digest, kar_mode_digest(&[2; 32], &[1; 32])); + assert_ne!(digest, kar_mode_digest(&[1; 32], &[3; 32])); + let mut loaded = LoadedModel { + handle: "synthetic-kar".into(), + descriptor: model, + load_config_version: LOAD_CONFIG_VERSION, + effective_mode: InferenceMode::ExperimentalKarPle { + profile_id: KAR_PROFILE.into(), + }, + mode_identity_digest: digest, + }; + assert!(validate_handle(&loaded, None).is_ok()); + loaded.mode_identity_digest = "sha256:bad".into(); + assert!(validate_handle(&loaded, None).is_err()); +} + +#[test] +fn configured_context_admission_preserves_verified_position_identity() { + let constants = InputConstants::test_fixture(); + let model_bound = Dimension::new(u64::from(constants.context_length())).unwrap(); + let configured_bound = Dimension::new(128).unwrap(); + for value in [0, 127] { + let position = native_position(&constants, 128, value).unwrap(); + assert_eq!(position, Position::new(value as u64, model_bound).unwrap()); + assert_ne!( + position, + Position::new(value as u64, configured_bound).unwrap() + ); + } + assert_eq!( + native_position(&constants, 128, 128).unwrap_err().code, + ErrorCode::ResourceExhausted + ); + assert!(native_position(&constants, 0, 0).is_err()); + assert!(native_position(&constants, constants.context_length() + 1, 0).is_err()); +} + +#[test] +fn fixed_identity_and_native_refusal_precede_artifact_access() { + let model = pinned_model_descriptor(); + assert_eq!(model.artifact_digest, MODEL_DIGEST); + assert!(validate_load(&model, &native_config()).is_ok()); + let mut config = native_config(); + config.allow_experimental = true; + assert!(validate_load(&model, &config).is_ok()); + config.inference_mode = InferenceMode::ExperimentalKarPle { + profile_id: "synthetic".into(), + }; + assert_eq!( + validate_load(&model, &config).unwrap_err().code, + ErrorCode::UnsupportedModel + ); + let mut loaded = LoadedModel { + handle: "synthetic-handle".into(), + descriptor: model.clone(), + load_config_version: LOAD_CONFIG_VERSION, + effective_mode: InferenceMode::Native, + mode_identity_digest: MODE_DIGEST.into(), + }; + assert!(validate_handle(&loaded, None).is_ok()); + // A KAR-expert Native Load publishes the source-bound digest, never the + // plain Native one; each owner accepts only its own. + let kar_native = kar_expert_mode_digest(MODE_DIGEST, &[7; 32]); + assert_ne!(kar_native, MODE_DIGEST); + assert!(validate_handle(&loaded, Some(&kar_native)).is_err()); + loaded.mode_identity_digest = kar_native.clone(); + assert!(validate_handle(&loaded, Some(&kar_native)).is_ok()); + assert!(validate_handle(&loaded, None).is_err()); + assert!( + validate_handle( + &loaded, + Some(&kar_expert_mode_digest(MODE_DIGEST, &[8; 32])) + ) + .is_err() + ); + loaded.mode_identity_digest = MODE_DIGEST.into(); + // The cold KAR archive hash needs the long budget even in Native mode. + assert_eq!( + load_reply_timeout(&InferenceMode::Native, false), + REPLY_TIMEOUT + ); + assert_eq!( + load_reply_timeout(&InferenceMode::Native, true), + KAR_LOAD_REPLY_TIMEOUT + ); + loaded.handle = "x".repeat(129); + assert!(validate_handle(&loaded, None).is_err()); + let mut wrong = model; + wrong.artifact_digest = SHARD0.into(); + assert!(validate_load(&wrong, &native_config()).is_err()); +} +#[test] +fn request_caps_are_checked_before_acceptance() { + let mut r = request(); + assert!(validate_request(&r).is_ok()); + r.max_output_tokens = OUTPUT_LIMIT + 1; + assert!(validate_request(&r).is_err()); + r.max_output_tokens = 1; + r.temperature_milli = 2001; + assert!(validate_request(&r).is_err()); + r.temperature_milli = 700; + assert!(validate_request(&r).is_ok()); + r.temperature_milli = 0; + r.prompt = "x".repeat(PROMPT_LIMIT + 1); + assert!(validate_request(&r).is_err()); +} +#[test] +fn sampling_requests_are_planned_instead_of_refused() { + let mut r = request(); + // plain greedy: no sampler, the ordinary compact path + assert!(matches!(request_sampler(&r, 5), Ok(None))); + // temperature: a sampler with the request's seed or the supplied entropy + r.temperature_milli = 700; + r.sampling.top_p_micro = Some(950_000); + r.sampling.top_k = Some(40); + let p = request_sampler(&r, 5).unwrap().expect("sampler"); + assert!(!p.greedy && p.seed == 5 && p.top_k == 40 && p.counter == 0); + r.sampling.seed = Some(77); + assert_eq!(request_sampler(&r, 5).unwrap().unwrap().seed, 77); + // greedy plus a penalty still needs the penalised argmax + r.temperature_milli = 0; + r.sampling = Default::default(); + r.sampling.presence_penalty_micro = Some(500_000); + let p = request_sampler(&r, 5).unwrap().expect("penalised greedy"); + assert!(p.greedy && p.penalty_last_n == 64); + // out-of-contract fields are refused before acceptance + for bad in [ + |r: &mut GenerationRequest| r.sampling.top_p_micro = Some(1_000_001), + |r: &mut GenerationRequest| r.sampling.repetition_penalty_micro = Some(0), + |r: &mut GenerationRequest| r.sampling.min_p_micro = Some(2_000_000), + |r: &mut GenerationRequest| r.sampling.frequency_penalty_micro = Some(3_000_000), + ] { + let mut r = request(); + bad(&mut r); + assert!(validate_request(&r).is_err()); + } +} +#[test] +fn utf8_split_tokens_publish_only_complete_prefix() { + let mut pending = Utf8Pending::default(); + assert_eq!(pending.push(&[b'a', 0xf0]).unwrap(), Some("a".into())); + assert!(pending.finish().is_err()); + assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None); + assert_eq!(pending.push(&[0x80]).unwrap(), Some("😀".into())); + assert!(pending.finish().is_ok()); + assert!(pending.push(&[0xff]).is_err()); +} +#[test] +fn utf8_length_replaces_incomplete_unicode_suffix_once() { + for suffix in [&[0xe2][..], &[0xf0, 0x9f, 0x98][..]] { + let mut pending = Utf8Pending::default(); + let mut deltas = vec![pending.push(b"a").unwrap().unwrap()]; + assert_eq!(pending.push(suffix).unwrap(), None); + assert!( + pending + .finish_length(|text| { + deltas.push(text); + Ok(()) + }) + .is_ok() + ); + let mut original = b"a".to_vec(); + original.extend_from_slice(suffix); + assert_eq!(deltas.concat(), String::from_utf8_lossy(&original)); + assert!(pending.finish().is_ok()); + assert!( + pending + .finish_length(|_| panic!("completed suffix emitted twice")) + .is_ok() + ); + } +} +#[test] +fn utf8_length_preserves_completed_split_unicode() { + let mut pending = Utf8Pending::default(); + let first = pending.push(&[b'a', 0xf0]).unwrap().unwrap(); + assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None); + let last = pending.push(&[0x80]).unwrap().unwrap(); + assert!( + pending + .finish_length(|_| panic!("complete Unicode emitted a replacement")) + .is_ok() + ); + assert_eq!(first + &last, "a😀"); + assert!(pending.finish().is_ok()); +} +#[test] +fn utf8_stop_keeps_incomplete_unicode_refusal() { + for suffix in [&[0xe2][..], &[0xf0, 0x9f, 0x98][..]] { + let mut pending = Utf8Pending::default(); + assert_eq!(pending.push(suffix).unwrap(), None); + assert!(pending.finish().is_err()); + assert_eq!(pending.0, suffix); + } +} +#[test] +fn utf8_interior_invalid_remains_refused_at_push() { + let mut pending = Utf8Pending::default(); + assert!(pending.push(&[b'a', 0xff, b'b']).is_err()); + assert!( + pending + .finish_length(|_| panic!("invalid interior bytes emitted a replacement")) + .is_err() + ); +} +#[test] +fn utf8_frame_bound_refuses_before_growth() { + let mut pending = Utf8Pending::default(); + assert!(pending.push(&vec![b'x'; FRAME_LIMIT + 1]).is_err()); + assert!(pending.0.is_empty()); +} +#[test] +fn cancel_is_independent_of_full_control_queue() { + let (tx, _rx) = mpsc::sync_channel(1); + let cancel = Arc::new(AtomicBool::new(false)); + let shared = Arc::new(Shared { + ready: AtomicBool::new(true), + shutdown: AtomicBool::new(false), + active: Mutex::new(Some(Active { + id: "synthetic-1".into(), + cancel: Arc::clone(&cancel), + })), + }); + let mut proxy = Proxy { + tx, + shared, + seen: RecentIds::default(), + kar_configured: false, + mtp_configured: false, + kar_experts_configured: false, + kar_expert_native_digest: None, + execution: EvaluationExecution::Native, + optimized_execution: false, + queued_owners: false, + streamed_spill: false, + retained_scratch: false, + resident_owners: false, + adaptive_slots: false, + original_serve: false, + }; + let (reply, _) = mpsc::sync_channel(1); + proxy + .send(Command::Load( + pinned_model_descriptor(), + native_config(), + reply, + )) + .unwrap(); + proxy.cancel("synthetic-1").unwrap(); + assert!(cancel.load(Ordering::Acquire)); + assert!(proxy.cancel("unknown").is_err()); + assert!(proxy.idle().is_err()); +} +#[test] +fn prompt_context_admission_is_before_forward() { + let tokenizer = + Tokenizer::from_vocabulary("gpt2", "qwen35", vec!["x".into()], vec![], None).unwrap(); + assert_eq!(prepare_prompt(&tokenizer, &request(), 2).unwrap(), vec![0]); + assert!(prepare_prompt(&tokenizer, &request(), 1).is_err()); + let mut r = request(); + r.prompt.clear(); + assert!(prepare_prompt(&tokenizer, &r, 2).is_err()); +} +#[test] +fn marked_control_token_text_is_encoded_as_text_and_the_templates_own_literals_stay_special() { + let (alphabet, _) = leleka_tokenizer::byte_alphabet(); + let mut tokens: Vec = alphabet.iter().map(char::to_string).collect(); + tokens.push("".into()); + tokens.push("".into()); + let mut types = vec![1u32; 256]; + types.extend([4, 4]); + let tokenizer = + Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, vec![], Some(types)).unwrap(); + let mut r = request(); + r.max_output_tokens = 1; + // The template's own `` and a quoted `` in the message. + r.prompt = format!("\n{}", tokenizer.marks().mark("a")); + let ids = prepare_prompt(&tokenizer, &r, 100).unwrap(); + assert_eq!(ids.iter().filter(|&&id| id == 256).count(), 1); + assert_eq!(ids.iter().filter(|&&id| id == 257).count(), 0); + assert_eq!(tokenizer.decode(&ids).unwrap(), "\na"); + // A prompt without marks is encoded as before. + r.prompt = "\na".into(); + assert_eq!( + prepare_prompt(&tokenizer, &r, 100).unwrap(), + tokenizer.encode(&r.prompt, true).unwrap() + ); +} diff --git a/crates/leleka-runtime/src/backend/utf8.rs b/crates/leleka-runtime/src/backend/utf8.rs new file mode 100644 index 00000000..ae8055db --- /dev/null +++ b/crates/leleka-runtime/src/backend/utf8.rs @@ -0,0 +1,74 @@ +//! Incremental UTF-8 publication of generated tokens and the terminal event. +use super::*; + +#[derive(Default)] +pub(super) struct Utf8Pending(pub(super) Vec); +impl Utf8Pending { + pub(super) fn push(&mut self, bytes: &[u8]) -> Result, BackendError> { + if self + .0 + .len() + .checked_add(bytes.len()) + .is_none_or(|len| len > FRAME_LIMIT) + { + return Err(exhausted("decoded token exceeds output frame limit")); + } + self.0 + .try_reserve(bytes.len()) + .map_err(|_| exhausted("token decoding allocation failed"))?; + self.0.extend_from_slice(bytes); + let valid = match std::str::from_utf8(&self.0) { + Ok(_) => self.0.len(), + Err(error) if error.error_len().is_none() => error.valid_up_to(), + Err(_) => return Err(unavailable("native token contains invalid UTF8")), + }; + if valid == 0 { + return Ok(None); + } + let text = std::str::from_utf8(&self.0[..valid]) + .map_err(|_| unavailable("native UTF8 prefix invalid"))? + .to_owned(); + self.0.drain(..valid); + Ok(Some(text)) + } + /// Length may cut a valid code point between tokens. Match the existing + /// tokenizer/daemon terminal replacement without advancing model state. + pub(super) fn finish_length( + &mut self, + emit: impl FnOnce(String) -> Result<(), GenerationFailure>, + ) -> Result<(), GenerationFailure> { + if self.0.is_empty() { + return Ok(()); + } + match std::str::from_utf8(&self.0) { + Err(error) if error.error_len().is_none() && error.valid_up_to() == 0 => {} + _ => return Err(unavailable("native token contains invalid UTF8").into()), + } + emit("\u{fffd}".to_owned())?; + self.0.clear(); + Ok(()) + } + pub(super) fn finish(&self) -> Result<(), BackendError> { + if self.0.is_empty() { + Ok(()) + } else { + Err(unavailable("generation ended with incomplete UTF8")) + } + } +} +pub(super) fn emit_terminal( + sink: &GenerationSink, + terminal: GenerationTerminal, +) -> Result<(), ContractError> { + let start = Instant::now(); + loop { + match sink.try_emit(GenerationEvent::Terminal(terminal.clone())) { + Err(ContractError::GenerationBackpressure) + if start.elapsed() < BACKPRESSURE_TIMEOUT => + { + thread::sleep(Duration::from_millis(5)) + } + result => return result, + } + } +} diff --git a/crates/leleka-runtime/src/backend/validate.rs b/crates/leleka-runtime/src/backend/validate.rs new file mode 100644 index 00000000..a82c026d --- /dev/null +++ b/crates/leleka-runtime/src/backend/validate.rs @@ -0,0 +1,115 @@ +//! Admission checks of loads, handles and generation requests. +use super::*; + +pub(super) fn validate_load( + model: &ModelDescriptor, + config: &RuntimeConfig, +) -> Result<(), BackendError> { + config + .validate() + .map_err(|_| invalid("invalid load configuration"))?; + if model != &pinned_model_descriptor() { + return Err(unsupported("unsupported pinned model identity")); + } + match &config.inference_mode { + InferenceMode::Native => {} + InferenceMode::ExperimentalKarPle { profile_id } if profile_id == KAR_PROFILE => {} + InferenceMode::ExperimentalMtp { profile_id } + if profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE => {} + _ => return Err(unsupported("experimental mode is not supported")), + } + Ok(()) +} +pub(super) fn load_reply_timeout(mode: &InferenceMode, kar_experts_configured: bool) -> Duration { + if requires_kar(mode) + || kar_experts_configured + || matches!(mode, InferenceMode::ExperimentalMtp { .. }) + { + KAR_LOAD_REPLY_TIMEOUT + } else { + REPLY_TIMEOUT + } +} +pub(super) fn validate_kar_selection( + config: &RuntimeConfig, + source_present: bool, +) -> Result<(), BackendError> { + if requires_kar(&config.inference_mode) && !source_present { + return Err(unsupported("KAR PLE operator source is absent")); + } + Ok(()) +} + +pub(super) fn requires_kar(mode: &InferenceMode) -> bool { + matches!(mode, InferenceMode::ExperimentalKarPle { .. }) + || matches!(mode, InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE) +} +pub(super) fn validate_mtp_selection( + config: &RuntimeConfig, + present: bool, +) -> Result<(), BackendError> { + if matches!(config.inference_mode, InferenceMode::ExperimentalMtp { .. }) && !present { + return Err(unsupported("MTP operator source is absent")); + } + Ok(()) +} +pub(super) fn validate_handle( + model: &LoadedModel, + kar_expert_native_digest: Option<&str>, +) -> Result<(), BackendError> { + if model.handle.is_empty() + || model.handle.len() > 128 + || model.handle.chars().any(char::is_control) + || model.descriptor != pinned_model_descriptor() + || model.load_config_version != LOAD_CONFIG_VERSION + || !match &model.effective_mode { + // With a KAR expert source the Native handle carries the source + // identity; it must equal the digest this owner would publish. + InferenceMode::Native => { + model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST) + } + InferenceMode::ExperimentalKarPle { profile_id } => { + profile_id == KAR_PROFILE + && model + .mode_identity_digest + .strip_prefix("sha256:") + .is_some_and(|hex| { + hex.len() == 64 + && hex + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + }) + } + InferenceMode::ExperimentalMtp { profile_id } => { + (profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE) + && model + .mode_identity_digest + .strip_prefix("sha256:") + .is_some_and(|hex| { + hex.len() == 64 + && hex + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + }) + } + _ => false, + } + { + return Err(invalid("invalid loaded model identity")); + } + Ok(()) +} + +pub(super) fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> { + if request.request_id.is_empty() + || request.request_id.len() > 128 + || request.request_id.chars().any(char::is_control) + || request.prompt.len() > PROMPT_LIMIT + || request.max_output_tokens == 0 + || request.max_output_tokens > OUTPUT_LIMIT + || request_sampler(request, 1).is_err() + { + return Err(invalid("unsupported generation request")); + } + Ok(()) +}