STRA-338 size: engine assemble takes AssembleInputs (assemble 55 -> 6), record_*_draft_kv shorter

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 15:31:54 +01:00
parent d0b2b633b8
commit 4e08fca79d
7 changed files with 146 additions and 153 deletions
@@ -169,6 +169,36 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
})
}
}
impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> {
/// The ten MTP pack matrices of the draft prefill, each checked against the pack's kind and shape.
fn prefill_weights<'m>(
&self,
binding: &ModelBinding,
mtp: &'m MoeWeightCache<'ctx>,
) -> Result<OriginalMtpPrefillWeights<'m, 'ctx>> {
let context = self.sources.context;
// Exact Original acquisition order, authentic pack descriptor checks.
let matrix = |role, expected| -> Result<&leleka_cuda_driver::DeviceBuffer<'ctx>> {
let (kind, rows, columns, buffer) = mtp.mtp_matrix(binding, context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(buffer)
};
Ok(OriginalMtpPrefillWeights {
embedding_norm: matrix(MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560))?,
embedding_fc: matrix(MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560))?,
hidden_norm: matrix(MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240))?,
hidden_fc: matrix(MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560))?,
gr_norm: matrix(MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240))?,
gr_down: matrix(MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240))?,
gr_up: matrix(MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320))?,
key: matrix(MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560))?,
value: matrix(MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560))?,
key_norm: matrix(MtpRole::KeyNorm, (MtpKind::F32, 1, 256))?,
})
}
}
impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> {
/// Called after the genuine all-row conditioning phase while its physical R
/// loan survives. `last_next` must match that phase's known next prompt ID.
@@ -193,44 +223,13 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
) -> Result<OriginalPromptDraftOutcome> {
let phase = self.check_final_sources(binding, dense, txn, preview, last_next)?;
let next = self.shifted_next_ids(txn, last_next)?;
let context = self.sources.context;
// Exact Original acquisition order, authentic pack descriptor checks.
let matrix = |role, expected| -> Result<&leleka_cuda_driver::DeviceBuffer<'ctx>> {
let (kind, rows, columns, buffer) = mtp.mtp_matrix(binding, context, role)?;
if (kind, rows, columns) != expected {
return Err(Error::InvalidDimension);
}
Ok(buffer)
};
let weights = OriginalMtpPrefillWeights {
embedding_norm: matrix(MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560))?,
embedding_fc: matrix(MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560))?,
hidden_norm: matrix(MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240))?,
hidden_fc: matrix(MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560))?,
gr_norm: matrix(MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240))?,
gr_down: matrix(MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240))?,
gr_up: matrix(MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320))?,
key: matrix(MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560))?,
value: matrix(MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560))?,
key_norm: matrix(MtpRole::KeyNorm, (MtpKind::F32, 1, 256))?,
};
let weights = self.prefill_weights(binding, mtp)?;
let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?;
// Input/draft host policy and all ten immutable device loans are live
// throughout drain; never mint scalar committed products for prior rows.
let result = producer
.record(
&mut self.device,
workspace,
ring,
prior,
&next,
usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?,
first_needed,
weights,
embedding,
policy,
cancelled,
)
.map_err(micro_driver_error)?;
#[rustfmt::skip]
let result = producer.record(&mut self.device, workspace, ring, prior, &next, start, first_needed, weights,
embedding, policy, cancelled).map_err(micro_driver_error)?;
self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, ring)
}
}
@@ -26,24 +26,13 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
) -> Result<OriginalPromptDraftOutcome> {
let phase = self.check_scalar_sources(binding, dense, txn, preview, last_next)?;
let next = self.shifted_next_ids(txn, last_next)?;
let context = self.sources.context;
check_retained_matrices(binding, mtp, context, &retained)?;
check_retained_matrices(binding, mtp, self.sources.context, &retained)?;
let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?;
// 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_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)?;
#[rustfmt::skip]
let result = producer.record_scalar_prefill(&mut self.device, workspace, ring, prior, &next, start, first_needed,
retained, policy, cancelled).map_err(micro_driver_error)?;
self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, ring)
}
}
@@ -37,7 +37,7 @@ use super::{
original_serve_residency::{self, ExpertTierConfig, GpuExpertPool, ResidencyState},
original_serve_seed::{self, SeedReport},
original_serve_verifier::{
AssembleFailure, DecodeResources, PLE_HISTORY_BYTES, ServeFailure, VerifyWeights, assemble,
AssembleFailure, AssembleInputs, DecodeResources, PLE_HISTORY_BYTES, ServeFailure, VerifyWeights,
assemble_with_window_fallback, disassemble, seed_ple_history,
},
original_spec_controller::{OriginalSpecController, SpecError},
@@ -5,8 +5,8 @@ use super::*;
mod decode_parts;
use decode_parts::{
AssembleInputs, RefillOwners, assemble_decode, decode_pcie_mode, gpu_expert_pool, narrow_window_policy,
resolve_assembled, return_owners, settle_deferred_refill, teardown_decode,
RefillOwners, assemble_decode, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, resolve_assembled,
return_owners, settle_deferred_refill, teardown_decode,
};
mod open_parts;
use open_parts::{
@@ -5,7 +5,6 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::original_serve_host::HostOutcome;
use crate::qwen_forward::session::original_verified::OriginalVerifiedBase;
use leleka_cuda_driver::{OriginalQsaMappedJournal, OriginalQsaResidentIndex};
type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48];
@@ -27,20 +26,6 @@ pub(super) fn decode_pcie_mode(
})
}
/// What `assemble` reads: the borrowed weights and constants of one decode phase.
pub(super) struct AssembleInputs<'x, 'a, 'ctx> {
pub(super) binding: &'x ModelBinding,
pub(super) context: &'ctx Context<'ctx>,
pub(super) weights: &'x VerifyWeights<'a, 'ctx>,
pub(super) output: &'x OriginalNativeOutput<'ctx>,
pub(super) base: &'x OriginalVerifiedBase<'ctx>,
pub(super) ple_history: &'a DeviceBuffer<'ctx>,
pub(super) rope: &'x RopeConstants,
pub(super) blobs: &'x ExpertBlobSizes,
pub(super) max_cells: usize,
pub(super) pcie_mode: u8,
}
/// The owners the refill hook (queued after assembly's own uploads) works on.
pub(super) struct RefillOwners<'r, 'ctx> {
pub(super) due: &'r mut bool,
@@ -96,34 +81,6 @@ pub(super) fn assemble_decode<'a, 'ctx>(
Ok(assembled)
}
impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> {
fn assemble(
&self,
owners: QsaOwners<'ctx>,
max_t: usize,
queue_refill: &mut impl FnMut() -> Result<()>,
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
let (binding, context, ple_history) = (self.binding, self.context, self.ple_history);
let (weights, output, base) = (self.weights, self.output, self.base);
let (rope, blobs, max_cells, pcie_mode) = (self.rope, self.blobs, self.max_cells, self.pcie_mode);
assemble(
binding,
weights,
context,
output,
base,
owners,
ple_history,
rope,
blobs,
max_t,
max_cells,
pcie_mode,
queue_refill,
)
}
}
/// One assembly attempt at `max_t`; the owners come back from a failure into `owners_slot` when a narrower window may
/// fit.
fn assemble_attempt<'a, 'ctx>(
@@ -196,62 +196,90 @@ pub(in crate::qwen_forward) struct VerifyWeights<'a, 'ctx> {
pub(in crate::qwen_forward) ple_scratch: &'a DeviceBuffer<'ctx>,
}
/// Build the canonical GDN image from the GDN priors, the QSA journal over the handed-over owners, and
/// record every window graph and the commit graph. `ple_history` must already hold the seeded image
/// (`seed_ple_history`) and outlive the phase; the caller keeps its own shared reference to read it back.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn assemble<'a, 'ctx>(
binding: &ModelBinding,
weights: &VerifyWeights<'a, 'ctx>,
context: &'ctx Context<'ctx>,
output: &OriginalNativeOutput<'ctx>,
base: &OriginalVerifiedBase<'ctx>,
mut owners: QsaOwners<'ctx>,
ple_history: &'a DeviceBuffer<'ctx>,
rope: &RopeConstants,
blobs: &ExpertBlobSizes,
max_t: usize,
max_cells: usize,
pcie_mode: u8,
after_prepare: &mut dyn FnMut() -> std::result::Result<(), Error>,
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
let dense = weights.dense;
// The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its
// first append, so a ONE-token prompt on a fresh stack reaches the capture with none: initialise it here
// (never through `reset`, which would change the epoch and orphan every prefix the session holds).
if let Err(failure) = ensure_resolvers(binding, dense, context, &mut owners) {
return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None });
/// What `assemble` reads: the borrowed weights and constants of one decode phase. `ple_history` must already hold the
/// seeded image (`seed_ple_history`) and outlive the phase; the caller keeps its own shared reference to read it back.
pub(in crate::qwen_forward) struct AssembleInputs<'x, 'a, 'ctx> {
pub(in crate::qwen_forward) binding: &'x ModelBinding,
pub(in crate::qwen_forward) context: &'ctx Context<'ctx>,
pub(in crate::qwen_forward) weights: &'x VerifyWeights<'a, 'ctx>,
pub(in crate::qwen_forward) output: &'x OriginalNativeOutput<'ctx>,
pub(in crate::qwen_forward) base: &'x OriginalVerifiedBase<'ctx>,
pub(in crate::qwen_forward) ple_history: &'a DeviceBuffer<'ctx>,
pub(in crate::qwen_forward) rope: &'x RopeConstants,
pub(in crate::qwen_forward) blobs: &'x ExpertBlobSizes,
pub(in crate::qwen_forward) max_cells: usize,
pub(in crate::qwen_forward) pcie_mode: u8,
}
impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> {
/// Build the canonical GDN image from the GDN priors, the QSA journal over the handed-over owners, and
/// record every window graph and the commit graph.
pub(in crate::qwen_forward) fn assemble(
&self,
owners: QsaOwners<'ctx>,
max_t: usize,
after_prepare: &mut impl FnMut() -> std::result::Result<(), Error>,
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
let (prepared, owners) = self.prepare(owners, max_t, after_prepare)?;
self.record(prepared, owners, max_t)
}
// Everything that can be refused WITHOUT consuming the owners is checked first.
let p = super::original_serve_profile::span("assemble.prepare");
let prepare = prepare_assembly(binding, dense, context, base, ple_history, (max_t, max_cells, blobs));
drop(p);
let (geometry, mut canonical, gamma) = match prepare {
Ok(parts) => parts,
Err(failure) => return Err(AssembleFailure { failure, owners: Some(owners), window_cap: None }),
};
// The caller's work that wants the intake uploads done and the graph capture still ahead (the lent-slot refill copies).
if let Err(error) = after_prepare() {
/// Everything that can be refused WITHOUT consuming the owners, then the caller's work that wants the intake uploads
/// done and the graph capture still ahead (the lent-slot refill copies).
fn prepare(
&self,
mut owners: QsaOwners<'ctx>,
max_t: usize,
after_prepare: &mut impl FnMut() -> std::result::Result<(), Error>,
) -> std::result::Result<(Prepared<'a, 'ctx>, QsaOwners<'ctx>), AssembleFailure<'ctx>> {
let refused = |failure, owners| AssembleFailure { failure, owners: Some(owners), window_cap: None };
// The window graphs bind each layer's streamed-KV resolver. The prompt path initialises it lazily on its
// first append, so a ONE-token prompt on a fresh stack reaches the capture with none: initialise it here
// (never through `reset`, which would change the epoch and orphan every prefix the session holds).
if let Err(failure) = ensure_resolvers(self.binding, self.weights.dense, self.context, &mut owners) {
return Err(refused(failure, owners));
}
let p = super::original_serve_profile::span("assemble.prepare");
let shape = (max_t, self.max_cells, self.blobs);
let prepare =
prepare_assembly(self.binding, self.weights.dense, self.context, self.base, self.ple_history, shape);
drop(p);
let prepared = match prepare {
Ok(parts) => parts,
Err(failure) => return Err(refused(failure, owners)),
};
if let Err(error) = after_prepare() {
drop(prepared.1);
return Err(refused(error.into(), owners));
}
Ok((prepared, owners))
}
/// From here the owners move into the journal; a failure gives them back when the journal can.
fn record(
&self,
prepared: Prepared<'a, 'ctx>,
owners: QsaOwners<'ctx>,
max_t: usize,
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
let (geometry, mut canonical, gamma) = prepared;
let (slots, indices, mapped) = split_owners(owners)?;
let p = super::original_serve_profile::span("assemble.qsa_journal");
let qsa = OriginalVerifyQsaJournal::new(self.context, indices, mapped, gamma, self.rope.verify_rope())
.map_err(AssembleFailure::lost)?;
drop(p);
let mut window_cap = None;
let env = RecordEnv::new(self, geometry, &qsa);
let recorded = capture_verifier(&env, &mut canonical, (max_t, self.pcie_mode), &mut window_cap);
drop(canonical);
return Err(AssembleFailure { failure: error.into(), owners: Some(owners), window_cap: None });
}
let (slots, indices, mapped) = split_owners(owners)?;
let p = super::original_serve_profile::span("assemble.qsa_journal");
let qsa = OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope.verify_rope())
.map_err(AssembleFailure::lost)?;
drop(p);
let mut window_cap = None;
let env = RecordEnv { binding, context, weights, output, ple_history, blobs, geometry, qsa: &qsa };
let recorded = capture_verifier(&env, &mut canonical, (max_t, pcie_mode), &mut window_cap);
drop(canonical);
match recorded {
Ok(verifier) => Ok(DecodeResources { verifier, qsa, slots }),
Err(failure) => {
// every aggregate is gone: the journal can give the owners back
let owners = recover(qsa, slots);
// a retry needs the owners back
let window_cap = window_cap.filter(|_| owners.is_some());
Err(AssembleFailure { failure, owners, window_cap })
match recorded {
Ok(verifier) => Ok(DecodeResources { verifier, qsa, slots }),
Err(failure) => {
// every aggregate is gone: the journal can give the owners back; a retry needs them back
let owners = recover(qsa, slots);
let window_cap = window_cap.filter(|_| owners.is_some());
Err(AssembleFailure { failure, owners, window_cap })
}
}
}
}
@@ -299,7 +327,7 @@ fn recover<'a, 'ctx>(qsa: Rc<OriginalVerifyQsaJournal<'a, 'ctx>>, slots: [usize;
}
mod assemble_parts;
use assemble_parts::{RecordEnv, capture_verifier, prepare_assembly, split_owners};
use assemble_parts::{Prepared, RecordEnv, capture_verifier, prepare_assembly, split_owners};
#[cfg(test)]
mod tests;
@@ -201,3 +201,23 @@ pub(super) fn capture_verifier<'a, 'ctx>(
};
record_windows(verifier, aggregates, shape, window_cap)
}
impl<'x, 'a, 'ctx> RecordEnv<'x, 'a, 'ctx> {
/// The recording inputs of one assembly over the journal `qsa`.
pub(super) fn new(
inputs: &AssembleInputs<'x, 'a, 'ctx>,
geometry: OriginalVerifyGeometry,
qsa: &'x Qsa<'a, 'ctx>,
) -> Self {
Self {
binding: inputs.binding,
context: inputs.context,
weights: inputs.weights,
output: inputs.output,
ple_history: inputs.ple_history,
blobs: inputs.blobs,
geometry,
qsa,
}
}
}