From 52db7c41d8779e87cc7cb5ba47d70ec53dc7429e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 02:14:54 +0100 Subject: [PATCH] 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)?;