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(); } }