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