Merge claude/hexagonal-finish-14ee3a into claude/par-e05: AdaptiveWave/WaveState (e03) kept, PacketWave runs, ExpertWeights, PromptWeights, DecodeStepOwners reconciled

Files:
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 03:07:53 +01:00
274 changed files with 4669 additions and 3959 deletions
+2
View File
@@ -71,6 +71,8 @@ mod original_mtp_bank;
mod original_mtp_coupled;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod original_mtp_draft_head;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod original_mtp_draft_round;
mod original_mtp_draft_vocab;
mod original_mtp_rt;
mod original_session_state;
+1 -1
View File
@@ -190,5 +190,5 @@ pub use original_int8::{
CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram,
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpRetainedFullWeights,
OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill,
OriginalMtpStepOutput,
OriginalMtpStepOutput, ScalarDraftKvSources,
};
@@ -210,26 +210,18 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
/// `original_mtp_scalar_prefill` owns another scratch bank and is refused with InvalidQwenShape. `Drafter::new`
/// moved the owner's stream into the drafter, so it is lent back for the call (the Original's `mtp.prefill` runs on
/// the drafter's `cs_`).
#[allow(clippy::too_many_arguments)]
pub fn record_scalar_prefill<'arena, 'loan>(
&mut self,
residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>,
workspace: &mut crate::NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
tokens: &[i32],
cell0: usize,
first_needed: usize,
retained: Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
policy: &OriginalMtpScalarPolicy,
cancelled: impl FnMut() -> bool,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
rows: PrefillRows<'_>,
sources: ScalarDraftKvSources<'_, 'ctx>,
) -> Result<DraftKvOutcome> {
self.validate_context(self.context)?;
let stream = self.stream.take().ok_or(Error::ContextPoisoned)?;
let scalar = self.scalar.as_mut().ok_or(Error::ContextPoisoned)?;
scalar.stream = Some(stream);
let result =
scalar.record(residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled);
let result = scalar.record(residual, run, rows, sources);
self.stream = scalar.stream.take();
if self.stream.is_none() || result.is_err() && self.context.is_poisoned() {
self.failed = true;
@@ -32,7 +32,7 @@ impl OriginalMtpForwardProgram<'_> {
if let Some(stage) = &mut self.coupled_stage {
self.tail.modules[20].launch(1, [1, 1, 1], [256, 1, 1], 0, stream, stage)?;
}
self.owners.modules[0].launch(11, [1, 1, 1], [256, 1, 1], 0, stream, &mut self.args.reset)?;
self.owners.modules[0].launch(11, LaunchShape::new([1, 1, 1], [256, 1, 1], 0), stream, &mut self.args.reset)?;
for (i, command) in self.prefix.iter_mut().enumerate() {
if i == 1
&& let Some(e) = &mut self.native_embedding
@@ -46,9 +46,7 @@ impl OriginalMtpForwardProgram<'_> {
fn launch_scalar(modules: &[Rc<Module>; 6], stream: usize, command: &mut ScalarCommand) -> Result<()> {
match command {
ScalarCommand::Kernel { asset, index, grid, block, shared, args } => {
modules[*asset].launch(*index, *grid, *block, *shared, stream, args)
}
ScalarCommand::Kernel { asset, index, shape, args } => modules[*asset].launch(*index, *shape, stream, args),
ScalarCommand::Copy { .. } => Err(Error::InvalidQwenShape),
}
}
@@ -129,9 +129,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
&mut cmds,
0,
11,
[1, 1, 1],
[256, 1, 1],
0,
LaunchShape::new([1, 1, 1], [256, 1, 1], 0),
vec![Arg::U64(scalar.flag(0, 0)?), Arg::I32(16)],
)?;
Ok(cmds)
@@ -268,9 +266,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
cmds,
3,
0,
[rows as u32, 1, 1],
[1024, 1, 1],
0,
LaunchShape::new([rows as u32, 1, 1], [1024, 1, 1], 0),
vec![Arg::U64(input), Arg::U64(weight), Arg::U64(out), Arg::I32(width), Arg::F32(1e-6)],
)
}
@@ -283,15 +279,19 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
wh: &[BufferHandle; 11],
t: usize,
) -> Result<u64> {
let group = 0usize;
scalar.finite(cmds, a.emb, t * 2560, group, 0)?;
scalar.finite(cmds, a.emb, t * 2560, 0)?;
Self::prefix_rms_norm(cmds, t, (a.emb, wh[0].qwen_address(), a.en), 2560)?;
scalar.finite(cmds, a.en, t * 2560, group, 1)?;
scalar.finite(cmds, a.en, t * 2560, 1)?;
let q = scalar.address(15, 8 * 80 * 36)?;
OriginalMtpScalarPrefill::quant(cmds, a.en, q, t)?;
scalar.q8_guard(cmds, q, t, group, 2)?;
OriginalMtpScalarPrefill::project(cmds, wh[1].qwen_address(), q, a.e2, t, 2560)?;
scalar.finite(cmds, a.e2, t * 2560, group, 2)?;
scalar.q8_guard(cmds, q, t, 2)?;
OriginalMtpScalarPrefill::project(
cmds,
ProjectionBuffers { weight: wh[1].qwen_address(), quantised: q, output: a.e2 },
t,
2560,
)?;
scalar.finite(cmds, a.e2, t * 2560, 2)?;
Ok(q)
}
@@ -303,16 +303,20 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
wh: &[BufferHandle; 11],
(q, t): (u64, usize),
) -> Result<()> {
let group = 0usize;
Self::prefix_rms_norm(cmds, t, (a.rin, wh[2].qwen_address(), a.hn), 10240)?;
scalar.finite(cmds, a.hn, t * 10240, group, 3)?;
scalar.finite(cmds, a.hn, t * 10240, 3)?;
for hc in (0..t * 4).step_by(8) {
let cols = 8.min(t * 4 - hc);
OriginalMtpScalarPrefill::quant(cmds, a.hn + (hc * 10240) as u64, q, cols)?;
scalar.q8_guard(cmds, q, cols, group, 4)?;
OriginalMtpScalarPrefill::project(cmds, wh[3].qwen_address(), q, a.h2 + (hc * 10240) as u64, cols, 2560)?;
scalar.q8_guard(cmds, q, cols, 4)?;
OriginalMtpScalarPrefill::project(
cmds,
ProjectionBuffers { weight: wh[3].qwen_address(), quantised: q, output: a.h2 + (hc * 10240) as u64 },
cols,
2560,
)?;
}
scalar.finite(cmds, a.h2, t * 10240, group, 4)?;
scalar.finite(cmds, a.h2, t * 10240, 4)?;
Ok(())
}
@@ -324,17 +328,14 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
wh: &[BufferHandle; 11],
(t, policy): (usize, &OriginalMtpScalarPolicy),
) -> Result<()> {
let group = 0usize;
OriginalMtpScalarPrefill::kernel(
cmds,
0,
4,
[40, t as u32, 1],
[256, 1, 1],
0,
LaunchShape::new([40, t as u32, 1], [256, 1, 1], 0),
vec![Arg::U64(a.h2), Arg::U64(a.e2), Arg::U64(a.r), Arg::I64(2560), Arg::I32(4)],
)?;
scalar.finite(cmds, a.r, t * 10240, group, 5)?;
scalar.finite(cmds, a.r, t * 10240, 5)?;
scalar.gr(cmds, t, wh, policy)?;
Self::prefix_gr_guards(scalar, cmds, a.mixed, t)
}
@@ -346,12 +347,11 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
mixed: u64,
t: usize,
) -> Result<()> {
let group = 0usize;
scalar.finite(cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?;
scalar.finite(cmds, scalar.address(7, t * 40960)?, t * 10240, group, 6)?;
scalar.finite(cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?;
scalar.finite(cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?;
scalar.finite(cmds, mixed, t * 2560, group, 8)
scalar.finite(cmds, scalar.address(9, t * 16)?, t * 4, 6)?;
scalar.finite(cmds, scalar.address(7, t * 40960)?, t * 10240, 6)?;
scalar.finite(cmds, scalar.address(8, t * 1280)?, t * 320, 7)?;
scalar.finite(cmds, scalar.address(10, t * 16)?, t * 4, 7)?;
scalar.finite(cmds, mixed, t * 2560, 8)
}
/// K and V projections of the mixed state into the current KV cells; returns `(k, v)` addresses.
@@ -362,14 +362,23 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
a: &PrefixAddrs,
(wh, q, t): (&[BufferHandle; 11], u64, usize),
) -> Result<(u64, u64)> {
let group = 0usize;
OriginalMtpScalarPrefill::quant(cmds, a.mixed, q, t)?;
scalar.q8_guard(cmds, q, t, group, 9)?;
scalar.q8_guard(cmds, q, t, 9)?;
let (kc, vc) = scalar.current_kv(ring)?;
OriginalMtpScalarPrefill::project(cmds, wh[7].qwen_address(), q, kc, t, 512)?;
scalar.finite(cmds, kc, t * 512, group, 10)?;
OriginalMtpScalarPrefill::project(cmds, wh[8].qwen_address(), q, vc, t, 512)?;
scalar.finite(cmds, vc, t * 512, group, 11)?;
OriginalMtpScalarPrefill::project(
cmds,
ProjectionBuffers { weight: wh[7].qwen_address(), quantised: q, output: kc },
t,
512,
)?;
scalar.finite(cmds, kc, t * 512, 10)?;
OriginalMtpScalarPrefill::project(
cmds,
ProjectionBuffers { weight: wh[8].qwen_address(), quantised: q, output: vc },
t,
512,
)?;
scalar.finite(cmds, vc, t * 512, 11)?;
Ok((kc, vc))
}
}
@@ -34,9 +34,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
cmds,
1,
0,
[10, t as u32, 1],
[32, 1, 1],
0,
LaunchShape::new([10, t as u32, 1], [32, 1, 1], 0),
vec![
Arg::I32(kind),
Arg::U64(table),
@@ -59,9 +57,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
cmds,
0,
5,
[10, t as u32, 1],
[256, 1, 1],
0,
LaunchShape::new([10, t as u32, 1], [256, 1, 1], 0),
vec![
Arg::U64(table),
Arg::U64(table + codes as u64),
@@ -101,20 +97,17 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
a: &PrefixAddrs,
(kv, wh, kc, vc, row): (&DraftKvPolicy, &[BufferHandle; 11], u64, u64, usize),
) -> Result<()> {
let group = 0usize;
let k = kc + (row * 2048) as u64;
OriginalMtpScalarPrefill::kernel(
cmds,
2,
9,
[2, 1, 1],
[256, 1, 1],
0,
LaunchShape::new([2, 1, 1], [256, 1, 1], 0),
vec![Arg::U64(k), Arg::U64(wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)],
)?;
scalar.finite(cmds, k, 512, group, 12)?;
scalar.finite(cmds, k, 512, 12)?;
Self::prefix_row_rope(cmds, kv, k, a.pos + (row * 96) as u64)?;
scalar.finite(cmds, k, 512, group, 13)?;
scalar.finite(cmds, k, 512, 13)?;
Self::prefix_step_append(cmds, ring, (a.step + (row * 16) as u64, k, vc + (row * 2048) as u64))
}
@@ -131,7 +124,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
}
values.extend([Arg::U64(step), Arg::U64(k), Arg::U64(v), Arg::I32(2), Arg::I32(256), Arg::I32(4)]);
values.extend(host.map(Arg::U64));
OriginalMtpScalarPrefill::kernel(cmds, 5, 0, [2, 4, 2], [64, 1, 1], 0, values)
OriginalMtpScalarPrefill::kernel(cmds, 5, 0, LaunchShape::new([2, 4, 2], [64, 1, 1], 0), values)
}
fn prefix_row_rope(cmds: &mut Vec<ScalarCommand>, kv: &DraftKvPolicy, k: u64, position: u64) -> Result<()> {
@@ -139,9 +132,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
cmds,
3,
1,
[4, 2, 1],
[32, 1, 1],
0,
LaunchShape::new([4, 2, 1], [32, 1, 1], 0),
vec![
Arg::U64(k),
Arg::U64(k),
@@ -172,9 +163,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
cmds,
3,
3,
[64, 1, 1],
[256, 1, 1],
0,
LaunchShape::new([64, 1, 1], [256, 1, 1], 0),
vec![
Arg::U64(ring.address(2)?),
Arg::U64(ring.address(3)?),
@@ -67,8 +67,8 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx> {
e.capture(c)?;
}
match cmd {
ScalarCommand::Kernel { asset, index, grid, block, shared, args } => {
self.program.owners.modules[*asset].launch(*index, *grid, *block, *shared, stream, args)?
ScalarCommand::Kernel { asset, index, shape, args } => {
self.program.owners.modules[*asset].launch(*index, *shape, stream, args)?
}
ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape),
}
@@ -70,6 +70,7 @@ pub use prefill::{
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, OriginalMtpPrefillWeights,
OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights,
OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, PrefillRows, RecordRun,
ScalarDraftKvSources,
};
struct Page {
runs: [Box<[u8]>; 4],
@@ -162,7 +162,7 @@ pub use scalar::{
CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram,
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpRetainedFullWeights,
OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill,
OriginalMtpStepOutput,
OriginalMtpStepOutput, ScalarDraftKvSources,
};
#[path = "mtp_original_prefill/impl_completeddraftkv.rs"]
@@ -1,5 +1,6 @@
//! Private fixed-symbol ABI for literal Original MTP ring/tail assets.
//! No arbitrary entry, public pointer, or stream ownership escapes this module.
use crate::mtp_dense_kv::original_int8::abi::LaunchShape;
use crate::{Error, Result, combine};
use std::ffi::{CStr, c_void};
pub(crate) enum Arg {
@@ -48,6 +49,7 @@ impl Arguments {
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod enabled {
use super::*;
use crate::mtp_dense_kv::original_int8::abi::LaunchDims;
type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32;
type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32;
type FunctionAttr = unsafe extern "C" fn(*mut c_void, i32, i32) -> i32;
@@ -263,12 +265,11 @@ mod enabled {
pub(crate) fn launch(
&self,
index: usize,
grid: [u32; 3],
block: [u32; 3],
shared: u32,
shape: LaunchShape,
stream: usize,
args: &mut Arguments,
) -> Result<()> {
let LaunchShape { dims: LaunchDims { grid, block }, shared } = shape;
let geometry = Geometry { grid, block, shared, stream };
geometry.validate()?;
let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
@@ -368,7 +369,7 @@ impl Module {
pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> {
pub(crate) fn launch(&self, _: usize, _: LaunchShape, _: usize, _: &mut Arguments) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> {
@@ -1,6 +1,17 @@
//! Literal cached MtpDrafter prefill graph scheduling. All kernel ABI arguments
//! and real physical input/scratch/weight owners survive capture and replay.
use super::*;
/// One group of prompt rows handed to the stream: its rows and cells, and the kernel and copy commands that run for it.
pub(super) struct GroupSubmission<'a> {
pub(super) index: usize,
pub(super) tokens: &'a [i32],
pub(super) first_cell: usize,
pub(super) has_mapped_inputs: bool,
pub(super) kernels: &'a mut Vec<ScalarCommand>,
pub(super) copies: &'a mut [ScalarCommand],
}
impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
pub(super) fn upload_records(&mut self, staging: &mut Vec<(BufferHandle, Vec<u8>)>) -> Result<()> {
self.pending_host.try_reserve(staging.len() + 1).map_err(|_| Error::HostAllocation)?;
@@ -53,33 +64,27 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(super) fn enqueue_group(
&mut self,
t: usize,
group: usize,
mapped: bool,
submission: &mut GroupSubmission<'_>,
weights: &Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
ring: &MtpOriginalInt8<'ctx>,
commands: &mut Vec<ScalarCommand>,
copies: &mut [ScalarCommand],
tokens: &[i32],
cell0: usize,
) -> Result<()> {
let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !mapped };
let mapped = submission.has_mapped_inputs;
let key = OriginalGraphKey::MtpPrefill { rows: submission.tokens.len() as u8, device_inputs: !mapped };
let found = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_some();
if !found {
self.record_new_graph(key, weights, ring, commands)?;
self.record_new_graph(key, weights, ring, submission.kernels)?;
}
if mapped {
self.write_mapped(tokens, cell0)?;
self.write_mapped(submission.tokens, submission.first_cell)?;
}
self.has_pending = true;
// These are the four literal Original copies before each device-input graph;
// mapped mode keeps only the actual Rin copy outside the captured copy kernels.
let module = Rc::clone(self.modules[0].as_ref().ok_or(Error::ContextPoisoned)?);
self.enqueue_copies(&module, copies)?;
self.replay_group(key, group, &module)
self.enqueue_copies(&module, submission.copies)?;
self.replay_group(key, submission.index, &module)
}
fn record_new_graph(
&mut self,
@@ -107,8 +112,8 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
let handle = capture.stream_handle(r.context)?;
for command in &mut r.commands {
match command {
ScalarCommand::Kernel { asset, index, grid, block, shared, args } => {
r.modules[*asset].launch(*index, *grid, *block, *shared, handle, args)?
ScalarCommand::Kernel { asset, index, shape, args } => {
r.modules[*asset].launch(*index, *shape, handle, args)?
}
ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape),
}
@@ -6,6 +6,7 @@ use super::*;
#[path = "mtp_original_scalar_ffi.rs"]
mod scalar_abi;
use crate::{OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, OriginalStreamKind};
use abi::LaunchShape;
use scalar_abi::{Arg, Arguments, Module};
#[path = "mtp_original_scalar_weights.rs"]
mod retained_weights;
@@ -78,9 +79,23 @@ pub use full_forward::{
OriginalMtpStepOutput,
};
enum ScalarCommand {
Kernel { asset: usize, index: usize, grid: [u32; 3], block: [u32; 3], shared: u32, args: Arguments },
Kernel { asset: usize, index: usize, shape: LaunchShape, args: Arguments },
Copy { dst: u64, src: u64, bytes: usize },
}
/// The device addresses of one Q8 projection: the weight, the quantised activations and the output.
#[derive(Clone, Copy)]
struct ProjectionBuffers {
weight: u64,
quantised: u64,
output: u64,
}
/// What the scalar draft K/V of a prompt is computed from: the ring snapshot it continues, the retained weights and
/// the policy (the scalar counterpart of `DraftKvSources`).
pub struct ScalarDraftKvSources<'a, 'ctx> {
pub prior: &'a MtpInt8Snapshot,
pub retained: Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
pub policy: &'a OriginalMtpScalarPolicy,
}
/// Real affine scalar producer. Cached Original capture must retain this owner
/// AND genuine model-lifetime whole weights (see the explicit graph handoff).
pub struct OriginalMtpScalarPrefill<'ctx> {
@@ -3,21 +3,24 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_originalmtpscalarprefill/call_admission.rs"]
mod call_admission;
#[path = "impl_originalmtpscalarprefill/group_capture.rs"]
mod group_capture;
#[path = "impl_originalmtpscalarprefill/group_loop.rs"]
mod group_loop;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs"]
mod impl_originalmtpscalarprefill_2;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs"]
mod impl_originalmtpscalarprefill_2_2;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs"]
mod impl_originalmtpscalarprefill_3;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs"]
mod impl_originalmtpscalarprefill_4;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs"]
mod impl_originalmtpscalarprefill_5;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs"]
mod impl_originalmtpscalarprefill_6;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs"]
mod impl_originalmtpscalarprefill_7;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs"]
mod impl_originalmtpscalarprefill_8;
#[path = "impl_originalmtpscalarprefill/kernel_commands.rs"]
mod kernel_commands;
#[path = "impl_originalmtpscalarprefill/record_operands.rs"]
mod record_operands;
#[allow(unused_imports)]
use impl_originalmtpscalarprefill_6::{Cap, ExternalOwners, GrRows, GroupIo, ScalarCall, ScalarStaged};
use record_operands::{
Cap, ExternalOwners, GrRows, GroupIo, GroupSpan, PagePublication, ScalarCall, ScalarGroupSources, ScalarOperands,
ScalarStaged,
};
@@ -1,6 +1,6 @@
//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (4). `record_impl` admits the call,
//! stages the weights and claims the policy; the group loop is in `impl_originalmtpscalarprefill_7.rs` and the capture
//! of one group in `impl_originalmtpscalarprefill_8.rs`.
//! The admission of one `OriginalMtpScalarPrefill::record_impl` call (STRA-338): the owner and prompt checks, the
//! alias checks and weight staging, and the policy claim. The group loop is in `group_loop.rs` and the capture of one
//! group in `group_capture.rs`.
#[allow(unused_imports)]
use super::*;
@@ -23,45 +23,39 @@ const SCALAR_EXTENTS: [usize; 11] = [
impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
/// Literal cached device-input or mapped-input per-T graph scheduling.
/// Unsupported storage/math branches return explicit fallback, never completion.
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn record_impl<'arena, 'loan>(
&mut self,
residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
tokens: &[i32],
cell0: usize,
first_needed: usize,
retained: Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
policy: &OriginalMtpScalarPolicy,
mut cancelled: impl FnMut() -> bool,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
rows: PrefillRows<'_>,
sources: ScalarDraftKvSources<'_, 'ctx>,
) -> Result<DraftKvOutcome> {
let PrefillRows { tokens, cell0, first_needed } = rows;
let ScalarDraftKvSources { prior, retained, policy } = sources;
let call = ScalarCall { prior, tokens, cell0, first_needed, policy };
self.record_scalar(residual, workspace, ring, &call, retained, &mut cancelled)
self.record_scalar(residual, run, &call, retained)
}
fn record_scalar(
&mut self,
residual: &mut OriginalDeviceResidual<'_, '_, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
call: &ScalarCall<'_>,
retained: Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<DraftKvOutcome> {
if let Some(outcome) = Self::early_outcome(call.policy, call.tokens)? {
return Ok(outcome);
}
let (weights, embedding) = retained.loans(self.context)?;
self.validate_scalar(residual, workspace, ring, call, &embedding)?;
self.validate_owners(run.workspace, run.ring, call.prior)?;
self.validate_prompt(residual, run.ring, call, &embedding)?;
let Some(first_group) = self.first_group(call) else {
return Ok(DraftKvOutcome::Skipped);
};
let rows = residual.lease_mut();
let staged = self.stage_scalar(rows, workspace, ring, (&weights, &embedding))?;
let staged = self.stage_scalar(rows, run.workspace, run.ring, (&weights, &embedding))?;
self.claim_policy(&retained, call.prior, call.policy)?;
let operands = (&staged, &retained, &embedding);
self.record_groups(rows, workspace, ring, (call, first_group), operands, cancelled)
let operands = ScalarOperands { staged: &staged, retained: &retained, embedding: &embedding };
self.record_groups(rows, run, (call, first_group), operands)
}
fn early_outcome(policy: &OriginalMtpScalarPolicy, tokens: &[i32]) -> Result<Option<DraftKvOutcome>> {
if let Some(fallback) = OriginalMtpPrefill::fallback_for(&policy.kv, tokens) {
@@ -70,19 +64,27 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
OriginalMtpPrefill::reject_bad_rope(&policy.kv)?;
Ok(None)
}
fn validate_scalar(
/// The owner, the draft ring, its prior snapshot and the batch workspace must all belong to this context.
fn validate_owners(
&self,
workspace: &NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
) -> Result<()> {
self.validate()?;
ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?;
ring.validate_snapshot(prior)?;
workspace.validate_context(self.context)?;
ring.validate_context(self.context)
}
/// The prompt must fit the residual rows, the ring and the owner, and every token must index the embedding table.
fn validate_prompt(
&self,
residual: &OriginalDeviceResidual<'_, '_, 'ctx>,
workspace: &NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
call: &ScalarCall<'_>,
embedding: &OriginalMtpEmbedding<'_, 'ctx>,
) -> Result<()> {
self.validate()?;
ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?;
ring.validate_snapshot(call.prior)?;
workspace.validate_context(self.context)?;
ring.validate_context(self.context)?;
if self.shape_rejected(residual, ring, call) {
return Err(Error::InvalidProjectionShape);
}
@@ -19,7 +19,13 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
self.cap_commit(cmds, cap)
}
fn cap_inputs(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>) -> Result<()> {
Self::kernel(cmds, 0, 11, [1, 1, 1], [256, 1, 1], 0, vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)])?;
Self::kernel(
cmds,
0,
11,
LaunchShape::new([1, 1, 1], [256, 1, 1], 0),
vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)],
)?;
if cap.policy.per_group_sync {
self.cap_map_inputs(cmds, cap)?;
}
@@ -31,7 +37,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?;
for (dst, offset, count) in [(io.tok, 0, t), (io.step, max_t * 4, t * 4), (io.pos, max_t * 20, t * 24)] {
let args = vec![Arg::U64(dst), Arg::U64(m.address(offset, count * 4)?), Arg::I32(count as i32)];
Self::kernel(cmds, 3, 2, [1, 1, 1], [128, 1, 1], 0, args)?;
Self::kernel(cmds, 3, 2, LaunchShape::new([1, 1, 1], [128, 1, 1], 0), args)?;
}
Ok(())
}
@@ -54,7 +60,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
Arg::U64((2560 / group) as u64),
Arg::U64(cap.io.emb),
];
Self::kernel(cmds, 0, 5, [10, cap.t as u32, 1], [256, 1, 1], 0, args)
Self::kernel(cmds, 0, 5, LaunchShape::new([10, cap.t as u32, 1], [256, 1, 1], 0), args)
}
}
}
@@ -68,64 +74,69 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
Arg::I64(2560),
Arg::U64(cap.io.emb),
];
Self::kernel(cmds, 1, 0, [10, cap.t as u32, 1], [32, 1, 1], 0, args)
Self::kernel(cmds, 1, 0, LaunchShape::new([10, cap.t as u32, 1], [32, 1, 1], 0), args)
}
/// The embedding half: finite guard, RMS norm and the Q8 projection into `e2`; returns the Q8 scratch.
fn cap_embed_chain(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>) -> Result<u64> {
let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group);
self.finite(cmds, io.emb, t * 2560, g, 0)?;
let (io, wh, t) = (&cap.io, cap.wh, cap.t);
self.finite(cmds, io.emb, t * 2560, 0)?;
let norm =
vec![Arg::U64(io.emb), Arg::U64(wh[0].qwen_address()), Arg::U64(io.en), Arg::I32(2560), Arg::F32(1e-6)];
Self::kernel(cmds, 3, 0, [t as u32, 1, 1], [1024, 1, 1], 0, norm)?;
self.finite(cmds, io.en, t * 2560, g, 1)?;
Self::kernel(cmds, 3, 0, LaunchShape::new([t as u32, 1, 1], [1024, 1, 1], 0), norm)?;
self.finite(cmds, io.en, t * 2560, 1)?;
let q = self.address(15, 8 * 80 * 36)?;
Self::quant(cmds, io.en, q, t)?;
self.q8_guard(cmds, q, t, g, 2)?;
Self::project(cmds, wh[1].qwen_address(), q, io.e2, t, 2560)?;
self.finite(cmds, io.e2, t * 2560, g, 2)?;
self.q8_guard(cmds, q, t, 2)?;
Self::project(cmds, ProjectionBuffers { weight: wh[1].qwen_address(), quantised: q, output: io.e2 }, t, 2560)?;
self.finite(cmds, io.e2, t * 2560, 2)?;
Ok(q)
}
/// The hidden half: RMS norm of the residual and the Q8 projection into `h2`, eight columns at a time.
fn cap_hidden(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>, q: u64) -> Result<()> {
let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group);
let (io, wh, t) = (&cap.io, cap.wh, cap.t);
let norm =
vec![Arg::U64(io.rin), Arg::U64(wh[2].qwen_address()), Arg::U64(io.hn), Arg::I32(10240), Arg::F32(1e-6)];
Self::kernel(cmds, 3, 0, [t as u32, 1, 1], [1024, 1, 1], 0, norm)?;
self.finite(cmds, io.hn, t * 10240, g, 3)?;
Self::kernel(cmds, 3, 0, LaunchShape::new([t as u32, 1, 1], [1024, 1, 1], 0), norm)?;
self.finite(cmds, io.hn, t * 10240, 3)?;
for hc in (0..t * 4).step_by(8) {
let cols = 8.min(t * 4 - hc);
Self::quant(cmds, io.hn + (hc * 10240) as u64, q, cols)?;
self.q8_guard(cmds, q, cols, g, 4)?;
Self::project(cmds, wh[3].qwen_address(), q, io.h2 + (hc * 10240) as u64, cols, 2560)?;
self.q8_guard(cmds, q, cols, 4)?;
Self::project(
cmds,
ProjectionBuffers { weight: wh[3].qwen_address(), quantised: q, output: io.h2 + (hc * 10240) as u64 },
cols,
2560,
)?;
}
self.finite(cmds, io.h2, t * 10240, g, 4)
self.finite(cmds, io.h2, t * 10240, 4)
}
fn cap_gr(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>) -> Result<()> {
let (io, t, g) = (&cap.io, cap.t, cap.group);
let (io, t) = (&cap.io, cap.t);
let args = vec![Arg::U64(io.h2), Arg::U64(io.e2), Arg::U64(io.r), Arg::I64(2560), Arg::I32(4)];
Self::kernel(cmds, 0, 4, [40, t as u32, 1], [256, 1, 1], 0, args)?;
self.finite(cmds, io.r, t * 10240, g, 5)?;
Self::kernel(cmds, 0, 4, LaunchShape::new([40, t as u32, 1], [256, 1, 1], 0), args)?;
self.finite(cmds, io.r, t * 10240, 5)?;
self.gr(cmds, t, cap.wh, cap.policy)?;
self.cap_gr_guards(cmds, cap)
}
fn cap_gr_guards(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>) -> Result<()> {
let (t, g) = (cap.t, cap.group);
self.finite(cmds, self.address(9, t * 16)?, t * 4, g, 6)?;
self.finite(cmds, self.address(7, t * 40960)?, t * 10240, g, 6)?;
self.finite(cmds, self.address(8, t * 1280)?, t * 320, g, 7)?;
self.finite(cmds, self.address(10, t * 16)?, t * 4, g, 7)?;
self.finite(cmds, cap.io.mixed, t * 2560, g, 8)
let t = cap.t;
self.finite(cmds, self.address(9, t * 16)?, t * 4, 6)?;
self.finite(cmds, self.address(7, t * 40960)?, t * 10240, 6)?;
self.finite(cmds, self.address(8, t * 1280)?, t * 320, 7)?;
self.finite(cmds, self.address(10, t * 16)?, t * 4, 7)?;
self.finite(cmds, cap.io.mixed, t * 2560, 8)
}
/// The K and V projections of the mixed state into the current KV; returns their addresses.
fn cap_kv(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>, q: u64) -> Result<(u64, u64)> {
let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group);
let (io, wh, t) = (&cap.io, cap.wh, cap.t);
Self::quant(cmds, io.mixed, q, t)?;
self.q8_guard(cmds, q, t, g, 9)?;
self.q8_guard(cmds, q, t, 9)?;
let (kc, vc) = self.current_kv(cap.ring)?;
Self::project(cmds, wh[7].qwen_address(), q, kc, t, 512)?;
self.finite(cmds, kc, t * 512, g, 10)?;
Self::project(cmds, wh[8].qwen_address(), q, vc, t, 512)?;
self.finite(cmds, vc, t * 512, g, 11)?;
Self::project(cmds, ProjectionBuffers { weight: wh[7].qwen_address(), quantised: q, output: kc }, t, 512)?;
self.finite(cmds, kc, t * 512, 10)?;
Self::project(cmds, ProjectionBuffers { weight: wh[8].qwen_address(), quantised: q, output: vc }, t, 512)?;
self.finite(cmds, vc, t * 512, 11)?;
Ok((kc, vc))
}
/// K norm and rope, then the step append kernel for one row.
@@ -133,10 +144,10 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
let (kc, vc) = kv;
let k = kc + (row * 2048) as u64;
let norm = vec![Arg::U64(k), Arg::U64(cap.wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)];
Self::kernel(cmds, 2, 9, [2, 1, 1], [256, 1, 1], 0, norm)?;
self.finite(cmds, k, 512, cap.group, 12)?;
Self::kernel(cmds, 2, 9, LaunchShape::new([2, 1, 1], [256, 1, 1], 0), norm)?;
self.finite(cmds, k, 512, 12)?;
Self::cap_rope(cmds, cap, row, k)?;
self.finite(cmds, k, 512, cap.group, 13)?;
self.finite(cmds, k, 512, 13)?;
self.cap_append(cmds, cap, row, (k, vc))
}
fn cap_rope(cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>, row: usize, k: u64) -> Result<()> {
@@ -157,7 +168,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
Arg::U64(0),
Arg::Words3([0; 3]),
];
Self::kernel(cmds, 3, 1, [4, 2, 1], [32, 1, 1], 0, args)
Self::kernel(cmds, 3, 1, LaunchShape::new([4, 2, 1], [32, 1, 1], 0), args)
}
/// Literal step append kernel and actual private step record, not batched prompt arithmetic.
fn cap_append(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>, row: usize, kv: (u64, u64)) -> Result<()> {
@@ -182,7 +193,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
Arg::U64(host[4]),
Arg::U64(host[5]),
];
Self::kernel(cmds, 5, 0, [2, 4, 2], [64, 1, 1], 0, args)
Self::kernel(cmds, 5, 0, LaunchShape::new([2, 4, 2], [64, 1, 1], 0), args)
}
fn cap_commit(&self, cmds: &mut Vec<ScalarCommand>, cap: &Cap<'_, 'ctx>) -> Result<()> {
let ring = cap.ring;
@@ -194,6 +205,6 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
Arg::I32(cap.t as i32),
Arg::U64(self.flag(0, 14)?),
];
Self::kernel(cmds, 3, 3, [64, 1, 1], [256, 1, 1], 0, args)
Self::kernel(cmds, 3, 3, LaunchShape::new([64, 1, 1], [256, 1, 1], 0), args)
}
}
@@ -0,0 +1,179 @@
//! The group loop of `OriginalMtpScalarPrefill::record_impl` (STRA-338): the page and record staging, the per-group
//! graph capture and enqueue, and the publication of the completed range.
use super::super::graph::GroupSubmission;
#[allow(unused_imports)]
use super::*;
/// Fills the `[tokens n][steps4*n][positions24*n]` records of a prompt.
fn fill_records(rec: &mut [u8], tokens: &[i32], cell0: usize) {
let n = tokens.len();
for (i, token) in tokens.iter().enumerate() {
let cell = cell0 + i;
rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes());
for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() {
let off = (n + i * 4 + j) * 4;
rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes());
}
for h in 0..24 {
let off = (n * 5 + i * 24 + h) * 4;
rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes());
}
}
}
impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
/// Stages the pages and records, restores the ring and records every group; publishes the completed range.
pub(in super::super) fn record_groups(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
at: (&ScalarCall<'_>, usize),
operands: ScalarOperands<'_, 'ctx>,
) -> Result<DraftKvOutcome> {
let (call, first_group) = at;
let generation = run.ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
let (first, end) = (call.cell0 + first_group, call.cell0 + call.tokens.len());
let first_page = first / 4;
let (pages, changed) = OriginalMtpPrefill::prepare_pages(call.prior, end, first_page)?;
// Literal prefill records [tokens n][steps4*n][positions24*n], one upload.
let (records, rec) = self.build_records(call)?;
let mut staging = vec![(records, rec)];
let mut cmds = Vec::new();
cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?;
if (run.cancelled)() {
return Ok(DraftKvOutcome::Cancelled);
}
self.restore_and_upload(run.workspace, run.ring, call, &mut staging)?;
let sources = ScalarGroupSources { call, operands, records };
if let Some(outcome) = self.run_groups(rows, run, &sources, &mut cmds)? {
return Ok(outcome);
}
self.complete(rows, run, call, PagePublication { pages, changed, first_page, first, end, generation })
}
fn build_records(&self, call: &ScalarCall<'_>) -> Result<(BufferHandle, Vec<u8>)> {
let mut rec = zero_bytes(call.tokens.len() * 29 * 4)?;
fill_records(&mut rec, call.tokens, call.cell0);
let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?;
let rec_h = rb.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(rb.bytes, 0, rec.len())?;
Ok((rec_h, rec))
}
fn restore_and_upload(
&mut self,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
call: &ScalarCall<'_>,
staging: &mut Vec<(BufferHandle, Vec<u8>)>,
) -> Result<()> {
ring.execute(workspace, Vec::new())?;
ring.restore(workspace, call.prior)?;
ring.current = None;
if !call.policy.per_group_sync {
self.upload_records(staging)?;
} else {
self.upload_records(&mut Vec::new())?;
}
staging.clear();
Ok(())
}
/// Stages, cancellation-checks and submits every group of the prompt that the ring does not hold yet.
fn run_groups(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
sources: &ScalarGroupSources<'_, 'ctx>,
commands: &mut Vec<ScalarCommand>,
) -> Result<Option<DraftKvOutcome>> {
let call = sources.call;
let n = call.tokens.len();
for (index, first_row) in (0..n).step_by(self.max_t).enumerate() {
let row_count = self.max_t.min(n - first_row);
if call.cell0 + first_row + row_count <= call.first_needed {
continue;
}
let span = GroupSpan { index, first_row, row_count };
let mut copies = self.stage_group(sources, run.ring, span, &mut *commands)?;
if (run.cancelled)() {
self.drain_graphs(rows, run.workspace)?;
return Ok(Some(DraftKvOutcome::Cancelled));
}
let submission = Self::submission(call, span, &mut *commands, &mut copies);
self.submit_group(rows, run, sources.operands.retained, submission)?;
}
Ok(None)
}
/// The scratch addresses and staging copies of one group, and its captured commands when no graph is cached.
fn stage_group(
&mut self,
sources: &ScalarGroupSources<'_, 'ctx>,
ring: &MtpOriginalInt8<'ctx>,
span: GroupSpan,
commands: &mut Vec<ScalarCommand>,
) -> Result<[ScalarCommand; 4]> {
let ScalarGroupSources { call, operands, records } = *sources;
let ScalarOperands { staged, embedding, .. } = operands;
let io = self.group_io(span.row_count)?;
let at = (call.tokens.len(), span.first_row, span.row_count);
let copies = Self::group_copies(&io, records, (staged.rh, staged.rbytes), at)?;
if self.needs_capture(span.row_count, call.policy.per_group_sync)? {
let wh = &staged.wh;
let cap = Cap { io, wh, eh: staged.eh, t: span.row_count, policy: call.policy, ring, embedding };
self.capture_group(commands, &cap)?;
}
Ok(copies)
}
/// The rows, cells and commands of one group; a mapped-input group needs only the residual copy.
fn submission<'a>(
call: &'a ScalarCall<'_>,
span: GroupSpan,
kernels: &'a mut Vec<ScalarCommand>,
copies: &'a mut [ScalarCommand; 4],
) -> GroupSubmission<'a> {
let has_mapped_inputs = call.policy.per_group_sync;
let copies = if has_mapped_inputs { &mut copies[3..] } else { &mut copies[..] };
let tokens = &call.tokens[span.first_row..span.first_row + span.row_count];
let first_cell = call.cell0 + span.first_row;
GroupSubmission { index: span.index, tokens, first_cell, has_mapped_inputs, kernels, copies }
}
fn needs_capture(&mut self, t: usize, per_group_sync: bool) -> Result<bool> {
let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !per_group_sync };
Ok(self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_none())
}
fn submit_group(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
retained: &Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
mut submission: GroupSubmission<'_>,
) -> Result<()> {
if let Err(primary) = self.enqueue_group(&mut submission, retained, run.ring) {
let drained = self.drain_graphs(rows, run.workspace);
return combine(Err(primary), drained);
}
submission.kernels.clear();
if submission.has_mapped_inputs {
self.drain_graphs(rows, run.workspace)?;
}
Ok(())
}
/// Drains the last graphs, reads the encoded pages back and publishes the completed range.
fn complete(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
call: &ScalarCall<'_>,
publication: PagePublication,
) -> Result<DraftKvOutcome> {
let PagePublication { pages, mut changed, first_page, first, end, generation } = publication;
if !call.policy.per_group_sync {
self.drain_graphs(rows, run.workspace)?;
}
if (run.cancelled)() {
return Ok(DraftKvOutcome::Cancelled);
}
for (p, runs) in changed.iter_mut().enumerate() {
run.ring.read_encoded_page(first_page + p, runs)?;
}
Ok(OriginalMtpPrefill::finish(run.ring, pages, changed, (first, end, generation)))
}
}
@@ -17,13 +17,11 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
cmds,
4,
if plain { 0 } else { 1 },
[t as u32, if plain { 1 } else { 4 }, 1],
[256, 1, 1],
0,
LaunchShape::new([t as u32, if plain { 1 } else { 4 }, 1], [256, 1, 1], 0),
vec![self.gr_args(0, t, wh, xn)?],
)?;
self.gr_chunks(cmds, GrRows { row_count: t, weights: wh, normalised: xn }, policy)?;
Self::kernel(cmds, 4, 3, [160, 1, 1], [256, 1, 1], 0, vec![self.gr_args(0, t, wh, xn)?])
Self::kernel(cmds, 4, 3, LaunchShape::new([160, 1, 1], [256, 1, 1], 0), vec![self.gr_args(0, t, wh, xn)?])
}
fn gr_chunks(
&self,
@@ -40,9 +38,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
cmds,
4,
self.gr_chunk_kernel(policy),
[41, 1, 1],
[256, 1, 1],
(ct * per_token) as u32,
LaunchShape::new([41, 1, 1], [256, 1, 1], (ct * per_token) as u32),
vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?],
)?;
}
@@ -57,33 +53,16 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
5
}
}
#[allow(clippy::too_many_arguments)]
/// Records the scalar draft K/V of the prompt `rows` and drains the stream when anything is still pending.
pub fn record<'arena, 'loan>(
&mut self,
residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
tokens: &[i32],
cell0: usize,
first_needed: usize,
retained: Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
policy: &OriginalMtpScalarPolicy,
cancelled: impl FnMut() -> bool,
run: &mut RecordRun<'_, 'ctx, impl FnMut() -> bool>,
rows: PrefillRows<'_>,
sources: ScalarDraftKvSources<'_, 'ctx>,
) -> Result<DraftKvOutcome> {
let result = self.record_impl(
residual,
workspace,
ring,
prior,
tokens,
cell0,
first_needed,
retained,
policy,
cancelled,
);
self.drain_pending(result, residual, workspace)
let result = self.record_impl(residual, run, rows, sources);
self.drain_pending(result, residual, run.workspace)
}
fn drain_pending<T>(
&mut self,
@@ -1,192 +0,0 @@
//! The group loop of `OriginalMtpScalarPrefill::record_impl` (STRA-338): the page and record staging, the per-group
//! graph capture and enqueue, and the publication of the completed range.
#[allow(unused_imports)]
use super::*;
/// Fills the `[tokens n][steps4*n][positions24*n]` records of a prompt.
fn fill_records(rec: &mut [u8], tokens: &[i32], cell0: usize) {
let n = tokens.len();
for (i, token) in tokens.iter().enumerate() {
let cell = cell0 + i;
rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes());
for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() {
let off = (n + i * 4 + j) * 4;
rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes());
}
for h in 0..24 {
let off = (n * 5 + i * 24 + h) * 4;
rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes());
}
}
}
impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
/// Stages the pages and records, restores the ring and records every group; publishes the completed range.
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn record_groups(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
at: (&ScalarCall<'_>, usize),
operands: (&ScalarStaged, &Rc<OriginalMtpRetainedScalarWeights<'ctx>>, &OriginalMtpEmbedding<'_, 'ctx>),
cancelled: &mut impl FnMut() -> bool,
) -> Result<DraftKvOutcome> {
let (call, first_group) = at;
let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?;
let (first, end) = (call.cell0 + first_group, call.cell0 + call.tokens.len());
let first_page = first / 4;
let (pages, changed) = OriginalMtpPrefill::prepare_pages(call.prior, end, first_page)?;
// Literal prefill records [tokens n][steps4*n][positions24*n], one upload.
let (rec_h, rec) = self.build_records(call)?;
let mut staging = vec![(rec_h, rec)];
let mut cmds = Vec::new();
cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?;
if cancelled() {
return Ok(DraftKvOutcome::Cancelled);
}
self.restore_and_upload(workspace, ring, call, &mut staging)?;
if let Some(outcome) =
self.run_groups(rows, workspace, ring, (call, operands), (rec_h, &mut cmds), cancelled)?
{
return Ok(outcome);
}
self.complete(rows, workspace, ring, call, (pages, changed), (first_page, first, end, generation), cancelled)
}
fn build_records(&self, call: &ScalarCall<'_>) -> Result<(BufferHandle, Vec<u8>)> {
let mut rec = zero_bytes(call.tokens.len() * 29 * 4)?;
fill_records(&mut rec, call.tokens, call.cell0);
let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?;
let rec_h = rb.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(rb.bytes, 0, rec.len())?;
Ok((rec_h, rec))
}
fn restore_and_upload(
&mut self,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
call: &ScalarCall<'_>,
staging: &mut Vec<(BufferHandle, Vec<u8>)>,
) -> Result<()> {
ring.execute(workspace, Vec::new())?;
ring.restore(workspace, call.prior)?;
ring.current = None;
if !call.policy.per_group_sync {
self.upload_records(staging)?;
} else {
self.upload_records(&mut Vec::new())?;
}
staging.clear();
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn run_groups(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
ctx: (
&ScalarCall<'_>,
(&ScalarStaged, &Rc<OriginalMtpRetainedScalarWeights<'ctx>>, &OriginalMtpEmbedding<'_, 'ctx>),
),
buf: (BufferHandle, &mut Vec<ScalarCommand>),
cancelled: &mut impl FnMut() -> bool,
) -> Result<Option<DraftKvOutcome>> {
let (call, operands) = ctx;
let (rec_h, cmds) = buf;
let n = call.tokens.len();
for (group, c) in (0..n).step_by(self.max_t).enumerate() {
let t = self.max_t.min(n - c);
if call.cell0 + c + t <= call.first_needed {
continue;
}
let at = (group, c, t);
if let Some(o) =
self.run_group(rows, workspace, ring, (call, operands), (at, rec_h, &mut *cmds), cancelled)?
{
return Ok(Some(o));
}
}
Ok(None)
}
#[allow(clippy::too_many_arguments)]
fn run_group(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
ctx: (
&ScalarCall<'_>,
(&ScalarStaged, &Rc<OriginalMtpRetainedScalarWeights<'ctx>>, &OriginalMtpEmbedding<'_, 'ctx>),
),
buf: ((usize, usize, usize), BufferHandle, &mut Vec<ScalarCommand>),
cancelled: &mut impl FnMut() -> bool,
) -> Result<Option<DraftKvOutcome>> {
let (call, (st, retained, embedding)) = ctx;
let (at, rec_h, cmds) = buf;
let (group, c, t) = at;
let io = self.group_io(t)?;
let mut copies = Self::group_copies(&io, rec_h, (st.rh, st.rbytes), (call.tokens.len(), c, t))?;
if self.needs_capture(t, call.policy.per_group_sync)? {
let cap = Cap { io, wh: &st.wh, eh: st.eh, t, group, policy: call.policy, ring, embedding };
self.capture_group(cmds, &cap)?;
}
if cancelled() {
self.drain_graphs(rows, workspace)?;
return Ok(Some(DraftKvOutcome::Cancelled));
}
self.submit_group(rows, workspace, ring, (call, retained), (at, cmds, &mut copies))?;
Ok(None)
}
fn needs_capture(&mut self, t: usize, per_group_sync: bool) -> Result<bool> {
let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !per_group_sync };
Ok(self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_none())
}
fn submit_group(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
ctx: (&ScalarCall<'_>, &Rc<OriginalMtpRetainedScalarWeights<'ctx>>),
run: ((usize, usize, usize), &mut Vec<ScalarCommand>, &mut [ScalarCommand; 4]),
) -> Result<()> {
let (call, retained) = ctx;
let ((group, c, t), cmds, copies) = run;
let sync = call.policy.per_group_sync;
let copies = if sync { &mut copies[3..] } else { &mut copies[..] };
let tokens = &call.tokens[c..c + t];
if let Err(primary) = self.enqueue_group(t, group, sync, retained, ring, cmds, copies, tokens, call.cell0 + c) {
let drained = self.drain_graphs(rows, workspace);
return combine(Err(primary), drained);
}
cmds.clear();
if sync {
self.drain_graphs(rows, workspace)?;
}
Ok(())
}
/// Drains the last graphs, reads the encoded pages back and publishes the completed range.
#[allow(clippy::too_many_arguments)]
fn complete(
&mut self,
rows: &mut OriginalPromptRows<'_, '_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
call: &ScalarCall<'_>,
pages: (Vec<Rc<Page>>, Vec<[Vec<u8>; 4]>),
range: (usize, usize, usize, u64),
cancelled: &mut impl FnMut() -> bool,
) -> Result<DraftKvOutcome> {
let ((pages, mut changed), (first_page, first, end, generation)) = (pages, range);
if !call.policy.per_group_sync {
self.drain_graphs(rows, workspace)?;
}
if cancelled() {
return Ok(DraftKvOutcome::Cancelled);
}
for (p, runs) in changed.iter_mut().enumerate() {
ring.read_encoded_page(first_page + p, runs)?;
}
Ok(OriginalMtpPrefill::finish(ring, pages, changed, (first, end, generation)))
}
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (2).
//! The scratch layout accessors and the kernel command emitters (`kernel`, `finite`, `q8_guard`, `quant`, `project`,
//! `gr_args`) of `OriginalMtpScalarPrefill` (STRA-338).
#[allow(unused_imports)]
use super::*;
@@ -61,35 +62,24 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
.checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)?
.qwen_address())
}
#[allow(clippy::too_many_arguments)]
/// Appends the launch of kernel `index` of module `asset` with `args` to the command list.
pub(in super::super) fn kernel(
cmds: &mut Vec<ScalarCommand>,
asset: usize,
index: usize,
grid: [u32; 3],
block: [u32; 3],
shared: u32,
shape: LaunchShape,
args: Vec<Arg>,
) -> Result<()> {
cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?;
cmds.push(ScalarCommand::Kernel { asset, index, grid, block, shared, args: Arguments::new(args)? });
cmds.push(ScalarCommand::Kernel { asset, index, shape, args: Arguments::new(args)? });
Ok(())
}
pub(in super::super) fn finite(
&self,
cmds: &mut Vec<ScalarCommand>,
data: u64,
n: usize,
_g: usize,
s: usize,
) -> Result<()> {
pub(in super::super) fn finite(&self, cmds: &mut Vec<ScalarCommand>, data: u64, n: usize, s: usize) -> Result<()> {
Self::kernel(
cmds,
2,
11,
[n.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
LaunchShape::new([n.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0),
vec![Arg::U64(data), Arg::I32(n as i32), Arg::U64(self.flag(0, s)?)],
)
}
@@ -98,16 +88,13 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
cmds: &mut Vec<ScalarCommand>,
q: u64,
rows: usize,
_g: usize,
s: usize,
) -> Result<()> {
Self::kernel(
cmds,
2,
12,
[(rows * 80).div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
LaunchShape::new([(rows * 80).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0),
vec![Arg::U64(q), Arg::I32((rows * 80) as i32), Arg::U64(self.flag(0, s)?)],
)
}
@@ -116,31 +103,26 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
cmds,
2,
0,
[(rows * 2560).div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
LaunchShape::new([(rows * 2560).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0),
vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)],
)
}
pub(in super::super) fn project(
cmds: &mut Vec<ScalarCommand>,
w: u64,
q: u64,
y: u64,
buffers: ProjectionBuffers,
rows: usize,
out: usize,
) -> Result<()> {
if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) {
return Err(Error::InvalidProjectionShape);
}
let ProjectionBuffers { weight, quantised, output } = buffers;
Self::kernel(
cmds,
2,
rows,
[out as u32, 1, 1],
[32, 4, 1],
0,
vec![Arg::U64(w), Arg::U64(q), Arg::U64(y), Arg::I32(2560), Arg::I32(out as i32)],
LaunchShape::new([out as u32, 1, 1], [32, 4, 1], 0),
vec![Arg::U64(weight), Arg::U64(quantised), Arg::U64(output), Arg::I32(2560), Arg::I32(out as i32)],
)
}
pub(in super::super) fn external(
@@ -43,12 +43,45 @@ pub(in super::super) struct Cap<'a, 'ctx> {
pub(in super::super) wh: &'a [BufferHandle; 11],
pub(in super::super) eh: BufferHandle,
pub(in super::super) t: usize,
pub(in super::super) group: usize,
pub(in super::super) policy: &'a OriginalMtpScalarPolicy,
pub(in super::super) ring: &'a MtpOriginalInt8<'ctx>,
pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'ctx>,
}
/// The staged weights, the retained weights and the embedding table every group of a prompt is recorded from.
#[derive(Clone, Copy)]
pub(in super::super) struct ScalarOperands<'a, 'ctx> {
pub(in super::super) staged: &'a ScalarStaged,
pub(in super::super) retained: &'a Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'ctx>,
}
/// Everything the groups of one prompt read: the call, the operands and the handle of the staged prompt records.
#[derive(Clone, Copy)]
pub(in super::super) struct ScalarGroupSources<'a, 'ctx> {
pub(in super::super) call: &'a ScalarCall<'a>,
pub(in super::super) operands: ScalarOperands<'a, 'ctx>,
pub(in super::super) records: BufferHandle,
}
/// Where one group of up to `max_t` prompt rows lies: its index, its first row and its row count.
#[derive(Clone, Copy)]
pub(in super::super) struct GroupSpan {
pub(in super::super) index: usize,
pub(in super::super) first_row: usize,
pub(in super::super) row_count: usize,
}
/// The prompt pages prepared before the groups ran and the cell range they publish once the stream is drained.
pub(in super::super) struct PagePublication {
pub(in super::super) pages: Vec<Rc<Page>>,
pub(in super::super) changed: Vec<[Vec<u8>; 4]>,
pub(in super::super) first_page: usize,
pub(in super::super) first: usize,
pub(in super::super) end: usize,
pub(in super::super) generation: u64,
}
/// The owners a buffer supplied from outside must not alias: the prompt rows, the batch workspace and the draft ring.
#[derive(Clone, Copy)]
pub(in super::super) struct ExternalOwners<'a, 'arena, 'loan, 'ctx> {
@@ -156,18 +156,12 @@ impl<'c> Rig<'c> {
self.ring.restore(&mut self.workspace, &prior).expect("ring reset");
let rows = self.arena.begin_rows(n).expect("rows");
let mut residual = OriginalDeviceResidual::for_probe(rows);
let old = self.standalone.record(
&mut residual,
&mut self.workspace,
&mut self.ring,
&prior,
tokens,
0,
0,
Rc::clone(&self.scalar_bank),
&self.policy,
|| false,
);
let mut cancelled = || false;
let mut run = RecordRun { workspace: &mut self.workspace, ring: &mut self.ring, cancelled: &mut cancelled };
let rows = PrefillRows { tokens, cell0: 0, first_needed: 0 };
let sources =
ScalarDraftKvSources { prior: &prior, retained: Rc::clone(&self.scalar_bank), policy: &self.policy };
let old = self.standalone.record(&mut residual, &mut run, rows, sources);
eprintln!("PREFLIGHT short n={n} standalone scalar owner: {:?}", old.as_ref().map(|_| "ok"));
matches!(old, Err(Error::InvalidQwenShape))
}
@@ -178,20 +172,14 @@ impl<'c> Rig<'c> {
let mut residual = OriginalDeviceResidual::for_probe(rows);
let prior = self.ring.empty_snapshot().expect("empty snapshot");
self.ring.restore(&mut self.workspace, &prior).expect("ring reset");
let mut cancelled = || false;
let mut run = RecordRun { workspace: &mut self.workspace, ring: &mut self.ring, cancelled: &mut cancelled };
let rows = PrefillRows { tokens, cell0: 0, first_needed: 0 };
let sources =
ScalarDraftKvSources { prior: &prior, retained: Rc::clone(&self.scalar_bank), policy: &self.policy };
let outcome = self
.drafter
.record_scalar_prefill(
&mut residual,
&mut self.workspace,
&mut self.ring,
&prior,
tokens,
0,
0,
Rc::clone(&self.scalar_bank),
&self.policy,
|| false,
)
.record_scalar_prefill(&mut residual, &mut run, rows, sources)
.unwrap_or_else(|e| panic!("n={n}: the drafter's own scalar owner refused: {e:?}"));
eprintln!("PREFLIGHT short n={n} drafter scalar owner: {}", outcome_label(&outcome));
assert!(matches!(outcome, DraftKvOutcome::Completed(_)), "n={n}");
@@ -15,7 +15,9 @@
//! No state is acknowledged from metadata: a region is only readable or
//! writable through the actual arena or the actual host owner.
use super::{OriginalSessionLayout, OriginalSessionQsaLayout, OriginalSessionSpan, OriginalSessionState};
use super::{
OriginalRingBlocks, OriginalSessionLayout, OriginalSessionQsaLayout, OriginalSessionSpan, OriginalSessionState,
};
use crate::{Context, Error, Result};
// ---- plain data and traits: no CUDA types below until `OriginalSessionLayout` (begin)
@@ -153,7 +155,7 @@ pub trait OriginalHostKv {
/// `kv_stream_reset` on a streamed layer's device map.
fn reset_stream_map(&mut self, owned: usize) -> Result<()>;
/// `kv_ring_restore` of host blocks `[begin, end)` into a ring's slots.
fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()>;
fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, blocks: OriginalRingBlocks) -> Result<()>;
}
/// Byte access to one session's state, in the runtime's vocabulary.
@@ -163,7 +165,7 @@ pub trait OriginalSessionBytes {
fn synchronize(&mut self) -> Result<()>;
fn set_ple_prev(&mut self, prev: [i32; 2]);
fn reset_stream_map(&mut self, owned: usize) -> Result<()>;
fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()>;
fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, blocks: OriginalRingBlocks) -> Result<()>;
}
/// Session lifecycle operations beyond raw bytes, supplied by the serving owner.
@@ -373,9 +375,9 @@ impl<H: OriginalHostKv> OriginalSessionBytes for OriginalConversationAccess<'_,
self.host.reset_stream_map(owned)
}
fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<()> {
fn restore_ring(&mut self, layer: OriginalKvLayer, format: i32, blocks: OriginalRingBlocks) -> Result<()> {
self.state.validate_context(self.context)?;
self.host.restore_ring(layer, format, begin, end, slots)
self.host.restore_ring(layer, format, blocks)
}
}
@@ -20,9 +20,9 @@ use crate::original_mtp_coupled::{
use crate::original_mtp_draft_head::OriginalMtpDraftHead;
use crate::original_mtp_loader::{CoupledPlan, KvPlan, OriginalMtpLoadPlan};
use crate::{
CompletedOriginalMtpDraft, Context, Error, MtpInt8Snapshot, MtpOriginalInt8, NativeHeadSelection,
OriginalMtpDrafter, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, OriginalVerifyWindow, Result,
SamplerParams,
AcceptedWindow, CompletedOriginalMtpDraft, Context, DraftOutput, DraftSampling, DraftTarget, Error,
MtpInt8Snapshot, MtpOriginalInt8, OriginalMtpDrafter, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights,
RepeatRowWindow, Result, SamplerParams,
};
use std::rc::Rc;
@@ -3,7 +3,7 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_originalmtpactor/draft_rounds.rs"]
mod draft_rounds;
#[path = "impl_originalmtpactor/impl_originalmtpactor_2.rs"]
mod impl_originalmtpactor_2;
#[path = "impl_originalmtpactor/impl_originalmtpactor_2_2.rs"]
mod impl_originalmtpactor_2_2;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl OriginalMtpActor (2).
//! The draft rounds of `OriginalMtpActor` (STRA-338): `draft`, `draft_first` and the verifier-window forms, each taking
//! the draft-round DTOs of `original_mtp_draft_round.rs`.
#[allow(unused_imports)]
use super::*;
@@ -10,20 +11,17 @@ impl<'ctx> OriginalMtpActor<'ctx> {
/// `draft(T, tokens, p, a, drafts, ...)` over a completed verifier window.
/// `max_drafts` and the coupled request come from this actor's settings.
#[allow(clippy::too_many_arguments)]
pub fn draft_from_verifier(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
accepted_row: usize,
target: DraftTarget<'_, 'ctx>,
window: AcceptedWindow<'ctx>,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
let staged = self.staged_coupled();
let coupled = staged.as_ref().map(|(p, h)| (*p, &**h));
let max_drafts = self.settings.max_drafts();
let DraftTarget { ring, prior, policy } = target;
let AcceptedWindow { window, selection, accepted_row } = window;
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_from_verifier(
ring,
prior,
@@ -39,21 +37,18 @@ impl<'ctx> OriginalMtpActor<'ctx> {
/// `draft_from_verifier` split around the host's work (`OriginalMtpDrafter::launch_from_verifier`); `after` is the
/// verifier's pending commit event.
#[allow(clippy::too_many_arguments)]
pub fn launch_draft_from_verifier(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
accepted_row: usize,
target: DraftTarget<'_, 'ctx>,
window: AcceptedWindow<'ctx>,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
after: Option<&mut crate::OriginalGpuEvent<'ctx>>,
) -> Result<()> {
let staged = self.staged_coupled();
let coupled = staged.as_ref().map(|(p, h)| (*p, &**h));
let max_drafts = self.settings.max_drafts();
let DraftTarget { ring, prior, policy } = target;
let AcceptedWindow { window, selection, accepted_row } = window;
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.launch_from_verifier(
ring,
prior,
@@ -78,20 +73,17 @@ impl<'ctx> OriginalMtpActor<'ctx> {
}
/// `draft_first(T, R_row, token, cell, ...)`: the Original repeat-row path.
#[allow(clippy::too_many_arguments)]
pub fn draft_first_from_verifier(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
rows: usize,
target: DraftTarget<'_, 'ctx>,
window: RepeatRowWindow<'ctx>,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
let staged = self.staged_coupled();
let coupled = staged.as_ref().map(|(p, h)| (*p, &**h));
let max_drafts = self.settings.max_drafts();
let DraftTarget { ring, prior, policy } = target;
let RepeatRowWindow { window, selection, rows } = window;
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_from_verifier(
ring,
prior,
@@ -106,67 +98,33 @@ impl<'ctx> OriginalMtpActor<'ctx> {
}
/// Public array form of `draft` (`drafts`/`probs` out-arguments).
#[allow(clippy::too_many_arguments)]
pub fn draft(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
accepted_row: usize,
target: DraftTarget<'_, 'ctx>,
window: AcceptedWindow<'ctx>,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
drafts: &mut [i32],
probabilities: Option<&mut [f32]>,
output: DraftOutput<'_>,
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
let staged = self.staged_coupled();
let coupled = staged.as_ref().map(|(p, h)| (*p, &**h));
let settings = self.settings;
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_public(
ring,
prior,
window,
selection,
accepted_row,
&settings,
min_probability,
policy,
coupled,
drafts,
probabilities,
)
let max_drafts = self.settings.max_drafts();
let sampling = DraftSampling { min_probability, max_drafts, coupled };
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_public(target, window, sampling, output)
}
/// Public array form of `draft_first`.
#[allow(clippy::too_many_arguments)]
pub fn draft_first(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
rows: usize,
target: DraftTarget<'_, 'ctx>,
window: RepeatRowWindow<'ctx>,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
drafts: &mut [i32],
probabilities: Option<&mut [f32]>,
output: DraftOutput<'_>,
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
let staged = self.staged_coupled();
let coupled = staged.as_ref().map(|(p, h)| (*p, &**h));
let settings = self.settings;
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_public(
ring,
prior,
window,
selection,
rows,
&settings,
min_probability,
policy,
coupled,
drafts,
probabilities,
)
let max_drafts = self.settings.max_drafts();
let sampling = DraftSampling { min_probability, max_drafts, coupled };
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_public(target, window, sampling, output)
}
/// `~MtpDrafter()`: stream drain, graphs and owners via the drafter's
@@ -200,32 +200,14 @@ impl<'ctx> OriginalMtpActor<'ctx> {
/// Scalar draft K/V prefill on the actor's own scalar owner (short prompts; see
/// `OriginalMtpDrafter::record_scalar_prefill`).
#[allow(clippy::too_many_arguments)]
pub fn record_scalar_prefill<'arena, 'loan>(
&mut self,
residual: &mut crate::OriginalDeviceResidual<'arena, 'loan, 'ctx>,
workspace: &mut crate::NativeBatchWorkspace<'ctx>,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
tokens: &[i32],
cell0: usize,
first_needed: usize,
retained: Rc<crate::OriginalMtpRetainedScalarWeights<'ctx>>,
policy: &crate::OriginalMtpScalarPolicy,
cancelled: impl FnMut() -> bool,
run: &mut crate::RecordRun<'_, 'ctx, impl FnMut() -> bool>,
rows: crate::PrefillRows<'_>,
sources: crate::ScalarDraftKvSources<'_, 'ctx>,
) -> Result<crate::DraftKvOutcome> {
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill(
residual,
workspace,
ring,
prior,
tokens,
cell0,
first_needed,
retained,
policy,
cancelled,
)
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill(residual, run, rows, sources)
}
/// Release everything the drafter bound to the verifier bank of the request that just ended (see
@@ -0,0 +1,44 @@
//! The inputs of one MTP draft round (STRA-338): the ring it writes into, the verifier window it continues from, how
//! its tokens are chosen and where the public array form puts them. The actor, the drafter and the engine adapters
//! pass these instead of a long positional argument list.
use crate::{
MtpInt8Snapshot, MtpOriginalInt8, NativeHeadSelection, OriginalMtpFullPolicy, OriginalVerifyWindow, SamplerParams,
};
/// The draft ring a round writes into, the snapshot of its prior state and the full-forward policy of the round.
pub struct DraftTarget<'a, 'ctx> {
pub ring: &'a mut MtpOriginalInt8<'ctx>,
pub prior: &'a MtpInt8Snapshot,
pub policy: &'a OriginalMtpFullPolicy,
}
/// A completed verifier window with the head selection of the same transaction and the last accepted row of the
/// window: what a regular round continues from.
pub struct AcceptedWindow<'ctx> {
pub window: OriginalVerifyWindow<'ctx>,
pub selection: NativeHeadSelection,
pub accepted_row: usize,
}
/// The single-row verifier window of the final prompt seed and the number of rows `T` the first round repeats it
/// for (the Original repeat-row path).
pub struct RepeatRowWindow<'ctx> {
pub window: OriginalVerifyWindow<'ctx>,
pub selection: NativeHeadSelection,
pub rows: usize,
}
/// How a round chooses its tokens: the probability floor, the draft cap and the coupled sampling request of the
/// actor's settings.
pub struct DraftSampling<'a> {
pub min_probability: f32,
pub max_drafts: i32,
pub coupled: Option<(SamplerParams, &'a [i32; 4096])>,
}
/// The caller's output arrays of the public array form: the draft tokens and, when wanted, their probabilities.
pub struct DraftOutput<'a> {
pub drafts: &'a mut [i32],
pub probabilities: Option<&'a mut [f32]>,
}
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::{AcceptedWindow, DraftOutput, DraftSampling, DraftTarget, RepeatRowWindow};
impl<'ctx> OriginalMtpDrafter<'ctx> {
pub(crate) fn loaded_max_t(&self) -> Result<usize> {
@@ -179,29 +180,25 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
/// Public-array adapter over the genuine existing graph executor. It NEVER
/// reads token/probability output before actual graph drain, and retains the
/// completed ring/window product in its return value for subsequent replay.
#[allow(clippy::too_many_arguments)]
pub(crate) fn draft_public(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
accepted_row: usize,
settings: &DraftSettings,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
coupled: Option<(SamplerParams, &[i32; 4096])>,
drafts: &mut [i32],
probabilities: Option<&mut [f32]>,
target: DraftTarget<'_, 'ctx>,
window: AcceptedWindow<'ctx>,
sampling: DraftSampling<'_>,
output: DraftOutput<'_>,
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
let DraftOutput { drafts, probabilities } = output;
self.validate_public_output_extent(drafts, probabilities.as_deref())?;
let DraftTarget { ring, prior, policy } = target;
let AcceptedWindow { window, selection, accepted_row } = window;
let DraftSampling { min_probability, max_drafts, coupled } = sampling;
let completion = self.draft_from_verifier(
ring,
prior,
window,
selection,
accepted_row,
settings.max_drafts(),
max_drafts,
min_probability,
policy,
coupled,
@@ -212,29 +209,25 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
/// Existing direct first-round executor makes T real synchronous D2D copies
/// of the authentic single-row verifier R, then stages T copies of its real
/// matching head token. Caller shape errors are refused BEFORE those copies.
#[allow(clippy::too_many_arguments)]
pub(crate) fn draft_first_public(
&mut self,
ring: &mut MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
window: OriginalVerifyWindow<'ctx>,
selection: NativeHeadSelection,
rows: usize,
settings: &DraftSettings,
min_probability: f32,
policy: &OriginalMtpFullPolicy,
coupled: Option<(SamplerParams, &[i32; 4096])>,
drafts: &mut [i32],
probabilities: Option<&mut [f32]>,
target: DraftTarget<'_, 'ctx>,
window: RepeatRowWindow<'ctx>,
sampling: DraftSampling<'_>,
output: DraftOutput<'_>,
) -> Result<CompletedOriginalMtpDraft<'ctx>> {
self.validate_first_public(drafts, probabilities.as_deref(), rows)?;
let DraftOutput { drafts, probabilities } = output;
self.validate_first_public(drafts, probabilities.as_deref(), window.rows)?;
let DraftTarget { ring, prior, policy } = target;
let RepeatRowWindow { window, selection, rows } = window;
let DraftSampling { min_probability, max_drafts, coupled } = sampling;
let completion = self.draft_first_from_verifier(
ring,
prior,
window,
selection,
rows,
settings.max_drafts(),
max_drafts,
min_probability,
policy,
coupled,
@@ -20,6 +20,14 @@ pub use conversation::{
};
use std::rc::Rc;
/// The host blocks `[begin, end)` of a drafter ring and the number of ring slots they land in (`block % slots`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct OriginalRingBlocks {
pub begin: i64,
pub end: i64,
pub slots: i64,
}
const ALIGN: usize = 256;
const PLE_HIST: usize = 9;
const PLE_DIM: usize = 10240;
@@ -11,11 +11,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
stage: OriginalVerifyGdnStage,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
begin: usize,
end: usize,
rows: std::ops::Range<usize>,
) -> Result<()> {
self.validate_context(self.physical.context)?;
let op = self.stage_operands(layer, begin, end)?;
let op = self.stage_operands(layer, rows.start, rows.end)?;
let mut commands = self.stage_commands(&op)?;
if chain::flags().ab && matches!(stage, OriginalVerifyGdnStage::AlphaBeta) {
return self.submit_launches(capture, vec![self.stage_ab_launch(&op)?]);
@@ -20,8 +20,7 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
OriginalVerifyGdnStage::AlphaBeta,
self.capture,
g,
rows.begin,
rows.end,
rows.begin..rows.end,
)?;
self.capture.side_end(0)?;
self.capture.side_fork(1)?;
@@ -50,8 +50,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
OriginalVerifyGdnStage::Conv,
self.capture,
layer,
rows.begin,
rows.end,
rows.begin..rows.end,
)
}
fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> {
@@ -62,8 +61,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
OriginalVerifyGdnStage::AlphaBeta,
self.capture,
layer,
rows.begin,
rows.end,
rows.begin..rows.end,
)
}
fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> {
@@ -76,8 +74,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
OriginalVerifyGdnStage::Recurrence,
self.capture,
layer,
rows.begin,
rows.end,
rows.begin..rows.end,
)
}
fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> {
@@ -95,7 +92,7 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
}
fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()> {
let base = &self.resources.base;
base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin, rows.end)
base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin..rows.end)
}
fn qsa_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> {
self.plan_launch(|p| p.qsa_q_path(q, rows, batched))
@@ -118,10 +118,9 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
begin: usize,
end: usize,
rows: std::ops::Range<usize>,
) -> Result<()> {
self.capture_append(journal, capture, LayerRows { layer, rows: begin..end }, false)
self.capture_append(journal, capture, LayerRows { layer, rows }, false)
}
/// Records the row appends of `target` (`commit`: the steps come from the accepted-position words).
pub(super) fn capture_append(
+4 -1
View File
@@ -47,7 +47,7 @@ pub use original_prefill_layout::{
};
pub use original_session_state::{
OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts,
OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts,
OriginalRegion, OriginalRingBlocks, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts,
};
pub use qsa_selected_kv::{QsaKvMisses, QsaSelectedKvProducts, QsaSelectedKvWorkspace};
pub use qwen_dispatch::fixed_operands::{
@@ -199,6 +199,7 @@ pub use original_expert_stager::{
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use mtp_dense_kv::{
OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill,
ScalarDraftKvSources,
};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use native_head::{
@@ -216,6 +217,8 @@ pub use original_file_expert_source::{
pub use original_gpu_schedule::OriginalStreamDrained;
pub use original_gpu_schedule::capture_timing as original_capture_timing;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use original_mtp_draft_round::{AcceptedWindow, DraftOutput, DraftSampling, DraftTarget, RepeatRowWindow};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use original_verify::chain::set_down_override as set_chain_down_override;
pub use original_verify::sm120::set_overrides as set_sm120_overrides;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
@@ -139,10 +139,9 @@ impl<'ctx> Replay<'ctx> {
&mut self,
mtp: &mut Option<Mtp<'ctx>>,
reset_snapshot: &mut Option<MtpInt8Snapshot>,
window: (NativeHeadSelection, Option<OriginalVerifyWindow<'ctx>>),
(selection, completed): (NativeHeadSelection, Option<OriginalVerifyWindow<'ctx>>),
(t, keep): (usize, usize),
) {
let (selection, completed) = window;
let (Some((ring, actor)), Some(done)) = (mtp.as_mut(), completed) else { return };
actor.set_prompt_len(1);
actor.set_max_drafts(3);
@@ -154,7 +153,9 @@ impl<'ctx> Replay<'ctx> {
keep - 1,
prior.next_position()
);
let drafted = actor.draft_from_verifier(ring, &prior, done, selection, keep - 1, 0.0, &full_policy());
let window = leleka_cuda_driver::AcceptedWindow { window: done, selection, accepted_row: keep - 1 };
let target = leleka_cuda_driver::DraftTarget { ring, prior: &prior, policy: &full_policy() };
let drafted = actor.draft_from_verifier(target, window, 0.0);
if let Some(d) =
step!(format!("actor.draft_from_verifier(t={t}, a={}) in {:?}", keep - 1, started.elapsed()), drafted)
{
@@ -1,5 +1,6 @@
//! The single-token generation step loop.
use super::*;
use crate::qwen_forward::executor::{StepCaches, StepRequest};
pub(super) struct Generation<'a, 'context, 'driver, C: Clock = SystemClock> {
pub(super) execution: EvaluationExecution,
@@ -68,14 +69,10 @@ impl<C: Clock> Generation<'_, '_, '_, C> {
let token = TokenId::new(u64::from(token), vocabulary).map_err(|_| invalid("native token invalid"))?;
let position = native_position(self.binding.input_constants(), self.context_tokens, position)?;
let forwarded = QwenForward::step_cached(
self.binding,
token,
position,
StepRequest { binding: self.binding, token, position },
self.session,
self.output,
self.kar_cache.as_deref_mut(),
self.moe_cache,
self.dense_cache,
StepCaches { kar: self.kar_cache.as_deref_mut(), moe: Some(self.moe_cache), dense: Some(self.dense_cache) },
);
let token = forwarded.map_err(|failure| self.forward_failure(failure, position))?;
if self.cancelled() {
@@ -104,14 +101,10 @@ impl<C: Clock> Generation<'_, '_, '_, C> {
.map_err(|e| self.mtp_error(e))?;
let position = native_position(self.binding.input_constants(), self.context_tokens, position)?;
let result = QwenForward::step_for_mtp_cached(
self.binding,
token,
position,
StepRequest { binding: self.binding, token, position },
self.session,
self.output,
self.kar_cache.as_deref_mut(),
Some(self.moe_cache),
Some(self.dense_cache),
StepCaches { kar: self.kar_cache.as_deref_mut(), moe: Some(self.moe_cache), dense: Some(self.dense_cache) },
);
let product = result.map_err(|e| self.mtp_error(e))?;
if self.cancelled() {
@@ -1,5 +1,6 @@
//! The MTP speculative generation loop.
use super::*;
use crate::qwen_forward::mtp::KnownNext;
mod tile_parts;
use tile_parts::{begin_decoder, commit_window, emit_token_text, prefill_tiles, verified_window};
@@ -50,7 +51,9 @@ fn warm_retained_edge<C: Clock>(
}
let (vocabulary, _) = mtp_vocabulary(run)?;
let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?;
decoder.warm_retained(run.binding, run.session, product, next, run.moe_cache).map_err(|e| run.mtp_error(e))
decoder
.warm_retained(run.binding, run.session, KnownNext { source: product, next_token: next }, run.moe_cache)
.map_err(|e| run.mtp_error(e))
}
/// What one iteration of the decode loop decided.
@@ -2,7 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::mtp_decode::MtpVerifiedWindow;
use crate::qwen_forward::mtp_decode::{MtpVerifiedWindow, MtpWindowRequest, WindowOwners};
/// The decoder to continue with, the product of the retained prefix, the tokens reused and the committed tokens so far.
pub(super) type Resumed = (MtpDecoder, Option<TargetStepProduct>, usize, Vec<u32>);
@@ -134,23 +134,21 @@ pub(super) fn verified_window<C: Clock>(
let cancel = run.cancel;
let shared = run.shared;
let sink = run.sink;
let request = MtpWindowRequest { binding: run.binding, source: product, spec };
let owners = WindowOwners {
target: run.session,
output: run.output,
kar_cache: run.kar_cache.as_deref_mut(),
cache: run.moe_cache,
dense_cache: run.dense_cache,
};
decoder
.window(
run.binding,
product,
run.session,
run.output,
run.kar_cache.as_deref_mut(),
run.moe_cache,
run.dense_cache,
spec,
|| {
cancel.load(Ordering::Acquire)
|| shared.shutdown.load(Ordering::Acquire)
|| sink.is_closed()
|| run.clock.since(start) > GENERATION_TIMEOUT
},
)
.window(request, owners, || {
cancel.load(Ordering::Acquire)
|| shared.shutdown.load(Ordering::Acquire)
|| sink.is_closed()
|| run.clock.since(start) > GENERATION_TIMEOUT
})
.map_err(|e| window_failure(run, e, start))
}
@@ -12,8 +12,8 @@ use super::model::{
StateRegion, StreamMap,
};
use leleka_cuda_driver::{
OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, OriginalSessionBytes,
OriginalSessionControl, OriginalSessionFacts,
OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, OriginalRingBlocks,
OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts,
};
fn layer(l: KvLayer) -> OriginalKvLayer {
@@ -198,7 +198,8 @@ impl<T: OriginalSessionBytes> StateMemory for OriginalDevice<T> {
}
fn restore_ring(&mut self, l: KvLayer, format: i32, blocks: RingBlocks) -> Result<(), String> {
self.session.restore_ring(layer(l), format, blocks.begin, blocks.end, blocks.slots).map_err(text)
let blocks = OriginalRingBlocks { begin: blocks.begin, end: blocks.end, slots: blocks.slots };
self.session.restore_ring(layer(l), format, blocks).map_err(text)
}
}
@@ -1,5 +1,6 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners as LoadedTarget;
use std::env;
#[path = "combined_changed_boundary_proof/rig.rs"]
pub(super) mod rig;
@@ -32,16 +33,17 @@ fn pinned_single_load_layer0_and_window_boundaries() {
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL));
// Both helpers use genuine fresh target owners on the one admitted
// binding/context/cache. No second source load or CUDA context is created.
// Both helpers use genuine fresh target owners on the one admitted binding/context/cache: no second load.
let layer0 = owners.run(&binding, &context, QwenForward::test_layer0_pair_on_loaded);
let window = matches!(&layer0, Ok(Ok(_)))
.then(|| owners.run(&binding, &context, QwenForward::test_window_boundaries_on_loaded));
let window = matches!(&layer0, Ok(Ok(_))).then(|| {
owners.run(&binding, &context, |binding, session, output, kar, moe, dense| {
QwenForward::test_window_boundaries_on_loaded(LoadedTarget { binding, session, output, kar, moe, dense })
})
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
// Preserve the phase failure after every teardown attempt; a later
// cleanup assertion must not obscure its original diagnostic cause.
// Preserve the phase failure after every teardown attempt; a later cleanup must not obscure its cause.
let report = unwrap_phase(layer0, "same-source layer0 diagnostic refused");
let window = unwrap_phase(window.expect("window proof was not admitted"), "changed window proof refused");
teardown.assert_clean();
@@ -49,6 +51,11 @@ fn pinned_single_load_layer0_and_window_boundaries() {
.write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR"))
.expect("exclusive bounded layer0 diagnostic write failed");
window.assert_success_and_print();
print_layer0_diagnostic_complete();
}
/// The closing line of the combined proof: what the layer0 diagnostic did and did not claim.
fn print_layer0_diagnostic_complete() {
eprintln!(
"layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled \
final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false \
@@ -2,6 +2,8 @@
//! Forced inputs are public IDs; no expected model tensors or invented state.
use super::combined_changed_boundary_proof::rig::Owners;
use super::*;
use crate::qwen_forward::mtp::KnownNext;
use crate::qwen_forward::mtp_decode::DraftHeadOwners;
use crate::qwen_forward::{mtp::PrefixDraftSnapshot, session::ResetReplaySnapshot};
const PREFIX: [u32; 3] = [0, 1, 0];
@@ -94,8 +96,9 @@ fn reference_pass<'ctx, 'driver>(
};
if let Some(&next) = COMPLETE.get(position + 1) {
let next = TokenId::new(u64::from(next), vocabulary).expect("reference known-next refused");
let edge = KnownNext { source: &product, next_token: next };
decoder
.warm(run.binding, run.session, &product, next, run.output, run.moe_cache)
.warm(run.binding, run.session, edge, DraftHeadOwners { output: run.output, cache: run.moe_cache })
.expect("reference actual full draft step failed");
}
latest = Some(product);
@@ -1,6 +1,7 @@
//! The four PUBLIC candidate proofs: they differ in the caches they load, in what they generate and in what
//! they conclude; the owner, the teardown and the artifacts are shared (`native_down_pair_run.rs`).
use super::*;
use crate::qwen_forward::moe_expert::LoadedArms;
use crate::qwen_forward::moe_weight_cache::LearnedMainWitness;
use fivecase_runtime::FiveCaseReport;
@@ -107,15 +108,16 @@ impl Proof for DirectDown {
// Only the changed direct Down proof shares this model load.
// The unchanged, previously qualified GDN helper is not repeated.
let mut session = QwenSession::for_binding_on_shared_device(run.binding, Rc::clone(run.context));
let down = QwenForward::test_direct_down_on_loaded(
run.binding,
run.context,
&mut session,
&mut owner.kar,
&mut owner.moe,
&owner.dense,
)
.expect("actual original-first direct Down packet proof failed");
let arms = LoadedArms {
binding: run.binding,
context: run.context,
session: &mut session,
kar: &mut owner.kar,
cache: &mut owner.moe,
dense: &owner.dense,
};
let down = QwenForward::test_direct_down_on_loaded(arms)
.expect("actual original-first direct Down packet proof failed");
drop(session);
let execution = EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr;
let arm = owner.armed_inputs(run).arm(&run.case.req, &run.case.ids, execution, DIRECT_PHASE);
@@ -1,6 +1,7 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::combined_changed_boundary_proof::rig::{DEVICE_BUDGET, Owners, bind_pinned, require_opt_in};
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use std::{env, panic::resume_unwind};
fn required_path(name: &str) -> PathBuf {
@@ -67,7 +68,9 @@ fn pinned_single_load_native_resident_mmq_model_numeric() {
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL));
let numerical = owners.run(&binding, &context, QwenForward::test_native_mmq_on_loaded);
let numerical = owners.run(&binding, &context, |binding, session, output, kar, moe, dense| {
QwenForward::test_native_mmq_on_loaded(LoadedTargetOwners { binding, session, output, kar, moe, dense })
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
@@ -1,6 +1,7 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::combined_changed_boundary_proof::rig::{DEVICE_BUDGET, MOE_REFUSAL, Owners, bind_pinned, require_opt_in};
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use std::{env, panic::resume_unwind};
fn required_path(name: &str) -> PathBuf {
@@ -17,7 +18,9 @@ fn pinned_single_load_resident_mmq_model_numeric() {
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let mut owners = Owners::load(&binding, context.as_ref(), (MoeWeightCache::new_mmq, MOE_REFUSAL));
let numerical = owners.run(&binding, &context, QwenForward::test_mmq_on_loaded);
let numerical = owners.run(&binding, &context, |binding, session, output, kar, moe, dense| {
QwenForward::test_mmq_on_loaded(LoadedTargetOwners { binding, session, output, kar, moe, dense })
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
@@ -10,6 +10,8 @@ use std::{
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
use crate::qwen_forward::oracle_capture::Caches;
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path")
}
@@ -17,13 +19,12 @@ fn required_path(name: &str) -> PathBuf {
/// Capture of two tokens on a fresh owner, then the observation cleanup.
fn capture_two<'d>(binding: &ModelBinding, context: &Rc<leleka_cuda_driver::Context<'d>>, owners: &mut Owners<'d>) {
let mut captured = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let caches = Caches { cache: &mut owners.kar, moe: &mut owners.moe, dense: &owners.dense };
let capture = crate::qwen_forward::oracle_capture::check_on_loaded(
binding,
&mut captured,
&owners.output,
&mut owners.kar,
&mut owners.moe,
&owners.dense,
caches,
required_path("LELEKA_STRA169_CAPTURE_DIR"),
);
let disabled = crate::qwen_forward::oracle_capture::disable(&owners.output);
@@ -0,0 +1,23 @@
//! The expert a projection, a cache fill or a loan refers to.
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertSelection, MoeExpertWeights};
/// One expert (a routed slot or the shared expert) of validated expert weights, under the binding that admitted
/// them. The three always travel together: weights are only meaningful for their binding, and the selection says
/// which expert of those weights is meant.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct BoundExpert<'a> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) weights: &'a MoeExpertWeights,
pub(in crate::qwen_forward) selection: MoeExpertSelection,
}
impl<'a> BoundExpert<'a> {
/// The routed expert in `slot` of the weights admitted under `binding`.
pub(in crate::qwen_forward) fn routed(
binding: &'a ModelBinding,
weights: &'a MoeExpertWeights,
slot: usize,
) -> Self {
Self { binding, weights, selection: MoeExpertSelection::Routed { slot } }
}
}
@@ -24,6 +24,15 @@ enum Slot<'ctx> {
InUse,
}
/// Which completed slot of the ephemeral owner is loaned and which member of the routed source it must equal,
/// under which model binding.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct TripletLoanRequest<'binding> {
pub(in crate::qwen_forward) binding: &'binding ModelBinding,
pub(in crate::qwen_forward) member: usize,
pub(in crate::qwen_forward) slot: usize,
}
pub(in crate::qwen_forward) struct EphemeralRoutedOwner<'ctx> {
binding: BindingIdentity,
context: &'ctx Context<'ctx>,
@@ -263,16 +263,15 @@ impl<'ctx> MappedStage<'ctx> {
}
pub(super) fn with_triplet<'source, 'group, T>(
&mut self,
slot: usize,
binding: &ModelBinding,
request: TripletLoanRequest<'_>,
source: &mut MoeRoutedSourceScope<'source, 'group>,
member: usize,
consume: impl FnOnce(
[&DeviceBuffer<'ctx>; 3],
[MoeWeightDescriptor; 3],
&mut MoeRoutedSourceScope<'source, 'group>,
) -> Result<T>,
) -> Result<T> {
let TripletLoanRequest { binding, member, slot } = request;
self.validate(binding, slot)?;
let fresh = EphemeralRoutedOwner::keys(binding, source, member)?;
let (keys, buffers, scratch) = self.loan_completed(slot, &fresh)?;
@@ -233,10 +233,8 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
/// buffers are temporary execution owners, never adaptive cache hits.
pub(in crate::qwen_forward) fn with_triplet<'source, 'group, T>(
&mut self,
slot: usize,
binding: &ModelBinding,
request: TripletLoanRequest<'_>,
source: &mut MoeRoutedSourceScope<'source, 'group>,
member: usize,
cancel_observed: &Cell<bool>,
consume: impl FnOnce(
[&DeviceBuffer<'ctx>; 3],
@@ -245,9 +243,9 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
) -> Result<T>,
) -> Result<T> {
let result = if let Some(mapped) = &mut self.mapped {
mapped.with_triplet(slot, binding, source, member, consume)
mapped.with_triplet(request, source, consume)
} else {
self.with_triplet_inner(slot, binding, source, member, consume)
self.with_triplet_inner(request, source, consume)
};
#[cfg(test)]
if self.mapped.is_some() && result.is_ok() {
@@ -30,16 +30,15 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
}
pub(in super::super) fn with_triplet_inner<'source, 'group, T>(
&mut self,
slot: usize,
binding: &ModelBinding,
request: TripletLoanRequest<'_>,
source: &mut MoeRoutedSourceScope<'source, 'group>,
member: usize,
consume: impl FnOnce(
[&DeviceBuffer<'ctx>; 3],
[MoeWeightDescriptor; 3],
&mut MoeRoutedSourceScope<'source, 'group>,
) -> Result<T>,
) -> Result<T> {
let TripletLoanRequest { binding, member, slot } = request;
self.validate_slot(binding, slot)?;
let fresh = Self::keys(binding, source, member)?;
let (keys, buffers) = self.loan_completed(slot, &fresh)?;
@@ -20,6 +20,13 @@ enum WeightSource {
Pinned,
RtDirectory,
}
/// The native MTP head and the optional gathered draft-vocabulary head that the full forward chooses between.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct MtpHeadSources<'a, 'ctx> {
pub(in crate::qwen_forward) native: &'a OriginalMtpNativeHead<'ctx>,
pub(in crate::qwen_forward) draft: Option<&'a leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
}
/// Clones share the same device allocations (`Rc`); no buffer is duplicated.
#[derive(Clone)]
pub(in crate::qwen_forward) struct RetainedOriginalMtpWeights<'ctx> {
@@ -186,20 +186,20 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
/// Exact full MTP forward role order. The caller lends the model-affine
/// native-head allocation from `OriginalNativeOutput::mtp_head`; this
/// cache never fabricates a replacement head buffer or dispatch profile.
#[allow(clippy::too_many_arguments)]
/// The id vocabulary is the native head's own vocabulary.
pub(in crate::qwen_forward) fn full_forward_weights(
&self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
prefix: Rc<leleka_cuda_driver::OriginalMtpRetainedPrefix<'ctx>>,
head: &OriginalMtpNativeHead<'ctx>,
id_vocab: usize,
draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
heads: MtpHeadSources<'_, 'ctx>,
) -> Result<Rc<leleka_cuda_driver::OriginalMtpRetainedFullWeights<'ctx>>> {
let head = heads.native;
let id_vocab = head.vocabulary();
self.admit_full_forward(binding, context, head, id_vocab)?;
let roles = self.acquire_roles(binding, context, FULL_FORWARD_ROLES)?;
let experts = self.expert_bank(binding, context)?;
let (head_weights, head_rows, subset) = Self::select_head(head, draft_head);
let (head_weights, head_rows, subset) = Self::select_head(heads);
let weights = FullWeights::retain(
context,
prefix,
@@ -231,13 +231,10 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
}
Ok(())
}
fn select_head(
head: &OriginalMtpNativeHead<'ctx>,
draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
) -> HeadBinding<'ctx> {
match draft_head {
fn select_head(heads: MtpHeadSources<'_, 'ctx>) -> HeadBinding<'ctx> {
match heads.draft {
Some(draft) => (draft.rows(), draft.count(), Some(draft.subset_pair())),
None => (head.weights(), head.vocabulary(), None),
None => (heads.native.weights(), heads.native.vocabulary(), None),
}
}
pub(in crate::qwen_forward) fn metadata_bytes(&self) -> Result<usize> {
@@ -1,24 +1,38 @@
//! Pure metadata/budget proof; never constructs a ModelBinding or device owner.
use super::*;
fn shared_descriptor(
layer: u32,
/// Shape, quantisation kind and byte size of one shared-expert weight role, independent of the layer.
struct SharedRoleShape {
role: u8,
raw_kind: u32,
columns: usize,
rows: usize,
bytes: usize,
) -> MoeWeightDescriptor {
}
fn shared_descriptor(layer: u32, shape: SharedRoleShape) -> MoeWeightDescriptor {
let SharedRoleShape { role, raw_kind, columns, rows, bytes } = shape;
MoeWeightDescriptor { layer, expert: None, role, raw_kind, columns, rows, bytes }
}
fn descriptor_set() -> Vec<[MoeWeightDescriptor; 4]> {
(0..48u32)
.map(|layer| {
[
shared_descriptor(layer, 0, 14, 2560, 640, 1_344_000),
shared_descriptor(layer, 1, 14, 2560, 640, 1_344_000),
shared_descriptor(layer, 2, 8, 640, 2560, 1_740_800),
shared_descriptor(layer, 3, 30, 2560, 1, 5120),
shared_descriptor(
layer,
SharedRoleShape { role: 0, raw_kind: 14, columns: 2560, rows: 640, bytes: 1_344_000 },
),
shared_descriptor(
layer,
SharedRoleShape { role: 1, raw_kind: 14, columns: 2560, rows: 640, bytes: 1_344_000 },
),
shared_descriptor(
layer,
SharedRoleShape { role: 2, raw_kind: 8, columns: 640, rows: 2560, bytes: 1_740_800 },
),
shared_descriptor(
layer,
SharedRoleShape { role: 3, raw_kind: 30, columns: 2560, rows: 1, bytes: 5120 },
),
]
})
.collect()
@@ -40,6 +40,7 @@ pub(crate) struct DenseCacheCounters {
}
/// What a resident-key selection scores: the candidate prior whose keys are searched, the index query vector and the
/// token position being selected for.
#[derive(Clone, Copy)]
pub(super) struct QsaSelectionRequest<'a> {
pub(super) candidate: &'a QsaPrior,
pub(super) index_query: &'a [f32],
@@ -144,7 +144,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
.ok_or(Error::IdentityMismatch)?
.try_borrow_mut()
.map_err(|_| Error::IdentityMismatch)?
.select(&self.binding, context, request.candidate, request.index_query, request.position)
.select(&self.binding, context, request)
}
pub(in super::super::super) fn gdn_input<'slot, 'source>(
&'slot self,
@@ -25,6 +25,7 @@ type StepCoreResult = (Option<TokenId>, Option<Box<[f32]>>);
pub(in crate::qwen_forward) mod original_prompt;
#[path = "executor_prefill_chunk.rs"]
mod prefill_chunk;
pub(in crate::qwen_forward) use prefill_chunk::mtp_window::{VerificationChunk, VerificationSource, WindowCaches};
/// MTP input from one fully committed target step. No public constructor.
pub(crate) struct TargetStepProduct {
@@ -80,14 +81,19 @@ mod impl_prefillstepproduct;
#[allow(unused_imports)]
use impl_prefillstepproduct::diagnose;
mod impl_qwenforward;
mod read_layer_attention_fn;
mod step_layer_fns;
mod read_layer_attention;
mod step_layers;
mod step_request;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(unused_imports)]
use read_layer_attention_fn::prepare_layer_attention_micro;
use read_layer_attention::LayerEntry;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(unused_imports)]
use read_layer_attention_fn::read_layer_attention;
use read_layer_attention::prepare_layer_attention_micro;
#[allow(unused_imports)]
use read_layer_attention_fn::validate_descriptors;
use read_layer_attention::read_layer_attention;
#[allow(unused_imports)]
use read_layer_attention_fn::validate_layer_plan;
use read_layer_attention::validate_descriptors;
#[allow(unused_imports)]
use read_layer_attention::validate_layer_plan;
pub(crate) use step_request::{StepCaches, StepPurpose, StepRequest};
@@ -3,9 +3,9 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_qwenforward/impl_qwenforward_2.rs"]
mod impl_qwenforward_2;
#[path = "impl_qwenforward/impl_qwenforward_2_2.rs"]
mod impl_qwenforward_2_2;
#[path = "impl_qwenforward/impl_qwenforward_3.rs"]
mod impl_qwenforward_3;
#[path = "impl_qwenforward/step_core.rs"]
mod step_core;
#[path = "impl_qwenforward/step_entries.rs"]
mod step_entries;
@@ -1,178 +0,0 @@
//! Moved out of the parent module by STRA-338: impl QwenForward.
#[allow(unused_imports)]
use super::*;
impl QwenForward {
pub(crate) fn step(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
) -> Result<TokenId> {
Self::step_inner(binding, token, pos, session, None, None)
}
/// Complete-forward entry retains the loaded output head across tokens.
/// Unsupported stages abort the same transaction without state publication.
pub(crate) fn step_with_output(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
) -> Result<TokenId> {
Self::step_inner(binding, token, pos, session, Some(output), None)
}
/// Explicit loaded KAR provider. Cache lifetime is borrowed from the
/// caller's stable owner-thread Context; it is never self-referential.
pub(crate) fn step_with_kar_ple_output(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
cache: &mut KarPleCache<'_>,
) -> Result<TokenId> {
Self::step_inner(binding, token, pos, session, Some(output), Some(cache))
}
pub(in super::super) fn step_inner(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: Option<&OutputStage<'_, '_>>,
kar_cache: Option<&mut KarPleCache<'_>>,
) -> Result<TokenId> {
Self::step_core(binding, token, pos, session, output, kar_cache, None, None, false, false)
.and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch))
}
/// Retain the pre-output four-stream residual only for explicit MTP use.
/// Native/KAR callers above keep their original allocation and math path.
pub(crate) fn step_for_mtp(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
) -> Result<TargetStepProduct> {
Self::step_for_mtp_cached(binding, token, pos, session, output, kar_cache, None, None)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn step_cached(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
moe_cache: &mut MoeWeightCache<'_>,
dense_cache: &DenseWeightCache<'_>,
) -> Result<TokenId> {
Self::step_core(
binding,
token,
pos,
session,
Some(output),
kar_cache,
Some(moe_cache),
Some(dense_cache),
false,
false,
)
.and_then(|(token, _)| token.ok_or(Error::IdentityMismatch))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn step_for_mtp_cached(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
moe_cache: Option<&mut MoeWeightCache<'_>>,
dense_cache: Option<&DenseWeightCache<'_>>,
) -> Result<TargetStepProduct> {
let (predicted, streams) = Self::step_core(
binding,
token,
pos,
session,
Some(output),
kar_cache,
moe_cache,
dense_cache,
true,
false,
)?;
target_product(binding, token, pos, session, predicted, streams)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn prefill_for_mtp_cached(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
moe_cache: &mut MoeWeightCache<'_>,
dense_cache: &DenseWeightCache<'_>,
) -> Result<PrefillStepProduct> {
let (predicted, streams) = Self::step_core(
binding,
token,
pos,
session,
Some(output),
kar_cache,
Some(moe_cache),
Some(dense_cache),
true,
true,
)?;
if predicted.is_some() {
return Err(Error::IdentityMismatch);
}
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()?,
})
}
@@ -1,6 +1,6 @@
//! Moved out of the parent module by STRA-338: impl QwenForward (2).
//! The shared body of every forward step: one completed transaction over the input row, the layers and the head.
use super::super::step_layer_fns::{
use super::super::step_layers::{
LayerCtx, capture_streams, finish_step, prepare_step_caches, run_layers, stage_input_row,
};
#[allow(unused_imports)]
@@ -9,19 +9,15 @@ 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,
token: TokenId,
pos: Position,
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: Option<&OutputStage<'_, '_>>,
kar_cache: Option<&mut KarPleCache<'_>>,
mut moe_cache: Option<&mut MoeWeightCache<'_>>,
dense_cache: Option<&DenseWeightCache<'_>>,
capture_mtp: bool,
prefill_only: bool,
caches: StepCaches<'_, '_, '_, '_>,
purpose: StepPurpose,
) -> Result<StepCoreResult> {
let StepRequest { binding, token, position: pos } = request;
let StepCaches { kar: kar_cache, moe: mut moe_cache, dense: dense_cache } = caches;
let mut streams = None;
let ctx = LayerCtx { binding, token, pos, dense: dense_cache };
let predicted = session.transact_completion(token, pos, &binding.identity(), |txn| {
@@ -29,8 +25,8 @@ impl QwenForward {
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 {
let predicted = finish_step(&ctx, txn, output, &final_residual, purpose.is_prefill_only())?;
if purpose.retains_streams() {
streams = Some(capture_streams(&final_residual)?);
}
Ok(predicted)
@@ -0,0 +1,127 @@
//! The forward-step entry points of QwenForward: greedy, KAR, MTP target and MTP prefill steps.
#[allow(unused_imports)]
use super::*;
impl QwenForward {
pub(crate) fn step(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
) -> Result<TokenId> {
Self::step_inner(StepRequest { binding, token, position: pos }, session, None, None)
}
/// Complete-forward entry retains the loaded output head across tokens.
/// Unsupported stages abort the same transaction without state publication.
pub(crate) fn step_with_output(
binding: &ModelBinding,
token: TokenId,
pos: Position,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
) -> Result<TokenId> {
Self::step_inner(StepRequest { binding, token, position: pos }, session, Some(output), None)
}
/// Explicit loaded KAR provider. Cache lifetime is borrowed from the
/// caller's stable owner-thread Context; it is never self-referential.
pub(crate) fn step_with_kar_ple_output(
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
cache: &mut KarPleCache<'_>,
) -> Result<TokenId> {
Self::step_inner(request, session, Some(output), Some(cache))
}
pub(in super::super) fn step_inner(
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: Option<&OutputStage<'_, '_>>,
kar_cache: Option<&mut KarPleCache<'_>>,
) -> Result<TokenId> {
let caches = StepCaches { kar: kar_cache, moe: None, dense: None };
Self::step_core(request, session, output, caches, StepPurpose::Greedy)
.and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch))
}
/// Retain the pre-output four-stream residual only for explicit MTP use.
/// Native/KAR callers above keep their original allocation and math path.
pub(crate) fn step_for_mtp(
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
) -> Result<TargetStepProduct> {
let caches = StepCaches { kar: kar_cache, moe: None, dense: None };
Self::step_for_mtp_cached(request, session, output, caches)
}
/// A complete greedy step through the supplied weight caches.
pub(crate) fn step_cached(
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
caches: StepCaches<'_, '_, '_, '_>,
) -> Result<TokenId> {
Self::step_core(request, session, Some(output), caches, StepPurpose::Greedy)
.and_then(|(token, _)| token.ok_or(Error::IdentityMismatch))
}
/// A complete step through the supplied weight caches that retains the MTP target product.
pub(crate) fn step_for_mtp_cached(
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
caches: StepCaches<'_, '_, '_, '_>,
) -> Result<TargetStepProduct> {
let (predicted, streams) = Self::step_core(request, session, Some(output), caches, StepPurpose::MtpTarget)?;
target_product(request, session, predicted, streams)
}
/// A known-next prefill step through the supplied weight caches that retains the MTP prefill product.
pub(crate) fn prefill_for_mtp_cached(
request: StepRequest<'_>,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
caches: StepCaches<'_, '_, '_, '_>,
) -> Result<PrefillStepProduct> {
let (predicted, streams) = Self::step_core(request, session, Some(output), caches, StepPurpose::MtpPrefill)?;
if predicted.is_some() {
return Err(Error::IdentityMismatch);
}
prefill_product(request, session, streams)
}
}
fn target_product(
request: StepRequest<'_>,
session: &QwenSession<'_>,
predicted: Option<TokenId>,
streams: Option<Box<[f32]>>,
) -> Result<TargetStepProduct> {
Ok(TargetStepProduct {
binding: request.binding.identity(),
token: request.token,
position: request.position,
predicted: predicted.ok_or(Error::IdentityMismatch)?,
streams: streams.ok_or(Error::IdentityMismatch)?,
origin: session.target_origin()?,
})
}
fn prefill_product(
request: StepRequest<'_>,
session: &QwenSession<'_>,
streams: Option<Box<[f32]>>,
) -> Result<PrefillStepProduct> {
Ok(PrefillStepProduct {
binding: request.binding.identity(),
token: request.token,
position: request.position,
streams: streams.ok_or(Error::IdentityMismatch)?,
origin: session.target_origin()?,
})
}
@@ -53,18 +53,26 @@ fn read_layer_one<'cache, 'ctx>(
GrStage::read_attention_after_ple(binding, layer, &ple, txn, cache)
}
/// A layer about to be read together with the residual left by the layer before it (none for the first layer).
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[derive(Clone, Copy)]
pub(super) struct LayerEntry<'a> {
pub(super) layer: LayerId,
pub(super) previous: Option<&'a InjectedResidual>,
}
/// 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.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) fn prepare_layer_attention_micro(
binding: &ModelBinding,
layer: LayerId,
previous: Option<&InjectedResidual>,
entry: LayerEntry<'_>,
txn: &mut QwenStepTxn,
cache: &DenseWeightCache<'_>,
ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>,
) -> Result<super::super::gr::GrMicroInput> {
let LayerEntry { layer, previous } = entry;
match layer.get() {
0 => {
if previous.is_some() {
@@ -72,7 +80,7 @@ pub(super) fn prepare_layer_attention_micro(
}
GrStage::prepare_micro_initial(binding, layer, txn)
}
1 => prepare_layer_one_micro(binding, layer, previous, txn, cache, ple_micro),
1 => prepare_layer_one_micro(binding, entry, txn, cache, ple_micro),
_ => GrStage::prepare_micro_after_ffn(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn),
}
}
@@ -80,12 +88,12 @@ pub(super) fn prepare_layer_attention_micro(
#[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>,
entry: LayerEntry<'_>,
txn: &mut QwenStepTxn,
cache: &DenseWeightCache<'_>,
ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>,
) -> Result<super::super::gr::GrMicroInput> {
let LayerEntry { layer, previous } = entry;
let previous = previous.ok_or(Error::IdentityMismatch)?;
let prior = txn.ple_prior()?;
let mut ple = diagnose(
@@ -1,6 +1,7 @@
//! Cache-reset-replay numerical proof, moved out of `executor.rs` by STRA-338 (size); same module path as before.
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use crate::qwen_forward::{
dense_weight_cache::DenseCacheCounters, moe_weight_cache::WeightCacheCounters, session::ResetReplaySnapshot,
};
@@ -108,17 +109,14 @@ impl Run<'_, '_, '_> {
baseline.try_reserve_exact(TOKENS.len()).expect("baseline retention allocation failed");
self.output.test_reset_replay_record(true).expect("logit observer refused");
for (index, token) in TOKENS.into_iter().enumerate() {
let greedy = QwenForward::step_cached(
self.binding,
TokenId::new(token, self.fixed.vocabulary).expect("fixed token refused"),
Position::new(index as u64, self.fixed.context_length).expect("fixed position refused"),
session,
self.output,
Some(&mut *cache),
moe_cache,
dense_cache,
)
.expect("cached baseline full forward refused");
let request = StepRequest {
binding: self.binding,
token: TokenId::new(token, self.fixed.vocabulary).expect("fixed token refused"),
position: Position::new(index as u64, self.fixed.context_length).expect("fixed position refused"),
};
let caches = StepCaches { kar: Some(&mut *cache), moe: Some(&mut *moe_cache), dense: Some(dense_cache) };
let greedy = QwenForward::step_cached(request, session, self.output, caches)
.expect("cached baseline full forward refused");
baseline.push(capture_committed(self.binding, session, self.output, greedy, index));
}
baseline
@@ -131,15 +129,13 @@ impl Run<'_, '_, '_> {
cache: &mut KarPleCache<'_>,
expected: &CapturedStep,
) {
let greedy = QwenForward::step_with_kar_ple_output(
self.binding,
TokenId::new(TOKENS[index], self.fixed.vocabulary).expect("fixed replay token refused"),
Position::new(index as u64, self.fixed.context_length).expect("fixed replay position refused"),
session,
self.output,
cache,
)
.expect("legacy uncached full forward refused");
let request = StepRequest {
binding: self.binding,
token: TokenId::new(TOKENS[index], self.fixed.vocabulary).expect("fixed replay token refused"),
position: Position::new(index as u64, self.fixed.context_length).expect("fixed replay position refused"),
};
let greedy = QwenForward::step_with_kar_ple_output(request, session, self.output, cache)
.expect("legacy uncached full forward refused");
let actual = capture_committed(self.binding, session, self.output, greedy, index);
assert!(actual.greedy == expected.greedy, "replay greedy mismatch at step {index}");
assert!(actual.logits.as_ref() == expected.logits.as_ref(), "full logit word mismatch at step {index}");
@@ -200,14 +196,8 @@ fn report_numerical_pass(charged: usize, moe: &WeightCacheCounters, dense: &Dens
/// Narrow test entry can borrow an already verified/loaded operator owner.
/// It never opens model paths, swaps providers or reloads weights/cache.
pub(in crate::qwen_forward) fn check_on_loaded(
binding: &ModelBinding,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
cache: &mut KarPleCache<'_>,
moe_cache: &mut MoeWeightCache<'_>,
dense_cache: &DenseWeightCache<'_>,
) {
pub(in crate::qwen_forward) fn check_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) {
let LoadedTargetOwners { binding, session, output, kar: cache, moe: moe_cache, dense: dense_cache } = owners;
let charged = assert_topology(binding);
let run = Run { binding, output, fixed: fixed_dimensions(binding) };
let fresh = session.test_reset_replay_snapshot(binding).expect("fresh session snapshot refused");
@@ -305,7 +295,14 @@ fn pinned_kar_cached_vs_legacy_same_session_reset_replays_all_logits_and_numeric
let dense_cache =
DenseWeightCache::new(&binding, context.as_ref()).expect("actor-owned dense weight cache load failed");
let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
check_on_loaded(&binding, &mut session, &output, &mut cache, &mut moe_cache, &dense_cache);
check_on_loaded(LoadedTargetOwners {
binding: &binding,
session: &mut session,
output: &output,
kar: &mut cache,
moe: &mut moe_cache,
dense: &dense_cache,
});
drop(session);
let (moe_closed, dense_closed) = close_owners(moe_cache, dense_cache, cache, output);
assert_teardown_clean(&close_context(moe_closed.is_ok(), dense_closed.is_ok(), context));
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::gdn::GdnLayerInput;
use crate::qwen_forward::moe_expert::ExpertRowRequest;
use crate::qwen_forward::qsa_attention::QsaReady;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -17,6 +18,13 @@ pub(super) struct LayerCtx<'a, 'ctx> {
pub(super) dense: Option<&'a DenseWeightCache<'ctx>>,
}
/// The layer one phase runs: its checked id and its kind (GDN or QSA).
#[derive(Clone, Copy)]
struct LayerSite {
layer: LayerId,
kind: BoundLayerKind,
}
/// Validate the complete producer-bound descriptor sequence before touching any model rows or invoking a stage.
pub(super) fn prepare_step_caches(
binding: &ModelBinding,
@@ -101,7 +109,8 @@ pub(super) fn run_layers(
eprintln!("integration: starting layer {}", descriptor.index());
let kind = descriptor.kind();
let index = descriptor.index();
let completed = run_layer(ctx, txn, index, kind, layer_bound, previous.as_ref(), moe_cache.as_deref_mut())?;
let site = LayerSite { layer: LayerId::new(u64::from(index), layer_bound)?, kind };
let completed = run_layer(ctx, txn, site, previous.as_ref(), moe_cache.as_deref_mut())?;
txn.mark_layer_complete(&completed)?;
previous = Some(completed);
}
@@ -112,13 +121,11 @@ pub(super) fn run_layers(
fn run_layer(
ctx: &LayerCtx<'_, '_>,
txn: &mut QwenStepTxn,
descriptor_index: u32,
kind: BoundLayerKind,
layer_bound: Dimension,
site: LayerSite,
previous: Option<&InjectedResidual>,
moe_cache: Option<&mut MoeWeightCache<'_>>,
) -> Result<InjectedResidual> {
let layer = LayerId::new(u64::from(descriptor_index), layer_bound)?;
let LayerSite { layer, kind } = site;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if oracle_capture::enabled() {
oracle_capture::begin(ctx.pos.get(), layer.get() as i32)?;
@@ -276,8 +283,10 @@ fn qsa_attention_indexed(
layer,
prepared,
txn,
dense_cache,
dense_cache.and_then(DenseWeightCache::qsa_attention_workspace),
crate::qwen_forward::qsa_attention::attention_scratch::QsaScratchLoan {
cache: dense_cache,
scratch: dense_cache.and_then(DenseWeightCache::qsa_attention_workspace),
},
),
)?;
Ok(attention)
@@ -345,7 +354,7 @@ fn moe_ffn_inject(
ForwardPhase::MoeExpert,
layer.get(),
pos,
MoeExpertStage::execute(binding, layer, route, ffn.ready(), txn, moe_cache),
MoeExpertStage::execute(binding, ExpertRowRequest { layer, route, input: ffn.ready() }, txn, moe_cache),
)?;
experts.validate_origin(&binding.identity())?;
experts.identity().validate(token, pos, layer)?;
@@ -0,0 +1,41 @@
//! The inputs of one forward step, grouped by meaning: what is forwarded, which caches serve it, what it is for.
use super::{DenseWeightCache, KarPleCache, ModelBinding, MoeWeightCache, Position, TokenId};
/// What one forward step runs: the model binding and the token at its position.
#[derive(Clone, Copy)]
pub(crate) struct StepRequest<'a> {
pub(crate) binding: &'a ModelBinding,
pub(crate) token: TokenId,
pub(crate) position: Position,
}
/// The weight caches one forward step reads and fills. An absent cache selects the uncached path of that provider.
pub(crate) struct StepCaches<'a, 'kar, 'moe, 'dense> {
pub(crate) kar: Option<&'a mut KarPleCache<'kar>>,
pub(crate) moe: Option<&'a mut MoeWeightCache<'moe>>,
pub(crate) dense: Option<&'a DenseWeightCache<'dense>>,
}
/// What a forward step is for: it decides whether the pre-output streams are retained and the output head is read.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum StepPurpose {
/// A complete greedy step: the predicted token is published, nothing is retained for MTP.
Greedy,
/// A complete step whose pre-output four-stream residual is retained as the MTP target product.
MtpTarget,
/// A known-next prefill step: the streams are retained and no token is predicted.
MtpPrefill,
}
impl StepPurpose {
/// Whether the four-stream residual is copied out for the MTP draft.
pub(crate) fn retains_streams(self) -> bool {
self != Self::Greedy
}
/// Whether the step stops before the output head.
pub(crate) fn is_prefill_only(self) -> bool {
self == Self::MtpPrefill
}
}
@@ -1,30 +1,18 @@
//! Only the explicitly selected new full-model MMQ gate. Old observers unchanged.
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use crate::qwen_forward::mtp::KnownNext;
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
use crate::qwen_forward::mtp_decode::MtpDecoder;
use crate::qwen_forward::session::ResetReplaySnapshot;
impl QwenForward {
pub(crate) fn test_mmq_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
) {
check_mmq_on_loaded(binding, session, output, kar, moe, dense);
pub(crate) fn test_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) {
check_mmq_on_loaded(owners);
}
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
) {
let mut run = MmqRun::new(binding, session, output, kar, moe, dense);
pub(in crate::qwen_forward) fn check_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) {
let binding = owners.binding;
let mut run = MmqRun::new(owners);
let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required");
let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused");
@@ -38,7 +26,8 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>(
run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
let chunk = run.candidate_chunk(&mut candidate_draft);
let head_exact = run.compare_head(&baseline, &chunk);
let exact = run.compare_chunk(&baseline, &baseline_streams, &chunk, &candidate_draft, head_exact);
let scalar_baseline = ScalarBaseline { observation: &baseline, streams: &baseline_streams };
let exact = run.compare_chunk(scalar_baseline, &chunk, &candidate_draft, head_exact);
let continued_exact = run.candidate_continuation(&mut candidate_draft, &chunk, &continued, &exact);
let continued_draft_exact = candidate_draft.test_chunk_eq(&continued.draft);
run.output.test_reset_replay_record(false).expect("head observer did not drain");
@@ -87,6 +76,13 @@ pub(super) struct ChunkExact {
pub(super) draft: bool,
}
/// The scalar target step the candidate chunk is compared with: its observation and residual stream words.
#[derive(Clone, Copy)]
struct ScalarBaseline<'a> {
observation: &'a Observation,
streams: &'a [u32],
}
/// Exactness flags of the continuation step.
struct ContinuedExact {
head: bool,
@@ -94,14 +90,8 @@ struct ContinuedExact {
}
impl<'a, 'driver, 'o, 'p, 'k, 'd> MmqRun<'a, 'driver, 'o, 'p, 'k, 'd> {
pub(super) fn new(
binding: &'a ModelBinding,
session: &'a mut QwenSession<'driver>,
output: &'a OutputStage<'o, 'p>,
kar: &'a mut KarPleCache<'k>,
moe: &'a mut MoeWeightCache<'driver>,
dense: &'a DenseWeightCache<'d>,
) -> Self {
pub(super) fn new(owners: LoadedTargetOwners<'a, 'driver, 'o, 'p, 'k, 'd>) -> Self {
let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners;
let vocab = Dimension::new(248320).expect("vocabulary refused");
let ids: Vec<_> =
[0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect();
@@ -115,33 +105,24 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
pub(super) fn warm_scalar_prefix(&mut self, scalar_draft: &mut MtpDecoder) {
self.output.test_reset_replay_record(true).expect("head observer refused");
for index in 0..3 {
let source = QwenForward::prefill_for_mtp_cached(
self.binding,
self.ids[index],
pos(index as u64),
self.session,
self.output,
Some(&mut *self.kar),
self.moe,
self.dense,
)
.expect("scalar known-next target refused");
let request = StepRequest { binding: self.binding, token: self.ids[index], position: pos(index as u64) };
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
let source = QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches)
.expect("scalar known-next target refused");
scalar_draft
.warm_prefill(self.binding, self.session, &source, self.ids[index + 1], self.moe)
.warm_prefill(
self.binding,
self.session,
KnownNext { source: &source, next_token: self.ids[index + 1] },
self.moe,
)
.expect("scalar known-next warm refused");
}
}
pub(super) fn mtp_step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
QwenForward::step_for_mtp_cached(
self.binding,
token,
pos(position),
self.session,
self.output,
Some(&mut *self.kar),
Some(&mut *self.moe),
Some(self.dense),
)
let request = StepRequest { binding: self.binding, token, position: pos(position) };
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
QwenForward::step_for_mtp_cached(request, self.session, self.output, caches)
}
pub(super) fn scalar_final_step(
&mut self,
@@ -166,11 +147,16 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
source: &TargetStepProduct,
) -> Observation {
scalar_draft
.warm_retained(self.binding, self.session, source, self.next, self.moe)
.warm_retained(self.binding, self.session, KnownNext { source, next_token: self.next }, self.moe)
.expect("scalar retained edge refused");
let continuation = self.mtp_step(self.next, 4).expect("scalar continuation refused");
scalar_draft
.warm_retained(self.binding, self.session, &continuation, self.follow, self.moe)
.warm_retained(
self.binding,
self.session,
KnownNext { source: &continuation, next_token: self.follow },
self.moe,
)
.expect("scalar continuation warm refused");
let greedy = continuation.predicted(self.session).expect("baseline continuation origin invalid");
let logits = self.output.test_reset_replay_take_logits().expect("baseline continuation head missing");
@@ -307,12 +293,12 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
}
fn compare_chunk(
&mut self,
baseline: &Observation,
baseline_streams: &[u32],
scalar_baseline: ScalarBaseline<'_>,
chunk: &ChunkRun,
candidate_draft: &MtpDecoder,
head: bool,
) -> ChunkExact {
let ScalarBaseline { observation: baseline, streams: baseline_streams } = scalar_baseline;
let predicted = chunk.product.predicted(self.session).expect("chunk current origin invalid");
assert_eq!(baseline.greedy, predicted, "greedy mismatch");
let actual_streams =
@@ -334,11 +320,21 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
.validate_resume(self.binding, self.session, &chunk.product, &[0, 1, 0, 1])
.expect("chunk resume fence refused");
candidate_draft
.warm_retained(self.binding, self.session, &chunk.product, self.next, self.moe)
.warm_retained(
self.binding,
self.session,
KnownNext { source: &chunk.product, next_token: self.next },
self.moe,
)
.expect("chunk retained edge refused");
let continuation = self.mtp_step(self.next, 4).expect("chunk continuation refused");
candidate_draft
.warm_retained(self.binding, self.session, &continuation, self.follow, self.moe)
.warm_retained(
self.binding,
self.session,
KnownNext { source: &continuation, next_token: self.follow },
self.moe,
)
.expect("chunk continuation warm refused");
let actual_greedy = continuation.predicted(self.session).expect("candidate continuation origin invalid");
let actual_logits = self.output.test_reset_replay_take_logits().expect("candidate continuation head missing");
@@ -18,6 +18,17 @@ struct ReadyVerifiedDraft<'draft, 'binding> {
count: usize,
warmed: usize,
}
/// The weight caches a joint publication warms the draft against: the MoE cache always, the dense cache
/// only when the target window leased a device GDN state that must be sealed.
pub(in crate::qwen_forward) struct WindowCaches<'a, 'moe, 'dense> {
pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'moe>,
pub(in crate::qwen_forward) dense: Option<&'a DenseWeightCache<'dense>>,
}
/// The draft chunk stage being warmed together with the MoE cache its rows run against.
struct DraftWarmup<'a, 'stage, 'cache> {
stage: &'a mut MtpChunkStage<'stage>,
cache: &'a MoeWeightCache<'cache>,
}
impl VerifiedDraftPublication for ReadyVerifiedDraft<'_, '_> {
fn validate(&self, txn: &QwenChunkTxn<'_, '_>, prefix: &VerifiedTargetPrefix) -> Result<()> {
txn.validate_verified_prefix(prefix)?;
@@ -49,28 +60,28 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
cache: &MoeWeightCache<'_>,
cancelled: impl FnMut() -> bool,
) -> Result<TargetStepProduct> {
self.publish_joint_with_gdn_replay(binding, draft, cache, None, cancelled)
self.publish_joint_with_gdn_replay(binding, draft, WindowCaches { moe: cache, dense: None }, cancelled)
}
pub(in crate::qwen_forward) fn publish_joint_with_gdn_replay(
mut self,
binding: &ModelBinding,
draft: &mut MtpSession,
cache: &MoeWeightCache<'_>,
dense: Option<&DenseWeightCache<'_>>,
caches: WindowCaches<'_, '_, '_>,
mut cancelled: impl FnMut() -> bool,
) -> Result<TargetStepProduct> {
self.txn.validate_verified_prefix(&self.prefix)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.seal_leased_gdn(binding, dense, &mut cancelled)?;
self.seal_leased_gdn(binding, caches.dense, &mut cancelled)?;
let start = self.txn.start_position();
let count = self.prefix.count();
let rows = self.copy_accepted_rows(count)?;
// The existing stage validates actual draft KV/window/epoch/owner and
// requires genuine draft.next_position == actual target chunk start.
let mut stage = draft.stage_chunk(binding, &self.txn)?;
self.warm_accepted_rows(binding, cache, &mut stage, &rows, &mut cancelled)?;
let warmup = DraftWarmup { stage: &mut stage, cache: caches.moe };
self.warm_accepted_rows(binding, warmup, &rows, &mut cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
@@ -101,8 +112,7 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
fn warm_accepted_rows(
&mut self,
binding: &ModelBinding,
cache: &MoeWeightCache<'_>,
stage: &mut MtpChunkStage<'_>,
warmup: DraftWarmup<'_, '_, '_>,
rows: &[ChunkRowResidual],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
@@ -115,18 +125,25 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? || next.is_none() {
return Err(Error::IdentityMismatch);
}
mtp::warm_chunk_row(binding, &mut self.txn, row, stage, cache)?;
mtp::warm_chunk_row(binding, &mut self.txn, row, warmup.stage, warmup.cache)?;
}
Ok(())
}
}
/// The target step a verification window continues from, and the end-of-sequence token that closes it.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct VerificationSource<'a> {
pub(in crate::qwen_forward) product: &'a TargetStepProduct,
pub(in crate::qwen_forward) eos: Option<TokenId>,
}
/// The borrowed inputs of the verification chunk that the session, caches and cancel hook do not carry.
struct VerificationChunk<'a, 'o, 'p, 'd> {
binding: &'a ModelBinding,
proposals: &'a [TokenId],
output: &'a OutputStage<'o, 'p>,
dense_cache: &'a DenseWeightCache<'d>,
host_remaining: usize,
pub(in crate::qwen_forward) struct VerificationChunk<'a, 'o, 'p, 'd> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) source: VerificationSource<'a>,
pub(in crate::qwen_forward) proposals: &'a [TokenId],
pub(in crate::qwen_forward) output: &'a OutputStage<'o, 'p>,
pub(in crate::qwen_forward) dense_cache: &'a DenseWeightCache<'d>,
pub(in crate::qwen_forward) host_remaining: usize,
}
// Descending bounded admission, never a numeric/identity/poison retry.
fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()>) -> Result<usize> {
@@ -147,13 +164,12 @@ fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()
impl QwenForward {
pub(in crate::qwen_forward) fn mtp_target_window_capacity(
binding: &ModelBinding,
source: &TargetStepProduct,
eos: Option<TokenId>,
source: VerificationSource<'_>,
target: &QwenSession<'_>,
limit: usize,
host_remaining: usize,
) -> Result<usize> {
QwenChunkTxn::validate_verification_source(binding, source, eos, target)?;
QwenChunkTxn::validate_verification_source(binding, source.product, source.eos, target)?;
legal_target_rows(limit, |rows| QwenChunkTxn::preflight_mtp_verification(target, binding, rows, host_remaining))
}
@@ -201,30 +217,23 @@ impl QwenForward {
/// Explicit source-only candidate. Preserves Native/scalar MTP/defaults.
/// Existing Q6/MoE/GR batching survives; GDN uses unchanged scalar pending
/// producers here so every possible accepted prefix has actual state.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn prepare_mtp_target_window<'session, 'driver>(
binding: &ModelBinding,
source: &TargetStepProduct,
proposals: &[TokenId],
eos: Option<TokenId>,
inputs: VerificationChunk<'_, '_, '_, '_>,
session: &'session mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
moe_cache: &mut MoeWeightCache<'driver>,
dense_cache: &DenseWeightCache<'_>,
host_remaining: usize,
mut cancelled: impl FnMut() -> bool,
) -> Result<PreparedMtpTargetWindow<'session, 'driver>> {
let seed = QwenChunkTxn::validate_verification_source(binding, source, eos, session)?;
let (binding, source, proposals) = (inputs.binding, inputs.source, inputs.proposals);
let seed = QwenChunkTxn::validate_verification_source(binding, source.product, source.eos, session)?;
Self::admit_mtp_window(seed, proposals, moe_cache, &mut cancelled)?;
// Refuse the complete journal charge before cache/provider growth.
QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), host_remaining)?;
let inputs = VerificationChunk { binding, proposals, output, dense_cache, host_remaining };
QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), inputs.host_remaining)?;
let txn = Self::prepare_verification_chunk(inputs, session, kar_cache, moe_cache, &mut cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let prefix = txn.select_verified_prefix(binding, source, eos)?;
let prefix = txn.select_verified_prefix(binding, source.product, source.eos)?;
Ok(PreparedMtpTargetWindow { txn, prefix })
}
}
@@ -1,6 +1,7 @@
//! Separate native-certified activation model observer. Original failed observer unchanged.
use super::mmq_evaluation::{ChunkExact, ChunkRun, MmqRun, Observation, pos};
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use crate::qwen_forward::mtp_decode::MtpDecoder;
#[derive(Debug)]
@@ -45,26 +46,15 @@ pub(crate) struct NativeMmqReport {
pub(crate) native_fallback_layers: u64,
}
impl QwenForward {
pub(crate) fn test_native_mmq_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
) -> NativeMmqReport {
check_native_mmq_on_loaded(binding, session, output, kar, moe, dense)
pub(crate) fn test_native_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) -> NativeMmqReport {
check_native_mmq_on_loaded(owners)
}
}
pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
pub(in crate::qwen_forward) fn check_native_mmq_on_loaded(
owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>,
) -> NativeMmqReport {
let mut run = MmqRun::new(binding, session, output, kar, moe, dense);
let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners;
let mut run = MmqRun::new(LoadedTargetOwners { binding, session, output, kar, moe, dense });
let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required");
let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused");
@@ -77,27 +67,26 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>(
run.late_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
let chunk = run.candidate_chunk(&mut candidate_draft);
let (exact, actual_greedy) = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft);
let verdict = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft);
let after = run.native_continuation(&mut candidate_draft, &chunk, &continued);
run.output.test_reset_replay_record(false).expect("head observer did not drain");
native_report(&baseline, &continued, &chunk, &exact, actual_greedy, &after)
native_report(&baseline, &continued, &chunk, &verdict, &after)
}
fn native_report(
baseline: &Observation,
continued: &Observation,
chunk: &ChunkRun,
exact: &ChunkExact,
actual_greedy: TokenId,
verdict: &NativeChunkVerdict,
after: &NativeContinued,
) -> NativeMmqReport {
NativeMmqReport {
final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, actual_greedy),
final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, verdict.greedy),
continuation_head: HeadObservation::new(&continued.logits, &after.logits, continued.greedy, after.greedy),
head_exact: exact.head,
residual_exact: exact.residual,
target_exact: exact.target,
draft_exact: exact.draft,
head_exact: verdict.exact.head,
residual_exact: verdict.exact.residual,
target_exact: verdict.exact.target,
draft_exact: verdict.exact.draft,
continued_head_exact: after.head,
continued_target_exact: after.target,
continued_draft_exact: after.draft,
@@ -107,6 +96,12 @@ fn native_report(
}
}
/// How the candidate chunk compares with the scalar baseline: tensor exactness and the candidate's greedy token.
struct NativeChunkVerdict {
exact: ChunkExact,
greedy: TokenId,
}
/// What the continuation step after the candidate chunk observed.
struct NativeContinued {
logits: Box<[u32]>,
@@ -124,7 +119,7 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
baseline_streams: &[u32],
chunk: &ChunkRun,
candidate_draft: &MtpDecoder,
) -> (ChunkExact, TokenId) {
) -> NativeChunkVerdict {
let actual_greedy = chunk.product.predicted(self.session).expect("MMQ current origin invalid");
let head = baseline.logits.as_ref() == chunk.logits.as_ref();
let actual_streams =
@@ -134,7 +129,7 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
.state
.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk state invalid"));
let draft = candidate_draft.test_chunk_eq(&baseline.draft);
(ChunkExact { head, residual, target, draft }, actual_greedy)
NativeChunkVerdict { exact: ChunkExact { head, residual, target, draft }, greedy: actual_greedy }
}
fn native_continuation(
&mut self,
@@ -2,11 +2,13 @@
//! result stays pending until the real MTP forward owner joins publication.
//! This is an unselected source port, not a serving qualification.
use super::super::original_mtp_full_owner::{
OriginalMtpFullAssembly, OriginalMtpFullOwner, OriginalMtpLoadError, OriginalMtpRequest,
DraftAttachmentTables, DraftAttachmentTarget, OriginalMtpFullAssembly, OriginalMtpFullOwner, OriginalMtpLoadError,
RtMtpLoad,
};
use super::super::output::OriginalPromptSample;
use super::super::output_native::OriginalNativeOutput;
use super::super::prompt_device_rows::{OriginalDraftKvPending, OriginalPromptDraftOutcome};
use super::super::prompt_device_rows::{
OriginalDraftKvPending, OriginalPromptDraftOutcome, PromptWeights, QsaLayerDevices, RowsUpload,
};
use super::super::prompt_device_rows::{
PromptDeviceFinal, PromptDeviceNormedRows, PromptDeviceRows, PromptDeviceSource,
};
@@ -110,6 +112,16 @@ pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx> {
pub last_published: Option<(TargetStepOrigin, Option<TokenId>)>,
}
#[path = "executor_original_prompt/executor_construction_operands.rs"]
mod executor_construction_operands;
pub(in crate::qwen_forward) use executor_construction_operands::{ExecutorSizing, ExecutorTarget};
#[path = "executor_original_prompt/prompt_chunk_operands.rs"]
mod prompt_chunk_operands;
pub(in crate::qwen_forward) use prompt_chunk_operands::{
ChunkCaches, ChunkDraft, PromptChunkSource, PromptChunkTarget,
};
#[allow(unused_imports)]
use prompt_chunk_operands::{ChunkInFlight, ChunkRollback, ChunkWork, OpenChunk};
#[path = "executor_original_prompt/staged_input_enabled_fn.rs"]
mod staged_input_enabled_fn;
#[allow(unused_imports)]
@@ -0,0 +1,18 @@
//! The operand groups the construction of `OriginalPromptExecutor` takes.
use super::*;
/// The target model weights, the target session and the device context a prompt executor is built over.
pub(in crate::qwen_forward) struct ExecutorTarget<'a, 'ctx> {
pub(in crate::qwen_forward) weights: PromptWeights<'a, 'ctx>,
pub(in crate::qwen_forward) session: &'a mut QwenSession<'ctx>,
pub(in crate::qwen_forward) context: &'ctx Context<'ctx>,
}
/// The sizes of a prompt executor: the prompt chunk capacity, the widest verifier window and whether the GR norm is
/// fused into the injection.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct ExecutorSizing {
pub(in crate::qwen_forward) capacity: usize,
pub(in crate::qwen_forward) max_t: usize,
pub(in crate::qwen_forward) fused: bool,
}
@@ -4,6 +4,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::session::original_prompt::{DraftRollback, PromptPublication};
impl Drop for OriginalPromptExecutor<'_> {
fn drop(&mut self) {
@@ -14,15 +15,11 @@ impl OriginalPromptPending<'_, '_, '_> {
/// Any fallible publication leaves the owning transaction present so Drop
/// restores both real physical accepted prefixes. Success consumes it.
pub(in crate::qwen_forward) fn publish(mut self) -> Result<(TargetStepOrigin, Option<TokenId>)> {
let result = self.txn.as_mut().ok_or(Error::IdentityMismatch)?.publish(
self.binding,
self.dense,
self.layers,
&self.completed,
self.draft,
&self.draft_kv,
&self.sample,
);
let weights = PromptWeights { binding: self.binding, dense: self.dense };
let publication =
PromptPublication { completed: &self.completed, draft_kv: &self.draft_kv, sample: &self.sample };
let txn = self.txn.as_mut().ok_or(Error::IdentityMismatch)?;
let result = txn.publish(weights, self.layers, publication, self.draft);
if result.is_ok() {
self.txn.take();
}
@@ -32,17 +29,9 @@ impl OriginalPromptPending<'_, '_, '_> {
impl Drop for OriginalPromptPending<'_, '_, '_> {
fn drop(&mut self) {
if let Some(txn) = self.txn.take() {
if txn
.abort_with_draft(
self.binding,
self.dense,
self.layers,
&self.checkpoint,
self.draft,
&self.draft_checkpoint,
)
.is_err()
{
let weights = PromptWeights { binding: self.binding, dense: self.dense };
let rollback = DraftRollback { draft: self.draft, prior: &self.draft_checkpoint };
if txn.abort_with_draft(weights, self.layers, &self.checkpoint, rollback).is_err() {
*self.failed = true;
}
}
@@ -60,20 +49,14 @@ impl crate::backend::original_prompt::PromptRunner for OriginalPromptComposer<'_
if self.session.target_origin()?.next_position() != action.first as u64 {
return Err(Error::IdentityMismatch);
}
let pending = self.executor.forward(
self.binding,
self.dense,
&mut *self.session,
self.source,
action.count,
self.kar.as_deref_mut(),
&mut *self.moe,
&mut *self.arena,
&mut *self.draft,
self.embedding,
self.policy,
&mut *self.cancel,
)?;
let target = PromptChunkTarget {
weights: PromptWeights::new(self.binding, self.dense),
session: &mut *self.session,
tokens: PromptChunkSource { source: self.source, count: action.count },
};
let caches = ChunkCaches { kar: self.kar.as_deref_mut(), moe: &mut *self.moe, arena: &mut *self.arena };
let draft = ChunkDraft { session: &mut *self.draft, embedding: self.embedding, policy: self.policy };
let pending = self.executor.forward(target, caches, draft, &mut *self.cancel)?;
self.last_published = Some(pending.publish()?);
Ok(())
}
@@ -3,7 +3,7 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs"]
mod impl_originalpromptexecutor;
#[path = "impl_originalpromptexecutor_2/executor_construction.rs"]
mod executor_construction;
#[path = "impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs"]
mod impl_originalpromptexecutor_2_2;
@@ -8,34 +8,25 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// Eager model/session owners precede expert prefix planning. The twelve
/// resident checkpoints are installed together only after all producers exist.
pub(in crate::qwen_forward) fn new(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
session: &mut QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
target: ExecutorTarget<'_, 'ctx>,
moe: &MoeWeightCache<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
capacity: usize,
max_t: usize,
fused: bool,
sizing: ExecutorSizing,
) -> Result<Self> {
// Pinned-pack source: the MoE cache already holds and charged the roles.
let retained = moe.retain_original_mtp_weights(binding, context)?;
Self::new_with_mtp_weights(binding, dense, session, context, retained, embedding, capacity, max_t, fused)
let retained = moe.retain_original_mtp_weights(target.weights.binding, target.context)?;
Self::new_with_mtp_weights(target, retained, embedding, sizing)
}
/// Same construction over any retained MTP role bank (the pinned pack, or
/// the Original-literal RT directory bank of `select_rt_mtp`).
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn new_with_mtp_weights(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
session: &mut QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
target: ExecutorTarget<'_, 'ctx>,
retained: RetainedOriginalMtpWeights<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
capacity: usize,
max_t: usize,
fused: bool,
sizing: ExecutorSizing,
) -> Result<Self> {
let ExecutorTarget { weights: PromptWeights { binding, dense }, session, context } = target;
let ExecutorSizing { capacity, max_t, fused } = sizing;
Self::check_construction(binding, dense, session, context, (capacity, max_t))?;
let mut owner = Self::empty(binding, context, (capacity, max_t, fused));
let result = owner.build_owners(binding, (dense, session), retained, embedding);
@@ -203,29 +194,25 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// Returns both owners; the draft session is the sole mutator of the
/// ring, the executor holds the actor. Any failure releases everything
/// built so far through the owners' own closure order.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn select_rt_mtp(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
session: &mut QwenSession<'ctx>,
context: &'ctx Context<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
output: &OriginalNativeOutput<'ctx>,
rt_directory: &std::path::Path,
target: ExecutorTarget<'_, 'ctx>,
tables: DraftAttachmentTables<'_, 'ctx>,
load: RtMtpLoad<'_>,
capacity: usize,
fused: bool,
request: &OriginalMtpRequest,
) -> std::result::Result<(Self, OriginalDraftSession<'ctx>), OriginalMtpLoadError> {
let ExecutorTarget { weights, session, context } = target;
let (binding, request) = (weights.binding, load.request);
if !(1..=8).contains(&request.max_t) || request.prompt_capacity != capacity || binding.layer_count() != 48 {
return Err(Error::IdentityMismatch.into());
}
let retained = Self::load_rt_retained(binding, context, rt_directory)?;
let retained = Self::load_rt_retained(binding, context, load.directory)?;
let (shared, max_t) = (retained.clone(), request.max_t);
let target = ExecutorTarget { weights, session: &mut *session, context };
let mut executor =
Self::new_with_mtp_weights(binding, dense, session, context, shared, embedding, capacity, max_t, fused)?;
let dir = rt_directory;
let assembly =
OriginalMtpFullOwner::assemble_rt(binding, session, context, &retained, embedding, output, request, dir)?;
Self::new_with_mtp_weights(target, shared, tables.embedding, ExecutorSizing { capacity, max_t, fused })?;
let assembly_target = DraftAttachmentTarget { binding, session: &*session, context };
let assembly = OriginalMtpFullOwner::assemble_rt(assembly_target, &retained, tables, load)?;
let draft = executor.install_full_mtp(binding, session, assembly)?;
Ok((executor, draft))
}
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::session::original_prompt::ParkedPoint;
/// The index image and mapped K/V journal of each of the twelve resident QSA layers, by layer slot.
type QsaOwners<'ctx> =
@@ -144,8 +145,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// the executor, as for `restore_session`.
pub(in crate::qwen_forward) fn import_session(
&mut self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
weights: PromptWeights<'_, 'ctx>,
session: &mut QwenSession<'ctx>,
parked: &ParkedSession,
blocks: &[&ParkedBlock],
@@ -153,7 +153,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
if self.failed || self.context.is_poisoned() {
return Err(Error::CudaExecution);
}
let imported = session.import_parked(binding, dense, &mut self.layers, parked, blocks);
let PromptWeights { binding, dense } = weights;
let point = ParkedPoint { session: parked, blocks };
let imported = session.import_parked(PromptWeights::new(binding, dense), &mut self.layers, point);
if imported.is_err() {
self.failed = true;
}
@@ -3,7 +3,7 @@
#[allow(unused_imports)]
use super::*;
#[path = "impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs"]
mod impl_originalpromptexecutor;
#[path = "impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs"]
mod impl_originalpromptexecutor_2;
#[path = "impl_originalpromptexecutor_2_2/prompt_chunk_forward.rs"]
mod prompt_chunk_forward;
@@ -2,18 +2,21 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::prompt_device_rows::{DraftKvRequest, FinalPromptSources};
use leleka_cuda_driver::{MtpInt8Snapshot, MtpOriginalInt8, NativeBatchWorkspace, OriginalMtpActor, RecordRun};
use crate::qwen_forward::prompt_device_rows::{
DraftKvRequest, FinalPromptSources, ScalarDraftKvRequest, ScalarPromptSources,
};
use leleka_cuda_driver::{
MtpInt8Snapshot, MtpOriginalInt8, NativeBatchWorkspace, OriginalMtpActor, RecordRun, ScalarDraftKvSources,
};
/// The read-only inputs both draft-KV producers (batched and scalar fallback) take from the chunk.
struct DraftKvInputs<'a, 'ctx> {
binding: &'a ModelBinding,
dense: &'a DenseWeightCache<'ctx>,
moe: &'a MoeWeightCache<'ctx>,
txn: &'a OriginalPromptTxn<'a, 'ctx>,
final_row: &'a PromptDeviceFinal,
sample: &'a OriginalPromptSample,
context: &'ctx Context<'ctx>,
pub(super) struct DraftKvInputs<'a, 'ctx> {
pub(super) weights: PromptWeights<'a, 'ctx>,
pub(super) moe: &'a MoeWeightCache<'ctx>,
pub(super) txn: &'a OriginalPromptTxn<'a, 'ctx>,
pub(super) final_row: &'a PromptDeviceFinal,
pub(super) sample: &'a OriginalPromptSample,
pub(super) context: &'ctx Context<'ctx>,
}
/// The batched draft producer and the batch workspace it records through.
@@ -23,20 +26,40 @@ struct BatchedDraftDevice<'a, 'ctx> {
}
/// The ring and its snapshot the draft KV is written into, and the first position that is still needed.
type DraftRing<'a, 'ctx> = (&'a mut MtpOriginalInt8<'ctx>, &'a MtpInt8Snapshot, usize);
struct DraftRing<'a, 'ctx> {
ring: &'a mut MtpOriginalInt8<'ctx>,
prior: &'a MtpInt8Snapshot,
first_needed: usize,
}
/// The scalar fallback's actor, retained scalar weights and retained MTP weights.
type DraftScalarOwners<'a, 'ctx> = (
&'a mut OriginalMtpActor<'ctx>,
std::rc::Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
&'a RetainedOriginalMtpWeights<'ctx>,
);
struct DraftScalarOwners<'a, 'ctx> {
actor: &'a mut OriginalMtpActor<'ctx>,
scalar_weights: std::rc::Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
retained_mtp: &'a RetainedOriginalMtpWeights<'ctx>,
}
/// The owners of the two producers: the batched one and the scalar fallback's.
type DraftProducers<'a, 'ctx> = (&'a mut OriginalMtpPrefill<'ctx>, DraftScalarOwners<'a, 'ctx>);
struct DraftProducers<'a, 'ctx> {
batched: &'a mut OriginalMtpPrefill<'ctx>,
scalar: DraftScalarOwners<'a, 'ctx>,
}
/// The embedding, scalar policy and cancellation the producers share.
type DraftExtras<'a, 'ctx, C> = (&'a OriginalPromptEmbedding<'ctx>, (&'a OriginalMtpScalarPolicy, &'a mut C));
struct DraftExtras<'a, 'ctx, C> {
embedding: &'a OriginalPromptEmbedding<'ctx>,
policy: &'a OriginalMtpScalarPolicy,
cancelled: &'a mut C,
}
/// What the scalar fallback needs when the batched producer falls back: its owners, the ring, the policy and the
/// cancellation poll.
struct ScalarFallback<'a, 'ctx, C> {
owners: DraftScalarOwners<'a, 'ctx>,
ring: DraftRing<'a, 'ctx>,
policy: &'a OriginalMtpScalarPolicy,
cancelled: &'a mut C,
}
fn outcome_name(outcome: &OriginalPromptDraftOutcome) -> &'static str {
match outcome {
@@ -68,47 +91,42 @@ fn completed_draft(outcome: OriginalPromptDraftOutcome) -> Result<OriginalDraftK
impl<'ctx> OriginalPromptExecutor<'ctx> {
/// Records the draft KV of the chunk into the draft session's pending ring.
#[allow(clippy::too_many_arguments)]
pub(super) fn record_draft_kv(
&mut self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
moe: &MoeWeightCache<'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
chunk: (&mut PromptDeviceRows<'_, '_, '_, 'ctx>, &PromptDeviceFinal, &OriginalPromptSample),
draft_args: DraftArgs<'_, 'ctx>,
inputs: DraftKvInputs<'_, 'ctx>,
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
draft: ChunkDraft<'_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<OriginalDraftKvPending> {
let draft_span = prof::span(PStage::DraftKv, Some(self.context as &dyn prof::Drain));
let draft_kv = self.draft_kv_in_ring(binding, dense, moe, txn, chunk, draft_args, cancelled)?;
let draft_kv = self.draft_kv_in_ring(inputs, rows, draft, cancelled)?;
trace_step("forward: draft kv ok");
drop(draft_span);
Ok(draft_kv)
}
#[allow(clippy::too_many_arguments)]
fn draft_kv_in_ring(
&mut self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
moe: &MoeWeightCache<'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
(rows, final_row, sample): (&mut PromptDeviceRows<'_, '_, '_, 'ctx>, &PromptDeviceFinal, &OriginalPromptSample),
(draft, embedding, policy): DraftArgs<'_, 'ctx>,
inputs: DraftKvInputs<'_, 'ctx>,
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
draft: ChunkDraft<'_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<OriginalDraftKvPending> {
let binding = inputs.weights.binding;
let producer = self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?;
// The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared
// layout is paired with that owner's main arena, a standalone owner is refused with InvalidQwenShape.
let (context, max_t) = (self.context, self.max_t);
let scalar = self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding, context, max_t)?;
let actor = self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding, context, max_t)?;
let scalar_weights = std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?);
let retained_mtp = self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?;
let inputs = DraftKvInputs { binding, dense, moe, txn, final_row, sample, context };
draft
.with_pending_ring(binding, txn, |ring, prior, first_needed| {
let producers = (producer, (scalar, scalar_weights, &retained_mtp));
inputs.record_in_ring(rows, producers, (ring, prior, first_needed), (embedding, (policy, cancelled)))
let ChunkDraft { session, embedding, policy } = draft;
session
.with_pending_ring(binding, inputs.txn, |ring, prior, first_needed| {
let scalar = DraftScalarOwners { actor, scalar_weights, retained_mtp: &retained_mtp };
let producers = DraftProducers { batched: producer, scalar };
let ring = DraftRing { ring, prior, first_needed };
inputs.record_in_ring(rows, producers, ring, DraftExtras { embedding, policy, cancelled })
})
.map_err(|error| trace_error("with_pending_ring", error))
}
@@ -119,21 +137,25 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> {
fn record_in_ring(
&self,
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
(producer, scalar_owners): DraftProducers<'_, 'ctx>,
(ring, prior, first_needed): DraftRing<'_, 'ctx>,
(embedding, (policy, cancelled)): DraftExtras<'_, 'ctx, impl FnMut() -> bool>,
producers: DraftProducers<'_, 'ctx>,
draft_ring: DraftRing<'_, 'ctx>,
extras: DraftExtras<'_, 'ctx, impl FnMut() -> bool>,
) -> Result<OriginalDraftKvPending> {
let DraftProducers { batched: producer, scalar: scalar_owners } = producers;
let DraftRing { ring, prior, first_needed } = draft_ring;
let DraftExtras { embedding, policy, cancelled } = extras;
crate::bringup_trace!(
"DBG[{:.0}s] draft ring open first_needed={first_needed:?}",
crate::qwen_forward::original_serve_stack::dbg_el()
);
let mut workspace =
self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?;
let batched_ring = (&mut *ring, prior, first_needed);
let batched = (embedding, (policy, &mut *cancelled));
let PromptWeights { binding, dense } = self.weights;
let mut workspace = dense.native_batch_workspace(binding, self.context)?.ok_or(Error::IdentityMismatch)?;
let batched_ring = DraftRing { ring: &mut *ring, prior, first_needed };
let batched = DraftExtras { embedding, policy, cancelled: &mut *cancelled };
let device = BatchedDraftDevice { producer, workspace: &mut workspace };
let outcome = self.record_batched(rows, device, batched_ring, batched)?;
let scalar = (scalar_owners, (ring, prior, first_needed), (policy, cancelled));
let scalar =
ScalarFallback { owners: scalar_owners, ring: DraftRing { ring, prior, first_needed }, policy, cancelled };
let outcome = self.scalar_fallback(outcome, rows, &mut workspace, scalar)?;
trace_outcome("after scalar fallback", &outcome);
completed_draft(outcome)
@@ -143,13 +165,16 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> {
&self,
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
device: BatchedDraftDevice<'_, 'ctx>,
(ring, prior, first_needed): DraftRing<'_, 'ctx>,
(embedding, (policy, cancelled)): DraftExtras<'_, 'ctx, impl FnMut() -> bool>,
draft_ring: DraftRing<'_, 'ctx>,
extras: DraftExtras<'_, 'ctx, impl FnMut() -> bool>,
) -> Result<OriginalPromptDraftOutcome> {
let BatchedDraftDevice { producer, workspace } = device;
let DraftRing { ring, prior, first_needed } = draft_ring;
let DraftExtras { embedding, policy, cancelled } = extras;
let PromptWeights { binding, dense } = self.weights;
let sources = FinalPromptSources {
binding: self.binding,
dense: self.dense,
binding,
dense,
mtp: self.moe,
txn: self.txn,
preview: self.final_row,
@@ -157,7 +182,7 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> {
};
let mut cancelled = cancelled;
let run = RecordRun { workspace, ring, cancelled: &mut cancelled };
let embedding = embedding.borrow(self.binding, self.context)?;
let embedding = embedding.borrow(binding, self.context)?;
let request = DraftKvRequest { prior, embedding, first_needed, policy: &policy.kv };
let outcome = rows.record_original_draft_kv(sources, producer, run, request)?;
if let OriginalPromptDraftOutcome::Fallback(reason) = &outcome {
@@ -173,16 +198,10 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> {
outcome: OriginalPromptDraftOutcome,
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
(owners, ring, (policy, cancelled)): (
DraftScalarOwners<'_, 'ctx>,
DraftRing<'_, 'ctx>,
(&OriginalMtpScalarPolicy, &mut impl FnMut() -> bool),
),
fallback: ScalarFallback<'_, 'ctx, impl FnMut() -> bool>,
) -> Result<OriginalPromptDraftOutcome> {
match outcome {
OriginalPromptDraftOutcome::Fallback(_) => {
self.record_scalar(rows, owners, workspace, ring, (policy, cancelled))
}
OriginalPromptDraftOutcome::Fallback(_) => self.record_scalar(rows, workspace, fallback),
other => Ok(other),
}
}
@@ -190,26 +209,23 @@ impl<'ctx> DraftKvInputs<'_, 'ctx> {
fn record_scalar(
&self,
rows: &mut PromptDeviceRows<'_, '_, '_, 'ctx>,
(scalar, scalar_weights, retained_mtp): DraftScalarOwners<'_, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
(ring, prior, first_needed): DraftRing<'_, 'ctx>,
(policy, cancelled): (&OriginalMtpScalarPolicy, &mut impl FnMut() -> bool),
fallback: ScalarFallback<'_, 'ctx, impl FnMut() -> bool>,
) -> Result<OriginalPromptDraftOutcome> {
rows.record_original_scalar_draft_kv(
self.binding,
self.dense,
retained_mtp,
self.txn,
self.final_row,
self.sample.next(),
scalar,
workspace,
ring,
prior,
scalar_weights,
first_needed,
policy,
cancelled,
)
let ScalarFallback { owners, ring: draft_ring, policy, cancelled } = fallback;
let DraftScalarOwners { actor, scalar_weights, retained_mtp } = owners;
let DraftRing { ring, prior, first_needed } = draft_ring;
let PromptWeights { binding, dense } = self.weights;
let sources = ScalarPromptSources {
binding,
dense,
mtp: retained_mtp,
txn: self.txn,
preview: self.final_row,
last_next: self.sample.next(),
};
let run = RecordRun { workspace, ring, cancelled };
let kv = ScalarDraftKvSources { prior, retained: scalar_weights, policy };
rows.record_original_scalar_draft_kv(sources, actor, run, ScalarDraftKvRequest { sources: kv, first_needed })
}
}
@@ -37,17 +37,16 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// Ends the chunk's expert stream, then previews the conditioning row and takes its sample.
pub(super) fn prepare_final_row<'arena, 'loan>(
&self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
moe: &mut MoeWeightCache<'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
work: &mut ChunkWork<'_, '_, 'ctx>,
carrier: Carrier<'_, 'arena, 'loan, 'ctx>,
) -> Result<(PromptDeviceRows<'static, 'arena, 'loan, 'ctx>, PromptDeviceFinal, OriginalPromptSample)> {
let PromptWeights { binding, dense } = work.weights;
let txn = work.txn;
let Carrier::Plain(mut rows) = carrier else {
return Err(Error::IdentityMismatch);
};
// the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers
moe.end_prompt_stream()?;
work.moe.end_prompt_stream()?;
let final_span = prof::span(PStage::Final, Some(self.context as &dyn prof::Drain));
trace_step("forward: all layers ok, final row");
let preview = rows.preview_conditioning(binding, dense, txn);
@@ -75,8 +74,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
}
let first = txn.start_position();
let count = txn.len();
let hash =
rows.with_final_residual(binding, dense, txn, final_row, |residual| hash_final_rows(residual, count))?;
let hash = rows.with_final_residual(PromptWeights::new(binding, dense), txn, final_row, |residual| {
hash_final_rows(residual, count)
})?;
eprintln!(
"PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}",
hash.0,
@@ -8,6 +8,22 @@ use crate::qwen_forward::kar_ple_cache::KarPleStaged;
/// two tokens before the chunk (the per-token host path stages nothing).
type StagedPrompt = (Option<StagedInput>, Option<KarPleStaged>, Option<[i32; 2]>);
/// The chunk-wide staged embedding input and staged PLE rows; both are present after the batched staging and both
/// are absent on the per-token host path.
pub(super) struct StagedChunkInput<'a> {
pub(super) input: Option<&'a StagedInput>,
pub(super) ple: Option<KarPleStaged>,
}
/// Everything the device scatter of the staged rows consumes: the arena lease, one source per row and the staged
/// input with its PLE rows.
struct StagedUpload<'a, 'arena, 'loan, 'ctx> {
lease: leleka_cuda_driver::OriginalPromptRows<'arena, 'loan, 'ctx>,
sources: Vec<PromptDeviceSource<'static, 'ctx>>,
input: &'a StagedInput,
ple: KarPleStaged,
}
impl<'ctx> OriginalPromptExecutor<'ctx> {
pub(super) fn stage_prompt_inputs(
binding: &ModelBinding,
@@ -43,7 +59,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
first_predecessors = Some(step.input_predecessors()?);
}
match kar.as_deref() {
Some(cache) => InputStage::consume_kar_deferred(binding, cache, token, pos, step, &mut staged),
Some(cache) => {
let input = crate::qwen_forward::input::PositionedToken { token, position: pos };
InputStage::consume_kar_deferred(binding, cache, input, step, &mut staged)
}
None => Err(Error::IdentityMismatch),
}
})?;
@@ -75,29 +94,31 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
}
/// Source rows, upload and device initialization of the chunk's rows.
#[allow(clippy::too_many_arguments)]
pub(super) fn initialize_prompt_rows<'arena, 'loan>(
&mut self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
tokens: &[TokenId],
chunk: &ChunkInFlight<'_, '_, 'ctx>,
kar: &mut Option<&mut KarPleCache<'ctx>>,
arena: &'arena mut OriginalPrefillArena<'loan, 'ctx>,
(staged_input, staged_ple): (Option<&StagedInput>, Option<KarPleStaged>),
staged: StagedChunkInput<'_>,
) -> Result<PromptDeviceRows<'static, 'arena, 'loan, 'ctx>> {
let weights = chunk.weights;
let (binding, tokens, txn) = (weights.binding, chunk.window, &*chunk.txn);
let drain = Some(self.context as &dyn prof::Drain);
let init_span = prof::span(PStage::Initialize, drain);
let sources = Self::prompt_sources(binding, self.context, txn, tokens.len())?;
let upload_span = prof::span(PStage::InitUpload, drain);
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
let lease = arena.begin_rows(tokens.len()).map_err(driver_error)?;
let rows = match (staged_input, staged_ple) {
let rows = match (staged.input, staged.ple) {
(Some(input), Some(ple)) => {
let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?;
Self::initialize_staged_rows(binding, dense, self.context, prompt, cache, lease, sources, (input, ple))?
let upload = StagedUpload { lease, sources, input, ple };
Self::initialize_staged_rows(weights, self.context, prompt, cache, upload)?
}
_ => {
let upload = RowsUpload { lease, stage: None };
PromptDeviceRows::initialize(weights, self.context, prompt, upload, sources)?
}
_ => PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, None)?,
};
drop(upload_span);
drop(init_span);
@@ -105,17 +126,15 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
}
/// The device scatters the staged embedding and PLE rows; the PLE cache learns them only after that succeeded.
#[allow(clippy::too_many_arguments)]
fn initialize_staged_rows<'arena, 'loan>(
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
weights: PromptWeights<'_, 'ctx>,
context: &'ctx Context<'ctx>,
prompt: &mut OriginalPromptDevice<'ctx>,
cache: &mut KarPleCache<'ctx>,
lease: leleka_cuda_driver::OriginalPromptRows<'arena, 'loan, 'ctx>,
sources: Vec<PromptDeviceSource<'static, 'ctx>>,
(input, ple): (&StagedInput, KarPleStaged),
upload: StagedUpload<'_, 'arena, 'loan, 'ctx>,
) -> Result<PromptDeviceRows<'static, 'arena, 'loan, 'ctx>> {
let PromptWeights { binding, dense } = weights;
let StagedUpload { lease, sources, input, ple } = upload;
let result = Self::scatter_staged_rows(binding, dense, context, (prompt, cache), (lease, sources, input, &ple));
match result {
Ok(rows) => {
@@ -169,19 +188,20 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
ple_updates: ple.updates(),
ple_slots: ple.slots(),
};
PromptDeviceRows::initialize(binding, dense, context, prompt, lease, sources, Some(stage))
let upload = RowsUpload { lease, stage: Some(stage) };
PromptDeviceRows::initialize(PromptWeights::new(binding, dense), context, prompt, upload, sources)
}
/// The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes
/// (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there.
pub(super) fn read_ahead_next_chunk(
&self,
binding: &ModelBinding,
source: &std::rc::Rc<OriginalPromptInput>,
(tokens, first_position): (&[TokenId], u64),
chunk: &ChunkInFlight<'_, '_, 'ctx>,
kar: &mut Option<&mut KarPleCache<'ctx>>,
first_predecessors: Option<[i32; 2]>,
) {
let (binding, source) = (chunk.weights.binding, chunk.source);
let (tokens, first_position) = (chunk.window, chunk.first_position);
let (Some(cache), Some(kar_binding), Some(mut before)) =
(kar.as_deref_mut(), binding.kar_ple_binding(), first_predecessors)
else {
@@ -16,14 +16,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// Layer-major order: every layer completes all rows of the chunk before the next starts.
pub(super) fn run_layers<'w, 'arena, 'loan>(
&mut self,
binding: &ModelBinding,
dense: &'w DenseWeightCache<'ctx>,
moe: &mut MoeWeightCache<'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
work: &mut ChunkWork<'w, '_, 'ctx>,
mut carrier: Carrier<'w, 'arena, 'loan, 'ctx>,
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
let binding = work.weights.binding;
for layer in binding.ordered_layers() {
carrier = self.run_layer(layer, binding, dense, moe, txn, carrier)?;
carrier = self.run_layer(layer, work, carrier)?;
}
Ok(carrier)
}
@@ -31,12 +29,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
fn run_layer<'w, 'arena, 'loan>(
&mut self,
layer: &BoundLayer,
binding: &ModelBinding,
dense: &'w DenseWeightCache<'ctx>,
moe: &mut MoeWeightCache<'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
work: &mut ChunkWork<'w, '_, 'ctx>,
carrier: Carrier<'w, 'arena, 'loan, 'ctx>,
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
let weights = work.weights;
let PromptWeights { binding, dense } = weights;
let txn = work.txn;
let index = layer.index();
crate::bringup_trace!(
"DBG[{:.0}s] forward layer {index} {:?} begin",
@@ -47,10 +45,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
let mut read = self.read_attention(binding, dense, carrier, index)?;
crate::bringup_trace!("DBG[{:.0}s] L{index} attn-read ok", crate::qwen_forward::original_serve_stack::dbg_el());
validated(|| read.validate_original_rows(binding, dense))?;
let ffn = self.complete_mixer(binding, dense, txn, read, layer)?;
let ffn = self.complete_mixer(weights, txn, read, layer)?;
crate::bringup_trace!("DBG[{:.0}s] L{index} mixer ok", crate::qwen_forward::original_serve_stack::dbg_el());
let read = self.read_ffn(binding, dense, ffn, index)?;
let carrier = self.complete_moe(binding, dense, moe, read, index)?;
let carrier = self.complete_moe(weights, &mut *work.moe, read, index)?;
crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok", crate::qwen_forward::original_serve_stack::dbg_el());
Ok(carrier)
}
@@ -105,8 +103,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// The token mixer (GDN or QSA) of the layer, fused with the next norm when `fused`.
fn complete_mixer<'w, 'arena, 'loan>(
&mut self,
binding: &ModelBinding,
dense: &'w DenseWeightCache<'ctx>,
weights: PromptWeights<'w, 'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
layer: &BoundLayer,
@@ -120,9 +117,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
drain,
);
let ffn = if self.fused {
Carrier::Normed(self.mixer_normed(binding, dense, txn, read, layer)?)
Carrier::Normed(self.mixer_normed(weights, txn, read, layer)?)
} else {
Carrier::Plain(self.mixer_plain(binding, dense, txn, read, layer)?)
Carrier::Plain(self.mixer_plain(weights, txn, read, layer)?)
};
drop(mixer_span);
Ok(ffn)
@@ -130,8 +127,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
fn mixer_normed<'w, 'arena, 'loan>(
&mut self,
binding: &ModelBinding,
dense: &'w DenseWeightCache<'ctx>,
weights: PromptWeights<'w, 'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
layer: &BoundLayer,
@@ -139,51 +135,47 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
match layer.kind() {
BoundLayerKind::Gdn => read.complete_original_gdn_normed(
binding,
dense,
weights,
txn,
prompt,
self.gdn.as_mut().ok_or(Error::IdentityMismatch)?,
),
BoundLayerKind::Qsa => read.complete_original_qsa_normed(
binding,
dense,
weights,
txn,
prompt,
self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?,
self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
QsaLayerDevices {
layer_owner: self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?,
qsa: self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
transport: self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
attention: self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
},
),
}
}
fn mixer_plain<'arena, 'loan>(
&mut self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
weights: PromptWeights<'_, 'ctx>,
txn: &OriginalPromptTxn<'_, 'ctx>,
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
layer: &BoundLayer,
) -> Result<PromptDeviceRows<'static, 'arena, 'loan, 'ctx>> {
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
match layer.kind() {
BoundLayerKind::Gdn => read.complete_original_gdn(
binding,
dense,
txn,
prompt,
self.gdn.as_mut().ok_or(Error::IdentityMismatch)?,
),
BoundLayerKind::Gdn => {
read.complete_original_gdn(weights, txn, prompt, self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)
}
BoundLayerKind::Qsa => read.complete_original_qsa(
binding,
dense,
weights,
txn,
prompt,
self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?,
self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
QsaLayerDevices {
layer_owner: self.layers[layer.index() as usize].as_mut().ok_or(Error::IdentityMismatch)?,
qsa: self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,
transport: self.transport.as_mut().ok_or(Error::IdentityMismatch)?,
attention: self.attention.as_mut().ok_or(Error::IdentityMismatch)?,
},
),
}
}
@@ -217,12 +209,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
fn complete_moe<'w, 'arena, 'loan>(
&mut self,
binding: &ModelBinding,
dense: &'w DenseWeightCache<'ctx>,
weights: PromptWeights<'w, 'ctx>,
moe: &mut MoeWeightCache<'ctx>,
read: PromptDeviceRead<'static, 'arena, 'loan, 'ctx>,
index: u32,
) -> Result<Carrier<'w, 'arena, 'loan, 'ctx>> {
let PromptWeights { binding, dense } = weights;
let drain = Some(self.context as &dyn prof::Drain);
let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
let moe_span = prof::span(PStage::Moe, drain);
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::session::original_prompt::DraftRollback;
#[path = "impl_originalpromptexecutor/forward_draft.rs"]
mod forward_draft;
@@ -11,18 +12,12 @@ mod forward_final;
mod forward_input;
#[path = "impl_originalpromptexecutor/forward_layers.rs"]
mod forward_layers;
/// The draft session, its embedding and the scalar policy that record the draft KV of a chunk.
type DraftArgs<'a, 'ctx> =
(&'a mut OriginalDraftSession<'ctx>, &'a OriginalPromptEmbedding<'ctx>, &'a OriginalMtpScalarPolicy);
use forward_draft::DraftKvInputs;
use forward_input::StagedChunkInput;
/// What a completed chunk leaves for the publisher: the final row, its sample and the draft KV.
type ForwardDone = (PromptDeviceFinal, OriginalPromptSample, OriginalDraftKvPending);
/// The draft session and the two checkpoints a failed chunk is rolled back to.
type ForwardRollback<'program, 'ctx> =
(&'program mut OriginalDraftSession<'ctx>, OriginalSessionCheckpoint<'ctx>, OriginalDraftCheckpoint);
/// The initialized rows of a chunk, the two tokens before it and the staged host input that must outlive the chunk.
type StagedRows<'arena, 'loan, 'ctx> =
(PromptDeviceRows<'static, 'arena, 'loan, 'ctx>, Option<[i32; 2]>, Option<StagedInput>);
@@ -41,50 +36,44 @@ fn trace_error(step: &str, error: Error) -> Error {
impl<'ctx> OriginalPromptExecutor<'ctx> {
/// No target position is advanced here. Every read is actual GR arithmetic;
/// recurrent/KV/PLE seals belong to the same still-private source transaction.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn forward<'session, 'program, 'loan>(
&'program mut self,
binding: &'program ModelBinding,
dense: &'program DenseWeightCache<'ctx>,
session: &'session mut QwenSession<'ctx>,
source: &std::rc::Rc<OriginalPromptInput>,
count: usize,
kar: Option<&mut KarPleCache<'ctx>>,
moe: &mut MoeWeightCache<'ctx>,
arena: &mut OriginalPrefillArena<'loan, 'ctx>,
draft: &'program mut OriginalDraftSession<'ctx>,
embedding: &OriginalPromptEmbedding<'ctx>,
policy: &OriginalMtpScalarPolicy,
target: PromptChunkTarget<'session, 'program, 'ctx>,
caches: ChunkCaches<'_, 'loan, 'ctx>,
mut draft: ChunkDraft<'program, 'ctx>,
mut cancelled: impl FnMut() -> bool,
) -> Result<OriginalPromptPending<'session, 'program, 'ctx>> {
let (tokens, first_position) = self.admit_window(binding, dense, session, source, count, arena.capacity())?;
let PromptChunkTarget { weights, session, tokens: chunk_source } = target;
let binding = weights.binding;
let ChunkCaches { kar, moe, arena } = caches;
let (window, first_position) = self.admit_window(weights, session, chunk_source, arena.capacity())?;
let _launch_sync = leleka_cuda_driver::PromptSyncTrace::enter();
if tokens.is_empty() || tokens.len() > self.capacity || arena.capacity() != self.capacity {
if window.is_empty() || window.len() > self.capacity || arena.capacity() != self.capacity {
return Err(Error::InvalidDimension);
}
let checkpoint = session.original_checkpoint(binding)?;
let draft_checkpoint = draft.checkpoint(binding, session)?;
let draft_checkpoint = draft.session.checkpoint(binding, session)?;
let PromptChunkSource { source, count } = chunk_source;
let mut txn = OriginalPromptTxn::begin(session, binding, source, count)?;
let (window, draft_args) = ((tokens, first_position), (&mut *draft, embedding, policy));
let owners = (kar, (&mut *moe, arena));
let operation =
self.forward_operation((binding, dense), &mut txn, (window, source), owners, draft_args, &mut cancelled);
self.finish_forward(operation, (binding, dense), (txn, moe), (draft, checkpoint, draft_checkpoint))
let chunk = ChunkInFlight { weights, txn: &mut txn, window, first_position, source };
let caches = ChunkCaches { kar, moe: &mut *moe, arena };
let operation = self.forward_operation(chunk, caches, draft.reborrow(), &mut cancelled);
let rollback = ChunkRollback { draft: draft.session, checkpoint, draft_checkpoint };
self.finish_forward(operation, weights, OpenChunk { txn, moe }, rollback)
}
/// The prompt window of the chunk and its first position, after the executor accepted the session.
fn admit_window<'src>(
&self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
weights: PromptWeights<'_, 'ctx>,
session: &mut QwenSession<'ctx>,
source: &'src std::rc::Rc<OriginalPromptInput>,
count: usize,
chunk_source: PromptChunkSource<'src>,
arena_capacity: usize,
) -> Result<(&'src [TokenId], u64)> {
self.validate(binding, dense, session)?;
let PromptChunkSource { source, count } = chunk_source;
self.validate(weights.binding, weights.dense, session)?;
let first_position = session.target_origin()?.next_position();
let tokens = source.window(binding, first_position, count)?;
let tokens = source.window(weights.binding, first_position, count)?;
crate::bringup_trace!(
"DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={arena_capacity} count={count}",
crate::qwen_forward::original_serve_stack::dbg_el(),
@@ -98,28 +87,31 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
fn finish_forward<'session, 'program>(
&'program mut self,
operation: Result<ForwardDone>,
(binding, dense): (&'program ModelBinding, &'program DenseWeightCache<'ctx>),
(txn, moe): (OriginalPromptTxn<'session, 'ctx>, &mut MoeWeightCache<'ctx>),
(draft, checkpoint, draft_checkpoint): ForwardRollback<'program, 'ctx>,
weights: PromptWeights<'program, 'ctx>,
open: OpenChunk<'session, '_, 'ctx>,
mut rollback: ChunkRollback<'program, 'ctx>,
) -> Result<OriginalPromptPending<'session, 'program, 'ctx>> {
match operation {
Err(primary) => {
self.forward_failed(binding, dense, txn, moe, (&checkpoint, draft, &draft_checkpoint), &primary);
self.forward_failed(weights, open, &mut rollback, &primary);
Err(primary)
}
Ok((completed, sample, draft_kv)) => Ok(OriginalPromptPending {
txn: Some(txn),
binding,
dense,
layers: &mut self.layers,
failed: &mut self.failed,
checkpoint,
completed,
sample,
draft_kv,
draft,
draft_checkpoint,
}),
Ok((completed, sample, draft_kv)) => {
let ChunkRollback { draft, checkpoint, draft_checkpoint } = rollback;
Ok(OriginalPromptPending {
txn: Some(open.txn),
binding: weights.binding,
dense: weights.dense,
layers: &mut self.layers,
failed: &mut self.failed,
checkpoint,
completed,
sample,
draft_kv,
draft,
draft_checkpoint,
})
}
}
}
@@ -127,57 +119,61 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// the draft KV. Its error is rolled back by `forward`.
fn forward_operation<'loan>(
&mut self,
(binding, dense): (&ModelBinding, &DenseWeightCache<'ctx>),
txn: &mut OriginalPromptTxn<'_, 'ctx>,
(window, source): ((&[TokenId], u64), &std::rc::Rc<OriginalPromptInput>),
(mut kar, (moe, arena)): (
Option<&mut KarPleCache<'ctx>>,
(&mut MoeWeightCache<'ctx>, &mut OriginalPrefillArena<'loan, 'ctx>),
),
draft_args: DraftArgs<'_, 'ctx>,
mut chunk: ChunkInFlight<'_, '_, 'ctx>,
caches: ChunkCaches<'_, 'loan, 'ctx>,
draft: ChunkDraft<'_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<ForwardDone> {
// The last prompt seed belongs to Original Verifier. Every row
// admitted here must have its authentic next token in the source.
txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?;
let (rows, first_predecessors, _staged) =
self.stage_prompt_rows((binding, dense), txn, window.0, (&mut kar, arena))?;
self.read_ahead_next_chunk(binding, source, window, &mut kar, first_predecessors);
let carrier = self.run_layers(binding, dense, moe, txn, Carrier::Plain(rows))?;
self.finish_chunk_rows((binding, dense), (moe, txn), carrier, (draft_args, cancelled))
chunk.txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?;
let ChunkCaches { mut kar, moe, arena } = caches;
let (rows, first_predecessors, _staged) = self.stage_prompt_rows(&mut chunk, &mut kar, arena)?;
self.read_ahead_next_chunk(&chunk, &mut kar, first_predecessors);
let mut work = ChunkWork { weights: chunk.weights, moe, txn: &*chunk.txn };
let carrier = self.run_layers(&mut work, Carrier::Plain(rows))?;
self.finish_chunk_rows(work, carrier, draft, cancelled)
}
/// Stages the inputs of the chunk and initializes its rows on the device; the staged host input is returned
/// because the chunk keeps it until the end.
fn stage_prompt_rows<'arena, 'loan>(
&mut self,
(binding, dense): (&ModelBinding, &DenseWeightCache<'ctx>),
txn: &mut OriginalPromptTxn<'_, 'ctx>,
tokens: &[TokenId],
(kar, arena): (&mut Option<&mut KarPleCache<'ctx>>, &'arena mut OriginalPrefillArena<'loan, 'ctx>),
chunk: &mut ChunkInFlight<'_, '_, 'ctx>,
kar: &mut Option<&mut KarPleCache<'ctx>>,
arena: &'arena mut OriginalPrefillArena<'loan, 'ctx>,
) -> Result<StagedRows<'arena, 'loan, 'ctx>> {
let (staged_input, staged_ple, first_predecessors) = Self::stage_prompt_inputs(binding, txn, tokens, kar)?;
let staged = (staged_input.as_ref(), staged_ple);
let rows = self.initialize_prompt_rows(binding, dense, txn, tokens, kar, arena, staged)?;
let binding = chunk.weights.binding;
let (staged_input, staged_ple, first_predecessors) =
Self::stage_prompt_inputs(binding, &mut *chunk.txn, chunk.window, kar)?;
let staged = StagedChunkInput { input: staged_input.as_ref(), ple: staged_ple };
let rows = self.initialize_prompt_rows(chunk, kar, arena, staged)?;
Ok((rows, first_predecessors, staged_input))
}
/// The final row of the last layer, its sample, the draft KV and the end of the preview.
fn finish_chunk_rows(
&mut self,
(binding, dense): (&ModelBinding, &DenseWeightCache<'ctx>),
(moe, txn): (&mut MoeWeightCache<'ctx>, &mut OriginalPromptTxn<'_, 'ctx>),
mut work: ChunkWork<'_, '_, 'ctx>,
carrier: Carrier<'_, '_, '_, 'ctx>,
(draft_args, cancelled): (DraftArgs<'_, 'ctx>, &mut impl FnMut() -> bool),
draft: ChunkDraft<'_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<ForwardDone> {
let (mut rows, final_row, sample) = self.prepare_final_row(binding, dense, moe, txn, carrier)?;
let chunk = (&mut rows, &final_row, &sample);
let draft_kv = self.record_draft_kv(binding, dense, moe, txn, chunk, draft_args, cancelled)?;
let (mut rows, final_row, sample) = self.prepare_final_row(&mut work, carrier)?;
let inputs = DraftKvInputs {
weights: work.weights,
moe: &*work.moe,
txn: work.txn,
final_row: &final_row,
sample: &sample,
context: self.context,
};
let draft_kv = self.record_draft_kv(inputs, &mut rows, draft, cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Session));
}
let _span = prof::span(PStage::FinishPreview, Some(self.context as &dyn prof::Drain));
rows.finish_after_preview(binding, dense, txn, &final_row)
rows.finish_after_preview(work.weights.binding, work.weights.dense, work.txn, &final_row)
.map_err(|error| trace_error("finish_after_preview", error))?;
Ok((final_row, sample, draft_kv))
}
@@ -185,17 +181,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
/// Roll back after a failed chunk: stop the expert stream, then abort the transaction and the draft.
fn forward_failed(
&mut self,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
txn: OriginalPromptTxn<'_, 'ctx>,
moe: &mut MoeWeightCache<'ctx>,
(checkpoint, draft, draft_checkpoint): (
&OriginalSessionCheckpoint<'ctx>,
&mut OriginalDraftSession<'ctx>,
&OriginalDraftCheckpoint,
),
weights: PromptWeights<'_, 'ctx>,
open: OpenChunk<'_, '_, 'ctx>,
rollback: &mut ChunkRollback<'_, 'ctx>,
primary: &Error,
) {
let OpenChunk { txn, moe } = open;
crate::bringup_trace!(
"DBG[{:.0}s] forward operation failed: {primary:?}",
crate::qwen_forward::original_serve_stack::dbg_el()
@@ -204,7 +195,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
if moe.end_prompt_stream().is_err() {
self.failed = true;
}
let cleanup = txn.abort_with_draft(binding, dense, &mut self.layers, checkpoint, draft, draft_checkpoint);
let ChunkRollback { draft, checkpoint, draft_checkpoint } = rollback;
let rollback = DraftRollback { draft, prior: draft_checkpoint };
let cleanup = txn.abort_with_draft(weights, &mut self.layers, checkpoint, rollback);
if cleanup.is_err() || self.context.is_poisoned() {
self.failed = true;
}
@@ -0,0 +1,66 @@
//! The operand groups one batched prompt chunk passes between the phases of `OriginalPromptExecutor::forward`.
use super::*;
/// The next `count` tokens of the prompt source that one chunk consumes.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct PromptChunkSource<'a> {
pub(in crate::qwen_forward) source: &'a std::rc::Rc<OriginalPromptInput>,
pub(in crate::qwen_forward) count: usize,
}
/// What one chunk advances: the target model weights, the target session and the prompt tokens it consumes.
pub(in crate::qwen_forward) struct PromptChunkTarget<'session, 'program, 'ctx> {
pub(in crate::qwen_forward) weights: PromptWeights<'program, 'ctx>,
pub(in crate::qwen_forward) session: &'session mut QwenSession<'ctx>,
pub(in crate::qwen_forward) tokens: PromptChunkSource<'program>,
}
/// The PLE cache, the expert cache and the device arena a chunk computes in.
pub(in crate::qwen_forward) struct ChunkCaches<'a, 'loan, 'ctx> {
pub(in crate::qwen_forward) kar: Option<&'a mut KarPleCache<'ctx>>,
pub(in crate::qwen_forward) moe: &'a mut MoeWeightCache<'ctx>,
pub(in crate::qwen_forward) arena: &'a mut OriginalPrefillArena<'loan, 'ctx>,
}
/// The draft session of a chunk, the embedding its draft KV is computed from and the scalar draft policy.
pub(in crate::qwen_forward) struct ChunkDraft<'a, 'ctx> {
pub(in crate::qwen_forward) session: &'a mut OriginalDraftSession<'ctx>,
pub(in crate::qwen_forward) embedding: &'a OriginalPromptEmbedding<'ctx>,
pub(in crate::qwen_forward) policy: &'a OriginalMtpScalarPolicy,
}
impl<'ctx> ChunkDraft<'_, 'ctx> {
/// The same draft for a shorter borrow, so the draft session is usable again after the chunk.
pub(in crate::qwen_forward) fn reborrow(&mut self) -> ChunkDraft<'_, 'ctx> {
ChunkDraft { session: &mut *self.session, embedding: self.embedding, policy: self.policy }
}
}
/// A chunk whose inputs are being staged: its weights, open prompt transaction and the window it consumes.
pub(super) struct ChunkInFlight<'a, 'txn, 'ctx> {
pub(super) weights: PromptWeights<'a, 'ctx>,
pub(super) txn: &'a mut OriginalPromptTxn<'txn, 'ctx>,
pub(super) window: &'a [TokenId],
pub(super) first_position: u64,
pub(super) source: &'a std::rc::Rc<OriginalPromptInput>,
}
/// What every layer and the final row of a chunk work against: weights, expert cache and prompt transaction.
pub(super) struct ChunkWork<'a, 'txn, 'ctx> {
pub(super) weights: PromptWeights<'a, 'ctx>,
pub(super) moe: &'a mut MoeWeightCache<'ctx>,
pub(super) txn: &'a OriginalPromptTxn<'txn, 'ctx>,
}
/// The still-open prompt transaction of a chunk and the expert cache whose prompt stream a failure must end.
pub(super) struct OpenChunk<'session, 'a, 'ctx> {
pub(super) txn: OriginalPromptTxn<'session, 'ctx>,
pub(super) moe: &'a mut MoeWeightCache<'ctx>,
}
/// The draft session and the two checkpoints a failed chunk is rolled back to.
pub(super) struct ChunkRollback<'program, 'ctx> {
pub(super) draft: &'program mut OriginalDraftSession<'ctx>,
pub(super) checkpoint: OriginalSessionCheckpoint<'ctx>,
pub(super) draft_checkpoint: OriginalDraftCheckpoint,
}
@@ -5,7 +5,8 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::executor::{PrefillStepProduct, TargetStepProduct};
use crate::qwen_forward::executor::{PrefillStepProduct, StepCaches, StepRequest, TargetStepProduct};
use crate::qwen_forward::mtp::KnownNext;
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
use crate::qwen_forward::mtp_decode::MtpDecoder;
use crate::qwen_forward::session::ResetReplaySnapshot;
@@ -65,25 +66,15 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
fn prefill(&mut self, ids: &Ids, (token, n): (TokenId, u64), what: &str) -> PrefillStepProduct {
let position = ids.position(n);
let kar = Some(&mut *self.kar);
QwenForward::prefill_for_mtp_cached(
self.binding,
token,
position,
self.session,
self.output,
kar,
self.moe,
self.dense,
)
.expect(what)
let request = StepRequest { binding: self.binding, token, position };
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches).expect(what)
}
fn step_final(&mut self, ids: &Ids) -> TargetStepProduct {
let (kar, moe) = (Some(&mut *self.kar), Some(&mut *self.moe));
let position = ids.position(3);
let (binding, output, dense) = (self.binding, self.output, Some(self.dense));
QwenForward::step_for_mtp_cached(binding, ids.ids[3], position, self.session, output, kar, moe, dense)
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
let request = StepRequest { binding: self.binding, token: ids.ids[3], position: ids.position(3) };
QwenForward::step_for_mtp_cached(request, self.session, self.output, caches)
.expect("scalar final target refused")
}
@@ -120,7 +111,12 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
let source = self.prefill(ids, (ids.ids[index], index as u64), "scalar known-next target refused");
let successor = ids.ids[index + 1];
draft
.warm_prefill(self.binding, self.session, &source, successor, self.moe)
.warm_prefill(
self.binding,
self.session,
KnownNext { source: &source, next_token: successor },
self.moe,
)
.expect("scalar known-next warm refused");
}
let source = self.step_final(ids);
@@ -142,10 +138,12 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
source: &TargetStepProduct,
) -> (ResetReplaySnapshot, MtpChunkNumericSnapshot) {
let (binding, next) = (self.binding, ids.next);
draft.warm_retained(binding, self.session, source, next, self.moe).expect("scalar retained edge refused");
draft
.warm_retained(binding, self.session, KnownNext { source, next_token: next }, self.moe)
.expect("scalar retained edge refused");
let continuation = self.prefill(ids, (next, 4), "scalar continuation refused");
draft
.warm_prefill(binding, self.session, &continuation, ids.follow, self.moe)
.warm_prefill(binding, self.session, KnownNext { source: &continuation, next_token: ids.follow }, self.moe)
.expect("scalar continuation warm refused");
let state = self.snapshot("scalar continuation state invalid");
(state, draft.test_chunk_snapshot())
@@ -232,13 +230,20 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
assert!(candidate.test_chunk_eq(&baseline.draft), "actual draft KV/residual mismatch");
let (binding, next) = (self.binding, ids.next);
candidate.validate_resume(binding, self.session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused");
candidate.warm_retained(binding, self.session, &actual, next, self.moe).expect("chunk retained edge refused");
candidate
.warm_retained(binding, self.session, KnownNext { source: &actual, next_token: next }, self.moe)
.expect("chunk retained edge refused");
}
/// The continuation row after the chunk matches the scalar continuation.
fn compare_continuation(&mut self, ids: &Ids, baseline: &Baseline, candidate: &mut MtpDecoder) {
let continuation = self.prefill(ids, (ids.next, 4), "chunk continuation refused");
let warm = candidate.warm_prefill(self.binding, self.session, &continuation, ids.follow, self.moe);
let warm = candidate.warm_prefill(
self.binding,
self.session,
KnownNext { source: &continuation, next_token: ids.follow },
self.moe,
);
warm.expect("chunk continuation warm refused");
let state = self.snapshot("chunk continuation invalid");
assert!(baseline.continued_state.numeric_eq(&state), "continued target mismatch");
@@ -105,8 +105,10 @@ impl QwenForward {
layer,
prepared,
txn,
Some(dense),
dense.qsa_attention_workspace(),
crate::qwen_forward::qsa_attention::attention_scratch::QsaScratchLoan {
cache: Some(dense),
scratch: dense.qsa_attention_workspace(),
},
),
)
}
@@ -91,7 +91,8 @@ impl QwenForward {
return Err(Error::Unsupported(Stage::Executor));
}
let prior = previous[index].as_ref();
prepare_layer_attention_micro(env.binding, layer, prior, txn, env.dense, ple_micro.as_deref_mut())
let entry = LayerEntry { layer, previous: prior };
prepare_layer_attention_micro(env.binding, entry, txn, env.dense, ple_micro.as_deref_mut())
},
|inputs| {
let (bank, rows) = Self::read_micro_bank(env, inputs)?;
@@ -3,7 +3,9 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::gr::GrBatchRow;
use crate::qwen_forward::moe_expert::ExpertReady;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use crate::qwen_forward::moe_expert::NativePromptFinish;
use crate::qwen_forward::moe_expert::{ChunkFfnLayer, ExpertReady};
use crate::qwen_forward::session::chunk::{ChunkFfnRow, FfnInjectionRow, PreparedLayerRow};
/// Releases the native MoE products of the window, if it had any.
@@ -77,13 +79,17 @@ impl QwenForward {
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
ChunkMoePolicy::Layer0Diagnostic => Err(Error::IdentityMismatch),
ChunkMoePolicy::Native | ChunkMoePolicy::ExperimentalRetainedGr => {
MoeExpertStage::execute_chunk(binding, layer, ffn_rows, chunk, moe_cache, cancelled)
let ffn = ChunkFfnLayer { binding, layer, rows: ffn_rows };
MoeExpertStage::execute_chunk(ffn, chunk, moe_cache, cancelled)
}
ChunkMoePolicy::ExperimentalResidentMmq
| ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr
| ChunkMoePolicy::ExperimentalMtpVerification => {
MoeExpertStage::execute_chunk_mmq(binding, layer, ffn_rows, chunk, moe_cache, cancelled)
}
| ChunkMoePolicy::ExperimentalMtpVerification => MoeExpertStage::execute_chunk_mmq(
ChunkFfnLayer { binding, layer, rows: ffn_rows },
chunk,
moe_cache,
cancelled,
),
}
}
@@ -103,9 +109,9 @@ impl QwenForward {
let products = native_moe.as_mut().ok_or(Error::IdentityMismatch);
Some(products.and_then(|products| {
let binding = env.binding;
MoeExpertStage::execute_chunk_mmq_native_prompt(
binding, layer, ffn_rows, chunk, moe_cache, cancelled, products, env.dense,
)
let ffn = ChunkFfnLayer { binding, layer, rows: ffn_rows };
let finish = NativePromptFinish { products, dense: env.dense };
MoeExpertStage::execute_chunk_mmq_native_prompt(ffn, chunk, moe_cache, cancelled, finish)
}))
}
@@ -7,7 +7,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::gdn::chunk_device::GdnChunkDevice;
use crate::qwen_forward::gr::{DetachedGrRead, GrMicroAttentionBank, GrMicroAttentionBlock};
use crate::qwen_forward::gr::{DetachedGrRead, GrMicroAttentionBank, GrMicroAttentionBlock, MicroBlockRequest};
use crate::qwen_forward::moe_prefill_batch::MoeMicroProducts;
use crate::qwen_forward::q6_attention_columns::ProjectionRow;
use crate::qwen_forward::session::chunk::{ChunkAttentionRow, ChunkFfnRow, PreparedLayerRow};
@@ -36,15 +36,20 @@ fn route_shared_micro<'driver>(
let router = cache.router(binding, layer.get())?;
let transient = MoePrefillStage::transient_bytes(inputs.len(), MoeBf16Profile::HighOnly)?;
moe_cache.reserve_mmq_transient(binding, current, transient)?;
moe_cache.with_native_shared_weights(binding, current, layer, transient, |context, weights, resources| {
cache.retained_context(binding, context)?;
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
let gemm = workspace.gdn_gemm().map_err(crate::qwen_forward::qsa_index::driver_error)?;
let window = WindowReads { binding, layer, reads: inputs };
let operands = WindowOperands { router, weights: &weights, combine: None };
let loans = PrefillLoans { current: context, resources, gemm: &gemm };
MoePrefillStage::route_shared_micro(window, operands, loans)
})
moe_cache.with_native_shared_weights(
binding,
current,
crate::qwen_forward::moe_weight_cache::SharedWeightsRequest { layer, transient_bytes: transient },
|context, weights, resources| {
cache.retained_context(binding, context)?;
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
let gemm = workspace.gdn_gemm().map_err(crate::qwen_forward::qsa_index::driver_error)?;
let window = WindowReads { binding, layer, reads: inputs };
let operands = WindowOperands { router, weights: &weights, combine: None };
let loans = PrefillLoans { current: context, resources, gemm: &gemm };
MoePrefillStage::route_shared_micro(window, operands, loans)
},
)
}
/// The FFN row of every proof and detached read: routed from the shared products or from the FFN read.
@@ -62,6 +62,7 @@ fn gdn_micro_block(
result.validate_origin(&env.binding.identity())?;
result.identity().validate(txn.token(), txn.position(), env.layer)?;
let (output, identity) = (result.output(), result.identity());
let block = GrStage::prepare_micro_attention_block(env.binding, bank, local, read, output, identity, txn)?;
let request = MicroBlockRequest { index: local, read, block: output, identity };
let block = GrStage::prepare_micro_attention_block(env.binding, bank, request, txn)?;
Ok((block, result.into_edge()))
}
@@ -61,7 +61,8 @@ fn device_gdn_block<'ctx>(
result.validate_origin(&binding.identity())?;
result.identity().validate(token, position, layer)?;
let (output, identity) = (result.output(), result.identity());
let block = GrStage::prepare_micro_attention_block(binding, bank, local, read, output, identity, txn)?;
let request = MicroBlockRequest { index: local, read, block: output, identity };
let block = GrStage::prepare_micro_attention_block(binding, bank, request, txn)?;
Ok((block, result.into_edge()))
}
@@ -78,11 +79,13 @@ fn host_block<'ctx>(
BoundLayerKind::Gdn => {
let result =
QwenForward::gdn_host_attention((binding, cache), layer, ids, (txn, read), projection.first_mut())?;
GrStage::prepare_micro_attention_block(binding, bank, local, read, result.output(), result.identity(), txn)
let request = MicroBlockRequest { index: local, read, block: result.output(), identity: result.identity() };
GrStage::prepare_micro_attention_block(binding, bank, request, txn)
}
BoundLayerKind::Qsa => {
let result = QwenForward::qsa_host_attention((binding, cache), layer, ids, (txn, read), projection)?;
GrStage::prepare_micro_attention_block(binding, bank, local, read, result.output(), result.identity(), txn)
let request = MicroBlockRequest { index: local, read, block: result.output(), identity: result.identity() };
GrStage::prepare_micro_attention_block(binding, bank, request, txn)
}
}
}
@@ -3,12 +3,13 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::gr::ResidualReady;
use crate::qwen_forward::prompt_device_rows::PromptWeights;
use crate::qwen_forward::qsa_attention::QsaReady;
use crate::qwen_forward::qsa_attention::{
NativeAttended, NativePromptAttentionBatch, NativePromptAttentionBatch as Batch, PromptDevices,
};
use crate::qwen_forward::qsa_native_resources::NativeQsaResources;
use crate::qwen_forward::qsa_prefill_batch::NativeProjectionRow;
use crate::qwen_forward::qsa_prefill_batch::{AttendedRows, NativeProjectionRow, NativeQsaDevices};
use crate::qwen_forward::qsa_prompt_index::{self, PromptChunkOwners, PromptIndexDevices};
use leleka_cuda_driver::{QsaPromptAttention, QsaPromptIndexWorkspace, QsaPromptKv, QsaPromptStage};
@@ -51,14 +52,13 @@ fn qsa_native_project<'source, 'ctx>(
let (binding, cache) = (env.binding, env.cache);
let mut owner = cache.qsa_native_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?;
let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?;
let devices = NativeQsaDevices { owner: &mut owner, workspace: &mut workspace };
crate::qwen_forward::qsa_prefill_batch::project(
binding,
cache,
PromptWeights::new(binding, cache),
chunk,
env.layer,
inputs,
&mut owner,
&mut workspace,
devices,
)
}
@@ -143,16 +143,9 @@ fn qsa_native_project_out<'ctx>(
let mut owner = cache.qsa_native_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?;
let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?;
let layer = env.layer;
crate::qwen_forward::qsa_prefill_batch::project_out(
binding,
cache,
chunk,
layer,
attended,
proofs,
&mut owner,
&mut workspace,
)
let devices = NativeQsaDevices { owner: &mut owner, workspace: &mut workspace };
let rows = AttendedRows { rows: attended, proofs };
crate::qwen_forward::qsa_prefill_batch::project_out(PromptWeights::new(binding, cache), chunk, layer, rows, devices)
}
/// One attention block per row from the projected-out QSA results.
@@ -172,7 +165,8 @@ fn qsa_native_output_blocks<'ctx>(
result.validate_origin(&env.binding.identity(), env.layer)?;
result.identity().validate(txn.token(), txn.position(), env.layer)?;
let (output, identity) = (result.output(), result.identity());
GrStage::prepare_micro_attention_block(env.binding, bank, local, read, output, identity, txn)
let request = MicroBlockRequest { index: local, read, block: output, identity };
GrStage::prepare_micro_attention_block(env.binding, bank, request, txn)
})?;
micro.blocks.push(block);
}
@@ -2,6 +2,7 @@
//! The returned report owns only counts/booleans; its assertions belong AFTER
//! the caller has closed all actual GPU owners and checked allocated_bytes=0.
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use crate::qwen_forward::mtp_decode::MtpDecoder;
use std::{cell::Cell, rc::Rc};
@@ -94,16 +95,12 @@ impl WindowProofReport {
}
impl QwenForward {
pub(crate) fn test_window_boundaries_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
pub(crate) fn test_window_boundaries_on_loaded(
owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>,
) -> Result<WindowProofReport> {
let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners;
// Early errors still return to the root-owned cleanup envelope.
let result = run(binding, session, output, kar, moe, dense);
let result = run(binding, session, ProofDevices { output, kar, moe, dense });
if result.is_ok() {
output.test_reset_replay_record(false)?;
}
@@ -128,17 +125,14 @@ fn tokens(count: usize, vocab: Dimension) -> Result<Vec<TokenId>> {
#[path = "executor_window_numeric/proof.rs"]
mod proof;
use proof::{CancelReport, CandidateReport, Proof};
use proof::{CancelReport, CandidateReport, Proof, ProofDevices};
fn run<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
devices: ProofDevices<'_, '_, '_, '_, 'driver, '_>,
) -> Result<WindowProofReport> {
let mut proof = Proof::open(binding, session, output, kar, moe, dense)?;
let mut proof = Proof::open(binding, session, devices)?;
// A: unchanged actual Native4 target/draft path FIRST. The new candidate
// changes only the sealed window size; no retrospective baseline policy.
let baseline = proof.baseline()?;
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::mtp::KnownNext;
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
use crate::qwen_forward::session::ResetReplaySnapshot;
@@ -56,31 +57,41 @@ fn count_differences<A, B>(a: &[A], b: &[B], same: impl Fn(&A, &B) -> bool) -> u
if a.len() == b.len() { a.iter().zip(b).filter(|(x, y)| !same(x, y)).count() } else { usize::MAX }
}
/// The output head and the weight caches the proof drives, borrowed from the loaded target owners.
pub(super) struct ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd> {
pub(super) output: &'a OutputStage<'o, 'p>,
pub(super) kar: &'a mut KarPleCache<'k>,
pub(super) moe: &'a mut MoeWeightCache<'driver>,
pub(super) dense: &'a DenseWeightCache<'d>,
}
/// The rows of one windowed prefill chunk: the model they run on, their tokens and the known next token.
#[derive(Clone, Copy)]
struct ChunkRequest<'a> {
binding: &'a ModelBinding,
ids: &'a [TokenId],
known_next: Option<TokenId>,
}
/// The windowed prefill transaction under the experimental retained-GR policy. The transaction borrows only the
/// session; every other owner is reborrowed for this call alone.
#[allow(clippy::too_many_arguments)]
fn prepare_txn<'s, 'driver>(
binding: &ModelBinding,
request: ChunkRequest<'_>,
session: &'s mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
ids: &[TokenId],
known_next: Option<TokenId>,
devices: &mut ProofDevices<'_, '_, '_, '_, 'driver, '_>,
boundary: BoundaryPlan,
cancelled: impl FnMut() -> bool,
) -> Result<QwenChunkTxn<'s, 'driver>> {
let policy = ChunkMoePolicy::ExperimentalRetainedGr;
QwenForward::prepare_prefill_chunk_with_policy_windowed(
binding,
ids,
known_next,
request.binding,
request.ids,
request.known_next,
session,
output,
Some(kar),
moe,
dense,
devices.output,
Some(&mut *devices.kar),
&mut *devices.moe,
devices.dense,
HOST_BUDGET,
cancelled,
policy,
@@ -93,10 +104,7 @@ fn prepare_txn<'s, 'driver>(
pub(super) struct Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
pub(super) binding: &'a ModelBinding,
pub(super) session: &'a mut QwenSession<'driver>,
pub(super) output: &'a OutputStage<'o, 'p>,
pub(super) kar: &'a mut KarPleCache<'k>,
pub(super) moe: &'a mut MoeWeightCache<'driver>,
pub(super) dense: &'a DenseWeightCache<'d>,
pub(super) devices: ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd>,
pub(super) vocab: Dimension,
pub(super) bounds: Dimension,
pub(super) ids: Vec<TokenId>,
@@ -109,10 +117,7 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
pub(super) fn open(
binding: &'a ModelBinding,
session: &'a mut QwenSession<'driver>,
output: &'a OutputStage<'o, 'p>,
kar: &'a mut KarPleCache<'k>,
moe: &'a mut MoeWeightCache<'driver>,
dense: &'a DenseWeightCache<'d>,
devices: ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd>,
) -> Result<Self> {
let vocab = Dimension::new(248320)?;
let bounds = crate::qwen_forward::contract::position_dimension();
@@ -121,8 +126,8 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) {
return Err(Error::IdentityMismatch);
}
output.test_reset_replay_record(true)?;
Ok(Self { binding, session, output, kar, moe, dense, vocab, bounds, ids, next, follow })
devices.output.test_reset_replay_record(true)?;
Ok(Self { binding, session, devices, vocab, bounds, ids, next, follow })
}
}
@@ -142,7 +147,12 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
let product = self.baseline_prefill(&mut draft)?;
let (logits, greedy, bits) = self.baseline_outputs(&product)?;
let (target, mtp) = self.snapshots(&draft)?;
draft.warm_retained(self.binding, self.session, &product, self.next, self.moe)?;
draft.warm_retained(
self.binding,
self.session,
KnownNext { source: &product, next_token: self.next },
self.devices.moe,
)?;
self.continuation(&mut draft)?;
let (continued_target, continued_mtp) = self.snapshots(&draft)?;
drop(product);
@@ -158,10 +168,10 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
None,
self.session,
draft,
self.output,
Some(&mut *self.kar),
self.moe,
self.dense,
self.devices.output,
Some(&mut *self.devices.kar),
self.devices.moe,
self.devices.dense,
HOST_BUDGET,
|| false,
)?
@@ -169,7 +179,7 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
}
fn baseline_outputs(&self, product: &TargetStepProduct) -> Result<(Box<[u32]>, TokenId, Vec<u32>)> {
let logits = self.output.test_reset_replay_take_logits()?;
let logits = self.devices.output.test_reset_replay_take_logits()?;
let greedy = product.predicted(self.session)?;
let stream = product.streams(self.binding, self.ids[3], Position::new(3, self.bounds)?, self.session)?;
let mut bits = Vec::new();
@@ -181,24 +191,26 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
/// The continuation row after the window: one more actual prefill step, then the draft warm.
fn continuation(&mut self, draft: &mut MtpDecoder) -> Result<()> {
let position = Position::new(4, self.bounds)?;
let step = QwenForward::prefill_for_mtp_cached(
let request = StepRequest { binding: self.binding, token: self.next, position };
let caches = StepCaches {
kar: Some(&mut *self.devices.kar),
moe: Some(&mut *self.devices.moe),
dense: Some(self.devices.dense),
};
let step = QwenForward::prefill_for_mtp_cached(request, self.session, self.devices.output, caches)?;
draft.warm_prefill(
self.binding,
self.next,
position,
self.session,
self.output,
Some(&mut *self.kar),
self.moe,
self.dense,
KnownNext { source: &step, next_token: self.follow },
self.devices.moe,
)?;
draft.warm_prefill(self.binding, self.session, &step, self.follow, self.moe)?;
Ok(())
}
pub(super) fn candidate(&mut self, base: &Baseline) -> Result<CandidateReport> {
let mut draft = MtpDecoder::new(self.binding)?;
let (product, full_journal) = self.stage_full_micro(&mut draft)?;
let logits = self.output.test_reset_replay_take_logits()?;
let logits = self.devices.output.test_reset_replay_take_logits()?;
let position = Position::new(3, self.bounds)?;
let stream = product.streams(self.binding, self.ids[3], position, self.session)?;
let logit_differences = count_differences(&base.logits, &logits, |a, b| a == b);
@@ -229,19 +241,24 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
product: &TargetStepProduct,
) -> Result<(bool, bool)> {
draft.validate_resume(self.binding, self.session, product, &[0, 1, 0, 1])?;
draft.warm_retained(self.binding, self.session, product, self.next, self.moe)?;
draft.warm_retained(
self.binding,
self.session,
KnownNext { source: product, next_token: self.next },
self.devices.moe,
)?;
self.continuation(draft)?;
let target_equal = base.continued_target.numeric_eq(&self.snapshot()?);
Ok((target_equal, draft.test_chunk_eq(&base.continued_mtp)))
}
fn stage_full_micro(&mut self, draft: &mut MtpDecoder) -> Result<(TargetStepProduct, Journal)> {
let (binding, output, dense) = (self.binding, self.output, self.dense);
let binding = self.binding;
let plan = BoundaryPlan::FullMicro2;
let mut txn =
prepare_txn(binding, self.session, output, self.kar, self.moe, dense, &self.ids, None, plan, || false)?;
let request = ChunkRequest { binding, ids: &self.ids, known_next: None };
let mut txn = prepare_txn(request, self.session, &mut self.devices, plan, || false)?;
let journal = owned_journal(&txn)?;
let ready = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false)?;
let ready = draft.stage_prefill_chunk(binding, &mut txn, self.devices.moe, || false)?;
let source = txn.publish_joint(ready)?.into_target_product().ok_or(Error::IdentityMismatch)?;
Ok((source, journal))
}
@@ -277,13 +294,14 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
}
fn stage_first_layer(&mut self, ids: &[TokenId], draft: &mut MtpDecoder) -> Result<FirstLayer> {
let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next));
let binding = self.binding;
let plan = BoundaryPlan::FirstLayer;
let mut txn = prepare_txn(binding, self.session, output, self.kar, self.moe, dense, ids, next, plan, || false)?;
let request = ChunkRequest { binding, ids, known_next: Some(self.next) };
let mut txn = prepare_txn(request, self.session, &mut self.devices, plan, || false)?;
let finite_words = txn.test_partial_words();
let journal = owned_journal(&txn)?;
let publication_refused = txn.test_publication_preflight_refused();
let staged = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false);
let staged = draft.stage_prefill_chunk(binding, &mut txn, self.devices.moe, || false);
let mtp_refused = matches!(staged, Err(Error::IdentityMismatch));
Ok(FirstLayer { finite_words, journal, publication_refused, mtp_refused })
}
@@ -311,8 +329,8 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
/// The caches still validate against the MTP context, which must not be poisoned.
fn healthy(&mut self) -> Result<bool> {
let context = self.session.mtp_context()?;
self.moe.validate(self.binding, context)?;
self.dense.validate(self.binding)?;
self.devices.moe.validate(self.binding, context)?;
self.devices.dense.validate(self.binding)?;
Ok(!context.is_poisoned())
}
@@ -323,10 +341,8 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
observed: Rc::clone(observation),
cancelled: Rc::clone(&cancellation),
};
let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next));
let (session, kar, moe) = (&mut *self.session, &mut *self.kar, &mut *self.moe);
let prepared =
prepare_txn(binding, session, output, kar, moe, dense, &actual_ids, next, plan, || cancellation.get());
let request = ChunkRequest { binding: self.binding, ids: &actual_ids, known_next: Some(self.next) };
let prepared = prepare_txn(request, self.session, &mut self.devices, plan, || cancellation.get());
Ok(matches!(prepared, Err(Error::Unsupported(Stage::Executor))))
}
}
@@ -97,7 +97,7 @@ mod batch_chunk;
pub(in crate::qwen_forward) use batch_chunk::GrBatchRow;
pub(in crate::qwen_forward) use batch_chunk::GrMicroAttentionBlock as GrMicroBlock;
pub(in crate::qwen_forward) use batch_chunk::{
GrMicroAttention, GrMicroAttentionBank, GrMicroAttentionBlock, GrMicroInput,
GrMicroAttention, GrMicroAttentionBank, GrMicroAttentionBlock, GrMicroInput, MicroBlockRequest,
};
#[path = "gr_attention_chunk.rs"]
@@ -4,6 +4,13 @@
use super::super::dense_weight_cache::GrResident;
use super::*;
/// What one GR read consumes: the residual role being read, whose token/layer it belongs to and its streams.
pub(super) struct GrReadSource<'streams> {
role: GrRole,
identity: TokenLayer,
streams: &'streams [f32],
}
impl GrStage {
pub(in super::super) fn apply<'cache, 'ctx>(
binding: &ModelBinding,
@@ -22,7 +29,8 @@ impl GrStage {
return Err(Error::IdentityMismatch);
}
let identity = TokenLayer::new(input.token(), input.position(), layer);
Self::read(binding, GrRole::Attention(layer.get()), identity, input.streams().values(), txn, cache)
let source = GrReadSource { role: GrRole::Attention(layer.get()), identity, streams: input.streams().values() };
Self::read(binding, source, txn, cache)
}
pub(in super::super) fn read_ffn<'cache, 'ctx>(
@@ -34,7 +42,9 @@ impl GrStage {
) -> Result<GrRead<'cache, 'ctx>> {
residual.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
residual.identity.validate(txn.token(), txn.position(), layer)?;
Self::read(binding, GrRole::Ffn(layer.get()), residual.identity, residual.streams(), txn, cache)
let source =
GrReadSource { role: GrRole::Ffn(layer.get()), identity: residual.identity, streams: residual.streams() };
Self::read(binding, source, txn, cache)
}
pub(in super::super) fn read_attention<'cache, 'ctx>(
@@ -54,14 +64,12 @@ impl GrStage {
residual.validate_origin(&binding.identity(), GrRole::Ffn(previous))?;
let previous_layer = LayerId::new(u64::from(previous), Dimension::new(u64::from(binding.layer_count()))?)?;
residual.identity.validate(txn.token(), txn.position(), previous_layer)?;
Self::read(
binding,
GrRole::Attention(layer.get()),
TokenLayer::new(txn.token(), txn.position(), layer),
residual.streams(),
txn,
cache,
)
let source = GrReadSource {
role: GrRole::Attention(layer.get()),
identity: TokenLayer::new(txn.token(), txn.position(), layer),
streams: residual.streams(),
};
Self::read(binding, source, txn, cache)
}
pub(in super::super) fn read_attention_after_ple<'cache, 'ctx>(
@@ -78,17 +86,17 @@ impl GrStage {
}
ple.validate_origin(&binding.identity())?;
ple.identity().validate(txn.token(), txn.position(), layer)?;
Self::read(binding, GrRole::Attention(1), ple.identity(), ple.streams(), txn, cache)
let source = GrReadSource { role: GrRole::Attention(1), identity: ple.identity(), streams: ple.streams() };
Self::read(binding, source, txn, cache)
}
pub(super) fn read<'cache, 'ctx>(
binding: &ModelBinding,
role: GrRole,
identity: TokenLayer,
streams: &[f32],
source: GrReadSource<'_>,
txn: &mut QwenStepTxn,
cache: Option<&'cache DenseWeightCache<'ctx>>,
) -> Result<GrRead<'cache, 'ctx>> {
let GrReadSource { role, identity, streams } = source;
let context = Self::admit_read(binding, identity, streams, txn)?;
let resident = cache.map(|c| c.gr(binding, role)).transpose()?;
let weights = resolve_gr_weights(binding, role, resident)?;
@@ -18,6 +18,13 @@ pub(super) struct Stage<'c> {
pub(super) failed: &'c Rc<Cell<bool>>,
}
// The expectations every handoff round is compared with: the weights and the allocation before the proof.
#[derive(Clone, Copy)]
struct HandoffBaseline<'m, 'c> {
weights: Weights<'m, 'c>,
allocated_bytes_before: usize,
}
impl<'c> Stage<'c> {
fn weights<'m>(matrices: &'m [DeviceBuffer<'c>]) -> Result<Weights<'m, 'c>> {
matrices.try_into().map_err(|_| Error::InvalidDimension)
@@ -312,7 +319,7 @@ impl<'c> Stage<'c> {
let (expected, block) = self.refusal_phase(&mut lease, matrices, before, tally)?;
let weights = Self::weights(matrices)?;
self.lease_refusals(&mut lease, weights, (&expected, &block), tally)?;
self.handoff_rounds(cell, &mut lease, weights, before, tally)?;
self.handoff_rounds(cell, &mut lease, HandoffBaseline { weights, allocated_bytes_before: before }, tally)?;
self.replace_refusals(&mut lease, tally)?;
// Abort exposes no readiness capability. Next actual call fully
// overwrites the failed candidate and all FFN read outputs.
@@ -331,13 +338,12 @@ impl<'c> Stage<'c> {
&self,
cell: &RefCell<GrScratch<'c>>,
lease: &mut GrScratch<'c>,
weights: Weights<'_, 'c>,
before: usize,
baseline: HandoffBaseline<'_, 'c>,
tally: &mut Tally,
) -> Result<()> {
for pattern in [0, 1, 1, 2] {
self.handoff_check(lease, weights, pattern, tally)?;
if self.context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() {
self.handoff_check(lease, baseline.weights, pattern, tally)?;
if self.context.allocated_bytes() != baseline.allocated_bytes_before || cell.try_borrow_mut().is_ok() {
tally.differences += 1;
}
tally.guards += 1;
@@ -1,5 +1,9 @@
//! Closed prepared producer for the actual chunk FFN injection.
use super::*;
#[path = "gr_batch_chunk/gr_batch_operands.rs"]
mod gr_batch_operands;
pub(in crate::qwen_forward) use gr_batch_operands::{GrBatchScope, MicroBlockRequest};
/// An immutable current-row input minted only by one of the three original
/// producer paths, within the caller's authentic chunk phase fence.
pub(in crate::qwen_forward) struct GrMicroInput {
@@ -49,9 +53,9 @@ mod impl_grmicroinput;
pub(super) use impl_grmicroinput::micro_driver_error;
#[allow(unused_imports)]
pub(super) use impl_grmicroinput::save_micro_values;
#[path = "gr_batch_chunk/batch_inject.rs"]
mod batch_inject;
#[path = "gr_batch_chunk/impl_grstage.rs"]
mod impl_grstage;
#[path = "gr_batch_chunk/impl_grstage_2.rs"]
mod impl_grstage_2;
#[path = "gr_batch_chunk/inject_batch_fns.rs"]
mod inject_batch_fns;
@@ -124,17 +124,15 @@ pub(super) fn finish_queued(
/// The generic device path: upload, inject, download and release every owner whatever the outcome.
pub(super) fn device_inject<'c>(
binding: &ModelBinding,
context: &'c Context<'c>,
cache: &DenseWeightCache<'_>,
scope: GrBatchScope<'_, 'c>,
failed: &Cell<bool>,
rows: Vec<GrBatchRow>,
operands: &BatchOperands,
) -> Result<Vec<InjectedResidual>> {
admit_budget(context, rows.len() * (2 * 40960 + 10240 + 16))?;
admit_budget(scope.context, rows.len() * (2 * 40960 + 10240 + 16))?;
let (mut residual, mut output, mut injection, mut candidate) = (None, None, None, None);
let mut owners = [&mut residual, &mut output, &mut injection, &mut candidate];
let result = inject_on_device(binding, context, cache, rows, operands, &mut owners);
let result = inject_on_device(scope, rows, operands, &mut owners);
// Attempt every owned release even after a CUDA or finite refusal.
let mut cleanup = Ok(());
for buffer in [candidate, injection, output, residual].into_iter().flatten() {
@@ -152,13 +150,12 @@ pub(super) fn device_inject<'c>(
type Owners<'a, 'c> = [&'a mut Option<DeviceBuffer<'c>>; 4];
fn inject_on_device<'c>(
binding: &ModelBinding,
context: &'c Context<'c>,
cache: &DenseWeightCache<'_>,
scope: GrBatchScope<'_, 'c>,
rows: Vec<GrBatchRow>,
operands: &BatchOperands,
owners: &mut Owners<'_, 'c>,
) -> Result<Vec<InjectedResidual>> {
let GrBatchScope { binding, cache, context } = scope;
let [residual, output, injection, candidate] = owners;
**residual = Some(upload_f32(context, &operands.streams)?);
**output = Some(upload_f32(context, &operands.blocks)?);
@@ -0,0 +1,21 @@
//! The operand groups of the GR batch and micro-window operations.
use super::*;
/// The model binding, the dense weight cache and the device context one GR batch operation is valid in; they
/// always travel together.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct GrBatchScope<'a, 'ctx> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) cache: &'a DenseWeightCache<'ctx>,
pub(in crate::qwen_forward) context: &'ctx Context<'ctx>,
}
/// One micro-bank row whose attention block is prepared for publication: the row index, its detached read, the
/// computed block and the token-layer identity the block must carry.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct MicroBlockRequest<'a> {
pub(in crate::qwen_forward) index: usize,
pub(in crate::qwen_forward) read: &'a DetachedGrRead,
pub(in crate::qwen_forward) block: &'a [f32],
pub(in crate::qwen_forward) identity: TokenLayer,
}
@@ -39,12 +39,11 @@ impl<'ctx> GrMicroDevice<'ctx> {
}
pub(in super::super) fn read_native(
&mut self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
context: &Context<'_>,
scope: GrBatchScope<'_, 'ctx>,
weights: [&DeviceBuffer<'_>; 4],
epsilon: f32,
) -> Result<leleka_cuda_driver::GrMicroValues> {
let GrBatchScope { binding, cache, context } = scope;
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
match self {
Self::Native(owner) => owner.read(weights, epsilon, &mut workspace).map_err(micro_driver_error),
@@ -53,11 +52,10 @@ impl<'ctx> GrMicroDevice<'ctx> {
}
pub(in super::super) fn inject_native(
&mut self,
binding: &ModelBinding,
cache: &DenseWeightCache<'ctx>,
context: &Context<'_>,
scope: GrBatchScope<'_, 'ctx>,
blocks: &[f32],
) -> Result<Box<[f32]>> {
let GrBatchScope { binding, cache, context } = scope;
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
match self {
Self::Native(owner) => owner.inject(blocks, &mut workspace).map_err(micro_driver_error),
@@ -94,7 +94,7 @@ impl GrStage {
let mut device = GrMicroDevice::Legacy(
context.gr_microbatch_read(inputs.len(), &batch.streams).map_err(micro_driver_error)?,
);
let env = MicroEnv { binding, cache, context };
let env = GrBatchScope { binding, cache, context };
let result = (|| {
let weights = ready_micro_weights(weights)?;
let values = device.read(weights, resident.weights.epsilon()).map_err(micro_driver_error)?;
@@ -114,10 +114,10 @@ impl GrStage {
let batch = collect_micro_batch(binding, &inputs)?;
let (resident, weights) = micro_weights(cache, binding, batch.role)?;
let mut device = open_native_micro_device(binding, cache, context, inputs.len(), &batch.streams)?;
let env = MicroEnv { binding, cache, context };
let env = GrBatchScope { binding, cache, context };
let result = (|| {
let weights = ready_micro_weights(weights)?;
let values = device.read_native(binding, cache, context, weights, resident.weights.epsilon())?;
let values = device.read_native(env, weights, resident.weights.epsilon())?;
env.detach_rows(inputs, &values, &failed)
})();
env.seal(batch, device, failed, result)
@@ -125,12 +125,10 @@ impl GrStage {
pub(in crate::qwen_forward) fn prepare_micro_attention_block(
binding: &ModelBinding,
bank: &GrMicroAttentionBank<'_>,
index: usize,
read: &DetachedGrRead,
block: &[f32],
identity: TokenLayer,
request: MicroBlockRequest<'_>,
txn: &mut QwenStepTxn,
) -> Result<GrMicroAttentionBlock> {
let MicroBlockRequest { index, read, block, identity } = request;
read.retained_handoff_available()?;
txn.validate_binding(&binding.identity())?;
check_micro_bank(bank, binding, txn)?;
@@ -246,13 +244,7 @@ fn open_native_micro_device<'ctx>(
.map_err(micro_driver_error)?,
))
}
// What the micro read needs besides the device owner.
struct MicroEnv<'a, 'ctx> {
binding: &'a ModelBinding,
cache: &'a DenseWeightCache<'ctx>,
context: &'ctx Context<'ctx>,
}
impl<'a, 'ctx> MicroEnv<'a, 'ctx> {
impl<'a, 'ctx> GrBatchScope<'a, 'ctx> {
fn detach_rows(
&self,
inputs: Vec<GrMicroInput>,
@@ -1,9 +1,9 @@
//! Moved out of the parent module by STRA-338: impl GrStage.
#[allow(unused_imports)]
use super::inject_batch_fns::{device_inject, gather_batch};
use super::batch_inject::{device_inject, gather_batch};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::inject_batch_fns::{finish_queued, queued_inject};
use super::batch_inject::{finish_queued, queued_inject};
use super::*;
impl GrStage {
@@ -68,7 +68,7 @@ impl GrStage {
if let Some(values) = queued_inject(binding, context, cache, &failed, &operands)? {
return finish_queued(binding, context, cache, rows, values);
}
device_inject(binding, context, cache, &failed, rows, &operands)
device_inject(GrBatchScope { binding, cache, context }, &failed, rows, &operands)
}
}

Some files were not shown because too many files have changed in this diff Show More