From a75eb041d52b59bb481311acdf49a63bac977a8d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 01:56:32 +0100 Subject: [PATCH 01/42] STRA-338 params e03: forward step takes StepRequest/StepCaches/StepPurpose; layer phases take LayerSite/LayerEntry; window proof takes LoadedOwners Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_attention.rs --- .../src/backend/generate.rs | 17 +-- .../combined_changed_boundary_proof.rs | 20 ++- .../src/qwen_forward/executor.rs | 7 + .../impl_qwenforward/impl_qwenforward_2.rs | 143 ++++++------------ .../impl_qwenforward/impl_qwenforward_2_2.rs | 18 +-- .../executor/read_layer_attention_fn.rs | 18 ++- .../executor/reset_replay_sdet.rs | 43 +++--- .../qwen_forward/executor/step_layer_fns.rs | 16 +- .../src/qwen_forward/executor/step_request.rs | 66 ++++++++ .../qwen_forward/executor_mmq_evaluation.rs | 28 +--- .../check_chunk_on_loaded_fn.rs | 24 +-- .../impl_qwenforward_3/window_attention.rs | 3 +- .../qwen_forward/executor_window_numeric.rs | 15 +- .../executor_window_numeric/proof.rs | 102 ++++++------- .../impl_mtpdecoder/impl_mtpdecoder_3.rs | 14 +- .../check_loaded_fn/position_at_fn.rs | 14 +- .../src/qwen_forward/oracle_capture.rs | 8 +- 17 files changed, 267 insertions(+), 289 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor/step_request.rs diff --git a/crates/engine-qwen35-cuda/src/backend/generate.rs b/crates/engine-qwen35-cuda/src/backend/generate.rs index 6e723e25..b555e176 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate.rs @@ -1,5 +1,6 @@ //! The single-token generation step loop. use super::*; +use crate::qwen_forward::executor::{StepCaches, StepRequest}; pub(super) struct Generation<'a, 'context, 'driver, C: Clock = SystemClock> { pub(super) execution: EvaluationExecution, @@ -68,14 +69,10 @@ impl Generation<'_, '_, '_, C> { let token = TokenId::new(u64::from(token), vocabulary).map_err(|_| invalid("native token invalid"))?; let position = native_position(self.binding.input_constants(), self.context_tokens, position)?; let forwarded = QwenForward::step_cached( - self.binding, - token, - position, + StepRequest { binding: self.binding, token, position }, self.session, self.output, - self.kar_cache.as_deref_mut(), - self.moe_cache, - self.dense_cache, + StepCaches { kar: self.kar_cache.as_deref_mut(), moe: Some(self.moe_cache), dense: Some(self.dense_cache) }, ); let token = forwarded.map_err(|failure| self.forward_failure(failure, position))?; if self.cancelled() { @@ -104,14 +101,10 @@ impl Generation<'_, '_, '_, C> { .map_err(|e| self.mtp_error(e))?; let position = native_position(self.binding.input_constants(), self.context_tokens, position)?; let result = QwenForward::step_for_mtp_cached( - self.binding, - token, - position, + StepRequest { binding: self.binding, token, position }, self.session, self.output, - self.kar_cache.as_deref_mut(), - Some(self.moe_cache), - Some(self.dense_cache), + StepCaches { kar: self.kar_cache.as_deref_mut(), moe: Some(self.moe_cache), dense: Some(self.dense_cache) }, ); let product = result.map_err(|e| self.mtp_error(e))?; if self.cancelled() { diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs index 180bb78b..364c242e 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs @@ -1,5 +1,6 @@ //! Private sole new changed-path model gate; actual source identity/load preserved. use super::*; +use crate::qwen_forward::executor::{LoadedCaches, LoadedOwners}; use std::env; #[path = "combined_changed_boundary_proof/rig.rs"] pub(super) mod rig; @@ -32,16 +33,18 @@ fn pinned_single_load_layer0_and_window_boundaries() { let device = driver.device(0).expect("prefix CUDA device0 unavailable"); let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL)); - // Both helpers use genuine fresh target owners on the one admitted - // binding/context/cache. No second source load or CUDA context is created. + // Both helpers use genuine fresh target owners on the one admitted binding/context/cache: no second load. let layer0 = owners.run(&binding, &context, QwenForward::test_layer0_pair_on_loaded); - let window = matches!(&layer0, Ok(Ok(_))) - .then(|| owners.run(&binding, &context, QwenForward::test_window_boundaries_on_loaded)); + let window = matches!(&layer0, Ok(Ok(_))).then(|| { + owners.run(&binding, &context, |binding, session, output, kar, moe, dense| { + let caches = LoadedCaches { kar, moe, dense }; + QwenForward::test_window_boundaries_on_loaded(binding, session, LoadedOwners { output, caches }) + }) + }); let mut teardown = owners.close(true); teardown.close_context(context); drop((binding, inherited)); - // Preserve the phase failure after every teardown attempt; a later - // cleanup assertion must not obscure its original diagnostic cause. + // Preserve the phase failure after every teardown attempt; a later cleanup must not obscure its cause. let report = unwrap_phase(layer0, "same-source layer0 diagnostic refused"); let window = unwrap_phase(window.expect("window proof was not admitted"), "changed window proof refused"); teardown.assert_clean(); @@ -49,6 +52,11 @@ fn pinned_single_load_layer0_and_window_boundaries() { .write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR")) .expect("exclusive bounded layer0 diagnostic write failed"); window.assert_success_and_print(); + print_layer0_diagnostic_complete(); +} + +/// The closing line of the combined proof: what the layer0 diagnostic did and did not claim. +fn print_layer0_diagnostic_complete() { eprintln!( "layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled \ final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false \ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs index 362279c4..745eac7e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs @@ -82,6 +82,10 @@ use impl_prefillstepproduct::diagnose; mod impl_qwenforward; mod read_layer_attention_fn; mod step_layer_fns; +mod step_request; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unused_imports)] +use read_layer_attention_fn::LayerEntry; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] use read_layer_attention_fn::prepare_layer_attention_micro; @@ -91,3 +95,6 @@ use read_layer_attention_fn::read_layer_attention; use read_layer_attention_fn::validate_descriptors; #[allow(unused_imports)] use read_layer_attention_fn::validate_layer_plan; +#[cfg(test)] +pub(crate) use step_request::{LoadedCaches, LoadedOwners}; +pub(crate) use step_request::{StepCaches, StepPurpose, StepRequest}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs index 9c203f27..67312143 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs @@ -10,7 +10,7 @@ impl QwenForward { pos: Position, session: &mut QwenSession<'_>, ) -> Result { - Self::step_inner(binding, token, pos, session, None, None) + Self::step_inner(StepRequest { binding, token, position: pos }, session, None, None) } /// Complete-forward entry retains the loaded output head across tokens. @@ -22,139 +22,90 @@ impl QwenForward { session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, ) -> Result { - Self::step_inner(binding, token, pos, session, Some(output), None) + Self::step_inner(StepRequest { binding, token, position: pos }, session, Some(output), None) } /// Explicit loaded KAR provider. Cache lifetime is borrowed from the /// caller's stable owner-thread Context; it is never self-referential. pub(crate) fn step_with_kar_ple_output( - binding: &ModelBinding, - token: TokenId, - pos: Position, + request: StepRequest<'_>, session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, cache: &mut KarPleCache<'_>, ) -> Result { - Self::step_inner(binding, token, pos, session, Some(output), Some(cache)) + Self::step_inner(request, session, Some(output), Some(cache)) } pub(in super::super) fn step_inner( - binding: &ModelBinding, - token: TokenId, - pos: Position, + request: StepRequest<'_>, session: &mut QwenSession<'_>, output: Option<&OutputStage<'_, '_>>, kar_cache: Option<&mut KarPleCache<'_>>, ) -> Result { - Self::step_core(binding, token, pos, session, output, kar_cache, None, None, false, false) + let caches = StepCaches { kar: kar_cache, moe: None, dense: None }; + Self::step_core(request, session, output, caches, StepPurpose::Greedy) .and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch)) } /// Retain the pre-output four-stream residual only for explicit MTP use. /// Native/KAR callers above keep their original allocation and math path. pub(crate) fn step_for_mtp( - binding: &ModelBinding, - token: TokenId, - pos: Position, + request: StepRequest<'_>, session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, kar_cache: Option<&mut KarPleCache<'_>>, ) -> Result { - Self::step_for_mtp_cached(binding, token, pos, session, output, kar_cache, None, None) - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn step_cached( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, - ) -> Result { - Self::step_core( - binding, - token, - pos, - session, - Some(output), - kar_cache, - Some(moe_cache), - Some(dense_cache), - false, - false, - ) - .and_then(|(token, _)| token.ok_or(Error::IdentityMismatch)) - } - #[allow(clippy::too_many_arguments)] - pub(crate) fn step_for_mtp_cached( - binding: &ModelBinding, - token: TokenId, - pos: Position, - session: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: Option<&mut MoeWeightCache<'_>>, - dense_cache: Option<&DenseWeightCache<'_>>, - ) -> Result { - let (predicted, streams) = Self::step_core( - binding, - token, - pos, - session, - Some(output), - kar_cache, - moe_cache, - dense_cache, - true, - false, - )?; - target_product(binding, token, pos, session, predicted, streams) + let caches = StepCaches { kar: kar_cache, moe: None, dense: None }; + Self::step_for_mtp_cached(request, session, output, caches) } - #[allow(clippy::too_many_arguments)] - pub(crate) fn prefill_for_mtp_cached( - binding: &ModelBinding, - token: TokenId, - pos: Position, + /// A complete greedy step through the supplied weight caches. + pub(crate) fn step_cached( + request: StepRequest<'_>, session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - moe_cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, + caches: StepCaches<'_, '_, '_, '_>, + ) -> Result { + Self::step_core(request, session, Some(output), caches, StepPurpose::Greedy) + .and_then(|(token, _)| token.ok_or(Error::IdentityMismatch)) + } + + /// A complete step through the supplied weight caches that retains the MTP target product. + pub(crate) fn step_for_mtp_cached( + request: StepRequest<'_>, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + caches: StepCaches<'_, '_, '_, '_>, + ) -> Result { + let (predicted, streams) = Self::step_core(request, session, Some(output), caches, StepPurpose::MtpTarget)?; + target_product(request, session, predicted, streams) + } + + /// A known-next prefill step through the supplied weight caches that retains the MTP prefill product. + pub(crate) fn prefill_for_mtp_cached( + request: StepRequest<'_>, + session: &mut QwenSession<'_>, + output: &OutputStage<'_, '_>, + caches: StepCaches<'_, '_, '_, '_>, ) -> Result { - let (predicted, streams) = Self::step_core( - binding, - token, - pos, - session, - Some(output), - kar_cache, - Some(moe_cache), - Some(dense_cache), - true, - true, - )?; + let (predicted, streams) = Self::step_core(request, session, Some(output), caches, StepPurpose::MtpPrefill)?; if predicted.is_some() { return Err(Error::IdentityMismatch); } - prefill_product(binding, token, pos, session, streams) + prefill_product(request, session, streams) } } fn target_product( - binding: &ModelBinding, - token: TokenId, - pos: Position, + request: StepRequest<'_>, session: &QwenSession<'_>, predicted: Option, streams: Option>, ) -> Result { Ok(TargetStepProduct { - binding: binding.identity(), - token, - position: pos, + binding: request.binding.identity(), + token: request.token, + position: request.position, predicted: predicted.ok_or(Error::IdentityMismatch)?, streams: streams.ok_or(Error::IdentityMismatch)?, origin: session.target_origin()?, @@ -162,16 +113,14 @@ fn target_product( } fn prefill_product( - binding: &ModelBinding, - token: TokenId, - pos: Position, + request: StepRequest<'_>, session: &QwenSession<'_>, streams: Option>, ) -> Result { Ok(PrefillStepProduct { - binding: binding.identity(), - token, - position: pos, + binding: request.binding.identity(), + token: request.token, + position: request.position, streams: streams.ok_or(Error::IdentityMismatch)?, origin: session.target_origin()?, }) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs index d2360663..41404d57 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs @@ -9,19 +9,15 @@ use super::*; impl QwenForward { /// A forward without its output head can never publish, so it is refused before reading any row or running any /// layer. The cache preparation above keeps its precedence; nothing has been staged yet. - #[allow(clippy::too_many_arguments)] pub(in super::super) fn step_core( - binding: &ModelBinding, - token: TokenId, - pos: Position, + request: StepRequest<'_>, session: &mut QwenSession<'_>, output: Option<&OutputStage<'_, '_>>, - kar_cache: Option<&mut KarPleCache<'_>>, - mut moe_cache: Option<&mut MoeWeightCache<'_>>, - dense_cache: Option<&DenseWeightCache<'_>>, - capture_mtp: bool, - prefill_only: bool, + caches: StepCaches<'_, '_, '_, '_>, + purpose: StepPurpose, ) -> Result { + let StepRequest { binding, token, position: pos } = request; + let StepCaches { kar: kar_cache, moe: mut moe_cache, dense: dense_cache } = caches; let mut streams = None; let ctx = LayerCtx { binding, token, pos, dense: dense_cache }; let predicted = session.transact_completion(token, pos, &binding.identity(), |txn| { @@ -29,8 +25,8 @@ impl QwenForward { let output = output.ok_or(Error::Unsupported(Stage::Output))?; stage_input_row(binding, token, pos, kar_cache, txn)?; let final_residual = run_layers(&ctx, txn, layer_bound, moe_cache.as_deref_mut())?; - let predicted = finish_step(&ctx, txn, output, &final_residual, prefill_only)?; - if capture_mtp { + let predicted = finish_step(&ctx, txn, output, &final_residual, purpose.is_prefill_only())?; + if purpose.retains_streams() { streams = Some(capture_streams(&final_residual)?); } Ok(predicted) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs index 01c375f4..b32f0f28 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs @@ -53,18 +53,26 @@ fn read_layer_one<'cache, 'ctx>( GrStage::read_attention_after_ple(binding, layer, &ple, txn, cache) } +/// A layer about to be read together with the residual left by the layer before it (none for the first layer). +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[derive(Clone, Copy)] +pub(super) struct LayerEntry<'a> { + pub(super) layer: LayerId, + pub(super) previous: Option<&'a InjectedResidual>, +} + /// Mint the actual row input without performing a scalar GR read. The real /// layer-one PLE history still advances in chronological transaction order; /// the caller completes GR only after collecting the genuine micro-window. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) fn prepare_layer_attention_micro( binding: &ModelBinding, - layer: LayerId, - previous: Option<&InjectedResidual>, + entry: LayerEntry<'_>, txn: &mut QwenStepTxn, cache: &DenseWeightCache<'_>, ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>, ) -> Result { + let LayerEntry { layer, previous } = entry; match layer.get() { 0 => { if previous.is_some() { @@ -72,7 +80,7 @@ pub(super) fn prepare_layer_attention_micro( } GrStage::prepare_micro_initial(binding, layer, txn) } - 1 => prepare_layer_one_micro(binding, layer, previous, txn, cache, ple_micro), + 1 => prepare_layer_one_micro(binding, entry, txn, cache, ple_micro), _ => GrStage::prepare_micro_after_ffn(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn), } } @@ -80,12 +88,12 @@ pub(super) fn prepare_layer_attention_micro( #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn prepare_layer_one_micro( binding: &ModelBinding, - layer: LayerId, - previous: Option<&InjectedResidual>, + entry: LayerEntry<'_>, txn: &mut QwenStepTxn, cache: &DenseWeightCache<'_>, ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>, ) -> Result { + let LayerEntry { layer, previous } = entry; let previous = previous.ok_or(Error::IdentityMismatch)?; let prior = txn.ple_prior()?; let mut ple = diagnose( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_sdet.rs index d9dc761a..9c2b62b1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/reset_replay_sdet.rs @@ -108,17 +108,14 @@ impl Run<'_, '_, '_> { baseline.try_reserve_exact(TOKENS.len()).expect("baseline retention allocation failed"); self.output.test_reset_replay_record(true).expect("logit observer refused"); for (index, token) in TOKENS.into_iter().enumerate() { - let greedy = QwenForward::step_cached( - self.binding, - TokenId::new(token, self.fixed.vocabulary).expect("fixed token refused"), - Position::new(index as u64, self.fixed.context_length).expect("fixed position refused"), - session, - self.output, - Some(&mut *cache), - moe_cache, - dense_cache, - ) - .expect("cached baseline full forward refused"); + let request = StepRequest { + binding: self.binding, + token: TokenId::new(token, self.fixed.vocabulary).expect("fixed token refused"), + position: Position::new(index as u64, self.fixed.context_length).expect("fixed position refused"), + }; + let caches = StepCaches { kar: Some(&mut *cache), moe: Some(&mut *moe_cache), dense: Some(dense_cache) }; + let greedy = QwenForward::step_cached(request, session, self.output, caches) + .expect("cached baseline full forward refused"); baseline.push(capture_committed(self.binding, session, self.output, greedy, index)); } baseline @@ -131,15 +128,13 @@ impl Run<'_, '_, '_> { cache: &mut KarPleCache<'_>, expected: &CapturedStep, ) { - let greedy = QwenForward::step_with_kar_ple_output( - self.binding, - TokenId::new(TOKENS[index], self.fixed.vocabulary).expect("fixed replay token refused"), - Position::new(index as u64, self.fixed.context_length).expect("fixed replay position refused"), - session, - self.output, - cache, - ) - .expect("legacy uncached full forward refused"); + let request = StepRequest { + binding: self.binding, + token: TokenId::new(TOKENS[index], self.fixed.vocabulary).expect("fixed replay token refused"), + position: Position::new(index as u64, self.fixed.context_length).expect("fixed replay position refused"), + }; + let greedy = QwenForward::step_with_kar_ple_output(request, session, self.output, cache) + .expect("legacy uncached full forward refused"); let actual = capture_committed(self.binding, session, self.output, greedy, index); assert!(actual.greedy == expected.greedy, "replay greedy mismatch at step {index}"); assert!(actual.logits.as_ref() == expected.logits.as_ref(), "full logit word mismatch at step {index}"); @@ -204,10 +199,9 @@ pub(in crate::qwen_forward) fn check_on_loaded( binding: &ModelBinding, session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, - cache: &mut KarPleCache<'_>, - moe_cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, + caches: LoadedCaches<'_, '_, '_, '_>, ) { + let LoadedCaches { kar: cache, moe: moe_cache, dense: dense_cache } = caches; let charged = assert_topology(binding); let run = Run { binding, output, fixed: fixed_dimensions(binding) }; let fresh = session.test_reset_replay_snapshot(binding).expect("fresh session snapshot refused"); @@ -305,7 +299,8 @@ fn pinned_kar_cached_vs_legacy_same_session_reset_replays_all_logits_and_numeric let dense_cache = DenseWeightCache::new(&binding, context.as_ref()).expect("actor-owned dense weight cache load failed"); let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - check_on_loaded(&binding, &mut session, &output, &mut cache, &mut moe_cache, &dense_cache); + let caches = LoadedCaches { kar: &mut cache, moe: &mut moe_cache, dense: &dense_cache }; + check_on_loaded(&binding, &mut session, &output, caches); drop(session); let (moe_closed, dense_closed) = close_owners(moe_cache, dense_cache, cache, output); assert_teardown_clean(&close_context(moe_closed.is_ok(), dense_closed.is_ok(), context)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs index a78bb3fc..921524e4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs @@ -16,6 +16,13 @@ pub(super) struct LayerCtx<'a, 'ctx> { pub(super) dense: Option<&'a DenseWeightCache<'ctx>>, } +/// The layer one phase runs: its checked id and its kind (GDN or QSA). +#[derive(Clone, Copy)] +struct LayerSite { + layer: LayerId, + kind: BoundLayerKind, +} + /// Validate the complete producer-bound descriptor sequence before touching any model rows or invoking a stage. pub(super) fn prepare_step_caches( binding: &ModelBinding, @@ -100,7 +107,8 @@ pub(super) fn run_layers( eprintln!("integration: starting layer {}", descriptor.index()); let kind = descriptor.kind(); let index = descriptor.index(); - let completed = run_layer(ctx, txn, index, kind, layer_bound, previous.as_ref(), moe_cache.as_deref_mut())?; + let site = LayerSite { layer: LayerId::new(u64::from(index), layer_bound)?, kind }; + let completed = run_layer(ctx, txn, site, previous.as_ref(), moe_cache.as_deref_mut())?; txn.mark_layer_complete(&completed)?; previous = Some(completed); } @@ -111,13 +119,11 @@ pub(super) fn run_layers( fn run_layer( ctx: &LayerCtx<'_, '_>, txn: &mut QwenStepTxn, - descriptor_index: u32, - kind: BoundLayerKind, - layer_bound: Dimension, + site: LayerSite, previous: Option<&InjectedResidual>, moe_cache: Option<&mut MoeWeightCache<'_>>, ) -> Result { - let layer = LayerId::new(u64::from(descriptor_index), layer_bound)?; + let LayerSite { layer, kind } = site; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if oracle_capture::enabled() { oracle_capture::begin(ctx.pos.get(), layer.get() as i32)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_request.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_request.rs new file mode 100644 index 00000000..5a433499 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_request.rs @@ -0,0 +1,66 @@ +//! The inputs of one forward step, grouped by meaning: what is forwarded, which caches serve it, what it is for. + +#[cfg(test)] +use super::OutputStage; +use super::{DenseWeightCache, KarPleCache, ModelBinding, MoeWeightCache, Position, TokenId}; + +/// What one forward step runs: the model binding and the token at its position. +#[derive(Clone, Copy)] +pub(crate) struct StepRequest<'a> { + pub(crate) binding: &'a ModelBinding, + pub(crate) token: TokenId, + pub(crate) position: Position, +} + +/// The weight caches one forward step reads and fills. An absent cache selects the uncached path of that provider. +pub(crate) struct StepCaches<'a, 'kar, 'moe, 'dense> { + pub(crate) kar: Option<&'a mut KarPleCache<'kar>>, + pub(crate) moe: Option<&'a mut MoeWeightCache<'moe>>, + pub(crate) dense: Option<&'a DenseWeightCache<'dense>>, +} + +/// What a forward step is for: it decides whether the pre-output streams are retained and the output head is read. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum StepPurpose { + /// A complete greedy step: the predicted token is published, nothing is retained for MTP. + Greedy, + /// A complete step whose pre-output four-stream residual is retained as the MTP target product. + MtpTarget, + /// A known-next prefill step: the streams are retained and no token is predicted. + MtpPrefill, +} + +impl StepPurpose { + /// Whether the four-stream residual is copied out for the MTP draft. + pub(crate) fn retains_streams(self) -> bool { + self != Self::Greedy + } + + /// Whether the step stops before the output head. + pub(crate) fn is_prefill_only(self) -> bool { + self == Self::MtpPrefill + } +} + +/// The three weight caches a test borrows from its loaded owners; unlike `StepCaches` every cache is present. +#[cfg(test)] +pub(crate) struct LoadedCaches<'a, 'kar, 'moe, 'dense> { + pub(crate) kar: &'a mut KarPleCache<'kar>, + pub(crate) moe: &'a mut MoeWeightCache<'moe>, + pub(crate) dense: &'a DenseWeightCache<'dense>, +} + +#[cfg(test)] +impl<'kar, 'moe, 'dense> LoadedCaches<'_, 'kar, 'moe, 'dense> { + /// The same caches as the optional set one forward step takes, reborrowed for one step. + pub(crate) fn step_caches(&mut self) -> StepCaches<'_, 'kar, 'moe, 'dense> { + StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) } + } +} + +/// The output head and the weight caches a loaded proof borrows from the owners that outlive it. +#[cfg(test)] +pub(crate) struct LoadedOwners<'a, 'out, 'driver, 'kar, 'moe, 'dense> { + pub(crate) output: &'a OutputStage<'out, 'driver>, + pub(crate) caches: LoadedCaches<'a, 'kar, 'moe, 'dense>, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs index eaa69a5b..db0a1b66 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs @@ -115,33 +115,19 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { pub(super) fn warm_scalar_prefix(&mut self, scalar_draft: &mut MtpDecoder) { self.output.test_reset_replay_record(true).expect("head observer refused"); for index in 0..3 { - let source = QwenForward::prefill_for_mtp_cached( - self.binding, - self.ids[index], - pos(index as u64), - self.session, - self.output, - Some(&mut *self.kar), - self.moe, - self.dense, - ) - .expect("scalar known-next target refused"); + let request = StepRequest { binding: self.binding, token: self.ids[index], position: pos(index as u64) }; + let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) }; + let source = QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches) + .expect("scalar known-next target refused"); scalar_draft .warm_prefill(self.binding, self.session, &source, self.ids[index + 1], self.moe) .expect("scalar known-next warm refused"); } } pub(super) fn mtp_step(&mut self, token: TokenId, position: u64) -> Result { - QwenForward::step_for_mtp_cached( - self.binding, - token, - pos(position), - self.session, - self.output, - Some(&mut *self.kar), - Some(&mut *self.moe), - Some(self.dense), - ) + let request = StepRequest { binding: self.binding, token, position: pos(position) }; + let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) }; + QwenForward::step_for_mtp_cached(request, self.session, self.output, caches) } pub(super) fn scalar_final_step( &mut self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs index 2af0a3e7..24f216a4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs @@ -5,7 +5,7 @@ #[allow(unused_imports)] use super::*; -use crate::qwen_forward::executor::{PrefillStepProduct, TargetStepProduct}; +use crate::qwen_forward::executor::{PrefillStepProduct, StepCaches, StepRequest, TargetStepProduct}; use crate::qwen_forward::mtp::MtpChunkNumericSnapshot; use crate::qwen_forward::mtp_decode::MtpDecoder; use crate::qwen_forward::session::ResetReplaySnapshot; @@ -65,25 +65,15 @@ impl Rig<'_, '_, '_, '_, '_, '_> { fn prefill(&mut self, ids: &Ids, (token, n): (TokenId, u64), what: &str) -> PrefillStepProduct { let position = ids.position(n); - let kar = Some(&mut *self.kar); - QwenForward::prefill_for_mtp_cached( - self.binding, - token, - position, - self.session, - self.output, - kar, - self.moe, - self.dense, - ) - .expect(what) + let request = StepRequest { binding: self.binding, token, position }; + let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) }; + QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches).expect(what) } fn step_final(&mut self, ids: &Ids) -> TargetStepProduct { - let (kar, moe) = (Some(&mut *self.kar), Some(&mut *self.moe)); - let position = ids.position(3); - let (binding, output, dense) = (self.binding, self.output, Some(self.dense)); - QwenForward::step_for_mtp_cached(binding, ids.ids[3], position, self.session, output, kar, moe, dense) + let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) }; + let request = StepRequest { binding: self.binding, token: ids.ids[3], position: ids.position(3) }; + QwenForward::step_for_mtp_cached(request, self.session, self.output, caches) .expect("scalar final target refused") } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_attention.rs index 211a47cc..05ddaff9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_attention.rs @@ -91,7 +91,8 @@ impl QwenForward { return Err(Error::Unsupported(Stage::Executor)); } let prior = previous[index].as_ref(); - prepare_layer_attention_micro(env.binding, layer, prior, txn, env.dense, ple_micro.as_deref_mut()) + let entry = LayerEntry { layer, previous: prior }; + prepare_layer_attention_micro(env.binding, entry, txn, env.dense, ple_micro.as_deref_mut()) }, |inputs| { let (bank, rows) = Self::read_micro_bank(env, inputs)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs index 3f7db81e..40d31292 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs @@ -97,13 +97,11 @@ impl QwenForward { pub(crate) fn test_window_boundaries_on_loaded<'driver>( binding: &ModelBinding, session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, + owners: LoadedOwners<'_, '_, '_, '_, 'driver, '_>, ) -> Result { + let output = owners.output; // Early errors still return to the root-owned cleanup envelope. - let result = run(binding, session, output, kar, moe, dense); + let result = run(binding, session, owners); if result.is_ok() { output.test_reset_replay_record(false)?; } @@ -133,12 +131,9 @@ use proof::{CancelReport, CandidateReport, Proof}; fn run<'driver>( binding: &ModelBinding, session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, + owners: LoadedOwners<'_, '_, '_, '_, 'driver, '_>, ) -> Result { - let mut proof = Proof::open(binding, session, output, kar, moe, dense)?; + let mut proof = Proof::open(binding, session, owners)?; // A: unchanged actual Native4 target/draft path FIRST. The new candidate // changes only the sealed window size; no retrospective baseline policy. let baseline = proof.baseline()?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs index 408cd2be..22703c4b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs @@ -56,31 +56,33 @@ fn count_differences(a: &[A], b: &[B], same: impl Fn(&A, &B) -> bool) -> u if a.len() == b.len() { a.iter().zip(b).filter(|(x, y)| !same(x, y)).count() } else { usize::MAX } } +/// The rows of one windowed prefill chunk: the model they run on, their tokens and the known next token. +#[derive(Clone, Copy)] +struct ChunkRequest<'a> { + binding: &'a ModelBinding, + ids: &'a [TokenId], + known_next: Option, +} + /// The windowed prefill transaction under the experimental retained-GR policy. The transaction borrows only the /// session; every other owner is reborrowed for this call alone. -#[allow(clippy::too_many_arguments)] fn prepare_txn<'s, 'driver>( - binding: &ModelBinding, + request: ChunkRequest<'_>, session: &'s mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, - ids: &[TokenId], - known_next: Option, + owners: &mut LoadedOwners<'_, '_, '_, '_, 'driver, '_>, boundary: BoundaryPlan, cancelled: impl FnMut() -> bool, ) -> Result> { let policy = ChunkMoePolicy::ExperimentalRetainedGr; QwenForward::prepare_prefill_chunk_with_policy_windowed( - binding, - ids, - known_next, + request.binding, + request.ids, + request.known_next, session, - output, - Some(kar), - moe, - dense, + owners.output, + Some(&mut *owners.caches.kar), + &mut *owners.caches.moe, + owners.caches.dense, HOST_BUDGET, cancelled, policy, @@ -93,10 +95,7 @@ fn prepare_txn<'s, 'driver>( pub(super) struct Proof<'a, 'driver, 'k, 'o, 'p, 'd> { pub(super) binding: &'a ModelBinding, pub(super) session: &'a mut QwenSession<'driver>, - pub(super) output: &'a OutputStage<'o, 'p>, - pub(super) kar: &'a mut KarPleCache<'k>, - pub(super) moe: &'a mut MoeWeightCache<'driver>, - pub(super) dense: &'a DenseWeightCache<'d>, + pub(super) owners: LoadedOwners<'a, 'o, 'p, 'k, 'driver, 'd>, pub(super) vocab: Dimension, pub(super) bounds: Dimension, pub(super) ids: Vec, @@ -109,10 +108,7 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> { pub(super) fn open( binding: &'a ModelBinding, session: &'a mut QwenSession<'driver>, - output: &'a OutputStage<'o, 'p>, - kar: &'a mut KarPleCache<'k>, - moe: &'a mut MoeWeightCache<'driver>, - dense: &'a DenseWeightCache<'d>, + owners: LoadedOwners<'a, 'o, 'p, 'k, 'driver, 'd>, ) -> Result { let vocab = Dimension::new(248320)?; let bounds = crate::qwen_forward::contract::position_dimension(); @@ -121,8 +117,8 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> { if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) { return Err(Error::IdentityMismatch); } - output.test_reset_replay_record(true)?; - Ok(Self { binding, session, output, kar, moe, dense, vocab, bounds, ids, next, follow }) + owners.output.test_reset_replay_record(true)?; + Ok(Self { binding, session, owners, vocab, bounds, ids, next, follow }) } } @@ -142,7 +138,7 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { let product = self.baseline_prefill(&mut draft)?; let (logits, greedy, bits) = self.baseline_outputs(&product)?; let (target, mtp) = self.snapshots(&draft)?; - draft.warm_retained(self.binding, self.session, &product, self.next, self.moe)?; + draft.warm_retained(self.binding, self.session, &product, self.next, self.owners.caches.moe)?; self.continuation(&mut draft)?; let (continued_target, continued_mtp) = self.snapshots(&draft)?; drop(product); @@ -158,10 +154,10 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { None, self.session, draft, - self.output, - Some(&mut *self.kar), - self.moe, - self.dense, + self.owners.output, + Some(&mut *self.owners.caches.kar), + self.owners.caches.moe, + self.owners.caches.dense, HOST_BUDGET, || false, )? @@ -169,7 +165,7 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { } fn baseline_outputs(&self, product: &TargetStepProduct) -> Result<(Box<[u32]>, TokenId, Vec)> { - let logits = self.output.test_reset_replay_take_logits()?; + let logits = self.owners.output.test_reset_replay_take_logits()?; let greedy = product.predicted(self.session)?; let stream = product.streams(self.binding, self.ids[3], Position::new(3, self.bounds)?, self.session)?; let mut bits = Vec::new(); @@ -181,24 +177,17 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { /// The continuation row after the window: one more actual prefill step, then the draft warm. fn continuation(&mut self, draft: &mut MtpDecoder) -> Result<()> { let position = Position::new(4, self.bounds)?; - let step = QwenForward::prefill_for_mtp_cached( - self.binding, - self.next, - position, - self.session, - self.output, - Some(&mut *self.kar), - self.moe, - self.dense, - )?; - draft.warm_prefill(self.binding, self.session, &step, self.follow, self.moe)?; + let request = StepRequest { binding: self.binding, token: self.next, position }; + let caches = self.owners.caches.step_caches(); + let step = QwenForward::prefill_for_mtp_cached(request, self.session, self.owners.output, caches)?; + draft.warm_prefill(self.binding, self.session, &step, self.follow, self.owners.caches.moe)?; Ok(()) } pub(super) fn candidate(&mut self, base: &Baseline) -> Result { let mut draft = MtpDecoder::new(self.binding)?; let (product, full_journal) = self.stage_full_micro(&mut draft)?; - let logits = self.output.test_reset_replay_take_logits()?; + let logits = self.owners.output.test_reset_replay_take_logits()?; let position = Position::new(3, self.bounds)?; let stream = product.streams(self.binding, self.ids[3], position, self.session)?; let logit_differences = count_differences(&base.logits, &logits, |a, b| a == b); @@ -229,19 +218,19 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { product: &TargetStepProduct, ) -> Result<(bool, bool)> { draft.validate_resume(self.binding, self.session, product, &[0, 1, 0, 1])?; - draft.warm_retained(self.binding, self.session, product, self.next, self.moe)?; + draft.warm_retained(self.binding, self.session, product, self.next, self.owners.caches.moe)?; self.continuation(draft)?; let target_equal = base.continued_target.numeric_eq(&self.snapshot()?); Ok((target_equal, draft.test_chunk_eq(&base.continued_mtp))) } fn stage_full_micro(&mut self, draft: &mut MtpDecoder) -> Result<(TargetStepProduct, Journal)> { - let (binding, output, dense) = (self.binding, self.output, self.dense); + let binding = self.binding; let plan = BoundaryPlan::FullMicro2; - let mut txn = - prepare_txn(binding, self.session, output, self.kar, self.moe, dense, &self.ids, None, plan, || false)?; + let request = ChunkRequest { binding, ids: &self.ids, known_next: None }; + let mut txn = prepare_txn(request, self.session, &mut self.owners, plan, || false)?; let journal = owned_journal(&txn)?; - let ready = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false)?; + let ready = draft.stage_prefill_chunk(binding, &mut txn, self.owners.caches.moe, || false)?; let source = txn.publish_joint(ready)?.into_target_product().ok_or(Error::IdentityMismatch)?; Ok((source, journal)) } @@ -277,13 +266,14 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { } fn stage_first_layer(&mut self, ids: &[TokenId], draft: &mut MtpDecoder) -> Result { - let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next)); + let binding = self.binding; let plan = BoundaryPlan::FirstLayer; - let mut txn = prepare_txn(binding, self.session, output, self.kar, self.moe, dense, ids, next, plan, || false)?; + let request = ChunkRequest { binding, ids, known_next: Some(self.next) }; + let mut txn = prepare_txn(request, self.session, &mut self.owners, plan, || false)?; let finite_words = txn.test_partial_words(); let journal = owned_journal(&txn)?; let publication_refused = txn.test_publication_preflight_refused(); - let staged = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false); + let staged = draft.stage_prefill_chunk(binding, &mut txn, self.owners.caches.moe, || false); let mtp_refused = matches!(staged, Err(Error::IdentityMismatch)); Ok(FirstLayer { finite_words, journal, publication_refused, mtp_refused }) } @@ -311,8 +301,8 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { /// The caches still validate against the MTP context, which must not be poisoned. fn healthy(&mut self) -> Result { let context = self.session.mtp_context()?; - self.moe.validate(self.binding, context)?; - self.dense.validate(self.binding)?; + self.owners.caches.moe.validate(self.binding, context)?; + self.owners.caches.dense.validate(self.binding)?; Ok(!context.is_poisoned()) } @@ -323,10 +313,8 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { observed: Rc::clone(observation), cancelled: Rc::clone(&cancellation), }; - let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next)); - let (session, kar, moe) = (&mut *self.session, &mut *self.kar, &mut *self.moe); - let prepared = - prepare_txn(binding, session, output, kar, moe, dense, &actual_ids, next, plan, || cancellation.get()); + let request = ChunkRequest { binding: self.binding, ids: &actual_ids, known_next: Some(self.next) }; + let prepared = prepare_txn(request, self.session, &mut self.owners, plan, || cancellation.get()); Ok(matches!(prepared, Err(Error::Unsupported(Stage::Executor)))) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs index d30fe4f5..7b921b84 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::executor::{StepCaches, StepRequest}; use crate::qwen_forward::mtp::MtpCheckpoint; type WindowResult = std::result::Result; @@ -240,16 +241,9 @@ impl MtpDecoder { let position = Position::new(position, crate::qwen_forward::contract::position_dimension())?; let (output, dense) = (cx.output, cx.dense_cache); let kar = kar_cache.as_deref_mut(); - let product = QwenForward::step_for_mtp_cached( - binding, - expected, - position, - target, - output, - kar, - Some(cache), - Some(dense), - )?; + let request = StepRequest { binding, token: expected, position }; + let caches = StepCaches { kar, moe: Some(cache), dense: Some(dense) }; + let product = QwenForward::step_for_mtp_cached(request, target, output, caches)?; let next = product.predicted(target)?; st.latest = Some(product); Ok(next) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs index 691aa283..dd3d7583 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::executor::{StepCaches, StepRequest}; pub(super) fn position_at(position: u64) -> Position { Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap() @@ -25,16 +26,9 @@ impl Shared<'_, '_, '_, '_, '_> { native: &mut MoeWeightCache<'ctx>, (token, position): (TokenId, u64), ) -> Result { - QwenForward::step_for_mtp_cached( - self.binding, - token, - position_at(position), - target, - self.output, - Some(&mut *self.kar), - Some(native), - Some(self.dense), - ) + let request = StepRequest { binding: self.binding, token, position: position_at(position) }; + let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(native), dense: Some(self.dense) }; + QwenForward::step_for_mtp_cached(request, target, self.output, caches) } pub(super) fn window<'ctx>( &mut self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs index 61fb27e7..f41d025d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs @@ -3,7 +3,7 @@ use super::contract::{Dimension, Position, TokenId}; use super::{ contract::{Error, Result}, dense_weight_cache::DenseWeightCache, - executor::QwenForward, + executor::{QwenForward, StepCaches, StepRequest}, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache, output::OutputStage, @@ -230,8 +230,10 @@ fn capture_position( } begin(position, -1)?; let (token, position_id) = (TokenId::new(token, vocabulary)?, Position::new(position, context)?); - let (cache, moe, dense) = (Some(&mut *caches.cache), &mut *caches.moe, caches.dense); - let greedy = QwenForward::step_cached(binding, token, position_id, session, output, cache, moe, dense)?; + let request = StepRequest { binding, token, position: position_id }; + let step_caches = + StepCaches { kar: Some(&mut *caches.cache), moe: Some(&mut *caches.moe), dense: Some(caches.dense) }; + let greedy = QwenForward::step_cached(request, session, output, step_caches)?; emit_logits(output, greedy.get())?; session.oracle_capture_committed(binding, position)?; finish_position() From 5aa0cb3b19e99ffa82875b9a49f396f1212e08e4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:01:32 +0100 Subject: [PATCH 02/42] STRA-338 params e02: shared-permanent proof builds descriptors from SharedRoleShape --- .../cache_shared_permanent_sdet.rs | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs index 196803e7..1125459b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs @@ -1,24 +1,38 @@ //! Pure metadata/budget proof; never constructs a ModelBinding or device owner. use super::*; -fn shared_descriptor( - layer: u32, +/// Shape, quantisation kind and byte size of one shared-expert weight role, independent of the layer. +struct SharedRoleShape { role: u8, raw_kind: u32, columns: usize, rows: usize, bytes: usize, -) -> MoeWeightDescriptor { +} +fn shared_descriptor(layer: u32, shape: SharedRoleShape) -> MoeWeightDescriptor { + let SharedRoleShape { role, raw_kind, columns, rows, bytes } = shape; MoeWeightDescriptor { layer, expert: None, role, raw_kind, columns, rows, bytes } } fn descriptor_set() -> Vec<[MoeWeightDescriptor; 4]> { (0..48u32) .map(|layer| { [ - shared_descriptor(layer, 0, 14, 2560, 640, 1_344_000), - shared_descriptor(layer, 1, 14, 2560, 640, 1_344_000), - shared_descriptor(layer, 2, 8, 640, 2560, 1_740_800), - shared_descriptor(layer, 3, 30, 2560, 1, 5120), + shared_descriptor( + layer, + SharedRoleShape { role: 0, raw_kind: 14, columns: 2560, rows: 640, bytes: 1_344_000 }, + ), + shared_descriptor( + layer, + SharedRoleShape { role: 1, raw_kind: 14, columns: 2560, rows: 640, bytes: 1_344_000 }, + ), + shared_descriptor( + layer, + SharedRoleShape { role: 2, raw_kind: 8, columns: 640, rows: 2560, bytes: 1_740_800 }, + ), + shared_descriptor( + layer, + SharedRoleShape { role: 3, raw_kind: 30, columns: 2560, rows: 1, bytes: 5120 }, + ), ] }) .collect() From b8e52a0ef48599ed650aefcf883374633eb81676 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:01:33 +0100 Subject: [PATCH 03/42] STRA-338 params e02: MMQ model gate takes LoadedTargetOwners, compare_chunk takes ScalarBaseline --- .../gpu_proofs/resident_mmq_model_proof.rs | 5 +- .../qwen_forward/executor_mmq_evaluation.rs | 49 +++++++------------ .../executor_native_mmq_evaluation.rs | 3 +- .../src/qwen_forward/loaded_target_owners.rs | 17 +++++++ .../src/qwen_forward/mod.rs | 2 + 5 files changed, 44 insertions(+), 32 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs index 8ab56d5c..6d2f00d9 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs @@ -1,6 +1,7 @@ //! Private sole new changed-path model gate; actual source identity/load preserved. use super::combined_changed_boundary_proof::rig::{DEVICE_BUDGET, MOE_REFUSAL, Owners, bind_pinned, require_opt_in}; use super::*; +use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; use std::{env, panic::resume_unwind}; fn required_path(name: &str) -> PathBuf { @@ -17,7 +18,9 @@ fn pinned_single_load_resident_mmq_model_numeric() { let device = driver.device(0).expect("prefix CUDA device0 unavailable"); let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); let mut owners = Owners::load(&binding, context.as_ref(), (MoeWeightCache::new_mmq, MOE_REFUSAL)); - let numerical = owners.run(&binding, &context, QwenForward::test_mmq_on_loaded); + let numerical = owners.run(&binding, &context, |binding, session, output, kar, moe, dense| { + QwenForward::test_mmq_on_loaded(LoadedTargetOwners { binding, session, output, kar, moe, dense }) + }); let mut teardown = owners.close(true); teardown.close_context(context); drop((binding, inherited)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs index eaa69a5b..ff4f7152 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs @@ -1,30 +1,17 @@ //! Only the explicitly selected new full-model MMQ gate. Old observers unchanged. use super::*; +use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; use crate::qwen_forward::mtp::MtpChunkNumericSnapshot; use crate::qwen_forward::mtp_decode::MtpDecoder; use crate::qwen_forward::session::ResetReplaySnapshot; impl QwenForward { - pub(crate) fn test_mmq_on_loaded<'driver>( - binding: &ModelBinding, - session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, - ) { - check_mmq_on_loaded(binding, session, output, kar, moe, dense); + pub(crate) fn test_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) { + check_mmq_on_loaded(owners); } } -#[allow(clippy::too_many_arguments)] -pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( - binding: &ModelBinding, - session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, -) { - let mut run = MmqRun::new(binding, session, output, kar, moe, dense); +pub(in crate::qwen_forward) fn check_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) { + let binding = owners.binding; + let mut run = MmqRun::new(owners); let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused"); assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required"); let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused"); @@ -38,7 +25,8 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft); let chunk = run.candidate_chunk(&mut candidate_draft); let head_exact = run.compare_head(&baseline, &chunk); - let exact = run.compare_chunk(&baseline, &baseline_streams, &chunk, &candidate_draft, head_exact); + let scalar_baseline = ScalarBaseline { observation: &baseline, streams: &baseline_streams }; + let exact = run.compare_chunk(scalar_baseline, &chunk, &candidate_draft, head_exact); let continued_exact = run.candidate_continuation(&mut candidate_draft, &chunk, &continued, &exact); let continued_draft_exact = candidate_draft.test_chunk_eq(&continued.draft); run.output.test_reset_replay_record(false).expect("head observer did not drain"); @@ -87,6 +75,13 @@ pub(super) struct ChunkExact { pub(super) draft: bool, } +/// The scalar target step the candidate chunk is compared with: its observation and residual stream words. +#[derive(Clone, Copy)] +struct ScalarBaseline<'a> { + observation: &'a Observation, + streams: &'a [u32], +} + /// Exactness flags of the continuation step. struct ContinuedExact { head: bool, @@ -94,14 +89,8 @@ struct ContinuedExact { } impl<'a, 'driver, 'o, 'p, 'k, 'd> MmqRun<'a, 'driver, 'o, 'p, 'k, 'd> { - pub(super) fn new( - binding: &'a ModelBinding, - session: &'a mut QwenSession<'driver>, - output: &'a OutputStage<'o, 'p>, - kar: &'a mut KarPleCache<'k>, - moe: &'a mut MoeWeightCache<'driver>, - dense: &'a DenseWeightCache<'d>, - ) -> Self { + pub(super) fn new(owners: LoadedTargetOwners<'a, 'driver, 'o, 'p, 'k, 'd>) -> Self { + let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners; let vocab = Dimension::new(248320).expect("vocabulary refused"); let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect(); @@ -307,12 +296,12 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { } fn compare_chunk( &mut self, - baseline: &Observation, - baseline_streams: &[u32], + scalar_baseline: ScalarBaseline<'_>, chunk: &ChunkRun, candidate_draft: &MtpDecoder, head: bool, ) -> ChunkExact { + let ScalarBaseline { observation: baseline, streams: baseline_streams } = scalar_baseline; let predicted = chunk.product.predicted(self.session).expect("chunk current origin invalid"); assert_eq!(baseline.greedy, predicted, "greedy mismatch"); let actual_streams = diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs index b7716cf2..0d56428c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs @@ -1,6 +1,7 @@ //! Separate native-certified activation model observer. Original failed observer unchanged. use super::mmq_evaluation::{ChunkExact, ChunkRun, MmqRun, Observation, pos}; use super::*; +use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; use crate::qwen_forward::mtp_decode::MtpDecoder; #[derive(Debug)] @@ -64,7 +65,7 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( moe: &mut MoeWeightCache<'driver>, dense: &DenseWeightCache<'_>, ) -> NativeMmqReport { - let mut run = MmqRun::new(binding, session, output, kar, moe, dense); + let mut run = MmqRun::new(LoadedTargetOwners { binding, session, output, kar, moe, dense }); let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused"); assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required"); let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs b/crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs new file mode 100644 index 00000000..1182dd62 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs @@ -0,0 +1,17 @@ +//! The freshly loaded target model and its device caches, as one value a `test_*_on_loaded` GPU phase receives. +use super::{ + dense_weight_cache::DenseWeightCache, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache, + output::OutputStage, session::QwenSession, +}; +use crate::model_binding::qwen4exp_input::ModelBinding; + +/// The loaded target model and every cache one on-loaded observation borrows; it exists so a phase takes one +/// argument instead of six owners that always travel together. +pub(crate) struct LoadedTargetOwners<'a, 'driver, 'o, 'p, 'k, 'd> { + pub(crate) binding: &'a ModelBinding, + pub(crate) session: &'a mut QwenSession<'driver>, + pub(crate) output: &'a OutputStage<'o, 'p>, + pub(crate) kar: &'a mut KarPleCache<'k>, + pub(crate) moe: &'a mut MoeWeightCache<'driver>, + pub(crate) dense: &'a DenseWeightCache<'d>, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs index d860c67d..1542ee18 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs @@ -11,6 +11,8 @@ pub(crate) mod kar_ple_cache; pub(crate) mod moe_expert; pub(crate) mod moe_route; // Original Strata prefill MoE router + shared expert over a whole micro-window of genuine FFN reads. +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod loaded_target_owners; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod moe_prefill_batch; pub(crate) mod moe_weight_cache; From d446cf3b14256f5e6125532e278718da86b53b7c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:01:33 +0100 Subject: [PATCH 04/42] STRA-338 params e03: adaptive wave, MMQ layer walk, prompt finish and router projection take grouped DTOs --- .../src/qwen_forward/moe_group_adaptive.rs | 6 +- .../moe_group_adaptive/adaptive_wave_fn.rs | 86 +++++++++--------- .../moe_group_chunk/direct_packets_fns.rs | 4 +- .../src/qwen_forward/moe_mmq_adaptive.rs | 6 +- .../moe_mmq_adaptive/gather_fns.rs | 66 ++++++++------ .../qwen_forward/moe_mmq_adaptive/walk_fns.rs | 89 ++++++++++--------- .../src/qwen_forward/moe_mmq_slotpack.rs | 21 ++--- .../src/qwen_forward/moe_prompt_finish.rs | 39 ++++---- .../src/qwen_forward/moe_route.rs | 2 + .../moe_route/impl_routerlogits.rs | 3 +- .../moe_route/project_logits_fn.rs | 11 ++- 11 files changed, 181 insertions(+), 152 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs index 8f7476a2..17d62799 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs @@ -5,7 +5,7 @@ use super::*; mod adaptive_wave_fn; use crate::model_binding::qwen4exp_input::{MoeRoutedSourceScope, MoeWeightDescriptor}; use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error}; -use adaptive_wave_fn::AdaptiveWave; +use adaptive_wave_fn::{AdaptiveWave, WaveState}; #[allow(clippy::too_many_arguments)] pub(super) fn project_adaptive_groups<'ctx>( @@ -27,8 +27,8 @@ pub(super) fn project_adaptive_groups<'ctx>( } let (residents, misses) = split_resident_misses(binding, rows, groups, cache)?; let job_allowance = wave_job_allowance(residents.capacity(), misses.capacity())?; - let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared }; - wave.run(cache, down, cancelled, actual, &residents, &misses, job_allowance) + let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared, actual }; + wave.run(&mut WaveState { cache, down, cancelled }, &residents, &misses, job_allowance) } /// Actual outer wave directories coexist with owned jobs until join. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs index 0ac5f825..ddb6fae7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs @@ -6,45 +6,57 @@ use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, runtim /// The shared inputs of one adaptive wave: resident groups on the GPU, misses on the owned CPU pool. #[derive(Clone, Copy)] -pub(super) struct AdaptiveWave<'a, 'ctx> { +pub(super) struct AdaptiveWave<'a, 'ctx, 'txn, 'driver> { pub(super) context: &'ctx Context<'ctx>, pub(super) binding: &'a ModelBinding, pub(super) rows: &'a [ChunkFfnRow], pub(super) scope: &'a DownScope<'ctx>, pub(super) origins: &'a [Rc], pub(super) prepared: &'a [RoutedGateUpQ8<'a>], + pub(super) actual: Option<&'a QwenChunkTxn<'txn, 'driver>>, } -impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { +/// What an adaptive wave mutates while it runs: the weight cache, the down-projection slots and the cancellation +/// poll, which is checked before every batch and every completed member. +pub(super) struct WaveState<'w, 'cache, 'ctx, F: FnMut() -> bool> { + pub(super) cache: &'w mut MoeWeightCache<'cache>, + pub(super) down: &'w mut [[Option>; K]], + pub(super) cancelled: &'w mut F, +} + +/// One batch of CPU miss groups, with the resident GPU groups that run overlapped with it (first batch only). +#[derive(Clone, Copy)] +struct MissBatch<'a> { + groups: &'a [&'a [Pair]], + residents: Option<&'a [&'a [Pair]]>, +} + +impl<'ctx> AdaptiveWave<'_, 'ctx, '_, '_> { /// Run the miss batches in order; the resident GPU groups run once, overlapped with the first batch. - #[allow(clippy::too_many_arguments)] - pub(super) fn run( + pub(super) fn run bool>( &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, '_>>, + state: &mut WaveState<'_, '_, 'ctx, F>, residents: &[&[Pair]], misses: &[&[Pair]], job_allowance: usize, ) -> Result<()> { let mut gpu_done = false; - let cpu_owner = cache.cpu_miss_owner(self.binding)?; + let cpu_owner = state.cache.cpu_miss_owner(self.binding)?; let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let mut offset = 0usize; while offset < misses.len() { let end = miss_batch_end(self.rows, misses, offset)?; - let batch = &misses[offset..end]; + let groups = &misses[offset..end]; offset = end; - if cancelled() { + if (state.cancelled)() { return Err(Error::Unsupported(Stage::Executor)); } let resident = if gpu_done { None } else { Some(residents) }; - self.run_batch(cache, down, cancelled, actual, &mut cpu, batch, resident, job_allowance)?; + self.run_batch(state, &mut cpu, MissBatch { groups, residents: resident }, job_allowance)?; gpu_done = true; } if !gpu_done { - self.project_residents(residents, cache, down, cancelled)?; + self.project_residents(residents, state)?; } Ok(()) } @@ -53,23 +65,19 @@ impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { /// the CPU side, then upload the completed rows. Model-lifetime stacks/native scratch were admitted before the /// pool. This request admits <=16 jobs and <=48MiB INCLUDING actual directory, preparation and start/join /// metadata/capacities. Callees measure their own retained capacities against this remaining allowance before send. - #[allow(clippy::too_many_arguments)] - fn run_batch( + fn run_batch bool>( &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, '_>>, + state: &mut WaveState<'_, '_, 'ctx, F>, cpu: &mut CpuMissWorkspace, - batch: &[&[Pair]], - residents: Option<&[&[Pair]]>, + batch: MissBatch<'_>, job_allowance: usize, ) -> Result<()> { + let MissBatch { groups: batch, residents } = batch; let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, job_allowance)?; let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; let gpu_result = match residents { None => Ok(()), - Some(residents) => self.project_residents(residents, cache, down, cancelled), + Some(residents) => self.project_residents(residents, state), }; // Always drain actual CPU consumers, including GPU failure/cancellation. // Preserve the primary GPU failure; no source allocation outlives join. @@ -79,33 +87,28 @@ impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { if completed.len() != batch.len() { return Err(Error::IdentityMismatch); } - self.finish_members(cache, down, cancelled, actual, completed, batch) + self.finish_members(state, completed, batch) } - fn finish_members( + fn finish_members bool>( &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, '_>>, + state: &mut WaveState<'_, '_, 'ctx, F>, completed: Vec, batch: &[&[Pair]], ) -> Result<()> { for (values, pairs) in completed.into_iter().zip(batch) { - if cancelled() { + if (state.cancelled)() { return Err(Error::Unsupported(Stage::Executor)); } - self.finish_member(cache, down, actual, pairs, values)?; + self.finish_member(state, pairs, values)?; } Ok(()) } - fn project_residents( + fn project_residents bool>( &self, residents: &[&[Pair]], - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, + state: &mut WaveState<'_, '_, 'ctx, F>, ) -> Result<()> { let (context, binding, rows) = (self.context, self.binding, self.rows); project_residents( @@ -113,25 +116,24 @@ impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { binding, rows, residents, - cache, + state.cache, self.prepared, self.scope, self.origins, - down, - cancelled, + state.down, + state.cancelled, ) } - fn finish_member( + fn finish_member bool>( &self, - cache: &mut MoeWeightCache<'_>, - down: &mut [[Option>; K]], - actual: Option<&QwenChunkTxn<'_, '_>>, + state: &mut WaveState<'_, '_, 'ctx, F>, pairs: &[Pair], values: CpuMissRows, ) -> Result<()> { let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins); - let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?; + let (cache, down) = (&mut *state.cache, &mut *state.down); + let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, self.actual)?; upload_completed_rows(self.scope, binding, &keys, pairs, &values, origins, down)?; drop(values.into_values()); Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs index 3441aefb..f053c5d1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs @@ -167,7 +167,9 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { packet.validate(&self.origins[index], binding, rows[index].row().route.identity())?; refs.push(&packet.packet); } - prompt_finish::finish(self.context, binding, layer, rows, actual, self.scope, &refs, cache, finish, cancelled) + let window = + prompt_finish::PromptRows { context: self.context, binding, layer, rows, txn: actual, scope: self.scope }; + prompt_finish::finish(window, &refs, cache, finish, cancelled) } /// Complete each row's packet and run the shared tail, row by row. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs index 180f5e8f..642c249d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs @@ -9,7 +9,7 @@ use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer}; mod gather_fns; #[path = "moe_mmq_adaptive/walk_fns.rs"] mod walk_fns; -use walk_fns::{SlotState, Walk}; +use walk_fns::{SlotState, StagingPlan, Walk, WalkOwners}; #[allow(clippy::too_many_arguments)] pub(super) fn execute_adaptive_groups<'ctx>( @@ -94,7 +94,9 @@ fn execute_inner<'ctx>( let classified = walk.classify(cache, packets)?; let (mut wait, mut state) = walk.open_staging(cache, classified.maximum_charge)?; walk.fill_slots(cache, cancelled, &classified, &mut state)?; - walk.walk(&mut source, cache, packets, cancelled, &mut wait, &classified, &mut state, counts.len())?; + let mut owners = WalkOwners { mmq_layer: &mut source, cache: &mut *cache, packets: &mut *packets, cancelled }; + let mut plan = StagingPlan { classified: &classified, state: &mut state }; + walk.walk(&mut owners, &mut wait, &mut plan, counts.len())?; walk.finish(source, cache, &classified, &state) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs index 425b1dcd..ae315dd7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs @@ -1,33 +1,29 @@ //! Gather of one expert's matrices into the admitted bank (STRA-338 size: extract-method only). -use super::walk_fns::Walk; +use super::walk_fns::{ExpertGroup, Walk, WalkOwners}; #[allow(unused_imports)] use super::*; impl<'ctx> Walk<'_, '_, 'ctx> { /// Gather one expert's three matrices into the admitted bank, from the adaptive owner or its staged slot. - #[allow(clippy::too_many_arguments)] - pub(super) fn gather_expert( + pub(super) fn gather_expert bool>( &self, - expert: usize, - pairs: &[Pair], - cache: &mut MoeWeightCache<'ctx>, - activation: &mut OriginalMmqLayer<'_, 'ctx>, - packets: &mut SlotPacks<'_, '_, 'ctx>, + group: ExpertGroup<'_>, + owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>, ephemeral_slot: Option, - cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { - let _origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + let ExpertGroup { expert, pairs } = group; + let _origin = owners.packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; let mut members = Vec::new(); members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; let first = pairs.first().ok_or(Error::IdentityMismatch)?; let row = self.rows.get(first.row).ok_or(Error::IdentityMismatch)?; let (keys, formats, charge) = gather_layouts(self.binding, row, first)?; self.fill_members(pairs, &mut members)?; - cache.reserve_mmq_transient(self.binding, self.context, charge)?; + owners.cache.reserve_mmq_transient(self.binding, self.context, charge)?; self.binding.with_moe_routed_source(&members, binding_error, |source| { check_expert_keys(source, &keys, pairs.len())?; - self.gather_source(source, formats, pairs, cache, activation, ephemeral_slot, cancelled) + self.gather_source(source, GatheredExpert { formats, pairs, ephemeral_slot }, owners) }) } @@ -40,17 +36,14 @@ impl<'ctx> Walk<'_, '_, 'ctx> { Ok(()) } - #[allow(clippy::too_many_arguments)] - fn gather_source( + fn gather_source bool>( &self, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, - formats: [leleka_cuda_driver::MmqFormat; 3], - pairs: &[Pair], - cache: &MoeWeightCache<'ctx>, - activation: &mut OriginalMmqLayer<'_, 'ctx>, - ephemeral_slot: Option, - cancelled: &mut impl FnMut() -> bool, + gathered: GatheredExpert<'_>, + owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>, ) -> Result<()> { + let GatheredExpert { formats, pairs, ephemeral_slot } = gathered; + let WalkOwners { mmq_layer: activation, cache, cancelled, .. } = owners; let binding = self.binding; let cancel_observed = Cell::new(false); let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); @@ -58,7 +51,8 @@ impl<'ctx> Walk<'_, '_, 'ctx> { |raw: [&DeviceBuffer<'ctx>; 3], health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { - self.after_gather(activation, formats, raw, health, source, &mut observed_cancel, pairs) + self.stage_gathered(activation, formats, raw, &mut observed_cancel)?; + self.confirm_gather(health, source, &mut observed_cancel, pairs) }; match ephemeral_slot { Some(slot) => { @@ -68,23 +62,28 @@ impl<'ctx> Walk<'_, '_, 'ctx> { } } - /// The genuine bytes are retained in the admitted bank, not a synthetic MmqWeights view. The actual staging - /// owner can be reused only after this confirmed gather + source/current-row health boundary. - #[allow(clippy::too_many_arguments)] - fn after_gather( + /// The genuine bytes are retained in the admitted bank, not a synthetic MmqWeights view. + fn stage_gathered( &self, activation: &mut OriginalMmqLayer<'_, 'ctx>, formats: [leleka_cuda_driver::MmqFormat; 3], raw: [&DeviceBuffer<'ctx>; 3], + observed_cancel: &mut impl FnMut() -> bool, + ) -> Result<()> { + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + activation.stage_expert(formats, raw).map_err(mmq_error) + } + + /// The actual staging owner can be reused only after this confirmed gather + source/current-row health boundary. + fn confirm_gather( + &self, health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>, observed_cancel: &mut impl FnMut() -> bool, pairs: &[Pair], ) -> Result<()> { - if observed_cancel() { - return Err(Error::Unsupported(Stage::Executor)); - } - activation.stage_expert(formats, raw).map_err(mmq_error)?; source.finish().map_err(binding_error)?; health.validate(self.binding, self.context)?; if observed_cancel() { @@ -94,6 +93,15 @@ impl<'ctx> Walk<'_, '_, 'ctx> { } } +/// One gathered expert: its routed pairs, the formats of its three matrices and the ephemeral slot it was staged +/// in (none for a resident expert). +#[derive(Clone, Copy)] +struct GatheredExpert<'a> { + formats: [leleka_cuda_driver::MmqFormat; 3], + pairs: &'a [Pair], + ephemeral_slot: Option, +} + type ExpertLayouts = ([MoeWeightDescriptor; 3], [leleka_cuda_driver::MmqFormat; 3], usize); /// The Gate/Up/Down descriptors of one expert, their formats and the summed byte charge. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs index 49285e52..e29fbb8b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs @@ -25,6 +25,28 @@ pub(super) struct Batch { pub(super) consumed: usize, } +/// The classification of the layer's experts and the staging slots being filled from its misses. +pub(super) struct StagingPlan<'a> { + pub(super) classified: &'a Classified, + pub(super) state: &'a mut SlotState, +} + +/// One used expert: its index and the row/slot pairs routed to it. +#[derive(Clone, Copy)] +pub(super) struct ExpertGroup<'a> { + pub(super) expert: usize, + pub(super) pairs: &'a [Pair], +} + +/// The mutable owners one adaptive prompt layer walk drives: the MMQ layer run, the weight cache, the packet slots +/// and the cancellation poll. +pub(super) struct WalkOwners<'w, 'layer, 'ctx, 'pa, 'pb, F: FnMut() -> bool> { + pub(super) mmq_layer: &'w mut OriginalMmqLayer<'layer, 'ctx>, + pub(super) cache: &'w mut MoeWeightCache<'ctx>, + pub(super) packets: &'w mut SlotPacks<'pa, 'pb, 'ctx>, + pub(super) cancelled: &'w mut F, +} + /// The sealed layer rows and expert groups one adaptive prompt layer walks. pub(super) struct Walk<'a, 't, 'ctx> { pub(super) txn: &'a QwenChunkTxn<'t, 'ctx>, @@ -134,6 +156,7 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> { Ok(charge) } + /// Stage the first group of one missed expert into its ephemeral slot. pub(super) fn stage_miss( &self, cache: &MoeWeightCache<'ctx>, @@ -141,7 +164,17 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> { expert: usize, slot: usize, ) -> Result<()> { - stage(cache, self.context, self.binding, self.rows, &self.groups[expert], slot, cancelled) + let (binding, pairs) = (self.binding, &self.groups[expert]); + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let first = pairs.first().ok_or(Error::IdentityMismatch)?; + let row = self.rows.get(first.row).ok_or(Error::IdentityMismatch)?; + let members = [(&row.row().weights, first.slot)]; + let owner = cache.ephemeral_routed_owner(binding, self.context)?; + binding.with_moe_routed_source(&members, binding_error, |source| { + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0) + }) } /// The first staging wave: one miss per slot. @@ -166,32 +199,27 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> { /// Literal prompt order: residents and staged misses share one ID walk. The real bank retains gathered bytes /// until the <=16-expert numerical run. - #[allow(clippy::too_many_arguments)] - pub(super) fn walk( + pub(super) fn walk bool>( &self, - source: &mut OriginalMmqLayer<'_, 'ctx>, - cache: &mut MoeWeightCache<'ctx>, - packets: &mut SlotPacks<'_, '_, 'ctx>, - cancelled: &mut impl FnMut() -> bool, + owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>, wait: &mut impl FnMut(usize) -> Result<()>, - classified: &Classified, - state: &mut SlotState, + plan: &mut StagingPlan<'_>, used_count: usize, ) -> Result<()> { let mut batch = Batch { experts: [0; 16], count: 0, consumed: 0 }; for (expert, pairs) in self.used() { - if cancelled() { + if (owners.cancelled)() { return Err(Error::Unsupported(Stage::Executor)); } - let slot = self.wait_slot(wait, classified, state, expert)?; - self.gather_expert(expert, pairs, cache, source, packets, slot, cancelled)?; + let slot = self.wait_slot(wait, plan.classified, plan.state, expert)?; + self.gather_expert(ExpertGroup { expert, pairs: pairs.as_slice() }, owners, slot)?; batch.experts[batch.count] = expert; batch.count += 1; batch.consumed += 1; if batch.count == 16 || batch.consumed == used_count { - self.run_batch(source, cache, packets, cancelled, &mut batch)?; + self.run_batch(owners, &mut batch)?; } - self.refill(cache, cancelled, classified, state, slot)?; + self.refill(owners.cache, owners.cancelled, plan, slot)?; } Ok(()) } @@ -213,14 +241,12 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> { Ok(Some(slot)) } - pub(super) fn run_batch( + pub(super) fn run_batch bool>( &self, - source: &mut OriginalMmqLayer<'_, 'ctx>, - cache: &mut MoeWeightCache<'ctx>, - packets: &mut SlotPacks<'_, '_, 'ctx>, - cancelled: &mut impl FnMut() -> bool, + owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>, batch: &mut Batch, ) -> Result<()> { + let WalkOwners { mmq_layer: source, cache, packets, cancelled } = owners; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } @@ -248,13 +274,13 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> { &self, cache: &MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - classified: &Classified, - state: &mut SlotState, + plan: &mut StagingPlan<'_>, slot: Option, ) -> Result<()> { let Some(slot) = slot else { return Ok(()); }; + let StagingPlan { classified, state } = plan; state.slots[slot] = None; if state.next < classified.miss_count { let expert = classified.misses[state.next]; @@ -265,24 +291,3 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> { Ok(()) } } - -fn stage( - cache: &MoeWeightCache<'_>, - context: &Context<'_>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - pairs: &[Pair], - slot: usize, - cancelled: &mut impl FnMut() -> bool, -) -> Result<()> { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let first = pairs.first().ok_or(Error::IdentityMismatch)?; - let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let members = [(&row.row().weights, first.slot)]; - let owner = cache.ephemeral_routed_owner(binding, context)?; - binding.with_moe_routed_source(&members, binding_error, |source| { - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0) - }) -} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs index ca02b9b9..9e5acb45 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs @@ -234,18 +234,15 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { packet.complete(self.scope)?; packets.push(packet); } - super::prompt_finish::finish( - self.context, - self.binding, - self.layer, - self.rows, - self.txn, - self.scope, - &packets, - cache, - finish, - cancelled, - ) + let window = super::prompt_finish::PromptRows { + context: self.context, + binding: self.binding, + layer: self.layer, + rows: self.rows, + txn: self.txn, + scope: self.scope, + }; + super::prompt_finish::finish(window, &packets, cache, finish, cancelled) } fn finish_values( &self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs index bf9ccd0f..a07140c3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs @@ -12,13 +12,21 @@ pub(super) struct NativePromptFinish<'loan, 'ctx, 'dense> { } /// The sealed window rows one native prompt finish is checked against. -struct PromptRows<'a, 'session, 'ctx> { - context: &'ctx Context<'ctx>, - binding: &'a ModelBinding, - layer: LayerId, - rows: &'a [ChunkFfnRow], - txn: &'a QwenChunkTxn<'session, 'ctx>, - scope: &'a DownScope<'ctx>, +pub(super) struct PromptRows<'a, 'session, 'ctx> { + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, + pub(super) rows: &'a [ChunkFfnRow], + pub(super) txn: &'a QwenChunkTxn<'session, 'ctx>, + pub(super) scope: &'a DownScope<'ctx>, +} + +/// The complete Down packets of a window, the token-layer identities they were validated against and the transport +/// buffer they are gathered into for the combine. +struct PacketBank<'a, 'ctx> { + packets: &'a [&'a ResidentPackedDown<'ctx>], + expected: &'a [TokenLayer], + dm: &'a mut TransportBuffer<'ctx>, } impl<'ctx> PromptRows<'_, '_, 'ctx> { fn validate_shape(&self, packets: &[&ResidentPackedDown<'ctx>]) -> Result<()> { @@ -150,12 +158,12 @@ impl<'ctx> PromptRows<'_, '_, 'ctx> { } fn run( &self, - packets: &[&ResidentPackedDown<'ctx>], + bank: PacketBank<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, finish: &mut NativePromptFinish<'_, 'ctx, '_>, - (expected, dm): (&[TokenLayer], &mut TransportBuffer<'ctx>), cancelled: &mut impl FnMut() -> bool, ) -> Result> { + let PacketBank { packets, expected, dm } = bank; self.copy_packets_into(packets, dm, cancelled)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); @@ -182,25 +190,20 @@ impl<'ctx> PromptRows<'_, '_, 'ctx> { } let dm_bytes = self.reserve_dm(cache)?; let mut dm = self.scope.allocate(dm_bytes)?; - let operation = self.run(packets, cache, finish, (&expected, &mut dm), cancelled); + let operation = self.run(PacketBank { packets, expected: &expected, dm: &mut dm }, cache, finish, cancelled); self.scope.record(&operation); let cleanup = dm.close(); operation.and_then(|values| cleanup.map(|()| values)) } } -#[allow(clippy::too_many_arguments)] +/// Finish the native prompt window of `rows` over its complete Down packets. pub(super) fn finish<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], - txn: &QwenChunkTxn<'_, 'ctx>, - scope: &DownScope<'ctx>, + rows: PromptRows<'_, '_, 'ctx>, packets: &[&ResidentPackedDown<'ctx>], cache: &mut MoeWeightCache<'ctx>, finish: &mut NativePromptFinish<'_, 'ctx, '_>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { - PromptRows { context, binding, layer, rows, txn, scope }.finish(packets, cache, finish, cancelled) + rows.finish(packets, cache, finish, cancelled) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs index a8524d0d..5efd66fd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs @@ -99,6 +99,8 @@ use impl_routerlogits::admit_projection_budget; pub(super) use impl_routerlogits::validate_activation; mod project_logits_fn; #[allow(unused_imports)] +use project_logits_fn::RouterInput; +#[allow(unused_imports)] use project_logits_fn::binding_error; #[allow(unused_imports)] use project_logits_fn::collect_logits; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs index 0639d50f..c356b5db 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs @@ -138,7 +138,8 @@ impl MoeRouteStage { { return Self::route_leased(binding, layer, identity, txn, lease); } - let values = project_logits(context, binding, &weights, residual.mixed(), layer.get(), cache)?; + let input = RouterInput { layer: layer.get(), activation: residual.mixed() }; + let values = project_logits(context, binding, &weights, input, cache)?; let logits = logits_from_values(binding, layer, identity, values)?; Self::route(binding, layer, &logits, identity.token(), txn) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs index 7898c553..cc3e6423 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs @@ -44,14 +44,21 @@ fn finish_logits( Ok(values) } +/// The mixed residual of one layer that the router projects, with the layer whose router matrix applies to it. +#[derive(Clone, Copy)] +pub(super) struct RouterInput<'a> { + pub(super) layer: u32, + pub(super) activation: &'a [f32], +} + pub(super) fn project_logits( context: &Context<'_>, binding: &ModelBinding, weights: &MoeRouteWeights, - activation: &[f32], - layer: u32, + input: RouterInput<'_>, cache: Option<&DenseWeightCache<'_>>, ) -> Result<[f32; EXPERTS]> { + let RouterInput { layer, activation } = input; let input_bytes = activation_bytes(activation); let mut input = context.allocate(input_bytes.len()).map_err(map_driver_error)?; input.copy_from(&input_bytes).map_err(map_driver_error)?; From c76f3264797b7a35b5d08e83dc89c11c13d0f8d5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:01:34 +0100 Subject: [PATCH 05/42] STRA-338 params e02: prompt rows take PromptWeights/RowsUpload, prompt chunk forward takes target/caches/draft groups, scalar draft KV takes sources and request Files: crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs --- .../qwen_forward/executor_original_prompt.rs | 11 +- .../impl_drop_for_originalpromptexecutor.rs | 22 +-- .../impl_originalpromptexecutor_2_2.rs | 4 +- .../impl_originalpromptexecutor.rs | 170 +++++++++--------- .../forward_draft.rs | 170 ++++++++++-------- .../forward_final.rs | 14 +- .../forward_input.rs | 55 ++++-- .../forward_layers.rs | 76 ++++---- .../prompt_chunk_operands.rs | 66 +++++++ .../src/qwen_forward/original_mtp_prefill.rs | 2 +- .../original_mtp_scalar_prefill.rs | 34 ++-- .../src/qwen_forward/original_serve_stack.rs | 6 +- ...mpl_prefixdevice_for_originalservestack.rs | 4 +- .../original_serve_stack/impl_promptchunk.rs | 22 +-- .../src/qwen_forward/prompt_device_rows.rs | 7 + .../impl_promptdeviceread.rs | 1 + .../impl_promptdeviceread_2.rs | 45 ++--- .../produce_original_gdn_fn.rs | 21 +-- .../impl_promptplehistory.rs | 4 +- .../impl_promptdevicerows.rs | 30 ++-- .../impl_promptdevicerows_2.rs | 15 +- .../impl_std_ops_deref_2.rs | 4 +- .../prompt_device_rows/prompt_weights.rs | 18 ++ .../prompt_device_rows/rows_upload.rs | 9 + .../scalar_draft_kv_operands.rs | 26 +++ 25 files changed, 478 insertions(+), 358 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/prompt_chunk_operands.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/prompt_weights.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/rows_upload.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/scalar_draft_kv_operands.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs index 77b4887c..80220529 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs @@ -6,7 +6,9 @@ use super::super::original_mtp_full_owner::{ }; use super::super::output::OriginalPromptSample; use super::super::output_native::OriginalNativeOutput; -use super::super::prompt_device_rows::{OriginalDraftKvPending, OriginalPromptDraftOutcome}; +use super::super::prompt_device_rows::{ + OriginalDraftKvPending, OriginalPromptDraftOutcome, PromptWeights, QsaLayerDevices, RowsUpload, +}; use super::super::prompt_device_rows::{ PromptDeviceFinal, PromptDeviceNormedRows, PromptDeviceRows, PromptDeviceSource, }; @@ -110,6 +112,13 @@ pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx> { pub last_published: Option<(TargetStepOrigin, Option)>, } +#[path = "executor_original_prompt/prompt_chunk_operands.rs"] +mod prompt_chunk_operands; +pub(in crate::qwen_forward) use prompt_chunk_operands::{ + ChunkCaches, ChunkDraft, PromptChunkSource, PromptChunkTarget, +}; +#[allow(unused_imports)] +use prompt_chunk_operands::{ChunkInFlight, ChunkRollback, ChunkWork, OpenChunk}; #[path = "executor_original_prompt/staged_input_enabled_fn.rs"] mod staged_input_enabled_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs index e85d1238..0d34fb78 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs @@ -60,20 +60,14 @@ impl crate::backend::original_prompt::PromptRunner for OriginalPromptComposer<'_ if self.session.target_origin()?.next_position() != action.first as u64 { return Err(Error::IdentityMismatch); } - let pending = self.executor.forward( - self.binding, - self.dense, - &mut *self.session, - self.source, - action.count, - self.kar.as_deref_mut(), - &mut *self.moe, - &mut *self.arena, - &mut *self.draft, - self.embedding, - self.policy, - &mut *self.cancel, - )?; + let target = PromptChunkTarget { + weights: PromptWeights::new(self.binding, self.dense), + session: &mut *self.session, + tokens: PromptChunkSource { source: self.source, count: action.count }, + }; + let caches = ChunkCaches { kar: self.kar.as_deref_mut(), moe: &mut *self.moe, arena: &mut *self.arena }; + let draft = ChunkDraft { session: &mut *self.draft, embedding: self.embedding, policy: self.policy }; + let pending = self.executor.forward(target, caches, draft, &mut *self.cancel)?; self.last_published = Some(pending.publish()?); Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs index 47500c64..f7e0e6c3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs @@ -144,8 +144,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// the executor, as for `restore_session`. pub(in crate::qwen_forward) fn import_session( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, session: &mut QwenSession<'ctx>, parked: &ParkedSession, blocks: &[&ParkedBlock], @@ -153,6 +152,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { if self.failed || self.context.is_poisoned() { return Err(Error::CudaExecution); } + let PromptWeights { binding, dense } = weights; let imported = session.import_parked(binding, dense, &mut self.layers, parked, blocks); if imported.is_err() { self.failed = true; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs index f87ade97..adc3396a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs @@ -11,18 +11,12 @@ mod forward_final; mod forward_input; #[path = "impl_originalpromptexecutor/forward_layers.rs"] mod forward_layers; - -/// The draft session, its embedding and the scalar policy that record the draft KV of a chunk. -type DraftArgs<'a, 'ctx> = - (&'a mut OriginalDraftSession<'ctx>, &'a OriginalPromptEmbedding<'ctx>, &'a OriginalMtpScalarPolicy); +use forward_draft::DraftKvInputs; +use forward_input::StagedChunkInput; /// What a completed chunk leaves for the publisher: the final row, its sample and the draft KV. type ForwardDone = (PromptDeviceFinal, OriginalPromptSample, OriginalDraftKvPending); -/// The draft session and the two checkpoints a failed chunk is rolled back to. -type ForwardRollback<'program, 'ctx> = - (&'program mut OriginalDraftSession<'ctx>, OriginalSessionCheckpoint<'ctx>, OriginalDraftCheckpoint); - /// The initialized rows of a chunk, the two tokens before it and the staged host input that must outlive the chunk. type StagedRows<'arena, 'loan, 'ctx> = (PromptDeviceRows<'static, 'arena, 'loan, 'ctx>, Option<[i32; 2]>, Option); @@ -41,50 +35,44 @@ fn trace_error(step: &str, error: Error) -> Error { impl<'ctx> OriginalPromptExecutor<'ctx> { /// No target position is advanced here. Every read is actual GR arithmetic; /// recurrent/KV/PLE seals belong to the same still-private source transaction. - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn forward<'session, 'program, 'loan>( &'program mut self, - binding: &'program ModelBinding, - dense: &'program DenseWeightCache<'ctx>, - session: &'session mut QwenSession<'ctx>, - source: &std::rc::Rc, - count: usize, - kar: Option<&mut KarPleCache<'ctx>>, - moe: &mut MoeWeightCache<'ctx>, - arena: &mut OriginalPrefillArena<'loan, 'ctx>, - draft: &'program mut OriginalDraftSession<'ctx>, - embedding: &OriginalPromptEmbedding<'ctx>, - policy: &OriginalMtpScalarPolicy, + target: PromptChunkTarget<'session, 'program, 'ctx>, + caches: ChunkCaches<'_, 'loan, 'ctx>, + mut draft: ChunkDraft<'program, 'ctx>, mut cancelled: impl FnMut() -> bool, ) -> Result> { - let (tokens, first_position) = self.admit_window(binding, dense, session, source, count, arena.capacity())?; + let PromptChunkTarget { weights, session, tokens: chunk_source } = target; + let binding = weights.binding; + let ChunkCaches { kar, moe, arena } = caches; + let (window, first_position) = self.admit_window(weights, session, chunk_source, arena.capacity())?; let _launch_sync = leleka_cuda_driver::PromptSyncTrace::enter(); - if tokens.is_empty() || tokens.len() > self.capacity || arena.capacity() != self.capacity { + if window.is_empty() || window.len() > self.capacity || arena.capacity() != self.capacity { return Err(Error::InvalidDimension); } let checkpoint = session.original_checkpoint(binding)?; - let draft_checkpoint = draft.checkpoint(binding, session)?; + let draft_checkpoint = draft.session.checkpoint(binding, session)?; + let PromptChunkSource { source, count } = chunk_source; let mut txn = OriginalPromptTxn::begin(session, binding, source, count)?; - let (window, draft_args) = ((tokens, first_position), (&mut *draft, embedding, policy)); - let owners = (kar, (&mut *moe, arena)); - let operation = - self.forward_operation((binding, dense), &mut txn, (window, source), owners, draft_args, &mut cancelled); - self.finish_forward(operation, (binding, dense), (txn, moe), (draft, checkpoint, draft_checkpoint)) + let chunk = ChunkInFlight { weights, txn: &mut txn, window, first_position, source }; + let caches = ChunkCaches { kar, moe: &mut *moe, arena }; + let operation = self.forward_operation(chunk, caches, draft.reborrow(), &mut cancelled); + let rollback = ChunkRollback { draft: draft.session, checkpoint, draft_checkpoint }; + self.finish_forward(operation, weights, OpenChunk { txn, moe }, rollback) } /// The prompt window of the chunk and its first position, after the executor accepted the session. fn admit_window<'src>( &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, session: &mut QwenSession<'ctx>, - source: &'src std::rc::Rc, - count: usize, + chunk_source: PromptChunkSource<'src>, arena_capacity: usize, ) -> Result<(&'src [TokenId], u64)> { - self.validate(binding, dense, session)?; + let PromptChunkSource { source, count } = chunk_source; + self.validate(weights.binding, weights.dense, session)?; let first_position = session.target_origin()?.next_position(); - let tokens = source.window(binding, first_position, count)?; + let tokens = source.window(weights.binding, first_position, count)?; crate::bringup_trace!( "DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={arena_capacity} count={count}", crate::qwen_forward::original_serve_stack::dbg_el(), @@ -98,28 +86,31 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { fn finish_forward<'session, 'program>( &'program mut self, operation: Result, - (binding, dense): (&'program ModelBinding, &'program DenseWeightCache<'ctx>), - (txn, moe): (OriginalPromptTxn<'session, 'ctx>, &mut MoeWeightCache<'ctx>), - (draft, checkpoint, draft_checkpoint): ForwardRollback<'program, 'ctx>, + weights: PromptWeights<'program, 'ctx>, + open: OpenChunk<'session, '_, 'ctx>, + mut rollback: ChunkRollback<'program, 'ctx>, ) -> Result> { match operation { Err(primary) => { - self.forward_failed(binding, dense, txn, moe, (&checkpoint, draft, &draft_checkpoint), &primary); + self.forward_failed(weights, open, &mut rollback, &primary); Err(primary) } - Ok((completed, sample, draft_kv)) => Ok(OriginalPromptPending { - txn: Some(txn), - binding, - dense, - layers: &mut self.layers, - failed: &mut self.failed, - checkpoint, - completed, - sample, - draft_kv, - draft, - draft_checkpoint, - }), + Ok((completed, sample, draft_kv)) => { + let ChunkRollback { draft, checkpoint, draft_checkpoint } = rollback; + Ok(OriginalPromptPending { + txn: Some(open.txn), + binding: weights.binding, + dense: weights.dense, + layers: &mut self.layers, + failed: &mut self.failed, + checkpoint, + completed, + sample, + draft_kv, + draft, + draft_checkpoint, + }) + } } } @@ -127,57 +118,61 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// the draft KV. Its error is rolled back by `forward`. fn forward_operation<'loan>( &mut self, - (binding, dense): (&ModelBinding, &DenseWeightCache<'ctx>), - txn: &mut OriginalPromptTxn<'_, 'ctx>, - (window, source): ((&[TokenId], u64), &std::rc::Rc), - (mut kar, (moe, arena)): ( - Option<&mut KarPleCache<'ctx>>, - (&mut MoeWeightCache<'ctx>, &mut OriginalPrefillArena<'loan, 'ctx>), - ), - draft_args: DraftArgs<'_, 'ctx>, + mut chunk: ChunkInFlight<'_, '_, 'ctx>, + caches: ChunkCaches<'_, 'loan, 'ctx>, + draft: ChunkDraft<'_, 'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result { // The last prompt seed belongs to Original Verifier. Every row // admitted here must have its authentic next token in the source. - txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; - let (rows, first_predecessors, _staged) = - self.stage_prompt_rows((binding, dense), txn, window.0, (&mut kar, arena))?; - self.read_ahead_next_chunk(binding, source, window, &mut kar, first_predecessors); - let carrier = self.run_layers(binding, dense, moe, txn, Carrier::Plain(rows))?; - self.finish_chunk_rows((binding, dense), (moe, txn), carrier, (draft_args, cancelled)) + chunk.txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; + let ChunkCaches { mut kar, moe, arena } = caches; + let (rows, first_predecessors, _staged) = self.stage_prompt_rows(&mut chunk, &mut kar, arena)?; + self.read_ahead_next_chunk(&chunk, &mut kar, first_predecessors); + let mut work = ChunkWork { weights: chunk.weights, moe, txn: &*chunk.txn }; + let carrier = self.run_layers(&mut work, Carrier::Plain(rows))?; + self.finish_chunk_rows(work, carrier, draft, cancelled) } /// Stages the inputs of the chunk and initializes its rows on the device; the staged host input is returned /// because the chunk keeps it until the end. fn stage_prompt_rows<'arena, 'loan>( &mut self, - (binding, dense): (&ModelBinding, &DenseWeightCache<'ctx>), - txn: &mut OriginalPromptTxn<'_, 'ctx>, - tokens: &[TokenId], - (kar, arena): (&mut Option<&mut KarPleCache<'ctx>>, &'arena mut OriginalPrefillArena<'loan, 'ctx>), + chunk: &mut ChunkInFlight<'_, '_, 'ctx>, + kar: &mut Option<&mut KarPleCache<'ctx>>, + arena: &'arena mut OriginalPrefillArena<'loan, 'ctx>, ) -> Result> { - let (staged_input, staged_ple, first_predecessors) = Self::stage_prompt_inputs(binding, txn, tokens, kar)?; - let staged = (staged_input.as_ref(), staged_ple); - let rows = self.initialize_prompt_rows(binding, dense, txn, tokens, kar, arena, staged)?; + let binding = chunk.weights.binding; + let (staged_input, staged_ple, first_predecessors) = + Self::stage_prompt_inputs(binding, &mut *chunk.txn, chunk.window, kar)?; + let staged = StagedChunkInput { input: staged_input.as_ref(), ple: staged_ple }; + let rows = self.initialize_prompt_rows(chunk, kar, arena, staged)?; Ok((rows, first_predecessors, staged_input)) } /// The final row of the last layer, its sample, the draft KV and the end of the preview. fn finish_chunk_rows( &mut self, - (binding, dense): (&ModelBinding, &DenseWeightCache<'ctx>), - (moe, txn): (&mut MoeWeightCache<'ctx>, &mut OriginalPromptTxn<'_, 'ctx>), + mut work: ChunkWork<'_, '_, 'ctx>, carrier: Carrier<'_, '_, '_, 'ctx>, - (draft_args, cancelled): (DraftArgs<'_, 'ctx>, &mut impl FnMut() -> bool), + draft: ChunkDraft<'_, 'ctx>, + cancelled: &mut impl FnMut() -> bool, ) -> Result { - let (mut rows, final_row, sample) = self.prepare_final_row(binding, dense, moe, txn, carrier)?; - let chunk = (&mut rows, &final_row, &sample); - let draft_kv = self.record_draft_kv(binding, dense, moe, txn, chunk, draft_args, cancelled)?; + let (mut rows, final_row, sample) = self.prepare_final_row(&mut work, carrier)?; + let inputs = DraftKvInputs { + weights: work.weights, + moe: &*work.moe, + txn: work.txn, + final_row: &final_row, + sample: &sample, + context: self.context, + }; + let draft_kv = self.record_draft_kv(inputs, &mut rows, draft, cancelled)?; if cancelled() { return Err(Error::Unsupported(Stage::Session)); } let _span = prof::span(PStage::FinishPreview, Some(self.context as &dyn prof::Drain)); - rows.finish_after_preview(binding, dense, txn, &final_row) + rows.finish_after_preview(work.weights.binding, work.weights.dense, work.txn, &final_row) .map_err(|error| trace_error("finish_after_preview", error))?; Ok((final_row, sample, draft_kv)) } @@ -185,17 +180,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// Roll back after a failed chunk: stop the expert stream, then abort the transaction and the draft. fn forward_failed( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - txn: OriginalPromptTxn<'_, 'ctx>, - moe: &mut MoeWeightCache<'ctx>, - (checkpoint, draft, draft_checkpoint): ( - &OriginalSessionCheckpoint<'ctx>, - &mut OriginalDraftSession<'ctx>, - &OriginalDraftCheckpoint, - ), + weights: PromptWeights<'_, 'ctx>, + open: OpenChunk<'_, '_, 'ctx>, + rollback: &mut ChunkRollback<'_, 'ctx>, primary: &Error, ) { + let OpenChunk { txn, moe } = open; crate::bringup_trace!( "DBG[{:.0}s] forward operation failed: {primary:?}", crate::qwen_forward::original_serve_stack::dbg_el() @@ -204,7 +194,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { if moe.end_prompt_stream().is_err() { self.failed = true; } - let cleanup = txn.abort_with_draft(binding, dense, &mut self.layers, checkpoint, draft, draft_checkpoint); + let ChunkRollback { draft, checkpoint, draft_checkpoint } = rollback; + let cleanup = + txn.abort_with_draft(weights.binding, weights.dense, &mut self.layers, checkpoint, draft, draft_checkpoint); if cleanup.is_err() || self.context.is_poisoned() { self.failed = true; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_draft.rs index 95975a69..738b9085 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_draft.rs @@ -2,18 +2,19 @@ #[allow(unused_imports)] use super::*; -use crate::qwen_forward::prompt_device_rows::{DraftKvRequest, FinalPromptSources}; +use crate::qwen_forward::prompt_device_rows::{ + DraftKvRequest, FinalPromptSources, ScalarDraftKvRequest, ScalarPromptSources, +}; use leleka_cuda_driver::{MtpInt8Snapshot, MtpOriginalInt8, NativeBatchWorkspace, OriginalMtpActor, RecordRun}; /// The read-only inputs both draft-KV producers (batched and scalar fallback) take from the chunk. -struct DraftKvInputs<'a, 'ctx> { - binding: &'a ModelBinding, - dense: &'a DenseWeightCache<'ctx>, - moe: &'a MoeWeightCache<'ctx>, - txn: &'a OriginalPromptTxn<'a, 'ctx>, - final_row: &'a PromptDeviceFinal, - sample: &'a OriginalPromptSample, - context: &'ctx Context<'ctx>, +pub(super) struct DraftKvInputs<'a, 'ctx> { + pub(super) weights: PromptWeights<'a, 'ctx>, + pub(super) moe: &'a MoeWeightCache<'ctx>, + pub(super) txn: &'a OriginalPromptTxn<'a, 'ctx>, + pub(super) final_row: &'a PromptDeviceFinal, + pub(super) sample: &'a OriginalPromptSample, + pub(super) context: &'ctx Context<'ctx>, } /// The batched draft producer and the batch workspace it records through. @@ -23,20 +24,40 @@ struct BatchedDraftDevice<'a, 'ctx> { } /// The ring and its snapshot the draft KV is written into, and the first position that is still needed. -type DraftRing<'a, 'ctx> = (&'a mut MtpOriginalInt8<'ctx>, &'a MtpInt8Snapshot, usize); +struct DraftRing<'a, 'ctx> { + ring: &'a mut MtpOriginalInt8<'ctx>, + prior: &'a MtpInt8Snapshot, + first_needed: usize, +} /// The scalar fallback's actor, retained scalar weights and retained MTP weights. -type DraftScalarOwners<'a, 'ctx> = ( - &'a mut OriginalMtpActor<'ctx>, - std::rc::Rc>, - &'a RetainedOriginalMtpWeights<'ctx>, -); +struct DraftScalarOwners<'a, 'ctx> { + actor: &'a mut OriginalMtpActor<'ctx>, + scalar_weights: std::rc::Rc>, + retained_mtp: &'a RetainedOriginalMtpWeights<'ctx>, +} /// The owners of the two producers: the batched one and the scalar fallback's. -type DraftProducers<'a, 'ctx> = (&'a mut OriginalMtpPrefill<'ctx>, DraftScalarOwners<'a, 'ctx>); +struct DraftProducers<'a, 'ctx> { + batched: &'a mut OriginalMtpPrefill<'ctx>, + scalar: DraftScalarOwners<'a, 'ctx>, +} /// The embedding, scalar policy and cancellation the producers share. -type DraftExtras<'a, 'ctx, C> = (&'a OriginalPromptEmbedding<'ctx>, (&'a OriginalMtpScalarPolicy, &'a mut C)); +struct DraftExtras<'a, 'ctx, C> { + embedding: &'a OriginalPromptEmbedding<'ctx>, + policy: &'a OriginalMtpScalarPolicy, + cancelled: &'a mut C, +} + +/// What the scalar fallback needs when the batched producer falls back: its owners, the ring, the policy and the +/// cancellation poll. +struct ScalarFallback<'a, 'ctx, C> { + owners: DraftScalarOwners<'a, 'ctx>, + ring: DraftRing<'a, 'ctx>, + policy: &'a OriginalMtpScalarPolicy, + cancelled: &'a mut C, +} fn outcome_name(outcome: &OriginalPromptDraftOutcome) -> &'static str { match outcome { @@ -68,47 +89,42 @@ fn completed_draft(outcome: OriginalPromptDraftOutcome) -> Result OriginalPromptExecutor<'ctx> { /// Records the draft KV of the chunk into the draft session's pending ring. - #[allow(clippy::too_many_arguments)] pub(super) fn record_draft_kv( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - moe: &MoeWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, 'ctx>, - chunk: (&mut PromptDeviceRows<'_, '_, '_, 'ctx>, &PromptDeviceFinal, &OriginalPromptSample), - draft_args: DraftArgs<'_, 'ctx>, + inputs: DraftKvInputs<'_, 'ctx>, + rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>, + draft: ChunkDraft<'_, 'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result { let draft_span = prof::span(PStage::DraftKv, Some(self.context as &dyn prof::Drain)); - let draft_kv = self.draft_kv_in_ring(binding, dense, moe, txn, chunk, draft_args, cancelled)?; + let draft_kv = self.draft_kv_in_ring(inputs, rows, draft, cancelled)?; trace_step("forward: draft kv ok"); drop(draft_span); Ok(draft_kv) } - #[allow(clippy::too_many_arguments)] fn draft_kv_in_ring( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - moe: &MoeWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, 'ctx>, - (rows, final_row, sample): (&mut PromptDeviceRows<'_, '_, '_, 'ctx>, &PromptDeviceFinal, &OriginalPromptSample), - (draft, embedding, policy): DraftArgs<'_, 'ctx>, + inputs: DraftKvInputs<'_, 'ctx>, + rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>, + draft: ChunkDraft<'_, 'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result { + let binding = inputs.weights.binding; let producer = self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?; // The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared // layout is paired with that owner's main arena, a standalone owner is refused with InvalidQwenShape. let (context, max_t) = (self.context, self.max_t); - let scalar = self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding, context, max_t)?; + let actor = self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding, context, max_t)?; let scalar_weights = std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?); let retained_mtp = self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?; - let inputs = DraftKvInputs { binding, dense, moe, txn, final_row, sample, context }; - draft - .with_pending_ring(binding, txn, |ring, prior, first_needed| { - let producers = (producer, (scalar, scalar_weights, &retained_mtp)); - inputs.record_in_ring(rows, producers, (ring, prior, first_needed), (embedding, (policy, cancelled))) + let ChunkDraft { session, embedding, policy } = draft; + session + .with_pending_ring(binding, inputs.txn, |ring, prior, first_needed| { + let scalar = DraftScalarOwners { actor, scalar_weights, retained_mtp: &retained_mtp }; + let producers = DraftProducers { batched: producer, scalar }; + let ring = DraftRing { ring, prior, first_needed }; + inputs.record_in_ring(rows, producers, ring, DraftExtras { embedding, policy, cancelled }) }) .map_err(|error| trace_error("with_pending_ring", error)) } @@ -119,21 +135,25 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> { fn record_in_ring( &self, rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>, - (producer, scalar_owners): DraftProducers<'_, 'ctx>, - (ring, prior, first_needed): DraftRing<'_, 'ctx>, - (embedding, (policy, cancelled)): DraftExtras<'_, 'ctx, impl FnMut() -> bool>, + producers: DraftProducers<'_, 'ctx>, + draft_ring: DraftRing<'_, 'ctx>, + extras: DraftExtras<'_, 'ctx, impl FnMut() -> bool>, ) -> Result { + let DraftProducers { batched: producer, scalar: scalar_owners } = producers; + let DraftRing { ring, prior, first_needed } = draft_ring; + let DraftExtras { embedding, policy, cancelled } = extras; crate::bringup_trace!( "DBG[{:.0}s] draft ring open first_needed={first_needed:?}", crate::qwen_forward::original_serve_stack::dbg_el() ); - let mut workspace = - self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; - let batched_ring = (&mut *ring, prior, first_needed); - let batched = (embedding, (policy, &mut *cancelled)); + let PromptWeights { binding, dense } = self.weights; + let mut workspace = dense.native_batch_workspace(binding, self.context)?.ok_or(Error::IdentityMismatch)?; + let batched_ring = DraftRing { ring: &mut *ring, prior, first_needed }; + let batched = DraftExtras { embedding, policy, cancelled: &mut *cancelled }; let device = BatchedDraftDevice { producer, workspace: &mut workspace }; let outcome = self.record_batched(rows, device, batched_ring, batched)?; - let scalar = (scalar_owners, (ring, prior, first_needed), (policy, cancelled)); + let scalar = + ScalarFallback { owners: scalar_owners, ring: DraftRing { ring, prior, first_needed }, policy, cancelled }; let outcome = self.scalar_fallback(outcome, rows, &mut workspace, scalar)?; trace_outcome("after scalar fallback", &outcome); completed_draft(outcome) @@ -143,13 +163,16 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> { &self, rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>, device: BatchedDraftDevice<'_, 'ctx>, - (ring, prior, first_needed): DraftRing<'_, 'ctx>, - (embedding, (policy, cancelled)): DraftExtras<'_, 'ctx, impl FnMut() -> bool>, + draft_ring: DraftRing<'_, 'ctx>, + extras: DraftExtras<'_, 'ctx, impl FnMut() -> bool>, ) -> Result { let BatchedDraftDevice { producer, workspace } = device; + let DraftRing { ring, prior, first_needed } = draft_ring; + let DraftExtras { embedding, policy, cancelled } = extras; + let PromptWeights { binding, dense } = self.weights; let sources = FinalPromptSources { - binding: self.binding, - dense: self.dense, + binding, + dense, mtp: self.moe, txn: self.txn, preview: self.final_row, @@ -157,7 +180,7 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> { }; let mut cancelled = cancelled; let run = RecordRun { workspace, ring, cancelled: &mut cancelled }; - let embedding = embedding.borrow(self.binding, self.context)?; + let embedding = embedding.borrow(binding, self.context)?; let request = DraftKvRequest { prior, embedding, first_needed, policy: &policy.kv }; let outcome = rows.record_original_draft_kv(sources, producer, run, request)?; if let OriginalPromptDraftOutcome::Fallback(reason) = &outcome { @@ -173,16 +196,10 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> { outcome: OriginalPromptDraftOutcome, rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, - (owners, ring, (policy, cancelled)): ( - DraftScalarOwners<'_, 'ctx>, - DraftRing<'_, 'ctx>, - (&OriginalMtpScalarPolicy, &mut impl FnMut() -> bool), - ), + fallback: ScalarFallback<'_, 'ctx, impl FnMut() -> bool>, ) -> Result { match outcome { - OriginalPromptDraftOutcome::Fallback(_) => { - self.record_scalar(rows, owners, workspace, ring, (policy, cancelled)) - } + OriginalPromptDraftOutcome::Fallback(_) => self.record_scalar(rows, workspace, fallback), other => Ok(other), } } @@ -190,26 +207,23 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> { fn record_scalar( &self, rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>, - (scalar, scalar_weights, retained_mtp): DraftScalarOwners<'_, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, - (ring, prior, first_needed): DraftRing<'_, 'ctx>, - (policy, cancelled): (&OriginalMtpScalarPolicy, &mut impl FnMut() -> bool), + fallback: ScalarFallback<'_, 'ctx, impl FnMut() -> bool>, ) -> Result { - rows.record_original_scalar_draft_kv( - self.binding, - self.dense, - retained_mtp, - self.txn, - self.final_row, - self.sample.next(), - scalar, - workspace, - ring, - prior, - scalar_weights, - first_needed, - policy, - cancelled, - ) + let ScalarFallback { owners, ring: draft_ring, policy, cancelled } = fallback; + let DraftScalarOwners { actor, scalar_weights, retained_mtp } = owners; + let DraftRing { ring, prior, first_needed } = draft_ring; + let PromptWeights { binding, dense } = self.weights; + let sources = ScalarPromptSources { + binding, + dense, + mtp: retained_mtp, + txn: self.txn, + preview: self.final_row, + last_next: self.sample.next(), + }; + let run = RecordRun { workspace, ring, cancelled }; + let request = ScalarDraftKvRequest { prior, retained: scalar_weights, first_needed, policy }; + rows.record_original_scalar_draft_kv(sources, actor, run, request) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_final.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_final.rs index e5391ca5..3ed639b2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_final.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_final.rs @@ -37,17 +37,16 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// Ends the chunk's expert stream, then previews the conditioning row and takes its sample. pub(super) fn prepare_final_row<'arena, 'loan>( &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - moe: &mut MoeWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, 'ctx>, + work: &mut ChunkWork<'_, '_, 'ctx>, carrier: Carrier<'_, 'arena, 'loan, 'ctx>, ) -> Result<(PromptDeviceRows<'static, 'arena, 'loan, 'ctx>, PromptDeviceFinal, OriginalPromptSample)> { + let PromptWeights { binding, dense } = work.weights; + let txn = work.txn; let Carrier::Plain(mut rows) = carrier else { return Err(Error::IdentityMismatch); }; // the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers - moe.end_prompt_stream()?; + work.moe.end_prompt_stream()?; let final_span = prof::span(PStage::Final, Some(self.context as &dyn prof::Drain)); trace_step("forward: all layers ok, final row"); let preview = rows.preview_conditioning(binding, dense, txn); @@ -75,8 +74,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { } let first = txn.start_position(); let count = txn.len(); - let hash = - rows.with_final_residual(binding, dense, txn, final_row, |residual| hash_final_rows(residual, count))?; + let hash = rows.with_final_residual(PromptWeights::new(binding, dense), txn, final_row, |residual| { + hash_final_rows(residual, count) + })?; eprintln!( "PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}", hash.0, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs index f4eaa39f..f7915772 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs @@ -8,6 +8,22 @@ use crate::qwen_forward::kar_ple_cache::KarPleStaged; /// two tokens before the chunk (the per-token host path stages nothing). type StagedPrompt = (Option, Option, Option<[i32; 2]>); +/// The chunk-wide staged embedding input and staged PLE rows; both are present after the batched staging and both +/// are absent on the per-token host path. +pub(super) struct StagedChunkInput<'a> { + pub(super) input: Option<&'a StagedInput>, + pub(super) ple: Option, +} + +/// Everything the device scatter of the staged rows consumes: the arena lease, one source per row and the staged +/// input with its PLE rows. +struct StagedUpload<'a, 'arena, 'loan, 'ctx> { + lease: leleka_cuda_driver::OriginalPromptRows<'arena, 'loan, 'ctx>, + sources: Vec>, + input: &'a StagedInput, + ple: KarPleStaged, +} + impl<'ctx> OriginalPromptExecutor<'ctx> { pub(super) fn stage_prompt_inputs( binding: &ModelBinding, @@ -75,29 +91,31 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { } /// Source rows, upload and device initialization of the chunk's rows. - #[allow(clippy::too_many_arguments)] pub(super) fn initialize_prompt_rows<'arena, 'loan>( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, 'ctx>, - tokens: &[TokenId], + chunk: &ChunkInFlight<'_, '_, 'ctx>, kar: &mut Option<&mut KarPleCache<'ctx>>, arena: &'arena mut OriginalPrefillArena<'loan, 'ctx>, - (staged_input, staged_ple): (Option<&StagedInput>, Option), + staged: StagedChunkInput<'_>, ) -> Result> { + let weights = chunk.weights; + let (binding, tokens, txn) = (weights.binding, chunk.window, &*chunk.txn); let drain = Some(self.context as &dyn prof::Drain); let init_span = prof::span(PStage::Initialize, drain); let sources = Self::prompt_sources(binding, self.context, txn, tokens.len())?; let upload_span = prof::span(PStage::InitUpload, drain); let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; let lease = arena.begin_rows(tokens.len()).map_err(driver_error)?; - let rows = match (staged_input, staged_ple) { + let rows = match (staged.input, staged.ple) { (Some(input), Some(ple)) => { let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; - Self::initialize_staged_rows(binding, dense, self.context, prompt, cache, lease, sources, (input, ple))? + let upload = StagedUpload { lease, sources, input, ple }; + Self::initialize_staged_rows(weights, self.context, prompt, cache, upload)? + } + _ => { + let upload = RowsUpload { lease, stage: None }; + PromptDeviceRows::initialize(weights, self.context, prompt, upload, sources)? } - _ => PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, None)?, }; drop(upload_span); drop(init_span); @@ -105,17 +123,15 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { } /// The device scatters the staged embedding and PLE rows; the PLE cache learns them only after that succeeded. - #[allow(clippy::too_many_arguments)] fn initialize_staged_rows<'arena, 'loan>( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, context: &'ctx Context<'ctx>, prompt: &mut OriginalPromptDevice<'ctx>, cache: &mut KarPleCache<'ctx>, - lease: leleka_cuda_driver::OriginalPromptRows<'arena, 'loan, 'ctx>, - sources: Vec>, - (input, ple): (&StagedInput, KarPleStaged), + upload: StagedUpload<'_, 'arena, 'loan, 'ctx>, ) -> Result> { + let PromptWeights { binding, dense } = weights; + let StagedUpload { lease, sources, input, ple } = upload; let result = Self::scatter_staged_rows(binding, dense, context, (prompt, cache), (lease, sources, input, &ple)); match result { Ok(rows) => { @@ -169,19 +185,20 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { ple_updates: ple.updates(), ple_slots: ple.slots(), }; - PromptDeviceRows::initialize(binding, dense, context, prompt, lease, sources, Some(stage)) + let upload = RowsUpload { lease, stage: Some(stage) }; + PromptDeviceRows::initialize(PromptWeights::new(binding, dense), context, prompt, upload, sources) } /// The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes /// (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there. pub(super) fn read_ahead_next_chunk( &self, - binding: &ModelBinding, - source: &std::rc::Rc, - (tokens, first_position): (&[TokenId], u64), + chunk: &ChunkInFlight<'_, '_, 'ctx>, kar: &mut Option<&mut KarPleCache<'ctx>>, first_predecessors: Option<[i32; 2]>, ) { + let (binding, source) = (chunk.weights.binding, chunk.source); + let (tokens, first_position) = (chunk.window, chunk.first_position); let (Some(cache), Some(kar_binding), Some(mut before)) = (kar.as_deref_mut(), binding.kar_ple_binding(), first_predecessors) else { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_layers.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_layers.rs index 095a670e..be50cb46 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_layers.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_layers.rs @@ -16,14 +16,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// Layer-major order: every layer completes all rows of the chunk before the next starts. pub(super) fn run_layers<'w, 'arena, 'loan>( &mut self, - binding: &ModelBinding, - dense: &'w DenseWeightCache<'ctx>, - moe: &mut MoeWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, 'ctx>, + work: &mut ChunkWork<'w, '_, 'ctx>, mut carrier: Carrier<'w, 'arena, 'loan, 'ctx>, ) -> Result> { + let binding = work.weights.binding; for layer in binding.ordered_layers() { - carrier = self.run_layer(layer, binding, dense, moe, txn, carrier)?; + carrier = self.run_layer(layer, work, carrier)?; } Ok(carrier) } @@ -31,12 +29,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { fn run_layer<'w, 'arena, 'loan>( &mut self, layer: &BoundLayer, - binding: &ModelBinding, - dense: &'w DenseWeightCache<'ctx>, - moe: &mut MoeWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, 'ctx>, + work: &mut ChunkWork<'w, '_, 'ctx>, carrier: Carrier<'w, 'arena, 'loan, 'ctx>, ) -> Result> { + let weights = work.weights; + let PromptWeights { binding, dense } = weights; + let txn = work.txn; let index = layer.index(); crate::bringup_trace!( "DBG[{:.0}s] forward layer {index} {:?} begin", @@ -47,10 +45,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { let mut read = self.read_attention(binding, dense, carrier, index)?; crate::bringup_trace!("DBG[{:.0}s] L{index} attn-read ok", crate::qwen_forward::original_serve_stack::dbg_el()); validated(|| read.validate_original_rows(binding, dense))?; - let ffn = self.complete_mixer(binding, dense, txn, read, layer)?; + let ffn = self.complete_mixer(weights, txn, read, layer)?; crate::bringup_trace!("DBG[{:.0}s] L{index} mixer ok", crate::qwen_forward::original_serve_stack::dbg_el()); let read = self.read_ffn(binding, dense, ffn, index)?; - let carrier = self.complete_moe(binding, dense, moe, read, index)?; + let carrier = self.complete_moe(weights, &mut *work.moe, read, index)?; crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok", crate::qwen_forward::original_serve_stack::dbg_el()); Ok(carrier) } @@ -105,8 +103,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// The token mixer (GDN or QSA) of the layer, fused with the next norm when `fused`. fn complete_mixer<'w, 'arena, 'loan>( &mut self, - binding: &ModelBinding, - dense: &'w DenseWeightCache<'ctx>, + weights: PromptWeights<'w, 'ctx>, txn: &OriginalPromptTxn<'_, 'ctx>, read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>, layer: &BoundLayer, @@ -120,9 +117,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { drain, ); let ffn = if self.fused { - Carrier::Normed(self.mixer_normed(binding, dense, txn, read, layer)?) + Carrier::Normed(self.mixer_normed(weights, txn, read, layer)?) } else { - Carrier::Plain(self.mixer_plain(binding, dense, txn, read, layer)?) + Carrier::Plain(self.mixer_plain(weights, txn, read, layer)?) }; drop(mixer_span); Ok(ffn) @@ -130,8 +127,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { fn mixer_normed<'w, 'arena, 'loan>( &mut self, - binding: &ModelBinding, - dense: &'w DenseWeightCache<'ctx>, + weights: PromptWeights<'w, 'ctx>, txn: &OriginalPromptTxn<'_, 'ctx>, read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>, layer: &BoundLayer, @@ -139,51 +135,47 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; match layer.kind() { BoundLayerKind::Gdn => read.complete_original_gdn_normed( - binding, - dense, + weights, txn, prompt, self.gdn.as_mut().ok_or(Error::IdentityMismatch)?, ), BoundLayerKind::Qsa => read.complete_original_qsa_normed( - binding, - dense, + weights, txn, prompt, - self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?, - self.qsa.as_mut().ok_or(Error::IdentityMismatch)?, - self.transport.as_mut().ok_or(Error::IdentityMismatch)?, - self.attention.as_mut().ok_or(Error::IdentityMismatch)?, + QsaLayerDevices { + layer_owner: self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?, + qsa: self.qsa.as_mut().ok_or(Error::IdentityMismatch)?, + transport: self.transport.as_mut().ok_or(Error::IdentityMismatch)?, + attention: self.attention.as_mut().ok_or(Error::IdentityMismatch)?, + }, ), } } fn mixer_plain<'arena, 'loan>( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, 'ctx>, read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>, layer: &BoundLayer, ) -> Result> { let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; match layer.kind() { - BoundLayerKind::Gdn => read.complete_original_gdn( - binding, - dense, - txn, - prompt, - self.gdn.as_mut().ok_or(Error::IdentityMismatch)?, - ), + BoundLayerKind::Gdn => { + read.complete_original_gdn(weights, txn, prompt, self.gdn.as_mut().ok_or(Error::IdentityMismatch)?) + } BoundLayerKind::Qsa => read.complete_original_qsa( - binding, - dense, + weights, txn, prompt, - self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?, - self.qsa.as_mut().ok_or(Error::IdentityMismatch)?, - self.transport.as_mut().ok_or(Error::IdentityMismatch)?, - self.attention.as_mut().ok_or(Error::IdentityMismatch)?, + QsaLayerDevices { + layer_owner: self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?, + qsa: self.qsa.as_mut().ok_or(Error::IdentityMismatch)?, + transport: self.transport.as_mut().ok_or(Error::IdentityMismatch)?, + attention: self.attention.as_mut().ok_or(Error::IdentityMismatch)?, + }, ), } } @@ -217,12 +209,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { fn complete_moe<'w, 'arena, 'loan>( &mut self, - binding: &ModelBinding, - dense: &'w DenseWeightCache<'ctx>, + weights: PromptWeights<'w, 'ctx>, moe: &mut MoeWeightCache<'ctx>, read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>, index: u32, ) -> Result> { + let PromptWeights { binding, dense } = weights; let drain = Some(self.context as &dyn prof::Drain); let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; let moe_span = prof::span(PStage::Moe, drain); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/prompt_chunk_operands.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/prompt_chunk_operands.rs new file mode 100644 index 00000000..c076f038 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/prompt_chunk_operands.rs @@ -0,0 +1,66 @@ +//! The operand groups one batched prompt chunk passes between the phases of `OriginalPromptExecutor::forward`. +use super::*; + +/// The next `count` tokens of the prompt source that one chunk consumes. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct PromptChunkSource<'a> { + pub(in crate::qwen_forward) source: &'a std::rc::Rc, + pub(in crate::qwen_forward) count: usize, +} + +/// What one chunk advances: the target model weights, the target session and the prompt tokens it consumes. +pub(in crate::qwen_forward) struct PromptChunkTarget<'session, 'program, 'ctx> { + pub(in crate::qwen_forward) weights: PromptWeights<'program, 'ctx>, + pub(in crate::qwen_forward) session: &'session mut QwenSession<'ctx>, + pub(in crate::qwen_forward) tokens: PromptChunkSource<'program>, +} + +/// The PLE cache, the expert cache and the device arena a chunk computes in. +pub(in crate::qwen_forward) struct ChunkCaches<'a, 'loan, 'ctx> { + pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>, + pub(in crate::qwen_forward) moe: &'a mut MoeWeightCache<'ctx>, + pub(in crate::qwen_forward) arena: &'a mut OriginalPrefillArena<'loan, 'ctx>, +} + +/// The draft session of a chunk, the embedding its draft KV is computed from and the scalar draft policy. +pub(in crate::qwen_forward) struct ChunkDraft<'a, 'ctx> { + pub(in crate::qwen_forward) session: &'a mut OriginalDraftSession<'ctx>, + pub(in crate::qwen_forward) embedding: &'a OriginalPromptEmbedding<'ctx>, + pub(in crate::qwen_forward) policy: &'a OriginalMtpScalarPolicy, +} + +impl<'ctx> ChunkDraft<'_, 'ctx> { + /// The same draft for a shorter borrow, so the draft session is usable again after the chunk. + pub(in crate::qwen_forward) fn reborrow(&mut self) -> ChunkDraft<'_, 'ctx> { + ChunkDraft { session: &mut *self.session, embedding: self.embedding, policy: self.policy } + } +} + +/// A chunk whose inputs are being staged: its weights, open prompt transaction and the window it consumes. +pub(super) struct ChunkInFlight<'a, 'txn, 'ctx> { + pub(super) weights: PromptWeights<'a, 'ctx>, + pub(super) txn: &'a mut OriginalPromptTxn<'txn, 'ctx>, + pub(super) window: &'a [TokenId], + pub(super) first_position: u64, + pub(super) source: &'a std::rc::Rc, +} + +/// What every layer and the final row of a chunk work against: weights, expert cache and prompt transaction. +pub(super) struct ChunkWork<'a, 'txn, 'ctx> { + pub(super) weights: PromptWeights<'a, 'ctx>, + pub(super) moe: &'a mut MoeWeightCache<'ctx>, + pub(super) txn: &'a OriginalPromptTxn<'txn, 'ctx>, +} + +/// The still-open prompt transaction of a chunk and the expert cache whose prompt stream a failure must end. +pub(super) struct OpenChunk<'session, 'a, 'ctx> { + pub(super) txn: OriginalPromptTxn<'session, 'ctx>, + pub(super) moe: &'a mut MoeWeightCache<'ctx>, +} + +/// The draft session and the two checkpoints a failed chunk is rolled back to. +pub(super) struct ChunkRollback<'program, 'ctx> { + pub(super) draft: &'program mut OriginalDraftSession<'ctx>, + pub(super) checkpoint: OriginalSessionCheckpoint<'ctx>, + pub(super) draft_checkpoint: OriginalDraftCheckpoint, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs index 36c15a84..ebca318c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs @@ -7,7 +7,7 @@ use super::*; use crate::model_binding::qwen4exp_input::{MtpKind, MtpRole}; use leleka_cuda_driver::{ CompletedDraftKv, DraftKvOutcome, DraftKvPolicy, DraftKvSources, MtpInt8Snapshot, MtpOriginalInt8, - NativeBatchWorkspace, OriginalMtpEmbedding, OriginalMtpPrefill, OriginalMtpPrefillWeights, PrefillRows, RecordRun, + OriginalMtpEmbedding, OriginalMtpPrefill, OriginalMtpPrefillWeights, PrefillRows, RecordRun, }; /// Affine runtime handoff. Does not publish either canonical target or draft. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs index 9dfd4ba0..5ff8ce44 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs @@ -2,29 +2,21 @@ //! phase, shifted actual IDs and current ring receipt, literal scalar producer. use super::*; use crate::qwen_forward::moe_weight_cache::RetainedOriginalMtpWeights; -use leleka_cuda_driver::{OriginalMtpActor, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy}; +use leleka_cuda_driver::{OriginalMtpActor, OriginalMtpRetainedScalarWeights}; impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { /// Original Prefill uses only known-next conditioning with no head/D2H. /// The genuine all-row R and immutable input owners survive through drain. - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn record_original_scalar_draft_kv( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - mtp: &RetainedOriginalMtpWeights<'ctx>, - txn: &OriginalPromptTxn<'_, '_>, - preview: &PromptDeviceFinal, - last_next: TokenId, + sources: ScalarPromptSources<'_, 'ctx>, producer: &mut OriginalMtpActor<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - retained: Rc>, - first_needed: usize, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, + run: RecordRun<'_, 'ctx, impl FnMut() -> bool>, + request: ScalarDraftKvRequest<'_, 'ctx>, ) -> Result { - let phase = self.check_scalar_sources(binding, dense, txn, preview, last_next)?; + let ScalarPromptSources { binding, dense, mtp, txn, preview, last_next } = sources; + let RecordRun { workspace, ring, cancelled } = run; + let ScalarDraftKvRequest { prior, retained, first_needed, policy } = request; + let phase = self.check_scalar_sources(sources)?; let next = self.shifted_next_ids(txn, last_next)?; check_retained_matrices(binding, mtp, self.sources.context, &retained)?; let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?; @@ -126,14 +118,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx } /// The scalar producer also pins the lease and the prompt's known next token. - fn check_scalar_sources( - &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - txn: &OriginalPromptTxn<'_, '_>, - preview: &PromptDeviceFinal, - last_next: TokenId, - ) -> Result> { + fn check_scalar_sources(&self, sources: ScalarPromptSources<'_, 'ctx>) -> Result> { + let ScalarPromptSources { binding, dense, txn, preview, last_next, .. } = sources; let phase = self.sources_phase(binding, dense, txn, preview, last_next)?; if !self.sources_agree(txn, preview, &phase)? { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index cd0351d0..95d6beed 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -21,7 +21,10 @@ use super::{ contract::{Error, Result}, dense_weight_cache::DenseWeightCache, - executor::original_prompt::{OriginalPromptExecutor, embedding::OriginalPromptEmbedding}, + executor::original_prompt::{ + ChunkCaches, ChunkDraft, OriginalPromptExecutor, PromptChunkSource, PromptChunkTarget, + embedding::OriginalPromptEmbedding, + }, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache, original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, @@ -42,6 +45,7 @@ use super::{ }, original_spec_controller::{OriginalSpecController, SpecError}, output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, + prompt_device_rows::PromptWeights, session::{ QwenSession, original_prompt::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs index 2465cc3a..d4036699 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs @@ -44,8 +44,8 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); let _p = profile::span("prefix.import_session"); // a refused import touches nothing; a failed physical one poisons the executor - let imported = - self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); + let weights = PromptWeights::new(self.binding, &self.dense); + let imported = self.executor.import_session(weights, &mut self.session, &state.session, &blocks); if let Err(error) = imported { self.mark_broken(error); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs index 047f252b..6e337048 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs @@ -11,20 +11,14 @@ impl<'ctx> PromptChunk<'_, 'ctx> { arena: &mut OriginalPrefillArena<'_, 'ctx>, cancel: &mut dyn FnMut() -> bool, ) -> std::result::Result<(), SpecError> { - let pending = self.executor.forward( - self.binding, - self.dense, - &mut *self.session, - self.source, - count, - self.kar.as_deref_mut(), - &mut *self.moe, - &mut *arena, - &mut *self.draft, - self.embedding, - self.scalar_policy, - || cancel(), - ); + let target = PromptChunkTarget { + weights: PromptWeights::new(self.binding, self.dense), + session: &mut *self.session, + tokens: PromptChunkSource { source: self.source, count }, + }; + let caches = ChunkCaches { kar: self.kar.as_deref_mut(), moe: &mut *self.moe, arena: &mut *arena }; + let draft = ChunkDraft { session: &mut *self.draft, embedding: self.embedding, policy: self.scalar_policy }; + let pending = self.executor.forward(target, caches, draft, || cancel()); let pending = forward_outcome(pending, cancel)?; crate::bringup_trace!("DBG[{:.0}s] forward ok, publishing", dbg_el()); let _span = super::super::prefill_profile::span(super::super::prefill_profile::Stage::Publish, None); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs index 94af73dd..51f93362 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs @@ -80,10 +80,17 @@ pub(in crate::qwen_forward) use mtp_prefill::{ mod impl_promptdeviceread; mod impl_std_ops_deref; +pub(in crate::qwen_forward) use impl_promptdeviceread::QsaLayerDevices; #[allow(unused_imports)] use impl_promptdeviceread::produce_original_gdn; #[allow(unused_imports)] use impl_promptdeviceread::produce_original_qsa; mod impl_promptplehistory; +mod prompt_weights; +pub(in crate::qwen_forward) use prompt_weights::PromptWeights; +mod rows_upload; +mod scalar_draft_kv_operands; #[allow(unused_imports)] use impl_promptplehistory::{micro_driver_error, run_transfer}; +pub(in crate::qwen_forward) use rows_upload::RowsUpload; +pub(in crate::qwen_forward) use scalar_draft_kv_operands::{ScalarDraftKvRequest, ScalarPromptSources}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs index 078345a2..8da627d9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs @@ -6,6 +6,7 @@ use super::*; mod impl_promptdeviceread_2; mod produce_original_gdn_fn; +pub(in crate::qwen_forward) use produce_original_gdn_fn::QsaLayerDevices; #[allow(unused_imports)] pub(super) use produce_original_gdn_fn::produce_original_gdn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs index db530eb8..171a2d0c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs @@ -14,8 +14,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx } pub(in crate::qwen_forward) fn validate_row( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, index: usize, role: GrRole, @@ -23,7 +22,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx if index != self.sources.validated { return Err(Error::IdentityMismatch); } - let id = self.sources.current(binding, cache, txn, index, role)?; + let id = self.sources.current(weights, txn, index, role)?; self.sources.validated += 1; Ok(id) } @@ -51,14 +50,14 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx /// Only its genuine completed end recurrence/history enters the journal. pub(in crate::qwen_forward) fn complete_original_gdn( self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, producer: &mut OriginalPromptDevice<'ctx>, gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, ) -> Result> { + let PromptWeights { binding, dense } = weights; let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; - self.complete_with(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { + self.complete_with(weights, producer, GrRole::Ffn(layer.get()), |read| { let mut lap = Lap::off(); let (mut state, rows) = GdnLayer::enter(binding, dense, txn, context, layer, &mut lap)?; let (block, edges) = state.compute(binding, dense, rows, read, gdn)?; @@ -68,12 +67,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx } pub(in crate::qwen_forward) fn complete_original_gdn_normed<'weight>( self, - binding: &ModelBinding, - dense: &'weight DenseWeightCache<'ctx>, + weights: PromptWeights<'weight, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, producer: &mut OriginalPromptDevice<'ctx>, gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, ) -> Result> { + let PromptWeights { binding, dense } = weights; let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with_normed(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { produce_original_gdn(binding, dense, txn, context, layer, read, gdn) @@ -81,35 +80,27 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx } pub(in crate::qwen_forward) fn complete_original_qsa( self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, 'ctx>, producer: &mut OriginalPromptDevice<'ctx>, - layer_owner: &mut super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, - qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, - transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, - attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, + devices: QsaLayerDevices<'_, 'ctx>, ) -> Result> { + let PromptWeights { binding, dense } = weights; let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; - self.complete_with(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { - let devices = QsaLayerDevices { layer_owner, qsa, transport, attention }; + self.complete_with(weights, producer, GrRole::Ffn(layer.get()), |read| { produce_original_qsa(binding, dense, txn, context, layer, read, devices) }) } pub(in crate::qwen_forward) fn complete_original_qsa_normed<'weight>( self, - binding: &ModelBinding, - dense: &'weight DenseWeightCache<'ctx>, + weights: PromptWeights<'weight, 'ctx>, txn: &OriginalPromptTxn<'_, 'ctx>, producer: &mut OriginalPromptDevice<'ctx>, - layer_owner: &mut super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, - qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, - transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, - attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, + devices: QsaLayerDevices<'_, 'ctx>, ) -> Result> { + let PromptWeights { binding, dense } = weights; let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with_normed(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { - let devices = QsaLayerDevices { layer_owner, qsa, transport, attention }; produce_original_qsa(binding, dense, txn, context, layer, read, devices) }) } @@ -132,7 +123,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx let next = layer.checked_add(1).ok_or(Error::Overflow)?; let role = if next == binding.layer_count() { GrRole::Final } else { GrRole::Attention(next) }; let context = self.sources.context; - self.complete_with(binding, dense, producer, role, |read| { + self.complete_with(PromptWeights::new(binding, dense), producer, role, |read| { let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; cache.original_prompt_moe(binding, dense, id, read, &mut workspace) }) @@ -163,18 +154,18 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx /// Block. Root retains chronological source proof and all causal journals. pub(in crate::qwen_forward) fn complete_with( self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, producer: &mut OriginalPromptDevice<'ctx>, next_role: GrRole, produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> DeviceBlockResult<'arena, 'loan, 'ctx>, ) -> Result> { + let PromptWeights { binding, dense: cache } = weights; self.check_next_role(binding, cache, next_role)?; let block = produce_block(self.device, produce)?; self.sources.validate(binding, cache)?; let context = self.sources.context; let span = inject_span(context); - let device = run_transfer(binding, cache, context, producer, span, |producer, workspace| { + let device = run_transfer(weights, context, producer, span, |producer, workspace| { producer.inject_gr(block, workspace).map_err(micro_driver_error) })?; self.sources.validate(binding, cache)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs index ab934c04..156586de 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs @@ -122,11 +122,11 @@ pub(in super::super) fn produce_original_gdn<'arena, 'loan, 'ctx>( } /// The devices of one resident QSA layer: its index/KV owner, the prompt producer, the transport and the attention. -pub(in super::super) struct QsaLayerDevices<'a, 'ctx> { - pub(in super::super) layer_owner: &'a mut ResidentQsaLayer<'ctx>, - pub(in super::super) qsa: &'a mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, - pub(in super::super) transport: &'a mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, - pub(in super::super) attention: &'a mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, +pub(in crate::qwen_forward) struct QsaLayerDevices<'a, 'ctx> { + pub(in crate::qwen_forward) layer_owner: &'a mut ResidentQsaLayer<'ctx>, + pub(in crate::qwen_forward) qsa: &'a mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + pub(in crate::qwen_forward) transport: &'a mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + pub(in crate::qwen_forward) attention: &'a mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, } /// One prompt QSA layer between its host setup and its stage: inputs, prior and the batch workspace. @@ -250,7 +250,7 @@ impl<'weight, 'source, 'arena, 'loan, 'ctx> PromptDeviceNormedRows<'weight, 'sou if index != self.sources.validated { return Err(Error::IdentityMismatch); } - let id = self.sources.current(binding, cache, txn, index, role)?; + let id = self.sources.current(PromptWeights::new(binding, cache), txn, index, role)?; self.sources.validated += 1; Ok(id) } @@ -284,7 +284,7 @@ impl<'weight, 'source, 'arena, 'loan, 'ctx> PromptDeviceNormedRows<'weight, 'sou return Err(Error::IdentityMismatch); } let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); - run_transfer(binding, cache, context, producer, (), |producer, workspace| { + run_transfer(PromptWeights::new(binding, cache), context, producer, (), |producer, workspace| { producer .read_gr_normed(device, workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) .map_err(micro_driver_error) @@ -309,9 +309,10 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx self.sources.validate(binding, cache)?; let context = self.sources.context; let span = inject_span(context); - let device = run_transfer(binding, cache, context, producer, span, |producer, workspace| { - producer.inject_gr_fused(block, workspace, gamma, epsilon).map_err(micro_driver_error) - })?; + let device = + run_transfer(PromptWeights::new(binding, cache), context, producer, span, |producer, workspace| { + producer.inject_gr_fused(block, workspace, gamma, epsilon).map_err(micro_driver_error) + })?; self.sources.validate(binding, cache)?; if let Some(phase) = self.sources.original_phase()? { phase.inject(self.sources.role, next_role)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs index a31370c0..7e9fa0f0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs @@ -59,13 +59,13 @@ pub(super) fn micro_driver_error(error: leleka_cuda_driver::Error) -> Error { /// the transfer has returned; a producer that failed then marks the transport failed, before the transfer's own result /// is handed back. pub(super) fn run_transfer<'ctx, T>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, context: &Context<'_>, producer: &mut OriginalPromptDevice<'ctx>, span: impl Sized, transfer: impl FnOnce(&mut OriginalPromptDevice<'ctx>, &mut NativeBatchWorkspace<'ctx>) -> Result, ) -> Result { + let PromptWeights { binding, dense: cache } = weights; let result = (|| { let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; transfer(&mut *producer, &mut workspace) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs index 74530906..fce0eed5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs @@ -78,12 +78,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx /// the genuine MTP producer. No host reconstruction substitutes for it. pub(in crate::qwen_forward) fn with_final_residual( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, completed: &PromptDeviceFinal, execute: impl FnOnce(&mut OriginalDeviceResidual<'arena, 'loan, 'ctx>) -> Result, ) -> Result { + let PromptWeights { binding, dense: cache } = weights; self.validate_preview(binding, cache, txn, completed)?; let value = execute(&mut self.device)?; self.validate_preview(binding, cache, txn, completed)?; @@ -151,14 +151,14 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx }) } pub(in crate::qwen_forward) fn initialize( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, context: &Context<'_>, producer: &mut OriginalPromptDevice<'ctx>, - lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + upload: RowsUpload<'_, 'arena, 'loan, 'ctx>, rows: Vec>, - stage: Option>, ) -> Result { + let PromptWeights { binding, dense: cache } = weights; + let RowsUpload { lease, stage } = upload; let context = cache.retained_context(binding, context)?; if rows.is_empty() || rows.len() != lease.rows() { return Err(Error::InvalidDimension); @@ -169,21 +169,20 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx // and PLE embeddings. Later layer phases retain this same device R. // The driver stages every row's streams and PLE embedding in place (one pass, same bytes and refusals). sources.check_staging(stage.is_some())?; - let device = Self::stage_rows(binding, cache, context, producer, lease, &sources, stage)?; + let device = Self::stage_rows(weights, context, producer, RowsUpload { lease, stage }, &sources)?; sources.finish_initialize(binding, cache)?; Ok(Self { sources, device }) } fn stage_rows( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, context: &Context<'_>, producer: &mut OriginalPromptDevice<'ctx>, - lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + upload: RowsUpload<'_, 'arena, 'loan, 'ctx>, sources: &Sources<'source, 'ctx>, - stage: Option>, ) -> Result> { + let RowsUpload { lease, stage } = upload; if let Some(stage) = stage { - return run_transfer(binding, cache, context, producer, (), |producer, workspace| { + return run_transfer(weights, context, producer, (), |producer, workspace| { producer.initialize_staged(lease, workspace, stage).map_err(micro_driver_error) }); } @@ -192,7 +191,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx for s in &sources.rows { slices.push((s.input.streams().values(), s.input.ple_embedding())); } - run_transfer(binding, cache, context, producer, (), |producer, workspace| { + run_transfer(weights, context, producer, (), |producer, workspace| { producer.initialize_rows(lease, workspace, &slices).map_err(micro_driver_error) }) } @@ -205,8 +204,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx } pub(in crate::qwen_forward) fn validate_row( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, index: usize, role: GrRole, @@ -214,7 +212,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx if index != self.sources.validated { return Err(Error::IdentityMismatch); } - let id = self.sources.current(binding, cache, txn, index, role)?; + let id = self.sources.current(weights, txn, index, role)?; self.sources.validated += 1; Ok(id) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs index 8853dee1..5e057ba4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs @@ -14,9 +14,10 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx self.check_ple(binding, cache, history)?; let context = self.sources.context; let weights = Self::ple_weights(binding, cache, context)?; - self.device = run_transfer(binding, cache, context, producer, (), |producer, workspace| { - producer.apply_ple(self.device, workspace, weights, &mut history.device).map_err(micro_driver_error) - })?; + self.device = + run_transfer(PromptWeights::new(binding, cache), context, producer, (), |producer, workspace| { + producer.apply_ple(self.device, workspace, weights, &mut history.device).map_err(micro_driver_error) + })?; self.sources.validate(binding, cache)?; history.completed_rows = Some(self.sources.rows.len()); if let Some(phase) = self.sources.original_phase()? { @@ -66,7 +67,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx ) -> Result> { self.sources.begin_read(binding, cache, role)?; let context = self.sources.context; - let device = Self::read_device(self.device, binding, cache, context, producer, role)?; + let device = Self::read_device(self.device, PromptWeights::new(binding, cache), context, producer, role)?; self.sources.validate(binding, cache)?; if let Some(phase) = self.sources.original_phase()? { phase.read(role)?; @@ -77,18 +78,18 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx } fn read_device( device: OriginalDeviceResidual<'arena, 'loan, 'ctx>, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, context: &Context<'_>, producer: &mut OriginalPromptDevice<'ctx>, role: GrRole, ) -> Result> { + let PromptWeights { binding, dense: cache } = weights; let resident = cache.gr(binding, role)?; if !resident.weights.matches(&binding.identity(), role) { return Err(Error::IdentityMismatch); } let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); - run_transfer(binding, cache, context, producer, (), |producer, workspace| { + run_transfer(weights, context, producer, (), |producer, workspace| { producer .read_gr(device, workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) .map_err(micro_driver_error) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs index 36730cff..a5507fc0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs @@ -198,12 +198,12 @@ impl Sources<'_, '_> { } pub(in super::super) fn current( &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, index: usize, role: GrRole, ) -> Result { + let PromptWeights { binding, dense: cache } = weights; self.validate(binding, cache)?; if self.role != role || !std::ptr::eq(self.context, txn.cuda_context()?) { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/prompt_weights.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/prompt_weights.rs new file mode 100644 index 00000000..c7805f59 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/prompt_weights.rs @@ -0,0 +1,18 @@ +//! The two model-wide owners every prompt row phase is validated against. +use super::*; + +/// The model binding and the dense weight cache a prompt phase validates its rows against and reads its weights +/// from; they always travel together, so a phase takes this one value instead of two parameters. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct PromptWeights<'w, 'ctx> { + pub(in crate::qwen_forward) binding: &'w ModelBinding, + pub(in crate::qwen_forward) dense: &'w DenseWeightCache<'ctx>, +} + +impl<'w, 'ctx> PromptWeights<'w, 'ctx> { + /// The weights of one loaded model: its binding and the dense cache built for it. + #[inline] + pub(in crate::qwen_forward) fn new(binding: &'w ModelBinding, dense: &'w DenseWeightCache<'ctx>) -> Self { + Self { binding, dense } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/rows_upload.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/rows_upload.rs new file mode 100644 index 00000000..4dafefcd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/rows_upload.rs @@ -0,0 +1,9 @@ +//! What device initialization of the prompt rows uploads from. +use super::*; + +/// The arena lease the rows of a chunk live in and the optional chunk-wide staged input (embedding rows and PLE +/// updates) they are initialized from; `None` means the per-token host rows are uploaded instead. +pub(in crate::qwen_forward) struct RowsUpload<'stage, 'arena, 'loan, 'ctx> { + pub(in crate::qwen_forward) lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + pub(in crate::qwen_forward) stage: Option>, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/scalar_draft_kv_operands.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/scalar_draft_kv_operands.rs new file mode 100644 index 00000000..160c4829 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/scalar_draft_kv_operands.rs @@ -0,0 +1,26 @@ +//! The operands of the scalar draft-KV recording, the fallback of the batched producer. +use super::*; +use crate::qwen_forward::moe_weight_cache::RetainedOriginalMtpWeights; +use leleka_cuda_driver::{MtpInt8Snapshot, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy}; + +/// The binding, the dense cache, the retained MTP weights and the prompt transaction with its final row that the +/// scalar draft KV of a finished prompt is checked against and derived from; `last_next` is the prompt's known next +/// token. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ScalarPromptSources<'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) mtp: &'a RetainedOriginalMtpWeights<'ctx>, + pub(in crate::qwen_forward) txn: &'a OriginalPromptTxn<'a, 'ctx>, + pub(in crate::qwen_forward) preview: &'a PromptDeviceFinal, + pub(in crate::qwen_forward) last_next: TokenId, +} + +/// What the scalar draft KV is computed from: the prior ring snapshot, the retained scalar weights, the first prompt +/// row that is still missing and the scalar draft policy. +pub(in crate::qwen_forward) struct ScalarDraftKvRequest<'a, 'ctx> { + pub(in crate::qwen_forward) prior: &'a MtpInt8Snapshot, + pub(in crate::qwen_forward) retained: Rc>, + pub(in crate::qwen_forward) first_needed: usize, + pub(in crate::qwen_forward) policy: &'a OriginalMtpScalarPolicy, +} From 34996e5a4a83a341a433a8e6d9e04c1a61bd0fd6 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:05:09 +0100 Subject: [PATCH 06/42] STRA-338 params e02: prompt executor construction takes ExecutorTarget/ExecutorSizing, MTP draft assembly takes DraftTarget/DraftTargetTables/RtMtpLoad --- .../qwen_forward/executor_original_prompt.rs | 6 ++- .../executor_construction_operands.rs | 18 +++++++ .../impl_originalpromptexecutor.rs | 49 +++++++------------ .../qwen_forward/original_mtp_full_owner.rs | 3 ++ .../original_mtp_full_owner/draft_operands.rs | 25 ++++++++++ .../impl_originalmtpfullowner.rs | 35 +++++-------- .../src/qwen_forward/original_serve_stack.rs | 6 +-- .../impl_originalservestack/open_parts.rs | 33 +++++++------ 8 files changed, 100 insertions(+), 75 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/executor_construction_operands.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/draft_operands.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs index 80220529..5c56604d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs @@ -2,10 +2,9 @@ //! result stays pending until the real MTP forward owner joins publication. //! This is an unselected source port, not a serving qualification. use super::super::original_mtp_full_owner::{ - OriginalMtpFullAssembly, OriginalMtpFullOwner, OriginalMtpLoadError, OriginalMtpRequest, + DraftTarget, DraftTargetTables, OriginalMtpFullAssembly, OriginalMtpFullOwner, OriginalMtpLoadError, RtMtpLoad, }; use super::super::output::OriginalPromptSample; -use super::super::output_native::OriginalNativeOutput; use super::super::prompt_device_rows::{ OriginalDraftKvPending, OriginalPromptDraftOutcome, PromptWeights, QsaLayerDevices, RowsUpload, }; @@ -112,6 +111,9 @@ pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx> { pub last_published: Option<(TargetStepOrigin, Option)>, } +#[path = "executor_original_prompt/executor_construction_operands.rs"] +mod executor_construction_operands; +pub(in crate::qwen_forward) use executor_construction_operands::{ExecutorSizing, ExecutorTarget}; #[path = "executor_original_prompt/prompt_chunk_operands.rs"] mod prompt_chunk_operands; pub(in crate::qwen_forward) use prompt_chunk_operands::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/executor_construction_operands.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/executor_construction_operands.rs new file mode 100644 index 00000000..504121a8 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/executor_construction_operands.rs @@ -0,0 +1,18 @@ +//! The operand groups the construction of `OriginalPromptExecutor` takes. +use super::*; + +/// The target model weights, the target session and the device context a prompt executor is built over. +pub(in crate::qwen_forward) struct ExecutorTarget<'a, 'ctx> { + pub(in crate::qwen_forward) weights: PromptWeights<'a, 'ctx>, + pub(in crate::qwen_forward) session: &'a mut QwenSession<'ctx>, + pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, +} + +/// The sizes of a prompt executor: the prompt chunk capacity, the widest verifier window and whether the GR norm is +/// fused into the injection. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ExecutorSizing { + pub(in crate::qwen_forward) capacity: usize, + pub(in crate::qwen_forward) max_t: usize, + pub(in crate::qwen_forward) fused: bool, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs index 77f8fb50..c3cb6ece 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs @@ -8,34 +8,25 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// Eager model/session owners precede expert prefix planning. The twelve /// resident checkpoints are installed together only after all producers exist. pub(in crate::qwen_forward) fn new( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - session: &mut QwenSession<'ctx>, - context: &'ctx Context<'ctx>, + target: ExecutorTarget<'_, 'ctx>, moe: &MoeWeightCache<'ctx>, embedding: &OriginalPromptEmbedding<'ctx>, - capacity: usize, - max_t: usize, - fused: bool, + sizing: ExecutorSizing, ) -> Result { // Pinned-pack source: the MoE cache already holds and charged the roles. - let retained = moe.retain_original_mtp_weights(binding, context)?; - Self::new_with_mtp_weights(binding, dense, session, context, retained, embedding, capacity, max_t, fused) + let retained = moe.retain_original_mtp_weights(target.weights.binding, target.context)?; + Self::new_with_mtp_weights(target, retained, embedding, sizing) } /// Same construction over any retained MTP role bank (the pinned pack, or /// the Original-literal RT directory bank of `select_rt_mtp`). - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn new_with_mtp_weights( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - session: &mut QwenSession<'ctx>, - context: &'ctx Context<'ctx>, + target: ExecutorTarget<'_, 'ctx>, retained: RetainedOriginalMtpWeights<'ctx>, embedding: &OriginalPromptEmbedding<'ctx>, - capacity: usize, - max_t: usize, - fused: bool, + sizing: ExecutorSizing, ) -> Result { + let ExecutorTarget { weights: PromptWeights { binding, dense }, session, context } = target; + let ExecutorSizing { capacity, max_t, fused } = sizing; Self::check_construction(binding, dense, session, context, (capacity, max_t))?; let mut owner = Self::empty(binding, context, (capacity, max_t, fused)); let result = owner.build_owners(binding, (dense, session), retained, embedding); @@ -203,29 +194,25 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { /// Returns both owners; the draft session is the sole mutator of the /// ring, the executor holds the actor. Any failure releases everything /// built so far through the owners' own closure order. - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn select_rt_mtp( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - session: &mut QwenSession<'ctx>, - context: &'ctx Context<'ctx>, - embedding: &OriginalPromptEmbedding<'ctx>, - output: &OriginalNativeOutput<'ctx>, - rt_directory: &std::path::Path, + target: ExecutorTarget<'_, 'ctx>, + tables: DraftTargetTables<'_, 'ctx>, + load: RtMtpLoad<'_>, capacity: usize, fused: bool, - request: &OriginalMtpRequest, ) -> std::result::Result<(Self, OriginalDraftSession<'ctx>), OriginalMtpLoadError> { + let ExecutorTarget { weights, session, context } = target; + let (binding, request) = (weights.binding, load.request); if !(1..=8).contains(&request.max_t) || request.prompt_capacity != capacity || binding.layer_count() != 48 { return Err(Error::IdentityMismatch.into()); } - let retained = Self::load_rt_retained(binding, context, rt_directory)?; + let retained = Self::load_rt_retained(binding, context, load.directory)?; let (shared, max_t) = (retained.clone(), request.max_t); + let target = ExecutorTarget { weights, session: &mut *session, context }; let mut executor = - Self::new_with_mtp_weights(binding, dense, session, context, shared, embedding, capacity, max_t, fused)?; - let dir = rt_directory; - let assembly = - OriginalMtpFullOwner::assemble_rt(binding, session, context, &retained, embedding, output, request, dir)?; + Self::new_with_mtp_weights(target, shared, tables.embedding, ExecutorSizing { capacity, max_t, fused })?; + let assembly_target = DraftTarget { binding, session: &*session, context }; + let assembly = OriginalMtpFullOwner::assemble_rt(assembly_target, &retained, tables, load)?; let draft = executor.install_full_mtp(binding, session, assembly)?; Ok((executor, draft)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs index 8e607a83..b8e9217e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs @@ -22,6 +22,9 @@ use leleka_cuda_driver::{ }; use std::{path::Path, rc::Rc}; +mod draft_operands; +pub(in crate::qwen_forward) use draft_operands::{DraftTarget, DraftTargetTables, RtMtpLoad}; + /// Everything `MtpDrafter::load(rt_dir, g, ss, max_t, err, window)` receives /// besides geometry (which comes from the binding) and the RT directory. #[derive(Clone, Copy, Debug)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/draft_operands.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/draft_operands.rs new file mode 100644 index 00000000..5ce026bd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/draft_operands.rs @@ -0,0 +1,25 @@ +//! The operand groups the assembly of the full MTP draft owner takes. +use super::*; +use std::path::Path; + +/// The target model and session an MTP draft is attached to, with the device context both live on. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct DraftTarget<'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) session: &'a QwenSession<'ctx>, + pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, +} + +/// The target-side tables the draft layer reads: the prompt embedding and the native output head. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct DraftTargetTables<'a, 'ctx> { + pub(in crate::qwen_forward) embedding: &'a OriginalPromptEmbedding<'ctx>, + pub(in crate::qwen_forward) output: &'a OriginalNativeOutput<'ctx>, +} + +/// What `MtpDrafter::load` receives from an RT directory: the request and the directory it is read from. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct RtMtpLoad<'a> { + pub(in crate::qwen_forward) request: &'a OriginalMtpRequest, + pub(in crate::qwen_forward) directory: &'a Path, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs index 567b5bb5..d99ba09e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs @@ -31,48 +31,37 @@ impl<'ctx> OriginalMtpFullOwner<'ctx> { /// then `RetainedOriginalMtpWeights::from_rt_bank`); `rt_directory` is read /// again here only for the optional `draft_vocab.bin`, exactly where /// `bind` reads it. - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn assemble_rt( - binding: &ModelBinding, - session: &QwenSession<'ctx>, - context: &'ctx Context<'ctx>, + target: DraftTarget<'_, 'ctx>, retained: &RetainedOriginalMtpWeights<'ctx>, - embedding: &OriginalPromptEmbedding<'ctx>, - output: &OriginalNativeOutput<'ctx>, - request: &OriginalMtpRequest, - rt_directory: &Path, + tables: DraftTargetTables<'_, 'ctx>, + load: RtMtpLoad<'_>, ) -> std::result::Result, OriginalMtpLoadError> { - Self::assemble_core(binding, session, context, retained, embedding, output, request, Some(rt_directory)) + Self::assemble_core(target, retained, tables, load.request, Some(load.directory)) } /// Same assembly over the digest-pinned pack held by the MoE cache (no RT /// directory, hence no draft-vocab subset). - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn assemble( - binding: &ModelBinding, - session: &QwenSession<'ctx>, - context: &'ctx Context<'ctx>, + target: DraftTarget<'_, 'ctx>, moe: &MoeWeightCache<'ctx>, - embedding: &OriginalPromptEmbedding<'ctx>, - output: &OriginalNativeOutput<'ctx>, + tables: DraftTargetTables<'_, 'ctx>, request: &OriginalMtpRequest, ) -> std::result::Result, OriginalMtpLoadError> { // Source keeps all MTP roles immutable for the life of cached graphs. - let retained = moe.retain_original_mtp_weights(binding, context)?; - Self::assemble_core(binding, session, context, &retained, embedding, output, request, None) + let retained = moe.retain_original_mtp_weights(target.binding, target.context)?; + Self::assemble_core(target, &retained, tables, request, None) } - #[allow(clippy::too_many_arguments)] pub(super) fn assemble_core( - binding: &ModelBinding, - session: &QwenSession<'ctx>, - context: &'ctx Context<'ctx>, + target: DraftTarget<'_, 'ctx>, retained: &RetainedOriginalMtpWeights<'ctx>, - embedding: &OriginalPromptEmbedding<'ctx>, - output: &OriginalNativeOutput<'ctx>, + tables: DraftTargetTables<'_, 'ctx>, request: &OriginalMtpRequest, rt_directory: Option<&Path>, ) -> std::result::Result, OriginalMtpLoadError> { + let DraftTarget { binding, session, context } = target; + let DraftTargetTables { embedding, output } = tables; Self::admit_core(binding, session, context, request)?; let prepared = Self::prepare_load(binding, context, (retained, output), (request, rt_directory))?; let weights = Self::retained_weights(binding, context, (retained, embedding), &prepared)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index 95d6beed..56a11915 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -22,12 +22,12 @@ use super::{ contract::{Error, Result}, dense_weight_cache::DenseWeightCache, executor::original_prompt::{ - ChunkCaches, ChunkDraft, OriginalPromptExecutor, PromptChunkSource, PromptChunkTarget, - embedding::OriginalPromptEmbedding, + ChunkCaches, ChunkDraft, ExecutorSizing, ExecutorTarget, OriginalPromptExecutor, PromptChunkSource, + PromptChunkTarget, embedding::OriginalPromptEmbedding, }, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache, - original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, + original_mtp_full_owner::{DraftTarget, DraftTargetTables, OriginalMtpFullOwner, OriginalMtpRequest, RtMtpLoad}, original_serve_config::{ ExpertBlobSizes, RopeConstants, expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, }, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs index 92afeeda..02193a52 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs @@ -192,19 +192,18 @@ pub(super) fn open_executor<'a, 'ctx>( let Weights { output, embedding, dense, .. } = weights; let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS); Ok(match &config.rt_directory { - Some(directory) => OriginalPromptExecutor::select_rt_mtp( - binding, - dense, - session, - context, - embedding, - output, - directory, - config.capacity, - true, - &request, - ) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, + Some(directory) => { + let target = ExecutorTarget { weights: PromptWeights::new(binding, dense), session, context }; + let load = RtMtpLoad { request: &request, directory }; + OriginalPromptExecutor::select_rt_mtp( + target, + DraftTargetTables { embedding, output }, + load, + config.capacity, + true, + ) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })? + } None => { open_full_mtp_executor(binding, context, session, weights, (config.capacity, verifier_max_t), &request)? } @@ -222,10 +221,12 @@ fn open_full_mtp_executor<'a, 'ctx>( ) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> { let Weights { output, embedding, dense, moe, .. } = weights; let (capacity, verifier_max_t) = sizes; + let target = ExecutorTarget { weights: PromptWeights::new(binding, dense), session: &mut *session, context }; + let sizing = ExecutorSizing { capacity, max_t: verifier_max_t, fused: true }; let mut executor = - OriginalPromptExecutor::new(binding, dense, session, context, moe, embedding, capacity, verifier_max_t, true) - .map_err(at("OriginalPromptExecutor::new"))?; - let assembly = OriginalMtpFullOwner::assemble(binding, session, context, moe, embedding, output, request) + OriginalPromptExecutor::new(target, moe, embedding, sizing).map_err(at("OriginalPromptExecutor::new"))?; + let draft_target = DraftTarget { binding, session: &*session, context }; + let assembly = OriginalMtpFullOwner::assemble(draft_target, moe, DraftTargetTables { embedding, output }, request) .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; let draft = executor.install_full_mtp(binding, session, assembly).map_err(at("install_full_mtp"))?; Ok((executor, draft)) From eb16795230f8683fd146674d2caaddb1fbfd7e62 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:01 +0100 Subject: [PATCH 07/42] STRA-338 params e04: ephemeral routed triplet loan takes a TripletLoanRequest Files: none --- .../src/qwen_forward/cache_ephemeral_routed.rs | 9 +++++++++ .../impl_drop_for_ephemeralroutedowner.rs | 5 ++--- .../impl_ephemeralroutedowner_2_2.rs | 8 +++----- .../impl_ephemeralroutedowner_3.rs | 5 ++--- .../src/qwen_forward/moe_group_resident_queue.rs | 9 ++++++--- .../src/qwen_forward/moe_mmq_adaptive/gather_fns.rs | 9 ++++++--- .../src/qwen_forward/moe_weight_cache.rs | 2 +- .../moe_weight_cache/impl_moeweightcache_2.rs | 7 +++---- 8 files changed, 32 insertions(+), 22 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs index 482d2f5a..7b3d20eb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs @@ -24,6 +24,15 @@ enum Slot<'ctx> { InUse, } +/// Which completed slot of the ephemeral owner is loaned and which member of the routed source it must equal, +/// under which model binding. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct TripletLoanRequest<'binding> { + pub(in crate::qwen_forward) binding: &'binding ModelBinding, + pub(in crate::qwen_forward) member: usize, + pub(in crate::qwen_forward) slot: usize, +} + pub(in crate::qwen_forward) struct EphemeralRoutedOwner<'ctx> { binding: BindingIdentity, context: &'ctx Context<'ctx>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs index 2f373fb8..430b20b4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs @@ -263,16 +263,15 @@ impl<'ctx> MappedStage<'ctx> { } pub(super) fn with_triplet<'source, 'group, T>( &mut self, - slot: usize, - binding: &ModelBinding, + request: TripletLoanRequest<'_>, source: &mut MoeRoutedSourceScope<'source, 'group>, - member: usize, consume: impl FnOnce( [&DeviceBuffer<'ctx>; 3], [MoeWeightDescriptor; 3], &mut MoeRoutedSourceScope<'source, 'group>, ) -> Result, ) -> Result { + let TripletLoanRequest { binding, member, slot } = request; self.validate(binding, slot)?; let fresh = EphemeralRoutedOwner::keys(binding, source, member)?; let (keys, buffers, scratch) = self.loan_completed(slot, &fresh)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs index d849b3f7..c4783ab9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs @@ -233,10 +233,8 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> { /// buffers are temporary execution owners, never adaptive cache hits. pub(in crate::qwen_forward) fn with_triplet<'source, 'group, T>( &mut self, - slot: usize, - binding: &ModelBinding, + request: TripletLoanRequest<'_>, source: &mut MoeRoutedSourceScope<'source, 'group>, - member: usize, cancel_observed: &Cell, consume: impl FnOnce( [&DeviceBuffer<'ctx>; 3], @@ -245,9 +243,9 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> { ) -> Result, ) -> Result { let result = if let Some(mapped) = &mut self.mapped { - mapped.with_triplet(slot, binding, source, member, consume) + mapped.with_triplet(request, source, consume) } else { - self.with_triplet_inner(slot, binding, source, member, consume) + self.with_triplet_inner(request, source, consume) }; #[cfg(test)] if self.mapped.is_some() && result.is_ok() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs index 9e6f659f..accb5d67 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs @@ -30,16 +30,15 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> { } pub(in super::super) fn with_triplet_inner<'source, 'group, T>( &mut self, - slot: usize, - binding: &ModelBinding, + request: TripletLoanRequest<'_>, source: &mut MoeRoutedSourceScope<'source, 'group>, - member: usize, consume: impl FnOnce( [&DeviceBuffer<'ctx>; 3], [MoeWeightDescriptor; 3], &mut MoeRoutedSourceScope<'source, 'group>, ) -> Result, ) -> Result { + let TripletLoanRequest { binding, member, slot } = request; self.validate_slot(binding, slot)?; let fresh = Self::keys(binding, source, member)?; let (keys, buffers) = self.loan_completed(slot, &fresh)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs index 0973e516..1a2313f5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs @@ -131,9 +131,12 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> { }; let binding = self.group.binding; match ephemeral_slot { - Some(slot) => { - cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) - } + Some(slot) => cache.with_ephemeral_triplet_routed_source( + crate::qwen_forward::moe_weight_cache::TripletLoanRequest { binding, member: 0, slot }, + source, + &cancel_observed, + consume, + ), None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs index 425b1dcd..1bfc54fe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs @@ -61,9 +61,12 @@ impl<'ctx> Walk<'_, '_, 'ctx> { self.after_gather(activation, formats, raw, health, source, &mut observed_cancel, pairs) }; match ephemeral_slot { - Some(slot) => { - cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) - } + Some(slot) => cache.with_ephemeral_triplet_routed_source( + crate::qwen_forward::moe_weight_cache::TripletLoanRequest { binding, member: 0, slot }, + source, + &cancel_observed, + consume, + ), None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index 2a25b9a8..47a1e518 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -42,7 +42,7 @@ pub(crate) use cache_strata_adaptive::AdaptiveWitness; #[path = "cache_original_verify.rs"] mod cache_original_verify; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(in crate::qwen_forward) use cache_ephemeral_routed::observe_cancel; +pub(in crate::qwen_forward) use cache_ephemeral_routed::{TripletLoanRequest, observe_cancel}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use cache_original_verify::SharedKeys; use std::collections::HashMap; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs index 595a614c..730d6782 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs @@ -94,10 +94,8 @@ impl<'ctx> MoeWeightCache<'ctx> { } pub(in super::super) fn with_ephemeral_triplet_routed_source<'source, 'group, T>( &self, - binding: &ModelBinding, + request: cache_ephemeral_routed::TripletLoanRequest<'_>, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, - member: usize, - slot: usize, cancel_observed: &std::cell::Cell, consume: impl FnOnce( [&DeviceBuffer<'ctx>; 3], @@ -105,6 +103,7 @@ impl<'ctx> MoeWeightCache<'ctx> { &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, ) -> Result, ) -> Result { + let cache_ephemeral_routed::TripletLoanRequest { binding, member, .. } = request; self.validate(binding, self.context)?; source.validate_binding(binding).map_err(binding_error)?; let keys = [ @@ -115,7 +114,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed }; let owner = self.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?; let mut owner = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - owner.with_triplet(slot, binding, source, member, cancel_observed, |raw, actual_keys, source| { + owner.with_triplet(request, source, cancel_observed, |raw, actual_keys, source| { if actual_keys != keys { return Err(Error::IdentityMismatch); } From 1abe60e7b4513bf0bb218f6b0eed799d25cc24c0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:02 +0100 Subject: [PATCH 08/42] STRA-338 params e04: GR read takes a GrReadSource, handoff rounds a HandoffBaseline Files: none --- .../src/qwen_forward/gr/impl_grstage.rs | 36 +++++++++++-------- .../gr/output_workspace_gpu/stage_fn.rs | 16 ++++++--- 2 files changed, 33 insertions(+), 19 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs index dbe49ba0..a373da11 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs @@ -4,6 +4,13 @@ use super::super::dense_weight_cache::GrResident; use super::*; +/// What one GR read consumes: the residual role being read, whose token/layer it belongs to and its streams. +pub(super) struct GrReadSource<'streams> { + role: GrRole, + identity: TokenLayer, + streams: &'streams [f32], +} + impl GrStage { pub(in super::super) fn apply<'cache, 'ctx>( binding: &ModelBinding, @@ -22,7 +29,8 @@ impl GrStage { return Err(Error::IdentityMismatch); } let identity = TokenLayer::new(input.token(), input.position(), layer); - Self::read(binding, GrRole::Attention(layer.get()), identity, input.streams().values(), txn, cache) + let source = GrReadSource { role: GrRole::Attention(layer.get()), identity, streams: input.streams().values() }; + Self::read(binding, source, txn, cache) } pub(in super::super) fn read_ffn<'cache, 'ctx>( @@ -34,7 +42,9 @@ impl GrStage { ) -> Result> { residual.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; residual.identity.validate(txn.token(), txn.position(), layer)?; - Self::read(binding, GrRole::Ffn(layer.get()), residual.identity, residual.streams(), txn, cache) + let source = + GrReadSource { role: GrRole::Ffn(layer.get()), identity: residual.identity, streams: residual.streams() }; + Self::read(binding, source, txn, cache) } pub(in super::super) fn read_attention<'cache, 'ctx>( @@ -54,14 +64,12 @@ impl GrStage { residual.validate_origin(&binding.identity(), GrRole::Ffn(previous))?; let previous_layer = LayerId::new(u64::from(previous), Dimension::new(u64::from(binding.layer_count()))?)?; residual.identity.validate(txn.token(), txn.position(), previous_layer)?; - Self::read( - binding, - GrRole::Attention(layer.get()), - TokenLayer::new(txn.token(), txn.position(), layer), - residual.streams(), - txn, - cache, - ) + let source = GrReadSource { + role: GrRole::Attention(layer.get()), + identity: TokenLayer::new(txn.token(), txn.position(), layer), + streams: residual.streams(), + }; + Self::read(binding, source, txn, cache) } pub(in super::super) fn read_attention_after_ple<'cache, 'ctx>( @@ -78,17 +86,17 @@ impl GrStage { } ple.validate_origin(&binding.identity())?; ple.identity().validate(txn.token(), txn.position(), layer)?; - Self::read(binding, GrRole::Attention(1), ple.identity(), ple.streams(), txn, cache) + let source = GrReadSource { role: GrRole::Attention(1), identity: ple.identity(), streams: ple.streams() }; + Self::read(binding, source, txn, cache) } pub(super) fn read<'cache, 'ctx>( binding: &ModelBinding, - role: GrRole, - identity: TokenLayer, - streams: &[f32], + source: GrReadSource<'_>, txn: &mut QwenStepTxn, cache: Option<&'cache DenseWeightCache<'ctx>>, ) -> Result> { + let GrReadSource { role, identity, streams } = source; let context = Self::admit_read(binding, identity, streams, txn)?; let resident = cache.map(|c| c.gr(binding, role)).transpose()?; let weights = resolve_gr_weights(binding, role, resident)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/stage_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/stage_fn.rs index 82ebc38f..215f17a5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/stage_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/stage_fn.rs @@ -18,6 +18,13 @@ pub(super) struct Stage<'c> { pub(super) failed: &'c Rc>, } +// The expectations every handoff round is compared with: the weights and the allocation before the proof. +#[derive(Clone, Copy)] +struct HandoffBaseline<'m, 'c> { + weights: Weights<'m, 'c>, + allocated_bytes_before: usize, +} + impl<'c> Stage<'c> { fn weights<'m>(matrices: &'m [DeviceBuffer<'c>]) -> Result> { matrices.try_into().map_err(|_| Error::InvalidDimension) @@ -312,7 +319,7 @@ impl<'c> Stage<'c> { let (expected, block) = self.refusal_phase(&mut lease, matrices, before, tally)?; let weights = Self::weights(matrices)?; self.lease_refusals(&mut lease, weights, (&expected, &block), tally)?; - self.handoff_rounds(cell, &mut lease, weights, before, tally)?; + self.handoff_rounds(cell, &mut lease, HandoffBaseline { weights, allocated_bytes_before: before }, tally)?; self.replace_refusals(&mut lease, tally)?; // Abort exposes no readiness capability. Next actual call fully // overwrites the failed candidate and all FFN read outputs. @@ -331,13 +338,12 @@ impl<'c> Stage<'c> { &self, cell: &RefCell>, lease: &mut GrScratch<'c>, - weights: Weights<'_, 'c>, - before: usize, + baseline: HandoffBaseline<'_, 'c>, tally: &mut Tally, ) -> Result<()> { for pattern in [0, 1, 1, 2] { - self.handoff_check(lease, weights, pattern, tally)?; - if self.context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() { + self.handoff_check(lease, baseline.weights, pattern, tally)?; + if self.context.allocated_bytes() != baseline.allocated_bytes_before || cell.try_borrow_mut().is_ok() { tally.differences += 1; } tally.guards += 1; From dc052ba5c2f40550c9d63984a77276073277563a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:02 +0100 Subject: [PATCH 09/42] STRA-338 params e04: PLE input stage groups tokens, bound weights, resident entry and step rows Files: none --- .../forward_input.rs | 5 ++- .../src/qwen_forward/input.rs | 1 + .../src/qwen_forward/input/impl_inputstage.rs | 11 +++++- .../qwen_forward/input/impl_inputstage_2.rs | 37 ++++++++++++++----- .../src/qwen_forward/input/ple_cuda_fn.rs | 18 ++++++--- 5 files changed, 55 insertions(+), 17 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs index f4eaa39f..96b48aab 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor/forward_input.rs @@ -43,7 +43,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { first_predecessors = Some(step.input_predecessors()?); } match kar.as_deref() { - Some(cache) => InputStage::consume_kar_deferred(binding, cache, token, pos, step, &mut staged), + Some(cache) => { + let input = crate::qwen_forward::input::PositionedToken { token, position: pos }; + InputStage::consume_kar_deferred(binding, cache, input, step, &mut staged) + } None => Err(Error::IdentityMismatch), } })?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input.rs index 0aaa08f9..9639619a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input.rs @@ -221,6 +221,7 @@ mod ple_tests { mod impl_inputstage; mod impl_residualstreams; +pub(super) use impl_inputstage::PositionedToken; #[allow(unused_imports)] use impl_inputstage::gather_ple; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs index 8dccda6f..b92a8756 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs @@ -3,6 +3,13 @@ #[allow(unused_imports)] use super::*; +/// A prompt token with the position it occupies in the transaction. +#[derive(Clone, Copy)] +pub(in super::super) struct PositionedToken { + pub(in super::super) token: TokenId, + pub(in super::super) position: Position, +} + impl InputStage { pub(in super::super) fn consume( binding: &ModelBinding, @@ -48,11 +55,11 @@ impl InputStage { pub(in super::super) fn consume_kar_deferred( binding: &ModelBinding, cache: &kar_cache::KarPleCache<'_>, - token: TokenId, - pos: Position, + input: PositionedToken, txn: &mut QwenStepTxn, staged: &mut StagedInput, ) -> Result { + let PositionedToken { token, position: pos } = input; let (_, rows) = admit_kar_input(binding, cache, token, pos, txn)?; let unique = match staged.unique.get(&token.get()) { Some(&u) => u, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs index 26da65ad..9cf834e2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs @@ -118,6 +118,25 @@ fn micro_entry<'c>( } Ok(entry) } +/// The PLE weights of one binding: the weights are only valid for the binding they were read from. +#[derive(Clone, Copy)] +struct BoundPleWeights<'a> { + binding: &'a ModelBinding, + weights: &'a Rc, +} +/// The resident PLE entry of a dense weight cache, with the cache that retains it. +#[derive(Clone, Copy)] +struct ResidentPle<'a, 'ctx> { + cache: &'a DenseWeightCache<'ctx>, + entry: &'a PleResident, +} +/// The host rows one PLE step consumes: the token embedding, the residual streams and the conv history. +#[derive(Clone, Copy)] +struct PleStepRows<'a> { + embedding: &'a [f32], + streams: &'a [f32], + history: &'a [f32], +} fn ple_candidate( context: &Context<'_>, (binding, weights): (&ModelBinding, &Rc), @@ -126,7 +145,9 @@ fn ple_candidate( identity: TokenLayer, ) -> Result { if let Some((cache, entry)) = cached { - ple_cuda_cached(context, binding, weights, entry, cache, embedding, streams, history, identity) + let bound = BoundPleWeights { binding, weights }; + let resident = ResidentPle { cache, entry }; + ple_cuda_cached(context, bound, resident, PleStepRows { embedding, streams, history }, identity) } else { ple_cuda(context, (binding, weights), (embedding, streams, history), None) } @@ -168,18 +189,16 @@ fn resolve_ple_weights<'c>( } Ok((resident, weights)) } -#[allow(clippy::too_many_arguments)] pub(super) fn ple_cuda_cached( context: &Context<'_>, - binding: &ModelBinding, - weights: &Rc, - entry: &PleResident, - cache: &DenseWeightCache<'_>, - embedding: &[f32], - streams: &[f32], - history: &[f32], + bound: BoundPleWeights<'_>, + resident: ResidentPle<'_, '_>, + rows: PleStepRows<'_>, identity: TokenLayer, ) -> Result { + let BoundPleWeights { binding, weights } = bound; + let ResidentPle { cache, entry } = resident; + let PleStepRows { embedding, streams, history } = rows; check_cached_ple(cache, context, (binding, weights, entry), identity)?; let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs index 670aea3e..d1b35291 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs @@ -31,8 +31,10 @@ fn project_key_value( resident: Option<(&DenseWeightCache<'_>, &PleResident)>, ) -> Result<(Box<[f32]>, Box<[f32]>)> { let emb = ple_upload_f32(context, embedding)?; - let key_values = ple_project(context, binding, weights, PleMatrixRole::Key, &emb, resident)?; - let value_values = ple_project(context, binding, weights, PleMatrixRole::Value, &emb, resident)?; + let key = PleMatrixSelection { binding, weights, role: PleMatrixRole::Key }; + let key_values = ple_project(context, key, &emb, resident)?; + let value = PleMatrixSelection { binding, weights, role: PleMatrixRole::Value }; + let value_values = ple_project(context, value, &emb, resident)?; emb.release().map_err(ple_driver_error)?; Ok((key_values, value_values)) } @@ -175,14 +177,20 @@ impl<'c> PleWork<'c> { Ok(()) } } +/// Which PLE projection matrix is read: its role (key or value), the binding it comes from and that binding's weights. +#[derive(Clone, Copy)] +pub(super) struct PleMatrixSelection<'a> { + binding: &'a ModelBinding, + weights: &'a PleWeights, + role: PleMatrixRole, +} pub(super) fn ple_project( context: &Context<'_>, - binding: &ModelBinding, - weights: &PleWeights, - role: PleMatrixRole, + matrix: PleMatrixSelection<'_>, embedding: &DeviceBuffer<'_>, resident: Option<(&DenseWeightCache<'_>, &PleResident)>, ) -> Result> { + let PleMatrixSelection { binding, weights, role } = matrix; if role == PleMatrixRole::Key && let Some((cache, entry)) = resident { From 4b99d52b478d3185068e69452091f72b52b2c9e8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:28 +0100 Subject: [PATCH 10/42] STRA-338 params r02: scalar prefill chain (kernel, finite, project, record, groups) Module::launch takes the shared LaunchShape; OriginalMtpScalarPrefill::kernel takes it too, finite and q8_guard lose the unused group argument, project takes ProjectionBuffers. record/record_impl/record_scalar/record_groups take RecordRun, PrefillRows and the new ScalarDraftKvSources; validate_scalar is split into validate_owners and validate_prompt; the group loop (run_groups, stage_group, submit_group, enqueue_group, complete) passes ScalarGroupSources, GroupSpan, GroupSubmission and PagePublication. OriginalMtpDrafter/OriginalMtpActor::record_scalar_prefill pass the same DTOs. Files: crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_parts.rs crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_rows.rs crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs --- crates/cuda-driver/src/mtp_dense_kv.rs | 2 +- .../impl_originalmtpdrafter_3.rs | 16 +- .../impl_originalmtpforwardprogram.rs | 6 +- .../prefix_parts.rs | 77 +++++---- .../prefix_rows.rs | 27 +--- .../impl_originalmtpdraftprogram.rs | 4 +- crates/cuda-driver/src/mtp_original_int8.rs | 1 + .../cuda-driver/src/mtp_original_prefill.rs | 2 +- .../src/mtp_original_scalar_ffi.rs | 9 +- .../src/mtp_original_scalar_graph.rs | 35 ++-- .../src/mtp_original_scalar_prefill.rs | 17 +- .../impl_originalmtpscalarprefill.rs | 5 +- .../impl_originalmtpscalarprefill_2_2.rs | 41 ++--- .../impl_originalmtpscalarprefill_3.rs | 39 ++--- .../impl_originalmtpscalarprefill_4.rs | 52 +++--- .../impl_originalmtpscalarprefill_6.rs | 35 +++- .../impl_originalmtpscalarprefill_7.rs | 153 ++++++++---------- .../impl_originalmtpscalarprefill_8.rs | 87 +++++----- .../src/mtp_original_scalar_short_gpu.rs | 36 ++--- .../impl_originalmtpactor_2.rs | 26 +-- crates/cuda-driver/src/root_exports.rs | 1 + .../original_mtp_scalar_prefill.rs | 15 +- 22 files changed, 334 insertions(+), 352 deletions(-) diff --git a/crates/cuda-driver/src/mtp_dense_kv.rs b/crates/cuda-driver/src/mtp_dense_kv.rs index 4b147f2d..4be9b0c3 100644 --- a/crates/cuda-driver/src/mtp_dense_kv.rs +++ b/crates/cuda-driver/src/mtp_dense_kv.rs @@ -190,5 +190,5 @@ pub use original_int8::{ CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, - OriginalMtpStepOutput, + OriginalMtpStepOutput, ScalarDraftKvSources, }; diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs index 1097fa12..8b3b2f41 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs @@ -210,26 +210,18 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { /// `original_mtp_scalar_prefill` owns another scratch bank and is refused with InvalidQwenShape. `Drafter::new` /// moved the owner's stream into the drafter, so it is lent back for the call (the Original's `mtp.prefill` runs on /// the drafter's `cs_`). - #[allow(clippy::too_many_arguments)] pub fn record_scalar_prefill<'arena, 'loan>( &mut self, residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut crate::NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, + rows: PrefillRows<'_>, + sources: ScalarDraftKvSources<'_, 'ctx>, ) -> Result { self.validate_context(self.context)?; let stream = self.stream.take().ok_or(Error::ContextPoisoned)?; let scalar = self.scalar.as_mut().ok_or(Error::ContextPoisoned)?; scalar.stream = Some(stream); - let result = - scalar.record(residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled); + let result = scalar.record(residual, run, rows, sources); self.stream = scalar.stream.take(); if self.stream.is_none() || result.is_err() && self.context.is_poisoned() { self.failed = true; diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs index 8c61349e..b5a4add6 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs @@ -32,7 +32,7 @@ impl OriginalMtpForwardProgram<'_> { if let Some(stage) = &mut self.coupled_stage { self.tail.modules[20].launch(1, [1, 1, 1], [256, 1, 1], 0, stream, stage)?; } - self.owners.modules[0].launch(11, [1, 1, 1], [256, 1, 1], 0, stream, &mut self.args.reset)?; + self.owners.modules[0].launch(11, LaunchShape::new([1, 1, 1], [256, 1, 1], 0), stream, &mut self.args.reset)?; for (i, command) in self.prefix.iter_mut().enumerate() { if i == 1 && let Some(e) = &mut self.native_embedding @@ -46,9 +46,7 @@ impl OriginalMtpForwardProgram<'_> { fn launch_scalar(modules: &[Rc; 6], stream: usize, command: &mut ScalarCommand) -> Result<()> { match command { - ScalarCommand::Kernel { asset, index, grid, block, shared, args } => { - modules[*asset].launch(*index, *grid, *block, *shared, stream, args) - } + ScalarCommand::Kernel { asset, index, shape, args } => modules[*asset].launch(*index, *shape, stream, args), ScalarCommand::Copy { .. } => Err(Error::InvalidQwenShape), } } diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_parts.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_parts.rs index fa3d593b..41b1cccb 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_parts.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_parts.rs @@ -129,9 +129,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { &mut cmds, 0, 11, - [1, 1, 1], - [256, 1, 1], - 0, + LaunchShape::new([1, 1, 1], [256, 1, 1], 0), vec![Arg::U64(scalar.flag(0, 0)?), Arg::I32(16)], )?; Ok(cmds) @@ -268,9 +266,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { cmds, 3, 0, - [rows as u32, 1, 1], - [1024, 1, 1], - 0, + LaunchShape::new([rows as u32, 1, 1], [1024, 1, 1], 0), vec![Arg::U64(input), Arg::U64(weight), Arg::U64(out), Arg::I32(width), Arg::F32(1e-6)], ) } @@ -283,15 +279,19 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { wh: &[BufferHandle; 11], t: usize, ) -> Result { - let group = 0usize; - scalar.finite(cmds, a.emb, t * 2560, group, 0)?; + scalar.finite(cmds, a.emb, t * 2560, 0)?; Self::prefix_rms_norm(cmds, t, (a.emb, wh[0].qwen_address(), a.en), 2560)?; - scalar.finite(cmds, a.en, t * 2560, group, 1)?; + scalar.finite(cmds, a.en, t * 2560, 1)?; let q = scalar.address(15, 8 * 80 * 36)?; OriginalMtpScalarPrefill::quant(cmds, a.en, q, t)?; - scalar.q8_guard(cmds, q, t, group, 2)?; - OriginalMtpScalarPrefill::project(cmds, wh[1].qwen_address(), q, a.e2, t, 2560)?; - scalar.finite(cmds, a.e2, t * 2560, group, 2)?; + scalar.q8_guard(cmds, q, t, 2)?; + OriginalMtpScalarPrefill::project( + cmds, + ProjectionBuffers { weight: wh[1].qwen_address(), quantised: q, output: a.e2 }, + t, + 2560, + )?; + scalar.finite(cmds, a.e2, t * 2560, 2)?; Ok(q) } @@ -303,16 +303,20 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { wh: &[BufferHandle; 11], (q, t): (u64, usize), ) -> Result<()> { - let group = 0usize; Self::prefix_rms_norm(cmds, t, (a.rin, wh[2].qwen_address(), a.hn), 10240)?; - scalar.finite(cmds, a.hn, t * 10240, group, 3)?; + scalar.finite(cmds, a.hn, t * 10240, 3)?; for hc in (0..t * 4).step_by(8) { let cols = 8.min(t * 4 - hc); OriginalMtpScalarPrefill::quant(cmds, a.hn + (hc * 10240) as u64, q, cols)?; - scalar.q8_guard(cmds, q, cols, group, 4)?; - OriginalMtpScalarPrefill::project(cmds, wh[3].qwen_address(), q, a.h2 + (hc * 10240) as u64, cols, 2560)?; + scalar.q8_guard(cmds, q, cols, 4)?; + OriginalMtpScalarPrefill::project( + cmds, + ProjectionBuffers { weight: wh[3].qwen_address(), quantised: q, output: a.h2 + (hc * 10240) as u64 }, + cols, + 2560, + )?; } - scalar.finite(cmds, a.h2, t * 10240, group, 4)?; + scalar.finite(cmds, a.h2, t * 10240, 4)?; Ok(()) } @@ -324,17 +328,14 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { wh: &[BufferHandle; 11], (t, policy): (usize, &OriginalMtpScalarPolicy), ) -> Result<()> { - let group = 0usize; OriginalMtpScalarPrefill::kernel( cmds, 0, 4, - [40, t as u32, 1], - [256, 1, 1], - 0, + LaunchShape::new([40, t as u32, 1], [256, 1, 1], 0), vec![Arg::U64(a.h2), Arg::U64(a.e2), Arg::U64(a.r), Arg::I64(2560), Arg::I32(4)], )?; - scalar.finite(cmds, a.r, t * 10240, group, 5)?; + scalar.finite(cmds, a.r, t * 10240, 5)?; scalar.gr(cmds, t, wh, policy)?; Self::prefix_gr_guards(scalar, cmds, a.mixed, t) } @@ -346,12 +347,11 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { mixed: u64, t: usize, ) -> Result<()> { - let group = 0usize; - scalar.finite(cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?; - scalar.finite(cmds, scalar.address(7, t * 40960)?, t * 10240, group, 6)?; - scalar.finite(cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?; - scalar.finite(cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?; - scalar.finite(cmds, mixed, t * 2560, group, 8) + scalar.finite(cmds, scalar.address(9, t * 16)?, t * 4, 6)?; + scalar.finite(cmds, scalar.address(7, t * 40960)?, t * 10240, 6)?; + scalar.finite(cmds, scalar.address(8, t * 1280)?, t * 320, 7)?; + scalar.finite(cmds, scalar.address(10, t * 16)?, t * 4, 7)?; + scalar.finite(cmds, mixed, t * 2560, 8) } /// K and V projections of the mixed state into the current KV cells; returns `(k, v)` addresses. @@ -362,14 +362,23 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { a: &PrefixAddrs, (wh, q, t): (&[BufferHandle; 11], u64, usize), ) -> Result<(u64, u64)> { - let group = 0usize; OriginalMtpScalarPrefill::quant(cmds, a.mixed, q, t)?; - scalar.q8_guard(cmds, q, t, group, 9)?; + scalar.q8_guard(cmds, q, t, 9)?; let (kc, vc) = scalar.current_kv(ring)?; - OriginalMtpScalarPrefill::project(cmds, wh[7].qwen_address(), q, kc, t, 512)?; - scalar.finite(cmds, kc, t * 512, group, 10)?; - OriginalMtpScalarPrefill::project(cmds, wh[8].qwen_address(), q, vc, t, 512)?; - scalar.finite(cmds, vc, t * 512, group, 11)?; + OriginalMtpScalarPrefill::project( + cmds, + ProjectionBuffers { weight: wh[7].qwen_address(), quantised: q, output: kc }, + t, + 512, + )?; + scalar.finite(cmds, kc, t * 512, 10)?; + OriginalMtpScalarPrefill::project( + cmds, + ProjectionBuffers { weight: wh[8].qwen_address(), quantised: q, output: vc }, + t, + 512, + )?; + scalar.finite(cmds, vc, t * 512, 11)?; Ok((kc, vc)) } } diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_rows.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_rows.rs index 86352d45..1a6c5a76 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_rows.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/prefix_rows.rs @@ -34,9 +34,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { cmds, 1, 0, - [10, t as u32, 1], - [32, 1, 1], - 0, + LaunchShape::new([10, t as u32, 1], [32, 1, 1], 0), vec![ Arg::I32(kind), Arg::U64(table), @@ -59,9 +57,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { cmds, 0, 5, - [10, t as u32, 1], - [256, 1, 1], - 0, + LaunchShape::new([10, t as u32, 1], [256, 1, 1], 0), vec![ Arg::U64(table), Arg::U64(table + codes as u64), @@ -101,20 +97,17 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { a: &PrefixAddrs, (kv, wh, kc, vc, row): (&DraftKvPolicy, &[BufferHandle; 11], u64, u64, usize), ) -> Result<()> { - let group = 0usize; let k = kc + (row * 2048) as u64; OriginalMtpScalarPrefill::kernel( cmds, 2, 9, - [2, 1, 1], - [256, 1, 1], - 0, + LaunchShape::new([2, 1, 1], [256, 1, 1], 0), vec![Arg::U64(k), Arg::U64(wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)], )?; - scalar.finite(cmds, k, 512, group, 12)?; + scalar.finite(cmds, k, 512, 12)?; Self::prefix_row_rope(cmds, kv, k, a.pos + (row * 96) as u64)?; - scalar.finite(cmds, k, 512, group, 13)?; + scalar.finite(cmds, k, 512, 13)?; Self::prefix_step_append(cmds, ring, (a.step + (row * 16) as u64, k, vc + (row * 2048) as u64)) } @@ -131,7 +124,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { } values.extend([Arg::U64(step), Arg::U64(k), Arg::U64(v), Arg::I32(2), Arg::I32(256), Arg::I32(4)]); values.extend(host.map(Arg::U64)); - OriginalMtpScalarPrefill::kernel(cmds, 5, 0, [2, 4, 2], [64, 1, 1], 0, values) + OriginalMtpScalarPrefill::kernel(cmds, 5, 0, LaunchShape::new([2, 4, 2], [64, 1, 1], 0), values) } fn prefix_row_rope(cmds: &mut Vec, kv: &DraftKvPolicy, k: u64, position: u64) -> Result<()> { @@ -139,9 +132,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { cmds, 3, 1, - [4, 2, 1], - [32, 1, 1], - 0, + LaunchShape::new([4, 2, 1], [32, 1, 1], 0), vec![ Arg::U64(k), Arg::U64(k), @@ -172,9 +163,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { cmds, 3, 3, - [64, 1, 1], - [256, 1, 1], - 0, + LaunchShape::new([64, 1, 1], [256, 1, 1], 0), vec![ Arg::U64(ring.address(2)?), Arg::U64(ring.address(3)?), diff --git a/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs b/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs index a3ead7a6..0a10fa7b 100644 --- a/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs +++ b/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs @@ -67,8 +67,8 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx> { e.capture(c)?; } match cmd { - ScalarCommand::Kernel { asset, index, grid, block, shared, args } => { - self.program.owners.modules[*asset].launch(*index, *grid, *block, *shared, stream, args)? + ScalarCommand::Kernel { asset, index, shape, args } => { + self.program.owners.modules[*asset].launch(*index, *shape, stream, args)? } ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape), } diff --git a/crates/cuda-driver/src/mtp_original_int8.rs b/crates/cuda-driver/src/mtp_original_int8.rs index bce76328..5ff59b4d 100644 --- a/crates/cuda-driver/src/mtp_original_int8.rs +++ b/crates/cuda-driver/src/mtp_original_int8.rs @@ -70,6 +70,7 @@ pub use prefill::{ OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, PrefillRows, RecordRun, + ScalarDraftKvSources, }; struct Page { runs: [Box<[u8]>; 4], diff --git a/crates/cuda-driver/src/mtp_original_prefill.rs b/crates/cuda-driver/src/mtp_original_prefill.rs index 72eec0d8..9e40671c 100644 --- a/crates/cuda-driver/src/mtp_original_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill.rs @@ -162,7 +162,7 @@ pub use scalar::{ CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, - OriginalMtpStepOutput, + OriginalMtpStepOutput, ScalarDraftKvSources, }; #[path = "mtp_original_prefill/impl_completeddraftkv.rs"] diff --git a/crates/cuda-driver/src/mtp_original_scalar_ffi.rs b/crates/cuda-driver/src/mtp_original_scalar_ffi.rs index 5771b7e4..b4c6ac95 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_ffi.rs @@ -1,5 +1,6 @@ //! Private fixed-symbol ABI for literal Original MTP ring/tail assets. //! No arbitrary entry, public pointer, or stream ownership escapes this module. +use crate::mtp_dense_kv::original_int8::abi::LaunchShape; use crate::{Error, Result, combine}; use std::ffi::{CStr, c_void}; pub(crate) enum Arg { @@ -48,6 +49,7 @@ impl Arguments { #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; + use crate::mtp_dense_kv::original_int8::abi::LaunchDims; type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; type FunctionAttr = unsafe extern "C" fn(*mut c_void, i32, i32) -> i32; @@ -263,12 +265,11 @@ mod enabled { pub(crate) fn launch( &self, index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, + shape: LaunchShape, stream: usize, args: &mut Arguments, ) -> Result<()> { + let LaunchShape { dims: LaunchDims { grid, block }, shared } = shape; let geometry = Geometry { grid, block, shared, stream }; geometry.validate()?; let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; @@ -368,7 +369,7 @@ impl Module { pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: LaunchShape, _: usize, _: &mut Arguments) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> { diff --git a/crates/cuda-driver/src/mtp_original_scalar_graph.rs b/crates/cuda-driver/src/mtp_original_scalar_graph.rs index 5c681c53..a24c1944 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_graph.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_graph.rs @@ -1,6 +1,17 @@ //! Literal cached MtpDrafter prefill graph scheduling. All kernel ABI arguments //! and real physical input/scratch/weight owners survive capture and replay. use super::*; + +/// One group of prompt rows handed to the stream: its rows and cells, and the kernel and copy commands that run for it. +pub(super) struct GroupSubmission<'a> { + pub(super) index: usize, + pub(super) tokens: &'a [i32], + pub(super) first_cell: usize, + pub(super) has_mapped_inputs: bool, + pub(super) kernels: &'a mut Vec, + pub(super) copies: &'a mut [ScalarCommand], +} + impl<'ctx> OriginalMtpScalarPrefill<'ctx> { pub(super) fn upload_records(&mut self, staging: &mut Vec<(BufferHandle, Vec)>) -> Result<()> { self.pending_host.try_reserve(staging.len() + 1).map_err(|_| Error::HostAllocation)?; @@ -53,33 +64,27 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { } Ok(()) } - #[allow(clippy::too_many_arguments)] pub(super) fn enqueue_group( &mut self, - t: usize, - group: usize, - mapped: bool, + submission: &mut GroupSubmission<'_>, weights: &Rc>, ring: &MtpOriginalInt8<'ctx>, - commands: &mut Vec, - copies: &mut [ScalarCommand], - tokens: &[i32], - cell0: usize, ) -> Result<()> { - let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !mapped }; + let mapped = submission.has_mapped_inputs; + let key = OriginalGraphKey::MtpPrefill { rows: submission.tokens.len() as u8, device_inputs: !mapped }; let found = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_some(); if !found { - self.record_new_graph(key, weights, ring, commands)?; + self.record_new_graph(key, weights, ring, submission.kernels)?; } if mapped { - self.write_mapped(tokens, cell0)?; + self.write_mapped(submission.tokens, submission.first_cell)?; } self.has_pending = true; // These are the four literal Original copies before each device-input graph; // mapped mode keeps only the actual Rin copy outside the captured copy kernels. let module = Rc::clone(self.modules[0].as_ref().ok_or(Error::ContextPoisoned)?); - self.enqueue_copies(&module, copies)?; - self.replay_group(key, group, &module) + self.enqueue_copies(&module, submission.copies)?; + self.replay_group(key, submission.index, &module) } fn record_new_graph( &mut self, @@ -107,8 +112,8 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { let handle = capture.stream_handle(r.context)?; for command in &mut r.commands { match command { - ScalarCommand::Kernel { asset, index, grid, block, shared, args } => { - r.modules[*asset].launch(*index, *grid, *block, *shared, handle, args)? + ScalarCommand::Kernel { asset, index, shape, args } => { + r.modules[*asset].launch(*index, *shape, handle, args)? } ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape), } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs index f10f8c27..022bfeea 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs @@ -6,6 +6,7 @@ use super::*; #[path = "mtp_original_scalar_ffi.rs"] mod scalar_abi; use crate::{OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, OriginalStreamKind}; +use abi::LaunchShape; use scalar_abi::{Arg, Arguments, Module}; #[path = "mtp_original_scalar_weights.rs"] mod retained_weights; @@ -78,9 +79,23 @@ pub use full_forward::{ OriginalMtpStepOutput, }; enum ScalarCommand { - Kernel { asset: usize, index: usize, grid: [u32; 3], block: [u32; 3], shared: u32, args: Arguments }, + Kernel { asset: usize, index: usize, shape: LaunchShape, args: Arguments }, Copy { dst: u64, src: u64, bytes: usize }, } +/// The device addresses of one Q8 projection: the weight, the quantised activations and the output. +#[derive(Clone, Copy)] +struct ProjectionBuffers { + weight: u64, + quantised: u64, + output: u64, +} +/// What the scalar draft K/V of a prompt is computed from: the ring snapshot it continues, the retained weights and +/// the policy (the scalar counterpart of `DraftKvSources`). +pub struct ScalarDraftKvSources<'a, 'ctx> { + pub prior: &'a MtpInt8Snapshot, + pub retained: Rc>, + pub policy: &'a OriginalMtpScalarPolicy, +} /// Real affine scalar producer. Cached Original capture must retain this owner /// AND genuine model-lifetime whole weights (see the explicit graph handoff). pub struct OriginalMtpScalarPrefill<'ctx> { diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs index 147c1e36..bd8fbd98 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs @@ -20,4 +20,7 @@ mod impl_originalmtpscalarprefill_7; #[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs"] mod impl_originalmtpscalarprefill_8; #[allow(unused_imports)] -use impl_originalmtpscalarprefill_6::{Cap, ExternalOwners, GrRows, GroupIo, ScalarCall, ScalarStaged}; +use impl_originalmtpscalarprefill_6::{ + Cap, ExternalOwners, GrRows, GroupIo, GroupSpan, PagePublication, ScalarCall, ScalarGroupSources, ScalarOperands, + ScalarStaged, +}; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs index 9382b772..9ec1b515 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs @@ -61,35 +61,24 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? .qwen_address()) } - #[allow(clippy::too_many_arguments)] + /// Appends the launch of kernel `index` of module `asset` with `args` to the command list. pub(in super::super) fn kernel( cmds: &mut Vec, asset: usize, index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, + shape: LaunchShape, args: Vec, ) -> Result<()> { cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(ScalarCommand::Kernel { asset, index, grid, block, shared, args: Arguments::new(args)? }); + cmds.push(ScalarCommand::Kernel { asset, index, shape, args: Arguments::new(args)? }); Ok(()) } - pub(in super::super) fn finite( - &self, - cmds: &mut Vec, - data: u64, - n: usize, - _g: usize, - s: usize, - ) -> Result<()> { + pub(in super::super) fn finite(&self, cmds: &mut Vec, data: u64, n: usize, s: usize) -> Result<()> { Self::kernel( cmds, 2, 11, - [n.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, + LaunchShape::new([n.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0), vec![Arg::U64(data), Arg::I32(n as i32), Arg::U64(self.flag(0, s)?)], ) } @@ -98,16 +87,13 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { cmds: &mut Vec, q: u64, rows: usize, - _g: usize, s: usize, ) -> Result<()> { Self::kernel( cmds, 2, 12, - [(rows * 80).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, + LaunchShape::new([(rows * 80).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0), vec![Arg::U64(q), Arg::I32((rows * 80) as i32), Arg::U64(self.flag(0, s)?)], ) } @@ -116,31 +102,26 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { cmds, 2, 0, - [(rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, + LaunchShape::new([(rows * 2560).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0), vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], ) } pub(in super::super) fn project( cmds: &mut Vec, - w: u64, - q: u64, - y: u64, + buffers: ProjectionBuffers, rows: usize, out: usize, ) -> Result<()> { if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { return Err(Error::InvalidProjectionShape); } + let ProjectionBuffers { weight, quantised, output } = buffers; Self::kernel( cmds, 2, rows, - [out as u32, 1, 1], - [32, 4, 1], - 0, - vec![Arg::U64(w), Arg::U64(q), Arg::U64(y), Arg::I32(2560), Arg::I32(out as i32)], + LaunchShape::new([out as u32, 1, 1], [32, 4, 1], 0), + vec![Arg::U64(weight), Arg::U64(quantised), Arg::U64(output), Arg::I32(2560), Arg::I32(out as i32)], ) } pub(in super::super) fn external( diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs index c56b0108..0695cc18 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs @@ -17,13 +17,11 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { cmds, 4, if plain { 0 } else { 1 }, - [t as u32, if plain { 1 } else { 4 }, 1], - [256, 1, 1], - 0, + LaunchShape::new([t as u32, if plain { 1 } else { 4 }, 1], [256, 1, 1], 0), vec![self.gr_args(0, t, wh, xn)?], )?; self.gr_chunks(cmds, GrRows { row_count: t, weights: wh, normalised: xn }, policy)?; - Self::kernel(cmds, 4, 3, [160, 1, 1], [256, 1, 1], 0, vec![self.gr_args(0, t, wh, xn)?]) + Self::kernel(cmds, 4, 3, LaunchShape::new([160, 1, 1], [256, 1, 1], 0), vec![self.gr_args(0, t, wh, xn)?]) } fn gr_chunks( &self, @@ -40,9 +38,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { cmds, 4, self.gr_chunk_kernel(policy), - [41, 1, 1], - [256, 1, 1], - (ct * per_token) as u32, + LaunchShape::new([41, 1, 1], [256, 1, 1], (ct * per_token) as u32), vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], )?; } @@ -57,33 +53,16 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { 5 } } - #[allow(clippy::too_many_arguments)] + /// Records the scalar draft K/V of the prompt `rows` and drains the stream when anything is still pending. pub fn record<'arena, 'loan>( &mut self, residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, + rows: PrefillRows<'_>, + sources: ScalarDraftKvSources<'_, 'ctx>, ) -> Result { - let result = self.record_impl( - residual, - workspace, - ring, - prior, - tokens, - cell0, - first_needed, - retained, - policy, - cancelled, - ); - self.drain_pending(result, residual, workspace) + let result = self.record_impl(residual, run, rows, sources); + self.drain_pending(result, residual, run.workspace) } fn drain_pending( &mut self, diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs index a0ddd343..57925433 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs @@ -23,45 +23,39 @@ const SCALAR_EXTENTS: [usize; 11] = [ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { /// Literal cached device-input or mapped-input per-T graph scheduling. /// Unsupported storage/math branches return explicit fallback, never completion. - #[allow(clippy::too_many_arguments)] pub(in super::super) fn record_impl<'arena, 'loan>( &mut self, residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - mut cancelled: impl FnMut() -> bool, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, + rows: PrefillRows<'_>, + sources: ScalarDraftKvSources<'_, 'ctx>, ) -> Result { + let PrefillRows { tokens, cell0, first_needed } = rows; + let ScalarDraftKvSources { prior, retained, policy } = sources; let call = ScalarCall { prior, tokens, cell0, first_needed, policy }; - self.record_scalar(residual, workspace, ring, &call, retained, &mut cancelled) + self.record_scalar(residual, run, &call, retained) } fn record_scalar( &mut self, residual: &mut OriginalDeviceResidual<'_, '_, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, call: &ScalarCall<'_>, retained: Rc>, - cancelled: &mut impl FnMut() -> bool, ) -> Result { if let Some(outcome) = Self::early_outcome(call.policy, call.tokens)? { return Ok(outcome); } let (weights, embedding) = retained.loans(self.context)?; - self.validate_scalar(residual, workspace, ring, call, &embedding)?; + self.validate_owners(run.workspace, run.ring, call.prior)?; + self.validate_prompt(residual, run.ring, call, &embedding)?; let Some(first_group) = self.first_group(call) else { return Ok(DraftKvOutcome::Skipped); }; let rows = residual.lease_mut(); - let staged = self.stage_scalar(rows, workspace, ring, (&weights, &embedding))?; + let staged = self.stage_scalar(rows, run.workspace, run.ring, (&weights, &embedding))?; self.claim_policy(&retained, call.prior, call.policy)?; - let operands = (&staged, &retained, &embedding); - self.record_groups(rows, workspace, ring, (call, first_group), operands, cancelled) + let operands = ScalarOperands { staged: &staged, retained: &retained, embedding: &embedding }; + self.record_groups(rows, run, (call, first_group), operands) } fn early_outcome(policy: &OriginalMtpScalarPolicy, tokens: &[i32]) -> Result> { if let Some(fallback) = OriginalMtpPrefill::fallback_for(&policy.kv, tokens) { @@ -70,19 +64,27 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { OriginalMtpPrefill::reject_bad_rope(&policy.kv)?; Ok(None) } - fn validate_scalar( + /// The owner, the draft ring, its prior snapshot and the batch workspace must all belong to this context. + fn validate_owners( + &self, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + ) -> Result<()> { + self.validate()?; + ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; + ring.validate_snapshot(prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context) + } + /// The prompt must fit the residual rows, the ring and the owner, and every token must index the embedding table. + fn validate_prompt( &self, residual: &OriginalDeviceResidual<'_, '_, 'ctx>, - workspace: &NativeBatchWorkspace<'ctx>, ring: &MtpOriginalInt8<'ctx>, call: &ScalarCall<'_>, embedding: &OriginalMtpEmbedding<'_, 'ctx>, ) -> Result<()> { - self.validate()?; - ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; - ring.validate_snapshot(call.prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; if self.shape_rejected(residual, ring, call) { return Err(Error::InvalidProjectionShape); } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs index b48cc64a..c62832c8 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs @@ -43,12 +43,45 @@ pub(in super::super) struct Cap<'a, 'ctx> { pub(in super::super) wh: &'a [BufferHandle; 11], pub(in super::super) eh: BufferHandle, pub(in super::super) t: usize, - pub(in super::super) group: usize, pub(in super::super) policy: &'a OriginalMtpScalarPolicy, pub(in super::super) ring: &'a MtpOriginalInt8<'ctx>, pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'ctx>, } +/// The staged weights, the retained weights and the embedding table every group of a prompt is recorded from. +#[derive(Clone, Copy)] +pub(in super::super) struct ScalarOperands<'a, 'ctx> { + pub(in super::super) staged: &'a ScalarStaged, + pub(in super::super) retained: &'a Rc>, + pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'ctx>, +} + +/// Everything the groups of one prompt read: the call, the operands and the handle of the staged prompt records. +#[derive(Clone, Copy)] +pub(in super::super) struct ScalarGroupSources<'a, 'ctx> { + pub(in super::super) call: &'a ScalarCall<'a>, + pub(in super::super) operands: ScalarOperands<'a, 'ctx>, + pub(in super::super) records: BufferHandle, +} + +/// Where one group of up to `max_t` prompt rows lies: its index, its first row and its row count. +#[derive(Clone, Copy)] +pub(in super::super) struct GroupSpan { + pub(in super::super) index: usize, + pub(in super::super) first_row: usize, + pub(in super::super) row_count: usize, +} + +/// The prompt pages prepared before the groups ran and the cell range they publish once the stream is drained. +pub(in super::super) struct PagePublication { + pub(in super::super) pages: Vec>, + pub(in super::super) changed: Vec<[Vec; 4]>, + pub(in super::super) first_page: usize, + pub(in super::super) first: usize, + pub(in super::super) end: usize, + pub(in super::super) generation: u64, +} + /// The owners a buffer supplied from outside must not alias: the prompt rows, the batch workspace and the draft ring. #[derive(Clone, Copy)] pub(in super::super) struct ExternalOwners<'a, 'arena, 'loan, 'ctx> { diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs index 5cb1d370..f1a29081 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs @@ -1,6 +1,7 @@ //! The group loop of `OriginalMtpScalarPrefill::record_impl` (STRA-338): the page and record staging, the per-group //! graph capture and enqueue, and the publication of the completed range. +use super::super::graph::GroupSubmission; #[allow(unused_imports)] use super::*; @@ -23,36 +24,32 @@ fn fill_records(rec: &mut [u8], tokens: &[i32], cell0: usize) { impl<'ctx> OriginalMtpScalarPrefill<'ctx> { /// Stages the pages and records, restores the ring and records every group; publishes the completed range. - #[allow(clippy::too_many_arguments)] pub(in super::super) fn record_groups( &mut self, rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, at: (&ScalarCall<'_>, usize), - operands: (&ScalarStaged, &Rc>, &OriginalMtpEmbedding<'_, 'ctx>), - cancelled: &mut impl FnMut() -> bool, + operands: ScalarOperands<'_, 'ctx>, ) -> Result { let (call, first_group) = at; - let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; + let generation = run.ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let (first, end) = (call.cell0 + first_group, call.cell0 + call.tokens.len()); let first_page = first / 4; let (pages, changed) = OriginalMtpPrefill::prepare_pages(call.prior, end, first_page)?; // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. - let (rec_h, rec) = self.build_records(call)?; - let mut staging = vec![(rec_h, rec)]; + let (records, rec) = self.build_records(call)?; + let mut staging = vec![(records, rec)]; let mut cmds = Vec::new(); cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; - if cancelled() { + if (run.cancelled)() { return Ok(DraftKvOutcome::Cancelled); } - self.restore_and_upload(workspace, ring, call, &mut staging)?; - if let Some(outcome) = - self.run_groups(rows, workspace, ring, (call, operands), (rec_h, &mut cmds), cancelled)? - { + self.restore_and_upload(run.workspace, run.ring, call, &mut staging)?; + let sources = ScalarGroupSources { call, operands, records }; + if let Some(outcome) = self.run_groups(rows, run, &sources, &mut cmds)? { return Ok(outcome); } - self.complete(rows, workspace, ring, call, (pages, changed), (first_page, first, end, generation), cancelled) + self.complete(rows, run, call, PagePublication { pages, changed, first_page, first, end, generation }) } fn build_records(&self, call: &ScalarCall<'_>) -> Result<(BufferHandle, Vec)> { let mut rec = zero_bytes(call.tokens.len() * 29 * 4)?; @@ -79,64 +76,64 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { staging.clear(); Ok(()) } - #[allow(clippy::too_many_arguments)] + /// Stages, cancellation-checks and submits every group of the prompt that the ring does not hold yet. fn run_groups( &mut self, rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &MtpOriginalInt8<'ctx>, - ctx: ( - &ScalarCall<'_>, - (&ScalarStaged, &Rc>, &OriginalMtpEmbedding<'_, 'ctx>), - ), - buf: (BufferHandle, &mut Vec), - cancelled: &mut impl FnMut() -> bool, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, + sources: &ScalarGroupSources<'_, 'ctx>, + commands: &mut Vec, ) -> Result> { - let (call, operands) = ctx; - let (rec_h, cmds) = buf; + let call = sources.call; let n = call.tokens.len(); - for (group, c) in (0..n).step_by(self.max_t).enumerate() { - let t = self.max_t.min(n - c); - if call.cell0 + c + t <= call.first_needed { + for (index, first_row) in (0..n).step_by(self.max_t).enumerate() { + let row_count = self.max_t.min(n - first_row); + if call.cell0 + first_row + row_count <= call.first_needed { continue; } - let at = (group, c, t); - if let Some(o) = - self.run_group(rows, workspace, ring, (call, operands), (at, rec_h, &mut *cmds), cancelled)? - { - return Ok(Some(o)); + let span = GroupSpan { index, first_row, row_count }; + let mut copies = self.stage_group(sources, run.ring, span, &mut *commands)?; + if (run.cancelled)() { + self.drain_graphs(rows, run.workspace)?; + return Ok(Some(DraftKvOutcome::Cancelled)); } + let submission = Self::submission(call, span, &mut *commands, &mut copies); + self.submit_group(rows, run, sources.operands.retained, submission)?; } Ok(None) } - #[allow(clippy::too_many_arguments)] - fn run_group( + /// The scratch addresses and staging copies of one group, and its captured commands when no graph is cached. + fn stage_group( &mut self, - rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, + sources: &ScalarGroupSources<'_, 'ctx>, ring: &MtpOriginalInt8<'ctx>, - ctx: ( - &ScalarCall<'_>, - (&ScalarStaged, &Rc>, &OriginalMtpEmbedding<'_, 'ctx>), - ), - buf: ((usize, usize, usize), BufferHandle, &mut Vec), - cancelled: &mut impl FnMut() -> bool, - ) -> Result> { - let (call, (st, retained, embedding)) = ctx; - let (at, rec_h, cmds) = buf; - let (group, c, t) = at; - let io = self.group_io(t)?; - let mut copies = Self::group_copies(&io, rec_h, (st.rh, st.rbytes), (call.tokens.len(), c, t))?; - if self.needs_capture(t, call.policy.per_group_sync)? { - let cap = Cap { io, wh: &st.wh, eh: st.eh, t, group, policy: call.policy, ring, embedding }; - self.capture_group(cmds, &cap)?; + span: GroupSpan, + commands: &mut Vec, + ) -> Result<[ScalarCommand; 4]> { + let ScalarGroupSources { call, operands, records } = *sources; + let ScalarOperands { staged, embedding, .. } = operands; + let io = self.group_io(span.row_count)?; + let at = (call.tokens.len(), span.first_row, span.row_count); + let copies = Self::group_copies(&io, records, (staged.rh, staged.rbytes), at)?; + if self.needs_capture(span.row_count, call.policy.per_group_sync)? { + let wh = &staged.wh; + let cap = Cap { io, wh, eh: staged.eh, t: span.row_count, policy: call.policy, ring, embedding }; + self.capture_group(commands, &cap)?; } - if cancelled() { - self.drain_graphs(rows, workspace)?; - return Ok(Some(DraftKvOutcome::Cancelled)); - } - self.submit_group(rows, workspace, ring, (call, retained), (at, cmds, &mut copies))?; - Ok(None) + Ok(copies) + } + /// The rows, cells and commands of one group; a mapped-input group needs only the residual copy. + fn submission<'a>( + call: &'a ScalarCall<'_>, + span: GroupSpan, + kernels: &'a mut Vec, + copies: &'a mut [ScalarCommand; 4], + ) -> GroupSubmission<'a> { + let has_mapped_inputs = call.policy.per_group_sync; + let copies = if has_mapped_inputs { &mut copies[3..] } else { &mut copies[..] }; + let tokens = &call.tokens[span.first_row..span.first_row + span.row_count]; + let first_cell = call.cell0 + span.first_row; + GroupSubmission { index: span.index, tokens, first_cell, has_mapped_inputs, kernels, copies } } fn needs_capture(&mut self, t: usize, per_group_sync: bool) -> Result { let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !per_group_sync }; @@ -145,48 +142,38 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { fn submit_group( &mut self, rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &MtpOriginalInt8<'ctx>, - ctx: (&ScalarCall<'_>, &Rc>), - run: ((usize, usize, usize), &mut Vec, &mut [ScalarCommand; 4]), + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, + retained: &Rc>, + mut submission: GroupSubmission<'_>, ) -> Result<()> { - let (call, retained) = ctx; - let ((group, c, t), cmds, copies) = run; - let sync = call.policy.per_group_sync; - let copies = if sync { &mut copies[3..] } else { &mut copies[..] }; - let tokens = &call.tokens[c..c + t]; - if let Err(primary) = self.enqueue_group(t, group, sync, retained, ring, cmds, copies, tokens, call.cell0 + c) { - let drained = self.drain_graphs(rows, workspace); + if let Err(primary) = self.enqueue_group(&mut submission, retained, run.ring) { + let drained = self.drain_graphs(rows, run.workspace); return combine(Err(primary), drained); } - cmds.clear(); - if sync { - self.drain_graphs(rows, workspace)?; + submission.kernels.clear(); + if submission.has_mapped_inputs { + self.drain_graphs(rows, run.workspace)?; } Ok(()) } /// Drains the last graphs, reads the encoded pages back and publishes the completed range. - #[allow(clippy::too_many_arguments)] fn complete( &mut self, rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, + run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>, call: &ScalarCall<'_>, - pages: (Vec>, Vec<[Vec; 4]>), - range: (usize, usize, usize, u64), - cancelled: &mut impl FnMut() -> bool, + publication: PagePublication, ) -> Result { - let ((pages, mut changed), (first_page, first, end, generation)) = (pages, range); + let PagePublication { pages, mut changed, first_page, first, end, generation } = publication; if !call.policy.per_group_sync { - self.drain_graphs(rows, workspace)?; + self.drain_graphs(rows, run.workspace)?; } - if cancelled() { + if (run.cancelled)() { return Ok(DraftKvOutcome::Cancelled); } for (p, runs) in changed.iter_mut().enumerate() { - ring.read_encoded_page(first_page + p, runs)?; + run.ring.read_encoded_page(first_page + p, runs)?; } - Ok(OriginalMtpPrefill::finish(ring, pages, changed, (first, end, generation))) + Ok(OriginalMtpPrefill::finish(run.ring, pages, changed, (first, end, generation))) } } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs index 8902776e..572d75a8 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs @@ -19,7 +19,13 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { self.cap_commit(cmds, cap) } fn cap_inputs(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { - Self::kernel(cmds, 0, 11, [1, 1, 1], [256, 1, 1], 0, vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)])?; + Self::kernel( + cmds, + 0, + 11, + LaunchShape::new([1, 1, 1], [256, 1, 1], 0), + vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], + )?; if cap.policy.per_group_sync { self.cap_map_inputs(cmds, cap)?; } @@ -31,7 +37,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; for (dst, offset, count) in [(io.tok, 0, t), (io.step, max_t * 4, t * 4), (io.pos, max_t * 20, t * 24)] { let args = vec![Arg::U64(dst), Arg::U64(m.address(offset, count * 4)?), Arg::I32(count as i32)]; - Self::kernel(cmds, 3, 2, [1, 1, 1], [128, 1, 1], 0, args)?; + Self::kernel(cmds, 3, 2, LaunchShape::new([1, 1, 1], [128, 1, 1], 0), args)?; } Ok(()) } @@ -54,7 +60,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Arg::U64((2560 / group) as u64), Arg::U64(cap.io.emb), ]; - Self::kernel(cmds, 0, 5, [10, cap.t as u32, 1], [256, 1, 1], 0, args) + Self::kernel(cmds, 0, 5, LaunchShape::new([10, cap.t as u32, 1], [256, 1, 1], 0), args) } } } @@ -68,64 +74,69 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Arg::I64(2560), Arg::U64(cap.io.emb), ]; - Self::kernel(cmds, 1, 0, [10, cap.t as u32, 1], [32, 1, 1], 0, args) + Self::kernel(cmds, 1, 0, LaunchShape::new([10, cap.t as u32, 1], [32, 1, 1], 0), args) } /// The embedding half: finite guard, RMS norm and the Q8 projection into `e2`; returns the Q8 scratch. fn cap_embed_chain(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result { - let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group); - self.finite(cmds, io.emb, t * 2560, g, 0)?; + let (io, wh, t) = (&cap.io, cap.wh, cap.t); + self.finite(cmds, io.emb, t * 2560, 0)?; let norm = vec![Arg::U64(io.emb), Arg::U64(wh[0].qwen_address()), Arg::U64(io.en), Arg::I32(2560), Arg::F32(1e-6)]; - Self::kernel(cmds, 3, 0, [t as u32, 1, 1], [1024, 1, 1], 0, norm)?; - self.finite(cmds, io.en, t * 2560, g, 1)?; + Self::kernel(cmds, 3, 0, LaunchShape::new([t as u32, 1, 1], [1024, 1, 1], 0), norm)?; + self.finite(cmds, io.en, t * 2560, 1)?; let q = self.address(15, 8 * 80 * 36)?; Self::quant(cmds, io.en, q, t)?; - self.q8_guard(cmds, q, t, g, 2)?; - Self::project(cmds, wh[1].qwen_address(), q, io.e2, t, 2560)?; - self.finite(cmds, io.e2, t * 2560, g, 2)?; + self.q8_guard(cmds, q, t, 2)?; + Self::project(cmds, ProjectionBuffers { weight: wh[1].qwen_address(), quantised: q, output: io.e2 }, t, 2560)?; + self.finite(cmds, io.e2, t * 2560, 2)?; Ok(q) } /// The hidden half: RMS norm of the residual and the Q8 projection into `h2`, eight columns at a time. fn cap_hidden(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, q: u64) -> Result<()> { - let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group); + let (io, wh, t) = (&cap.io, cap.wh, cap.t); let norm = vec![Arg::U64(io.rin), Arg::U64(wh[2].qwen_address()), Arg::U64(io.hn), Arg::I32(10240), Arg::F32(1e-6)]; - Self::kernel(cmds, 3, 0, [t as u32, 1, 1], [1024, 1, 1], 0, norm)?; - self.finite(cmds, io.hn, t * 10240, g, 3)?; + Self::kernel(cmds, 3, 0, LaunchShape::new([t as u32, 1, 1], [1024, 1, 1], 0), norm)?; + self.finite(cmds, io.hn, t * 10240, 3)?; for hc in (0..t * 4).step_by(8) { let cols = 8.min(t * 4 - hc); Self::quant(cmds, io.hn + (hc * 10240) as u64, q, cols)?; - self.q8_guard(cmds, q, cols, g, 4)?; - Self::project(cmds, wh[3].qwen_address(), q, io.h2 + (hc * 10240) as u64, cols, 2560)?; + self.q8_guard(cmds, q, cols, 4)?; + Self::project( + cmds, + ProjectionBuffers { weight: wh[3].qwen_address(), quantised: q, output: io.h2 + (hc * 10240) as u64 }, + cols, + 2560, + )?; } - self.finite(cmds, io.h2, t * 10240, g, 4) + self.finite(cmds, io.h2, t * 10240, 4) } fn cap_gr(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { - let (io, t, g) = (&cap.io, cap.t, cap.group); + let (io, t) = (&cap.io, cap.t); let args = vec![Arg::U64(io.h2), Arg::U64(io.e2), Arg::U64(io.r), Arg::I64(2560), Arg::I32(4)]; - Self::kernel(cmds, 0, 4, [40, t as u32, 1], [256, 1, 1], 0, args)?; - self.finite(cmds, io.r, t * 10240, g, 5)?; + Self::kernel(cmds, 0, 4, LaunchShape::new([40, t as u32, 1], [256, 1, 1], 0), args)?; + self.finite(cmds, io.r, t * 10240, 5)?; self.gr(cmds, t, cap.wh, cap.policy)?; self.cap_gr_guards(cmds, cap) } fn cap_gr_guards(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { - let (t, g) = (cap.t, cap.group); - self.finite(cmds, self.address(9, t * 16)?, t * 4, g, 6)?; - self.finite(cmds, self.address(7, t * 40960)?, t * 10240, g, 6)?; - self.finite(cmds, self.address(8, t * 1280)?, t * 320, g, 7)?; - self.finite(cmds, self.address(10, t * 16)?, t * 4, g, 7)?; - self.finite(cmds, cap.io.mixed, t * 2560, g, 8) + let t = cap.t; + self.finite(cmds, self.address(9, t * 16)?, t * 4, 6)?; + self.finite(cmds, self.address(7, t * 40960)?, t * 10240, 6)?; + self.finite(cmds, self.address(8, t * 1280)?, t * 320, 7)?; + self.finite(cmds, self.address(10, t * 16)?, t * 4, 7)?; + self.finite(cmds, cap.io.mixed, t * 2560, 8) } /// The K and V projections of the mixed state into the current KV; returns their addresses. fn cap_kv(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, q: u64) -> Result<(u64, u64)> { - let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group); + let (io, wh, t) = (&cap.io, cap.wh, cap.t); Self::quant(cmds, io.mixed, q, t)?; - self.q8_guard(cmds, q, t, g, 9)?; + self.q8_guard(cmds, q, t, 9)?; let (kc, vc) = self.current_kv(cap.ring)?; - Self::project(cmds, wh[7].qwen_address(), q, kc, t, 512)?; - self.finite(cmds, kc, t * 512, g, 10)?; - Self::project(cmds, wh[8].qwen_address(), q, vc, t, 512)?; - self.finite(cmds, vc, t * 512, g, 11)?; + Self::project(cmds, ProjectionBuffers { weight: wh[7].qwen_address(), quantised: q, output: kc }, t, 512)?; + self.finite(cmds, kc, t * 512, 10)?; + Self::project(cmds, ProjectionBuffers { weight: wh[8].qwen_address(), quantised: q, output: vc }, t, 512)?; + self.finite(cmds, vc, t * 512, 11)?; Ok((kc, vc)) } /// K norm and rope, then the step append kernel for one row. @@ -133,10 +144,10 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { let (kc, vc) = kv; let k = kc + (row * 2048) as u64; let norm = vec![Arg::U64(k), Arg::U64(cap.wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)]; - Self::kernel(cmds, 2, 9, [2, 1, 1], [256, 1, 1], 0, norm)?; - self.finite(cmds, k, 512, cap.group, 12)?; + Self::kernel(cmds, 2, 9, LaunchShape::new([2, 1, 1], [256, 1, 1], 0), norm)?; + self.finite(cmds, k, 512, 12)?; Self::cap_rope(cmds, cap, row, k)?; - self.finite(cmds, k, 512, cap.group, 13)?; + self.finite(cmds, k, 512, 13)?; self.cap_append(cmds, cap, row, (k, vc)) } fn cap_rope(cmds: &mut Vec, cap: &Cap<'_, 'ctx>, row: usize, k: u64) -> Result<()> { @@ -157,7 +168,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Arg::U64(0), Arg::Words3([0; 3]), ]; - Self::kernel(cmds, 3, 1, [4, 2, 1], [32, 1, 1], 0, args) + Self::kernel(cmds, 3, 1, LaunchShape::new([4, 2, 1], [32, 1, 1], 0), args) } /// Literal step append kernel and actual private step record, not batched prompt arithmetic. fn cap_append(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, row: usize, kv: (u64, u64)) -> Result<()> { @@ -182,7 +193,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Arg::U64(host[4]), Arg::U64(host[5]), ]; - Self::kernel(cmds, 5, 0, [2, 4, 2], [64, 1, 1], 0, args) + Self::kernel(cmds, 5, 0, LaunchShape::new([2, 4, 2], [64, 1, 1], 0), args) } fn cap_commit(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { let ring = cap.ring; @@ -194,6 +205,6 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Arg::I32(cap.t as i32), Arg::U64(self.flag(0, 14)?), ]; - Self::kernel(cmds, 3, 3, [64, 1, 1], [256, 1, 1], 0, args) + Self::kernel(cmds, 3, 3, LaunchShape::new([64, 1, 1], [256, 1, 1], 0), args) } } diff --git a/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs b/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs index 381ef22e..385aedb3 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs @@ -156,18 +156,12 @@ impl<'c> Rig<'c> { self.ring.restore(&mut self.workspace, &prior).expect("ring reset"); let rows = self.arena.begin_rows(n).expect("rows"); let mut residual = OriginalDeviceResidual::for_probe(rows); - let old = self.standalone.record( - &mut residual, - &mut self.workspace, - &mut self.ring, - &prior, - tokens, - 0, - 0, - Rc::clone(&self.scalar_bank), - &self.policy, - || false, - ); + let mut cancelled = || false; + let mut run = RecordRun { workspace: &mut self.workspace, ring: &mut self.ring, cancelled: &mut cancelled }; + let rows = PrefillRows { tokens, cell0: 0, first_needed: 0 }; + let sources = + ScalarDraftKvSources { prior: &prior, retained: Rc::clone(&self.scalar_bank), policy: &self.policy }; + let old = self.standalone.record(&mut residual, &mut run, rows, sources); eprintln!("PREFLIGHT short n={n} standalone scalar owner: {:?}", old.as_ref().map(|_| "ok")); matches!(old, Err(Error::InvalidQwenShape)) } @@ -178,20 +172,14 @@ impl<'c> Rig<'c> { let mut residual = OriginalDeviceResidual::for_probe(rows); let prior = self.ring.empty_snapshot().expect("empty snapshot"); self.ring.restore(&mut self.workspace, &prior).expect("ring reset"); + let mut cancelled = || false; + let mut run = RecordRun { workspace: &mut self.workspace, ring: &mut self.ring, cancelled: &mut cancelled }; + let rows = PrefillRows { tokens, cell0: 0, first_needed: 0 }; + let sources = + ScalarDraftKvSources { prior: &prior, retained: Rc::clone(&self.scalar_bank), policy: &self.policy }; let outcome = self .drafter - .record_scalar_prefill( - &mut residual, - &mut self.workspace, - &mut self.ring, - &prior, - tokens, - 0, - 0, - Rc::clone(&self.scalar_bank), - &self.policy, - || false, - ) + .record_scalar_prefill(&mut residual, &mut run, rows, sources) .unwrap_or_else(|e| panic!("n={n}: the drafter's own scalar owner refused: {e:?}")); eprintln!("PREFLIGHT short n={n} drafter scalar owner: {}", outcome_label(&outcome)); assert!(matches!(outcome, DraftKvOutcome::Completed(_)), "n={n}"); diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs index a1fbce7f..c11d6e54 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs @@ -200,32 +200,14 @@ impl<'ctx> OriginalMtpActor<'ctx> { /// Scalar draft K/V prefill on the actor's own scalar owner (short prompts; see /// `OriginalMtpDrafter::record_scalar_prefill`). - #[allow(clippy::too_many_arguments)] pub fn record_scalar_prefill<'arena, 'loan>( &mut self, residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut crate::NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &crate::OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, + run: &mut crate::RecordRun<'_, 'ctx, impl FnMut() -> bool>, + rows: crate::PrefillRows<'_>, + sources: crate::ScalarDraftKvSources<'_, 'ctx>, ) -> Result { - self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill( - residual, - workspace, - ring, - prior, - tokens, - cell0, - first_needed, - retained, - policy, - cancelled, - ) + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill(residual, run, rows, sources) } /// Release everything the drafter bound to the verifier bank of the request that just ended (see diff --git a/crates/cuda-driver/src/root_exports.rs b/crates/cuda-driver/src/root_exports.rs index 857ab6a6..c00eff46 100644 --- a/crates/cuda-driver/src/root_exports.rs +++ b/crates/cuda-driver/src/root_exports.rs @@ -199,6 +199,7 @@ pub use original_expert_stager::{ #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use mtp_dense_kv::{ OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, + ScalarDraftKvSources, }; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use native_head::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs index 9dfd4ba0..0e110d72 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs @@ -2,7 +2,10 @@ //! phase, shifted actual IDs and current ring receipt, literal scalar producer. use super::*; use crate::qwen_forward::moe_weight_cache::RetainedOriginalMtpWeights; -use leleka_cuda_driver::{OriginalMtpActor, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy}; +use leleka_cuda_driver::{ + OriginalMtpActor, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, PrefillRows, RecordRun, + ScalarDraftKvSources, +}; impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { /// Original Prefill uses only known-next conditioning with no head/D2H. /// The genuine all-row R and immutable input owners survive through drain. @@ -22,7 +25,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx retained: Rc>, first_needed: usize, policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, + mut cancelled: impl FnMut() -> bool, ) -> Result { let phase = self.check_scalar_sources(binding, dense, txn, preview, last_next)?; let next = self.shifted_next_ids(txn, last_next)?; @@ -30,9 +33,11 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?; // Input/draft host policy and all eleven immutable device owners are live // throughout drain; never mint scalar committed products for prior rows. - #[rustfmt::skip] - let result = producer.record_scalar_prefill(&mut self.device, workspace, ring, prior, &next, start, - first_needed, retained, policy, cancelled).map_err(micro_driver_error)?; + let mut run = RecordRun { workspace, ring, cancelled: &mut cancelled }; + let rows = PrefillRows { tokens: &next, cell0: start, first_needed }; + let sources = ScalarDraftKvSources { prior, retained, policy }; + let result = + producer.record_scalar_prefill(&mut self.device, &mut run, rows, sources).map_err(micro_driver_error)?; self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, ring) } } From 083119c233fe19d3d8a4e0ae8579ebcc46e4f35c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:35 +0100 Subject: [PATCH 11/42] STRA-338 params r02: MTP draft round passes DraftTarget, AcceptedWindow, RepeatRowWindow, DraftSampling, DraftOutput OriginalMtpActor::draft_from_verifier/launch_draft_from_verifier/draft_first_from_verifier/draft/draft_first and OriginalMtpDrafter::draft_public/draft_first_public take the new draft-round DTOs (original_mtp_draft_round.rs) instead of eight to twelve positional arguments; the engine adapter and the preflight probe build them at the call. Files: crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs --- crates/cuda-driver/src/lib.rs | 2 + .../src/original_mtp_actor_loaded.rs | 6 +- .../impl_originalmtpactor_2_2.rs | 91 +++++-------------- .../src/original_mtp_draft_round.rs | 44 +++++++++ .../impl_originalmtpdrafter.rs | 47 ++++------ crates/cuda-driver/src/root_exports.rs | 2 + .../synthetic_verifier/replay.rs | 7 +- .../original_mtp_verified_adapter.rs | 4 +- .../impl_originalpromptexecutor.rs | 21 ++--- 9 files changed, 109 insertions(+), 115 deletions(-) create mode 100644 crates/cuda-driver/src/original_mtp_draft_round.rs diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index 01e4792b..0ddb0f77 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -71,6 +71,8 @@ mod original_mtp_bank; mod original_mtp_coupled; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod original_mtp_draft_head; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +mod original_mtp_draft_round; mod original_mtp_draft_vocab; mod original_mtp_rt; mod original_session_state; diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded.rs b/crates/cuda-driver/src/original_mtp_actor_loaded.rs index de6fced0..75f2f548 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded.rs @@ -20,9 +20,9 @@ use crate::original_mtp_coupled::{ use crate::original_mtp_draft_head::OriginalMtpDraftHead; use crate::original_mtp_loader::{CoupledPlan, KvPlan, OriginalMtpLoadPlan}; use crate::{ - CompletedOriginalMtpDraft, Context, Error, MtpInt8Snapshot, MtpOriginalInt8, NativeHeadSelection, - OriginalMtpDrafter, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, OriginalVerifyWindow, Result, - SamplerParams, + AcceptedWindow, CompletedOriginalMtpDraft, Context, DraftOutput, DraftSampling, DraftTarget, Error, + MtpInt8Snapshot, MtpOriginalInt8, OriginalMtpDrafter, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, + RepeatRowWindow, Result, SamplerParams, }; use std::rc::Rc; diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs index edc33546..6c49b143 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs @@ -10,20 +10,17 @@ impl<'ctx> OriginalMtpActor<'ctx> { /// `draft(T, tokens, p, a, drafts, ...)` over a completed verifier window. /// `max_drafts` and the coupled request come from this actor's settings. - #[allow(clippy::too_many_arguments)] pub fn draft_from_verifier( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, + target: DraftTarget<'_, 'ctx>, + window: AcceptedWindow<'ctx>, min_probability: f32, - policy: &OriginalMtpFullPolicy, ) -> Result> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let max_drafts = self.settings.max_drafts(); + let DraftTarget { ring, prior, policy } = target; + let AcceptedWindow { window, selection, accepted_row } = window; self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_from_verifier( ring, prior, @@ -39,21 +36,18 @@ impl<'ctx> OriginalMtpActor<'ctx> { /// `draft_from_verifier` split around the host's work (`OriginalMtpDrafter::launch_from_verifier`); `after` is the /// verifier's pending commit event. - #[allow(clippy::too_many_arguments)] pub fn launch_draft_from_verifier( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, + target: DraftTarget<'_, 'ctx>, + window: AcceptedWindow<'ctx>, min_probability: f32, - policy: &OriginalMtpFullPolicy, after: Option<&mut crate::OriginalGpuEvent<'ctx>>, ) -> Result<()> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let max_drafts = self.settings.max_drafts(); + let DraftTarget { ring, prior, policy } = target; + let AcceptedWindow { window, selection, accepted_row } = window; self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.launch_from_verifier( ring, prior, @@ -78,20 +72,17 @@ impl<'ctx> OriginalMtpActor<'ctx> { } /// `draft_first(T, R_row, token, cell, ...)`: the Original repeat-row path. - #[allow(clippy::too_many_arguments)] pub fn draft_first_from_verifier( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - rows: usize, + target: DraftTarget<'_, 'ctx>, + window: RepeatRowWindow<'ctx>, min_probability: f32, - policy: &OriginalMtpFullPolicy, ) -> Result> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let max_drafts = self.settings.max_drafts(); + let DraftTarget { ring, prior, policy } = target; + let RepeatRowWindow { window, selection, rows } = window; self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_from_verifier( ring, prior, @@ -106,67 +97,33 @@ impl<'ctx> OriginalMtpActor<'ctx> { } /// Public array form of `draft` (`drafts`/`probs` out-arguments). - #[allow(clippy::too_many_arguments)] pub fn draft( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, + target: DraftTarget<'_, 'ctx>, + window: AcceptedWindow<'ctx>, min_probability: f32, - policy: &OriginalMtpFullPolicy, - drafts: &mut [i32], - probabilities: Option<&mut [f32]>, + output: DraftOutput<'_>, ) -> Result> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let settings = self.settings; - self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_public( - ring, - prior, - window, - selection, - accepted_row, - &settings, - min_probability, - policy, - coupled, - drafts, - probabilities, - ) + let max_drafts = self.settings.max_drafts(); + let sampling = DraftSampling { min_probability, max_drafts, coupled }; + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_public(target, window, sampling, output) } /// Public array form of `draft_first`. - #[allow(clippy::too_many_arguments)] pub fn draft_first( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - rows: usize, + target: DraftTarget<'_, 'ctx>, + window: RepeatRowWindow<'ctx>, min_probability: f32, - policy: &OriginalMtpFullPolicy, - drafts: &mut [i32], - probabilities: Option<&mut [f32]>, + output: DraftOutput<'_>, ) -> Result> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); - let settings = self.settings; - self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_public( - ring, - prior, - window, - selection, - rows, - &settings, - min_probability, - policy, - coupled, - drafts, - probabilities, - ) + let max_drafts = self.settings.max_drafts(); + let sampling = DraftSampling { min_probability, max_drafts, coupled }; + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_public(target, window, sampling, output) } /// `~MtpDrafter()`: stream drain, graphs and owners via the drafter's diff --git a/crates/cuda-driver/src/original_mtp_draft_round.rs b/crates/cuda-driver/src/original_mtp_draft_round.rs new file mode 100644 index 00000000..6caf1f4d --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_draft_round.rs @@ -0,0 +1,44 @@ +//! The inputs of one MTP draft round (STRA-338): the ring it writes into, the verifier window it continues from, how +//! its tokens are chosen and where the public array form puts them. The actor, the drafter and the engine adapters +//! pass these instead of a long positional argument list. + +use crate::{ + MtpInt8Snapshot, MtpOriginalInt8, NativeHeadSelection, OriginalMtpFullPolicy, OriginalVerifyWindow, SamplerParams, +}; + +/// The draft ring a round writes into, the snapshot of its prior state and the full-forward policy of the round. +pub struct DraftTarget<'a, 'ctx> { + pub ring: &'a mut MtpOriginalInt8<'ctx>, + pub prior: &'a MtpInt8Snapshot, + pub policy: &'a OriginalMtpFullPolicy, +} + +/// A completed verifier window with the head selection of the same transaction and the last accepted row of the +/// window: what a regular round continues from. +pub struct AcceptedWindow<'ctx> { + pub window: OriginalVerifyWindow<'ctx>, + pub selection: NativeHeadSelection, + pub accepted_row: usize, +} + +/// The single-row verifier window of the final prompt seed and the number of rows `T` the first round repeats it +/// for (the Original repeat-row path). +pub struct RepeatRowWindow<'ctx> { + pub window: OriginalVerifyWindow<'ctx>, + pub selection: NativeHeadSelection, + pub rows: usize, +} + +/// How a round chooses its tokens: the probability floor, the draft cap and the coupled sampling request of the +/// actor's settings. +pub struct DraftSampling<'a> { + pub min_probability: f32, + pub max_drafts: i32, + pub coupled: Option<(SamplerParams, &'a [i32; 4096])>, +} + +/// The caller's output arrays of the public array form: the draft tokens and, when wanted, their probabilities. +pub struct DraftOutput<'a> { + pub drafts: &'a mut [i32], + pub probabilities: Option<&'a mut [f32]>, +} diff --git a/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs index f697a91c..9769487d 100644 --- a/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs +++ b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::{AcceptedWindow, DraftOutput, DraftSampling, DraftTarget, RepeatRowWindow}; impl<'ctx> OriginalMtpDrafter<'ctx> { pub(crate) fn loaded_max_t(&self) -> Result { @@ -179,29 +180,25 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { /// Public-array adapter over the genuine existing graph executor. It NEVER /// reads token/probability output before actual graph drain, and retains the /// completed ring/window product in its return value for subsequent replay. - #[allow(clippy::too_many_arguments)] pub(crate) fn draft_public( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, - settings: &DraftSettings, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - drafts: &mut [i32], - probabilities: Option<&mut [f32]>, + target: DraftTarget<'_, 'ctx>, + window: AcceptedWindow<'ctx>, + sampling: DraftSampling<'_>, + output: DraftOutput<'_>, ) -> Result> { + let DraftOutput { drafts, probabilities } = output; self.validate_public_output_extent(drafts, probabilities.as_deref())?; + let DraftTarget { ring, prior, policy } = target; + let AcceptedWindow { window, selection, accepted_row } = window; + let DraftSampling { min_probability, max_drafts, coupled } = sampling; let completion = self.draft_from_verifier( ring, prior, window, selection, accepted_row, - settings.max_drafts(), + max_drafts, min_probability, policy, coupled, @@ -212,29 +209,25 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { /// Existing direct first-round executor makes T real synchronous D2D copies /// of the authentic single-row verifier R, then stages T copies of its real /// matching head token. Caller shape errors are refused BEFORE those copies. - #[allow(clippy::too_many_arguments)] pub(crate) fn draft_first_public( &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - rows: usize, - settings: &DraftSettings, - min_probability: f32, - policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - drafts: &mut [i32], - probabilities: Option<&mut [f32]>, + target: DraftTarget<'_, 'ctx>, + window: RepeatRowWindow<'ctx>, + sampling: DraftSampling<'_>, + output: DraftOutput<'_>, ) -> Result> { - self.validate_first_public(drafts, probabilities.as_deref(), rows)?; + let DraftOutput { drafts, probabilities } = output; + self.validate_first_public(drafts, probabilities.as_deref(), window.rows)?; + let DraftTarget { ring, prior, policy } = target; + let RepeatRowWindow { window, selection, rows } = window; + let DraftSampling { min_probability, max_drafts, coupled } = sampling; let completion = self.draft_first_from_verifier( ring, prior, window, selection, rows, - settings.max_drafts(), + max_drafts, min_probability, policy, coupled, diff --git a/crates/cuda-driver/src/root_exports.rs b/crates/cuda-driver/src/root_exports.rs index c00eff46..a684a2b1 100644 --- a/crates/cuda-driver/src/root_exports.rs +++ b/crates/cuda-driver/src/root_exports.rs @@ -217,6 +217,8 @@ pub use original_file_expert_source::{ pub use original_gpu_schedule::OriginalStreamDrained; pub use original_gpu_schedule::capture_timing as original_capture_timing; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub use original_mtp_draft_round::{AcceptedWindow, DraftOutput, DraftSampling, DraftTarget, RepeatRowWindow}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_verify::chain::set_down_override as set_chain_down_override; pub use original_verify::sm120::set_overrides as set_sm120_overrides; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs index 1468e91b..6f11fe65 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier/replay.rs @@ -139,10 +139,9 @@ impl<'ctx> Replay<'ctx> { &mut self, mtp: &mut Option>, reset_snapshot: &mut Option, - window: (NativeHeadSelection, Option>), + (selection, completed): (NativeHeadSelection, Option>), (t, keep): (usize, usize), ) { - let (selection, completed) = window; let (Some((ring, actor)), Some(done)) = (mtp.as_mut(), completed) else { return }; actor.set_prompt_len(1); actor.set_max_drafts(3); @@ -154,7 +153,9 @@ impl<'ctx> Replay<'ctx> { keep - 1, prior.next_position() ); - let drafted = actor.draft_from_verifier(ring, &prior, done, selection, keep - 1, 0.0, &full_policy()); + let window = leleka_cuda_driver::AcceptedWindow { window: done, selection, accepted_row: keep - 1 }; + let target = leleka_cuda_driver::DraftTarget { ring, prior: &prior, policy: &full_policy() }; + let drafted = actor.draft_from_verifier(target, window, 0.0); if let Some(d) = step!(format!("actor.draft_from_verifier(t={t}, a={}) in {:?}", keep - 1, started.elapsed()), drafted) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs index c2292461..5303a767 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs @@ -10,8 +10,8 @@ use super::{ }; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; use leleka_cuda_driver::{ - CompletedOriginalMtpDraft, Context, NativeHeadSelection, OriginalGpuEvent, OriginalMtpFullPolicy, - OriginalVerifyWindow, SamplerParams, + AcceptedWindow, CompletedOriginalMtpDraft, Context, DraftTarget, NativeHeadSelection, OriginalGpuEvent, + OriginalMtpFullPolicy, OriginalVerifyWindow, RepeatRowWindow, SamplerParams, }; /// One completed `Verifier::run` receipt, before the target commit. It owns diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs index 13f81767..2822989c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs @@ -28,8 +28,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { before.validate(session)?; let actor = self.checked_mtp_actor(binding)?; draft.with_mtp_launch_ring(binding, session, &before, &prospective, |ring, prior| { + let target = DraftTarget { ring, prior, policy }; actor - .launch_draft_from_verifier(ring, prior, window, selection, accepted_row, min_p, policy, after) + .launch_draft_from_verifier(target, AcceptedWindow { window, selection, accepted_row }, min_p, after) .map_err(driver_error) })?; Ok(OriginalLaunchedMtpDraft { binding: binding.identity(), before, prospective }) @@ -111,16 +112,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { let actor = self.checked_mtp_actor(binding)?; let completed = draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| { + let target = DraftTarget { ring, prior, policy }; + let (window, selection, accepted_row) = (receipt.window, receipt.selection, receipt.accepted_row); actor - .draft_from_verifier( - ring, - prior, - receipt.window, - receipt.selection, - receipt.accepted_row, - min_p, - policy, - ) + .draft_from_verifier(target, AcceptedWindow { window, selection, accepted_row }, min_p) .map_err(driver_error) })?; self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed) @@ -147,9 +142,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { let actor = self.checked_mtp_actor(binding)?; let completed = draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| { - actor - .draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy) - .map_err(driver_error) + let target = DraftTarget { ring, prior, policy }; + let window = RepeatRowWindow { window: receipt.window, selection: receipt.selection, rows }; + actor.draft_first_from_verifier(target, window, min_p).map_err(driver_error) })?; self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed) } From 9e74f4a0e629ce0de95ec2b4889bd2eb08d6dd92 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:40 +0100 Subject: [PATCH 12/42] STRA-338 params r02: capture_layer_stage and capture_append_rows take the row range Both took begin and end next to the layer; they now take `rows: Range`. Files: crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs --- .../impl_originalverifygdnjournal_2_2.rs | 5 ++--- .../impl_originalverifywindowops.rs | 3 +-- .../impl_windowops_for_originalverifywindowops.rs | 11 ++++------- .../impl_originalverifyqsajournal_2.rs | 5 ++--- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs index 8d0bf2fe..5201c5c1 100644 --- a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs @@ -11,11 +11,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { stage: OriginalVerifyGdnStage, capture: &mut OriginalCapture<'_, 'ctx>, layer: usize, - begin: usize, - end: usize, + rows: std::ops::Range, ) -> Result<()> { self.validate_context(self.physical.context)?; - let op = self.stage_operands(layer, begin, end)?; + let op = self.stage_operands(layer, rows.start, rows.end)?; let mut commands = self.stage_commands(&op)?; if chain::flags().ab && matches!(stage, OriginalVerifyGdnStage::AlphaBeta) { return self.submit_launches(capture, vec![self.stage_ab_launch(&op)?]); diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs index f51c53b4..57985e99 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs @@ -20,8 +20,7 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { OriginalVerifyGdnStage::AlphaBeta, self.capture, g, - rows.begin, - rows.end, + rows.begin..rows.end, )?; self.capture.side_end(0)?; self.capture.side_fork(1)?; diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs index d28755b7..accbe35d 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs @@ -50,8 +50,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { OriginalVerifyGdnStage::Conv, self.capture, layer, - rows.begin, - rows.end, + rows.begin..rows.end, ) } fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> { @@ -62,8 +61,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { OriginalVerifyGdnStage::AlphaBeta, self.capture, layer, - rows.begin, - rows.end, + rows.begin..rows.end, ) } fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> { @@ -76,8 +74,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { OriginalVerifyGdnStage::Recurrence, self.capture, layer, - rows.begin, - rows.end, + rows.begin..rows.end, ) } fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { @@ -95,7 +92,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { } fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()> { let base = &self.resources.base; - base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin, rows.end) + base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin..rows.end) } fn qsa_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { self.plan_launch(|p| p.qsa_q_path(q, rows, batched)) diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs index fa808feb..ef9c7252 100644 --- a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs @@ -118,10 +118,9 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { journal: &OriginalVerifyGdnJournal<'_, 'ctx>, capture: &mut OriginalCapture<'_, 'ctx>, layer: usize, - begin: usize, - end: usize, + rows: std::ops::Range, ) -> Result<()> { - self.capture_append(journal, capture, LayerRows { layer, rows: begin..end }, false) + self.capture_append(journal, capture, LayerRows { layer, rows }, false) } /// Records the row appends of `target` (`commit`: the steps come from the accepted-position words). pub(super) fn capture_append( From 47a5938f2f6e35ebdf8f3f7f209755c6255f6432 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:07:40 +0100 Subject: [PATCH 13/42] STRA-338 params r02: restore_ring takes OriginalRingBlocks (begin, end, slots) --- .../src/original_conversation_state.rs | 16 ++++++++++++---- crates/cuda-driver/src/original_session_state.rs | 2 +- crates/cuda-driver/src/root_exports.rs | 2 +- .../src/conversation/original.rs | 7 ++++--- 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/crates/cuda-driver/src/original_conversation_state.rs b/crates/cuda-driver/src/original_conversation_state.rs index 209c1cf3..e9aa1691 100644 --- a/crates/cuda-driver/src/original_conversation_state.rs +++ b/crates/cuda-driver/src/original_conversation_state.rs @@ -46,6 +46,14 @@ pub enum OriginalKvLayer { Draft, } +/// The host blocks `[begin, end)` of a drafter ring and the number of ring slots they land in (`block % slots`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct OriginalRingBlocks { + pub begin: i64, + pub end: i64, + pub slots: i64, +} + /// A byte range of session state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum OriginalRegion { @@ -153,7 +161,7 @@ pub trait OriginalHostKv { /// `kv_stream_reset` on a streamed layer's device map. fn reset_stream_map(&mut self, owned: usize) -> Result<()>; /// `kv_ring_restore` of host blocks `[begin, end)` into a ring's slots. - fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()>; + fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, blocks: OriginalRingBlocks) -> Result<()>; } /// Byte access to one session's state, in the runtime's vocabulary. @@ -163,7 +171,7 @@ pub trait OriginalSessionBytes { fn synchronize(&mut self) -> Result<()>; fn set_ple_prev(&mut self, prev: [i32; 2]); fn reset_stream_map(&mut self, owned: usize) -> Result<()>; - fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()>; + fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, blocks: OriginalRingBlocks) -> Result<()>; } /// Session lifecycle operations beyond raw bytes, supplied by the serving owner. @@ -373,9 +381,9 @@ impl OriginalSessionBytes for OriginalConversationAccess<'_, self.host.reset_stream_map(owned) } - fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()> { + fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, blocks: OriginalRingBlocks) -> Result<()> { self.state.validate_context(self.context)?; - self.host.restore_ring(layer, format, begin, end, slots) + self.host.restore_ring(layer, format, blocks) } } diff --git a/crates/cuda-driver/src/original_session_state.rs b/crates/cuda-driver/src/original_session_state.rs index e9be1b86..c8903dc2 100644 --- a/crates/cuda-driver/src/original_session_state.rs +++ b/crates/cuda-driver/src/original_session_state.rs @@ -16,7 +16,7 @@ pub(crate) use conversation::OriginalConversationAccess; #[allow(unused_imports)] pub use conversation::{ OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, - OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, + OriginalRegion, OriginalRingBlocks, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, }; use std::rc::Rc; diff --git a/crates/cuda-driver/src/root_exports.rs b/crates/cuda-driver/src/root_exports.rs index a684a2b1..56fa7df0 100644 --- a/crates/cuda-driver/src/root_exports.rs +++ b/crates/cuda-driver/src/root_exports.rs @@ -47,7 +47,7 @@ pub use original_prefill_layout::{ }; pub use original_session_state::{ OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, - OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, + OriginalRegion, OriginalRingBlocks, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, }; pub use qsa_selected_kv::{QsaKvMisses, QsaSelectedKvProducts, QsaSelectedKvWorkspace}; pub use qwen_dispatch::fixed_operands::{ diff --git a/crates/engine-qwen35-cuda/src/conversation/original.rs b/crates/engine-qwen35-cuda/src/conversation/original.rs index 5c658bdd..a6b5195e 100644 --- a/crates/engine-qwen35-cuda/src/conversation/original.rs +++ b/crates/engine-qwen35-cuda/src/conversation/original.rs @@ -12,8 +12,8 @@ use super::model::{ StateRegion, StreamMap, }; use leleka_cuda_driver::{ - OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, OriginalSessionBytes, - OriginalSessionControl, OriginalSessionFacts, + OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, OriginalRingBlocks, + OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, }; fn layer(l: KvLayer) -> OriginalKvLayer { @@ -198,7 +198,8 @@ impl StateMemory for OriginalDevice { } fn restore_ring(&mut self, l: KvLayer, format: i32, blocks: RingBlocks) -> Result<(), String> { - self.session.restore_ring(layer(l), format, blocks.begin, blocks.end, blocks.slots).map_err(text) + let blocks = OriginalRingBlocks { begin: blocks.begin, end: blocks.end, slots: blocks.slots }; + self.session.restore_ring(layer(l), format, blocks).map_err(text) } } From 79cf15fdbc8d73491aa772dc5114fb2789d7129d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:08:26 +0100 Subject: [PATCH 14/42] STRA-338 params e01: full MTP forward weights take the head sources as one value (vocabulary derived from the native head) --- .../cache_original_mtp_weights.rs | 7 +++++++ .../impl_retainedoriginalmtpweights.rs | 19 ++++++++----------- .../src/qwen_forward/moe_weight_cache.rs | 2 +- .../qwen_forward/original_mtp_full_owner.rs | 2 +- .../impl_originalmtpfullowner.rs | 4 ++-- 5 files changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs index 1738ba24..72ab6fc0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs @@ -20,6 +20,13 @@ enum WeightSource { Pinned, RtDirectory, } +/// The native MTP head and the optional gathered draft-vocabulary head that the full forward chooses between. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct MtpHeadSources<'a, 'ctx> { + pub(in crate::qwen_forward) native: &'a OriginalMtpNativeHead<'ctx>, + pub(in crate::qwen_forward) draft: Option<&'a leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>, +} + /// Clones share the same device allocations (`Rc`); no buffer is duplicated. #[derive(Clone)] pub(in crate::qwen_forward) struct RetainedOriginalMtpWeights<'ctx> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs index b4c7d0b9..6495a7b7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs @@ -186,20 +186,20 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> { /// Exact full MTP forward role order. The caller lends the model-affine /// native-head allocation from `OriginalNativeOutput::mtp_head`; this /// cache never fabricates a replacement head buffer or dispatch profile. - #[allow(clippy::too_many_arguments)] + /// The id vocabulary is the native head's own vocabulary. pub(in crate::qwen_forward) fn full_forward_weights( &self, binding: &ModelBinding, context: &'ctx Context<'ctx>, prefix: Rc>, - head: &OriginalMtpNativeHead<'ctx>, - id_vocab: usize, - draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>, + heads: MtpHeadSources<'_, 'ctx>, ) -> Result>> { + let head = heads.native; + let id_vocab = head.vocabulary(); self.admit_full_forward(binding, context, head, id_vocab)?; let roles = self.acquire_roles(binding, context, FULL_FORWARD_ROLES)?; let experts = self.expert_bank(binding, context)?; - let (head_weights, head_rows, subset) = Self::select_head(head, draft_head); + let (head_weights, head_rows, subset) = Self::select_head(heads); let weights = FullWeights::retain( context, prefix, @@ -231,13 +231,10 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> { } Ok(()) } - fn select_head( - head: &OriginalMtpNativeHead<'ctx>, - draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>, - ) -> HeadBinding<'ctx> { - match draft_head { + fn select_head(heads: MtpHeadSources<'_, 'ctx>) -> HeadBinding<'ctx> { + match heads.draft { Some(draft) => (draft.rows(), draft.count(), Some(draft.subset_pair())), - None => (head.weights(), head.vocabulary(), None), + None => (heads.native.weights(), heads.native.vocabulary(), None), } } pub(in crate::qwen_forward) fn metadata_bytes(&self) -> Result { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index 2a25b9a8..618d2299 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -337,7 +337,7 @@ pub(super) struct RoutedSourceHealth<'cache, 'ctx> { #[path = "cache_original_mtp_weights.rs"] mod original_mtp_weights; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(in crate::qwen_forward) use original_mtp_weights::RetainedOriginalMtpWeights; +pub(in crate::qwen_forward) use original_mtp_weights::{MtpHeadSources, RetainedOriginalMtpWeights}; mod validate_ranked_profile_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs index 8e607a83..bc35f0ec 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs @@ -10,7 +10,7 @@ use super::{ contract::{Error, Result, Stage}, executor::original_prompt::embedding::OriginalPromptEmbedding, - moe_weight_cache::{MoeWeightCache, RetainedOriginalMtpWeights}, + moe_weight_cache::{MoeWeightCache, MtpHeadSources, RetainedOriginalMtpWeights}, output_native::{OriginalMtpNativeHead, OriginalNativeOutput}, session::{QwenSession, original_prompt::draft::OriginalDraftSession}, }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs index 567b5bb5..974536d0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner/impl_originalmtpfullowner.rs @@ -143,8 +143,8 @@ impl<'ctx> OriginalMtpFullOwner<'ctx> { let head = &prepared.head; let scalar = retained.scalar_prefill_weights(binding, context, embedding)?; let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?); - let draft_head = prepared.draft_head.as_ref(); - Ok(retained.full_forward_weights(binding, context, prefix, head, head.vocabulary(), draft_head)?) + let heads = MtpHeadSources { native: head, draft: prepared.draft_head.as_ref() }; + Ok(retained.full_forward_weights(binding, context, prefix, heads)?) } pub(super) fn shared_drafter( context: &'ctx Context<'ctx>, From 8102387b56a0aee4909139c049b2e5509b587a49 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:08:27 +0100 Subject: [PATCH 15/42] STRA-338 params e01: MTP target window capacity, preparation, joint publication and draft warm-up take domain values --- .../src/qwen_forward/executor.rs | 1 + .../src/qwen_forward/executor_mtp_window.rs | 67 +++++++++++-------- .../src/qwen_forward/mtp_decode.rs | 4 +- .../impl_mtpdecoder/impl_mtpdecoder_2_2.rs | 12 ++-- .../mtp_decoder_batch_gpu/check_loaded_fn.rs | 15 +++-- 5 files changed, 57 insertions(+), 42 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs index 362279c4..1ad49fa7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs @@ -25,6 +25,7 @@ type StepCoreResult = (Option, Option>); pub(in crate::qwen_forward) mod original_prompt; #[path = "executor_prefill_chunk.rs"] mod prefill_chunk; +pub(in crate::qwen_forward) use prefill_chunk::mtp_window::{VerificationChunk, VerificationSource, WindowCaches}; /// MTP input from one fully committed target step. No public constructor. pub(crate) struct TargetStepProduct { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs index d75cb2d4..0db4a1a1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs @@ -18,6 +18,17 @@ struct ReadyVerifiedDraft<'draft, 'binding> { count: usize, warmed: usize, } +/// The weight caches a joint publication warms the draft against: the MoE cache always, the dense cache +/// only when the target window leased a device GDN state that must be sealed. +pub(in crate::qwen_forward) struct WindowCaches<'a, 'moe, 'dense> { + pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'moe>, + pub(in crate::qwen_forward) dense: Option<&'a DenseWeightCache<'dense>>, +} +/// The draft chunk stage being warmed together with the MoE cache its rows run against. +struct DraftWarmup<'a, 'stage, 'cache> { + stage: &'a mut MtpChunkStage<'stage>, + cache: &'a MoeWeightCache<'cache>, +} impl VerifiedDraftPublication for ReadyVerifiedDraft<'_, '_> { fn validate(&self, txn: &QwenChunkTxn<'_, '_>, prefix: &VerifiedTargetPrefix) -> Result<()> { txn.validate_verified_prefix(prefix)?; @@ -49,28 +60,28 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { cache: &MoeWeightCache<'_>, cancelled: impl FnMut() -> bool, ) -> Result { - self.publish_joint_with_gdn_replay(binding, draft, cache, None, cancelled) + self.publish_joint_with_gdn_replay(binding, draft, WindowCaches { moe: cache, dense: None }, cancelled) } pub(in crate::qwen_forward) fn publish_joint_with_gdn_replay( mut self, binding: &ModelBinding, draft: &mut MtpSession, - cache: &MoeWeightCache<'_>, - dense: Option<&DenseWeightCache<'_>>, + caches: WindowCaches<'_, '_, '_>, mut cancelled: impl FnMut() -> bool, ) -> Result { self.txn.validate_verified_prefix(&self.prefix)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - self.seal_leased_gdn(binding, dense, &mut cancelled)?; + self.seal_leased_gdn(binding, caches.dense, &mut cancelled)?; let start = self.txn.start_position(); let count = self.prefix.count(); let rows = self.copy_accepted_rows(count)?; // The existing stage validates actual draft KV/window/epoch/owner and // requires genuine draft.next_position == actual target chunk start. let mut stage = draft.stage_chunk(binding, &self.txn)?; - self.warm_accepted_rows(binding, cache, &mut stage, &rows, &mut cancelled)?; + let warmup = DraftWarmup { stage: &mut stage, cache: caches.moe }; + self.warm_accepted_rows(binding, warmup, &rows, &mut cancelled)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } @@ -101,8 +112,7 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { fn warm_accepted_rows( &mut self, binding: &ModelBinding, - cache: &MoeWeightCache<'_>, - stage: &mut MtpChunkStage<'_>, + warmup: DraftWarmup<'_, '_, '_>, rows: &[ChunkRowResidual], cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { @@ -115,18 +125,25 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? || next.is_none() { return Err(Error::IdentityMismatch); } - mtp::warm_chunk_row(binding, &mut self.txn, row, stage, cache)?; + mtp::warm_chunk_row(binding, &mut self.txn, row, warmup.stage, warmup.cache)?; } Ok(()) } } +/// The target step a verification window continues from, and the end-of-sequence token that closes it. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct VerificationSource<'a> { + pub(in crate::qwen_forward) product: &'a TargetStepProduct, + pub(in crate::qwen_forward) eos: Option, +} /// The borrowed inputs of the verification chunk that the session, caches and cancel hook do not carry. -struct VerificationChunk<'a, 'o, 'p, 'd> { - binding: &'a ModelBinding, - proposals: &'a [TokenId], - output: &'a OutputStage<'o, 'p>, - dense_cache: &'a DenseWeightCache<'d>, - host_remaining: usize, +pub(in crate::qwen_forward) struct VerificationChunk<'a, 'o, 'p, 'd> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) source: VerificationSource<'a>, + pub(in crate::qwen_forward) proposals: &'a [TokenId], + pub(in crate::qwen_forward) output: &'a OutputStage<'o, 'p>, + pub(in crate::qwen_forward) dense_cache: &'a DenseWeightCache<'d>, + pub(in crate::qwen_forward) host_remaining: usize, } // Descending bounded admission, never a numeric/identity/poison retry. fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()>) -> Result { @@ -147,13 +164,12 @@ fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<() impl QwenForward { pub(in crate::qwen_forward) fn mtp_target_window_capacity( binding: &ModelBinding, - source: &TargetStepProduct, - eos: Option, + source: VerificationSource<'_>, target: &QwenSession<'_>, limit: usize, host_remaining: usize, ) -> Result { - QwenChunkTxn::validate_verification_source(binding, source, eos, target)?; + QwenChunkTxn::validate_verification_source(binding, source.product, source.eos, target)?; legal_target_rows(limit, |rows| QwenChunkTxn::preflight_mtp_verification(target, binding, rows, host_remaining)) } @@ -201,30 +217,23 @@ impl QwenForward { /// Explicit source-only candidate. Preserves Native/scalar MTP/defaults. /// Existing Q6/MoE/GR batching survives; GDN uses unchanged scalar pending /// producers here so every possible accepted prefix has actual state. - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn prepare_mtp_target_window<'session, 'driver>( - binding: &ModelBinding, - source: &TargetStepProduct, - proposals: &[TokenId], - eos: Option, + inputs: VerificationChunk<'_, '_, '_, '_>, session: &'session mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, kar_cache: Option<&mut KarPleCache<'_>>, moe_cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - host_remaining: usize, mut cancelled: impl FnMut() -> bool, ) -> Result> { - let seed = QwenChunkTxn::validate_verification_source(binding, source, eos, session)?; + let (binding, source, proposals) = (inputs.binding, inputs.source, inputs.proposals); + let seed = QwenChunkTxn::validate_verification_source(binding, source.product, source.eos, session)?; Self::admit_mtp_window(seed, proposals, moe_cache, &mut cancelled)?; // Refuse the complete journal charge before cache/provider growth. - QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), host_remaining)?; - let inputs = VerificationChunk { binding, proposals, output, dense_cache, host_remaining }; + QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), inputs.host_remaining)?; let txn = Self::prepare_verification_chunk(inputs, session, kar_cache, moe_cache, &mut cancelled)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let prefix = txn.select_verified_prefix(binding, source, eos)?; + let prefix = txn.select_verified_prefix(binding, source.product, source.eos)?; Ok(PreparedMtpTargetWindow { txn, prefix }) } } 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 2dbafda1..366f22ba 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs @@ -3,7 +3,9 @@ use super::{ contract::{Dimension, Error, Position, Result, TokenId}, - executor::{PrefillStepProduct, QwenForward, TargetStepProduct}, + executor::{ + PrefillStepProduct, QwenForward, TargetStepProduct, VerificationChunk, VerificationSource, WindowCaches, + }, kar_ple_cache::KarPleCache, mtp::{self, MtpInput, MtpSession, reserve}, output::OutputStage, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs index fc6dc368..8fdc56a9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs @@ -87,7 +87,8 @@ impl MtpDecoder { }; // Pure complete-state admission before any draft/canonical mutation. let budget = capacity_budget(cache, host_remaining)?; - let capacity = QwenForward::mtp_target_window_capacity(binding, source, eos, target, limit, budget)?; + let source = VerificationSource { product: source, eos }; + let capacity = QwenForward::mtp_target_window_capacity(binding, source, target, limit, budget)?; Ok(BatchedPlan { first, limit, reuse_first_seed, seed_host_charge, host_remaining, capacity }) } @@ -231,15 +232,16 @@ impl MtpDecoder { let (source, eos, output, dense) = (cx.source, cx.eos, cx.output, cx.dense_cache); let (kar, proposals, host) = (kar_cache.as_deref_mut(), &st.candidates[..rows], plan.host_remaining); let observer = observe_cancel(cancelled, &mut fired); - let prepared = QwenForward::prepare_mtp_target_window( - binding, source, proposals, eos, target, output, kar, cache, dense, host, observer, - ); + let source = VerificationSource { product: source, eos }; + let chunk = VerificationChunk { binding, source, proposals, output, dense_cache: dense, host_remaining: host }; + let prepared = QwenForward::prepare_mtp_target_window(chunk, target, kar, cache, observer); let pending = prepared.map_err(|error| window_stage_error(error, fired))?; cx.check_accepted(pending.accepted_rows(), rows)?; st.tokens.extend_from_slice(&st.candidates[..pending.accepted_rows()]); let mut fired = false; let observer = observe_cancel(cancelled, &mut fired); - let published = pending.publish_joint_with_gdn_replay(binding, &mut self.draft, cache, Some(dense), observer); + let caches = WindowCaches { moe: cache, dense: Some(dense) }; + let published = pending.publish_joint_with_gdn_replay(binding, &mut self.draft, caches, observer); published.map_err(|error| window_stage_error(error, fired)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs index aba63bf3..ec0fab4f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs @@ -9,16 +9,17 @@ use crate::qwen_forward::mtp_decode::MtpVerifiedWindow; macro_rules! prepare_window { ($flow:expr, $candidate:expr, ($source:expr, $proposals:expr, $eos:expr)) => { QwenForward::prepare_mtp_target_window( - $flow.shared.binding, - $source, - $proposals, - $eos, + $crate::qwen_forward::executor::VerificationChunk { + binding: $flow.shared.binding, + source: $crate::qwen_forward::executor::VerificationSource { product: $source, eos: $eos }, + proposals: $proposals, + output: $flow.shared.output, + dense_cache: $flow.shared.dense, + host_remaining: TRANSACTION_CAP, + }, &mut $flow.target, - $flow.shared.output, Some(&mut *$flow.shared.kar), $candidate, - $flow.shared.dense, - TRANSACTION_CAP, || false, ) }; From b37e74250dfedc7b715e457cb0b14e6cdc1ad38c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:08:27 +0100 Subject: [PATCH 16/42] STRA-338 params e01: native MMQ report takes the chunk verdict; layer-0 comparison takes the compared tensor --- .../executor_native_mmq_evaluation.rs | 27 +++++++++------- .../qwen_forward/layer0_mmq_observation.rs | 31 +++++++++++-------- 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs index b7716cf2..8b94f02d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs @@ -77,27 +77,26 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( run.late_row_cancel(&mut candidate_draft, &fresh, &fresh_draft); run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft); let chunk = run.candidate_chunk(&mut candidate_draft); - let (exact, actual_greedy) = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft); + let verdict = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft); let after = run.native_continuation(&mut candidate_draft, &chunk, &continued); run.output.test_reset_replay_record(false).expect("head observer did not drain"); - native_report(&baseline, &continued, &chunk, &exact, actual_greedy, &after) + native_report(&baseline, &continued, &chunk, &verdict, &after) } fn native_report( baseline: &Observation, continued: &Observation, chunk: &ChunkRun, - exact: &ChunkExact, - actual_greedy: TokenId, + verdict: &NativeChunkVerdict, after: &NativeContinued, ) -> NativeMmqReport { NativeMmqReport { - final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, actual_greedy), + final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, verdict.greedy), continuation_head: HeadObservation::new(&continued.logits, &after.logits, continued.greedy, after.greedy), - head_exact: exact.head, - residual_exact: exact.residual, - target_exact: exact.target, - draft_exact: exact.draft, + head_exact: verdict.exact.head, + residual_exact: verdict.exact.residual, + target_exact: verdict.exact.target, + draft_exact: verdict.exact.draft, continued_head_exact: after.head, continued_target_exact: after.target, continued_draft_exact: after.draft, @@ -107,6 +106,12 @@ fn native_report( } } +/// How the candidate chunk compares with the scalar baseline: tensor exactness and the candidate's greedy token. +struct NativeChunkVerdict { + exact: ChunkExact, + greedy: TokenId, +} + /// What the continuation step after the candidate chunk observed. struct NativeContinued { logits: Box<[u32]>, @@ -124,7 +129,7 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { baseline_streams: &[u32], chunk: &ChunkRun, candidate_draft: &MtpDecoder, - ) -> (ChunkExact, TokenId) { + ) -> NativeChunkVerdict { let actual_greedy = chunk.product.predicted(self.session).expect("MMQ current origin invalid"); let head = baseline.logits.as_ref() == chunk.logits.as_ref(); let actual_streams = @@ -134,7 +139,7 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { .state .numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk state invalid")); let draft = candidate_draft.test_chunk_eq(&baseline.draft); - (ChunkExact { head, residual, target, draft }, actual_greedy) + NativeChunkVerdict { exact: ChunkExact { head, residual, target, draft }, greedy: actual_greedy } } fn native_continuation( &mut self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs index 0be03149..fc54353b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs @@ -217,7 +217,15 @@ pub(crate) fn complete(witness: [u64; 3]) -> Result<()> { Ok(()) }) } -fn comparison(role: &str, row: usize, slot: Option, expert: Option, a: &[u32], b: &[u32]) -> String { +/// Which tensor of the layer-0 capture a comparison line describes: its role, input row, route slot and expert. +struct ComparedTensor { + role: &'static str, + row: usize, + slot: Option, + expert: Option, +} +fn comparison(tensor: ComparedTensor, a: &[u32], b: &[u32]) -> String { + let ComparedTensor { role, row, slot, expert } = tensor; assert_eq!(a.len(), b.len()); let first = a.iter().zip(b).position(|(a, b)| a != b); let count = a.iter().zip(b).filter(|(a, b)| a != b).count(); @@ -287,29 +295,26 @@ impl Report { fn push_row_comparisons(&self, row: usize, comparisons: &mut String) { for slot in 0..SLOTS { let lo = (row * SLOTS + slot) * N; - comparisons.push_str(&comparison( - "packed_down", + let tensor = ComparedTensor { + role: "packed_down", row, - Some(slot), - Some(self.ids[row * SLOTS + slot]), + slot: Some(slot), + expert: Some(self.ids[row * SLOTS + slot]), + }; + comparisons.push_str(&comparison( + tensor, &self.arms[0].packed[lo..lo + N], &self.arms[1].packed[lo..lo + N], )); } let lo = row * N; comparisons.push_str(&comparison( - "shared_scaled", - row, - None, - None, + ComparedTensor { role: "shared_scaled", row, slot: None, expert: None }, &self.arms[0].shared[lo..lo + N], &self.arms[1].shared[lo..lo + N], )); comparisons.push_str(&comparison( - "final", - row, - None, - None, + ComparedTensor { role: "final", row, slot: None, expert: None }, &self.arms[0].final_values[lo..lo + N], &self.arms[1].final_values[lo..lo + N], )); From 6dae6edc155fa4775b96c88db601d3c1ae27b473 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:08:28 +0100 Subject: [PATCH 17/42] STRA-338 params e01: grouped chunk experts (direct packets, source-backed groups, shared tail, slot packs, direct Down proof) take domain values Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs --- .../src/gpu_proofs/native_down_pair_proofs.rs | 20 +- .../impl_qwenforward_3/window_experts.rs | 5 +- .../src/qwen_forward/moe_expert.rs | 4 +- .../src/qwen_forward/moe_group_adaptive.rs | 3 +- .../packet_plan_fn.rs | 3 +- .../src/qwen_forward/moe_group_chunk.rs | 16 +- .../moe_group_chunk/bound_rows_fn.rs | 130 +++++------ .../moe_group_chunk/direct_packets_fns.rs | 86 ++++---- .../moe_group_chunk/execute_bound_fn.rs | 23 +- .../moe_group_chunk/finish_shared_with_fn.rs | 36 ++-- .../moe_group_chunk/impl_preparedmoerow.rs | 54 +++-- .../ordered_down_refusal_fn.rs | 94 +++----- .../project_group_direct_fn.rs | 48 ++--- .../moe_group_chunk/project_group_fn.rs | 79 ++++--- .../project_group_source_consumers_fn.rs | 204 ++++++++++-------- .../project_group_source_fenced_fn.rs | 78 ++++--- .../qwen_forward/moe_group_down_direct_gpu.rs | 14 +- .../moe_group_down_direct_gpu/arm_fn.rs | 15 +- .../impl_loadedarms.rs | 13 +- .../qwen_forward/moe_group_resident_queue.rs | 11 +- .../src/qwen_forward/moe_layer0_pair.rs | 2 +- .../src/qwen_forward/moe_mmq_chunk.rs | 10 +- .../moe_mmq_chunk/resident_fns.rs | 7 +- .../src/qwen_forward/moe_mmq_slotpack.rs | 82 +++---- 24 files changed, 528 insertions(+), 509 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs index a0788f5f..f7306d30 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_pair_proofs.rs @@ -1,6 +1,7 @@ //! The four PUBLIC candidate proofs: they differ in the caches they load, in what they generate and in what //! they conclude; the owner, the teardown and the artifacts are shared (`native_down_pair_run.rs`). use super::*; +use crate::qwen_forward::moe_expert::LoadedArms; use crate::qwen_forward::moe_weight_cache::LearnedMainWitness; use fivecase_runtime::FiveCaseReport; @@ -107,15 +108,16 @@ impl Proof for DirectDown { // Only the changed direct Down proof shares this model load. // The unchanged, previously qualified GDN helper is not repeated. let mut session = QwenSession::for_binding_on_shared_device(run.binding, Rc::clone(run.context)); - let down = QwenForward::test_direct_down_on_loaded( - run.binding, - run.context, - &mut session, - &mut owner.kar, - &mut owner.moe, - &owner.dense, - ) - .expect("actual original-first direct Down packet proof failed"); + let arms = LoadedArms { + binding: run.binding, + context: run.context, + session: &mut session, + kar: &mut owner.kar, + cache: &mut owner.moe, + dense: &owner.dense, + }; + let down = QwenForward::test_direct_down_on_loaded(arms) + .expect("actual original-first direct Down packet proof failed"); drop(session); let execution = EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr; let arm = owner.armed_inputs(run).arm(&run.case.req, &run.case.ids, execution, DIRECT_PHASE); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs index 37fbc0de..bc805ec8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs @@ -3,7 +3,7 @@ #[allow(unused_imports)] use super::*; use crate::qwen_forward::gr::GrBatchRow; -use crate::qwen_forward::moe_expert::ExpertReady; +use crate::qwen_forward::moe_expert::{ChunkFfnLayer, ExpertReady}; use crate::qwen_forward::session::chunk::{ChunkFfnRow, PreparedLayerRow}; /// Releases the native MoE products of the window, if it had any. @@ -77,7 +77,8 @@ impl QwenForward { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] ChunkMoePolicy::Layer0Diagnostic => Err(Error::IdentityMismatch), ChunkMoePolicy::Native | ChunkMoePolicy::ExperimentalRetainedGr => { - MoeExpertStage::execute_chunk(binding, layer, ffn_rows, chunk, moe_cache, cancelled) + let ffn = ChunkFfnLayer { binding, layer, rows: ffn_rows }; + MoeExpertStage::execute_chunk(ffn, chunk, moe_cache, cancelled) } ChunkMoePolicy::ExperimentalResidentMmq | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs index 2264e4bf..063c8afb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs @@ -20,7 +20,9 @@ mod moe_down; use moe_down::{DownScope, DownSelection, PackedDown, RetainedDown, TransportBuffer}; #[path = "moe_group_chunk.rs"] mod grouped; -pub(in crate::qwen_forward) use grouped::PreparedMoeRow; +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) use grouped::LoadedArms; +pub(in crate::qwen_forward) use grouped::{ChunkFfnLayer, PreparedMoeRow}; const N: usize = 2560; const FF: usize = 640; const K: usize = 10; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs index 8f7476a2..e6a2fab7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs @@ -110,7 +110,8 @@ fn project_residents<'ctx>( if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?; + let group = ExpertGroup { context, binding, rows, pairs, scope, origins }; + project_group(group, cache, prepared, down, cancelled)?; } Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs index 904f65d7..0c95b255 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/packet_plan_fn.rs @@ -47,7 +47,8 @@ impl<'g> PacketPlan<'g> { continue; } let pairs = groups[expert].as_slice(); - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; + let members = PacketGroupMembers { rows, pairs, origins }; + validate_packet_pairs(actual, binding, members, packets)?; self.classify_pairs(binding, rows, pairs, cache)?; } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs index a4d2eaac..6fdc947a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs @@ -62,6 +62,8 @@ mod layer0_pair; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_group_down_direct_gpu.rs"] mod direct_gpu; +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) use direct_gpu::LoadedArms; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_group_adaptive.rs"] @@ -69,6 +71,7 @@ mod adaptive; #[path = "moe_group_chunk/impl_preparedmoerow.rs"] mod impl_preparedmoerow; +pub(in crate::qwen_forward) use impl_preparedmoerow::ChunkFfnLayer; #[allow(unused_imports)] use impl_preparedmoerow::grouped_pairs; #[path = "moe_group_chunk/bound_rows_fn.rs"] @@ -80,20 +83,17 @@ use execute_bound_fn::execute_bound; #[path = "moe_group_chunk/project_group_fn.rs"] mod project_group_fn; #[allow(unused_imports)] -use project_group_fn::project_group; +use project_group_fn::{ExpertGroup, project_group}; #[path = "moe_group_chunk/project_group_direct_fn.rs"] mod project_group_direct_fn; #[path = "moe_group_chunk/project_group_shared_fns.rs"] mod project_group_shared_fns; #[allow(unused_imports)] use project_group_direct_fn::project_group_direct; -#[path = "moe_group_chunk/project_group_source_fenced_fn.rs"] -mod project_group_source_fenced_fn; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[allow(unused_imports)] -use project_group_source_fenced_fn::project_group_source_fenced; #[path = "moe_group_chunk/project_group_source_consumers_fn.rs"] mod project_group_source_consumers_fn; +#[path = "moe_group_chunk/project_group_source_fenced_fn.rs"] +mod project_group_source_fenced_fn; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] use project_group_source_consumers_fn::project_group_source_consumers; @@ -102,7 +102,7 @@ mod direct_packets_fns; #[path = "moe_group_chunk/ordered_down_refusal_fn.rs"] mod ordered_down_refusal_fn; #[allow(unused_imports)] -use ordered_down_refusal_fn::execute_direct_packets; +use ordered_down_refusal_fn::PacketGroupMembers; #[allow(unused_imports)] use ordered_down_refusal_fn::finish_shared; #[allow(unused_imports)] @@ -118,6 +118,8 @@ use ordered_down_refusal_fn::validate_packet_pairs; #[path = "moe_group_chunk/finish_shared_with_fn.rs"] mod finish_shared_with_fn; #[allow(unused_imports)] +use finish_shared_with_fn::RowTail; +#[allow(unused_imports)] use finish_shared_with_fn::finish_shared_with; #[allow(unused_imports)] use finish_shared_with_fn::uses_adaptive; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs index a024a038..3e56168e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs @@ -1,5 +1,7 @@ //! The uploaded rows of one chunk and their ungrouped/grouped execution (STRA-338 size: extract-method only). +use super::direct_packets_fns::PacketRun; +use super::finish_shared_with_fn::RowTail; #[allow(unused_imports)] use super::*; @@ -11,46 +13,55 @@ pub(super) struct BoundRows<'a, 'ctx> { pub(super) scope: &'a DownScope<'ctx>, pub(super) activations: &'a [TransportBuffer<'ctx>], pub(super) prepared: &'a [RoutedGateUpQ8<'a>], + /// Whether the rows run as sorted expert groups instead of row by row. + pub(super) grouped: bool, +} + +/// The inputs only the direct-packet path consumes: the sealed chunk transaction its packets are validated +/// against (absent on the ordinary path) and the optional native prompt finish. +pub(super) struct DirectPacketInputs<'a, 'session, 'ctx, 'dense> { + pub(super) actual: Option<&'a QwenChunkTxn<'session, 'ctx>>, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(super) native: Option>, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + pub(super) marker: std::marker::PhantomData<&'dense ()>, +} + +/// The expert groups of the chunk rows, in ascending expert order, and the Down origin of every row. +#[derive(Clone, Copy)] +pub(super) struct ExpertGroupPlan<'a> { + pub(super) groups: &'a [Vec], + pub(super) origins: &'a [Rc], +} + +/// What the scalar-Down path projects the expert groups into: the per-row Down cells, following the plan. +struct GroupProjection<'a, 'session, 'ctx> { + plan: ExpertGroupPlan<'a>, + actual: Option<&'a QwenChunkTxn<'session, 'ctx>>, + down: &'a mut [[Option>; K]], } impl<'a, 'ctx> BoundRows<'a, 'ctx> { pub(super) fn execute( &self, - grouped: bool, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, 'ctx>>, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< - prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, + direct: DirectPacketInputs<'_, '_, 'ctx, '_>, ) -> Result> { - if !grouped { - return self.execute_ungrouped( - cache, - cancelled, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native, - ); + if !self.grouped { + return self.execute_ungrouped(cache, cancelled, direct); } - self.execute_grouped( - cache, - cancelled, - actual, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native, - ) + self.execute_grouped(cache, cancelled, direct) } fn execute_ungrouped( &self, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< - prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, + direct: DirectPacketInputs<'_, '_, 'ctx, '_>, ) -> Result> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if native.is_some() { + if direct.native.is_some() { return Err(Error::IdentityMismatch); } let rows = self.rows; @@ -83,31 +94,30 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { &self, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, 'ctx>>, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< - prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, + direct: DirectPacketInputs<'_, '_, 'ctx, '_>, ) -> Result> { let groups = route_groups(self.rows)?; let origins = down_origins(self.binding, self.rows)?; if use_direct_packets(cache) { - return execute_direct_packets( - self.context, - self.binding, - self.rows, - &groups, - cache, - self.prepared, - self.activations, - self.scope, - &origins, - cancelled, - actual.ok_or(Error::IdentityMismatch)?, + let run = PacketRun { + context: self.context, + binding: self.binding, + rows: self.rows, + scope: self.scope, + origins: &origins, + activations: self.activations, + groups: &groups, + prepared: self.prepared, + actual: direct.actual.ok_or(Error::IdentityMismatch)?, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native, - ); + native: direct.native, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + marker: std::marker::PhantomData, + }; + return run.execute(cache, cancelled); } - self.execute_scalar_down(cache, cancelled, actual, &groups, &origins) + let plan = ExpertGroupPlan { groups: &groups, origins: &origins }; + self.execute_scalar_down(cache, cancelled, direct.actual, plan) } fn execute_scalar_down( @@ -115,13 +125,13 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, actual: Option<&QwenChunkTxn<'_, 'ctx>>, - groups: &[Vec], - origins: &[Rc], + plan: ExpertGroupPlan<'_>, ) -> Result> { let mut down = Vec::new(); down.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; down.resize_with(self.rows.len(), || std::array::from_fn::<_, K, _>(|_| None)); - let operation = self.project_and_combine(cache, cancelled, actual, groups, origins, &mut down); + let mut projection = GroupProjection { plan, actual, down: &mut down }; + let operation = self.project_and_combine(cache, cancelled, &mut projection); let mut close = Ok(()); for actual in down.into_iter().flatten().flatten() { let next = actual.output.close(); @@ -137,12 +147,9 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { &self, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, 'ctx>>, - groups: &[Vec], - origins: &[Rc], - down: &mut Vec<[Option>; K]>, + projection: &mut GroupProjection<'_, '_, 'ctx>, ) -> Result> { - self.project_groups(cache, cancelled, actual, groups, origins, down)?; + self.project_groups(cache, cancelled, projection)?; let rows = self.rows; let mut outputs = Vec::new(); outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; @@ -152,7 +159,7 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - outputs.push(self.combine_row(cache, i, &mut down[i], &origins[i])?); + outputs.push(self.combine_row(cache, i, &mut projection.down[i], &projection.plan.origins[i])?); } Ok(outputs) } @@ -161,19 +168,18 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { &self, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, 'ctx>>, - groups: &[Vec], - origins: &[Rc], - down: &mut [[Option>; K]], + projection: &mut GroupProjection<'_, '_, 'ctx>, ) -> Result<()> { - self.project_adaptive(cache, cancelled, actual, groups, origins, down)?; + self.project_adaptive(cache, cancelled, projection)?; let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope); + let ExpertGroupPlan { groups, origins } = projection.plan; let adaptive_done = uses_adaptive(cache); for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive_done) { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - project_group(context, binding, rows, pairs, cache, self.prepared, scope, origins, down, cancelled)?; + let group = ExpertGroup { context, binding, rows, pairs, scope, origins }; + project_group(group, cache, self.prepared, &mut *projection.down, cancelled)?; } Ok(()) } @@ -187,15 +193,14 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { &self, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, 'ctx>>, - groups: &[Vec], - origins: &[Rc], - down: &mut [[Option>; K]], + projection: &mut GroupProjection<'_, '_, 'ctx>, ) -> Result<()> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if cache.uses_strata_adaptive_experts() { let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope); let prepared = self.prepared; + let ExpertGroupPlan { groups, origins } = projection.plan; + let (actual, down) = (projection.actual, &mut *projection.down); adaptive::project_adaptive_groups( context, binding, rows, groups, cache, prepared, scope, origins, down, cancelled, actual, )?; @@ -223,7 +228,8 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] packed.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?; - finish_shared(context, binding, row, self.activations[i].buffer()?, cache, scope, origin, &packed) + let activation = self.activations[i].buffer()?; + finish_shared(RowTail { context, binding, row, activation, scope, origin }, cache, &packed) })(); let close = packed.close(); let values = output?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs index 3441aefb..1f7589f8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/direct_packets_fns.rs @@ -1,37 +1,42 @@ -//! Phases of `execute_direct_packets` (STRA-338 size: extract-method only). +//! Phases of the direct-packet layer batch (STRA-338 size: extract-method only). -#[allow(unused_imports)] +use super::finish_shared_with_fn::RowTail; use super::ordered_down_refusal_fn::close_packets; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::project_group_direct_fn::DirectRun; use super::*; -/// The sealed rows, their origins and shared activations of one direct-packet layer batch. -pub(super) struct PacketRun<'a, 'ctx, 'l, 'd> { +/// The sealed rows, their origins, expert groups and shared activations of one direct-packet layer batch. +pub(super) struct PacketRun<'a, 'session, 'ctx, 'l, 'd, 'q> { pub(super) context: &'ctx Context<'ctx>, pub(super) binding: &'a ModelBinding, pub(super) rows: &'a [ChunkFfnRow], pub(super) scope: &'a DownScope<'ctx>, pub(super) origins: &'a [Rc], pub(super) activations: &'a [TransportBuffer<'ctx>], + /// The expert groups of the rows, in ascending expert order. + pub(super) groups: &'a [Vec], + /// The Q8 owner of every uploaded activation. + pub(super) prepared: &'a [RoutedGateUpQ8<'q>], + /// The sealed chunk transaction every packet is validated against. + pub(super) actual: &'a QwenChunkTxn<'session, 'ctx>, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) native: Option>, #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(super) marker: std::marker::PhantomData<(&'l (), &'d ())>, } -impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { +impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> { /// Reserve the packets, run the batch and close every packet whatever the outcome. pub(super) fn execute( self, - groups: &[Vec], cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result> { let mut packets = Vec::new(); packets.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; let scope = self.scope; - let operation = self.operate(&mut packets, groups, cache, prepared, cancelled, actual); + let operation = self.operate(&mut packets, cache, cancelled); scope.record(&operation); let cleanup = close_packets(packets); operation.and_then(|values| cleanup.map(|()| values)) @@ -41,19 +46,16 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { fn operate( mut self, packets: &mut Vec>, - groups: &[Vec], cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result> { self.init_packets(packets)?; - self.project_groups(packets, groups, cache, prepared, cancelled, actual)?; + self.project_groups(packets, cache, cancelled)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(mut finish) = self.native.take() { - return self.finish_native(packets, cache, &mut finish, cancelled, actual); + return self.finish_native(packets, cache, &mut finish, cancelled); } - self.finish_rows(packets, cache, cancelled, actual) + self.finish_rows(packets, cache, cancelled) } /// One empty packet per authenticated row. @@ -70,45 +72,39 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { } /// The adaptive producer (when selected) or every non-empty expert group, one at a time. - #[allow(clippy::too_many_arguments)] pub(super) fn project_groups( &self, packets: &mut [ActualSlotPacket<'ctx>], - groups: &[Vec], cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result<()> { let adaptive = uses_adaptive(cache); - self.project_adaptive(adaptive, packets, groups, cache, prepared, cancelled, actual)?; - for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive) { + if adaptive { + self.project_adaptive(packets, cache, cancelled)?; + } + for pairs in self.groups.iter().filter(|group| !group.is_empty() && !adaptive) { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - self.project_one(pairs, packets, cache, prepared, cancelled, actual)?; + self.project_one(pairs, packets, cache, cancelled)?; } Ok(()) } - #[allow(clippy::too_many_arguments)] #[cfg_attr( not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")), allow(unused_variables) )] fn project_adaptive( &self, - adaptive: bool, packets: &mut [ActualSlotPacket<'ctx>], - groups: &[Vec], cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result<()> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if adaptive { + { let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope); + let (groups, prepared, actual) = (self.groups, self.prepared, self.actual); adaptive_packets::project_adaptive_packets( context, binding, @@ -126,26 +122,24 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { Ok(()) } - #[allow(clippy::too_many_arguments)] fn project_one( &self, pairs: &[Pair], packets: &mut [ActualSlotPacket<'ctx>], cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result<()> { - let (context, binding, rows, scope, origins) = - (self.context, self.binding, self.rows, self.scope, self.origins); #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - return project_group_source_fenced( - context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, - ); + return self.project_group_fenced(pairs, cache, DirectRun { actual: self.actual, packets, cancelled }); #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - return project_group_direct( - context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, - ); + { + let (context, binding, rows, scope, origins) = + (self.context, self.binding, self.rows, self.scope, self.origins); + let (prepared, actual) = (self.prepared, self.actual); + return project_group_direct( + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, + ); + } } /// The native prompt finish consumes the completed packets of every row. @@ -156,9 +150,8 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { cache: &mut MoeWeightCache<'ctx>, finish: &mut prompt_finish::NativePromptFinish<'_, 'ctx, '_>, cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result> { - let (rows, binding) = (self.rows, self.binding); + let (rows, binding, actual) = (self.rows, self.binding, self.actual); let layer = rows[0].row().route.identity().layer(); let mut refs = Vec::new(); refs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; @@ -176,8 +169,8 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { packets: &[ActualSlotPacket<'ctx>], cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, ) -> Result> { + let actual = self.actual; let mut outputs = Vec::new(); outputs.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; for (index, row) in self.rows.iter().enumerate() { @@ -207,13 +200,10 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] packet.packet.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?; let activation = self.activations[index].buffer()?; + let tail = RowTail { context, binding, row, activation, scope, origin }; if use_shared_tail(cache) { - return packet.packet.with_completed(scope, |completed| { - finish_shared_queued(context, binding, row, activation, cache, scope, origin, completed) - }); + return packet.packet.with_completed(scope, |completed| finish_shared_queued(tail, cache, completed)); } - finish_shared_with(context, binding, row, activation, cache, scope, origin, |weights, scaled| { - packet.packet.combine(scope, weights, scaled) - }) + finish_shared_with(tail, cache, |weights, scaled| packet.packet.combine(scope, weights, scaled)) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs index 56eee4cf..dd1bb00f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs @@ -1,35 +1,26 @@ //! Moved out of the parent module by STRA-338: fn execute_bound. -use super::bound_rows_fn::BoundRows; +use super::bound_rows_fn::{BoundRows, DirectPacketInputs}; #[allow(unused_imports)] use super::*; pub(super) fn execute_bound<'ctx>( context: &Context<'_>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], + layer: ChunkFfnLayer<'_>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - actual: Option<&QwenChunkTxn<'_, 'ctx>>, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< - prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, + direct: DirectPacketInputs<'_, '_, 'ctx, '_>, ) -> Result> { + let (binding, rows) = (layer.binding, layer.rows); let context = cache.mmq_context(binding, context)?; let (grouped, scope, failed) = open_bound(binding, rows, cache, context)?; let (mut activations, mut prepared) = (reserved(rows.len())?, reserved(rows.len())?); let admission = upload_activations(rows, &scope, cancelled, &mut activations) .and_then(|()| prepare_owners(context, cancelled, &activations, &mut prepared)); let result = admission.and_then(|()| { - let bound = BoundRows { context, binding, rows, scope: &scope, activations: &activations, prepared: &prepared }; - bound.execute( - grouped, - cache, - cancelled, - actual, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native, - ) + let (scope, activations, prepared) = (&scope, &activations, &prepared); + let bound = BoundRows { context, binding, rows, scope, activations, prepared, grouped }; + bound.execute(cache, cancelled, direct) }); scope.record(&result); finish_bound(&failed, cache, result, close_prepared(prepared), activations) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs index 96d2aca7..7ff1f5cd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs @@ -3,6 +3,18 @@ #[allow(unused_imports)] use super::*; +/// What the shared-expert tail of one row reads besides the weight cache: the row, its activation, the Down scope and +/// the row's origin. +#[derive(Clone, Copy)] +pub(super) struct RowTail<'a, 'ctx, 'buf> { + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) row: &'a PreparedMoeRow, + pub(super) activation: &'a DeviceBuffer<'buf>, + pub(super) scope: &'a DownScope<'ctx>, + pub(super) origin: &'a Rc, +} + /// Partial owners of the shared expert of one row; every one is closed explicitly, whatever failed. #[derive(Default)] struct SharedOwners<'ctx> { @@ -12,15 +24,8 @@ struct SharedOwners<'ctx> { route_weights: Option>, } impl<'ctx> SharedOwners<'ctx> { - fn scale_shared( - &mut self, - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - row: &PreparedMoeRow, - activation: &DeviceBuffer<'_>, - cache: &mut MoeWeightCache<'_>, - (scope, origin): (&DownScope<'ctx>, &Rc), - ) -> Result<()> { + fn scale_shared(&mut self, tail: RowTail<'_, 'ctx, '_>, cache: &mut MoeWeightCache<'_>) -> Result<()> { + let RowTail { context, binding, row, activation, scope, origin } = tail; let selection = MoeExpertSelection::Shared; self.shared = Some( @@ -67,25 +72,18 @@ impl<'ctx> SharedOwners<'ctx> { } } -#[allow(clippy::too_many_arguments)] pub(super) fn finish_shared_with<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - row: &PreparedMoeRow, - activation: &DeviceBuffer<'_>, + tail: RowTail<'_, 'ctx, '_>, cache: &mut MoeWeightCache<'_>, - scope: &DownScope<'ctx>, - origin: &Rc, combine: impl FnOnce(&DeviceBuffer<'_>, &super::super::moe_down::ScaledDown<'_>) -> Result>, ) -> Result> { + let (row, scope) = (tail.row, tail.scope); #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if crate::qwen_forward::layer0_mmq_observation::enabled() { crate::qwen_forward::layer0_mmq_observation::row(row.route.identity().position().get())?; } let mut owners = SharedOwners::default(); - let operation = owners - .scale_shared(context, binding, row, activation, cache, (scope, origin)) - .and_then(|()| owners.combine_with(row, scope, combine)); + let operation = owners.scale_shared(tail, cache).and_then(|()| owners.combine_with(row, scope, combine)); scope.record(&operation); let cleanup = owners.close_all(); operation.and_then(|values| cleanup.map(|()| values)) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs index 01d8aed1..95523aae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs @@ -1,8 +1,17 @@ //! Moved out of the parent module by STRA-338: impl PreparedMoeRow, impl MoeExpertStage, fn grouped_pairs. +use super::bound_rows_fn::DirectPacketInputs; #[allow(unused_imports)] use super::*; +/// The FFN rows of one chunk layer together with the binding they were sealed against. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ChunkFfnLayer<'a> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) layer: LayerId, + pub(in crate::qwen_forward) rows: &'a [ChunkFfnRow], +} + impl PreparedMoeRow { pub(in crate::qwen_forward) fn validate( &self, @@ -57,13 +66,12 @@ impl MoeExpertStage { Ok(row) } pub(in crate::qwen_forward) fn execute_chunk<'ctx>( - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + ffn: ChunkFfnLayer<'_>, chunk: &mut QwenChunkTxn<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { + let ChunkFfnLayer { layer, rows, .. } = ffn; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); @@ -75,22 +83,20 @@ impl MoeExpertStage { } if use_direct_packets(cache) { return chunk.batch_outputs_ffn(layer, rows, |actual, context| { - execute_bound_unprompted(context, binding, rows, cache, cancelled, Some(actual)) + execute_bound_unprompted(context, ffn, cache, cancelled, Some(actual)) }); } - chunk.batch_outputs(|context| execute_bound_unprompted(context, binding, rows, cache, cancelled, None)) + chunk.batch_outputs(|context| execute_bound_unprompted(context, ffn, cache, cancelled, None)) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn execute_chunk_native_prompt<'ctx>( - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + ffn: ChunkFfnLayer<'_>, chunk: &mut QwenChunkTxn<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - products: &mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>, - dense: &super::super::super::dense_weight_cache::DenseWeightCache<'_>, + finish: prompt_finish::NativePromptFinish<'_, 'ctx, '_>, ) -> Result> { + let ChunkFfnLayer { layer, rows, .. } = ffn; if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) || !use_direct_packets(cache) { return Err(Error::IdentityMismatch); } @@ -98,37 +104,27 @@ impl MoeExpertStage { chunk.validate_ffn_row(chunk.micro_row_index(index)?, layer, row)?; } chunk.batch_outputs_ffn(layer, rows, |actual, context| { - execute_bound( - context, - binding, - rows, - cache, - cancelled, - Some(actual), - Some(prompt_finish::NativePromptFinish { products, dense }), - ) + let direct = DirectPacketInputs { actual: Some(actual), native: Some(finish) }; + execute_bound(context, ffn, cache, cancelled, direct) }) } } /// `execute_bound` of the ordinary chunk path: no native prompt finish. fn execute_bound_unprompted<'ctx>( context: &Context<'_>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], + ffn: ChunkFfnLayer<'_>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, actual: Option<&QwenChunkTxn<'_, 'ctx>>, ) -> Result> { - execute_bound( - context, - binding, - rows, - cache, - cancelled, + let direct = DirectPacketInputs { actual, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - None, - ) + native: None, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + marker: std::marker::PhantomData, + }; + execute_bound(context, ffn, cache, cancelled, direct) } // Actual Strata counts/offsets algorithm, with per-row uniqueness and a checked // inverse mapping. Private route producers are the only production input. pub(super) fn grouped_pairs(ids: &[[u32; K]]) -> Result>> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs index 9a0dd709..bcdb3042 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs @@ -1,19 +1,18 @@ //! Moved out of the parent module by STRA-338: fn ordered_down_refusal, fn use_direct_packets, fn //! validate_packet_pairs, fn execute_direct_packets, fn finish_shared, fn use_shared_tail .... -#[allow(unused_imports)] -use super::direct_packets_fns::PacketRun; +use super::finish_shared_with_fn::RowTail; +use super::project_group_direct_fn::{DownProjection, RefusalReplay}; use super::*; pub(super) fn ordered_down_refusal( context: &Context<'_>, - kind: MoeMatrixKind, - matrix: CachedMoeMatrix<'_, '_>, - hidden: &[f32], - selections: &[DownSelection], + projection: DownProjection<'_>, + replay: RefusalReplay<'_>, scope: &DownScope<'_>, cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { + let RefusalReplay { hidden_values: hidden, selections } = replay; if hidden.len() != selections.len() * FF { return Err(Error::IdentityMismatch); } @@ -21,7 +20,7 @@ pub(super) fn ordered_down_refusal( if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - replay_selection(context, kind, matrix, values, *selection, scope)?; + replay_selection(context, projection, values, *selection, scope)?; } // A native failing status with every scalar column valid is an internal // inconsistency, never permission to publish candidate output. @@ -30,12 +29,12 @@ pub(super) fn ordered_down_refusal( /// One column of the ordered replay: upload its hidden values, project, and close both owners. fn replay_selection( context: &Context<'_>, - kind: MoeMatrixKind, - matrix: CachedMoeMatrix<'_, '_>, + projection: DownProjection<'_>, values: &[f32; FF], selection: DownSelection, scope: &DownScope<'_>, ) -> Result<()> { + let DownProjection { kind, matrix, .. } = projection; let activation = scope.upload(values)?; let result = scope .project(selection, |out| launch_cached_projection(context, kind, matrix, activation.buffer()?, out, N, FF)); @@ -64,14 +63,21 @@ pub(super) fn use_direct_packets(cache: &MoeWeightCache<'_>) -> bool { #[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] cache.uses_direct_native_down_packets() } +/// The chunk rows, the row/slot pairs of one expert group and each row's Down origin: what the validation of a +/// group's packets reads besides the binding and the packets themselves. +#[derive(Clone, Copy)] +pub(super) struct PacketGroupMembers<'a> { + pub(super) rows: &'a [ChunkFfnRow], + pub(super) pairs: &'a [Pair], + pub(super) origins: &'a [Rc], +} pub(super) fn validate_packet_pairs( actual: &QwenChunkTxn<'_, '_>, binding: &ModelBinding, - rows: &[ChunkFfnRow], - pairs: &[Pair], - origins: &[Rc], + members: PacketGroupMembers<'_>, packets: &[ActualSlotPacket<'_>], ) -> Result<()> { + let PacketGroupMembers { rows, pairs, origins } = members; if !(1..=64).contains(&pairs.len()) || packets.len() != rows.len() || origins.len() != rows.len() { return Err(Error::IdentityMismatch); } @@ -79,7 +85,7 @@ pub(super) fn validate_packet_pairs( return Err(Error::IdentityMismatch); } for pair in pairs { - validate_pair(actual, binding, rows, pair, origins, packets)?; + validate_pair(actual, binding, members, pair, packets)?; } Ok(()) } @@ -87,11 +93,11 @@ pub(super) fn validate_packet_pairs( fn validate_pair( actual: &QwenChunkTxn<'_, '_>, binding: &ModelBinding, - rows: &[ChunkFfnRow], + members: PacketGroupMembers<'_>, pair: &Pair, - origins: &[Rc], packets: &[ActualSlotPacket<'_>], ) -> Result<()> { + let PacketGroupMembers { rows, origins, .. } = members; if pair.row >= rows.len() || pair.slot >= K { return Err(Error::IdentityMismatch); } @@ -101,38 +107,6 @@ fn validate_pair( row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; packets[pair.row].validate(&origins[pair.row], binding, identity) } -#[allow(clippy::too_many_arguments)] -pub(super) fn execute_direct_packets<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - groups: &[Vec], - cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], - activations: &[TransportBuffer<'ctx>], - scope: &DownScope<'ctx>, - origins: &[Rc], - cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, 'ctx>, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< - prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, -) -> Result> { - let run = PacketRun { - context, - binding, - rows, - scope, - origins, - activations, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - native, - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - marker: std::marker::PhantomData, - }; - run.execute(groups, cache, prepared, cancelled, actual) -} - /// Close every packet; the first failure is kept and every packet is closed. pub(super) fn close_packets(packets: Vec>) -> Result<()> { let mut cleanup = Ok(()); @@ -144,25 +118,16 @@ pub(super) fn close_packets(packets: Vec>) -> Result<()> { } cleanup } -#[allow(clippy::too_many_arguments)] pub(super) fn finish_shared<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - row: &PreparedMoeRow, - activation: &DeviceBuffer<'_>, + tail: RowTail<'_, 'ctx, '_>, cache: &mut MoeWeightCache<'_>, - scope: &DownScope<'ctx>, - origin: &Rc, packed: &PackedDown<'ctx>, ) -> Result> { + let scope = tail.scope; if use_shared_tail(cache) { - return packed.with_completed(scope, |packet| { - finish_shared_queued(context, binding, row, activation, cache, scope, origin, packet) - }); + return packed.with_completed(scope, |packet| finish_shared_queued(tail, cache, packet)); } - finish_shared_with(context, binding, row, activation, cache, scope, origin, |weights, scaled| { - packed.combine(scope, weights, scaled) - }) + finish_shared_with(tail, cache, |weights, scaled| packed.combine(scope, weights, scaled)) } // Existing capture providers require their original intermediate readbacks. // Their reference path is retained rather than emitting incomplete observations. @@ -173,17 +138,12 @@ pub(super) fn use_shared_tail(cache: &MoeWeightCache<'_>) -> bool { } cache.has_target_shared_tail() } -#[allow(clippy::too_many_arguments)] pub(super) fn finish_shared_queued( - context: &Context<'_>, - binding: &ModelBinding, - row: &PreparedMoeRow, - activation: &DeviceBuffer<'_>, + tail: RowTail<'_, '_, '_>, cache: &mut MoeWeightCache<'_>, - scope: &DownScope<'_>, - origin: &Rc, packet: &DeviceBuffer<'_>, ) -> Result> { + let RowTail { context, binding, row, activation, scope, origin } = tail; let identity = row.route.identity(); row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; if !origin.binding.matches(&binding.identity()) || origin.identity != identity { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs index bac01e2a..f89317ba 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs @@ -18,7 +18,7 @@ pub(super) fn project_group_direct<'ctx>( cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, '_>, ) -> Result<()> { - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; + validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?; let first = pairs[0]; let weights = &rows[first.row].row().weights; let selection = MoeExpertSelection::Routed { slot: first.slot }; @@ -33,23 +33,23 @@ pub(super) fn project_group_direct<'ctx>( /// The Down matrix of a group: its kind, the routed format it is stored in and the cached matrix itself. #[derive(Clone, Copy)] -struct DownProjection<'a> { - kind: MoeMatrixKind, - format: RoutedFormat, - matrix: CachedMoeMatrix<'a, 'a>, +pub(super) struct DownProjection<'a> { + pub(super) kind: MoeMatrixKind, + pub(super) format: RoutedFormat, + pub(super) matrix: CachedMoeMatrix<'a, 'a>, } /// The chunk transaction, the slot packets a group fills and the cancellation poll of one direct run. -struct DirectRun<'a, 'session, 'driver, 'ctx, C> { - actual: &'a QwenChunkTxn<'session, 'driver>, - packets: &'a mut [ActualSlotPacket<'ctx>], - cancelled: &'a mut C, +pub(super) struct DirectRun<'a, 'session, 'driver, 'ctx, C> { + pub(super) actual: &'a QwenChunkTxn<'session, 'driver>, + pub(super) packets: &'a mut [ActualSlotPacket<'ctx>], + pub(super) cancelled: &'a mut C, } /// The transport buffers a direct group allocates in turn: Gate, Up and the activated hidden rows. #[derive(Default)] -struct GroupBuffers<'ctx> { - gate: Option>, - up: Option>, - hidden: Option>, +pub(super) struct GroupBuffers<'ctx> { + pub(super) gate: Option>, + pub(super) up: Option>, + pub(super) hidden: Option>, } /// The activated hidden rows of a group: the device transport buffer and its finite host copy. struct SwigluHidden<'a, 'ctx> { @@ -57,15 +57,15 @@ struct SwigluHidden<'a, 'ctx> { values: &'a [f32], } /// The device buffers of one grouped Down launch: the hidden activations read and the output written. -struct DownBuffers<'a, 'ctx> { - input: &'a DeviceBuffer<'ctx>, - out: &'a mut DeviceBuffer<'ctx>, +pub(super) struct DownBuffers<'a, 'ctx> { + pub(super) input: &'a DeviceBuffer<'ctx>, + pub(super) out: &'a mut DeviceBuffer<'ctx>, } /// What the ordered replay of a numerical Q8 refusal reads: the finite hidden values and the Down selections. #[derive(Clone, Copy)] -struct RefusalReplay<'a> { - hidden_values: &'a [f32], - selections: &'a [DownSelection], +pub(super) struct RefusalReplay<'a> { + pub(super) hidden_values: &'a [f32], + pub(super) selections: &'a [DownSelection], } /// The identity of one direct group: one expert, its row/slot pairs and the actual row origins. @@ -192,14 +192,11 @@ impl<'a, 'ctx> DirectGroup<'a, 'ctx> { replay: RefusalReplay<'_>, cancel: &mut impl FnMut() -> bool, ) -> Result<()> { - let DownProjection { kind, format, matrix } = projection; + let DownProjection { format, matrix, .. } = projection; let DownBuffers { input, out } = buffers; - let RefusalReplay { hidden_values, selections } = replay; let columns = DownColumns { total: self.pairs.len(), format }; let result = launch_down_plain(self.context, matrix, input, out, columns)?; - down_outcome(result, || { - ordered_down_refusal(self.context, kind, matrix, hidden_values, selections, self.scope, cancel) - }) + down_outcome(result, || ordered_down_refusal(self.context, projection, replay, self.scope, cancel)) } /// Private grouping has one pair per actual row, in ascending row order. Validate all row origins before @@ -212,7 +209,8 @@ impl<'a, 'ctx> DirectGroup<'a, 'ctx> { cancel: &mut impl FnMut() -> bool, ) -> Result<()> { let (context, binding, pairs) = (self.context, self.binding, self.pairs); - validate_packet_pairs(actual, binding, self.rows, pairs, self.origins, packets)?; + let members = PacketGroupMembers { rows: self.rows, pairs, origins: self.origins }; + validate_packet_pairs(actual, binding, members, packets)?; let mut targets = packet_targets(pairs, packets)?; super::super::moe_down::ResidentPackedDown::copy_group_with(self.scope, &mut targets, |copies| { context.copy_routed_down_columns_to_slots(source, pairs.len(), copies).map_err(driver_error)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs index 2ecb0bbe..4f9be91e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338: fn project_group. +use super::project_group_direct_fn::{DownProjection, GroupBuffers, RefusalReplay}; #[allow(unused_imports)] use super::project_group_shared_fns::{ check_group_descriptors, close_group_buffers, down_kind_format, down_outcome, gate_up_format, gate_up_plain, @@ -7,29 +8,34 @@ use super::project_group_shared_fns::{ }; use super::*; -#[allow(clippy::too_many_arguments)] +/// One expert's row/slot pairs against the chunk rows, the Down scope and the Down origin of every row. +#[derive(Clone, Copy)] +pub(super) struct ExpertGroup<'a, 'ctx> { + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) rows: &'a [ChunkFfnRow], + pub(super) pairs: &'a [Pair], + pub(super) scope: &'a DownScope<'ctx>, + pub(super) origins: &'a [Rc], +} + pub(super) fn project_group<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - pairs: &[Pair], + group: ExpertGroup<'_, 'ctx>, cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, - origins: &[Rc], down: &mut [[Option>; K]], cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { + let ExpertGroup { context, binding, rows, pairs, scope, origins } = group; let first = pairs[0]; let weights = &rows[first.row].row().weights; let selection = MoeExpertSelection::Routed { slot: first.slot }; check_group_descriptors(binding, rows, pairs, weights, selection)?; - let group = ResidentGroup { context, binding, pairs, scope, origins, weights, selection }; - let mut gate = None; - let mut up = None; - let mut hidden = None; - let operation = group.run(cache, prepared, down, cancelled, &mut gate, &mut up, &mut hidden); + let resident = ResidentGroup { context, binding, pairs, scope, origins, weights, selection }; + let mut buffers = GroupBuffers::default(); + let operation = resident.run(cache, prepared, ResidentRun { down, cancelled }, &mut buffers); scope.record(&operation); + let GroupBuffers { gate, up, hidden } = buffers; operation.and(close_group_buffers(hidden, up, gate)) } @@ -45,24 +51,35 @@ struct ResidentGroup<'a, 'ctx> { selection: MoeExpertSelection, } +/// The Down output cells a resident group fills and the cancellation poll of its run. +struct ResidentRun<'a, 'ctx, C> { + down: &'a mut [[Option>; K]], + cancelled: &'a mut C, +} + +/// The activated hidden rows of a resident group: the device buffer and, unless the adaptive path only checks +/// finiteness on the device, the finite host copy. +struct ResidentHidden<'a, 'ctx> { + buffer: &'a Option>, + values: &'a Option>, +} + impl<'a, 'ctx> ResidentGroup<'a, 'ctx> { - #[allow(clippy::too_many_arguments)] fn run( &self, cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - down: &mut [[Option>; K]], - cancelled: &mut impl FnMut() -> bool, - gate: &mut Option>, - up: &mut Option>, - hidden: &mut Option>, + run: ResidentRun<'_, 'ctx, impl FnMut() -> bool>, + buffers: &mut GroupBuffers<'ctx>, ) -> Result<()> { - self.project_gate_up(cache, prepared, cancelled, gate, up)?; + let ResidentRun { down, cancelled } = run; + self.project_gate_up(cache, prepared, cancelled, buffers)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let hidden_values = self.swiglu_hidden(cache, gate, up, hidden)?; - self.project_down(cache, down, cancelled, hidden, &hidden_values) + let hidden_values = self.swiglu_hidden(cache, &buffers.gate, &buffers.up, &mut buffers.hidden)?; + let hidden = ResidentHidden { buffer: &buffers.hidden, values: &hidden_values }; + self.project_down(cache, down, cancelled, hidden) } fn project_gate_up( @@ -70,9 +87,9 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> { cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - gate: &mut Option>, - up: &mut Option>, + buffers: &mut GroupBuffers<'ctx>, ) -> Result<()> { + let (gate, up) = (&mut buffers.gate, &mut buffers.up); let refs = prepared_refs(self.pairs, prepared)?; for (role, output) in [(MoeMatrixRole::Gate, gate), (MoeMatrixRole::Up, up)] { if cancelled() { @@ -174,9 +191,9 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> { cache: &mut MoeWeightCache<'_>, down: &mut [[Option>; K]], cancelled: &mut impl FnMut() -> bool, - hidden: &Option>, - hidden_values: &Option>, + hidden: ResidentHidden<'_, 'ctx>, ) -> Result<()> { + let ResidentHidden { buffer: hidden, values: hidden_values } = hidden; let (binding, pairs, scope, selection) = (self.binding, self.pairs, self.scope, self.selection); let (kind, format) = down_kind_format(self.weights, selection)?; let selections = self.free_selections(down)?; @@ -244,8 +261,10 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> { scope.with_workspace(|workspace| { let result = launch_down_in_workspace(workspace, matrix, args.input, out, pairs.len(), args.format)?; down_outcome(result, || { - let actual_values = args.refusal_values(pairs.len())?; - ordered_down_refusal(context, args.kind, matrix, &actual_values, args.selections, scope, cancel) + let hidden_values = args.refusal_values(pairs.len())?; + let projection = DownProjection { kind: args.kind, format: args.format, matrix }; + let replay = RefusalReplay { hidden_values: &hidden_values, selections: args.selections }; + ordered_down_refusal(context, projection, replay, scope, cancel) }) }) } @@ -264,8 +283,10 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> { let columns = DownColumns { total: pairs.len(), format: args.format }; let result = launch_down_plain(context, matrix, args.input, out, columns)?; down_outcome(result, || { - let actual_values = args.refusal_values(pairs.len())?; - ordered_down_refusal(context, args.kind, matrix, &actual_values, args.selections, scope, cancel) + let hidden_values = args.refusal_values(pairs.len())?; + let projection = DownProjection { kind: args.kind, format: args.format, matrix }; + let replay = RefusalReplay { hidden_values: &hidden_values, selections: args.selections }; + ordered_down_refusal(context, projection, replay, scope, cancel) }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs index cb2dcd07..0dbab9fd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs @@ -1,7 +1,9 @@ //! Moved out of the parent module by STRA-338: fn project_group_source_consumers. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -use super::project_group_direct_fn::DirectGroup; +use super::project_group_direct_fn::{ + DirectGroup, DirectRun, DownBuffers, DownProjection, GroupBuffers, RefusalReplay, +}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::project_group_shared_fns::{ close_group_buffers, down_kind_format, down_outcome, gate_up_format, hidden_buffer, launch_down_in_workspace, @@ -14,35 +16,54 @@ use crate::model_binding::qwen4exp_input::MoeRoutedSourceScope; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use crate::qwen_forward::moe_weight_cache::RoutedSourceHealth; +/// The weight cache and the opened routed-source scope the matrices of one source-backed group are read through. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +struct SourceMatrices<'a, 'cache, 'src, 'file> { + cache: &'a mut MoeWeightCache<'cache>, + source: &'a mut MoeRoutedSourceScope<'src, 'file>, +} + +/// The grouped output of one Gate or Up role, its stored format and the finite stage that completes it. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +struct GateUpTarget<'a, 'ctx> { + grouped: &'a mut TransportBuffer<'ctx>, + format: RoutedFormat, + stage: leleka_cuda_driver::RoutedFiniteStage, +} + +/// One source-backed Down launch: the actor workspace it runs in, the Down matrix and the per-pair selections. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +struct SourceDownLaunch<'a, 'ctx> { + workspace: &'a mut leleka_cuda_driver::RoutedGroupWorkspace<'ctx>, + projection: DownProjection<'a>, + selections: &'a [DownSelection], +} + +/// What ends the source scope after the last private consumer: the cache health and the opened source itself. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +struct SourceTail<'a, 'ctx, 'src, 'file> { + health: &'a RoutedSourceHealth<'a, 'ctx>, + source: &'a mut MoeRoutedSourceScope<'src, 'file>, +} + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[allow(clippy::too_many_arguments)] pub(super) fn project_group_source_consumers<'ctx>( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - pairs: &[Pair], + group: DirectGroup<'_, 'ctx>, cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, - origins: &[Rc], - packets: &mut [ActualSlotPacket<'ctx>], - cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, + run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>, source: &mut MoeRoutedSourceScope<'_, '_>, ) -> Result<()> { - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - let first = pairs[0]; - let weights = &rows[first.row].row().weights; - let selection = MoeExpertSelection::Routed { slot: first.slot }; + let DirectGroup { binding, rows, pairs, scope, origins, .. } = group; + let DirectRun { actual, packets, cancelled } = run; + validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?; source.validate_binding(binding).map_err(binding_error)?; check_source_members(source, pairs.len())?; - let group = DirectGroup { context, binding, rows, pairs, scope, origins, weights, selection }; - let mut gate = None; - let mut up = None; - let mut hidden = None; - let operation = - group.run_source(cache, prepared, actual, packets, cancelled, source, &mut gate, &mut up, &mut hidden); + let mut buffers = GroupBuffers::default(); + let matrices = SourceMatrices { cache, source }; + let operation = group.run_source(matrices, prepared, DirectRun { actual, packets, cancelled }, &mut buffers); scope.record(&operation); + let GroupBuffers { gate, up, hidden } = buffers; operation.and(close_group_buffers(hidden, up, gate)) } @@ -63,37 +84,31 @@ pub(super) fn check_source_members(source: &mut MoeRoutedSourceScope<'_, '_>, me #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> DirectGroup<'_, 'ctx> { - #[allow(clippy::too_many_arguments)] fn run_source( &self, - cache: &mut MoeWeightCache<'_>, + mut matrices: SourceMatrices<'_, '_, '_, '_>, prepared: &[RoutedGateUpQ8<'_>], - actual: &QwenChunkTxn<'_, '_>, - packets: &mut [ActualSlotPacket<'ctx>], - cancelled: &mut impl FnMut() -> bool, - source: &mut MoeRoutedSourceScope<'_, '_>, - gate: &mut Option>, - up: &mut Option>, - hidden: &mut Option>, + run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>, + buffers: &mut GroupBuffers<'ctx>, ) -> Result<()> { - self.source_gate_up(cache, prepared, cancelled, source, gate, up)?; + let DirectRun { actual, packets, cancelled } = run; + self.source_gate_up(&mut matrices, prepared, cancelled, buffers)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - self.source_swiglu(gate, up, hidden)?; - self.source_down(cache, actual, packets, cancelled, source, hidden) + self.source_swiglu(buffers)?; + self.source_down(&mut matrices, DirectRun { actual, packets, cancelled }, &buffers.hidden) } fn source_gate_up( &self, - cache: &mut MoeWeightCache<'_>, + matrices: &mut SourceMatrices<'_, '_, '_, '_>, prepared: &[RoutedGateUpQ8<'_>], cancelled: &mut impl FnMut() -> bool, - source: &mut MoeRoutedSourceScope<'_, '_>, - gate: &mut Option>, - up: &mut Option>, + buffers: &mut GroupBuffers<'ctx>, ) -> Result<()> { let (pairs, scope) = (self.pairs, self.scope); + let (gate, up) = (&mut buffers.gate, &mut buffers.up); let refs = prepared_refs(pairs, prepared)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); @@ -107,18 +122,18 @@ impl<'ctx> DirectGroup<'_, 'ctx> { let mut columns = workspace.begin_columns(&refs); // Same full Gate completion precedes every Up operation. let stage = leleka_cuda_driver::RoutedFiniteStage::Gate; - self.source_gate_up_role(cache, source, &mut columns, MoeMatrixRole::Gate, grouped, format, stage)?; + let target = GateUpTarget { grouped, format, stage }; + self.source_gate_up_role(matrices, &mut columns, MoeMatrixRole::Gate, target)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - self.source_up(cache, source, &mut columns, up) + self.source_up(matrices, &mut columns, up) }) } fn source_up( &self, - cache: &mut MoeWeightCache<'_>, - source: &mut MoeRoutedSourceScope<'_, '_>, + matrices: &mut SourceMatrices<'_, '_, '_, '_>, columns: &mut leleka_cuda_driver::RoutedColumnsLoan<'_, '_, '_, 'ctx>, up: &mut Option>, ) -> Result<()> { @@ -127,21 +142,18 @@ impl<'ctx> DirectGroup<'_, 'ctx> { let grouped = up.as_mut().ok_or(Error::IdentityMismatch)?; // Same full Up completion precedes SwiGLU and Down reuse. let stage = leleka_cuda_driver::RoutedFiniteStage::Up; - self.source_gate_up_role(cache, source, columns, MoeMatrixRole::Up, grouped, format, stage) + self.source_gate_up_role(matrices, columns, MoeMatrixRole::Up, GateUpTarget { grouped, format, stage }) } - #[allow(clippy::too_many_arguments)] fn source_gate_up_role( &self, - cache: &mut MoeWeightCache<'_>, - source: &mut MoeRoutedSourceScope<'_, '_>, + matrices: &mut SourceMatrices<'_, '_, '_, '_>, columns: &mut leleka_cuda_driver::RoutedColumnsLoan<'_, '_, '_, 'ctx>, role: MoeMatrixRole, - grouped: &mut TransportBuffer<'ctx>, - format: RoutedFormat, - stage: leleka_cuda_driver::RoutedFiniteStage, + target: GateUpTarget<'_, 'ctx>, ) -> Result<()> { - cache.with_matrix_routed_source(self.binding, source, 0, role, |matrix, _, _| { + let GateUpTarget { grouped, format, stage } = target; + matrices.cache.with_matrix_routed_source(self.binding, matrices.source, 0, role, |matrix, _, _| { match matrix { CachedMoeMatrix::Raw(raw) => columns.project_gate_up(raw, grouped.buffer_mut()?, format), CachedMoeMatrix::Dual(actual, owner) => { @@ -157,12 +169,8 @@ impl<'ctx> DirectGroup<'_, 'ctx> { }) } - fn source_swiglu( - &self, - gate: &Option>, - up: &Option>, - hidden: &mut Option>, - ) -> Result<()> { + fn source_swiglu(&self, buffers: &mut GroupBuffers<'ctx>) -> Result<()> { + let (gate, up, hidden) = (&buffers.gate, &buffers.up, &mut buffers.hidden); swiglu_into_hidden(self.context, self.scope, gate, up, hidden, self.pairs.len())?; let stage = leleka_cuda_driver::RoutedFiniteStage::Hidden; self.scope.finite_stage(hidden_buffer(hidden)?, stage, self.pairs.len()) @@ -170,54 +178,76 @@ impl<'ctx> DirectGroup<'_, 'ctx> { fn source_down( &self, - cache: &mut MoeWeightCache<'_>, - actual: &QwenChunkTxn<'_, '_>, - packets: &mut [ActualSlotPacket<'ctx>], - cancelled: &mut impl FnMut() -> bool, - source: &mut MoeRoutedSourceScope<'_, '_>, + matrices: &mut SourceMatrices<'_, '_, '_, '_>, + run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>, hidden: &Option>, ) -> Result<()> { - let (binding, pairs, scope) = (self.binding, self.pairs, self.scope); + let DirectRun { actual, packets, cancelled } = run; + let (binding, scope) = (self.binding, self.scope); let (kind, format) = down_kind_format(self.weights, self.selection)?; let selections = self.packet_selections(packets)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } scope.with_workspace(|workspace| { - cache.with_matrix_routed_source(binding, source, 0, MoeMatrixRole::Down, |matrix, health, source| { - scope.project_columns_direct( - &selections, - |out, cancel| { - let input = hidden_buffer(hidden)?; - self.source_down_columns(workspace, matrix, kind, format, input, out, &selections, cancel) - }, - |down_source, cancel| self.source_copy_down(actual, packets, health, source, down_source, cancel), - cancelled, - ) - }) + matrices.cache.with_matrix_routed_source( + binding, + matrices.source, + 0, + MoeMatrixRole::Down, + |matrix, health, source| { + let projection = DownProjection { kind, format, matrix }; + let launch = SourceDownLaunch { workspace, projection, selections: &selections }; + let run = DirectRun { actual, packets: &mut *packets, cancelled: &mut *cancelled }; + self.project_source_down(launch, SourceTail { health, source }, hidden, run) + }, + ) })?; Ok(()) } + /// The grouped Down projection of a source-backed group, then the copy of its columns into the row packets. + fn project_source_down( + &self, + launch: SourceDownLaunch<'_, 'ctx>, + tail: SourceTail<'_, '_, '_, '_>, + hidden: &Option>, + run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>, + ) -> Result<()> { + let SourceDownLaunch { workspace, projection, selections } = launch; + let DirectRun { actual, packets, cancelled } = run; + self.scope.project_columns_direct( + selections, + |out, cancel| { + let input = hidden_buffer(hidden)?; + let launch = SourceDownLaunch { workspace: &mut *workspace, projection, selections }; + self.source_down_columns(launch, DownBuffers { input, out }, cancel) + }, + |down_source, cancel| { + let copy_run = DirectRun { actual, packets: &mut *packets, cancelled: cancel }; + self.source_copy_down(copy_run, tail, down_source) + }, + cancelled, + ) + } + /// Only the numerical refusal needs host values. The unchanged full Hidden download observes the same alive /// allocation, then original ascending-row arbitration runs. - #[allow(clippy::too_many_arguments)] fn source_down_columns( &self, - workspace: &mut leleka_cuda_driver::RoutedGroupWorkspace<'ctx>, - matrix: CachedMoeMatrix<'_, '_>, - kind: MoeMatrixKind, - format: RoutedFormat, - input: &DeviceBuffer<'ctx>, - out: &mut DeviceBuffer<'ctx>, - selections: &[DownSelection], + launch: SourceDownLaunch<'_, 'ctx>, + buffers: DownBuffers<'_, 'ctx>, cancel: &mut impl FnMut() -> bool, ) -> Result<()> { + let SourceDownLaunch { workspace, projection, selections } = launch; + let DownProjection { format, matrix, .. } = projection; + let DownBuffers { input, out } = buffers; let pairs = self.pairs; let result = launch_down_in_workspace(workspace, matrix, input, out, pairs.len(), format)?; down_outcome(result, || { let hidden_values = download_f32(input, pairs.len() * FF)?; - ordered_down_refusal(self.context, kind, matrix, &hidden_values, selections, self.scope, cancel) + let replay = RefusalReplay { hidden_values: &hidden_values, selections }; + ordered_down_refusal(self.context, projection, replay, self.scope, cancel) }) } @@ -226,15 +256,15 @@ impl<'ctx> DirectGroup<'_, 'ctx> { /// coverage or group acceptance; failure discards all copied private packets. fn source_copy_down( &self, - actual: &QwenChunkTxn<'_, '_>, - packets: &mut [ActualSlotPacket<'ctx>], - health: &RoutedSourceHealth<'_, '_>, - source: &mut MoeRoutedSourceScope<'_, '_>, + run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>, + tail: SourceTail<'_, '_, '_, '_>, down_source: &DeviceBuffer<'ctx>, - cancel: &mut impl FnMut() -> bool, ) -> Result<()> { + let DirectRun { actual, packets, cancelled: cancel } = run; + let SourceTail { health, source } = tail; let (context, binding, pairs) = (self.context, self.binding, self.pairs); - validate_packet_pairs(actual, binding, self.rows, pairs, self.origins, packets)?; + let members = PacketGroupMembers { rows: self.rows, pairs, origins: self.origins }; + validate_packet_pairs(actual, binding, members, packets)?; let mut targets = packet_targets(pairs, packets)?; super::super::moe_down::ResidentPackedDown::copy_group_with(self.scope, &mut targets, |copies| { context.copy_routed_down_columns_to_slots(down_source, pairs.len(), copies).map_err(driver_error)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs index 8f6cb017..6e17c01a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs @@ -1,5 +1,9 @@ //! Moved out of the parent module by STRA-338: fn project_group_source_fenced. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::direct_packets_fns::PacketRun; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::project_group_direct_fn::{DirectGroup, DirectRun}; #[allow(unused_imports)] use super::*; @@ -13,37 +17,49 @@ fn source_members<'a>(rows: &'a [ChunkFfnRow], pairs: &[Pair]) -> Result( - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - rows: &[ChunkFfnRow], - pairs: &[Pair], - cache: &mut MoeWeightCache<'_>, - prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, - origins: &[Rc], - packets: &mut [ActualSlotPacket<'ctx>], - cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, -) -> Result<()> { - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - cache.validate(binding, context)?; - if !cache.uses_direct_native_down_packets() { - return Err(Error::IdentityMismatch); +impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> { + /// One expert group of the layer batch, identified by its pairs, with the weights its first pair selects. + fn direct_group<'g>(&'g self, pairs: &'g [Pair]) -> DirectGroup<'g, 'ctx> { + let first = pairs[0]; + let weights = &self.rows[first.row].row().weights; + let selection = MoeExpertSelection::Routed { slot: first.slot }; + DirectGroup { + context: self.context, + binding: self.binding, + rows: self.rows, + pairs, + scope: self.scope, + origins: self.origins, + weights, + selection, + } + } + + /// The source callback keeps the actual artifact RefMut for all descriptor + /// and cold-read consumers. Its mapped-error bridge preserves runtime + /// primary failures while still attempting the mandatory source finish. + /// The real cache is rechecked after the matrix loan and source loan have ended; + /// private packets still belong to `PacketRun::execute` on any failure. + pub(super) fn project_group_fenced( + &self, + pairs: &[Pair], + cache: &mut MoeWeightCache<'_>, + run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>, + ) -> Result<()> { + let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins); + let DirectRun { actual, packets, cancelled } = run; + validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?; + cache.validate(binding, context)?; + if !cache.uses_direct_native_down_packets() { + return Err(Error::IdentityMismatch); + } + let members = source_members(rows, pairs)?; + let operation = binding.with_moe_routed_source(&members, binding_error, |source| { + let consumers = DirectRun { actual, packets: &mut *packets, cancelled: &mut *cancelled }; + project_group_source_consumers(self.direct_group(pairs), cache, self.prepared, consumers, source) + }); + let health_check = cache.validate(binding, context); + operation.and(health_check) } - let members = source_members(rows, pairs)?; - let operation = binding.with_moe_routed_source(&members, binding_error, |source| { - project_group_source_consumers( - context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, source, - ) - }); - let health_check = cache.validate(binding, context); - operation.and(health_check) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs index d7e0fb6a..1137e4dc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs @@ -50,13 +50,13 @@ struct DirectRun { words: usize, } /// The loaded direct-Down inputs of one fresh session; every arm is run against the same snapshot. -struct LoadedArms<'a, 'k, 'ctx> { - binding: &'a ModelBinding, - context: &'a Rc>, - session: &'a mut QwenSession<'ctx>, - kar: &'a mut KarPleCache<'k>, - cache: &'a mut MoeWeightCache<'ctx>, - dense: &'a DenseWeightCache<'ctx>, +pub(crate) struct LoadedArms<'a, 'k, 'ctx> { + pub(crate) binding: &'a ModelBinding, + pub(crate) context: &'a Rc>, + pub(crate) session: &'a mut QwenSession<'ctx>, + pub(crate) kar: &'a mut KarPleCache<'k>, + pub(crate) cache: &'a mut MoeWeightCache<'ctx>, + pub(crate) dense: &'a DenseWeightCache<'ctx>, } #[path = "moe_group_down_direct_gpu/policy_fn.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/arm_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/arm_fn.rs index e28fcdc2..e62ae7f6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/arm_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/arm_fn.rs @@ -3,26 +3,21 @@ #[allow(unused_imports)] use super::*; -#[allow(clippy::too_many_arguments)] pub(super) fn arm<'ctx>( - binding: &ModelBinding, - context: &Rc>, - session: &mut QwenSession<'ctx>, - kar: &mut KarPleCache<'_>, - cache: &mut MoeWeightCache<'ctx>, - dense: &DenseWeightCache<'ctx>, + arms: &mut LoadedArms<'_, '_, 'ctx>, old: bool, cancel_after_copy: bool, ) -> Result { + let (binding, context, dense) = (arms.binding, arms.context, arms.dense); + let (session, kar, cache) = (&mut *arms.session, &mut *arms.kar, &mut *arms.cache); let observation = Observation::begin(old)?; let (layer, tokens) = arm_tokens()?; let transient = 3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK; cache.reserve_mmq_transient(binding, context, transient)?; let mut chunk = QwenChunkTxn::begin(session, binding, &tokens, None, 512 * 1024 * 1024)?; let rows = arm_chunk_rows(binding, kar, dense, layer, &mut chunk)?; - let values = MoeExpertStage::execute_chunk(binding, layer, &rows, &mut chunk, cache, &mut || { - cancel_probe(cancel_after_copy) - })?; + let ffn = ChunkFfnLayer { binding, layer, rows: &rows }; + let values = MoeExpertStage::execute_chunk(ffn, &mut chunk, cache, &mut || cancel_probe(cancel_after_copy))?; let packets = observation.take()?; // Completed layer0 FFN products remain private: no injection/head/all48 or // joint target publication. A canceled real chunk is dropped, not repaired. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/impl_loadedarms.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/impl_loadedarms.rs index 0909b500..c932072c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/impl_loadedarms.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu/impl_loadedarms.rs @@ -5,7 +5,7 @@ use super::*; impl LoadedArms<'_, '_, '_> { pub(super) fn arm(&mut self, old: bool, cancel_after_copy: bool) -> Result { - arm(self.binding, self.context, self.session, self.kar, self.cache, self.dense, old, cancel_after_copy) + arm(self, old, cancel_after_copy) } pub(super) fn matches_snapshot(&self, initial: &ResetReplaySnapshot) -> Result { Ok(initial.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding)?)) @@ -64,15 +64,8 @@ impl LoadedArms<'_, '_, '_> { impl QwenForward { /// ONE genuine loaded binding/fresh session. Every arm independently mints /// real three-row chunk/FFN proofs; canceled chunks are dropped unchanged. - pub(crate) fn test_direct_down_on_loaded<'ctx>( - binding: &ModelBinding, - context: &Rc>, - session: &mut QwenSession<'ctx>, - kar: &mut KarPleCache<'_>, - cache: &mut MoeWeightCache<'ctx>, - dense: &DenseWeightCache<'ctx>, - ) -> Result { - let mut arms = LoadedArms { binding, context, session, kar, cache, dense }; + pub(crate) fn test_direct_down_on_loaded<'ctx>(mut arms: LoadedArms<'_, '_, 'ctx>) -> Result { + let context = arms.context; let initial = arms.precheck()?; let mut run = arms.reference_and_candidate(&initial)?; let (cancelled_after_copy, reset_exact) = arms.cancel_and_recover(&initial, &mut run)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs index 0973e516..831855c8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs @@ -1,5 +1,5 @@ //! Closed original-kernel resident expert pipeline and genuine packet handoff. -use super::project_group_direct_fn::DirectGroup; +use super::project_group_direct_fn::{DirectGroup, DownProjection, RefusalReplay}; use super::project_group_shared_fns::{down_format, gate_up_format, packet_targets}; use super::project_group_source_consumers_fn::check_source_members; use super::*; @@ -20,7 +20,7 @@ pub(super) fn project_group_packets<'ctx>( actual: &QwenChunkTxn<'_, '_>, ephemeral_slot: Option, ) -> Result<()> { - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; + validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?; cache.validate(binding, context)?; if !uses_adaptive(cache) || !use_direct_packets(cache) { return Err(Error::IdentityMismatch); @@ -185,7 +185,9 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> { let values = download_f32(hidden.ok_or(Error::IdentityMismatch)?, self.group.pairs.len() * FF)?; let matrix = CachedMoeMatrix::Raw(down); let (context, scope) = (self.group.context, self.group.scope); - ordered_down_refusal(context, self.down_kind, matrix, &values, &self.selections, scope, observed_cancel) + let projection = DownProjection { kind: self.down_kind, format: self.down_format, matrix }; + let replay = RefusalReplay { hidden_values: &values, selections: &self.selections }; + ordered_down_refusal(context, projection, replay, scope, observed_cancel) } fn copy_down( @@ -199,7 +201,8 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> { ) -> Result<()> { let group = &self.group; let (context, binding, pairs) = (group.context, group.binding, group.pairs); - validate_packet_pairs(actual, binding, group.rows, pairs, group.origins, packets)?; + let members = PacketGroupMembers { rows: group.rows, pairs, origins: group.origins }; + validate_packet_pairs(actual, binding, members, packets)?; let mut targets = packet_targets(pairs, packets)?; super::super::moe_down::ResidentPackedDown::copy_group_with(group.scope, &mut targets, |copies| { context.copy_routed_down_columns_to_slots(down_source, pairs.len(), copies).map_err(driver_error)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs index 8db1b6d9..6c6885a7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs @@ -72,7 +72,7 @@ impl MoeExpertStage { ) -> Result<()> { let _arm = observation::arm(arm)?; let products = if arm == 0 { - Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)? + Self::execute_chunk(ChunkFfnLayer { binding, layer, rows }, chunk, cache, &mut || false)? } else { Self::execute_chunk_mmq(binding, layer, rows, chunk, cache, &mut || false)? }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index 78c8313f..91786425 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -1,6 +1,6 @@ //! Explicit experimental adaptive MMQ chunk producer. Native T1 stays native. //! Real sealed rows, one source/Q8 layer batch, real group leases, one slotpack. -use super::resident_slotpack::SlotPacks; +use super::resident_slotpack::{SealedLayer, SlotPacks}; use super::*; use leleka_cuda_driver::MmqWorkspace; #[path = "moe_mmq_chunk/admission_fns.rs"] @@ -144,12 +144,10 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> { let (binding, layer, rows) = (self.binding, self.layer, self.rows); #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(finish) = self.native { - let (products, dense) = (finish.products, finish.dense); - return MoeExpertStage::execute_chunk_native_prompt( - binding, layer, rows, chunk, cache, cancelled, products, dense, - ); + let ffn = ChunkFfnLayer { binding, layer, rows }; + return MoeExpertStage::execute_chunk_native_prompt(ffn, chunk, cache, cancelled, finish); } - let result = MoeExpertStage::execute_chunk(binding, layer, rows, chunk, cache, cancelled); + let result = MoeExpertStage::execute_chunk(ChunkFfnLayer { binding, layer, rows }, chunk, cache, cancelled); #[cfg(test)] if result.is_ok() { cache.note_test_mmq_dispatch(false, rows.len()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs index 6f3beaef..1632c758 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs @@ -158,7 +158,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> { ) -> Result> { let (inputs, ids) = self.gather_rows()?; let groups = grouped_pairs(&ids)?; - let mut packets = SlotPacks::new(self.txn, self.binding, self.layer, self.rows, self.context, scope)?; + let mut packets = SlotPacks::new(self.sealed_layer(), self.rows, self.context, scope)?; let mut activations = reserved(self.rows.len())?; let operation = self.operate( scope, @@ -177,6 +177,11 @@ impl<'ctx> Resident<'_, '_, 'ctx> { operation.and_then(|values| cleanup.map(|()| values)) } + /// The sealed transaction, binding and layer the window rows are validated against. + fn sealed_layer(&self) -> SealedLayer<'_, '_, 'ctx> { + SealedLayer { txn: self.txn, binding: self.binding, layer: self.layer } + } + fn gather_rows(&self) -> Result<(Vec, Vec<[u32; K]>)> { let mut inputs = reserved(self.rows.len().checked_mul(N).ok_or(Error::Overflow)?)?; let mut ids = reserved(self.rows.len())?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs index ca02b9b9..e3934ef6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs @@ -20,22 +20,25 @@ pub(super) struct SlotPacks<'source, 'session, 'ctx> { origins: Vec>, packets: Vec>, } -fn validate_row( - txn: &QwenChunkTxn<'_, '_>, - binding: &ModelBinding, - layer: LayerId, - index: usize, - row: &ChunkFfnRow, - origin: &Rc, -) -> Result<()> { - let global = txn.micro_row_index(index)?; - txn.validate_ffn_row(global, layer, row)?; - let (token, position) = txn.row_ids(global)?; - if !origin.binding.matches(&binding.identity()) || origin.identity != row.row().route.identity() { - return Err(Error::IdentityMismatch); +/// The sealed chunk transaction, the binding and the layer a window row is validated against. +#[derive(Clone, Copy)] +pub(super) struct SealedLayer<'a, 'session, 'ctx> { + pub(super) txn: &'a QwenChunkTxn<'session, 'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, +} +impl SealedLayer<'_, '_, '_> { + fn validate_row(&self, index: usize, row: &ChunkFfnRow, origin: &Rc) -> Result<()> { + let Self { txn, binding, layer } = *self; + let global = txn.micro_row_index(index)?; + txn.validate_ffn_row(global, layer, row)?; + let (token, position) = txn.row_ids(global)?; + if !origin.binding.matches(&binding.identity()) || origin.identity != row.row().route.identity() { + return Err(Error::IdentityMismatch); + } + origin.identity.validate(token, position, layer)?; + row.row().validate(&binding.identity(), token, position, layer) } - origin.identity.validate(token, position, layer)?; - row.row().validate(&binding.identity(), token, position, layer) } /// The sealed rows a group copy is validated against, borrowed apart from the mutable packet storage. struct RowsView<'a, 'session, 'ctx> { @@ -45,7 +48,7 @@ struct RowsView<'a, 'session, 'ctx> { rows: &'a [ChunkFfnRow], origins: &'a [Rc], } -impl RowsView<'_, '_, '_> { +impl<'a, 'session, 'ctx> RowsView<'a, 'session, 'ctx> { fn validate_group_columns(&self, group: &GroupOrigin) -> Result<()> { for (column, pair) in group.pairs.iter().enumerate() { let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?; @@ -54,10 +57,13 @@ impl RowsView<'_, '_, '_> { { return Err(Error::IdentityMismatch); } - validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?; + self.sealed().validate_row(pair.row, row, origin)?; } Ok(()) } + fn sealed(&self) -> SealedLayer<'a, 'session, 'ctx> { + SealedLayer { txn: self.txn, binding: self.binding, layer: self.layer } + } } /// The packets of the group rows, in ascending row order, each with the slot its column lands in. fn select_packets<'p, 'ctx>( @@ -112,13 +118,12 @@ fn reserve_packets<'ctx>( } impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { pub(super) fn new( - txn: &'source QwenChunkTxn<'session, 'ctx>, - binding: &'source ModelBinding, - layer: LayerId, + sealed: SealedLayer<'source, 'session, 'ctx>, rows: &'source [ChunkFfnRow], context: &'ctx Context<'ctx>, scope: &'source DownScope<'ctx>, ) -> Result { + let SealedLayer { txn, binding, layer } = sealed; if rows.len() != txn.micro_len()? || !(1..=64).contains(&rows.len()) || !std::ptr::eq(context, txn.context()?) { return Err(Error::IdentityMismatch); } @@ -126,6 +131,9 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { let (origins, packets) = reserve_packets(binding, rows, scope)?; Ok(Self { owner: Rc::new(()), txn, binding, layer, rows, context, scope, origins, packets }) } + fn sealed(&self) -> SealedLayer<'source, 'session, 'ctx> { + SealedLayer { txn: self.txn, binding: self.binding, layer: self.layer } + } pub(super) fn group(&self, expert: u32, pairs: &[Pair]) -> Result { if expert >= 512 || !(1..=self.rows.len()).contains(&pairs.len()) { return Err(Error::InvalidExpert); @@ -146,7 +154,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { fn admit_pair(&self, expert: u32, previous: Option, pair: &Pair) -> Result> { let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?; let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?; - validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?; + self.sealed().validate_row(pair.row, row, origin)?; if pair.slot >= K || previous.is_some_and(|old| old >= pair.row) || row.row().route.experts()[pair.slot].get() != expert @@ -165,7 +173,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { let mut previous = None; for (column, pair) in group.pairs.iter().enumerate() { let origin = self.admit_group_column(group, column, previous, pair)?; - validate_row(self.txn, self.binding, self.layer, pair.row, origin.0, origin.1)?; + self.sealed().validate_row(pair.row, origin.0, origin.1)?; previous = Some(pair.row); } Ok(()) @@ -230,7 +238,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { let mut packets = Vec::new(); packets.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; for (index, packet) in self.packets.iter().enumerate() { - validate_row(self.txn, self.binding, self.layer, index, &self.rows[index], &self.origins[index])?; + self.sealed().validate_row(index, &self.rows[index], &self.origins[index])?; packet.complete(self.scope)?; packets.push(packet); } @@ -249,21 +257,15 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { } fn finish_values( &self, - row: &ChunkFfnRow, - origin: &Rc, + tail: RowTail<'_, 'ctx, '_>, packed: &ResidentPackedDown<'ctx>, - activation: &DeviceBuffer<'_>, cache: &mut MoeWeightCache<'_>, ) -> Result> { - let (context, binding, scope) = (self.context, self.binding, self.scope); + let scope = self.scope; if use_shared_tail(cache) { - packed.with_completed(scope, |packet| { - finish_shared_queued(context, binding, row.row(), activation, cache, scope, origin, packet) - }) + packed.with_completed(scope, |packet| finish_shared_queued(tail, cache, packet)) } else { - finish_shared_with(context, binding, row.row(), activation, cache, scope, origin, |weights, scaled| { - packed.combine(scope, weights, scaled) - }) + finish_shared_with(tail, cache, |weights, scaled| packed.combine(scope, weights, scaled)) } } pub(super) fn finish_row( @@ -275,14 +277,22 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { ) -> Result { let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; let origin = self.origins.get(index).ok_or(Error::IdentityMismatch)?; - validate_row(self.txn, self.binding, self.layer, index, row, origin)?; + self.sealed().validate_row(index, row, origin)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } let packed = self.packets.get(index).ok_or(Error::IdentityMismatch)?; packed.complete(self.scope)?; - let values = self.finish_values(row, origin, packed, activation, cache)?; - validate_row(self.txn, self.binding, self.layer, index, row, origin)?; + let tail = RowTail { + context: self.context, + binding: self.binding, + row: row.row(), + activation, + scope: self.scope, + origin, + }; + let values = self.finish_values(tail, packed, cache)?; + self.sealed().validate_row(index, row, origin)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } From 80c9c4aca056f772e33ae45ca6bebf7cc68fa129 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:10:40 +0100 Subject: [PATCH 18/42] STRA-338 params e03: MTP windows take MtpWindowRequest/WindowOwners, draft warms take KnownNextEdge Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs --- .../src/backend/generate_mtp.rs | 5 +- .../src/backend/generate_mtp/tile_parts.rs | 32 +++-- .../src/gpu_proofs/combined_prefix_numeric.rs | 4 +- .../qwen_forward/executor_mmq_evaluation.rs | 32 ++++- .../check_chunk_on_loaded_fn.rs | 31 ++++- .../executor_window_numeric/proof.rs | 22 +++- .../src/qwen_forward/mtp_decode.rs | 2 + .../impl_mtpdecoder/batched_support.rs | 20 ++- .../impl_mtpdecoder/impl_mtpdecoder_2.rs | 33 ++--- .../impl_mtpdecoder/impl_mtpdecoder_2_2.rs | 107 ++++++++-------- .../impl_mtpdecoder/impl_mtpdecoder_3.rs | 114 ++++++++---------- .../qwen_forward/mtp_decode/window_request.rs | 37 ++++++ .../check_loaded_fn/impl_flow.rs | 3 +- .../check_loaded_fn/position_at_fn.rs | 16 +-- 14 files changed, 268 insertions(+), 190 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/window_request.rs diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs index d65f5faa..5ef3bd53 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs @@ -1,5 +1,6 @@ //! The MTP speculative generation loop. use super::*; +use crate::qwen_forward::mtp_decode::KnownNextEdge; mod tile_parts; use tile_parts::{begin_decoder, commit_window, emit_token_text, prefill_tiles, verified_window}; @@ -50,7 +51,9 @@ fn warm_retained_edge( } let (vocabulary, _) = mtp_vocabulary(run)?; let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?; - decoder.warm_retained(run.binding, run.session, product, next, run.moe_cache).map_err(|e| run.mtp_error(e)) + decoder + .warm_retained(run.binding, run.session, KnownNextEdge { source: product, known_next: next }, run.moe_cache) + .map_err(|e| run.mtp_error(e)) } /// What one iteration of the decode loop decided. diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp/tile_parts.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp/tile_parts.rs index e8098fd9..7c5600ac 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate_mtp/tile_parts.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate_mtp/tile_parts.rs @@ -2,7 +2,7 @@ #[allow(unused_imports)] use super::*; -use crate::qwen_forward::mtp_decode::MtpVerifiedWindow; +use crate::qwen_forward::mtp_decode::{MtpVerifiedWindow, MtpWindowRequest, WindowOwners}; /// The decoder to continue with, the product of the retained prefix, the tokens reused and the committed tokens so far. pub(super) type Resumed = (MtpDecoder, Option, usize, Vec); @@ -134,23 +134,21 @@ pub(super) fn verified_window( let cancel = run.cancel; let shared = run.shared; let sink = run.sink; + let request = MtpWindowRequest { binding: run.binding, source: product, spec }; + let owners = WindowOwners { + target: run.session, + output: run.output, + kar_cache: run.kar_cache.as_deref_mut(), + cache: run.moe_cache, + dense_cache: run.dense_cache, + }; decoder - .window( - run.binding, - product, - run.session, - run.output, - run.kar_cache.as_deref_mut(), - run.moe_cache, - run.dense_cache, - spec, - || { - cancel.load(Ordering::Acquire) - || shared.shutdown.load(Ordering::Acquire) - || sink.is_closed() - || run.clock.since(start) > GENERATION_TIMEOUT - }, - ) + .window(request, owners, || { + cancel.load(Ordering::Acquire) + || shared.shutdown.load(Ordering::Acquire) + || sink.is_closed() + || run.clock.since(start) > GENERATION_TIMEOUT + }) .map_err(|e| window_failure(run, e, start)) } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs index 8a12efcd..29b476d3 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs @@ -2,6 +2,7 @@ //! Forced inputs are public IDs; no expected model tensors or invented state. use super::combined_changed_boundary_proof::rig::Owners; use super::*; +use crate::qwen_forward::mtp_decode::{DraftHeadOwners, KnownNextEdge}; use crate::qwen_forward::{mtp::PrefixDraftSnapshot, session::ResetReplaySnapshot}; const PREFIX: [u32; 3] = [0, 1, 0]; @@ -94,8 +95,9 @@ fn reference_pass<'ctx, 'driver>( }; if let Some(&next) = COMPLETE.get(position + 1) { let next = TokenId::new(u64::from(next), vocabulary).expect("reference known-next refused"); + let edge = KnownNextEdge { source: &product, known_next: next }; decoder - .warm(run.binding, run.session, &product, next, run.output, run.moe_cache) + .warm(run.binding, run.session, edge, DraftHeadOwners { output: run.output, cache: run.moe_cache }) .expect("reference actual full draft step failed"); } latest = Some(product); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs index db0a1b66..5557aadd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs @@ -1,7 +1,7 @@ //! Only the explicitly selected new full-model MMQ gate. Old observers unchanged. use super::*; use crate::qwen_forward::mtp::MtpChunkNumericSnapshot; -use crate::qwen_forward::mtp_decode::MtpDecoder; +use crate::qwen_forward::mtp_decode::{KnownNextEdge, MtpDecoder}; use crate::qwen_forward::session::ResetReplaySnapshot; impl QwenForward { pub(crate) fn test_mmq_on_loaded<'driver>( @@ -120,7 +120,12 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { let source = QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches) .expect("scalar known-next target refused"); scalar_draft - .warm_prefill(self.binding, self.session, &source, self.ids[index + 1], self.moe) + .warm_prefill( + self.binding, + self.session, + KnownNextEdge { source: &source, known_next: self.ids[index + 1] }, + self.moe, + ) .expect("scalar known-next warm refused"); } } @@ -152,11 +157,16 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { source: &TargetStepProduct, ) -> Observation { scalar_draft - .warm_retained(self.binding, self.session, source, self.next, self.moe) + .warm_retained(self.binding, self.session, KnownNextEdge { source, known_next: self.next }, self.moe) .expect("scalar retained edge refused"); let continuation = self.mtp_step(self.next, 4).expect("scalar continuation refused"); scalar_draft - .warm_retained(self.binding, self.session, &continuation, self.follow, self.moe) + .warm_retained( + self.binding, + self.session, + KnownNextEdge { source: &continuation, known_next: self.follow }, + self.moe, + ) .expect("scalar continuation warm refused"); let greedy = continuation.predicted(self.session).expect("baseline continuation origin invalid"); let logits = self.output.test_reset_replay_take_logits().expect("baseline continuation head missing"); @@ -320,11 +330,21 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> { .validate_resume(self.binding, self.session, &chunk.product, &[0, 1, 0, 1]) .expect("chunk resume fence refused"); candidate_draft - .warm_retained(self.binding, self.session, &chunk.product, self.next, self.moe) + .warm_retained( + self.binding, + self.session, + KnownNextEdge { source: &chunk.product, known_next: self.next }, + self.moe, + ) .expect("chunk retained edge refused"); let continuation = self.mtp_step(self.next, 4).expect("chunk continuation refused"); candidate_draft - .warm_retained(self.binding, self.session, &continuation, self.follow, self.moe) + .warm_retained( + self.binding, + self.session, + KnownNextEdge { source: &continuation, known_next: self.follow }, + self.moe, + ) .expect("chunk continuation warm refused"); let actual_greedy = continuation.predicted(self.session).expect("candidate continuation origin invalid"); let actual_logits = self.output.test_reset_replay_take_logits().expect("candidate continuation head missing"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs index 24f216a4..79774830 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs @@ -7,7 +7,7 @@ use super::*; use crate::qwen_forward::executor::{PrefillStepProduct, StepCaches, StepRequest, TargetStepProduct}; use crate::qwen_forward::mtp::MtpChunkNumericSnapshot; -use crate::qwen_forward::mtp_decode::MtpDecoder; +use crate::qwen_forward::mtp_decode::{KnownNextEdge, MtpDecoder}; use crate::qwen_forward::session::ResetReplaySnapshot; const HOST_REMAINING: usize = 512 * 1024 * 1024; @@ -110,7 +110,12 @@ impl Rig<'_, '_, '_, '_, '_, '_> { let source = self.prefill(ids, (ids.ids[index], index as u64), "scalar known-next target refused"); let successor = ids.ids[index + 1]; draft - .warm_prefill(self.binding, self.session, &source, successor, self.moe) + .warm_prefill( + self.binding, + self.session, + KnownNextEdge { source: &source, known_next: successor }, + self.moe, + ) .expect("scalar known-next warm refused"); } let source = self.step_final(ids); @@ -132,10 +137,17 @@ impl Rig<'_, '_, '_, '_, '_, '_> { source: &TargetStepProduct, ) -> (ResetReplaySnapshot, MtpChunkNumericSnapshot) { let (binding, next) = (self.binding, ids.next); - draft.warm_retained(binding, self.session, source, next, self.moe).expect("scalar retained edge refused"); + draft + .warm_retained(binding, self.session, KnownNextEdge { source, known_next: next }, self.moe) + .expect("scalar retained edge refused"); let continuation = self.prefill(ids, (next, 4), "scalar continuation refused"); draft - .warm_prefill(binding, self.session, &continuation, ids.follow, self.moe) + .warm_prefill( + binding, + self.session, + KnownNextEdge { source: &continuation, known_next: ids.follow }, + self.moe, + ) .expect("scalar continuation warm refused"); let state = self.snapshot("scalar continuation state invalid"); (state, draft.test_chunk_snapshot()) @@ -222,13 +234,20 @@ impl Rig<'_, '_, '_, '_, '_, '_> { assert!(candidate.test_chunk_eq(&baseline.draft), "actual draft KV/residual mismatch"); let (binding, next) = (self.binding, ids.next); candidate.validate_resume(binding, self.session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused"); - candidate.warm_retained(binding, self.session, &actual, next, self.moe).expect("chunk retained edge refused"); + candidate + .warm_retained(binding, self.session, KnownNextEdge { source: &actual, known_next: next }, self.moe) + .expect("chunk retained edge refused"); } /// The continuation row after the chunk matches the scalar continuation. fn compare_continuation(&mut self, ids: &Ids, baseline: &Baseline, candidate: &mut MtpDecoder) { let continuation = self.prefill(ids, (ids.next, 4), "chunk continuation refused"); - let warm = candidate.warm_prefill(self.binding, self.session, &continuation, ids.follow, self.moe); + let warm = candidate.warm_prefill( + self.binding, + self.session, + KnownNextEdge { source: &continuation, known_next: ids.follow }, + self.moe, + ); warm.expect("chunk continuation warm refused"); let state = self.snapshot("chunk continuation invalid"); assert!(baseline.continued_state.numeric_eq(&state), "continued target mismatch"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs index 22703c4b..86acb579 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric/proof.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; use crate::qwen_forward::mtp::MtpChunkNumericSnapshot; +use crate::qwen_forward::mtp_decode::KnownNextEdge; use crate::qwen_forward::session::ResetReplaySnapshot; const HOST_BUDGET: usize = 512 * 1024 * 1024; @@ -138,7 +139,12 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { let product = self.baseline_prefill(&mut draft)?; let (logits, greedy, bits) = self.baseline_outputs(&product)?; let (target, mtp) = self.snapshots(&draft)?; - draft.warm_retained(self.binding, self.session, &product, self.next, self.owners.caches.moe)?; + draft.warm_retained( + self.binding, + self.session, + KnownNextEdge { source: &product, known_next: self.next }, + self.owners.caches.moe, + )?; self.continuation(&mut draft)?; let (continued_target, continued_mtp) = self.snapshots(&draft)?; drop(product); @@ -180,7 +186,12 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { let request = StepRequest { binding: self.binding, token: self.next, position }; let caches = self.owners.caches.step_caches(); let step = QwenForward::prefill_for_mtp_cached(request, self.session, self.owners.output, caches)?; - draft.warm_prefill(self.binding, self.session, &step, self.follow, self.owners.caches.moe)?; + draft.warm_prefill( + self.binding, + self.session, + KnownNextEdge { source: &step, known_next: self.follow }, + self.owners.caches.moe, + )?; Ok(()) } @@ -218,7 +229,12 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> { product: &TargetStepProduct, ) -> Result<(bool, bool)> { draft.validate_resume(self.binding, self.session, product, &[0, 1, 0, 1])?; - draft.warm_retained(self.binding, self.session, product, self.next, self.owners.caches.moe)?; + draft.warm_retained( + self.binding, + self.session, + KnownNextEdge { source: product, known_next: self.next }, + self.owners.caches.moe, + )?; self.continuation(draft)?; let target_equal = base.continued_target.numeric_eq(&self.snapshot()?); Ok((target_equal, draft.test_chunk_eq(&base.continued_mtp))) 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 2dbafda1..fd201c3d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs @@ -183,6 +183,7 @@ mod impl_mtpwindowspec; use impl_mtpwindowspec::kv_prefill_host_charge; mod first_seed_reuse_enabled_fn; mod impl_mtpdecoder; +mod window_request; #[allow(unused_imports)] use first_seed_reuse_enabled_fn::first_seed_reuse_enabled; #[allow(unused_imports)] @@ -191,3 +192,4 @@ use first_seed_reuse_enabled_fn::needed_draft_predictions; use first_seed_reuse_enabled_fn::window_limit; #[allow(unused_imports)] use first_seed_reuse_enabled_fn::window_stage_error; +pub(crate) use window_request::{DraftHeadOwners, KnownNextEdge, MtpWindowRequest, WindowOwners}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs index 9731d9ef..b59eea9c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs @@ -6,7 +6,20 @@ use super::*; use crate::qwen_forward::mtp::MtpCheckpoint; pub(super) type WindowResult = std::result::Result; -pub(super) type FirstSeed = Option<(MtpCheckpoint, mtp::MtpFrame)>; + +/// The draft checkpoint taken after the first draft step, kept with the frame it was taken at so a window can +/// restore it instead of warming the draft again. +pub(super) struct RetainedFirstSeed { + pub(super) checkpoint: MtpCheckpoint, + pub(super) frame: mtp::MtpFrame, +} +pub(super) type FirstSeed = Option; + +/// The authoritative first prediction of a window and the number of draft steps its depth and the context allow. +pub(super) struct WindowHead { + pub(super) first: TokenId, + pub(super) limit: usize, +} /// The sizing of one batched window, fixed before any draft or canonical mutation. pub(super) struct BatchedPlan { @@ -38,13 +51,12 @@ pub(super) struct BatchedCtx<'a, 'c, 'd, 'x> { impl<'a, 'c, 'd, 'x> BatchedCtx<'a, 'c, 'd, 'x> { pub(super) fn new( - binding: &'a ModelBinding, - source: &'a TargetStepProduct, + request: &'a MtpWindowRequest<'a>, output: &'a OutputStage<'c, 'd>, dense_cache: &'a DenseWeightCache<'x>, - spec: &MtpWindowSpec, plan: BatchedPlan, ) -> Self { + let (binding, source, spec) = (request.binding, &request.source, &request.spec); Self { binding, source, output, dense_cache, eos: spec.eos, remaining: spec.remaining, plan } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs index cf9a012d..63af578e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs @@ -98,11 +98,11 @@ impl MtpDecoder { &mut self, binding: &ModelBinding, target: &mut QwenSession<'_>, - source: &TargetStepProduct, - known_next: TokenId, - output: &OutputStage<'_, '_>, - cache: &MoeWeightCache<'_>, + edge: KnownNextEdge<'_, TargetStepProduct>, + head: DraftHeadOwners<'_, '_, '_, '_>, ) -> Result<()> { + let KnownNextEdge { source, known_next } = edge; + let DraftHeadOwners { output, cache } = head; let prior = self.draft.checkpoint()?; let result = (|| { let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; @@ -123,10 +123,10 @@ impl MtpDecoder { &mut self, binding: &ModelBinding, target: &mut QwenSession<'_>, - source: &TargetStepProduct, - known_next: TokenId, + edge: KnownNextEdge<'_, TargetStepProduct>, cache: &MoeWeightCache<'_>, ) -> Result<()> { + let KnownNextEdge { source, known_next } = edge; let prior = self.draft.checkpoint()?; let result = (|| { let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; @@ -144,10 +144,10 @@ impl MtpDecoder { &mut self, binding: &ModelBinding, target: &mut QwenSession<'_>, - source: &PrefillStepProduct, - known_next: TokenId, + edge: KnownNextEdge<'_, PrefillStepProduct>, cache: &MoeWeightCache<'_>, ) -> Result<()> { + let KnownNextEdge { source, known_next } = edge; let prior = self.draft.checkpoint()?; let result = (|| { let input = MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?; @@ -161,23 +161,16 @@ impl MtpDecoder { Ok(()) } - #[allow(clippy::too_many_arguments)] pub(crate) fn window<'driver>( &mut self, - binding: &ModelBinding, - source: TargetStepProduct, - target: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar_cache: Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - spec: MtpWindowSpec, + request: MtpWindowRequest<'_>, + owners: WindowOwners<'_, 'driver, '_, '_, '_, '_>, cancelled: impl FnMut() -> bool, ) -> std::result::Result { - if cache.requires_iq3_mmq_admission() { - self.window_batched(binding, source, target, output, kar_cache, cache, dense_cache, spec, cancelled) + if owners.cache.requires_iq3_mmq_admission() { + self.window_batched(request, owners, cancelled) } else { - self.window_scalar(binding, source, target, output, kar_cache, cache, dense_cache, spec, cancelled) + self.window_scalar(request, owners, cancelled) } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs index fc6dc368..e72d36f5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs @@ -4,47 +4,42 @@ use super::*; use super::batched_support::*; -use crate::qwen_forward::mtp::MtpCheckpoint; impl MtpDecoder { /// Selected only by the existing explicit IQ3 integer/native Down policy. /// Draft depth remains configured; target batch capacity is separately /// admitted. Only predictions consumed by that capacity are generated/countable. - #[allow(clippy::too_many_arguments)] pub(in super::super) fn window_batched<'driver>( &mut self, - binding: &ModelBinding, - source: TargetStepProduct, - target: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - mut kar_cache: Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'driver>, - dense_cache: &DenseWeightCache<'_>, - spec: MtpWindowSpec, + request: MtpWindowRequest<'_>, + mut owners: WindowOwners<'_, 'driver, '_, '_, '_, '_>, mut cancelled: impl FnMut() -> bool, ) -> WindowResult { - let plan = match self.batched_plan(binding, &source, target, cache, &spec, &mut cancelled)? { + let plan = match self.batched_plan(&request, owners.target, owners.cache, &mut cancelled)? { Ok(plan) => plan, - Err(eos) => return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos, draft_steps: 0 }), + Err(eos) => { + return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: request.source, eos, draft_steps: 0 }); + } }; - let (target_prior, mut st) = (target.checkpoint()?, self.batched_state(&plan)?); - let cx = BatchedCtx::new(binding, &source, output, dense_cache, &spec, plan); - match self.batched_body(&cx, target, &mut kar_cache, cache, &mut cancelled, &mut st) { + let (target_prior, mut st) = (owners.target.checkpoint()?, self.batched_state(&plan)?); + let cx = BatchedCtx::new(&request, owners.output, owners.dense_cache, plan); + match self.batched_body(&cx, &mut owners, &mut cancelled, &mut st) { Ok((latest, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens: st.tokens, latest, eos, draft_steps }), - Err(error) => Err(self.batched_rollback(target, &st, error, |t| t.restore_checkpoint(&target_prior))), + Err(error) => { + Err(self.batched_rollback(owners.target, &st, error, |t| t.restore_checkpoint(&target_prior))) + } } } /// Validate the source and size the window. `Err(eos)` is a trivially empty window. fn batched_plan( &self, - binding: &ModelBinding, - source: &TargetStepProduct, + request: &MtpWindowRequest<'_>, target: &QwenSession<'_>, cache: &MoeWeightCache<'_>, - spec: &MtpWindowSpec, cancelled: &mut impl FnMut() -> bool, ) -> WindowResult> { + let MtpWindowRequest { binding, source, spec } = request; source.mtp_source(binding, target)?; let first = source.predicted(target)?; let source_position = source.position(target)?.get(); @@ -56,7 +51,7 @@ impl MtpDecoder { } self.require_batched_admission(cache)?; let limit = window_limit(source_position, spec.depth, spec.remaining)?; - Ok(Ok(self.batched_sizing(binding, source, target, cache, spec.eos, first, limit)?)) + Ok(Ok(self.batched_sizing(request, target, cache, WindowHead { first, limit })?)) } fn require_batched_admission(&self, cache: &MoeWeightCache<'_>) -> Result<()> { @@ -66,17 +61,15 @@ impl MtpDecoder { Ok(()) } - #[allow(clippy::too_many_arguments)] fn batched_sizing( &self, - binding: &ModelBinding, - source: &TargetStepProduct, + request: &MtpWindowRequest<'_>, target: &QwenSession<'_>, cache: &MoeWeightCache<'_>, - eos: Option, - first: TokenId, - limit: usize, + head: WindowHead, ) -> Result { + let (binding, source, eos) = (request.binding, &request.source, request.spec.eos); + let WindowHead { first, limit } = head; let reuse_first_seed = limit > 1 && first_seed_reuse_enabled(cache); let seed_host_charge = if reuse_first_seed { self.draft.first_seed_host_charge()? } else { 0 }; let host_remaining = self.prefill_host_remaining(512 * 1024 * 1024)?; @@ -104,28 +97,28 @@ impl MtpDecoder { fn batched_body<'driver>( &mut self, cx: &BatchedCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'driver>, - kar_cache: &mut Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'driver>, + owners: &mut WindowOwners<'_, 'driver, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut BatchedState, ) -> WindowResult<(TargetStepProduct, bool, usize)> { - let (first_seed, draft_steps) = self.batched_draft_chain(cx, target, cache, cancelled, st)?; - self.batched_rewind(cx, target, cache, cancelled, st, first_seed)?; + let (first_seed, draft_steps) = self.batched_draft_chain(cx, owners, cancelled, st)?; + match first_seed { + Some(seed) => self.batched_restore_seed(cx, owners.target, st, &seed)?, + None => self.batched_rewarm(cx, owners, cancelled, st)?, + } if cancelled() { return Err(MtpWindowError::Cancelled); } - let product = self.batched_window(cx, target, kar_cache, cache, cancelled, st)?; - batched_after_publish(cx.binding, cache, cancelled)?; - let eos = Some(product.predicted(target)?) == cx.eos; + let product = self.batched_window(cx, owners, cancelled, st)?; + batched_after_publish(cx.binding, owners.cache, cancelled)?; + let eos = Some(product.predicted(owners.target)?) == cx.eos; Ok((product, eos, draft_steps)) } fn batched_draft_chain( &mut self, cx: &BatchedCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'_>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut BatchedState, ) -> WindowResult<(FirstSeed, usize)> { @@ -136,11 +129,11 @@ impl MtpDecoder { let Some(candidate) = next_candidate(st, cx.eos, cancelled)? else { break; }; - let input = self.batched_chain_input(cx, target, cache, previous.as_ref(), candidate)?; + let input = self.batched_chain_input(cx, owners, previous.as_ref(), candidate)?; let seed_frame = plan.seed_frame(previous.is_none(), &input); - let product = mtp::step(binding, target, &mut self.draft, input, cx.output, cache)?; + let product = mtp::step(binding, owners.target, &mut self.draft, input, cx.output, owners.cache)?; first_seed = self.capture_seed(plan, seed_frame)?.or(first_seed); - st.candidates.push(product.predicted(binding, target)?); + st.candidates.push(product.predicted(binding, owners.target)?); previous = Some(product); } Ok((first_seed, st.candidates.len().checked_sub(1).ok_or(Error::Overflow)?)) @@ -148,17 +141,20 @@ impl MtpDecoder { /// Retain the first-seed checkpoint beside its frame when the first draft step asked for reuse. fn capture_seed(&self, plan: &BatchedPlan, frame: Option) -> Result { - frame.map(|frame| Ok((self.draft.checkpoint_first_seed(plan.seed_host_charge)?, frame))).transpose() + let checkpoint = |frame| { + Ok(RetainedFirstSeed { checkpoint: self.draft.checkpoint_first_seed(plan.seed_host_charge)?, frame }) + }; + frame.map(checkpoint).transpose() } fn batched_chain_input( &self, cx: &BatchedCtx<'_, '_, '_, '_>, - target: &QwenSession<'_>, - cache: &MoeWeightCache<'_>, + owners: &WindowOwners<'_, '_, '_, '_, '_, '_>, previous: Option<&mtp::MtpStepProduct>, candidate: TokenId, ) -> Result { + let (target, cache) = (&*owners.target, &*owners.cache); match previous { Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache), None => MtpInput::from_target(cx.binding, target, &self.draft, cx.source, candidate, cache), @@ -172,32 +168,26 @@ impl MtpDecoder { cx: &BatchedCtx<'_, '_, '_, '_>, target: &QwenSession<'_>, st: &mut BatchedState, - seed: &MtpCheckpoint, - frame: &mtp::MtpFrame, + seed: &RetainedFirstSeed, ) -> WindowResult<()> { - let (binding, source) = (cx.binding, cx.source); + let (binding, source, frame) = (cx.binding, cx.source, &seed.frame); source.mtp_source(binding, target)?; if source.predicted(target)? != frame.token() || source.position(target)? != frame.position() { return Err(Error::IdentityMismatch.into()); } - self.draft.restore_first_seed(binding, target, frame, seed, &mut st.draft_priors[0])?; + self.draft.restore_first_seed(binding, target, frame, &seed.checkpoint, &mut st.draft_priors[0])?; Ok(()) } - /// Rewind the transient draft chain: restore the retained first seed, or restore, remint and re-warm. - fn batched_rewind( + /// Rewind the transient draft chain without a retained first seed: restore, remint and re-warm. + fn batched_rewarm( &mut self, cx: &BatchedCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'_>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut BatchedState, - first_seed: FirstSeed, ) -> WindowResult<()> { let (binding, source) = (cx.binding, cx.source); - if let Some((seed, frame)) = first_seed { - return self.batched_restore_seed(cx, target, st, &seed, &frame); - } self.draft.restore(&st.draft_priors[0])?; st.draft_priors.clear(); // The old speculative epoch is unusable after rewind. Failure @@ -206,8 +196,8 @@ impl MtpDecoder { if cancelled() { return Err(MtpWindowError::Cancelled); } - let input = MtpInput::from_target(binding, target, &self.draft, source, cx.plan.first, cache)?; - mtp::warm_step(binding, target, &mut self.draft, input, cache)?; + let input = MtpInput::from_target(binding, owners.target, &self.draft, source, cx.plan.first, owners.cache)?; + mtp::warm_step(binding, owners.target, &mut self.draft, input, owners.cache)?; Ok(()) } @@ -218,13 +208,12 @@ impl MtpDecoder { fn batched_window<'driver>( &mut self, cx: &BatchedCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'driver>, - kar_cache: &mut Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'driver>, + owners: &mut WindowOwners<'_, 'driver, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut BatchedState, ) -> WindowResult { let (binding, plan) = (cx.binding, &cx.plan); + let WindowOwners { target, kar_cache, cache, .. } = owners; let rows = plan.capacity.min(plan.limit).min(st.candidates.len()); poll_before_window(binding, cache)?; let mut fired = false; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs index 7b921b84..29090876 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs @@ -16,7 +16,6 @@ struct ScalarCtx<'a, 'c, 'd, 'x> { eos: Option, limit: usize, source_position: u64, - first: TokenId, } impl ScalarCtx<'_, '_, '_, '_> { @@ -33,6 +32,15 @@ struct ScalarState { candidates: Vec, tokens: Vec, latest: Option, + /// The authoritative target prediction the next candidate is checked against. + expected: TokenId, +} + +/// The target product and the candidate token the first draft step of a chain is anchored to. +#[derive(Clone, Copy)] +struct DraftAnchor<'a> { + latest: Option<&'a TargetStepProduct>, + candidate: TokenId, } /// Validate the source and size the window. `Err(eos)` is a trivially empty window (nothing remaining, or the @@ -74,31 +82,27 @@ fn empty_window(latest: TargetStepProduct, eos: bool) -> MtpVerifiedWindow { } impl MtpDecoder { - #[allow(clippy::too_many_arguments)] pub(crate) fn window_scalar( &mut self, - binding: &ModelBinding, - source: TargetStepProduct, - target: &mut QwenSession<'_>, - output: &OutputStage<'_, '_>, - mut kar_cache: Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, - spec: MtpWindowSpec, + request: MtpWindowRequest<'_>, + mut owners: WindowOwners<'_, '_, '_, '_, '_, '_>, mut cancelled: impl FnMut() -> bool, ) -> WindowResult { - let (first, source_position, limit) = match scalar_start(binding, &source, target, &spec, &mut cancelled)? { + let MtpWindowRequest { binding, source, spec } = request; + let start = scalar_start(binding, &source, owners.target, &spec, &mut cancelled)?; + let (first, source_position, limit) = match start { Ok(start) => start, Err(eos) => return Ok(empty_window(source, eos)), }; - let (target_prior, mut state) = (target.checkpoint()?, self.scalar_state(first, source, limit)?); - let cx = ScalarCtx { binding, output, dense_cache, eos: spec.eos, limit, source_position, first }; - match self.scalar_body(&cx, target, &mut kar_cache, cache, &mut cancelled, &mut state) { + let (target_prior, mut state) = (owners.target.checkpoint()?, self.scalar_state(first, source, limit)?); + let (output, dense_cache) = (owners.output, owners.dense_cache); + let cx = ScalarCtx { binding, output, dense_cache, eos: spec.eos, limit, source_position }; + match self.scalar_body(&cx, &mut owners, &mut cancelled, &mut state) { Ok((product, eos, draft_steps)) => Ok(verified_window(state.tokens, product, eos, draft_steps)), Err(error) => { let restore = |cause: Option| { - cause.inspect(|cause| target.note_mtp_failure(cause)); - target.restore_checkpoint(&target_prior) + cause.inspect(|cause| owners.target.note_mtp_failure(cause)); + owners.target.restore_checkpoint(&target_prior) }; self.scalar_rollback(&state, error, restore)?; Err(error) @@ -112,7 +116,7 @@ impl MtpDecoder { let mut candidates = reserve(limit + 1)?; candidates.push(first); let tokens = reserve(limit)?; - Ok(ScalarState { draft_priors, candidates, tokens, latest: Some(source) }) + Ok(ScalarState { draft_priors, candidates, tokens, latest: Some(source), expected: first }) } /// Draft chain, rewind to a fresh-epoch checkpoint, then verified catch-up against the real target. A matching @@ -124,18 +128,16 @@ impl MtpDecoder { fn scalar_body( &mut self, cx: &ScalarCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'_>, - kar_cache: &mut Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut ScalarState, ) -> WindowResult<(TargetStepProduct, bool, usize)> { - self.scalar_draft_chain(cx, target, cache, cancelled, st)?; + self.scalar_draft_chain(cx, owners, cancelled, st)?; let draft_steps = st.candidates.len() - 1; self.draft.restore(&st.draft_priors[0])?; st.draft_priors.clear(); st.draft_priors.push(self.draft.checkpoint()?); - let (expected, mut eos) = self.scalar_verify(cx, target, kar_cache, cache, cancelled, st)?; + let (expected, mut eos) = self.scalar_verify(cx, owners, cancelled, st)?; if Some(expected) == cx.eos { eos = true; } @@ -150,8 +152,7 @@ impl MtpDecoder { fn scalar_draft_chain( &mut self, cx: &ScalarCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'_>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut ScalarState, ) -> WindowResult<()> { @@ -164,9 +165,10 @@ impl MtpDecoder { if Some(candidate) == cx.eos { break; } - let input = self.scalar_chain_input(cx, target, cache, previous.as_ref(), st, candidate)?; - let product = mtp::step(cx.binding, target, &mut self.draft, input, cx.output, cache)?; - st.candidates.push(product.predicted(cx.binding, target)?); + let anchor = DraftAnchor { latest: st.latest.as_ref(), candidate }; + let input = self.scalar_chain_input(cx, owners, previous.as_ref(), anchor)?; + let product = mtp::step(cx.binding, owners.target, &mut self.draft, input, cx.output, owners.cache)?; + st.candidates.push(product.predicted(cx.binding, owners.target)?); previous = Some(product); } Ok(()) @@ -175,17 +177,16 @@ impl MtpDecoder { fn scalar_chain_input( &self, cx: &ScalarCtx<'_, '_, '_, '_>, - target: &QwenSession<'_>, - cache: &MoeWeightCache<'_>, + owners: &WindowOwners<'_, '_, '_, '_, '_, '_>, previous: Option<&mtp::MtpStepProduct>, - st: &ScalarState, - candidate: TokenId, + anchor: DraftAnchor<'_>, ) -> Result { + let (target, cache) = (&*owners.target, &*owners.cache); match previous { Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache), None => { - let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?; - MtpInput::from_target(cx.binding, target, &self.draft, latest, candidate, cache) + let latest = anchor.latest.ok_or(Error::IdentityMismatch)?; + MtpInput::from_target(cx.binding, target, &self.draft, latest, anchor.candidate, cache) } } } @@ -195,73 +196,64 @@ impl MtpDecoder { fn scalar_verify( &mut self, cx: &ScalarCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'_>, - kar_cache: &mut Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut ScalarState, ) -> WindowResult<(TokenId, bool)> { - let mut expected = cx.first; let mut eos = false; for index in 0..cx.limit.min(st.candidates.len()) { if cancelled() { return Err(MtpWindowError::Cancelled); } - if Some(expected) == cx.eos { + if Some(st.expected) == cx.eos { eos = true; break; } let candidate = st.candidates[index]; - if candidate != expected { + if candidate != st.expected { break; } - expected = self.scalar_accept(cx, target, kar_cache, cache, cancelled, st, expected)?; + self.scalar_accept(cx, owners, cancelled, st)?; st.tokens.push(candidate); } - Ok((expected, eos)) + Ok((st.expected, eos)) } /// Rebuild persistent cell i from CURRENT actual target R_i and verified token i+1 before target advancement /// invalidates R_i. Do not call warm(): its nested rewind would invalidate this window's fresh-epoch rollback - /// checkpoint on failure. The new prediction is read while the product is still current. - #[allow(clippy::too_many_arguments)] + /// checkpoint on failure. The new prediction is read while the product is still current and becomes the next + /// expected token. fn scalar_accept( &mut self, cx: &ScalarCtx<'_, '_, '_, '_>, - target: &mut QwenSession<'_>, - kar_cache: &mut Option<&mut KarPleCache<'_>>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &mut ScalarState, - expected: TokenId, - ) -> WindowResult { + ) -> WindowResult<()> { let binding = cx.binding; let position = cx.next_position(st.tokens.len())?; - self.scalar_warm(binding, target, cache, cancelled, st, expected)?; + self.scalar_warm(binding, owners, cancelled, st)?; let position = Position::new(position, crate::qwen_forward::contract::position_dimension())?; - let (output, dense) = (cx.output, cx.dense_cache); - let kar = kar_cache.as_deref_mut(); - let request = StepRequest { binding, token: expected, position }; - let caches = StepCaches { kar, moe: Some(cache), dense: Some(dense) }; - let product = QwenForward::step_for_mtp_cached(request, target, output, caches)?; - let next = product.predicted(target)?; + let request = StepRequest { binding, token: st.expected, position }; + let kar = owners.kar_cache.as_deref_mut(); + let caches = StepCaches { kar, moe: Some(&mut *owners.cache), dense: Some(cx.dense_cache) }; + let product = QwenForward::step_for_mtp_cached(request, owners.target, cx.output, caches)?; + st.expected = product.predicted(owners.target)?; st.latest = Some(product); - Ok(next) + Ok(()) } /// Warm the persistent draft cell from the current target product, then honour cancellation. fn scalar_warm( &mut self, binding: &ModelBinding, - target: &mut QwenSession<'_>, - cache: &mut MoeWeightCache<'_>, + owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>, cancelled: &mut impl FnMut() -> bool, st: &ScalarState, - expected: TokenId, ) -> WindowResult<()> { let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?; - let input = MtpInput::from_target(binding, target, &self.draft, latest, expected, cache)?; - mtp::warm_step(binding, target, &mut self.draft, input, cache)?; + let input = MtpInput::from_target(binding, owners.target, &self.draft, latest, st.expected, owners.cache)?; + mtp::warm_step(binding, owners.target, &mut self.draft, input, owners.cache)?; if cancelled() { return Err(MtpWindowError::Cancelled); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/window_request.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/window_request.rs new file mode 100644 index 00000000..f26e6fd7 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/window_request.rs @@ -0,0 +1,37 @@ +//! What one MTP window runs on and for: the request to verify and the target owners that serve it. + +use super::{ + DenseWeightCache, KarPleCache, ModelBinding, MoeWeightCache, MtpWindowSpec, OutputStage, QwenSession, + TargetStepProduct, +}; +use crate::qwen_forward::contract::TokenId; + +/// One MTP window to verify: the model, the authoritative target product it extends and its depth, remaining and +/// EOS bounds. +pub(crate) struct MtpWindowRequest<'a> { + pub(crate) binding: &'a ModelBinding, + pub(crate) source: TargetStepProduct, + pub(crate) spec: MtpWindowSpec, +} + +/// The target session and the device owners one MTP window reads and fills: output head, KAR PLE cache, MoE weight +/// cache and dense weight cache. +pub(crate) struct WindowOwners<'a, 'driver, 'out, 'head, 'kar, 'dense> { + pub(crate) target: &'a mut QwenSession<'driver>, + pub(crate) output: &'a OutputStage<'out, 'head>, + pub(crate) kar_cache: Option<&'a mut KarPleCache<'kar>>, + pub(crate) cache: &'a mut MoeWeightCache<'driver>, + pub(crate) dense_cache: &'a DenseWeightCache<'dense>, +} + +/// The output head and the MoE weight cache one full draft step, head included, reads. +pub(crate) struct DraftHeadOwners<'a, 'out, 'head, 'moe> { + pub(crate) output: &'a OutputStage<'out, 'head>, + pub(crate) cache: &'a MoeWeightCache<'moe>, +} + +/// A known-next prompt edge: the target product the draft is warmed from and the authoritative token that follows it. +pub(crate) struct KnownNextEdge<'a, Source> { + pub(crate) source: &'a Source, + pub(crate) known_next: TokenId, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs index b9e7f874..68c69302 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::mtp_decode::KnownNextEdge; impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> { pub(super) fn step(&mut self, token: TokenId, position: u64) -> Result { @@ -10,7 +11,7 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> { } pub(super) fn warm(&mut self, draft: &mut MtpDecoder, source: &TargetStepProduct, token: TokenId) -> Result<()> { let native = self.cache_slot.as_mut().unwrap(); - draft.warm_retained(self.shared.binding, &mut self.target, source, token, native) + draft.warm_retained(self.shared.binding, &mut self.target, KnownNextEdge { source, known_next: token }, native) } pub(super) fn observe(&self, source: &TargetStepProduct) -> Expected { observe(self.shared.binding, &self.target, self.shared.output, source) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs index dd3d7583..7842c914 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/position_at_fn.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; use crate::qwen_forward::executor::{StepCaches, StepRequest}; +use crate::qwen_forward::mtp_decode::{MtpWindowRequest, WindowOwners}; pub(super) fn position_at(position: u64) -> Position { Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap() @@ -37,17 +38,10 @@ impl Shared<'_, '_, '_, '_, '_> { (source, spec): (TargetStepProduct, MtpWindowSpec), cancelled: impl FnMut() -> bool, ) -> std::result::Result { - decoder.window( - self.binding, - source, - target, - self.output, - Some(&mut *self.kar), - cache, - self.dense, - spec, - cancelled, - ) + let request = MtpWindowRequest { binding: self.binding, source, spec }; + let (output, dense_cache) = (self.output, self.dense); + let owners = WindowOwners { target, output, kar_cache: Some(&mut *self.kar), cache, dense_cache }; + decoder.window(request, owners, cancelled) } } From 681c60951907e12b7c58ea4121e573fa602bc616 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:11:38 +0100 Subject: [PATCH 19/42] STRA-338 params e04: expert MLP/projection family takes BoundExpert, ExpertMatrix, ExpertActivation; MMQ chunk entries take ChunkFfnLayer Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs --- .../src/qwen_forward/bound_expert.rs | 12 +++ .../qwen_forward/executor/step_layer_fns.rs | 7 +- .../impl_qwenforward_3/window_experts.rs | 19 +++-- .../src/qwen_forward/mod.rs | 1 + .../moe_activation_reuse_gpu/encoded_fn.rs | 8 +- .../former_fixture_domain_refusal_fn.rs | 34 +++++++-- .../src/qwen_forward/moe_expert.rs | 12 ++- .../moe_expert/cached_mlp_down_fn.rs | 75 ++++++++----------- .../qwen_forward/moe_expert/expert_mlp_fn.rs | 40 ++++------ .../moe_expert/finish_with_parts_fn.rs | 24 +++--- .../moe_expert/impl_expertready.rs | 70 ++++++++--------- .../moe_expert/project_matrix_fn.rs | 59 +++++++++------ .../src/qwen_forward/moe_group_chunk.rs | 3 + .../moe_group_chunk/bound_rows_fn.rs | 17 ++--- .../moe_group_chunk/finish_shared_with_fn.rs | 15 ++-- .../moe_group_chunk/impl_preparedmoerow.rs | 8 ++ .../ordered_down_refusal_fn.rs | 5 +- .../src/qwen_forward/moe_layer0_pair.rs | 2 +- .../src/qwen_forward/moe_mmq_chunk.rs | 45 +++++------ .../src/qwen_forward/moe_prompt_finish.rs | 6 +- 20 files changed, 254 insertions(+), 208 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs new file mode 100644 index 00000000..f95f9894 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs @@ -0,0 +1,12 @@ +//! The expert a projection, a cache fill or a loan refers to. +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertSelection, MoeExpertWeights}; + +/// One expert (a routed slot or the shared expert) of validated expert weights, under the binding that admitted +/// them. The three always travel together: weights are only meaningful for their binding, and the selection says +/// which expert of those weights is meant. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct BoundExpert<'a> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) weights: &'a MoeExpertWeights, + pub(in crate::qwen_forward) selection: MoeExpertSelection, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs index a78bb3fc..d8e7ed60 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs @@ -340,7 +340,12 @@ fn moe_ffn_inject( ForwardPhase::MoeExpert, layer.get(), pos, - MoeExpertStage::execute(binding, layer, route, ffn.ready(), txn, moe_cache), + MoeExpertStage::execute( + binding, + crate::qwen_forward::moe_expert::ExpertRowRequest { layer, route, input: ffn.ready() }, + txn, + moe_cache, + ), )?; experts.validate_origin(&binding.identity())?; experts.identity().validate(token, pos, layer)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs index 37fbc0de..65b63ebe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/window_experts.rs @@ -3,7 +3,9 @@ #[allow(unused_imports)] use super::*; use crate::qwen_forward::gr::GrBatchRow; -use crate::qwen_forward::moe_expert::ExpertReady; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use crate::qwen_forward::moe_expert::NativePromptFinish; +use crate::qwen_forward::moe_expert::{ChunkFfnLayer, ExpertReady}; use crate::qwen_forward::session::chunk::{ChunkFfnRow, PreparedLayerRow}; /// Releases the native MoE products of the window, if it had any. @@ -81,9 +83,12 @@ impl QwenForward { } ChunkMoePolicy::ExperimentalResidentMmq | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - | ChunkMoePolicy::ExperimentalMtpVerification => { - MoeExpertStage::execute_chunk_mmq(binding, layer, ffn_rows, chunk, moe_cache, cancelled) - } + | ChunkMoePolicy::ExperimentalMtpVerification => MoeExpertStage::execute_chunk_mmq( + ChunkFfnLayer { binding, layer, rows: ffn_rows }, + chunk, + moe_cache, + cancelled, + ), } } @@ -103,9 +108,9 @@ impl QwenForward { let products = native_moe.as_mut().ok_or(Error::IdentityMismatch); Some(products.and_then(|products| { let binding = env.binding; - MoeExpertStage::execute_chunk_mmq_native_prompt( - binding, layer, ffn_rows, chunk, moe_cache, cancelled, products, env.dense, - ) + let ffn = ChunkFfnLayer { binding, layer, rows: ffn_rows }; + let finish = NativePromptFinish { products, dense: env.dense }; + MoeExpertStage::execute_chunk_mmq_native_prompt(ffn, chunk, moe_cache, cancelled, finish) })) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs index d860c67d..8f9b6d35 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs @@ -1,6 +1,7 @@ //! Physical Qwen stage registry. Declaring a stage does not implement it. //! The shared contract and explicit incomplete shells arrive in phase B. +mod bound_expert; pub(crate) mod contract; pub(crate) mod dense_weight_cache; pub(crate) mod executor; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs index c76d2e14..0746f8bc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs @@ -181,10 +181,10 @@ pub(super) fn format_case(context: &Context<'_>, kind: MoeMatrixKind, routed: bo let gate_matrix = upload_bytes(context, &gate_bytes).unwrap(); let up_matrix = upload_bytes(context, &up_bytes).unwrap(); let down_matrix = upload_bytes(context, &down_bytes).unwrap(); - let gate = project_retained_gate_up(context, |out| launch_projection(context, kind, &gate_matrix, &x, out, FF, N)) - .unwrap(); - let up = - project_retained_gate_up(context, |out| launch_projection(context, kind, &up_matrix, &x, out, FF, N)).unwrap(); + let dims = MatrixDims { kind, rows: FF, columns: N }; + let gate = + project_retained_gate_up(context, |out| launch_projection(context, dims, &gate_matrix, &x, out)).unwrap(); + let up = project_retained_gate_up(context, |out| launch_projection(context, dims, &up_matrix, &x, out)).unwrap(); for buffer in [&gate, &up] { for value in download_f32(buffer, FF).unwrap().iter() { assert!(value.abs() < 20., "fixture exceeds predeclared Gate/Up bound"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs index e301c56e..601da80d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs @@ -21,11 +21,23 @@ impl<'ctx> DomainFixture<'ctx> { let up_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 1)).unwrap(); let down_matrix = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap(); let gate = project_retained_gate_up(context, |output| { - launch_projection(context, MoeMatrixKind::Iq3Xxs, &gate_matrix, &x, output, FF, N) + launch_projection( + context, + MatrixDims { kind: MoeMatrixKind::Iq3Xxs, rows: FF, columns: N }, + &gate_matrix, + &x, + output, + ) }) .unwrap(); let up = project_retained_gate_up(context, |output| { - launch_projection(context, MoeMatrixKind::Iq3Xxs, &up_matrix, &x, output, FF, N) + launch_projection( + context, + MatrixDims { kind: MoeMatrixKind::Iq3Xxs, rows: FF, columns: N }, + &up_matrix, + &x, + output, + ) }) .unwrap(); let mut hidden = context.allocate(FF * 4).unwrap(); @@ -111,8 +123,14 @@ fn late_nan_projection_refused(context: &Context<'_>) { let x = upload_f32(context, &[0.25; N]).unwrap(); let initial = context.allocated_bytes(); assert_eq!( - project_retained_gate_up(context, |out| launch_projection(context, MoeMatrixKind::Q6K, &w, &x, out, FF, N)) - .err(), + project_retained_gate_up(context, |out| launch_projection( + context, + MatrixDims { kind: MoeMatrixKind::Q6K, rows: FF, columns: N }, + &w, + &x, + out + )) + .err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), initial); @@ -128,7 +146,13 @@ fn down_shape_refused(context: &Context<'_>) { wrong.copy_from(&sentinel).unwrap(); let initial = context.allocated_bytes(); let result = finish_cached_mlp(context, raw(context, &[0.25; FF]), raw(context, &[0.5; FF]), |hidden| { - launch_projection(context, MoeMatrixKind::RoutedIq4Nl, &w, hidden, &mut wrong, N, FF)?; + launch_projection( + context, + MatrixDims { kind: MoeMatrixKind::RoutedIq4Nl, rows: N, columns: FF }, + &w, + hidden, + &mut wrong, + )?; panic!("wrong Down output must refuse"); }); assert_eq!(result.err(), Some(Error::InvalidDimension)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs index 2264e4bf..c0d2c732 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs @@ -1,5 +1,6 @@ //! Artifact-bound selected experts and one independent shared expert. #![allow(dead_code)] +use super::bound_expert::BoundExpert; use super::contract::{Error, LayerId, Result, Stage, TokenLayer}; use super::gr::ResidualReady; use super::moe_route::RoutedExperts; @@ -20,7 +21,9 @@ mod moe_down; use moe_down::{DownScope, DownSelection, PackedDown, RetainedDown, TransportBuffer}; #[path = "moe_group_chunk.rs"] mod grouped; -pub(in crate::qwen_forward) use grouped::PreparedMoeRow; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(in crate::qwen_forward) use grouped::NativePromptFinish; +pub(in crate::qwen_forward) use grouped::{ChunkFfnLayer, PreparedMoeRow}; const N: usize = 2560; const FF: usize = 640; const K: usize = 10; @@ -62,6 +65,9 @@ mod moe_activation_reuse_gpu; mod tests; mod impl_expertready; +pub(in crate::qwen_forward) use impl_expertready::ExpertRowRequest; +#[allow(unused_imports)] +use impl_expertready::StepCuda; #[allow(unused_imports)] use impl_expertready::execute_cuda; #[allow(unused_imports)] @@ -75,6 +81,8 @@ use finish_with_parts_fn::execute_cuda_cached; use finish_with_parts_fn::finish_with_parts; mod cached_mlp_down_fn; #[allow(unused_imports)] +use cached_mlp_down_fn::DownProvenance; +#[allow(unused_imports)] use cached_mlp_down_fn::cached_gate_up_scoped; #[allow(unused_imports)] use cached_mlp_down_fn::cached_mlp_down; @@ -105,6 +113,8 @@ use project_matrix_fn::launch_cached_projection; use project_matrix_fn::launch_projection; #[allow(unused_imports)] use project_matrix_fn::project_matrix; +#[allow(unused_imports)] +use project_matrix_fn::{DeclaredMatrix, ExpertActivation, ExpertMatrix, MatrixDims}; mod validate_values_fn; #[allow(unused_imports)] use validate_values_fn::binding_error; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs index ff43de7f..d2efb3c4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs @@ -29,15 +29,21 @@ fn swiglu_hidden( Ok(()) } +/// The step-local scope that records a Down computation and the origin its results are minted under. +#[derive(Clone, Copy)] +pub(super) struct DownProvenance<'a, 'ctx> { + pub(super) scope: &'a DownScope<'ctx>, + pub(super) origin: &'a Rc, +} + fn project_down<'ctx>( context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, + expert: BoundExpert<'_>, cache: &mut MoeWeightCache<'_>, scope: &DownScope<'ctx>, hidden: &TransportBuffer<'_>, ) -> Result> { + let BoundExpert { binding, weights, selection } = expert; cache.validate(binding, context)?; let (columns, rows) = weights.shape(selection, MoeMatrixRole::Down).map_err(binding_error)?; let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; @@ -50,7 +56,7 @@ fn project_down<'ctx>( MoeExpertSelection::Shared => DownSelection::Shared, }; scope.project(numeric_selection, |output| { - launch_cached_projection(context, kind, matrix, hidden.buffer()?, output, rows, columns) + launch_cached_projection(context, MatrixDims { kind, rows, columns }, matrix, hidden.buffer()?, output) }) } @@ -76,15 +82,13 @@ fn close_down_parts<'ctx>( /// Gate and Up of one expert plus the hidden buffer they feed; a failure closes every owner already made. fn gate_up_hidden<'ctx>( context: &'ctx Context<'ctx>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - (activation, prepared): (&DeviceBuffer<'_>, Option<&RoutedGateUpQ8<'_>>), + expert: BoundExpert<'_>, + activation: ExpertActivation<'_, '_>, cache: &mut MoeWeightCache<'_>, scope: &DownScope<'ctx>, ) -> Result<(TransportBuffer<'ctx>, TransportBuffer<'ctx>, TransportBuffer<'ctx>)> { let scoped = |cache: &mut MoeWeightCache<'_>, role| { - cached_gate_up_scoped(context, binding, weights, selection, role, activation, cache, prepared, scope) + cached_gate_up_scoped(context, ExpertMatrix { expert, role }, activation, cache, scope) }; let gate = scoped(cache, MoeMatrixRole::Gate)?; let up = match scoped(cache, MoeMatrixRole::Up) { @@ -104,75 +108,58 @@ fn gate_up_hidden<'ctx>( } } -#[allow(clippy::too_many_arguments)] pub(super) fn cached_mlp_down<'ctx>( context: &'ctx Context<'ctx>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - activation: &DeviceBuffer<'_>, + expert: BoundExpert<'_>, + activation: ExpertActivation<'_, '_>, cache: &mut MoeWeightCache<'_>, - prepared: Option<&RoutedGateUpQ8<'_>>, - scope: &DownScope<'ctx>, - origin: &Rc, + provenance: DownProvenance<'_, 'ctx>, ) -> Result> { - check_origin(origin, binding, weights)?; - let inputs = (activation, prepared); - let (gate, up, mut hidden) = gate_up_hidden(context, binding, weights, selection, inputs, cache, scope)?; + let DownProvenance { scope, origin } = provenance; + check_origin(origin, expert.binding, expert.weights)?; + let (gate, up, mut hidden) = gate_up_hidden(context, expert, activation, cache, scope)?; let result = swiglu_hidden(context, scope, &gate, &up, &mut hidden) - .and_then(|()| project_down(context, binding, weights, selection, cache, scope, &hidden)); + .and_then(|()| project_down(context, expert, cache, scope, &hidden)); close_down_parts(scope, result, gate, up, hidden).map(|output| ActualDown { origin: Rc::clone(origin), - selection, + selection: expert.selection, output, }) } fn launch_scoped_gate_up( context: &Context<'_>, matrix: CachedMoeMatrix<'_, '_>, - dims: MatrixDims, - selection: MoeExpertSelection, - prepared: Option<&RoutedGateUpQ8<'_>>, - activation: &DeviceBuffer<'_>, + declared: DeclaredMatrix, + activation: ExpertActivation<'_, '_>, output: &mut TransportBuffer<'_>, ) -> Result<()> { - match prepared { + let DeclaredMatrix { selection, dims, .. } = declared; + match activation.prepared { Some(prepared) => { let format = gate_up_prepared_format(selection, dims.kind)?; launch_cached_prepared(context, matrix, prepared, output.buffer_mut()?, format)?; } None => { - launch_cached_projection( - context, - dims.kind, - matrix, - activation, - output.buffer_mut()?, - dims.rows, - dims.columns, - )?; + launch_cached_projection(context, dims, matrix, activation.buffer, output.buffer_mut()?)?; } } download_f32(output.buffer()?, FF).map(|_| ()) } -#[allow(clippy::too_many_arguments)] pub(super) fn cached_gate_up_scoped<'ctx>( context: &'ctx Context<'ctx>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - role: MoeMatrixRole, - activation: &DeviceBuffer<'_>, + requested: ExpertMatrix<'_>, + activation: ExpertActivation<'_, '_>, cache: &mut MoeWeightCache<'_>, - prepared: Option<&RoutedGateUpQ8<'_>>, scope: &DownScope<'ctx>, ) -> Result> { + let ExpertMatrix { expert: BoundExpert { binding, weights, selection }, role } = requested; let dims = gate_up_dims(weights, selection, role)?; cache.validate(binding, context)?; let matrix = cache.matrix(binding, weights, selection, role)?; let mut output = scope.allocate(FF * 4)?; - let result = launch_scoped_gate_up(context, matrix, dims, selection, prepared, activation, &mut output); + let declared = DeclaredMatrix { selection, role, dims }; + let result = launch_scoped_gate_up(context, matrix, declared, activation, &mut output); scope.record(&result); if let Err(primary) = result { let _ = output.close(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs index 94392d7e..803ed68a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs @@ -7,24 +7,22 @@ use super::*; pub(super) fn expert_mlp( context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - activation: &DeviceBuffer<'_>, + expert: BoundExpert<'_>, + activation: ExpertActivation<'_, '_>, mut cache: Option<&mut MoeWeightCache<'_>>, - prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { if let Some(cache) = cache.as_deref_mut() { - return cached_expert_mlp(context, binding, weights, selection, activation, cache, prepared); + return cached_expert_mlp(context, expert, activation, cache); } // Genuine uncached diagnostic: keep its original download/reupload chain. let project = |role, cache: Option<&mut MoeWeightCache<'_>>| { - project_matrix(context, binding, weights, selection, role, activation, cache, prepared) + project_matrix(context, ExpertMatrix { expert, role }, activation, cache) }; let gate = project(MoeMatrixRole::Gate, cache.as_deref_mut())?; let up = project(MoeMatrixRole::Up, cache.as_deref_mut())?; let hidden = uncached_hidden(context, gate, up)?; - let result = project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, &hidden, cache, None); + let down = ExpertMatrix { expert, role: MoeMatrixRole::Down }; + let result = project_matrix(context, down, ExpertActivation { buffer: &hidden, prepared: None }, cache); let release = hidden.release().map_err(driver_error); match result { Err(error) => Err(error), @@ -36,15 +34,12 @@ pub(super) fn expert_mlp( } fn cached_expert_mlp( context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - activation: &DeviceBuffer<'_>, + expert: BoundExpert<'_>, + activation: ExpertActivation<'_, '_>, cache: &mut MoeWeightCache<'_>, - prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { let project = |role, cache: &mut MoeWeightCache<'_>| { - project_cached_gate_up(context, binding, weights, selection, role, activation, cache, prepared) + project_cached_gate_up(context, ExpertMatrix { expert, role }, activation, cache) }; let gate = project(MoeMatrixRole::Gate, cache)?; let up = match project(MoeMatrixRole::Up, cache) { @@ -55,7 +50,8 @@ fn cached_expert_mlp( } }; finish_cached_mlp(context, gate, up, |hidden| { - project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, hidden, Some(cache), None) + let down = ExpertMatrix { expert, role: MoeMatrixRole::Down }; + project_matrix(context, down, ExpertActivation { buffer: hidden, prepared: None }, Some(cache)) }) } /// Re-uploads the host Gate/Up of the uncached diagnostic and returns the checked SwiGLU hidden buffer. @@ -69,26 +65,22 @@ fn uncached_hidden<'ctx>(context: &'ctx Context<'_>, gate: Box<[f32]>, up: Box<[ up.release().map_err(driver_error)?; Ok(hidden) } -#[allow(clippy::too_many_arguments)] pub(super) fn project_cached_gate_up<'ctx>( context: &'ctx Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - role: MoeMatrixRole, - activation: &DeviceBuffer<'_>, + requested: ExpertMatrix<'_>, + activation: ExpertActivation<'_, '_>, cache: &mut MoeWeightCache<'_>, - prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { + let ExpertMatrix { expert: BoundExpert { binding, weights, selection }, role } = requested; let dims = gate_up_dims(weights, selection, role)?; cache.validate(binding, context)?; let matrix = cache.matrix(binding, weights, selection, role)?; - project_retained_gate_up(context, |output| match prepared { + project_retained_gate_up(context, |output| match activation.prepared { Some(prepared) => { let format = gate_up_prepared_format(selection, dims.kind)?; launch_cached_prepared(context, matrix, prepared, output, format) } - None => launch_cached_projection(context, dims.kind, matrix, activation, output, dims.rows, dims.columns), + None => launch_cached_projection(context, dims, matrix, activation.buffer, output), }) } // Fixed 640-value projection lifecycle shared by the cached artifact path and diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs index ea6c96bf..0266c4cc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs @@ -55,8 +55,9 @@ fn scaled_shared<'ctx>( activation: &DeviceBuffer<'_>, mut cache: Option<&mut MoeWeightCache<'_>>, ) -> Result> { + let expert = BoundExpert { binding, weights, selection: MoeExpertSelection::Shared }; let shared = - expert_mlp(context, binding, weights, MoeExpertSelection::Shared, activation, cache.as_deref_mut(), None)?; + expert_mlp(context, expert, ExpertActivation { buffer: activation, prepared: None }, cache.as_deref_mut())?; let shared_input = upload_f32(context, &shared)?; let (scalar, owned_scalar) = shared_scalar_buffers(context, binding, weights, activation, cache)?; let mut scaled = context.allocate(N * 4).map_err(driver_error)?; @@ -68,14 +69,11 @@ fn scaled_shared<'ctx>( /// Shared expert, router-weighted combine and readback over already computed /// routed expert outputs (`parts` is K*N values in router slot order). pub(super) fn finish_with_parts( - context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - activation: &DeviceBuffer<'_>, - route: &RoutedExperts, + step: &StepCuda<'_, '_, '_>, parts: &[f32], cache: Option<&mut MoeWeightCache<'_>>, ) -> Result> { + let StepCuda { context, binding, weights, activation, route } = *step; let scaled = scaled_shared(context, binding, weights, activation, cache)?; let parts = upload_f32(context, &parts)?; let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get()); @@ -137,8 +135,10 @@ impl<'ctx> CachedRun<'_, 'ctx, '_, '_> { cache: &mut MoeWeightCache<'_>, prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { - let (context, binding, weights, activation) = (self.context, self.binding, self.weights, self.activation); - cached_mlp_down(context, binding, weights, selection, activation, cache, prepared, self.scope, self.origin) + let expert = BoundExpert { binding: self.binding, weights: self.weights, selection }; + let activation = ExpertActivation { buffer: self.activation, prepared }; + let provenance = DownProvenance { scope: self.scope, origin: self.origin }; + cached_mlp_down(self.context, expert, activation, cache, provenance) } fn take(&self, down: ActualDown<'ctx>, selection: MoeExpertSelection) -> Result> { down.take(self.origin, self.binding, self.route.identity(), selection) @@ -204,16 +204,12 @@ impl<'ctx> CachedOwners<'ctx> { ] } } -#[allow(clippy::too_many_arguments)] pub(super) fn execute_cuda_cached( - context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - activation: &DeviceBuffer<'_>, - route: &RoutedExperts, + step: &StepCuda<'_, '_, '_>, cache: &mut MoeWeightCache<'_>, prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { + let StepCuda { context, binding, weights, activation, route } = *step; cache.validate(binding, context)?; route.validate_binding(&binding.identity())?; if !weights.matches(&binding.identity(), route.identity().layer().get()) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs index bad68ece..0db8714c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs @@ -60,12 +60,19 @@ fn admitted_weights(binding: &ModelBinding, layer: LayerId, route: &RoutedExpert Ok(weights) } /// The validated inputs of one expert step on the device. -struct StepCuda<'a, 'c, 'b> { - context: &'a Context<'c>, - binding: &'a ModelBinding, - weights: &'a MoeExpertWeights, - activation: &'a DeviceBuffer<'b>, - route: &'a RoutedExperts, +pub(super) struct StepCuda<'a, 'c, 'b> { + pub(super) context: &'a Context<'c>, + pub(super) binding: &'a ModelBinding, + pub(super) weights: &'a MoeExpertWeights, + pub(super) activation: &'a DeviceBuffer<'b>, + pub(super) route: &'a RoutedExperts, +} +/// The FFN row of one layer handed to its experts: the layer, the routed experts chosen for it (consumed) and the +/// residual that feeds them. +pub(in super::super) struct ExpertRowRequest<'a> { + pub(in super::super) layer: LayerId, + pub(in super::super) route: RoutedExperts, + pub(in super::super) input: &'a ResidualReady, } impl StepCuda<'_, '_, '_> { /// The expert output and the result of closing the step-local prepared owner. @@ -75,7 +82,7 @@ impl StepCuda<'_, '_, '_> { layer: LayerId, cache: Option<&mut MoeWeightCache<'_>>, ) -> (Result>, Result<()>) { - let Self { context, binding, weights, activation, route } = *self; + let binding = self.binding; // One immutable, step-local owner only on the explicitly selected // cache path. It never enters the weight cache or recurrence state. if let Some(kar) = binding.kar_expert_source() { @@ -85,18 +92,17 @@ impl StepCuda<'_, '_, '_> { // refuse: it is simply not consulted for any expert here (the // shared expert takes the uncached path inside the KAR branch). let host = input.mixed(); - return (execute_cuda_kar(context, binding, weights, activation, route, host, (layer.get(), kar)), Ok(())); + return (execute_cuda_kar(self, host, layer.get(), kar), Ok(())); } match cache { Some(cache) => self.dispatch_prepared(cache), - None => (execute_cuda(context, binding, weights, activation, route, None, None), Ok(())), + None => (execute_cuda(self, None, None), Ok(())), } } fn dispatch_prepared(&self, cache: &mut MoeWeightCache<'_>) -> (Result>, Result<()>) { - let Self { context, binding, weights, activation, route } = *self; - match context.prepare_routed_gate_up_q8(activation) { + match self.context.prepare_routed_gate_up_q8(self.activation) { Ok(prepared) => { - let result = execute_cuda(context, binding, weights, activation, route, Some(cache), Some(&prepared)); + let result = execute_cuda(self, Some(cache), Some(&prepared)); // Always attempt owner close before releasing its borrowed // activation, including a projection/readback failure. let closed = prepared.close().map_err(driver_error); @@ -109,12 +115,11 @@ impl StepCuda<'_, '_, '_> { impl MoeExpertStage { pub(in super::super) fn execute( binding: &ModelBinding, - layer: LayerId, - route: RoutedExperts, - input: &ResidualReady, + request: ExpertRowRequest<'_>, txn: &mut QwenStepTxn, mut cache: Option<&mut MoeWeightCache<'_>>, ) -> Result { + let ExpertRowRequest { layer, route, input } = request; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); @@ -133,45 +138,34 @@ impl MoeExpertStage { } } pub(super) fn execute_cuda( - context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - activation: &DeviceBuffer<'_>, - route: &RoutedExperts, + step: &StepCuda<'_, '_, '_>, mut cache: Option<&mut MoeWeightCache<'_>>, prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { + let StepCuda { context, binding, weights, activation, .. } = *step; if let Some(cache) = cache.as_deref_mut() { - return execute_cuda_cached(context, binding, weights, activation, route, cache, prepared); + return execute_cuda_cached(step, cache, prepared); } let mut parts = Vec::new(); parts.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?; for slot in 0..K { - let output = expert_mlp( - context, - binding, - weights, - MoeExpertSelection::Routed { slot }, - activation, - cache.as_deref_mut(), - prepared, - )?; + let expert = BoundExpert { binding, weights, selection: MoeExpertSelection::Routed { slot } }; + let output = + expert_mlp(context, expert, ExpertActivation { buffer: activation, prepared }, cache.as_deref_mut())?; validate_values(&output, N)?; parts.extend_from_slice(&output); } - finish_with_parts(context, binding, weights, activation, route, &parts, cache) + finish_with_parts(step, &parts, cache) } /// Routed experts from the KAR source, then the unchanged shared expert and /// combine. Every routed output is checked finite before it is combined. pub(super) fn execute_cuda_kar( - context: &Context<'_>, - binding: &ModelBinding, - weights: &MoeExpertWeights, - activation: &DeviceBuffer<'_>, - route: &RoutedExperts, + step: &StepCuda<'_, '_, '_>, host_input: &[f32], - (layer, kar): (u32, &KarExpertSource), + layer: u32, + kar: &KarExpertSource, ) -> Result> { + let StepCuda { context, route, .. } = *step; let mut parts = Vec::new(); parts.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?; for slot in 0..K { @@ -180,7 +174,7 @@ pub(super) fn execute_cuda_kar( validate_values(&output, N)?; parts.extend_from_slice(&output); } - finish_with_parts(context, binding, weights, activation, route, &parts, None) + finish_with_parts(step, &parts, None) } pub(super) fn kar_error(error: KarSourceError) -> Error { match error { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs index 63c26391..25bd8d4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs @@ -12,6 +12,28 @@ pub(super) struct MatrixDims { pub(super) kind: MoeMatrixKind, } +/// A Gate, Up or Down matrix of a bound expert. +#[derive(Clone, Copy)] +pub(super) struct ExpertMatrix<'a> { + pub(super) expert: BoundExpert<'a>, + pub(super) role: MoeMatrixRole, +} + +/// The activation a projection reads and, for a routed Gate/Up, its prepared Q8 form. +#[derive(Clone, Copy)] +pub(super) struct ExpertActivation<'a, 'ctx> { + pub(super) buffer: &'a DeviceBuffer<'ctx>, + pub(super) prepared: Option<&'a RoutedGateUpQ8<'ctx>>, +} + +/// An expert matrix (which expert, which role) together with the shape the binding declares for it. +#[derive(Clone, Copy)] +pub(super) struct DeclaredMatrix { + pub(super) selection: MoeExpertSelection, + pub(super) role: MoeMatrixRole, + pub(super) dims: MatrixDims, +} + fn matrix_dims(weights: &MoeExpertWeights, selection: MoeExpertSelection, role: MoeMatrixRole) -> Result { let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?; let kind = weights.kind(selection, role).map_err(binding_error)?; @@ -73,12 +95,12 @@ fn upload_raw_matrix<'ctx>( fn project_into( context: &Context<'_>, matrix: CachedMoeMatrix<'_, '_>, - dims: MatrixDims, - (selection, role): (MoeExpertSelection, MoeMatrixRole), - (activation, prepared): (&DeviceBuffer<'_>, Option<&RoutedGateUpQ8<'_>>), + declared: DeclaredMatrix, + activation: ExpertActivation<'_, '_>, output: &mut DeviceBuffer<'_>, ) -> Result> { - match prepared { + let DeclaredMatrix { selection, role, dims } = declared; + match activation.prepared { Some(prepared) => { if !matches!(selection, MoeExpertSelection::Routed { .. }) || !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up) @@ -91,7 +113,7 @@ fn project_into( launch_cached_prepared(context, matrix, prepared, output, format)?; } None => { - launch_cached_projection(context, dims.kind, matrix, activation, output, dims.rows, dims.columns)?; + launch_cached_projection(context, dims, matrix, activation.buffer, output)?; } } download_f32(output, dims.rows) @@ -119,17 +141,13 @@ fn allocate_output<'ctx>(context: &'ctx Context<'_>, rows: usize) -> Result, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, - role: MoeMatrixRole, - activation: &DeviceBuffer<'_>, + requested: ExpertMatrix<'_>, + activation: ExpertActivation<'_, '_>, cache: Option<&mut MoeWeightCache<'_>>, - prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { + let ExpertMatrix { expert: BoundExpert { binding, weights, selection }, role } = requested; let dims = matrix_dims(weights, selection, role)?; if ![FF, N].contains(&dims.rows) { return Err(Error::InvalidDimension); @@ -147,7 +165,8 @@ pub(super) fn project_matrix( } }; let mut output = allocate_output(context, dims.rows)?; - let result = project_into(context, matrix, dims, (selection, role), (activation, prepared), &mut output); + let declared = DeclaredMatrix { selection, role, dims }; + let result = project_into(context, matrix, declared, activation, &mut output); close_projection(result, output, owned) } // Retained legacy 64-row transport reference for its original refusal tests. // Production projects the complete matrix above, without host projection/math. @@ -193,20 +212,17 @@ pub(super) fn dual_routed_format(format: leleka_cuda_driver::MmqFormat) -> Route F::Q2Down => RoutedFormat::Q2_0, } } -#[allow(clippy::too_many_arguments)] pub(super) fn launch_cached_projection( context: &Context<'_>, - kind: MoeMatrixKind, + dims: MatrixDims, matrix: CachedMoeMatrix<'_, '_>, activation: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, - rows: usize, - columns: usize, ) -> Result<()> { match matrix { - CachedMoeMatrix::Raw(raw) => launch_projection(context, kind, raw, activation, output, rows, columns), + CachedMoeMatrix::Raw(raw) => launch_projection(context, dims, raw, activation, output), CachedMoeMatrix::Dual(format, owner) => { - if dual_format_kind(format) != (kind, rows, columns) { + if dual_format_kind(format) != (dims.kind, dims.rows, dims.columns) { return Err(Error::IdentityMismatch); } owner.native_q8_1(activation, output).map_err(driver_error) @@ -283,13 +299,12 @@ fn launch_plan(kind: MoeMatrixKind) -> Option { } pub(super) fn launch_projection( context: &Context<'_>, - kind: MoeMatrixKind, + dims: MatrixDims, matrix: &DeviceBuffer<'_>, activation: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, - rows: usize, - columns: usize, ) -> Result<()> { + let MatrixDims { columns, rows, kind } = dims; let Some(plan) = launch_plan(kind) else { return Err(Error::Unsupported(Stage::MoeExpert)); }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs index a4d2eaac..1e596ff3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs @@ -10,6 +10,8 @@ mod adaptive_packets; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_prompt_finish.rs"] mod prompt_finish; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(in crate::qwen_forward) use prompt_finish::NativePromptFinish; #[path = "moe_mmq_chunk.rs"] mod resident; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -69,6 +71,7 @@ mod adaptive; #[path = "moe_group_chunk/impl_preparedmoerow.rs"] mod impl_preparedmoerow; +pub(in crate::qwen_forward) use impl_preparedmoerow::ChunkFfnLayer; #[allow(unused_imports)] use impl_preparedmoerow::grouped_pairs; #[path = "moe_group_chunk/bound_rows_fn.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs index a024a038..78d481d9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/bound_rows_fn.rs @@ -67,15 +67,14 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> { fn ungrouped_row(&self, cache: &mut MoeWeightCache<'ctx>, i: usize) -> Result { let row = self.rows[i].row(); - let values = execute_cuda_cached( - self.context, - self.binding, - &row.weights, - self.activations[i].buffer()?, - &row.route, - cache, - Some(&self.prepared[i]), - )?; + let step = StepCuda { + context: self.context, + binding: self.binding, + weights: &row.weights, + activation: self.activations[i].buffer()?, + route: &row.route, + }; + let values = execute_cuda_cached(&step, cache, Some(&self.prepared[i]))?; ExpertReady::from_completed(self.binding.identity(), row.route.identity(), values) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs index 96d2aca7..d54650d4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs @@ -22,11 +22,16 @@ impl<'ctx> SharedOwners<'ctx> { (scope, origin): (&DownScope<'ctx>, &Rc), ) -> Result<()> { let selection = MoeExpertSelection::Shared; - self.shared = - Some( - cached_mlp_down(context, binding, &row.weights, selection, activation, cache, None, scope, origin)? - .take(origin, binding, row.route.identity(), selection)?, - ); + self.shared = Some( + cached_mlp_down( + context, + BoundExpert { binding, weights: &row.weights, selection }, + ExpertActivation { buffer: activation, prepared: None }, + cache, + DownProvenance { scope, origin }, + )? + .take(origin, binding, row.route.identity(), selection)?, + ); let scalar_weights = cache.shared_scalar(binding, &row.weights)?; self.scalar = Some(scope.shared_scalar(activation, scalar_weights)?); self.scaled = Some( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs index 01d8aed1..2b97460d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs @@ -3,6 +3,14 @@ #[allow(unused_imports)] use super::*; +/// The FFN rows of one chunk layer together with the binding they were sealed against. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ChunkFfnLayer<'a> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) layer: LayerId, + pub(in crate::qwen_forward) rows: &'a [ChunkFfnRow], +} + impl PreparedMoeRow { pub(in crate::qwen_forward) fn validate( &self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs index 9a0dd709..29924aab 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs @@ -37,8 +37,9 @@ fn replay_selection( scope: &DownScope<'_>, ) -> Result<()> { let activation = scope.upload(values)?; - let result = scope - .project(selection, |out| launch_cached_projection(context, kind, matrix, activation.buffer()?, out, N, FF)); + let result = scope.project(selection, |out| { + launch_cached_projection(context, MatrixDims { kind, rows: N, columns: FF }, matrix, activation.buffer()?, out) + }); let close_activation = activation.close(); match result { Err(primary) => { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs index 8db1b6d9..599ac96f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs @@ -74,7 +74,7 @@ impl MoeExpertStage { let products = if arm == 0 { Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)? } else { - Self::execute_chunk_mmq(binding, layer, rows, chunk, cache, &mut || false)? + Self::execute_chunk_mmq(ChunkFfnLayer { binding, layer, rows }, chunk, cache, &mut || false)? }; check_products(binding, rows, &products)?; validate_sources(binding, layer, rows, chunk, false)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index 78c8313f..59a4a7d9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -15,17 +15,13 @@ use resident_fns::execute_resident; impl MoeExpertStage { pub(in crate::qwen_forward) fn execute_chunk_mmq<'ctx>( - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + ffn: ChunkFfnLayer<'_>, chunk: &mut QwenChunkTxn<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { Self::execute_chunk_mmq_with_finish( - binding, - layer, - rows, + ffn, chunk, cache, cancelled, @@ -35,29 +31,16 @@ impl MoeExpertStage { } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn execute_chunk_mmq_native_prompt<'ctx>( - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + ffn: ChunkFfnLayer<'_>, chunk: &mut QwenChunkTxn<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, - products: &mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>, - dense: &super::super::super::dense_weight_cache::DenseWeightCache<'_>, + finish: super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, ) -> Result> { - Self::execute_chunk_mmq_with_finish( - binding, - layer, - rows, - chunk, - cache, - cancelled, - Some(super::prompt_finish::NativePromptFinish { products, dense }), - ) + Self::execute_chunk_mmq_with_finish(ffn, chunk, cache, cancelled, Some(finish)) } fn execute_chunk_mmq_with_finish<'ctx>( - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + ffn: ChunkFfnLayer<'_>, chunk: &mut QwenChunkTxn<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, @@ -65,6 +48,7 @@ impl MoeExpertStage { super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, >, ) -> Result> { + let ChunkFfnLayer { binding, layer, rows } = ffn; if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) { return Err(Error::InvalidDimension); } @@ -81,6 +65,12 @@ impl MoeExpertStage { } } +/// The sealed chunk transaction a resident batch reads and the device context it runs on. +pub(super) struct ActualChunk<'a, 'ctx> { + pub(super) txn: &'a QwenChunkTxn<'a, 'ctx>, + pub(super) context: &'ctx Context<'ctx>, +} + /// One MMQ layer batch: the rows plus the optional native prompt finish. pub(super) struct ChunkCall<'a, 'ctx, 'l, 'd> { pub(super) binding: &'a ModelBinding, @@ -171,7 +161,7 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> { return Err(Error::IdentityMismatch); } cache.with_mmq_workspace(binding, context, admission, |cache, workspace| { - self.resident(actual, context, cache, workspace, cancelled) + self.resident(ActualChunk { txn: actual, context }, cache, workspace, cancelled) }) }); #[cfg(test)] @@ -185,15 +175,14 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> { fn resident( self, - actual: &QwenChunkTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, + actual: ActualChunk<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, workspace: &mut MmqWorkspace<'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { execute_resident( - actual, - context, + actual.txn, + actual.context, self.binding, self.layer, self.rows, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs index bf9ccd0f..69e5eb50 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs @@ -6,9 +6,9 @@ use super::super::super::moe_prefill_batch::{ use super::super::moe_down::ResidentPackedDown; use super::*; -pub(super) struct NativePromptFinish<'loan, 'ctx, 'dense> { - pub(super) products: &'loan mut MoeMicroProducts<'ctx>, - pub(super) dense: &'loan DenseWeightCache<'dense>, +pub(in crate::qwen_forward) struct NativePromptFinish<'loan, 'ctx, 'dense> { + pub(in crate::qwen_forward) products: &'loan mut MoeMicroProducts<'ctx>, + pub(in crate::qwen_forward) dense: &'loan DenseWeightCache<'dense>, } /// The sealed window rows one native prompt finish is checked against. From 52db7c41d8779e87cc7cb5ba47d70ec53dc7429e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:14:54 +0100 Subject: [PATCH 20/42] STRA-338 params e04: weight cache MTP step, shared tail, MMQ triplet and chunk admission take domain request structs Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/ffn_rows.rs --- .../prepare_micro_ffn_rows_fn/ffn_rows.rs | 19 +++-- .../src/qwen_forward/moe_expert.rs | 5 ++ .../ordered_down_refusal_fn.rs | 7 +- .../project_group_source_consumers_fn.rs | 31 ++++--- .../src/qwen_forward/moe_mmq_chunk.rs | 6 +- .../moe_mmq_chunk/resident_fns.rs | 3 +- .../src/qwen_forward/moe_weight_cache.rs | 8 ++ .../moe_weight_cache/cache_requests.rs | 72 +++++++++++++++++ .../impl_moeweightcache_3.rs | 5 +- .../impl_moeweightcache_4.rs | 81 +++++++------------ .../impl_moeweightcache_5.rs | 18 ++--- .../impl_moeweightcache_6.rs | 39 +++++---- .../impl_moeweightcache_8.rs | 4 +- .../mtp_attention/release_transport_fn.rs | 5 +- .../qwen_forward/mtp_experts/impl_mtpblock.rs | 16 +--- .../qwen_forward/shared_expert_workspace.rs | 38 ++++++--- 16 files changed, 221 insertions(+), 136 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_requests.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/ffn_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/ffn_rows.rs index c88d516e..ae6e16ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/ffn_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/ffn_rows.rs @@ -34,12 +34,19 @@ fn route_shared_micro<'driver>( let router = cache.router(binding, layer.get())?; let transient = MoePrefillStage::transient_bytes(inputs.len(), MoeBf16Profile::HighOnly)?; moe_cache.reserve_mmq_transient(binding, current, transient)?; - moe_cache.with_native_shared_weights(binding, current, layer, transient, |context, weights, resources| { - cache.retained_context(binding, context)?; - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - let gemm = workspace.gdn_gemm().map_err(crate::qwen_forward::qsa_index::driver_error)?; - MoePrefillStage::route_shared_micro(binding, layer, inputs, context, router, weights, None, resources, &gemm) - }) + moe_cache.with_native_shared_weights( + binding, + current, + crate::qwen_forward::moe_weight_cache::SharedWeightsRequest { layer, transient_bytes: transient }, + |context, weights, resources| { + cache.retained_context(binding, context)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let gemm = workspace.gdn_gemm().map_err(crate::qwen_forward::qsa_index::driver_error)?; + MoePrefillStage::route_shared_micro( + binding, layer, inputs, context, router, weights, None, resources, &gemm, + ) + }, + ) } /// The FFN row of every proof and detached read: routed from the shared products or from the FFN read. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs index c0d2c732..6e1b6180 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs @@ -4,7 +4,12 @@ use super::bound_expert::BoundExpert; use super::contract::{Error, LayerId, Result, Stage, TokenLayer}; use super::gr::ResidualReady; use super::moe_route::RoutedExperts; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unused_imports)] +use super::moe_weight_cache::SourceMatrix; use super::moe_weight_cache::{CachedMoeMatrix, MoeWeightCache}; +#[allow(unused_imports)] +use super::moe_weight_cache::{MmqChunkRequest, SharedTailRow}; use super::session::QwenStepTxn; use crate::model_binding::kar_expert_source::{KarExpertSource, KarSourceError}; use crate::model_binding::qwen4exp_input::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs index 29924aab..f1623097 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs @@ -191,7 +191,12 @@ pub(super) fn finish_shared_queued( return Err(Error::IdentityMismatch); } let route = std::array::from_fn(|i| row.route.weights()[i].get()); - let result = cache.compose_target_shared_tail(binding, context, &row.weights, identity, activation, packet, &route); + let result = cache.compose_target_shared_tail( + binding, + context, + SharedTailRow { weights: &row.weights, identity }, + crate::qwen_forward::shared_expert_workspace::SharedTailInputs { activation, packed: packet, route: &route }, + ); scope.record(&result); let values = result?; row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs index cb2dcd07..1958d1be 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs @@ -141,7 +141,7 @@ impl<'ctx> DirectGroup<'_, 'ctx> { format: RoutedFormat, stage: leleka_cuda_driver::RoutedFiniteStage, ) -> Result<()> { - cache.with_matrix_routed_source(self.binding, source, 0, role, |matrix, _, _| { + cache.with_matrix_routed_source(self.binding, source, SourceMatrix { member: 0, role }, |matrix, _, _| { match matrix { CachedMoeMatrix::Raw(raw) => columns.project_gate_up(raw, grouped.buffer_mut()?, format), CachedMoeMatrix::Dual(actual, owner) => { @@ -184,17 +184,24 @@ impl<'ctx> DirectGroup<'_, 'ctx> { return Err(Error::Unsupported(Stage::Executor)); } scope.with_workspace(|workspace| { - cache.with_matrix_routed_source(binding, source, 0, MoeMatrixRole::Down, |matrix, health, source| { - scope.project_columns_direct( - &selections, - |out, cancel| { - let input = hidden_buffer(hidden)?; - self.source_down_columns(workspace, matrix, kind, format, input, out, &selections, cancel) - }, - |down_source, cancel| self.source_copy_down(actual, packets, health, source, down_source, cancel), - cancelled, - ) - }) + cache.with_matrix_routed_source( + binding, + source, + SourceMatrix { member: 0, role: MoeMatrixRole::Down }, + |matrix, health, source| { + scope.project_columns_direct( + &selections, + |out, cancel| { + let input = hidden_buffer(hidden)?; + self.source_down_columns(workspace, matrix, kind, format, input, out, &selections, cancel) + }, + |down_source, cancel| { + self.source_copy_down(actual, packets, health, source, down_source, cancel) + }, + cancelled, + ) + }, + ) })?; Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index 59a4a7d9..c3246649 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -120,7 +120,11 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> { } else { Vec::new() }; - cache.admit_mmq_chunk(binding, chunk.context()?, rows.len(), &triplets, original_prompt) + cache.admit_mmq_chunk( + binding, + chunk.context()?, + MmqChunkRequest { row_count: rows.len(), triplets: &triplets, original_prompt }, + ) } /// Actual21/23, T1 and GU22 under the IQ3-only policy take native. This is an admission decision BEFORE MMQ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs index 6f3beaef..01c2a3f1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs @@ -312,7 +312,8 @@ impl<'ctx> Resident<'_, '_, 'ctx> { let indices = self.group_indices(row, first, pairs)?; let group = source.gather_gate_up(&indices).map_err(mmq_error)?; let selection = MoeExpertSelection::Routed { slot: first.slot }; - cache.with_mmq_triplet(self.binding, &row.row().weights, selection, original_prompt, |gate, up, down| { + let expert = BoundExpert { binding: self.binding, weights: &row.row().weights, selection }; + cache.with_mmq_triplet(expert, original_prompt, |gate, up, down| { let hidden = group.gate_up(gate, up).map_err(mmq_error)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index 47a1e518..030b97d0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -10,8 +10,16 @@ use leleka_cuda_driver::{ RoutedGroupWorkspace, RoutedStageFiniteGuard, }; use std::cell::{Cell, RefCell}; +#[path = "moe_weight_cache/cache_requests.rs"] +mod cache_requests; #[path = "mtp_kv_resident.rs"] mod mtp_kv_resident; +pub(in crate::qwen_forward) use super::bound_expert::BoundExpert; +pub(in crate::qwen_forward) use cache_requests::{ + FixedMtpWeights, MmqChunkRequest, MtpExpertPicks, MtpStepSite, PendingMtpKv, SharedTailRow, +}; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(in crate::qwen_forward) use cache_requests::{SharedWeightsRequest, SourceMatrix}; use mtp_kv_resident::MtpKvResident; #[path = "cache_lru_index.rs"] mod cache_lru_index; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_requests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_requests.rs new file mode 100644 index 00000000..3bb0f684 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_requests.rs @@ -0,0 +1,72 @@ +//! The request objects the encoded-weight cache serves: which MTP step, which shared tail, which source matrix. +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeWeightDescriptor}; +use crate::qwen_forward::contract::TokenLayer; +use crate::qwen_forward::mtp::{DenseKv, MtpFrame}; +use crate::qwen_forward::session::QwenSession; +use leleka_cuda_driver::{Context, DeviceBuffer}; + +/// Where and under which draft frame one fixed MTP step runs: the model binding, the device context, the session +/// and the frame, all of which the cache admits together before it touches a weight. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct MtpStepSite<'a, 'c, 's> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) context: &'a Context<'c>, + pub(in crate::qwen_forward) session: &'a QwenSession<'s>, + pub(in crate::qwen_forward) frame: &'a MtpFrame, +} + +/// The cache-owned expert bank and the four dense shared-expert matrices a fixed MTP step is checked against. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct FixedMtpWeights<'a, 'k> { + pub(in crate::qwen_forward) bank: &'a DeviceBuffer<'k>, + pub(in crate::qwen_forward) shared: [&'a DeviceBuffer<'k>; 4], +} + +/// The mixed hidden row of an MTP step and the ten routed expert ids and router weights it was routed to. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct MtpExpertPicks<'a> { + pub(in crate::qwen_forward) mixed: &'a [f32], + pub(in crate::qwen_forward) ids: [u32; 10], + pub(in crate::qwen_forward) weights: [f32; 10], +} + +/// The draft KV step waiting to be prepared and attended: its dense KV, frame, binding and device context. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct PendingMtpKv<'a, 'c> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) context: &'a Context<'c>, + pub(in crate::qwen_forward) next: &'a DenseKv, + pub(in crate::qwen_forward) frame: &'a MtpFrame, +} + +/// The row whose target shared-expert tail is composed: its expert weights and its token/layer identity. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct SharedTailRow<'a> { + pub(in crate::qwen_forward) weights: &'a MoeExpertWeights, + pub(in crate::qwen_forward) identity: TokenLayer, +} + +/// What one MMQ chunk is admitted for: its row count, the Gate/Up/Down descriptors of each row and whether it is +/// the original prompt operator. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct MmqChunkRequest<'a> { + pub(in crate::qwen_forward) row_count: usize, + pub(in crate::qwen_forward) triplets: &'a [[MoeWeightDescriptor; 3]], + pub(in crate::qwen_forward) original_prompt: bool, +} + +/// Which matrix of the routed source scope is read: the group member and the matrix role. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct SourceMatrix { + pub(in crate::qwen_forward) member: usize, + pub(in crate::qwen_forward) role: crate::model_binding::qwen4exp_input::MoeMatrixRole, +} + +/// Which layer's shared weights are lent and how many transient bytes must still fit while they are lent. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct SharedWeightsRequest { + pub(in crate::qwen_forward) layer: crate::qwen_forward::contract::LayerId, + pub(in crate::qwen_forward) transient_bytes: usize, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs index a2d9e332..a27464ac 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs @@ -169,15 +169,14 @@ impl<'ctx> MoeWeightCache<'ctx> { &mut self, binding: &ModelBinding, context: &Context<'_>, - layer: super::super::super::contract::LayerId, - transient: usize, + request: SharedWeightsRequest, execute: impl FnOnce( &'ctx Context<'ctx>, super::super::super::moe_prefill_batch::SharedWeights<'_, 'ctx>, &mut super::super::super::moe_prefill_batch::MoePrefillResources<'ctx>, ) -> Result, ) -> Result { - let keys = self.admit_native_shared(binding, context, layer, transient)?; + let keys = self.admit_native_shared(binding, context, request.layer, request.transient_bytes)?; let buffers = raw_shared_buffers(&self.main, &keys)?; let mut owner = self.native_prefill_resources(binding, context)?; let result = execute( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs index 57c21d7f..f1ef3b89 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338: impl MoeWeightCache (4). +use super::super::super::shared_expert_workspace::{SharedTailInputs, SharedTailKeys, WorkspaceOwner}; use super::impl_moeweightcache_3::shared_keys_fn::{raw_shared_buffers, shared_descriptors}; #[allow(unused_imports)] use super::*; @@ -8,17 +9,14 @@ impl<'ctx> MoeWeightCache<'ctx> { /// Source-descriptor admission precedes all fills. Requested entries cannot /// evict one another; every actual weight remains immutably borrowed until /// the closed driver's completion/readback has consumed the result. - #[allow(clippy::too_many_arguments)] pub(in super::super::super) fn compose_target_shared_tail( &mut self, binding: &ModelBinding, context: &Context<'_>, - weights: &MoeExpertWeights, - identity: super::super::super::contract::TokenLayer, - activation: &DeviceBuffer<'_>, - packed: &DeviceBuffer<'_>, - route: &[f32; 10], + row: SharedTailRow<'_>, + inputs: SharedTailInputs<'_, '_>, ) -> Result> { + let SharedTailRow { weights, identity } = row; self.validate(binding, context)?; if !weights.matches(&binding.identity(), identity.layer().get()) { return Err(Error::IdentityMismatch); @@ -26,7 +24,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let keys = shared_descriptors(binding, weights)?; self.fill_shared_weights(binding, weights, &keys)?; self.validate(binding, context)?; - let result = self.compose_shared(binding, context, identity, &keys, (activation, packed, route)); + let result = self.compose_shared(binding, context, SharedTailKeys { identity, keys: &keys }, inputs); if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } @@ -40,54 +38,30 @@ impl<'ctx> MoeWeightCache<'ctx> { &mut self, binding: &ModelBinding, context: &Context<'_>, - identity: super::super::super::contract::TokenLayer, - keys: &[MoeWeightDescriptor; 4], - (activation, packed, route): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &[f32; 10]), + keyed: SharedTailKeys<'_>, + inputs: SharedTailInputs<'_, '_>, ) -> Result> { - let buffers = raw_shared_buffers(&self.main, keys)?; - self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose( - binding, - &self.mmq_owner, - context, - identity, - keys, - buffers, - activation, - packed, - route, - ) + let buffers = raw_shared_buffers(&self.main, keyed.keys)?; + let authenticated = WorkspaceOwner { binding, owner: &self.mmq_owner, context }; + self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose(authenticated, keyed, buffers, inputs) } - #[allow(clippy::too_many_arguments)] pub(in super::super::super) fn compose_fixed_mtp_experts( &self, - binding: &ModelBinding, - context: &Context<'_>, - frame: &super::super::super::mtp::MtpFrame, - session: &super::super::super::session::QwenSession<'_>, - bank: &DeviceBuffer<'_>, - shared: [&DeviceBuffer<'_>; 4], - mixed: &[f32], - ids: [u32; 10], - weights: [f32; 10], + site: MtpStepSite<'_, '_, '_>, + weights: FixedMtpWeights<'_, '_>, + picks: MtpExpertPicks<'_>, failed: Rc>, ) -> Result> { - self.admit_fixed_mtp(binding, context, frame, session, bank, shared)?; - let result = - self.compose_mtp_slot(binding, context, (frame, session), (bank, shared), (mixed, ids, weights), &failed); - if failed.get() || context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.admit_fixed_mtp(site, weights)?; + let result = self.compose_mtp_slot(site, weights, picks, &failed); + if failed.get() || site.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } result } - fn admit_fixed_mtp( - &self, - binding: &ModelBinding, - context: &Context<'_>, - frame: &super::super::super::mtp::MtpFrame, - session: &super::super::super::session::QwenSession<'_>, - bank: &DeviceBuffer<'_>, - shared: [&DeviceBuffer<'_>; 4], - ) -> Result<()> { + fn admit_fixed_mtp(&self, site: MtpStepSite<'_, '_, '_>, weights: FixedMtpWeights<'_, '_>) -> Result<()> { + let MtpStepSite { binding, context, session, frame } = site; + let FixedMtpWeights { bank, shared } = weights; self.validate(binding, context)?; frame.validate(binding, session)?; if !self.requires_iq3_mmq_admission() { @@ -110,13 +84,14 @@ impl<'ctx> MoeWeightCache<'ctx> { } fn compose_mtp_slot( &self, - binding: &ModelBinding, - context: &Context<'_>, - (frame, session): (&super::super::super::mtp::MtpFrame, &super::super::super::session::QwenSession<'_>), - (bank, shared): (&DeviceBuffer<'_>, [&DeviceBuffer<'_>; 4]), - (mixed, ids, weights): (&[f32], [u32; 10], [f32; 10]), + site: MtpStepSite<'_, '_, '_>, + weights: FixedMtpWeights<'_, '_>, + picks: MtpExpertPicks<'_>, failed: &Rc>, ) -> Result> { + let MtpStepSite { binding, context, session, frame } = site; + let FixedMtpWeights { bank, shared } = weights; + let MtpExpertPicks { mixed, ids, weights } = picks; let mut slot = self.mtp_experts.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; slot.as_mut().ok_or(Error::IdentityMismatch)?.compose( binding, @@ -154,13 +129,11 @@ impl<'ctx> MoeWeightCache<'ctx> { } pub(in super::super::super) fn attend_mtp_kv( &self, - binding: &ModelBinding, - context: &Context<'_>, - next: &super::super::super::mtp::DenseKv, - frame: &super::super::super::mtp::MtpFrame, + step: PendingMtpKv<'_, '_>, query: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { + let PendingMtpKv { binding, context, next, frame } = step; self.prepare_mtp_kv(binding, context, next, frame)?; let mut slot = self.mtp_kv.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.attend( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs index 7ea120e7..f8ee88a9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs @@ -71,10 +71,9 @@ impl<'ctx> MoeWeightCache<'ctx> { &self, binding: &ModelBinding, context: &Context<'_>, - rows: usize, - triplets: &[[MoeWeightDescriptor; 3]], - original_prompt: bool, + request: MmqChunkRequest<'_>, ) -> Result> { + let MmqChunkRequest { row_count: rows, triplets, original_prompt } = request; self.validate(binding, context)?; self.check_mmq_chunk_shape(rows, original_prompt)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -122,9 +121,7 @@ impl<'ctx> MoeWeightCache<'ctx> { /// missing/evicted descriptor refuses, never manufactures a weight view. pub(in super::super::super) fn with_mmq_triplet( &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, + expert: BoundExpert<'_>, original_prompt: bool, execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, ) -> Result { @@ -132,17 +129,16 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(Error::IdentityMismatch); } if original_prompt || self.requires_iq3_mmq_admission() { - return self.with_integer_mmq_triplet(binding, weights, selection, original_prompt, execute); + return self.with_integer_mmq_triplet(expert, original_prompt, execute); } - self.with_native_mmq_triplet(binding, weights, selection, execute) + self.with_native_mmq_triplet(expert, execute) } fn with_native_mmq_triplet( &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, + expert: BoundExpert<'_>, execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, ) -> Result { + let BoundExpert { binding, weights, selection } = expert; self.validate(binding, self.context)?; let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; let mut keys = Vec::new(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs index 53a2ad7e..bd058881 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs @@ -5,6 +5,14 @@ use super::*; const TRIPLET_ROLES: [MoeMatrixRole; 3] = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; +/// The cache totals a published triplet leaves behind: bytes held in the main set, the next LRU age and the bytes read +/// from the source to produce it. +struct TripletAccounting { + main_bytes: usize, + next_age: u64, + read_bytes: usize, +} + /// The Gate/Up/Down identity of one requested triplet and how much of it is missing from the cache. struct TripletPlan { keys: [MoeWeightDescriptor; 3], @@ -19,16 +27,15 @@ impl<'ctx> MoeWeightCache<'ctx> { // Every requested owner stays resident while missing roles are admitted. pub(in super::super) fn with_integer_mmq_triplet( &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, + expert: BoundExpert<'_>, original_prompt: bool, execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, ) -> Result { + let BoundExpert { binding, weights, selection } = expert; self.validate(binding, self.context)?; let plan = self.triplet_plan(binding, weights, selection, original_prompt)?; let next_age = self.triplet_admit(&plan)?; - self.triplet_fill(binding, weights, selection, original_prompt, &plan, next_age)?; + self.triplet_fill(expert, original_prompt, &plan, next_age)?; self.triplet_note_hits(&plan); self.validate(binding, self.context)?; let [gate, up, down] = self.triplet_owners(&plan.keys)?; @@ -37,15 +44,14 @@ impl<'ctx> MoeWeightCache<'ctx> { fn triplet_fill( &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, + expert: BoundExpert<'_>, original_prompt: bool, plan: &TripletPlan, next_age: u64, ) -> Result<()> { + let BoundExpert { binding, weights, selection } = expert; match plan.missing { - 3 => self.triplet_full_miss(binding, weights, selection, original_prompt, plan, next_age), + 3 => self.triplet_full_miss(expert, original_prompt, plan, next_age), 0 => self.triplet_hit(plan, next_age), _ => self.triplet_partial(binding, weights, selection, plan), } @@ -135,13 +141,12 @@ impl<'ctx> MoeWeightCache<'ctx> { fn triplet_full_miss( &mut self, - binding: &ModelBinding, - weights: &MoeExpertWeights, - selection: MoeExpertSelection, + expert: BoundExpert<'_>, original_prompt: bool, plan: &TripletPlan, next_age: u64, ) -> Result<()> { + let BoundExpert { binding, weights, selection } = expert; let update = self.prepare_lru_updates(&self.triplet_ages(plan, next_age))?; // Read actual bound spans before any upload. The driver owns its // padded staging until all attempted copies have completed. @@ -156,7 +161,7 @@ impl<'ctx> MoeWeightCache<'ctx> { self.close_triplet_owners(owners); return Err(primary); } - self.publish_triplet(plan, owners, main_bytes, next_age, read_bytes); + self.publish_triplet(plan, owners, TripletAccounting { main_bytes, next_age, read_bytes }); Ok(()) } @@ -191,14 +196,8 @@ impl<'ctx> MoeWeightCache<'ctx> { /// No fallible allocation/validation follows the first insertion. /// Publish the complete triplet only after driver completion. - fn publish_triplet( - &mut self, - plan: &TripletPlan, - owners: [MmqWeights<'ctx>; 3], - main_bytes: usize, - next_age: u64, - read_bytes: usize, - ) { + fn publish_triplet(&mut self, plan: &TripletPlan, owners: [MmqWeights<'ctx>; 3], accounting: TripletAccounting) { + let TripletAccounting { main_bytes, next_age, read_bytes } = accounting; for (index, owner) in owners.into_iter().enumerate() { let weight = EncodedWeight::Dual(plan.formats[index], owner); let age = self.age + index as u64 + 1; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs index 0236a8e7..f743b451 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs @@ -32,14 +32,14 @@ impl<'ctx> MoeWeightCache<'ctx> { &mut self, binding: &ModelBinding, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, - member: usize, - role: MoeMatrixRole, + matrix: SourceMatrix, consume: impl FnOnce( CachedMoeMatrix<'_, 'ctx>, &RoutedSourceHealth<'_, 'ctx>, &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>, ) -> Result, ) -> Result { + let SourceMatrix { member, role } = matrix; self.validate(binding, self.context)?; if !self.uses_direct_native_down_packets() { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs index e48bc157..c730e443 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs @@ -100,10 +100,7 @@ impl<'ctx> AttendBuffers<'ctx> { self.q = Some(upload_transport_f32(context, query, failed)?); self.y = Some(allocate(context, Q)?); cache.attend_mtp_kv( - binding, - context, - pending, - frame, + crate::qwen_forward::moe_weight_cache::PendingMtpKv { binding, context, next: pending, frame }, self.q.as_ref().ok_or(Error::CudaExecution)?, self.y.as_mut().ok_or(Error::CudaExecution)?, )?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs index 30b4f77a..841be4be 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs @@ -121,18 +121,10 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> { let (binding, context, session) = (self.binding, self.context, self.session); let mixed = input.mixed(); let cache = self.cache; - cache.compose_fixed_mtp_experts( - binding, - context, - frame, - session, - bank, - shared, - mixed, - ids, - route_weights, - failed, - ) + let site = crate::qwen_forward::moe_weight_cache::MtpStepSite { binding, context, session, frame }; + let weights = crate::qwen_forward::moe_weight_cache::FixedMtpWeights { bank, shared }; + let picks = crate::qwen_forward::moe_weight_cache::MtpExpertPicks { mixed, ids, weights: route_weights }; + cache.compose_fixed_mtp_experts(site, weights, picks, failed) } else { mtp_expert_transport::compose(self.context, bank, shared, input.mixed(), ids, route_weights, failed) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs index 941a2652..91e0f544 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs @@ -10,6 +10,29 @@ use std::rc::Rc; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) const ALLOCATED_BYTES: usize = 42_092; +/// What a shared-tail compose is authenticated against: the cache's binding, MMQ owner token and device context. +#[derive(Clone, Copy)] +pub(super) struct WorkspaceOwner<'a, 'c> { + pub(super) binding: &'a ModelBinding, + pub(super) owner: &'a Rc<()>, + pub(super) context: &'a Context<'c>, +} + +/// The row a shared tail belongs to and the four descriptors of its shared weights. +#[derive(Clone, Copy)] +pub(super) struct SharedTailKeys<'a> { + pub(super) identity: TokenLayer, + pub(super) keys: &'a [MoeWeightDescriptor; 4], +} + +/// The activation, the packed routed output and the ten router weights the shared tail combines. +#[derive(Clone, Copy)] +pub(super) struct SharedTailInputs<'a, 'b> { + pub(super) activation: &'a DeviceBuffer<'b>, + pub(super) packed: &'a DeviceBuffer<'b>, + pub(super) route: &'a [f32; 10], +} + pub(super) struct TargetSharedWorkspace<'ctx> { binding: BindingIdentity, owner: Rc<()>, @@ -116,19 +139,16 @@ impl<'ctx> TargetSharedWorkspace<'ctx> { } Ok(()) } - #[allow(clippy::too_many_arguments)] pub(super) fn compose( &mut self, - binding: &ModelBinding, - owner: &Rc<()>, - context: &Context<'_>, - identity: TokenLayer, - keys: &[MoeWeightDescriptor; 4], + authenticated: WorkspaceOwner<'_, '_>, + keyed: SharedTailKeys<'_>, buffers: [&DeviceBuffer<'ctx>; 4], - activation: &DeviceBuffer<'_>, - packed: &DeviceBuffer<'_>, - route: &[f32; 10], + inputs: SharedTailInputs<'_, '_>, ) -> Result> { + let WorkspaceOwner { binding, owner, context } = authenticated; + let SharedTailKeys { identity, keys } = keyed; + let SharedTailInputs { activation, packed, route } = inputs; self.check_compose(binding, (owner, context), identity, (keys, &buffers))?; let weights = shared_weights(keys, buffers)?; let completion = self.workspace.compose(activation, weights, packed, route).map_err(driver_error)?; From f1e216a316c0a39f23a7a7c195a3306ebc19b96d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:15:10 +0100 Subject: [PATCH 21/42] STRA-338 params e03: MTP expert transport takes ExpertWeights/SelectedRoute/RoutedExpert; first-seed restore takes RetainedFirstSeed; adaptive wave left to e05 --- .../src/qwen_forward/moe_group_adaptive.rs | 6 +- .../moe_group_adaptive/adaptive_wave_fn.rs | 86 +++++++++---------- .../src/qwen_forward/mtp.rs | 2 +- .../impl_mtpdecoder/batched_support.rs | 9 +- .../impl_mtpdecoder/impl_mtpdecoder_2_2.rs | 3 +- .../src/qwen_forward/mtp_expert_transport.rs | 6 +- .../mtp_expert_transport/impl_role.rs | 11 ++- .../mtp_expert_transport/shared_project_fn.rs | 55 +++++++----- .../mtp_expert_transport_gpu/exact_fn.rs | 3 +- .../mtp_expert_transport_gpu/phases_fn.rs | 8 +- .../private_owner_guards_fn.rs | 4 +- .../src/qwen_forward/mtp_expert_workspace.rs | 18 +++- .../qwen_forward/mtp_experts/impl_mtpblock.rs | 4 +- .../src/qwen_forward/mtp_state.rs | 7 ++ .../qwen_forward/mtp_state/impl_mtpsession.rs | 7 +- 15 files changed, 129 insertions(+), 100 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs index 17d62799..8f7476a2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs @@ -5,7 +5,7 @@ use super::*; mod adaptive_wave_fn; use crate::model_binding::qwen4exp_input::{MoeRoutedSourceScope, MoeWeightDescriptor}; use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error}; -use adaptive_wave_fn::{AdaptiveWave, WaveState}; +use adaptive_wave_fn::AdaptiveWave; #[allow(clippy::too_many_arguments)] pub(super) fn project_adaptive_groups<'ctx>( @@ -27,8 +27,8 @@ pub(super) fn project_adaptive_groups<'ctx>( } let (residents, misses) = split_resident_misses(binding, rows, groups, cache)?; let job_allowance = wave_job_allowance(residents.capacity(), misses.capacity())?; - let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared, actual }; - wave.run(&mut WaveState { cache, down, cancelled }, &residents, &misses, job_allowance) + let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared }; + wave.run(cache, down, cancelled, actual, &residents, &misses, job_allowance) } /// Actual outer wave directories coexist with owned jobs until join. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs index ddb6fae7..0ac5f825 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive/adaptive_wave_fn.rs @@ -6,57 +6,45 @@ use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, runtim /// The shared inputs of one adaptive wave: resident groups on the GPU, misses on the owned CPU pool. #[derive(Clone, Copy)] -pub(super) struct AdaptiveWave<'a, 'ctx, 'txn, 'driver> { +pub(super) struct AdaptiveWave<'a, 'ctx> { pub(super) context: &'ctx Context<'ctx>, pub(super) binding: &'a ModelBinding, pub(super) rows: &'a [ChunkFfnRow], pub(super) scope: &'a DownScope<'ctx>, pub(super) origins: &'a [Rc], pub(super) prepared: &'a [RoutedGateUpQ8<'a>], - pub(super) actual: Option<&'a QwenChunkTxn<'txn, 'driver>>, } -/// What an adaptive wave mutates while it runs: the weight cache, the down-projection slots and the cancellation -/// poll, which is checked before every batch and every completed member. -pub(super) struct WaveState<'w, 'cache, 'ctx, F: FnMut() -> bool> { - pub(super) cache: &'w mut MoeWeightCache<'cache>, - pub(super) down: &'w mut [[Option>; K]], - pub(super) cancelled: &'w mut F, -} - -/// One batch of CPU miss groups, with the resident GPU groups that run overlapped with it (first batch only). -#[derive(Clone, Copy)] -struct MissBatch<'a> { - groups: &'a [&'a [Pair]], - residents: Option<&'a [&'a [Pair]]>, -} - -impl<'ctx> AdaptiveWave<'_, 'ctx, '_, '_> { +impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> { /// Run the miss batches in order; the resident GPU groups run once, overlapped with the first batch. - pub(super) fn run bool>( + #[allow(clippy::too_many_arguments)] + pub(super) fn run( &self, - state: &mut WaveState<'_, '_, 'ctx, F>, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + actual: Option<&QwenChunkTxn<'_, '_>>, residents: &[&[Pair]], misses: &[&[Pair]], job_allowance: usize, ) -> Result<()> { let mut gpu_done = false; - let cpu_owner = state.cache.cpu_miss_owner(self.binding)?; + let cpu_owner = cache.cpu_miss_owner(self.binding)?; let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let mut offset = 0usize; while offset < misses.len() { let end = miss_batch_end(self.rows, misses, offset)?; - let groups = &misses[offset..end]; + let batch = &misses[offset..end]; offset = end; - if (state.cancelled)() { + if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } let resident = if gpu_done { None } else { Some(residents) }; - self.run_batch(state, &mut cpu, MissBatch { groups, residents: resident }, job_allowance)?; + self.run_batch(cache, down, cancelled, actual, &mut cpu, batch, resident, job_allowance)?; gpu_done = true; } if !gpu_done { - self.project_residents(residents, state)?; + self.project_residents(residents, cache, down, cancelled)?; } Ok(()) } @@ -65,19 +53,23 @@ impl<'ctx> AdaptiveWave<'_, 'ctx, '_, '_> { /// the CPU side, then upload the completed rows. Model-lifetime stacks/native scratch were admitted before the /// pool. This request admits <=16 jobs and <=48MiB INCLUDING actual directory, preparation and start/join /// metadata/capacities. Callees measure their own retained capacities against this remaining allowance before send. - fn run_batch bool>( + #[allow(clippy::too_many_arguments)] + fn run_batch( &self, - state: &mut WaveState<'_, '_, 'ctx, F>, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + actual: Option<&QwenChunkTxn<'_, '_>>, cpu: &mut CpuMissWorkspace, - batch: MissBatch<'_>, + batch: &[&[Pair]], + residents: Option<&[&[Pair]]>, job_allowance: usize, ) -> Result<()> { - let MissBatch { groups: batch, residents } = batch; let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, job_allowance)?; let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; let gpu_result = match residents { None => Ok(()), - Some(residents) => self.project_residents(residents, state), + Some(residents) => self.project_residents(residents, cache, down, cancelled), }; // Always drain actual CPU consumers, including GPU failure/cancellation. // Preserve the primary GPU failure; no source allocation outlives join. @@ -87,28 +79,33 @@ impl<'ctx> AdaptiveWave<'_, 'ctx, '_, '_> { if completed.len() != batch.len() { return Err(Error::IdentityMismatch); } - self.finish_members(state, completed, batch) + self.finish_members(cache, down, cancelled, actual, completed, batch) } - fn finish_members bool>( + fn finish_members( &self, - state: &mut WaveState<'_, '_, 'ctx, F>, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, + actual: Option<&QwenChunkTxn<'_, '_>>, completed: Vec, batch: &[&[Pair]], ) -> Result<()> { for (values, pairs) in completed.into_iter().zip(batch) { - if (state.cancelled)() { + if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - self.finish_member(state, pairs, values)?; + self.finish_member(cache, down, actual, pairs, values)?; } Ok(()) } - fn project_residents bool>( + fn project_residents( &self, residents: &[&[Pair]], - state: &mut WaveState<'_, '_, 'ctx, F>, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { let (context, binding, rows) = (self.context, self.binding, self.rows); project_residents( @@ -116,24 +113,25 @@ impl<'ctx> AdaptiveWave<'_, 'ctx, '_, '_> { binding, rows, residents, - state.cache, + cache, self.prepared, self.scope, self.origins, - state.down, - state.cancelled, + down, + cancelled, ) } - fn finish_member bool>( + fn finish_member( &self, - state: &mut WaveState<'_, '_, 'ctx, F>, + cache: &mut MoeWeightCache<'_>, + down: &mut [[Option>; K]], + actual: Option<&QwenChunkTxn<'_, '_>>, pairs: &[Pair], values: CpuMissRows, ) -> Result<()> { let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins); - let (cache, down) = (&mut *state.cache, &mut *state.down); - let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, self.actual)?; + let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?; upload_completed_rows(self.scope, binding, &keys, pairs, &values, origins, down)?; drop(values.into_values()); Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs index 2e799a64..1d48a872 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs @@ -15,12 +15,12 @@ mod kv_only; #[path = "mtp_state.rs"] mod state; pub(super) use kv_only::produce_chunk_kv_only; -pub(in crate::qwen_forward) use state::MtpCheckpoint; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use state::MtpChunkNumericSnapshot; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) use state::PrefixDraftSnapshot; pub(super) use state::{DenseKv, MtpChunkStage, MtpKvPrefill, MtpSession, ReadyMtpKvPrefill}; +pub(in crate::qwen_forward) use state::{MtpCheckpoint, RetainedFirstSeed}; /// Created only from a successful current target product or a checked draft /// successor. Reset/rewind invalidates every prior branch capability. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs index b59eea9c..2ec3a737 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_support.rs @@ -3,16 +3,9 @@ #[allow(unused_imports)] use super::*; -use crate::qwen_forward::mtp::MtpCheckpoint; +use crate::qwen_forward::mtp::{MtpCheckpoint, RetainedFirstSeed}; pub(super) type WindowResult = std::result::Result; - -/// The draft checkpoint taken after the first draft step, kept with the frame it was taken at so a window can -/// restore it instead of warming the draft again. -pub(super) struct RetainedFirstSeed { - pub(super) checkpoint: MtpCheckpoint, - pub(super) frame: mtp::MtpFrame, -} pub(super) type FirstSeed = Option; /// The authoritative first prediction of a window and the number of draft steps its depth and the context allow. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs index e72d36f5..13fc3b20 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs @@ -4,6 +4,7 @@ use super::*; use super::batched_support::*; +use crate::qwen_forward::mtp::RetainedFirstSeed; impl MtpDecoder { /// Selected only by the existing explicit IQ3 integer/native Down policy. @@ -175,7 +176,7 @@ impl MtpDecoder { if source.predicted(target)? != frame.token() || source.position(target)? != frame.position() { return Err(Error::IdentityMismatch.into()); } - self.draft.restore_first_seed(binding, target, frame, &seed.checkpoint, &mut st.draft_priors[0])?; + self.draft.restore_first_seed(binding, target, seed, &mut st.draft_priors[0])?; Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs index e1eb0a34..1f4270b8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs @@ -60,12 +60,10 @@ mod impl_role; #[allow(unused_imports)] use impl_role::at; #[allow(unused_imports)] -use impl_role::routed; +use impl_role::{RoutedExpert, routed}; #[path = "mtp_expert_transport/shared_project_fn.rs"] mod shared_project_fn; #[allow(unused_imports)] -pub(super) use shared_project_fn::compose; -#[allow(unused_imports)] use shared_project_fn::compose_inner; #[cfg(test)] #[allow(unused_imports)] @@ -77,3 +75,5 @@ pub(super) use shared_project_fn::fixed_reference; use shared_project_fn::shared; #[allow(unused_imports)] use shared_project_fn::shared_project; +#[allow(unused_imports)] +pub(super) use shared_project_fn::{ExpertWeights, SelectedRoute, compose}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs index b938f252..f0dd63c7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs @@ -224,14 +224,21 @@ fn routed_down( cleanup?; Ok(output) } +/// One routed expert of a token: the slot it fills in the route and its expert id. +#[derive(Clone, Copy)] +pub(super) struct RoutedExpert { + pub(super) slot: usize, + pub(super) expert: u32, +} + pub(super) fn routed( transport: &mut Transport<'_>, bank: &DeviceBuffer<'_>, - slot: usize, - expert: u32, + selected: RoutedExpert, q: usize, scales: usize, ) -> Result { + let RoutedExpert { slot, expert } = selected; if slot >= K || expert >= 512 { return Err(Error::InvalidExpert); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs index a2f1a847..b8c6a758 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs @@ -134,20 +134,32 @@ impl Packed { }) } } +/// The routed expert bank and the four shared-expert weight buffers one MTP expert block reads. +#[derive(Clone, Copy)] +pub(in super::super) struct ExpertWeights<'a, 'ctx> { + pub(in super::super) bank: &'a DeviceBuffer<'ctx>, + pub(in super::super) shared: [&'a DeviceBuffer<'ctx>; 4], +} + +/// The routed experts a token selected and the routing weights that scale their outputs. +#[derive(Clone, Copy)] +pub(in super::super) struct SelectedRoute { + pub(in super::super) ids: [u32; K], + pub(in super::super) weights: [f32; K], +} + pub(in super::super) fn compose( context: &Context<'_>, - bank: &DeviceBuffer<'_>, - shared_weights: [&DeviceBuffer<'_>; 4], + expert_weights: ExpertWeights<'_, '_>, mixed: &[f32], - ids: [u32; K], - weights: [f32; K], + route: SelectedRoute, failed: Rc>, ) -> Result> { validate_values(mixed, N)?; - let signed = ids.map(|id| i32::try_from(id).unwrap_or(-1)); - validate_route(signed, &weights)?; + let signed = route.ids.map(|id| i32::try_from(id).unwrap_or(-1)); + validate_route(signed, &route.weights)?; let mut transport = Transport::new(context, failed)?; - let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights); + let result = compose_inner(&mut transport, expert_weights, mixed, route); transport.finish(result) } /// Every routed expert's Down, packed in slot order; the first failure stops before any later expert runs. @@ -159,19 +171,19 @@ fn pack_routed( (q, scales): (usize, usize), ) -> Result<()> { for (slot, expert) in ids.into_iter().enumerate() { - let down = routed(transport, bank, slot, expert, q, scales)?; + let down = routed(transport, bank, RoutedExpert { slot, expert }, q, scales)?; packed.pack(transport, down)?; } Ok(()) } pub(super) fn compose_inner( transport: &mut Transport<'_>, - bank: &DeviceBuffer<'_>, - shared_weights: [&DeviceBuffer<'_>; 4], + expert_weights: ExpertWeights<'_, '_>, mixed: &[f32], - ids: [u32; K], - weights: [f32; K], + route: SelectedRoute, ) -> Result> { + let ExpertWeights { bank, shared: shared_weights } = expert_weights; + let SelectedRoute { ids, weights } = route; let input = transport.upload(mixed)?; let mut packed = Packed::new(transport, ids)?; let (q, scales) = transport.quantize(input, false)?; @@ -186,18 +198,16 @@ pub(super) fn compose_inner( #[cfg(test)] pub(super) fn compose_observed( context: &Context<'_>, - bank: &DeviceBuffer<'_>, - shared_weights: [&DeviceBuffer<'_>; 4], + expert_weights: ExpertWeights<'_, '_>, mixed: &[f32], - ids: [u32; K], - weights: [f32; K], + route: SelectedRoute, failed: Rc>, ) -> Result { validate_values(mixed, N)?; - validate_route(ids.map(|id| i32::try_from(id).unwrap_or(-1)), &weights)?; + validate_route(route.ids.map(|id| i32::try_from(id).unwrap_or(-1)), &route.weights)?; let mut transport = Transport::new(context, failed)?; transport.observations = Some(Vec::new()); - let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights); + let result = compose_inner(&mut transport, expert_weights, mixed, route); let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?; let values = transport.finish(result)?; Ok((values, observations)) @@ -205,12 +215,11 @@ pub(super) fn compose_observed( #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super) fn fixed_reference( context: &Context<'_>, - bank: &DeviceBuffer<'_>, - shared: [&DeviceBuffer<'_>; 4], + expert_weights: ExpertWeights<'_, '_>, mixed: &[f32], - ids: [u32; K], - weights: [f32; K], + route: SelectedRoute, ) -> Result { - let (output, observed) = compose_observed(context, bank, shared, mixed, ids, weights, Rc::new(Cell::new(false)))?; + let failed = Rc::new(Cell::new(false)); + let (output, observed) = compose_observed(context, expert_weights, mixed, route, failed)?; Ok((output, observed.into_iter().map(|(role, values)| (format!("{role:?}"), values)).collect())) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs index 6278c5ad..481eaca7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs @@ -227,7 +227,8 @@ pub(super) fn compare_observed( expected: &Original, failed: Rc>, ) { - let (output, observed) = compose_observed(ctx, bank, w, mixed, IDS, ROUTE, failed).unwrap(); + let (weights, route) = (ExpertWeights { bank, shared: w }, SelectedRoute { ids: IDS, weights: ROUTE }); + let (output, observed) = compose_observed(ctx, weights, mixed, route, failed).unwrap(); assert_eq!(observed.len(), 38); let parts: Vec = expected.routed.iter().flat_map(|v| v.iter().copied()).collect(); let mut words = 0; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/phases_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/phases_fn.rs index 90f3506b..6b2b181b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/phases_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/phases_fn.rs @@ -28,7 +28,8 @@ impl<'c> Env<'c> { mixed: &[f32], (ids, route): ([u32; K], [f32; K]), ) -> Result> { - compose(self.ctx, bank, w, mixed, ids, route, self.failed.clone()) + let route = SelectedRoute { ids, weights: route }; + compose(self.ctx, ExpertWeights { bank, shared: w }, mixed, route, self.failed.clone()) } pub(super) fn pair_cases(&self, bank: &DeviceBuffer<'_>, w: Weights<'_, '_>) { let ctx = self.ctx; @@ -113,11 +114,12 @@ impl<'c> Env<'c> { mixed: &[f32], ) { let foreign = device.create_context(144 * 1024 * 1024).unwrap(); - let result = compose(&foreign, bank, w, mixed, IDS, ROUTE, Rc::new(Cell::new(false))); + let (weights, route) = (ExpertWeights { bank, shared: w }, SelectedRoute { ids: IDS, weights: ROUTE }); + let result = compose(&foreign, weights, mixed, route, Rc::new(Cell::new(false))); refusal(result, Error::IdentityMismatch, &foreign, 0, &self.refusals); foreign.close().unwrap(); let low = device.create_context(DEVICE_PEAK - 1).unwrap(); - let result = compose(&low, bank, w, mixed, IDS, ROUTE, Rc::new(Cell::new(false))); + let result = compose(&low, weights, mixed, route, Rc::new(Cell::new(false))); refusal(result, Error::InputAllocation, &low, 0, &self.refusals); low.close().unwrap(); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs index 3b826337..3b3119cb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs @@ -28,7 +28,7 @@ fn slot_guards( count: Count<'_>, ) { let (q, scales) = t.quantize(input, false).unwrap(); - let wrong_slot = routed(t, bank, 1, IDS[1], q, scales).unwrap(); + let wrong_slot = routed(t, bank, RoutedExpert { slot: 1, expert: IDS[1] }, q, scales).unwrap(); let charge = ctx.allocated_bytes(); refusal(packed.pack(t, wrong_slot), Error::IdentityMismatch, ctx, charge, count); assert_eq!(packed.next, 0); @@ -54,7 +54,7 @@ pub(super) fn private_owner_guards( slot_guards(ctx, &mut t, &mut packed, (bank, w, input), count); let rival_input = rival.upload(mixed).unwrap(); let (rq, rs) = rival.quantize(rival_input, false).unwrap(); - let foreign_invocation = routed(&mut rival, bank, 0, IDS[0], rq, rs).unwrap(); + let foreign_invocation = routed(&mut rival, bank, RoutedExpert { slot: 0, expert: IDS[0] }, rq, rs).unwrap(); let charge = ctx.allocated_bytes(); refusal(packed.pack(&mut t, foreign_invocation), Error::IdentityMismatch, ctx, charge, count); assert_eq!(packed.next, 0); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs index dd1b2282..4013547f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs @@ -94,7 +94,7 @@ pub(in crate::qwen_forward) struct MtpExpertWorkspace<'ctx> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod fixed_workspace_gpu { - use super::super::mtp_expert_transport::fixed_reference; + use super::super::mtp_expert_transport::{ExpertWeights, SelectedRoute, fixed_reference}; use super::*; use leleka_cuda_driver::Driver; const BANK_BYTES: usize = 707_788_800; @@ -244,7 +244,9 @@ mod fixed_workspace_gpu { } fn compare_pattern(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32]) -> usize { // Original allocation path and its direct unchanged quantizers FIRST. - let (expected, original) = fixed_reference(self.ctx, &self.bank, self.w(), mixed, IDS, ROUTE).unwrap(); + let (weights, route) = + (ExpertWeights { bank: &self.bank, shared: self.w() }, SelectedRoute { ids: IDS, weights: ROUTE }); + let (expected, original) = fixed_reference(self.ctx, weights, mixed, route).unwrap(); let scales = reference_scale_sets(self.ctx, mixed, &original); assert_eq!(original.len(), 38); assert_eq!(scales.len(), 11); @@ -295,14 +297,22 @@ mod fixed_workspace_gpu { corpus[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes()); self.bank.copy_from(corpus).unwrap(); assert_eq!( - fixed_reference(self.ctx, &self.bank, self.w(), mixed, IDS, ROUTE).err(), + fixed_reference( + self.ctx, + ExpertWeights { bank: &self.bank, shared: self.w() }, + mixed, + SelectedRoute { ids: IDS, weights: ROUTE } + ) + .err(), Some(Error::NonFinite) ); assert_eq!(self.compose_with(storage, mixed, false).err(), Some(Error::NonFinite)); storage.check().unwrap(); corpus[at..at + 2].copy_from_slice(&saved); self.bank.copy_from(corpus).unwrap(); - let (expected, _) = fixed_reference(self.ctx, &self.bank, self.w(), mixed, IDS, ROUTE).unwrap(); + let route = SelectedRoute { ids: IDS, weights: ROUTE }; + let (expected, _) = + fixed_reference(self.ctx, ExpertWeights { bank: &self.bank, shared: self.w() }, mixed, route).unwrap(); let actual = self.compose_with(storage, mixed, false).unwrap(); exact(&expected, &actual); actual.len() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs index 30b4f77a..da966395 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs @@ -134,7 +134,9 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> { failed, ) } else { - mtp_expert_transport::compose(self.context, bank, shared, input.mixed(), ids, route_weights, failed) + let expert_weights = mtp_expert_transport::ExpertWeights { bank, shared }; + let route = mtp_expert_transport::SelectedRoute { ids, weights: route_weights }; + mtp_expert_transport::compose(self.context, expert_weights, input.mixed(), route, failed) } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs index 14aac754..aed63761 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs @@ -63,6 +63,13 @@ pub(in crate::qwen_forward) struct MtpCheckpoint { retained: Rc>, } +/// The draft checkpoint taken after the first draft step, kept with the frame it was taken at so a window can +/// restore it instead of warming the draft again. +pub(in crate::qwen_forward) struct RetainedFirstSeed { + pub(in crate::qwen_forward) checkpoint: MtpCheckpoint, + pub(in crate::qwen_forward) frame: MtpFrame, +} + #[cfg(test)] #[path = "mtp_state/tests.rs"] mod tests; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs index dc6f04ac..1c996a92 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs @@ -124,15 +124,14 @@ impl MtpSession { &mut self, binding: &ModelBinding, target: &crate::qwen_forward::session::QwenSession<'_>, - expected: &MtpFrame, - seed: &MtpCheckpoint, + seed: &RetainedFirstSeed, original: &mut MtpCheckpoint, ) -> Result<()> { - expected.validate(binding, target)?; + seed.frame.validate(binding, target)?; if !self.binding.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } - self.restore_first_seed_checked(expected, seed, original) + self.restore_first_seed_checked(&seed.frame, &seed.checkpoint, original) } pub(super) fn restore_first_seed_checked( From 0c682e2aa2a5dfcef4accf00701b3c42458749f4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:15:18 +0100 Subject: [PATCH 22/42] STRA-338 params r02: name the split files by content; OriginalRingBlocks lives in original_session_state.rs impl_originalmtpscalarprefill_{2_2,4,6,7,8}.rs become kernel_commands, call_admission, record_operands, group_loop and group_capture; impl_originalmtpactor_2_2.rs becomes draft_rounds. OriginalRingBlocks moves out of original_conversation_state.rs, which would otherwise pass the 400-line file limit. --- .../impl_originalmtpscalarprefill.rs | 22 +++++++++---------- ...tpscalarprefill_4.rs => call_admission.rs} | 6 ++--- ...mtpscalarprefill_8.rs => group_capture.rs} | 0 ...nalmtpscalarprefill_7.rs => group_loop.rs} | 0 ...calarprefill_2_2.rs => kernel_commands.rs} | 3 ++- ...pscalarprefill_6.rs => record_operands.rs} | 0 .../src/original_conversation_state.rs | 12 +++------- .../impl_originalmtpactor.rs | 4 ++-- ...riginalmtpactor_2_2.rs => draft_rounds.rs} | 3 ++- .../cuda-driver/src/original_session_state.rs | 10 ++++++++- 10 files changed, 32 insertions(+), 28 deletions(-) rename crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/{impl_originalmtpscalarprefill_4.rs => call_admission.rs} (96%) rename crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/{impl_originalmtpscalarprefill_8.rs => group_capture.rs} (100%) rename crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/{impl_originalmtpscalarprefill_7.rs => group_loop.rs} (100%) rename crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/{impl_originalmtpscalarprefill_2_2.rs => kernel_commands.rs} (97%) rename crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/{impl_originalmtpscalarprefill_6.rs => record_operands.rs} (100%) rename crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/{impl_originalmtpactor_2_2.rs => draft_rounds.rs} (96%) diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs index bd8fbd98..03486fb1 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs @@ -3,24 +3,24 @@ #[allow(unused_imports)] use super::*; +#[path = "impl_originalmtpscalarprefill/call_admission.rs"] +mod call_admission; +#[path = "impl_originalmtpscalarprefill/group_capture.rs"] +mod group_capture; +#[path = "impl_originalmtpscalarprefill/group_loop.rs"] +mod group_loop; #[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs"] mod impl_originalmtpscalarprefill_2; -#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs"] -mod impl_originalmtpscalarprefill_2_2; #[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs"] mod impl_originalmtpscalarprefill_3; -#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs"] -mod impl_originalmtpscalarprefill_4; #[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs"] mod impl_originalmtpscalarprefill_5; -#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs"] -mod impl_originalmtpscalarprefill_6; -#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs"] -mod impl_originalmtpscalarprefill_7; -#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs"] -mod impl_originalmtpscalarprefill_8; +#[path = "impl_originalmtpscalarprefill/kernel_commands.rs"] +mod kernel_commands; +#[path = "impl_originalmtpscalarprefill/record_operands.rs"] +mod record_operands; #[allow(unused_imports)] -use impl_originalmtpscalarprefill_6::{ +use record_operands::{ Cap, ExternalOwners, GrRows, GroupIo, GroupSpan, PagePublication, ScalarCall, ScalarGroupSources, ScalarOperands, ScalarStaged, }; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/call_admission.rs similarity index 96% rename from crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs rename to crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/call_admission.rs index 57925433..5f4e10ac 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/call_admission.rs @@ -1,6 +1,6 @@ -//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (4). `record_impl` admits the call, -//! stages the weights and claims the policy; the group loop is in `impl_originalmtpscalarprefill_7.rs` and the capture -//! of one group in `impl_originalmtpscalarprefill_8.rs`. +//! The admission of one `OriginalMtpScalarPrefill::record_impl` call (STRA-338): the owner and prompt checks, the +//! alias checks and weight staging, and the policy claim. The group loop is in `group_loop.rs` and the capture of one +//! group in `group_capture.rs`. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/group_capture.rs similarity index 100% rename from crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs rename to crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/group_capture.rs diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/group_loop.rs similarity index 100% rename from crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs rename to crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/group_loop.rs diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/kernel_commands.rs similarity index 97% rename from crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs rename to crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/kernel_commands.rs index 9ec1b515..78239be3 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/kernel_commands.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (2). +//! The scratch layout accessors and the kernel command emitters (`kernel`, `finite`, `q8_guard`, `quant`, `project`, +//! `gr_args`) of `OriginalMtpScalarPrefill` (STRA-338). #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/record_operands.rs similarity index 100% rename from crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs rename to crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/record_operands.rs diff --git a/crates/cuda-driver/src/original_conversation_state.rs b/crates/cuda-driver/src/original_conversation_state.rs index e9aa1691..a8a74a08 100644 --- a/crates/cuda-driver/src/original_conversation_state.rs +++ b/crates/cuda-driver/src/original_conversation_state.rs @@ -15,7 +15,9 @@ //! No state is acknowledged from metadata: a region is only readable or //! writable through the actual arena or the actual host owner. -use super::{OriginalSessionLayout, OriginalSessionQsaLayout, OriginalSessionSpan, OriginalSessionState}; +use super::{ + OriginalRingBlocks, OriginalSessionLayout, OriginalSessionQsaLayout, OriginalSessionSpan, OriginalSessionState, +}; use crate::{Context, Error, Result}; // ---- plain data and traits: no CUDA types below until `OriginalSessionLayout` (begin) @@ -46,14 +48,6 @@ pub enum OriginalKvLayer { Draft, } -/// The host blocks `[begin, end)` of a drafter ring and the number of ring slots they land in (`block % slots`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct OriginalRingBlocks { - pub begin: i64, - pub end: i64, - pub slots: i64, -} - /// A byte range of session state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum OriginalRegion { diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs index 442dc9ec..37c653b3 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor.rs @@ -3,7 +3,7 @@ #[allow(unused_imports)] use super::*; +#[path = "impl_originalmtpactor/draft_rounds.rs"] +mod draft_rounds; #[path = "impl_originalmtpactor/impl_originalmtpactor_2.rs"] mod impl_originalmtpactor_2; -#[path = "impl_originalmtpactor/impl_originalmtpactor_2_2.rs"] -mod impl_originalmtpactor_2_2; diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/draft_rounds.rs similarity index 96% rename from crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs rename to crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/draft_rounds.rs index 6c49b143..560852fb 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/draft_rounds.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalMtpActor (2). +//! The draft rounds of `OriginalMtpActor` (STRA-338): `draft`, `draft_first` and the verifier-window forms, each taking +//! the draft-round DTOs of `original_mtp_draft_round.rs`. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/original_session_state.rs b/crates/cuda-driver/src/original_session_state.rs index c8903dc2..bc0b890d 100644 --- a/crates/cuda-driver/src/original_session_state.rs +++ b/crates/cuda-driver/src/original_session_state.rs @@ -16,10 +16,18 @@ pub(crate) use conversation::OriginalConversationAccess; #[allow(unused_imports)] pub use conversation::{ OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, - OriginalRegion, OriginalRingBlocks, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, + OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, }; use std::rc::Rc; +/// The host blocks `[begin, end)` of a drafter ring and the number of ring slots they land in (`block % slots`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct OriginalRingBlocks { + pub begin: i64, + pub end: i64, + pub slots: i64, +} + const ALIGN: usize = 256; const PLE_HIST: usize = 9; const PLE_DIM: usize = 10240; From 788c5005903b4ba4f546f362c380eb2c2f957be1 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:17:05 +0100 Subject: [PATCH 23/42] STRA-338 params e04: MTP chunk warm-up and KV staging scan, loaded-batch proof take domain structs Files: none --- .../src/qwen_forward/mtp.rs | 2 +- .../src/qwen_forward/mtp_decode_chunk.rs | 57 ++++++++------- .../src/qwen_forward/mtp_decoder_batch_gpu.rs | 7 +- .../mtp_decoder_batch_gpu/check_loaded_fn.rs | 10 +-- .../check_loaded_fn/impl_flow.rs | 16 ++++- .../check_loaded_fn/impl_flow_2.rs | 9 +-- .../src/qwen_forward/mtp_state.rs | 2 +- .../src/qwen_forward/mtp_state_warming.rs | 1 + .../qwen_forward/mtp_state_warming/stage.rs | 72 ++++++++++++------- 9 files changed, 107 insertions(+), 69 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs index 2e799a64..eed81420 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs @@ -20,7 +20,7 @@ pub(in crate::qwen_forward) use state::MtpCheckpoint; pub(in crate::qwen_forward) use state::MtpChunkNumericSnapshot; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) use state::PrefixDraftSnapshot; -pub(super) use state::{DenseKv, MtpChunkStage, MtpKvPrefill, MtpSession, ReadyMtpKvPrefill}; +pub(super) use state::{ChunkModel, DenseKv, MtpChunkStage, MtpKvPrefill, MtpSession, ReadyMtpKvPrefill}; /// Created only from a successful current target product or a checked draft /// successor. Reset/rewind invalidates every prior branch capability. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs index 79475e1c..4d551d2e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs @@ -52,7 +52,7 @@ impl MtpDecoder { self.kv_prefill .as_mut() .ok_or(Error::IdentityMismatch)? - .stage_chunk(binding, &mut self.draft, txn, cache, cancelled) + .stage_chunk(mtp::ChunkModel { binding, cache }, &mut self.draft, txn, cancelled) .map(ReadyMtpPrefill::Kv) } } @@ -74,33 +74,40 @@ fn snapshot_rows( fn check_cancelled(cancelled: &mut impl FnMut() -> bool) -> Result<()> { if cancelled() { Err(Error::Unsupported(super::super::contract::Stage::Executor)) } else { Ok(()) } } -/// Warms the draft with every row that has a known next token; only the final row may lack one. -fn warm_rows( - binding: &ModelBinding, - txn: &mut QwenChunkTxn<'_, '_>, - rows: &[crate::qwen_forward::session::chunk::ChunkRowResidual], - stage: &mut mtp::MtpChunkStage<'_>, - (start, cache): (u64, &MoeWeightCache<'_>), - cancelled: &mut impl FnMut() -> bool, -) -> Result { - let mut warmed = 0; - for (index, row) in rows.iter().enumerate() { - check_cancelled(cancelled)?; - let (_, position, next, _) = txn.validate_row(row)?; - if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? { - return Err(Error::IdentityMismatch); - } - if next.is_none() { - if index + 1 != rows.len() { +/// The sealed rows of one chunk that warm the draft: where they start and the binding and cache they are warmed from. +struct RowWarmup<'a, 'c> { + binding: &'a ModelBinding, + cache: &'a MoeWeightCache<'c>, + start: u64, + rows: &'a [crate::qwen_forward::session::chunk::ChunkRowResidual], +} +impl RowWarmup<'_, '_> { + /// Warms the draft with every row that has a known next token; only the final row may lack one. + fn run( + &self, + txn: &mut QwenChunkTxn<'_, '_>, + stage: &mut mtp::MtpChunkStage<'_>, + cancelled: &mut impl FnMut() -> bool, + ) -> Result { + let mut warmed = 0; + for (index, row) in self.rows.iter().enumerate() { + check_cancelled(cancelled)?; + let (_, position, next, _) = txn.validate_row(row)?; + if position.get() != self.start.checked_add(index as u64).ok_or(Error::Overflow)? { return Err(Error::IdentityMismatch); } - continue; + if next.is_none() { + if index + 1 != self.rows.len() { + return Err(Error::IdentityMismatch); + } + continue; + } + mtp::warm_chunk_row(self.binding, txn, row, stage, self.cache)?; + check_cancelled(cancelled)?; + warmed += 1; } - mtp::warm_chunk_row(binding, txn, row, stage, cache)?; - check_cancelled(cancelled)?; - warmed += 1; + Ok(warmed) } - Ok(warmed) } impl MtpDecoder { @@ -113,7 +120,7 @@ impl MtpDecoder { ) -> Result> { let (start, end, rows) = snapshot_rows(txn)?; let mut stage = self.draft.stage_chunk(binding, txn)?; - let warmed = warm_rows(binding, txn, &rows, &mut stage, (start, cache), &mut cancelled)?; + let warmed = RowWarmup { binding, cache, start, rows: &rows }.run(txn, &mut stage, &mut cancelled)?; let draft_end = start.checked_add(warmed as u64).ok_or(Error::Overflow)?; if cancelled() { return Err(Error::Unsupported(super::super::contract::Stage::Executor)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs index e7054dba..8c7820a0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs @@ -139,8 +139,9 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() { let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); let mut cache = Some(MoeWeightCache::new(&binding, context.as_ref()).unwrap()); let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap(); - let numerical = - catch_unwind(AssertUnwindSafe(|| check_loaded(&binding, &context, &output, &mut kar, &mut cache, &dense))); + let numerical = catch_unwind(AssertUnwindSafe(|| { + check_loaded(Shared { binding: &binding, output: &output, dense: &dense, kar: &mut kar }, &context, &mut cache) + })); let down = teardown(&context, output, kar, (cache, dense)); let closed = Rc::try_unwrap(context).ok().map(|c| c.close()); drop(binding); @@ -174,4 +175,4 @@ use impl_collection::row_matches; #[path = "mtp_decoder_batch_gpu/check_loaded_fn.rs"] mod check_loaded_fn; #[allow(unused_imports)] -use check_loaded_fn::check_loaded; +use check_loaded_fn::{Shared, check_loaded}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs index aba63bf3..f6a50a04 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs @@ -25,11 +25,11 @@ macro_rules! prepare_window { } /// The loan of the loaded stages every scalar step, window preparation and decoder window runs against. -struct Shared<'a, 'o, 'p, 'k, 'd> { - binding: &'a ModelBinding, - output: &'a OutputStage<'o, 'p>, - dense: &'a DenseWeightCache<'d>, - kar: &'a mut KarPleCache<'k>, +pub(super) struct Shared<'a, 'o, 'p, 'k, 'd> { + pub(super) binding: &'a ModelBinding, + pub(super) output: &'a OutputStage<'o, 'p>, + pub(super) dense: &'a DenseWeightCache<'d>, + pub(super) kar: &'a mut KarPleCache<'k>, } /// The tokens and draft snapshots every later phase compares against. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs index b9e7f874..d0a6fc5d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow.rs @@ -3,6 +3,15 @@ #[allow(unused_imports)] use super::*; +/// What the cancelled T3 window is compared with: the reference tokens, the two accepted row expectations and the tail +/// product the cancelled publication must drop. +struct CancelledWindow<'a> { + refs: &'a Refs, + expected0: &'a Expected, + expected1: &'a Expected, + expected_tail: Expected, +} + impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> { pub(super) fn step(&mut self, token: TokenId, position: u64) -> Result { let native = self.cache_slot.as_mut().unwrap(); @@ -117,11 +126,11 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> { pub(super) fn cancelled_publish( &mut self, source: &TargetStepProduct, - (refs, expected0, expected1): (&Refs, &Expected, &Expected), - expected_tail: Expected, + window: CancelledWindow<'_>, decoder: &mut MtpDecoder, (target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot), ) { + let CancelledWindow { refs, expected0, expected1, expected_tail } = window; let collection = Collection::begin(3).unwrap(); let candidate = self.cache_slot.as_mut().unwrap(); let proposals = [refs.seed, refs.next, refs.wrong]; @@ -160,7 +169,8 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> { let draft_prior = decoder.draft.checkpoint().unwrap(); self.refuse_windows(source, refs, &decoder, (&target_before, &draft_before)); let before = (&target_before, &draft_before); - self.cancelled_publish(source, (refs, expected0, expected1), expected_tail, &mut decoder, before); + let window = CancelledWindow { refs, expected0, expected1, expected_tail }; + self.cancelled_publish(source, window, &mut decoder, before); self.report.check(self.target.restore_checkpoint(&target_prior).is_ok()); self.report.check(decoder.draft.restore(&draft_prior).is_ok()); drop(target_prior); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow_2.rs index 66ff9e0f..b4251c37 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn/impl_flow_2.rs @@ -99,15 +99,12 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> { } pub(in super::super) fn check_loaded<'ctx>( - binding: &ModelBinding, + shared: Shared<'_, '_, '_, '_, '_>, context: &'ctx Rc>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, cache_slot: &mut Option>, - dense: &DenseWeightCache<'_>, ) -> Report { - admit_binding(binding); - let mut flow = Flow::open(Shared { binding, output, dense, kar }, context, cache_slot); + admit_binding(shared.binding); + let mut flow = Flow::open(shared, context, cache_slot); let prefix = flow.reference_prefix(); let Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued } = flow.reference_tail(prefix); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs index 14aac754..def24bde 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs @@ -14,7 +14,7 @@ mod warming; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use chunk::MtpChunkNumericSnapshot; pub(in crate::qwen_forward) use chunk::MtpChunkStage; -pub(in crate::qwen_forward) use warming::{MtpKvPrefill, ReadyMtpKvPrefill}; +pub(in crate::qwen_forward) use warming::{ChunkModel, MtpKvPrefill, ReadyMtpKvPrefill}; struct CellPair { key: Box<[u8]>, value: Box<[u8]>, 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 4ebc717a..328d14ae 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 @@ -214,5 +214,6 @@ impl ChunkDraftPublication for ReadyMtpKvPrefill<'_, '_> { } #[path = "mtp_state_warming/stage.rs"] mod stage; +pub(in crate::qwen_forward) use stage::ChunkModel; #[path = "mtp_state_warming/validate.rs"] mod validate; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming/stage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming/stage.rs index 19dccc7c..fdd0de90 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming/stage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming/stage.rs @@ -14,6 +14,28 @@ struct StageEnv<'a, 'c> { original: &'a MtpSession, cache: &'a MoeWeightCache<'c>, } +/// What a chunk scan reads and accumulates: the borrowed model handles and the coverage collected so far. +struct ChunkScan<'a, 'c> { + env: StageEnv<'a, 'c>, + scan: Scan, +} +/// The model binding and the weight cache a warming chunk is staged against. +pub(in crate::qwen_forward) struct ChunkModel<'binding, 'cache, 'ctx> { + pub(in crate::qwen_forward) binding: &'binding ModelBinding, + pub(in crate::qwen_forward) cache: &'cache MoeWeightCache<'ctx>, +} +/// One chunk row to scan: the row itself, the chunk's start position and the row's index within the chunk. +struct RowAt<'a> { + start: usize, + index: usize, + row: &'a ChunkRowResidual, +} +/// A scanned row together with the MTP frame minted for it and its global index. +struct FramedRow<'a> { + row: &'a ChunkRowResidual, + frame: &'a MtpFrame, + global: usize, +} /// A validated row of the scan: its global index and what the target step produced for it. struct ScanRow { global: usize, @@ -24,20 +46,20 @@ struct ScanRow { impl MtpKvPrefill { pub(in crate::qwen_forward) fn stage_chunk<'owner, 'binding>( &'owner mut self, - binding: &'binding ModelBinding, + model: ChunkModel<'binding, '_, '_>, original: &'owner mut MtpSession, txn: &mut QwenChunkTxn<'_, '_>, - cache: &MoeWeightCache<'_>, mut cancelled: impl FnMut() -> bool, ) -> Result> { + let ChunkModel { binding, cache } = model; self.validate_original(binding, original, txn.original_session()?)?; let (start, end) = self.admit_chunk_range(txn)?; - let (mut scan, rows) = self.begin_scan(txn)?; - let env = StageEnv { binding, original, cache }; + let (scan, rows) = self.begin_scan(txn)?; + let mut state = ChunkScan { env: StageEnv { binding, original, cache }, scan }; for (index, row) in rows.iter().enumerate() { - self.scan_row(&env, txn, &mut scan, (start, index), (row, &mut cancelled))?; + self.scan_row(&mut state, txn, RowAt { start, index, row }, &mut cancelled)?; } - let Scan { cells, last, full } = scan; + let Scan { cells, last, full } = state.scan; let ready = ReadyMtpKvPrefill { owner: self, original, binding, start, end, cells, last, full }; ready.validate(txn)?; Ok(ready) @@ -66,12 +88,12 @@ impl MtpKvPrefill { } fn scan_row( &self, - env: &StageEnv<'_, '_>, + state: &mut ChunkScan<'_, '_>, txn: &mut QwenChunkTxn<'_, '_>, - scan: &mut Scan, - (start, index): (usize, usize), - (row, cancelled): (&ChunkRowResidual, &mut impl FnMut() -> bool), + at: RowAt<'_>, + cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { + let RowAt { start, index, row } = at; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } @@ -79,7 +101,7 @@ impl MtpKvPrefill { let (token, position, next, _) = txn.validate_row(row)?; self.admit_scanned_row(global, (token, position.get()), next)?; if let Some(next) = next { - self.scan_next(env, txn, scan, row, ScanRow { global, position, next })?; + self.scan_next(state, txn, row, ScanRow { global, position, next })?; } if cancelled() { return Err(Error::Unsupported(Stage::Executor)); @@ -94,9 +116,8 @@ impl MtpKvPrefill { } fn scan_next( &self, - env: &StageEnv<'_, '_>, + state: &mut ChunkScan<'_, '_>, txn: &mut QwenChunkTxn<'_, '_>, - scan: &mut Scan, row: &ChunkRowResidual, at: ScanRow, ) -> Result<()> { @@ -110,11 +131,12 @@ impl MtpKvPrefill { generation: self.generation, depth: 0, }; - frame.validate(env.binding, txn.original_session()?)?; + frame.validate(state.env.binding, txn.original_session()?)?; + let framed = FramedRow { row, frame: &frame, global: at.global }; if at.global + 2 == self.tokens.len() { - scan.full = Some(self.hydrate(env, txn, scan, row, (&frame, at.global))?); + state.scan.full = Some(self.hydrate(state, txn, framed)?); } else if at.global >= self.first_needed { - self.push_cell(env, txn, scan, row, &frame)?; + self.push_cell(state, txn, framed)?; } Ok(()) } @@ -122,13 +144,13 @@ impl MtpKvPrefill { /// cell required by the ordinary prior window. fn hydrate( &self, - env: &StageEnv<'_, '_>, + state: &ChunkScan<'_, '_>, txn: &mut QwenChunkTxn<'_, '_>, - scan: &Scan, - row: &ChunkRowResidual, - (frame, global): (&MtpFrame, usize), + framed: FramedRow<'_>, ) -> Result { - let mut candidate = self.seed_candidate(env.original, scan, global)?; + let FramedRow { row, frame, global } = framed; + let env = &state.env; + let mut candidate = self.seed_candidate(env.original, &state.scan, global)?; txn.with_mtp_row(row, |target, actual_position, actual_next, streams, anchor| { if actual_position != frame.position || actual_next != frame.token || !anchor.same_prefix(&frame.origin) { return Err(Error::IdentityMismatch); @@ -170,12 +192,12 @@ impl MtpKvPrefill { } fn push_cell( &self, - env: &StageEnv<'_, '_>, + state: &mut ChunkScan<'_, '_>, txn: &mut QwenChunkTxn<'_, '_>, - scan: &mut Scan, - row: &ChunkRowResidual, - frame: &MtpFrame, + framed: FramedRow<'_>, ) -> Result<()> { + let FramedRow { row, frame, .. } = framed; + let ChunkScan { env, scan } = state; let product = mtp::produce_chunk_kv_only(env.binding, txn, row, frame, env.cache)?; let (produced, key, value) = product.consume(env.binding, txn.original_session()?, frame)?; super::super::validate_half(&key)?; From a6ea6a02ebe88f8bb24309c422f801d65de6de8e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:02 +0100 Subject: [PATCH 24/42] STRA-338 params e01: MTP draft input takes KnownNext, draft step takes StepSessions and InputRows; norm role decides the hidden/embedding norm Files: (none) --- .../src/qwen_forward/mtp.rs | 10 +++++++ .../src/qwen_forward/mtp/impl_mtpframe.rs | 23 +++++++++------- .../src/qwen_forward/mtp/step_fn.rs | 19 +++++++------- .../src/qwen_forward/mtp_decode.rs | 2 +- .../impl_mtpdecoder/impl_mtpdecoder_2.rs | 26 ++++++++++++++++--- .../impl_mtpdecoder/impl_mtpdecoder_2_2.rs | 10 ++++--- .../impl_mtpdecoder/impl_mtpdecoder_3.rs | 19 +++++++++++--- 7 files changed, 79 insertions(+), 30 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs index 2e799a64..39bee9db 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs @@ -38,6 +38,16 @@ pub(super) struct MtpInput { frame: MtpFrame, streams: Box<[f32]>, } +/// The target step product a draft input extends together with the known next token it is conditioned on. +pub(super) struct KnownNext<'a, P> { + pub(super) source: &'a P, + pub(super) next_token: TokenId, +} +/// The target session and the draft session that one MTP draft step advances together. +pub(super) struct StepSessions<'a, 'driver, 'draft> { + pub(super) target: &'a mut QwenSession<'driver>, + pub(super) draft: &'draft mut MtpSession, +} /// A completed draft with its exact post-MLP residual. Only this composer can /// publish draft state after the reused main output head finishes successfully. pub(super) struct MtpStepProduct { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs index e6e23b46..973a4808 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs @@ -37,6 +37,11 @@ impl MtpFrame { && self.origin.same_prefix(&other.origin) } } +/// The hidden residual streams of the source row and the embedding row of the next token. +struct InputRows<'a> { + streams: &'a [f32], + embedding: &'a [f32], +} impl MtpInput { pub(in super::super) fn from_previous( binding: &ModelBinding, @@ -67,10 +72,10 @@ impl MtpInput { binding: &ModelBinding, session: &QwenSession<'_>, draft: &MtpSession, - source: &TargetStepProduct, - next_token: TokenId, + next: KnownNext<'_, TargetStepProduct>, cache: &MoeWeightCache<'_>, ) -> Result { + let KnownNext { source, next_token } = next; let (_, position, streams, origin) = source.mtp_source(binding, session)?; let frame = draft.frame(binding, position, next_token, origin)?; frame.validate(binding, session)?; @@ -80,10 +85,10 @@ impl MtpInput { binding: &ModelBinding, session: &QwenSession<'_>, draft: &MtpSession, - source: &PrefillStepProduct, - next_token: TokenId, + next: KnownNext<'_, PrefillStepProduct>, cache: &MoeWeightCache<'_>, ) -> Result { + let KnownNext { source, next_token } = next; let (_, position, streams, origin) = source.mtp_source(binding, session)?; let frame = draft.frame(binding, position, next_token, origin)?; frame.validate(binding, session)?; @@ -106,7 +111,7 @@ impl MtpInput { preflight(context, 2 * 40960 + 5 * 10240 + 2 * 1310720 + 10000)?; let embedding = binding.embedding_row(frame.token.get()).map_err(binding_error)?; if cache.has_mtp_input_workspace() { - return Self::compute_queued(binding, session, frame, streams, &embedding, cache); + return Self::compute_queued(binding, session, frame, InputRows { streams, embedding: &embedding }, cache); } Self::compute_host(binding, session, frame, (streams, &embedding), (context, cache)) } @@ -117,9 +122,9 @@ impl MtpInput { (streams, embedding): (&[f32], &[f32]), (context, cache): (&Context<'_>, &MoeWeightCache<'_>), ) -> Result { - let en = norm(context, binding, MtpRole::EmbeddingNorm, embedding, false, cache)?; + let en = norm(context, binding, MtpRole::EmbeddingNorm, embedding, cache)?; let e2 = project(context, binding, MtpRole::FcEmbedding, &en, cache)?; - let hn = norm(context, binding, MtpRole::HiddenNorm, streams, true, cache)?; + let hn = norm(context, binding, MtpRole::HiddenNorm, streams, cache)?; let h2 = project_hidden_chunks(context, binding, &hn, cache)?; let result = broadcast_streams(context, &h2, &e2)?; frame.validate(binding, session)?; @@ -130,10 +135,10 @@ impl MtpInput { binding: &ModelBinding, session: &QwenSession<'_>, frame: MtpFrame, - streams: &[f32], - embedding: &[f32], + rows: InputRows<'_>, cache: &MoeWeightCache<'_>, ) -> Result { + let InputRows { streams, embedding } = rows; let context = session.mtp_context()?; let en_gamma = f32_weights(binding, MtpRole::EmbeddingNorm, cache)?; validate_values(embedding, 2560)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs index dc7c6b80..9ffd44de 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs @@ -6,13 +6,12 @@ use super::*; pub(in super::super) fn step( binding: &ModelBinding, - session: &mut QwenSession<'_>, - draft: &mut MtpSession, + sessions: StepSessions<'_, '_, '_>, input: MtpInput, output: &super::super::output::OutputStage<'_, '_>, cache: &MoeWeightCache<'_>, ) -> Result { - step_core(binding, session, draft, input, Some(output), cache)?.ok_or(Error::IdentityMismatch) + step_core(binding, sessions, input, Some(output), cache)?.ok_or(Error::IdentityMismatch) } /// Known-next warm path publishes the real draft state, without an unused head. pub(in super::super) fn warm_step( @@ -22,7 +21,7 @@ pub(in super::super) fn warm_step( input: MtpInput, cache: &MoeWeightCache<'_>, ) -> Result<()> { - if step_core(binding, session, draft, input, None, cache)?.is_some() { + if step_core(binding, StepSessions { target: session, draft }, input, None, cache)?.is_some() { return Err(Error::IdentityMismatch); } Ok(()) @@ -96,12 +95,12 @@ fn copy_streams(values: &[f32]) -> Result<(Vec, Vec)> { } fn step_run( binding: &ModelBinding, - session: &mut QwenSession<'_>, - draft: &mut MtpSession, + sessions: &mut StepSessions<'_, '_, '_>, input: MtpInput, output: Option<&super::super::output::OutputStage<'_, '_>>, (cache, transport_failed): (&MoeWeightCache<'_>, &Rc>), ) -> Result> { + let (session, draft) = (&mut *sessions.target, &mut *sessions.draft); input.frame.validate(binding, session)?; draft.prior(&input.frame)?; let blocks = run_blocks(binding, &input, (session, draft), cache, transport_failed)?; @@ -115,14 +114,14 @@ fn step_run( } pub(super) fn step_core( binding: &ModelBinding, - session: &mut QwenSession<'_>, - draft: &mut MtpSession, + mut sessions: StepSessions<'_, '_, '_>, input: MtpInput, output: Option<&super::super::output::OutputStage<'_, '_>>, cache: &MoeWeightCache<'_>, ) -> Result> { let transport_failed = Rc::new(Cell::new(false)); - let result = step_run(binding, session, draft, input, output, (cache, &transport_failed)); + let result = step_run(binding, &mut sessions, input, output, (cache, &transport_failed)); + let session = &mut *sessions.target; if transport_failed.get() { session.note_mtp_failure(&Error::CudaExecution); } @@ -181,9 +180,9 @@ pub(super) fn norm( binding: &ModelBinding, role: MtpRole, values: &[f32], - hidden: bool, cache: &MoeWeightCache<'_>, ) -> Result> { + let hidden = role == MtpRole::HiddenNorm; let gamma = f32_weights(binding, role, cache)?; let n = norm_width(hidden); validate_values(values, n)?; 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 366f22ba..fe8f6764 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs @@ -7,7 +7,7 @@ use super::{ PrefillStepProduct, QwenForward, TargetStepProduct, VerificationChunk, VerificationSource, WindowCaches, }, kar_ple_cache::KarPleCache, - mtp::{self, MtpInput, MtpSession, reserve}, + mtp::{self, KnownNext, MtpInput, MtpSession, StepSessions, reserve}, output::OutputStage, session::QwenSession, }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs index cf9a012d..f4271a98 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs @@ -105,8 +105,14 @@ impl MtpDecoder { ) -> Result<()> { let prior = self.draft.checkpoint()?; let result = (|| { - let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; - mtp::step(binding, target, &mut self.draft, input, output, cache)?; + let input = MtpInput::from_target( + binding, + target, + &self.draft, + KnownNext { source, next_token: known_next }, + cache, + )?; + mtp::step(binding, StepSessions { target, draft: &mut self.draft }, input, output, cache)?; Ok(()) })(); if let Err(error) = result { @@ -129,7 +135,13 @@ impl MtpDecoder { ) -> Result<()> { let prior = self.draft.checkpoint()?; let result = (|| { - let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; + let input = MtpInput::from_target( + binding, + target, + &self.draft, + KnownNext { source, next_token: known_next }, + cache, + )?; mtp::warm_step(binding, target, &mut self.draft, input, cache) })(); if let Err(error) = result { @@ -150,7 +162,13 @@ impl MtpDecoder { ) -> Result<()> { let prior = self.draft.checkpoint()?; let result = (|| { - let input = MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?; + let input = MtpInput::from_prefill( + binding, + target, + &self.draft, + KnownNext { source, next_token: known_next }, + cache, + )?; mtp::warm_step(binding, target, &mut self.draft, input, cache) })(); if let Err(error) = result { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs index 8fdc56a9..47ca6dee 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs @@ -139,7 +139,7 @@ impl MtpDecoder { }; let input = self.batched_chain_input(cx, target, cache, previous.as_ref(), candidate)?; let seed_frame = plan.seed_frame(previous.is_none(), &input); - let product = mtp::step(binding, target, &mut self.draft, input, cx.output, cache)?; + let product = mtp::step(binding, StepSessions { target, draft: &mut self.draft }, input, cx.output, cache)?; first_seed = self.capture_seed(plan, seed_frame)?.or(first_seed); st.candidates.push(product.predicted(binding, target)?); previous = Some(product); @@ -162,7 +162,10 @@ impl MtpDecoder { ) -> Result { match previous { Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache), - None => MtpInput::from_target(cx.binding, target, &self.draft, cx.source, candidate, cache), + None => { + let next = KnownNext { source: cx.source, next_token: candidate }; + MtpInput::from_target(cx.binding, target, &self.draft, next, cache) + } } } @@ -207,7 +210,8 @@ impl MtpDecoder { if cancelled() { return Err(MtpWindowError::Cancelled); } - let input = MtpInput::from_target(binding, target, &self.draft, source, cx.plan.first, cache)?; + let next = KnownNext { source, next_token: cx.plan.first }; + let input = MtpInput::from_target(binding, target, &self.draft, next, cache)?; mtp::warm_step(binding, target, &mut self.draft, input, cache)?; Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs index d30fe4f5..36a6a8e3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs @@ -164,7 +164,8 @@ impl MtpDecoder { break; } let input = self.scalar_chain_input(cx, target, cache, previous.as_ref(), st, candidate)?; - let product = mtp::step(cx.binding, target, &mut self.draft, input, cx.output, cache)?; + let product = + mtp::step(cx.binding, StepSessions { target, draft: &mut self.draft }, input, cx.output, cache)?; st.candidates.push(product.predicted(cx.binding, target)?); previous = Some(product); } @@ -184,7 +185,13 @@ impl MtpDecoder { Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache), None => { let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?; - MtpInput::from_target(cx.binding, target, &self.draft, latest, candidate, cache) + MtpInput::from_target( + cx.binding, + target, + &self.draft, + KnownNext { source: latest, next_token: candidate }, + cache, + ) } } } @@ -266,7 +273,13 @@ impl MtpDecoder { expected: TokenId, ) -> WindowResult<()> { let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?; - let input = MtpInput::from_target(binding, target, &self.draft, latest, expected, cache)?; + let input = MtpInput::from_target( + binding, + target, + &self.draft, + KnownNext { source: latest, next_token: expected }, + cache, + )?; mtp::warm_step(binding, target, &mut self.draft, input, cache)?; if cancelled() { return Err(MtpWindowError::Cancelled); From fb23ce34519d0cba747557d22a0405ad0feea13f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:03 +0100 Subject: [PATCH 25/42] STRA-338 params e01: fixed draft MoE composition takes FrameAnchor, WorkspaceClaim and ExpertInputs; routed expert takes RouteSlot and QuantizedIndices Files: (none) --- .../impl_moeweightcache_4.rs | 18 +++------ .../src/qwen_forward/mtp_expert_workspace.rs | 38 ++++++++++++++++++- .../impl_drop_for_transport.rs | 34 ++++++----------- .../mtp_expert_workspace/impl_fixedbuffers.rs | 18 +++------ 4 files changed, 58 insertions(+), 50 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs index 57c21d7f..9c130183 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs @@ -3,6 +3,7 @@ use super::impl_moeweightcache_3::shared_keys_fn::{raw_shared_buffers, shared_descriptors}; #[allow(unused_imports)] use super::*; +use crate::qwen_forward::mtp_experts::fixed_workspace::{ExpertInputs, FrameAnchor, WorkspaceClaim}; impl<'ctx> MoeWeightCache<'ctx> { /// Source-descriptor admission precedes all fills. Requested entries cannot @@ -118,19 +119,10 @@ impl<'ctx> MoeWeightCache<'ctx> { failed: &Rc>, ) -> Result> { let mut slot = self.mtp_experts.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - slot.as_mut().ok_or(Error::IdentityMismatch)?.compose( - binding, - &self.mmq_owner, - context, - frame, - session, - bank, - shared, - mixed, - ids, - weights, - Rc::clone(failed), - ) + let anchor = FrameAnchor { binding, frame, session }; + let claim = WorkspaceClaim { owner: &self.mmq_owner, context }; + let inputs = ExpertInputs { bank, shared, mixed, ids, weights }; + slot.as_mut().ok_or(Error::IdentityMismatch)?.compose(anchor, claim, inputs, Rc::clone(failed)) } pub(in super::super::super) fn has_mtp_kv_ring(&self) -> Result { let slot = self.mtp_kv.try_borrow().map_err(|_| Error::IdentityMismatch)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs index dd1b2282..6d7fdd74 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs @@ -91,6 +91,39 @@ pub(in crate::qwen_forward) struct MtpExpertWorkspace<'ctx> { owner: Rc<()>, storage: FixedBuffers<'ctx>, } +/// The draft frame, checked against the model binding and the target session before and after a composition. +pub(in crate::qwen_forward) struct FrameAnchor<'a, 'session> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) frame: &'a MtpFrame, + pub(in crate::qwen_forward) session: &'a QwenSession<'session>, +} +/// The cache owner token and the device context that must be the ones this workspace was created for. +pub(in crate::qwen_forward) struct WorkspaceClaim<'a, 'ctx> { + pub(in crate::qwen_forward) owner: &'a Rc<()>, + pub(in crate::qwen_forward) context: &'a Context<'ctx>, +} +/// What one draft composition reads: the expert bank, the shared-expert matrices, the mixed hidden row and the +/// ids and weights of the ten routed experts. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ExpertInputs<'a, 'bank, 'shared> { + pub(in crate::qwen_forward) bank: &'a DeviceBuffer<'bank>, + pub(in crate::qwen_forward) shared: [&'a DeviceBuffer<'shared>; 4], + pub(in crate::qwen_forward) mixed: &'a [f32], + pub(in crate::qwen_forward) ids: [u32; K], + pub(in crate::qwen_forward) weights: [f32; K], +} +/// The slot a routed expert occupies in the ten-expert route and the expert it selects. +#[derive(Clone, Copy)] +struct RouteSlot { + slot: usize, + expert: u32, +} +/// The transport indices of the quantized input values and their scales. +#[derive(Clone, Copy)] +struct QuantizedIndices { + values: usize, + scales: usize, +} #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod fixed_workspace_gpu { @@ -198,7 +231,7 @@ mod fixed_workspace_gpu { ) -> Result { let mut t = Transport::new(storage, Rc::new(Cell::new(false)))?; t.observations = Some(Vec::new()); - let result = compose_inner(&mut t, bank, w, mixed, IDS, ROUTE); + let result = compose_inner(&mut t, ExpertInputs { bank, shared: w, mixed, ids: IDS, weights: ROUTE }); let observed = t.observations.take().ok_or(Error::IdentityMismatch)?; t.finish(result.map(|output| (output, observed))) } @@ -308,7 +341,8 @@ mod fixed_workspace_gpu { actual.len() } fn compose_with(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32], failed: bool) -> Result> { - compose(storage, &self.bank, self.w(), mixed, IDS, ROUTE, Rc::new(Cell::new(failed))) + let inputs = ExpertInputs { bank: &self.bank, shared: self.w(), mixed, ids: IDS, weights: ROUTE }; + compose(storage, inputs, Rc::new(Cell::new(failed))) } fn refuse_bad_input_and_failed_flag(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32]) { let mut bad = mixed.to_vec(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs index 762e4b61..2b226023 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs @@ -55,15 +55,14 @@ fn routed_down( pub(super) fn routed( transport: &mut Transport<'_, '_>, bank: &DeviceBuffer<'_>, - slot: usize, - expert: u32, - q: usize, - scales: usize, + pick: RouteSlot, + quantized: QuantizedIndices, ) -> Result { + let RouteSlot { slot, expert } = pick; if slot >= K || expert >= 512 { return Err(Error::InvalidExpert); } - let hidden_index = routed_hidden(transport, bank, (slot, expert), (q, scales))?; + let hidden_index = routed_hidden(transport, bank, (slot, expert), (quantized.values, quantized.scales))?; routed_down(transport, bank, (slot, expert), hidden_index) } pub(super) fn shared_project( @@ -205,20 +204,15 @@ impl Packed { }) } } -#[allow(clippy::too_many_arguments)] pub(super) fn compose( storage: &mut FixedBuffers<'_>, - bank: &DeviceBuffer<'_>, - shared_weights: [&DeviceBuffer<'_>; 4], - mixed: &[f32], - ids: [u32; K], - weights: [f32; K], + inputs: ExpertInputs<'_, '_, '_>, failed: Rc>, ) -> Result> { - validate_values(mixed, N)?; - validate_route(ids.map(|id| i32::try_from(id).unwrap_or(-1)), &weights)?; + validate_values(inputs.mixed, N)?; + validate_route(inputs.ids.map(|id| i32::try_from(id).unwrap_or(-1)), &inputs.weights)?; let mut transport = Transport::new(storage, failed)?; - let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights); + let result = compose_inner(&mut transport, inputs); transport.finish(result) } /// Every routed expert's Down, packed in slot order; the first failure stops before any later expert runs. @@ -230,19 +224,13 @@ fn pack_routed( (q, scales): (usize, usize), ) -> Result<()> { for (slot, expert) in ids.into_iter().enumerate() { - let down = routed(transport, bank, slot, expert, q, scales)?; + let down = routed(transport, bank, RouteSlot { slot, expert }, QuantizedIndices { values: q, scales })?; packed.pack(transport, down)?; } Ok(()) } -pub(super) fn compose_inner( - transport: &mut Transport<'_, '_>, - bank: &DeviceBuffer<'_>, - shared_weights: [&DeviceBuffer<'_>; 4], - mixed: &[f32], - ids: [u32; K], - weights: [f32; K], -) -> Result> { +pub(super) fn compose_inner(transport: &mut Transport<'_, '_>, inputs: ExpertInputs<'_, '_, '_>) -> Result> { + let ExpertInputs { bank, shared: shared_weights, mixed, ids, weights } = inputs; let input = transport.upload(mixed, Slot::Input)?; let mut packed = Packed::new(transport, ids)?; let (q, scales) = transport.quantize(input, false)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs index 2b7ae51b..b0f4477a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs @@ -70,21 +70,15 @@ impl<'ctx> MtpExpertWorkspace<'ctx> { ) -> Result { Ok(Self { binding, owner, storage: FixedBuffers::new(context)? }) } - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn compose( &mut self, - binding: &ModelBinding, - owner: &Rc<()>, - context: &Context<'_>, - frame: &MtpFrame, - session: &QwenSession<'_>, - bank: &DeviceBuffer<'_>, - shared: [&DeviceBuffer<'_>; 4], - mixed: &[f32], - ids: [u32; K], - weights: [f32; K], + anchor: FrameAnchor<'_, '_>, + claim: WorkspaceClaim<'_, '_>, + inputs: ExpertInputs<'_, '_, '_>, failed: Rc>, ) -> Result> { + let FrameAnchor { binding, frame, session } = anchor; + let WorkspaceClaim { owner, context } = claim; frame.validate(binding, session)?; if !self.binding.matches(&binding.identity()) || !Rc::ptr_eq(&self.owner, owner) @@ -94,7 +88,7 @@ impl<'ctx> MtpExpertWorkspace<'ctx> { return Err(Error::IdentityMismatch); } self.storage.check()?; - let result = compose(&mut self.storage, bank, shared, mixed, ids, weights, failed); + let result = compose(&mut self.storage, inputs, failed); result.and_then(|values| frame.validate(binding, session).map(|()| values)) } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { From 88ade88d374edf64e3ebcfb3e039001eb7ef858b Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:03 +0100 Subject: [PATCH 26/42] STRA-338 params e01: PLE transport composition takes the closed weights and the three host rows Files: (none) --- .../qwen_forward/input/impl_inputstage_2.rs | 8 ++-- .../src/qwen_forward/ple_key_retained_gpu.rs | 19 +++----- .../src/qwen_forward/ple_transport.rs | 7 +++ .../ple_transport/compose_inner_fn.rs | 47 +++++++------------ .../qwen_forward/ple_transport/impl_role.rs | 25 ++++------ 5 files changed, 42 insertions(+), 64 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs index 26da65ad..af9b9a55 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs @@ -218,14 +218,16 @@ fn compose_cached_ple( let key = cache.ple_key(entry)?; let value = cache.ple_value(entry)?; let aux = cache.ple_aux(entry)?; + let weights = leleka_cuda_driver::PleClosedWeights { key, value, aux }; + let rows = ple_transport::PleRows { embedding, streams, history }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let result = if let Some(mut queue) = cache.ple_queue(binding, context)? { - ple_transport::compose_queued(&mut queue, context, key, value, aux, embedding, streams, history, failed) + ple_transport::compose_queued(&mut queue, context, weights, rows, failed) } else { - ple_transport::compose(context, key, value, aux, embedding, streams, history, failed) + ple_transport::compose(context, weights, rows, failed) }; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let result = ple_transport::compose(context, key, value, aux, embedding, streams, history, failed); + let result = ple_transport::compose(context, weights, rows, failed); result } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs index 480be07f..fa165518 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs @@ -2,7 +2,7 @@ #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::{ple_upload, ple_upload_f32}; use super::*; -use leleka_cuda_driver::Driver; +use leleka_cuda_driver::{Driver, PleClosedWeights}; struct Matrices<'ctx> { key: DeviceBuffer<'ctx>, value: DeviceBuffer<'ctx>, @@ -17,7 +17,8 @@ fn refused( (key, value, aux): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, [&DeviceBuffer<'_>; 4]), (embedding, streams, history): (&[f32], &[f32], &[f32]), ) -> Result { - compose(ctx, key, value, aux, embedding, streams, history, Rc::new(Cell::new(false))) + let rows = PleRows { embedding, streams, history }; + compose(ctx, PleClosedWeights { key, value, aux }, rows, Rc::new(Cell::new(false))) } #[test] @@ -55,17 +56,9 @@ fn prove_trace(ctx: &Context<'_>, matrices: &Matrices<'_>, charged: usize, zero: let expected = original(ctx, matrices, &embedding, &streams, &history); assert_eq!(ctx.allocated_bytes(), charged); let failed = Rc::new(Cell::new(false)); - let observed = compose_observed( - ctx, - &matrices.key, - &matrices.value, - matrices.aux(), - &embedding, - &streams, - &history, - failed.clone(), - ) - .unwrap(); + let weights = PleClosedWeights { key: &matrices.key, value: &matrices.value, aux: matrices.aux() }; + let rows = PleRows { embedding: &embedding, streams: &streams, history: &history }; + let observed = compose_observed(ctx, weights, rows, failed.clone()).unwrap(); check_trace(observed, &expected); assert_eq!(embedding.iter().chain(&streams).chain(&history).map(|x| x.to_bits()).collect::>(), snapshot); assert!(!failed.get()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs index f43412e3..ad9ceaec 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs @@ -30,6 +30,13 @@ struct Finite { role: Role, invocation: Rc<()>, } +/// The three host rows one PLE composition reads: the token embedding, the residual streams and the conv history. +#[derive(Clone, Copy)] +pub(super) struct PleRows<'a> { + pub(super) embedding: &'a [f32], + pub(super) streams: &'a [f32], + pub(super) history: &'a [f32], +} struct Transport<'ctx> { context: &'ctx Context<'ctx>, buffers: Vec>>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs index c42217e2..08994a11 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs @@ -2,17 +2,15 @@ #[allow(unused_imports)] use super::*; +use leleka_cuda_driver::PleClosedWeights; -#[allow(clippy::too_many_arguments)] pub(super) fn compose_inner( transport: &mut Transport<'_>, - key_matrix: &DeviceBuffer<'_>, - value_matrix: &DeviceBuffer<'_>, - aux: [&DeviceBuffer<'_>; 4], - embedding: &[f32], - streams: &[f32], - history: &[f32], + weights: PleClosedWeights<'_, '_>, + rows: PleRows<'_>, ) -> Result { + let PleClosedWeights { key: key_matrix, value: value_matrix, aux } = weights; + let PleRows { embedding, streams, history } = rows; let (raw_key, value_index) = project_key_value(transport, key_matrix, value_matrix, embedding)?; let residual = transport.upload(streams)?; let prior = transport.upload(history)?; @@ -174,21 +172,16 @@ fn conv_operands<'a, 'ctx>( } #[cfg(test)] -#[allow(clippy::too_many_arguments)] pub(super) fn compose_observed( context: &Context<'_>, - key_matrix: &DeviceBuffer<'_>, - value_matrix: &DeviceBuffer<'_>, - aux: [&DeviceBuffer<'_>; 4], - embedding: &[f32], - streams: &[f32], - history: &[f32], + weights: PleClosedWeights<'_, '_>, + rows: PleRows<'_>, failed: Rc>, ) -> Result { - admit(key_matrix, value_matrix, &aux, embedding, streams, history)?; + admit(&weights, rows)?; let mut transport = Transport::new(context, failed)?; transport.observations = Some(Vec::new()); - let result = compose_inner(&mut transport, key_matrix, value_matrix, aux, embedding, streams, history); + let result = compose_inner(&mut transport, weights, rows); let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?; let output = transport.finish(result)?; Ok((output, observations)) @@ -196,24 +189,18 @@ pub(super) fn compose_observed( /// Explicit selected producer only. The caller retains the real PleOwner, /// current TokenLayer, prior and exact cache weight lineage before/after this call. -#[allow(clippy::too_many_arguments)] pub(in super::super) fn compose_queued( queue: &mut leleka_cuda_driver::PleClosedQueue<'_>, context: &Context<'_>, - key_matrix: &DeviceBuffer<'_>, - value_matrix: &DeviceBuffer<'_>, - aux: [&DeviceBuffer<'_>; 4], - embedding: &[f32], - streams: &[f32], - history: &[f32], + weights: PleClosedWeights<'_, '_>, + rows: PleRows<'_>, failed: Rc>, ) -> Result { - admit(key_matrix, value_matrix, &aux, embedding, streams, history)?; + admit(&weights, rows)?; if failed.get() { return Err(Error::CudaExecution); } - let weights = leleka_cuda_driver::PleClosedWeights { key: key_matrix, value: value_matrix, aux }; - let result = compose_on_queue(queue, context, weights, embedding, streams, history); + let result = compose_on_queue(queue, context, weights, rows); if matches!(result, Err(Error::CudaExecution)) || queue.is_failed() { failed.set(true); } @@ -223,13 +210,11 @@ pub(in super::super) fn compose_queued( fn compose_on_queue( queue: &mut leleka_cuda_driver::PleClosedQueue<'_>, context: &Context<'_>, - weights: leleka_cuda_driver::PleClosedWeights<'_, '_>, - embedding: &[f32], - streams: &[f32], - history: &[f32], + weights: PleClosedWeights<'_, '_>, + rows: PleRows<'_>, ) -> Result { queue.validate_context(context).map_err(ple_driver_error)?; - let completion = queue.compose(weights, embedding, streams, history).map_err(ple_driver_error)?; + let completion = queue.compose(weights, rows.embedding, rows.streams, rows.history).map_err(ple_driver_error)?; let (streams, history) = completion.into_parts().map_err(|_| Error::NonFinite)?; ple_values(&streams, PLE_HC)?; ple_values(&history, PLE_HISTORY)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs index 2918a30b..6fc785a4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +use leleka_cuda_driver::PleClosedWeights; impl Role { pub(super) fn count(self) -> usize { @@ -146,30 +147,20 @@ pub(super) fn at<'a, 'ctx>(buffers: &'a [Option>], index: usi buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } -#[allow(clippy::too_many_arguments)] pub(in super::super) fn compose( context: &Context<'_>, - key_matrix: &DeviceBuffer<'_>, - value_matrix: &DeviceBuffer<'_>, - aux: [&DeviceBuffer<'_>; 4], - embedding: &[f32], - streams: &[f32], - history: &[f32], + weights: PleClosedWeights<'_, '_>, + rows: PleRows<'_>, failed: Rc>, ) -> Result { - admit(key_matrix, value_matrix, &aux, embedding, streams, history)?; + admit(&weights, rows)?; let mut transport = Transport::new(context, failed)?; - let result = compose_inner(&mut transport, key_matrix, value_matrix, aux, embedding, streams, history); + let result = compose_inner(&mut transport, weights, rows); transport.finish(result) } -pub(super) fn admit( - key: &DeviceBuffer<'_>, - value: &DeviceBuffer<'_>, - aux: &[&DeviceBuffer<'_>; 4], - embedding: &[f32], - streams: &[f32], - history: &[f32], -) -> Result<()> { +pub(super) fn admit(weights: &PleClosedWeights<'_, '_>, rows: PleRows<'_>) -> Result<()> { + let PleRows { embedding, streams, history } = rows; + let (key, value, aux) = (weights.key, weights.value, &weights.aux); ple_values(embedding, 2560)?; ple_values(streams, PLE_HC)?; ple_values(history, PLE_HISTORY)?; From 0956833f7870c0f0d61b27d2e151c7c003cc7505 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:04 +0100 Subject: [PATCH 27/42] STRA-338 params e01: resident QSA index-key cache selects through QsaSelectionRequest Files: (none) --- .../src/qwen_forward/dense_weight_cache.rs | 1 + .../impl_denseweightcache_5.rs | 2 +- .../src/qwen_forward/qsa_index_resident.rs | 14 +++++++++----- .../qsa_index_resident/max_rows_fn.rs | 17 ++++++++--------- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs index 73f571c8..903fcff5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs @@ -40,6 +40,7 @@ pub(crate) struct DenseCacheCounters { } /// What a resident-key selection scores: the candidate prior whose keys are searched, the index query vector and the /// token position being selected for. +#[derive(Clone, Copy)] pub(super) struct QsaSelectionRequest<'a> { pub(super) candidate: &'a QsaPrior, pub(super) index_query: &'a [f32], diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs index df58e912..eb7b659c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs @@ -144,7 +144,7 @@ impl<'ctx> DenseWeightCache<'ctx> { .ok_or(Error::IdentityMismatch)? .try_borrow_mut() .map_err(|_| Error::IdentityMismatch)? - .select(&self.binding, context, request.candidate, request.index_query, request.position) + .select(&self.binding, context, request) } pub(in super::super::super) fn gdn_input<'slot, 'source>( &'slot self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs index 357078a5..71f8510e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs @@ -165,7 +165,8 @@ mod gpu { ); let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior(); let expected = select(context, &next.score_keys().unwrap(), &next.0.dead, iq, p as u32).unwrap(); - let actual = cache.select(binding, context, &next, iq, p as u32).unwrap(); + let request = QsaSelectionRequest { candidate: &next, index_query: iq, position: p as u32 }; + let actual = cache.select(binding, context, request).unwrap(); assert_eq!(actual.as_ref(), expected.as_ref()); total += actual.len(); prior = next; @@ -177,10 +178,11 @@ mod gpu { let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq); let replacement = synthetic_late_prior_for(binding.clone(), 190004); let expected = select(context, &replacement.score_keys().unwrap(), &replacement.0.dead, iq, 190003).unwrap(); - let actual = cache.select(binding, context, &replacement, iq, 190003).unwrap(); + let request = QsaSelectionRequest { candidate: &replacement, index_query: iq, position: 190003 }; + let actual = cache.select(binding, context, request).unwrap(); assert_eq!(actual.as_ref(), expected.as_ref()); let uploads = cache.uploads; - assert_eq!(cache.select(binding, context, &replacement, iq, 190003).unwrap().as_ref(), expected.as_ref()); + assert_eq!(cache.select(binding, context, request).unwrap().as_ref(), expected.as_ref()); assert_eq!(cache.uploads, uploads); (replacement, uploads) } @@ -193,10 +195,12 @@ mod gpu { let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq); let wrong = BindingIdentity::test_identity(); // Bound position and malformed source must refuse before any transfer. - assert!(cache.select(&wrong, context, replacement, iq, 190002).is_err()); + let wrong_position = QsaSelectionRequest { candidate: replacement, index_query: iq, position: 190002 }; + assert!(cache.select(&wrong, context, wrong_position).is_err()); let mut bad = *iq; bad[511] = f32::NAN; - assert!(cache.select(binding, context, replacement, &bad, 190003).is_err()); + let malformed = QsaSelectionRequest { candidate: replacement, index_query: &bad, position: 190003 }; + assert!(cache.select(binding, context, malformed).is_err()); assert_eq!(cache.uploads, uploads); } #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs index c0caeb47..3252a29f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs @@ -144,18 +144,17 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { &mut self, binding: &BindingIdentity, context: &Context<'_>, - next: &QsaPrior, - iq: &[f32], - p: u32, + request: QsaSelectionRequest<'_>, ) -> Result> { if self.failed.get() { return Err(Error::CudaExecution); } - self.check_select(binding, context, next, iq, p)?; + self.check_select(binding, context, request)?; + let next = request.candidate; let slot = next.layer().get() as usize / 4; let rows = next.0.pooled.len().checked_add(1).ok_or(Error::Overflow)?; let action = self.plan(slot, rows, next)?; - let result = self.apply_action(slot, action, next, iq, p); + let result = self.apply_action(slot, action, request); if result.is_err() { self.failed.set(true); } @@ -165,10 +164,9 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { &self, binding: &BindingIdentity, context: &Context<'_>, - next: &QsaPrior, - iq: &[f32], - p: u32, + request: QsaSelectionRequest<'_>, ) -> Result<()> { + let QsaSelectionRequest { candidate: next, index_query: iq, position: p } = request; if !self.binding.matches(binding) || !next.0.binding.matches(binding) || !std::ptr::eq(self.context, context) @@ -192,7 +190,8 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { } Ok(entry.prior.as_ref().map(|old| update(old, next)).transpose()?.unwrap_or(Update::Reload)) } - fn apply_action(&mut self, slot: usize, action: Update, next: &QsaPrior, iq: &[f32], p: u32) -> Result> { + fn apply_action(&mut self, slot: usize, action: Update, request: QsaSelectionRequest<'_>) -> Result> { + let QsaSelectionRequest { candidate: next, index_query: iq, position: p } = request; match action { Update::Reload => self.reload(slot, next)?, Update::Append(row) => self.append_row(slot, next, row)?, From 840622a04eeac1e2398d92c9f7c509dbe4c6ad4e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:04 +0100 Subject: [PATCH 28/42] STRA-338 params e01: KV cell comparison, verifier assembly preparation, QSA input parity proof and oracle capture take domain values Files: (none) --- .../src/gpu_proofs/singleload_proof.rs | 7 ++-- .../src/qwen_forward/mtp_kv_only.rs | 12 ++++-- .../src/qwen_forward/oracle_capture.rs | 35 ++++++++++------- .../qwen_forward/original_serve_verifier.rs | 6 +-- .../original_serve_verifier/assemble_parts.rs | 38 +++++++++---------- .../src/qwen_forward/qsa_input_reuse_gpu.rs | 13 +++++-- 6 files changed, 63 insertions(+), 48 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs index 5f830307..75020c11 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs @@ -10,6 +10,8 @@ use std::{ panic::{AssertUnwindSafe, catch_unwind, resume_unwind}, }; +use crate::qwen_forward::oracle_capture::Caches; + fn required_path(name: &str) -> PathBuf { env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path") } @@ -17,13 +19,12 @@ fn required_path(name: &str) -> PathBuf { /// Capture of two tokens on a fresh owner, then the observation cleanup. fn capture_two<'d>(binding: &ModelBinding, context: &Rc>, owners: &mut Owners<'d>) { let mut captured = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context)); + let caches = Caches { cache: &mut owners.kar, moe: &mut owners.moe, dense: &owners.dense }; let capture = crate::qwen_forward::oracle_capture::check_on_loaded( binding, &mut captured, &owners.output, - &mut owners.kar, - &mut owners.moe, - &owners.dense, + caches, required_path("LELEKA_STRA169_CAPTURE_DIR"), ); let disabled = crate::qwen_forward::oracle_capture::disable(&owners.output); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs index 2e7c73f0..8872a40d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs @@ -77,7 +77,7 @@ pub(in crate::qwen_forward) fn compare_kv_cell_on_loaded_input( cache: &MoeWeightCache<'_>, ) -> Result { let failed = Rc::new(Cell::new(false)); - let result = compare_kv_cell_inner(binding, target, draft, input, cache, &failed); + let result = compare_kv_cell_inner(binding, target, ComparedKvCell { draft, input }, cache, &failed); if failed.get() { target.note_mtp_failure(&Error::CudaExecution); } @@ -86,15 +86,21 @@ pub(in crate::qwen_forward) fn compare_kv_cell_on_loaded_input( } result } +/// The draft session and the draft input whose attention K/V cell is compared with the canonical producer. +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +struct ComparedKvCell<'a> { + draft: &'a MtpSession, + input: &'a MtpInput, +} #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn compare_kv_cell_inner( binding: &ModelBinding, target: &mut QwenSession<'_>, - draft: &MtpSession, - input: &MtpInput, + compared: ComparedKvCell<'_>, cache: &MoeWeightCache<'_>, failed: &Rc>, ) -> Result { + let ComparedKvCell { draft, input } = compared; use super::super::{mtp_attention, mtp_gr}; let read = mtp_gr::attention_read(binding, input, target, cache)?; let reference = mtp_attention::MtpAttentionStage::run(binding, &read, draft, target, cache, Rc::clone(failed))?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs index 61fb27e7..5e35ef0c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs @@ -185,10 +185,10 @@ fn finish_position() -> Result<()> { }) } /// The three weight caches one captured forward step reads and fills. -struct Caches<'a, 'k, 'm, 'd> { - cache: &'a mut KarPleCache<'k>, - moe: &'a mut MoeWeightCache<'m>, - dense: &'a DenseWeightCache<'d>, +pub(crate) struct Caches<'a, 'k, 'm, 'd> { + pub(crate) cache: &'a mut KarPleCache<'k>, + pub(crate) moe: &'a mut MoeWeightCache<'m>, + pub(crate) dense: &'a DenseWeightCache<'d>, } fn admit_capture(binding: &ModelBinding, session: &QwenSession<'_>) -> Result<()> { if binding.layer_count() != 48 || binding.kar_ple_binding().is_none() { @@ -217,14 +217,23 @@ fn emit_logits(output: &OutputStage<'_, '_>, greedy: u32) -> Result<()> { file_words("logits.f32", &logits)?; file_words("greedy.i32", &[greedy]) } +/// One captured forward step: its position and token, with the vocabulary and context dimensions they are checked +/// against. +#[derive(Clone, Copy)] +struct CaptureStep { + position: u64, + token: u64, + vocabulary: Dimension, + context: Dimension, +} fn capture_position( binding: &ModelBinding, session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, caches: &mut Caches<'_, '_, '_, '_>, - (vocabulary, context): (Dimension, Dimension), - (position, token): (u64, u64), + step: CaptureStep, ) -> Result<()> { + let CaptureStep { position, token, vocabulary, context } = step; if position >= CONFIGURED_CONTEXT { return Err(Error::InvalidPosition); } @@ -236,23 +245,20 @@ fn capture_position( session.oracle_capture_committed(binding, position)?; finish_position() } -#[allow(clippy::too_many_arguments)] pub(crate) fn check_on_loaded( binding: &ModelBinding, session: &mut QwenSession<'_>, output: &OutputStage<'_, '_>, - cache: &mut KarPleCache<'_>, - moe_cache: &mut MoeWeightCache<'_>, - dense_cache: &DenseWeightCache<'_>, + mut caches: Caches<'_, '_, '_, '_>, directory: PathBuf, ) -> Result<()> { admit_capture(binding, session)?; initialize(directory)?; output.test_reset_replay_record(true)?; - let dimensions = capture_dimensions(binding)?; - let mut caches = Caches { cache, moe: moe_cache, dense: dense_cache }; + let (vocabulary, context) = capture_dimensions(binding)?; for (position, token) in [0u64, 1].into_iter().enumerate() { - capture_position(binding, session, output, &mut caches, dimensions, (position as u64, token))?; + let step = CaptureStep { position: position as u64, token, vocabulary, context }; + capture_position(binding, session, output, &mut caches, step)?; } output.test_reset_replay_record(false)?; with(|c| write(c, "CAPTURE-COMPLETE.txt", b"candidate_capture_complete=2\ncomparison_performed=false\n"))?; @@ -310,7 +316,8 @@ fn run_capture(binding: &ModelBinding, context: &Rc AssembleInputs<'_, 'a, 'ctx> { return Err(refused(failure, owners)); } let p = super::original_serve_profile::span("assemble.prepare"); - let shape = (max_t, self.max_cells, self.blobs); - let prepare = - prepare_assembly(self.binding, self.weights.dense, self.context, self.base, self.ple_history, shape); + let prepare = self.prepare_assembly(max_t); drop(p); let prepared = match prepare { Ok(parts) => parts, @@ -336,7 +334,7 @@ fn recover<'a, 'ctx>(qsa: Rc>, slots: [usize; } mod assemble_parts; -use assemble_parts::{Prepared, RecordEnv, capture_verifier, prepare_assembly, split_owners}; +use assemble_parts::{Prepared, RecordEnv, capture_verifier, split_owners}; #[cfg(test)] mod tests; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs index 7c40de3c..d06e4379 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/assemble_parts.rs @@ -16,28 +16,24 @@ pub(super) type QsaParts<'ctx> = pub(super) type Prepared<'a, 'ctx> = (OriginalVerifyGeometry, OriginalVerifyCanonicalGdn<'ctx>, [&'a DeviceBuffer<'ctx>; 12]); -/// Everything that can be refused WITHOUT consuming the owners. -pub(super) fn prepare_assembly<'a, 'ctx>( - binding: &ModelBinding, - dense: &'a DenseWeightCache<'ctx>, - context: &'ctx Context<'ctx>, - base: &OriginalVerifiedBase<'ctx>, - ple_history: &DeviceBuffer<'ctx>, - shape: (usize, usize, &ExpertBlobSizes), -) -> std::result::Result, ServeFailure> { - let (max_t, max_cells, blobs) = shape; - let geometry = verify_geometry(max_t, max_cells, blobs)?; - blobs.layout()?; - let priors = gdn_layer_priors(binding, base)?; - let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values()); - let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history()); - let canonical = context.original_verify_canonical_gdn(states, histories)?; - // PLE history: the seeded device image the commit graph keeps current. - if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES { - return Err(Error::InvalidDimension.into()); +impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> { + /// Everything that can be refused WITHOUT consuming the owners. + pub(super) fn prepare_assembly(&self, max_t: usize) -> std::result::Result, ServeFailure> { + let (binding, dense, context) = (self.binding, self.weights.dense, self.context); + let (base, ple_history, blobs) = (self.base, self.ple_history, self.blobs); + let geometry = verify_geometry(max_t, self.max_cells, blobs)?; + blobs.layout()?; + let priors = gdn_layer_priors(binding, base)?; + let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values()); + let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history()); + let canonical = context.original_verify_canonical_gdn(states, histories)?; + // PLE history: the seeded device image the commit graph keeps current. + if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES { + return Err(Error::InvalidDimension.into()); + } + let gamma = dense.original_verify_qsa_gamma(binding)?; + Ok((geometry, canonical, gamma)) } - let gamma = dense.original_verify_qsa_gamma(binding)?; - Ok((geometry, canonical, gamma)) } /// From here the owners move into the journal: the twelve resident layers in ascending slot order. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs index fb692525..885a3d2d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs @@ -97,7 +97,7 @@ fn prove_parity(context: &Context<'_>, binding: &BindingIdentity, scratch: &RefC (QsaMatrixRole::Q, 12288, 3), (QsaMatrixRole::IndexQ, 512, 4), ] { - prove_role(context, binding, &lease, &input, role, zero); + prove_role(context, binding, &lease, ParityInput { values: &input, zero }, role); } assert_eq!(input.iter().map(|v| v.to_bits()).collect::>(), source_bits); drop(lease); @@ -105,14 +105,21 @@ fn prove_parity(context: &Context<'_>, binding: &BindingIdentity, scratch: &RefC assert_eq!(context.allocated_bytes(), INPUT_BYTES); } +/// The input row of the parity proof and whether it is the signed-zero variant. +#[derive(Clone, Copy)] +struct ParityInput<'a> { + values: &'a [f32], + zero: bool, +} + fn prove_role( context: &Context<'_>, binding: &BindingIdentity, lease: &QsaInputLease<'_, '_, '_>, - input: &[f32], + source: ParityInput<'_>, (role, rows, seed): (QsaMatrixRole, usize, usize), - zero: bool, ) { + let ParityInput { values: input, zero } = source; let bytes = matrix_bytes(rows, seed); let matrix = bytes_upload(context, &bytes); let fresh = upload(context, input).unwrap(); From 89258ce6fc217f5a221782b597f3268d1c8c558c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:05 +0100 Subject: [PATCH 29/42] STRA-338 params e01: native MMQ model gate takes LoadedTargetOwners (same type and file as e02) Files: (none) --- .../native_resident_mmq_model_proof.rs | 5 ++++- .../executor_native_mmq_evaluation.rs | 22 +++++-------------- .../src/qwen_forward/loaded_target_owners.rs | 17 ++++++++++++++ .../src/qwen_forward/mod.rs | 2 ++ 4 files changed, 29 insertions(+), 17 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs index 9a1991e2..d407e2ea 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs @@ -1,6 +1,7 @@ //! Private sole new changed-path model gate; actual source identity/load preserved. use super::combined_changed_boundary_proof::rig::{DEVICE_BUDGET, Owners, bind_pinned, require_opt_in}; use super::*; +use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; use std::{env, panic::resume_unwind}; fn required_path(name: &str) -> PathBuf { @@ -67,7 +68,9 @@ fn pinned_single_load_native_resident_mmq_model_numeric() { let device = driver.device(0).expect("prefix CUDA device0 unavailable"); let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL)); - let numerical = owners.run(&binding, &context, QwenForward::test_native_mmq_on_loaded); + let numerical = owners.run(&binding, &context, |binding, session, output, kar, moe, dense| { + QwenForward::test_native_mmq_on_loaded(LoadedTargetOwners { binding, session, output, kar, moe, dense }) + }); let mut teardown = owners.close(true); teardown.close_context(context); drop((binding, inherited)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs index 8b94f02d..429d8c82 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs @@ -1,6 +1,7 @@ //! Separate native-certified activation model observer. Original failed observer unchanged. use super::mmq_evaluation::{ChunkExact, ChunkRun, MmqRun, Observation, pos}; use super::*; +use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; use crate::qwen_forward::mtp_decode::MtpDecoder; #[derive(Debug)] @@ -45,25 +46,14 @@ pub(crate) struct NativeMmqReport { pub(crate) native_fallback_layers: u64, } impl QwenForward { - pub(crate) fn test_native_mmq_on_loaded<'driver>( - binding: &ModelBinding, - session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, - ) -> NativeMmqReport { - check_native_mmq_on_loaded(binding, session, output, kar, moe, dense) + pub(crate) fn test_native_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) -> NativeMmqReport { + check_native_mmq_on_loaded(owners) } } -pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( - binding: &ModelBinding, - session: &mut QwenSession<'driver>, - output: &OutputStage<'_, '_>, - kar: &mut KarPleCache<'_>, - moe: &mut MoeWeightCache<'driver>, - dense: &DenseWeightCache<'_>, +pub(in crate::qwen_forward) fn check_native_mmq_on_loaded( + owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>, ) -> NativeMmqReport { + let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners; let mut run = MmqRun::new(binding, session, output, kar, moe, dense); let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused"); assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs b/crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs new file mode 100644 index 00000000..1182dd62 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/loaded_target_owners.rs @@ -0,0 +1,17 @@ +//! The freshly loaded target model and its device caches, as one value a `test_*_on_loaded` GPU phase receives. +use super::{ + dense_weight_cache::DenseWeightCache, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache, + output::OutputStage, session::QwenSession, +}; +use crate::model_binding::qwen4exp_input::ModelBinding; + +/// The loaded target model and every cache one on-loaded observation borrows; it exists so a phase takes one +/// argument instead of six owners that always travel together. +pub(crate) struct LoadedTargetOwners<'a, 'driver, 'o, 'p, 'k, 'd> { + pub(crate) binding: &'a ModelBinding, + pub(crate) session: &'a mut QwenSession<'driver>, + pub(crate) output: &'a OutputStage<'o, 'p>, + pub(crate) kar: &'a mut KarPleCache<'k>, + pub(crate) moe: &'a mut MoeWeightCache<'driver>, + pub(crate) dense: &'a DenseWeightCache<'d>, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs index d860c67d..1542ee18 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs @@ -11,6 +11,8 @@ pub(crate) mod kar_ple_cache; pub(crate) mod moe_expert; pub(crate) mod moe_route; // Original Strata prefill MoE router + shared expert over a whole micro-window of genuine FFN reads. +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod loaded_target_owners; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod moe_prefill_batch; pub(crate) mod moe_weight_cache; From b59d3f65f58840a2db2e7c175ec405bd14a0783d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:14 +0100 Subject: [PATCH 30/42] STRA-338 params e04: serve stack takes CpuGroup, SwapSources, QsaOwnerHome, TierResources and ExecutorOpening Files: none --- .../original_serve_pool/impl_cpuexpertpool.rs | 15 ++++-- .../src/qwen_forward/original_serve_seed.rs | 25 ++++++---- .../impl_originalservestack.rs | 8 +-- .../impl_originalservestack/decode_parts.rs | 50 ++++++++++++------- .../impl_originalservestack_2/open_phases.rs | 3 +- .../impl_originalservestack_2_2.rs | 17 ++++--- .../impl_originalservestack_4/decode_steps.rs | 29 +++++------ .../impl_originalservestack_5.rs | 15 +++--- .../impl_originalservestack/open_parts.rs | 33 +++++++----- 9 files changed, 115 insertions(+), 80 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs index fe12c89e..cd965141 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs @@ -3,6 +3,14 @@ #[allow(unused_imports)] use super::*; +/// One group of CPU expert entries: its input rows, the sink their outputs are written to and which entries the CPU +/// owns (`None`: all). +pub(super) struct CpuGroup<'a, 'r, 'b, 'c> { + rows: &'a OriginalVerifyCpuRows<'r>, + sink: &'a mut OriginalVerifyCpuSink<'b, 'c>, + include: Option<&'a [bool]>, +} + impl CpuExpertPool<'_> { /// Compute the entries `include` selects (all when `None`) and write the group's output: every computed /// `(row, slot)` gets its expert's row, every other one zeros (the GPU tier owns it; expert_source.cpp @@ -18,7 +26,7 @@ impl CpuExpertPool<'_> { let mut clock = window_trace::now(); let plan = Self::plan_group(&rows, count, include, &mut clock)?; if self.direct.is_some() { - self.run_direct(&rows, sink, include, &plan, &mut clock)?; + self.run_direct(CpuGroup { rows: &rows, sink: &mut *sink, include }, &plan, &mut clock)?; if self.legacy.is_some() { let results = self.legacy_results(&rows, &plan, &mut clock)?; return self.compare(sink, &plan, &results); @@ -59,12 +67,11 @@ impl CpuExpertPool<'_> { /// synchronous dispatch writing every computed row in place. pub(super) fn run_direct( &mut self, - rows: &OriginalVerifyCpuRows<'_>, - sink: &mut OriginalVerifyCpuSink<'_, '_>, - include: Option<&[bool]>, + entries: CpuGroup<'_, '_, '_, '_>, plan: &[ExpertJob], clock: &mut Option, ) -> Result<()> { + let CpuGroup { rows, sink, include } = entries; let binding = self.binding; let tier = self.direct.as_mut().ok_or(Error::IdentityMismatch)?; let (opened, group) = tier.open_for_group(binding, rows, plan)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs index 85fa24a0..b5e6b0c7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs @@ -67,18 +67,25 @@ pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: u choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) } +/// Where the source spans of the incoming experts come from: the binding, the weight cache, the CPU tier and the span +/// cache that remembers spans already opened. +pub(super) struct SwapSources<'a, 'ctx, 'p> { + pub(super) binding: &'a ModelBinding, + pub(super) moe: &'a MoeWeightCache<'ctx>, + pub(super) cpu: &'a mut CpuExpertPool<'p>, + pub(super) known: &'a mut SpanCache, +} + /// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the /// batch; /// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened /// under one fence (the direct CPU tier's admission when it is on). pub(super) fn queue_swaps<'ctx>( - binding: &ModelBinding, - moe: &MoeWeightCache<'ctx>, + sources: &mut SwapSources<'_, 'ctx, '_>, cache: &mut OriginalExpertCache<'ctx>, - cpu: &mut CpuExpertPool<'_>, - known: &mut SpanCache, swaps: &[Swap], ) -> Result<()> { + let (binding, moe) = (sources.binding, sources.moe); let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; let mut layer_swaps: Vec> = vec![Vec::new(); LAYERS]; for swap in swaps { @@ -89,7 +96,8 @@ pub(super) fn queue_swaps<'ctx>( continue; } let incoming: Vec = group.iter().map(|s| s.incoming as u32).collect(); - let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, known, layer, &incoming)?; + let spans: Vec<[ResidentExpertBankSpan; 3]> = + source_spans(sources.cpu, &bank, moe, binding, sources.known, layer, &incoming)?; for (swap, spans) in group.iter().zip(spans) { let slot = cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?; cache.swap_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?; @@ -104,11 +112,8 @@ pub(super) fn queue_swaps<'ctx>( /// and a /// cycle is broken through one temporary expert. Returns the swaps made. pub(super) fn restore_placement<'ctx>( - binding: &ModelBinding, - moe: &MoeWeightCache<'ctx>, + sources: &mut SwapSources<'_, 'ctx, '_>, cache: &mut OriginalExpertCache<'ctx>, - cpu: &mut CpuExpertPool<'_>, - known: &mut SpanCache, initial: &[Option<(usize, usize)>], ) -> Result { let mut made = 0usize; @@ -116,7 +121,7 @@ pub(super) fn restore_placement<'ctx>( cache.wait_swaps().map_err(|e| driver_error(&e))?; let Some(swaps) = restore_round(cache, initial)? else { return Ok(made) }; made += swaps.len(); - queue_swaps(binding, moe, cache, cpu, known, &swaps)?; + queue_swaps(sources, cache, &swaps)?; } Err(Error::IdentityMismatch) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs index 0414b419..9fbceaa0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs @@ -5,13 +5,13 @@ use super::*; mod decode_parts; use decode_parts::{ - RefillOwners, assemble_decode, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, resolve_assembled, - return_owners, settle_deferred_refill, teardown_decode, + QsaOwnerHome, RefillOwners, TierResources, assemble_decode, decode_pcie_mode, gpu_expert_pool, + narrow_window_policy, resolve_assembled, return_owners, settle_deferred_refill, teardown_decode, }; mod open_parts; use open_parts::{ - Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor, open_expert_cache, - open_prefix, serve_policies, share_rt_dense_roles, + ExecutorOpening, Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor, + open_expert_cache, open_prefix, serve_policies, share_rt_dense_roles, }; mod serve_parts; use serve_parts::{ServeEnv, serve_over_host}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs index 31bee371..f660c59b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/decode_parts.rs @@ -9,6 +9,28 @@ use leleka_cuda_driver::{OriginalQsaMappedJournal, OriginalQsaResidentIndex}; type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48]; +/// The executor, binding, dense cache and session the physical QSA owners go back to when a decode phase ends. +pub(super) struct QsaOwnerHome<'a, 'ctx> { + pub(super) executor: &'a mut OriginalPromptExecutor<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) dense: &'a DenseWeightCache<'ctx>, + pub(super) session: &'a mut QwenSession<'ctx>, +} +impl<'ctx> QsaOwnerHome<'_, 'ctx> { + /// Hands the owners back to the executor at the session's lineage. + fn adopt(&mut self, owners: QsaOwners<'ctx>) -> Result<()> { + self.executor.adopt_qsa_owners(self.binding, self.dense, self.session, owners) + } +} + +/// The weight cache, VRAM expert cache, CPU pool and residency state the window's expert tier is built over. +pub(super) struct TierResources<'p, 'a, 'ctx> { + pub(super) moe: &'p MoeWeightCache<'ctx>, + pub(super) cache: &'p mut OriginalExpertCache<'ctx>, + pub(super) cpu: &'p mut CpuExpertPool<'a>, + pub(super) state: &'p mut ResidencyState, +} + /// generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. pub(super) fn decode_pcie_mode( config: &StackConfig, @@ -132,10 +154,7 @@ pub(super) fn return_owners<'a, 'ctx>( /// The assembly's outcome: the resources, or the failure with the owners given back (or the stack marked broken). pub(super) fn resolve_assembled<'a, 'ctx>( assembled: std::result::Result, AssembleFailure<'ctx>>, - executor: &mut OriginalPromptExecutor<'ctx>, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - session: &mut QwenSession<'ctx>, + mut home: QsaOwnerHome<'_, 'ctx>, broken: &mut Option, ) -> std::result::Result, SpecError> { let lost = match assembled { @@ -144,7 +163,7 @@ pub(super) fn resolve_assembled<'a, 'ctx>( }; operator_line("assemble", &lost.failure); if let Some(owners) = lost.owners { - if let Err(error) = executor.adopt_qsa_owners(binding, dense, session, owners) { + if let Err(error) = home.adopt(owners) { broken.get_or_insert(error); } } else { @@ -182,12 +201,10 @@ pub(super) fn narrow_window_policy( /// The window's expert tier over the VRAM cache: the GPU share first, the CPU pool on the rest. pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>( binding: &'a ModelBinding, - moe: &'p MoeWeightCache<'ctx>, - cache: &'p mut OriginalExpertCache<'ctx>, - cpu: &'p mut CpuExpertPool<'a>, - state: &'p mut ResidencyState, + resources: TierResources<'p, 'a, 'ctx>, tier: &ExpertTierConfig, ) -> Result> { + let TierResources { moe, cache, cpu, state } = resources; let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; let pcie_num = tier.pcie_num_for(bank.pageable()); let tail_rank = original_serve_residency::effective_tail_rank(&*cache); @@ -211,25 +228,21 @@ pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>( /// The end of the decode phase: release the MTP drafter's bindings to this verifier's bank, close the verifier and /// take the /// physical QSA owners back at the session's lineage (an abandoned window is rolled back there). -#[allow(clippy::too_many_arguments)] pub(super) fn teardown_decode<'a, 'ctx>( resources: DecodeResources<'a, 'ctx>, outcome: Option, - executor: &mut OriginalPromptExecutor<'ctx>, - binding: &ModelBinding, + mut home: QsaOwnerHome<'_, 'ctx>, context: &'ctx Context<'ctx>, - dense: &DenseWeightCache<'ctx>, - session: &mut QwenSession<'ctx>, broken: &mut Option, ) { - release_mtp(executor, binding, broken); + release_mtp(&mut *home.executor, home.binding, broken); // the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a // request vram_note(context, "decode end before disassemble"); let p = profile::span("decode.disassemble"); let disassembled = disassemble(resources); drop(p); - adopt_disassembled(disassembled, (executor, binding, dense, session), broken); + adopt_disassembled(disassembled, home, broken); if outcome.is_some_and(|o| o.failed) { broken.get_or_insert(Error::IdentityMismatch); } @@ -250,14 +263,13 @@ fn release_mtp(executor: &mut OriginalPromptExecutor<'_>, binding: &ModelBinding /// The owners the disassembly gave back return to the executor; a lost one marks the stack broken. fn adopt_disassembled<'ctx>( disassembled: std::result::Result, ServeFailure>, - host: (&mut OriginalPromptExecutor<'ctx>, &ModelBinding, &DenseWeightCache<'ctx>, &mut QwenSession<'ctx>), + mut home: QsaOwnerHome<'_, 'ctx>, broken: &mut Option, ) { - let (executor, binding, dense, session) = host; match disassembled { Ok(owners) => { let _p = profile::span("decode.adopt"); - if let Err(error) = executor.adopt_qsa_owners(binding, dense, session, owners) { + if let Err(error) = home.adopt(owners) { broken.get_or_insert(error); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2/open_phases.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2/open_phases.rs index 616fc1d1..53e4a371 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2/open_phases.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2/open_phases.rs @@ -58,7 +58,8 @@ pub(super) fn load_core<'a, 'ctx>( let weights = load_weights(binding, context, config, ctx.layout)?; let mut session = QwenSession::for_binding_on_shared_device(binding, shared); let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); - let opened = open_executor(binding, context, config, &weights, &mut session, verifier.0, verifier.1)?; + let opening = ExecutorOpening::new(config, verifier.0, verifier.1); + let opened = open_executor(binding, context, &opening, &weights, &mut session)?; let (executor, draft) = opened; let Weights { output, embedding, kar, dense, mut moe } = weights; share_rt_dense_roles(config, &executor, &mut moe)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs index 42de9492..eae4bd08 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs @@ -281,14 +281,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { self.tier.residency.clear_usage(); self.policy.controller = self.policy.settings.controller()?; match self.expert_cache.as_mut() { - Some(cache) => original_serve_seed::restore_placement( - self.binding, - &self.moe, - cache, - &mut self.pool, - &mut self.tier.residency.spans, - &self.tier.initial_owners, - ), + Some(cache) => { + let mut sources = original_serve_seed::SwapSources { + binding: self.binding, + moe: &self.moe, + cpu: &mut self.pool, + known: &mut self.tier.residency.spans, + }; + original_serve_seed::restore_placement(&mut sources, cache, &self.tier.initial_owners) + } None => Ok(0), } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs index 3ade0590..2f88ee78 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs @@ -111,16 +111,13 @@ impl<'s, 'a, 'ctx> DecodeView<'s, 'a, 'ctx> { dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" } ); - let executor = &mut *self.owners.executor; - let session = &mut *self.owners.session; - let resources = resolve_assembled( - assembled, - executor, - self.ids.binding, - self.reads.dense, - session, - &mut *self.book.broken, - )?; + let home = QsaOwnerHome { + executor: &mut *self.owners.executor, + binding: self.ids.binding, + dense: self.reads.dense, + session: &mut *self.owners.session, + }; + let resources = resolve_assembled(assembled, home, &mut *self.book.broken)?; self.narrow(resources, used_max_t) } @@ -180,9 +177,13 @@ impl<'s, 'a, 'ctx> DecodeView<'s, 'a, 'ctx> { let channels = (&mut emit, &mut cancel); let (served, verifier, outcome) = serve_over_host(verifier, host, request, channels, env)?; let resources = DecodeResources { verifier, qsa, slots }; - let (executor, session) = (&mut *self.owners.executor, &mut *self.owners.session); - let (binding, context, dense) = (self.ids.binding, self.ids.context, self.reads.dense); - teardown_decode(resources, outcome, executor, binding, context, dense, session, &mut *self.book.broken); + let home = QsaOwnerHome { + executor: &mut *self.owners.executor, + binding: self.ids.binding, + dense: self.reads.dense, + session: &mut *self.owners.session, + }; + teardown_decode(resources, outcome, home, self.ids.context, &mut *self.book.broken); served } } @@ -206,7 +207,7 @@ fn expert_pool<'q, 'p: 'q, 'a, 'ctx>( Some(cache) => { let tier_config = &policy.config.expert_tier; let (cpu, state) = (&mut *tier.pool, &mut *tier.residency); - let pool = gpu_expert_pool(ids.binding, reads.moe, cache, cpu, state, tier_config); + let pool = gpu_expert_pool(ids.binding, TierResources { moe: reads.moe, cache, cpu, state }, tier_config); Ok(slot.insert(pool.map_err(SpecError::Forward)?)) } None => Ok(&mut *tier.pool), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs index 6d18fe76..b63a7a61 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs @@ -105,14 +105,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let swaps = original_serve_seed::plan(counts, cache, max, keep); let planned = self.config.clock.since(started); let mut report = original_serve_seed::summarize(counts, &swaps); - original_serve_seed::queue_swaps( - self.binding, - &self.moe, - cache, - &mut self.pool, - &mut self.tier.residency.spans, - &swaps, - )?; + let mut sources = original_serve_seed::SwapSources { + binding: self.binding, + moe: &self.moe, + cpu: &mut self.pool, + known: &mut self.tier.residency.spans, + }; + original_serve_seed::queue_swaps(&mut sources, cache, &swaps)?; report.plan_ms = planned.as_secs_f64() * 1e3; report.queue_ms = (self.config.clock.since(started) - planned).as_secs_f64() * 1e3; self.tier.residency.add_usage(counts, usage); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs index 92afeeda..81d45f37 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs @@ -178,19 +178,31 @@ fn load_moe<'ctx>( Ok(moe) } +/// How the prompt executor and its MTP drafter are opened: the stack config, the verifier's widest window and the +/// drafter request derived from them. +pub(super) struct ExecutorOpening<'a> { + config: &'a StackConfig, + verifier_max_t: usize, + request: OriginalMtpRequest, +} +impl<'a> ExecutorOpening<'a> { + /// The opening for a verifier of window width `verifier_max_t`; `coupled` is whether the policy is coupled. + pub(super) fn new(config: &'a StackConfig, verifier_max_t: usize, coupled: bool) -> Self { + let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS); + Self { config, verifier_max_t, request } + } +} + /// The prompt executor with its MTP drafter: from the RT directory, or the full MTP owner over the pinned pack. -#[allow(clippy::too_many_arguments)] pub(super) fn open_executor<'a, 'ctx>( binding: &'a ModelBinding, context: &'ctx Context<'ctx>, - config: &StackConfig, + opening: &ExecutorOpening<'_>, weights: &Weights<'ctx>, session: &mut QwenSession<'ctx>, - verifier_max_t: usize, - coupled: bool, ) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> { let Weights { output, embedding, dense, .. } = weights; - let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS); + let (config, request) = (opening.config, &opening.request); Ok(match &config.rt_directory { Some(directory) => OriginalPromptExecutor::select_rt_mtp( binding, @@ -202,12 +214,10 @@ pub(super) fn open_executor<'a, 'ctx>( directory, config.capacity, true, - &request, + request, ) .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, - None => { - open_full_mtp_executor(binding, context, session, weights, (config.capacity, verifier_max_t), &request)? - } + None => open_full_mtp_executor(binding, context, session, weights, opening)?, }) } @@ -217,11 +227,10 @@ fn open_full_mtp_executor<'a, 'ctx>( context: &'ctx Context<'ctx>, session: &mut QwenSession<'ctx>, weights: &Weights<'ctx>, - sizes: (usize, usize), - request: &OriginalMtpRequest, + opening: &ExecutorOpening<'_>, ) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> { let Weights { output, embedding, dense, moe, .. } = weights; - let (capacity, verifier_max_t) = sizes; + let (capacity, verifier_max_t, request) = (opening.config.capacity, opening.verifier_max_t, &opening.request); let mut executor = OriginalPromptExecutor::new(binding, dense, session, context, moe, embedding, capacity, verifier_max_t, true) .map_err(at("OriginalPromptExecutor::new"))?; From 1479858a56a85e583c4da2be5aeff3c3e427b8a8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:17 +0100 Subject: [PATCH 31/42] STRA-338 params e02: GR batch operations take GrBatchScope, micro attention block takes MicroBlockRequest Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/gdn_native.rs crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/plain_rows.rs crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs --- .../prepare_micro_ffn_rows_fn.rs | 2 +- .../prepare_micro_ffn_rows_fn/gdn_native.rs | 3 ++- .../prepare_micro_ffn_rows_fn/plain_rows.rs | 9 ++++--- .../prepare_micro_ffn_rows_fn/qsa_native.rs | 26 +++++++------------ .../engine-qwen35-cuda/src/qwen_forward/gr.rs | 2 +- .../src/qwen_forward/gr_batch_chunk.rs | 4 +++ .../gr_batch_chunk/gr_batch_operands.rs | 21 +++++++++++++++ .../gr_batch_chunk/impl_grmicroinput.rs | 10 +++---- .../gr_batch_chunk/impl_grstage.rs | 20 +++++--------- .../gr_batch_chunk/impl_grstage_2.rs | 2 +- .../gr_batch_chunk/inject_batch_fns.rs | 13 ++++------ .../src/qwen_forward/gr_retained_handoff.rs | 8 ++++-- 12 files changed, 67 insertions(+), 53 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/gr_batch_operands.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs index 7637e14b..c7830af4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs @@ -7,7 +7,7 @@ #[allow(unused_imports)] use super::*; use crate::qwen_forward::gdn::chunk_device::GdnChunkDevice; -use crate::qwen_forward::gr::{DetachedGrRead, GrMicroAttentionBank, GrMicroAttentionBlock}; +use crate::qwen_forward::gr::{DetachedGrRead, GrMicroAttentionBank, GrMicroAttentionBlock, MicroBlockRequest}; use crate::qwen_forward::moe_prefill_batch::MoeMicroProducts; use crate::qwen_forward::q6_attention_columns::ProjectionRow; use crate::qwen_forward::session::chunk::{ChunkAttentionRow, ChunkFfnRow, PreparedLayerRow}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/gdn_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/gdn_native.rs index 94932cf0..112ef3cc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/gdn_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/gdn_native.rs @@ -60,6 +60,7 @@ fn gdn_micro_block( result.validate_origin(&env.binding.identity())?; result.identity().validate(txn.token(), txn.position(), env.layer)?; let (output, identity) = (result.output(), result.identity()); - let block = GrStage::prepare_micro_attention_block(env.binding, bank, local, read, output, identity, txn)?; + let request = MicroBlockRequest { index: local, read, block: output, identity }; + let block = GrStage::prepare_micro_attention_block(env.binding, bank, request, txn)?; Ok((block, result.into_edge())) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/plain_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/plain_rows.rs index 0b051dbc..f6605111 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/plain_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/plain_rows.rs @@ -61,7 +61,8 @@ fn device_gdn_block<'ctx>( result.validate_origin(&binding.identity())?; result.identity().validate(token, position, layer)?; let (output, identity) = (result.output(), result.identity()); - let block = GrStage::prepare_micro_attention_block(binding, bank, local, read, output, identity, txn)?; + let request = MicroBlockRequest { index: local, read, block: output, identity }; + let block = GrStage::prepare_micro_attention_block(binding, bank, request, txn)?; Ok((block, result.into_edge())) } @@ -78,11 +79,13 @@ fn host_block<'ctx>( BoundLayerKind::Gdn => { let result = QwenForward::gdn_host_attention((binding, cache), layer, ids, (txn, read), projection.first_mut())?; - GrStage::prepare_micro_attention_block(binding, bank, local, read, result.output(), result.identity(), txn) + let request = MicroBlockRequest { index: local, read, block: result.output(), identity: result.identity() }; + GrStage::prepare_micro_attention_block(binding, bank, request, txn) } BoundLayerKind::Qsa => { let result = QwenForward::qsa_host_attention((binding, cache), layer, ids, (txn, read), projection)?; - GrStage::prepare_micro_attention_block(binding, bank, local, read, result.output(), result.identity(), txn) + let request = MicroBlockRequest { index: local, read, block: result.output(), identity: result.identity() }; + GrStage::prepare_micro_attention_block(binding, bank, request, txn) } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs index a42d7485..18ecf4a1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn/qsa_native.rs @@ -3,12 +3,13 @@ #[allow(unused_imports)] use super::*; use crate::qwen_forward::gr::ResidualReady; +use crate::qwen_forward::prompt_device_rows::PromptWeights; use crate::qwen_forward::qsa_attention::QsaReady; use crate::qwen_forward::qsa_attention::{ NativeAttended, NativePromptAttentionBatch, NativePromptAttentionBatch as Batch, }; use crate::qwen_forward::qsa_native_resources::NativeQsaResources; -use crate::qwen_forward::qsa_prefill_batch::NativeProjectionRow; +use crate::qwen_forward::qsa_prefill_batch::{AttendedRows, NativeProjectionRow, NativeQsaDevices}; use crate::qwen_forward::qsa_prompt_index; use leleka_cuda_driver::{QsaPromptAttention, QsaPromptIndexWorkspace, QsaPromptKv, QsaPromptStage}; @@ -51,14 +52,13 @@ fn qsa_native_project<'source, 'ctx>( let (binding, cache) = (env.binding, env.cache); let mut owner = cache.qsa_native_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; + let devices = NativeQsaDevices { owner: &mut owner, workspace: &mut workspace }; crate::qwen_forward::qsa_prefill_batch::project( - binding, - cache, + PromptWeights::new(binding, cache), chunk, env.layer, inputs, - &mut owner, - &mut workspace, + devices, ) } @@ -140,16 +140,9 @@ fn qsa_native_project_out<'ctx>( let mut owner = cache.qsa_native_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; let layer = env.layer; - crate::qwen_forward::qsa_prefill_batch::project_out( - binding, - cache, - chunk, - layer, - attended, - proofs, - &mut owner, - &mut workspace, - ) + let devices = NativeQsaDevices { owner: &mut owner, workspace: &mut workspace }; + let rows = AttendedRows { rows: attended, proofs }; + crate::qwen_forward::qsa_prefill_batch::project_out(PromptWeights::new(binding, cache), chunk, layer, rows, devices) } /// One attention block per row from the projected-out QSA results. @@ -169,7 +162,8 @@ fn qsa_native_output_blocks<'ctx>( result.validate_origin(&env.binding.identity(), env.layer)?; result.identity().validate(txn.token(), txn.position(), env.layer)?; let (output, identity) = (result.output(), result.identity()); - GrStage::prepare_micro_attention_block(env.binding, bank, local, read, output, identity, txn) + let request = MicroBlockRequest { index: local, read, block: output, identity }; + GrStage::prepare_micro_attention_block(env.binding, bank, request, txn) })?; micro.blocks.push(block); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs index 7e267cae..0fe7f78f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs @@ -97,7 +97,7 @@ mod batch_chunk; pub(in crate::qwen_forward) use batch_chunk::GrBatchRow; pub(in crate::qwen_forward) use batch_chunk::GrMicroAttentionBlock as GrMicroBlock; pub(in crate::qwen_forward) use batch_chunk::{ - GrMicroAttention, GrMicroAttentionBank, GrMicroAttentionBlock, GrMicroInput, + GrMicroAttention, GrMicroAttentionBank, GrMicroAttentionBlock, GrMicroInput, MicroBlockRequest, }; #[path = "gr_attention_chunk.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs index fad74e6b..16afb4c5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs @@ -1,5 +1,9 @@ //! Closed prepared producer for the actual chunk FFN injection. use super::*; +#[path = "gr_batch_chunk/gr_batch_operands.rs"] +mod gr_batch_operands; +pub(in crate::qwen_forward) use gr_batch_operands::{GrBatchScope, MicroBlockRequest}; + /// An immutable current-row input minted only by one of the three original /// producer paths, within the caller's authentic chunk phase fence. pub(in crate::qwen_forward) struct GrMicroInput { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/gr_batch_operands.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/gr_batch_operands.rs new file mode 100644 index 00000000..36af237e --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/gr_batch_operands.rs @@ -0,0 +1,21 @@ +//! The operand groups of the GR batch and micro-window operations. +use super::*; + +/// The model binding, the dense weight cache and the device context one GR batch operation is valid in; they +/// always travel together. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct GrBatchScope<'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, +} + +/// One micro-bank row whose attention block is prepared for publication: the row index, its detached read, the +/// computed block and the token-layer identity the block must carry. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct MicroBlockRequest<'a> { + pub(in crate::qwen_forward) index: usize, + pub(in crate::qwen_forward) read: &'a DetachedGrRead, + pub(in crate::qwen_forward) block: &'a [f32], + pub(in crate::qwen_forward) identity: TokenLayer, +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs index 3cff3389..8231fe8f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs @@ -39,12 +39,11 @@ impl<'ctx> GrMicroDevice<'ctx> { } pub(in super::super) fn read_native( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - context: &Context<'_>, + scope: GrBatchScope<'_, 'ctx>, weights: [&DeviceBuffer<'_>; 4], epsilon: f32, ) -> Result { + let GrBatchScope { binding, cache, context } = scope; let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; match self { Self::Native(owner) => owner.read(weights, epsilon, &mut workspace).map_err(micro_driver_error), @@ -53,11 +52,10 @@ impl<'ctx> GrMicroDevice<'ctx> { } pub(in super::super) fn inject_native( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - context: &Context<'_>, + scope: GrBatchScope<'_, 'ctx>, blocks: &[f32], ) -> Result> { + let GrBatchScope { binding, cache, context } = scope; let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; match self { Self::Native(owner) => owner.inject(blocks, &mut workspace).map_err(micro_driver_error), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs index 7ac18c73..3cf4e09a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs @@ -94,7 +94,7 @@ impl GrStage { let mut device = GrMicroDevice::Legacy( context.gr_microbatch_read(inputs.len(), &batch.streams).map_err(micro_driver_error)?, ); - let env = MicroEnv { binding, cache, context }; + let env = GrBatchScope { binding, cache, context }; let result = (|| { let weights = ready_micro_weights(weights)?; let values = device.read(weights, resident.weights.epsilon()).map_err(micro_driver_error)?; @@ -114,10 +114,10 @@ impl GrStage { let batch = collect_micro_batch(binding, &inputs)?; let (resident, weights) = micro_weights(cache, binding, batch.role)?; let mut device = open_native_micro_device(binding, cache, context, inputs.len(), &batch.streams)?; - let env = MicroEnv { binding, cache, context }; + let env = GrBatchScope { binding, cache, context }; let result = (|| { let weights = ready_micro_weights(weights)?; - let values = device.read_native(binding, cache, context, weights, resident.weights.epsilon())?; + let values = device.read_native(env, weights, resident.weights.epsilon())?; env.detach_rows(inputs, &values, &failed) })(); env.seal(batch, device, failed, result) @@ -125,12 +125,10 @@ impl GrStage { pub(in crate::qwen_forward) fn prepare_micro_attention_block( binding: &ModelBinding, bank: &GrMicroAttentionBank<'_>, - index: usize, - read: &DetachedGrRead, - block: &[f32], - identity: TokenLayer, + request: MicroBlockRequest<'_>, txn: &mut QwenStepTxn, ) -> Result { + let MicroBlockRequest { index, read, block, identity } = request; read.retained_handoff_available()?; txn.validate_binding(&binding.identity())?; check_micro_bank(bank, binding, txn)?; @@ -246,13 +244,7 @@ fn open_native_micro_device<'ctx>( .map_err(micro_driver_error)?, )) } -// What the micro read needs besides the device owner. -struct MicroEnv<'a, 'ctx> { - binding: &'a ModelBinding, - cache: &'a DenseWeightCache<'ctx>, - context: &'ctx Context<'ctx>, -} -impl<'a, 'ctx> MicroEnv<'a, 'ctx> { +impl<'a, 'ctx> GrBatchScope<'a, 'ctx> { fn detach_rows( &self, inputs: Vec, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs index bd139bb5..b5d66de1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs @@ -68,7 +68,7 @@ impl GrStage { if let Some(values) = queued_inject(binding, context, cache, &failed, &operands)? { return finish_queued(binding, context, cache, rows, values); } - device_inject(binding, context, cache, &failed, rows, &operands) + device_inject(GrBatchScope { binding, cache, context }, &failed, rows, &operands) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs index d33154d1..8801efd0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs @@ -124,17 +124,15 @@ pub(super) fn finish_queued( /// The generic device path: upload, inject, download and release every owner whatever the outcome. pub(super) fn device_inject<'c>( - binding: &ModelBinding, - context: &'c Context<'c>, - cache: &DenseWeightCache<'_>, + scope: GrBatchScope<'_, 'c>, failed: &Cell, rows: Vec, operands: &BatchOperands, ) -> Result> { - admit_budget(context, rows.len() * (2 * 40960 + 10240 + 16))?; + admit_budget(scope.context, rows.len() * (2 * 40960 + 10240 + 16))?; let (mut residual, mut output, mut injection, mut candidate) = (None, None, None, None); let mut owners = [&mut residual, &mut output, &mut injection, &mut candidate]; - let result = inject_on_device(binding, context, cache, rows, operands, &mut owners); + let result = inject_on_device(scope, rows, operands, &mut owners); // Attempt every owned release even after a CUDA or finite refusal. let mut cleanup = Ok(()); for buffer in [candidate, injection, output, residual].into_iter().flatten() { @@ -152,13 +150,12 @@ pub(super) fn device_inject<'c>( type Owners<'a, 'c> = [&'a mut Option>; 4]; fn inject_on_device<'c>( - binding: &ModelBinding, - context: &'c Context<'c>, - cache: &DenseWeightCache<'_>, + scope: GrBatchScope<'_, 'c>, rows: Vec, operands: &BatchOperands, owners: &mut Owners<'_, 'c>, ) -> Result> { + let GrBatchScope { binding, cache, context } = scope; let [residual, output, injection, candidate] = owners; **residual = Some(upload_f32(context, &operands.streams)?); **output = Some(upload_f32(context, &operands.blocks)?); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs index 9f71df2c..fcfa5599 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs @@ -84,6 +84,10 @@ struct FfnInjection<'a, 'ctx> { failed: &'a Rc>, } impl<'a, 'ctx> FfnInjection<'a, 'ctx> { + /// The binding, dense cache and context this injection runs in. + fn scope(&self) -> batch_chunk::GrBatchScope<'a, 'ctx> { + batch_chunk::GrBatchScope { binding: self.binding, cache: self.cache, context: self.context } + } fn inject_and_read( &self, device: &mut batch_chunk::GrMicroDevice<'ctx>, @@ -101,7 +105,7 @@ impl<'a, 'ctx> FfnInjection<'a, 'ctx> { } fn inject_streams(&self, device: &mut batch_chunk::GrMicroDevice<'ctx>, values: &[f32]) -> Result> { if matches!(&*device, batch_chunk::GrMicroDevice::Native(_)) { - device.inject_native(self.binding, self.cache, self.context, values) + device.inject_native(self.scope(), values) } else { device.inject(values).map_err(batch_chunk::micro_driver_error) } @@ -113,7 +117,7 @@ impl<'a, 'ctx> FfnInjection<'a, 'ctx> { epsilon: f32, ) -> Result { if matches!(&*device, batch_chunk::GrMicroDevice::Native(_)) { - device.read_native(self.binding, self.cache, self.context, [gamma?, down?, up?, inject?], epsilon) + device.read_native(self.scope(), [gamma?, down?, up?, inject?], epsilon) } else { device.read([gamma?, down?, up?, inject?], epsilon).map_err(batch_chunk::micro_driver_error) } From b4a54171e02e321a87b74471f4e0dd674537ab7c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:17 +0100 Subject: [PATCH 32/42] STRA-338 params e02: resident MMQ layer takes Resident/LayerResources/RoutedGroups, layer-0 arm takes Layer0Rows --- .../src/qwen_forward/moe_layer0_pair.rs | 14 +- .../src/qwen_forward/moe_mmq_adaptive.rs | 47 ++--- .../src/qwen_forward/moe_mmq_chunk.rs | 9 +- .../moe_mmq_chunk/resident_fns.rs | 173 ++++++++++-------- 4 files changed, 122 insertions(+), 121 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs index 8db1b6d9..0650fce1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs @@ -61,15 +61,21 @@ fn witness_delta(before: (u64, u64, u64), after: (u64, u64, u64)) -> Result<[u64 after.2.checked_sub(before.2).ok_or(Error::Overflow)?, ]) } +/// The layer-0 FFN rows of a chunk with the binding and layer they belong to. +#[derive(Clone, Copy)] +struct Layer0Rows<'a> { + binding: &'a ModelBinding, + layer: LayerId, + rows: &'a [ChunkFfnRow], +} impl MoeExpertStage { fn test_layer0_arm<'ctx>( - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + layer0: Layer0Rows<'_>, chunk: &mut QwenChunkTxn<'_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, arm: usize, ) -> Result<()> { + let Layer0Rows { binding, layer, rows } = layer0; let _arm = observation::arm(arm)?; let products = if arm == 0 { Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)? @@ -93,7 +99,7 @@ impl MoeExpertStage { observation::cache(0, counters(cache))?; let before = cache.test_mmq_dispatch_witness(); for arm in 0..2 { - Self::test_layer0_arm(binding, layer, rows, chunk, cache, arm)?; + Self::test_layer0_arm(Layer0Rows { binding, layer, rows }, chunk, cache, arm)?; } observation::complete(witness_delta(before, cache.test_mmq_dispatch_witness())?) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs index 180f5e8f..c1c0d9b9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs @@ -9,32 +9,26 @@ use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer}; mod gather_fns; #[path = "moe_mmq_adaptive/walk_fns.rs"] mod walk_fns; +use super::resident_fns::{LayerResources, Resident, RoutedGroups}; use walk_fns::{SlotState, Walk}; -#[allow(clippy::too_many_arguments)] pub(super) fn execute_adaptive_groups<'ctx>( - txn: &QwenChunkTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], - groups: &[Vec], - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, - inputs: &[f32], + resident: &Resident<'_, '_, 'ctx>, + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, + routed: RoutedGroups<'_>, packets: &mut SlotPacks<'_, '_, 'ctx>, - cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { - cache.validate(binding, context)?; - check_adaptive_request(txn, cache, workspace, rows, groups)?; - let ephemeral = cache.ephemeral_routed_owner(binding, context)?; - let operation = - execute_inner(txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled); + let Resident { txn, context, binding, layer, rows } = *resident; + resources.cache.validate(binding, context)?; + check_adaptive_request(txn, resources.cache, resources.workspace, rows, routed.groups)?; + let ephemeral = resources.cache.ephemeral_routed_owner(binding, context)?; + let walk = Walk { txn, context, binding, layer, rows, groups: routed.groups }; + let operation = execute_inner(&walk, resources, routed.inputs, packets); // Even an identity, numeric, copy, or cancellation refusal drains all real // pending events. Healthy idle allocations remain owned for the next layer. let cleanup = ephemeral.try_borrow_mut().map_err(|_| Error::IdentityMismatch).and_then(|mut owner| owner.drain()); if context.is_poisoned() || matches!(&cleanup, Err(Error::CudaExecution)) { - cache.note_transport_failure(); + resources.cache.note_transport_failure(); } operation.and(cleanup) } @@ -70,24 +64,17 @@ fn check_adaptive_rows( Ok(()) } -#[allow(clippy::too_many_arguments)] fn execute_inner<'ctx>( - txn: &QwenChunkTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], - groups: &[Vec], - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, + walk: &Walk<'_, '_, 'ctx>, + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, inputs: &[f32], packets: &mut SlotPacks<'_, '_, 'ctx>, - cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { - let (counts, sorted_rows) = count_groups(rows, groups)?; - let walk = Walk { txn, context, binding, layer, rows, groups }; + let (cache, workspace) = (&mut *resources.cache, &mut *resources.workspace); + let cancelled = &mut *resources.cancelled; + let (counts, sorted_rows) = count_groups(walk.rows, walk.groups)?; walk.authenticate(packets)?; - let tokens = u32::try_from(rows.len()).map_err(|_| Error::Overflow)?; + let tokens = u32::try_from(walk.rows.len()).map_err(|_| Error::Overflow)?; let mut source = workspace.prepare_original_expert_layer(inputs, tokens, &counts, &sorted_rows).map_err(mmq_error)?; walk.observe_rows(cache)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index 78c8313f..1ccbf8ec 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -11,7 +11,7 @@ mod original_adaptive; #[path = "moe_mmq_chunk/resident_fns.rs"] mod resident_fns; use admission_fns::{mmq_triplets, rows_supported}; -use resident_fns::execute_resident; +use resident_fns::{Resident, execute_resident}; impl MoeExpertStage { pub(in crate::qwen_forward) fn execute_chunk_mmq<'ctx>( @@ -191,12 +191,9 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> { workspace: &mut MmqWorkspace<'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { + let resident = Resident { txn: actual, context, binding: self.binding, layer: self.layer, rows: self.rows }; execute_resident( - actual, - context, - self.binding, - self.layer, - self.rows, + resident, cache, workspace, cancelled, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs index 6f3beaef..a6de1ad9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs @@ -5,21 +5,56 @@ use super::*; use leleka_cuda_driver::MmqChunkActivation; /// The sealed rows of one resident MMQ layer batch. -struct Resident<'a, 't, 'ctx> { - txn: &'a QwenChunkTxn<'t, 'ctx>, - context: &'ctx Context<'ctx>, - binding: &'a ModelBinding, - layer: LayerId, - rows: &'a [ChunkFfnRow], +pub(super) struct Resident<'a, 't, 'ctx> { + pub(super) txn: &'a QwenChunkTxn<'t, 'ctx>, + pub(super) context: &'ctx Context<'ctx>, + pub(super) binding: &'a ModelBinding, + pub(super) layer: LayerId, + pub(super) rows: &'a [ChunkFfnRow], +} + +/// The expert cache, the MMQ workspace and the cancellation poll that one resident layer runs on. +pub(super) struct LayerResources<'a, 'ctx, C> { + pub(super) cache: &'a mut MoeWeightCache<'ctx>, + pub(super) workspace: &'a mut MmqWorkspace<'ctx>, + pub(super) cancelled: &'a mut C, +} + +/// The expert cache and the cancellation poll that every projection of a layer mutates. +struct LayerState<'a, 'ctx, C> { + cache: &'a mut MoeWeightCache<'ctx>, + cancelled: &'a mut C, +} + +/// The routed expert groups of a layer and the shared activations their gate/up projections read. +#[derive(Clone, Copy)] +pub(super) struct RoutedGroups<'a> { + pub(super) groups: &'a [Vec], + pub(super) inputs: &'a [f32], +} + +/// One expert whose gate/up/down projection runs: its routed pairs and whether the Original prompt MMQ layout +/// applies. +#[derive(Clone, Copy)] +struct ExpertProjection<'p> { + expert: usize, + pairs: &'p [Pair], + original_prompt: bool, +} + +/// How the rows of a layer are finished: the shared activations uploaded through the down scope and, on the +/// native prompt path, the native prompt finish. +struct LayerFinish<'a, 'ctx, 'dense> { + scope: &'a DownScope<'ctx>, + activations: &'a mut Vec>, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native: Option>, + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + marker: std::marker::PhantomData<&'dense ()>, } -#[allow(clippy::too_many_arguments)] pub(super) fn execute_resident<'ctx>( - txn: &QwenChunkTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, - binding: &ModelBinding, - layer: LayerId, - rows: &[ChunkFfnRow], + resident: Resident<'_, '_, 'ctx>, cache: &mut MoeWeightCache<'ctx>, workspace: &mut MmqWorkspace<'ctx>, cancelled: &mut impl FnMut() -> bool, @@ -30,7 +65,6 @@ pub(super) fn execute_resident<'ctx>( #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); - let resident = Resident { txn, context, binding, layer, rows }; resident.execute( cache, workspace, @@ -59,11 +93,10 @@ impl<'ctx> Resident<'_, '_, 'ctx> { self.admit(cache)?; let failed = Rc::new(Cell::new(false)); let scope = DownScope::new(self.context, Rc::clone(&failed)); + let mut resources = LayerResources { cache, workspace, cancelled }; let result = self.run( &scope, - cache, - workspace, - cancelled, + &mut resources, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native, ); @@ -71,7 +104,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> { // numerical body. Drop cleanup may set the shared flag while preserving a // non-transport primary; never lose that uncertain-free cache fence. if failed.get() || self.context.is_poisoned() { - cache.note_transport_failure(); + resources.cache.note_transport_failure(); } result } @@ -149,9 +182,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> { fn run( &self, scope: &DownScope<'ctx>, - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, - cancelled: &mut impl FnMut() -> bool, + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, >, @@ -160,18 +191,16 @@ impl<'ctx> Resident<'_, '_, 'ctx> { let groups = grouped_pairs(&ids)?; let mut packets = SlotPacks::new(self.txn, self.binding, self.layer, self.rows, self.context, scope)?; let mut activations = reserved(self.rows.len())?; - let operation = self.operate( + let finish = LayerFinish { scope, - cache, - workspace, - cancelled, - &groups, - &inputs, - &mut packets, - &mut activations, + activations: &mut activations, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native, - ); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + marker: std::marker::PhantomData, + }; + let operation = + self.operate(resources, RoutedGroups { groups: &groups, inputs: &inputs }, &mut packets, finish); scope.record(&operation); let cleanup = close_resident(packets, activations); operation.and_then(|values| cleanup.map(|()| values)) @@ -188,73 +217,63 @@ impl<'ctx> Resident<'_, '_, 'ctx> { Ok((inputs, ids)) } - #[allow(clippy::too_many_arguments)] fn operate( &self, - scope: &DownScope<'ctx>, - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, - cancelled: &mut impl FnMut() -> bool, - groups: &[Vec], - inputs: &[f32], + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, + routed: RoutedGroups<'_>, packets: &mut SlotPacks<'_, '_, 'ctx>, - activations: &mut Vec>, - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option< - super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - >, + mut finish: LayerFinish<'_, 'ctx, '_>, ) -> Result> { - if cancelled() { + if (resources.cancelled)() { return Err(Error::Unsupported(Stage::Executor)); } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let original_prompt = native.is_some() && cache.has_original_prompt_mmq(); + let original_prompt = finish.native.is_some() && resources.cache.has_original_prompt_mmq(); #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let original_prompt = false; - self.project_all(cache, workspace, cancelled, original_prompt, groups, inputs, packets)?; + self.project_all(resources, routed, packets, original_prompt)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(finish) = native.as_mut() { - return packets.finish_native_micro(cache, finish, cancelled); + if let Some(native) = finish.native.as_mut() { + return packets.finish_native_micro(resources.cache, native, resources.cancelled); } - self.finish_rows(scope, cache, cancelled, packets, activations) + self.finish_rows(resources, packets, &mut finish) } /// Shared expert is unchanged native math. Its existing private scalar staging is retained, not advertised as /// device-resident. fn finish_rows( &self, - scope: &DownScope<'ctx>, - cache: &mut MoeWeightCache<'ctx>, - cancelled: &mut impl FnMut() -> bool, + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, packets: &SlotPacks<'_, '_, 'ctx>, - activations: &mut Vec>, + finish: &mut LayerFinish<'_, 'ctx, '_>, ) -> Result> { + let (cache, cancelled) = (&mut *resources.cache, &mut *resources.cancelled); let mut outputs = reserved(self.rows.len())?; for (index, row) in self.rows.iter().enumerate() { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - activations.push(scope.upload(row.row().read.ready().mixed())?); - let activation = activations.last().ok_or(Error::IdentityMismatch)?.buffer()?; + finish.activations.push(finish.scope.upload(row.row().read.ready().mixed())?); + let activation = finish.activations.last().ok_or(Error::IdentityMismatch)?.buffer()?; outputs.push(packets.finish_row(index, activation, cache, cancelled)?); } Ok(outputs) } - #[allow(clippy::too_many_arguments)] fn project_all( &self, - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, - cancelled: &mut impl FnMut() -> bool, - original_prompt: bool, - groups: &[Vec], - inputs: &[f32], + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, + routed: RoutedGroups<'_>, packets: &mut SlotPacks<'_, '_, 'ctx>, + original_prompt: bool, ) -> Result<()> { let tokens = u32::try_from(self.rows.len()).map_err(|_| Error::Overflow)?; - if self.project_adaptive(cache, workspace, cancelled, original_prompt, groups, inputs, packets)? { + if self.project_adaptive(resources, routed, packets, original_prompt)? { return Ok(()); } + let RoutedGroups { groups, inputs } = routed; + let workspace = &mut *resources.workspace; + let mut state = LayerState { cache: &mut *resources.cache, cancelled: &mut *resources.cancelled }; let mut source = if original_prompt { workspace.prepare_original_gate_up_chunk(inputs, tokens) } else { @@ -262,51 +281,43 @@ impl<'ctx> Resident<'_, '_, 'ctx> { } .map_err(mmq_error)?; for (expert, pairs) in groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty()) { - if cancelled() { + if (state.cancelled)() { return Err(Error::Unsupported(Stage::Executor)); } // finite group lease has expired after each call; the same workspace is reused. - self.project_expert(cache, cancelled, original_prompt, &mut source, expert, pairs, packets)?; + let projection = ExpertProjection { expert, pairs, original_prompt }; + self.project_expert(&mut state, &mut source, projection, packets)?; } Ok(()) } /// The Strata adaptive producer handles the whole layer when selected; `true` means it did. - #[allow(clippy::too_many_arguments)] fn project_adaptive( &self, - cache: &mut MoeWeightCache<'ctx>, - workspace: &mut MmqWorkspace<'ctx>, - cancelled: &mut impl FnMut() -> bool, - original_prompt: bool, - groups: &[Vec], - inputs: &[f32], + resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>, + routed: RoutedGroups<'_>, packets: &mut SlotPacks<'_, '_, 'ctx>, + original_prompt: bool, ) -> Result { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if original_prompt && cache.uses_strata_adaptive_experts() { - let (txn, context, binding, layer, rows) = (self.txn, self.context, self.binding, self.layer, self.rows); - super::original_adaptive::execute_adaptive_groups( - txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled, - )?; + if original_prompt && resources.cache.uses_strata_adaptive_experts() { + super::original_adaptive::execute_adaptive_groups(self, resources, routed, packets)?; return Ok(true); } #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let _ = (cache, workspace, cancelled, original_prompt, groups, inputs, packets); + let _ = (resources, routed, packets, original_prompt); Ok(false) } - #[allow(clippy::too_many_arguments)] fn project_expert( &self, - cache: &mut MoeWeightCache<'ctx>, - cancelled: &mut impl FnMut() -> bool, - original_prompt: bool, + state: &mut LayerState<'_, 'ctx, impl FnMut() -> bool>, source: &mut MmqChunkActivation<'_, 'ctx>, - expert: usize, - pairs: &[Pair], + projection: ExpertProjection<'_>, packets: &mut SlotPacks<'_, '_, 'ctx>, ) -> Result<()> { + let ExpertProjection { expert, pairs, original_prompt } = projection; + let (cache, cancelled) = (&mut *state.cache, &mut *state.cancelled); let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; let (first, row) = self.group_head(pairs)?; let indices = self.group_indices(row, first, pairs)?; From 8a654aedb2a02aab0cb287f4500880ae12f6d363 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:17 +0100 Subject: [PATCH 33/42] STRA-338 params e02: MTP expert compose takes Bound/MtpRoutingScope, MTP KV mirror takes MtpKvClaim --- .../src/qwen_forward/moe_weight_cache.rs | 2 +- .../impl_moeweightcache_4.rs | 7 +++++-- .../qwen_forward/mtp_experts/impl_mtpblock.rs | 15 ++++++-------- .../src/qwen_forward/mtp_experts/route_fn.rs | 20 ++++++++++++------- .../src/qwen_forward/mtp_kv_resident.rs | 18 ++++++++--------- 5 files changed, 34 insertions(+), 28 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index 2a25b9a8..ffefd98a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -12,7 +12,7 @@ use leleka_cuda_driver::{ use std::cell::{Cell, RefCell}; #[path = "mtp_kv_resident.rs"] mod mtp_kv_resident; -use mtp_kv_resident::MtpKvResident; +use mtp_kv_resident::{MtpKvClaim, MtpKvResident}; #[path = "cache_lru_index.rs"] mod cache_lru_index; use cache_lru_index::{LruIndex, PreparedUpdates}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs index 57c21d7f..06e453d7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs @@ -145,8 +145,11 @@ impl<'ctx> MoeWeightCache<'ctx> { ) -> Result<()> { self.validate(binding, context)?; let mut slot = self.mtp_kv.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - let result = - slot.as_mut().ok_or(Error::IdentityMismatch)?.prepare(binding, context, &self.mmq_owner, next, frame); + let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.prepare( + MtpKvClaim { binding, context, owner: &self.mmq_owner }, + next, + frame, + ); if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs index 30b4f77a..d36ea296 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs @@ -45,7 +45,8 @@ impl MtpExpertStage { let context = session.mtp_context()?; preflight(context, DEVICE_PEAK)?; let (ids, weights) = route_mixed(context, binding, input, cache)?; - let output = compose_bound(context, binding, input, session, ids, weights, cache, Rc::clone(failed))?; + let call = Bound { context, binding, session, cache }; + let output = compose_bound(call, input, ids, weights, Rc::clone(failed))?; validate_values(&output, N)?; input.frame().validate(binding, session)?; Ok(MtpBlock { frame: input.frame().clone(), output }) @@ -109,12 +110,12 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> { } pub(super) fn compose( &self, - frame: &MtpFrame, input: &MtpMlpReady, weights: BoundWeights<'_, '_>, picks: ([u32; K], [f32; K]), failed: Rc>, ) -> Result> { + let frame = input.frame(); let (ids, route_weights) = picks; let BoundWeights { bank, shared } = weights; if self.cache.requires_iq3_mmq_admission() { @@ -138,23 +139,19 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> { } } } -#[allow(clippy::too_many_arguments)] pub(super) fn compose_bound( - context: &Context<'_>, - binding: &ModelBinding, + call: Bound<'_, '_, '_, '_>, input: &MtpMlpReady, - session: &QwenSession<'_>, ids: [u32; K], weights: [f32; K], - cache: &MoeWeightCache<'_>, failed: Rc>, ) -> Result> { // Only this current frame-bound invocation can supply the numeric helper. // No device product escapes to a later draft position or rollback epoch. - let call = Bound { context, binding, session, cache }; + let (binding, session) = (call.binding, call.session); let frame = input.frame().clone(); call.admit(&frame)?; - let values = call.compose(&frame, input, call.weights()?, (ids, weights), failed)?; + let values = call.compose(input, call.weights()?, (ids, weights), failed)?; frame.validate(binding, session)?; if !frame.same(input.frame()) { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs index f848b535..979f68e3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs @@ -24,15 +24,21 @@ fn route_on_device( let weights: [f32; K] = download(weights, K)?.as_ref().try_into().map_err(|_| Error::InvalidDimension)?; Ok((validate_route(ids, &weights)?, weights)) } +/// The device context, model binding and expert cache the MTP routed and shared expert math runs against. +#[derive(Clone, Copy)] +pub(super) struct MtpRoutingScope<'a, 'c, 'k> { + pub(super) context: &'a Context<'c>, + pub(super) binding: &'a ModelBinding, + pub(super) cache: &'a MoeWeightCache<'k>, +} pub(super) fn compose( - context: &Context<'_>, - binding: &ModelBinding, + scope: MtpRoutingScope<'_, '_, '_>, mixed: &[f32], x: &DeviceBuffer<'_>, ids: [u32; K], weights: [f32; K], - cache: &MoeWeightCache<'_>, ) -> Result> { + let MtpRoutingScope { context, binding, cache } = scope; let parts = routed_parts(context, binding, x, ids, cache)?; let shared = shared(context, binding, mixed, x, cache)?; combine_uploaded(context, &parts, &weights, &shared) @@ -49,8 +55,9 @@ pub(super) fn routed_parts( context.mtp_quantize_scaled_2560(x, &mut q, &mut scales).map_err(moe_driver_error)?; download(&scales, 80)?; // Must inspect FP32 scales before any dot. let mut parts = reserve(K * N)?; + let scope = MtpRoutingScope { context, binding, cache }; for expert in ids { - let values = routed(context, binding, expert, &q, &scales, cache)?; + let values = routed(scope, expert, &q, &scales)?; validate_values(&values, N)?; parts.extend_from_slice(&values); } @@ -78,13 +85,12 @@ pub(super) fn combine_uploaded( Ok(result) } pub(super) fn routed( - context: &Context<'_>, - binding: &ModelBinding, + scope: MtpRoutingScope<'_, '_, '_>, expert: u32, q: &DeviceBuffer<'_>, scales: &DeviceBuffer<'_>, - cache: &MoeWeightCache<'_>, ) -> Result> { + let MtpRoutingScope { context, binding, cache } = scope; let bank = cache.mtp_bank(binding, context)?; let hidden = routed_hidden(context, bank, expert, q, scales)?; routed_down(context, bank, expert, hidden) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs index 6d897e46..671b3cbb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs @@ -8,6 +8,13 @@ use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; use leleka_cuda_driver::{Context, DeviceBuffer, MtpDenseKvRing}; use std::rc::Rc; const RING_BYTES: usize = 128 * 1024 * 1024; +/// The binding, device context and cache owner token a caller claims the mirror for; the mirror refuses any other. +#[derive(Clone, Copy)] +pub(super) struct MtpKvClaim<'a, 'c> { + pub(super) binding: &'a ModelBinding, + pub(super) context: &'a Context<'c>, + pub(super) owner: &'a Rc<()>, +} /// A cache entry is a numerical mirror, never a checkpoint or host publication. pub(super) struct MtpKvResident<'ctx> { binding: BindingIdentity, @@ -29,15 +36,8 @@ impl<'ctx> MtpKvResident<'ctx> { } Ok(Self { binding, context, owner, ring, prior: None }) } - pub(super) fn prepare( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - owner: &Rc<()>, - next: &DenseKv, - frame: &MtpFrame, - ) -> Result<()> { - self.admit(binding, context, owner)?; + pub(super) fn prepare(&mut self, claim: MtpKvClaim<'_, '_>, next: &DenseKv, frame: &MtpFrame) -> Result<()> { + self.admit(claim.binding, claim.context, claim.owner)?; next.ring_validate(frame)?; let position = u32::try_from(frame.position().get()).map_err(|_| Error::Overflow)?; if self.prior.as_ref().map(|old| next.ring_same(old, frame)).transpose()?.unwrap_or(false) { From d5d61d2c0bd739b78fd5d129914ab6b701621fed Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:18 +0100 Subject: [PATCH 34/42] STRA-338 params e02: QSA input lease takes LeaseClaim, native QSA projections take PromptWeights/AttentionRow/NativeQsaDevices --- .../qsa_index/dispatch_projection_fn.rs | 3 +- .../qsa_index/impl_qsaindexstage.rs | 7 ++- .../src/qwen_forward/qsa_input_reuse_gpu.rs | 9 ++-- .../src/qwen_forward/qsa_input_scratch.rs | 11 ++--- .../src/qwen_forward/qsa_prefill_batch.rs | 4 ++ .../qsa_prefill_batch/concat_mixed_fn.rs | 14 +++--- .../qsa_prefill_batch/native_error_fn.rs | 47 +++++++++---------- .../qsa_prefill_batch/projection_operands.rs | 29 ++++++++++++ .../src/qwen_forward/qsa_prompt_index.rs | 15 +++--- 9 files changed, 86 insertions(+), 53 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_operands.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs index 5e5eaadc..0ead0948 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::gdn::LeaseClaim; pub(super) fn dispatch_projection( context: &Context<'_>, @@ -78,7 +79,7 @@ pub(super) fn project_input( }; let (columns, rows) = weights.shape(role); validate_values(x, columns)?; - source.buffer(&binding.identity(), context, weights.layer(), role, x)?; + source.buffer(&LeaseClaim { binding: &binding.identity(), context, layer: weights.layer(), source: x }, role)?; let cache = cache.ok_or(Error::IdentityMismatch)?; let entry = cache.qsa(binding, weights.layer())?; if !weights.matches(&binding.identity(), weights.layer()) || !std::ptr::eq(entry.weights.as_ref(), weights) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs index bc3750c4..b57ad135 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs @@ -2,6 +2,8 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::prompt_device_rows::PromptWeights; +use crate::qwen_forward::qsa_prefill_batch::AttentionRow; impl QsaIndexStage { pub(in super::super) fn prepare( @@ -96,7 +98,7 @@ impl QsaIndexStage { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Qsa); - native.validate_fresh(binding, cache, txn, layer, input)?; + native.validate_fresh(PromptWeights::new(binding, cache), txn, AttentionRow { layer, input })?; let p = Self::admit(binding, layer, input, pos, prior, txn)?; let context = txn.cuda_context()?; admit_budget(context)?; @@ -113,7 +115,8 @@ impl QsaIndexStage { native: &mut super::super::qsa_prefill_batch::NativeProjectionRow<'_, '_>, ) -> Result { let (binding, layer, input) = (prep.binding, prep.layer, prep.input); - let mut take = |role| native.take(binding, cache, txn, layer, input, role); + let (weights, row) = (PromptWeights::new(binding, cache), AttentionRow { layer, input }); + let mut take = |role| native.take(weights, txn, row, role); let raw = take(QsaMatrixRole::IndexK)?; let k = take(QsaMatrixRole::K)?; let v = take(QsaMatrixRole::V)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs index fb692525..38dfece0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs @@ -1,6 +1,7 @@ //! New QSA current-source lease parity; synthetic component, never ModelBinding. #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::*; +use crate::qwen_forward::gdn::LeaseClaim; use input_scratch::INPUT_BYTES; use leleka_cuda_driver::Driver; use std::{ @@ -122,7 +123,7 @@ fn prove_role( output.release().unwrap(); fresh.release().unwrap(); let charged = context.allocated_bytes(); - let admitted = lease.buffer(binding, context, 3, role, input).unwrap(); + let admitted = lease.buffer(&LeaseClaim { binding, context, layer: 3, source: input }, role).unwrap(); let mut retained_input = vec![0; INPUT_BYTES]; admitted.copy_to(&mut retained_input).unwrap(); assert_eq!(retained_input, input.iter().flat_map(|v| v.to_le_bytes()).collect::>()); @@ -184,7 +185,8 @@ fn prove_buffer_refusals( (binding, context, 3, QsaMatrixRole::IndexK, copy.as_slice(), Error::IdentityMismatch), (binding, context, 3, QsaMatrixRole::Out, input, Error::InvalidDimension), ] { - assert_eq!(lease.buffer(candidate_binding, candidate_context, layer, role, source).err(), Some(expected)); + let claim = LeaseClaim { binding: candidate_binding, context: candidate_context, layer, source }; + assert_eq!(lease.buffer(&claim, role).err(), Some(expected)); } assert_eq!(lease.activation(context, 6144).err(), Some(Error::InvalidDimension)); } @@ -223,7 +225,8 @@ fn prove_sticky_close( ) { let replacement = vec![-0.0625; 2560]; let lease = QsaInputScratch::lease(scratch.borrow_mut(), binding, context, 7, &replacement).unwrap(); - assert!(lease.buffer(binding, context, 7, QsaMatrixRole::IndexQ, &replacement).is_ok()); + let claim = LeaseClaim { binding, context, layer: 7, source: &replacement }; + assert!(lease.buffer(&claim, QsaMatrixRole::IndexQ).is_ok()); let mut overwritten = vec![0; INPUT_BYTES]; lease.activation(context, 2560).unwrap().copy_to(&mut overwritten).unwrap(); assert_eq!(overwritten, (-0.0625_f32).to_le_bytes().repeat(2560)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs index f958271c..0dcd0bc6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs @@ -2,6 +2,7 @@ use super::{ BindingIdentity, Context, DeviceBuffer, Error, QsaMatrixRole, Result, admit_budget, driver_error, validate_values, }; +use crate::qwen_forward::gdn::LeaseClaim; use std::{ cell::{Cell, RefMut}, rc::Rc, @@ -94,14 +95,8 @@ impl<'ctx> QsaInputScratch<'ctx> { } } impl<'ctx> QsaInputLease<'_, '_, 'ctx> { - pub(super) fn buffer( - &self, - binding: &BindingIdentity, - context: &Context<'_>, - layer: u32, - role: QsaMatrixRole, - source: &[f32], - ) -> Result<&DeviceBuffer<'ctx>> { + pub(super) fn buffer(&self, claim: &LeaseClaim<'_, '_>, role: QsaMatrixRole) -> Result<&DeviceBuffer<'ctx>> { + let LeaseClaim { binding, context, layer, source } = *claim; if !self.slot.binding.matches(binding) || !std::ptr::eq(self.slot.context, context) || self.layer != layer diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs index b6918ecb..3e8f9f06 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs @@ -5,6 +5,7 @@ use super::{ contract::{Error, LayerId, Result, Stage}, dense_weight_cache::{DenseWeightCache, QsaResident}, gr::ResidualReady, + prompt_device_rows::PromptWeights, qsa_index::validate_values, session::{QwenStepTxn, TargetStepOrigin, chunk::QwenChunkTxn}, }; @@ -35,6 +36,9 @@ pub(super) struct NativeOutRow<'ctx> { values: Box<[f32]>, } +#[path = "qsa_prefill_batch/projection_operands.rs"] +mod projection_operands; +pub(super) use projection_operands::{AttendedRows, AttentionRow, ChunkAttentionSlot, NativeQsaDevices}; mod native_error_fn; #[allow(unused_imports)] use native_error_fn::check_batch; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs index 79c8c12b..2bb6032d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs @@ -93,17 +93,17 @@ impl NativeOutRow<'_> { Ok(self.values) } } -#[allow(clippy::too_many_arguments)] // Actual attention producers and current chunk fence. +/// Actual attention producers and current chunk fence. pub(in super::super) fn project_out<'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, chunk: &QwenChunkTxn<'_, '_>, layer: LayerId, - rows: &[super::super::qsa_attention::NativeAttended<'_, 'ctx>], - proofs: &[super::super::session::chunk::PreparedLayerRow], - owner: &mut QsaNativeBatchWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + attended: AttendedRows<'_, 'ctx>, + devices: NativeQsaDevices<'_, 'ctx>, ) -> Result> { + let PromptWeights { binding, dense: cache } = weights; + let AttendedRows { rows, proofs } = attended; + let NativeQsaDevices { owner, workspace } = devices; let context = cache.retained_context(binding, chunk.context()?)?; check_batch(rows.len(), owner.capacity(), chunk)?; if proofs.len() != rows.len() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs index 167c3ed0..3be3d37b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs @@ -22,12 +22,12 @@ pub(super) fn native(kind: QsaMatrixKind) -> Result { impl<'source> NativeProjectionRow<'source, '_> { pub(in super::super) fn validate( &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, + row: AttentionRow<'_>, ) -> Result<()> { + let PromptWeights { binding, dense: cache } = weights; + let AttentionRow { layer, input } = row; txn.validate_projection_branch(&self.origin)?; txn.validate_input(input.identity().token(), input.identity().position())?; let context = txn.cuda_context()?; @@ -64,13 +64,11 @@ impl<'source> NativeProjectionRow<'source, '_> { } pub(in super::super) fn validate_fresh( &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, + row: AttentionRow<'_>, ) -> Result<()> { - self.validate(binding, cache, txn, layer, input)?; + self.validate(weights, txn, row)?; if self.values.iter().any(Option::is_none) { return Err(Error::IdentityMismatch); } @@ -81,13 +79,12 @@ impl<'source> NativeProjectionRow<'source, '_> { } pub(in super::super) fn attend_origin( &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, layer: LayerId, identity: super::super::contract::TokenLayer, ) -> Result { - self.validate(binding, cache, txn, layer, self.source)?; + self.validate(weights, txn, AttentionRow { layer, input: self.source })?; if identity != self.source.identity() { return Err(Error::IdentityMismatch); } @@ -95,13 +92,13 @@ impl<'source> NativeProjectionRow<'source, '_> { } pub(in super::super) fn take_prompt( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, chunk: &QwenChunkTxn<'_, '_>, - layer: LayerId, - local: usize, + slot: ChunkAttentionSlot, role: QsaMatrixRole, ) -> Result> { + let PromptWeights { binding, dense: cache } = weights; + let ChunkAttentionSlot { layer, local } = slot; self.origin.validate(chunk.original_session()?)?; let context = cache.retained_context(binding, chunk.context()?)?; let entry = cache.qsa(binding, layer.get())?; @@ -144,28 +141,26 @@ impl<'source> NativeProjectionRow<'source, '_> { } pub(in super::super) fn take( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'_>, + weights: PromptWeights<'_, '_>, txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, + row: AttentionRow<'_>, role: QsaMatrixRole, ) -> Result> { - self.validate(binding, cache, txn, layer, input)?; + self.validate(weights, txn, row)?; let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; self.values[i].take().ok_or(Error::IdentityMismatch) } } -#[allow(clippy::too_many_arguments)] // Genuine chunk and separately admitted fixed native owners. +/// Genuine chunk and separately admitted fixed native owners. pub(in super::super) fn project<'source, 'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, chunk: &QwenChunkTxn<'_, '_>, layer: LayerId, inputs: &[&'source ResidualReady], - owner: &mut QsaNativeBatchWorkspace<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + devices: NativeQsaDevices<'_, 'ctx>, ) -> Result>> { + let PromptWeights { binding, dense: cache } = weights; + let NativeQsaDevices { owner, workspace } = devices; let (context, origin) = chunk_owners(binding, cache, chunk)?; check_batch(inputs.len(), owner.capacity(), chunk)?; check_inputs(binding, chunk, layer, inputs)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_operands.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_operands.rs new file mode 100644 index 00000000..cbec5325 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_operands.rs @@ -0,0 +1,29 @@ +//! The operand groups of the native QSA prompt projections. +use super::*; + +/// One attention-layer input row: the layer and the ready residual it was produced for. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct AttentionRow<'a> { + pub(in crate::qwen_forward) layer: LayerId, + pub(in crate::qwen_forward) input: &'a ResidualReady, +} + +/// Row `local` of the chunk's micro batch at `layer`. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ChunkAttentionSlot { + pub(in crate::qwen_forward) layer: LayerId, + pub(in crate::qwen_forward) local: usize, +} + +/// The QSA native workspace and the shared native batch workspace a projection runs on. +pub(in crate::qwen_forward) struct NativeQsaDevices<'a, 'ctx> { + pub(in crate::qwen_forward) owner: &'a mut QsaNativeBatchWorkspace<'ctx>, + pub(in crate::qwen_forward) workspace: &'a mut NativeBatchWorkspace<'ctx>, +} + +/// The attended rows of a layer and the chunk proof of each row. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct AttendedRows<'a, 'ctx> { + pub(in crate::qwen_forward) rows: &'a [super::super::qsa_attention::NativeAttended<'a, 'ctx>], + pub(in crate::qwen_forward) proofs: &'a [super::super::session::chunk::PreparedLayerRow], +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs index 5aa0b7ef..f661ad58 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs @@ -5,8 +5,9 @@ use super::{ contract::{Error, LayerId, Result}, dense_weight_cache::{DenseWeightCache, QsaResident}, gr::ResidualReady, + prompt_device_rows::PromptWeights, qsa_index::{QsaPrior, validate_values}, - qsa_prefill_batch::NativeProjectionRow, + qsa_prefill_batch::{ChunkAttentionSlot, NativeProjectionRow}, session::{ TargetStepOrigin, chunk::{PreparedLayerRow, QwenChunkTxn}, @@ -68,16 +69,18 @@ impl PromptHost { chunk: &QwenChunkTxn<'_, '_>, layer: LayerId, ) -> Result<()> { + let weights = PromptWeights::new(binding, cache); for (local, row) in rows.iter_mut().enumerate() { - self.k.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::K)?); - self.v.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::V)?); - let q = row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::Q)?; + let slot = ChunkAttentionSlot { layer, local }; + self.k.extend_from_slice(&row.take_prompt(weights, chunk, slot, QsaMatrixRole::K)?); + self.v.extend_from_slice(&row.take_prompt(weights, chunk, slot, QsaMatrixRole::V)?); + let q = row.take_prompt(weights, chunk, slot, QsaMatrixRole::Q)?; for h in 0..24 { self.gate.extend_from_slice(&q[h * 512 + 256..h * 512 + 512]); } self.qfull.extend_from_slice(&q); - self.raw.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexK)?); - self.iq.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexQ)?); + self.raw.extend_from_slice(&row.take_prompt(weights, chunk, slot, QsaMatrixRole::IndexK)?); + self.iq.extend_from_slice(&row.take_prompt(weights, chunk, slot, QsaMatrixRole::IndexQ)?); } Ok(()) } From 7c56ce7ccc09fc254e6766d6d91dc2f2a1b818e3 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:20:18 +0100 Subject: [PATCH 35/42] STRA-338 params e02: MTP draft ring transitions take WindowOrigins, native head verification takes NativeHeadGraphRun Files: crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs --- .../original_mtp_verified_adapter.rs | 5 +- .../impl_originalpromptexecutor.rs | 55 ++++++++++--------- .../src/qwen_forward/output_native.rs | 10 +++- .../qwen_forward/session_original_draft.rs | 3 + .../impl_originaldraftcheckpoint.rs | 13 ++--- .../session_original_draft/window_origins.rs | 10 ++++ 6 files changed, 59 insertions(+), 37 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/window_origins.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs index c2292461..2c17e8d9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs @@ -6,7 +6,10 @@ use super::{ contract::{Error, Result}, executor::{TargetStepProduct, original_prompt::OriginalPromptExecutor}, - session::{QwenSession, TargetStepOrigin, original_prompt::draft::OriginalDraftSession}, + session::{ + QwenSession, TargetStepOrigin, + original_prompt::draft::{OriginalDraftSession, WindowOrigins}, + }, }; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; use leleka_cuda_driver::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs index 13f81767..337c40ed 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalpromptexecutor.rs @@ -27,7 +27,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { let prospective = self.launch_origin(session, &window, &before, accepted_row)?; before.validate(session)?; let actor = self.checked_mtp_actor(binding)?; - draft.with_mtp_launch_ring(binding, session, &before, &prospective, |ring, prior| { + let origins = WindowOrigins { before: &before, after: &prospective }; + draft.with_mtp_launch_ring(binding, session, origins, |ring, prior| { actor .launch_draft_from_verifier(ring, prior, window, selection, accepted_row, min_p, policy, after) .map_err(driver_error) @@ -82,11 +83,11 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { return Err(Error::IdentityMismatch); } let actor = self.mtp_actor(binding)?; - let completed = - draft.with_mtp_transition_ring(binding, session, &launched.before, &committed, |ring, prior| { - actor.finish_draft_from_verifier(ring, prior, policy).map_err(driver_error) - })?; - draft.publish_mtp_completion(binding, session, &launched.before, &committed, &completed)?; + let origins = WindowOrigins { before: &launched.before, after: &committed }; + let completed = draft.with_mtp_transition_ring(binding, session, origins, |ring, prior| { + actor.finish_draft_from_verifier(ring, prior, policy).map_err(driver_error) + })?; + draft.publish_mtp_completion(binding, session, origins, &completed)?; Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed }) } /// Literal source order: verifier completion -> target commit -> full MTP @@ -109,20 +110,20 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { return Err(Error::InvalidDimension); } let actor = self.checked_mtp_actor(binding)?; - let completed = - draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| { - actor - .draft_from_verifier( - ring, - prior, - receipt.window, - receipt.selection, - receipt.accepted_row, - min_p, - policy, - ) - .map_err(driver_error) - })?; + let origins = WindowOrigins { before: &receipt.before, after: &receipt.committed }; + let completed = draft.with_mtp_transition_ring(binding, session, origins, |ring, prior| { + actor + .draft_from_verifier( + ring, + prior, + receipt.window, + receipt.selection, + receipt.accepted_row, + min_p, + policy, + ) + .map_err(driver_error) + })?; self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed) } /// generate.cpp `mtp.draft_first(o.spec, ss.R, x, p - 1, drafts, ...)`: the @@ -145,12 +146,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { return Err(Error::InvalidDimension); } let actor = self.checked_mtp_actor(binding)?; - let completed = - draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| { - actor - .draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy) - .map_err(driver_error) - })?; + let origins = WindowOrigins { before: &receipt.before, after: &receipt.committed }; + let completed = draft.with_mtp_transition_ring(binding, session, origins, |ring, prior| { + actor + .draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy) + .map_err(driver_error) + })?; self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed) } /// The loaded actor, refused when its draft cap was never configured. @@ -173,7 +174,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { (before, committed): (&TargetStepOrigin, TargetStepOrigin), completed: CompletedOriginalMtpDraft<'ctx>, ) -> Result> { - draft.publish_mtp_completion(binding, session, before, &committed, &completed)?; + draft.publish_mtp_completion(binding, session, WindowOrigins { before, after: &committed }, &completed)?; Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed }) } /// `mtp.set_draft_sampling(req_sp)` (a no-op unless coupled setup succeeded). diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs index 987ed94a..c276469e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs @@ -66,6 +66,12 @@ fn driver(e: leleka_cuda_driver::Error) -> Error { _ => Error::CudaExecution, } } +/// A native-head graph and the GPU stream it was launched on, finished together. +pub(in crate::qwen_forward) struct NativeHeadGraphRun<'a, 'ctx, R: OriginalNativeHeadGraphResources<'ctx>> { + pub(in crate::qwen_forward) graph: &'a mut OriginalGpuGraph<'ctx, R>, + pub(in crate::qwen_forward) stream: &'a mut OriginalGpuStream<'ctx>, +} + impl<'ctx> OriginalNativeOutput<'ctx> { pub(in crate::qwen_forward) fn load( binding: &ModelBinding, @@ -165,11 +171,11 @@ impl<'ctx> OriginalNativeOutput<'ctx> { pub(in crate::qwen_forward) fn finish_verification>( &self, binding: &ModelBinding, - graph: &mut OriginalGpuGraph<'ctx, R>, - stream: &mut OriginalGpuStream<'ctx>, + launch: NativeHeadGraphRun<'_, 'ctx, R>, sampling: NativeHeadSampling<'_, 'ctx>, mut authenticate: impl FnMut() -> Result<()>, ) -> Result { + let NativeHeadGraphRun { graph, stream } = launch; self.validate(binding, self.context)?; authenticate()?; graph.validate_native_head(self.head.as_ref().ok_or(Error::IdentityMismatch)?).map_err(driver)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs index b94bd5ca..fa195d0d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs @@ -73,6 +73,9 @@ mod first_materialized_tests { } } +#[path = "session_original_draft/window_origins.rs"] +mod window_origins; +pub(in crate::qwen_forward) use window_origins::WindowOrigins; #[path = "session_original_draft/impl_originaldraftcheckpoint.rs"] mod impl_originaldraftcheckpoint; #[path = "session_original_draft/impl_originaldraftsession_2.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs index e5e00d50..26e80c3a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs @@ -192,11 +192,10 @@ impl<'ctx> OriginalDraftSession<'ctx> { &mut self, binding: &ModelBinding, session: &QwenSession<'ctx>, - before: &TargetStepOrigin, - committed: &TargetStepOrigin, + origins: WindowOrigins<'_>, execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result, ) -> Result { - self.check_transition(binding, session, (before, committed))?; + self.check_transition(binding, session, (origins.before, origins.after))?; self.run_validated_ring(execute) } /// `with_mtp_transition_ring` for a draft LAUNCHED while the verifier's commit of `prospective` is enqueued and @@ -207,10 +206,10 @@ impl<'ctx> OriginalDraftSession<'ctx> { &mut self, binding: &ModelBinding, session: &QwenSession<'ctx>, - before: &TargetStepOrigin, - prospective: &TargetStepOrigin, + origins: WindowOrigins<'_>, execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result, ) -> Result { + let WindowOrigins { before, after: prospective } = origins; if self.failed || !self.binding.matches(&binding.identity()) || !self.origin.same_prefix(before) @@ -232,10 +231,10 @@ impl<'ctx> OriginalDraftSession<'ctx> { &mut self, binding: &ModelBinding, session: &QwenSession<'ctx>, - before: &TargetStepOrigin, - committed: &TargetStepOrigin, + origins: WindowOrigins<'_>, completed: &CompletedOriginalMtpDraft<'ctx>, ) -> Result<()> { + let WindowOrigins { before, after: committed } = origins; // The preceding graph replaced `self.snapshot` with its completed // speculative snapshot, so this publication must validate that new // physical current state directly. Re-entering the pre-graph loan diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/window_origins.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/window_origins.rs new file mode 100644 index 00000000..5243b930 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/window_origins.rs @@ -0,0 +1,10 @@ +//! The two target origins a verified-window draft transition is checked against. +use super::*; + +/// The target origin before a verified window and the origin it moves to: the committed one, or for a draft launched +/// while the commit is still enqueued the prospective one. The independent MTP ring is anchored at `before`. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct WindowOrigins<'a> { + pub(in crate::qwen_forward) before: &'a TargetStepOrigin, + pub(in crate::qwen_forward) after: &'a TargetStepOrigin, +} From 8ebeadb365eec8972881c96fab59cac0a33cd985 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:21:57 +0100 Subject: [PATCH 36/42] STRA-338 params e03: serve port draft calls take CommittedWindow/FirstDraftSeed/DraftLimits, serve_request takes SpeculativeRequest/ServeCallbacks, draft seed takes TargetSeedRow Files: crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs --- .../src/qwen_forward/mtp_expert_workspace.rs | 26 ++++------ .../qwen_forward/mtp_experts/impl_mtpblock.rs | 9 ++-- .../src/qwen_forward/original_serve_engine.rs | 47 ++++++++++++------- .../impl_draftcompletion_2.rs | 22 ++++----- ...inalfirstdraftengine_for_originalservee.rs | 2 +- ...alfirstdraftengine_for_originalservee_2.rs | 4 +- .../impl_originalservesettings.rs | 35 +++++++++++--- .../serve_rounds_fn.rs | 24 +++------- .../original_serve_engine/tests.rs | 37 ++++++++------- .../tests/constructor_validates_dimensions.rs | 24 +++++----- .../tests/restore_attempts_do_not_depend.rs | 9 +++- ...l_nativeservehost_for_originalservehost.rs | 30 +++++------- .../src/qwen_forward/original_serve_native.rs | 37 ++++++--------- .../impl_nativewindow.rs | 6 ++- ...l_originalserveport_for_nativeserveport.rs | 21 ++++----- .../impl_originalservestack/serve_parts.rs | 20 ++++---- .../lifecycle_fake/port.rs | 24 +++++----- .../lifecycle_fake/stack.rs | 20 ++++---- .../original_spec_controller/tests.rs | 5 +- .../src/qwen_forward/original_spec_draft.rs | 20 ++++---- 20 files changed, 209 insertions(+), 213 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs index 4013547f..ba5090cc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs @@ -94,7 +94,7 @@ pub(in crate::qwen_forward) struct MtpExpertWorkspace<'ctx> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod fixed_workspace_gpu { - use super::super::mtp_expert_transport::{ExpertWeights, SelectedRoute, fixed_reference}; + use super::super::mtp_expert_transport::{ExpertWeights, FixedReference, SelectedRoute, fixed_reference}; use super::*; use leleka_cuda_driver::Driver; const BANK_BYTES: usize = 707_788_800; @@ -244,9 +244,7 @@ mod fixed_workspace_gpu { } fn compare_pattern(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32]) -> usize { // Original allocation path and its direct unchanged quantizers FIRST. - let (weights, route) = - (ExpertWeights { bank: &self.bank, shared: self.w() }, SelectedRoute { ids: IDS, weights: ROUTE }); - let (expected, original) = fixed_reference(self.ctx, weights, mixed, route).unwrap(); + let (expected, original) = self.reference(mixed).unwrap(); let scales = reference_scale_sets(self.ctx, mixed, &original); assert_eq!(original.len(), 38); assert_eq!(scales.len(), 11); @@ -296,27 +294,21 @@ mod fixed_workspace_gpu { let saved: [u8; 2] = corpus[at..at + 2].try_into().unwrap(); corpus[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes()); self.bank.copy_from(corpus).unwrap(); - assert_eq!( - fixed_reference( - self.ctx, - ExpertWeights { bank: &self.bank, shared: self.w() }, - mixed, - SelectedRoute { ids: IDS, weights: ROUTE } - ) - .err(), - Some(Error::NonFinite) - ); + assert_eq!(self.reference(mixed).err(), Some(Error::NonFinite)); assert_eq!(self.compose_with(storage, mixed, false).err(), Some(Error::NonFinite)); storage.check().unwrap(); corpus[at..at + 2].copy_from_slice(&saved); self.bank.copy_from(corpus).unwrap(); - let route = SelectedRoute { ids: IDS, weights: ROUTE }; - let (expected, _) = - fixed_reference(self.ctx, ExpertWeights { bank: &self.bank, shared: self.w() }, mixed, route).unwrap(); + let (expected, _) = self.reference(mixed).unwrap(); let actual = self.compose_with(storage, mixed, false).unwrap(); exact(&expected, &actual); actual.len() } + /// The original-path reference composition over the bank and the fixed route. + fn reference(&self, mixed: &[f32]) -> Result { + let weights = ExpertWeights { bank: &self.bank, shared: self.w() }; + fixed_reference(self.ctx, weights, mixed, SelectedRoute { ids: IDS, weights: ROUTE }) + } fn compose_with(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32], failed: bool) -> Result> { compose(storage, &self.bank, self.w(), mixed, IDS, ROUTE, Rc::new(Cell::new(failed))) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs index da966395..0dba6e74 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338. +use super::mtp_expert_transport::{ExpertWeights, SelectedRoute}; #[allow(unused_imports)] use super::*; @@ -119,7 +120,6 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> { let BoundWeights { bank, shared } = weights; if self.cache.requires_iq3_mmq_admission() { let (binding, context, session) = (self.binding, self.context, self.session); - let mixed = input.mixed(); let cache = self.cache; cache.compose_fixed_mtp_experts( binding, @@ -128,15 +128,14 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> { session, bank, shared, - mixed, + input.mixed(), ids, route_weights, failed, ) } else { - let expert_weights = mtp_expert_transport::ExpertWeights { bank, shared }; - let route = mtp_expert_transport::SelectedRoute { ids, weights: route_weights }; - mtp_expert_transport::compose(self.context, expert_weights, input.mixed(), route, failed) + let route = SelectedRoute { ids, weights: route_weights }; + mtp_expert_transport::compose(self.context, ExpertWeights { bank, shared }, input.mixed(), route, failed) } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs index eeadfb18..e36c001e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs @@ -10,7 +10,7 @@ use super::contract::{Error, Result}; use super::original_spec_adaptive::AdaptiveConfig; use super::original_spec_controller::{NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecError}; -use super::original_spec_draft::{DraftPick, OriginalDraftEngine, OriginalFirstDraftEngine}; +use super::original_spec_draft::{DraftPick, OriginalDraftEngine, OriginalFirstDraftEngine, TargetSeedRow}; use super::original_spec_policy::MAX_T; use crate::settings::EnvSource; use std::rc::Rc; @@ -26,6 +26,29 @@ pub(crate) struct DraftCompletion { pub(crate) accepted_row: usize, } +/// The chain length cap and the confidence floor of one draft stage. +#[derive(Clone, Copy, Debug)] +pub(crate) struct DraftLimits { + pub(crate) max_drafts: usize, + pub(crate) min_p: f32, +} + +/// The committed verifier window a draft follows: where it starts, the accepted row and the verified outputs. +pub(crate) struct CommittedWindow<'a, Window> { + pub(crate) window: &'a Window, + pub(crate) position: i64, + pub(crate) accepted_row: usize, + pub(crate) outputs: &'a [i32], +} + +/// The retained prefill seed of the CLI's first draft: its `t` rows, and the cell and token the draft starts from. +pub(crate) struct FirstDraftSeed<'a, Seed> { + pub(crate) seed: &'a Seed, + pub(crate) t: usize, + pub(crate) cell: i64, + pub(crate) token: i32, +} + /// The genuine physical owners behind the serve loop. Every method that touches /// the GPU or a session must complete (or fence) its real commands before /// returning an error, and a failed restore must poison the owner it touched. @@ -69,27 +92,17 @@ pub(crate) trait OriginalServePort { fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()>; /// Literal `draft_from_verifier`: needs the committed window (commit already /// enqueued, event dependency honored by the owner) and all T real rows. - #[allow(clippy::too_many_arguments)] fn draft_committed( &mut self, - window: &Self::Window, - position: i64, - accepted_row: usize, - outputs: &[i32], - max_drafts: usize, - min_p: f32, + committed: CommittedWindow<'_, Self::Window>, + limits: DraftLimits, coupled: bool, ) -> Result; fn drain_draft(&mut self) -> Result<()>; - #[allow(clippy::too_many_arguments)] fn draft_first( &mut self, - seed: &Self::Seed, - t: usize, - cell: i64, - token: i32, - max_drafts: usize, - min_p: f32, + first: FirstDraftSeed<'_, Self::Seed>, + limits: DraftLimits, coupled: bool, ) -> Result; fn drain_first(&mut self) -> Result<()>; @@ -185,6 +198,6 @@ mod tests; mod impl_draftcompletion; mod impl_originalfirstdraftengine_for_originalservee; #[allow(unused_imports)] -pub(crate) use impl_originalfirstdraftengine_for_originalservee::serve_request; -#[allow(unused_imports)] use impl_originalfirstdraftengine_for_originalservee::tr_port; +#[allow(unused_imports)] +pub(crate) use impl_originalfirstdraftengine_for_originalservee::{ServeCallbacks, SpeculativeRequest, serve_request}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs index 43a2a8ac..0363e579 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs @@ -205,11 +205,10 @@ impl OriginalDraftEngine> for Orig fn full_target_seed( &mut self, verified: &ServedWindow, - row: usize, - cell: i64, - token: i32, + seed: TargetSeedRow, coupled: bool, ) -> Result { + let TargetSeedRow { row, cell, token } = seed; self.usable()?; self.window_ok(verified)?; self.admit_seed(verified, row, cell, token)?; @@ -218,15 +217,14 @@ impl OriginalDraftEngine> for Orig return Err(Error::IdentityMismatch); } let max_picks = self.plan_drafts.max(1); - let completion = self.port.draft_committed( - &verified.window, - verified.position, - row, - &verified.outputs[..verified.t], - self.plan_drafts, - self.min_p, - coupled, - )?; + let committed = CommittedWindow { + window: &verified.window, + position: verified.position, + accepted_row: row, + outputs: &verified.outputs[..verified.t], + }; + let limits = DraftLimits { max_drafts: self.plan_drafts, min_p: self.min_p }; + let completion = self.port.draft_committed(committed, limits, coupled)?; completion.validate(self.vocabulary, max_picks, cell, row)?; let pick = self.cached_pick(&completion, 0); self.draft = DraftStage::Seeded { completion, next: 1 }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs index c7975d1d..1d201d6c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs @@ -13,7 +13,7 @@ struct RoundTally { mod impl_originalfirstdraftengine_for_originalservee_2; mod impl_originalservesettings; #[allow(unused_imports)] -pub(crate) use impl_originalservesettings::serve_request; +pub(crate) use impl_originalservesettings::{ServeCallbacks, SpeculativeRequest, serve_request}; mod serve_rounds_fn; #[allow(unused_imports)] use serve_rounds_fn::serve_round; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalfirstdraftengine_for_originalservee_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalfirstdraftengine_for_originalservee_2.rs index a7239039..ed1f4806 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalfirstdraftengine_for_originalservee_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalfirstdraftengine_for_originalservee_2.rs @@ -25,7 +25,9 @@ impl OriginalFirstDraftEngine for OriginalServeEn if !matches!(self.first, FirstStage::Idle) { return Err(Error::IdentityMismatch); } - let completion = self.port.draft_first(seed, self.max_t, cell, token, self.max_drafts, self.min_p, coupled)?; + let first = FirstDraftSeed { seed, t: self.max_t, cell, token }; + let limits = DraftLimits { max_drafts: self.max_drafts, min_p: self.min_p }; + let completion = self.port.draft_first(first, limits, coupled)?; completion.validate(self.vocabulary, self.max_drafts.max(1), cell, 0)?; let pick = self.cached_pick(&completion, 0); self.first = FirstStage::Seeded { completion, next: 1, cell }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalservesettings.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalservesettings.rs index 07ad70e2..948f4f0b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalservesettings.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/impl_originalservesettings.rs @@ -173,20 +173,41 @@ impl OriginalServeSettings { ) } } +/// The part of a request the speculative serve loop reads: prompt, new-token budget, draft confidence floor and stop +/// tokens. +#[derive(Clone, Copy)] +pub(crate) struct SpeculativeRequest<'a> { + pub(crate) prompt: &'a [i32], + pub(crate) max_new: usize, + pub(crate) min_p: f32, + pub(crate) eos: &'a [i32], +} + +impl<'a> SpeculativeRequest<'a> { + /// The speculative view of a validated serve request: its prompt, budget, draft floor and stop tokens. + pub(crate) fn from_request(request: &'a crate::qwen_forward::original_serve_request::ServeRequest) -> Self { + Self { prompt: &request.prompt, max_new: request.max_new, min_p: request.spec_min_p, eos: &request.eos } + } +} + +/// The three hooks of the serve loop: emit the committed tokens, poll cancellation, read the clock in milliseconds. +pub(crate) struct ServeCallbacks { + pub(crate) emit: Emit, + pub(crate) cancel: Cancel, + pub(crate) clock_ms: ClockMs, +} + /// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed /// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the /// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded. pub(crate) fn serve_request( controller: &mut OriginalSpecController, engine: &mut E, - prompt: &[i32], - max_new: usize, - min_p: f32, - eos: &[i32], - mut emit: impl FnMut(&[i32]) -> Result<()>, - mut cancel: impl FnMut() -> bool, - mut clock_ms: impl FnMut() -> f64, + request: SpeculativeRequest<'_>, + callbacks: ServeCallbacks Result<()>, impl FnMut() -> bool, impl FnMut() -> f64>, ) -> std::result::Result { + let SpeculativeRequest { prompt, max_new, min_p, eos } = request; + let ServeCallbacks { mut emit, mut cancel, mut clock_ms } = callbacks; let begin_span = super::super::super::original_serve_profile::span("ctrl.begin_request"); controller.begin_request(prompt, max_new, min_p, eos)?; drop(begin_span); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/serve_rounds_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/serve_rounds_fn.rs index 223b42ce..31da9df6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/serve_rounds_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee/serve_rounds_fn.rs @@ -125,36 +125,24 @@ impl OriginalServePort for TracePort

{ fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next)) } - #[allow(clippy::too_many_arguments)] fn draft_committed( &mut self, - window: &Self::Window, - position: i64, - accepted_row: usize, - outputs: &[i32], - max_drafts: usize, - min_p: f32, + committed: CommittedWindow<'_, Self::Window>, + limits: DraftLimits, coupled: bool, ) -> Result { - tr_port("draft_committed", || { - self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled) - }) + tr_port("draft_committed", || self.0.draft_committed(committed, limits, coupled)) } fn drain_draft(&mut self) -> Result<()> { tr_port("drain_draft", || self.0.drain_draft()) } - #[allow(clippy::too_many_arguments)] fn draft_first( &mut self, - seed: &Self::Seed, - t: usize, - cell: i64, - token: i32, - max_drafts: usize, - min_p: f32, + first: FirstDraftSeed<'_, Self::Seed>, + limits: DraftLimits, coupled: bool, ) -> Result { - tr_port("draft_first", || self.0.draft_first(seed, t, cell, token, max_drafts, min_p, coupled)) + tr_port("draft_first", || self.0.draft_first(first, limits, coupled)) } fn drain_first(&mut self) -> Result<()> { tr_port("drain_first", || self.0.drain_first()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs index 9ceebf2a..5bc911ea 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs @@ -162,14 +162,12 @@ impl OriginalServePort for Fake { } fn draft_committed( &mut self, - w: &Win, - position: i64, - a: usize, - outputs: &[i32], - max_drafts: usize, - min_p: f32, + committed: CommittedWindow<'_, Win>, + limits: DraftLimits, _coupled: bool, ) -> Result { + let CommittedWindow { window: w, position, accepted_row: a, outputs } = committed; + let DraftLimits { max_drafts, min_p } = limits; self.log(format!("draft a={a}")); if self.fails("draft") { return Err(Error::CudaExecution); @@ -195,14 +193,12 @@ impl OriginalServePort for Fake { } fn draft_first( &mut self, - _: &i32, - _t: usize, - cell: i64, - token: i32, - max_drafts: usize, - min_p: f32, - _c: bool, + first: FirstDraftSeed<'_, i32>, + limits: DraftLimits, + _coupled: bool, ) -> Result { + let FirstDraftSeed { cell, token, .. } = first; + let DraftLimits { max_drafts, min_p } = limits; self.log("draft-first"); let mut ids = vec![model(token)]; let mut probs = vec![0.9f32]; @@ -219,6 +215,10 @@ impl OriginalServePort for Fake { } } +/// The window row a draft is seeded from, as the engine tests build it. +fn seed_row(row: usize, cell: i64, token: i32) -> TargetSeedRow { + TargetSeedRow { row, cell, token } +} fn engine(prompt: &[i32], max_t: usize) -> (OriginalServeEngine, Rc>) { let (f, w) = Fake::new(prompt); (OriginalServeEngine::new(f, VOCAB, max_t, max_t - 1).unwrap(), w) @@ -290,24 +290,25 @@ fn serve( cancel: impl FnMut() -> bool, fail_emit_after: Option, ) -> (std::result::Result, Vec, OriginalSpecController, OriginalServeEngine) { - let (r, out, c, e, _) = serve_in(p, max_new, eos, cancel, fail_emit_after, 4096); + let request = SpeculativeRequest { prompt: p, max_new, min_p: 0.0, eos }; + let (r, out, c, e, _) = serve_in(request, cancel, fail_emit_after, 4096); (r, out, c, e) } fn serve_in( - p: &[i32], - max_new: usize, - eos: &[i32], + request: SpeculativeRequest<'_>, mut cancel: impl FnMut() -> bool, fail_emit_after: Option, max_context: i64, ) -> ServedIn { + let p = request.prompt; let (f, w) = Fake::new(p); let s = serve_settings(max_context); let mut e = OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_t - 1).unwrap(); let mut c = s.controller().unwrap(); let mut out = Vec::new(); let emit = recording_emit(&mut out, Rc::clone(&w), fail_emit_after); - let r = serve_request(&mut c, &mut e, p, max_new, 0.0, eos, emit, &mut cancel, || 0.0); + let callbacks = ServeCallbacks { emit, cancel: &mut cancel, clock_ms: || 0.0 }; + let r = serve_request(&mut c, &mut e, request, callbacks); (r, out, c, e, w) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs index 83c21eb9..a3e306bf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs @@ -158,15 +158,15 @@ fn draft_requires_the_commit_before_and_the_literal_stage_order() { assert_eq!(e.replay_target_kv(&v, 3, &outs).err(), Some(Error::IdentityMismatch)); assert_eq!(e.replay_target_kv(&v, 2, &[outs[0] + 1]).err(), Some(Error::IdentityMismatch)); // seed before replay is refused - assert_eq!(e.full_target_seed(&v, 0, 2, outs[0], false).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).err(), Some(Error::IdentityMismatch)); e.replay_target_kv(&v, 2, &outs).unwrap(); // a second replay without drain assert_eq!(e.replay_target_kv(&v, 2, &outs).err(), Some(Error::IdentityMismatch)); // seed row must be the accepted row, cell p+a, token the verified output - assert_eq!(e.full_target_seed(&v, 1, 3, outs[0], false).err(), Some(Error::IdentityMismatch)); - assert_eq!(e.full_target_seed(&v, 0, 3, outs[0], false).err(), Some(Error::IdentityMismatch)); - assert_eq!(e.full_target_seed(&v, 0, 2, outs[0] + 1, false).err(), Some(Error::IdentityMismatch)); - let pick = e.full_target_seed(&v, 0, 2, outs[0], false).unwrap(); + assert_eq!(e.full_target_seed(&v, seed_row(1, 3, outs[0]), false).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.full_target_seed(&v, seed_row(0, 3, outs[0]), false).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.full_target_seed(&v, seed_row(0, 2, outs[0] + 1), false).err(), Some(Error::IdentityMismatch)); + let pick = e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).unwrap(); assert_eq!(pick.token, model(outs[0])); e.drain_draft().unwrap(); e.drain_verified(v).unwrap(); @@ -181,7 +181,7 @@ fn chain_steps_are_served_from_the_one_shot_completion_with_cell_and_token_check let outs = e.outputs(&v).to_vec(); e.commit_verified(&mut v, 1).unwrap(); e.replay_target_kv(&v, 2, &outs).unwrap(); - let s = e.full_target_seed(&v, 0, 2, outs[0], false).unwrap(); + let s = e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).unwrap(); // chain: cell p+a+j, previous token must be the previous pick assert_eq!(e.full_chain_step(4, 2, s.token, false).err(), Some(Error::IdentityMismatch)); assert_eq!(e.full_chain_step(3, 1, s.token + 1, false).err(), Some(Error::IdentityMismatch)); @@ -204,7 +204,7 @@ fn running_past_the_one_shot_completion_is_refused() { let outs = e.outputs(&v).to_vec(); e.commit_verified(&mut v, 1).unwrap(); e.replay_target_kv(&v, 2, &outs).unwrap(); - let s = e.full_target_seed(&v, 0, 2, outs[0], false).unwrap(); + let s = e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).unwrap(); // max_t=2 -> one draft only assert_eq!(e.full_chain_step(3, 1, s.token, false).err(), Some(Error::IdentityMismatch)); e.drain_draft().unwrap(); @@ -220,10 +220,10 @@ fn coupled_draft_needs_this_windows_staged_history() { let outs = e.outputs(&v).to_vec(); e.commit_verified(&mut v, 1).unwrap(); e.replay_target_kv(&v, 2, &outs).unwrap(); - assert_eq!(e.full_target_seed(&v, 0, 2, outs[0], true).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.full_target_seed(&v, seed_row(0, 2, outs[0]), true).err(), Some(Error::IdentityMismatch)); e.stage_coupled_history(&p[..3], outs[0]).unwrap(); assert!(events(&w).iter().any(|s| s.starts_with("history 3"))); - e.full_target_seed(&v, 0, 2, outs[0], true).unwrap(); + e.full_target_seed(&v, seed_row(0, 2, outs[0]), true).unwrap(); e.drain_draft().unwrap(); e.drain_verified(v).unwrap(); // a staged history never carries into the next window @@ -232,7 +232,7 @@ fn coupled_draft_needs_this_windows_staged_history() { let o2 = e.outputs(&v2).to_vec(); e.commit_verified(&mut v2, 1).unwrap(); e.replay_target_kv(&v2, 3, &o2).unwrap(); - assert_eq!(e.full_target_seed(&v2, 0, 3, o2[0], true).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.full_target_seed(&v2, seed_row(0, 3, o2[0]), true).err(), Some(Error::IdentityMismatch)); e.stage_coupled_history(&p[..3], -1).err(); e.drain_draft().unwrap(); e.drain_verified(v2).unwrap(); @@ -246,7 +246,7 @@ fn stopping_the_chain_without_a_literal_reason_is_detected_at_drain() { let outs = e.outputs(&v).to_vec(); e.commit_verified(&mut v, 1).unwrap(); e.replay_target_kv(&v, 2, &outs).unwrap(); - e.full_target_seed(&v, 0, 2, outs[0], false).unwrap(); + e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).unwrap(); // 3 picks were produced at min_p 0 and the cap is 3: stopping after one is not literal assert_eq!(e.drain_draft().err(), Some(Error::IdentityMismatch)); e.drain_verified(v).unwrap(); @@ -262,7 +262,7 @@ fn a_confidence_stop_matches_the_floor() { e.commit_verified(&mut v, 1).unwrap(); e.replay_target_kv(&v, 2, &outs).unwrap(); // the fake's first pick has probability 0.9 < 0.95, so it is the only one - let s = e.full_target_seed(&v, 0, 2, outs[0], false).unwrap(); + let s = e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).unwrap(); assert!(s.probability < 0.95); e.drain_draft().unwrap(); e.drain_verified(v).unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs index 7c5df2f9..1ac9138e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs @@ -25,7 +25,7 @@ fn restore_attempts_do_not_depend_on_engine_health_and_reset_draft_state() { let ev = events(&w); assert!(idx(&ev, "wait-commit") < idx(&ev, "restore-target"), "{ev:?}"); // the stale draft stage is gone: the receipt cannot seed anymore - assert_eq!(e.full_target_seed(&v, 0, 2, outs[0], false).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.full_target_seed(&v, seed_row(0, 2, outs[0]), false).err(), Some(Error::IdentityMismatch)); let _ = e.drain_verified(v); // a failing target restore still lets the draft restore run and poisons w.borrow_mut().fail_restore = Some("target"); @@ -218,7 +218,12 @@ fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() let p = prompt_long(); for k in 1..=9i64 { let max_context = p.len() as i64 - 1 + k; - let (r, out, c, e, w) = serve_in(&p, 1000, &[], || false, None, max_context); + let (r, out, c, e, w) = serve_in( + SpeculativeRequest { prompt: &p, max_new: 1000, min_p: 0.0, eos: &[] }, + || false, + None, + max_context, + ); let r = r.unwrap_or_else(|err| panic!("k {k}: {err:?}")); assert_eq!(r.stop, ServeStop::Context, "k {k}"); assert_eq!(out.len() as i64, k, "k {k}: one token per row that fits"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs index 39e27591..9d1b5e26 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs @@ -2,6 +2,8 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::original_serve_engine::{DraftLimits, FirstDraftSeed}; +use crate::qwen_forward::original_serve_native::NativeCommittedWindow; impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { type TargetCheckpoint = LedgerCheckpoint; @@ -112,14 +114,12 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { fn draft_committed( &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, + committed: NativeCommittedWindow<'ctx>, + limits: DraftLimits, _coupled: bool, ) -> Result { + let NativeCommittedWindow { window, selection, position, accepted_row } = committed; + let DraftLimits { max_drafts, min_p } = limits; let before = self.admit_draft_origin(position, max_drafts)?; let p = profile::span("draft.receipt"); let receipt = OriginalCommittedMtpReceipt::for_published_window( @@ -139,14 +139,12 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { } fn launch_draft( &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, + committed: NativeCommittedWindow<'ctx>, + limits: DraftLimits, after: Option<&mut OriginalGpuEvent<'ctx>>, ) -> Result<()> { + let NativeCommittedWindow { window, selection, position, accepted_row } = committed; + let DraftLimits { max_drafts, min_p } = limits; if self.launched.is_some() { return Err(Error::IdentityMismatch); } @@ -184,12 +182,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { } fn draft_first( &mut self, - _seed: &(), - _t: usize, - _cell: i64, - _token: i32, - _max_drafts: usize, - _min_p: f32, + _first: FirstDraftSeed<'_, ()>, + _limits: DraftLimits, _coupled: bool, ) -> Result { // generate.cpp calls `draft_first` only on the CLI's first window; the serve loop drafts from the diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs index accb5e6e..de22da20 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs @@ -10,7 +10,7 @@ //! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the //! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. use super::contract::{Error, Result}; -use super::original_serve_engine::{DraftCompletion, OriginalServePort}; +use super::original_serve_engine::{CommittedWindow, DraftCompletion, DraftLimits, FirstDraftSeed, OriginalServePort}; use super::original_serve_profile as profile; use leleka_cuda_driver::{ NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalVerifier, @@ -18,6 +18,14 @@ use leleka_cuda_driver::{ }; use std::cell::RefCell; +/// A completed driver window to draft from: its head selection, where it starts and the accepted row. +pub(in crate::qwen_forward) struct NativeCommittedWindow<'ctx> { + pub(in crate::qwen_forward) window: OriginalVerifyWindow<'ctx>, + pub(in crate::qwen_forward) selection: NativeHeadSelection, + pub(in crate::qwen_forward) position: i64, + pub(in crate::qwen_forward) accepted_row: usize, +} + /// What the serving owner must supply for the verified-window serve path. pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { type TargetCheckpoint; @@ -61,42 +69,27 @@ pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()>; fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()>; /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. - #[allow(clippy::too_many_arguments)] fn draft_committed( &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, + committed: NativeCommittedWindow<'ctx>, + limits: DraftLimits, coupled: bool, ) -> Result; /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... - #[allow(clippy::too_many_arguments)] fn launch_draft( &mut self, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - position: i64, - accepted_row: usize, - max_drafts: usize, - min_p: f32, + committed: NativeCommittedWindow<'ctx>, + limits: DraftLimits, after: Option<&mut OriginalGpuEvent<'ctx>>, ) -> Result<()>; /// ...and completed AFTER it, over the published branch. fn finish_draft(&mut self) -> Result; fn drain_draft(&mut self) -> Result<()>; - #[allow(clippy::too_many_arguments)] fn draft_first( &mut self, - seed: &Self::Seed, - t: usize, - cell: i64, - token: i32, - max_drafts: usize, - min_p: f32, + first: FirstDraftSeed<'_, Self::Seed>, + limits: DraftLimits, coupled: bool, ) -> Result; fn drain_first(&mut self) -> Result<()>; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs index dc936239..10addb08 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs @@ -182,7 +182,8 @@ where let launched = { let _p = profile::span("draft.launch"); let after = if draft_waits_for_commit() { self.verifier.pending_commit_event() } else { None }; - self.host.launch_draft(completed, selection, position, accepted_row, max_drafts, min_p, after) + let committed = NativeCommittedWindow { window: completed, selection, position, accepted_row }; + self.host.launch_draft(committed, DraftLimits { max_drafts, min_p }, after) }; if let Err(e) = launched { self.failed = true; @@ -210,7 +211,8 @@ where let (completed, selection) = self.take_window_parts(window)?; let draft = { let _p = profile::span("draft.mtp"); - self.host.draft_committed(completed, selection, position, accepted_row, max_drafts, min_p, coupled) + let committed = NativeCommittedWindow { window: completed, selection, position, accepted_row }; + self.host.draft_committed(committed, DraftLimits { max_drafts, min_p }, coupled) }; if draft.is_err() { self.failed = true; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs index db99a27a..03a87919 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs @@ -144,14 +144,12 @@ where } fn draft_committed( &mut self, - window: &NativeWindow, - position: i64, - accepted_row: usize, - outputs: &[i32], - max_drafts: usize, - min_p: f32, + committed: CommittedWindow<'_, NativeWindow>, + limits: DraftLimits, coupled: bool, ) -> Result { + let CommittedWindow { window, position, accepted_row, outputs } = committed; + let DraftLimits { max_drafts, min_p } = limits; self.live()?; let _p = profile::span("round.draft_committed"); // Literal order: commit enqueued first, draft depends on its event on the same stream. @@ -172,16 +170,13 @@ where } fn draft_first( &mut self, - seed: &H::Seed, - t: usize, - cell: i64, - token: i32, - max_drafts: usize, - min_p: f32, + first: FirstDraftSeed<'_, H::Seed>, + limits: DraftLimits, coupled: bool, ) -> Result { self.live()?; - let c = self.host.draft_first(seed, t, cell, token, max_drafts, min_p, coupled)?; + let cell = first.cell; + let c = self.host.draft_first(first, limits, coupled)?; trace_draft_line(cell, 0, &c); Ok(c) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs index 3e410580..2d7de959 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/serve_parts.rs @@ -2,7 +2,7 @@ #[allow(unused_imports)] use super::*; -use crate::qwen_forward::original_serve_engine::OriginalServePort; +use crate::qwen_forward::original_serve_engine::{OriginalServePort, ServeCallbacks, SpeculativeRequest}; use crate::qwen_forward::original_serve_host::HostOutcome; use leleka_cuda_driver::{OriginalVerifier, OriginalVerifyWindowResources}; @@ -68,20 +68,16 @@ fn run_engine( let started = config.clock.now(); let serve_span = profile::span("decode.serve"); let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { - serve_request( - controller, - engine, - &request.prompt, - request.max_new, - request.spec_min_p, - &request.eos, - |tokens| { + let speculative = SpeculativeRequest::from_request(request); + let callbacks = ServeCallbacks { + emit: |tokens: &[i32]| { marks.note_first_round(&config.clock); emit(tokens) }, - &mut *cancel, - || config.clock.since(started).as_secs_f64() * 1e3, - ) + cancel: &mut *cancel, + clock_ms: || config.clock.since(started).as_secs_f64() * 1e3, + }; + serve_request(controller, engine, speculative, callbacks) }); drop(serve_span); note_request_end(controller, env.arm_label, &result); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs index 95afec51..8c21a384 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs @@ -1,7 +1,9 @@ //! The per-round seam: `OriginalServePort` over the scripted device. use super::{FakeDevice, model}; use crate::qwen_forward::contract::{Error, Result}; -use crate::qwen_forward::original_serve_engine::{DraftCompletion, OriginalServePort}; +use crate::qwen_forward::original_serve_engine::{ + CommittedWindow, DraftCompletion, DraftLimits, FirstDraftSeed, OriginalServePort, +}; /// A verify window: the rows the engine staged and the model's answer to each. pub(crate) struct Window { @@ -114,14 +116,12 @@ impl OriginalServePort for FakeDevice { fn draft_committed( &mut self, - _window: &Window, - position: i64, - accepted_row: usize, - outputs: &[i32], - max_drafts: usize, - min_p: f32, + committed: CommittedWindow<'_, Window>, + limits: DraftLimits, _coupled: bool, ) -> Result { + let CommittedWindow { position, accepted_row, outputs, .. } = committed; + let DraftLimits { max_drafts, min_p } = limits; self.log(format!("draft a={accepted_row}")); let (ids, probabilities) = self.draft_chain(outputs[accepted_row], max_drafts, min_p); Ok(DraftCompletion { ids, probabilities, first_cell: position + accepted_row as i64, accepted_row }) @@ -133,14 +133,12 @@ impl OriginalServePort for FakeDevice { fn draft_first( &mut self, - _: &(), - _t: usize, - cell: i64, - token: i32, - max_drafts: usize, - min_p: f32, + first: FirstDraftSeed<'_, ()>, + limits: DraftLimits, _coupled: bool, ) -> Result { + let FirstDraftSeed { cell, token, .. } = first; + let DraftLimits { max_drafts, min_p } = limits; self.log("draft-first"); let (ids, probabilities) = self.draft_chain(token, max_drafts, min_p); Ok(DraftCompletion { ids, probabilities, first_cell: cell, accepted_row: 0 }) 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 0aca6d5b..2fef8e9c 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 @@ -7,7 +7,7 @@ use super::{FakeBlock, FakeDevice, FakeState, GRID, VOCAB}; use crate::backend::original_prompt::PromptAction; use crate::qwen_forward::contract::Error; use crate::qwen_forward::original_serve_engine::{ - OriginalServeEngine, OriginalServeSettings, ServeOutcome, serve_request, + OriginalServeEngine, OriginalServeSettings, ServeCallbacks, ServeOutcome, SpeculativeRequest, serve_request, }; use crate::qwen_forward::original_spec_controller::{OriginalSpecController, SpecError}; use leleka_obs::time::{Clock, ManualClock}; @@ -167,17 +167,13 @@ impl FakeStack { OriginalServeEngine::new(self.dev.clone(), VOCAB, self.settings.max_t, self.settings.max_drafts())?; engine.set_min_p(request.spec_min_p)?; let (clock, started) = (self.clock.clone(), self.clock.now()); - serve_request( - &mut self.controller, - &mut engine, - &request.prompt, - request.max_new, - request.spec_min_p, - &request.eos, - |tokens| emit(tokens), - &mut *cancel, - || clock.since(started).as_secs_f64() * 1e3, - ) + let speculative = SpeculativeRequest::from_request(request); + let callbacks = ServeCallbacks { + emit: |tokens: &[i32]| emit(tokens), + cancel: &mut *cancel, + clock_ms: || clock.since(started).as_secs_f64() * 1e3, + }; + serve_request(&mut self.controller, &mut engine, speculative, callbacks) } fn prefix_resume(&mut self, request: &ServeRequest) -> Option { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs index c0bc6079..0d0eed8d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs @@ -1,6 +1,6 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). -use super::super::original_spec_draft::{DraftPick, OriginalFirstDraftEngine}; +use super::super::original_spec_draft::{DraftPick, OriginalFirstDraftEngine, TargetSeedRow}; use super::*; mod golden; @@ -75,7 +75,8 @@ impl OriginalDraftEngine for Fake { self.plans.push((max_drafts, min_p)); Ok(()) } - fn full_target_seed(&mut self, v: &Verif, row: usize, cell: i64, token: i32, _coupled: bool) -> Result { + fn full_target_seed(&mut self, v: &Verif, seed: TargetSeedRow, _coupled: bool) -> Result { + let TargetSeedRow { row, cell, token } = seed; self.trip("seed")?; assert_eq!(cell, v.position + row as i64); assert_eq!(token, v.outputs[row]); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs index c8819551..594ec6d5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs @@ -44,6 +44,14 @@ impl DraftBatch { } } +/// The verified window row a draft is seeded from: the row, its cell `p + row` and the target output at that cell. +#[derive(Clone, Copy, Debug)] +pub(crate) struct TargetSeedRow { + pub(crate) row: usize, + pub(crate) cell: i64, + pub(crate) token: i32, +} + /// Implemented only by Root's actual draft/cache/verification owner adapter. /// `Verified` retains ALL T real target residual rows and their actual target /// predictions. Neither an ID list nor this trait is a finite/origin certificate. @@ -56,14 +64,7 @@ pub(crate) trait OriginalDraftEngine { fn replay_target_kv(&mut self, verified: &Verified, p: i64, outputs: &[i32]) -> Result<()>; /// Select the real residual row a and target output a at cell p+a, run full /// draft layer, overwrite that KV cell identically, retain resulting R/token. - fn full_target_seed( - &mut self, - verified: &Verified, - row: usize, - cell: i64, - token: i32, - coupled: bool, - ) -> Result; + fn full_target_seed(&mut self, verified: &Verified, seed: TargetSeedRow, coupled: bool) -> Result; /// Consume the previous ACTUAL draft R/token held by this adapter. Cell is /// p+a+j; sampler counter is cell+1, not the current target window row. fn full_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, coupled: bool) -> Result; @@ -156,7 +157,8 @@ impl DraftPreparation { engine.replay_target_kv(verified, p, outputs)?; let cell = p.checked_add(a as i64).ok_or(Error::Overflow)?; let mut batch = DraftBatch::empty(); - batch.push(engine.full_target_seed(verified, a, cell, outputs[a], coupled)?, self.vocabulary)?; + let seed = TargetSeedRow { row: a, cell, token: outputs[a] }; + batch.push(engine.full_target_seed(verified, seed, coupled)?, self.vocabulary)?; self.chain(&mut batch, cell, min_p, |next_cell, j, previous| { engine.full_chain_step(next_cell, j, previous, coupled) })?; From cf888462ad657635ec14f1a2d4438c31c4400bd6 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:23:36 +0100 Subject: [PATCH 37/42] STRA-338 params e04: output head row, QSA scratch loan and resident scalar row take domain structs Files: crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/host_attention.rs --- .../qwen_forward/executor/step_layer_fns.rs | 6 ++- .../impl_qwenforward_3/host_attention.rs | 6 ++- .../src/qwen_forward/output.rs | 13 ++++++ .../impl_outputstage/impl_outputstage_2.rs | 23 +++++------ .../impl_outputstage/impl_outputstage_2_2.rs | 12 +++--- .../src/qwen_forward/qsa_attention_scratch.rs | 12 +++++- .../src/qwen_forward/qsa_resident_scalar.rs | 39 +++++++++++++++++- .../qsa_resident_scalar/driver_fn.rs | 33 +++++++-------- .../impl_residentqsascalar.rs | 40 +++++++------------ .../project_gated_out_fn.rs | 18 ++++----- 10 files changed, 120 insertions(+), 82 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs index d8e7ed60..855af9a3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs @@ -271,8 +271,10 @@ fn qsa_attention_indexed( layer, prepared, txn, - dense_cache, - dense_cache.and_then(DenseWeightCache::qsa_attention_workspace), + crate::qwen_forward::qsa_attention::attention_scratch::QsaScratchLoan { + cache: dense_cache, + scratch: dense_cache.and_then(DenseWeightCache::qsa_attention_workspace), + }, ), )?; Ok(attention) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/host_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/host_attention.rs index af416152..2fc27c3b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/host_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3/host_attention.rs @@ -104,8 +104,10 @@ impl QwenForward { layer, prepared, txn, - Some(dense), - dense.qsa_attention_workspace(), + crate::qwen_forward::qsa_attention::attention_scratch::QsaScratchLoan { + cache: Some(dense), + scratch: dense.qsa_attention_workspace(), + }, ), ) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output.rs index bc2ddc4a..7845caea 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output.rs @@ -47,6 +47,19 @@ pub(super) struct FiniteLogits { values: LogitValues, } +/// The logits row being produced: the binding it belongs to, the token it follows and the position it is for. +pub(super) struct LogitsRow { + binding: BindingIdentity, + token: TokenId, + position: Position, +} + +/// The injected residual of the final layer a compact argmax was computed for, with that layer. +pub(super) struct ResidualAtLayer<'a> { + residual: &'a InjectedResidual, + layer: LayerId, +} + /// Authentic selected head result for one real pending final row. The private /// constructor below consumes a completed vocabulary witness; callers cannot /// substitute an arbitrary token as the MTP shifted final input. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs index 0d2d45f2..a0011d02 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs @@ -21,8 +21,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if self.sampler_wants(completed.position())? { return Err(Error::Unsupported(Stage::Output)); } - let logits = - self.project_mixed(binding.identity(), completed.token(), completed.position(), &mixed, context, false)?; + let row = LogitsRow { binding: binding.identity(), token: completed.token(), position: completed.position() }; + let logits = self.project_mixed(row, &mixed, context, false)?; self.certify_prompt_logits(binding, completed, txn, logits) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -154,7 +154,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { } let logits = self.head_logits(identity, (token, position), &mixed, txn)?; if matches!(&logits.values, LogitValues::Compact(_)) { - self.finish_compact_step(binding, residual, txn, layer, &logits)?; + self.finish_compact_step(binding, ResidualAtLayer { residual, layer }, txn, &logits)?; } Ok(logits) } @@ -209,18 +209,19 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { txn: &mut QwenStepTxn, ) -> Result { let sampled = self.sampler_wants(position)?; - let logits = self.project_mixed(identity, token, position, mixed, txn.cuda_context()?, sampled)?; + let row = LogitsRow { binding: identity, token, position }; + let logits = self.project_mixed(row, mixed, txn.cuda_context()?, sampled)?; if sampled { self.sample_complete(logits) } else { Ok(logits) } } /// The compact argmax is only accepted when the step is still the one it was computed for. fn finish_compact_step( &self, binding: &ModelBinding, - residual: &InjectedResidual, + final_residual: ResidualAtLayer<'_>, txn: &mut QwenStepTxn, - layer: LayerId, logits: &FiniteLogits, ) -> Result<()> { + let ResidualAtLayer { residual, layer } = final_residual; let (token, position) = (txn.token(), txn.position()); let current = binding.identity(); txn.validate_binding(¤t)?; @@ -258,14 +259,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if self.sampler_wants(mixed.frame().position())? { return Err(Error::Unsupported(Stage::Output)); } - let logits = self.project_mixed( - identity, - mixed.frame().token(), - mixed.frame().position(), - mixed.values(), - context, - false, - )?; + let row = LogitsRow { binding: identity, token: mixed.frame().token(), position: mixed.frame().position() }; + let logits = self.project_mixed(row, mixed.values(), context, false)?; if matches!(&logits.values, LogitValues::Compact(_)) { self.finish_compact_mtp(binding, mixed, session, &logits)?; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs index b6fb7cf4..52d5f7c7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs @@ -120,9 +120,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { pub(in super::super) fn project_mixed( &self, - identity: BindingIdentity, - token: TokenId, - position: Position, + row: LogitsRow, mixed: &[f32], context: &Context<'_>, force_full: bool, @@ -131,8 +129,9 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Head); if self.wants_compact(force_full)? { - return self.project_mixed_compact(identity, token, position, mixed, context); + return self.project_mixed_compact(row, mixed, context); } + let LogitsRow { binding: identity, token, position } = row; self.check_projection(&identity, mixed, context)?; let mut decoded_logits = None; self.with_projected(context, mixed, |candidate| { @@ -172,12 +171,11 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { pub(in super::super) fn project_mixed_compact( &self, - identity: BindingIdentity, - token: TokenId, - position: Position, + row: LogitsRow, mixed: &[f32], context: &Context<'_>, ) -> Result { + let LogitsRow { binding: identity, token, position } = row; self.check_projection(&identity, mixed, context)?; let mut selection = None; self.with_projected(context, mixed, |candidate| { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs index 34e9f73c..3e6254e7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs @@ -266,6 +266,14 @@ impl Drop for QsaAttentionLease<'_, '_, '_> { } } +/// The dense weight cache and the attention scratch that enable the selected QSA decode; when either is missing the +/// plain decode runs instead. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct QsaScratchLoan<'a, 'c, 's> { + pub(in crate::qwen_forward) cache: Option<&'a DenseWeightCache<'c>>, + pub(in crate::qwen_forward) scratch: Option<&'a RefCell>>, +} + // New explicit seam only. None/non-selected delegates the entire original body. impl QsaAttentionStage { pub(in crate::qwen_forward) fn decode_with_scratch( @@ -273,9 +281,9 @@ impl QsaAttentionStage { layer: LayerId, prepared: QsaPrepared, txn: &mut QwenStepTxn, - cache: Option<&DenseWeightCache<'_>>, - scratch: Option<&RefCell>>, + loan: QsaScratchLoan<'_, '_, '_>, ) -> Result { + let QsaScratchLoan { cache, scratch } = loan; let (Some(scratch), Some(cache)) = (scratch, cache) else { return Self::decode(binding, layer, prepared, txn, cache); }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs index 4e829bda..2f09d528 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs @@ -30,8 +30,43 @@ pub(in crate::qwen_forward) struct ResidentQsaScalarReady<'source, 'ctx> { seal: ResidentQsaSeal<'ctx>, } /// The attention, transport and gate owners of one scalar row. -type ScalarOwners<'a, 'ctx> = - (&'a mut QsaNativeDecode<'ctx>, &'a mut OriginalQsaResidentTransport<'ctx>, &'a mut QsaNativeGate<'ctx>); +pub(in crate::qwen_forward) struct ScalarOwners<'a, 'ctx> { + attention: &'a mut QsaNativeDecode<'ctx>, + stage: &'a mut OriginalQsaResidentTransport<'ctx>, + gate_owner: &'a mut QsaNativeGate<'ctx>, +} +/// The checked step one scalar row is processed for: the model binding, the dense weight cache, the step transaction +/// and the input residual. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ScalarStep<'a, 'weights, 'source, 'ctx> { + binding: &'a ModelBinding, + cache: &'weights DenseWeightCache<'ctx>, + txn: &'a QwenStepTxn<'a, 'a>, + input: &'source ResidualReady, +} +/// The layer a scalar row continues and the prior lineage (index and KV prefix) it continues from. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ScalarContinuation<'a, 'ctx> { + layer: LayerId, + prior: &'a ResidentQsaPrior<'ctx>, +} +/// The model binding and its dense weight cache, which a gate-and-Out launch reads weights through. +#[derive(Clone, Copy)] +struct BoundDense<'a, 'ctx> { + binding: &'a ModelBinding, + cache: &'a DenseWeightCache<'ctx>, +} +/// The attended values of a row and the head-gate slice they are gated with. +#[derive(Clone, Copy)] +struct GateRows<'a> { + attended: &'a [f32], + gate: &'a [f32], +} +/// The gate owner and the native batch workspace a gate-and-Out launch runs on. +struct GateDevices<'a, 'ctx> { + owner: &'a mut QsaNativeGate<'ctx>, + workspace: &'a mut NativeBatchWorkspace<'ctx>, +} /// The five host projections of one input row and the head-gate slice of the full Q. struct ScalarHost { raw: Box<[f32]>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/driver_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/driver_fn.rs index 8503c275..aab20ad4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/driver_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/driver_fn.rs @@ -86,30 +86,28 @@ impl<'ctx> ResidentQsaLayer<'ctx> { /// The guards of `prepare_scalar` before any projection: the step, the lineage, the weights and the input. pub(super) fn scalar_guards<'w>( &self, - binding: &ModelBinding, - cache: &'w DenseWeightCache<'ctx>, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &ResidualReady, - prior: &ResidentQsaPrior<'ctx>, + step: ScalarStep<'_, 'w, '_, 'ctx>, + continuation: ScalarContinuation<'_, 'ctx>, ) -> Result<(&'ctx Context<'ctx>, &'w QsaResident, Rc<()>)> { + let ScalarStep { binding, cache, txn, input } = step; + let ScalarContinuation { layer, prior } = continuation; check_scalar_txn(txn, binding, input, layer, prior)?; let context = cache.retained_context(binding, txn.cuda_context()?)?; cache.validate(binding)?; let entry = cache.qsa(binding, layer.get())?; - self.check_scalar_prior(binding, txn, layer, prior, (context, entry))?; + self.check_scalar_prior(step, continuation, (context, entry))?; validate_values(input.mixed(), 2560)?; check_scalar_shapes(entry)?; Ok((context, entry, txn.residual_handoff_owner()?)) } pub(super) fn check_scalar_prior( &self, - binding: &ModelBinding, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - prior: &ResidentQsaPrior<'ctx>, + step: ScalarStep<'_, '_, '_, 'ctx>, + continuation: ScalarContinuation<'_, 'ctx>, (context, entry): (&Context<'ctx>, &QsaResident), ) -> Result<()> { + let ScalarStep { binding, txn, .. } = step; + let ScalarContinuation { layer, prior } = continuation; if !self.current.same_prior(prior) || layer != prior.layer() || prior.next_position() != txn.position().get() @@ -123,19 +121,16 @@ impl<'ctx> ResidentQsaLayer<'ctx> { self.index.validate_checkpoint(&prior.0.index).map_err(driver)?; self.kv.validate_prefix(&prior.0.kv).map_err(driver) } - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn prepare_scalar<'source, 'lease, 'index, 'weights>( &'index mut self, - binding: &ModelBinding, - cache: &'weights DenseWeightCache<'ctx>, - txn: &QwenStepTxn<'_, '_>, - layer: LayerId, - input: &'source ResidualReady, - prior: &ResidentQsaPrior<'ctx>, + step: ScalarStep<'_, 'weights, 'source, 'ctx>, + continuation: ScalarContinuation<'_, 'ctx>, owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - let (context, entry, transaction) = self.scalar_guards(binding, cache, txn, layer, input, prior)?; + let ScalarStep { binding, cache, txn, input } = step; + let ScalarContinuation { layer, prior } = continuation; + let (context, entry, transaction) = self.scalar_guards(step, continuation)?; let host = ScalarHost::gather(context, binding, cache, entry, input)?; let norms = cache.qsa_norms(entry)?; let selected = host.select(owner, (&mut self.index, &prior.0.index), norms, workspace)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs index 0dbf06d2..f4454537 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs @@ -66,67 +66,57 @@ impl<'source, 'lease, 'index, 'weights, 'ctx> ResidentQsaScalar<'source, 'lease, } pub(super) fn gate_out( &self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + step: ScalarStep<'_, '_, '_, 'ctx>, attended: &[f32], - gate_owner: &mut QsaNativeGate<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, + devices: GateDevices<'_, 'ctx>, ) -> Result> { - let failed = cache.transport_failure_flag(binding, self.context)?; + let dense = BoundDense { binding: step.binding, cache: step.cache }; let provider = self.provider.as_ref(); - gate_and_out(binding, cache, self.context, provider, attended, &self.gate, gate_owner, workspace, &failed) + gate_and_out(dense, self.context, provider, GateRows { attended, gate: &self.gate }, devices) } /// The device work of one scalar row: append, attend, gate and Out; the seal or the abort follows. pub(super) fn run( &mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - txn: &QwenStepTxn<'_, '_>, - input: &ResidualReady, - (attention, stage, gate_owner): ScalarOwners<'_, 'ctx>, + step: ScalarStep<'_, '_, '_, 'ctx>, + owners: ScalarOwners<'_, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, ) -> Result<(Box<[f32]>, OriginalQsaMappedAppend)> { + let ScalarStep { binding, cache, txn, input } = step; + let ScalarOwners { attention, stage, gate_owner } = owners; self.validate(binding, cache, txn, input)?; super::super::super::admit_budget(self.context)?; let append = self.kv.append_resident_decode(workspace, stage, &self.prior.0.kv, &self.selected).map_err(driver)?; let attended = self.attend(workspace, attention, &append)?; validate_values(&attended, 6144)?; - let values = self.gate_out(binding, cache, &attended, gate_owner, workspace)?; + let values = self.gate_out(step, &attended, GateDevices { owner: gate_owner, workspace: &mut *workspace })?; self.validate(binding, cache, txn, input)?; validate_values(&values, 2560)?; Ok((values, append)) } - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn complete( mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - txn: &QwenStepTxn<'_, '_>, - input: &ResidualReady, - attention: &mut QsaNativeDecode<'ctx>, - stage: &mut OriginalQsaResidentTransport<'ctx>, - gate_owner: &mut QsaNativeGate<'ctx>, + step: ScalarStep<'_, '_, '_, 'ctx>, + owners: ScalarOwners<'_, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - match self.run(binding, cache, txn, input, (attention, stage, gate_owner), workspace) { + match self.run(step, owners, &mut *workspace) { Err(primary) => { let index = self.selected.abort(workspace).map_err(driver); let kv = self.kv.rollback(workspace, &self.prior.0.kv).map_err(driver); let _ = (index, kv); Err(primary) } - Ok((values, append)) => self.seal_ready(binding, cache, txn, workspace, (values, append)), + Ok((values, append)) => self.seal_ready(step, workspace, (values, append)), } } pub(super) fn seal_ready( self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - txn: &QwenStepTxn<'_, '_>, + step: ScalarStep<'_, '_, '_, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, (values, append): (Box<[f32]>, OriginalQsaMappedAppend), ) -> Result> { + let ScalarStep { binding, cache, txn, .. } = step; let Self { binding: id, context, layer, source, prior, provider, transaction, selected, kv: journal, .. } = self; let index = selected.seal(workspace, 1).map_err(driver); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs index 8400bd02..48dc752e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs @@ -54,21 +54,21 @@ pub(super) fn release_gate_buffers(buffers: GateBuffers<'_>) -> Result<()> { } cleanup } -#[allow(clippy::too_many_arguments)] // Actual role-specific weights and closed current finite inputs. +// Actual role-specific weights and closed current finite inputs. pub(super) fn gate_and_out<'ctx>( - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, + dense: BoundDense<'_, 'ctx>, context: &'ctx Context<'ctx>, weights: &QsaWeights, - attended: &[f32], - gate: &[f32], - owner: &mut QsaNativeGate<'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - failed: &Cell, + rows: GateRows<'_>, + devices: GateDevices<'_, 'ctx>, ) -> Result> { + let BoundDense { binding, cache } = dense; + let GateRows { attended, gate } = rows; + let GateDevices { owner, workspace } = devices; + let failed = cache.transport_failure_flag(binding, context)?; let mut buffers: GateBuffers<'ctx> = std::array::from_fn(|_| None); let operation = (|| { - upload_gate_inputs(&mut buffers, context, (attended, gate), failed)?; + upload_gate_inputs(&mut buffers, context, (attended, gate), &failed)?; apply_gate(&mut buffers, owner, workspace)?; project_gated_out(&mut buffers, (binding, cache), context, weights) })(); From 2995c6cabd3eed0e62e44016a47e7cf9d7a8d7c0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:26:46 +0100 Subject: [PATCH 38/42] STRA-338 params e03: prompt transaction takes PromptWeights/DraftRollback/PromptPublication/ParkedPoint, QSA seal takes ResidentSealOwners, cached decode takes SelectedKv --- .../impl_drop_for_originalpromptexecutor.rs | 29 ++++++------------- .../impl_originalpromptexecutor_2_2.rs | 4 ++- .../impl_originalpromptexecutor.rs | 5 +++- .../produce_original_gdn_fn.rs | 7 +++-- .../qsa_attention/impl_qsaready.rs | 15 +++++++--- .../src/qwen_forward/qsa_resident_device.rs | 1 + .../impl_residentqsacompleted.rs | 18 ++++++++---- .../qwen_forward/session_original_prompt.rs | 9 ++++++ .../impl_qwensession.rs | 22 +++++++------- .../impl_originalprompttxn_2_2.rs | 8 ++--- .../impl_originalprompttxn_3.rs | 9 +++--- .../prompt_txn_owners.rs | 25 ++++++++++++++++ 12 files changed, 98 insertions(+), 54 deletions(-) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/prompt_txn_owners.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs index e85d1238..cfe738c0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs @@ -4,6 +4,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::session::original_prompt::{DraftRollback, PromptPublication, PromptWeights}; impl Drop for OriginalPromptExecutor<'_> { fn drop(&mut self) { @@ -14,15 +15,11 @@ impl OriginalPromptPending<'_, '_, '_> { /// Any fallible publication leaves the owning transaction present so Drop /// restores both real physical accepted prefixes. Success consumes it. pub(in crate::qwen_forward) fn publish(mut self) -> Result<(TargetStepOrigin, Option)> { - let result = self.txn.as_mut().ok_or(Error::IdentityMismatch)?.publish( - self.binding, - self.dense, - self.layers, - &self.completed, - self.draft, - &self.draft_kv, - &self.sample, - ); + let weights = PromptWeights { binding: self.binding, dense: self.dense }; + let publication = + PromptPublication { completed: &self.completed, draft_kv: &self.draft_kv, sample: &self.sample }; + let txn = self.txn.as_mut().ok_or(Error::IdentityMismatch)?; + let result = txn.publish(weights, self.layers, publication, self.draft); if result.is_ok() { self.txn.take(); } @@ -32,17 +29,9 @@ impl OriginalPromptPending<'_, '_, '_> { impl Drop for OriginalPromptPending<'_, '_, '_> { fn drop(&mut self) { if let Some(txn) = self.txn.take() { - if txn - .abort_with_draft( - self.binding, - self.dense, - self.layers, - &self.checkpoint, - self.draft, - &self.draft_checkpoint, - ) - .is_err() - { + let weights = PromptWeights { binding: self.binding, dense: self.dense }; + let rollback = DraftRollback { draft: self.draft, prior: &self.draft_checkpoint }; + if txn.abort_with_draft(weights, self.layers, &self.checkpoint, rollback).is_err() { *self.failed = true; } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs index 47500c64..ecb9b6ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::session::original_prompt::{ParkedPoint, PromptWeights}; /// The index image and mapped K/V journal of each of the twelve resident QSA layers, by layer slot. type QsaOwners<'ctx> = @@ -153,7 +154,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { if self.failed || self.context.is_poisoned() { return Err(Error::CudaExecution); } - let imported = session.import_parked(binding, dense, &mut self.layers, parked, blocks); + let weights = PromptWeights { binding, dense }; + let imported = session.import_parked(weights, &mut self.layers, ParkedPoint { session: parked, blocks }); if imported.is_err() { self.failed = true; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs index f87ade97..ac448979 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::session::original_prompt::{DraftRollback, PromptWeights}; #[path = "impl_originalpromptexecutor/forward_draft.rs"] mod forward_draft; @@ -204,7 +205,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { if moe.end_prompt_stream().is_err() { self.failed = true; } - let cleanup = txn.abort_with_draft(binding, dense, &mut self.layers, checkpoint, draft, draft_checkpoint); + let weights = PromptWeights { binding, dense }; + let rollback = DraftRollback { draft, prior: draft_checkpoint }; + let cleanup = txn.abort_with_draft(weights, &mut self.layers, checkpoint, rollback); if cleanup.is_err() || self.context.is_poisoned() { self.failed = true; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs index ab934c04..c4d99217 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs @@ -7,7 +7,7 @@ use super::*; use super::super::super::gdn::chunk_device::{ChunkEdge, GdnChunkDevice}; use super::super::super::gdn::{GdnPrior, PromptLayer, PromptProgram, PromptSource}; use super::super::super::qsa_index::prompt_device::resident_device::{ - ResidentQsaCompleted, ResidentQsaLayer, ResidentQsaPrior, ResidentQsaSelection, + ResidentQsaCompleted, ResidentQsaLayer, ResidentQsaPrior, ResidentQsaSelection, ResidentSealOwners, }; use super::super::super::session::chunk::{GdnChunkRow, GdnChunkSeal, GdnChunkStart}; use std::cell::RefMut; @@ -206,8 +206,9 @@ impl<'a, 's, 'ctx> QsaLayerRun<'a, 's, 'ctx> { completed.validate_rows(self.binding, self.dense, session, &self.inputs)?; self.lap.at(4, "validate_rows"); let accepted = self.txn.len(); - let ws = &mut self.workspace; - let seal = completed.seal_prefix(self.binding, self.dense, session, &self.inputs, qsa, ws, accepted)?; + let (binding, cache, workspace) = (self.binding, self.dense, &mut self.workspace); + let owners = ResidentSealOwners { binding, cache, session, producer: qsa, workspace }; + let seal = completed.seal_prefix(owners, &self.inputs, accepted)?; self.lap.at(5, "seal_prefix"); drop(self.workspace); self.txn.stage_qsa(self.binding, self.dense, seal)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs index aa86874f..fe1bdf93 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs @@ -88,7 +88,7 @@ impl QsaAttentionStage { let context = txn.cuda_context()?; admit_budget(context)?; if let Some(cache) = cache { - return decode_cached(binding, &prepared, context, cache, &k, &v, width); + return decode_cached(binding, &prepared, context, cache, SelectedKv { keys: &k, values: &v, width }); } Self::decode_host(binding, &prepared, context, (&k, &v), width) } @@ -192,15 +192,22 @@ impl<'ctx> QsaGated<'ctx> { primary.map_or(cleanup, Err) } } +/// The canonical halfword pages of the selected keys and values and the width of the selection they were copied for. +#[derive(Clone, Copy)] +pub(super) struct SelectedKv<'a> { + pub(super) keys: &'a [u8], + pub(super) values: &'a [u8], + pub(super) width: u32, +} + pub(super) fn decode_cached( binding: &ModelBinding, prepared: &QsaPrepared, context: &Context<'_>, cache: &DenseWeightCache<'_>, - keys: &[u8], - values: &[u8], - width: u32, + selected: SelectedKv<'_>, ) -> Result { + let SelectedKv { keys, values, width } = selected; let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; let attended = attend_retained(context, prepared.q(), keys, values, width, failed)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs index 9adcc71b..beebc703 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs @@ -87,6 +87,7 @@ pub(in crate::qwen_forward) use scalar::{ResidentQsaScalar, ResidentQsaScalarRea #[path = "qsa_resident_device/impl_residentqsacompleted.rs"] mod impl_residentqsacompleted; +pub(in crate::qwen_forward) use impl_residentqsacompleted::ResidentSealOwners; #[path = "qsa_resident_device/impl_residentqsalayer.rs"] mod impl_residentqsalayer; #[path = "qsa_resident_device/impl_residentqsalayer_2.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs index 106d3be7..5e581408 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs @@ -4,6 +4,16 @@ use super::impl_residentqsalayer::mint; use super::*; +/// The owners a resident QSA prefix seal validates against and commits through: model binding, dense weight cache, +/// original session, prompt producer and native batch workspace. +pub(in crate::qwen_forward) struct ResidentSealOwners<'a, 'ctx> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>, + pub(in crate::qwen_forward) session: &'a QwenSession<'ctx>, + pub(in crate::qwen_forward) producer: &'a mut OriginalQsaResidentPromptDevice<'ctx>, + pub(in crate::qwen_forward) workspace: &'a mut NativeBatchWorkspace<'ctx>, +} + impl<'index, 'weights, 'ctx> ResidentQsaCompleted<'index, 'weights, 'ctx> { pub(in crate::qwen_forward) fn first(&self) -> u64 { self.prior.next_position() @@ -95,17 +105,13 @@ impl<'index, 'weights, 'ctx> ResidentQsaCompleted<'index, 'weights, 'ctx> { txn.validate_input(id.token(), id.position())?; Ok((local, id)) } - #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn seal_prefix( mut self, - binding: &ModelBinding, - cache: &DenseWeightCache<'ctx>, - session: &QwenSession<'ctx>, + owners: ResidentSealOwners<'_, 'ctx>, inputs: &[&InputReady], - producer: &mut OriginalQsaResidentPromptDevice<'ctx>, - ws: &mut NativeBatchWorkspace<'ctx>, accepted: usize, ) -> Result> { + let ResidentSealOwners { binding, cache, session, producer, workspace: ws } = owners; self.validate_rows(binding, cache, session, inputs)?; if accepted > self.rows() { return Err(Error::InvalidPosition); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs index 84a62ed8..df6fabdc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs @@ -9,6 +9,9 @@ use super::*; use std::cell::{Cell, RefCell}; #[path = "session_original_draft.rs"] pub(in crate::qwen_forward) mod draft; +#[path = "session_original_prompt/prompt_txn_owners.rs"] +mod prompt_txn_owners; +pub(in crate::qwen_forward) use prompt_txn_owners::{DraftRollback, PromptPublication, PromptWeights}; /// Actual tokenized request owner. Known-next conditioning IDs are read from /// this same immutable input, never from a sampled or caller-labelled token. @@ -39,6 +42,12 @@ pub(in crate::qwen_forward) struct ParkedSession { gdn: [Option; STATE_CAPACITY], tails: [Option>; STATE_CAPACITY], } +/// A parked session point and the blocks that hold the cells below its position. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct ParkedPoint<'a> { + pub(in crate::qwen_forward) session: &'a ParkedSession, + pub(in crate::qwen_forward) blocks: &'a [&'a ParkedBlock], +} /// The cells `first_token .. first_token + tokens` of every resident QSA layer, as plain bytes. pub(in crate::qwen_forward) struct ParkedBlock { first_token: usize, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs index 08173b5b..8d06668c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs @@ -259,8 +259,9 @@ impl<'driver> QwenSession<'driver> { &self, binding: &ModelBinding, layers: &[Option>; STATE_CAPACITY], - (parked, blocks): (&ParkedSession, &[&ParkedBlock]), + point: ParkedPoint<'_>, ) -> Result<()> { + let ParkedPoint { session: parked, blocks } = point; self.target_origin()?; if !self.binding.matches(&binding.identity()) || self.layer_count != 48 @@ -282,12 +283,13 @@ impl<'driver> QwenSession<'driver> { /// Write every layer's parked cells and re-mint its witness, attempting all of them; the first failure is returned. fn import_layers( &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'driver>, + weights: PromptWeights<'_, 'driver>, layers: &mut [Option>; STATE_CAPACITY], - (parked, blocks): (&ParkedSession, &[&ParkedBlock]), + point: ParkedPoint<'_>, workspace: &mut leleka_cuda_driver::NativeBatchWorkspace<'driver>, ) -> Result<(RestoredLayers<'driver>, Option)> { + let PromptWeights { binding, dense } = weights; + let ParkedPoint { session: parked, blocks } = point; let mut restored = std::array::from_fn(|_| None); let mut first_error = None; let end = usize::try_from(parked.position).map_err(|_| Error::Overflow)?; @@ -332,16 +334,16 @@ impl<'driver> QwenSession<'driver> { /// is bumped first, fencing every older checkpoint. pub(in crate::qwen_forward) fn import_parked( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'driver>, + weights: PromptWeights<'_, 'driver>, layers: &mut [Option>; STATE_CAPACITY], - parked: &ParkedSession, - blocks: &[&ParkedBlock], + point: ParkedPoint<'_>, ) -> Result<()> { - self.check_import(binding, layers, (parked, blocks))?; + let PromptWeights { binding, dense } = weights; + let parked = point.session; + self.check_import(binding, layers, point)?; self.fence_import_branch()?; let mut workspace = self.import_workspace(binding, dense)?; - let (restored, first_error) = self.import_layers(binding, dense, layers, (parked, blocks), &mut workspace)?; + let (restored, first_error) = self.import_layers(weights, layers, point, &mut workspace)?; drop(workspace); self.fail_first(first_error)?; self.complete_cuda()?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs index 37282b8c..7ad3aee8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs @@ -146,13 +146,13 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> { /// inferred from a requested position or the draft's end metadata. pub(in crate::qwen_forward) fn abort_with_draft( self, - binding: &ModelBinding, - dense: &DenseWeightCache<'driver>, + weights: PromptWeights<'_, 'driver>, layers: &mut [Option>; STATE_CAPACITY], checkpoint: &OriginalSessionCheckpoint<'driver>, - draft: &mut draft::OriginalDraftSession<'driver>, - prior: &draft::OriginalDraftCheckpoint, + rollback: DraftRollback<'_, 'driver>, ) -> Result<()> { + let PromptWeights { binding, dense } = weights; + let DraftRollback { draft, prior } = rollback; self.phase.failed.set(true); let mut first = draft.restore_physical(binding, dense, prior).err(); if let Err(error) = self.session.restore_original_checkpoint(binding, dense, layers, checkpoint) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs index 4e9a4bbf..646134b4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs @@ -142,14 +142,13 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> { /// No host QsaIndexPrior is fabricated from an end-only resident checkpoint. pub(in crate::qwen_forward) fn publish( &mut self, - binding: &ModelBinding, - dense: &DenseWeightCache<'driver>, + weights: PromptWeights<'_, 'driver>, layers: &mut [Option>; STATE_CAPACITY], - completed: &super::super::super::super::prompt_device_rows::PromptDeviceFinal, + publication: PromptPublication<'_>, draft: &mut draft::OriginalDraftSession<'driver>, - draft_kv: &super::super::super::super::prompt_device_rows::OriginalDraftKvPending, - sample: &super::super::super::super::output::OriginalPromptSample, ) -> Result<(TargetStepOrigin, Option)> { + let PromptWeights { binding, dense } = weights; + let PromptPublication { completed, draft_kv, sample } = publication; self.validate_publish_inputs(binding, completed, draft_kv, sample)?; let draft_permit = draft.prepare_publication(binding, self, draft_kv.completed())?; let end = Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/prompt_txn_owners.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/prompt_txn_owners.rs new file mode 100644 index 00000000..012fc09a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/prompt_txn_owners.rs @@ -0,0 +1,25 @@ +//! The owners and inputs a prompt transaction is published, aborted or imported with, grouped by meaning. + +use super::draft::{OriginalDraftCheckpoint, OriginalDraftSession}; +use super::*; + +/// The model binding and the dense weight cache a prompt transaction validates and restores against. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct PromptWeights<'a, 'driver> { + pub(in crate::qwen_forward) binding: &'a ModelBinding, + pub(in crate::qwen_forward) dense: &'a DenseWeightCache<'driver>, +} + +/// The draft session of a prompt transaction and the checkpoint a failed prompt restores it to. +pub(in crate::qwen_forward) struct DraftRollback<'a, 'driver> { + pub(in crate::qwen_forward) draft: &'a mut OriginalDraftSession<'driver>, + pub(in crate::qwen_forward) prior: &'a OriginalDraftCheckpoint, +} + +/// The final device rows, the pending draft K/V and the sampled token a prompt publication commits together. +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) struct PromptPublication<'a> { + pub(in crate::qwen_forward) completed: &'a crate::qwen_forward::prompt_device_rows::PromptDeviceFinal, + pub(in crate::qwen_forward) draft_kv: &'a crate::qwen_forward::prompt_device_rows::OriginalDraftKvPending, + pub(in crate::qwen_forward) sample: &'a crate::qwen_forward::output::OriginalPromptSample, +} From 7fedb835fe2c4886540654ca8faa48a685d1df8a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:27:44 +0100 Subject: [PATCH 39/42] STRA-338 params e02: rename mechanically named modules of the touched families (prompt_chunk_forward, executor_construction, read_completion, resident_layer, native_projection_row, projection_rows, mtp_block, routed_and_shared_experts, batch_inject) --- .../impl_originalpromptexecutor_2.rs | 4 +- ...ptexecutor.rs => executor_construction.rs} | 0 .../impl_originalpromptexecutor_2_2.rs | 4 +- ...mptexecutor.rs => prompt_chunk_forward.rs} | 0 .../src/qwen_forward/gr_batch_chunk.rs | 4 +- .../{inject_batch_fns.rs => batch_inject.rs} | 0 .../gr_batch_chunk/impl_grstage_2.rs | 4 +- .../src/qwen_forward/moe_mmq_adaptive.rs | 2 +- .../src/qwen_forward/moe_mmq_chunk.rs | 6 +-- .../{resident_fns.rs => resident_layer.rs} | 0 .../src/qwen_forward/mtp_experts.rs | 38 +++++++++--------- .../{impl_mtpblock.rs => mtp_block.rs} | 0 ...ute_fn.rs => routed_and_shared_experts.rs} | 0 .../impl_promptdeviceread.rs | 2 +- ...omptdeviceread_2.rs => read_completion.rs} | 0 .../src/qwen_forward/qsa_prefill_batch.rs | 40 +++++++++---------- ...e_error_fn.rs => native_projection_row.rs} | 0 ...{concat_mixed_fn.rs => projection_rows.rs} | 0 18 files changed, 52 insertions(+), 52 deletions(-) rename crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/{impl_originalpromptexecutor.rs => executor_construction.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/{impl_originalpromptexecutor.rs => prompt_chunk_forward.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/{inject_batch_fns.rs => batch_inject.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/{resident_fns.rs => resident_layer.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/{impl_mtpblock.rs => mtp_block.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/{route_fn.rs => routed_and_shared_experts.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/{impl_promptdeviceread_2.rs => read_completion.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/{native_error_fn.rs => native_projection_row.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/{concat_mixed_fn.rs => projection_rows.rs} (100%) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs index 8b9b48f8..3ebc064b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs @@ -3,7 +3,7 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs"] -mod impl_originalpromptexecutor; +#[path = "impl_originalpromptexecutor_2/executor_construction.rs"] +mod executor_construction; #[path = "impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs"] mod impl_originalpromptexecutor_2_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/executor_construction.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/executor_construction.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs index 00ba2798..eba052f5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs @@ -3,7 +3,7 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs"] -mod impl_originalpromptexecutor; #[path = "impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs"] mod impl_originalpromptexecutor_2; +#[path = "impl_originalpromptexecutor_2_2/prompt_chunk_forward.rs"] +mod prompt_chunk_forward; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/prompt_chunk_forward.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/prompt_chunk_forward.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs index 16afb4c5..6b452834 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs @@ -53,9 +53,9 @@ mod impl_grmicroinput; pub(super) use impl_grmicroinput::micro_driver_error; #[allow(unused_imports)] pub(super) use impl_grmicroinput::save_micro_values; +#[path = "gr_batch_chunk/batch_inject.rs"] +mod batch_inject; #[path = "gr_batch_chunk/impl_grstage.rs"] mod impl_grstage; #[path = "gr_batch_chunk/impl_grstage_2.rs"] mod impl_grstage_2; -#[path = "gr_batch_chunk/inject_batch_fns.rs"] -mod inject_batch_fns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/batch_inject.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/batch_inject.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs index b5d66de1..121b48eb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs @@ -1,9 +1,9 @@ //! Moved out of the parent module by STRA-338: impl GrStage. #[allow(unused_imports)] -use super::inject_batch_fns::{device_inject, gather_batch}; +use super::batch_inject::{device_inject, gather_batch}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -use super::inject_batch_fns::{finish_queued, queued_inject}; +use super::batch_inject::{finish_queued, queued_inject}; use super::*; impl GrStage { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs index c1c0d9b9..ba6f455c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs @@ -9,7 +9,7 @@ use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer}; mod gather_fns; #[path = "moe_mmq_adaptive/walk_fns.rs"] mod walk_fns; -use super::resident_fns::{LayerResources, Resident, RoutedGroups}; +use super::resident_layer::{LayerResources, Resident, RoutedGroups}; use walk_fns::{SlotState, Walk}; pub(super) fn execute_adaptive_groups<'ctx>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index 1ccbf8ec..f0d477ac 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -8,10 +8,10 @@ mod admission_fns; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_mmq_adaptive.rs"] mod original_adaptive; -#[path = "moe_mmq_chunk/resident_fns.rs"] -mod resident_fns; +#[path = "moe_mmq_chunk/resident_layer.rs"] +mod resident_layer; use admission_fns::{mmq_triplets, rows_supported}; -use resident_fns::{Resident, execute_resident}; +use resident_layer::{Resident, execute_resident}; impl MoeExpertStage { pub(in crate::qwen_forward) fn execute_chunk_mmq<'ctx>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_layer.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_layer.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs index b6418c98..38896308 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs @@ -47,42 +47,42 @@ struct S2Tile { #[cfg(test)] mod tests; -mod impl_mtpblock; +mod mtp_block; #[allow(unused_imports)] -use impl_mtpblock::admit_input; +use mtp_block::admit_input; #[allow(unused_imports)] -use impl_mtpblock::compose_bound; +use mtp_block::compose_bound; #[allow(unused_imports)] -use impl_mtpblock::moe_driver_error; +use mtp_block::moe_driver_error; #[allow(unused_imports)] -use impl_mtpblock::route_mixed; +use mtp_block::route_mixed; #[allow(unused_imports)] -use impl_mtpblock::validate_route; -mod route_fn; +use mtp_block::validate_route; +mod routed_and_shared_experts; #[allow(unused_imports)] -use route_fn::combine_uploaded; +use routed_and_shared_experts::combine_uploaded; #[allow(unused_imports)] -use route_fn::compose; +use routed_and_shared_experts::compose; #[allow(unused_imports)] -use route_fn::down_tile; +use routed_and_shared_experts::down_tile; #[allow(unused_imports)] -use route_fn::gate_up_tile; +use routed_and_shared_experts::gate_up_tile; #[allow(unused_imports)] -use route_fn::route; +use routed_and_shared_experts::route; #[allow(unused_imports)] -use route_fn::routed; +use routed_and_shared_experts::routed; #[allow(unused_imports)] -use route_fn::routed_down; +use routed_and_shared_experts::routed_down; #[allow(unused_imports)] -use route_fn::routed_hidden; +use routed_and_shared_experts::routed_hidden; #[allow(unused_imports)] -use route_fn::routed_parts; +use routed_and_shared_experts::routed_parts; #[allow(unused_imports)] -use route_fn::scale_shared; +use routed_and_shared_experts::scale_shared; #[allow(unused_imports)] -use route_fn::shared; +use routed_and_shared_experts::shared; #[allow(unused_imports)] -use route_fn::shared_hidden; +use routed_and_shared_experts::shared_hidden; mod append_row_fn; #[allow(unused_imports)] use append_row_fn::append_row; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_block.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/impl_mtpblock.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_block.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/routed_and_shared_experts.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/route_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/routed_and_shared_experts.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs index 8da627d9..4d45c01a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs @@ -4,8 +4,8 @@ #[allow(unused_imports)] use super::*; -mod impl_promptdeviceread_2; mod produce_original_gdn_fn; +mod read_completion; pub(in crate::qwen_forward) use produce_original_gdn_fn::QsaLayerDevices; #[allow(unused_imports)] pub(super) use produce_original_gdn_fn::produce_original_gdn; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/read_completion.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/read_completion.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs index 3e8f9f06..53ae9e72 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs @@ -39,41 +39,41 @@ pub(super) struct NativeOutRow<'ctx> { #[path = "qsa_prefill_batch/projection_operands.rs"] mod projection_operands; pub(super) use projection_operands::{AttendedRows, AttentionRow, ChunkAttentionSlot, NativeQsaDevices}; -mod native_error_fn; +mod native_projection_row; #[allow(unused_imports)] -use native_error_fn::check_batch; +use native_projection_row::check_batch; #[allow(unused_imports)] -use native_error_fn::check_input; +use native_projection_row::check_input; #[allow(unused_imports)] -use native_error_fn::check_inputs; +use native_projection_row::check_inputs; #[allow(unused_imports)] -use native_error_fn::chunk_owners; +use native_projection_row::chunk_owners; #[allow(unused_imports)] -use native_error_fn::native; +use native_projection_row::native; #[allow(unused_imports)] -use native_error_fn::native_error; +use native_projection_row::native_error; #[allow(unused_imports)] -pub(super) use native_error_fn::project; +pub(super) use native_projection_row::project; #[allow(unused_imports)] -use native_error_fn::project_batches; -mod concat_mixed_fn; +use native_projection_row::project_batches; +mod projection_rows; #[allow(unused_imports)] -use concat_mixed_fn::check_batches; +use projection_rows::check_batches; #[allow(unused_imports)] -use concat_mixed_fn::check_shapes; +use projection_rows::check_shapes; #[allow(unused_imports)] -use concat_mixed_fn::concat_mixed; +use projection_rows::concat_mixed; #[allow(unused_imports)] -use concat_mixed_fn::gather_rows; +use projection_rows::gather_rows; #[allow(unused_imports)] -pub(super) use concat_mixed_fn::project_out; +pub(super) use projection_rows::project_out; #[allow(unused_imports)] -use concat_mixed_fn::project_rows; +use projection_rows::project_rows; #[allow(unused_imports)] -use concat_mixed_fn::ready_rows; +use projection_rows::ready_rows; #[allow(unused_imports)] -use concat_mixed_fn::retained_matrices; +use projection_rows::retained_matrices; #[allow(unused_imports)] -use concat_mixed_fn::row_values; +use projection_rows::row_values; #[allow(unused_imports)] -use concat_mixed_fn::split_rows; +use projection_rows::split_rows; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_projection_row.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_error_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/native_projection_row.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_rows.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/concat_mixed_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_rows.rs From 38674f47819b6508a10318d423ae9785e29ea990 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:28:01 +0100 Subject: [PATCH 40/42] STRA-338 params e04: keep the touched call sites within the 30-line function limit Files: none --- .../src/qwen_forward/bound_expert.rs | 11 +++++++ .../qwen_forward/executor/step_layer_fns.rs | 8 ++--- .../project_group_source_consumers_fn.rs | 33 +++++++++---------- .../qwen_forward/moe_group_resident_queue.rs | 14 ++++---- .../moe_mmq_chunk/resident_fns.rs | 3 +- .../impl_originalservestack_4/decode_steps.rs | 8 ++--- 6 files changed, 37 insertions(+), 40 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs index f95f9894..936a0d13 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/bound_expert.rs @@ -10,3 +10,14 @@ pub(in crate::qwen_forward) struct BoundExpert<'a> { pub(in crate::qwen_forward) weights: &'a MoeExpertWeights, pub(in crate::qwen_forward) selection: MoeExpertSelection, } + +impl<'a> BoundExpert<'a> { + /// The routed expert in `slot` of the weights admitted under `binding`. + pub(in crate::qwen_forward) fn routed( + binding: &'a ModelBinding, + weights: &'a MoeExpertWeights, + slot: usize, + ) -> Self { + Self { binding, weights, selection: MoeExpertSelection::Routed { slot } } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs index 855af9a3..5207604e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs @@ -2,6 +2,7 @@ #[allow(unused_imports)] use super::*; +use crate::qwen_forward::moe_expert::ExpertRowRequest; use crate::qwen_forward::qsa_attention::QsaReady; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -342,12 +343,7 @@ fn moe_ffn_inject( ForwardPhase::MoeExpert, layer.get(), pos, - MoeExpertStage::execute( - binding, - crate::qwen_forward::moe_expert::ExpertRowRequest { layer, route, input: ffn.ready() }, - txn, - moe_cache, - ), + MoeExpertStage::execute(binding, ExpertRowRequest { layer, route, input: ffn.ready() }, txn, moe_cache), )?; experts.validate_origin(&binding.identity())?; experts.identity().validate(token, pos, layer)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs index 1958d1be..c524a7cd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs @@ -14,6 +14,10 @@ use crate::model_binding::qwen4exp_input::MoeRoutedSourceScope; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use crate::qwen_forward::moe_weight_cache::RoutedSourceHealth; +/// The Down matrix of the only member of the routed source scope a direct group reads. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +const ONLY_MEMBER_DOWN: SourceMatrix = SourceMatrix { member: 0, role: MoeMatrixRole::Down }; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(clippy::too_many_arguments)] pub(super) fn project_group_source_consumers<'ctx>( @@ -184,24 +188,17 @@ impl<'ctx> DirectGroup<'_, 'ctx> { return Err(Error::Unsupported(Stage::Executor)); } scope.with_workspace(|workspace| { - cache.with_matrix_routed_source( - binding, - source, - SourceMatrix { member: 0, role: MoeMatrixRole::Down }, - |matrix, health, source| { - scope.project_columns_direct( - &selections, - |out, cancel| { - let input = hidden_buffer(hidden)?; - self.source_down_columns(workspace, matrix, kind, format, input, out, &selections, cancel) - }, - |down_source, cancel| { - self.source_copy_down(actual, packets, health, source, down_source, cancel) - }, - cancelled, - ) - }, - ) + cache.with_matrix_routed_source(binding, source, ONLY_MEMBER_DOWN, |matrix, health, source| { + scope.project_columns_direct( + &selections, + |out, cancel| { + let input = hidden_buffer(hidden)?; + self.source_down_columns(workspace, matrix, kind, format, input, out, &selections, cancel) + }, + |down_source, cancel| self.source_copy_down(actual, packets, health, source, down_source, cancel), + cancelled, + ) + }) })?; Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs index 1a2313f5..03e183b4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs @@ -3,6 +3,7 @@ use super::project_group_direct_fn::DirectGroup; use super::project_group_shared_fns::{down_format, gate_up_format, packet_targets}; use super::project_group_source_consumers_fn::check_source_members; use super::*; +use crate::qwen_forward::moe_weight_cache::TripletLoanRequest; use leleka_cuda_driver::{RoutedResidentOutputs, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights}; #[allow(clippy::too_many_arguments)] @@ -129,15 +130,12 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> { self.compose_copy(queue, raw, outputs, &mut observed_cancel, actual, packets, health, source) }) }; - let binding = self.group.binding; match ephemeral_slot { - Some(slot) => cache.with_ephemeral_triplet_routed_source( - crate::qwen_forward::moe_weight_cache::TripletLoanRequest { binding, member: 0, slot }, - source, - &cancel_observed, - consume, - ), - None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), + Some(slot) => { + let loan = TripletLoanRequest { binding: self.group.binding, member: 0, slot }; + cache.with_ephemeral_triplet_routed_source(loan, source, &cancel_observed, consume) + } + None => cache.with_adaptive_triplet_routed_source(self.group.binding, source, 0, consume), } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs index 01c2a3f1..0a0a13bb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk/resident_fns.rs @@ -311,8 +311,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> { let (first, row) = self.group_head(pairs)?; let indices = self.group_indices(row, first, pairs)?; let group = source.gather_gate_up(&indices).map_err(mmq_error)?; - let selection = MoeExpertSelection::Routed { slot: first.slot }; - let expert = BoundExpert { binding: self.binding, weights: &row.row().weights, selection }; + let expert = BoundExpert::routed(self.binding, &row.row().weights, first.slot); cache.with_mmq_triplet(expert, original_prompt, |gate, up, down| { let hidden = group.gate_up(gate, up).map_err(mmq_error)?; if cancelled() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs index 2f88ee78..1a4adabf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4/decode_steps.rs @@ -177,12 +177,8 @@ impl<'s, 'a, 'ctx> DecodeView<'s, 'a, 'ctx> { let channels = (&mut emit, &mut cancel); let (served, verifier, outcome) = serve_over_host(verifier, host, request, channels, env)?; let resources = DecodeResources { verifier, qsa, slots }; - let home = QsaOwnerHome { - executor: &mut *self.owners.executor, - binding: self.ids.binding, - dense: self.reads.dense, - session: &mut *self.owners.session, - }; + let (executor, session) = (&mut *self.owners.executor, &mut *self.owners.session); + let home = QsaOwnerHome { executor, binding: self.ids.binding, dense: self.reads.dense, session }; teardown_decode(resources, outcome, home, self.ids.context, &mut *self.book.broken); served } From fc18d971ea373cc2a3700db14a40ee5365c05647 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:28:13 +0100 Subject: [PATCH 41/42] STRA-338 params e03: rename mechanically named modules of the touched families (step_entries, step_core, step_layers, read_layer_attention, expert_gather, layer_walk, batched_window, scalar_window, draft_warm_and_window) --- .../src/qwen_forward/executor.rs | 14 +++++++------- .../src/qwen_forward/executor/impl_qwenforward.rs | 8 ++++---- .../{impl_qwenforward_2_2.rs => step_core.rs} | 4 ++-- .../{impl_qwenforward_2.rs => step_entries.rs} | 2 +- ...yer_attention_fn.rs => read_layer_attention.rs} | 0 .../executor/{step_layer_fns.rs => step_layers.rs} | 0 .../src/qwen_forward/moe_mmq_adaptive.rs | 10 +++++----- .../{gather_fns.rs => expert_gather.rs} | 2 +- .../{walk_fns.rs => layer_walk.rs} | 0 .../src/qwen_forward/mtp_decode/impl_mtpdecoder.rs | 6 +++--- .../{impl_mtpdecoder_2_2.rs => batched_window.rs} | 2 +- ...pl_mtpdecoder_2.rs => draft_warm_and_window.rs} | 2 +- .../{impl_mtpdecoder_3.rs => scalar_window.rs} | 2 +- 13 files changed, 26 insertions(+), 26 deletions(-) rename crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/{impl_qwenforward_2_2.rs => step_core.rs} (92%) rename crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/{impl_qwenforward_2.rs => step_entries.rs} (97%) rename crates/engine-qwen35-cuda/src/qwen_forward/executor/{read_layer_attention_fn.rs => read_layer_attention.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/executor/{step_layer_fns.rs => step_layers.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/{gather_fns.rs => expert_gather.rs} (99%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/{walk_fns.rs => layer_walk.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/{impl_mtpdecoder_2_2.rs => batched_window.rs} (99%) rename crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/{impl_mtpdecoder_2.rs => draft_warm_and_window.rs} (98%) rename crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/{impl_mtpdecoder_3.rs => scalar_window.rs} (99%) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs index 745eac7e..8b79f303 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs @@ -80,21 +80,21 @@ mod impl_prefillstepproduct; #[allow(unused_imports)] use impl_prefillstepproduct::diagnose; mod impl_qwenforward; -mod read_layer_attention_fn; -mod step_layer_fns; +mod read_layer_attention; +mod step_layers; mod step_request; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] -use read_layer_attention_fn::LayerEntry; +use read_layer_attention::LayerEntry; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] -use read_layer_attention_fn::prepare_layer_attention_micro; +use read_layer_attention::prepare_layer_attention_micro; #[allow(unused_imports)] -use read_layer_attention_fn::read_layer_attention; +use read_layer_attention::read_layer_attention; #[allow(unused_imports)] -use read_layer_attention_fn::validate_descriptors; +use read_layer_attention::validate_descriptors; #[allow(unused_imports)] -use read_layer_attention_fn::validate_layer_plan; +use read_layer_attention::validate_layer_plan; #[cfg(test)] pub(crate) use step_request::{LoadedCaches, LoadedOwners}; pub(crate) use step_request::{StepCaches, StepPurpose, StepRequest}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward.rs index 1e13d656..b8aeb41c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward.rs @@ -3,9 +3,9 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_qwenforward/impl_qwenforward_2.rs"] -mod impl_qwenforward_2; -#[path = "impl_qwenforward/impl_qwenforward_2_2.rs"] -mod impl_qwenforward_2_2; #[path = "impl_qwenforward/impl_qwenforward_3.rs"] mod impl_qwenforward_3; +#[path = "impl_qwenforward/step_core.rs"] +mod step_core; +#[path = "impl_qwenforward/step_entries.rs"] +mod step_entries; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/step_core.rs similarity index 92% rename from crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/step_core.rs index 41404d57..dad90ea4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/step_core.rs @@ -1,6 +1,6 @@ -//! Moved out of the parent module by STRA-338: impl QwenForward (2). +//! The shared body of every forward step: one completed transaction over the input row, the layers and the head. -use super::super::step_layer_fns::{ +use super::super::step_layers::{ LayerCtx, capture_streams, finish_step, prepare_step_caches, run_layers, stage_input_row, }; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/step_entries.rs similarity index 97% rename from crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/step_entries.rs index 67312143..716c4665 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/step_entries.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: impl QwenForward. +//! The forward-step entry points of QwenForward: greedy, KAR, MTP target and MTP prefill steps. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layers.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layer_fns.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layers.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs index 642c249d..639aab88 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs @@ -5,11 +5,11 @@ use crate::model_binding::qwen4exp_input::MoeWeightDescriptor; use crate::qwen_forward::moe_weight_cache::original_dual_layout; use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer}; -#[path = "moe_mmq_adaptive/gather_fns.rs"] -mod gather_fns; -#[path = "moe_mmq_adaptive/walk_fns.rs"] -mod walk_fns; -use walk_fns::{SlotState, StagingPlan, Walk, WalkOwners}; +#[path = "moe_mmq_adaptive/expert_gather.rs"] +mod expert_gather; +#[path = "moe_mmq_adaptive/layer_walk.rs"] +mod layer_walk; +use layer_walk::{SlotState, StagingPlan, Walk, WalkOwners}; #[allow(clippy::too_many_arguments)] pub(super) fn execute_adaptive_groups<'ctx>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/expert_gather.rs similarity index 99% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/expert_gather.rs index ae315dd7..cb9dcc9a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/gather_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/expert_gather.rs @@ -1,6 +1,6 @@ //! Gather of one expert's matrices into the admitted bank (STRA-338 size: extract-method only). -use super::walk_fns::{ExpertGroup, Walk, WalkOwners}; +use super::layer_walk::{ExpertGroup, Walk, WalkOwners}; #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/layer_walk.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/walk_fns.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive/layer_walk.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs index 43bceba9..94ecf179 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder.rs @@ -4,6 +4,6 @@ use super::*; mod batched_support; -mod impl_mtpdecoder_2; -mod impl_mtpdecoder_2_2; -mod impl_mtpdecoder_3; +mod batched_window; +mod draft_warm_and_window; +mod scalar_window; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_window.rs similarity index 99% rename from crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_window.rs index 13fc3b20..2942c5c2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/batched_window.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: impl MtpDecoder (2). +//! The batched MTP window: draft chain, rewind, then the joint target window (IQ3 integer/native Down policy). #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/draft_warm_and_window.rs similarity index 98% rename from crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/draft_warm_and_window.rs index 63af578e..67207e4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/draft_warm_and_window.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: impl MtpDecoder. +//! MtpDecoder: draft warming along known-next edges, and the window entry that picks the batched or scalar window. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/scalar_window.rs similarity index 99% rename from crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/scalar_window.rs index 29090876..027a0d02 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/scalar_window.rs @@ -1,4 +1,4 @@ -//! Moved out of the parent module by STRA-338: impl MtpDecoder (3). +//! The scalar MTP window: draft chain, rewind, then verified catch-up one target step at a time. #[allow(unused_imports)] use super::*; From f95d9ab4bfea55dd665dffd3bbeb0d1bc0fab046 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:34:18 +0100 Subject: [PATCH 42/42] STRA-338 params e04: rename the expert projection and scalar QSA row files by content; ExecutorOpening in its own file Files: none --- .../src/qwen_forward/moe_expert.rs | 56 +++++++++---------- ..._with_parts_fn.rs => cached_expert_run.rs} | 0 ...trix_fn.rs => expert_matrix_projection.rs} | 0 ...{expert_mlp_fn.rs => expert_mlp_values.rs} | 2 +- .../{impl_expertready.rs => expert_step.rs} | 0 ...ed_mlp_down_fn.rs => scoped_expert_mlp.rs} | 2 +- .../impl_originalservestack.rs | 6 +- .../executor_opening.rs | 19 +++++++ .../impl_originalservestack/open_parts.rs | 15 ----- .../src/qwen_forward/qsa_resident_scalar.rs | 32 +++++------ ...ated_out_fn.rs => gated_out_projection.rs} | 0 .../{driver_fn.rs => scalar_row_admission.rs} | 0 ...residentqsascalar.rs => scalar_row_run.rs} | 0 13 files changed, 69 insertions(+), 63 deletions(-) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/{finish_with_parts_fn.rs => cached_expert_run.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/{project_matrix_fn.rs => expert_matrix_projection.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/{expert_mlp_fn.rs => expert_mlp_values.rs} (98%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/{impl_expertready.rs => expert_step.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/{cached_mlp_down_fn.rs => scoped_expert_mlp.rs} (98%) create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/executor_opening.rs rename crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/{project_gated_out_fn.rs => gated_out_projection.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/{driver_fn.rs => scalar_row_admission.rs} (100%) rename crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/{impl_residentqsascalar.rs => scalar_row_run.rs} (100%) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs index 6e1b6180..37ac72fe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs @@ -69,57 +69,57 @@ mod moe_activation_reuse_gpu; #[cfg(test)] mod tests; -mod impl_expertready; -pub(in crate::qwen_forward) use impl_expertready::ExpertRowRequest; +mod expert_step; +pub(in crate::qwen_forward) use expert_step::ExpertRowRequest; #[allow(unused_imports)] -use impl_expertready::StepCuda; +use expert_step::StepCuda; #[allow(unused_imports)] -use impl_expertready::execute_cuda; +use expert_step::execute_cuda; #[allow(unused_imports)] -use impl_expertready::execute_cuda_kar; +use expert_step::execute_cuda_kar; #[allow(unused_imports)] -use impl_expertready::kar_error; -mod finish_with_parts_fn; +use expert_step::kar_error; +mod cached_expert_run; #[allow(unused_imports)] -use finish_with_parts_fn::execute_cuda_cached; +use cached_expert_run::execute_cuda_cached; #[allow(unused_imports)] -use finish_with_parts_fn::finish_with_parts; -mod cached_mlp_down_fn; +use cached_expert_run::finish_with_parts; +mod scoped_expert_mlp; #[allow(unused_imports)] -use cached_mlp_down_fn::DownProvenance; +use scoped_expert_mlp::DownProvenance; #[allow(unused_imports)] -use cached_mlp_down_fn::cached_gate_up_scoped; +use scoped_expert_mlp::cached_gate_up_scoped; #[allow(unused_imports)] -use cached_mlp_down_fn::cached_mlp_down; -mod expert_mlp_fn; +use scoped_expert_mlp::cached_mlp_down; +mod expert_mlp_values; #[allow(unused_imports)] -use expert_mlp_fn::expert_mlp; +use expert_mlp_values::expert_mlp; #[allow(unused_imports)] -use expert_mlp_fn::finish_cached_mlp; +use expert_mlp_values::finish_cached_mlp; #[allow(unused_imports)] -use expert_mlp_fn::project_cached_gate_up; +use expert_mlp_values::project_cached_gate_up; #[allow(unused_imports)] -use expert_mlp_fn::project_retained_gate_up; -mod project_matrix_fn; +use expert_mlp_values::project_retained_gate_up; +mod expert_matrix_projection; #[allow(unused_imports)] -use project_matrix_fn::admit_budget; +use expert_matrix_projection::admit_budget; #[cfg(test)] #[allow(unused_imports)] -use project_matrix_fn::collect_rows; +use expert_matrix_projection::collect_rows; #[allow(unused_imports)] -use project_matrix_fn::dual_format_kind; +use expert_matrix_projection::dual_format_kind; #[allow(unused_imports)] -use project_matrix_fn::dual_routed_format; +use expert_matrix_projection::dual_routed_format; #[allow(unused_imports)] -use project_matrix_fn::launch_cached_prepared; +use expert_matrix_projection::launch_cached_prepared; #[allow(unused_imports)] -use project_matrix_fn::launch_cached_projection; +use expert_matrix_projection::launch_cached_projection; #[allow(unused_imports)] -use project_matrix_fn::launch_projection; +use expert_matrix_projection::launch_projection; #[allow(unused_imports)] -use project_matrix_fn::project_matrix; +use expert_matrix_projection::project_matrix; #[allow(unused_imports)] -use project_matrix_fn::{DeclaredMatrix, ExpertActivation, ExpertMatrix, MatrixDims}; +use expert_matrix_projection::{DeclaredMatrix, ExpertActivation, ExpertMatrix, MatrixDims}; mod validate_values_fn; #[allow(unused_imports)] use validate_values_fn::binding_error; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_expert_run.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_expert_run.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_matrix_projection.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_matrix_projection.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_values.rs similarity index 98% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_values.rs index 803ed68a..17b840bb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_values.rs @@ -1,7 +1,7 @@ //! Moved out of the parent module by STRA-338: fn expert_mlp, fn project_cached_gate_up, fn project_retained_gate_up, //! fn finish_cached_mlp. -use super::project_matrix_fn::{gate_up_dims, gate_up_prepared_format}; +use super::expert_matrix_projection::{gate_up_dims, gate_up_prepared_format}; #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_step.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_step.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/scoped_expert_mlp.rs similarity index 98% rename from crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/scoped_expert_mlp.rs index d2efb3c4..72ee6771 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/scoped_expert_mlp.rs @@ -1,6 +1,6 @@ //! Moved out of the parent module by STRA-338: fn cached_mlp_down, fn cached_gate_up_scoped. -use super::project_matrix_fn::{MatrixDims, gate_up_dims, gate_up_prepared_format}; +use super::expert_matrix_projection::{MatrixDims, gate_up_dims, gate_up_prepared_format}; #[allow(unused_imports)] use super::*; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs index 9fbceaa0..c469ee93 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack.rs @@ -8,10 +8,12 @@ use decode_parts::{ QsaOwnerHome, RefillOwners, TierResources, assemble_decode, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, resolve_assembled, return_owners, settle_deferred_refill, teardown_decode, }; +mod executor_opening; +use executor_opening::ExecutorOpening; mod open_parts; use open_parts::{ - ExecutorOpening, Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor, - open_expert_cache, open_prefix, serve_policies, share_rt_dense_roles, + Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor, open_expert_cache, + open_prefix, serve_policies, share_rt_dense_roles, }; mod serve_parts; use serve_parts::{ServeEnv, serve_over_host}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/executor_opening.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/executor_opening.rs new file mode 100644 index 00000000..0f7f8802 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/executor_opening.rs @@ -0,0 +1,19 @@ +//! How the prompt executor and its MTP drafter are opened. + +#[allow(unused_imports)] +use super::*; + +/// How the prompt executor and its MTP drafter are opened: the stack config, the verifier's widest window and the +/// drafter request derived from them. +pub(super) struct ExecutorOpening<'a> { + pub(super) config: &'a StackConfig, + pub(super) verifier_max_t: usize, + pub(super) request: OriginalMtpRequest, +} +impl<'a> ExecutorOpening<'a> { + /// The opening for a verifier of window width `verifier_max_t`; `coupled` is whether the policy is coupled. + pub(super) fn new(config: &'a StackConfig, verifier_max_t: usize, coupled: bool) -> Self { + let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS); + Self { config, verifier_max_t, request } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs index 81d45f37..cffebc4e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/open_parts.rs @@ -178,21 +178,6 @@ fn load_moe<'ctx>( Ok(moe) } -/// How the prompt executor and its MTP drafter are opened: the stack config, the verifier's widest window and the -/// drafter request derived from them. -pub(super) struct ExecutorOpening<'a> { - config: &'a StackConfig, - verifier_max_t: usize, - request: OriginalMtpRequest, -} -impl<'a> ExecutorOpening<'a> { - /// The opening for a verifier of window width `verifier_max_t`; `coupled` is whether the policy is coupled. - pub(super) fn new(config: &'a StackConfig, verifier_max_t: usize, coupled: bool) -> Self { - let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS); - Self { config, verifier_max_t, request } - } -} - /// The prompt executor with its MTP drafter: from the RT directory, or the full MTP owner over the pinned pack. pub(super) fn open_executor<'a, 'ctx>( binding: &'a ModelBinding, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs index 2f09d528..20ed6f7c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs @@ -79,29 +79,29 @@ struct ScalarHost { /// The role buffers of one gate-and-Out run: attended, gate, gated, Out. type GateBuffers<'ctx> = [Option>; 4]; -#[path = "qsa_resident_scalar/driver_fn.rs"] -mod driver_fn; +#[path = "qsa_resident_scalar/scalar_row_admission.rs"] +mod scalar_row_admission; #[allow(unused_imports)] -use driver_fn::check_scalar_shapes; +use scalar_row_admission::check_scalar_shapes; #[allow(unused_imports)] -use driver_fn::check_scalar_txn; +use scalar_row_admission::check_scalar_txn; #[allow(unused_imports)] -use driver_fn::check_txn_input; +use scalar_row_admission::check_txn_input; #[allow(unused_imports)] -use driver_fn::driver; +use scalar_row_admission::driver; #[allow(unused_imports)] -use driver_fn::scalar_gate; -#[path = "qsa_resident_scalar/impl_residentqsascalar.rs"] -mod impl_residentqsascalar; +use scalar_row_admission::scalar_gate; +#[path = "qsa_resident_scalar/scalar_row_run.rs"] +mod scalar_row_run; #[allow(unused_imports)] -use impl_residentqsascalar::apply_gate; +use scalar_row_run::apply_gate; #[allow(unused_imports)] -use impl_residentqsascalar::upload_gate_inputs; -#[path = "qsa_resident_scalar/project_gated_out_fn.rs"] -mod project_gated_out_fn; +use scalar_row_run::upload_gate_inputs; +#[path = "qsa_resident_scalar/gated_out_projection.rs"] +mod gated_out_projection; #[allow(unused_imports)] -use project_gated_out_fn::gate_and_out; +use gated_out_projection::gate_and_out; #[allow(unused_imports)] -use project_gated_out_fn::project_gated_out; +use gated_out_projection::project_gated_out; #[allow(unused_imports)] -use project_gated_out_fn::release_gate_buffers; +use gated_out_projection::release_gate_buffers; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/gated_out_projection.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/project_gated_out_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/gated_out_projection.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/driver_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/scalar_row_admission.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/driver_fn.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/scalar_row_admission.rs diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/scalar_row_run.rs similarity index 100% rename from crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/impl_residentqsascalar.rs rename to crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar/scalar_row_run.rs