STRA-338 size: cuda-driver OriginalMmqLayer::execute_original_copy_ring split into preflight/stream/group/status helpers (172 -> 16 lines)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 13:52:01 +01:00
parent f021ce73cb
commit 68cbcc2b88
@@ -16,12 +16,27 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
formats: [MmqFormat; 3],
sources: &[[leleka_model_format::qwen4exp::ResidentExpertBankSpan; 3]],
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
self.copy_ring_preflight(read, sources.len())?;
let groups = self.counts.len().div_ceil(16);
let mut ring =
copy_ring::Ring::new(self.workspace.context, read, layer, schedule, bank, formats, sources, groups)?;
let operation = self.stream_through_ring(&mut ring, read, formats, sources.len());
let close = ring.close();
if operation.is_err() || close.is_err() {
// A failed layer cannot masquerade as a completed output or resume midway.
// Numeric refusal does not poison Context; caller must discard this lease.
self.next = 0;
self.completed = true;
}
combine(operation, close)
}
fn copy_ring_preflight(&self, read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, sources: usize) -> Result<()> {
if self.next != 0
|| self.staged != 0
|| self.completed
|| self.formats.is_some()
|| sources.len() != self.counts.len()
|| sources != self.counts.len()
|| self.arena.is_none()
|| !read.context_matches(self.workspace.context)
|| read.rows() as u32 != self.total / 10
@@ -37,147 +52,196 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
return Err(Error::ContextMismatch);
}
}
let groups = self.counts.len().div_ceil(16);
let mut ring =
copy_ring::Ring::new(self.workspace.context, read, layer, schedule, bank, formats, sources, groups)?;
let operation = (|| {
// The actual carved ring size determines the literal STAGE-1 lookahead.
let stages = read.lease().copy_ring_slots()?;
let lookahead = stages - 1;
let mut staged = 0usize;
for j in 0..sources.len() {
while staged < sources.len() && staged <= j + lookahead {
ring.stage_one(staged, formats)?;
staged += 1;
}
let b = self.bank()?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let wh = self.handle(WG, self.staged * gu * 2, gu * 2, 16)?;
let dh = self.handle(WD, self.staged * down, down, 16)?;
ring.gather(j, formats, b.gather.ok_or(Error::ContextPoisoned)?, wh, dh)?;
self.formats = Some(formats);
self.staged += 1;
if self.staged < 16 && j + 1 < sources.len() {
continue;
}
let group = self.next / 16;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
for stage in 0..4 {
let flag = ring.flag(group, stage)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
1,
ffi::MmqResidentArguments::zero(flag, 1),
))?;
}
for (index, bytes) in [(WG, gu * 2 * self.staged), (WD, down * self.staged)] {
let h = self.handle(index, bytes, 4096, 4)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
1024,
ffi::MmqResidentArguments::zero(h, 1024),
))?;
}
self.enqueue_ring_project(&mut ring, formats[0], WG, XQ, GU, false, self.width(formats[0])?)?;
let b = self.bank()?;
let gu_source =
self.handle(GU, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)?;
let gu_flag = ring.flag(group, 0)?;
ring.enqueue(Command::Helper(
b.gu_finite.ok_or(Error::ContextPoisoned)?,
nr * 1280,
ffi::MmqResidentArguments::finite(gu_source, gu_flag, 0, nr * 1280, 0),
))?;
let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?;
ring.enqueue(Command::Swiglu(
b.swiglu.ok_or(Error::ContextPoisoned)?,
nr,
ffi::MmqOriginalSwigluArguments::new(gu_source, h, nr),
))?;
let h_flag = ring.flag(group, 1)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
nr * 640,
ffi::MmqResidentArguments::finite(h, h_flag, 0, nr * 640, 0),
))?;
let ql = layout(MmqFormat::Iq4NlDown, 2560, nr, 64)?;
let q = self.handle(HQ, 0, ql.packed, 16)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::zero(q, (ql.packed / 4) as u32),
))?;
ring.enqueue(Command::Quantize(
self.workspace
.experiment
.as_ref()
.ok_or(Error::ContextPoisoned)?
.quantizer
.ok_or(Error::ContextPoisoned)?,
ql,
ffi::MmqQuantArguments::original_indexed(h, None, q, ql),
))?;
let q_flag = ring.flag(group, 2)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::finite(q, q_flag, 1, (ql.payload / 144) as u32, (128 * 144) as u32),
))?;
self.enqueue_ring_project(&mut ring, formats[2], WD, HQ, D, true, self.width(formats[2])?)?;
let d = self.handle(D, 0, nr as usize * 2560 * 4, 4)?;
let d_flag = ring.flag(group, 3)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
nr * 2560,
ffi::MmqResidentArguments::finite(d, d_flag, 0, nr * 2560, 0),
))?;
// These are private enqueue cursors, NOT ready/finite publication. All
// group flags remain independently owned until the final genuine drain.
self.next += self.staged;
self.staged = 0;
self.formats = None;
Ok(())
}
/// Stages, gathers and enqueues every group of 16 experts, then drains and checks the group statuses.
fn stream_through_ring(
&mut self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
formats: [MmqFormat; 3],
sources: usize,
) -> Result<()> {
// The actual carved ring size determines the literal STAGE-1 lookahead.
let stages = read.lease().copy_ring_slots()?;
let lookahead = stages - 1;
let mut staged = 0usize;
for j in 0..sources {
while staged < sources && staged <= j + lookahead {
ring.stage_one(staged, formats)?;
staged += 1;
}
let flags = ring.finish_statuses()?;
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
let gu = u32::from_le_bytes(words[0]);
let h = u32::from_le_bytes(words[1]);
let q = u32::from_le_bytes(words[2]);
let down = u32::from_le_bytes(words[3]);
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
self.ring_gather(ring, j, formats)?;
if self.staged < 16 && j + 1 < sources {
continue;
}
Ok(())
})();
let close = ring.close();
if operation.is_err() || close.is_err() {
// A failed layer cannot masquerade as a completed output or resume midway.
// Numeric refusal does not poison Context; caller must discard this lease.
self.next = 0;
self.completed = true;
self.ring_enqueue_group(ring, formats)?;
}
combine(operation, close)
Self::check_ring_statuses(ring.finish_statuses()?)
}
fn ring_gather(&mut self, ring: &mut copy_ring::Ring<'_, 'ctx>, j: usize, formats: [MmqFormat; 3]) -> Result<()> {
let b = self.bank()?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let wh = self.handle(WG, self.staged * gu * 2, gu * 2, 16)?;
let dh = self.handle(WD, self.staged * down, down, 16)?;
ring.gather(j, formats, b.gather.ok_or(Error::ContextPoisoned)?, wh, dh)?;
self.formats = Some(formats);
self.staged += 1;
Ok(())
}
/// Enqueues the whole Gate/Up, SwiGLU and Down chain of the staged group with its finite guards.
fn ring_enqueue_group(&mut self, ring: &mut copy_ring::Ring<'_, 'ctx>, formats: [MmqFormat; 3]) -> Result<()> {
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let group = self.next / 16;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
self.ring_enqueue_zeroes(ring, group, (gu, down))?;
self.enqueue_ring_project(ring, formats[0], WG, XQ, GU, false, self.width(formats[0])?)?;
let h = self.ring_enqueue_swiglu(ring, group, nr)?;
self.ring_enqueue_down(ring, formats, (group, nr, h))?;
// These are private enqueue cursors, NOT ready/finite publication. All
// group flags remain independently owned until the final genuine drain.
self.next += self.staged;
self.staged = 0;
self.formats = None;
Ok(())
}
/// Clears the four group flags and the Gate/Up and Down weight scratch.
fn ring_enqueue_zeroes(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
group: usize,
(gu, down): (usize, usize),
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
for stage in 0..4 {
let flag = ring.flag(group, stage)?;
ring.enqueue(Command::Helper(self.workspace.kernel(0)?, 1, ffi::MmqResidentArguments::zero(flag, 1)))?;
}
for (index, bytes) in [(WG, gu * 2 * self.staged), (WD, down * self.staged)] {
let h = self.handle(index, bytes, 4096, 4)?;
ring.enqueue(Command::Helper(self.workspace.kernel(0)?, 1024, ffi::MmqResidentArguments::zero(h, 1024)))?;
}
Ok(())
}
/// Gate/Up finite guard, SwiGLU and its finite guard; returns the SwiGLU output handle.
fn ring_enqueue_swiglu(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
group: usize,
nr: u32,
) -> Result<ffi::BufferHandle> {
use crate::ffi::original_enqueue::Command;
let b = self.bank()?;
let gu_source = self.handle(GU, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)?;
let gu_flag = ring.flag(group, 0)?;
ring.enqueue(Command::Helper(
b.gu_finite.ok_or(Error::ContextPoisoned)?,
nr * 1280,
ffi::MmqResidentArguments::finite(gu_source, gu_flag, 0, nr * 1280, 0),
))?;
let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?;
ring.enqueue(Command::Swiglu(
b.swiglu.ok_or(Error::ContextPoisoned)?,
nr,
ffi::MmqOriginalSwigluArguments::new(gu_source, h, nr),
))?;
let h_flag = ring.flag(group, 1)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
nr * 640,
ffi::MmqResidentArguments::finite(h, h_flag, 0, nr * 640, 0),
))?;
Ok(h)
}
/// Quantizes the SwiGLU output `h`, projects Down and guards both results.
fn ring_enqueue_down(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
formats: [MmqFormat; 3],
(group, nr, h): (usize, u32, ffi::BufferHandle),
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
self.ring_enqueue_quantize(ring, group, (nr, h))?;
self.enqueue_ring_project(ring, formats[2], WD, HQ, D, true, self.width(formats[2])?)?;
let d = self.handle(D, 0, nr as usize * 2560 * 4, 4)?;
let d_flag = ring.flag(group, 3)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
nr * 2560,
ffi::MmqResidentArguments::finite(d, d_flag, 0, nr * 2560, 0),
))
}
/// Zeroes the Q8 scratch, quantizes the SwiGLU output `h` into it and guards the result.
fn ring_enqueue_quantize(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
group: usize,
(nr, h): (u32, ffi::BufferHandle),
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let ql = layout(MmqFormat::Iq4NlDown, 2560, nr, 64)?;
let q = self.handle(HQ, 0, ql.packed, 16)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(0)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::zero(q, (ql.packed / 4) as u32),
))?;
let quantizer = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.quantizer;
ring.enqueue(Command::Quantize(
quantizer.ok_or(Error::ContextPoisoned)?,
ql,
ffi::MmqQuantArguments::original_indexed(h, None, q, ql),
))?;
let q_flag = ring.flag(group, 2)?;
ring.enqueue(Command::Helper(
self.workspace.kernel(1)?,
(ql.packed / 4) as u32,
ffi::MmqResidentArguments::finite(q, q_flag, 1, (ql.payload / 144) as u32, (128 * 144) as u32),
))
}
/// Maps the finite/Q8 witness words of every group to the first refusal.
fn check_ring_statuses(flags: &[u8]) -> Result<()> {
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
Self::check_group_status([0, 1, 2, 3].map(|i| u32::from_le_bytes(words[i])))?;
}
Ok(())
}
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
pub(super) fn enqueue_ring_project(
&self,