From 2bba521553766c2ef3d575fa43a328e18aaddc5a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 13:57:14 +0100 Subject: [PATCH] STRA-338 size: split OriginalGdnPromptDevice::produce into admission, command list and drain --- .../impl_originalgdnpromptdevice.rs | 8 + .../impl_originalgdnpromptdevice_2_2.rs | 576 +++--------------- .../impl_originalgdnpromptdevice_4.rs | 345 +++++++++++ .../impl_originalgdnpromptdevice_5.rs | 199 ++++++ .../impl_originalgdnpromptdevice_6.rs | 107 ++++ 5 files changed, 746 insertions(+), 489 deletions(-) create mode 100644 crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs create mode 100644 crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_5.rs create mode 100644 crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_6.rs diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs index 3a1c7522..9f1e8f32 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs @@ -9,3 +9,11 @@ mod impl_originalgdnpromptdevice_2; mod impl_originalgdnpromptdevice_2_2; #[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs"] mod impl_originalgdnpromptdevice_3; +#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs"] +mod impl_originalgdnpromptdevice_4; +#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_5.rs"] +mod impl_originalgdnpromptdevice_5; +#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_6.rs"] +mod impl_originalgdnpromptdevice_6; +#[allow(unused_imports)] +use impl_originalgdnpromptdevice_6::{Binder, Carve, Carved, Handles, Phase}; diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs index 630a1a7c..f7d8f88e 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs @@ -1,7 +1,9 @@ -//! Moved out of the parent module by STRA-338: impl OriginalGdnPromptDevice (2). +//! Moved out of the parent module by STRA-338: impl OriginalGdnPromptDevice (2). `produce` admits the buffers, records +//! the command list (`impl_originalgdnpromptdevice_4.rs`) and drains it (`impl_originalgdnpromptdevice_5.rs`). #[allow(unused_imports)] use super::*; +use crate::OriginalPromptRows; impl<'ctx> OriginalGdnPromptDevice<'ctx> { /// Consumes the actual affine GR read. `state` is untouched prior; only @@ -16,9 +18,21 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { next_state: &DeviceBuffer<'ctx>, history: &[f32], ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Box<[f32]>)> { - let lease = read.lease(); let t = read.rows(); - if self.is_failed() || lease.is_failed() { + self.admit(&read, workspace, history)?; + let handles = self.admit_handles(read.lease(), (workspace, t), &weights, (state, next_state))?; + let commands = self.build_commands(&handles, weights.formats, t)?; + let values = self.drain(workspace, commands, history, (&handles, t))?; + Ok((read.from_completed_block(), values)) + } + fn admit( + &self, + read: &OriginalDeviceGrRead<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + history: &[f32], + ) -> Result<()> { + let t = read.rows(); + if self.is_failed() || read.lease().is_failed() { return Err(Error::ContextPoisoned); } if !read.context_matches(self.context) { @@ -30,31 +44,46 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { if history.iter().any(|x| !x.is_finite()) { return Err(Error::NonFiniteMmqOutput("GDN prior history")); } - workspace.validate_context(self.context)?; + workspace.validate_context(self.context) + } + /// Every owner/alias/shape admission precedes the first write. + fn admit_handles( + &self, + lease: &OriginalPromptRows<'_, '_, '_>, + rows: (&NativeBatchWorkspace<'ctx>, usize), + weights: &OriginalGdnPromptWeights<'_, 'ctx>, + io: (&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>), + ) -> Result { + let (workspace, t) = rows; let batch = self.batch.as_ref().ok_or(Error::ContextPoisoned)?; let status = batch.status_handle()?; - let mut bindings = Bindings::new(); - let mut buffer = |role: Role, b: &DeviceBuffer<'_>, bytes: usize| -> Result { - if !std::ptr::eq(b.context, self.context) { - return Err(Error::ContextMismatch); - } - if b.len() != bytes { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 4)?; - workspace.reject_alias(h, bytes)?; - if h.overlaps(bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - bindings.bind(role, h, bytes)?; - Ok(h) - }; - let scratch = buffer(Role::Scratch, self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, SCRATCH)?; - let hin = buffer(Role::History, self.history[0].as_ref().ok_or(Error::ContextPoisoned)?, HISTORY)?; - let hout = buffer(Role::NextHistory, self.history[1].as_ref().ok_or(Error::ContextPoisoned)?, HISTORY)?; - let sin = buffer(Role::StateIn, state, STATE_WORDS * 4)?; - let sout = buffer(Role::StateOut, next_state, STATE_WORDS * 4)?; + let mut binder = Binder { context: self.context, workspace, status, bindings: Bindings::new(), t }; + let [scratch, hin, hout, sin, sout] = self.admit_state(&mut binder, io)?; + let (w, a) = Self::admit_weights(&mut binder, weights, sin)?; + let c = self.admit_carved(&mut binder, lease)?; + Ok(Handles { status, scratch, hin, hout, sin, sout, w, a, c }) + } + fn admit_state( + &self, + binder: &mut Binder<'_, 'ctx>, + io: (&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>), + ) -> Result<[ffi::BufferHandle; 5]> { + let scratch = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + let scratch = binder.buffer(Role::Scratch, scratch, SCRATCH)?; + let hin = self.history[0].as_ref().ok_or(Error::ContextPoisoned)?; + let hin = binder.buffer(Role::History, hin, HISTORY)?; + let hout = self.history[1].as_ref().ok_or(Error::ContextPoisoned)?; + let hout = binder.buffer(Role::NextHistory, hout, HISTORY)?; + let sin = binder.buffer(Role::StateIn, io.0, STATE_WORDS * 4)?; + let sout = binder.buffer(Role::StateOut, io.1, STATE_WORDS * 4)?; + Ok([scratch, hin, hout, sin, sout]) + } + #[allow(clippy::type_complexity)] + fn admit_weights( + binder: &mut Binder<'_, 'ctx>, + weights: &OriginalGdnPromptWeights<'_, 'ctx>, + sin: ffi::BufferHandle, + ) -> Result<([ffi::BufferHandle; 5], [ffi::BufferHandle; 4])> { let mut w = [sin; 5]; for (i, role, n, k) in [ (0, Role::QkvW, C, N), @@ -64,478 +93,47 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { (4, Role::BetaW, HV, N), ] { let bytes = if i < 3 { weights.formats[i].matrix_bytes(n, k)? } else { n * k * 2 }; - w[i] = buffer(role, weights.matrices[i], bytes)?; + w[i] = binder.buffer(role, weights.matrices[i], bytes)?; } let mut a = [sin; 4]; for (i, role, n) in [(0, Role::ConvW, C * 4 * 4), (1, Role::Dt, HV * 4), (2, Role::SsmA, HV * 4), (3, Role::Gamma, S * 4)] { - a[i] = buffer(role, weights.aux[i], n)?; + a[i] = binder.buffer(role, weights.aux[i], n)?; } - drop(buffer); - let mut carved = |role: Role, - phase: Option<(&str, usize)>, - common: Option<(OriginalPromptSpan, usize)>| - -> Result { - let (h, capacity, bytes) = if let Some((name, width)) = phase { - let (h, n) = lease.span(PrefillPhase::Gdn, name)?; - (h, n, t * width) - } else { - let (r, width) = common.ok_or(Error::InvalidQwenShape)?; - let (h, n) = lease.common_span(r)?; - (h, n, t * width) - }; - let h = h.checked_subspan(capacity, 0, bytes)?; - h.validate_projection_extent(bytes, 2)?; - workspace.reject_alias(h, bytes)?; - if h.overlaps(bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - bindings.bind(role, h, bytes)?; - Ok(h) - }; - let mixed = carved(Role::MixedH, None, Some((OriginalPromptSpan::MixedHalf, 5120)))?; - let high = carved(Role::MixedBf, None, Some((OriginalPromptSpan::MixedHigh, 5120)))?; + Ok((w, a)) + } + fn admit_carved(&self, binder: &mut Binder<'_, 'ctx>, lease: &OriginalPromptRows<'_, '_, '_>) -> Result { + let (mixed, high, lower) = self.admit_mixed(binder, lease)?; + let p = Self::admit_phase(binder, lease)?; + let bo = binder.carved(lease, Role::Bo, Carve::Common(OriginalPromptSpan::Block, N * 4))?; + Ok(Carved { mixed, high, lower, p, bo }) + } + #[allow(clippy::type_complexity)] + fn admit_mixed( + &self, + binder: &mut Binder<'_, 'ctx>, + lease: &OriginalPromptRows<'_, '_, '_>, + ) -> Result<(ffi::BufferHandle, ffi::BufferHandle, Option)> { + let mixed = binder.carved(lease, Role::MixedH, Carve::Common(OriginalPromptSpan::MixedHalf, 5120))?; + let high = binder.carved(lease, Role::MixedBf, Carve::Common(OriginalPromptSpan::MixedHigh, 5120))?; let lower = if self.profile == crate::GrNativeProfile::HighAndLow { - Some(carved(Role::MixedBfLo, None, Some((OriginalPromptSpan::MixedLow, 5120)))?) + Some(binder.carved(lease, Role::MixedBfLo, Carve::Common(OriginalPromptSpan::MixedLow, 5120))?) } else { None }; - let qkv = carved(Role::Qkv, Some(("qkv", C * 4)), None)?; - let z = carved(Role::Z, Some(("z", ZV * 4)), None)?; - let ab = carved(Role::Ab, Some(("ab", HV * 8)), None)?; - let gate = carved(Role::Gate, Some(("gate", HV * 4)), None)?; - let beta = carved(Role::Beta, Some(("beta", HV * 4)), None)?; - let h = carved(Role::H, Some(("hbuf", C * 4)), None)?; - let y = carved(Role::Y, Some(("y", ZV * 4)), None)?; - let yh = carved(Role::Y16, Some(("y_h", ZV * 2)), None)?; - let bo = carved(Role::Bo, None, Some((OriginalPromptSpan::Block, N * 4)))?; - drop(carved); - // Every owner/alias/shape admission above precedes the first write. - let mut commands = Vec::new(); - commands.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?; - let funcs = batch.functions.as_ref().ok_or(Error::ContextPoisoned)?; - let mut push = |kernel: Kernel, geometry: ([u32; 3], [u32; 3]), args: &[ffi::KernelArg]| -> Result<()> { - commands.push(DeviceCommand::Kernel { - function: funcs.get(kernel), - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - }; - push(Kernel::Zero, linear(SLOTS)?, &[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?; - drop(push); - let add_kernel = |commands: &mut Vec, - kernel: Kernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg]| - -> Result<()> { - commands.push(DeviceCommand::Kernel { - function: funcs.get(kernel), - grid: geometry.0, - block: geometry.1, - args: ffi::GdnPrefillArguments::new(args)?, - }); - Ok(()) - }; - let scan = |commands: &mut Vec, stage: GdnBatchStage, data: ffi::BufferHandle| -> Result<()> { - let word = status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; - add_kernel( - commands, - if stage.is_half() { Kernel::FiniteF16 } else { Kernel::FiniteF32 }, - linear(stage.elements(t))?, - &[ - ffi::KernelArg::Pointer(data), - ffi::KernelArg::Pointer(word), - ffi::KernelArg::U32(stage.elements(t) as u32), - ], - ) - }; - let fast_dequant = crate::prefill_stage::fast_dequant(); - let native = |commands: &mut Vec, - format: GdnNativeFormat, - input, - weight, - output, - n: usize, - k: usize| - -> Result<()> { - if fast_dequant { - let total = n * k; - commands.push(DeviceCommand::Stage { - index: crate::prefill_stage::DEQUANT_FIRST - + match format { - GdnNativeFormat::Q8_0 => 0, - GdnNativeFormat::Q4K => 1, - GdnNativeFormat::Q5K => 2, - GdnNativeFormat::Q6K => 3, - GdnNativeFormat::Iq4Nl => 4, - GdnNativeFormat::Iq4Xs => 5, - }, - grid: u32::try_from(total.div_ceil(256)).map_err(|_| Error::InvalidQwenShape)?, - block: 256, - args: KernelArguments::new(vec![ - A::Address(weight), - A::I64((k / format.block().0 * format.block().1) as i64), - A::I64(total as i64), - A::I64((k / 32) as i64), - A::Address(scratch), - ]), - }); - } else { - add_kernel( - commands, - format.kernel(), - linear(n * (k / 32))?, - &[ - ffi::KernelArg::Pointer(weight), - ffi::KernelArg::I64((k / format.block().0 * format.block().1) as i64), - ffi::KernelArg::I64(0), - ffi::KernelArg::I64(n as i64), - ffi::KernelArg::I64((k / 32) as i64), - ffi::KernelArg::Pointer(scratch), - ], - )?; - } - commands.push(DeviceCommand::Gemm { - bf16: false, - x: input, - w: scratch, - y: output, - n: n as i32, - k: k as i32, - ldy: n as i32, - offset: 0, - beta: 0., - }); - Ok(()) - }; - scan(&mut commands, GdnBatchStage::MixedH, mixed)?; - // t > 64 with fused guards: the guards of qkv, the convolution output, the normalised q/k, z, the readout, y and its - // FP16 image ride on the kernels that read or write those tensors (same status words) - let fused = crate::prefill_stage::fused_scans() && t > 64; - let word = |stage: GdnBatchStage| status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4); - native(&mut commands, weights.formats[0], mixed, w[0], qkv, C, N)?; - if !fused { - scan(&mut commands, GdnBatchStage::Qkv, qkv)?; - } - native(&mut commands, weights.formats[1], mixed, w[1], z, ZV, N)?; - if !fused { - scan(&mut commands, GdnBatchStage::Z, z)?; - } - for (i, offset) in [(3, 0), (4, HV)] { - commands.push(DeviceCommand::Gemm { - bf16: true, - x: high, - w: w[i], - y: ab, - n: HV as i32, - k: N as i32, - ldy: 96, - offset, - beta: 0., - }); - if let Some(lo) = lower { - commands.push(DeviceCommand::Gemm { - bf16: true, - x: lo, - w: w[i], - y: ab, - n: HV as i32, - k: N as i32, - ldy: 96, - offset, - beta: 1., - }) - } - } - scan(&mut commands, GdnBatchStage::Ab, ab)?; - add_kernel( - &mut commands, - Kernel::Gates, - linear(t * HV)?, - &[ - ffi::KernelArg::Pointer(ab), - ffi::KernelArg::Pointer(a[1]), - ffi::KernelArg::Pointer(a[2]), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::I64(t as i64), - ], - )?; - scan(&mut commands, GdnBatchStage::Gate, gate)?; - scan(&mut commands, GdnBatchStage::Beta, beta)?; - if t <= 64 { - add_kernel( - &mut commands, - Kernel::Conv, - ([80, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hin), - ffi::KernelArg::Pointer(hout), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(a[0]), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::I64(t as i64), - ], - )? - } else { - if fused { - commands.push(DeviceCommand::Stage { - index: crate::prefill_stage::GDN_CONV_TILED, - grid: 40 * t.div_ceil(64) as u32, - block: 256, - args: KernelArguments::new(vec![ - A::Address(hin), - A::Address(qkv), - A::Address(a[0]), - A::Address(h), - A::I64(t as i64), - A::Address(word(GdnBatchStage::Qkv)?), - A::Address(word(GdnBatchStage::ConvH)?), - ]), - }); - } else { - add_kernel( - &mut commands, - Kernel::ConvTiled, - ([80, t.div_ceil(64) as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hin), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::Pointer(a[0]), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::I64(t as i64), - ], - )?; - } - add_kernel( - &mut commands, - Kernel::ConvHist, - ([80, 1, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(hout), - ffi::KernelArg::Pointer(hin), - ffi::KernelArg::Pointer(qkv), - ffi::KernelArg::I64(t as i64), - ], - )?; - } - if !fused { - scan(&mut commands, GdnBatchStage::ConvH, h)?; - } - scan(&mut commands, GdnBatchStage::NextHistory, hout)?; - if fused { - commands.push(DeviceCommand::Stage { - index: crate::prefill_stage::GDN_L2, - grid: (32 * t).div_ceil(2) as u32, - block: 256, - args: KernelArguments::new(vec![ - A::Address(h), - A::F32(GDN_BATCH_EPSILON), - A::I64(t as i64), - A::Address(word(GdnBatchStage::Qk)?), - ]), - }); - } else { - add_kernel( - &mut commands, - Kernel::L2, - ([32, t as u32, 1], [128, 1, 1]), - &[ffi::KernelArg::Pointer(h), ffi::KernelArg::F32(GDN_BATCH_EPSILON)], - )?; - scan(&mut commands, GdnBatchStage::Qk, h)?; - } - let witness = status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?; - if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) { - let kh = !crate::prefill_stage::fast_rec(); - commands.push(DeviceCommand::Stage { - index: if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC }, - grid: if kh { 64 } else { 192 }, - block: 128, - args: KernelArguments::new(vec![ - A::Address(sin), - A::Address(sout), - A::Address(h), - A::Address(gate), - A::Address(beta), - A::Address(y), - A::I64(t as i64), - A::Address(witness), - ]), - }); - } else { - add_kernel( - &mut commands, - Kernel::RecColsPipe, - ([192, 1, 1], [32, 4, 1]), - &[ - ffi::KernelArg::Pointer(sin), - ffi::KernelArg::Pointer(sout), - ffi::KernelArg::Pointer(h), - ffi::KernelArg::Pointer(gate), - ffi::KernelArg::Pointer(beta), - ffi::KernelArg::Pointer(y), - ffi::KernelArg::I64(t as i64), - ffi::KernelArg::Pointer(witness), - ], - )?; - } - scan(&mut commands, GdnBatchStage::NextState, sout)?; - if fused { - commands.push(DeviceCommand::Stage { - index: if crate::prefill_stage::gdn_nostore() { - crate::prefill_stage::GDN_OUT_NORM_Y16 - } else { - crate::prefill_stage::GDN_OUT_NORM - }, - grid: (48 * t).div_ceil(2) as u32, - block: 256, - args: KernelArguments::new(vec![ - A::Address(z), - A::Address(a[3]), - A::F32(GDN_BATCH_EPSILON), - A::Address(y), - A::Address(yh), - A::I64(t as i64), - A::Address(word(GdnBatchStage::Z)?), - A::Address(word(GdnBatchStage::Readout)?), - A::Address(word(GdnBatchStage::Y)?), - A::Address(word(GdnBatchStage::Y16)?), - ]), - }); - } else { - scan(&mut commands, GdnBatchStage::Readout, y)?; - add_kernel( - &mut commands, - Kernel::OutNorm, - ([t as u32, 48, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(z), - ffi::KernelArg::Pointer(a[3]), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ffi::KernelArg::Pointer(y), - ffi::KernelArg::Pointer(yh), - ], - )?; - scan(&mut commands, GdnBatchStage::Y, y)?; - scan(&mut commands, GdnBatchStage::Y16, yh)?; - } - native(&mut commands, weights.formats[2], yh, w[2], bo, N, ZV)?; - scan(&mut commands, GdnBatchStage::Bo, bo)?; - let mut history_bytes = staging(HISTORY)?; - for (x, b) in history.iter().zip(history_bytes.as_chunks_mut::<4>().0) { - b.copy_from_slice(&x.to_le_bytes()) - } - let mut flags = staging(STATUS_BYTES)?; - let mut final_history = staging(HISTORY)?; - let mut values = Vec::new(); - values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; - let context = self.context; - let blas = workspace.blas()?; - let guard = match context.enter() { - Ok(g) => g, - Err(e) => { - self.failed = true; - context.poison(); - context.retain_driver(); - return Err(e); - } - }; - if self.stage.is_none() { - match KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES) { - Ok(m) => self.stage = Some(m), - Err(e) => { - let pop = guard.finish(); - self.failed = true; - return combine(Err(e), pop).map(|()| unreachable!("stage module")); - } - } - } - let timed = crate::command_profile::enabled(); - let started = std::time::Instant::now(); - let mut operation = - context.driver.api.copy_from(hin, &history_bytes).and_then(|()| context.driver.api.synchronize()); - if timed { - crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); - } - for (index, cmd) in commands.iter_mut().enumerate() { - if operation.is_err() { - break; - } - let started = std::time::Instant::now(); - let label = match cmd { - DeviceCommand::Kernel { .. } => "kernel", - DeviceCommand::Gemm { .. } => "gemm", - DeviceCommand::Stage { .. } => "stage", - }; - operation = match cmd { - DeviceCommand::Kernel { function, grid, block, args } => context.driver.api.launch_gdn_native( - *function, - GdnStream::from_raw(blas.stream()), - *grid, - *block, - args, - ), - DeviceCommand::Gemm { bf16, x, w, y, n, k, ldy, offset, beta } => { - blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta) - } - DeviceCommand::Stage { index, grid, block, args } => match self.stage.as_ref() { - Some(module) => module.launch(*index, *grid, *block, blas.stream(), args), - None => Err(Error::ContextPoisoned), - }, - }; - if timed && operation.is_ok() { - operation = blas.synchronize(); - crate::command_profile::add("gdn", index + 1, label, started.elapsed()); - } - } - let started = std::time::Instant::now(); - let sync = blas.synchronize(); - if operation.is_ok() && sync.is_ok() { - operation = context - .driver - .api - .copy_to(status, &mut flags) - .and_then(|()| context.driver.api.copy_to(hout, &mut final_history)) - } - let all = context.driver.api.synchronize(); - if timed { - crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed()); - } - let pop = guard.finish(); - let result = combine(combine(combine(operation, sync), all), pop); - if result.is_err() { - // A failed drain has no trustworthy completion boundary. Retain the - // command and host buffers before returning, so none can be freed - // while driver work may still reference them. - self.failed = true; - context.poison(); - context.retain_driver(); - std::mem::forget((commands, history_bytes, flags, final_history)); - workspace.mark_failed(); - return result.map(|()| unreachable!("failed GDN drain")); - } - let refusal = match decode_statuses(&flags, SLOTS) { - Ok(r) => r, - Err(e) => { - self.failed = true; - context.poison(); - context.retain_driver(); - return Err(e); - } - }; - if let Some(stage) = refusal { - return Err(Error::NonFiniteMmqOutput(match stage { - GdnBatchStage::Bo => "GDN block", - _ => "GDN prompt stage", - })); - } - values.extend(final_history.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if values.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("GDN final history")); - } - Ok((read.from_completed_block(), values.into_boxed_slice())) + Ok((mixed, high, lower)) + } + fn admit_phase(binder: &mut Binder<'_, 'ctx>, lease: &OriginalPromptRows<'_, '_, '_>) -> Result { + Ok(Phase { + qkv: binder.carved(lease, Role::Qkv, Carve::Phase("qkv", C * 4))?, + z: binder.carved(lease, Role::Z, Carve::Phase("z", ZV * 4))?, + ab: binder.carved(lease, Role::Ab, Carve::Phase("ab", HV * 8))?, + gate: binder.carved(lease, Role::Gate, Carve::Phase("gate", HV * 4))?, + beta: binder.carved(lease, Role::Beta, Carve::Phase("beta", HV * 4))?, + h: binder.carved(lease, Role::H, Carve::Phase("hbuf", C * 4))?, + y: binder.carved(lease, Role::Y, Carve::Phase("y", ZV * 4))?, + yh: binder.carved(lease, Role::Y16, Carve::Phase("y_h", ZV * 2))?, + }) } } diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs new file mode 100644 index 00000000..c44a0391 --- /dev/null +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs @@ -0,0 +1,345 @@ +//! Command list of `OriginalGdnPromptDevice::produce` (STRA-338): the kernels, GEMMs and prefill-stage launches of one +//! run, recorded in the order of the former single function. Nothing is submitted here. + +#[allow(unused_imports)] +use super::*; + +/// The commands of one run under construction. +struct Cmds<'f, 'ctx> { + funcs: &'f Functions, + context: &'ctx Context<'ctx>, + hd: Handles, + t: usize, + /// t > 64 with fused guards: the guards of qkv, the convolution output, the normalised q/k, z, the readout, y and + /// its FP16 image ride on the kernels that read or write those tensors (same status words). + fused: bool, + fast_dequant: bool, + list: Vec, +} + +/// Index offset of the element-parallel dequantization kernel of a format. +fn dequant_offset(format: GdnNativeFormat) -> usize { + match format { + GdnNativeFormat::Q8_0 => 0, + GdnNativeFormat::Q4K => 1, + GdnNativeFormat::Q5K => 2, + GdnNativeFormat::Q6K => 3, + GdnNativeFormat::Iq4Nl => 4, + GdnNativeFormat::Iq4Xs => 5, + } +} + +impl<'ctx> OriginalGdnPromptDevice<'ctx> { + pub(in super::super) fn build_commands( + &self, + hd: &Handles, + formats: [GdnNativeFormat; 3], + t: usize, + ) -> Result> { + let mut list = Vec::new(); + list.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?; + let funcs = self.batch.as_ref().ok_or(Error::ContextPoisoned)?.functions.as_ref(); + let funcs = funcs.ok_or(Error::ContextPoisoned)?; + let mut c = Cmds::new(funcs, self.context, (*hd, t), list); + c.begin()?; + c.projections(formats)?; + c.gates()?; + c.convolution_l2()?; + c.recurrence()?; + c.output(formats[2])?; + Ok(c.list) + } +} + +impl<'f, 'ctx> Cmds<'f, 'ctx> { + fn new( + funcs: &'f Functions, + context: &'ctx Context<'ctx>, + run: (Handles, usize), + list: Vec, + ) -> Self { + let (hd, t) = run; + let fused = crate::prefill_stage::fused_scans() && t > 64; + Self { funcs, context, hd, t, fused, fast_dequant: crate::prefill_stage::fast_dequant(), list } + } + fn kernel(&mut self, kernel: Kernel, geometry: ([u32; 3], [u32; 3]), args: &[ffi::KernelArg]) -> Result<()> { + self.list.push(DeviceCommand::Kernel { + function: self.funcs.get(kernel), + grid: geometry.0, + block: geometry.1, + args: ffi::GdnPrefillArguments::new(args)?, + }); + Ok(()) + } + /// A `prefill_stage` kernel (1-D grid). + fn stage(&mut self, index: usize, grid: u32, block: u32, args: Vec) { + self.list.push(DeviceCommand::Stage { index, grid, block, args: KernelArguments::new(args) }); + } + fn word(&self, stage: GdnBatchStage) -> Result { + self.hd.status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) + } + /// The finite guard of `data` into the status word of `stage`. + fn scan(&mut self, stage: GdnBatchStage, data: ffi::BufferHandle) -> Result<()> { + let word = self.word(stage)?; + let kernel = if stage.is_half() { Kernel::FiniteF16 } else { Kernel::FiniteF32 }; + let count = stage.elements(self.t); + let args = [ffi::KernelArg::Pointer(data), ffi::KernelArg::Pointer(word), ffi::KernelArg::U32(count as u32)]; + self.kernel(kernel, linear(count)?, &args) + } + /// Dequantizes `weight` into the scratch and multiplies it with `input`. + fn native( + &mut self, + format: GdnNativeFormat, + input: ffi::BufferHandle, + weight: ffi::BufferHandle, + output: ffi::BufferHandle, + shape: (usize, usize), + ) -> Result<()> { + let (n, k) = shape; + if self.fast_dequant { + self.dequant_stage(format, weight, shape)?; + } else { + self.dequant_kernel(format, weight, shape)?; + } + let (x, w, y, n, k) = (input, self.hd.scratch, output, n as i32, k as i32); + self.list.push(DeviceCommand::Gemm { bf16: false, x, w, y, n, k, ldy: n, offset: 0, beta: 0. }); + Ok(()) + } + fn dequant_stage( + &mut self, + format: GdnNativeFormat, + weight: ffi::BufferHandle, + shape: (usize, usize), + ) -> Result<()> { + let (n, k) = shape; + let total = n * k; + let index = crate::prefill_stage::DEQUANT_FIRST + dequant_offset(format); + let grid = u32::try_from(total.div_ceil(256)).map_err(|_| Error::InvalidQwenShape)?; + let args = vec![ + A::Address(weight), + A::I64((k / format.block().0 * format.block().1) as i64), + A::I64(total as i64), + A::I64((k / 32) as i64), + A::Address(self.hd.scratch), + ]; + self.stage(index, grid, 256, args); + Ok(()) + } + fn dequant_kernel( + &mut self, + format: GdnNativeFormat, + weight: ffi::BufferHandle, + shape: (usize, usize), + ) -> Result<()> { + let (n, k) = shape; + let args = [ + ffi::KernelArg::Pointer(weight), + ffi::KernelArg::I64((k / format.block().0 * format.block().1) as i64), + ffi::KernelArg::I64(0), + ffi::KernelArg::I64(n as i64), + ffi::KernelArg::I64((k / 32) as i64), + ffi::KernelArg::Pointer(self.hd.scratch), + ]; + self.kernel(format.kernel(), linear(n * (k / 32))?, &args) + } + fn begin(&mut self) -> Result<()> { + let status = ffi::KernelArg::Pointer(self.hd.status); + self.kernel(Kernel::Zero, linear(SLOTS)?, &[status, ffi::KernelArg::U32(SLOTS as u32)])?; + self.scan(GdnBatchStage::MixedH, self.hd.c.mixed) + } + fn projections(&mut self, formats: [GdnNativeFormat; 3]) -> Result<()> { + let (hd, fused) = (self.hd, self.fused); + self.native(formats[0], hd.c.mixed, hd.w[0], hd.c.p.qkv, (C, N))?; + if !fused { + self.scan(GdnBatchStage::Qkv, hd.c.p.qkv)?; + } + self.native(formats[1], hd.c.mixed, hd.w[1], hd.c.p.z, (ZV, N))?; + if !fused { + self.scan(GdnBatchStage::Z, hd.c.p.z)?; + } + Ok(()) + } + /// The alpha and beta GEMMs (high, and low when the profile has it), their gates and guards. + fn gates(&mut self) -> Result<()> { + let hd = self.hd; + for (i, offset) in [(3, 0), (4, HV)] { + self.gemm_ab(hd.c.high, hd.w[i], offset, 0.); + if let Some(lo) = hd.c.lower { + self.gemm_ab(lo, hd.w[i], offset, 1.); + } + } + self.scan(GdnBatchStage::Ab, hd.c.p.ab)?; + let args = [ + ffi::KernelArg::Pointer(hd.c.p.ab), + ffi::KernelArg::Pointer(hd.a[1]), + ffi::KernelArg::Pointer(hd.a[2]), + ffi::KernelArg::Pointer(hd.c.p.gate), + ffi::KernelArg::Pointer(hd.c.p.beta), + ffi::KernelArg::I64(self.t as i64), + ]; + self.kernel(Kernel::Gates, linear(self.t * HV)?, &args)?; + self.scan(GdnBatchStage::Gate, hd.c.p.gate)?; + self.scan(GdnBatchStage::Beta, hd.c.p.beta) + } + fn gemm_ab(&mut self, x: ffi::BufferHandle, w: ffi::BufferHandle, offset: usize, beta: f32) { + let (n, k, y) = (HV as i32, N as i32, self.hd.c.p.ab); + self.list.push(DeviceCommand::Gemm { bf16: true, x, w, y, n, k, ldy: 96, offset, beta }); + } + fn convolution_l2(&mut self) -> Result<()> { + self.convolution()?; + self.l2() + } + fn convolution(&mut self) -> Result<()> { + let (hd, t) = (self.hd, self.t); + let (qkv, h, geometry) = (hd.c.p.qkv, hd.c.p.h, ([80, 1, 1], [128, 1, 1])); + if t <= 64 { + let args = [ + ffi::KernelArg::Pointer(hd.hin), + ffi::KernelArg::Pointer(hd.hout), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::Pointer(hd.a[0]), + ffi::KernelArg::Pointer(h), + ffi::KernelArg::I64(t as i64), + ]; + self.kernel(Kernel::Conv, geometry, &args)?; + } else { + self.conv_tiled()?; + let args = [ + ffi::KernelArg::Pointer(hd.hout), + ffi::KernelArg::Pointer(hd.hin), + ffi::KernelArg::Pointer(qkv), + ffi::KernelArg::I64(t as i64), + ]; + self.kernel(Kernel::ConvHist, geometry, &args)?; + } + if !self.fused { + self.scan(GdnBatchStage::ConvH, h)?; + } + self.scan(GdnBatchStage::NextHistory, hd.hout) + } + fn conv_tiled(&mut self) -> Result<()> { + let (hd, t) = (self.hd, self.t); + if self.fused { + let args = vec![ + A::Address(hd.hin), + A::Address(hd.c.p.qkv), + A::Address(hd.a[0]), + A::Address(hd.c.p.h), + A::I64(t as i64), + A::Address(self.word(GdnBatchStage::Qkv)?), + A::Address(self.word(GdnBatchStage::ConvH)?), + ]; + self.stage(crate::prefill_stage::GDN_CONV_TILED, 40 * t.div_ceil(64) as u32, 256, args); + return Ok(()); + } + let args = [ + ffi::KernelArg::Pointer(hd.hin), + ffi::KernelArg::Pointer(hd.c.p.qkv), + ffi::KernelArg::Pointer(hd.a[0]), + ffi::KernelArg::Pointer(hd.c.p.h), + ffi::KernelArg::I64(t as i64), + ]; + self.kernel(Kernel::ConvTiled, ([80, t.div_ceil(64) as u32, 1], [128, 1, 1]), &args) + } + fn l2(&mut self) -> Result<()> { + let (h, t) = (self.hd.c.p.h, self.t); + if self.fused { + let word = self.word(GdnBatchStage::Qk)?; + let args = vec![A::Address(h), A::F32(GDN_BATCH_EPSILON), A::I64(t as i64), A::Address(word)]; + self.stage(crate::prefill_stage::GDN_L2, (32 * t).div_ceil(2) as u32, 256, args); + return Ok(()); + } + let args = [ffi::KernelArg::Pointer(h), ffi::KernelArg::F32(GDN_BATCH_EPSILON)]; + self.kernel(Kernel::L2, ([32, t as u32, 1], [128, 1, 1]), &args)?; + self.scan(GdnBatchStage::Qk, h) + } + /// The state recurrence: the staged kernel when requested or usable, the original pipe kernel otherwise. + fn recurrence(&mut self) -> Result<()> { + let witness = self.word(GdnBatchStage::StateSteps)?; + if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) { + self.recurrence_staged(witness); + } else { + self.recurrence_pipe(witness)?; + } + self.scan(GdnBatchStage::NextState, self.hd.sout) + } + fn recurrence_staged(&mut self, witness: ffi::BufferHandle) { + let kh = !crate::prefill_stage::fast_rec(); + let index = if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC }; + let (p, sin, sout) = (self.hd.c.p, self.hd.sin, self.hd.sout); + let args = vec![ + A::Address(sin), + A::Address(sout), + A::Address(p.h), + A::Address(p.gate), + A::Address(p.beta), + A::Address(p.y), + A::I64(self.t as i64), + A::Address(witness), + ]; + self.stage(index, if kh { 64 } else { 192 }, 128, args); + } + fn recurrence_pipe(&mut self, witness: ffi::BufferHandle) -> Result<()> { + let (p, sin, sout) = (self.hd.c.p, self.hd.sin, self.hd.sout); + let args = [ + ffi::KernelArg::Pointer(sin), + ffi::KernelArg::Pointer(sout), + ffi::KernelArg::Pointer(p.h), + ffi::KernelArg::Pointer(p.gate), + ffi::KernelArg::Pointer(p.beta), + ffi::KernelArg::Pointer(p.y), + ffi::KernelArg::I64(self.t as i64), + ffi::KernelArg::Pointer(witness), + ]; + self.kernel(Kernel::RecColsPipe, ([192, 1, 1], [32, 4, 1]), &args) + } + /// The output norm and the projection of the block output. + fn output(&mut self, format: GdnNativeFormat) -> Result<()> { + let hd = self.hd; + if self.fused { + self.out_norm_fused()?; + } else { + self.out_norm()?; + } + self.native(format, hd.c.p.yh, hd.w[2], hd.c.bo, (N, ZV))?; + self.scan(GdnBatchStage::Bo, hd.c.bo) + } + fn out_norm_fused(&mut self) -> Result<()> { + let (hd, t) = (self.hd, self.t); + let index = if crate::prefill_stage::gdn_nostore() { + crate::prefill_stage::GDN_OUT_NORM_Y16 + } else { + crate::prefill_stage::GDN_OUT_NORM + }; + let (p, gamma) = (hd.c.p, hd.a[3]); + let args = vec![ + A::Address(p.z), + A::Address(gamma), + A::F32(GDN_BATCH_EPSILON), + A::Address(p.y), + A::Address(p.yh), + A::I64(t as i64), + A::Address(self.word(GdnBatchStage::Z)?), + A::Address(self.word(GdnBatchStage::Readout)?), + A::Address(self.word(GdnBatchStage::Y)?), + A::Address(self.word(GdnBatchStage::Y16)?), + ]; + self.stage(index, (48 * t).div_ceil(2) as u32, 256, args); + Ok(()) + } + fn out_norm(&mut self) -> Result<()> { + let (hd, t) = (self.hd, self.t); + let p = hd.c.p; + self.scan(GdnBatchStage::Readout, p.y)?; + let args = [ + ffi::KernelArg::Pointer(p.z), + ffi::KernelArg::Pointer(hd.a[3]), + ffi::KernelArg::F32(GDN_BATCH_EPSILON), + ffi::KernelArg::Pointer(p.y), + ffi::KernelArg::Pointer(p.yh), + ]; + self.kernel(Kernel::OutNorm, ([t as u32, 48, 1], [128, 1, 1]), &args)?; + self.scan(GdnBatchStage::Y, p.y)?; + self.scan(GdnBatchStage::Y16, p.yh) + } +} diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_5.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_5.rs new file mode 100644 index 00000000..853d0498 --- /dev/null +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_5.rs @@ -0,0 +1,199 @@ +//! Drain of `OriginalGdnPromptDevice::produce` (STRA-338): submits the command list on the batch stream, reads the +//! status words and the final history back, and decides whether the run was clean. A failed drain retains the command +//! and host buffers, because driver work may still reference them. + +#[allow(unused_imports)] +use super::*; +use crate::CurrentGuard; + +/// Host buffers of one run: the history upload, the status words and final history read back, and the decoded history. +struct Host { + history_bytes: Vec, + flags: Vec, + final_history: Vec, + values: Vec, +} + +impl Host { + fn new(history: &[f32]) -> Result { + let mut history_bytes = staging(HISTORY)?; + for (x, b) in history.iter().zip(history_bytes.as_chunks_mut::<4>().0) { + b.copy_from_slice(&x.to_le_bytes()) + } + let flags = staging(STATUS_BYTES)?; + let final_history = staging(HISTORY)?; + let mut values = Vec::new(); + values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; + Ok(Self { history_bytes, flags, final_history, values }) + } + /// Retains the command and host staging buffers of a failed drain; the decoded values are released normally. + fn retain(self, commands: Vec) { + let Self { history_bytes, flags, final_history, values } = self; + std::mem::forget((commands, history_bytes, flags, final_history)); + drop(values); + } +} + +fn command_label(cmd: &DeviceCommand) -> &'static str { + match cmd { + DeviceCommand::Kernel { .. } => "kernel", + DeviceCommand::Gemm { .. } => "gemm", + DeviceCommand::Stage { .. } => "stage", + } +} + +impl<'ctx> OriginalGdnPromptDevice<'ctx> { + /// Runs the commands and returns the final history, or the refusal of the first stage that was not finite. + pub(in super::super) fn drain( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + commands: Vec, + history: &[f32], + run: (&Handles, usize), + ) -> Result> { + let host = Host::new(history)?; + let host = self.execute(workspace, (commands, host), run)?; + self.decode_run(host) + } + fn fail_context(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + fn execute( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + owned: (Vec, Host), + run: (&Handles, usize), + ) -> Result { + let ((mut commands, mut host), (hd, t)) = (owned, run); + let blas = workspace.blas()?; + let guard = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.fail_context(); + return Err(e); + } + }; + let guard = self.ensure_stage(guard)?; + let outcome = self.stream_run(blas, (&mut commands, &mut host), (hd, t)); + let pop = guard.finish(); + let result = combine(outcome, pop); + if result.is_err() { + // A failed drain has no trustworthy completion boundary. Retain the + // command and host buffers before returning, so none can be freed + // while driver work may still reference them. + self.fail_context(); + host.retain(commands); + workspace.mark_failed(); + return result.map(|()| unreachable!("failed GDN drain")); + } + Ok(host) + } + /// Submits the commands, drains the stream and reads the status words and final history back. + fn stream_run( + &self, + blas: &crate::ple_batch_ffi::Blas, + buffers: (&mut [DeviceCommand], &mut Host), + run: (&Handles, usize), + ) -> Result<()> { + let ((commands, host), (hd, t)) = (buffers, run); + let timed = crate::command_profile::enabled(); + let mut operation = self.submit(blas, commands, (&host.history_bytes, hd.hin, t), timed); + let started = std::time::Instant::now(); + let sync = blas.synchronize(); + if operation.is_ok() && sync.is_ok() { + operation = self.read_back(hd, host); + } + let all = self.context.driver.api.synchronize(); + if timed { + crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed()); + } + combine(combine(operation, sync), all) + } + fn ensure_stage(&mut self, guard: CurrentGuard<'ctx, 'ctx>) -> Result> { + if self.stage.is_none() { + match KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES) { + Ok(m) => self.stage = Some(m), + Err(e) => { + let pop = guard.finish(); + self.failed = true; + return combine(Err(e), pop).map(|()| unreachable!("stage module")); + } + } + } + Ok(guard) + } + /// Uploads the history and launches the commands in order; stops at the first failure. + fn submit( + &self, + blas: &crate::ple_batch_ffi::Blas, + commands: &mut [DeviceCommand], + upload: (&[u8], ffi::BufferHandle, usize), + timed: bool, + ) -> Result<()> { + let (bytes, hin, t) = upload; + let api = &self.context.driver.api; + let started = std::time::Instant::now(); + let mut operation = api.copy_from(hin, bytes).and_then(|()| api.synchronize()); + if timed { + crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); + } + for (index, cmd) in commands.iter_mut().enumerate() { + if operation.is_err() { + break; + } + let started = std::time::Instant::now(); + let label = command_label(cmd); + operation = self.launch(blas, cmd, t); + if timed && operation.is_ok() { + operation = blas.synchronize(); + crate::command_profile::add("gdn", index + 1, label, started.elapsed()); + } + } + operation + } + fn launch(&self, blas: &crate::ple_batch_ffi::Blas, cmd: &mut DeviceCommand, t: usize) -> Result<()> { + match cmd { + DeviceCommand::Kernel { function, grid, block, args } => self.context.driver.api.launch_gdn_native( + *function, + GdnStream::from_raw(blas.stream()), + *grid, + *block, + args, + ), + DeviceCommand::Gemm { bf16, x, w, y, n, k, ldy, offset, beta } => { + blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta) + } + DeviceCommand::Stage { index, grid, block, args } => match self.stage.as_ref() { + Some(module) => module.launch(*index, *grid, *block, blas.stream(), args), + None => Err(Error::ContextPoisoned), + }, + } + } + fn read_back(&self, hd: &Handles, host: &mut Host) -> Result<()> { + let api = &self.context.driver.api; + api.copy_to(hd.status, &mut host.flags).and_then(|()| api.copy_to(hd.hout, &mut host.final_history)) + } + /// The first refused stage, or the final history when every guard stayed clean. + fn decode_run(&mut self, mut host: Host) -> Result> { + let refusal = match decode_statuses(&host.flags, SLOTS) { + Ok(r) => r, + Err(e) => { + self.fail_context(); + return Err(e); + } + }; + if let Some(stage) = refusal { + return Err(Error::NonFiniteMmqOutput(match stage { + GdnBatchStage::Bo => "GDN block", + _ => "GDN prompt stage", + })); + } + host.values.extend(host.final_history.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if host.values.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("GDN final history")); + } + Ok(host.values.into_boxed_slice()) + } +} diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_6.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_6.rs new file mode 100644 index 00000000..e2e019f8 --- /dev/null +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_6.rs @@ -0,0 +1,107 @@ +//! Buffers of `OriginalGdnPromptDevice::produce` (STRA-338): the admitted handles of a run and the binder that admits +//! them (owner, extent, alias and role checks) in the order of the former single function. + +#[allow(unused_imports)] +use super::*; +use crate::OriginalPromptRows; + +/// How a span is carved out of the prompt arena: a phase span of the GDN layout or a common span, with its row width. +pub(in super::super) enum Carve { + Phase(&'static str, usize), + Common(OriginalPromptSpan, usize), +} + +/// The phase buffers of the GDN prompt kernels. +#[derive(Clone, Copy)] +pub(in super::super) struct Phase { + pub(in super::super) qkv: ffi::BufferHandle, + pub(in super::super) z: ffi::BufferHandle, + pub(in super::super) ab: ffi::BufferHandle, + pub(in super::super) gate: ffi::BufferHandle, + pub(in super::super) beta: ffi::BufferHandle, + pub(in super::super) h: ffi::BufferHandle, + pub(in super::super) y: ffi::BufferHandle, + pub(in super::super) yh: ffi::BufferHandle, +} + +/// The spans carved out of the arena. +#[derive(Clone, Copy)] +pub(in super::super) struct Carved { + pub(in super::super) mixed: ffi::BufferHandle, + pub(in super::super) high: ffi::BufferHandle, + pub(in super::super) lower: Option, + pub(in super::super) p: Phase, + pub(in super::super) bo: ffi::BufferHandle, +} + +/// Every buffer one run reads or writes, after admission. +#[derive(Clone, Copy)] +pub(in super::super) struct Handles { + pub(in super::super) status: ffi::BufferHandle, + pub(in super::super) scratch: ffi::BufferHandle, + pub(in super::super) hin: ffi::BufferHandle, + pub(in super::super) hout: ffi::BufferHandle, + pub(in super::super) sin: ffi::BufferHandle, + pub(in super::super) sout: ffi::BufferHandle, + pub(in super::super) w: [ffi::BufferHandle; 5], + pub(in super::super) a: [ffi::BufferHandle; 4], + pub(in super::super) c: Carved, +} + +/// Admits buffers of one run: each is bound to a role and may not overlap the status words or another role. +pub(in super::super) struct Binder<'a, 'ctx> { + pub(in super::super) context: &'ctx Context<'ctx>, + pub(in super::super) workspace: &'a NativeBatchWorkspace<'ctx>, + pub(in super::super) status: ffi::BufferHandle, + pub(in super::super) bindings: Bindings, + pub(in super::super) t: usize, +} + +impl Binder<'_, '_> { + pub(in super::super) fn buffer( + &mut self, + role: Role, + b: &DeviceBuffer<'_>, + bytes: usize, + ) -> Result { + if !std::ptr::eq(b.context, self.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + self.workspace.reject_alias(h, bytes)?; + if h.overlaps(bytes, self.status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + self.bindings.bind(role, h, bytes)?; + Ok(h) + } + pub(in super::super) fn carved( + &mut self, + lease: &OriginalPromptRows<'_, '_, '_>, + role: Role, + carve: Carve, + ) -> Result { + let (h, capacity, bytes) = match carve { + Carve::Phase(name, width) => { + let (h, n) = lease.span(PrefillPhase::Gdn, name)?; + (h, n, self.t * width) + } + Carve::Common(span, width) => { + let (h, n) = lease.common_span(span)?; + (h, n, self.t * width) + } + }; + let h = h.checked_subspan(capacity, 0, bytes)?; + h.validate_projection_extent(bytes, 2)?; + self.workspace.reject_alias(h, bytes)?; + if h.overlaps(bytes, self.status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + self.bindings.bind(role, h, bytes)?; + Ok(h) + } +}