STRA-338 size: engine backend/generate_mtp: generate_mtp_resume split into begin_decoder/prefill_tiles/verified_window/commit_window (fn_lines 216 -> ~85)
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
//! The MTP speculative generation loop.
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp_decode::MtpVerifiedWindow;
|
||||
|
||||
pub(super) fn generate_mtp<C: Clock>(
|
||||
run: Generation<'_, '_, '_, C>,
|
||||
@@ -9,16 +10,16 @@ pub(super) fn generate_mtp<C: Clock>(
|
||||
generate_mtp_resume(run, prompt, max, None, &mut None)
|
||||
}
|
||||
|
||||
pub(super) fn generate_mtp_resume<C: Clock>(
|
||||
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<TargetStepProduct>, usize, Vec<u32>);
|
||||
|
||||
/// A fresh decoder, or the retained one after its prefix was validated against this prompt.
|
||||
fn begin_decoder<C: Clock>(
|
||||
run: &mut Generation<'_, '_, '_, C>,
|
||||
prompt: &[u32],
|
||||
max: u32,
|
||||
resume: Option<MtpContinuation>,
|
||||
publish: &mut Option<MtpContinuation>,
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
*publish = None;
|
||||
let start = run.clock.now();
|
||||
let (mut decoder, mut latest, reused, mut committed) = match resume {
|
||||
) -> Result<Resumed, GenerationFailure> {
|
||||
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<C: Clock>(
|
||||
0,
|
||||
Vec::new(),
|
||||
),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode one token, push it through the UTF-8 buffer and emit the text it completes.
|
||||
fn emit_token_text<C: Clock>(
|
||||
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<C: Clock>(
|
||||
run: &mut Generation<'_, '_, '_, C>,
|
||||
prompt: &[u32],
|
||||
decoder: &mut MtpDecoder,
|
||||
start: Instant,
|
||||
state: (usize, &mut Option<TargetStepProduct>, &mut Vec<u32>),
|
||||
) -> 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<C: Clock>(
|
||||
run: &mut Generation<'_, '_, '_, C>,
|
||||
decoder: &mut MtpDecoder,
|
||||
product: TargetStepProduct,
|
||||
spec: MtpWindowSpec,
|
||||
start: Instant,
|
||||
) -> Result<MtpVerifiedWindow, GenerationFailure> {
|
||||
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<C: Clock>(
|
||||
run: &Generation<'_, '_, '_, C>,
|
||||
window: MtpVerifiedWindow,
|
||||
utf8: &mut Utf8Pending,
|
||||
progress: (&mut Vec<u32>, &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<C: Clock>(
|
||||
mut run: Generation<'_, '_, '_, C>,
|
||||
prompt: &[u32],
|
||||
max: u32,
|
||||
resume: Option<MtpContinuation>,
|
||||
publish: &mut Option<MtpContinuation>,
|
||||
) -> 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<C: Clock>(
|
||||
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<C: Clock>(
|
||||
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<C: Clock>(
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user