STRA-338 size: cuda-driver OriginalMtpForwardProgram assembly and mmq weight uploads end <= 30 lines, complexity <= 10

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 15:37:38 +01:00
parent f7d748211a
commit 82df6cd43b
9 changed files with 287 additions and 215 deletions
+150 -121
View File
@@ -12,6 +12,18 @@ impl Context<'_> {
for (padded, source) in staging.iter_mut().zip(raw) {
padded[..source.len()].copy_from_slice(source);
}
let buffers = self.allocate_triplet(&layouts)?;
let operation = self.triplet_upload(&buffers, &mut staging);
if let Err(primary) = operation {
// Poisoned release retains uncertain native allocations/charges;
// completed failures attempt every owner, never publish a prefix.
return combine(Err(primary), release_triplet(self, buffers));
}
Ok(self.publish_triplet(formats, buffers))
}
/// One device buffer per layout; a failed allocation releases the ones already made.
fn allocate_triplet(&self, layouts: &[Layout; 3]) -> Result<[Option<DeviceBuffer<'_>>; 3]> {
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for (slot, layout) in layouts.iter().enumerate() {
match self.allocate(layout.weight) {
@@ -19,60 +31,64 @@ impl Context<'_> {
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
}
}
let operation = self.triplet_upload(&buffers, &mut staging);
if let Err(primary) = operation {
// Poisoned release retains uncertain native allocations/charges;
// completed failures attempt every owner, never publish a prefix.
return combine(Err(primary), release_triplet(self, buffers));
}
Ok(buffers)
}
fn publish_triplet<'a>(
&'a self,
formats: [MmqFormat; 3],
buffers: [Option<DeviceBuffer<'a>>; 3],
) -> [MmqWeights<'a>; 3] {
let [Some(gate), Some(up), Some(down)] = buffers else {
unreachable!("all triplet allocations completed before upload")
unreachable!("all triplet allocations completed before the upload")
};
Ok([
[
MmqWeights { context: self, format: formats[0], buffer: Some(gate) },
MmqWeights { context: self, format: formats[1], buffer: Some(up) },
MmqWeights { context: self, format: formats[2], buffer: Some(down) },
])
]
}
/// Format, source and budget admission of three host weight images; returns their layouts.
fn triplet_admit(&self, formats: [MmqFormat; 3], raw: &[&[u8]; 3]) -> Result<[Layout; 3]> {
/// Context state and formats (`allowed` Gate/Up kinds, Iq4NlDown or Q2Down for Down) of a weight triplet.
fn admit_formats(&self, formats: [MmqFormat; 3], allowed: &[MmqFormat]) -> Result<[Layout; 3]> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !formats[..2].iter().all(|format| matches!(format, MmqFormat::Iq3XxsGateUp | MmqFormat::Iq2SGateUp))
if !formats[..2].iter().all(|format| allowed.contains(format))
|| !matches!(formats[2], MmqFormat::Iq4NlDown | MmqFormat::Q2Down)
{
return Err(Error::InvalidProjectionShape);
}
let layouts = [formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?];
Ok([formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?])
}
/// The padded charge must fit the context budget.
fn admit_charge(&self, charge: usize) -> Result<()> {
if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) {
return Err(Error::BudgetExceeded);
}
Ok(())
}
/// Format, source and budget admission of three host weight images; returns their layouts.
fn triplet_admit(&self, formats: [MmqFormat; 3], raw: &[&[u8]; 3]) -> Result<[Layout; 3]> {
let layouts = self.admit_formats(formats, &[MmqFormat::Iq3XxsGateUp, MmqFormat::Iq2SGateUp])?;
let mut charge = 0usize;
// Validate every source before allocating staging or entering CUDA.
for (source, layout) in raw.iter().zip(layouts) {
if source.len() != layout.raw_weight {
return Err(Error::InvalidProjectionShape);
}
if source
.chunks_exact(layout.block_bytes)
.any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00)
{
return Err(Error::InvalidQ8Activation);
}
check_weight_blocks(source, &layout)?;
charge = charge.checked_add(layout.weight).ok_or(Error::BudgetExceeded)?;
}
if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) {
return Err(Error::BudgetExceeded);
}
self.admit_charge(charge)?;
Ok(layouts)
}
/// Copies the three padded staging images into their device buffers under one confirmed fence.
fn triplet_upload(&self, buffers: &[Option<DeviceBuffer<'_>>; 3], staging: &mut [Vec<u8>; 3]) -> Result<()> {
let handles = [
buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
];
let handles = buffer_handles(buffers)?;
let guard = self.enter()?;
let mut copy = Ok(());
for (handle, padded) in handles.into_iter().zip(staging.iter()) {
@@ -109,25 +125,12 @@ impl Context<'_> {
bytes(layouts[1].weight - layouts[1].raw_weight)?,
bytes(layouts[2].weight - layouts[2].raw_weight)?,
];
let mut buffers: [Option<DeviceBuffer<'_>>; 3] = std::array::from_fn(|_| None);
for i in 0..3 {
match self.allocate(layouts[i].weight) {
Ok(buffer) => buffers[i] = Some(buffer),
Err(primary) => return combine(Err(primary), release_triplet(self, buffers)),
}
}
let buffers = self.allocate_triplet(&layouts)?;
let operation = self.device_triplet_operation(&buffers, &mut tails, (&layouts, &raw), sources);
if let Err(primary) = operation {
return combine(Err(primary), release_triplet(self, buffers));
}
let [Some(gate), Some(up), Some(down)] = buffers else {
unreachable!("all padded triplet allocations complete before any copy")
};
Ok([
MmqWeights { context: self, format: formats[0], buffer: Some(gate) },
MmqWeights { context: self, format: formats[1], buffer: Some(up) },
MmqWeights { context: self, format: formats[2], buffer: Some(down) },
])
Ok(self.publish_triplet(formats, buffers))
}
/// Format, context, extent, alias and budget admission of three raw GPU owners; returns layouts and handles.
@@ -136,32 +139,21 @@ impl Context<'_> {
formats: [MmqFormat; 3],
raw: &[&DeviceBuffer<'_>; 3],
) -> Result<([Layout; 3], [ffi::BufferHandle; 3])> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !formats[..2].iter().all(|format| {
matches!(
format,
MmqFormat::Iq3XxsGateUp
| MmqFormat::Iq2SGateUp
| MmqFormat::Iq3SGateUp
| MmqFormat::Iq4XsGateUp
| MmqFormat::Iq4NlGateUp
)
}) || !matches!(formats[2], MmqFormat::Iq4NlDown | MmqFormat::Q2Down)
{
return Err(Error::InvalidProjectionShape);
}
let layouts = [formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?];
let allowed = [
MmqFormat::Iq3XxsGateUp,
MmqFormat::Iq2SGateUp,
MmqFormat::Iq3SGateUp,
MmqFormat::Iq4XsGateUp,
MmqFormat::Iq4NlGateUp,
];
let layouts = self.admit_formats(formats, &allowed)?;
let sources = [
raw[0].handle.ok_or(Error::ContextPoisoned)?,
raw[1].handle.ok_or(Error::ContextPoisoned)?,
raw[2].handle.ok_or(Error::ContextPoisoned)?,
];
let charge = self.device_triplet_charge(formats, raw, (&layouts, &sources))?;
if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) {
return Err(Error::BudgetExceeded);
}
self.admit_charge(charge)?;
Ok((layouts, sources))
}
@@ -200,27 +192,9 @@ impl Context<'_> {
(layouts, raw): (&[Layout; 3], &[&DeviceBuffer<'_>; 3]),
sources: [ffi::BufferHandle; 3],
) -> Result<()> {
let targets = [
buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
];
let all = [
(sources[0], raw[0].bytes),
(sources[1], raw[1].bytes),
(sources[2], raw[2].bytes),
(targets[0], layouts[0].weight),
(targets[1], layouts[1].weight),
(targets[2], layouts[2].weight),
];
for i in 3..6 {
all[i].0.validate_projection_extent(all[i].1, 4)?;
for j in 0..i {
if all[i].0.overlaps(all[i].1, all[j].0, all[j].1) {
return Err(Error::OutputAliasesInput);
}
}
}
let targets = buffer_handles(buffers)?;
let raw_bytes = [raw[0].bytes, raw[1].bytes, raw[2].bytes];
check_padded_targets((sources, targets), raw_bytes, layouts)?;
let mut tail_handles = [None; 3];
for i in 0..3 {
if !tails[i].is_empty() {
@@ -228,7 +202,7 @@ impl Context<'_> {
Some(targets[i].checked_subspan(layouts[i].weight, layouts[i].raw_weight, tails[i].len())?);
}
}
self.device_triplet_copy((targets, sources), (&tail_handles, tails), [raw[0].bytes, raw[1].bytes, raw[2].bytes])
self.device_triplet_copy((targets, sources), (&tail_handles, tails), raw_bytes)
}
/// One guarded sequence of tail uploads and device-to-device weight copies, drained by one synchronize.
@@ -239,6 +213,25 @@ impl Context<'_> {
raw_bytes: [usize; 3],
) -> Result<()> {
let guard = self.enter()?;
let copy = self.device_triplet_enqueue((targets, sources), (tail_handles, tails), raw_bytes);
let sync = self.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.poisoned.set(true);
}
if sync.is_err() || pop.is_err() {
std::mem::forget(std::mem::take(tails));
}
combine(combine(copy, sync), pop)
}
/// Enqueues each tail upload and weight copy, stopping at the first failure.
fn device_triplet_enqueue(
&self,
(targets, sources): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 3]),
(tail_handles, tails): (&[Option<ffi::BufferHandle>; 3], &[Vec<u8>; 3]),
raw_bytes: [usize; 3],
) -> Result<()> {
let mut copy = Ok(());
for i in 0..3 {
if let Some(tail) = tail_handles[i] {
@@ -252,15 +245,7 @@ impl Context<'_> {
break;
}
}
let sync = self.driver.api.synchronize();
let pop = guard.finish();
if copy.is_err() || sync.is_err() || pop.is_err() {
self.poisoned.set(true);
}
if sync.is_err() || pop.is_err() {
std::mem::forget(std::mem::take(tails));
}
combine(combine(copy, sync), pop)
copy
}
/// Closed owned cold Gate/Up upload; no tail padding, no module loading.
@@ -274,23 +259,17 @@ impl Context<'_> {
if self.is_poisoned() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
let format = match kind {
MmqFormat::Iq3XxsGateUp => RoutedFormat::IQ3_XXS,
MmqFormat::Iq2SGateUp => RoutedFormat::IQ2_S,
_ => return Err(Error::UnsupportedProjection),
};
let l = kind.layout(1)?;
if shape != (ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 })
|| l.weight != l.raw_weight
|| raw.len() != l.raw_weight
{
return Err(Error::InvalidProjectionShape);
}
if raw.chunks_exact(l.block_bytes).any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) {
return Err(Error::InvalidQ8Activation);
}
let l = owned_gate_up_layout(shape, kind, raw.len())?;
check_weight_blocks(&raw, &l)?;
let mut b = self.allocate(l.weight)?;
if let Err(error) = b.copy_from_owned(raw) {
let upload = b.copy_from_owned(raw);
let b = self.settle_upload(b, upload)?;
Ok(MmqWeights { context: self, format: kind, buffer: Some(b) })
}
/// A failed upload poisons the context and releases the buffer; the upload error stays primary.
fn settle_upload<'a>(&'a self, b: DeviceBuffer<'a>, upload: Result<()>) -> Result<DeviceBuffer<'a>> {
if let Err(error) = upload {
self.poisoned.set(true);
let cleanup = b.release();
if cleanup.is_err() {
@@ -298,7 +277,7 @@ impl Context<'_> {
}
return combine(Err(error), cleanup);
}
Ok(MmqWeights { context: self, format: kind, buffer: Some(b) })
Ok(b)
}
/// One producer-owned padded native/MMQ matrix. No experimental modules are loaded.
@@ -310,20 +289,70 @@ impl Context<'_> {
if raw.len() != l.raw_weight {
return Err(Error::InvalidProjectionShape);
}
if raw.chunks_exact(l.block_bytes).any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) {
return Err(Error::InvalidQ8Activation);
}
check_weight_blocks(raw, &l)?;
let mut padded = bytes(l.weight)?;
padded[..raw.len()].copy_from_slice(raw);
let mut b = self.allocate(l.weight)?;
if let Err(error) = b.copy_from(&padded) {
self.poisoned.set(true);
let cleanup = b.release();
if cleanup.is_err() {
self.poisoned.set(true);
}
return combine(Err(error), cleanup);
}
let upload = b.copy_from(&padded);
let b = self.settle_upload(b, upload)?;
Ok(MmqWeights { context: self, format, buffer: Some(b) })
}
}
/// The weights of a source may not carry a NaN/Inf scale in any block header.
fn check_weight_blocks(raw: &[u8], l: &Layout) -> Result<()> {
if raw.chunks_exact(l.block_bytes).any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) {
return Err(Error::InvalidQ8Activation);
}
Ok(())
}
fn buffer_handles(buffers: &[Option<DeviceBuffer<'_>>; 3]) -> Result<[ffi::BufferHandle; 3]> {
Ok([
buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?,
])
}
/// The padded targets need a 4-byte aligned extent and may overlap neither the sources nor each other.
fn check_padded_targets(
(sources, targets): ([ffi::BufferHandle; 3], [ffi::BufferHandle; 3]),
raw_bytes: [usize; 3],
layouts: &[Layout; 3],
) -> Result<()> {
let all = [
(sources[0], raw_bytes[0]),
(sources[1], raw_bytes[1]),
(sources[2], raw_bytes[2]),
(targets[0], layouts[0].weight),
(targets[1], layouts[1].weight),
(targets[2], layouts[2].weight),
];
for i in 3..6 {
all[i].0.validate_projection_extent(all[i].1, 4)?;
for j in 0..i {
if all[i].0.overlaps(all[i].1, all[j].0, all[j].1) {
return Err(Error::OutputAliasesInput);
}
}
}
Ok(())
}
/// The layout of an owned Gate/Up upload: Iq3Xxs or Iq2S, exactly the closed 640x2560 shape, no tail padding.
fn owned_gate_up_layout(shape: ProjectionSpec, kind: MmqFormat, raw_len: usize) -> Result<Layout> {
let format = match kind {
MmqFormat::Iq3XxsGateUp => RoutedFormat::IQ3_XXS,
MmqFormat::Iq2SGateUp => RoutedFormat::IQ2_S,
_ => return Err(Error::UnsupportedProjection),
};
let l = kind.layout(1)?;
if shape != (ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 })
|| l.weight != l.raw_weight
|| raw_len != l.raw_weight
{
return Err(Error::InvalidProjectionShape);
}
Ok(l)
}
@@ -123,23 +123,38 @@ struct ForwardPrefix<'a, 'ctx> {
/// prepared prefix plan. Generic callers cannot create or replace these owners.
pub struct OriginalMtpForwardProgram<'ctx> {
context: &'ctx Context<'ctx>,
prefix_modules: [Rc<Module>; 6],
prefix_scratch: Rc<DeviceBuffer<'ctx>>,
prefix_status: Rc<DeviceBuffer<'ctx>>,
prefix_records: Rc<DeviceBuffer<'ctx>>,
prefix_mapped: Rc<RefCell<Option<mapped_records::MappedOwner>>>,
owners: PrefixOwners<'ctx>,
ring: MtpOriginalRingResources<'ctx>,
tail: Rc<FullOwned<'ctx>>,
prefix: Vec<ScalarCommand>,
tail_commands: Vec<FullCommand>,
split: Box<full_abi::Copy2D>,
window: abi::Arguments,
tail_reset: Arguments,
args: TailArgs,
native_embedding: Option<OriginalMtpNativeGather<'ctx>>,
coupled_stage: Option<FA>,
addrs: ScalarAddrs,
}
/// The scalar prefix's modules and the buffers its commands run on.
struct PrefixOwners<'ctx> {
modules: [Rc<Module>; 6],
scratch: Rc<DeviceBuffer<'ctx>>,
status: Rc<DeviceBuffer<'ctx>>,
records: Rc<DeviceBuffer<'ctx>>,
mapped: Rc<RefCell<Option<mapped_records::MappedOwner>>>,
}
/// Launch arguments of the tail: the q split copy, the step window and the tail flag reset.
struct TailArgs {
split: Box<full_abi::Copy2D>,
window: abi::Arguments,
reset: Arguments,
}
/// Device addresses the selection kernel reads.
struct ScalarAddrs {
residual_offset: usize,
input_address: u64,
token_address: u64,
input: u64,
token: u64,
}
/// Actual recorded draft, not target acceptance or canonical state authority.
@@ -11,10 +11,10 @@ impl OriginalGraphResources for OriginalMtpForwardProgram<'_> {
}
self.tail.validate(c)?;
self.ring.validate_context(c)?;
for b in [&self.prefix_scratch, &self.prefix_status, &self.prefix_records] {
for b in [&self.owners.scratch, &self.owners.status, &self.owners.records] {
checked(c, b, b.bytes)?;
}
if self.prefix_mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_none() {
if self.owners.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_none() {
return Err(Error::ContextPoisoned);
}
Ok(())
@@ -13,7 +13,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.prefix_modules[0].launch(11, [1, 1, 1], [256, 1, 1], 0, stream, &mut self.tail_reset)?;
self.owners.modules[0].launch(11, [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
@@ -22,7 +22,7 @@ impl OriginalMtpForwardProgram<'_> {
}
match command {
ScalarCommand::Kernel { asset, index, grid, block, shared, args } => {
self.prefix_modules[*asset].launch(*index, *grid, *block, *shared, stream, args)?
self.owners.modules[*asset].launch(*index, *grid, *block, *shared, stream, args)?
}
ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape),
}
@@ -31,7 +31,7 @@ impl OriginalMtpForwardProgram<'_> {
// window_ids positions in record_forward, before attention launch.
for command in self.tail_commands.iter_mut() {
if command.asset == 16 && command.index == 0 {
self.tail.modules[13].copy2d(&self.split, stream)?;
self.tail.modules[13].copy2d(&self.args.split, stream)?;
}
if (command.asset == 19 || command.asset == symbols::DAILY_ASSET) && command.index == 0 {
self.ring.physical.modules[1].as_ref().ok_or(Error::ContextPoisoned)?.launch(
@@ -40,7 +40,7 @@ impl OriginalMtpForwardProgram<'_> {
[256, 1, 1],
0,
stream,
&mut self.window,
&mut self.args.window,
)?;
}
self.tail.modules[command.asset].launch(
@@ -55,8 +55,8 @@ impl OriginalMtpForwardProgram<'_> {
Ok(())
}
pub fn metadata_bytes(&self) -> Result<usize> {
let mut n = self.window.metadata_bytes()
+ self.tail_reset.metadata_bytes()
let mut n = self.args.window.metadata_bytes()
+ self.args.reset.metadata_bytes()
+ self.native_embedding.as_ref().map_or(0, OriginalMtpNativeGather::metadata_bytes)
+ self.coupled_stage.as_ref().map_or(0, FA::metadata_bytes)
+ std::mem::size_of::<Self>()
@@ -87,8 +87,8 @@ impl OriginalMtpForwardProgram<'_> {
})?;
let copies = (|| {
self.context.driver.api.copy_to(
self.prefix_status.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(
self.prefix_status.bytes,
self.owners.status.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(
self.owners.status.bytes,
0,
64,
)?,
@@ -16,7 +16,39 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
step_row: usize,
) -> Result<OriginalMtpForwardProgram<'ctx>> {
self.program_reject_aliases(scalar, ring)?;
let p = ForwardPrefix {
let p = self.program_prefix(scalar, ring, step_row)?;
let commands = self.plan(&p, policy)?;
let window = self.program_window(&p, ring)?;
let coupled_stage = self.program_coupled_stage(policy)?;
Ok(OriginalMtpForwardProgram {
context: scalar.context,
owners: Self::program_owners(scalar)?,
ring: ring.retain_physical_resources()?,
tail: Rc::clone(&self.inner),
prefix,
tail_commands: commands,
args: self.program_tail_args(window)?,
native_embedding,
coupled_stage,
addrs: Self::program_addrs(scalar)?,
})
}
fn program_addrs(scalar: &OriginalMtpScalarPrefill<'ctx>) -> Result<ScalarAddrs> {
Ok(ScalarAddrs {
residual_offset: scalar.layout.offsets[1],
input: scalar.address(0, 40960)?,
token: scalar.address(12, 4)?,
})
}
fn program_prefix<'a>(
&self,
scalar: &'a OriginalMtpScalarPrefill<'ctx>,
ring: &'a MtpOriginalInt8<'ctx>,
step_row: usize,
) -> Result<ForwardPrefix<'a, 'ctx>> {
Ok(ForwardPrefix {
scalar,
ring,
step: self.inner.address(31)? + (step_row * 16) as u64,
@@ -25,35 +57,34 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
r: scalar.address(1, 40960)?,
mixed: scalar.address(11, 10240)?,
inj: scalar.address(10, 16)?,
};
let commands = self.plan(&p, policy)?;
let modules = Self::program_modules(scalar)?;
let window = abi::Arguments::new(vec![
})
}
fn program_window(&self, p: &ForwardPrefix<'_, 'ctx>, ring: &MtpOriginalInt8<'ctx>) -> Result<abi::Arguments> {
abi::Arguments::new(vec![
abi::Arg::U64(p.step),
abi::Arg::I32(32768),
abi::Arg::U64(self.inner.attention(ring)?.3),
abi::Arg::I64(32768),
])?;
let coupled_stage = self.program_coupled_stage(policy)?;
Ok(OriginalMtpForwardProgram {
context: scalar.context,
prefix_modules: modules,
prefix_scratch: Rc::clone(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?),
prefix_status: Rc::clone(scalar.status.as_ref().ok_or(Error::ContextPoisoned)?),
prefix_records: Rc::clone(scalar.records.as_ref().ok_or(Error::ContextPoisoned)?),
prefix_mapped: Rc::clone(&scalar.mapped),
ring: ring.retain_physical_resources()?,
tail: Rc::clone(&self.inner),
prefix,
tail_commands: commands,
])
}
/// The retained scalar prefix modules and buffers.
fn program_owners(scalar: &OriginalMtpScalarPrefill<'ctx>) -> Result<PrefixOwners<'ctx>> {
Ok(PrefixOwners {
modules: Self::program_modules(scalar)?,
scratch: Rc::clone(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?),
status: Rc::clone(scalar.status.as_ref().ok_or(Error::ContextPoisoned)?),
records: Rc::clone(scalar.records.as_ref().ok_or(Error::ContextPoisoned)?),
mapped: Rc::clone(&scalar.mapped),
})
}
fn program_tail_args(&self, window: abi::Arguments) -> Result<TailArgs> {
Ok(TailArgs {
split: Box::new(full_abi::Copy2D::q_split(self.inner.address(0)?, self.inner.address(1)?)),
window,
tail_reset: Arguments::new(vec![Arg::U64(self.inner.address(27)?), Arg::I32(TAIL_FLAGS as i32)])?,
native_embedding,
coupled_stage,
residual_offset: scalar.layout.offsets[1],
input_address: scalar.address(0, 40960)?,
token_address: scalar.address(12, 4)?,
reset: Arguments::new(vec![Arg::U64(self.inner.address(27)?), Arg::I32(TAIL_FLAGS as i32)])?,
})
}
/// Every buffer the full-forward scratch must not alias: all prefix and tail weights, the expert bank, the head
@@ -84,12 +115,39 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
) -> Result<()> {
let (scratch, sh) = self.program_validate(scalar, ring)?;
self.program_reject_scratch_overlap(scalar, scratch, sh)?;
if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) {
return Err(Error::InvalidQwenShape);
}
for extra in self.inner.extras.iter().flatten() {
self.program_reject_extra_alias(scalar, ring, extra)?;
}
Self::prefix_reject_ring_overlap(ring, sh, scratch.bytes)
}
/// Context checks; returns the tail scratch and its handle.
fn program_validate(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
) -> Result<(&Rc<DeviceBuffer<'ctx>>, BufferHandle)> {
validate_scalar_prefix(scalar)?;
ring.validate_context(self.inner.context)?;
self.validate_context(scalar.context)?;
let scratch = self.inner.scratch.as_ref().ok_or(Error::ContextPoisoned)?;
ring.reject_state_alias(scratch)?;
let sh = scratch.handle.ok_or(Error::ContextPoisoned)?;
Ok((scratch, sh))
}
/// The tail scratch overlaps a weight or scalar buffer only when that buffer is the genuinely shared scalar scratch.
fn program_reject_scratch_overlap(
&self,
scalar: &OriginalMtpScalarPrefill<'ctx>,
scratch: &DeviceBuffer<'ctx>,
sh: BufferHandle,
) -> Result<()> {
for b in self.program_buffers(scalar)? {
if sh.overlaps(scratch.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) {
let genuine_shared = self.inner.shares_original(scalar)
@@ -99,17 +157,6 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
}
}
}
if self.inner.original_layout.is_some() && !self.inner.shares_original(scalar) {
return Err(Error::InvalidQwenShape);
}
for extra in self.inner.extras.iter().flatten() {
self.program_reject_extra_alias(scalar, ring, extra)?;
}
for b in ring.buffers()?.iter().flatten() {
if sh.overlaps(scratch.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
}
@@ -127,12 +174,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
return Err(Error::OutputAliasesInput);
}
}
for b in ring.buffers()?.iter().flatten() {
if h.overlaps(extra.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) {
return Err(Error::OutputAliasesInput);
}
}
Ok(())
Self::prefix_reject_ring_overlap(ring, h, extra.bytes)
}
/// The six scalar-prefix modules the program retains.
@@ -89,7 +89,11 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
Ok(())
}
fn prefix_reject_ring_overlap(ring: &MtpOriginalInt8<'ctx>, h: BufferHandle, bytes: usize) -> Result<()> {
pub(in super::super) fn prefix_reject_ring_overlap(
ring: &MtpOriginalInt8<'ctx>,
h: BufferHandle,
bytes: usize,
) -> Result<()> {
for output in ring.buffers()?.iter().flatten() {
if h.overlaps(bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) {
return Err(Error::OutputAliasesInput);
@@ -123,34 +123,15 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
ring: &MtpOriginalInt8<'ctx>,
(step, k, v): (u64, u64, u64),
) -> Result<()> {
let mut host = [0u64; 8];
host[2..6].copy_from_slice(&ring.host_addresses()?);
let host = ring.host_addresses()?;
// Literal step append kernel and actual private step record, not batched prompt arithmetic.
OriginalMtpScalarPrefill::kernel(
cmds,
5,
0,
[2, 4, 2],
[64, 1, 1],
0,
vec![
Arg::U64(ring.address(0)?),
Arg::U64(ring.address(1)?),
Arg::U64(ring.address(2)?),
Arg::U64(ring.address(3)?),
Arg::U64(ring.address(4)?),
Arg::U64(step),
Arg::U64(k),
Arg::U64(v),
Arg::I32(2),
Arg::I32(256),
Arg::I32(4),
Arg::U64(host[2]),
Arg::U64(host[3]),
Arg::U64(host[4]),
Arg::U64(host[5]),
],
)
let mut values = Vec::with_capacity(15);
for i in 0..5 {
values.push(Arg::U64(ring.address(i)?));
}
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)
}
fn prefix_row_rope(cmds: &mut Vec<ScalarCommand>, kv: &DraftKvPolicy, k: u64, position: u64) -> Result<()> {
@@ -39,7 +39,7 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx> {
}
match cmd {
ScalarCommand::Kernel { asset, index, grid, block, shared, args } => {
self.program.prefix_modules[*asset].launch(*index, *grid, *block, *shared, stream, args)?
self.program.owners.modules[*asset].launch(*index, *grid, *block, *shared, stream, args)?
}
ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape),
}
@@ -7,15 +7,16 @@ pub(super) fn post_select(p: &OriginalMtpForwardProgram<'_>, j: usize) -> Result
let mut v = Vec::new();
mtp_select(
&mut v,
p.prefix_scratch
p.owners
.scratch
.handle
.ok_or(Error::ContextPoisoned)?
.checked_subspan(p.prefix_scratch.bytes, p.residual_offset, 40960)?
.checked_subspan(p.owners.scratch.bytes, p.addrs.residual_offset, 40960)?
.qwen_address(),
p.tail.address(34)?,
p.tail.address(33)? + 4,
p.input_address,
p.token_address,
p.addrs.input,
p.addrs.token,
p.tail.mapped_address(p.tail.max_t * 228 + 256, p.tail.max_t * 4)?,
j,
p.tail.address(35)?,