diff --git a/architecture.json b/architecture.json index e714fc85..f9364c07 100644 --- a/architecture.json +++ b/architecture.json @@ -174,35 +174,18 @@ {"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/backend/session.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"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": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, + {"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": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/mtp_frame.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/dense_kv.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/prefix_draft_snapshot.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/warming.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_attention/dense_geometry.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/mtp_window_spec.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, + {"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/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_config.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_controller/trace_enabled.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_draft.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_draft/prefill_records.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_index/context.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_native_resources.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"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/chunk/host_charge_bounded.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/verify/verified_target_prefix.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"}, {"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"}, {"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"}, diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs index e7a2e3ab..8f75539c 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs @@ -20,7 +20,7 @@ pub(super) fn begin_decoder( ) -> Result { Ok(match resume { Some(old) => { - if !append_compatible(&old.tokens, prompt) { + if !append_compatible(run.binding.input_constants().bound_cells(), &old.tokens, prompt) { return Err(invalid("resident MTP prefix mismatch").into()); } old.decoder 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 5337b909..4447aff2 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs @@ -146,7 +146,7 @@ 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 first CUDA context user. +/// --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"); @@ -266,8 +266,8 @@ 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(); - let loaded = bind_laptop(start); configure_cells(); + let loaded = bind_laptop(start); 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"); 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 a9c22b26..4436c534 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 @@ -44,16 +44,23 @@ fn open_archive(laptop: bool) -> InheritedKarArchive { fn load_experts(binding: &mut ModelBinding, laptop: bool) { if laptop { binding.load_mapped_expert_source().expect("mapped expert source load failed"); - 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)"); - } } else { 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)"); + } +} fn load(laptop: bool) -> Pinned { + if laptop { + configure_laptop_cells(); + } 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) diff --git a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs index fc80c128..8b4c8125 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs @@ -154,7 +154,9 @@ fn resumable( shared: &Shared, prompt: &[u32], ) -> bool { - if entry.loaded != *loaded || !append_compatible(&entry.continuation.tokens, prompt) { + if entry.loaded != *loaded + || !append_compatible(binding.input_constants().bound_cells(), &entry.continuation.tokens, prompt) + { return false; } let resume = &entry.continuation; diff --git a/crates/engine-qwen35-cuda/src/backend/session.rs b/crates/engine-qwen35-cuda/src/backend/session.rs index d81085e9..da4aa419 100644 --- a/crates/engine-qwen35-cuda/src/backend/session.rs +++ b/crates/engine-qwen35-cuda/src/backend/session.rs @@ -16,10 +16,10 @@ pub(super) struct MtpContinuation { /// Exactly target-committed IDs, never a speculative or merely emitted ID. pub(super) tokens: Vec, } -pub(super) fn append_compatible(committed: &[u32], incoming: &[u32]) -> bool { +pub(super) fn append_compatible(serving_cells: u64, committed: &[u32], incoming: &[u32]) -> bool { !committed.is_empty() - && committed.len() as u64 <= crate::qwen_forward::contract::serving_cells() - && incoming.len() as u64 <= crate::qwen_forward::contract::serving_cells() + && committed.len() as u64 <= serving_cells + && incoming.len() as u64 <= serving_cells && incoming.starts_with(committed) } 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 f508fc69..6e6540df 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs @@ -72,8 +72,14 @@ impl<'a> TensorSignature<'a> { } } +/// What one binding stamps on everything built from it: the serving context in cells, fixed when the model is bound. +pub(crate) struct BindingSeal { + serving_cells: u64, +} + +/// The identity of one model binding: two identities match only when they are clones of the same one. #[derive(Clone)] -pub(crate) struct BindingIdentity(Rc<()>); +pub(crate) struct BindingIdentity(Rc); #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum BoundLayerKind { @@ -92,6 +98,8 @@ pub(crate) struct InputConstants { multipliers: [u64; 3], eos: u32, context_length: u32, + /// The serving context in cells (the bound of every `Position`), fixed when the model is bound. + serving_cells: u32, } pub(crate) struct ModelBinding { @@ -128,8 +136,8 @@ mod tests { } #[test] fn exact_model_identity_is_retained_and_not_reconstructible_from_value() { - let first = BindingIdentity(Rc::new(())); - let second = BindingIdentity(Rc::new(())); + let first = BindingIdentity::new(262_144); + let second = BindingIdentity::new(262_144); assert!(first.matches(&first.clone())); assert!(!first.matches(&second)); } 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 7e64b905..cb196846 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 @@ -3,7 +3,7 @@ //! the artifact (PLE head offsets and vocabularies, EOS, context length) with their validation. use super::{ - BindingIdentity, BoundLayer, BoundLayerKind, InputBindingError, InputConstants, InputResult, PLE_ROWS, + BindingIdentity, BindingSeal, BoundLayer, BoundLayerKind, InputBindingError, InputConstants, InputResult, PLE_ROWS, Qwen4ExpArtifact, Rc, fmt, }; @@ -14,9 +14,16 @@ impl fmt::Display for InputBindingError { } impl std::error::Error for InputBindingError {} impl BindingIdentity { + pub(super) fn new(serving_cells: u64) -> Self { + Self(Rc::new(BindingSeal { serving_cells })) + } pub(crate) fn matches(&self, other: &Self) -> bool { Rc::ptr_eq(&self.0, &other.0) } + /// The serving context in cells (the bound of every `Position`) the model was bound under. + pub(crate) fn bound_cells(&self) -> u64 { + self.0.serving_cells + } } impl BoundLayer { pub(crate) fn index(&self) -> u32 { @@ -38,6 +45,8 @@ 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)?, }; constants.validate()?; Ok(constants) @@ -68,7 +77,11 @@ impl InputConstants { /// The serving context in cells (the bound of every `Position`): 262144 unless the process configured a /// larger one. NOT the artifact's metadata value; that is [`Self::trained_context`]. pub(crate) fn context_length(&self) -> u32 { - crate::qwen_forward::contract::serving_cells() as u32 + self.serving_cells + } + /// The same bound as `u64`, the width of a sequence position. + pub(crate) fn bound_cells(&self) -> u64 { + u64::from(self.serving_cells) } /// The context the artifact was trained over (`context_length` metadata), validated to be 262144. #[allow(dead_code)] 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 7f268be3..86708f07 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 @@ -24,12 +24,13 @@ impl ModelBinding { validate_ple_descriptor(&artifact)?; let layers = bind_layers(&artifact)?; let (expert_count, expert_used_count) = bind_expert_counts(&artifact)?; + let identity = BindingIdentity::new(constants.bound_cells()); Ok(Self { artifact: RefCell::new(artifact), constants, embedding_kind, embedding_bytes, - identity: BindingIdentity(Rc::new(())), + identity, layers, expert_count, expert_used_count, diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs index 6eecb9b7..6e92e777 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs @@ -36,6 +36,7 @@ impl InputConstants { multipliers: [23703573157769, 20109073645365, 8052911324071], eos: 248044, context_length: 262144, + serving_cells: 262144, } } } @@ -68,6 +69,6 @@ pub(super) fn bind_layer(artifact: &Qwen4ExpArtifact, index: u32, interval: u32) #[cfg(test)] impl BindingIdentity { pub(crate) fn test_identity() -> Self { - Self(Rc::new(())) + Self::new(262_144) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs index 64e8041a..4c671279 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs @@ -82,7 +82,7 @@ impl Dimension { } } -/// The serving context in cells: every sequence position lies in `0..serving_cells()`. +/// 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 diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs index 82321638..9bc0c2bc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs @@ -11,9 +11,9 @@ use super::{ }; impl MtpFrame { - fn within_bounds(&self) -> Result { + fn within_bounds(&self, serving_cells: u64) -> Result { Ok(self.token == TokenId::new(u64::from(self.token.get()), Dimension::new(248320)?)? - && self.position.get() < crate::qwen_forward::contract::serving_cells() + && self.position.get() < serving_cells && self.depth < 4) } pub(in super::super) fn validate(&self, binding: &ModelBinding, session: &QwenSession<'_>) -> Result<()> { @@ -22,7 +22,7 @@ impl MtpFrame { return Err(Error::IdentityMismatch); } binding.mtp_weights().map_err(binding_error)?.validate_binding(binding).map_err(binding_error)?; - if !self.within_bounds()? { + if !self.within_bounds(binding.input_constants().bound_cells())? { return Err(Error::IdentityMismatch); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs index 31f5eb5a..cc56a0cf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs @@ -49,17 +49,17 @@ mod tests { #[test] fn exact_transaction_row_bounds_preserve_native64_and_admit_outer256() { - assert_eq!(checked_chunk_end(170000, 64, 64), Ok(170064)); - assert_eq!(checked_chunk_end(170000, 65, 64), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(170000, 64, 64, 262_144), Ok(170064)); + assert_eq!(checked_chunk_end(170000, 65, 64, 262_144), Err(Error::IdentityMismatch)); for rows in [64, 65, 256] { - assert_eq!(checked_chunk_end(190000, rows, 256), Ok(190000 + rows as u64)); + assert_eq!(checked_chunk_end(190000, rows, 256, 262_144), Ok(190000 + rows as u64)); } - assert_eq!(checked_chunk_end(190000, 257, 256), Err(Error::IdentityMismatch)); - assert_eq!(checked_chunk_end(0, 0, 64), Err(Error::IdentityMismatch)); - assert_eq!(checked_chunk_end(0, 65, 65), Err(Error::IdentityMismatch)); - assert_eq!(checked_chunk_end(u64::MAX, 1, 64), Err(Error::Overflow)); - assert_eq!(checked_chunk_end(262080, 64, 64), Ok(262144)); - assert_eq!(checked_chunk_end(262081, 64, 64), Err(Error::InvalidPosition)); + assert_eq!(checked_chunk_end(190000, 257, 256, 262_144), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(0, 0, 64, 262_144), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(0, 65, 65, 262_144), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(u64::MAX, 1, 64, 262_144), Err(Error::Overflow)); + assert_eq!(checked_chunk_end(262080, 64, 64, 262_144), Ok(262144)); + assert_eq!(checked_chunk_end(262081, 64, 64, 262_144), Err(Error::InvalidPosition)); } #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs index 5c5a9210..32fbbe6b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs @@ -8,21 +8,21 @@ use super::{ ValidatedWarmEnd, }; -pub(super) fn checked_chunk_end(start: u64, rows: usize, limit: usize) -> Result { +pub(super) fn checked_chunk_end(start: u64, rows: usize, limit: usize, serving_cells: u64) -> Result { if !matches!(limit, 64 | 256) || rows == 0 || rows > limit { return Err(Error::IdentityMismatch); } let end = start.checked_add(u64::try_from(rows).map_err(|_| Error::Overflow)?).ok_or(Error::Overflow)?; - if end > crate::qwen_forward::contract::serving_cells() { + if end > serving_cells { return Err(Error::InvalidPosition); } Ok(end) } impl ValidatedWarmEnd { - pub(super) fn from_txn(txn: &QwenChunkTxn<'_, '_>) -> Result { + pub(super) fn from_txn(txn: &QwenChunkTxn<'_, '_>, serving_cells: u64) -> Result { let start = txn.start_position(); let rows = txn.rows(); - let end = checked_chunk_end(start, rows.len(), txn.warm_row_limit())?; + let end = checked_chunk_end(start, rows.len(), txn.warm_row_limit(), serving_cells)?; if end != txn.end_position() { return Err(Error::IdentityMismatch); } @@ -49,7 +49,7 @@ impl MtpSession { binding: &ModelBinding, txn: &QwenChunkTxn<'_, '_>, ) -> Result> { - let bound = ValidatedWarmEnd::from_txn(txn)?; + let bound = ValidatedWarmEnd::from_txn(txn, binding.input_constants().bound_cells())?; let target = txn.original_session()?; let start = Position::new(txn.start_position(), crate::qwen_forward::contract::position_dimension())?; binding @@ -72,7 +72,7 @@ impl MtpSession { anchor: TargetStepOrigin, start: Position, ) -> Result> { - let end = checked_chunk_end(start.get(), 64, 64)?; + let end = checked_chunk_end(start.get(), 64, 64, 262_144)?; self.stage_chunk_with_end(target, anchor, start, ValidatedWarmEnd(end)) } pub(super) fn stage_chunk_with_end<'a>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs index d00ef22e..cd95e4b4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs @@ -15,7 +15,7 @@ impl DenseKv { || !Rc::ptr_eq(&self.owner, &frame.epoch) || frame.generation != frame.epoch.get() || frame.position.get() != self.next_position - || self.next_position >= crate::qwen_forward::contract::serving_cells() + || self.next_position >= self.binding.bound_cells() { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs index c2ef55a6..44422f37 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs @@ -65,7 +65,7 @@ impl MtpSession { || !Rc::ptr_eq(&self.kv.owner, &self.epoch) || self.kv.next_position != self.next_position || self.next_position == 0 - || self.next_position > crate::qwen_forward::contract::serving_cells() + || self.next_position > binding.input_constants().bound_cells() || self.target_owner.as_ref().is_none_or(|old| !old.same_session(¤t.origin)) { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs index ae61a8d7..9d8d32ce 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs @@ -34,7 +34,7 @@ impl MtpKvPrefill { original: &MtpSession, tokens: &[TokenId], ) -> Result { - Self::admit_tokens(tokens)?; + Self::admit_tokens(tokens, binding.input_constants().bound_cells())?; binding.mtp_weights().map_err(mtp::binding_error)?.validate_binding(binding).map_err(mtp::binding_error)?; let anchor = target.target_origin()?; anchor.validate(target)?; @@ -46,8 +46,8 @@ impl MtpKvPrefill { owner.validate_original(binding, original, target)?; Ok(owner) } - fn admit_tokens(tokens: &[TokenId]) -> Result<()> { - if tokens.len() < 2 || tokens.len() as u64 > crate::qwen_forward::contract::serving_cells() { + fn admit_tokens(tokens: &[TokenId], serving_cells: u64) -> Result<()> { + if tokens.len() < 2 || tokens.len() as u64 > serving_cells { return Err(Error::InvalidDimension); } let vocab = Dimension::new(248320)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs index 7312adca..d43830b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs @@ -85,7 +85,7 @@ fn admit_run<'a, 'd>( input.frame().validate(binding, session)?; let prior = draft.prior(input.frame())?; validate_read_values(input)?; - let geometry = geometry(input.frame().position().get())?; + let geometry = geometry(input.frame().position().get(), binding.input_constants().bound_cells())?; check_roles( binding, &[ @@ -198,7 +198,7 @@ pub(in super::super) fn produce_kv_cell( ) -> Result { input.frame().validate(binding, session)?; validate_read_values(input)?; - let geometry = geometry(input.frame().position().get())?; + let geometry = geometry(input.frame().position().get(), binding.input_constants().bound_cells())?; check_roles( binding, &[ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs index 09552f82..3484991a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs @@ -8,8 +8,8 @@ use super::{ validate_values, }; -pub(super) fn geometry(position: u64) -> Result { - if position >= crate::qwen_forward::contract::serving_cells() { +pub(super) fn geometry(position: u64, serving_cells: u64) -> Result { + if position >= serving_cells { return Err(Error::InvalidPosition); } let position = u32::try_from(position).map_err(|_| Error::InvalidPosition)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs index 4ba4a4d3..ff55f60a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs @@ -23,7 +23,7 @@ pub(super) struct Tiny { impl Tiny { pub(super) fn new() -> Self { let (keys, values) = half_kv(1, false); - Self { query: vec![0.125; Q], gate: vec![0.25; Q], keys, values, shape: geometry(0).unwrap() } + Self { query: vec![0.125; Q], gate: vec![0.25; Q], keys, values, shape: geometry(0, 262_144).unwrap() } } /// The one-cell key and value window. fn window(&self) -> KvWindow<'_> { @@ -47,7 +47,7 @@ fn pair_inputs(zero: bool) -> (Vec, Vec) { impl<'c> Env<'c> { fn pair_case(&self, matrix: &DeviceBuffer<'_>, position: u32, zero: bool) { let context = self.context; - let shape = geometry(u64::from(position)).unwrap(); + let shape = geometry(u64::from(position), 262_144).unwrap(); let (query, gate) = pair_inputs(zero); let (query_bits, gate_bits) = (bits(&query), bits(&gate)); let (keys, values) = half_kv(shape.width, zero); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs index 8e0eb2e1..72db5e31 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs @@ -14,17 +14,17 @@ fn mtp_attention_new_causal_geometry_and_budget_boundaries() { (32768, 32768, 33554432, 12681472), (262143, 32768, 33554432, 12681472), ] { - let g = geometry(position).unwrap(); + let g = geometry(position, 262_144).unwrap(); assert_eq!((g.width, g.half_bytes, g.scratch), (width, half_bytes, scratch)); assert_eq!(g.device_bytes, 2 * half_bytes + scratch + 49152 + 2097152); } - for position in [crate::qwen_forward::contract::serving_cells(), u32::MAX as u64, u64::MAX] { - assert!(matches!(geometry(position), Err(Error::InvalidPosition))); + for position in [262_144, u32::MAX as u64, u64::MAX] { + assert!(matches!(geometry(position, 262_144), Err(Error::InvalidPosition))); } } #[test] fn mtp_attention_new_window_shape_halfdomains_and_caller_preservation() { - let g = geometry(0).unwrap(); + let g = geometry(0, 262_144).unwrap(); let mut keys = vec![0u8; 1024]; let mut values = vec![0u8; 1024]; for (i, word) in [0x0001u16, 0x8000, 0x0400, 0x7bff].into_iter().enumerate() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs index 30fd5619..8a5646ca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs @@ -60,12 +60,12 @@ mod tests { #[test] fn window_never_exceeds_remaining_or_last_target_position() { - assert_eq!(window_limit(0, 4, 9), Ok(4)); - assert_eq!(window_limit(0, 4, 2), Ok(2)); - assert_eq!(window_limit(262140, 4, 9), Ok(3)); - assert_eq!(window_limit(262142, 4, 9), Ok(1)); - assert_eq!(window_limit(262143, 4, 9), Err(Error::InvalidPosition)); - assert_eq!(window_limit(u64::MAX, 4, 9), Err(Error::Overflow)); + assert_eq!(window_limit(0, 4, 9, 262_144), Ok(4)); + assert_eq!(window_limit(0, 4, 2, 262_144), Ok(2)); + assert_eq!(window_limit(262140, 4, 9, 262_144), Ok(3)); + assert_eq!(window_limit(262142, 4, 9, 262_144), Ok(1)); + assert_eq!(window_limit(262143, 4, 9, 262_144), Err(Error::InvalidPosition)); + assert_eq!(window_limit(u64::MAX, 4, 9, 262_144), Err(Error::Overflow)); } } @@ -92,7 +92,7 @@ mod draft_bound_tests { for position in [0, 262140, 262142] { for depth in 1..=4 { for remaining in 1..=6 { - let limit = window_limit(position, depth, remaining).unwrap(); + let limit = window_limit(position, depth, remaining, 262_144).unwrap(); assert_capacity_cases(&predictions, limit); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs index b5aff2b2..8a5e1711 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs @@ -25,9 +25,9 @@ pub(super) fn needed_draft_predictions(capacity: usize, limit: usize) -> Result< capacity.min(limit).checked_sub(1).ok_or(Error::Overflow) } -pub(super) fn window_limit(position: u64, depth: usize, remaining: usize) -> Result { +pub(super) fn window_limit(position: u64, depth: usize, remaining: usize, serving_cells: u64) -> Result { let next = position.checked_add(1).ok_or(Error::Overflow)?; - let available = crate::qwen_forward::contract::serving_cells().checked_sub(next).ok_or(Error::InvalidPosition)?; + let available = serving_cells.checked_sub(next).ok_or(Error::InvalidPosition)?; let limit = depth.min(remaining).min(usize::try_from(available).map_err(|_| Error::Overflow)?); if limit == 0 { Err(Error::InvalidPosition) } else { Ok(limit) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs index 86f1f904..df384c62 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs @@ -55,7 +55,7 @@ impl MtpDecoder { return Ok(Err(eos)); } self.require_batched_admission(cache)?; - let limit = window_limit(source_position, spec.depth, spec.remaining)?; + let limit = window_limit(source_position, spec.depth, spec.remaining, binding.input_constants().bound_cells())?; Ok(Ok(self.batched_sizing(request, target, cache, WindowHead { first, limit })?)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs index 63900082..110b134b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs @@ -18,11 +18,12 @@ impl MtpDecoder { if prompt.len() == 1 { return Ok(decoder); } - if !(2..=crate::qwen_forward::contract::serving_cells() as usize).contains(&prompt.len()) { + let serving_cells = binding.input_constants().bound_cells(); + if !(2..=serving_cells as usize).contains(&prompt.len()) { return Err(Error::InvalidDimension); } // Admit this persistent baseline before allocating the owner/queue. - let host_charge = kv_prefill_host_charge(prompt.len())?; + let host_charge = kv_prefill_host_charge(prompt.len(), serving_cells)?; if host_charge > 512 * 1024 * 1024 { return Err(Error::InputAllocation); } @@ -67,7 +68,7 @@ impl MtpDecoder { ) -> Result<()> { let (token, position, _, origin) = source.mtp_source(binding, target)?; if committed.is_empty() - || committed.len() as u64 > crate::qwen_forward::contract::serving_cells() + || committed.len() as u64 > binding.input_constants().bound_cells() || position.get().checked_add(1) != Some(committed.len() as u64) || committed.last().copied() != Some(token.get()) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs index f7572575..0824f0a5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs @@ -67,7 +67,7 @@ fn scalar_start( if Some(first) == spec.eos { return Ok(Err(true)); } - let limit = window_limit(source_position, spec.depth, spec.remaining)?; + let limit = window_limit(source_position, spec.depth, spec.remaining, binding.input_constants().bound_cells())?; Ok(Ok((first, source_position, limit))) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs index 5a7aa4a3..f6d1498e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs @@ -38,8 +38,8 @@ impl MtpVerifiedWindow { // Conservative charge separate from the transaction's existing 98MiB MTP // temporaries: actual 64MiB payload, cell/allocator metadata, three bounded // pointer vectors, and conversion Vec + immutable actual whole-prompt Box. -pub(super) fn kv_prefill_host_charge(prompt_len: usize) -> Result { - if !(2..=crate::qwen_forward::contract::serving_cells() as usize).contains(&prompt_len) { +pub(super) fn kv_prefill_host_charge(prompt_len: usize, serving_cells: u64) -> Result { + if !(2..=serving_cells as usize).contains(&prompt_len) { return Err(Error::InvalidDimension); } (64usize * 1024 * 1024) 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 74892860..3baae87a 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 @@ -62,16 +62,15 @@ impl StackConfig { fn capacity_invalid(&self) -> bool { !ADMITTED_CAPACITIES.contains(&self.capacity) || self.kv_footprint().is_none() || self.capacity > 8192 } - fn context_invalid(&self) -> bool { - self.max_context < 1 - || self.max_context as u64 > super::super::contract::serving_cells() - || !(1..=64).contains(&self.cpu_workers) + 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) } - pub(crate) fn validate(&self) -> Result<()> { + /// `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<()> { if self.kv_format != KvFormat::Int8 { return Err(Error::Unsupported(super::super::contract::Stage::Session)); } - if self.capacity_invalid() || self.context_invalid() { + if self.capacity_invalid() || self.context_invalid(serving_cells) { 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 74e37f21..1dad386f 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,7 +39,7 @@ 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().map_err(at("config.validate"))?; + config.validate(binding.input_constants().bound_cells()).map_err(at("config.validate"))?; // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { error: Error::InvalidDimension, 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 762f9f38..cee01510 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 @@ -33,8 +33,7 @@ pub(super) struct Assembly<'a, 'ctx> { /// The cell count, the window policies, the RoPE constants, the expert blob sizes and formats and the prefill layout, /// in the order `open` computed them. pub(super) fn prepare(binding: &ModelBinding, config: &StackConfig) -> std::result::Result { - let max_cells = - usize::try_from(crate::qwen_forward::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; + let max_cells = usize::try_from(binding.input_constants().bound_cells()).map_err(|_| failure(Error::Overflow))?; let policies = serve_policies(config)?; let rope = RopeConstants::from_serving_context(); let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs index 27b2dd32..2e78bde1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs @@ -236,7 +236,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let (options, reread_to) = self.prompt_options(resume)?; let capacity = self.config.capacity; let plan = PromptPlan::new_in_context( - crate::qwen_forward::contract::serving_cells(), + self.binding.input_constants().bound_cells(), tokens, ResumePoint { resume, reread_to }, None, 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 8031996a..f875782f 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 @@ -32,15 +32,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().is_ok(), "{capacity}"); + assert!(StackConfig { capacity, ..config.clone() }.validate(262_144).is_ok(), "{capacity}"); } for capacity in [0usize, 255, 300, 16384, 32768] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); + assert!(StackConfig { capacity, ..config.clone() }.validate(262_144).is_err(), "{capacity}"); } - assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); - assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); + 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()); } #[test] @@ -52,8 +52,8 @@ 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().is_ok()); - assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); + assert!(config.validate(262_144).is_ok()); + assert!(StackConfig { conversation: None, ..config }.validate(262_144).is_ok(), "the cache can be turned off"); } #[test] @@ -62,12 +62,12 @@ fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); assert_eq!(config.kv_footprint().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().is_ok(), "{kv_resident}"); + assert!(StackConfig { kv_resident, ..config.clone() }.validate(262_144).is_ok(), "{kv_resident}"); } - assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); + assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate(262_144).is_err()); for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { assert_eq!( - StackConfig { kv_format, ..config.clone() }.validate(), + StackConfig { kv_format, ..config.clone() }.validate(262_144), Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) ); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs index 461e4fd9..422a55ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs @@ -170,11 +170,11 @@ mod tests { use super::*; #[test] fn chunk_incremental_retention_is_bounded_and_refuses_invalid_counts() { - assert_eq!(host_charge(0, 0), Err(Error::InvalidDimension)); - assert_eq!(host_charge(65, 1), Err(Error::InvalidDimension)); - assert_eq!(host_charge(4, 262145), Err(Error::InvalidDimension)); - assert!(host_charge(64, 190000).unwrap() < 512 * 1024 * 1024); - assert!(host_charge(64, 190000).unwrap() > host_charge(4, 190000).unwrap()); + assert_eq!(host_charge(0, 0, 262_144), Err(Error::InvalidDimension)); + assert_eq!(host_charge(65, 1, 262_144), Err(Error::InvalidDimension)); + assert_eq!(host_charge(4, 262145, 262_144), Err(Error::InvalidDimension)); + assert!(host_charge(64, 190000, 262_144).unwrap() < 512 * 1024 * 1024); + assert!(host_charge(64, 190000, 262_144).unwrap() > host_charge(4, 190000, 262_144).unwrap()); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs index 3cb0b173..f5d04e4b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs @@ -265,6 +265,6 @@ impl ChunkCommit { // Charge new rolling GDN/PLE, two QSA pointer vectors and appended pages, // all T inputs + residuals + copied warm witnesses; baseline owners/caches // remain charged externally. Does not retain T full recurrent snapshots. -pub(super) fn host_charge(tokens: usize, end: u64) -> Result { - host_charge_bounded(tokens, end, 64) +pub(super) fn host_charge(tokens: usize, end: u64, serving_cells: u64) -> Result { + host_charge_bounded(tokens, end, 64, serving_cells) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs index 39409dea..f37bf440 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs @@ -4,8 +4,8 @@ use super::{Error, Rc, Result}; -pub(super) fn host_charge_bounded(tokens: usize, end: u64, limit: usize) -> Result { - if !(1..=limit).contains(&tokens) || end > crate::qwen_forward::contract::serving_cells() { +pub(super) fn host_charge_bounded(tokens: usize, end: u64, limit: usize, serving_cells: u64) -> Result { + if !(1..=limit).contains(&tokens) || end > serving_cells { return Err(Error::InvalidDimension); } let rolling: usize = 36 * (786432 + 30720) * 4 + 9 * 10240 * 4; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs index 5213dba6..30a19213 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs @@ -180,11 +180,11 @@ fn prompt_origin( } Ok(origin) } -/// The end position of the prompt, which must stay below the model context and the served cells. +/// The end position of the prompt, which must stay below the served cells (the model context of the binding). fn prompt_end(session: &QwenSession<'_>, binding: &ModelBinding, count: usize) -> Result<(u64, Dimension)> { let end = session.next_position.checked_add(count as u64).ok_or(Error::Overflow)?; let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?; - if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() { + if end >= u64::from(context_bound.get()) { return Err(Error::InvalidPosition); } Ok((end, context_bound)) @@ -207,7 +207,12 @@ fn admit_prompt_host( (end, host_remaining, windowed): (u64, usize, bool), ) -> Result<()> { check_vocab(tokens, known_next)?; - let charge = if windowed { host_charge_bounded(tokens.len(), end, 256)? } else { host_charge(tokens.len(), end)? }; + let cells = session.binding.bound_cells(); + let charge = if windowed { + host_charge_bounded(tokens.len(), end, 256, cells)? + } else { + host_charge(tokens.len(), end, cells)? + }; if charge > host_remaining { return Err(Error::InputAllocation); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs index 7ac97543..89dbe9cf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs @@ -43,10 +43,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::IdentityMismatch); } let end = session.next_position.checked_add(tokens as u64).ok_or(Error::Overflow)?; - let total = verification_total_charge(tokens, end)?; - if end >= u64::from(binding.input_constants().context_length()) - || end >= crate::qwen_forward::contract::serving_cells() - { + let total = verification_total_charge(tokens, end, binding.input_constants().bound_cells())?; + if end >= u64::from(binding.input_constants().context_length()) { return Err(Error::InvalidPosition); } if total > host_remaining.min(HOST_LIMIT) { @@ -63,7 +61,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ) -> Result { Self::preflight_mtp_verification(session, binding, tokens.len(), host_remaining)?; let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?; - let extra = verification_extra_charge(tokens.len(), end)?; + let extra = verification_extra_charge(tokens.len(), end, binding.input_constants().bound_cells())?; let available = host_remaining.min(HOST_LIMIT).checked_sub(extra).ok_or(Error::InputAllocation)?; // Both charges are admitted before rows, pointer journals or numeric // producers allocate. This preserves the old admission and VRAM cap. @@ -83,8 +81,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// The host charge of the rows plus the device-GDN metadata must fit what remains of the verification cap. fn admit_verification_charge(&self, metadata: usize, host_remaining: usize) -> Result<()> { - let charged = host_charge_bounded(self.rows.len(), self.end, 256)? - .checked_add(verification_extra_charge(self.rows.len(), self.end)?) + let serving_cells = self.session.binding.bound_cells(); + let charged = host_charge_bounded(self.rows.len(), self.end, 256, serving_cells)? + .checked_add(verification_extra_charge(self.rows.len(), self.end, serving_cells)?) .and_then(|n| n.checked_add(metadata)) .ok_or(Error::Overflow)?; if charged > host_remaining.min(HOST_LIMIT) { @@ -388,7 +387,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } /// The host charge of `tokens` rows ending at `end` plus the verification extra charge. -fn verification_total_charge(tokens: usize, end: u64) -> Result { - let extra = verification_extra_charge(tokens, end)?; - host_charge_bounded(tokens, end, 256)?.checked_add(extra).ok_or(Error::Overflow) +fn verification_total_charge(tokens: usize, end: u64, serving_cells: u64) -> Result { + let extra = verification_extra_charge(tokens, end, serving_cells)?; + host_charge_bounded(tokens, end, 256, serving_cells)?.checked_add(extra).ok_or(Error::Overflow) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs index 3615e73f..1c5a2630 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs @@ -30,17 +30,17 @@ fn real_head_decision_stops_at_first_rejection_or_eos() { } #[test] fn complete_journal_charge_preserves_512_mib_refusal() { - assert_eq!(verification_extra_charge(0, 1), Err(Error::InvalidDimension)); - assert_eq!(verification_extra_charge(5, 5), Err(Error::InvalidDimension)); - assert_eq!(verification_extra_charge(2, 262145), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(0, 1, 262_144), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(5, 5, 262_144), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(2, 262145, 262_144), Err(Error::InvalidDimension)); for rows in [2, 3] { - let charge = host_charge_bounded(rows, rows as u64, 256).unwrap() - + verification_extra_charge(rows, rows as u64).unwrap(); + let charge = host_charge_bounded(rows, rows as u64, 256, 262_144).unwrap() + + verification_extra_charge(rows, rows as u64, 262_144).unwrap(); assert!(charge < HOST_LIMIT); } - let four = host_charge_bounded(4, 4, 256).unwrap() + verification_extra_charge(4, 4).unwrap(); + let four = host_charge_bounded(4, 4, 256, 262_144).unwrap() + verification_extra_charge(4, 4, 262_144).unwrap(); assert!(four > HOST_LIMIT); - assert!(verification_extra_charge(3, 190000).unwrap() > verification_extra_charge(3, 3).unwrap()); + assert!(verification_extra_charge(3, 190000, 262_144).unwrap() > verification_extra_charge(3, 3, 262_144).unwrap()); } // This tests private session/phase admission, NOT a ModelBinding, CUDA diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs index 168b1746..4652fd22 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs @@ -11,8 +11,8 @@ impl VerifiedTargetPrefix { // Existing admission already charges one rolling state. Journal references // retain T-1 additional genuine states, PLE histories and QSA pointer vectors. -pub(super) fn verification_extra_charge(tokens: usize, end: u64) -> Result { - if !(1..=4).contains(&tokens) || end > crate::qwen_forward::contract::serving_cells() { +pub(super) fn verification_extra_charge(tokens: usize, end: u64, serving_cells: u64) -> Result { + if !(1..=4).contains(&tokens) || end > serving_cells { return Err(Error::InvalidDimension); } let extra = tokens - 1;