Merge branch 'claude/size-eng-am2' into claude/hexagonal-integ

# Conflicts:
#	limits-baseline.json
This commit is contained in:
Pavlo Ratushnyi
2026-11-06 15:13:18 +01:00
20 changed files with 1756 additions and 1047 deletions
@@ -110,14 +110,7 @@ impl QwenForward {
true,
false,
)?;
Ok(TargetStepProduct {
binding: binding.identity(),
token,
position: pos,
predicted: predicted.ok_or(Error::IdentityMismatch)?,
streams: streams.ok_or(Error::IdentityMismatch)?,
origin: session.target_origin()?,
})
target_product(binding, token, pos, session, predicted, streams)
}
#[allow(clippy::too_many_arguments)]
@@ -146,12 +139,40 @@ impl QwenForward {
if predicted.is_some() {
return Err(Error::IdentityMismatch);
}
Ok(PrefillStepProduct {
binding: binding.identity(),
token,
position: pos,
streams: streams.ok_or(Error::IdentityMismatch)?,
origin: session.target_origin()?,
})
prefill_product(binding, token, pos, session, streams)
}
}
fn target_product(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &QwenSession<'_>,
predicted: Option<TokenId>,
streams: Option<Box<[f32]>>,
) -> Result<TargetStepProduct> {
Ok(TargetStepProduct {
binding: binding.identity(),
token,
position: pos,
predicted: predicted.ok_or(Error::IdentityMismatch)?,
streams: streams.ok_or(Error::IdentityMismatch)?,
origin: session.target_origin()?,
})
}
fn prefill_product(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &QwenSession<'_>,
streams: Option<Box<[f32]>>,
) -> Result<PrefillStepProduct> {
Ok(PrefillStepProduct {
binding: binding.identity(),
token,
position: pos,
streams: streams.ok_or(Error::IdentityMismatch)?,
origin: session.target_origin()?,
})
}
@@ -7,6 +7,8 @@ use super::super::step_layer_fns::{
use super::*;
impl QwenForward {
/// A forward without its output head can never publish, so it is refused before reading any row or running any
/// layer. The cache preparation above keeps its precedence; nothing has been staged yet.
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn step_core(
binding: &ModelBinding,
@@ -24,14 +26,8 @@ impl QwenForward {
let ctx = LayerCtx { binding, token, pos, dense: dense_cache };
let predicted = session.transact_completion(token, pos, &binding.identity(), |txn| {
let layer_bound = prepare_step_caches(binding, dense_cache, moe_cache.as_deref_mut(), txn)?;
// A forward without its output head can never publish, so refuse
// before reading any row or running any layer. Everything above
// keeps its precedence; nothing has been staged yet.
let output = output.ok_or(Error::Unsupported(Stage::Output))?;
stage_input_row(binding, token, pos, kar_cache, txn)?;
let final_residual = run_layers(&ctx, txn, layer_bound, moe_cache.as_deref_mut())?;
let predicted = finish_step(&ctx, txn, output, &final_residual, prefill_only)?;
if capture_mtp {
@@ -20,30 +20,38 @@ pub(super) fn read_layer_attention<'cache, 'ctx>(
}
GrStage::apply(binding, layer, txn, cache)
}
1 => {
let previous = previous.ok_or(Error::IdentityMismatch)?;
let prior = txn.ple_prior()?;
let mut ple = diagnose(
ForwardPhase::Ple,
layer.get(),
txn.position(),
InputStage::apply_ple_cached(binding, previous, &prior, txn, cache),
)?;
ple.validate_origin(&binding.identity())?;
ple.identity().validate(txn.token(), txn.position(), layer)?;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if super::super::oracle_capture::enabled() {
super::super::oracle_capture::stage_f32(1, "ple_residual", ple.streams())?;
}
let pending = ple.take_pending()?;
txn.stage_ple(&prior, pending)?;
GrStage::read_attention_after_ple(binding, layer, &ple, txn, cache)
}
1 => read_layer_one(binding, layer, previous, txn, cache),
_ => GrStage::read_attention(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn, cache),
}
}
/// Layer one consumes and stages the real PLE producer before the GR attention read.
fn read_layer_one<'cache, 'ctx>(
binding: &ModelBinding,
layer: LayerId,
previous: Option<&InjectedResidual>,
txn: &mut QwenStepTxn,
cache: Option<&'cache DenseWeightCache<'ctx>>,
) -> Result<GrRead<'cache, 'ctx>> {
let previous = previous.ok_or(Error::IdentityMismatch)?;
let prior = txn.ple_prior()?;
let mut ple = diagnose(
ForwardPhase::Ple,
layer.get(),
txn.position(),
InputStage::apply_ple_cached(binding, previous, &prior, txn, cache),
)?;
ple.validate_origin(&binding.identity())?;
ple.identity().validate(txn.token(), txn.position(), layer)?;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if super::super::oracle_capture::enabled() {
super::super::oracle_capture::stage_f32(1, "ple_residual", ple.streams())?;
}
let pending = ple.take_pending()?;
txn.stage_ple(&prior, pending)?;
GrStage::read_attention_after_ple(binding, layer, &ple, txn, cache)
}
/// Mint the actual row input without performing a scalar GR read. The real
/// layer-one PLE history still advances in chronological transaction order;
/// the caller completes GR only after collecting the genuine micro-window.
@@ -63,28 +71,38 @@ pub(super) fn prepare_layer_attention_micro(
}
GrStage::prepare_micro_initial(binding, layer, txn)
}
1 => {
let previous = previous.ok_or(Error::IdentityMismatch)?;
let prior = txn.ple_prior()?;
let mut ple = diagnose(
ForwardPhase::Ple,
layer.get(),
txn.position(),
match ple_micro {
Some(batch) => batch.take_ready(binding, previous, &prior, txn),
None => InputStage::apply_ple_cached(binding, previous, &prior, txn, Some(cache)),
},
)?;
ple.validate_origin(&binding.identity())?;
ple.identity().validate(txn.token(), txn.position(), layer)?;
let pending = ple.take_pending()?;
txn.stage_ple(&prior, pending)?;
GrStage::prepare_micro_after_ple(binding, layer, &ple, txn)
}
1 => prepare_layer_one_micro(binding, layer, previous, txn, cache, ple_micro),
_ => GrStage::prepare_micro_after_ffn(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn),
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn prepare_layer_one_micro(
binding: &ModelBinding,
layer: LayerId,
previous: Option<&InjectedResidual>,
txn: &mut QwenStepTxn,
cache: &DenseWeightCache<'_>,
ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>,
) -> Result<super::super::gr::GrMicroInput> {
let previous = previous.ok_or(Error::IdentityMismatch)?;
let prior = txn.ple_prior()?;
let mut ple = diagnose(
ForwardPhase::Ple,
layer.get(),
txn.position(),
match ple_micro {
Some(batch) => batch.take_ready(binding, previous, &prior, txn),
None => InputStage::apply_ple_cached(binding, previous, &prior, txn, Some(cache)),
},
)?;
ple.validate_origin(&binding.identity())?;
ple.identity().validate(txn.token(), txn.position(), layer)?;
let pending = ple.take_pending()?;
txn.stage_ple(&prior, pending)?;
GrStage::prepare_micro_after_ple(binding, layer, &ple, txn)
}
pub(super) fn validate_layer_plan(binding: &ModelBinding) -> Result<Dimension> {
validate_descriptors(
binding.layer_count(),
@@ -28,16 +28,26 @@ pub(super) fn prepare_step_caches(
cache.validate(binding)?;
}
if let Some(cache) = moe_cache {
let context = txn.cuda_context()?;
if dense_cache.map(|dense| dense.gdn_four_borrow(binding, context)).transpose()?.unwrap_or(false) {
cache.reserve_mmq_transient(binding, context, super::super::gdn::FOUR_BORROW_BYTES)?;
} else {
cache.prepare_step(binding, txn.cuda_context()?)?;
}
reserve_moe_step(binding, dense_cache, cache, txn)?;
}
Ok(layer_bound)
}
fn reserve_moe_step(
binding: &ModelBinding,
dense_cache: Option<&DenseWeightCache<'_>>,
cache: &mut MoeWeightCache<'_>,
txn: &mut QwenStepTxn,
) -> Result<()> {
let context = txn.cuda_context()?;
if dense_cache.map(|dense| dense.gdn_four_borrow(binding, context)).transpose()?.unwrap_or(false) {
cache.reserve_mmq_transient(binding, context, super::super::gdn::FOUR_BORROW_BYTES)?;
} else {
cache.prepare_step(binding, txn.cuda_context()?)?;
}
Ok(())
}
/// Consume and stage the input row (native or KAR provider).
pub(super) fn stage_input_row(
binding: &ModelBinding,
@@ -1,8 +1,11 @@
//! Separate whole-expert resident GPU / owned native CPU miss producer.
//! Only genuine completed rows reach the original ascending-slot combine.
use super::*;
use crate::model_binding::qwen4exp_input::MoeWeightDescriptor;
#[path = "moe_group_adaptive/adaptive_wave_fn.rs"]
mod adaptive_wave_fn;
use crate::model_binding::qwen4exp_input::{MoeRoutedSourceScope, MoeWeightDescriptor};
use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error};
use adaptive_wave_fn::AdaptiveWave;
#[allow(clippy::too_many_arguments)]
pub(super) fn project_adaptive_groups<'ctx>(
@@ -23,60 +26,19 @@ pub(super) fn project_adaptive_groups<'ctx>(
cache.observe_strata_adaptive_row(binding, &row.row().weights)?;
}
let (residents, misses) = split_resident_misses(binding, rows, groups, cache)?;
// Actual outer wave directories coexist with owned jobs until join.
let job_allowance = wave_job_allowance(residents.capacity(), misses.capacity())?;
let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared };
wave.run(cache, down, cancelled, actual, &residents, &misses, job_allowance)
}
/// Actual outer wave directories coexist with owned jobs until join.
fn wave_job_allowance(residents: usize, misses: usize) -> Result<usize> {
let wave_metadata = residents
.capacity()
.checked_add(misses.capacity())
.checked_add(misses)
.and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>()))
.and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>()))
.ok_or(Error::Overflow)?;
let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)?;
let mut gpu_done = false;
let cpu_owner = cache.cpu_miss_owner(binding)?;
let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let mut offset = 0usize;
while offset < misses.len() {
let end = miss_batch_end(rows, &misses, offset)?;
let batch = &misses[offset..end];
offset = end;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let jobs = prepare_cpu_jobs(binding, rows, batch, &cpu, job_allowance)?;
// Model-lifetime stacks/native scratch were admitted before the pool.
// This request admits <=16 jobs and <=48MiB INCLUDING actual directory,
// preparation and start/join metadata/capacities. Callees measure their
// own retained capacities against this remaining allowance before send.
let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?;
let gpu_result = if gpu_done {
Ok(())
} else {
let done =
project_residents(context, binding, rows, &residents, cache, prepared, scope, origins, down, cancelled);
gpu_done = done.is_ok();
done
};
// Always drain actual CPU consumers, including GPU failure/cancellation.
// Preserve the primary GPU failure; no source allocation outlives join.
let completed = pending.join().map_err(runtime_error);
gpu_result?;
let completed = completed?;
if completed.len() != batch.len() {
return Err(Error::IdentityMismatch);
}
for (values, pairs) in completed.into_iter().zip(batch) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?;
upload_completed_rows(scope, binding, &keys, pairs, &values, origins, down)?;
drop(values.into_values());
}
}
if !gpu_done {
project_residents(context, binding, rows, &residents, cache, prepared, scope, origins, down, cancelled)?;
}
Ok(())
(48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)
}
/// Resident groups run on the GPU; misses are cut into row-ordered batches of at most eight pairs.
@@ -110,7 +72,7 @@ fn split_resident_misses<'g>(
}
/// End of the next CPU batch: at most 16 miss groups with distinct experts.
fn miss_batch_end(rows: &[ChunkFfnRow], misses: &[&[Pair]], offset: usize) -> Result<usize> {
pub(super) fn miss_batch_end(rows: &[ChunkFfnRow], misses: &[&[Pair]], offset: usize) -> Result<usize> {
let mut end = offset;
let mut seen = [false; 512];
while end < misses.len() && end - offset < 16 {
@@ -154,7 +116,7 @@ fn project_residents<'ctx>(
}
/// Prepare the owned CPU jobs of one batch under the 48MiB wave allowance.
fn prepare_cpu_jobs(
pub(super) fn prepare_cpu_jobs(
binding: &ModelBinding,
rows: &[ChunkFfnRow],
batch: &[&[Pair]],
@@ -189,28 +151,12 @@ fn prepare_cpu_job(
) -> Result<PreparedCpuMiss> {
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
let mut inputs = Vec::new();
inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
for pair in pairs {
inputs.push(rows[pair.row].row().read.ready().mixed());
}
let inputs = row_inputs(rows, pairs)?;
binding.with_moe_routed_source(&members, binding_error, |source| {
// Final immutable native blob temporarily coexists with all
// three actual source role Boxes and the owned row inputs.
let raw_bytes =
[MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold(0usize, |n, role| {
n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow)
})?;
let preparation_peak = raw_bytes
.checked_mul(2)
.and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows)))
.and_then(|n| n.checked_add(prepared_bytes))
.and_then(|n| n.checked_add(preparation_metadata))
.and_then(|n| {
inputs.capacity().checked_mul(std::mem::size_of::<&[f32]>()).and_then(|refs| n.checked_add(refs))
})
.and_then(|n| n.checked_add(std::mem::size_of::<PreparedCpuMiss>()))
.ok_or(Error::Overflow)?;
let raw_bytes = source_raw_bytes(source)?;
let preparation_peak = preparation_peak(raw_bytes, &inputs, prepared_bytes, preparation_metadata)?;
if preparation_peak > job_allowance {
return Err(Error::InputAllocation);
}
@@ -222,6 +168,45 @@ fn prepare_cpu_job(
})
}
pub(super) fn source_keys(source: &MoeRoutedSourceScope<'_, '_>) -> Result<[MoeWeightDescriptor; 3]> {
Ok([
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
])
}
fn row_inputs<'r>(rows: &'r [ChunkFfnRow], pairs: &[Pair]) -> Result<Vec<&'r [f32]>> {
let mut inputs = Vec::new();
inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
for pair in pairs {
inputs.push(rows[pair.row].row().read.ready().mixed());
}
Ok(inputs)
}
fn source_raw_bytes(source: &MoeRoutedSourceScope<'_, '_>) -> Result<usize> {
[MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold(0usize, |n, role| {
n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow)
})
}
fn preparation_peak(
raw_bytes: usize,
inputs: &Vec<&[f32]>,
prepared_bytes: usize,
preparation_metadata: usize,
) -> Result<usize> {
raw_bytes
.checked_mul(2)
.and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows)))
.and_then(|n| n.checked_add(prepared_bytes))
.and_then(|n| n.checked_add(preparation_metadata))
.and_then(|n| inputs.capacity().checked_mul(std::mem::size_of::<&[f32]>()).and_then(|refs| n.checked_add(refs)))
.and_then(|n| n.checked_add(std::mem::size_of::<PreparedCpuMiss>()))
.ok_or(Error::Overflow)
}
/// Validate one completed CPU batch member against its source descriptors and row origins.
#[allow(clippy::too_many_arguments)]
fn completed_keys<'ctx>(
@@ -238,11 +223,7 @@ fn completed_keys<'ctx>(
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
binding.with_moe_routed_source(&members, binding_error, |source| {
let keys = [
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
];
let keys = source_keys(source)?;
if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N {
return Err(Error::IdentityMismatch);
}
@@ -0,0 +1,139 @@
//! The adaptive wave: resident GPU groups beside owned CPU miss batches (STRA-338 size: extract-method only).
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, runtime_error};
/// The shared inputs of one adaptive wave: resident groups on the GPU, misses on the owned CPU pool.
#[derive(Clone, Copy)]
pub(super) struct AdaptiveWave<'a, 'ctx> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) rows: &'a [ChunkFfnRow],
pub(super) scope: &'a DownScope<'ctx>,
pub(super) origins: &'a [Rc<DownOrigin>],
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
}
impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> {
/// Run the miss batches in order; the resident GPU groups run once, overlapped with the first batch.
#[allow(clippy::too_many_arguments)]
pub(super) fn run(
&self,
cache: &mut MoeWeightCache<'_>,
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, '_>>,
residents: &[&[Pair]],
misses: &[&[Pair]],
job_allowance: usize,
) -> Result<()> {
let mut gpu_done = false;
let cpu_owner = cache.cpu_miss_owner(self.binding)?;
let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let mut offset = 0usize;
while offset < misses.len() {
let end = miss_batch_end(self.rows, misses, offset)?;
let batch = &misses[offset..end];
offset = end;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let resident = if gpu_done { None } else { Some(residents) };
self.run_batch(cache, down, cancelled, actual, &mut cpu, batch, resident, job_allowance)?;
gpu_done = true;
}
if !gpu_done {
self.project_residents(residents, cache, down, cancelled)?;
}
Ok(())
}
/// Start the CPU jobs of one batch, run the resident GPU groups (first batch only) while they execute, drain
/// the CPU side, then upload the completed rows. Model-lifetime stacks/native scratch were admitted before the
/// pool. This request admits <=16 jobs and <=48MiB INCLUDING actual directory, preparation and start/join
/// metadata/capacities. Callees measure their own retained capacities against this remaining allowance before send.
#[allow(clippy::too_many_arguments)]
fn run_batch(
&self,
cache: &mut MoeWeightCache<'_>,
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, '_>>,
cpu: &mut CpuMissWorkspace,
batch: &[&[Pair]],
residents: Option<&[&[Pair]]>,
job_allowance: usize,
) -> Result<()> {
let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, job_allowance)?;
let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?;
let gpu_result = match residents {
None => Ok(()),
Some(residents) => self.project_residents(residents, cache, down, cancelled),
};
// Always drain actual CPU consumers, including GPU failure/cancellation.
// Preserve the primary GPU failure; no source allocation outlives join.
let completed = pending.join().map_err(runtime_error);
gpu_result?;
let completed = completed?;
if completed.len() != batch.len() {
return Err(Error::IdentityMismatch);
}
self.finish_members(cache, down, cancelled, actual, completed, batch)
}
fn finish_members(
&self,
cache: &mut MoeWeightCache<'_>,
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, '_>>,
completed: Vec<CpuMissRows>,
batch: &[&[Pair]],
) -> Result<()> {
for (values, pairs) in completed.into_iter().zip(batch) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.finish_member(cache, down, actual, pairs, values)?;
}
Ok(())
}
fn project_residents(
&self,
residents: &[&[Pair]],
cache: &mut MoeWeightCache<'_>,
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let (context, binding, rows) = (self.context, self.binding, self.rows);
project_residents(
context,
binding,
rows,
residents,
cache,
self.prepared,
self.scope,
self.origins,
down,
cancelled,
)
}
fn finish_member(
&self,
cache: &mut MoeWeightCache<'_>,
down: &mut [[Option<ActualDown<'ctx>>; K]],
actual: Option<&QwenChunkTxn<'_, '_>>,
pairs: &[Pair],
values: CpuMissRows,
) -> Result<()> {
let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins);
let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?;
upload_completed_rows(self.scope, binding, &keys, pairs, &values, origins, down)?;
drop(values.into_values());
Ok(())
}
}
@@ -7,6 +7,10 @@ use crate::qwen_forward::cpu_expert_miss::runtime_error;
mod project_adaptive_packets_fn;
#[allow(unused_imports)]
pub(super) use project_adaptive_packets_fn::project_adaptive_packets;
#[path = "moe_group_adaptive_packets/packet_plan_fn.rs"]
mod packet_plan_fn;
#[path = "moe_group_adaptive_packets/packet_wave_fn.rs"]
mod packet_wave_fn;
#[path = "moe_group_adaptive_packets/project_inner_fn.rs"]
mod project_inner_fn;
#[allow(unused_imports)]
@@ -14,6 +18,4 @@ use project_inner_fn::project_inner;
#[path = "moe_group_adaptive_packets/stage_gpu_wave_fn.rs"]
mod stage_gpu_wave_fn;
#[allow(unused_imports)]
use stage_gpu_wave_fn::consume_gpu_wave;
#[allow(unused_imports)]
use stage_gpu_wave_fn::stage_gpu_wave;
@@ -0,0 +1,167 @@
//! Expert-group plan of one adaptive packet wave (STRA-338 size: extract-method only).
#[allow(unused_imports)]
use super::*;
/// The expert groups of one wave split into resident GPU groups, CPU miss batches and the GPU miss queue.
pub(super) struct PacketPlan<'g> {
pub(super) residents: Vec<&'g [Pair]>,
pub(super) distinct_misses: Vec<&'g [Pair]>,
pub(super) misses: Vec<&'g [Pair]>,
pub(super) gpu_misses: Vec<&'g [Pair]>,
}
impl<'g> PacketPlan<'g> {
pub(super) fn new(groups: usize) -> Result<Self> {
let mut residents = Vec::new();
let mut distinct_misses = Vec::new();
let mut misses = Vec::new();
let mut gpu_misses = Vec::new();
residents.try_reserve_exact(groups).map_err(|_| Error::InputAllocation)?;
distinct_misses.try_reserve_exact(groups).map_err(|_| Error::InputAllocation)?;
gpu_misses.try_reserve_exact(groups).map_err(|_| Error::InputAllocation)?;
misses.try_reserve_exact(groups * 8).map_err(|_| Error::InputAllocation)?;
Ok(Self { residents, distinct_misses, misses, gpu_misses })
}
/// Literal Strata row-major first occurrence. Group storage remains indexed
/// by expert; packet combine keeps its original ten-slot f64 ordering.
#[allow(clippy::too_many_arguments)]
pub(super) fn classify(
&mut self,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
groups: &'g [Vec<Pair>],
cache: &mut MoeWeightCache<'_>,
origins: &[Rc<DownOrigin>],
packets: &[ActualSlotPacket<'_>],
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
let mut seen = [false; 512];
for row in rows {
for selected in row.row().route.experts() {
let expert = selected.get() as usize;
if expert >= groups.len() || expert >= 512 {
return Err(Error::InvalidExpert);
}
if std::mem::replace(&mut seen[expert], true) {
continue;
}
let pairs = groups[expert].as_slice();
validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?;
self.classify_pairs(binding, rows, pairs, cache)?;
}
}
Ok(())
}
fn classify_pairs(
&mut self,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
pairs: &'g [Pair],
cache: &mut MoeWeightCache<'_>,
) -> Result<()> {
let first = pairs[0];
let weights = &rows[first.row].row().weights;
if cache.strata_adaptive_resident(binding, weights, MoeExpertSelection::Routed { slot: first.slot })? {
self.residents.push(pairs);
} else {
self.distinct_misses.push(pairs);
}
Ok(())
}
pub(super) fn assign_misses(
&mut self,
context: &Context<'_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
cache: &MoeWeightCache<'_>,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
if actual.is_mtp_verification()? {
return self.assign_mtp(context, binding, rows, cache);
}
// Prompt phase stages every used nonresident expert by actual expert ID.
// Legacy factory remains two-slot detached copies. The separately
// selected mapped factory owns real registered banks and16 fixed slots;
// prompt groups preserve expert-ID order with bounded reuse waves.
// Every pair was authenticated above; sorting allocates no directory.
self.distinct_misses.sort_unstable_by_key(|pairs| {
let first = pairs[0];
rows[first.row].row().route.experts()[first.slot].get()
});
for pairs in &self.distinct_misses {
self.gpu_misses.push(*pairs);
}
Ok(())
}
/// Private mode binds 141/256 explicitly. It is not an assertion that the
/// bandwidth-adjusted live Original17 selected exactly 0.55.
pub(super) fn assign_mtp(
&mut self,
context: &Context<'_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
cache: &MoeWeightCache<'_>,
) -> Result<()> {
let gpu_count = self.distinct_misses.len().checked_mul(141).ok_or(Error::Overflow)? / 256;
let cpu_count = self.distinct_misses.len().checked_sub(gpu_count).ok_or(Error::Overflow)?;
for (index, pairs) in self.distinct_misses.iter().enumerate() {
let tail = index >= cpu_count;
if tail && tail_eligible(context, binding, rows, cache, pairs, self.gpu_misses.len())? {
self.gpu_misses.push(*pairs);
} else {
for batch in pairs.chunks(8) {
self.misses.push(batch);
}
}
}
Ok(())
}
/// Actual outer wave directories coexist with owned jobs until join.
pub(super) fn job_allowance(&self) -> Result<usize> {
let wave_metadata = self
.residents
.capacity()
.checked_add(self.misses.capacity())
.and_then(|n| n.checked_add(self.distinct_misses.capacity()))
.and_then(|n| n.checked_add(self.gpu_misses.capacity()))
.and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>()))
.and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>()))
.and_then(|n| {
n.checked_add(std::mem::size_of::<[Option<usize>; 18]>() + std::mem::size_of::<&mut [Option<usize>]>())
})
.ok_or(Error::Overflow)?;
(48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)
}
}
/// Whether a native tail miss may take a GPU slot. Native tail only: no replacement quota from the CPU prefix.
/// Capacity is actual allocated single16/split8 owner, not T.
pub(super) fn tail_eligible(
context: &Context<'_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
cache: &MoeWeightCache<'_>,
pairs: &[Pair],
gpu_len: usize,
) -> Result<bool> {
if !cache.uses_mapped_expert_source()? {
return Ok(true);
}
let owner = cache.ephemeral_routed_owner(binding, context)?;
let capacity = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count();
if gpu_len >= capacity || pairs.len() > 64 {
return Ok(false);
}
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
binding.with_moe_routed_source(&members, binding_error, |source| {
let eligible = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.mapped_eligible(binding, source, 0)?;
source.finish().map_err(binding_error)?;
Ok(eligible)
})
}
@@ -0,0 +1,305 @@
//! GPU queue and CPU miss batches of one adaptive packet wave (STRA-338 size: extract-method only).
use super::super::adaptive::{miss_batch_end, prepare_cpu_jobs, source_keys};
use super::packet_plan_fn::PacketPlan;
#[allow(unused_imports)]
use super::*;
use crate::model_binding::qwen4exp_input::MoeWeightDescriptor;
use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace};
/// The GPU miss queue state: the shared miss list, the next miss to stage and the occupied ephemeral slots, plus the
/// resident groups and CPU miss batches that run beside it.
pub(super) struct GpuWave<'a, 'g> {
pub(super) misses: &'a [&'g [Pair]],
pub(super) residents: &'a [&'g [Pair]],
pub(super) cpu_misses: &'a [&'g [Pair]],
pub(super) job_allowance: usize,
pub(super) next: usize,
pub(super) slots: &'a mut [Option<usize>],
pub(super) done: bool,
}
/// The shared inputs of one packet wave.
#[derive(Clone, Copy)]
pub(super) struct PacketWave<'a, 'ctx> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) rows: &'a [ChunkFfnRow],
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
pub(super) scope: &'a DownScope<'ctx>,
pub(super) origins: &'a [Rc<DownOrigin>],
}
impl<'a, 'ctx> PacketWave<'a, 'ctx> {
pub(super) fn stage(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let (context, binding, rows) = (self.context, self.binding, self.rows);
stage_gpu_wave(context, binding, rows, gpu.misses, cache, &mut gpu.next, gpu.slots, cancelled)
}
/// Wait for and project every occupied ephemeral slot of the GPU queue.
pub(super) fn consume(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
for (slot, directory) in gpu.slots.iter_mut().enumerate() {
let Some(index) = *directory else {
continue;
};
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let owner = cache.ephemeral_routed_owner(self.binding, self.context)?;
owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, self.binding)?;
let pairs = gpu.misses.get(index).ok_or(Error::IdentityMismatch)?;
self.project_one(pairs, Some(slot), cache, packets, cancelled, actual)?;
*directory = None;
}
Ok(())
}
pub(super) fn project_residents(
&self,
gpu: &GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
for pairs in gpu.residents {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.project_one(pairs, None, cache, packets, cancelled, actual)?;
}
Ok(())
}
fn project_one(
&self,
pairs: &[Pair],
slot: Option<usize>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
let (context, binding, rows) = (self.context, self.binding, self.rows);
let (prepared, scope, origins) = (self.prepared, self.scope, self.origins);
resident_queue::project_group_packets(
context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, slot,
)
}
/// Residents (once), then the staged GPU misses, then the next stage of the queue.
pub(super) fn gpu_phase(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
if !gpu.done {
self.project_residents(gpu, cache, packets, cancelled, actual)?;
gpu.done = true;
}
self.consume(gpu, cache, packets, cancelled, actual)?;
self.stage(gpu, cache, cancelled)?;
Ok(())
}
pub(super) fn finish_gpu(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
if !gpu.done {
self.project_residents(gpu, cache, packets, cancelled, actual)?;
}
while gpu.slots.iter().any(Option::is_some) {
self.consume(gpu, cache, packets, cancelled, actual)?;
self.stage(gpu, cache, cancelled)?;
}
Ok(())
}
pub(super) fn run_misses(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
let cpu_owner = cache.cpu_miss_owner(self.binding)?;
let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let misses = gpu.cpu_misses;
let mut offset = 0usize;
while offset < misses.len() {
let end = miss_batch_end(self.rows, misses, offset)?;
let batch = &misses[offset..end];
offset = end;
self.run_batch(gpu, cache, packets, cancelled, actual, &mut cpu, batch)?;
}
Ok(())
}
/// Start the prepared CPU jobs, overlap the GPU phase, drain the CPU side, then upload the completed rows.
/// Model-lifetime stacks/native scratch were admitted before the pool. This request admits <=16 jobs and
/// <=48MiB INCLUDING actual directory, preparation and start/join metadata/capacities. Callees measure their own
/// retained capacities against this remaining allowance before send. Always drain actual CPU consumers,
/// including GPU failure/cancellation; preserve the primary GPU failure; no source allocation outlives join.
#[allow(clippy::too_many_arguments)]
pub(super) fn run_batch(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
cpu: &mut CpuMissWorkspace,
batch: &[&[Pair]],
) -> Result<()> {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, gpu.job_allowance)?;
let pending = cpu.start(jobs, gpu.job_allowance).map_err(runtime_error)?;
let gpu_result = self.gpu_phase(gpu, cache, packets, cancelled, actual);
let completed = pending.join().map_err(runtime_error);
gpu_result?;
let completed = completed?;
if completed.len() != batch.len() {
return Err(Error::IdentityMismatch);
}
for (values, pairs) in completed.into_iter().zip(batch) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.finish_member(cache, packets, cancelled, actual, pairs, values)?;
}
Ok(())
}
pub(super) fn finish_member(
&self,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
pairs: &[Pair],
values: CpuMissRows,
) -> Result<()> {
let keys = self.completed_keys(cache, packets, actual, pairs, &values)?;
for (row_index, pair) in pairs.iter().enumerate() {
self.upload_pair(cache, packets, cancelled, actual, &keys, &values, row_index, pair)?;
}
drop(values.into_values());
Ok(())
}
/// Validate one completed CPU batch member against its source descriptors, row origins and packets.
pub(super) fn completed_keys(
&self,
cache: &MoeWeightCache<'_>,
packets: &[ActualSlotPacket<'ctx>],
actual: &QwenChunkTxn<'_, '_>,
pairs: &[Pair],
values: &CpuMissRows,
) -> Result<[MoeWeightDescriptor; 3]> {
let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins);
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
binding.with_moe_routed_source(&members, binding_error, |source| {
let keys = source_keys(source)?;
if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N {
return Err(Error::IdentityMismatch);
}
source.finish().map_err(binding_error)?;
cache.validate(binding, context)?;
for pair in pairs {
self.check_row_current(actual, pair)?;
packets[pair.row].validate(&origins[pair.row], binding, rows[pair.row].row().route.identity())?;
}
Ok(keys)
})
}
/// The actual immutable row, binding and origin remain current.
pub(super) fn check_row_current(&self, actual: &QwenChunkTxn<'_, '_>, pair: &Pair) -> Result<()> {
let (binding, rows, origins) = (self.binding, self.rows, self.origins);
actual.validate_ffn_row(
actual.micro_row_index(pair.row)?,
rows[pair.row].row().route.identity().layer(),
&rows[pair.row],
)?;
let row = rows[pair.row].row();
let id = row.route.identity();
row.validate(&binding.identity(), id.token(), id.position(), id.layer())?;
if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id {
return Err(Error::IdentityMismatch);
}
Ok(())
}
/// Retain the genuine completed CPU owner until every actual upload
/// and device Down finite check has completed. No host-only proof.
#[allow(clippy::too_many_arguments)]
pub(super) fn upload_pair(
&self,
cache: &MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
keys: &[MoeWeightDescriptor; 3],
values: &CpuMissRows,
row_index: usize,
pair: &Pair,
) -> Result<()> {
let selection = DownSelection::Routed(pair.slot);
let output = self.scope.upload_cpu_completed_row(self.binding, keys, selection, values, row_index)?;
// The actual CPU row owns a completed H2D and whole Down finite
// scan. Its device owner and the completed CPU owner stay alive
// through the direct copy and post-copy causal checks.
let copy_result = output.with_completed(self.scope, selection, |buffer| {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.copy_completed_row(cache, packets, cancelled, actual, pair, buffer)
});
let cleanup = output.close();
copy_result.and(cleanup)
}
pub(super) fn copy_completed_row(
&self,
cache: &MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
pair: &Pair,
buffer: &DeviceBuffer<'ctx>,
) -> Result<()> {
let mut target = [(&mut packets[pair.row].packet, pair.slot)];
super::super::moe_down::ResidentPackedDown::copy_group_with(self.scope, &mut target, |copies| {
self.context.copy_routed_down_columns_to_slots(buffer, 1, copies).map_err(driver_error)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
cache.validate(self.binding, self.context)?;
self.check_row_current(actual, pair)
})
}
}
@@ -1,5 +1,7 @@
//! Moved out of the parent module by STRA-338: fn project_inner.
use super::packet_plan_fn::PacketPlan;
use super::packet_wave_fn::{GpuWave, PacketWave};
#[allow(unused_imports)]
use super::*;
@@ -17,345 +19,37 @@ pub(super) fn project_inner<'ctx>(
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
observe_adaptive(binding, rows, cache)?;
let mut plan = PacketPlan::new(groups.len())?;
plan.classify(binding, rows, groups, cache, origins, packets, actual)?;
plan.assign_misses(context, binding, rows, cache, actual)?;
let slot_count = ephemeral_slot_count(context, binding, cache)?;
let mut legacy_slots = [None; 2];
let mut mapped_slots = [None; 16];
let slots: &mut [Option<usize>] = if slot_count == 2 { &mut legacy_slots } else { &mut mapped_slots[..slot_count] };
let wave = PacketWave { context, binding, rows, prepared, scope, origins };
let (misses, residents, cpu_misses) = (&plan.gpu_misses[..], &plan.residents[..], &plan.misses[..]);
let mut gpu = GpuWave { misses, residents, cpu_misses, job_allowance: 0, next: 0, slots, done: false };
wave.stage(&mut gpu, cache, cancelled)?;
gpu.job_allowance = plan.job_allowance()?;
wave.run_misses(&mut gpu, cache, packets, cancelled, actual)?;
wave.finish_gpu(&mut gpu, cache, packets, cancelled, actual)
}
fn observe_adaptive(binding: &ModelBinding, rows: &[ChunkFfnRow], cache: &mut MoeWeightCache<'_>) -> Result<()> {
cache.poll_strata_adaptive(binding, false)?;
for row in rows {
cache.observe_strata_adaptive_row(binding, &row.row().weights)?;
}
let mut residents = Vec::new();
let mut distinct_misses = Vec::new();
let mut misses = Vec::new();
let mut gpu_misses = Vec::new();
let mut seen = [false; 512];
residents.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?;
distinct_misses.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?;
gpu_misses.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?;
misses.try_reserve_exact(groups.len() * 8).map_err(|_| Error::InputAllocation)?;
// Literal Strata row-major first occurrence. Group storage remains indexed
// by expert; packet combine keeps its original ten-slot f64 ordering.
for row in rows {
for selected in row.row().route.experts() {
let expert = selected.get() as usize;
if expert >= groups.len() || expert >= 512 {
return Err(Error::InvalidExpert);
}
if seen[expert] {
continue;
}
seen[expert] = true;
let pairs = groups[expert].as_slice();
validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?;
let first = pairs[0];
if cache.strata_adaptive_resident(
binding,
&rows[first.row].row().weights,
MoeExpertSelection::Routed { slot: first.slot },
)? {
residents.push(pairs);
} else {
distinct_misses.push(pairs);
}
}
}
if actual.is_mtp_verification()? {
// Private mode binds 141/256 explicitly. It is not an assertion that the
// bandwidth-adjusted live Original17 selected exactly 0.55.
let gpu_count = distinct_misses.len().checked_mul(141).ok_or(Error::Overflow)? / 256;
let cpu_count = distinct_misses.len().checked_sub(gpu_count).ok_or(Error::Overflow)?;
for (index, pairs) in distinct_misses.iter().enumerate() {
let mut eligible = index >= cpu_count;
if eligible && cache.uses_mapped_expert_source()? {
let owner = cache.ephemeral_routed_owner(binding, context)?;
let capacity = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count();
// Native tail only: no replacement quota from the CPU prefix.
// Capacity is actual allocated single16/split8 owner, not T.
eligible = gpu_misses.len() < capacity && pairs.len() <= 64;
if eligible {
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
eligible = binding.with_moe_routed_source(&members, binding_error, |source| {
let eligible = owner
.try_borrow()
.map_err(|_| Error::IdentityMismatch)?
.mapped_eligible(binding, source, 0)?;
source.finish().map_err(binding_error)?;
Ok(eligible)
})?;
}
}
if eligible {
gpu_misses.push(*pairs);
} else {
for batch in pairs.chunks(8) {
misses.push(batch);
}
}
}
} else {
// Prompt phase stages every used nonresident expert by actual expert ID.
// Legacy factory remains two-slot detached copies. The separately
// selected mapped factory owns real registered banks and16 fixed slots;
// prompt groups preserve expert-ID order with bounded reuse waves.
// Every pair was authenticated above; sorting allocates no directory.
distinct_misses.sort_unstable_by_key(|pairs| {
let first = pairs[0];
rows[first.row].row().route.experts()[first.slot].get()
});
for pairs in &distinct_misses {
gpu_misses.push(*pairs);
}
}
let mut gpu_next = 0;
let slot_count =
cache.ephemeral_routed_owner(binding, context)?.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count();
let mut legacy_slots = [None; 2];
let mut mapped_slots = [None; 16];
Ok(())
}
/// The actual slot count of the ephemeral routed owner: legacy two-slot copies or the mapped 8/16-slot factory.
fn ephemeral_slot_count(context: &Context<'_>, binding: &ModelBinding, cache: &MoeWeightCache<'_>) -> Result<usize> {
let owner = cache.ephemeral_routed_owner(binding, context)?;
let slot_count = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count();
if !matches!(slot_count, 2 | 8 | 16) {
return Err(Error::IdentityMismatch);
}
let mut slots: &mut [Option<usize>] =
if slot_count == 2 { &mut legacy_slots } else { &mut mapped_slots[..slot_count] };
stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?;
// Actual outer wave directories coexist with owned jobs until join.
let wave_metadata = residents
.capacity()
.checked_add(misses.capacity())
.and_then(|n| n.checked_add(distinct_misses.capacity()))
.and_then(|n| n.checked_add(gpu_misses.capacity()))
.and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>()))
.and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>()))
.and_then(|n| {
n.checked_add(std::mem::size_of::<[Option<usize>; 18]>() + std::mem::size_of::<&mut [Option<usize>]>())
})
.ok_or(Error::Overflow)?;
let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)?;
let mut gpu_done = false;
let cpu_owner = cache.cpu_miss_owner(binding)?;
let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
let mut offset = 0usize;
while offset < misses.len() {
let mut end = offset;
let mut seen = [false; 512];
while end < misses.len() && end - offset < 16 {
let first = misses[end][0];
let expert = rows[first.row].row().route.experts()[first.slot].get() as usize;
if expert >= 512 {
return Err(Error::InvalidExpert);
}
if seen[expert] {
break;
}
seen[expert] = true;
end += 1;
}
if end == offset {
return Err(Error::IdentityMismatch);
}
let batch = &misses[offset..end];
offset = end;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let mut jobs = Vec::new();
jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?;
let mut prepared_bytes = 0usize;
let preparation_metadata = jobs
.capacity()
.checked_mul(std::mem::size_of::<crate::qwen_forward::cpu_expert_miss::PreparedCpuMiss>())
.ok_or(Error::Overflow)?;
for pairs in batch {
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
let mut inputs = Vec::new();
inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
for pair in *pairs {
inputs.push(rows[pair.row].row().read.ready().mixed());
}
let job = binding.with_moe_routed_source(&members, binding_error, |source| {
// Final immutable native blob temporarily coexists with all
// three actual source role Boxes and the owned row inputs.
let raw_bytes = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold(
0usize,
|n, role| {
n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow)
},
)?;
let preparation_peak = raw_bytes
.checked_mul(2)
.and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows)))
.and_then(|n| n.checked_add(prepared_bytes))
.and_then(|n| n.checked_add(preparation_metadata))
.and_then(|n| {
inputs
.capacity()
.checked_mul(std::mem::size_of::<&[f32]>())
.and_then(|refs| n.checked_add(refs))
})
.and_then(|n| {
n.checked_add(std::mem::size_of::<crate::qwen_forward::cpu_expert_miss::PreparedCpuMiss>())
})
.ok_or(Error::Overflow)?;
if preparation_peak > job_allowance {
return Err(Error::InputAllocation);
}
let job = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?;
// Owned immutable validated bytes detach before other actor GPU
// callbacks; no RefMut/source/Context crosses the CPU thread.
source.finish().map_err(binding_error)?;
Ok(job)
})?;
prepared_bytes =
prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?).ok_or(Error::InputAllocation)?;
if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) {
return Err(Error::InputAllocation);
}
jobs.push(job);
}
// Model-lifetime stacks/native scratch were admitted before the pool.
// This request admits <=16 jobs and <=48MiB INCLUDING actual directory,
// preparation and start/join metadata/capacities. Callees measure their
// own retained capacities against this remaining allowance before send.
let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?;
let gpu_result = (|| {
if !gpu_done {
for pairs in &residents {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
resident_queue::project_group_packets(
context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual,
None,
)?;
}
gpu_done = true;
}
consume_gpu_wave(
context,
binding,
rows,
&gpu_misses,
cache,
prepared,
scope,
origins,
packets,
&mut slots,
cancelled,
actual,
)?;
stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?;
Ok(())
})();
// Always drain actual CPU consumers, including GPU failure/cancellation.
// Preserve the primary GPU failure; no source allocation outlives join.
let completed = pending.join().map_err(runtime_error);
gpu_result?;
let completed = completed?;
if completed.len() != batch.len() {
return Err(Error::IdentityMismatch);
}
for (values, pairs) in completed.into_iter().zip(batch) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let first = pairs[0];
let members = [(&rows[first.row].row().weights, first.slot)];
let keys = binding.with_moe_routed_source(&members, binding_error, |source| {
let keys = [
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
];
if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N {
return Err(Error::IdentityMismatch);
}
source.finish().map_err(binding_error)?;
cache.validate(binding, context)?;
for pair in *pairs {
actual.validate_ffn_row(
actual.micro_row_index(pair.row)?,
rows[pair.row].row().route.identity().layer(),
&rows[pair.row],
)?;
let row = rows[pair.row].row();
let id = row.route.identity();
row.validate(&binding.identity(), id.token(), id.position(), id.layer())?;
if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id {
return Err(Error::IdentityMismatch);
}
packets[pair.row].validate(&origins[pair.row], binding, id)?;
}
Ok(keys)
})?;
// Retain the genuine completed CPU owner until every actual upload
// and device Down finite check has completed. No host-only proof.
for (row_index, pair) in pairs.iter().enumerate() {
let output = scope.upload_cpu_completed_row(
binding,
&keys,
DownSelection::Routed(pair.slot),
&values,
row_index,
)?;
// The actual CPU row owns a completed H2D and whole Down finite
// scan. Its device owner and the completed CPU owner stay alive
// through the direct copy and post-copy causal checks.
let copy_result = output.with_completed(scope, DownSelection::Routed(pair.slot), |buffer| {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let mut target = [(&mut packets[pair.row].packet, pair.slot)];
super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut target, |copies| {
context.copy_routed_down_columns_to_slots(buffer, 1, copies).map_err(driver_error)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
cache.validate(binding, context)?;
actual.validate_ffn_row(
actual.micro_row_index(pair.row)?,
rows[pair.row].row().route.identity().layer(),
&rows[pair.row],
)?;
let row = rows[pair.row].row();
let id = row.route.identity();
row.validate(&binding.identity(), id.token(), id.position(), id.layer())?;
if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id {
return Err(Error::IdentityMismatch);
}
Ok(())
})
});
let cleanup = output.close();
copy_result.and(cleanup)?;
}
drop(values.into_values());
}
}
if !gpu_done {
for pairs in residents {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
resident_queue::project_group_packets(
context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, None,
)?;
}
}
while slots.iter().any(Option::is_some) {
consume_gpu_wave(
context,
binding,
rows,
&gpu_misses,
cache,
prepared,
scope,
origins,
packets,
&mut slots,
cancelled,
actual,
)?;
stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?;
}
Ok(())
Ok(slot_count)
}
@@ -34,45 +34,3 @@ pub(super) fn stage_gpu_wave<'ctx>(
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(super) fn consume_gpu_wave<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
groups: &[&[Pair]],
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
packets: &mut [ActualSlotPacket<'ctx>],
slots: &mut [Option<usize>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
for (slot, directory) in slots.iter_mut().enumerate() {
let Some(index) = *directory else {
continue;
};
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let owner = cache.ephemeral_routed_owner(binding, context)?;
owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?;
resident_queue::project_group_packets(
context,
binding,
rows,
groups.get(index).ok_or(Error::IdentityMismatch)?,
cache,
prepared,
scope,
origins,
packets,
cancelled,
actual,
Some(slot),
)?;
*directory = None;
}
Ok(())
}
@@ -70,6 +70,8 @@ mod adaptive;
mod impl_preparedmoerow;
#[allow(unused_imports)]
use impl_preparedmoerow::grouped_pairs;
#[path = "moe_group_chunk/bound_rows_fn.rs"]
mod bound_rows_fn;
#[path = "moe_group_chunk/execute_bound_fn.rs"]
mod execute_bound_fn;
#[allow(unused_imports)]
@@ -0,0 +1,252 @@
//! The uploaded rows of one chunk and their ungrouped/grouped execution (STRA-338 size: extract-method only).
#[allow(unused_imports)]
use super::*;
/// The uploaded rows of one chunk: activations and Q8 owners all alive for the whole execution.
pub(super) struct BoundRows<'a, 'ctx> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) rows: &'a [ChunkFfnRow],
pub(super) scope: &'a DownScope<'ctx>,
pub(super) activations: &'a [TransportBuffer<'ctx>],
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
}
impl<'a, 'ctx> BoundRows<'a, 'ctx> {
pub(super) fn execute(
&self,
grouped: bool,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
if !grouped {
return self.execute_ungrouped(
cache,
cancelled,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
}
self.execute_grouped(
cache,
cancelled,
actual,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
)
}
fn execute_ungrouped(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if native.is_some() {
return Err(Error::IdentityMismatch);
}
let rows = self.rows;
let mut outputs = Vec::new();
outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
for i in 0..rows.len() {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
outputs.push(self.ungrouped_row(cache, i)?);
}
Ok(outputs)
}
fn ungrouped_row(&self, cache: &mut MoeWeightCache<'ctx>, i: usize) -> Result<ExpertReady> {
let row = self.rows[i].row();
let values = execute_cuda_cached(
self.context,
self.binding,
&row.weights,
self.activations[i].buffer()?,
&row.route,
cache,
Some(&self.prepared[i]),
)?;
ExpertReady::from_completed(self.binding.identity(), row.route.identity(), values)
}
fn execute_grouped(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
let groups = route_groups(self.rows)?;
let origins = down_origins(self.binding, self.rows)?;
if use_direct_packets(cache) {
return execute_direct_packets(
self.context,
self.binding,
self.rows,
&groups,
cache,
self.prepared,
self.activations,
self.scope,
&origins,
cancelled,
actual.ok_or(Error::IdentityMismatch)?,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
}
self.execute_scalar_down(cache, cancelled, actual, &groups, &origins)
}
fn execute_scalar_down(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
) -> Result<Vec<ExpertReady>> {
let mut down = Vec::new();
down.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
down.resize_with(self.rows.len(), || std::array::from_fn::<_, K, _>(|_| None));
let operation = self.project_and_combine(cache, cancelled, actual, groups, origins, &mut down);
let mut close = Ok(());
for actual in down.into_iter().flatten().flatten() {
let next = actual.output.close();
if close.is_ok() {
close = next;
}
}
operation.and_then(|values| close.map(|()| values))
}
/// Project every expert group (adaptive producer first when selected), then combine row by row.
fn project_and_combine(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut Vec<[Option<ActualDown<'ctx>>; K]>,
) -> Result<Vec<ExpertReady>> {
self.project_groups(cache, cancelled, actual, groups, origins, down)?;
let rows = self.rows;
let mut outputs = Vec::new();
outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
// Sorting compute by expert never changes the original slot 0..9
// order of the exact f64 combine kernel.
for i in 0..rows.len() {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
outputs.push(self.combine_row(cache, i, &mut down[i], &origins[i])?);
}
Ok(outputs)
}
fn project_groups(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
) -> Result<()> {
self.project_adaptive(cache, cancelled, actual, groups, origins, down)?;
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
let adaptive_done = uses_adaptive(cache);
for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive_done) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
project_group(context, binding, rows, pairs, cache, self.prepared, scope, origins, down, cancelled)?;
}
Ok(())
}
/// The adaptive producer runs first when the cache selects it.
#[cfg_attr(
not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")),
allow(unused_variables)
)]
fn project_adaptive(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
) -> Result<()> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.uses_strata_adaptive_experts() {
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
let prepared = self.prepared;
adaptive::project_adaptive_groups(
context, binding, rows, groups, cache, prepared, scope, origins, down, cancelled, actual,
)?;
}
Ok(())
}
fn combine_row(
&self,
cache: &mut MoeWeightCache<'ctx>,
i: usize,
down_row: &mut [Option<ActualDown<'ctx>>; K],
origin: &Rc<DownOrigin>,
) -> Result<ExpertReady> {
let (context, binding, scope) = (self.context, self.binding, self.scope);
let row = self.rows[i].row();
let mut packed = PackedDown::new(scope)?;
let output = (|| {
for (slot, cell) in down_row.iter_mut().enumerate() {
let actual = cell.take().ok_or(Error::IdentityMismatch)?;
packed.pack(
scope,
actual.take(origin, binding, row.route.identity(), MoeExpertSelection::Routed { slot })?,
)?;
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
packed.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?;
finish_shared(context, binding, row, self.activations[i].buffer()?, cache, scope, origin, &packed)
})();
let close = packed.close();
let values = output?;
close?;
ExpertReady::from_completed(binding.identity(), row.route.identity(), values)
}
}
/// The expert groups of the chunk rows, in ascending expert order.
fn route_groups(rows: &[ChunkFfnRow]) -> Result<Vec<Vec<Pair>>> {
let mut ids = Vec::new();
ids.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
for row in rows {
ids.push(std::array::from_fn(|i| row.row().route.experts()[i].get()));
}
grouped_pairs(&ids)
}
fn down_origins(binding: &ModelBinding, rows: &[ChunkFfnRow]) -> Result<Vec<Rc<DownOrigin>>> {
let mut origins = Vec::new();
origins.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
for row in rows {
origins.push(Rc::new(DownOrigin { binding: binding.identity(), identity: row.row().route.identity() }));
}
Ok(origins)
}
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: fn execute_bound.
use super::bound_rows_fn::BoundRows;
#[allow(unused_imports)]
use super::*;
@@ -14,33 +15,15 @@ pub(super) fn execute_bound<'ctx>(
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
// The same binding/pointer validation returns the stable actor Context.
// This keeps a finite-guard loan independent of the immutable matrix loan.
let context = cache.mmq_context(binding, context)?;
let extended_group = is_extended_group(cache, rows)?;
reserve_and_admit(binding, rows, cache, context, extended_group)?;
let grouped = grouped_mode(cache, rows, extended_group)?;
let failed = Rc::new(Cell::new(false));
let scope = down_scope(binding, cache, context, &failed)?;
let mut activations = Vec::new();
activations.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
let mut prepared = Vec::new();
prepared.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
let mut admission = upload_activations(rows, &scope, cancelled, &mut activations);
if admission.is_ok() {
admission = prepare_owners(context, cancelled, &activations, &mut prepared);
}
let (grouped, scope, failed) = open_bound(binding, rows, cache, context)?;
let (mut activations, mut prepared) = (reserved(rows.len())?, reserved(rows.len())?);
let admission = upload_activations(rows, &scope, cancelled, &mut activations)
.and_then(|()| prepare_owners(context, cancelled, &activations, &mut prepared));
let result = admission.and_then(|()| {
let bound = BoundRows { context, binding, rows, scope: &scope, activations: &activations, prepared: &prepared };
if !grouped {
return bound.execute_ungrouped(
cache,
cancelled,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
}
bound.execute_grouped(
bound.execute(
grouped,
cache,
cancelled,
actual,
@@ -49,11 +32,34 @@ pub(super) fn execute_bound<'ctx>(
)
});
scope.record(&result);
let mut cleanup = close_prepared(prepared);
let activations_closed = close_activations(activations);
if cleanup.is_ok() {
cleanup = activations_closed;
}
finish_bound(&failed, cache, result, close_prepared(prepared), activations)
}
/// The same binding/pointer validation returns the stable actor Context. This keeps a finite-guard loan
/// independent of the immutable matrix loan. Admission, grouping mode and the Down scope follow in order.
fn open_bound<'ctx>(
binding: &ModelBinding,
rows: &[ChunkFfnRow],
cache: &mut MoeWeightCache<'ctx>,
context: &'ctx Context<'ctx>,
) -> Result<(bool, DownScope<'ctx>, Rc<Cell<bool>>)> {
let extended_group = is_extended_group(cache, rows)?;
reserve_and_admit(binding, rows, cache, context, extended_group)?;
let grouped = grouped_mode(cache, rows, extended_group)?;
let failed = Rc::new(Cell::new(false));
let scope = down_scope(binding, cache, context, &failed)?;
Ok((grouped, scope, failed))
}
/// Close the activations after the Q8 owners; any failure marks the transport as failed.
fn finish_bound(
failed: &Rc<Cell<bool>>,
cache: &mut MoeWeightCache<'_>,
result: Result<Vec<ExpertReady>>,
prepared_closed: Result<()>,
activations: Vec<TransportBuffer<'_>>,
) -> Result<Vec<ExpertReady>> {
let cleanup = prepared_closed.and(close_activations(activations));
if failed.get() || cleanup.is_err() {
cache.note_transport_failure();
}
@@ -149,6 +155,12 @@ fn down_scope<'ctx>(
})
}
fn reserved<T>(count: usize) -> Result<Vec<T>> {
let mut items = Vec::new();
items.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?;
Ok(items)
}
fn upload_activations<'ctx>(
rows: &[ChunkFfnRow],
scope: &DownScope<'ctx>,
@@ -206,192 +218,3 @@ fn close_activations(activations: Vec<TransportBuffer<'_>>) -> Result<()> {
}
cleanup
}
/// The uploaded rows of one chunk: activations and Q8 owners all alive for the whole execution.
struct BoundRows<'a, 'ctx> {
context: &'ctx Context<'ctx>,
binding: &'a ModelBinding,
rows: &'a [ChunkFfnRow],
scope: &'a DownScope<'ctx>,
activations: &'a [TransportBuffer<'ctx>],
prepared: &'a [RoutedGateUpQ8<'a>],
}
impl<'a, 'ctx> BoundRows<'a, 'ctx> {
fn execute_ungrouped(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if native.is_some() {
return Err(Error::IdentityMismatch);
}
let rows = self.rows;
let mut outputs = Vec::new();
outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
for i in 0..rows.len() {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
outputs.push(self.ungrouped_row(cache, i)?);
}
Ok(outputs)
}
fn ungrouped_row(&self, cache: &mut MoeWeightCache<'ctx>, i: usize) -> Result<ExpertReady> {
let row = self.rows[i].row();
let values = execute_cuda_cached(
self.context,
self.binding,
&row.weights,
self.activations[i].buffer()?,
&row.route,
cache,
Some(&self.prepared[i]),
)?;
ExpertReady::from_completed(self.binding.identity(), row.route.identity(), values)
}
fn execute_grouped(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
let (binding, rows) = (self.binding, self.rows);
let mut ids = Vec::new();
ids.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
for row in rows {
ids.push(std::array::from_fn(|i| row.row().route.experts()[i].get()));
}
let groups = grouped_pairs(&ids)?;
let mut origins = Vec::new();
origins.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
for row in rows {
origins.push(Rc::new(DownOrigin { binding: binding.identity(), identity: row.row().route.identity() }));
}
if use_direct_packets(cache) {
return execute_direct_packets(
self.context,
binding,
rows,
&groups,
cache,
self.prepared,
self.activations,
self.scope,
&origins,
cancelled,
actual.ok_or(Error::IdentityMismatch)?,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
}
self.execute_scalar_down(cache, cancelled, actual, &groups, &origins)
}
fn execute_scalar_down(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
) -> Result<Vec<ExpertReady>> {
let mut down = Vec::new();
down.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
down.resize_with(self.rows.len(), || std::array::from_fn::<_, K, _>(|_| None));
let operation = self.project_and_combine(cache, cancelled, actual, groups, origins, &mut down);
let mut close = Ok(());
for actual in down.into_iter().flatten().flatten() {
let next = actual.output.close();
if close.is_ok() {
close = next;
}
}
operation.and_then(|values| close.map(|()| values))
}
fn project_and_combine(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut Vec<[Option<ActualDown<'ctx>>; K]>,
) -> Result<Vec<ExpertReady>> {
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.uses_strata_adaptive_experts() {
adaptive::project_adaptive_groups(
context,
binding,
rows,
groups,
cache,
self.prepared,
scope,
origins,
down,
cancelled,
actual,
)?;
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
let _ = actual;
let adaptive_done = uses_adaptive(cache);
for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive_done) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
project_group(context, binding, rows, pairs, cache, self.prepared, scope, origins, down, cancelled)?;
}
let mut outputs = Vec::new();
outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
// Sorting compute by expert never changes the original slot 0..9
// order of the exact f64 combine kernel.
for i in 0..rows.len() {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
outputs.push(self.combine_row(cache, i, &mut down[i], &origins[i])?);
}
Ok(outputs)
}
fn combine_row(
&self,
cache: &mut MoeWeightCache<'ctx>,
i: usize,
down_row: &mut [Option<ActualDown<'ctx>>; K],
origin: &Rc<DownOrigin>,
) -> Result<ExpertReady> {
let (context, binding, scope) = (self.context, self.binding, self.scope);
let row = self.rows[i].row();
let mut packed = PackedDown::new(scope)?;
let output = (|| {
for (slot, cell) in down_row.iter_mut().enumerate() {
let actual = cell.take().ok_or(Error::IdentityMismatch)?;
packed.pack(
scope,
actual.take(origin, binding, row.route.identity(), MoeExpertSelection::Routed { slot })?,
)?;
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
packed.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?;
finish_shared(context, binding, row, self.activations[i].buffer()?, cache, scope, origin, &packed)
})();
let close = packed.close();
let values = output?;
close?;
ExpertReady::from_completed(binding.identity(), row.route.identity(), values)
}
}
@@ -15,6 +15,7 @@ mod kv_only;
#[path = "mtp_state.rs"]
mod state;
pub(super) use kv_only::produce_chunk_kv_only;
pub(in crate::qwen_forward) use state::MtpCheckpoint;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) use state::MtpChunkNumericSnapshot;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
mod batched_support;
mod impl_mtpdecoder_2;
mod impl_mtpdecoder_2_2;
mod impl_mtpdecoder_3;
@@ -0,0 +1,138 @@
//! Plan, context and state of one batched MTP window (STRA-338 size: extract-method only).
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::mtp::MtpCheckpoint;
pub(super) type WindowResult<T> = std::result::Result<T, MtpWindowError>;
pub(super) type FirstSeed = Option<(MtpCheckpoint, mtp::MtpFrame)>;
/// The sizing of one batched window, fixed before any draft or canonical mutation.
pub(super) struct BatchedPlan {
pub(super) first: TokenId,
pub(super) limit: usize,
pub(super) reuse_first_seed: bool,
pub(super) seed_host_charge: usize,
pub(super) host_remaining: usize,
pub(super) capacity: usize,
}
impl BatchedPlan {
/// The frame of the first draft step when first-seed reuse is selected.
pub(super) fn seed_frame(&self, first_step: bool, input: &MtpInput) -> Option<mtp::MtpFrame> {
(self.reuse_first_seed && first_step).then(|| input.frame().clone())
}
}
/// The immutable inputs of one batched window.
pub(super) struct BatchedCtx<'a, 'c, 'd, 'x> {
pub(super) binding: &'a ModelBinding,
pub(super) source: &'a TargetStepProduct,
pub(super) output: &'a OutputStage<'c, 'd>,
pub(super) dense_cache: &'a DenseWeightCache<'x>,
pub(super) eos: Option<TokenId>,
pub(super) remaining: usize,
pub(super) plan: BatchedPlan,
}
impl<'a, 'c, 'd, 'x> BatchedCtx<'a, 'c, 'd, 'x> {
pub(super) fn new(
binding: &'a ModelBinding,
source: &'a TargetStepProduct,
output: &'a OutputStage<'c, 'd>,
dense_cache: &'a DenseWeightCache<'x>,
spec: &MtpWindowSpec,
plan: BatchedPlan,
) -> Self {
Self { binding, source, output, dense_cache, eos: spec.eos, remaining: spec.remaining, plan }
}
pub(super) fn check_accepted(&self, accepted: usize, rows: usize) -> WindowResult<()> {
if accepted == 0 || accepted > rows || accepted > self.plan.capacity || accepted > self.remaining {
return Err(Error::IdentityMismatch.into());
}
Ok(())
}
}
/// The mutable draft checkpoints, candidates and accepted tokens of one batched window.
pub(super) struct BatchedState {
pub(super) draft_priors: Vec<MtpCheckpoint>,
pub(super) candidates: Vec<TokenId>,
pub(super) tokens: Vec<TokenId>,
}
/// `Some(eos)` when the window is trivially empty: nothing remains, or the authoritative prediction is EOS.
pub(super) fn trivial_window(spec: &MtpWindowSpec, first: TokenId) -> Option<bool> {
(spec.remaining == 0 || Some(first) == spec.eos).then(|| spec.remaining != 0 && Some(first) == spec.eos)
}
/// Independent actual CPU wave and ephemeral staging coexist. Both are inside the unchanged 512MiB request
/// admission.
pub(super) fn capacity_budget(cache: &MoeWeightCache<'_>, host_remaining: usize) -> Result<usize> {
if cache.uses_strata_adaptive_experts() {
host_remaining.checked_sub((48 + 16) * 1024 * 1024).ok_or(Error::InputAllocation)
} else {
Ok(host_remaining)
}
}
/// A closure that forwards the cancellation probe and remembers whether it ever fired.
pub(super) fn observe_cancel<'a>(
cancelled: &'a mut impl FnMut() -> bool,
fired: &'a mut bool,
) -> impl FnMut() -> bool + 'a {
move || {
let current = cancelled();
*fired |= current;
current
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) fn poll_before_window(binding: &ModelBinding, cache: &mut MoeWeightCache<'_>) -> Result<()> {
if cache.uses_strata_adaptive_experts() {
cache.poll_strata_adaptive(binding, true)?;
}
Ok(())
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
pub(super) fn poll_before_window(_binding: &ModelBinding, _cache: &mut MoeWeightCache<'_>) -> Result<()> {
Ok(())
}
/// Adaptive completion polls, the joint-publish test hook and the final cancellation check.
pub(super) fn batched_after_publish(
binding: &ModelBinding,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
) -> WindowResult<()> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.uses_strata_adaptive_experts() {
cache.poll_strata_adaptive(binding, false)?;
cache.strata_adaptive_completed_window(binding)?;
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
let _ = (binding, &cache);
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
batch_gpu::after_joint_publish();
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
Ok(())
}
/// The last candidate to extend the draft chain from; `None` when it is the EOS token.
pub(super) fn next_candidate(
st: &BatchedState,
eos: Option<TokenId>,
cancelled: &mut impl FnMut() -> bool,
) -> WindowResult<Option<TokenId>> {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let candidate = *st.candidates.last().ok_or(Error::IdentityMismatch)?;
Ok((Some(candidate) != eos).then_some(candidate))
}
@@ -23,11 +23,7 @@ impl MtpDecoder {
if host_charge > 512 * 1024 * 1024 {
return Err(Error::InputAllocation);
}
let vocabulary = Dimension::new(248320)?;
let mut tokens = reserve(prompt.len())?;
for &token in prompt {
tokens.push(TokenId::new(u64::from(token), vocabulary)?);
}
let tokens = prompt_tokens(prompt)?;
decoder.kv_prefill = Some(mtp::MtpKvPrefill::new(binding, target, &decoder.draft, &tokens)?);
decoder.kv_prefill_host_charge = host_charge;
Ok(decoder)
@@ -185,3 +181,12 @@ impl MtpDecoder {
}
}
}
fn prompt_tokens(prompt: &[u32]) -> Result<Vec<TokenId>> {
let vocabulary = Dimension::new(248320)?;
let mut tokens = reserve(prompt.len())?;
for &token in prompt {
tokens.push(TokenId::new(u64::from(token), vocabulary)?);
}
Ok(tokens)
}
@@ -3,6 +3,9 @@
#[allow(unused_imports)]
use super::*;
use super::batched_support::*;
use crate::qwen_forward::mtp::MtpCheckpoint;
impl MtpDecoder {
/// Selected only by the existing explicit IQ3 integer/native Down policy.
/// Draft depth remains configured; target batch capacity is separately
@@ -19,25 +22,61 @@ impl MtpDecoder {
dense_cache: &DenseWeightCache<'_>,
spec: MtpWindowSpec,
mut cancelled: impl FnMut() -> bool,
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
) -> WindowResult<MtpVerifiedWindow> {
let plan = match self.batched_plan(binding, &source, target, cache, &spec, &mut cancelled)? {
Ok(plan) => plan,
Err(eos) => return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos, draft_steps: 0 }),
};
let (target_prior, mut st) = (target.checkpoint()?, self.batched_state(&plan)?);
let cx = BatchedCtx::new(binding, &source, output, dense_cache, &spec, plan);
match self.batched_body(&cx, target, &mut kar_cache, cache, &mut cancelled, &mut st) {
Ok((latest, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens: st.tokens, latest, eos, draft_steps }),
Err(error) => Err(self.batched_rollback(target, &st, error, |t| t.restore_checkpoint(&target_prior))),
}
}
/// Validate the source and size the window. `Err(eos)` is a trivially empty window.
fn batched_plan(
&self,
binding: &ModelBinding,
source: &TargetStepProduct,
target: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
spec: &MtpWindowSpec,
cancelled: &mut impl FnMut() -> bool,
) -> WindowResult<std::result::Result<BatchedPlan, bool>> {
source.mtp_source(binding, target)?;
let first = source.predicted(target)?;
let source_position = source.position(target)?.get();
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
if spec.remaining == 0 || Some(first) == spec.eos {
return Ok(MtpVerifiedWindow {
tokens: Vec::new(),
latest: source,
eos: spec.remaining != 0 && Some(first) == spec.eos,
draft_steps: 0,
});
}
if self.kv_prefill.is_some() || !cache.requires_iq3_mmq_admission() {
return Err(Error::IdentityMismatch.into());
if let Some(eos) = trivial_window(spec, first) {
return Ok(Err(eos));
}
self.require_batched_admission(cache)?;
let limit = window_limit(source_position, spec.depth, spec.remaining)?;
Ok(Ok(self.batched_sizing(binding, source, target, cache, spec.eos, first, limit)?))
}
fn require_batched_admission(&self, cache: &MoeWeightCache<'_>) -> Result<()> {
if self.kv_prefill.is_some() || !cache.requires_iq3_mmq_admission() {
return Err(Error::IdentityMismatch);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn batched_sizing(
&self,
binding: &ModelBinding,
source: &TargetStepProduct,
target: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
eos: Option<TokenId>,
first: TokenId,
limit: usize,
) -> Result<BatchedPlan> {
let reuse_first_seed = limit > 1 && first_seed_reuse_enabled(cache);
let seed_host_charge = if reuse_first_seed { self.draft.first_seed_host_charge()? } else { 0 };
let host_remaining = self.prefill_host_remaining(512 * 1024 * 1024)?;
@@ -47,167 +86,188 @@ impl MtpDecoder {
host_remaining
};
// Pure complete-state admission before any draft/canonical mutation.
let capacity = QwenForward::mtp_target_window_capacity(
binding,
&source,
spec.eos,
target,
limit,
if cache.uses_strata_adaptive_experts() {
// Independent actual CPU wave and ephemeral staging coexist.
// Both are inside the unchanged 512MiB request admission.
host_remaining.checked_sub((48 + 16) * 1024 * 1024).ok_or(Error::InputAllocation)?
} else {
host_remaining
},
)?;
let target_prior = target.checkpoint()?;
let budget = capacity_budget(cache, host_remaining)?;
let capacity = QwenForward::mtp_target_window_capacity(binding, source, eos, target, limit, budget)?;
Ok(BatchedPlan { first, limit, reuse_first_seed, seed_host_charge, host_remaining, capacity })
}
fn batched_state(&mut self, plan: &BatchedPlan) -> Result<BatchedState> {
let mut draft_priors = reserve(1)?;
draft_priors.push(self.draft.checkpoint()?);
let mut candidates = reserve(limit + 1)?;
candidates.push(first);
let mut tokens = reserve(capacity)?;
let result = (|| {
let mut previous = None;
let mut first_seed = None;
let needed_predictions = needed_draft_predictions(capacity, limit)?;
for _ in 0..needed_predictions {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let candidate = *candidates.last().ok_or(Error::IdentityMismatch)?;
if Some(candidate) == spec.eos {
break;
}
let input = match previous.as_ref() {
Some(product) => MtpInput::from_previous(binding, target, &self.draft, product, cache)?,
None => MtpInput::from_target(binding, target, &self.draft, &source, candidate, cache)?,
};
let seed_frame =
if reuse_first_seed && previous.is_none() { Some(input.frame().clone()) } else { None };
let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?;
if let Some(frame) = seed_frame {
first_seed = Some((self.draft.checkpoint_first_seed(seed_host_charge)?, frame));
}
candidates.push(product.predicted(binding, target)?);
previous = Some(product);
}
drop(previous);
let draft_steps = candidates.len().checked_sub(1).ok_or(Error::Overflow)?;
if let Some((seed, frame)) = first_seed {
// Recheck the authoritative target source before coupled restore.
source.mtp_source(binding, target)?;
if source.predicted(target)? != frame.token() || source.position(target)? != frame.position() {
return Err(Error::IdentityMismatch.into());
}
self.draft.restore_first_seed(binding, target, &frame, &seed, &mut draft_priors[0])?;
// The seed is now the actual committed draft; dropping its extra
// checkpoint precedes target journal/catchup allocation.
} else {
self.draft.restore(&draft_priors[0])?;
draft_priors.clear();
// The old speculative epoch is unusable after rewind. Failure
// rollback retains only this new checkpoint; no nested warm rewind.
draft_priors.push(self.draft.checkpoint()?);
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let input = MtpInput::from_target(binding, target, &self.draft, &source, first, cache)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)?;
}
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let rows = capacity.min(limit).min(candidates.len());
let mut stage_cancelled = false;
// Complete the previous refill after genuine draft compute but before
// target window journal allocation, preserving the shared host cap.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.uses_strata_adaptive_experts() {
cache.poll_strata_adaptive(binding, true)?;
}
let pending_result = {
let mut observe_cancel = || {
let current = cancelled();
stage_cancelled |= current;
current
};
QwenForward::prepare_mtp_target_window(
binding,
&source,
&candidates[..rows],
spec.eos,
target,
output,
kar_cache.as_deref_mut(),
cache,
dense_cache,
host_remaining,
&mut observe_cancel,
)
let mut candidates = reserve(plan.limit + 1)?;
candidates.push(plan.first);
let tokens = reserve(plan.capacity)?;
Ok(BatchedState { draft_priors, candidates, tokens })
}
/// Draft chain, rewind (first-seed restore or fresh warm), then the joint target window.
fn batched_body<'driver>(
&mut self,
cx: &BatchedCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'driver>,
kar_cache: &mut Option<&mut KarPleCache<'_>>,
cache: &mut MoeWeightCache<'driver>,
cancelled: &mut impl FnMut() -> bool,
st: &mut BatchedState,
) -> WindowResult<(TargetStepProduct, bool, usize)> {
let (first_seed, draft_steps) = self.batched_draft_chain(cx, target, cache, cancelled, st)?;
self.batched_rewind(cx, target, cache, cancelled, st, first_seed)?;
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let product = self.batched_window(cx, target, kar_cache, cache, cancelled, st)?;
batched_after_publish(cx.binding, cache, cancelled)?;
let eos = Some(product.predicted(target)?) == cx.eos;
Ok((product, eos, draft_steps))
}
fn batched_draft_chain(
&mut self,
cx: &BatchedCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'_>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &mut BatchedState,
) -> WindowResult<(FirstSeed, usize)> {
let (binding, plan) = (cx.binding, &cx.plan);
let mut previous = None;
let mut first_seed = None;
for _ in 0..needed_draft_predictions(plan.capacity, plan.limit)? {
let Some(candidate) = next_candidate(st, cx.eos, cancelled)? else {
break;
};
let pending = pending_result.map_err(|error| window_stage_error(error, stage_cancelled))?;
let accepted = pending.accepted_rows();
if accepted == 0 || accepted > rows || accepted > capacity || accepted > spec.remaining {
return Err(Error::IdentityMismatch.into());
}
// Capacity was reserved before work; accepted IDs/counters are
// assembled before either owner commits. They stay private on error.
tokens.extend_from_slice(&candidates[..accepted]);
let mut stage_cancelled = false;
let published = {
let mut observe_cancel = || {
let current = cancelled();
stage_cancelled |= current;
current
};
pending.publish_joint_with_gdn_replay(
binding,
&mut self.draft,
cache,
Some(dense_cache),
&mut observe_cancel,
)
};
let product = published.map_err(|error| window_stage_error(error, stage_cancelled))?;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.uses_strata_adaptive_experts() {
cache.poll_strata_adaptive(binding, false)?;
cache.strata_adaptive_completed_window(binding)?;
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
batch_gpu::after_joint_publish();
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let eos = Some(product.predicted(target)?) == spec.eos;
Ok((product, eos, draft_steps))
})();
match result {
Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens, latest: product, eos, draft_steps }),
Err(error) => {
if let MtpWindowError::Forward(cause) = error {
target.note_mtp_failure(&cause);
}
// Attempt BOTH full restores even when the first is refused by
// poison. Retain the primary error; never return private IDs.
let target_restore = target.restore_checkpoint(&target_prior);
let draft_restore = match draft_priors.first() {
Some(prior) => self.draft.restore(prior),
None => Ok(()), // remint failed before actual catchup
};
if let Err(cause) = target_restore {
target.note_mtp_failure(&cause);
}
#[cfg(test)]
if target_restore.is_err() || draft_restore.is_err() {
eprintln!(
"MTP candidate rollback primary={error:?} target={target_restore:?} draft={draft_restore:?}"
);
}
let _ = draft_restore;
Err(error)
}
let input = self.batched_chain_input(cx, target, cache, previous.as_ref(), candidate)?;
let seed_frame = plan.seed_frame(previous.is_none(), &input);
let product = mtp::step(binding, target, &mut self.draft, input, cx.output, cache)?;
first_seed = self.capture_seed(plan, seed_frame)?.or(first_seed);
st.candidates.push(product.predicted(binding, target)?);
previous = Some(product);
}
Ok((first_seed, st.candidates.len().checked_sub(1).ok_or(Error::Overflow)?))
}
/// Retain the first-seed checkpoint beside its frame when the first draft step asked for reuse.
fn capture_seed(&self, plan: &BatchedPlan, frame: Option<mtp::MtpFrame>) -> Result<FirstSeed> {
frame.map(|frame| Ok((self.draft.checkpoint_first_seed(plan.seed_host_charge)?, frame))).transpose()
}
fn batched_chain_input(
&self,
cx: &BatchedCtx<'_, '_, '_, '_>,
target: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
previous: Option<&mtp::MtpStepProduct>,
candidate: TokenId,
) -> Result<MtpInput> {
match previous {
Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache),
None => MtpInput::from_target(cx.binding, target, &self.draft, cx.source, candidate, cache),
}
}
/// Recheck the authoritative target source before coupled restore. The seed is now the actual committed draft;
/// dropping its extra checkpoint precedes target journal/catchup allocation.
fn batched_restore_seed(
&mut self,
cx: &BatchedCtx<'_, '_, '_, '_>,
target: &QwenSession<'_>,
st: &mut BatchedState,
seed: &MtpCheckpoint,
frame: &mtp::MtpFrame,
) -> WindowResult<()> {
let (binding, source) = (cx.binding, cx.source);
source.mtp_source(binding, target)?;
if source.predicted(target)? != frame.token() || source.position(target)? != frame.position() {
return Err(Error::IdentityMismatch.into());
}
self.draft.restore_first_seed(binding, target, frame, seed, &mut st.draft_priors[0])?;
Ok(())
}
/// Rewind the transient draft chain: restore the retained first seed, or restore, remint and re-warm.
fn batched_rewind(
&mut self,
cx: &BatchedCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'_>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &mut BatchedState,
first_seed: FirstSeed,
) -> WindowResult<()> {
let (binding, source) = (cx.binding, cx.source);
if let Some((seed, frame)) = first_seed {
return self.batched_restore_seed(cx, target, st, &seed, &frame);
}
self.draft.restore(&st.draft_priors[0])?;
st.draft_priors.clear();
// The old speculative epoch is unusable after rewind. Failure
// rollback retains only this new checkpoint; no nested warm rewind.
st.draft_priors.push(self.draft.checkpoint()?);
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let input = MtpInput::from_target(binding, target, &self.draft, source, cx.plan.first, cache)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)?;
Ok(())
}
/// Prepare the joint target window over the accepted candidate prefix, then publish it. Capacity was reserved
/// before work; accepted IDs/counters are assembled before either owner commits and stay private on error. The
/// previous refill completes after genuine draft compute but before target window journal allocation,
/// preserving the shared host cap.
fn batched_window<'driver>(
&mut self,
cx: &BatchedCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'driver>,
kar_cache: &mut Option<&mut KarPleCache<'_>>,
cache: &mut MoeWeightCache<'driver>,
cancelled: &mut impl FnMut() -> bool,
st: &mut BatchedState,
) -> WindowResult<TargetStepProduct> {
let (binding, plan) = (cx.binding, &cx.plan);
let rows = plan.capacity.min(plan.limit).min(st.candidates.len());
poll_before_window(binding, cache)?;
let mut fired = false;
let (source, eos, output, dense) = (cx.source, cx.eos, cx.output, cx.dense_cache);
let (kar, proposals, host) = (kar_cache.as_deref_mut(), &st.candidates[..rows], plan.host_remaining);
let observer = observe_cancel(cancelled, &mut fired);
let prepared = QwenForward::prepare_mtp_target_window(
binding, source, proposals, eos, target, output, kar, cache, dense, host, observer,
);
let pending = prepared.map_err(|error| window_stage_error(error, fired))?;
cx.check_accepted(pending.accepted_rows(), rows)?;
st.tokens.extend_from_slice(&st.candidates[..pending.accepted_rows()]);
let mut fired = false;
let observer = observe_cancel(cancelled, &mut fired);
let published = pending.publish_joint_with_gdn_replay(binding, &mut self.draft, cache, Some(dense), observer);
published.map_err(|error| window_stage_error(error, fired))
}
/// Attempt BOTH full restores even when the first is refused by poison. Retain the primary error; never
/// return private IDs. The target closure restores the target checkpoint.
fn batched_rollback<'driver>(
&mut self,
target: &mut QwenSession<'driver>,
st: &BatchedState,
error: MtpWindowError,
restore_target: impl FnOnce(&mut QwenSession<'driver>) -> Result<()>,
) -> MtpWindowError {
if let MtpWindowError::Forward(cause) = error {
target.note_mtp_failure(&cause);
}
let target_restore = restore_target(target);
let draft_restore = match st.draft_priors.first() {
Some(prior) => self.draft.restore(prior),
None => Ok(()), // remint failed before actual catchup
};
if let Err(cause) = target_restore {
target.note_mtp_failure(&cause);
}
#[cfg(test)]
if target_restore.is_err() || draft_restore.is_err() {
eprintln!("MTP candidate rollback primary={error:?} target={target_restore:?} draft={draft_restore:?}");
}
let _ = draft_restore;
error
}
}
@@ -3,6 +3,75 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::mtp::MtpCheckpoint;
type WindowResult<T> = std::result::Result<T, MtpWindowError>;
/// The immutable inputs of one scalar window.
struct ScalarCtx<'a, 'c, 'd, 'x> {
binding: &'a ModelBinding,
output: &'a OutputStage<'c, 'd>,
dense_cache: &'a DenseWeightCache<'x>,
eos: Option<TokenId>,
limit: usize,
source_position: u64,
first: TokenId,
}
impl ScalarCtx<'_, '_, '_, '_> {
/// The target position of the next verified token: source + 1 + tokens verified so far.
fn next_position(&self, verified: usize) -> Result<u64> {
let offset = u64::try_from(verified).map_err(|_| Error::Overflow)?;
self.source_position.checked_add(1).and_then(|p| p.checked_add(offset)).ok_or(Error::Overflow)
}
}
/// The mutable candidate, token and product state of one scalar window.
struct ScalarState {
draft_priors: Vec<MtpCheckpoint>,
candidates: Vec<TokenId>,
tokens: Vec<TokenId>,
latest: Option<TargetStepProduct>,
}
/// Validate the source and size the window. `Err(eos)` is a trivially empty window (nothing remaining, or the
/// authoritative prediction is already EOS).
fn scalar_start(
binding: &ModelBinding,
source: &TargetStepProduct,
target: &QwenSession<'_>,
spec: &MtpWindowSpec,
cancelled: &mut impl FnMut() -> bool,
) -> WindowResult<std::result::Result<(TokenId, u64, usize), bool>> {
source.mtp_source(binding, target)?;
let first = source.predicted(target)?;
let source_position = source.position(target)?.get();
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
if spec.remaining == 0 {
return Ok(Err(false));
}
if Some(first) == spec.eos {
return Ok(Err(true));
}
let limit = window_limit(source_position, spec.depth, spec.remaining)?;
Ok(Ok((first, source_position, limit)))
}
fn verified_window(
tokens: Vec<TokenId>,
latest: TargetStepProduct,
eos: bool,
draft_steps: usize,
) -> MtpVerifiedWindow {
MtpVerifiedWindow { tokens, latest, eos, draft_steps }
}
fn empty_window(latest: TargetStepProduct, eos: bool) -> MtpVerifiedWindow {
MtpVerifiedWindow { tokens: Vec::new(), latest, eos, draft_steps: 0 }
}
impl MtpDecoder {
#[allow(clippy::too_many_arguments)]
pub(crate) fn window_scalar(
@@ -16,145 +85,212 @@ impl MtpDecoder {
dense_cache: &DenseWeightCache<'_>,
spec: MtpWindowSpec,
mut cancelled: impl FnMut() -> bool,
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
source.mtp_source(binding, target)?;
let first = source.predicted(target)?;
let source_position = source.position(target)?.get();
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
if spec.remaining == 0 {
return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos: false, draft_steps: 0 });
}
if Some(first) == spec.eos {
return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos: true, draft_steps: 0 });
}
let limit = window_limit(source_position, spec.depth, spec.remaining)?;
let target_prior = target.checkpoint()?;
let mut draft_priors = reserve(1)?;
draft_priors.push(self.draft.checkpoint()?);
let mut candidates = reserve(limit + 1)?;
candidates.push(first);
let mut tokens = reserve(limit)?;
let mut latest = Some(source);
let result = (|| {
let mut previous = None;
// All draft work is anchored to the original current target prefix.
// No source/product accessor from that prefix is used after target advance.
for _ in 0..limit {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let candidate = *candidates.last().ok_or(Error::IdentityMismatch)?;
if Some(candidate) == spec.eos {
break;
}
let input = match previous.as_ref() {
Some(product) => MtpInput::from_previous(binding, target, &self.draft, product, cache)?,
None => MtpInput::from_target(
binding,
target,
&self.draft,
latest.as_ref().ok_or(Error::IdentityMismatch)?,
candidate,
cache,
)?,
};
let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?;
candidates.push(product.predicted(binding, target)?);
previous = Some(product);
}
drop(previous);
let draft_steps = candidates.len() - 1;
// A matching token does not make its speculative residual/KV the
// actual target residual/KV. Discard the entire transient chain.
self.draft.restore(&draft_priors[0])?;
draft_priors.clear();
// Rewind increments the draft epoch. The old checkpoint must never
// be used by failure rollback after real catch-up starts. If minting
// fails, the draft is already initial and no catch-up has occurred.
draft_priors.push(self.draft.checkpoint()?);
let mut expected = first;
let mut eos = false;
for candidate in candidates.iter().take(limit) {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
// The authoritative target prediction controls both acceptance
// and EOS. A draft-only EOS cannot end a target generation.
if Some(expected) == spec.eos {
eos = true;
break;
}
if *candidate != expected {
break;
}
let offset = u64::try_from(tokens.len()).map_err(|_| Error::Overflow)?;
let position =
source_position.checked_add(1).and_then(|p| p.checked_add(offset)).ok_or(Error::Overflow)?;
// Rebuild persistent cell i from CURRENT actual target R_i and
// verified token i+1 before target advancement invalidates R_i.
// Do not call warm(): its nested rewind would invalidate this
// window's fresh-epoch rollback checkpoint on failure.
let input = MtpInput::from_target(
binding,
target,
&self.draft,
latest.as_ref().ok_or(Error::IdentityMismatch)?,
expected,
cache,
)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)?;
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let product = QwenForward::step_for_mtp_cached(
binding,
expected,
Position::new(position, crate::qwen_forward::contract::position_dimension())?,
target,
output,
kar_cache.as_deref_mut(),
Some(cache),
Some(dense_cache),
)?;
// Read the new prediction while this product is still current.
expected = product.predicted(target)?;
latest = Some(product);
tokens.push(*candidate);
}
if Some(expected) == spec.eos {
eos = true;
}
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let product = latest.take().ok_or(Error::IdentityMismatch)?;
// Exactly k real catch-up cells precede the current target product
// at p+k. Leave that final cell for the next window; neither rejected
// cells nor any speculative residual survive into its prefix.
Ok((product, eos, draft_steps))
})();
match result {
Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens, latest: product, eos, draft_steps }),
) -> WindowResult<MtpVerifiedWindow> {
let (first, source_position, limit) = match scalar_start(binding, &source, target, &spec, &mut cancelled)? {
Ok(start) => start,
Err(eos) => return Ok(empty_window(source, eos)),
};
let (target_prior, mut state) = (target.checkpoint()?, self.scalar_state(first, source, limit)?);
let cx = ScalarCtx { binding, output, dense_cache, eos: spec.eos, limit, source_position, first };
match self.scalar_body(&cx, target, &mut kar_cache, cache, &mut cancelled, &mut state) {
Ok((product, eos, draft_steps)) => Ok(verified_window(state.tokens, product, eos, draft_steps)),
Err(error) => {
if let MtpWindowError::Forward(cause) = error {
target.note_mtp_failure(&cause);
}
// Attempt both restores even when sticky CUDA failure prevents
// target restoration. Never return any tokens from this branch.
let target_restore = target.restore_checkpoint(&target_prior);
let draft_restore = match draft_priors.first() {
Some(prior) => self.draft.restore(prior),
// Only reachable if remint failed immediately after rewind:
// no old-epoch access and the draft is already initial.
None => Ok(()),
let restore = |cause: Option<Error>| {
cause.inspect(|cause| target.note_mtp_failure(cause));
target.restore_checkpoint(&target_prior)
};
target_restore?;
draft_restore?;
self.scalar_rollback(&state, error, restore)?;
Err(error)
}
}
}
fn scalar_state(&mut self, first: TokenId, source: TargetStepProduct, limit: usize) -> Result<ScalarState> {
let mut draft_priors = reserve(1)?;
draft_priors.push(self.draft.checkpoint()?);
let mut candidates = reserve(limit + 1)?;
candidates.push(first);
let tokens = reserve(limit)?;
Ok(ScalarState { draft_priors, candidates, tokens, latest: Some(source) })
}
/// Draft chain, rewind to a fresh-epoch checkpoint, then verified catch-up against the real target. A matching
/// token does not make its speculative residual/KV the actual target residual/KV, so the entire transient chain
/// is discarded. Rewind increments the draft epoch: the old checkpoint must never be used by failure rollback
/// after real catch-up starts. If minting fails, the draft is already initial and no catch-up has occurred.
/// Exactly k real catch-up cells precede the current target product at p+k; the final cell is left for the next
/// window, and neither rejected cells nor any speculative residual survive into its prefix.
fn scalar_body(
&mut self,
cx: &ScalarCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'_>,
kar_cache: &mut Option<&mut KarPleCache<'_>>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &mut ScalarState,
) -> WindowResult<(TargetStepProduct, bool, usize)> {
self.scalar_draft_chain(cx, target, cache, cancelled, st)?;
let draft_steps = st.candidates.len() - 1;
self.draft.restore(&st.draft_priors[0])?;
st.draft_priors.clear();
st.draft_priors.push(self.draft.checkpoint()?);
let (expected, mut eos) = self.scalar_verify(cx, target, kar_cache, cache, cancelled, st)?;
if Some(expected) == cx.eos {
eos = true;
}
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
Ok((st.latest.take().ok_or(Error::IdentityMismatch)?, eos, draft_steps))
}
/// All draft work is anchored to the original current target prefix.
/// No source/product accessor from that prefix is used after target advance.
fn scalar_draft_chain(
&mut self,
cx: &ScalarCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'_>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &mut ScalarState,
) -> WindowResult<()> {
let mut previous = None;
for _ in 0..cx.limit {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let candidate = *st.candidates.last().ok_or(Error::IdentityMismatch)?;
if Some(candidate) == cx.eos {
break;
}
let input = self.scalar_chain_input(cx, target, cache, previous.as_ref(), st, candidate)?;
let product = mtp::step(cx.binding, target, &mut self.draft, input, cx.output, cache)?;
st.candidates.push(product.predicted(cx.binding, target)?);
previous = Some(product);
}
Ok(())
}
fn scalar_chain_input(
&self,
cx: &ScalarCtx<'_, '_, '_, '_>,
target: &QwenSession<'_>,
cache: &MoeWeightCache<'_>,
previous: Option<&mtp::MtpStepProduct>,
st: &ScalarState,
candidate: TokenId,
) -> Result<MtpInput> {
match previous {
Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache),
None => {
let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?;
MtpInput::from_target(cx.binding, target, &self.draft, latest, candidate, cache)
}
}
}
/// The authoritative target prediction controls both acceptance and EOS. A draft-only EOS cannot end a target
/// generation.
fn scalar_verify(
&mut self,
cx: &ScalarCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'_>,
kar_cache: &mut Option<&mut KarPleCache<'_>>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &mut ScalarState,
) -> WindowResult<(TokenId, bool)> {
let mut expected = cx.first;
let mut eos = false;
for index in 0..cx.limit.min(st.candidates.len()) {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
if Some(expected) == cx.eos {
eos = true;
break;
}
let candidate = st.candidates[index];
if candidate != expected {
break;
}
expected = self.scalar_accept(cx, target, kar_cache, cache, cancelled, st, expected)?;
st.tokens.push(candidate);
}
Ok((expected, eos))
}
/// Rebuild persistent cell i from CURRENT actual target R_i and verified token i+1 before target advancement
/// invalidates R_i. Do not call warm(): its nested rewind would invalidate this window's fresh-epoch rollback
/// checkpoint on failure. The new prediction is read while the product is still current.
#[allow(clippy::too_many_arguments)]
fn scalar_accept(
&mut self,
cx: &ScalarCtx<'_, '_, '_, '_>,
target: &mut QwenSession<'_>,
kar_cache: &mut Option<&mut KarPleCache<'_>>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &mut ScalarState,
expected: TokenId,
) -> WindowResult<TokenId> {
let binding = cx.binding;
let position = cx.next_position(st.tokens.len())?;
self.scalar_warm(binding, target, cache, cancelled, st, expected)?;
let position = Position::new(position, crate::qwen_forward::contract::position_dimension())?;
let (output, dense) = (cx.output, cx.dense_cache);
let kar = kar_cache.as_deref_mut();
let product = QwenForward::step_for_mtp_cached(
binding,
expected,
position,
target,
output,
kar,
Some(cache),
Some(dense),
)?;
let next = product.predicted(target)?;
st.latest = Some(product);
Ok(next)
}
/// Warm the persistent draft cell from the current target product, then honour cancellation.
fn scalar_warm(
&mut self,
binding: &ModelBinding,
target: &mut QwenSession<'_>,
cache: &mut MoeWeightCache<'_>,
cancelled: &mut impl FnMut() -> bool,
st: &ScalarState,
expected: TokenId,
) -> WindowResult<()> {
let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?;
let input = MtpInput::from_target(binding, target, &self.draft, latest, expected, cache)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)?;
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
Ok(())
}
/// Attempt both restores even when sticky CUDA failure prevents target restoration. Never return any tokens
/// from this branch. The target closure records the forward failure first, then restores the target.
fn scalar_rollback(
&mut self,
st: &ScalarState,
error: MtpWindowError,
restore_target: impl FnOnce(Option<Error>) -> Result<()>,
) -> Result<()> {
let cause = if let MtpWindowError::Forward(cause) = error { Some(cause) } else { None };
let target_restore = restore_target(cause);
let draft_restore = match st.draft_priors.first() {
Some(prior) => self.draft.restore(prior),
// Only reachable if remint failed immediately after rewind:
// no old-epoch access and the draft is already initial.
None => Ok(()),
};
target_restore?;
draft_restore
}
}