From d6d7e2b32a7b9b202b09ca9b9a1f976ef30d74b2 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 8 Nov 2026 12:56:57 +0100 Subject: [PATCH] STRA-338 params q04: adaptive preload, draft KV finish, draft schedules, spec config and window failure take domain DTOs Co-Authored-By: Claude Sonnet 5.5 --- .../impl_moeweightcache_4.rs | 11 +- .../src/qwen_forward/cache_strata_adaptive.rs | 8 ++ .../impl_adaptivecache.rs | 15 ++- .../impl_adaptivecache/preload.rs | 18 +-- .../src/qwen_forward/original_mtp_prefill.rs | 32 +++--- .../original_mtp_scalar_prefill.rs | 5 +- .../original_mtp_verified_adapter.rs | 8 ++ .../impl_originalmtpdraftreceipt.rs | 10 +- .../src/qwen_forward/original_serve_engine.rs | 4 +- .../impl_originalservesettings.rs | 3 +- .../original_serve_engine/tests.rs | 7 +- .../tests/restore_attempts_do_not_depend.rs | 5 +- ...l_nativeservehost_for_originalservehost.rs | 6 +- .../original_serve_residency/tests.rs | 103 +++--------------- .../qwen_forward/original_spec_controller.rs | 11 ++ .../verify_parts.rs | 10 +- .../original_spec_controller/tests.rs | 22 ++-- .../adaptation_join_failure_is_reported.rs | 10 +- .../tests/config_rejects_out_of_range.rs | 27 ++--- .../original_spec_controller/tests/golden.rs | 3 +- .../trace_enabled_fn.rs | 4 +- .../src/qwen_forward/original_spec_draft.rs | 53 +++++---- .../original_spec_draft/prefill_records.rs | 11 +- .../produce_original_gdn_fn.rs | 26 ++--- .../impl_promptdeviceread/read_completion.rs | 11 +- .../qsa_prefill_batch/projection_rows.rs | 16 +-- 26 files changed, 208 insertions(+), 231 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs index 7e6b9620..4baf9c9d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs @@ -251,15 +251,8 @@ impl<'ctx> MoeWeightCache<'ctx> { working_reserve: WORKING_RESERVE, window_spill: plan.window_spill, }; - cache_strata_adaptive::AdaptiveCache::preload( - binding, - context, - profile, - plan.template, - limits, - shared_bytes, - plan.metadata, - ) + let sizing = cache_strata_adaptive::AdaptiveSizing { profile, template: plan.template, limits }; + cache_strata_adaptive::AdaptiveCache::preload(binding, context, sizing, shared_bytes, plan.metadata) } fn adopt_adaptive( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs index 336d79e6..6e39146e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs @@ -23,6 +23,14 @@ pub(super) struct Slot { pub(super) keys: [MoeWeightDescriptor; 3], pub(super) bytes: usize, } +/// What an adaptive policy is sized from: the profile ranking, the first-expert descriptors of every layer and the +/// memory limits it must fit. +#[derive(Clone, Copy)] +pub(super) struct AdaptiveSizing<'profile> { + pub(super) profile: &'profile RankedProfile, + pub(super) template: [[MoeWeightDescriptor; 3]; LAYERS], + pub(super) limits: ProfileLimits, +} /// All storage is bounded and reserved before any numeric/device consumer. /// `resident` names metadata slots only. The cache adapter must separately own /// the genuine whole weight buffers; no caller receives a raw slot capability. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs index aa73d5e7..98272c26 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs @@ -9,6 +9,14 @@ mod preload; type StagedPairs<'ctx> = Vec<(DeviceBuffer<'ctx>, Vec)>; type Staged<'ctx> = (Swap, StagedPairs<'ctx>); +/// The device bytes the admission of every slot role upload keeps free: the window spill reserve and the shared pool +/// the adaptive tier sits beside. +#[derive(Clone, Copy)] +struct UploadReserve { + spill_reserve: usize, + shared_bytes: usize, +} + /// Slot buffers and transfer queue, both reserved up front so later phases never allocate. struct Reserved<'ctx> { buffers: Vec; 3]>>, @@ -19,18 +27,17 @@ impl<'ctx> AdaptiveCache<'ctx> { pub(in super::super) fn preload( binding: &ModelBinding, context: &'ctx Context<'ctx>, - profile: &RankedProfile, - template: [[MoeWeightDescriptor; 3]; LAYERS], - limits: ProfileLimits, + sizing: AdaptiveSizing<'_>, shared_bytes: usize, external_metadata: usize, ) -> Result { + let AdaptiveSizing { profile, template, limits } = sizing; let largest = template.iter().try_fold(0usize, |max, keys| Ok::<_, Error>(max.max(blob_bytes(keys)?)))?; let spill_reserve = limits.window_spill.checked_add(largest).ok_or(Error::Overflow)?; let policy = AdaptivePolicy::new(profile, template, limits)?; let reserved = Self::reserve_owners(&policy, external_metadata)?; let mut owner = Self::unpublished(binding, context, policy, reserved); - if let Err(primary) = owner.preload_slots(binding, spill_reserve, shared_bytes) { + if let Err(primary) = owner.preload_slots(binding, UploadReserve { spill_reserve, shared_bytes }) { let _ = owner.close(); return Err(primary); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache/preload.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache/preload.rs index 23c77171..03db0acb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache/preload.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache/preload.rs @@ -19,17 +19,12 @@ impl<'ctx> AdaptiveCache<'ctx> { } Ok(Reserved { buffers, transfers }) } - pub(super) fn preload_slots( - &mut self, - binding: &ModelBinding, - spill_reserve: usize, - shared_bytes: usize, - ) -> Result<()> { + pub(super) fn preload_slots(&mut self, binding: &ModelBinding, reserve: UploadReserve) -> Result<()> { for slot in 0..self.buffers.len() { let keys = self.policy.slots[slot].keys; self.revalidate_keys(binding, keys)?; let mut loaded: [Option>; 3] = std::array::from_fn(|_| None); - if let Err(primary) = self.load_slot(binding, keys, spill_reserve, shared_bytes, &mut loaded) { + if let Err(primary) = self.load_slot(binding, keys, reserve, &mut loaded) { for buffer in loaded.into_iter().rev().flatten() { if buffer.release().is_err() { self.failed = true; @@ -45,12 +40,11 @@ impl<'ctx> AdaptiveCache<'ctx> { &mut self, binding: &ModelBinding, keys: [MoeWeightDescriptor; 3], - spill_reserve: usize, - shared_bytes: usize, + reserve: UploadReserve, loaded: &mut [Option>; 3], ) -> Result<()> { for (role, key) in keys.iter().copied().enumerate() { - self.admit_role_upload(&keys[role..], spill_reserve, shared_bytes)?; + self.admit_role_upload(&keys[role..], reserve)?; loaded[role] = Some(self.upload_role(binding, key)?); self.uploads = self.uploads.checked_add(key.bytes as u64).ok_or(Error::Overflow)?; } @@ -61,9 +55,9 @@ impl<'ctx> AdaptiveCache<'ctx> { pub(super) fn admit_role_upload( &self, remaining_keys: &[MoeWeightDescriptor], - spill_reserve: usize, - shared_bytes: usize, + reserve: UploadReserve, ) -> Result<()> { + let UploadReserve { spill_reserve, shared_bytes } = reserve; let context = self.context; let remaining = remaining_keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?; let required = 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 ebca318c..02e8e97e 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 @@ -112,13 +112,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx /// The pending prompt, the Final phase and the lease the draft conditioning reads must be one and the same. fn check_final_sources( &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, preview: &PromptDeviceFinal, last_next: TokenId, ) -> Result> { - let phase = self.sources_phase(binding, dense, txn, preview, last_next)?; + let phase = self.sources_phase(weights, txn, preview, last_next)?; if !self.final_sources_agree(txn, &phase)? { return Err(Error::IdentityMismatch); } @@ -129,13 +128,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx /// The sources, the pending prompt and the preview validate, and the sources name one Original phase. fn sources_phase( &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, preview: &PromptDeviceFinal, last_next: TokenId, ) -> Result> { - self.sources.validate(binding, dense)?; + self.sources.validate(weights.binding, weights.dense)?; txn.validate_final(preview)?; preview.validate_conditioning(last_next)?; self.sources.original_phase()?.ok_or(Error::IdentityMismatch) @@ -173,14 +171,13 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx /// After the producer: the sources and the phase are unchanged, and the outcome carries the pending receipt. fn finish_draft_kv( &self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, - pending: (&OriginalPromptTxn<'_, '_>, &PromptDeviceFinal, TokenId), - phase: Rc, + weights: PromptWeights<'_, 'ctx>, + prompt: FinalPromptPhase<'_, 'ctx>, result: DraftKvOutcome, ring: &MtpOriginalInt8<'ctx>, ) -> Result { - let (txn, preview, last_next) = pending; + let PromptWeights { binding, dense } = weights; + let FinalPromptPhase { txn, preview, last_next, phase } = prompt; self.sources.validate(binding, dense)?; txn.validate_final(preview)?; if !phase.same(&txn.phase()) { @@ -234,6 +231,14 @@ pub(in crate::qwen_forward) struct FinalPromptSources<'a, 'ctx> { pub(in crate::qwen_forward) preview: &'a PromptDeviceFinal, pub(in crate::qwen_forward) last_next: TokenId, } +/// The prompt transaction with its final row and known next token, and the Original phase their sources name: what +/// the outcome of a draft KV producer is checked against before it is handed on. +pub(in crate::qwen_forward) struct FinalPromptPhase<'a, '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, + pub(in crate::qwen_forward) phase: Rc, +} /// What the draft KV is computed from: the prior ring snapshot, the embedding table, the first prompt row that is /// still missing and the draft policy. pub(in crate::qwen_forward) struct DraftKvRequest<'a> { @@ -255,7 +260,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx ) -> Result { let FinalPromptSources { binding, dense, mtp, txn, preview, last_next } = sources; let DraftKvRequest { prior, embedding, first_needed, policy } = request; - let phase = self.check_final_sources(binding, dense, txn, preview, last_next)?; + let phase = self.check_final_sources(PromptWeights::new(binding, dense), txn, preview, last_next)?; let next = self.shifted_next_ids(txn, last_next)?; let weights = self.prefill_weights(binding, mtp)?; let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?; @@ -264,7 +269,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx let rows = PrefillRows { tokens: &next, cell0: start, first_needed }; let sources = DraftKvSources { prior, policy, weights, embedding }; let result = producer.record(&mut self.device, &mut run, rows, sources).map_err(micro_driver_error)?; - self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, run.ring) + let prompt = FinalPromptPhase { txn, preview, last_next, phase }; + self.finish_draft_kv(PromptWeights::new(binding, dense), prompt, result, run.ring) } } 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 85d3ce98..5ccbd48c 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 @@ -25,7 +25,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx let rows = PrefillRows { tokens: &next, cell0: start, first_needed }; let result = producer.record_scalar_prefill(&mut self.device, &mut run, rows, kv).map_err(micro_driver_error)?; - self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, run.ring) + let prompt = FinalPromptPhase { txn, preview, last_next, phase }; + self.finish_draft_kv(PromptWeights::new(binding, dense), prompt, result, run.ring) } } @@ -120,7 +121,7 @@ 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, sources: ScalarPromptSources<'_, 'ctx>) -> Result> { let ScalarPromptSources { binding, dense, txn, preview, last_next, .. } = sources; - let phase = self.sources_phase(binding, dense, txn, preview, last_next)?; + let phase = self.sources_phase(PromptWeights::new(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_mtp_verified_adapter.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs index e80d77d1..436d4fab 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 @@ -17,6 +17,14 @@ use leleka_cuda_driver::{ OriginalMtpFullPolicy, OriginalVerifyWindow, RepeatRowWindow, SamplerParams, }; +/// A completed verifier window with its head selection and the row up to which the target accepted it: what a draft +/// receipt is made from. +pub(in crate::qwen_forward) struct VerifiedWindow<'ctx> { + pub(in crate::qwen_forward) window: OriginalVerifyWindow<'ctx>, + pub(in crate::qwen_forward) selection: NativeHeadSelection, + pub(in crate::qwen_forward) accepted_row: usize, +} + /// One completed `Verifier::run` receipt, before the target commit. It owns /// the actual residual window and sampled target rows; the caller may only /// transform it into `OriginalCommittedMtpReceipt` after verifier commit has diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs index 2601f0ed..a0f032c2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter/impl_originalmtpdraftreceipt.rs @@ -42,10 +42,9 @@ impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> { binding: &ModelBinding, session: &QwenSession<'ctx>, context: &'ctx Context<'ctx>, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, - accepted_row: usize, + verified: VerifiedWindow<'ctx>, ) -> Result { + let VerifiedWindow { window, selection, accepted_row } = verified; let before = session.target_origin()?; window.validate_context(context).map_err(driver_error)?; window.validate_selection(&selection).map_err(driver_error)?; @@ -112,11 +111,10 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx> { binding: &ModelBinding, session: &QwenSession<'ctx>, context: &'ctx Context<'ctx>, - window: OriginalVerifyWindow<'ctx>, - selection: NativeHeadSelection, + verified: VerifiedWindow<'ctx>, before: TargetStepOrigin, - accepted_row: usize, ) -> Result { + let VerifiedWindow { window, selection, accepted_row } = verified; let committed = session.target_origin()?; check_window(&window, context, &selection)?; let (first, expected) = published_bounds(&window, accepted_row)?; 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 e36c001e..6f9cc1e0 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 @@ -9,7 +9,9 @@ //! a missing owner is `Error::Unsupported`, never a synthesized result. 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_controller::{ + NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecError, SpecWindow, +}; use super::original_spec_draft::{DraftPick, OriginalDraftEngine, OriginalFirstDraftEngine, TargetSeedRow}; use super::original_spec_policy::MAX_T; use crate::settings::EnvSource; 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 948f4f0b..b0c5802b 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 @@ -161,8 +161,7 @@ impl OriginalServeSettings { pub(crate) fn controller(&self) -> Result { OriginalSpecController::new( SpecConfig::new( - self.max_t, - self.mtp_max_t, + SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp_max_t }, self.max_context, self.vocabulary, self.suffix_min_match, 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 cf001108..e5cde18c 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 @@ -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_controller::{NanGuard, OriginalSpecController, SpecConfig, SpecError}; +use super::super::original_spec_controller::{NanGuard, OriginalSpecController, SpecConfig, SpecError, SpecWindow}; use super::super::original_spec_draft::{DraftPreparation, DraftSampling, VerifiedWindow}; use super::*; use std::cell::RefCell; @@ -256,7 +256,10 @@ fn run_request(skew: i32, max_t: usize, max_new: usize) -> (Vec, Vec NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { let DraftLimits { max_drafts, min_p } = limits; let before = self.admit_draft_origin(position, max_drafts)?; let p = profile::span("draft.receipt"); + let verified = VerifiedWindow { window, selection, accepted_row }; let receipt = OriginalCommittedMtpReceipt::for_published_window( self.binding, self.session, self.context, - window, - selection, + verified, before, - accepted_row, )?; drop(p); let _p = profile::span("draft.drafter"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs index df20fa7f..91435dd4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs @@ -112,6 +112,10 @@ use super::*; fn row(ids: [i32; 10]) -> Vec { ids.to_vec() } +/// The PCIe split policy of a test group. +fn policy(pcie_num: u32, staging: usize, tail_rank: u32) -> PcieSplitPolicy { + PcieSplitPolicy { pcie_num, staging, tail_rank } +} #[test] fn residents_are_vram_groups_in_routing_order_and_the_rest_is_the_cpus_without_pcie() { @@ -156,57 +160,23 @@ fn the_pcie_share_is_the_last_misses_in_routing_order_capped_by_staging() { fn a_restricted_pcie_share_takes_only_eligible_misses_and_never_more_than_the_unrestricted_one() { // 10 misses, share 141/256 -> m = 5 of all misses; only 11, 14, 16, 17 may be staged let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); + let group = RoutedGroup::new(&ids, 10, 40); let none = |_: u32| None; let ok = |e: u32| matches!(e, 11 | 14 | 16 | 17); - let s = split_group_pcie( - RoutedGroup::new(&ids, 10, 40), - none, - PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 0 }, - ok, - ) - .unwrap(); + let s = split_group_pcie(group, none, policy(141, 16, 0), ok).unwrap(); assert_eq!(s.pcie_experts, vec![11, 14, 16, 17], "capped by the eligible misses, routing order"); assert_eq!(s.kinds, vec![-1, 1, -1, -1, 1, -1, 1, 1, -1, -1]); // a smaller share takes the last eligible misses - let s = split_group_pcie( - RoutedGroup::new(&ids, 10, 40), - none, - PcieSplitPolicy { pcie_num: 64, staging: 16, tail_rank: 0 }, - ok, - ) - .unwrap(); // m = 10 * 64 >> 8 = 2 + let s = split_group_pcie(group, none, policy(64, 16, 0), ok).unwrap(); // m = 10 * 64 >> 8 = 2 assert_eq!(s.pcie_experts, vec![16, 17]); // nothing eligible, nothing staged; and the unrestricted split is the old one - assert!( - split_group_pcie( - RoutedGroup::new(&ids, 10, 40), - none, - PcieSplitPolicy { pcie_num: 256, staging: 16, tail_rank: 0 }, - |_| false - ) - .unwrap() - .plan - .pcie() - .is_empty() - ); - let all = split_group_pcie( - RoutedGroup::new(&ids, 10, 40), - none, - PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 0 }, - |_| true, - ) - .unwrap(); - let old = split_group(RoutedGroup::new(&ids, 10, 40), none, 141, 16).unwrap(); + assert!(split_group_pcie(group, none, policy(256, 16, 0), |_| false).unwrap().plan.pcie().is_empty()); + let all = split_group_pcie(group, none, policy(141, 16, 0), |_| true).unwrap(); + let old = split_group(group, none, 141, 16).unwrap(); assert_eq!((all.pcie_experts, all.kinds), (old.pcie_experts, old.kinds)); // residents and skipped experts are not eligible misses let resident = |e: u32| (e == 11).then_some(2usize); - let s = split_group_pcie( - RoutedGroup::new(&ids, 10, 40), - resident, - PcieSplitPolicy { pcie_num: 256, staging: 16, tail_rank: 0 }, - ok, - ) - .unwrap(); + let s = split_group_pcie(group, resident, policy(256, 16, 0), ok).unwrap(); assert_eq!(s.pcie_experts, vec![14, 16, 17]); } @@ -227,41 +197,19 @@ fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]); ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30])); let resident = |e: u32| (e == 40).then_some(3usize); - let off = split_group_tail( - RoutedGroup::new(&ids, 10, 20), - resident, - PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 0 }, - ) - .unwrap(); + let off = split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 0)).unwrap(); assert_eq!(off.skipped_experts, 0); assert!(off.kinds.iter().all(|&k| k != -2)); - let on = split_group_tail( - RoutedGroup::new(&ids, 10, 20), - resident, - PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 7 }, - ) - .unwrap(); + let on = split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 7)).unwrap(); assert_tail_skip_at_rank_seven_keeps_the_rest(&on, &off); // rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, // best rank 7) assert_eq!( - split_group_tail( - RoutedGroup::new(&ids, 10, 20), - resident, - PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 8 } - ) - .unwrap() - .skipped_experts, + split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 8)).unwrap().skipped_experts, 1 ); assert_eq!( - split_group_tail( - RoutedGroup::new(&ids, 10, 20), - resident, - PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 9 } - ) - .unwrap() - .skipped_experts, + split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 9)).unwrap().skipped_experts, 0 ); } @@ -292,34 +240,19 @@ fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() { // ten) let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]); let none = |_: u32| None; - let s = split_group_tail( - RoutedGroup::new(&ids, 10, 40), - none, - PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 7 }, - ) - .unwrap(); + let s = split_group_tail(RoutedGroup::new(&ids, 10, 40), none, policy(141, 16, 7)).unwrap(); assert_eq!(s.skipped_experts, 3); assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]); assert_eq!(s.pcie_experts, vec![14, 15, 16]); // a rank past the last slot skips nothing - let off = split_group_tail( - RoutedGroup::new(&ids, 10, 40), - none, - PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 10 }, - ) - .unwrap(); + let off = split_group_tail(RoutedGroup::new(&ids, 10, 40), none, policy(141, 16, 10)).unwrap(); assert_eq!(off.skipped_experts, 0); } #[test] fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() { let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - let s = split_group_tail( - RoutedGroup::new(&ids, 10, 40), - |_| None, - PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 1 }, - ) - .unwrap(); + let s = split_group_tail(RoutedGroup::new(&ids, 10, 40), |_| None, policy(0, 16, 1)).unwrap(); assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs index 1a1fe8e7..5c5fc25c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs @@ -64,6 +64,17 @@ pub(crate) struct NanGuard { inject_at: u64, inject_times: u32, } +/// How wide the speculative windows are: the verify window and the cap of the MTP chain (0 means the verify width). +#[derive(Clone, Copy)] +pub(crate) struct SpecWindow { + pub(crate) max_t: usize, + pub(crate) mtp_max_t: usize, +} +/// A window that failed to verify: the error and the restart attempt counter that a restart advances. +struct WindowFailure<'a> { + error: Error, + attempt: &'a mut u32, +} pub(crate) struct SpecConfig { max_t: usize, mtp_t: usize, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs index 76182772..44b3e99e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/verify_parts.rs @@ -210,12 +210,11 @@ impl OriginalSpecController { round: &Round<'_, E>, cancel: &mut impl FnMut() -> bool, ) -> SpecResult { - let guard = self.config.nan_guard; self.windows_checked = self.windows_checked.saturating_add(1); let mut attempt = 0u32; loop { let consumed = &self.request.as_ref().ok_or(Error::IdentityMismatch)?.consumed; - let checks = (self.config.vocabulary, guard, self.windows_checked, attempt); + let checks = (self.config.vocabulary, self.config.nan_guard, self.windows_checked, attempt); match run_window(engine, round, consumed, checks) { Ok(v) => { if attempt > 0 { @@ -227,7 +226,8 @@ impl OriginalSpecController { if let Some(v) = leftover { let _ = engine.drain_verified(v); } - if let Some(refused) = self.window_failed(engine, round, e, &mut attempt, cancel) { + let failure = WindowFailure { error: e, attempt: &mut attempt }; + if let Some(refused) = self.window_failed(engine, round, failure, cancel) { return Err(refused); } } @@ -247,10 +247,10 @@ impl OriginalSpecController { &mut self, engine: &mut E, round: &Round<'_, E>, - e: Error, - attempt: &mut u32, + failure: WindowFailure<'_>, cancel: &mut impl FnMut() -> bool, ) -> Option { + let WindowFailure { error: e, attempt } = failure; let (p, t) = (round.p, round.t); let guard = self.config.nan_guard; let what = format!("position {p}, {t} rows, attempt {} of {}: {e:?}", *attempt + 1, guard.retries); 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 0d0eed8d..9106725e 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, TargetSeedRow}; +use super::super::original_spec_draft::{DraftPick, FirstSeedPoint, OriginalFirstDraftEngine, TargetSeedRow}; use super::*; mod golden; @@ -186,7 +186,7 @@ impl Fake { } fn config(max_t: usize, mtp: usize, suffix: usize) -> SpecConfig { - SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap() + SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap() } fn prompt(n: usize) -> Vec { let mut v = vec![11]; @@ -221,22 +221,30 @@ fn begin(c: &mut OriginalSpecController, p: &[i32], max_new: usize, eos: &[i32]) c.begin_request(p, max_new, 0.0, eos).unwrap(); } +/// The speculation setup of a run to the context's end: the verify width, the MTP chain cap, the suffix match and +/// whether the adaptive window policy is on. +#[derive(Clone, Copy)] +struct EndRunSetup { + max_t: usize, + mtp: usize, + suffix: usize, + adaptive: bool, +} + /// Upstream 41cf05a0 `e85567b6`: the window and the MTP chain near the context's end must stay inside `max_context` /// cells (before: the whole request died with "ran out of context", or the draft wrote cells that do not exist). fn run_to_the_end( max_context: i64, prompt_len: usize, max_new: usize, - max_t: usize, - mtp: usize, - suffix: usize, + setup: EndRunSetup, min_p: f32, - adaptive: bool, ) -> (Fake, Vec, OriginalSpecController) { use super::super::original_spec_adaptive::AdaptiveConfig; + let EndRunSetup { max_t, mtp, suffix, adaptive } = setup; let p = prompt(prompt_len); let mut e = Fake::new(&p[..prompt_len - 1]); - let mut cfg = SpecConfig::new(max_t, mtp, 64, VOCAB, suffix, false).unwrap(); + let mut cfg = SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 64, VOCAB, suffix, false).unwrap(); cfg.max_context = max_context; if adaptive { cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(max_t, max_t - 1))); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs index 526c7c22..14771078 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs @@ -133,7 +133,10 @@ fn check_shape(g: &Greedy, shape: Shape) { let mut e = Fake::new(&g.p[..g.p.len() - 1]); e.bad_draft = bad; e.probs = pr.to_vec(); - let mut c = OriginalSpecController::new(SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap()).unwrap(); + let mut c = OriginalSpecController::new( + SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap(), + ) + .unwrap(); c.begin_request(&g.p, max_new, min_p, &eos).unwrap(); let out = drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); @@ -229,11 +232,12 @@ impl OriginalFirstDraftEngine for First { #[test] fn draft_first_entry_is_a_separate_literal_path_and_drains() { let prep = DraftPreparation::new(4, 3, VOCAB).unwrap(); + let (point, sampling) = (FirstSeedPoint { cell: 9, token: 5 }, DraftSampling { min_p: 0.0, coupled: false }); let mut f = First { log: Vec::new(), fail: false }; - let b = prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).unwrap(); + let b = prep.from_committed_seed(&mut f, &0u8, point, sampling).unwrap(); assert_eq!(b.produced(), 3); assert_eq!(f.log, ["replay", "seed", "chain", "chain", "drain"]); let mut f = First { log: Vec::new(), fail: true }; - assert_eq!(prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).err(), Some(Error::CudaExecution)); + assert_eq!(prep.from_committed_seed(&mut f, &0u8, point, sampling).err(), Some(Error::CudaExecution)); assert_eq!(f.log.last(), Some(&"drain")); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs index 2108a766..cf02f606 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs @@ -8,14 +8,14 @@ use super::*; #[test] fn config_rejects_out_of_range_and_mtp_zero_means_max_t() { - assert!(SpecConfig::new(0, 0, 4096, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(9, 0, 4096, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(4, 0, 0, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(4, 0, 262145, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(4, 0, 4096, 0, 0, false).is_err()); - assert_eq!(SpecConfig::new(4, 0, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); - assert_eq!(SpecConfig::new(4, 9, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); - assert_eq!(SpecConfig::new(4, 2, 4096, VOCAB, 0, false).unwrap().mtp_t, 2); + assert!(SpecConfig::new(SpecWindow { max_t: 0, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(SpecWindow { max_t: 9, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 0, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 262145, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, 0, 0, false).is_err()); + assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); + assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 9 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); + assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 2 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 2); } #[test] @@ -181,7 +181,7 @@ fn max_new_ends_inside_a_window_without_overshooting_output() { fn a_window_near_the_context_end_takes_only_the_rows_that_fit() { let p = prompt(4); let mut e = Fake::new(&p[..3]); - let mut cfg = SpecConfig::new(4, 4, 6, VOCAB, 0, false).unwrap(); + let mut cfg = SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 4 }, 6, VOCAB, 0, false).unwrap(); cfg.max_context = 6; let mut c = OriginalSpecController::new(cfg).unwrap(); begin(&mut c, &p, 100, &[]); @@ -204,7 +204,8 @@ fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() { let prompt_len = 10usize; let max_context = prompt_len as i64 - 1 + k; - let (e, out, c) = run_to_the_end(max_context, prompt_len, 1000, max_t, max_t, suffix, min_p, adaptive); + let setup = EndRunSetup { max_t, mtp: max_t, suffix, adaptive }; + let (e, out, c) = run_to_the_end(max_context, prompt_len, 1000, setup, min_p); let tag = format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}"); assert!(e.max_end <= max_context, "{tag}: touched cell {} of {max_context}", e.max_end); // the request ended because the context is full, with the greedy text of every row that fits @@ -222,13 +223,13 @@ fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() fn the_chain_is_shortened_near_the_end_and_restored_after_it() { // fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells // left. - let (e, _, _) = run_to_the_end(30, 10, 1000, 4, 4, 0, 0.0, false); + let (e, _, _) = run_to_the_end(30, 10, 1000, EndRunSetup { max_t: 4, mtp: 4, suffix: 0, adaptive: false }, 0.0); assert!(e.max_end <= 30); // plans: a clamped chain is asked for explicitly, never longer than the cells left assert!(e.plans.iter().all(|&(n, _)| (1..=3).contains(&n)), "{:?}", e.plans); assert!(e.plans.iter().any(|&(n, _)| n < 3), "the last rounds draft fewer than the full chain: {:?}", e.plans); // a request that never gets near the end never sets a plan (the fixed chain needs none) - let (e, _, _) = run_to_the_end(4096, 10, 40, 4, 4, 0, 0.0, false); + let (e, _, _) = run_to_the_end(4096, 10, 40, EndRunSetup { max_t: 4, mtp: 4, suffix: 0, adaptive: false }, 0.0); assert!(e.plans.is_empty(), "{:?}", e.plans); } @@ -236,7 +237,7 @@ fn the_chain_is_shortened_near_the_end_and_restored_after_it() { fn a_chain_clamped_by_one_request_is_restored_for_the_next() { let p = prompt(10); let mut e = Fake::new(&p[..9]); - let mut cfg = SpecConfig::new(4, 4, 64, VOCAB, 0, false).unwrap(); + let mut cfg = SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 4 }, 64, VOCAB, 0, false).unwrap(); cfg.max_context = 20; let mut c = OriginalSpecController::new(cfg).unwrap(); c.begin_request(&p, 1000, 0.0, &[]).unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs index 36dcf1dc..ea7481db 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs @@ -73,7 +73,8 @@ impl Scenario { let p = prompt(self.prompt_len); let mut e = Fake::new(&p[..self.prompt_len - 1]); e.bad_draft = self.bad_draft; - let mut cfg = SpecConfig::new(self.max_t, self.mtp, 64, VOCAB, 0, false).unwrap(); + let mut cfg = + SpecConfig::new(SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp }, 64, VOCAB, 0, false).unwrap(); cfg.max_context = self.max_context; if self.adaptive { cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(self.max_t, self.max_t - 1))); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs index 122e3c35..1cd791e1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs @@ -100,13 +100,13 @@ impl NanGuard { } impl SpecConfig { pub(crate) fn new( - max_t: usize, - mtp_max_t: usize, + window: SpecWindow, max_context: i64, vocabulary: u32, suffix_min_match: usize, coupled: bool, ) -> Result { + let SpecWindow { max_t, mtp_max_t } = window; if !(1..=MAX_T).contains(&max_t) || max_context < 1 || max_context > crate::qwen_forward::contract::serving_cells() as i64 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 42b63b6f..302a3453 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 @@ -90,6 +90,13 @@ pub(crate) struct VerifiedWindow<'a> { pub(crate) vetted: &'a mut PrefixMemo, } +/// Where a first draft seed sits: its cell and the target token there. +#[derive(Clone, Copy)] +pub(crate) struct FirstSeedPoint { + pub(crate) cell: i64, + pub(crate) token: i32, +} + /// How a draft samples: the confidence floor that cuts the chain, and whether sampling is coupled to the history. #[derive(Clone, Copy)] pub(crate) struct DraftSampling { @@ -125,11 +132,11 @@ impl DraftPreparation { &self, engine: &mut E, verified: &V, - window: VerifiedWindow<'_>, + mut window: VerifiedWindow<'_>, sampling: DraftSampling, ) -> Result { - let VerifiedWindow { first_cell: p, accepted: a, outputs, consumed, vetted } = window; - self.check_verified(p, a, outputs, consumed, vetted, sampling.min_p)?; + self.check_verified(&mut window, sampling.min_p)?; + let VerifiedWindow { first_cell: p, accepted: a, outputs, consumed, .. } = window; let window = SeedWindow { first_cell: p, accepted: a, outputs, consumed }; let result = self.seed_and_chain(engine, verified, window, sampling); let drain = engine.drain_draft(); @@ -137,15 +144,8 @@ impl DraftPreparation { // when an earlier finite/admission error is returned to the caller. drain_after(result, drain) } - fn check_verified( - &self, - p: i64, - a: usize, - outputs: &[i32], - consumed: &[i32], - vetted: &mut PrefixMemo, - min_p: f32, - ) -> Result<()> { + fn check_verified(&self, window: &mut VerifiedWindow<'_>, min_p: f32) -> Result<()> { + let VerifiedWindow { first_cell: p, accepted: a, outputs, consumed, ref mut vetted } = *window; if outputs.is_empty() || outputs.len() > self.max_t || a >= outputs.len() @@ -216,7 +216,7 @@ fn drain_after(result: Result, drain: Result<()>) -> Result Result { + let FirstSeedPoint { cell, token } = point; if cell < 0 || cell .checked_add(self.max_t as i64) .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) || token < 0 || token as u32 >= self.vocabulary - || !min_p.is_finite() + || !sampling.min_p.is_finite() { return Err(Error::InvalidDimension); } - let result = self.first_seed_and_chain(engine, seed, cell, token, min_p, coupled); + let result = self.first_seed_and_chain(engine, seed, point, sampling); let drain = engine.drain_first_seed(); drain_after(result, drain) } @@ -257,11 +256,11 @@ impl DraftPreparation { &self, engine: &mut E, seed: &S, - cell: i64, - token: i32, - min_p: f32, - coupled: bool, + point: FirstSeedPoint, + sampling: DraftSampling, ) -> Result { + let FirstSeedPoint { cell, token } = point; + let DraftSampling { min_p, coupled } = sampling; engine.replay_first_seed_kv(seed, self.max_t, cell, token)?; let mut batch = DraftBatch::empty(); batch.push(engine.full_first_seed(seed, cell, token, coupled)?, self.vocabulary)?; @@ -285,16 +284,14 @@ pub(crate) trait OriginalPrefillDraftEngine { ) -> Result<()>; fn drain_prefill(&mut self) -> Result<()>; } +/// Runs the batched draft prefill of `prompt`: the records uploaded once, then every group of `schedule` appended. pub(crate) fn prefill_draft>( engine: &mut E, prompt: &P, records: &PrefillRecords, - max_t: usize, - cell0: i64, - window: i64, - prompt_len: i64, + schedule: PrefillSchedule, ) -> Result<()> { - let groups = records.groups(max_t, cell0, window, prompt_len)?; + let groups = records.groups(schedule)?; let result = (|| { engine.upload_prefill_records(prompt, records)?; for (first, rows) in groups { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs index 62b6a7b0..bfda9ca1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs @@ -65,7 +65,8 @@ impl PrefillRecords { pub(crate) fn bytes(&self) -> usize { self.records.len() * 4 } - pub(crate) fn groups(&self, max_t: usize, cell0: i64, window: i64, prompt_len: i64) -> Result { + pub(crate) fn groups(&self, schedule: PrefillSchedule) -> Result { + let PrefillSchedule { max_t, cell0, window, prompt_len } = schedule; if !(1..=MAX_T).contains(&max_t) || cell0 != self.cell0 || !(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&window) @@ -77,6 +78,14 @@ impl PrefillRecords { Ok(PrefillGroups { next: 0, rows: self.rows, max_t, cell0, first_needed }) } } +/// How a prompt's draft prefill is grouped: rows per group, the first cell, the attention window and the prompt length. +#[derive(Clone, Copy)] +pub(crate) struct PrefillSchedule { + pub(crate) max_t: usize, + pub(crate) cell0: i64, + pub(crate) window: i64, + pub(crate) prompt_len: i64, +} pub(crate) struct PrefillGroups { next: usize, rows: usize, 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 7be995d8..a11d6664 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 @@ -45,13 +45,13 @@ pub(super) struct GdnLayer<'ctx> { } impl<'ctx> GdnLayer<'ctx> { pub(super) fn enter( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, - context: &'ctx Context<'ctx>, - layer: LayerId, + site: PromptLayerSite<'ctx>, lap: &mut Lap, ) -> Result<(Self, Vec)> { + let PromptWeights { binding, dense } = weights; + let PromptLayerSite { layer, context } = site; let prior = txn.gdn_prior(layer)?; lap.at(1, "in: gdn_prior"); let (start, rows) = GdnChunkStart::from_original_prompt(txn, layer, &prior)?; @@ -75,12 +75,12 @@ impl<'ctx> GdnLayer<'ctx> { } pub(super) fn leave( self, - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, '_>, edges: Vec, lap: &mut Lap, ) -> Result<()> { + let PromptWeights { binding, dense } = weights; let seal = GdnChunkSeal::from_original_prompt(txn, &self.start, edges)?; lap.at(5, "out: seal (row edges)"); let next = self.owner.finish(seal, binding, dense)?; @@ -108,18 +108,18 @@ pub(in super::super) fn produce_original_gdn<'arena, 'loan, 'ctx>( ) -> Result> { use super::super::super::prefill_profile::{Drain, Stage as P, span}; let PromptWeights { binding, dense } = weights; - let PromptLayerSite { layer, context } = site; + let context = site.context; let drain = Some(context as &dyn Drain); let mut lap = Lap::new("gdn-host"); let state_in = span(P::GdnStateIn, drain); - let (mut state, rows) = GdnLayer::enter(binding, dense, txn, context, layer, &mut lap)?; + let (mut state, rows) = GdnLayer::enter(weights, txn, site, &mut lap)?; drop(state_in); let compute = span(P::GdnCompute, drain); let (block, edges) = state.compute(binding, dense, PromptSource { rows, read }, gdn)?; drop(compute); lap.at(4, "compute: produce_prompt_device"); let _state_out = span(P::GdnStateOut, drain); - state.leave(binding, dense, txn, edges, &mut lap)?; + state.leave(weights, txn, edges, &mut lap)?; Ok(block) } @@ -214,14 +214,14 @@ impl<'a, 's, 'ctx> QsaLayerRun<'a, 's, 'ctx> { } } pub(in super::super) fn produce_original_qsa<'arena, 'loan, 'ctx>( - binding: &ModelBinding, - dense: &DenseWeightCache<'ctx>, + weights: PromptWeights<'_, 'ctx>, txn: &OriginalPromptTxn<'_, 'ctx>, - context: &'ctx Context<'ctx>, - layer: LayerId, + site: PromptLayerSite<'ctx>, read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, devices: QsaLayerDevices<'_, 'ctx>, ) -> Result> { + let PromptWeights { binding, dense } = weights; + let PromptLayerSite { layer, context } = site; let QsaLayerDevices { layer_owner, qsa, transport, attention } = devices; let mut run = QsaLayerRun::new(binding, dense, txn, context, layer)?; let selected = run.prepare(layer_owner, qsa, transport, read)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/read_completion.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/read_completion.rs index a12205c4..8dc9129f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/read_completion.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/read_completion.rs @@ -64,9 +64,10 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; 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 site = PromptLayerSite { layer, context }; + let (mut state, rows) = GdnLayer::enter(weights, txn, site, &mut lap)?; let (block, edges) = state.compute(binding, dense, PromptSource { rows, read }, gdn)?; - state.leave(binding, dense, txn, edges, &mut lap)?; + state.leave(weights, txn, edges, &mut lap)?; Ok(block) }) } @@ -89,10 +90,9 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx producer: &mut OriginalPromptDevice<'ctx>, devices: QsaLayerDevices<'_, 'ctx>, ) -> Result> { - let PromptWeights { binding, dense } = weights; let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?; self.complete_with(weights, producer, GrRole::Ffn(layer.get()), |read| { - produce_original_qsa(binding, dense, txn, context, layer, read, devices) + produce_original_qsa(weights, txn, PromptLayerSite { layer, context }, read, devices) }) } pub(in crate::qwen_forward) fn complete_original_qsa_normed<'weight>( @@ -102,10 +102,9 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx producer: &mut OriginalPromptDevice<'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(weights, producer, GrRole::Ffn(layer.get()), |read| { - produce_original_qsa(binding, dense, txn, context, layer, read, devices) + produce_original_qsa(weights, txn, PromptLayerSite { layer, context }, read, devices) }) } /// Complete actual FFN arithmetic on the same physical arena, then the diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_rows.rs index e1324eec..c8e77dc4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch/projection_rows.rs @@ -146,17 +146,13 @@ pub(super) fn gather_rows<'ctx>( context: &Context<'_>, ) -> Result<(Vec, Vec)> { let t = rows.len(); + let (weights, position) = (PromptWeights::new(binding, cache), ChunkLayer { chunk, layer }); let mut attended = Vec::new(); let mut gates = Vec::new(); attended.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; gates.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; for (local, row) in rows.iter().enumerate() { - row.validate( - PromptWeights::new(binding, cache), - ChunkLayer { chunk, layer }, - ProvenRow { local, proof: &proofs[local] }, - context, - )?; + row.validate(weights, position, ProvenRow { local, proof: &proofs[local] }, context)?; attended.extend_from_slice(row.values()); gates.extend_from_slice(row.gate()); } @@ -174,15 +170,11 @@ pub(super) fn ready_rows<'ctx>( (context, output): (&'ctx Context<'ctx>, &[f32]), ) -> Result> { let t = rows.len(); + let (weights, position) = (PromptWeights::new(binding, cache), ChunkLayer { chunk, layer }); let mut ready = Vec::new(); ready.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; for (local, row) in rows.iter().enumerate() { - row.validate( - PromptWeights::new(binding, cache), - ChunkLayer { chunk, layer }, - ProvenRow { local, proof: &proofs[local] }, - context, - )?; + row.validate(weights, position, ProvenRow { local, proof: &proofs[local] }, context)?; let mut values = Vec::new(); values.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; values.extend_from_slice(&output[local * 2560..(local + 1) * 2560]);