From 79765ac804bc7b8dacc36b75be5bb7e1f8045652 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 24 Nov 2026 00:59:18 +0100 Subject: [PATCH 1/5] engine: the serving context is a value from the composition root, not a process cell (STRA-338) ServingContext::new(cells, rope) replaces configure_serving_context and the process cell of cuda-model; serving_context() is gone. The backend spawn makes the value once (serving:: admit_context_tokens) and hands it down: OwnerThread -> LoadEnv -> ServedArtifact (the model binding captures it, ModelBinding::serving()) and Device::create_context_serving (every Context of the Load). Device::create_context stays the trained default for tools and tests. contract::serving_cells, the QSA index context()/device_peak() reads, the native-resources size read, the memory governor, the stack config and the RoPE constants read the binding or the Context instead; the stack open refuses a binding and a Context made for different serving contexts. The two laptop tools build their own value. Five process-global exceptions deleted (cuda-model serving_context, engine contract, binding_identity, qsa_index/context, qsa_native_resources). --- architecture.json | 5 -- .../cuda-driver/src/bringup_trace_enabled.rs | 5 +- crates/cuda-driver/src/root_exports.rs | 1 - .../preflight_00_sealed_asset_report.rs | 3 +- crates/cuda-model/src/serving_context.rs | 60 ++++++--------- crates/engine-qwen35-cuda/src/backend.rs | 4 +- crates/engine-qwen35-cuda/src/backend/load.rs | 2 + .../src/backend/load_admit.rs | 6 +- .../src/backend/load_bind.rs | 8 +- .../src/backend/load_cuda.rs | 15 ++-- .../src/backend/load_sources.rs | 14 ++-- .../src/backend/original_serve_laptop.rs | 34 +++++---- .../original_serve_memory_smoke/load.rs | 1 + .../original_serve_prefix_smoke/run.rs | 32 ++++---- .../engine-qwen35-cuda/src/backend/owner.rs | 3 + .../engine-qwen35-cuda/src/backend/spawn.rs | 13 ++-- .../engine-qwen35-cuda/src/memory_governor.rs | 5 +- .../src/model_binding/weight_binding.rs | 6 ++ .../weight_binding/binding_identity.rs | 6 +- .../weight_binding/model_binding.rs | 28 ++++--- .../weight_binding/served_artifact.rs | 24 ++++++ .../src/qwen_forward/contract.rs | 10 --- .../src/qwen_forward/original_serve_config.rs | 5 +- .../original_serve_config/tests.rs | 2 +- .../lifecycle_fake/stack.rs | 2 +- .../original_serve_stack/stack_config.rs | 18 +++-- .../stack_phases/open_phase_steps.rs | 9 ++- .../original_serve_stack_memory_classes.rs | 2 +- .../original_serve_stack_open/assemble.rs | 2 +- .../original_serve_stack/tests.rs | 28 ++++--- .../src/qwen_forward/qsa_attention.rs | 6 +- .../src/qwen_forward/qsa_index.rs | 19 ++--- .../src/qwen_forward/qsa_index/context.rs | 23 +++--- .../qwen_forward/qsa_index/index_kernels.rs | 6 +- .../qwen_forward/qsa_index/index_resident.rs | 13 ++-- .../qsa_index/index_resident/max_rows.rs | 34 ++++----- .../qwen_forward/qsa_index/native_state.rs | 4 +- .../qwen_forward/qsa_index/qsa_index_stage.rs | 8 +- .../src/qwen_forward/qsa_index/qsa_pending.rs | 4 +- .../qwen_forward/qsa_index/qsa_projection.rs | 6 +- .../qwen_forward/qsa_index/selected_cache.rs | 5 +- .../qwen_forward/qsa_index/validate_ids.rs | 7 +- .../src/qwen_forward/qsa_native_resources.rs | 11 ++- crates/engine-qwen35-cuda/src/serving.rs | 75 +++++++------------ 44 files changed, 291 insertions(+), 283 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/model_binding/weight_binding/served_artifact.rs diff --git a/architecture.json b/architecture.json index b9af636f..f5da92d3 100644 --- a/architecture.json +++ b/architecture.json @@ -53,7 +53,6 @@ "exceptions": [ {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "env-read", "reason": "EnvSwitch is the one reader of the operator environment in this crate: it reads one named variable on the first get() and applies a typed rule"}, {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "the OnceLock inside EnvSwitch caches the switch position for the process life (an immutable operator setting; a hot path pays one atomic load)"}, - {"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context is fixed once at engine start (configure_serving_context); the driver copies it into each Context when the Context is created and every kernel geometry reads it from the Context, so this cell is read at one place (create_context). The engine composition still reads it for the bind-time cell count; handing the value down from the config is the follow-up of S13. The resident KV window is not here: it belongs to the driver Context"}, {"crate": "leleka-cpu-worker", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, {"crate": "leleka-tokenizer", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, {"crate": "leleka-gptoss-npu", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, @@ -175,13 +174,9 @@ {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/binding_identity.rs", "ratchet": "process-global", "reason": "the model binding captures the serving context in cells once, when it is made (the driver's context is configured before the engine binds a model); the validators read the bound from the binding, not from the process"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/contract.rs", "ratchet": "process-global", "reason": "the engine's one reader of the driver's serving context (cells): contract::serving_cells() is called where a model is bound (InputConstants::from_artifact) and by sizing code that has no binding; every validator takes the bound from the binding"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_index/context.rs", "ratchet": "process-global", "reason": "the QSA index owner bounds positions and sizes its pages by the process geometry in about ten places (validate_ids, pending rows, native state, max rows, index image sizes) that are reached without a model binding; carrying the bound in QsaOwner is the next step. Same value as the driver's serving context, read through the engine's contract::serving_cells"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_native_resources.rs", "ratchet": "process-global", "reason": "the byte sizes of a layer's host image come from the process geometry (QsaGeometry over the serving cells) when the resource set is built, before any binding is passed in; they follow the QSA owner's bound (see qsa_index/context.rs)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, {"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: stall span of one timed drain, reported by the prefill stall trace"}, diff --git a/crates/cuda-driver/src/bringup_trace_enabled.rs b/crates/cuda-driver/src/bringup_trace_enabled.rs index 881a122a..0d411f27 100644 --- a/crates/cuda-driver/src/bringup_trace_enabled.rs +++ b/crates/cuda-driver/src/bringup_trace_enabled.rs @@ -51,9 +51,10 @@ impl Driver { } } impl<'driver> Device<'driver> { - /// A context for the serving context the process configured (the trained default when none was). + /// A context of the trained serving context (262144 cells, identity RoPE); the serving engine creates its + /// contexts with [`Device::create_context_serving`]. pub fn create_context(&self, byte_budget: usize) -> Result> { - self.create_context_serving(byte_budget, crate::serving_context::serving_context()) + self.create_context_serving(byte_budget, ServingContext::trained()) } /// A context whose buffers are sized and whose rotating kernels are parameterized for `serving`. pub fn create_context_serving(&self, byte_budget: usize, serving: ServingContext) -> Result> { diff --git a/crates/cuda-driver/src/root_exports.rs b/crates/cuda-driver/src/root_exports.rs index a7165607..6c7df95a 100644 --- a/crates/cuda-driver/src/root_exports.rs +++ b/crates/cuda-driver/src/root_exports.rs @@ -63,7 +63,6 @@ pub use leleka_cuda_model::original_mtp_loader::{ }; pub use leleka_cuda_model::serving_context::{ KV_RESIDENT_DEFAULT_CELLS, KV_RESIDENT_MIN_CELLS, MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS, - configure_serving_context, serving_context, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs index c2f4019e..50a4b8e8 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/preflight_00_sealed_asset_report.rs @@ -23,8 +23,7 @@ fn preflight_00_sealed_asset_report() { unsealed_window_assets() ); eprintln!("PREFLIGHT UNBOUND_PRODUCERS={UNBOUND_PRODUCERS:?}"); - let serving = serving_context(); - eprintln!("PREFLIGHT serving_cells={}", serving.geometry.cells()); + eprintln!("PREFLIGHT serving_cells={}", ServingContext::trained().geometry.cells()); } /// Device limits the sealed kernels assume (compute capability 12, shared-memory opt-in, SM count). diff --git a/crates/cuda-model/src/serving_context.rs b/crates/cuda-model/src/serving_context.rs index f043e18e..a87c61e9 100644 --- a/crates/cuda-model/src/serving_context.rs +++ b/crates/cuda-model/src/serving_context.rs @@ -1,18 +1,18 @@ -//! Process-wide serving context: the cell count every context-linear buffer is sized from, and the RoPE -//! scaling constants the analytic rotation kernels take as arguments. +//! The serving context: the cell count every context-linear buffer is sized from, and the RoPE scaling constants the +//! analytic rotation kernels take as arguments. //! //! This mirrors the Original, where `rope_scaling_set()` is "called once from the engine's startup ... before //! any graph exists" because the K already in the cache is stored post-RoPE and "a mid-run change would mix two //! scalings in one cache". The same holds for the cell count: sessions, host mappings and page tables are -//! sized from it. Call [`configure_serving_context`] once before creating any `Context` user; an -//! unconfigured process behaves exactly as before (`262144` cells, identity RoPE). +//! sized from it. The value is made once at the composition root ([`ServingContext::new`]) and handed down: the +//! model binding captures it, and every `Context` is created for it (`Device::create_context_serving`). There is no +//! process cell; [`ServingContext::trained`] (`262144` cells, identity RoPE) is the default of a bare `Context`. use crate::{Error, Result}; use leleka_context::{ geometry::{QsaGeometry, TRAINED_CELLS}, rope_scaling::{RopeKernelArgs, RopeScaling}, }; -use std::sync::OnceLock; /// The context the model was trained over, in cells. pub const TRAINED_CONTEXT_CELLS: usize = TRAINED_CELLS; @@ -21,7 +21,7 @@ pub const MAX_CONTEXT_CELLS: usize = leleka_context::geometry::MAX_CELLS; /// Rotated dimensions of the QSA layers (`QsaShapes::n_rot`). const N_ROT: i32 = 64; -/// What [`configure_serving_context`] fixed. +/// What one serving configuration fixed: made by [`ServingContext::new`] or [`ServingContext::trained`]. #[derive(Clone, Copy, Debug, PartialEq)] pub struct ServingContext { pub geometry: QsaGeometry, @@ -30,7 +30,18 @@ pub struct ServingContext { } impl ServingContext { - /// The unconfigured default: `262144` cells and the identity RoPE. + /// The serving context of `cells` and `rope`. `cells` must be a positive multiple of 4 no larger than + /// [`MAX_CONTEXT_CELLS`], the scaling must satisfy `rope_scaling_invalid`, and a context past the trained one + /// requires an active scaling (the stock angles are out of spec there, `setup.py`). + pub fn new(cells: usize, rope: &RopeScaling) -> Result { + let geometry = QsaGeometry::new(cells).map_err(|_| Error::InvalidDriverValue("serving context cell count"))?; + rope.validate().map_err(|_| Error::InvalidDriverValue("serving context rope scaling"))?; + if cells > TRAINED_CELLS && rope.kind == leleka_context::rope_scaling::RopeScalingType::None { + return Err(Error::InvalidDriverValue("contexts past the trained one need RoPE scaling")); + } + Ok(Self { geometry, rope: *rope, rope_args: rope.kernel_args(N_ROT) }) + } + /// The default: `262144` cells and the identity RoPE. pub fn trained() -> Self { Self { geometry: QsaGeometry::TRAINED, rope: RopeScaling::default(), rope_args: RopeKernelArgs::default() } } @@ -40,33 +51,6 @@ impl ServingContext { } } -static SERVING: OnceLock = OnceLock::new(); - -/// Fix the serving context for this process. The first call wins; a later call must request the same values. -/// `cells` must be a positive multiple of 4 no larger than [`MAX_CONTEXT_CELLS`], the scaling must satisfy -/// `rope_scaling_invalid`, and a context past the trained one requires an active scaling (the stock angles are -/// out of spec there, `setup.py`). -pub fn configure_serving_context(cells: usize, rope: &RopeScaling) -> Result<()> { - let geometry = QsaGeometry::new(cells).map_err(|_| Error::InvalidDriverValue("serving context cell count"))?; - rope.validate().map_err(|_| Error::InvalidDriverValue("serving context rope scaling"))?; - if cells > TRAINED_CELLS && rope.kind == leleka_context::rope_scaling::RopeScalingType::None { - return Err(Error::InvalidDriverValue("contexts past the trained one need RoPE scaling")); - } - let wanted = ServingContext { geometry, rope: *rope, rope_args: rope.kernel_args(N_ROT) }; - let got = SERVING.get_or_init(|| wanted); - if *got == wanted { - Ok(()) - } else { - Err(Error::InvalidDriverValue("serving context already configured differently")) - } -} - -/// The configured serving context, or the trained default when none was configured. -#[inline] -pub fn serving_context() -> ServingContext { - SERVING.get().copied().unwrap_or_else(ServingContext::trained) -} - /// The resident KV window (cells per QSA layer kept in VRAM, `--kv-resident`) of the default configuration. pub const KV_RESIDENT_DEFAULT_CELLS: usize = leleka_context::geometry::KV_RESIDENT_DEFAULT_CELLS; /// `qsa_kv_resident_min()`. @@ -125,10 +109,10 @@ mod tests { #[test] fn refuses_past_trained_without_scaling_and_bad_counts() { - assert!(configure_serving_context(524_288, &RopeScaling::default()).is_err()); - assert!(configure_serving_context(3, &RopeScaling::default()).is_err()); - assert!(configure_serving_context(0, &RopeScaling::default()).is_err()); + assert!(ServingContext::new(524_288, &RopeScaling::default()).is_err()); + assert!(ServingContext::new(3, &RopeScaling::default()).is_err()); + assert!(ServingContext::new(0, &RopeScaling::default()).is_err()); let bad = RopeScaling { kind: RopeScalingType::YaRN, factor: 0.5, ..RopeScaling::default() }; - assert!(configure_serving_context(524_288, &bad).is_err()); + assert!(ServingContext::new(524_288, &bad).is_err()); } } diff --git a/crates/engine-qwen35-cuda/src/backend.rs b/crates/engine-qwen35-cuda/src/backend.rs index 6a0cb522..00aabfc2 100644 --- a/crates/engine-qwen35-cuda/src/backend.rs +++ b/crates/engine-qwen35-cuda/src/backend.rs @@ -11,7 +11,7 @@ pub use original_serve::{ ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions, PrefixTail, }; mod measurement; -use crate::model_binding::weight_binding::{InputBindingError, ModelBinding}; +use crate::model_binding::weight_binding::{InputBindingError, ModelBinding, ServedArtifact}; // What only the preview serve path (generation loop, weight caches, resident conversations) works with. #[cfg(feature = "preview-path")] use crate::{ @@ -34,7 +34,7 @@ use leleka_backend_api::{ InferenceMode, LOAD_CONFIG_VERSION, LoadedModel, ModelDescriptor, RecentIds, RuntimeConfig, SupportedModelTuple, Usage, }; -use leleka_cuda_driver::Driver; +use leleka_cuda_driver::{Driver, ServingContext}; use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; use leleka_obs::time::{Clock, SystemClock}; use leleka_tokenizer::Tokenizer; diff --git a/crates/engine-qwen35-cuda/src/backend/load.rs b/crates/engine-qwen35-cuda/src/backend/load.rs index 685ab65c..9e5119c8 100644 --- a/crates/engine-qwen35-cuda/src/backend/load.rs +++ b/crates/engine-qwen35-cuda/src/backend/load.rs @@ -13,6 +13,8 @@ use leleka_cuda_driver::Context; #[derive(Clone, Copy)] pub(super) struct LoadEnv<'a> { pub(super) config: &'a NativeBackendConfig, + /// The serving context of the backend: the bound of the model binding and the geometry of the CUDA context. + pub(super) serving: leleka_cuda_driver::ServingContext, pub(super) rx: &'a Receiver, pub(super) shared: &'a Shared, pub(super) reply: &'a Reply, diff --git a/crates/engine-qwen35-cuda/src/backend/load_admit.rs b/crates/engine-qwen35-cuda/src/backend/load_admit.rs index 3446c81c..0de01268 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_admit.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_admit.rs @@ -173,7 +173,7 @@ pub(super) fn start_governor(env: &LoadEnv<'_>) -> Result) -> Result #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn governor_args( - config: &NativeBackendConfig, + env: &LoadEnv<'_>, options: &original_serve::OriginalServeOptions, ) -> crate::memory_governor::StartArgs { + let config = env.config; let inherited = config.kar_ple_inherited.as_ref(); crate::memory_governor::StartArgs { + geometry: env.serving.geometry, kv_resident: options.kv_resident.unwrap_or(leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS), gpu_budget_bytes: config.gpu_budget_bytes, kar_file_backed: inherited.map(InheritedKarArchive::file_backed), diff --git a/crates/engine-qwen35-cuda/src/backend/load_bind.rs b/crates/engine-qwen35-cuda/src/backend/load_bind.rs index f3e44a26..389c2d0a 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_bind.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_bind.rs @@ -1,9 +1,9 @@ //! The first half of a Load, before any CUDA object exists: sources, binding, identity, the expert bank. use super::{ BackendError, Identity, InputBindingError, LoadEnv, LoadPhase, ModelBinding, ModelDescriptor, PolicyFlags, - RuntimeConfig, Tokenizer, admit_kar_experts, bind_artifact, bind_selected, check_mtp_context, check_not_cancelled, - effective_identity, exhausted, invalid, load_failure, open_sources, original_serve, policy_digest, read_profile, - unavailable, + RuntimeConfig, ServedArtifact, Tokenizer, admit_kar_experts, bind_artifact, bind_selected, check_mtp_context, + check_not_cancelled, effective_identity, exhausted, invalid, load_failure, open_sources, original_serve, + policy_digest, read_profile, unavailable, }; use leleka_model_format::qwen4exp::ProvisionalExpertSource; @@ -41,7 +41,7 @@ fn bind_providers( let opened = open_sources(env, requested, flags)?; let parts = bind_artifact(opened.shard0, opened.shard1)?; check_mtp_context(env.config, requested)?; - let selected = bind_selected(env.config, requested, parts.artifact, opened.kar)?; + let selected = bind_selected(env.config, requested, ServedArtifact::new(parts.artifact, env.serving), opened.kar)?; let binding = admit_kar_experts(env, selected)?; let bound = Bound { binding, tokenizer: parts.tokenizer, eos: parts.eos, ranked_profile: None, flags }; Ok((bound, opened.capture)) diff --git a/crates/engine-qwen35-cuda/src/backend/load_cuda.rs b/crates/engine-qwen35-cuda/src/backend/load_cuda.rs index 18c4668a..7d42b61b 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_cuda.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_cuda.rs @@ -1,8 +1,7 @@ //! The CUDA half of a Load: driver, device context, load-time probes and the hand-over to the Original serve stack. use super::{ - Announcement, BackendError, Bound, Driver, Governed, LoadEnv, LoadPhase, ModelBinding, NativeBackendConfig, Rc, - build_loaded, exhausted, experimental_modes, load_failure, original_serve, probe_experimental, - probe_kar_level_decode, unavailable, + Announcement, BackendError, Bound, Driver, Governed, LoadEnv, LoadPhase, ModelBinding, Rc, build_loaded, exhausted, + experimental_modes, load_failure, original_serve, probe_experimental, probe_kar_level_decode, unavailable, }; use leleka_cuda_driver::Context; @@ -10,16 +9,14 @@ pub(super) fn open_driver() -> Result { Driver::load().map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable"))) } -pub(super) fn open_context<'d>( - config: &NativeBackendConfig, - driver: &'d Driver, -) -> Result>, BackendError> { +pub(super) fn open_context<'d>(env: &LoadEnv<'_>, driver: &'d Driver) -> Result>, BackendError> { + let config = env.config; 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) + .create_context_serving(config.gpu_budget_bytes as usize, env.serving) .map_err(|_| load_failure(LoadPhase::Context, exhausted("native CUDA context unavailable")))?, ); crate::load_clock::lap("cuda_driver_and_context"); @@ -34,7 +31,7 @@ pub(super) fn open_checked_context<'d>( governed: Governed, binding: &ModelBinding, ) -> Result>, BackendError> { - let context = open_context(env.config, driver)?; + let context = open_context(env, driver)?; check_vram(governed, &context, env.config.gpu_budget_bytes)?; if binding.kar_expert_source().is_some() { // Fail at Load, not at the first token, if the KAR level-decode PTX is diff --git a/crates/engine-qwen35-cuda/src/backend/load_sources.rs b/crates/engine-qwen35-cuda/src/backend/load_sources.rs index 5ada236e..c53d4051 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_sources.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_sources.rs @@ -2,8 +2,8 @@ use super::{ BackendError, InferenceMode, InheritedKarArchive, InputBindingError, InputResultKar, KAR_MTP_PROFILE, KarExpertSource, LoadEnv, LoadPhase, ModelBinding, NativeBackendConfig, PolicyFlags, Qwen4ExpArtifact, - RuntimeConfig, SHARD0, SHARD1, Tokenizer, VerifiedGgufFile, VerifiedSources, invalid, kar_mtp_requested, - load_failure, selected_binding_failure, unsupported, verify_sources_parallel, + RuntimeConfig, SHARD0, SHARD1, ServedArtifact, Tokenizer, VerifiedGgufFile, VerifiedSources, invalid, + kar_mtp_requested, load_failure, selected_binding_failure, unsupported, verify_sources_parallel, }; use leleka_model_format::qwen4exp::ProvisionalExpertSource; use leleka_model_format::verify_stamp::VerifyPolicy; @@ -137,7 +137,7 @@ pub(super) fn check_mtp_context(config: &NativeBackendConfig, requested: &Runtim pub(super) fn bind_selected( config: &NativeBackendConfig, requested: &RuntimeConfig, - artifact: Qwen4ExpArtifact, + artifact: ServedArtifact, kar: Option, ) -> Result { let bound = match &requested.inference_mode { @@ -151,7 +151,7 @@ pub(super) fn bind_selected( Ok(binding) } -fn bind_kar_ple(config: &NativeBackendConfig, artifact: Qwen4ExpArtifact) -> Result { +fn bind_kar_ple(config: &NativeBackendConfig, artifact: ServedArtifact) -> Result { if let Some(source) = config.kar_ple_inherited.as_ref() { return Ok(ModelBinding::from_artifact_with_inherited_kar_ple(artifact, source, &config.verification)); } @@ -163,7 +163,7 @@ fn bind_kar_ple(config: &NativeBackendConfig, artifact: Qwen4ExpArtifact) -> Res fn bind_mtp( config: &NativeBackendConfig, profile_id: &str, - artifact: Qwen4ExpArtifact, + artifact: ServedArtifact, kar: Option, ) -> Result { let (source, staging) = config.mtp_source.as_ref().ok_or_else(|| unsupported("MTP operator source is absent"))?; @@ -175,7 +175,7 @@ fn bind_mtp( fn bind_kar_mtp( config: &NativeBackendConfig, - artifact: Qwen4ExpArtifact, + artifact: ServedArtifact, kar: Option, (source, staging): (&Path, &Path), ) -> Result { @@ -194,7 +194,7 @@ fn bind_kar_mtp( /// The archive verified at the same time as the shards when it was, otherwise verified by the binding itself. fn bind_inherited_kar_mtp( - artifact: Qwen4ExpArtifact, + artifact: ServedArtifact, inherited: &InheritedKarArchive, prefetched: Option, (source, staging): (&Path, &Path), diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs index 4447aff2..30a04d33 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs @@ -28,7 +28,8 @@ //! Run: `cargo test -p leleka-engine-qwen35-cuda --features cuda-driver[,sm86] --release -- --ignored --nocapture //! original_serve_laptop_bench`. use super::{ - Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile, + Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, ServedArtifact, + ServingContext, VerifiedGgufFile, }; use crate::qwen_forward::{ original_serve_engine::ServeOutcome, @@ -101,18 +102,19 @@ fn open_inherited() -> InheritedKarArchive { /// The bound model with its expert source loaded; the archive handle stays alive beside it. struct Loaded { binding: ModelBinding, + serving: ServingContext, eos: u32, _inherited: InheritedKarArchive, } /// Bind the pinned artifact to the KAR and MTP inputs, then load the expert source of `LELEKA_LAPTOP_EXPERTS`. -fn bind_laptop(start: std::time::Instant) -> Loaded { +fn bind_laptop(start: std::time::Instant, serving: ServingContext) -> Loaded { let (shard0, shard1) = verify_shards(start); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); let inherited = open_inherited(); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, + ServedArtifact::new(artifact, serving), &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), @@ -126,7 +128,7 @@ fn bind_laptop(start: std::time::Instant) -> Loaded { memory_line() ); load_experts(&mut binding, start); - Loaded { binding, eos, _inherited: inherited } + Loaded { binding, serving, eos, _inherited: inherited } } fn load_experts(binding: &mut ModelBinding, start: std::time::Instant) { @@ -145,14 +147,16 @@ fn load_experts(binding: &mut ModelBinding, start: std::time::Instant) { ); } -/// Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by -/// --max-context). Unscaled RoPE; must precede the model binding (which carries it) and the first CUDA context user. -fn configure_cells() { - if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { - let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); - leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); - eprintln!("LAPTOP config: process geometry {cells} cells (experimental)"); - } +/// Experimental: a serving context of N cells instead of the trained 262144 (the Original sizes its KV by +/// --max-context). Unscaled RoPE; the model binding and the CUDA context are both made for it. +fn laptop_serving() -> ServingContext { + let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") else { + return ServingContext::trained(); + }; + let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); + let serving = ServingContext::new(cells, &Default::default()).expect("serving context refused"); + eprintln!("LAPTOP config: serving context {cells} cells (experimental)"); + serving } /// The cross-session prefix cache of `LELEKA_LAPTOP_PREFIX_MIB` (`auto` or MiB), when set. @@ -266,12 +270,12 @@ fn close_context(context: Rc>) { fn original_serve_laptop_bench() { assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required"); let start = std::time::Instant::now(); - configure_cells(); - let loaded = bind_laptop(start); + let loaded = bind_laptop(start, laptop_serving()); let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); + let context = + Rc::new(device.create_context_serving(budget_gib << 30, loaded.serving).expect("bounded Context unavailable")); let config = laptop_stack_config(); print_config(&config, budget_gib); let mut stack = match OriginalServeStack::open(&loaded.binding, context.as_ref(), Rc::clone(&context), config) { diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs index 8ae35a5d..b507203b 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_memory_smoke/load.rs @@ -90,6 +90,7 @@ fn start_governor( let governor = crate::memory_governor::startup( memory, &crate::memory_governor::StartArgs { + geometry: leleka_context::geometry::QsaGeometry::TRAINED, kv_resident: plan.resident, gpu_budget_bytes: (budget_gib as u64) << 30, kar_file_backed: Some(inherited.file_backed()), diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs index 4436c534..daef7311 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs @@ -6,10 +6,13 @@ use super::{ Qwen4ExpArtifact, Rc, SHARD0, SHARD1, ServeError, Served, StackConfig, Tokenizer, VerifiedGgufFile, dbg_el, env, filler, mem_available_mib, number, required_path, rss_mib, serve_one, text, workload, }; +use crate::model_binding::weight_binding::ServedArtifact; +use leleka_cuda_driver::ServingContext; /// The pinned tokenizer and EOS, the KAR archive and the binding with its expert source. struct Pinned { binding: ModelBinding, + serving: ServingContext, _inherited: InheritedKarArchive, tokenizer: Tokenizer, eos: u32, @@ -48,19 +51,19 @@ fn load_experts(binding: &mut ModelBinding, laptop: bool) { binding.load_resident_expert_source().expect("resident expert source load failed"); } } -/// Experimental: a process geometry of N cells (`LELEKA_LAPTOP_CELLS`). It is fixed before the model is bound, because -/// the binding carries the serving context. -fn configure_laptop_cells() { - if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { - let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); - leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); - eprintln!("PFX config: process geometry {cells} cells (experimental)"); - } +/// Experimental: a serving context of N cells (`LELEKA_LAPTOP_CELLS`). The model binding and the CUDA context are +/// both made for it. +fn laptop_serving() -> ServingContext { + let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") else { + return ServingContext::trained(); + }; + let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); + let serving = ServingContext::new(cells, &Default::default()).expect("serving context refused"); + eprintln!("PFX config: serving context {cells} cells (experimental)"); + serving } fn load(laptop: bool) -> Pinned { - if laptop { - configure_laptop_cells(); - } + let serving = if laptop { laptop_serving() } else { ServingContext::trained() }; let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) .expect("pinned shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) @@ -69,7 +72,7 @@ fn load(laptop: bool) -> Pinned { let (tokenizer, eos) = pinned_tokenizer(&artifact); let inherited = open_archive(laptop); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( - artifact, + ServedArtifact::new(artifact, serving), &inherited, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING"), @@ -77,7 +80,7 @@ fn load(laptop: bool) -> Pinned { ) .expect("actual pinned KAR+MTP binding failed"); load_experts(&mut binding, laptop); - Pinned { binding, _inherited: inherited, tokenizer, eos } + Pinned { binding, serving, _inherited: inherited, tokenizer, eos } } /// The cache the mode asks for: the prefix cache, the conversation cache of the Original, or none. fn set_mode(config: &mut StackConfig, plan: &Plan) { @@ -188,7 +191,8 @@ pub(super) fn run() { let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", if plan.laptop { 15 } else { 28 }); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); + let context = + Rc::new(device.create_context_serving(budget_gib << 30, pinned.serving).expect("bounded Context unavailable")); let failed = measure(&plan, &pinned, &context); Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); assert!(failed.is_empty(), "prefix-cache checks failed: {failed:?}"); diff --git a/crates/engine-qwen35-cuda/src/backend/owner.rs b/crates/engine-qwen35-cuda/src/backend/owner.rs index 06f75bea..d0bb33c5 100644 --- a/crates/engine-qwen35-cuda/src/backend/owner.rs +++ b/crates/engine-qwen35-cuda/src/backend/owner.rs @@ -58,6 +58,8 @@ pub(super) struct OwnerThread<'a> { pub(super) observer: Option, pub(super) commands: Receiver, pub(super) config: NativeBackendConfig, + /// The serving context this backend serves, made at spawn from `config.context_tokens`. + pub(super) serving: leleka_cuda_driver::ServingContext, pub(super) shared: &'a Shared, pub(super) instance: u64, /// The engine's memory services, created at spawn and dropped (the sampler stopped) with the owner thread. @@ -88,6 +90,7 @@ impl OwnerThread<'_> { fn load(&self, serial: u64, model: ModelDescriptor, requested: RuntimeConfig, reply: Reply) { let env = LoadEnv { config: &self.config, + serving: self.serving, rx: &self.commands, shared: self.shared, reply: &reply, diff --git a/crates/engine-qwen35-cuda/src/backend/spawn.rs b/crates/engine-qwen35-cuda/src/backend/spawn.rs index d7411c82..90f6d667 100644 --- a/crates/engine-qwen35-cuda/src/backend/spawn.rs +++ b/crates/engine-qwen35-cuda/src/backend/spawn.rs @@ -5,11 +5,12 @@ use leleka_memory::MemoryServices; use super::{ Arc, AtomicBool, Backend, BackendError, Command, ErrorCode, EvaluationExecution, EvaluationObserver, INSTANCE, MODE_DIGEST, Mutex, NativeBackendConfig, Ordering, OwnerExecution, OwnerGuard, OwnerThread, PolicyFlags, Proxy, - QUEUE, RecentIds, Shared, SyncSender, invalid, kar_expert_mode_digest, mpsc, thread, unavailable, + QUEUE, RecentIds, ServingContext, Shared, SyncSender, invalid, kar_expert_mode_digest, mpsc, thread, unavailable, }; -/// The configuration limits every native spawn checks before any thread or CUDA owner exists. -fn admit_native_resources(config: &NativeBackendConfig) -> Result<(), BackendError> { +/// The configuration limits every native spawn checks before any thread or CUDA owner exists, and the serving +/// context (cells, RoPE scaling) this backend serves: made here, once per backend, and handed down to every Load. +fn admit_native_resources(config: &NativeBackendConfig) -> Result { if config.context_tokens == 0 || u64::from(config.context_tokens) > leleka_context::rope_scaling::MAX_CHARTER_CONTEXT || config.gpu_budget_bytes == 0 @@ -19,7 +20,6 @@ fn admit_native_resources(config: &NativeBackendConfig) -> Result<(), BackendErr { 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}"), @@ -87,7 +87,7 @@ pub(super) fn spawn_backend_configured( observer: Option, selection: OwnerExecution, ) -> Result, BackendError> { - admit_native_resources(&config)?; + let serving = admit_native_resources(&config)?; let (tx, rx) = mpsc::sync_channel(QUEUE); let shared = Arc::new(Shared { ready: AtomicBool::new(false), shutdown: AtomicBool::new(false), active: Mutex::new(None) }); @@ -100,7 +100,8 @@ pub(super) fn spawn_backend_configured( .name("leleka-cuda-owner".into()) .spawn(move || { let _guard = OwnerGuard(Arc::clone(&worker_shared)); - OwnerThread { selection, observer, commands: rx, config, shared: &worker_shared, instance, memory }.run(); + let shared = &*worker_shared; + OwnerThread { selection, observer, commands: rx, config, serving, shared, instance, memory }.run(); }) .map_err(|_| unavailable("native owner thread unavailable"))?; Ok(Box::new(facts.into_proxy(tx, shared, proxy_memory))) diff --git a/crates/engine-qwen35-cuda/src/memory_governor.rs b/crates/engine-qwen35-cuda/src/memory_governor.rs index a88c785e..7fb3f64a 100644 --- a/crates/engine-qwen35-cuda/src/memory_governor.rs +++ b/crates/engine-qwen35-cuda/src/memory_governor.rs @@ -34,9 +34,10 @@ pub(crate) const OTHER_FIXED_ESTIMATE_RESIDENT: u64 = 3686 << 20; /// counted, native head 487, MoE arena 426, pool 38, ...). 2.5 GiB keeps a margin. pub(crate) const OTHER_FIXED_ESTIMATE: u64 = 2560 << 20; -/// How the stack was asked to run, as far as memory is concerned. +/// How the stack was asked to run, as far as memory is concerned (`geometry`: the serving context's cells). #[derive(Clone, Copy, Debug)] pub(crate) struct StartArgs { + pub geometry: leleka_context::geometry::QsaGeometry, pub kv_resident: usize, pub gpu_budget_bytes: u64, /// `None`: no inherited archive (the Original path refuses that elsewhere). @@ -111,7 +112,7 @@ fn bank_item(g: &Governor, args: &StartArgs, settings: &Settings) -> FixedItem { /// The fixed host footprint the plan must fit. fn fixed_items(g: &Governor, args: &StartArgs, settings: &Settings) -> Vec { - let footprint = leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(args.kv_resident).ok(); + let footprint = args.geometry.kv_stream_footprint(args.kv_resident).ok(); let mut fixed = Vec::new(); if let Some(f) = footprint { fixed.push(FixedItem::new( diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs index 6e6540df..3bebcee4 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs @@ -1,10 +1,14 @@ #![allow(dead_code)] +use leleka_cuda_driver::ServingContext; use leleka_model_format::qwen4exp::{GlobalRole, LayerRole, Qwen4ExpArtifact, ResolvedTensor, TensorRole}; use std::{cell::RefCell, fmt, rc::Rc}; mod decode; +mod served_artifact; +pub(crate) use served_artifact::ServedArtifact; + mod gr; pub(crate) use gr::{GrRole, GrWeights}; @@ -108,6 +112,8 @@ pub(crate) struct ModelBinding { embedding_kind: u32, embedding_bytes: usize, identity: BindingIdentity, + /// The serving context (cells, RoPE) the model is bound under: the one the composition root made. + serving: ServingContext, layers: Box<[BoundLayer]>, expert_count: u32, expert_used_count: u32, diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs index 45177d92..734f708c 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs @@ -7,6 +7,7 @@ use super::{ Qwen4ExpArtifact, Rc, fmt, }; use crate::qwen_forward::contract::Dimension; +use leleka_cuda_driver::ServingContext; impl fmt::Display for InputBindingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -41,7 +42,7 @@ impl BoundLayer { } } impl InputConstants { - pub(super) fn from_artifact(artifact: &Qwen4ExpArtifact) -> InputResult { + pub(super) fn from_artifact(artifact: &Qwen4ExpArtifact, serving: &ServingContext) -> InputResult { let t = artifact.topology(); if t.embedding_length() != 2560 || t.hc_count() != 4 || t.ple_layers() != [1] { return Err(InputBindingError::Metadata); @@ -52,8 +53,7 @@ impl InputConstants { multipliers: t.ple_layer_multipliers().try_into().map_err(|_| InputBindingError::Metadata)?, eos: t.ple_eos_token_id(), context_length: t.context_length(), - serving_cells: u32::try_from(crate::qwen_forward::contract::serving_cells()) - .map_err(|_| InputBindingError::Metadata)?, + serving_cells: u32::try_from(serving.geometry.cells()).map_err(|_| InputBindingError::Metadata)?, }; constants.validate()?; Ok(constants) diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs index 1f26a01b..daa7e6fa 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs @@ -3,8 +3,8 @@ use super::{ BindingError, BindingIdentity, BoundLayer, EMBEDDING_VALUES, GlobalRole, InputBindingError, InputConstants, - InputResult, ModelBinding, MtpWeights, PLE_ROW_VALUES, PLE_ROWS, Qwen4ExpArtifact, RefCell, TensorRole, VOCABULARY, - bind_layers, decode, mtp, validate_ple_descriptor, + InputResult, ModelBinding, MtpWeights, PLE_ROW_VALUES, PLE_ROWS, Qwen4ExpArtifact, RefCell, ServedArtifact, + ServingContext, TensorRole, VOCABULARY, bind_layers, decode, mtp, validate_ple_descriptor, }; use leleka_model_format::verify_stamp::VerifyPolicy; @@ -12,8 +12,9 @@ impl ModelBinding { pub(crate) fn bind() -> Result { Err(BindingError::Unsupported) } - pub(crate) fn from_artifact(artifact: Qwen4ExpArtifact) -> InputResult { - let constants = InputConstants::from_artifact(&artifact)?; + pub(crate) fn from_artifact(served: impl Into) -> InputResult { + let ServedArtifact { artifact, serving } = served.into(); + let constants = InputConstants::from_artifact(&artifact, &serving)?; let embedding = artifact.tensor(TensorRole::Global(GlobalRole::TokenEmbedding)).map_err(|_| InputBindingError::Geometry)?; if embedding.shard() != 0 || embedding.dimensions() != [2560, 248_320] { @@ -31,6 +32,7 @@ impl ModelBinding { embedding_kind, embedding_bytes, identity, + serving, layers, expert_count, expert_used_count, @@ -43,7 +45,7 @@ impl ModelBinding { /// Select the experimental provider before publishing the binding. There /// is deliberately no setter or fallback after a loaded identity exists. pub(crate) fn from_artifact_with_kar_ple( - artifact: Qwen4ExpArtifact, + artifact: impl Into, kar: leleka_model_format::kar::VerifiedKarPleArtifact, ) -> InputResult { let mut binding = Self::from_artifact(artifact)?; @@ -76,7 +78,7 @@ impl ModelBinding { /// Operator paths are consumed inside model binding, never from a request. /// The private loader retains an exclusively owned unnamed read-only inode. pub(crate) fn from_artifact_with_pinned_kar_ple( - artifact: Qwen4ExpArtifact, + artifact: impl Into, (source, owner_root): (&std::path::Path, &std::path::Path), verify: &VerifyPolicy, ) -> InputResult { @@ -88,7 +90,7 @@ impl ModelBinding { } pub(crate) fn from_artifact_with_inherited_kar_ple( - artifact: Qwen4ExpArtifact, + artifact: impl Into, source: &super::super::kar_ple_source::InheritedKarArchive, verify: &VerifyPolicy, ) -> InputResult { @@ -99,7 +101,7 @@ impl ModelBinding { /// Construct a fresh unpublished binding; no existing session can retain it. /// A retained pack is metadata/weight admission only, never draft readiness. pub(crate) fn from_artifact_with_pinned_mtp( - artifact: Qwen4ExpArtifact, + artifact: impl Into, source: &std::path::Path, owner_root: &std::path::Path, ) -> InputResult { @@ -122,7 +124,7 @@ impl ModelBinding { /// Both providers are admitted before this fresh binding is published. pub(crate) fn from_artifact_with_pinned_kar_mtp( - artifact: Qwen4ExpArtifact, + artifact: impl Into, kar: (&std::path::Path, &std::path::Path), (mtp_source, mtp_root): (&std::path::Path, &std::path::Path), verify: &VerifyPolicy, @@ -141,7 +143,7 @@ impl ModelBinding { /// Both providers are fully admitted before publishing this fresh binding. pub(crate) fn from_artifact_with_inherited_kar_mtp( - artifact: Qwen4ExpArtifact, + artifact: impl Into, source: &super::super::kar_ple_source::InheritedKarArchive, mtp_source: &std::path::Path, mtp_root: &std::path::Path, @@ -158,7 +160,7 @@ impl ModelBinding { /// As `from_artifact_with_inherited_kar_mtp`, for an archive that was verified earlier (on another thread, /// at the same time as the shards): the archive is still fully verified, only not here. pub(crate) fn from_artifact_with_verified_kar_mtp( - artifact: Qwen4ExpArtifact, + artifact: impl Into, kar: leleka_model_format::kar::VerifiedKarPleArtifact, mtp_source: &std::path::Path, mtp_root: &std::path::Path, @@ -183,6 +185,10 @@ impl ModelBinding { pub(crate) fn identity(&self) -> BindingIdentity { self.identity.clone() } + /// The serving context (cells, RoPE) this model was bound under. + pub(crate) fn serving(&self) -> &ServingContext { + &self.serving + } /// The `Position` dimension of the serving context this model was bound under. pub(crate) fn position_dimension(&self) -> crate::qwen_forward::contract::Dimension { self.identity.position_dimension() diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/served_artifact.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/served_artifact.rs new file mode 100644 index 00000000..a05b93cb --- /dev/null +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/served_artifact.rs @@ -0,0 +1,24 @@ +//! A verified artifact together with the serving context the model is bound under. + +use super::Qwen4ExpArtifact; +use leleka_cuda_driver::ServingContext; + +/// What a binding is made from: the verified artifact and the serving context (cells, RoPE) it will serve. The +/// composition root of a backend makes the serving context once and every binding takes it from here; a bare +/// artifact converts to the trained serving context (tools and tests that serve the trained 262144 cells). +pub(crate) struct ServedArtifact { + pub(super) artifact: Qwen4ExpArtifact, + pub(super) serving: ServingContext, +} + +impl ServedArtifact { + pub(crate) fn new(artifact: Qwen4ExpArtifact, serving: ServingContext) -> Self { + Self { artifact, serving } + } +} + +impl From for ServedArtifact { + fn from(artifact: Qwen4ExpArtifact) -> Self { + Self { artifact, serving: ServingContext::trained() } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs index 0abc5b5b..9fa7f94f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs @@ -82,16 +82,6 @@ impl Dimension { } } -/// The serving context in cells: every sequence position lies in `0..bound_cells()`. -/// -/// This is the ONE runtime context bound. It is `262144` (the trained context, the previous hard-coded pin) -/// unless `crate::serving::apply_effective_context` configured the process from a resolved -/// `context_policy::EffectiveContext` before the first session. The artifact's own metadata context -/// (`InputConstants::trained_context`) stays pinned to 262144: that is the model's identity, not a serving limit. -pub(crate) fn serving_cells() -> u64 { - leleka_cuda_driver::serving_context().geometry.cells() as u64 -} - /// The `Position` dimension of the trained serving context (262144 cells), for tests that build positions without /// a model binding. Production positions take their dimension from the binding they belong to. #[cfg(test)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs index 4ebb8397..6fe99157 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs @@ -159,9 +159,8 @@ pub(in crate::qwen_forward) struct RopeConstants { pub(in crate::qwen_forward) magnitude: f32, } impl RopeConstants { - /// From the process-wide serving context (`configure_serving_context`, fixed before any CUDA user). - pub(in crate::qwen_forward) fn from_serving_context() -> Self { - let serving = leleka_cuda_driver::serving_context(); + /// From the serving context the model is bound under. + pub(in crate::qwen_forward) fn from_serving_context(serving: &leleka_cuda_driver::ServingContext) -> Self { Self::from_parts(serving.rope.freq_base, serving.rope_args) } pub(in crate::qwen_forward) fn from_parts( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs index d27eb645..28863601 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs @@ -140,7 +140,7 @@ fn geometry_and_prefill_carve_close_for_the_selected_capacities_and_contexts() { let layout = options.carve().expect("carve"); assert_eq!(layout.capacity, capacity); // the four INT8 staging runs the resident QSA transport requires, byte for byte - let runs = leleka_cuda_driver::serving_context().geometry.stage_runs().unwrap(); + let runs = leleka_cuda_driver::ServingContext::trained().geometry.stage_runs().unwrap(); let want = [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])]; for (name, bytes) in want { let span = layout.span(leleka_cuda_driver::PrefillPhase::Common, name).expect(name); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs index bf2422bd..aefff5e8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs @@ -168,7 +168,7 @@ impl FakeStack { fn plan<'t>(&self, tokens: &'t [u32], resume: usize) -> Result, SpecError> { let options = self.plan_options(resume); let plan = PromptPlan::new_in_context( - crate::qwen_forward::contract::serving_cells(), + leleka_context::geometry::TRAINED_CELLS as u64, tokens, ResumePoint::at(resume), None, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs index 3baae87a..7bd553b3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs @@ -6,6 +6,7 @@ use super::{ ExpertTierConfig, KvFormat, LoanTier, PlanError, PrefillLayoutOptions, Result, ServeFailure, StackBlock, StackConfig, StackState, TtftMarks, }; +use leleka_context::geometry::QsaGeometry; impl Default for TtftMarks { fn default() -> Self { @@ -55,22 +56,23 @@ impl StackConfig { loan_tiers: serve.prefill_loan_tiers, } } - /// The streamed KV of this configuration (`None` when the window is not servable). - pub(crate) fn kv_footprint(&self) -> Option { - leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok() + /// The streamed KV of this configuration over `serving` (`None` when the window is not servable). + pub(crate) fn kv_footprint(&self, serving: QsaGeometry) -> Option { + serving.kv_stream_footprint(self.kv_resident).ok() } - fn capacity_invalid(&self) -> bool { - !ADMITTED_CAPACITIES.contains(&self.capacity) || self.kv_footprint().is_none() || self.capacity > 8192 + fn capacity_invalid(&self, serving: QsaGeometry) -> bool { + !ADMITTED_CAPACITIES.contains(&self.capacity) || self.kv_footprint(serving).is_none() || self.capacity > 8192 } fn context_invalid(&self, serving_cells: u64) -> bool { self.max_context < 1 || self.max_context as u64 > serving_cells || !(1..=64).contains(&self.cpu_workers) } - /// `serving_cells`: the serving context of the binding the stack is opened over (the ceiling of `max_context`). - pub(crate) fn validate(&self, serving_cells: u64) -> Result<()> { + /// `serving`: the geometry of the serving context of the binding the stack is opened over (its cell count is the + /// ceiling of `max_context`). + pub(crate) fn validate(&self, serving: QsaGeometry) -> Result<()> { if self.kv_format != KvFormat::Int8 { return Err(Error::Unsupported(super::super::contract::Stage::Session)); } - if self.capacity_invalid() || self.context_invalid(serving_cells) { + if self.capacity_invalid(serving) || self.context_invalid(serving.cells() as u64) { return Err(Error::InvalidDimension); } if let Some(conversation) = &self.conversation { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs index 4922c85a..e1a1aaf0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs @@ -39,19 +39,20 @@ pub(super) fn check_open<'ctx>( config: &StackConfig, ) -> std::result::Result<(), ServeFailure> { crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); - config.validate(binding.input_constants().bound_cells()).map_err(at("config.validate"))?; + config.validate(binding.serving().geometry).map_err(at("config.validate"))?; // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) context.configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { error: Error::InvalidDimension, detail: Some(format!( - "--kv-resident {}: the process already serves another resident KV window", + "--kv-resident {}: the context already serves another resident KV window", config.kv_resident )), })?; - if let Some(footprint) = config.kv_footprint() { + if let Some(footprint) = config.kv_footprint(binding.serving().geometry) { operator_note(&footprint.to_string()); } - if !std::ptr::eq(context, &**shared) { + // the model was bound and the context was created for the same serving context + if !std::ptr::eq(context, &**shared) || binding.serving() != context.serving() { return Err(failure(Error::IdentityMismatch)); } check_model_shape(binding) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs index 78ff2c3a..3658c9e8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_memory_classes.rs @@ -107,7 +107,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } fn register_kv_classes(&self) { use leleka_memory::{Space, When}; - if let Some(f) = self.config.kv_footprint() { + if let Some(f) = self.config.kv_footprint(self.binding.serving().geometry) { let host_class = InventoryClass { component: "kv", class: "host_pinned", diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs index 89ac2ba9..09d06ae3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs @@ -35,7 +35,7 @@ pub(super) struct Assembly<'a, 'ctx> { pub(super) fn prepare(binding: &ModelBinding, config: &StackConfig) -> std::result::Result { let max_cells = usize::try_from(binding.input_constants().bound_cells()).map_err(|_| failure(Error::Overflow))?; let policies = serve_policies(config, binding.input_constants().bound_cells())?; - let rope = RopeConstants::from_serving_context(); + let rope = RopeConstants::from_serving_context(binding.serving()); let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; let formats = expert_formats(binding).map_err(at("expert_formats"))?; let layout = prefill_layout_options(config.capacity, max_cells, &blobs); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs index f875782f..656cb0d6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs @@ -5,6 +5,7 @@ use super::{ ADMITTED_CAPACITIES, Error, ExpertBlobSizes, KvFormat, LoanTier, PlanError, PrefillLayoutOptions, StackConfig, TURN_TOKEN, plan_error, prefill_bytes, prefill_layout_options, tier_for, }; +use leleka_context::geometry::QsaGeometry; #[test] fn a_chunk_borrows_the_smallest_rung_that_holds_it() { @@ -32,15 +33,15 @@ fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_ let config = StackConfig::new(4096); assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); for capacity in [256usize, 1024, 8192] { - assert!(StackConfig { capacity, ..config.clone() }.validate(262_144).is_ok(), "{capacity}"); + assert!(StackConfig { capacity, ..config.clone() }.validate(QsaGeometry::TRAINED).is_ok(), "{capacity}"); } for capacity in [0usize, 255, 300, 16384, 32768] { - assert!(StackConfig { capacity, ..config.clone() }.validate(262_144).is_err(), "{capacity}"); + assert!(StackConfig { capacity, ..config.clone() }.validate(QsaGeometry::TRAINED).is_err(), "{capacity}"); } - assert!(StackConfig { max_context: 0, ..config.clone() }.validate(262_144).is_err()); - assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate(262_144).is_err()); - assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate(262_144).is_err()); - assert!(StackConfig { max_context: i64::MAX, ..config }.validate(262_144).is_err()); + assert!(StackConfig { max_context: 0, ..config.clone() }.validate(QsaGeometry::TRAINED).is_err()); + assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate(QsaGeometry::TRAINED).is_err()); + assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate(QsaGeometry::TRAINED).is_err()); + assert!(StackConfig { max_context: i64::MAX, ..config }.validate(QsaGeometry::TRAINED).is_err()); } #[test] @@ -52,22 +53,25 @@ fn the_conversation_cache_is_on_by_default_with_the_original_settings() { (6, 16_384, 2048) ); assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); - assert!(config.validate(262_144).is_ok()); - assert!(StackConfig { conversation: None, ..config }.validate(262_144).is_ok(), "the cache can be turned off"); + assert!(config.validate(QsaGeometry::TRAINED).is_ok()); + assert!( + StackConfig { conversation: None, ..config }.validate(QsaGeometry::TRAINED).is_ok(), + "the cache can be turned off" + ); } #[test] fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { let config = StackConfig::new(4096); assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); - assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); + assert_eq!(config.kv_footprint(QsaGeometry::TRAINED).map(|f| f.resident_pages), Some(8192)); for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { - assert!(StackConfig { kv_resident, ..config.clone() }.validate(262_144).is_ok(), "{kv_resident}"); + assert!(StackConfig { kv_resident, ..config.clone() }.validate(QsaGeometry::TRAINED).is_ok(), "{kv_resident}"); } - assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate(262_144).is_err()); + assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate(QsaGeometry::TRAINED).is_err()); for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { assert_eq!( - StackConfig { kv_format, ..config.clone() }.validate(262_144), + StackConfig { kv_format, ..config.clone() }.validate(QsaGeometry::TRAINED), Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) ); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs index 5a1737ff..ae964210 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs @@ -63,9 +63,9 @@ mod tests { assert_eq!(validate_values(&[f32::NAN], 1), Err(Error::NonFinite)); assert_eq!(validate_values(&[f32::INFINITY], 1), Err(Error::NonFinite)); assert_eq!(validate_values(&[], Q), Err(Error::InvalidDimension)); - assert_eq!(super::super::qsa_index::validate_ids(&[], 1), Err(Error::InvalidDimension)); - assert_eq!(super::super::qsa_index::validate_ids(&[1, 0], 2), Err(Error::InvalidPosition)); - assert_eq!(super::super::qsa_index::validate_ids(&[0, 0], 2), Err(Error::InvalidPosition)); + assert_eq!(super::super::qsa_index::validate_ids(&[], 1, 262_144), Err(Error::InvalidDimension)); + assert_eq!(super::super::qsa_index::validate_ids(&[1, 0], 2, 262_144), Err(Error::InvalidPosition)); + assert_eq!(super::super::qsa_index::validate_ids(&[0, 0], 2, 262_144), Err(Error::InvalidPosition)); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs index 159da480..a014bf68 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs @@ -178,14 +178,16 @@ mod tests { QsaPending::new(&first, identity(1), &halves(0), &halves(0), &changed), Err(Error::IdentityMismatch) )); - assert_eq!(validate_ids(&[0], 1), Ok(())); - assert_eq!(validate_ids(&[0, 2], 2), Err(Error::InvalidPosition)); - assert_eq!(validate_ids(&[0, 0], 2), Err(Error::InvalidPosition)); - assert_eq!(validate_ids(&[-1], 1), Err(Error::InvalidPosition)); - assert_eq!(validate_ids(&[], 0), Err(Error::InvalidDimension)); - assert_eq!(validate_ids(&[], context() as u64 + 1), Err(Error::InvalidDimension)); - let last: Vec = (context() - 2051..context()).map(|x| x as i32).collect(); - assert_eq!(validate_ids(&last, context() as u64), Ok(())); + const CELLS: usize = 262_144; + let bound = CELLS as u64; + assert_eq!(validate_ids(&[0], 1, bound), Ok(())); + assert_eq!(validate_ids(&[0, 2], 2, bound), Err(Error::InvalidPosition)); + assert_eq!(validate_ids(&[0, 0], 2, bound), Err(Error::InvalidPosition)); + assert_eq!(validate_ids(&[-1], 1, bound), Err(Error::InvalidPosition)); + assert_eq!(validate_ids(&[], 0, bound), Err(Error::InvalidDimension)); + assert_eq!(validate_ids(&[], bound + 1, bound), Err(Error::InvalidDimension)); + let last: Vec = (CELLS - 2051..CELLS).map(|x| x as i32).collect(); + assert_eq!(validate_ids(&last, bound, bound), Ok(())); } } @@ -248,7 +250,6 @@ mod native_state; pub(in crate::qwen_forward) mod prompt_device; mod context; -use context::context; use context::device_peak; mod index_kernels; mod qsa_index_stage; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs index a8c3655e..05598ca0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs @@ -11,19 +11,15 @@ use super::{ reserve, validate_half, validate_ids, validate_values, }; -/// The serving context in cells (262144 unless configured; see `contract::serving_cells`). -pub(super) fn context() -> usize { - crate::qwen_forward::contract::serving_cells() as usize -} -/// Device headroom every QSA step requires on top of what is allocated: 128 MiB at the trained 262144 cells. -/// The only context-proportional device buffers of a step are the pooled index keys (`128 f32` per 4-cell -/// block, uploaded for scoring) and one score word per block, so beyond the trained context the headroom grows -/// by exactly those extra rows. -pub(super) fn device_peak() -> usize { +/// Device headroom every QSA step requires on top of what is allocated, for a serving context of `serving_cells`: +/// 128 MiB at the trained 262144 cells. The only context-proportional device buffers of a step are the pooled index +/// keys (`128 f32` per 4-cell block, uploaded for scoring) and one score word per block, so beyond the trained +/// context the headroom grows by exactly those extra rows. +pub(super) fn device_peak(serving_cells: usize) -> usize { use leleka_context::geometry::QsaGeometry; const TRAINED_PEAK: usize = 128 * 1024 * 1024; let trained = QsaGeometry::TRAINED.pooled_rows(); - let serving = QsaGeometry::new(context()).map_or(trained, QsaGeometry::pooled_rows); + let serving = QsaGeometry::new(serving_cells).map_or(trained, QsaGeometry::pooled_rows); TRAINED_PEAK.saturating_add(serving.saturating_sub(trained).saturating_mul(128 * 4 + 4)) } impl QsaOwner { @@ -134,9 +130,10 @@ impl QsaPrior { } pub(super) fn validate_extent(&self) -> Result<()> { let n = usize::try_from(self.0.next_position).map_err(|_| Error::Overflow)?; + let bound = self.0.binding.bound_cells(); #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(snapshot) = &self.0.native_kv { - if n > context() + if n as u64 > bound || snapshot.next_position() != n || !self.0.pages.is_empty() || self.0.pooled.len() != n / 4 @@ -145,7 +142,7 @@ impl QsaPrior { } return Ok(()); } - if n > context() || self.0.pages.len() != n.div_ceil(4) || self.0.pooled.len() != n / 4 { + if n as u64 > bound || self.0.pages.len() != n.div_ceil(4) || self.0.pooled.len() != n / 4 { return Err(Error::InvalidDimension); } Ok(()) @@ -194,7 +191,7 @@ impl QsaPrior { if self.0.native_kv.is_some() { return Err(Error::Unsupported(Stage::QsaIndex)); } - validate_ids(ids, self.0.next_position)?; + validate_ids(ids, self.0.next_position, self.0.binding.bound_cells())?; let bytes = ids.len().checked_mul(KV * 2).ok_or(Error::Overflow)?; let mut k: Vec = reserve(bytes)?; let mut v: Vec = reserve(bytes)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_kernels.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_kernels.rs index 9198eed9..4821cddf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_kernels.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_kernels.rs @@ -152,7 +152,7 @@ pub(super) fn select_with_keys( let mut ids = context.allocate(2051 * 4).map_err(driver_error)?; ids.copy_from(&[0xff; 2051 * 4]).map_err(driver_error)?; context.qsa_block_topk(&scores, &mut ids, p).map_err(driver_error)?; - let out = read_ids(&ids, p)?; + let out = read_ids(&ids, p, context.serving_geometry().cells() as u64)?; release([dead, q, scores, ids])?; Ok(out) } @@ -177,14 +177,14 @@ fn score_blocks<'c>( Ok((dead, q, scores)) } /// The selected block ids the top-k kernel left in `ids`, validated for position `p`. -fn read_ids(ids: &DeviceBuffer<'_>, p: u32) -> Result> { +fn read_ids(ids: &DeviceBuffer<'_>, p: u32, bound_cells: u64) -> Result> { let bytes = download_bytes(ids, 2051 * 4)?; let width = (p as usize + 1).min(2051); let mut out = reserve(width)?; for word in bytes[..width * 4].as_chunks::<4>().0 { out.push(i32::from_le_bytes(*word)); } - validate_ids(&out, u64::from(p) + 1)?; + validate_ids(&out, u64::from(p) + 1, bound_cells)?; Ok(out.into_boxed_slice()) } pub(in super::super) fn project( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs index df49e8f6..a0dbb33e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs @@ -4,7 +4,7 @@ use super::combined_qsa_observer; use super::{ BindingIdentity, BlockQuery, Context, DeviceBuffer, Error, QsaPrior, QsaSelectionRequest, Rc, Result, admit_budget, - context, device_peak, driver_error, reserve, select_with_keys, validate_values, + device_peak, driver_error, reserve, select_with_keys, validate_values, }; #[cfg(test)] use super::{Directory, KvPage, LayerId, PAGE, Position, QsaOwner, State, TokenLayer}; @@ -96,11 +96,12 @@ mod tests { } #[test] fn resident_capacity_and_tail_guards_at_190k() { - assert_eq!(capacity(0), Err(Error::InvalidDimension)); - assert_eq!(capacity(max_rows() + 1), Err(Error::InvalidDimension)); - assert_eq!(capacity(190000 / 4 + 1), Ok(max_rows())); - assert_eq!(capacity(max_rows()), Ok(max_rows())); - assert_eq!(max_rows() * ROW_BYTES * 12, 402659328); + const BOUND: u64 = 262_144; + assert_eq!(capacity(0, BOUND), Err(Error::InvalidDimension)); + assert_eq!(capacity(max_rows(BOUND) + 1, BOUND), Err(Error::InvalidDimension)); + assert_eq!(capacity(190000 / 4 + 1, BOUND), Ok(max_rows(BOUND))); + assert_eq!(capacity(max_rows(BOUND), BOUND), Ok(max_rows(BOUND))); + assert_eq!(max_rows(BOUND) * ROW_BYTES * 12, 402659328); assert!(upload_words(&[1., f32::NAN]).is_err()); let empty = QsaPrior::empty( BindingIdentity::test_identity(), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs index 1536ddc7..88d6acbf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs @@ -6,13 +6,12 @@ use super::combined_qsa_observer; use super::{ BindingIdentity, BlockQuery, Cell, Context, Entry, Error, QsaIndexKeyCache, QsaPrior, QsaSelectionRequest, - ROW_BYTES, Rc, Result, Update, admit_budget, context, device_peak, driver_error, reserve, select_with_keys, - validate_values, + ROW_BYTES, Rc, Result, Update, admit_budget, device_peak, driver_error, reserve, select_with_keys, validate_values, }; -/// Pooled key rows of the serving context (`65537` at 262144 cells). -pub(super) fn max_rows() -> usize { - context() / 4 + 1 +/// Pooled key rows of a serving context of `bound_cells` (`65537` at 262144 cells). +pub(super) fn max_rows(bound_cells: u64) -> usize { + bound_cells as usize / 4 + 1 } pub(super) fn update(old: &QsaPrior, next: &QsaPrior) -> Result { old.validate_extent()?; @@ -49,11 +48,11 @@ fn append_rows(old: &QsaPrior, next: &QsaPrior) -> Result { Err(Error::InvalidDimension) } } -pub(super) fn capacity(rows: usize) -> Result { - if rows == 0 || rows > max_rows() { +pub(super) fn capacity(rows: usize, bound_cells: u64) -> Result { + if rows == 0 || rows > max_rows(bound_cells) { return Err(Error::InvalidDimension); } - Ok(max_rows()) + Ok(max_rows(bound_cells)) } pub(super) fn upload_words(values: &[f32]) -> Result> { validate_values(values, values.len())?; @@ -75,9 +74,9 @@ pub(super) fn delta(next: &QsaPrior, offset: usize) -> Result> { upload_words(&values) } impl<'ctx> QsaIndexKeyCache<'ctx> { - /// Bytes of one layer's mirror (`max_rows` pooled key rows). - pub(super) fn layer_bytes() -> Result { - max_rows().checked_mul(ROW_BYTES).ok_or(Error::Overflow) + /// Bytes of one layer's mirror (`max_rows` pooled key rows) of a serving context of `bound_cells`. + pub(super) fn layer_bytes(bound_cells: u64) -> Result { + max_rows(bound_cells).checked_mul(ROW_BYTES).ok_or(Error::Overflow) } /// The mirror serves the legacy host-canonical QSA path (`qsa_index.rs`, `QsaPrior`); the serve path keeps its /// keys in the resident index (`OriginalQsaResidentIndex`) and never calls `select`, so the twelve 32 MiB buffers @@ -99,7 +98,7 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { if failed.get() { return Err(Error::CudaExecution); } - Self::admit_mirror(context, eager)?; + Self::admit_mirror(&binding, context, eager)?; let mut cache = Self { binding, context, @@ -119,14 +118,14 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { Ok(cache) } /// Lazy: only the transient peak of one selection must fit; eager: the whole mirror too. - fn admit_mirror(context: &Context<'_>, eager: bool) -> Result<()> { - let bytes = Self::layer_bytes()?; + fn admit_mirror(binding: &BindingIdentity, context: &Context<'_>, eager: bool) -> Result<()> { + let bytes = Self::layer_bytes(binding.bound_cells())?; let total = bytes.checked_mul(12).ok_or(Error::Overflow)?; let charge = if eager { total } else { 0 }; if context .allocated_bytes() .checked_add(charge) - .and_then(|n| n.checked_add(device_peak())) + .and_then(|n| n.checked_add(device_peak(binding.bound_cells() as usize))) .is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); @@ -136,7 +135,7 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { /// The layer's mirror, allocated when it is first needed. pub(super) fn ensure(&mut self, slot: usize) -> Result<&mut Entry<'ctx>> { if self.entries[slot].is_none() { - let buffer = self.context.allocate(Self::layer_bytes()?).map_err(driver_error)?; + let buffer = self.context.allocate(Self::layer_bytes(self.binding.bound_cells())?).map_err(driver_error)?; self.entries[slot] = Some(Entry { prior: None, buffer }); } self.entries[slot].as_mut().ok_or(Error::IdentityMismatch) @@ -190,8 +189,9 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { } /// The layer's mirror is sized for `rows`; how it is brought up to `next`. fn plan(&mut self, slot: usize, rows: usize, next: &QsaPrior) -> Result { + let bound_cells = self.binding.bound_cells(); let entry = self.ensure(slot)?; - if entry.buffer.len() != capacity(rows)?.checked_mul(ROW_BYTES).ok_or(Error::Overflow)? { + if entry.buffer.len() != capacity(rows, bound_cells)?.checked_mul(ROW_BYTES).ok_or(Error::Overflow)? { return Err(Error::InvalidDimension); } Ok(entry.prior.as_ref().map(|old| update(old, next)).transpose()?.unwrap_or(Update::Reload)) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/native_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/native_state.rs index 28f9a951..8862a4b9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/native_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/native_state.rs @@ -1,7 +1,7 @@ //! Canonical mode17 state is the real completed INT8 owner, never decoded FP16. //! Chronological candidates are published by the existing genuine session journal. use super::{ - BindingIdentity, Directory, Error, LayerId, QsaOwner, QsaPending, QsaPrior, Rc, Result, State, TokenLayer, context, + BindingIdentity, Directory, Error, LayerId, QsaOwner, QsaPending, QsaPrior, Rc, Result, State, TokenLayer, driver_error, validate_values, }; use leleka_cuda_driver::{QsaKvSnapshot, QsaPromptIndexPrefix, QsaPromptKv}; @@ -96,7 +96,7 @@ impl QsaPending { (snapshot, index): (&QsaKvSnapshot, &QsaPromptIndexPrefix<'_>), (old, pos, end): (&QsaKvSnapshot, usize, usize), ) -> bool { - end > context() + end as u64 > prior.0.binding.bound_cells() || identity.layer() != prior.layer() || identity.position().get() != pos as u64 || snapshot.next_position() != end diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs index 8940076d..abf5dc47 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs @@ -7,8 +7,8 @@ use super::combined_qsa_observer; use super::{ Context, DenseWeightCache, DeviceBuffer, Error, GrRole, LayerId, ModelBinding, Norm, Position, ProjectionSources, QGate, QsaIndexStage, QsaLayerProjection, QsaMatrixRole, QsaPending, QsaPrepareRequest, QsaPrepared, QsaPrior, - QsaSelectionRequest, QsaWeights, QwenStepTxn, Rc, ResidualReady, Result, admit_budget, append, binding_error, - context, norm, pack, project_input, rope, select, split, validate_ids, validate_values, + QsaSelectionRequest, QsaWeights, QwenStepTxn, Rc, ResidualReady, Result, admit_budget, append, binding_error, norm, + pack, project_input, rope, select, split, validate_ids, validate_values, }; use crate::qwen_forward::prompt_device_rows::PromptWeights; use crate::qwen_forward::q6_attention_columns::{ColumnKey, RowAdmission}; @@ -133,7 +133,7 @@ impl QsaIndexStage { input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; txn.validate_qsa_prior(prior, layer)?; let p = u32::try_from(pos.get()).map_err(|_| Error::InvalidPosition)?; - if p as usize >= context() { + if u64::from(p) >= binding.input_constants().bound_cells() { return Err(Error::InvalidPosition); } validate_values(input.mixed(), 2560)?; @@ -242,7 +242,7 @@ impl QsaPrep<'_, '_, '_> { } else { select(self.context, &candidate.score_keys()?, &candidate.0.dead, iq, self.p)? }; - validate_ids(&ids, self.pos.get() + 1)?; + validate_ids(&ids, self.pos.get() + 1, self.binding.input_constants().bound_cells())?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] combined_qsa_observer::selected(cache.is_some()); Ok(ids) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_pending.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_pending.rs index 97b79c78..c1cd482a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_pending.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_pending.rs @@ -3,7 +3,7 @@ use super::{ BindingIdentity, Directory, Error, KV, KvPage, LayerId, PAGE, PackedKv, Position, QsaPending, QsaPrepared, - QsaPrior, QsaWeights, Rc, Result, Stage, State, TokenLayer, context, validate_half, validate_values, + QsaPrior, QsaWeights, Rc, Result, Stage, State, TokenLayer, validate_half, validate_values, }; impl QsaPending { @@ -39,7 +39,7 @@ impl QsaPending { } validate_values(index, 640)?; let pos = usize::try_from(prior.next_position()).map_err(|_| Error::Overflow)?; - if pos >= context() { + if pos as u64 >= prior.0.binding.bound_cells() { return Err(Error::InvalidPosition); } Ok(pos) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_projection.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_projection.rs index 1980b7b7..65059b2f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_projection.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_projection.rs @@ -161,7 +161,11 @@ fn note_failure(error: &Error, failed: &Cell) { } pub(in super::super) fn admit_budget(context: &Context<'_>) -> Result<()> { - if context.allocated_bytes().checked_add(device_peak()).is_none_or(|n| n > context.budget_bytes()) { + if context + .allocated_bytes() + .checked_add(device_peak(context.serving_geometry().cells())) + .is_none_or(|n| n > context.budget_bytes()) + { return Err(Error::InputAllocation); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/selected_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/selected_cache.rs index 3f9127d2..25903b34 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/selected_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/selected_cache.rs @@ -125,7 +125,7 @@ fn copy_cell(page: &KvPage, offset: u8, k: &mut Vec, v: &mut Vec) -> Res // The candidate carries real binding/session/layer authority; ids are actual causal selection. fn plan(old: &LayerDirectory, prior: &QsaPrior, ids: &[i32]) -> Result { prior.validate_extent()?; - validate_ids(ids, prior.next_position())?; + validate_ids(ids, prior.next_position(), prior.0.binding.bound_cells())?; let mut next = old.copy_for(&prior.0.owner)?; let sources = plan_sources(prior, ids)?; let mut protected = filled(SLOTS, false)?; @@ -183,7 +183,8 @@ fn admit_workspace(context: &Context<'_>, failed: &Cell) -> Result<()> { if failed.get() || context.is_poisoned() { return Err(Error::CudaExecution); } - let required = WORKSPACE_BYTES.checked_add(device_peak()).ok_or(Error::Overflow)?; + let required = + WORKSPACE_BYTES.checked_add(device_peak(context.serving_geometry().cells())).ok_or(Error::Overflow)?; if context.allocated_bytes().checked_add(required).is_none_or(|bytes| bytes > context.budget_bytes()) { return Err(Error::InputAllocation); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids.rs index 5588f8fb..9086064f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids.rs @@ -3,11 +3,12 @@ use super::{ Context, DenseWeightCache, DeviceBuffer, DriverError, Error, InputBindingError, ModelBinding, QsaMatrixKind, - QsaMatrixLayout, QsaMatrixRole, QsaWeights, Result, Stage, context, dispatch_projection, + QsaMatrixLayout, QsaMatrixRole, QsaWeights, Result, Stage, dispatch_projection, }; -pub(in super::super) fn validate_ids(ids: &[i32], n: u64) -> Result<()> { - if n == 0 || n > context() as u64 || ids.len() != usize::try_from(n).map_err(|_| Error::Overflow)?.min(2051) { +/// The selected block ids for `n` positions of a serving context of `bound_cells`. +pub(in super::super) fn validate_ids(ids: &[i32], n: u64, bound_cells: u64) -> Result<()> { + if n == 0 || n > bound_cells || ids.len() != usize::try_from(n).map_err(|_| Error::Overflow)?.min(2051) { return Err(Error::InvalidDimension); } let mut prev = -1; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs index 7e347cd2..84c59029 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs @@ -10,16 +10,15 @@ use leleka_cuda_driver::{ #[cfg_attr(target_os = "windows", allow(unused_imports))] use std::{cell::Cell, fs::File, io::Read, rc::Rc}; const LAYERS: usize = 12; -/// Byte sizes of one layer's canonical host image for the serving context (262144 cells unless configured), -/// derived from `leleka_context::geometry`; identical to the previous literals at the default. +/// Byte sizes of one layer's canonical host image for the serving context of the `Context` (262144 cells unless the +/// engine configured more), derived from `leleka_context::geometry`; identical to the previous literals at the default. struct Sizes { payload: usize, metadata: usize, index_image: usize, } -fn sizes() -> Result { - let cells = super::contract::serving_cells() as usize; - let g = leleka_context::geometry::QsaGeometry::new(cells).map_err(|_| Error::InvalidDimension)?; +fn sizes(context: &Context<'_>) -> Result { + let g = context.serving_geometry(); Ok(Sizes { payload: g.host_payload_bytes().map_err(|_| Error::Overflow)?, // Actual bounded backing-directory/header metadata and index key/tail images. Prefixes share real @@ -54,7 +53,7 @@ impl<'ctx> NativeQsaResources<'ctx> { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidDimension); } - let sizes = sizes()?; + let sizes = sizes(context)?; let host_canonical_limit = LAYERS * (sizes.payload + sizes.metadata + sizes.index_image); // Every real mapped bank has four16-aligned runs plus1024B allocation // slack from the literal Original pool layout. Canonical rollback bytes diff --git a/crates/engine-qwen35-cuda/src/serving.rs b/crates/engine-qwen35-cuda/src/serving.rs index e3d5b2be..fd3840cb 100644 --- a/crates/engine-qwen35-cuda/src/serving.rs +++ b/crates/engine-qwen35-cuda/src/serving.rs @@ -1,17 +1,17 @@ -//! Applies a resolved serving context to the process: the single place the runtime's context bound, -//! the driver's cell-linear buffer sizes and the RoPE constants of the rotating kernels are set from. +//! Makes the serving context of a backend: the single place the runtime's context bound, the driver's cell-linear +//! buffer sizes and the RoPE constants of the rotating kernels are set from. //! -//! The decision is [`leleka_context::context_policy::resolve_context`]; this module only installs it. -//! Installing is once per process and must precede the first CUDA context user (see -//! `leleka_cuda_driver::configure_serving_context`). The default (1 slot, trained context) installs nothing -//! and leaves the process exactly as the pinned 262144 runtime was. +//! The decision is [`leleka_context::context_policy::resolve_context`]; this module turns it into the +//! `ServingContext` value the backend start (the composition root) hands down: to the model binding and to every +//! CUDA `Context` the backend creates. The default (1 slot, trained context) is `ServingContext::trained()`, exactly +//! the pinned 262144 runtime. use leleka_context::{ context_policy::{ContextRequest, EffectiveContext, PolicyError, resolve_context}, memory_plan::KvFormat, rope_scaling::{RopeScalingType, TRAINED_CONTEXT}, }; -use leleka_cuda_driver::Error as DriverError; +use leleka_cuda_driver::{Error as DriverError, ServingContext}; /// Why an effective context cannot be served by this runtime. #[derive(Clone, Debug, PartialEq)] @@ -23,11 +23,6 @@ pub enum ServingError { KvFormat(&'static str), /// `context_policy::resolve_context` refused (rope rules, size ceiling or the memory planner). Policy(PolicyError), - /// The process already serves a different context geometry; it is fixed once per process. - ProcessGeometry { - configured: usize, - requested: usize, - }, Driver(DriverError), } @@ -37,9 +32,6 @@ impl std::fmt::Display for ServingError { Self::Slots(n) => write!(f, "the native runtime serves one slot, not {n}"), Self::KvFormat(k) => write!(f, "KV format {k} is not wired in the native runtime"), Self::Policy(e) => write!(f, "{e}"), - Self::ProcessGeometry { configured, requested } => { - write!(f, "the process already serves a {configured}-cell context and cannot serve {requested}") - } Self::Driver(e) => write!(f, "serving context rejected by the driver: {e:?}"), } } @@ -52,11 +44,11 @@ pub fn is_extended(ctx: &EffectiveContext) -> bool { ctx.ctx_per_slot > TRAINED_CONTEXT } -/// Install `ctx` for this process. +/// The serving context of `ctx`. /// -/// A trained-size, unscaled, single-slot context installs nothing. Anything else configures the driver; if +/// A trained-size, unscaled, single-slot context is the trained default. Anything else is a configured context; if /// the embedded PTX or frozen assets cannot serve it, the first affected launch refuses (no silent fallback). -pub fn apply_effective_context(ctx: &EffectiveContext) -> Result<(), ServingError> { +pub fn serving_context_of(ctx: &EffectiveContext) -> Result { if ctx.slots != 1 { return Err(ServingError::Slots(ctx.slots)); } @@ -64,39 +56,28 @@ pub fn apply_effective_context(ctx: &EffectiveContext) -> Result<(), ServingErro return Err(ServingError::KvFormat(ctx.kv_format.name())); } if !is_extended(ctx) && ctx.rope.kind == RopeScalingType::None { - return Ok(()); + return Ok(ServingContext::trained()); } let cells = usize::try_from(ctx.ctx_per_slot).map_err(|_| ServingError::Driver(DriverError::InvalidSize))?; - leleka_cuda_driver::configure_serving_context(cells, &ctx.rope).map_err(ServingError::Driver) + ServingContext::new(cells, &ctx.rope).map_err(ServingError::Driver) } -/// Admit the operator's `context_tokens` for this process (called once per backend start). +/// Admit the operator's `context_tokens` for one backend start and return the serving context it serves: /// -/// - `<= 262144`: nothing is configured and the process must still be at the trained geometry, so the -/// default behaviour is exactly the pinned runtime's. +/// - `<= 262144`: the trained context, so the default behaviour is exactly the pinned runtime's. /// - larger: the cell count is `context_tokens` rounded up to a whole KV page (4 cells); the rope method and /// factor follow `setup.py` (YaRN, factor = cells / 262144); the Original's memory planner (`plan.hpp` /// arithmetic, INT8 KV, `gpu_budget_bytes` as the pool) must close for the context, then the effective -/// context is installed. The planner is the Original's admission rule and is conservative here: this +/// context is the serving context. The planner is the Original's admission rule and is conservative here: this /// runtime keeps KV in pinned host memory, which the driver additionally checks against `MemAvailable`. -pub fn admit_context_tokens(context_tokens: u32, gpu_budget_bytes: u64) -> Result<(), ServingError> { - let trained = TRAINED_CONTEXT as usize; - let configured = leleka_cuda_driver::serving_context().geometry.cells(); +pub fn admit_context_tokens(context_tokens: u32, gpu_budget_bytes: u64) -> Result { let tokens = context_tokens as usize; - if tokens <= trained { - return if configured == trained { - Ok(()) - } else { - Err(ServingError::ProcessGeometry { configured, requested: trained }) - }; + if tokens <= TRAINED_CONTEXT as usize { + return Ok(ServingContext::trained()); } let cells = tokens.next_multiple_of(leleka_context::geometry::PAGE_CELLS); let request = ContextRequest::new(1, cells as u64, KvFormat::Int8, gpu_budget_bytes); - let effective = resolve_context(&request).map_err(ServingError::Policy)?; - if configured != trained && configured != cells { - return Err(ServingError::ProcessGeometry { configured, requested: cells }); - } - apply_effective_context(&effective) + serving_context_of(&resolve_context(&request).map_err(ServingError::Policy)?) } #[cfg(test)] @@ -105,18 +86,16 @@ mod tests { use leleka_context::rope_scaling::RopeScaling; #[test] - fn default_context_installs_nothing_and_matches_the_trained_geometry() { - assert_eq!(admit_context_tokens(262_144, 1), Ok(())); - assert_eq!(admit_context_tokens(1, 1), Ok(())); - assert_eq!(crate::qwen_forward::contract::serving_cells(), 262_144); + fn default_context_is_the_trained_serving_context() { + assert_eq!(admit_context_tokens(262_144, 1), Ok(ServingContext::trained())); + assert_eq!(admit_context_tokens(1, 1), Ok(ServingContext::trained())); } #[test] - fn extended_context_that_the_planner_rejects_is_refused_before_any_install() { - // 1x512K INT8 needs 6.96e9 B of pool: a 1 GB budget cannot close, nothing is configured. + fn extended_context_that_the_planner_rejects_is_refused() { + // 1x512K INT8 needs 6.96e9 B of pool: a 1 GB budget cannot close. let e = admit_context_tokens(524_288, 1_000_000_000).unwrap_err(); assert!(matches!(e, ServingError::Policy(ref p) if p.is_planner_rejection()), "{e}"); - assert_eq!(leleka_cuda_driver::serving_context().geometry.cells(), 262_144); // above the charter ceiling assert!(matches!( admit_context_tokens(524_289, u64::MAX / 2), @@ -125,14 +104,14 @@ mod tests { } #[test] - fn slots_and_kv_format_are_refused_without_touching_the_driver() { + fn slots_and_kv_format_are_refused() { let mut req = ContextRequest::new(2, 262_144, KvFormat::Int8, 32 << 30); let two = resolve_context(&req).unwrap(); - assert_eq!(apply_effective_context(&two), Err(ServingError::Slots(2))); + assert_eq!(serving_context_of(&two), Err(ServingError::Slots(2))); req.slots = 1; req.kv_format = KvFormat::Q4_0; let q4 = resolve_context(&req).unwrap(); - assert_eq!(apply_effective_context(&q4), Err(ServingError::KvFormat("q4_0"))); + assert_eq!(serving_context_of(&q4), Err(ServingError::KvFormat("q4_0"))); let _ = RopeScaling::default(); } } From 59515403365a8307d506834202e2cc3d12919523 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 24 Nov 2026 01:00:07 +0100 Subject: [PATCH 2/5] native-cpu-expert: drop the process expert layout and the GPU-wait hook nobody installs (STRA-338) install_layout/expert_layout (a process RwLock cell) and install_release_gpu_waits (a process OnceLock hook read on a pool stall) have no caller anywhere in the workspace, so the cells were never written and the hook never ran. They are deleted instead of injected; the origin of the pool's diagnostic millisecond clock is now a field of the pool's shared state (Shared::origin) instead of a process OnceLock. Three process-global exceptions deleted. --- architecture.json | 3 --- .../native-cpu-expert/src/rust_expert_layout.rs | 17 +---------------- .../native-cpu-expert/src/rust_general_pool.rs | 13 +++++++++---- .../src/rust_general_pool/epoch_scheduling.rs | 7 ++----- .../src/rust_general_pool/expert_pool.rs | 7 ++++--- .../src/rust_general_pool/job_default.rs | 14 ++------------ 6 files changed, 18 insertions(+), 43 deletions(-) diff --git a/architecture.json b/architecture.json index f5da92d3..7fa41e06 100644 --- a/architecture.json +++ b/architecture.json @@ -227,9 +227,6 @@ {"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "the process-wide VRAM ledger (LELEKA_VRAM_LEDGER): a diagnostic singleton fed by every allocation site"}, {"crate": "leleka-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "the marker files of the A/B controls: the paths named by the operator are read once and the time of the first look is kept (OnceLock), so a hot path looks at the disk at most every 250 ms; one type serves the three controls"}, {"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "FFI: `static mut stdout` is libc's C stream, declared in an extern block"}, - {"crate": "leleka-native-cpu-expert", "file": "src/rust_expert_layout.rs", "ratchet": "process-global", "reason": "the process-wide expert layout the pool threads read; it is set at load time by the engine"}, - {"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/job_default.rs", "ratchet": "process-global", "reason": "the origin instant of the pool's job timestamps"}, - {"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool.rs", "ratchet": "process-global", "reason": "the hook that releases the GPU waits, installed once by the engine (a function pointer)"}, {"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cell of a Setting: the operator's switches and the CPU probes the kernels dispatch on are computed on the first read and kept for the process life (immutable; a hot path pays one atomic load, and kernel code carries no context to pass a settings value through)"} ], "source_patterns": [ diff --git a/crates/native-cpu-expert/src/rust_expert_layout.rs b/crates/native-cpu-expert/src/rust_expert_layout.rs index 1620ae3c..e8b57b67 100644 --- a/crates/native-cpu-expert/src/rust_expert_layout.rs +++ b/crates/native-cpu-expert/src/rust_expert_layout.rs @@ -2,10 +2,7 @@ //! is numerical layout only; actual ModelBinding/source admission stays outside. use super::rust_ggml::{Kind, NativeFormat}; use super::{Error, FF, H, Result}; -use std::{ - path::Path, - sync::{OnceLock, RwLock}, -}; +use std::path::Path; #[derive(Clone)] pub struct ExpertLayout { pub native: bool, @@ -199,18 +196,6 @@ fn atoll(value: &str) -> i64 { } out.wrapping_mul(sign) } -static LAYOUT: OnceLock> = OnceLock::new(); -pub fn install_layout(layout: ExpertLayout) { - *LAYOUT.get_or_init(|| RwLock::new(ExpertLayout::canonical(0, 512))).write().unwrap_or_else(|p| p.into_inner()) = - layout; -} -pub fn expert_layout() -> ExpertLayout { - LAYOUT - .get_or_init(|| RwLock::new(ExpertLayout::canonical(0, 512))) - .read() - .unwrap_or_else(|p| p.into_inner()) - .clone() -} pub fn cpu_name() -> String { // SAFETY: CPUID is architectural on x86_64; leaves 0x80000002..=4 are queried only after leaf 0x80000000 reported // them. diff --git a/crates/native-cpu-expert/src/rust_general_pool.rs b/crates/native-cpu-expert/src/rust_general_pool.rs index 46513a5e..83a1a33f 100644 --- a/crates/native-cpu-expert/src/rust_general_pool.rs +++ b/crates/native-cpu-expert/src/rust_general_pool.rs @@ -9,7 +9,7 @@ use super::{Error, FF, H, Result}; use std::{ cell::UnsafeCell, sync::{ - Arc, Condvar, Mutex, OnceLock, + Arc, Condvar, Mutex, atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicU64, Ordering}, }, thread, @@ -79,9 +79,16 @@ struct Shared { single: Vec>, states: Vec, host: AtomicI32, + /// The instant `host_ms` and `now_ms` count from: the creation of this pool. + origin: Instant, host_ms: AtomicI64, } -static RELEASE_GPU_WAITS: OnceLock = OnceLock::new(); +impl Shared { + /// Milliseconds since this pool was created (diagnostic timestamps of the host thread). + fn now_ms(&self) -> i64 { + self.origin.elapsed().as_millis().min(i64::MAX as u128) as i64 + } +} #[derive(Clone, Debug)] pub struct Diagnostic { pub epoch: u32, @@ -113,8 +120,6 @@ mod exec; mod job_default; use job_default::alloc_with; use job_default::cells; -pub use job_default::install_release_gpu_waits; -use job_default::now_ms; mod epoch_scheduling; mod expert_pool; mod expert_pool_split_multi_run; diff --git a/crates/native-cpu-expert/src/rust_general_pool/epoch_scheduling.rs b/crates/native-cpu-expert/src/rust_general_pool/epoch_scheduling.rs index da5358dd..48c16f6d 100644 --- a/crates/native-cpu-expert/src/rust_general_pool/epoch_scheduling.rs +++ b/crates/native-cpu-expert/src/rust_general_pool/epoch_scheduling.rs @@ -1,7 +1,7 @@ //! `Shared` of the general pool: publishing a job epoch, claiming work, draining, the worker loop and the waits. //! Apart from `exec`, which runs one job. -use super::{Duration, Instant, Ordering, RELEASE_GPU_WAITS, Shared, now_ms}; +use super::{Duration, Instant, Ordering, Shared}; impl Shared { pub(super) fn publish(&self) { @@ -31,7 +31,7 @@ impl Shared { self.states[id].store(s, Ordering::Relaxed); } else { self.host.store(s, Ordering::Relaxed); - self.host_ms.store(now_ms(), Ordering::Relaxed); + self.host_ms.store(self.now_ms(), Ordering::Relaxed); } } pub(super) fn drain(&self, e: u32, id: usize) { @@ -91,9 +91,6 @@ impl Shared { } pub(super) fn stall(&self, what: &str) -> ! { eprintln!("strata: the CPU expert pool stalled {what}"); - if let Some(f) = RELEASE_GPU_WAITS.get() { - f(); - } std::process::abort() } pub(super) fn wait_parked(&self) { diff --git a/crates/native-cpu-expert/src/rust_general_pool/expert_pool.rs b/crates/native-cpu-expert/src/rust_general_pool/expert_pool.rs index f027a654..34b62c95 100644 --- a/crates/native-cpu-expert/src/rust_general_pool/expert_pool.rs +++ b/crates/native-cpu-expert/src/rust_general_pool/expert_pool.rs @@ -4,7 +4,7 @@ use super::{ Arc, AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicU64, Batch, Condvar, CpuTopology, Diagnostic, Duration, Error, ExpertPool, H, Instant, Job, Line, Mutex, NativeFormat, Ordering, PlanarJob, PoolAffinity, Result, Shared, - SingleScratch, SingleSplit, Split, UnsafeCell, alloc_with, cells, now_ms, thread, + SingleScratch, SingleSplit, Split, UnsafeCell, alloc_with, cells, thread, }; impl ExpertPool { @@ -74,7 +74,8 @@ impl ExpertPool { single: cells::(16)?, states: alloc_with(n, || AtomicI32::new(-1))?, host: AtomicI32::new(-10), - host_ms: AtomicI64::new(now_ms()), + origin: Instant::now(), + host_ms: AtomicI64::new(0), })) } fn spawn_worker(s: Arc, i: usize, core: i32) -> Result> { @@ -131,7 +132,7 @@ impl ExpertPool { mode, workers: s.states.iter().map(|s| s.load(Ordering::SeqCst)).collect(), host: s.host.load(Ordering::SeqCst), - host_for_ms: now_ms() - s.host_ms.load(Ordering::SeqCst), + host_for_ms: s.now_ms() - s.host_ms.load(Ordering::SeqCst), } } pub(super) fn phase(&mut self, mode: u32, tasks: usize, rows: usize, parts: usize) { diff --git a/crates/native-cpu-expert/src/rust_general_pool/job_default.rs b/crates/native-cpu-expert/src/rust_general_pool/job_default.rs index afa731eb..af1af7f5 100644 --- a/crates/native-cpu-expert/src/rust_general_pool/job_default.rs +++ b/crates/native-cpu-expert/src/rust_general_pool/job_default.rs @@ -1,10 +1,7 @@ //! Defaults of the pool's raw job and scratch types, the Send/Sync claim for Shared with its safety argument, -//! and small helpers: fallible zeroed allocation, the GPU-wait release hook and a process-relative millisecond clock. +//! and small helpers: fallible zeroed allocation. -use super::{ - Error, FF, Instant, Job, OnceLock, PlanarActivation, RELEASE_GPU_WAITS, Result, Shared, SingleSplit, Split, - UnsafeCell, -}; +use super::{Error, FF, Job, PlanarActivation, Result, Shared, SingleSplit, Split, UnsafeCell}; impl Default for Job { fn default() -> Self { @@ -45,10 +42,3 @@ pub(super) fn alloc_with(n: usize, make: impl FnMut() -> T) -> Result> pub(super) fn cells(n: usize) -> Result>> { alloc_with(n, || UnsafeCell::new(T::default())) } -pub fn install_release_gpu_waits(callback: fn()) -> Result<()> { - RELEASE_GPU_WAITS.set(callback).map_err(|_| Error::Shape) -} -pub(super) fn now_ms() -> i64 { - static START: OnceLock = OnceLock::new(); - START.get_or_init(Instant::now).elapsed().as_millis().min(i64::MAX as u128) as i64 -} From 52abe0a21afa8c4c406c8c5e1da2e1714dca7f85 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 24 Nov 2026 01:04:43 +0100 Subject: [PATCH 3/5] control-plane: the gpt-oss prompt date is a field of the model view, not a process cell (STRA-338) PromptDate was set once by serve into a process OnceLock and read by harmony_prompt::render. It is now ModelView::prompt_date, built from the config in build_state, and prepare_input_tokens hands it to render_prompt/render. The default of a bare AppState is still Utc, as the unset cell was. One process-global exception deleted. --- architecture.json | 1 - control-plane/src/app/state.rs | 3 +++ control-plane/src/responses.rs | 2 +- control-plane/src/responses/harmony_prompt.rs | 18 +++++------------- control-plane/src/responses/intake.rs | 2 +- .../src/responses/intake/intake_stages.rs | 3 ++- control-plane/src/serve/state.rs | 2 +- 7 files changed, 13 insertions(+), 18 deletions(-) diff --git a/architecture.json b/architecture.json index 7fa41e06..5792cd52 100644 --- a/architecture.json +++ b/architecture.json @@ -153,7 +153,6 @@ {"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "pure cache: the validity of a tool schema by its compact text, so the dozen schemas of a coding agent are compiled once, not three times per request"}, {"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "the compiled pinned chat template: immutable, built on first use, read by every request"}, {"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "the process-wide request counters and histograms that /metrics renders; written by every request"}, - {"crate": "leleka-control-plane", "file": "src/responses/harmony_prompt.rs", "ratchet": "process-global", "reason": "the gpt-oss prompt date: configuration set once by serve before the first request"}, {"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"}, diff --git a/control-plane/src/app/state.rs b/control-plane/src/app/state.rs index a12c15c1..a5494986 100644 --- a/control-plane/src/app/state.rs +++ b/control-plane/src/app/state.rs @@ -66,6 +66,8 @@ pub struct ModelView { pub prefix_cache: Arc, /// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`. pub memory: Arc, + /// What a gpt-oss system message says about the date (`prompt_date` in the config). + pub prompt_date: crate::responses::PromptDate, } /// Stores and process-wide services. @@ -120,6 +122,7 @@ impl Default for ModelView { vision: None, prefix_cache: Arc::new(Default::default()), memory: Arc::new(Default::default()), + prompt_date: crate::responses::PromptDate::Utc, } } } diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 047b9545..f95d90d6 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -54,7 +54,7 @@ use serde_json::Map; type SharedCodec = Arc; static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0); mod harmony_prompt; -pub use harmony_prompt::{PromptDate, set_prompt_date}; +pub use harmony_prompt::PromptDate; mod create; pub use create::create; mod errors; diff --git a/control-plane/src/responses/harmony_prompt.rs b/control-plane/src/responses/harmony_prompt.rs index 96dcc0cb..60646946 100644 --- a/control-plane/src/responses/harmony_prompt.rs +++ b/control-plane/src/responses/harmony_prompt.rs @@ -7,7 +7,6 @@ //! developer message; reasoning of earlier turns is not replayed (the template drops it), except for a //! tool-call message where the template keeps it; custom tools are not supported. -use std::sync::OnceLock; use std::time::{SystemTime, UNIX_EPOCH}; pub use leleka_gateway_domain::responses::PromptDate; @@ -19,22 +18,15 @@ use serde_json::Value; use super::CreateRequest; -static PROMPT_DATE: OnceLock = OnceLock::new(); - -/// Choose the date mode for the rest of the process (once, at start; later calls are ignored). -pub fn set_prompt_date(mode: PromptDate) { - let _ = PROMPT_DATE.set(mode); -} - pub(super) fn today() -> String { civil_date(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()) } -/// Render the Harmony prompt for `request` with today's date. The special markers are written as -/// sentinel characters, which the gpt-oss codec turns into the special tokens: text from the client can -/// never forge a marker. -pub(super) fn render(request: &CreateRequest) -> Result { - match PROMPT_DATE.get().unwrap_or(&PromptDate::Utc) { +/// Render the Harmony prompt for `request` with the date `mode` says (the model view's `prompt_date`). The special +/// markers are written as sentinel characters, which the gpt-oss codec turns into the special tokens: text from the +/// client can never forge a marker. +pub(super) fn render(request: &CreateRequest, mode: &PromptDate) -> Result { + match mode { PromptDate::Utc => render_dated(request, Some(&today()), true), PromptDate::Fixed(date) => render_dated(request, Some(date), true), PromptDate::None => render_dated(request, None, true), diff --git a/control-plane/src/responses/intake.rs b/control-plane/src/responses/intake.rs index d91f6da1..158cb990 100644 --- a/control-plane/src/responses/intake.rs +++ b/control-plane/src/responses/intake.rs @@ -90,7 +90,7 @@ pub(super) async fn prepare_input_tokens( encode_images: bool, ) -> Result> { resolve_previous(state, request).await?; - let (prompt, images) = render_prompt(&tokenizer, request)?; + let (prompt, images) = render_prompt(&tokenizer, request, &state.model.prompt_date)?; let (token_ids, prompt) = tokenize_prompt(tokenizer.clone(), prompt).await?; if images.is_empty() || !encode_images { return Ok(Prepared { diff --git a/control-plane/src/responses/intake/intake_stages.rs b/control-plane/src/responses/intake/intake_stages.rs index 31584953..e4178189 100644 --- a/control-plane/src/responses/intake/intake_stages.rs +++ b/control-plane/src/responses/intake/intake_stages.rs @@ -74,13 +74,14 @@ pub(super) async fn resolve_previous(state: &AppState, request: &mut CreateReque pub(super) fn render_prompt( tokenizer: &SharedCodec, request: &CreateRequest, + date: &crate::responses::PromptDate, ) -> Result<(String, Vec), Box> { let rendered = crate::stage_trace::time("render", || match tokenizer.family() { Family::Qwen35 => { let qwen = tokenizer.qwen().ok_or_else(|| "the Qwen family needs the Qwen tokenizer".to_owned())?; render_request(request, qwen.marks()) } - Family::GptOss => harmony_prompt::render(request).map(|prompt| (prompt, Vec::new())), + Family::GptOss => harmony_prompt::render(request, date).map(|prompt| (prompt, Vec::new())), }); rendered.map_err(|message| { refuse(StatusCode::BAD_REQUEST, "invalid_request_error", "invalid_prompt", Some("input"), &message) diff --git a/control-plane/src/serve/state.rs b/control-plane/src/serve/state.rs index 39182390..c7f02f55 100644 --- a/control-plane/src/serve/state.rs +++ b/control-plane/src/serve/state.rs @@ -48,6 +48,7 @@ pub(super) fn build_state(config: &Config, history: ResponseHistory) -> Result Date: Tue, 24 Nov 2026 01:04:59 +0100 Subject: [PATCH 4/5] architecture.json: every remaining process-global exception says why that site keeps its cell (STRA-338) The 32 remaining process-global exceptions are classified: instance-local OnceCell/OnceLock fields that the gate pattern only matches by type name, pure memos of constants or embedded sealed images, ambient immutable environment read below the Settings owner, FFI and logger-facade boundaries, diagnostics, and three entries marked "kept for now, NOT a boundary" (request_log counters, split_group_pcie tuning, vram_ledger) that can still take the value by argument. --- architecture.json | 64 +++++++++++++++++++++++------------------------ 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/architecture.json b/architecture.json index 5792cd52..dfb28e88 100644 --- a/architecture.json +++ b/architecture.json @@ -52,7 +52,7 @@ "_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.", "exceptions": [ {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "env-read", "reason": "EnvSwitch is the one reader of the operator environment in this crate: it reads one named variable on the first get() and applies a typed rule"}, - {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "the OnceLock inside EnvSwitch caches the switch position for the process life (an immutable operator setting; a hot path pays one atomic load)"}, + {"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "kept: operator environment switch. The OnceLock is the cell of each `static EnvSwitch` that is declared where the switch is read; the variable cannot change after process start, so the first-read value equals a fresh read, and the crate sits below the engine Settings owner, so a settings value cannot be handed down to it (dependency direction)"}, {"crate": "leleka-cpu-worker", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, {"crate": "leleka-tokenizer", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, {"crate": "leleka-gptoss-npu", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"}, @@ -70,7 +70,7 @@ {"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "env-read", "reason": "platform adapter (glibc heap): reads its own LELEKA_MEMORY_NO_TRIM switch once"}, {"crate": "leleka-native-parity-bench", "file": "src/lib.rs", "ratchet": "env-read", "reason": "benchmark host (L4): reads the operator's STRATA_IQ_MT_MIN override to report which value it measured"}, {"crate": "leleka-npu-worker", "file": "src/main.rs", "ratchet": "env-read", "reason": "worker binary (composition root): reads LELEKA_OPENVINO_ROOT into its configuration"}, - {"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cached LELEKA_NO_TRIM_FILE path: an immutable operator setting read once by the crate's one environment reader"}, + {"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_NO_TRIM_FILE path is ambient process environment, immutable after start (a cached read equals a fresh one); this crate is below the engine Settings owner and MemoryServices carries the governor, not the environment, so no settings value reaches the reader"}, {"crate": "leleka-memory", "file": "src/governor.rs", "ratchet": "dyn-trait", "reason": "port boundary: the Governor holds its MemoryPressure adapter as Arc, chosen at start-up (hexagonal.md, ports table)"}, {"crate": "leleka-memory", "file": "src/governor/operations/setup.rs", "ratchet": "dyn-trait", "reason": "port boundary: Governor::new takes the host as Arc (the adapter is chosen by the composition root) and source() hands it back"}, {"crate": "leleka-memory", "file": "src/lock/page_locking.rs", "ratchet": "dyn-trait", "reason": "port boundary: SharedPageLocking = Arc, the OS adapter of mmap/mlock chosen by the composition root"}, @@ -98,12 +98,12 @@ {"crate": "leleka-model-format", "file": "src/ple_reader/read_queue.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: readings of the per-row read queue's latency window, inside the reader loop"}, {"crate": "leleka-model-format", "file": "src/ple_reader/row_reading.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: latency measurement of one PLE row read, inside the reader loop"}, {"crate": "leleka-obs", "file": "src/time/clock.rs", "ratchet": "instant-now", "reason": "the clock adapter itself: SystemClock, AnyClock and ManualClock are the one place that reads the monotonic clock"}, - {"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "process-global", "reason": "platform adapter (glibc heap): the LELEKA_MEMORY_NO_TRIM switch is read once and cached"}, - {"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "process-global", "reason": "Windows interposer (FFI): the CUDA call tracer is process-wide state behind C-ABI hooks that carry no context pointer"}, - {"crate": "leleka-obs", "file": "src/lib.rs", "ratchet": "process-global", "reason": "the logger is process-wide: its Settings, rate limiter and request sink are built once from the environment"}, - {"crate": "leleka-obs", "file": "src/write_stderr.rs", "ratchet": "process-global", "reason": "the request-log sink of the process-wide logger (see lib.rs)"}, - {"crate": "leleka-tokenizer", "file": "src/lib.rs", "ratchet": "process-global", "reason": "immutable constant tables built once: the pre-tokenizer regex and the character classes"}, - {"crate": "leleka-gptoss-npu", "file": "src/half.rs", "ratchet": "process-global", "reason": "immutable constant table: the half-to-float conversion table, built once"}, + {"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "process-global", "reason": "kept: platform adapter over the glibc heap, which is itself process-wide; the LELEKA_MEMORY_NO_TRIM switch is ambient immutable environment read once, and the adapter is below the Settings owner"}, + {"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "process-global", "reason": "kept: FFI interposer boundary. The CUDA call tracer is state behind C-ABI hooks that the dynamic loader calls with no context pointer and no way to carry an argument; the process is the only scope that exists there"}, + {"crate": "leleka-obs", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: the logger facade, like the `log` crate, is process-wide by contract: elog! and request logging are called from every crate without a handle; its Settings, rate limiter and request sink are built once from the environment"}, + {"crate": "leleka-obs", "file": "src/write_stderr.rs", "ratchet": "process-global", "reason": "kept: the request-log sink of the process-wide logger facade of lib.rs (same reason: written by every thread, no handle at the call sites)"}, + {"crate": "leleka-tokenizer", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: immutable constant tables (the pre-tokenizer regex and the character classes) compiled on first use; a pure function of constants, a memo no caller can observe"}, + {"crate": "leleka-gptoss-npu", "file": "src/half.rs", "ratchet": "process-global", "reason": "kept: immutable constant table (half-to-float conversion), a pure function of constants built once; no caller can observe the memo"}, {"crate": "leleka-cuda-model", "file": "src/original_prefill_schedule.rs", "ratchet": "dyn-trait", "reason": "parameter struct SourceView borrows three residency queries (resident, pinned, transient) from the caller's tables; a generic parameter per closure would make the type unnameable in the callers' signatures"}, {"crate": "leleka-experimental-ref", "file": "src/remote_experts.rs", "ratchet": "dyn-trait", "reason": "parameter struct Candidates borrows the primary's residency test from the caller's table; generic parameters would leak into every caller's signature"}, {"crate": "leleka-cpu-worker", "file": "src/engine.rs", "ratchet": "dyn-trait", "reason": "port boundary: the engine holds the prefill accelerator (iGPU, NPU or split) as Box, chosen by the worker binary"}, @@ -123,10 +123,10 @@ {"crate": "leleka-model-format", "file": "src/qwen4exp/binding_topology.rs", "ratchet": "dyn-trait", "reason": "std::error::Error::source() returns &(dyn Error + 'static) by the trait's own signature"}, {"crate": "leleka-model-format", "file": "src/ple_reader.rs", "ratchet": "dyn-trait", "reason": "port boundary: the PLE reader holds its PageSource (file, direct-IO file or test double) as Arc"}, {"crate": "leleka-model-format", "file": "src/ple_reader/row_reading.rs", "ratchet": "dyn-trait", "reason": "port boundary: PleReader::open takes the PageSource as Arc"}, - {"crate": "leleka-model-format", "file": "src/huge_pages.rs", "ratchet": "process-global", "reason": "the huge-page mode is an operator setting parsed once from LELEKA_HUGEPAGES and cached for the process"}, - {"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "the identity-recheck switch is an operator setting parsed once and cached for the process"}, - {"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "a per-instance lazily opened set of file handles (a OnceLock field of the archive), not a process global"}, - {"crate": "leleka-model-format", "file": "src/kar/verified_kar_ple_artifact.rs", "ratchet": "process-global", "reason": "constructs the per-instance lazy handle cell of kar.rs, not a process global"}, + {"crate": "leleka-model-format", "file": "src/huge_pages.rs", "ratchet": "process-global", "reason": "kept: ambient environment. The huge-page mode (LELEKA_HUGEPAGES) is immutable after start so the cache equals a fresh read; model-format is below the engine Settings owner (dependency direction), so no settings value reaches the mapping helpers"}, + {"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "kept: ambient environment. The identity-recheck switch is immutable after start so the cache equals a fresh read; model-format is below the engine Settings owner (dependency direction)"}, + {"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "not a process global: a per-instance lazily opened set of file handles (a OnceLock field of the archive); the gate pattern matches the type name"}, + {"crate": "leleka-model-format", "file": "src/kar/verified_kar_ple_artifact.rs", "ratchet": "process-global", "reason": "not a process global: constructs the per-instance lazy handle cell of kar.rs; the gate pattern matches the type name"}, {"crate": "leleka-control-plane", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (number, path, flag, mode)"}, {"crate": "leleka-deploy", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (path, flag, text)"}, {"crate": "leleka-engine-host", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate and its binaries: credentials by name, the evaluation switches, the inherited child variables"}, @@ -150,10 +150,10 @@ {"crate": "leleka-engine-host", "file": "src/node.rs", "ratchet": "dyn-trait", "reason": "tonic server-streaming response type: the generated trait wants a boxed stream"}, {"crate": "leleka-engine-host", "file": "src/runtime_rpc.rs", "ratchet": "dyn-trait", "reason": "tonic server-streaming response type: the generated trait wants a boxed stream"}, {"crate": "leleka-backend-api", "file": "src/scripted.rs", "ratchet": "dyn-trait", "reason": "the scripted test engine stores the test's responder closure"}, - {"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "pure cache: the validity of a tool schema by its compact text, so the dozen schemas of a coding agent are compiled once, not three times per request"}, - {"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "the compiled pinned chat template: immutable, built on first use, read by every request"}, - {"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "the process-wide request counters and histograms that /metrics renders; written by every request"}, - {"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"}, + {"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "kept: pure memo (not state): the validity of a tool schema keyed by its compact text, so the dozen schemas of a coding agent compile once, not three times per request; the result depends on the key alone, so no caller can observe the cache; a per-request owner would defeat it"}, + {"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "kept: the compiled pinned chat template is an immutable constant of the build, compiled on first use and read by every request; a pure memo of a constant"}, + {"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "kept for now (NOT a boundary): the request counters and histograms that /metrics renders are written by the request middleware and read by the metrics handler; both reach AppState, so the registry can move into Services. Left because it touches the request path of every endpoint and the metrics tests; follow-up of STRA-338"}, + {"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "kept: diagnostic stage table of the replay harness and STRATA_STAGE_TRACE; time() and span() are called from deep helpers (render, tokenize) that carry no state argument, and the output is diagnostic only, never read by serving logic"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per routing prediction on the lookahead thread); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"}, @@ -172,12 +172,12 @@ {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_preview.rs", "ratchet": "dyn-trait", "reason": "Box is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the binding (lazy PLE reader); the gate pattern matches the type name"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises the instance field `ple_reader` of one ModelBinding; the gate pattern matches the type name"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "kept for now: the adaptive-tier tuning tuple is derived once from the process settings capture and emits the invalid-LELEKA_ADAPT_DECAY line once; it is read from three files (cross_layer_potential, source_spans, this one), so passing it needs a field on the residency state; not moved in this change (STRA-338 follow-up)"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "kept: DBG_T0, the epoch of the bring-up trace timestamps (dbg_el()); diagnostics only, called from trace macros in many files that hold no common owner, never read by serving logic"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the session; the gate pattern matches the type name"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises an instance field of one session; the gate pattern matches the type name"}, {"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: stall span of one timed drain, reported by the prefill stall trace"}, {"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream/chunk_issuing.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one chunk issue, summed into the copy-ring profile"}, {"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/original_mmq_copy_schedule/stream_start.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: start of the copy-ring stream, read once per stream for the profile"}, @@ -217,16 +217,16 @@ {"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/context.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"}, {"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"}, {"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch/moe_prefill_batch_lifecycle.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"}, - {"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "the verdict of the immutable MMQ artifact check, computed once"}, - {"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "the usability of the kh recurrence on this device: immutable result of a probe or proof of a sealed image, computed once and cached"}, - {"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "the RoPE ABI of the loaded index module: immutable result of a probe or proof of a sealed image, computed once and cached"}, - {"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "the resolver ABI of the loaded module: immutable result of a probe or proof of a sealed image, computed once and cached"}, - {"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_admission.rs", "ratchet": "process-global", "reason": "per-operation memo of the PTX proof: immutable result of a probe or proof of a sealed image, computed once and cached"}, - {"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "the table of PTX proof memos, one cell per operation: immutable result of a probe or proof of a sealed image, computed once and cached"}, - {"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "the process-wide VRAM ledger (LELEKA_VRAM_LEDGER): a diagnostic singleton fed by every allocation site"}, - {"crate": "leleka-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "the marker files of the A/B controls: the paths named by the operator are read once and the time of the first look is kept (OnceLock), so a hot path looks at the disk at most every 250 ms; one type serves the three controls"}, - {"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "FFI: `static mut stdout` is libc's C stream, declared in an extern block"}, - {"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cell of a Setting: the operator's switches and the CPU probes the kernels dispatch on are computed on the first read and kept for the process life (immutable; a hot path pays one atomic load, and kernel code carries no context to pass a settings value through)"} + {"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "kept: pure memo of the verdict of the immutable embedded MMQ artifact check (a function of the embedded bytes alone), so no caller can observe the cache; a Context-owned copy would re-prove the same bytes per Context"}, + {"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "kept: pure memo of a proof about an embedded sealed image (usability of the kh recurrence), a result per device that no caller can observe as state"}, + {"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "kept: pure memo of the RoPE ABI proof of the embedded index module, a function of the embedded bytes alone"}, + {"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "kept: pure memo of the resolver ABI proof of the embedded module, a function of the embedded bytes alone"}, + {"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_admission.rs", "ratchet": "process-global", "reason": "kept: per-operation pure memo of the PTX proof of an embedded sealed image, a function of the embedded bytes alone"}, + {"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "kept: the table of the PTX proof memos of asset_admission.rs, one cell per operation; pure functions of embedded bytes"}, + {"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "kept for now (diagnostic, NOT a boundary): the LELEKA_VRAM_LEDGER singleton is fed by every allocation site through free functions; the correct owner is the Context, which every allocation already reaches. Not moved in this change (STRA-338 follow-up)"}, + {"crate": "leleka-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "kept: the marker files of the A/B controls are operator-named paths read once with the time of the first look, so a hot path stats the disk at most every 250 ms; one type serves three controls"}, + {"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "kept: FFI. `static mut stdout` is libc's C stream, declared in an extern block; it is the C library's own global, not ours"}, + {"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the cell of each `static Setting` (operator switches and the CPU probes the kernels dispatch on), computed on first read from the immutable environment and the CPU; the kernels are free functions called from pool worker threads that carry no context to pass a value through, and a hot path pays one atomic load"} ], "source_patterns": [ {"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"}, From e9107fe43ca6306d9c6ef8c614faa123e4aa9d2b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Tue, 24 Nov 2026 02:01:08 +0100 Subject: [PATCH 5/5] comments: the serving context is no longer called process-wide (STRA-338) --- crates/cuda-model/src/lib.rs | 2 +- .../src/backend/original_serve_prefix_smoke.rs | 2 +- .../src/model_binding/weight_binding/binding_identity.rs | 2 +- .../src/qwen_forward/original_serve_config.rs | 2 +- .../engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/cuda-model/src/lib.rs b/crates/cuda-model/src/lib.rs index da5026b7..ae3d057b 100644 --- a/crates/cuda-model/src/lib.rs +++ b/crates/cuda-model/src/lib.rs @@ -1,7 +1,7 @@ //! Pure host-side models of the CUDA driver crate (`leleka-cuda-driver`), split out by STRA-338 S24. //! //! Nothing here touches the CUDA Driver API, a context, a device buffer, FFI or PTX: the error type, the closed -//! projection formats and geometries, the process-wide serving context, the planners and the pure halves of the +//! projection formats and geometries, the serving context value, the planners and the pure halves of the //! Original kernels. The driver re-exports every public item at its old path, so `leleka_cuda_driver::...` paths do //! not change. The `.cu`/`.ptx` sources and oracle fixtures that some tests check stay with the driver. #![forbid(unsafe_code)] diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs index bd48d9d9..df0f055a 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke.rs @@ -29,7 +29,7 @@ //! * `LELEKA_PFX_LAPTOP=yes` the laptop profile: the KAR archive as a read-only file //! (`LELEKA_LAPTOP_KAR_FILE`, else the sealed memfd), the routed experts mapped from the shard instead of copied into //! RAM, `LELEKA_LAPTOP_CPU_WORKERS` (7), the `auto` prefix budget of the laptop profile, `LELEKA_LAPTOP_CELLS` (a -//! smaller process geometry). +//! smaller serving context). //! //! Run: `cargo test -p leleka-engine-qwen35-cuda -- --ignored --exact //! backend::original_serve_prefix_smoke::original_serve_prefix_cache_smoke`. diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs index 734f708c..e69f95c6 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs @@ -81,7 +81,7 @@ impl InputConstants { pub(crate) fn eos(&self) -> u32 { self.eos } - /// The serving context in cells (the bound of every `Position`): 262144 unless the process configured a + /// The serving context in cells (the bound of every `Position`): 262144 unless the backend served a /// larger one. NOT the artifact's metadata value; that is [`Self::trained_context`]. pub(crate) fn context_length(&self) -> u32 { self.serving_cells diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs index 6fe99157..05be4207 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs @@ -1,4 +1,4 @@ -//! Mode17 values of the Original serve path, derived once from the model binding and the process serving +//! Mode17 values of the Original serve path, derived once from the model binding and the serving //! context. Everything here is configuration, never a certificate: each value names the line of the //! Original it mirrors, so a hardware run can diff them against the CLI it is compared with. use super::contract::{Error, Result}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index a77910c7..39d53067 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -116,7 +116,7 @@ pub(crate) struct StackConfig { /// Empty (no governor) for a stack that is opened without a memory-governed start, as in the smokes. pub(crate) memory: leleka_memory::MemoryServices, pub(crate) capacity: usize, - /// The request ceiling (`--max-context`): at most the process serving cell count. + /// The request ceiling (`--max-context`): at most the serving cell count of the binding. pub(crate) max_context: i64, /// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding. pub(crate) rt_directory: Option,