STRA-338 size: split OriginalPromptExecutor::forward into per-phase helpers
This commit is contained in:
+143
-442
@@ -3,6 +3,19 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "impl_originalpromptexecutor/forward_draft.rs"]
|
||||
mod forward_draft;
|
||||
#[path = "impl_originalpromptexecutor/forward_final.rs"]
|
||||
mod forward_final;
|
||||
#[path = "impl_originalpromptexecutor/forward_input.rs"]
|
||||
mod forward_input;
|
||||
#[path = "impl_originalpromptexecutor/forward_layers.rs"]
|
||||
mod forward_layers;
|
||||
|
||||
/// The draft session, its embedding and the scalar policy that record the draft KV of a chunk.
|
||||
type DraftArgs<'a, 'ctx> =
|
||||
(&'a mut OriginalDraftSession<'ctx>, &'a OriginalPromptEmbedding<'ctx>, &'a OriginalMtpScalarPolicy);
|
||||
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
/// No target position is advanced here. Every read is actual GR arithmetic;
|
||||
/// recurrent/KV/PLE seals belong to the same still-private source transaction.
|
||||
@@ -14,7 +27,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
session: &'session mut QwenSession<'ctx>,
|
||||
source: &std::rc::Rc<OriginalPromptInput>,
|
||||
count: usize,
|
||||
mut kar: Option<&mut KarPleCache<'ctx>>,
|
||||
kar: Option<&mut KarPleCache<'ctx>>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
arena: &mut OriginalPrefillArena<'loan, 'ctx>,
|
||||
draft: &'program mut OriginalDraftSession<'ctx>,
|
||||
@@ -22,16 +35,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
policy: &OriginalMtpScalarPolicy,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
) -> Result<OriginalPromptPending<'session, 'program, 'ctx>> {
|
||||
self.validate(binding, dense, session)?;
|
||||
let first_position = session.target_origin()?.next_position();
|
||||
let tokens = source.window(binding, first_position, count)?;
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={} count={count}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
tokens.len(),
|
||||
self.capacity,
|
||||
arena.capacity()
|
||||
);
|
||||
let (tokens, first_position) = self.admit_window(binding, dense, session, source, count, arena.capacity())?;
|
||||
let _launch_sync = leleka_cuda_driver::PromptSyncTrace::enter();
|
||||
if tokens.is_empty() || tokens.len() > self.capacity || arena.capacity() != self.capacity {
|
||||
return Err(Error::InvalidDimension);
|
||||
@@ -39,439 +43,60 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
let checkpoint = session.original_checkpoint(binding)?;
|
||||
let draft_checkpoint = draft.checkpoint(binding, session)?;
|
||||
let mut txn = OriginalPromptTxn::begin(session, binding, source, count)?;
|
||||
let profile_context = self.context;
|
||||
let drain = Some(profile_context as &dyn prof::Drain);
|
||||
let operation = (|| {
|
||||
// The last prompt seed belongs to Original Verifier. Every row
|
||||
// admitted here must have its authentic next token in the source.
|
||||
txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?;
|
||||
let input_span = prof::span(PStage::Input, None);
|
||||
// KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device
|
||||
// (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm).
|
||||
let mut staged_input = None;
|
||||
let mut staged_ple = None;
|
||||
let mut first_predecessors: Option<[i32; 2]> = None;
|
||||
if binding.kar_ple_binding().is_some() && staged_input_enabled() {
|
||||
let mut staged = StagedInput::default();
|
||||
for &token in tokens {
|
||||
txn.stage_input(|step| {
|
||||
let pos = step.position();
|
||||
if first_predecessors.is_none() {
|
||||
first_predecessors = Some(step.input_predecessors()?);
|
||||
}
|
||||
match kar.as_deref() {
|
||||
Some(cache) => {
|
||||
InputStage::consume_kar_deferred(binding, cache, token, pos, step, &mut staged)
|
||||
}
|
||||
None => Err(Error::IdentityMismatch),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let kar_binding = binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?;
|
||||
let _ple_span = prof::span(PStage::InputPle, None);
|
||||
staged_ple = Some(cache.stage_batch(kar_binding, staged.ple_rows())?);
|
||||
staged_input = Some(staged);
|
||||
} else {
|
||||
for &token in tokens {
|
||||
txn.stage_input(|step| {
|
||||
let pos = step.position();
|
||||
match (binding.kar_ple_binding(), kar.as_deref_mut()) {
|
||||
(None, None) => InputStage::consume(binding, token, pos, step),
|
||||
(Some(_), Some(cache)) => InputStage::consume_kar(binding, cache, token, pos, step),
|
||||
_ => Err(Error::IdentityMismatch),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
drop(input_span);
|
||||
let init_span = prof::span(PStage::Initialize, drain);
|
||||
let mut sources = Vec::new();
|
||||
sources.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let sources_span = prof::span(PStage::InitSources, None);
|
||||
for local in 0..tokens.len() {
|
||||
sources.push(PromptDeviceSource::from_original(binding, self.context, &txn, local)?);
|
||||
}
|
||||
drop(sources_span);
|
||||
let upload_span = prof::span(PStage::InitUpload, drain);
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let lease = arena.begin_rows(tokens.len()).map_err(driver_error)?;
|
||||
let rows = match (staged_input.as_ref(), staged_ple) {
|
||||
(Some(input), Some(ple)) => {
|
||||
let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let result = {
|
||||
let (ple_cache, ple_books) = cache.device_parts();
|
||||
let stage = PromptInputStage {
|
||||
embedding_rows: input.embedding_rows(),
|
||||
embedding_index: input.embedding_index(),
|
||||
ple_cache,
|
||||
ple_books,
|
||||
ple_updates: ple.updates(),
|
||||
ple_slots: ple.slots(),
|
||||
};
|
||||
PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, Some(stage))
|
||||
};
|
||||
match result {
|
||||
Ok(rows) => {
|
||||
cache.commit(ple);
|
||||
rows
|
||||
}
|
||||
// the device may already hold part of the scatter: the cache is not trusted again
|
||||
Err(error) => {
|
||||
cache.invalidate();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, None)?,
|
||||
};
|
||||
drop(upload_span);
|
||||
drop(init_span);
|
||||
// The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes
|
||||
// (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there.
|
||||
if let (Some(cache), Some(kar_binding), Some(mut before)) =
|
||||
(kar.as_deref_mut(), binding.kar_ple_binding(), first_predecessors)
|
||||
{
|
||||
let next_first = first_position + tokens.len() as u64;
|
||||
let want = self.capacity.min(source.len().saturating_sub(next_first as usize));
|
||||
if want > 0 {
|
||||
if let Ok(next) = source.window(binding, next_first, want) {
|
||||
for &token in tokens {
|
||||
before = [before[1], token.get() as i32];
|
||||
}
|
||||
if let Ok(rows) = InputStage::ple_rows_ahead(binding, before, next) {
|
||||
cache.read_ahead(kar_binding, &rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut carrier = Carrier::Plain(rows);
|
||||
for layer in binding.ordered_layers() {
|
||||
let index = layer.index();
|
||||
let role = super::super::super::super::super::gr::GrRole::Attention(index);
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward layer {index} {:?} begin",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
layer.kind()
|
||||
);
|
||||
if index == 1 {
|
||||
let Carrier::Plain(mut rows) = carrier else {
|
||||
return Err(Error::IdentityMismatch);
|
||||
};
|
||||
{
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
rows.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
let _span = prof::span(PStage::Ple, drain);
|
||||
let prior = txn.ple_prior()?;
|
||||
let mut history = InputStage::prepare_original_prompt_history(binding, dense, self.context, &txn)?;
|
||||
rows = rows.apply_ple(binding, dense, prompt, &mut history)?;
|
||||
InputStage::finish_original_prompt_history(binding, &txn, &prior, history)?;
|
||||
// The completed PLE operation changes the real row state.
|
||||
// Its output must pass fresh current-row validation.
|
||||
carrier = Carrier::Plain(rows);
|
||||
}
|
||||
let mut read = match carrier {
|
||||
Carrier::Plain(mut rows) => {
|
||||
{
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
rows.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
let _span = prof::span(PStage::AttnRead, drain);
|
||||
rows.read(binding, dense, prompt, role)?
|
||||
}
|
||||
Carrier::Normed(mut rows) => {
|
||||
{
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
rows.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
let _span = prof::span(PStage::AttnRead, drain);
|
||||
rows.read(binding, dense, prompt)?
|
||||
}
|
||||
};
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] L{index} attn-read ok",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
{
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
read.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
let mixer_span = prof::span(
|
||||
match layer.kind() {
|
||||
BoundLayerKind::Gdn => PStage::Gdn,
|
||||
BoundLayerKind::Qsa => PStage::Qsa,
|
||||
},
|
||||
drain,
|
||||
);
|
||||
let mut ffn = if self.fused {
|
||||
let rows = match layer.kind() {
|
||||
BoundLayerKind::Gdn => read.complete_original_gdn_normed(
|
||||
binding,
|
||||
dense,
|
||||
&txn,
|
||||
prompt,
|
||||
self.gdn.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
)?,
|
||||
BoundLayerKind::Qsa => read.complete_original_qsa_normed(
|
||||
binding,
|
||||
dense,
|
||||
&txn,
|
||||
prompt,
|
||||
self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
)?,
|
||||
};
|
||||
Carrier::Normed(rows)
|
||||
} else {
|
||||
let rows = match layer.kind() {
|
||||
BoundLayerKind::Gdn => read.complete_original_gdn(
|
||||
binding,
|
||||
dense,
|
||||
&txn,
|
||||
prompt,
|
||||
self.gdn.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
)?,
|
||||
BoundLayerKind::Qsa => read.complete_original_qsa(
|
||||
binding,
|
||||
dense,
|
||||
&txn,
|
||||
prompt,
|
||||
self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
)?,
|
||||
};
|
||||
Carrier::Plain(rows)
|
||||
};
|
||||
drop(mixer_span);
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] L{index} mixer ok",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
{
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
match &mut ffn {
|
||||
Carrier::Plain(rows) => {
|
||||
rows.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
Carrier::Normed(rows) => {
|
||||
rows.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
};
|
||||
}
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] L{index} ffn-validate ok",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
let ffn_span = prof::span(PStage::FfnRead, drain);
|
||||
let mut read = match ffn {
|
||||
Carrier::Plain(rows) => {
|
||||
rows.read(binding, dense, prompt, super::super::super::super::super::gr::GrRole::Ffn(index))?
|
||||
}
|
||||
Carrier::Normed(rows) => rows.read(binding, dense, prompt)?,
|
||||
};
|
||||
drop(ffn_span);
|
||||
{
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
read.validate_original_rows(binding, dense)?;
|
||||
}
|
||||
let moe_span = prof::span(PStage::Moe, drain);
|
||||
// Literal fused GR norm is prohibited across PLE and final head.
|
||||
carrier = if self.fused && index != 0 && index != 47 {
|
||||
Carrier::Normed(read.complete_original_moe_normed(binding, dense, moe, prompt)?)
|
||||
} else {
|
||||
Carrier::Plain(read.complete_original_moe(binding, dense, moe, prompt)?)
|
||||
};
|
||||
drop(moe_span);
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] L{index} moe ok",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
}
|
||||
let Carrier::Plain(mut rows) = carrier else {
|
||||
return Err(Error::IdentityMismatch);
|
||||
};
|
||||
// the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers
|
||||
moe.end_prompt_stream()?;
|
||||
let final_span = prof::span(PStage::Final, drain);
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward: all layers ok, final row",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
let final_row = rows.preview_conditioning(binding, dense, &txn).map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] preview_conditioning err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] final_row ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
// Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R
|
||||
// (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default.
|
||||
if crate::settings::process().diagnostics.trace_prefill_r {
|
||||
let first = txn.start_position();
|
||||
let count = txn.len();
|
||||
let hash = rows.with_final_residual(binding, dense, &txn, &final_row, |residual| {
|
||||
let mut hash = 0xcbf29ce484222325u64;
|
||||
let mut rows_hash = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
let row = residual.read_prompt_row(index).map_err(driver_error)?;
|
||||
let mut row_hash = 0xcbf29ce484222325u64;
|
||||
for value in row.iter() {
|
||||
for byte in value.to_le_bytes() {
|
||||
row_hash ^= u64::from(byte);
|
||||
row_hash = row_hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
}
|
||||
hash ^= row_hash;
|
||||
hash = hash.wrapping_mul(0x100000001b3);
|
||||
rows_hash.push(row_hash);
|
||||
}
|
||||
Ok((hash, rows_hash))
|
||||
})?;
|
||||
eprintln!(
|
||||
"PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}",
|
||||
hash.0,
|
||||
hash.1[0],
|
||||
hash.1[count - 1]
|
||||
);
|
||||
}
|
||||
let sample = OriginalPromptSample::conditioning(binding, &final_row, &txn).map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] sample conditioning err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] sample ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
drop(final_span);
|
||||
let draft_span = prof::span(PStage::DraftKv, drain);
|
||||
let producer = self.mtp_prefill.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 retained_mtp = self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?;
|
||||
let draft_kv = draft
|
||||
.with_pending_ring(binding, &txn, |ring, prior, first_needed| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] draft ring open first_needed={first_needed:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
let mut workspace =
|
||||
dense.native_batch_workspace(binding, self.context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let outcome = rows.record_original_draft_kv(
|
||||
binding,
|
||||
dense,
|
||||
moe,
|
||||
&txn,
|
||||
&final_row,
|
||||
sample.next(),
|
||||
producer,
|
||||
&mut workspace,
|
||||
ring,
|
||||
prior,
|
||||
embedding.borrow(binding, self.context)?,
|
||||
first_needed,
|
||||
&policy.kv,
|
||||
&mut cancelled,
|
||||
)?;
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] record_original_draft_kv -> {}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
match &outcome {
|
||||
OriginalPromptDraftOutcome::Completed(_) => "Completed",
|
||||
OriginalPromptDraftOutcome::Fallback(reason) => {
|
||||
crate::bringup_trace!("DBG fallback reason: {reason:?}");
|
||||
"Fallback"
|
||||
}
|
||||
OriginalPromptDraftOutcome::Skipped => "Skipped",
|
||||
OriginalPromptDraftOutcome::Cancelled => "Cancelled",
|
||||
}
|
||||
);
|
||||
let outcome = match outcome {
|
||||
OriginalPromptDraftOutcome::Fallback(_) => rows.record_original_scalar_draft_kv(
|
||||
binding,
|
||||
dense,
|
||||
&retained_mtp,
|
||||
&txn,
|
||||
&final_row,
|
||||
sample.next(),
|
||||
scalar,
|
||||
&mut workspace,
|
||||
ring,
|
||||
prior,
|
||||
scalar_weights,
|
||||
first_needed,
|
||||
policy,
|
||||
&mut cancelled,
|
||||
)?,
|
||||
other => other,
|
||||
};
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] after scalar fallback -> {}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
match &outcome {
|
||||
OriginalPromptDraftOutcome::Completed(_) => "Completed",
|
||||
OriginalPromptDraftOutcome::Fallback(_) => "Fallback",
|
||||
OriginalPromptDraftOutcome::Skipped => "Skipped",
|
||||
OriginalPromptDraftOutcome::Cancelled => "Cancelled",
|
||||
}
|
||||
);
|
||||
match outcome {
|
||||
OriginalPromptDraftOutcome::Completed(completed) => Ok(completed),
|
||||
// Optional unported storage and actual no-materialization
|
||||
// need separate genuine outcomes; refusal advances neither.
|
||||
OriginalPromptDraftOutcome::Fallback(_)
|
||||
| OriginalPromptDraftOutcome::Skipped
|
||||
| OriginalPromptDraftOutcome::Cancelled => Err(Error::Unsupported(Stage::Session)),
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] with_pending_ring err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward: draft kv ok",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
drop(draft_span);
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Session));
|
||||
}
|
||||
let _span = prof::span(PStage::FinishPreview, drain);
|
||||
rows.finish_after_preview(binding, dense, &txn, &final_row).map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] finish_after_preview err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
Ok((final_row, sample, draft_kv))
|
||||
})();
|
||||
let operation = self.forward_operation(
|
||||
binding,
|
||||
dense,
|
||||
&mut txn,
|
||||
(tokens, first_position),
|
||||
source,
|
||||
kar,
|
||||
moe,
|
||||
arena,
|
||||
(&mut *draft, embedding, policy),
|
||||
&mut cancelled,
|
||||
);
|
||||
self.finish_forward(operation, binding, dense, txn, moe, (draft, checkpoint, draft_checkpoint))
|
||||
}
|
||||
|
||||
/// The prompt window of the chunk and its first position, after the executor accepted the session.
|
||||
fn admit_window<'src>(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
session: &mut QwenSession<'ctx>,
|
||||
source: &'src std::rc::Rc<OriginalPromptInput>,
|
||||
count: usize,
|
||||
arena_capacity: usize,
|
||||
) -> Result<(&'src [TokenId], u64)> {
|
||||
self.validate(binding, dense, session)?;
|
||||
let first_position = session.target_origin()?.next_position();
|
||||
let tokens = source.window(binding, first_position, count)?;
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={arena_capacity} count={count}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
tokens.len(),
|
||||
self.capacity
|
||||
);
|
||||
Ok((tokens, first_position))
|
||||
}
|
||||
|
||||
/// An error rolls the transaction and the draft back; success leaves the pending target for the publisher.
|
||||
fn finish_forward<'session, 'program>(
|
||||
&'program mut self,
|
||||
operation: Result<(PromptDeviceFinal, OriginalPromptSample, OriginalDraftKvPending)>,
|
||||
binding: &'program ModelBinding,
|
||||
dense: &'program DenseWeightCache<'ctx>,
|
||||
txn: OriginalPromptTxn<'session, 'ctx>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
(draft, checkpoint, draft_checkpoint): (
|
||||
&'program mut OriginalDraftSession<'ctx>,
|
||||
OriginalSessionCheckpoint<'ctx>,
|
||||
OriginalDraftCheckpoint,
|
||||
),
|
||||
) -> Result<OriginalPromptPending<'session, 'program, 'ctx>> {
|
||||
match operation {
|
||||
Err(primary) => {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward operation failed: {primary:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
// stop the chunk's expert stream before the transaction rolls back
|
||||
if moe.end_prompt_stream().is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
let cleanup =
|
||||
txn.abort_with_draft(binding, dense, &mut self.layers, &checkpoint, draft, &draft_checkpoint);
|
||||
if cleanup.is_err() || self.context.is_poisoned() {
|
||||
self.failed = true;
|
||||
}
|
||||
self.forward_failed(binding, dense, txn, moe, (&checkpoint, draft, &draft_checkpoint), &primary);
|
||||
Err(primary)
|
||||
}
|
||||
Ok((completed, sample, draft_kv)) => Ok(OriginalPromptPending {
|
||||
@@ -489,4 +114,80 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole fallible part of one chunk: input staging, row initialization, every layer, the final row and
|
||||
/// the draft KV. Its error is rolled back by `forward`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn forward_operation<'program, 'loan>(
|
||||
&mut self,
|
||||
binding: &'program ModelBinding,
|
||||
dense: &'program DenseWeightCache<'ctx>,
|
||||
txn: &mut OriginalPromptTxn<'_, 'ctx>,
|
||||
(tokens, first_position): (&[TokenId], u64),
|
||||
source: &std::rc::Rc<OriginalPromptInput>,
|
||||
mut kar: Option<&mut KarPleCache<'ctx>>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
arena: &mut OriginalPrefillArena<'loan, 'ctx>,
|
||||
draft_args: DraftArgs<'_, 'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<(PromptDeviceFinal, OriginalPromptSample, OriginalDraftKvPending)> {
|
||||
// The last prompt seed belongs to Original Verifier. Every row
|
||||
// admitted here must have its authentic next token in the source.
|
||||
txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?;
|
||||
let (staged_input, staged_ple, first_predecessors) = Self::stage_prompt_inputs(binding, txn, tokens, &mut kar)?;
|
||||
let rows = self.initialize_prompt_rows(
|
||||
binding,
|
||||
dense,
|
||||
txn,
|
||||
tokens,
|
||||
&mut kar,
|
||||
arena,
|
||||
(staged_input.as_ref(), staged_ple),
|
||||
)?;
|
||||
self.read_ahead_next_chunk(binding, source, (tokens, first_position), &mut kar, first_predecessors);
|
||||
let carrier = self.run_layers(binding, dense, moe, txn, Carrier::Plain(rows))?;
|
||||
let (mut rows, final_row, sample) = self.prepare_final_row(binding, dense, moe, txn, carrier)?;
|
||||
let draft_kv =
|
||||
self.record_draft_kv(binding, dense, moe, txn, (&mut rows, &final_row, &sample), draft_args, cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Session));
|
||||
}
|
||||
let _span = prof::span(PStage::FinishPreview, Some(self.context as &dyn prof::Drain));
|
||||
rows.finish_after_preview(binding, dense, txn, &final_row).map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] finish_after_preview err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
Ok((final_row, sample, draft_kv))
|
||||
}
|
||||
|
||||
/// Roll back after a failed chunk: stop the expert stream, then abort the transaction and the draft.
|
||||
fn forward_failed(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
txn: OriginalPromptTxn<'_, 'ctx>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
(checkpoint, draft, draft_checkpoint): (
|
||||
&OriginalSessionCheckpoint<'ctx>,
|
||||
&mut OriginalDraftSession<'ctx>,
|
||||
&OriginalDraftCheckpoint,
|
||||
),
|
||||
primary: &Error,
|
||||
) {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward operation failed: {primary:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
// stop the chunk's expert stream before the transaction rolls back
|
||||
if moe.end_prompt_stream().is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
let cleanup = txn.abort_with_draft(binding, dense, &mut self.layers, checkpoint, draft, draft_checkpoint);
|
||||
if cleanup.is_err() || self.context.is_poisoned() {
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
//! STRA-338 size: the draft-KV phase of `OriginalPromptExecutor::forward`.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_driver::{MtpInt8Snapshot, MtpOriginalInt8, NativeBatchWorkspace, OriginalMtpActor};
|
||||
|
||||
/// The read-only inputs both draft-KV producers (batched and scalar fallback) take from the chunk.
|
||||
struct DraftKvInputs<'a, 'ctx> {
|
||||
binding: &'a ModelBinding,
|
||||
dense: &'a DenseWeightCache<'ctx>,
|
||||
moe: &'a MoeWeightCache<'ctx>,
|
||||
txn: &'a OriginalPromptTxn<'a, 'ctx>,
|
||||
final_row: &'a PromptDeviceFinal,
|
||||
sample: &'a OriginalPromptSample,
|
||||
context: &'ctx Context<'ctx>,
|
||||
}
|
||||
|
||||
/// The ring and its snapshot the draft KV is written into, and the first position that is still needed.
|
||||
type DraftRing<'a, 'ctx> = (&'a mut MtpOriginalInt8<'ctx>, &'a MtpInt8Snapshot, usize);
|
||||
|
||||
/// The owners of the two producers: the batched one, and the scalar fallback's actor, retained weights and MTP weights.
|
||||
type DraftProducers<'a, 'ctx> = (
|
||||
&'a mut OriginalMtpPrefill<'ctx>,
|
||||
(
|
||||
&'a mut OriginalMtpActor<'ctx>,
|
||||
std::rc::Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
|
||||
&'a RetainedOriginalMtpWeights<'ctx>,
|
||||
),
|
||||
);
|
||||
|
||||
/// The embedding, scalar policy and cancellation the producers share.
|
||||
type DraftExtras<'a, 'ctx, C> = (&'a OriginalPromptEmbedding<'ctx>, (&'a OriginalMtpScalarPolicy, &'a mut C));
|
||||
|
||||
fn outcome_name(outcome: &OriginalPromptDraftOutcome) -> &'static str {
|
||||
match outcome {
|
||||
OriginalPromptDraftOutcome::Completed(_) => "Completed",
|
||||
OriginalPromptDraftOutcome::Fallback(_) => "Fallback",
|
||||
OriginalPromptDraftOutcome::Skipped => "Skipped",
|
||||
OriginalPromptDraftOutcome::Cancelled => "Cancelled",
|
||||
}
|
||||
}
|
||||
|
||||
fn completed_draft(outcome: OriginalPromptDraftOutcome) -> Result<OriginalDraftKvPending> {
|
||||
match outcome {
|
||||
OriginalPromptDraftOutcome::Completed(completed) => Ok(completed),
|
||||
// Optional unported storage and actual no-materialization
|
||||
// need separate genuine outcomes; refusal advances neither.
|
||||
OriginalPromptDraftOutcome::Fallback(_)
|
||||
| OriginalPromptDraftOutcome::Skipped
|
||||
| OriginalPromptDraftOutcome::Cancelled => Err(Error::Unsupported(Stage::Session)),
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
/// Records the draft KV of the chunk into the draft session's pending ring.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn record_draft_kv(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
moe: &MoeWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
chunk: (&mut PromptDeviceRows<'_, '_, '_, 'ctx>, &PromptDeviceFinal, &OriginalPromptSample),
|
||||
draft_args: DraftArgs<'_, 'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<OriginalDraftKvPending> {
|
||||
let draft_span = prof::span(PStage::DraftKv, Some(self.context as &dyn prof::Drain));
|
||||
let draft_kv = self.draft_kv_in_ring(binding, dense, moe, txn, chunk, draft_args, cancelled)?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] forward: draft kv ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
drop(draft_span);
|
||||
Ok(draft_kv)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draft_kv_in_ring(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
moe: &MoeWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
(rows, final_row, sample): (&mut PromptDeviceRows<'_, '_, '_, 'ctx>, &PromptDeviceFinal, &OriginalPromptSample),
|
||||
(draft, embedding, policy): DraftArgs<'_, 'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<OriginalDraftKvPending> {
|
||||
let producer = self.mtp_prefill.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 retained_mtp = self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?;
|
||||
let inputs = DraftKvInputs { binding, dense, moe, txn, final_row, sample, context };
|
||||
draft
|
||||
.with_pending_ring(binding, txn, |ring, prior, first_needed| {
|
||||
let producers = (producer, (scalar, scalar_weights, &retained_mtp));
|
||||
inputs.record_in_ring(rows, producers, (ring, prior, first_needed), (embedding, (policy, cancelled)))
|
||||
})
|
||||
.map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] with_pending_ring err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> DraftKvInputs<'_, 'ctx> {
|
||||
/// The batched producer first; the scalar one only when the batched one falls back.
|
||||
fn record_in_ring(
|
||||
&self,
|
||||
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
|
||||
(producer, scalar_owners): DraftProducers<'_, 'ctx>,
|
||||
(ring, prior, first_needed): DraftRing<'_, 'ctx>,
|
||||
(embedding, (policy, cancelled)): DraftExtras<'_, 'ctx, impl FnMut() -> bool>,
|
||||
) -> Result<OriginalDraftKvPending> {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] draft ring open first_needed={first_needed:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
let mut workspace =
|
||||
self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let batched_ring = (&mut *ring, prior, first_needed);
|
||||
let batched = (embedding, (policy, &mut *cancelled));
|
||||
let outcome = self.record_batched(rows, producer, &mut workspace, batched_ring, batched)?;
|
||||
let outcome = match outcome {
|
||||
OriginalPromptDraftOutcome::Fallback(_) => self.record_scalar(
|
||||
rows,
|
||||
scalar_owners,
|
||||
&mut workspace,
|
||||
(ring, prior, first_needed),
|
||||
(policy, cancelled),
|
||||
)?,
|
||||
other => other,
|
||||
};
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] after scalar fallback -> {}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
outcome_name(&outcome)
|
||||
);
|
||||
completed_draft(outcome)
|
||||
}
|
||||
|
||||
fn record_batched(
|
||||
&self,
|
||||
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
|
||||
producer: &mut OriginalMtpPrefill<'ctx>,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
(ring, prior, first_needed): DraftRing<'_, 'ctx>,
|
||||
(embedding, (policy, cancelled)): DraftExtras<'_, 'ctx, impl FnMut() -> bool>,
|
||||
) -> Result<OriginalPromptDraftOutcome> {
|
||||
let outcome = rows.record_original_draft_kv(
|
||||
self.binding,
|
||||
self.dense,
|
||||
self.moe,
|
||||
self.txn,
|
||||
self.final_row,
|
||||
self.sample.next(),
|
||||
producer,
|
||||
workspace,
|
||||
ring,
|
||||
prior,
|
||||
embedding.borrow(self.binding, self.context)?,
|
||||
first_needed,
|
||||
&policy.kv,
|
||||
cancelled,
|
||||
)?;
|
||||
if let OriginalPromptDraftOutcome::Fallback(reason) = &outcome {
|
||||
crate::bringup_trace!("DBG fallback reason: {reason:?}");
|
||||
}
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] record_original_draft_kv -> {}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
outcome_name(&outcome)
|
||||
);
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn record_scalar(
|
||||
&self,
|
||||
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
|
||||
(scalar, scalar_weights, retained_mtp): (
|
||||
&mut OriginalMtpActor<'ctx>,
|
||||
std::rc::Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
|
||||
&RetainedOriginalMtpWeights<'ctx>,
|
||||
),
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
(ring, prior, first_needed): DraftRing<'_, 'ctx>,
|
||||
(policy, cancelled): (&OriginalMtpScalarPolicy, &mut impl FnMut() -> bool),
|
||||
) -> Result<OriginalPromptDraftOutcome> {
|
||||
rows.record_original_scalar_draft_kv(
|
||||
self.binding,
|
||||
self.dense,
|
||||
retained_mtp,
|
||||
self.txn,
|
||||
self.final_row,
|
||||
self.sample.next(),
|
||||
scalar,
|
||||
workspace,
|
||||
ring,
|
||||
prior,
|
||||
scalar_weights,
|
||||
first_needed,
|
||||
policy,
|
||||
cancelled,
|
||||
)
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
//! STRA-338 size: the final row of `OriginalPromptExecutor::forward` (conditioning preview, sample, R trace).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_driver::OriginalDeviceResidual;
|
||||
|
||||
const FNV_OFFSET: u64 = 0xcbf29ce484222325;
|
||||
const FNV_PRIME: u64 = 0x100000001b3;
|
||||
|
||||
/// FNV-1a over the little-endian bytes of one row.
|
||||
fn fnv1a_row(row: &[f32]) -> u64 {
|
||||
let mut row_hash = FNV_OFFSET;
|
||||
for value in row.iter() {
|
||||
for byte in value.to_le_bytes() {
|
||||
row_hash ^= u64::from(byte);
|
||||
row_hash = row_hash.wrapping_mul(FNV_PRIME);
|
||||
}
|
||||
}
|
||||
row_hash
|
||||
}
|
||||
|
||||
/// Hash of every row of the chunk's final residual and the per-row hashes (one drain per row).
|
||||
fn hash_final_rows(residual: &mut OriginalDeviceResidual<'_, '_, '_>, count: usize) -> Result<(u64, Vec<u64>)> {
|
||||
let mut hash = FNV_OFFSET;
|
||||
let mut rows_hash = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
let row = residual.read_prompt_row(index).map_err(driver_error)?;
|
||||
let row_hash = fnv1a_row(&row);
|
||||
hash ^= row_hash;
|
||||
hash = hash.wrapping_mul(FNV_PRIME);
|
||||
rows_hash.push(row_hash);
|
||||
}
|
||||
Ok((hash, rows_hash))
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
/// Ends the chunk's expert stream, then previews the conditioning row and takes its sample.
|
||||
pub(super) fn prepare_final_row<'arena, 'loan>(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
carrier: Carrier<'_, 'arena, 'loan, 'ctx>,
|
||||
) -> Result<(PromptDeviceRows<'static, 'arena, 'loan, 'ctx>, PromptDeviceFinal, OriginalPromptSample)> {
|
||||
let Carrier::Plain(mut rows) = carrier else {
|
||||
return Err(Error::IdentityMismatch);
|
||||
};
|
||||
// the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers
|
||||
moe.end_prompt_stream()?;
|
||||
let final_span = prof::span(PStage::Final, Some(self.context as &dyn prof::Drain));
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward: all layers ok, final row",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
let final_row = rows.preview_conditioning(binding, dense, txn).map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] preview_conditioning err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] final_row ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
Self::trace_prefill_r(binding, dense, txn, &mut rows, &final_row)?;
|
||||
let sample = OriginalPromptSample::conditioning(binding, &final_row, txn).map_err(|e| {
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] sample conditioning err {e:?}",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
e
|
||||
})?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] sample ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
drop(final_span);
|
||||
Ok((rows, final_row, sample))
|
||||
}
|
||||
|
||||
/// Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R
|
||||
/// (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default.
|
||||
fn trace_prefill_r(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
|
||||
final_row: &PromptDeviceFinal,
|
||||
) -> Result<()> {
|
||||
if !crate::settings::process().diagnostics.trace_prefill_r {
|
||||
return Ok(());
|
||||
}
|
||||
let first = txn.start_position();
|
||||
let count = txn.len();
|
||||
let hash =
|
||||
rows.with_final_residual(binding, dense, txn, final_row, |residual| hash_final_rows(residual, count))?;
|
||||
eprintln!(
|
||||
"PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}",
|
||||
hash.0,
|
||||
hash.1[0],
|
||||
hash.1[count - 1]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
//! STRA-338 size: the input phase of `OriginalPromptExecutor::forward` (staging, row upload, PLE read-ahead).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::kar_ple_cache::KarPleStaged;
|
||||
|
||||
/// What the staging of one chunk's inputs leaves behind: the chunk-wide staged input, the staged PLE rows and the
|
||||
/// two tokens before the chunk (the per-token host path stages nothing).
|
||||
type StagedPrompt = (Option<StagedInput>, Option<KarPleStaged>, Option<[i32; 2]>);
|
||||
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
pub(super) fn stage_prompt_inputs(
|
||||
binding: &ModelBinding,
|
||||
txn: &mut OriginalPromptTxn<'_, 'ctx>,
|
||||
tokens: &[TokenId],
|
||||
kar: &mut Option<&mut KarPleCache<'ctx>>,
|
||||
) -> Result<StagedPrompt> {
|
||||
let input_span = prof::span(PStage::Input, None);
|
||||
// KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device
|
||||
// (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm).
|
||||
let staged = if binding.kar_ple_binding().is_some() && staged_input_enabled() {
|
||||
Self::stage_inputs_batched(binding, txn, tokens, kar)?
|
||||
} else {
|
||||
Self::stage_inputs_per_token(binding, txn, tokens, kar)?;
|
||||
(None, None, None)
|
||||
};
|
||||
drop(input_span);
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn stage_inputs_batched(
|
||||
binding: &ModelBinding,
|
||||
txn: &mut OriginalPromptTxn<'_, 'ctx>,
|
||||
tokens: &[TokenId],
|
||||
kar: &mut Option<&mut KarPleCache<'ctx>>,
|
||||
) -> Result<StagedPrompt> {
|
||||
let mut first_predecessors: Option<[i32; 2]> = None;
|
||||
let mut staged = StagedInput::default();
|
||||
for &token in tokens {
|
||||
txn.stage_input(|step| {
|
||||
let pos = step.position();
|
||||
if first_predecessors.is_none() {
|
||||
first_predecessors = Some(step.input_predecessors()?);
|
||||
}
|
||||
match kar.as_deref() {
|
||||
Some(cache) => InputStage::consume_kar_deferred(binding, cache, token, pos, step, &mut staged),
|
||||
None => Err(Error::IdentityMismatch),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let kar_binding = binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?;
|
||||
let _ple_span = prof::span(PStage::InputPle, None);
|
||||
let staged_ple = Some(cache.stage_batch(kar_binding, staged.ple_rows())?);
|
||||
Ok((Some(staged), staged_ple, first_predecessors))
|
||||
}
|
||||
|
||||
fn stage_inputs_per_token(
|
||||
binding: &ModelBinding,
|
||||
txn: &mut OriginalPromptTxn<'_, 'ctx>,
|
||||
tokens: &[TokenId],
|
||||
kar: &mut Option<&mut KarPleCache<'ctx>>,
|
||||
) -> Result<()> {
|
||||
for &token in tokens {
|
||||
txn.stage_input(|step| {
|
||||
let pos = step.position();
|
||||
match (binding.kar_ple_binding(), kar.as_deref_mut()) {
|
||||
(None, None) => InputStage::consume(binding, token, pos, step),
|
||||
(Some(_), Some(cache)) => InputStage::consume_kar(binding, cache, token, pos, step),
|
||||
_ => Err(Error::IdentityMismatch),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Source rows, upload and device initialization of the chunk's rows.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn initialize_prompt_rows<'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
tokens: &[TokenId],
|
||||
kar: &mut Option<&mut KarPleCache<'ctx>>,
|
||||
arena: &'arena mut OriginalPrefillArena<'loan, 'ctx>,
|
||||
(staged_input, staged_ple): (Option<&StagedInput>, Option<KarPleStaged>),
|
||||
) -> Result<PromptDeviceRows<'static, 'arena, 'loan, 'ctx>> {
|
||||
let drain = Some(self.context as &dyn prof::Drain);
|
||||
let init_span = prof::span(PStage::Initialize, drain);
|
||||
let mut sources = Vec::new();
|
||||
sources.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let sources_span = prof::span(PStage::InitSources, None);
|
||||
for local in 0..tokens.len() {
|
||||
sources.push(PromptDeviceSource::from_original(binding, self.context, txn, local)?);
|
||||
}
|
||||
drop(sources_span);
|
||||
let upload_span = prof::span(PStage::InitUpload, drain);
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let lease = arena.begin_rows(tokens.len()).map_err(driver_error)?;
|
||||
let rows = match (staged_input, staged_ple) {
|
||||
(Some(input), Some(ple)) => {
|
||||
let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?;
|
||||
Self::initialize_staged_rows(binding, dense, self.context, prompt, cache, lease, sources, (input, ple))?
|
||||
}
|
||||
_ => PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, None)?,
|
||||
};
|
||||
drop(upload_span);
|
||||
drop(init_span);
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// The device scatters the staged embedding and PLE rows; the PLE cache learns them only after that succeeded.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn initialize_staged_rows<'arena, 'loan>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
prompt: &mut OriginalPromptDevice<'ctx>,
|
||||
cache: &mut KarPleCache<'ctx>,
|
||||
lease: leleka_cuda_driver::OriginalPromptRows<'arena, 'loan, 'ctx>,
|
||||
sources: Vec<PromptDeviceSource<'static, 'ctx>>,
|
||||
(input, ple): (&StagedInput, KarPleStaged),
|
||||
) -> Result<PromptDeviceRows<'static, 'arena, 'loan, 'ctx>> {
|
||||
let result = {
|
||||
let (ple_cache, ple_books) = cache.device_parts();
|
||||
let stage = PromptInputStage {
|
||||
embedding_rows: input.embedding_rows(),
|
||||
embedding_index: input.embedding_index(),
|
||||
ple_cache,
|
||||
ple_books,
|
||||
ple_updates: ple.updates(),
|
||||
ple_slots: ple.slots(),
|
||||
};
|
||||
PromptDeviceRows::initialize(binding, dense, context, prompt, lease, sources, Some(stage))
|
||||
};
|
||||
match result {
|
||||
Ok(rows) => {
|
||||
cache.commit(ple);
|
||||
Ok(rows)
|
||||
}
|
||||
// the device may already hold part of the scatter: the cache is not trusted again
|
||||
Err(error) => {
|
||||
cache.invalidate();
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes
|
||||
/// (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there.
|
||||
pub(super) fn read_ahead_next_chunk(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
source: &std::rc::Rc<OriginalPromptInput>,
|
||||
(tokens, first_position): (&[TokenId], u64),
|
||||
kar: &mut Option<&mut KarPleCache<'ctx>>,
|
||||
first_predecessors: Option<[i32; 2]>,
|
||||
) {
|
||||
let (Some(cache), Some(kar_binding), Some(mut before)) =
|
||||
(kar.as_deref_mut(), binding.kar_ple_binding(), first_predecessors)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let next_first = first_position + tokens.len() as u64;
|
||||
let want = self.capacity.min(source.len().saturating_sub(next_first as usize));
|
||||
if want == 0 {
|
||||
return;
|
||||
}
|
||||
let Ok(next) = source.window(binding, next_first, want) else { return };
|
||||
for &token in tokens {
|
||||
before = [before[1], token.get() as i32];
|
||||
}
|
||||
if let Ok(rows) = InputStage::ple_rows_ahead(binding, before, next) {
|
||||
cache.read_ahead(kar_binding, &rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
//! STRA-338 size: the layer loop of `OriginalPromptExecutor::forward`, one helper per phase of a layer.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::model_binding::qwen4exp_input::BoundLayer;
|
||||
use crate::qwen_forward::gr::GrRole;
|
||||
use crate::qwen_forward::prompt_device_rows::PromptDeviceRead;
|
||||
|
||||
/// One validation of the current row state, timed on its own.
|
||||
fn validated<R>(check: impl FnOnce() -> Result<R>) -> Result<R> {
|
||||
let _span = prof::span(PStage::Validate, None);
|
||||
check()
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
/// Layer-major order: every layer completes all rows of the chunk before the next starts.
|
||||
pub(super) fn run_layers<'w, 'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &'w DenseWeightCache<'ctx>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
mut carrier: Carrier<'w, 'arena, 'loan, 'ctx>,
|
||||
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
|
||||
for layer in binding.ordered_layers() {
|
||||
carrier = self.run_layer(layer, binding, dense, moe, txn, carrier)?;
|
||||
}
|
||||
Ok(carrier)
|
||||
}
|
||||
|
||||
fn run_layer<'w, 'arena, 'loan>(
|
||||
&mut self,
|
||||
layer: &BoundLayer,
|
||||
binding: &ModelBinding,
|
||||
dense: &'w DenseWeightCache<'ctx>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
carrier: Carrier<'w, 'arena, 'loan, 'ctx>,
|
||||
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
|
||||
let index = layer.index();
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] forward layer {index} {:?} begin",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el(),
|
||||
layer.kind()
|
||||
);
|
||||
let carrier = if index == 1 { self.apply_ple_rows(binding, dense, txn, carrier)? } else { carrier };
|
||||
let mut read = self.read_attention(binding, dense, carrier, index)?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] L{index} attn-read ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
validated(|| read.validate_original_rows(binding, dense))?;
|
||||
let ffn = self.complete_mixer(binding, dense, txn, read, layer)?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] L{index} mixer ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
let read = self.read_ffn(binding, dense, ffn, index)?;
|
||||
let carrier = self.complete_moe(binding, dense, moe, read, index)?;
|
||||
crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok", crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
Ok(carrier)
|
||||
}
|
||||
|
||||
/// Per-layer-input embeddings join the residual after layer 0.
|
||||
fn apply_ple_rows<'w, 'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
carrier: Carrier<'w, 'arena, 'loan, 'ctx>,
|
||||
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
|
||||
let drain = Some(self.context as &dyn prof::Drain);
|
||||
let Carrier::Plain(mut rows) = carrier else {
|
||||
return Err(Error::IdentityMismatch);
|
||||
};
|
||||
validated(|| rows.validate_original_rows(binding, dense))?;
|
||||
let _span = prof::span(PStage::Ple, drain);
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let prior = txn.ple_prior()?;
|
||||
let mut history = InputStage::prepare_original_prompt_history(binding, dense, self.context, txn)?;
|
||||
rows = rows.apply_ple(binding, dense, prompt, &mut history)?;
|
||||
InputStage::finish_original_prompt_history(binding, txn, &prior, history)?;
|
||||
// The completed PLE operation changes the real row state.
|
||||
// Its output must pass fresh current-row validation.
|
||||
Ok(Carrier::Plain(rows))
|
||||
}
|
||||
|
||||
fn read_attention<'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
carrier: Carrier<'_, 'arena, 'loan, 'ctx>,
|
||||
index: u32,
|
||||
) -> Result<PromptDeviceRead<'static, 'arena, 'loan, 'ctx>> {
|
||||
let drain = Some(self.context as &dyn prof::Drain);
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
match carrier {
|
||||
Carrier::Plain(mut rows) => {
|
||||
validated(|| rows.validate_original_rows(binding, dense))?;
|
||||
let _span = prof::span(PStage::AttnRead, drain);
|
||||
rows.read(binding, dense, prompt, GrRole::Attention(index))
|
||||
}
|
||||
Carrier::Normed(mut rows) => {
|
||||
validated(|| rows.validate_original_rows(binding, dense))?;
|
||||
let _span = prof::span(PStage::AttnRead, drain);
|
||||
rows.read(binding, dense, prompt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The token mixer (GDN or QSA) of the layer, fused with the next norm when `fused`.
|
||||
fn complete_mixer<'w, 'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &'w DenseWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
|
||||
layer: &BoundLayer,
|
||||
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
|
||||
let drain = Some(self.context as &dyn prof::Drain);
|
||||
let mixer_span = prof::span(
|
||||
match layer.kind() {
|
||||
BoundLayerKind::Gdn => PStage::Gdn,
|
||||
BoundLayerKind::Qsa => PStage::Qsa,
|
||||
},
|
||||
drain,
|
||||
);
|
||||
let ffn = if self.fused {
|
||||
Carrier::Normed(self.mixer_normed(binding, dense, txn, read, layer)?)
|
||||
} else {
|
||||
Carrier::Plain(self.mixer_plain(binding, dense, txn, read, layer)?)
|
||||
};
|
||||
drop(mixer_span);
|
||||
Ok(ffn)
|
||||
}
|
||||
|
||||
fn mixer_normed<'w, 'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &'w DenseWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
|
||||
layer: &BoundLayer,
|
||||
) -> Result<PromptDeviceNormedRows<'w, 'static, 'arena, 'loan, 'ctx>> {
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
match layer.kind() {
|
||||
BoundLayerKind::Gdn => read.complete_original_gdn_normed(
|
||||
binding,
|
||||
dense,
|
||||
txn,
|
||||
prompt,
|
||||
self.gdn.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
),
|
||||
BoundLayerKind::Qsa => read.complete_original_qsa_normed(
|
||||
binding,
|
||||
dense,
|
||||
txn,
|
||||
prompt,
|
||||
self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn mixer_plain<'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
|
||||
layer: &BoundLayer,
|
||||
) -> Result<PromptDeviceRows<'static, 'arena, 'loan, 'ctx>> {
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
match layer.kind() {
|
||||
BoundLayerKind::Gdn => read.complete_original_gdn(
|
||||
binding,
|
||||
dense,
|
||||
txn,
|
||||
prompt,
|
||||
self.gdn.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
),
|
||||
BoundLayerKind::Qsa => read.complete_original_qsa(
|
||||
binding,
|
||||
dense,
|
||||
txn,
|
||||
prompt,
|
||||
self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_ffn<'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
mut ffn: Carrier<'_, 'arena, 'loan, 'ctx>,
|
||||
index: u32,
|
||||
) -> Result<PromptDeviceRead<'static, 'arena, 'loan, 'ctx>> {
|
||||
let drain = Some(self.context as &dyn prof::Drain);
|
||||
validated(|| match &mut ffn {
|
||||
Carrier::Plain(rows) => rows.validate_original_rows(binding, dense),
|
||||
Carrier::Normed(rows) => rows.validate_original_rows(binding, dense),
|
||||
})?;
|
||||
crate::bringup_trace!(
|
||||
"DBG[{:.0}s] L{index} ffn-validate ok",
|
||||
crate::qwen_forward::original_serve_stack::dbg_el()
|
||||
);
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let ffn_span = prof::span(PStage::FfnRead, drain);
|
||||
let mut read = match ffn {
|
||||
Carrier::Plain(rows) => rows.read(binding, dense, prompt, GrRole::Ffn(index))?,
|
||||
Carrier::Normed(rows) => rows.read(binding, dense, prompt)?,
|
||||
};
|
||||
drop(ffn_span);
|
||||
validated(|| read.validate_original_rows(binding, dense))?;
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
fn complete_moe<'w, 'arena, 'loan>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
dense: &'w DenseWeightCache<'ctx>,
|
||||
moe: &mut MoeWeightCache<'ctx>,
|
||||
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
|
||||
index: u32,
|
||||
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
|
||||
let drain = Some(self.context as &dyn prof::Drain);
|
||||
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let moe_span = prof::span(PStage::Moe, drain);
|
||||
// Literal fused GR norm is prohibited across PLE and final head.
|
||||
let carrier = if self.fused && index != 0 && index != 47 {
|
||||
Carrier::Normed(read.complete_original_moe_normed(binding, dense, moe, prompt)?)
|
||||
} else {
|
||||
Carrier::Plain(read.complete_original_moe(binding, dense, moe, prompt)?)
|
||||
};
|
||||
drop(moe_span);
|
||||
Ok(carrier)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user