Merge branch 'claude/par-r02' into claude/hexagonal-finish-14ee3a

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 02:16:21 +01:00
39 changed files with 600 additions and 617 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)
{
@@ -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)
}
}
@@ -2,7 +2,10 @@
//! phase, shifted actual IDs and current ring receipt, literal scalar producer.
use super::*;
use crate::qwen_forward::moe_weight_cache::RetainedOriginalMtpWeights;
use leleka_cuda_driver::{OriginalMtpActor, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy};
use leleka_cuda_driver::{
OriginalMtpActor, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, PrefillRows, RecordRun,
ScalarDraftKvSources,
};
impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> {
/// Original Prefill uses only known-next conditioning with no head/D2H.
/// The genuine all-row R and immutable input owners survive through drain.
@@ -22,7 +25,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
retained: Rc<OriginalMtpRetainedScalarWeights<'ctx>>,
first_needed: usize,
policy: &OriginalMtpScalarPolicy,
cancelled: impl FnMut() -> bool,
mut cancelled: impl FnMut() -> bool,
) -> Result<OriginalPromptDraftOutcome> {
let phase = self.check_scalar_sources(binding, dense, txn, preview, last_next)?;
let next = self.shifted_next_ids(txn, last_next)?;
@@ -30,9 +33,11 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?;
// Input/draft host policy and all eleven immutable device owners are live
// throughout drain; never mint scalar committed products for prior rows.
#[rustfmt::skip]
let result = producer.record_scalar_prefill(&mut self.device, workspace, ring, prior, &next, start,
first_needed, retained, policy, cancelled).map_err(micro_driver_error)?;
let mut run = RecordRun { workspace, ring, cancelled: &mut cancelled };
let rows = PrefillRows { tokens: &next, cell0: start, first_needed };
let sources = ScalarDraftKvSources { prior, retained, policy };
let result =
producer.record_scalar_prefill(&mut self.device, &mut run, rows, sources).map_err(micro_driver_error)?;
self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, ring)
}
}
@@ -10,8 +10,8 @@ use super::{
};
use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding};
use leleka_cuda_driver::{
CompletedOriginalMtpDraft, Context, NativeHeadSelection, OriginalGpuEvent, OriginalMtpFullPolicy,
OriginalVerifyWindow, SamplerParams,
AcceptedWindow, CompletedOriginalMtpDraft, Context, DraftTarget, NativeHeadSelection, OriginalGpuEvent,
OriginalMtpFullPolicy, OriginalVerifyWindow, RepeatRowWindow, SamplerParams,
};
/// One completed `Verifier::run` receipt, before the target commit. It owns
@@ -28,8 +28,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
before.validate(session)?;
let actor = self.checked_mtp_actor(binding)?;
draft.with_mtp_launch_ring(binding, session, &before, &prospective, |ring, prior| {
let target = DraftTarget { ring, prior, policy };
actor
.launch_draft_from_verifier(ring, prior, window, selection, accepted_row, min_p, policy, after)
.launch_draft_from_verifier(target, AcceptedWindow { window, selection, accepted_row }, min_p, after)
.map_err(driver_error)
})?;
Ok(OriginalLaunchedMtpDraft { binding: binding.identity(), before, prospective })
@@ -111,16 +112,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
let actor = self.checked_mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| {
let target = DraftTarget { ring, prior, policy };
let (window, selection, accepted_row) = (receipt.window, receipt.selection, receipt.accepted_row);
actor
.draft_from_verifier(
ring,
prior,
receipt.window,
receipt.selection,
receipt.accepted_row,
min_p,
policy,
)
.draft_from_verifier(target, AcceptedWindow { window, selection, accepted_row }, min_p)
.map_err(driver_error)
})?;
self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed)
@@ -147,9 +142,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
let actor = self.checked_mtp_actor(binding)?;
let completed =
draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| {
actor
.draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy)
.map_err(driver_error)
let target = DraftTarget { ring, prior, policy };
let window = RepeatRowWindow { window: receipt.window, selection: receipt.selection, rows };
actor.draft_first_from_verifier(target, window, min_p).map_err(driver_error)
})?;
self.publish_draft_receipt(binding, session, draft, (&receipt.before, receipt.committed), completed)
}