From 9c0605adde5b37f982fd16e097d5cf66028a438a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 08:46:38 +0200 Subject: [PATCH] fix(serve): run the short-prompt scalar draft K/V prefill on the drafter's own scalar owner (238ba17 from claude/serve-preflight) Prompts under 64 rows hit the Original's literal RegionTooSmall fallback in the MMQ draft-KV recorder and then ran the scalar prefill on a standalone owner whose scratch bank is not paired with the ring's main arena (validate_original_main -> InvalidQwenShape -> InvalidDimension). The drafter now lends its stream to its own scalar owner (OriginalMtpDrafter/Actor::record_scalar_prefill). Real model, RTX 5090: the 19-token and 56-token prompts of the smoke corpus now serve (16 resp. 10 tokens, the latter ending on <|im_end|>). Structural evidence only; no numerical claim. Co-Authored-By: Claude Sonnet 5.5 --- .../src/mtp_original_full_drafter.rs | 31 +++++ .../src/mtp_original_scalar_prefill.rs | 4 + .../src/mtp_original_scalar_short_gpu.rs | 107 ++++++++++++++++++ .../cuda-driver/src/native_prompt_device.rs | 5 + .../src/original_mtp_actor_loaded.rs | 20 ++++ .../qwen_forward/executor_original_prompt.rs | 5 +- .../original_mtp_scalar_prefill.rs | 6 +- 7 files changed, 174 insertions(+), 4 deletions(-) create mode 100644 crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs diff --git a/crates/cuda-driver/src/mtp_original_full_drafter.rs b/crates/cuda-driver/src/mtp_original_full_drafter.rs index 4fb5a164..65d981b8 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter.rs @@ -406,6 +406,37 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { } combine(cleared, source) } + /// The scalar (non-MMQ) draft K/V prefill of a short prompt, run on THIS drafter's own scalar owner. The ring of the shared + /// layout is paired with that owner's main arena (`validate_original_main`): a standalone `original_mtp_scalar_prefill` + /// owns another scratch bank and is refused with InvalidQwenShape. `Drafter::new` moved the owner's stream into the drafter, + /// so it is lent back for the call (the Original's `mtp.prefill` runs on the drafter's `cs_`). + #[allow(clippy::too_many_arguments)] + pub fn record_scalar_prefill<'arena, 'loan>( + &mut self, + residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut crate::NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.validate_context(self.context)?; + let stream = self.stream.take().ok_or(Error::ContextPoisoned)?; + let scalar = self.scalar.as_mut().ok_or(Error::ContextPoisoned)?; + scalar.stream = Some(stream); + let result = scalar.record( + residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, + ); + self.stream = scalar.stream.take(); + if self.stream.is_none() || result.is_err() && self.context.is_poisoned() { + self.failed = true; + } + result + } pub fn close(mut self) -> Result<()> { self.close_inner() } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs index f0be9129..d2431b61 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs @@ -1474,3 +1474,7 @@ impl Drop for OriginalMtpScalarPrefill<'_> { #[path = "mtp_original_scalar_graph.rs"] mod graph; + +#[cfg(test)] +#[path = "mtp_original_scalar_short_gpu.rs"] +mod short_prompt_gpu; diff --git a/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs b/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs new file mode 100644 index 00000000..107ce0a6 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs @@ -0,0 +1,107 @@ +//! Root-only, model-free GPU proof of the short-prompt (scalar) draft K/V prefill the serve stack falls back to when the MMQ +//! prefill reports `RegionTooSmall` (prompts under 64 rows). Weights are uninitialised stand-ins of the exact sizes; nothing is +//! compared numerically. Enable with `LELEKA_MTP_SCALAR_SHORT_GPU=yes`. +use super::*; +use crate::{Driver, NativeHeadDispatch, PrefillKvStage, PrefillLayoutOptions}; +use std::rc::Rc; + +const ENABLE: &str = "LELEKA_MTP_SCALAR_SHORT_GPU"; + +fn options(capacity: usize) -> PrefillLayoutOptions { + let cells = 262_144usize; + PrefillLayoutOptions { + capacity, + n_expert: 512, + qsa_heads: 24, + qsa_selection: 2051, + qsa_max_blocks: cells / 4 + 2, + mmq_any: true, + mmq_fallback: false, + mmq_gu_max: 1_408_000, + mmq_down_max: 921_600, + max_expert_blob: 2_329_600, + pinned_share: 1.0, + stream_all_min: 1024, + ring_override: None, + gr_unfused: false, + bf16x2: false, + bf16x2_hc: false, + kv_stage: PrefillKvStage::Int8 { rows: cells * 2, head_dim: 256, without_key: false }, + kv_stage_own: false, + } +} + +#[test] +#[ignore = "Root-only: needs a CUDA device"] +fn short_prompts_record_on_the_drafters_own_scalar_owner_not_on_a_standalone_one() { + assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device"); + let context = device.create_context(6usize << 30).expect("context"); + let (max_t, capacity, vocab) = (6usize, 1024usize, 248_320usize); + let alloc = |n: usize| context.allocate(n).map(Rc::new).expect("alloc"); + + // scalar prefix bank + let extents = [10240, 2560 * 80 * 34, 40960, 2560 * 80 * 34, 40960, 320 * 10240 * 2, 10240 * 320 * 2, 512 * 80 * 34, 512 * 80 * 34, 1024, 4 * 10240 * 2]; + let roles: [Rc; 11] = extents.map(alloc); + let table = alloc(1100 * vocab); + let descriptor = OriginalMtpEmbedding::native(&table, 21, 1100, vocab).expect("embedding"); + let scalar_bank = Rc::new(OriginalMtpRetainedScalarWeights::retain(&context, roles, Rc::clone(&table), &descriptor).expect("scalar bank")); + let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(Rc::clone(&scalar_bank)).expect("prefix")); + // full bank + let full_extents: [usize; 15] = [ + 12288 * 80 * 34, 1024, 2560 * 192 * 34, 40960, 320 * 10240 * 2, 10240 * 320 * 2, 4 * 10240 * 2, 512 * 2560 * 2, + 640 * 80 * 34, 640 * 80 * 34, 2560 * 20 * 34, 5120, 40960, 320 * 10240 * 2, 10240 * 320 * 2, + ]; + let full_roles: [Rc; 15] = full_extents.map(alloc); + let weights = Rc::new( + OriginalMtpRetainedFullWeights::retain( + &context, prefix, full_roles, alloc(512 * 1_382_400), alloc(1100 * vocab), 21, vocab, vocab, None, NativeHeadDispatch::default(), + ) + .expect("full bank"), + ); + let (mut ring, scalar_shared, full) = + context.original_mtp_shared_layout_with_ring(Rc::clone(&weights), max_t, capacity, false).expect("shared layout"); + let mut drafter = OriginalMtpDrafter::new(full, scalar_shared).expect("drafter"); + let mut standalone = context.original_mtp_scalar_prefill(max_t, capacity).expect("standalone scalar owner"); + + let policy = OriginalMtpScalarPolicy { gr: OriginalMtpGrVariant::Plain, per_group_sync: false, kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)) }; + let mut workspace = context.native_batch_workspace().expect("workspace"); + let mut arena = context.original_prefill_arena(options(capacity)).expect("arena"); + + let mut standalone_refused = 0; + for n in [19usize, 56, 63, 2, 64] { + let tokens: Vec = (0..n as i32).map(|i| 1000 + i).collect(); + // both owners start from the empty ring each time + let prior = ring.empty_snapshot().expect("empty snapshot"); + ring.restore(&mut workspace, &prior).expect("ring reset"); + let rows = arena.begin_rows(n).expect("rows"); + let mut residual = OriginalDeviceResidual::for_probe(rows); + // the pre-fix wiring: a standalone owner against the paired ring + let old = standalone.record(&mut residual, &mut workspace, &mut ring, &prior, &tokens, 0, 0, Rc::clone(&scalar_bank), &policy, || false); + eprintln!("PREFLIGHT short n={n} standalone scalar owner: {:?}", old.as_ref().map(|_| "ok")); + if matches!(old, Err(Error::InvalidQwenShape)) { + standalone_refused += 1; + } + drop(residual); + let rows = arena.begin_rows(n).expect("rows"); + let mut residual = OriginalDeviceResidual::for_probe(rows); + let prior = ring.empty_snapshot().expect("empty snapshot"); + ring.restore(&mut workspace, &prior).expect("ring reset"); + let outcome = drafter + .record_scalar_prefill(&mut residual, &mut workspace, &mut ring, &prior, &tokens, 0, 0, Rc::clone(&scalar_bank), &policy, || false) + .unwrap_or_else(|e| panic!("n={n}: the drafter's own scalar owner refused: {e:?}")); + eprintln!("PREFLIGHT short n={n} drafter scalar owner: {}", match outcome { + DraftKvOutcome::Completed(_) => "completed", + DraftKvOutcome::Skipped => "skipped", + DraftKvOutcome::Cancelled => "cancelled", + DraftKvOutcome::Fallback(_) => "fallback", + }); + assert!(matches!(outcome, DraftKvOutcome::Completed(_)), "n={n}"); + } + eprintln!("PREFLIGHT standalone owner refused {standalone_refused} of 5 prompts"); + drop(arena); + standalone.close().expect("standalone close"); + drafter.close().expect("drafter close"); + ring.close().expect("ring close"); +} diff --git a/crates/cuda-driver/src/native_prompt_device.rs b/crates/cuda-driver/src/native_prompt_device.rs index 59b42ae1..3bde02fa 100644 --- a/crates/cuda-driver/src/native_prompt_device.rs +++ b/crates/cuda-driver/src/native_prompt_device.rs @@ -126,6 +126,11 @@ impl<'ctx> Context<'ctx> { } } impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { + /// Test-only: a residual over a bare row lease (the GPU short-prompt probe has no model rows). + #[cfg(test)] + pub(crate) fn for_probe(lease: OriginalPromptRows<'arena, 'loan, 'ctx>) -> Self { + Self { lease } + } pub(crate) fn lease(&self) -> &OriginalPromptRows<'arena, 'loan, 'ctx> { &self.lease } diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded.rs b/crates/cuda-driver/src/original_mtp_actor_loaded.rs index 40364df4..f2a1c982 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded.rs @@ -288,6 +288,26 @@ impl<'ctx> OriginalMtpActor<'ctx> { .idle_public() } + /// Scalar draft K/V prefill on the actor's own scalar owner (short prompts; see `OriginalMtpDrafter::record_scalar_prefill`). + #[allow(clippy::too_many_arguments)] + pub fn record_scalar_prefill<'arena, 'loan>( + &mut self, + residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut crate::NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &crate::OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill( + residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, + ) + } + /// Release everything the drafter bound to the verifier bank of the request that just ended (see /// `OriginalMtpDrafter::release_verifier_bindings`). Call it before the verifier is closed. pub fn release_verifier_bindings(&mut self) -> Result<()> { diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs index 7d74394d..38dd9bc4 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs @@ -332,7 +332,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{ let sample=OriginalPromptSample::conditioning(binding,&final_row,&txn).map_err(|e|{eprintln!("DBG[{:.0}s] sample conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; eprintln!("DBG[{:.0}s] sample ok",crate::qwen_forward::original_serve_stack::dbg_el()); let producer=self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?; - let scalar=self.mtp_scalar.as_mut().ok_or(Error::IdentityMismatch)?; + // The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared layout is paired + // with that owner's main arena, a standalone owner is refused with InvalidQwenShape. + let (context,max_t)=(self.context,self.max_t); + let scalar=self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t)?; let scalar_weights=std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?); let draft_kv=draft.with_pending_ring(binding,&txn,|ring,prior,first_needed|{ eprintln!("DBG[{:.0}s] draft ring open first_needed={first_needed:?}",crate::qwen_forward::original_serve_stack::dbg_el()); diff --git a/crates/leleka-runtime/src/qwen_forward/original_mtp_scalar_prefill.rs b/crates/leleka-runtime/src/qwen_forward/original_mtp_scalar_prefill.rs index ac87b59e..2a6a9683 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_mtp_scalar_prefill.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_mtp_scalar_prefill.rs @@ -1,7 +1,7 @@ //! Private child of genuine original_mtp_prefill runtime adapter. Same Final //! phase, shifted actual IDs and current ring receipt, literal scalar producer. use super::*; -use leleka_cuda_driver::{OriginalMtpScalarPrefill,OriginalMtpRetainedScalarWeights,OriginalMtpScalarPolicy}; +use leleka_cuda_driver::{OriginalMtpActor,OriginalMtpRetainedScalarWeights,OriginalMtpScalarPolicy}; impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx> { /// Original Prefill uses only known-next conditioning with no head/D2H. /// The genuine all-row R and immutable input owners survive through drain. @@ -9,7 +9,7 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx> { pub(in crate::qwen_forward) fn record_original_scalar_draft_kv( &mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,mtp:&MoeWeightCache<'ctx>, txn:&OriginalPromptTxn<'_, '_>,preview:&PromptDeviceFinal,last_next:TokenId, - producer:&mut OriginalMtpScalarPrefill<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>, + producer:&mut OriginalMtpActor<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>, ring:&mut MtpOriginalInt8<'ctx>,prior:&MtpInt8Snapshot, retained:Rc>,first_needed:usize,policy:&OriginalMtpScalarPolicy, cancelled:impl FnMut()->bool, @@ -56,7 +56,7 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx> { }).map_err(micro_driver_error)?; // Input/draft host policy and all eleven immutable device owners are live // throughout drain; never mint scalar committed products for prior rows. - let result=producer.record(&mut self.device,workspace,ring,prior,&next, + let result=producer.record_scalar_prefill(&mut self.device,workspace,ring,prior,&next, usize::try_from(txn.start_position()).map_err(|_|Error::Overflow)?,first_needed, retained,policy,cancelled).map_err(micro_driver_error)?; self.sources.validate(binding,dense)?;txn.validate_final(preview)?;