diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs index eefaa077..3c4aa078 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::MtpVerifiedWindow; pub(super) fn generate_mtp( run: Generation<'_, '_, '_, C>, @@ -9,16 +10,16 @@ pub(super) fn generate_mtp( generate_mtp_resume(run, prompt, max, None, &mut None) } -pub(super) fn generate_mtp_resume( - mut run: Generation<'_, '_, '_, C>, +/// The decoder to continue with, the product of the retained prefix, the tokens reused and the committed tokens so far. +type Resumed = (MtpDecoder, Option, usize, Vec); + +/// A fresh decoder, or the retained one after its prefix was validated against this prompt. +fn begin_decoder( + run: &mut Generation<'_, '_, '_, C>, prompt: &[u32], - max: u32, resume: Option, - publish: &mut Option, -) -> Result<(FinishReason, Usage), GenerationFailure> { - *publish = None; - let start = run.clock.now(); - let (mut decoder, mut latest, reused, mut committed) = match resume { +) -> Result { + Ok(match resume { Some(old) => { if !append_compatible(&old.tokens, prompt) { return Err(invalid("resident MTP prefix mismatch").into()); @@ -40,7 +41,154 @@ pub(super) fn generate_mtp_resume( 0, Vec::new(), ), - }; + }) +} + +/// Decode one token, push it through the UTF-8 buffer and emit the text it completes. +fn emit_token_text( + run: &Generation<'_, '_, '_, C>, + utf8: &mut Utf8Pending, + token: u32, +) -> Result<(), GenerationFailure> { + let bytes = run.tokenizer.decode_bytes(&[token]).map_err(|_| unavailable("MTP token decoding failed"))?; + if let Some(text) = utf8.push(&bytes)? { + run.emit(GenerationEvent::TextDelta { text })?; + } + Ok(()) +} + +/// The prompt's tiles after the retained prefix. Each tile preserves the genuine last-known-next edge. A final tile +/// obtains its actual head product; no intermediate greedy IDs are minted. +fn prefill_tiles( + run: &mut Generation<'_, '_, '_, C>, + prompt: &[u32], + decoder: &mut MtpDecoder, + start: Instant, + state: (usize, &mut Option, &mut Vec), +) -> Result<(), GenerationFailure> { + let (reused, latest, committed) = state; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts(); + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let adaptive_prefill = false; + let mut position = reused; + while position < prompt.len() { + if run.clock.since(start) > GENERATION_TIMEOUT { + return Err(unavailable("generation deadline exceeded").into()); + } + let mut end = position.saturating_add(run.prefill_tile_cap()).min(prompt.len()); + // Keep the last known-next edge and final head in one joint tile. + // A completed fresh KV warmer cannot admit a second final tile. + if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 { + end -= 1; + } + let next = prompt.get(end).copied(); + let product = if end - position == 1 && next.is_none() && !adaptive_prefill { + // Other policies keep the original lone-row actual-head producer. + Some(run.target_step(prompt[position], position)?) + } else { + run.prefill_chunk(&prompt[position..end], position, next, decoder, start)? + }; + if next.is_none() { + *latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?); + } else if product.is_some() { + return Err(invalid("unexpected intermediate prefill head").into()); + } + committed.extend_from_slice(&prompt[position..end]); + position = end; + } + Ok(()) +} + +/// The verified window from `product`: the cancel probe also watches the shutdown flag, the sink and the deadline. +fn verified_window( + run: &mut Generation<'_, '_, '_, C>, + decoder: &mut MtpDecoder, + product: TargetStepProduct, + spec: MtpWindowSpec, + start: Instant, +) -> Result { + let cancel = run.cancel; + let shared = run.shared; + let sink = run.sink; + 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 + }, + ) + .map_err(|e| match e { + MtpWindowError::Cancelled if run.clock.since(start) > GENERATION_TIMEOUT => { + GenerationFailure::Backend(unavailable("generation deadline exceeded")) + } + MtpWindowError::Cancelled => GenerationFailure::Cancelled, + MtpWindowError::Forward(error) => run.mtp_error(error), + }) +} + +/// Commit and emit the tokens of a verified window; returns the product to continue from and whether the window stopped. +fn commit_window( + run: &Generation<'_, '_, '_, C>, + window: MtpVerifiedWindow, + utf8: &mut Utf8Pending, + progress: (&mut Vec, &mut u64), +) -> Result<(TargetStepProduct, bool), GenerationFailure> { + let (committed, count) = progress; + { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-mtp phase=verified-window draft_steps={} accepted={}", + window.draft_steps(), + window.tokens().len() + ); + } + let draft_steps = window.draft_steps(); + let (tokens, next, stopped) = window.into_parts(); + run.observe(|r| { + let mut ids = [0; 4]; + if tokens.len() <= ids.len() { + for (slot, token) in ids.iter_mut().zip(&tokens) { + *slot = token.get(); + } + r.window(draft_steps, &ids[..tokens.len()], stopped); + } else { + r.window(draft_steps, &[u32::MAX; 5], stopped); + } + }); + if tokens.is_empty() && !stopped { + return Err(run.mtp_error(crate::qwen_forward::contract::Error::IdentityMismatch)); + } + for token in tokens { + run.observe(|r| r.token(token.get())); + committed.push(token.get()); + emit_token_text(run, utf8, token.get())?; + *count += 1; + } + Ok((next, stopped)) +} + +pub(super) fn generate_mtp_resume( + mut run: Generation<'_, '_, '_, C>, + prompt: &[u32], + max: u32, + resume: Option, + publish: &mut Option, +) -> Result<(FinishReason, Usage), GenerationFailure> { + *publish = None; + let start = run.clock.now(); + let (mut decoder, mut latest, reused, mut committed) = begin_decoder(&mut run, prompt, resume)?; run.observe(|r| r.retained(reused)); let vocabulary = Dimension::new(248320).map_err(|e| run.mtp_error(e))?; let eos = TokenId::new(u64::from(run.eos), vocabulary).map_err(|e| run.mtp_error(e))?; @@ -63,38 +211,7 @@ pub(super) fn generate_mtp_resume( 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))?; } - // Each tile preserves the genuine last-known-next edge. A final tile - // obtains its actual head product; no intermediate greedy IDs are minted. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts(); - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let adaptive_prefill = false; - let mut position = reused; - while position < prompt.len() { - if run.clock.since(start) > GENERATION_TIMEOUT { - return Err(unavailable("generation deadline exceeded").into()); - } - let mut end = position.saturating_add(run.prefill_tile_cap()).min(prompt.len()); - // Keep the last known-next edge and final head in one joint tile. - // A completed fresh KV warmer cannot admit a second final tile. - if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 { - end -= 1; - } - let next = prompt.get(end).copied(); - let product = if end - position == 1 && next.is_none() && !adaptive_prefill { - // Other policies keep the original lone-row actual-head producer. - Some(run.target_step(prompt[position], position)?) - } else { - run.prefill_chunk(&prompt[position..end], position, next, &mut decoder, start)? - }; - if next.is_none() { - latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?); - } else if product.is_some() { - return Err(invalid("unexpected intermediate prefill head").into()); - } - committed.extend_from_slice(&prompt[position..end]); - position = end; - } + prefill_tiles(&mut run, prompt, &mut decoder, start, (reused, &mut latest, &mut committed))?; let mut product = latest.ok_or_else(|| invalid("empty MTP prompt"))?; if reused == 0 && run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr { decoder.finish_kv_prefill(run.binding, run.session, &product, &committed).map_err(|e| run.mtp_error(e))?; @@ -122,13 +239,7 @@ pub(super) fn generate_mtp_resume( run.observe(|r| r.token(authoritative.get())); // The last public token is already authoritative. As in Native, // no draft or unused next-position target step runs at max output. - let bytes = run - .tokenizer - .decode_bytes(&[authoritative.get()]) - .map_err(|_| unavailable("MTP token decoding failed"))?; - if let Some(text) = utf8.push(&bytes)? { - run.emit(GenerationEvent::TextDelta { text })?; - } + emit_token_text(&run, &mut utf8, authoritative.get())?; count += 1; break FinishReason::Length; } @@ -138,68 +249,8 @@ pub(super) fn generate_mtp_resume( let _ = native_position(run.binding.input_constants(), run.context_tokens, position)?; let remaining = (max as usize - count as usize - 1).min(run.context_tokens as usize - position); let spec = MtpWindowSpec::new(4, remaining, Some(eos)).map_err(|e| run.mtp_error(e))?; - let cancel = run.cancel; - let shared = run.shared; - let sink = run.sink; - let window = 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 - }, - ) - .map_err(|e| match e { - MtpWindowError::Cancelled if run.clock.since(start) > GENERATION_TIMEOUT => { - GenerationFailure::Backend(unavailable("generation deadline exceeded")) - } - MtpWindowError::Cancelled => GenerationFailure::Cancelled, - MtpWindowError::Forward(error) => run.mtp_error(error), - })?; - { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-mtp phase=verified-window draft_steps={} accepted={}", - window.draft_steps(), - window.tokens().len() - ); - } - let draft_steps = window.draft_steps(); - let (tokens, next, stopped) = window.into_parts(); - run.observe(|r| { - let mut ids = [0; 4]; - if tokens.len() <= ids.len() { - for (slot, token) in ids.iter_mut().zip(&tokens) { - *slot = token.get(); - } - r.window(draft_steps, &ids[..tokens.len()], stopped); - } else { - r.window(draft_steps, &[u32::MAX; 5], stopped); - } - }); - if tokens.is_empty() && !stopped { - return Err(run.mtp_error(crate::qwen_forward::contract::Error::IdentityMismatch)); - } - for token in tokens { - run.observe(|r| r.token(token.get())); - committed.push(token.get()); - let bytes = - run.tokenizer.decode_bytes(&[token.get()]).map_err(|_| unavailable("MTP token decoding failed"))?; - if let Some(text) = utf8.push(&bytes)? { - run.emit(GenerationEvent::TextDelta { text })?; - } - count += 1; - } + let window = verified_window(&mut run, &mut decoder, product, spec, start)?; + let (next, stopped) = commit_window(&run, window, &mut utf8, (&mut committed, &mut count))?; product = next; if count == u64::from(max) { break FinishReason::Length;