diff --git a/crates/cuda-driver/src/batch_gr_preview.rs b/crates/cuda-driver/src/batch_gr_preview.rs index f623aa0e..1997c4a1 100644 --- a/crates/cuda-driver/src/batch_gr_preview.rs +++ b/crates/cuda-driver/src/batch_gr_preview.rs @@ -1,6 +1,19 @@ //! First real chunk primitive: one launch over independent GR token columns. //! Numerical experiment only; no production asset admission or session commit. use super::*; +/// The four device buffers of one batched residual-inject launch. +pub struct GrInjectBuffers<'a, 'b> { + pub residual: &'a DeviceBuffer<'b>, + pub output: &'a DeviceBuffer<'b>, + pub inject: &'a DeviceBuffer<'b>, + pub candidate: &'a mut DeviceBuffer<'b>, +} +/// The device buffers of one batched norm launch (shared gamma, per-token residual and output). +pub struct GrNormBuffers<'a, 'b> { + pub residual: &'a DeviceBuffer<'b>, + pub gamma: &'a DeviceBuffer<'b>, + pub output: &'a mut DeviceBuffer<'b>, +} fn batch_layout(operation: Operation, tokens: usize) -> Result { if !(1..=64).contains(&tokens) || !matches!( @@ -77,14 +90,8 @@ mod installed { } Ok(Self { context, module: Some(module), functions, launch_attempts: std::cell::Cell::new(0) }) } - pub fn inject( - &self, - tokens: usize, - residual: &DeviceBuffer<'_>, - output: &DeviceBuffer<'_>, - inject: &DeviceBuffer<'_>, - candidate: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn inject(&self, tokens: usize, buffers: GrInjectBuffers<'_, '_>) -> Result<()> { + let GrInjectBuffers { residual, output, inject, candidate } = buffers; self.run(Operation::InjectResidual, tokens, &[residual, output, inject, candidate]) } pub(super) fn run(&self, operation: Operation, tokens: usize, buffers: &[&DeviceBuffer<'_>]) -> Result<()> { @@ -196,14 +203,8 @@ mod installed { } impl Context<'_> { - pub fn gr_batch_inject_residual_f32( - &self, - tokens: usize, - residual: &DeviceBuffer<'_>, - output: &DeviceBuffer<'_>, - inject: &DeviceBuffer<'_>, - candidate: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn gr_batch_inject_residual_f32(&self, tokens: usize, buffers: GrInjectBuffers<'_, '_>) -> Result<()> { + let GrInjectBuffers { residual, output, inject, candidate } = buffers; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] { let dispatcher = installed::GrBatchPreview::new(self)?; @@ -225,14 +226,8 @@ impl Context<'_> { // Private ignored derivative proof entry; shared gamma, per-token R/output. impl Context<'_> { - pub fn gr_batch_norm_f32( - &self, - tokens: usize, - residual: &DeviceBuffer<'_>, - gamma: &DeviceBuffer<'_>, - epsilon: f32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn gr_batch_norm_f32(&self, tokens: usize, epsilon: f32, buffers: GrNormBuffers<'_, '_>) -> Result<()> { + let GrNormBuffers { residual, gamma, output } = buffers; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] { let dispatcher = installed::GrBatchPreview::new(self)?; diff --git a/crates/cuda-driver/src/closed_kernels_gpu.rs b/crates/cuda-driver/src/closed_kernels_gpu.rs index 512dc5f6..c1cef074 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu.rs @@ -59,6 +59,42 @@ struct Admitted { writes: bool, } +/// Grid, block and dynamic shared memory of one launch. +#[derive(Clone, Copy)] +pub(crate) struct Geometry { + pub(crate) grid: [u32; 3], + pub(crate) block: [u32; 3], + pub(crate) shared: u32, +} + +/// The buffers of one short FlashAttention step: `q`, `k`, `v`, the device `step` record, the optional mask, `out` and +/// `status`. +pub struct FlashStepBuffers<'a, 'b> { + pub q: &'a DeviceBuffer<'b>, + pub k: &'a DeviceBuffer<'b>, + pub v: &'a DeviceBuffer<'b>, + pub step: &'a DeviceBuffer<'b>, + pub mask: Option<&'a DeviceBuffer<'b>>, + pub out: &'a mut DeviceBuffer<'b>, + pub status: &'a mut DeviceBuffer<'b>, +} + +/// The input and output widths of an S-form GEMV. +#[derive(Clone, Copy)] +pub struct SGemvDims { + pub n_in: i64, + pub n_out: i64, +} + +/// The buffers of an S-form GEMV: activation `x`, packed `codes`, `scales`, the optional `offset` and the output `y`. +pub struct SGemvBuffers<'a, 'b> { + pub x: &'a DeviceBuffer<'b>, + pub codes: &'a DeviceBuffer<'b>, + pub scales: &'a DeviceBuffer<'b>, + pub offset: Option<&'a DeviceBuffer<'b>>, + pub y: &'a mut DeviceBuffer<'b>, +} + struct Launch { function: ffi::FunctionHandle, grid: [u32; 3], diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs index 3658c131..dd4ee5a6 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs @@ -84,12 +84,11 @@ impl<'c> ClosedKernels<'c> { pub(in super::super) fn build( &self, entry: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, + geometry: Geometry, slots: &[Slot], operands: &[Operand<'_, '_>], ) -> Result { + let Geometry { grid, block, shared } = geometry; let spec = &self.program.entries()[entry]; if !conforms(spec, slots) { return invalid("closed launch arguments differ from the entry's fixed signature"); @@ -171,7 +170,8 @@ impl<'c> ClosedKernels<'c> { let guard = context.enter()?; let mut launch = Ok(()); for l in &mut launches { - launch = context.driver.api.launch_closed(l.function, l.grid, l.block, l.shared, &mut l.args); + let geometry = Geometry { grid: l.grid, block: l.block, shared: l.shared }; + launch = context.driver.api.launch_closed(l.function, geometry, &mut l.args); if launch.is_err() { break; } diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs index 4ad754c9..305fa89d 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs @@ -65,12 +65,12 @@ impl<'a, 'b> FlashBuffers<'a, 'b> { fn s_gemv_operands<'a, 'b>( plan: &Plan, form: &SForm, - n_in: i64, - n_out: i64, - [x, codes, scales]: [&'a DeviceBuffer<'b>; 3], - offset: Option<&'a DeviceBuffer<'b>>, - y: &'a DeviceBuffer<'b>, + dims: SGemvDims, + buffers: SGemvBuffers<'a, 'b>, ) -> Result>> { + let SGemvDims { n_in, n_out } = dims; + let SGemvBuffers { x, codes, scales, offset, y } = buffers; + let y: &'a DeviceBuffer<'b> = y; let bytes = s_operand_bytes(plan.kernel, form, n_in, n_out)?; if bytes.offset.is_some() != offset.is_some() { return invalid("the S-form has an offset exactly when an offset buffer is passed"); @@ -95,27 +95,21 @@ impl<'c> ClosedKernels<'c> { /// `status` one i32 (0 = success, 1 = the step record is not a valid short step: `out` is then NaN). Launch /// geometry is the Original's `<<<24, dim3(32, 4)>>>`; the argument admission is `native_flash_attn::admit` /// verbatim (`idx_top_k` is the QSA index's top-k, which the Original also checks). - #[allow(clippy::too_many_arguments)] // closed ABI operands pub fn native_flash_attn_short( &self, - q: &DeviceBuffer<'_>, - k: &DeviceBuffer<'_>, - v: &DeviceBuffer<'_>, - step: &DeviceBuffer<'_>, - mask: Option<&DeviceBuffer<'_>>, + buffers: FlashStepBuffers<'_, '_>, capacity: i64, idx_top_k: i64, max_context: i32, - out: &mut DeviceBuffer<'_>, - status: &mut DeviceBuffer<'_>, ) -> Result<()> { + let FlashStepBuffers { q, k, v, step, mask, out, status } = buffers; self.expect(Program::NativeFlashAttn)?; let bytes = flash_bytes(capacity)?; let buffers = FlashBuffers { q, k, v, step, mask, out, status }; let (grid, block, shared) = buffers.admit(capacity, idx_top_k, max_context)?; let operands = buffers.operands(&bytes); let slots = flash_slots(max_context, mask.is_some()); - let launch = self.build(FLASH_SHORT, grid, block, shared, &slots, &operands)?; + let launch = self.build(FLASH_SHORT, Geometry { grid, block, shared }, &slots, &operands)?; self.run(vec![launch]) } @@ -139,14 +133,8 @@ impl<'c> ClosedKernels<'c> { writes: true, }]; let grid = [u32::try_from(slice.blocks).or_else(|_| invalid("poison slice exceeds the grid"))?, 1, 1]; - launches.push(self.build( - POISON_F32, - grid, - [device_arena::POISON_THREADS as u32, 1, 1], - 0, - &poison_slots(slice.n_floats)?, - &operands, - )?); + let geometry = Geometry { grid, block: [device_arena::POISON_THREADS as u32, 1, 1], shared: 0 }; + launches.push(self.build(POISON_F32, geometry, &poison_slots(slice.n_floats)?, &operands)?); } self.run(launches) } @@ -156,45 +144,20 @@ impl<'c> ClosedKernels<'c> { /// Launch a planned S-form GEMV (`plan_s_gemv*` of `s_gemv_legacy`) over admitted operands: fp16, `block_q8_K` or /// `block_q8_0` activation `x` (as the plan's kernel reads it), the packed `codes`, `scales` and (when the form has /// one) `offset`, and `y` of `n_out` floats. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn s_gemv( - &self, - plan: &Plan, - form: &SForm, - n_in: i64, - n_out: i64, - x: &DeviceBuffer<'_>, - codes: &DeviceBuffer<'_>, - scales: &DeviceBuffer<'_>, - offset: Option<&DeviceBuffer<'_>>, - y: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn s_gemv(&self, plan: &Plan, form: &SForm, dims: SGemvDims, buffers: SGemvBuffers<'_, '_>) -> Result<()> { self.expect(Program::SGemvLegacy)?; - let operands = s_gemv_operands(plan, form, n_in, n_out, [x, codes, scales], offset, y)?; - let slots = s_gemv_slots(plan, form, n_in, n_out, offset.is_some()); - let launch = self.build( - s_gemv_entry_index(plan.kernel), - plan.launch.grid, - plan.launch.block, - plan.launch.dynamic_shared, - &slots, - &operands, - )?; + let SGemvDims { n_in, n_out } = dims; + let has_offset = buffers.offset.is_some(); + let operands = s_gemv_operands(plan, form, dims, buffers)?; + let slots = s_gemv_slots(plan, form, n_in, n_out, has_offset); + let geometry = + Geometry { grid: plan.launch.grid, block: plan.launch.block, shared: plan.launch.dynamic_shared }; + let launch = self.build(s_gemv_entry_index(plan.kernel), geometry, &slots, &operands)?; self.run(vec![launch]) } /// The S2 kernels (`plan_s2_gemv*`): the 2-bit, group-64 form without offsets. - #[allow(clippy::too_many_arguments)] // closed ABI operands - pub fn s2_gemv( - &self, - plan: &Plan, - n_in: i64, - n_out: i64, - x: &DeviceBuffer<'_>, - codes: &DeviceBuffer<'_>, - scales: &DeviceBuffer<'_>, - y: &mut DeviceBuffer<'_>, - ) -> Result<()> { - self.s_gemv(plan, &SForm::default(), n_in, n_out, x, codes, scales, None, y) + pub fn s2_gemv(&self, plan: &Plan, dims: SGemvDims, buffers: SGemvBuffers<'_, '_>) -> Result<()> { + self.s_gemv(plan, &SForm::default(), dims, buffers) } } diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs index 41d7bbdf..e99ae6c0 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs @@ -8,7 +8,7 @@ //! cargo test -p leleka-cuda-driver --features cuda-driver -- --ignored closed_gpu //! Until the pins are frozen every test fails with the typed `Unpinned` refusal, which is the intended state. use super::closed_kernels::Program; -use super::closed_kernels_gpu::ClosedKernels; +use super::closed_kernels_gpu::{ClosedKernels, FlashStepBuffers, SGemvBuffers, SGemvDims}; use super::s_gemv_legacy::{self as sg, Codebook, Kernel, SForm}; use super::{Context, DeviceBuffer, Driver, device_arena, native_flash_attn as flash}; diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs index ae28e55f..077ae550 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke/cases.rs @@ -48,19 +48,9 @@ impl FlashCase { let mut out_b = upload(ctx, &vec![0xffu8; 24 * 256 * 4]); let mut status_b = upload(ctx, &(-1i32).to_le_bytes()); let mask = self.with_mask.then_some(&mask_b); - gpu.native_flash_attn_short( - &q_b, - &k_b, - &v_b, - &step_b, - mask, - CAPACITY as i64, - 2051, - 256, - &mut out_b, - &mut status_b, - ) - .unwrap(); + let buffers = + FlashStepBuffers { q: &q_b, k: &k_b, v: &v_b, step: &step_b, mask, out: &mut out_b, status: &mut status_b }; + gpu.native_flash_attn_short(buffers, CAPACITY as i64, 2051, 256).unwrap(); let status = i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()); (status, f32s(&download(&out_b, 24 * 256 * 4))) } @@ -92,8 +82,17 @@ pub(super) fn assert_invalid_step_refused<'c>(ctx: &'c Context<'c>, gpu: &Closed let (q_b, kv_b) = (upload(ctx, &zeros), upload(ctx, &vec![0u8; 256 * 1024])); let step_b = upload(ctx, &[0u8; 16]); let (mut out_b, mut status_b) = (upload(ctx, &zeros), upload(ctx, &0i32.to_le_bytes())); - gpu.native_flash_attn_short(&q_b, &kv_b, &zero_kv(ctx), &step_b, None, 256, 2051, 256, &mut out_b, &mut status_b) - .unwrap(); + let zero_v = zero_kv(ctx); + let buffers = FlashStepBuffers { + q: &q_b, + k: &kv_b, + v: &zero_v, + step: &step_b, + mask: None, + out: &mut out_b, + status: &mut status_b, + }; + gpu.native_flash_attn_short(buffers, 256, 2051, 256).unwrap(); assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP); assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan())); } @@ -140,13 +139,16 @@ impl<'a, 'c> Replay<'a, 'c> { /// Launches the planned kernel on activation `x` and compares with `want`: bit for bit when the case is exact. fn check(&mut self, what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]) { let (n_in, n_out) = (self.n_in, self.n_out); + let dims = SGemvDims { n_in, n_out }; let mut y = upload(self.ctx, &vec![0xffu8; n_out as usize * 4]); let s2 = matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8); if self.form.code_bits == 2 && s2 { - self.gpu.s2_gemv(&plan, n_in, n_out, x, &self.codes, &self.scales, &mut y).unwrap(); + let buffers = SGemvBuffers { x, codes: &self.codes, scales: &self.scales, offset: None, y: &mut y }; + self.gpu.s2_gemv(&plan, dims, buffers).unwrap(); } else { let offset = self.offset.as_ref(); - self.gpu.s_gemv(&plan, &self.form, n_in, n_out, x, &self.codes, &self.scales, offset, &mut y).unwrap(); + let buffers = SGemvBuffers { x, codes: &self.codes, scales: &self.scales, offset, y: &mut y }; + self.gpu.s_gemv(&plan, &self.form, dims, buffers).unwrap(); } let got = f32s(&download(&y, n_out as usize * 4)); let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); diff --git a/crates/cuda-driver/src/deferred_status.rs b/crates/cuda-driver/src/deferred_status.rs index c7a318b8..ca0fa31f 100644 --- a/crates/cuda-driver/src/deferred_status.rs +++ b/crates/cuda-driver/src/deferred_status.rs @@ -63,6 +63,17 @@ pub(crate) fn enabled() -> bool { *ON.get_or_init(|| std::env::var("LELEKA_PREFILL_DEFER_GUARDS").map_or(true, |v| v != "0")) } +/// One deferred check: the status words (`bytes` of them at `status`), their `stride`, the streams to order after the +/// readback and the labels of the guards. +#[derive(Clone, Copy)] +pub(crate) struct DeferredStatusCheck<'a> { + pub(crate) status: crate::ffi::BufferHandle, + pub(crate) bytes: usize, + pub(crate) stride: usize, + pub(crate) order: &'a [usize], + pub(crate) labels: &'a [&'static str], +} + #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod device { use super::evaluate; @@ -164,15 +175,8 @@ mod device { /// Steps 2-3: copy the words out behind the kernels, record the event, order every other stream after it, /// remember the check. - pub(crate) fn finish( - context: &Context<'_>, - status: BufferHandle, - bytes: usize, - stream: usize, - stride: usize, - order: &[usize], - labels: &[&'static str], - ) -> Result<()> { + pub(crate) fn finish(context: &Context<'_>, stream: usize, spec: super::DeferredStatusCheck<'_>) -> Result<()> { + let super::DeferredStatusCheck { status, bytes, stride, order, labels } = spec; STATE.with(|cell| { let mut guard = cell.borrow_mut(); let st = guard.as_mut().ok_or(Error::ContextPoisoned)?; @@ -236,15 +240,7 @@ mod unsupported { pub(crate) fn begin(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn finish( - _: &Context<'_>, - _: BufferHandle, - _: usize, - _: usize, - _: usize, - _: &[usize], - _: &[&'static str], - ) -> Result<()> { + pub(crate) fn finish(_: &Context<'_>, _: usize, _: super::DeferredStatusCheck<'_>) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn resolve(_: &Context<'_>) -> Result<()> { diff --git a/crates/cuda-driver/src/deferred_status_gpu.rs b/crates/cuda-driver/src/deferred_status_gpu.rs index 8087324f..878e0b12 100644 --- a/crates/cuda-driver/src/deferred_status_gpu.rs +++ b/crates/cuda-driver/src/deferred_status_gpu.rs @@ -65,7 +65,9 @@ fn deferred_status_equals_the_immediate_evaluation_and_poisons() { begin(&context, handle, BYTES, blas.stream(), 4096).expect("begin"); blas.synchronize().expect("sync"); put(status, words); // stands in for the kernels' flag writes - finish(&context, handle, BYTES, blas.stream(), STRIDE, &ORDER, &LABELS).expect("finish"); + let spec = + super::DeferredStatusCheck { status: handle, bytes: BYTES, stride: STRIDE, order: &ORDER, labels: &LABELS }; + finish(&context, blas.stream(), spec).expect("finish"); guard.finish().expect("pop"); }; clean_runs(&context, &mut status, &run); diff --git a/crates/cuda-driver/src/experimental_gpu_smoke.rs b/crates/cuda-driver/src/experimental_gpu_smoke.rs index 5e3d9f84..bb5fc0b6 100644 --- a/crates/cuda-driver/src/experimental_gpu_smoke.rs +++ b/crates/cuda-driver/src/experimental_gpu_smoke.rs @@ -254,15 +254,21 @@ fn resolve_inputs() -> (Vec, Vec) { (ids, steps) } +/// The arrays of one resolve: the host arrays the blocks are copied from and the slot arrays they land in. +struct CopyArrays<'a, 'c> { + host: &'a [DeviceBuffer<'c>], + slots: &'a mut [DeviceBuffer<'c>], +} + /// Uploads the ids and step records and runs `stream_resolve` (+ copy) over the host arrays into the slot arrays. fn resolve_on_device<'c>( ctx: &'c Context<'c>, gpu: &Experimental<'c>, buffers: &mut MapBuffers<'c>, - host: &[DeviceBuffer<'c>], - slots: &mut [DeviceBuffer<'c>], + arrays: CopyArrays<'_, 'c>, inputs: (&[i32], &[i32]), ) { + let CopyArrays { host, slots } = arrays; let (ids_b, steps_b) = (upload(ctx, &i32_bytes(inputs.0)), upload(ctx, &i32_bytes(inputs.1))); let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect(); let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect(); @@ -344,7 +350,7 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() { let mut buffers = MapBuffers::new(&ctx); gpu.stream_reset(&mut buffers.map(), STREAM_BLOCKS, STREAM_SLOTS).unwrap(); let (ids, steps) = resolve_inputs(); - resolve_on_device(&ctx, &gpu, &mut buffers, &host, &mut slots, (&ids, &steps)); + resolve_on_device(&ctx, &gpu, &mut buffers, CopyArrays { host: &host, slots: &mut slots }, (&ids, &steps)); assert_resolved_like_cpu(&buffers, &slots, &host_bytes, &runs, (&ids, &steps)); gpu.close().unwrap(); } diff --git a/crates/cuda-driver/src/ffi.rs b/crates/cuda-driver/src/ffi.rs index 993980da..b91cc9c8 100644 --- a/crates/cuda-driver/src/ffi.rs +++ b/crates/cuda-driver/src/ffi.rs @@ -97,8 +97,8 @@ pub(crate) struct Q5ProjectionArguments { #[path = "mmq_ffi.rs"] mod mmq_abi; pub(crate) use mmq_abi::{ - Iq3NativeIntegerArguments, MmqArguments, MmqFixupArguments, MmqOriginalGatherArguments, MmqOriginalSwigluArguments, - MmqQuantArguments, MmqResidentArguments, + Iq3NativeIntegerArguments, MmqArguments, MmqFixupArguments, MmqGatherShape, MmqGroupBuffers, MmqGroupRouting, + MmqGroupShape, MmqOriginalGatherArguments, MmqOriginalSwigluArguments, MmqQuantArguments, MmqResidentArguments, }; // Closed kernel-parameter storage of the Strata-prefill GDN / native dequant modules. diff --git a/crates/cuda-driver/src/gdn_batch_gemm.rs b/crates/cuda-driver/src/gdn_batch_gemm.rs index 532410ee..a85886db 100644 --- a/crates/cuda-driver/src/gdn_batch_gemm.rs +++ b/crates/cuda-driver/src/gdn_batch_gemm.rs @@ -67,14 +67,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { Ok(Self { workspace, stream: GdnStream::from_raw(stream) }) } - fn enqueue( - &self, - bf16: bool, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn enqueue(&self, bf16: bool, [x, w, y]: [&DeviceBuffer<'_>; 3], shape: GemmShape) -> Result<()> { let context = self.workspace.context_for_gdn(); self.workspace.validate_context(context)?; admit_shape(bf16, &shape)?; @@ -127,9 +120,9 @@ impl GdnGemm for NativeGdnGemm<'_, '_> { self.stream } fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { - self.enqueue(false, x, w, y, shape) + self.enqueue(false, [x, w, y], shape) } fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { - self.enqueue(true, x, w, y, shape) + self.enqueue(true, [x, w, y], shape) } } diff --git a/crates/cuda-driver/src/gdn_closed_queue.rs b/crates/cuda-driver/src/gdn_closed_queue.rs index 15aac277..475bd588 100644 --- a/crates/cuda-driver/src/gdn_closed_queue.rs +++ b/crates/cuda-driver/src/gdn_closed_queue.rs @@ -115,6 +115,40 @@ pub struct GdnRowPrefix<'lease, 'ctx> { fetch: Option, } +/// The six owners of the original convolution: the history and the QKV input (for the retained-row form the whole +/// batched columns owner), the conv weights, the next history and the raw and H outputs. +#[derive(Clone, Copy)] +pub struct GdnConvBuffers<'lease> { + pub history: &'lease DeviceBuffer<'lease>, + pub qkv: &'lease DeviceBuffer<'lease>, + pub weights: &'lease DeviceBuffer<'lease>, + pub next_history: &'lease DeviceBuffer<'lease>, + pub raw: &'lease DeviceBuffer<'lease>, + pub h: &'lease DeviceBuffer<'lease>, +} + +/// The seven owners of the recurrence: the current state, the Q/K and H producers, the gate and the beta sigmoid, the +/// next state and the readout. +#[derive(Clone, Copy)] +pub struct GdnRecurrenceBuffers<'lease> { + pub state: &'lease DeviceBuffer<'lease>, + pub qk: &'lease DeviceBuffer<'lease>, + pub h: &'lease DeviceBuffer<'lease>, + pub gate: &'lease DeviceBuffer<'lease>, + pub beta: &'lease DeviceBuffer<'lease>, + pub next_state: &'lease DeviceBuffer<'lease>, + pub readout: &'lease DeviceBuffer<'lease>, +} + +/// The four owners of the output norm: the readout and Z inputs, the gamma weights and the normalized output. +#[derive(Clone, Copy)] +pub struct GdnOutNormBuffers<'lease> { + pub readout: &'lease DeviceBuffer<'lease>, + pub z: &'lease DeviceBuffer<'lease>, + pub gamma: &'lease DeviceBuffer<'lease>, + pub normalized: &'lease DeviceBuffer<'lease>, +} + /// Completed drain. A numerical refusal withholds the canonical next history. pub struct GdnRowCompletion { refusal: Option, diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs index 1c85432b..358eca14 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix.rs @@ -3,9 +3,9 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_gdnrowprefix/impl_gdnrowprefix_2.rs"] -mod impl_gdnrowprefix_2; -#[path = "impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs"] -mod impl_gdnrowprefix_2_2; +#[path = "impl_gdnrowprefix/convolution_stages.rs"] +mod convolution_stages; #[path = "impl_gdnrowprefix/impl_gdnrowprefix_3.rs"] mod impl_gdnrowprefix_3; +#[path = "impl_gdnrowprefix/recurrence_stages.rs"] +mod recurrence_stages; diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/convolution_stages.rs similarity index 92% rename from crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs rename to crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/convolution_stages.rs index f1905175..08db9f9d 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/convolution_stages.rs @@ -153,15 +153,8 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { } /// Original convolution, then the raw, next-history and H scans in the /// legacy readback order. - pub fn conv_silu( - &mut self, - history: &'lease DeviceBuffer<'lease>, - qkv: &'lease DeviceBuffer<'lease>, - weights: &'lease DeviceBuffer<'lease>, - next_history: &'lease DeviceBuffer<'lease>, - raw: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { + pub fn conv_silu(&mut self, buffers: GdnConvBuffers<'lease>) -> Result<()> { + let GdnConvBuffers { history, qkv, weights, next_history, raw, h } = buffers; let result = (|| { self.ready(Step::Conv)?; if self.columns.is_some() { @@ -181,17 +174,10 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { /// The same convolution over the retained, already scanned QKV row. The /// whole batched owner is admitted first; only the fixed row range is /// derived from it. - #[allow(clippy::too_many_arguments)] // Six fixed source-defined owners and the row. - pub fn conv_silu_columns( - &mut self, - history: &'lease DeviceBuffer<'lease>, - columns: &'lease DeviceBuffer<'lease>, - row: usize, - weights: &'lease DeviceBuffer<'lease>, - next_history: &'lease DeviceBuffer<'lease>, - raw: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { + /// + /// `buffers.qkv` is the whole batched columns owner here. + pub fn conv_silu_columns(&mut self, buffers: GdnConvBuffers<'lease>, row: usize) -> Result<()> { + let GdnConvBuffers { history, qkv: columns, weights, next_history, raw, h } = buffers; let bufs = [history, columns, weights, next_history, raw, h]; let result = (|| { self.ready(Step::Conv)?; diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/recurrence_stages.rs similarity index 91% rename from crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs rename to crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/recurrence_stages.rs index 1a2422c6..e9c0f65d 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/recurrence_stages.rs @@ -61,17 +61,8 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { /// producers, exactly as `gdn_step_from_products_f32` admits them, then /// the full next-state scan and the readout scan. The queue's own finite /// function scans the next state; `GdnStateFiniteGuard` is not involved. - #[allow(clippy::too_many_arguments)] // Seven fixed source-defined owners. - pub fn recurrence( - &mut self, - state: &'lease DeviceBuffer<'lease>, - qk: &'lease DeviceBuffer<'lease>, - h: &'lease DeviceBuffer<'lease>, - gate: &'lease DeviceBuffer<'lease>, - beta: &'lease DeviceBuffer<'lease>, - next_state: &'lease DeviceBuffer<'lease>, - readout: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { + pub fn recurrence(&mut self, buffers: GdnRecurrenceBuffers<'lease>) -> Result<()> { + let GdnRecurrenceBuffers { state, qk, h, gate, beta, next_state, readout } = buffers; let bufs = [state, qk, h, gate, beta, next_state, readout]; let result = (|| { self.ready(Step::Recurrence)?; @@ -156,14 +147,8 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { })(); self.latch(result) } - pub fn out_norm( - &mut self, - readout: &'lease DeviceBuffer<'lease>, - z: &'lease DeviceBuffer<'lease>, - gamma: &'lease DeviceBuffer<'lease>, - normalized: &'lease DeviceBuffer<'lease>, - epsilon: f32, - ) -> Result<()> { + pub fn out_norm(&mut self, buffers: GdnOutNormBuffers<'lease>, epsilon: f32) -> Result<()> { + let GdnOutNormBuffers { readout, z, gamma, normalized } = buffers; let result = (|| { self.ready(Step::OutNorm)?; self.same(self.readout, readout)?; diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu.rs index 2028ae59..8052dfea 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu.rs @@ -96,15 +96,15 @@ use bytes_fn::read; use bytes_fn::scalar; #[allow(unused_imports)] use bytes_fn::upload; -#[path = "gdn_closed_queue_gpu/columns_pair_fn.rs"] -mod columns_pair_fn; +#[path = "gdn_closed_queue_gpu/columns_pair_cases.rs"] +mod columns_pair_cases; #[allow(unused_imports)] -use columns_pair_fn::clean_pair; +use columns_pair_cases::clean_pair; #[allow(unused_imports)] -use columns_pair_fn::columns_pair; +use columns_pair_cases::compare; #[allow(unused_imports)] -use columns_pair_fn::compare; +use columns_pair_cases::refusal_case; #[allow(unused_imports)] -use columns_pair_fn::refusal_case; +use columns_pair_cases::refuse; #[allow(unused_imports)] -use columns_pair_fn::refuse; +use columns_pair_cases::{ColumnsCase, ColumnsPoison, columns_pair}; diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs index 84beebcc..3925881f 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs @@ -25,6 +25,33 @@ pub(super) fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, off (0..count).map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset).collect() } impl<'a> Row<'a> { + /// The convolution owners of this row over the given QKV owner (the row's own or a retained columns owner). + pub(super) fn conv_buffers<'s>(&'s self, qkv: &'s DeviceBuffer<'s>) -> GdnConvBuffers<'s> { + GdnConvBuffers { + history: &self.history, + qkv, + weights: &self.weights, + next_history: &self.next_history, + raw: &self.raw, + h: &self.h, + } + } + /// The recurrence owners of this row writing `next_state`. + pub(super) fn recurrence_buffers<'s>(&'s self, next_state: &'s DeviceBuffer<'s>) -> GdnRecurrenceBuffers<'s> { + GdnRecurrenceBuffers { + state: &self.state, + qk: &self.qk, + h: &self.h, + gate: &self.gate, + beta: &self.sigmoid, + next_state, + readout: &self.readout, + } + } + /// The output-norm owners of this row. + pub(super) fn out_norm_buffers(&self) -> GdnOutNormBuffers<'_> { + GdnOutNormBuffers { readout: &self.readout, z: &self.z, gamma: &self.gamma, normalized: &self.normalized } + } pub(super) fn new(context: &'a Context<'_>, salt: usize, poison: Poison) -> Result { let (host_alpha, host_weights, host_state, host_z) = Self::host_inputs(salt, poison); let [history, qkv, weights, alpha, beta_raw] = Self::upload_front(context, salt, [&host_weights, &host_alpha])?; @@ -177,7 +204,7 @@ pub(super) fn queued<'q>(queue: &'q mut GdnRowQueue<'_>, row: &'q Row<'_>) -> Re let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + prefix.conv_silu(row.conv_buffers(&row.qkv))?; queue_after_conv(&mut prefix, row)?; prefix.finish() } @@ -187,9 +214,9 @@ fn queue_after_conv<'l>(prefix: &mut GdnRowPrefix<'l, '_>, row: &'l Row<'_>) -> prefix.qk_l2(&row.h, &row.qk, EPSILON)?; prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; - prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.next_state, &row.readout)?; + prefix.recurrence(row.recurrence_buffers(&row.next_state))?; prefix.scan_z(&row.z)?; - prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?; + prefix.out_norm(row.out_norm_buffers(), EPSILON)?; prefix.fetch_next_history(&row.next_history) } @@ -205,7 +232,7 @@ pub(super) fn queued_columns<'q>( prefix.scan_qkv_columns(columns, index)?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu_columns(&row.history, columns, index, &row.weights, &row.next_history, &row.raw, &row.h)?; + prefix.conv_silu_columns(row.conv_buffers(columns), index)?; queue_after_conv(&mut prefix, row)?; prefix.finish() } diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_cases.rs similarity index 81% rename from crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs rename to crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_cases.rs index 07f3b2ed..64517550 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_cases.rs @@ -3,25 +3,39 @@ #[allow(unused_imports)] use super::*; +/// The batched image of one retained-row case: the salt, the number of rows and the used row. +#[derive(Clone, Copy)] +pub(super) struct ColumnsCase { + pub(super) salt: usize, + pub(super) tokens: usize, + pub(super) used: usize, +} + +/// Which rows of the batched image carry a non-finite word. +#[derive(Clone, Copy)] +pub(super) struct ColumnsPoison { + pub(super) used: bool, + pub(super) other: bool, +} + /// Retained-row QKV must match the original sequence over the same row bit for /// bit; non-finite words in OTHER rows must not matter, in the used row they /// must refuse at the first stage. -#[allow(clippy::too_many_arguments)] // Test case selectors, not caller geometry. pub(super) fn columns_pair( context: &Context<'_>, queue: &mut GdnRowQueue<'_>, - salt: usize, - tokens: usize, - used: usize, - poison_used: bool, - poison_other: bool, + case: ColumnsCase, + poison: ColumnsPoison, report: &mut Report, ) -> Result<()> { + let ColumnsCase { salt, tokens, used } = case; + let ColumnsPoison { used: poison_used, other: poison_other } = poison; let image = poisoned_image(salt, tokens, used, poison_used, poison_other); let mut old = Row::new(context, salt, Poison::default())?; let actual = Row::new(context, salt, Poison::default())?; let columns = upload(context, &image)?; - let operation = compare_columns(context, queue, (&mut old, &actual), (&columns, used), poison_used, report); + let retained = RetainedColumns { buffer: &columns, row: used, poisoned: poison_used }; + let operation = compare_columns(context, queue, (&mut old, &actual), retained, report); combine(combine(combine(operation, old.release()), actual.release()), columns.release()) } @@ -39,19 +53,27 @@ fn poisoned_image(salt: usize, tokens: usize, used: usize, poison_used: bool, po image } -/// The original sequence over `rows.0`, then the queued program over `rows.1` with `columns` (buffer, row index). +/// The retained batched QKV owner, the used row index and whether that row is poisoned. +#[derive(Clone, Copy)] +struct RetainedColumns<'a> { + buffer: &'a DeviceBuffer<'a>, + row: usize, + poisoned: bool, +} + +/// The original sequence over `rows.0`, then the queued program over `rows.1` with the retained `columns`. fn compare_columns( context: &Context<'_>, queue: &mut GdnRowQueue<'_>, rows: (&mut Row<'_>, &Row<'_>), - columns: (&DeviceBuffer<'_>, usize), - poison_used: bool, + columns: RetainedColumns<'_>, report: &mut Report, ) -> Result<()> { let (old, actual) = rows; + let RetainedColumns { buffer, row, poisoned: poison_used } = columns; scalar(context, old)?; let expected = old.products()?; - let completion = queued_columns(queue, actual, columns.0, columns.1)?; + let completion = queued_columns(queue, actual, buffer, row)?; report.guards += 1; if poison_used { note_qkv_refusal(&completion, report); diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs index d70e8a9a..3364846b 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/scenarios.rs @@ -47,9 +47,10 @@ fn clean_and_refused_rows(context: &Context<'_>, queue: &mut GdnRowQueue<'_>, re /// irrelevant, the USED row refuses. fn column_groups(context: &Context<'_>, queue: &mut GdnRowQueue<'_>, report: &mut Report) -> Result<()> { for (tokens, used) in [(3usize, 0usize), (3, 1), (3, 2), (64, 63)] { - columns_pair(context, queue, 8, tokens, used, false, false, report)?; - columns_pair(context, queue, 8, tokens, used, false, true, report)?; - columns_pair(context, queue, 8, tokens, used, true, false, report)?; + let case = ColumnsCase { salt: 8, tokens, used }; + columns_pair(context, queue, case, ColumnsPoison { used: false, other: false }, report)?; + columns_pair(context, queue, case, ColumnsPoison { used: false, other: true }, report)?; + columns_pair(context, queue, case, ColumnsPoison { used: true, other: false }, report)?; clean_pair(context, queue, 3, report)?; } Ok(()) @@ -71,17 +72,13 @@ fn admission_refusals( fn scan_order_refusals(queue: &mut GdnRowQueue<'_>, row: &Row<'_>, report: &mut Report) -> Result<()> { // Convolution before the two input scans. let mut prefix = queue.begin()?; - refuse( - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), - Error::InvalidQwenShape, - report, - )?; + refuse(prefix.conv_silu(row.conv_buffers(&row.qkv)), Error::InvalidQwenShape, report)?; refuse(prefix.finish(), Error::InvalidQwenShape, report)?; // Q/K over a buffer that is not the convolution H output. let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + prefix.conv_silu(row.conv_buffers(&row.qkv))?; refuse(prefix.qk_l2(&row.raw, &row.qk, EPSILON), Error::InvalidQwenShape, report)?; // A latched admission error still drains the admitted prefix first. refuse(prefix.finish(), Error::InvalidQwenShape, report) @@ -92,15 +89,11 @@ fn recurrence_refusals(queue: &mut GdnRowQueue<'_>, row: &Row<'_>, report: &mut let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + prefix.conv_silu(row.conv_buffers(&row.qkv))?; prefix.qk_l2(&row.h, &row.qk, EPSILON)?; prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; - refuse( - prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.state, &row.readout), - Error::OutputAliasesInput, - report, - )?; + refuse(prefix.recurrence(row.recurrence_buffers(&row.state)), Error::OutputAliasesInput, report)?; refuse(prefix.finish(), Error::OutputAliasesInput, report) } @@ -129,7 +122,7 @@ fn fetch_refusals(queue: &mut GdnRowQueue<'_>, row: &Row<'_>, report: &mut Repor let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + prefix.conv_silu(row.conv_buffers(&row.qkv))?; refuse(prefix.fetch_next_history(&row.history), Error::InvalidQwenShape, report)?; refuse(prefix.finish(), Error::InvalidQwenShape, report)?; let mut prefix = queue.begin()?; @@ -194,11 +187,7 @@ fn retained_host_conv( prefix.scan_qkv_columns(image, 1)?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - refuse( - prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), - Error::InvalidQwenShape, - report, - )?; + refuse(prefix.conv_silu(row.conv_buffers(&row.qkv)), Error::InvalidQwenShape, report)?; refuse(prefix.finish(), Error::InvalidQwenShape, report) } @@ -214,10 +203,6 @@ fn retained_conv_columns( prefix.scan_qkv_columns(image, 1)?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - refuse( - prefix.conv_silu_columns(&row.history, conv.0, conv.1, &row.weights, &row.next_history, &row.raw, &row.h), - Error::InvalidQwenShape, - report, - )?; + refuse(prefix.conv_silu_columns(row.conv_buffers(conv.0), conv.1), Error::InvalidQwenShape, report)?; refuse(prefix.finish(), Error::InvalidQwenShape, report) } diff --git a/crates/cuda-driver/src/gdn_fused_t1.rs b/crates/cuda-driver/src/gdn_fused_t1.rs index e13dcdc1..5359decd 100644 --- a/crates/cuda-driver/src/gdn_fused_t1.rs +++ b/crates/cuda-driver/src/gdn_fused_t1.rs @@ -185,6 +185,31 @@ pub struct GdnFusedPrefix<'lease, 'ctx> { fetch: Option<(ffi::BufferHandle, ffi::BufferHandle)>, } +/// The seven operands of `fused_gdn_ab`: the activation, the two BF16 matrices, `dt`, `ssm_a`, and the gate and beta +/// outputs. +#[derive(Clone, Copy)] +pub struct GdnAbBuffers<'lease> { + pub mixed: &'lease DeviceBuffer<'lease>, + pub w_alpha: &'lease DeviceBuffer<'lease>, + pub w_beta: &'lease DeviceBuffer<'lease>, + pub dt: &'lease DeviceBuffer<'lease>, + pub ssm_a: &'lease DeviceBuffer<'lease>, + pub gate: &'lease DeviceBuffer<'lease>, + pub beta: &'lease DeviceBuffer<'lease>, +} + +/// The seven completed journal operands of the replay: state, Q/K, H, gate, beta, next state and readout. +#[derive(Clone, Copy)] +pub struct GdnReplayBuffers<'a> { + pub state: &'a DeviceBuffer<'a>, + pub qk: &'a DeviceBuffer<'a>, + pub h: &'a DeviceBuffer<'a>, + pub gate: &'a DeviceBuffer<'a>, + pub beta: &'a DeviceBuffer<'a>, + pub next: &'a DeviceBuffer<'a>, + pub readout: &'a DeviceBuffer<'a>, +} + /// Completed drain. A numerical refusal withholds the candidate state and history. pub struct GdnFusedCompletion { refusal: Option, diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs index 358ae628..a1f704fe 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix.rs @@ -3,7 +3,7 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs"] -mod impl_gdnfusedprefix_2; +#[path = "impl_gdnfusedprefix/fused_stage_binding.rs"] +mod fused_stage_binding; #[path = "impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs"] mod impl_gdnfusedprefix_2_2; diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/fused_stage_binding.rs similarity index 95% rename from crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs rename to crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/fused_stage_binding.rs index b132f862..ced271b0 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/fused_stage_binding.rs @@ -177,17 +177,8 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { } /// `fused_gdn_ab`: gate = softplus(alpha . x + dt) * ssm_a, beta = sigmoid(beta . x). `w_alpha` / `w_beta` are /// the exact BF16 `[48][2560]` matrices, `mixed` the exact f32 `[2560]` activation. - #[allow(clippy::too_many_arguments)] // The Original call has the same operand list. - pub fn ab( - &mut self, - mixed: &'lease DeviceBuffer<'lease>, - w_alpha: &'lease DeviceBuffer<'lease>, - w_beta: &'lease DeviceBuffer<'lease>, - dt: &'lease DeviceBuffer<'lease>, - ssm_a: &'lease DeviceBuffer<'lease>, - gate: &'lease DeviceBuffer<'lease>, - beta: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { + pub fn ab(&mut self, buffers: GdnAbBuffers<'lease>) -> Result<()> { + let GdnAbBuffers { mixed, w_alpha, w_beta, dt, ssm_a, gate, beta } = buffers; let result = (|| { self.ready(Step::Ab)?; let pointers = self.bind_ab([mixed, w_alpha, w_beta, dt, ssm_a, gate, beta])?; diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs index 5904b09a..b4168b5b 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs @@ -174,7 +174,8 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { let api = &self.batch.context.driver.api; let mut operation = Ok(()); for command in &mut self.commands { - operation = api.launch_gdn_native(command.function, stream, command.grid, command.block, &mut command.args); + let geometry = crate::GdnGeometry { grid: command.grid, block: command.block }; + operation = api.launch_gdn_native(command.function, stream, geometry, &mut command.args); if operation.is_err() { break; } diff --git a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs index 95b66405..545c60ff 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs @@ -72,17 +72,8 @@ impl Drop for GdnFusedT1<'_> { // Only completed real journal operands may be passed by the runtime. This method // produces state/readout numerics; it does not mint session or row authority. impl GdnFusedT1<'_> { - #[allow(clippy::too_many_arguments)] - pub fn replay_state_from_products( - &mut self, - state: &DeviceBuffer<'_>, - qk: &DeviceBuffer<'_>, - h: &DeviceBuffer<'_>, - gate: &DeviceBuffer<'_>, - beta: &DeviceBuffer<'_>, - next: &DeviceBuffer<'_>, - readout: &DeviceBuffer<'_>, - ) -> Result { + pub fn replay_state_from_products(&mut self, buffers: GdnReplayBuffers<'_>) -> Result { + let GdnReplayBuffers { state, qk, h, gate, beta, next, readout } = buffers; let mut prefix = self.begin()?; let arguments = prefix.bind_replay([state, qk, h, gate, beta, next, readout])?; prefix.push(FusedKernel::ReplayState, ([HV as u32, 1, 1], [S as u32, 4, 1]), &arguments)?; diff --git a/crates/cuda-driver/src/gdn_fused_t1_gpu.rs b/crates/cuda-driver/src/gdn_fused_t1_gpu.rs index 5333a7f6..dfadd77b 100644 --- a/crates/cuda-driver/src/gdn_fused_t1_gpu.rs +++ b/crates/cuda-driver/src/gdn_fused_t1_gpu.rs @@ -308,7 +308,15 @@ fn queue_program<'c>(prefix: &mut GdnFusedPrefix<'c, '_>, b: &'c RunBuffers<'c>, prefix.scan_inputs(&b.qkv, &b.z)?; prefix.seed_state(if from_resident { Some(&b.resident) } else { None }, &b.next_state)?; prefix.conv_l2(&b.hist, &b.conv, &b.h, EPS)?; - prefix.ab(&b.mixed, &b.wa, &b.wb, &b.dt, &b.a, &b.gate, &b.beta)?; + prefix.ab(GdnAbBuffers { + mixed: &b.mixed, + w_alpha: &b.wa, + w_beta: &b.wb, + dt: &b.dt, + ssm_a: &b.a, + gate: &b.gate, + beta: &b.beta, + })?; prefix.step_norm(&b.gamma, &b.y, EPS)?; prefix.fetch_candidate() } diff --git a/crates/cuda-driver/src/gdn_native_batch.rs b/crates/cuda-driver/src/gdn_native_batch.rs index 0fa74a4a..8c18b144 100644 --- a/crates/cuda-driver/src/gdn_native_batch.rs +++ b/crates/cuda-driver/src/gdn_native_batch.rs @@ -123,6 +123,13 @@ pub enum GdnNativeFormat { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct GdnStream(usize); +/// Grid and block shape of one launch of a GDN-family kernel. +#[derive(Clone, Copy)] +pub(crate) struct GdnGeometry { + pub(crate) grid: [u32; 3], + pub(crate) block: [u32; 3], +} + /// One shape of a GEMM the closed adapter performs on the context's launch /// (null) stream: `Y[t][y_offset + n] = alpha*sum_k X[t][k] * W[n][k] + beta*Y` /// with `alpha = 1`, row stride `ldy` (f32 words) of `Y`, `X` row stride `depth`, @@ -335,7 +342,7 @@ mod gpu; // Original physical prompt arena producer: old whole-owner API remains exact. #[path = "gdn_prompt_device.rs"] mod prompt_device; -pub use prompt_device::{OriginalGdnPromptDevice, OriginalGdnPromptWeights}; +pub use prompt_device::{OriginalGdnPromptDevice, OriginalGdnPromptState, OriginalGdnPromptWeights}; #[path = "gdn_native_batch/pinned_fn.rs"] mod pinned_fn; diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs index 4de60a62..aa0d28e1 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs @@ -142,7 +142,8 @@ impl Command<'_> { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { match self { Self::Kernel { function, stream, grid, block, args } => { - context.driver.api.launch_gdn_native(*function, *stream, *grid, *block, args) + let geometry = crate::GdnGeometry { grid: *grid, block: *block }; + context.driver.api.launch_gdn_native(*function, *stream, geometry, args) } Self::Gemm { gemm, bf16, x, w, y, shape } => { if *bf16 { diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs index 30af7baf..9c8070f0 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix.rs @@ -3,9 +3,9 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs"] -mod impl_gdnbatchprefix_2; -#[path = "impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs"] -mod impl_gdnbatchprefix_2_2; -#[path = "impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs"] -mod impl_gdnbatchprefix_3; +#[path = "impl_gdnbatchprefix/native_projection.rs"] +mod native_projection; +#[path = "impl_gdnbatchprefix/qkv_and_z_projections.rs"] +mod qkv_and_z_projections; +#[path = "impl_gdnbatchprefix/recurrence_and_output.rs"] +mod recurrence_and_output; diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/native_projection.rs similarity index 90% rename from crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs rename to crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/native_projection.rs index 6f2e99b8..3bf452e5 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/native_projection.rs @@ -3,6 +3,24 @@ #[allow(unused_imports)] use super::*; +/// The shape of one native projection: the GGUF `format`, the matrix `rows` x `depth` and the byte size of the f32 +/// output. +#[derive(Clone, Copy)] +pub(in super::super) struct NativeProjection { + pub(in super::super) format: GdnNativeFormat, + pub(in super::super) rows: usize, + pub(in super::super) depth: usize, + pub(in super::super) output_bytes: usize, +} + +/// The operands of one native projection: the weights, the FP16 scratch, the activation role and the output. +pub(in super::super) struct ProjectionOperands<'lease> { + pub(in super::super) weights: (Role, &'lease DeviceBuffer<'lease>), + pub(in super::super) scratch: &'lease DeviceBuffer<'lease>, + pub(in super::super) activation: Role, + pub(in super::super) output: (Role, &'lease DeviceBuffer<'lease>), +} + /// `actual` bytes are the exact size `bytes`, or at least `bytes` when `at_least`; a zero size is never admitted. fn size_admitted(actual: usize, bytes: usize, at_least: bool) -> bool { bytes != 0 && if at_least { actual >= bytes } else { actual == bytes } @@ -185,18 +203,13 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { } // ---------------------------------------------------------------- projections - #[allow(clippy::too_many_arguments)] // The fixed operands of one native projection. pub(in super::super) fn project_native( &mut self, - format: GdnNativeFormat, - weights: (Role, &'lease DeviceBuffer<'lease>), - scratch: &'lease DeviceBuffer<'lease>, - activation: Role, - output: (Role, &'lease DeviceBuffer<'lease>), - rows: usize, - depth: usize, - output_bytes: usize, + projection: NativeProjection, + operands: ProjectionOperands<'lease>, ) -> Result<()> { + let NativeProjection { format, rows, depth, output_bytes } = projection; + let ProjectionOperands { weights, scratch, activation, output } = operands; let matrix = format.matrix_bytes(rows, depth)?; let half_bytes = rows * depth * F16; let blocks = self.bind(weights.0, weights.1, matrix, false)?; diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/qkv_and_z_projections.rs similarity index 92% rename from crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs rename to crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/qkv_and_z_projections.rs index 8982be10..af18c257 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/qkv_and_z_projections.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338: impl GdnBatchPrefix (2). +use super::native_projection::{NativeProjection, ProjectionOperands}; #[allow(unused_imports)] use super::*; @@ -16,7 +17,14 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Qkv)?; let bytes = self.tokens * C * F32; - self.project_native(format, (Role::QkvW, weights), scratch, Role::MixedH, (Role::Qkv, qkv), C, N, bytes)?; + let projection = NativeProjection { format, rows: C, depth: N, output_bytes: bytes }; + let operands = ProjectionOperands { + weights: (Role::QkvW, weights), + scratch, + activation: Role::MixedH, + output: (Role::Qkv, qkv), + }; + self.project_native(projection, operands)?; self.scan(GdnBatchStage::Qkv, Role::Qkv)?; self.step = self.step.next(); Ok(()) @@ -34,7 +42,14 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Z)?; let bytes = self.tokens * ZV * F32; - self.project_native(format, (Role::ZW, weights), scratch, Role::MixedH, (Role::Z, z), ZV, N, bytes)?; + let projection = NativeProjection { format, rows: ZV, depth: N, output_bytes: bytes }; + let operands = ProjectionOperands { + weights: (Role::ZW, weights), + scratch, + activation: Role::MixedH, + output: (Role::Z, z), + }; + self.project_native(projection, operands)?; self.scan(GdnBatchStage::Z, Role::Z)?; self.step = self.step.next(); Ok(()) diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/recurrence_and_output.rs similarity index 95% rename from crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs rename to crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/recurrence_and_output.rs index 53d6d486..fed22cb0 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/recurrence_and_output.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338: impl GdnBatchPrefix (3). +use super::native_projection::{NativeProjection, ProjectionOperands}; #[allow(unused_imports)] use super::*; @@ -92,7 +93,14 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Out)?; let bytes = self.tokens * N * F32; - self.project_native(format, (Role::OutW, weights), scratch, Role::Y16, (Role::Bo, bo), N, ZV, bytes)?; + let projection = NativeProjection { format, rows: N, depth: ZV, output_bytes: bytes }; + let operands = ProjectionOperands { + weights: (Role::OutW, weights), + scratch, + activation: Role::Y16, + output: (Role::Bo, bo), + }; + self.project_native(projection, operands)?; self.scan(GdnBatchStage::Bo, Role::Bo)?; self.step = self.step.next(); Ok(()) diff --git a/crates/cuda-driver/src/gdn_native_batch_ffi.rs b/crates/cuda-driver/src/gdn_native_batch_ffi.rs index 8b792d26..bb039e7c 100644 --- a/crates/cuda-driver/src/gdn_native_batch_ffi.rs +++ b/crates/cuda-driver/src/gdn_native_batch_ffi.rs @@ -43,10 +43,10 @@ impl Api { &self, function: FunctionHandle, stream: batch::GdnStream, - grid: [u32; 3], - block: [u32; 3], + geometry: batch::GdnGeometry, args: &mut GdnPrefillArguments, ) -> Result<()> { + let batch::GdnGeometry { grid, block } = geometry; nonzero_geometry(grid, block)?; // SAFETY: geometry and parameter list are derived from the closed kernel // table and admitted extents; the owned argument storage survives the diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu.rs b/crates/cuda-driver/src/gdn_native_batch_gpu.rs index fbf36731..3beb967c 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu.rs @@ -153,19 +153,19 @@ use bytes_of_fn::pattern; #[allow(unused_imports)] use bytes_of_fn::q8_0; #[allow(unused_imports)] -use bytes_of_fn::reference; -#[allow(unused_imports)] use bytes_of_fn::sigm; #[allow(unused_imports)] use bytes_of_fn::words_of; -#[path = "gdn_native_batch_gpu/impl_hostgemm.rs"] -mod impl_hostgemm; #[allow(unused_imports)] -use impl_hostgemm::mismatch; +use bytes_of_fn::{Projections, reference}; +#[path = "gdn_native_batch_gpu/host_gemm_adapter.rs"] +mod host_gemm_adapter; #[allow(unused_imports)] -use impl_hostgemm::read; +use host_gemm_adapter::mismatch; #[allow(unused_imports)] -use impl_hostgemm::upload; +use host_gemm_adapter::read; +#[allow(unused_imports)] +use host_gemm_adapter::upload; #[path = "gdn_native_batch_gpu/run_case_fn.rs"] mod run_case_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs index cf13fe41..23807db8 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs @@ -99,19 +99,15 @@ pub(super) fn q8_0(rows: usize, cols: usize, salt: usize) -> (Vec, Vec) } (blocks, half) } -#[allow(clippy::too_many_arguments)] // The fixed operands of the original program. -pub(super) fn reference( - tokens: usize, - qkv: &[f32], - z: &[f32], - ab: &[f32], - history: &[f32], - conv_w: &[f32], - dt: &[f32], - a: &[f32], - gamma: &[f32], - state: &[f32], -) -> Reference { +/// The adapter outputs the host reference starts from: the qkv, z and (last) interleaved ab words. +pub(super) struct Projections<'a> { + pub(super) qkv: &'a [f32], + pub(super) z: &'a [f32], + pub(super) ab: &'a [f32], +} +pub(super) fn reference(tokens: usize, projections: Projections<'_>, host: &HostInputs) -> Reference { + let Projections { qkv, z, ab } = projections; + let HostInputs { history, conv_w, dt, a, gamma, state, .. } = host; let (gate, beta) = reference_gates(tokens, ab, dt, a); let mut h = reference_conv(tokens, qkv, history, conv_w); let next_history = reference_next_history(tokens, qkv, history); diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/host_gemm_adapter.rs similarity index 94% rename from crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs rename to crates/cuda-driver/src/gdn_native_batch_gpu/host_gemm_adapter.rs index 337024e2..2e4819cd 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/host_gemm_adapter.rs @@ -5,14 +5,7 @@ use super::*; impl HostGemm { - pub(super) fn run( - &self, - bf16: bool, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + pub(super) fn run(&self, bf16: bool, [x, w, y]: [&DeviceBuffer<'_>; 3], shape: GemmShape) -> Result<()> { self.calls.set(self.calls.get() + 1); let (xb, wb, yb) = (read(x)?, read(w)?, read(y)?); let (xh, wh) = (halves_of(&xb), halves_of(&wb)); @@ -20,7 +13,7 @@ impl HostGemm { host_gemm(bf16, shape, [&xh, &wh], &mut out)?; self.poison_output(shape, &mut out); y.context.driver.api.copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?; - self.capture(bf16, shape, &wh, xb, out); + self.capture(shape, (!bf16).then_some(&wh[..]), xb, out); Ok(()) } /// The configured NaN in the last output word of the Z and the alpha/beta projections. @@ -30,11 +23,11 @@ impl HostGemm { out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001); } } - /// Records the call: the FP16 matrix (F16 calls only), the input image and the output words. - fn capture(&self, bf16: bool, shape: GemmShape, wh: &[u16], xb: Vec, out: Vec) { + /// Records the call: the FP16 matrix (`Some` for F16 calls only), the input image and the output words. + fn capture(&self, shape: GemmShape, wh: Option<&[u16]>, xb: Vec, out: Vec) { let GemmShape { rows, depth, .. } = shape; let mut captured = self.captured.borrow_mut(); - if !bf16 { + if let Some(wh) = wh { captured.scratch.push((rows, wh[..rows * depth].to_vec())); } captured.x.push((depth, xb)); @@ -69,10 +62,10 @@ impl GdnGemm for HostGemm { GdnStream::default_stream() } fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { - self.run(false, x, w, y, shape) + self.run(false, [x, w, y], shape) } fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { - self.run(true, x, w, y, shape) + self.run(true, [x, w, y], shape) } } diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs index 812b45a4..de7729ad 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs @@ -140,8 +140,7 @@ fn host_reference(f: &Fixture<'_>, captured: &Captured, tokens: usize) -> Result .find(|(r, _)| *r == HV) .map(|(_, y)| y) .ok_or(Error::InvalidDriverValue("ab calls missing"))?; - let host = &f.host; - Ok(reference(tokens, qkv, z, ab, &host.history, &host.conv_w, &host.dt, &host.a, &host.gamma, &host.state)) + Ok(reference(tokens, Projections { qkv, z, ab }, &f.host)) } /// The device words are finite and close to the reference words of the same name. diff --git a/crates/cuda-driver/src/gdn_prompt_device.rs b/crates/cuda-driver/src/gdn_prompt_device.rs index 8bb93dd3..9a0eba28 100644 --- a/crates/cuda-driver/src/gdn_prompt_device.rs +++ b/crates/cuda-driver/src/gdn_prompt_device.rs @@ -26,6 +26,12 @@ pub struct OriginalGdnPromptWeights<'w, 'ctx> { pub formats: [GdnNativeFormat; 3], pub aux: [&'w DeviceBuffer<'ctx>; 4], } +/// The prior state and history of one produced block, and the buffer that receives the next state. +pub struct OriginalGdnPromptState<'a, 'ctx> { + pub state: &'a DeviceBuffer<'ctx>, + pub next_state: &'a DeviceBuffer<'ctx>, + pub history: &'a [f32], +} enum DeviceCommand { Kernel { function: ffi::FunctionHandle, 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 9f1e8f32..3ed6810a 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice.rs @@ -5,15 +5,15 @@ use super::*; #[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs"] mod impl_originalgdnpromptdevice_2; -#[path = "impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs"] -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; +#[path = "impl_originalgdnpromptdevice/prompt_block_produce.rs"] +mod prompt_block_produce; +#[path = "impl_originalgdnpromptdevice/prompt_command_list.rs"] +mod prompt_command_list; #[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_5.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_5.rs index 853d0498..ee85484c 100644 --- 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 @@ -158,8 +158,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { DeviceCommand::Kernel { function, grid, block, args } => self.context.driver.api.launch_gdn_native( *function, GdnStream::from_raw(blas.stream()), - *grid, - *block, + crate::GdnGeometry { grid: *grid, block: *block }, args, ), DeviceCommand::Gemm { bf16, x, w, y, n, k, ldy, offset, beta } => { 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/prompt_block_produce.rs similarity index 96% rename from crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs rename to crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/prompt_block_produce.rs index f7d8f88e..adcf029b 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/prompt_block_produce.rs @@ -1,5 +1,5 @@ //! 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`). +//! the command list (`prompt_command_list.rs`) and drains it (`impl_originalgdnpromptdevice_5.rs`). #[allow(unused_imports)] use super::*; @@ -8,16 +8,14 @@ use crate::OriginalPromptRows; impl<'ctx> OriginalGdnPromptDevice<'ctx> { /// Consumes the actual affine GR read. `state` is untouched prior; only /// `next_state` is written. Runtime alone may adopt it after this clean drain. - #[allow(clippy::too_many_arguments)] pub fn produce<'arena, 'loan>( &mut self, read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, workspace: &mut NativeBatchWorkspace<'ctx>, weights: OriginalGdnPromptWeights<'_, 'ctx>, - state: &DeviceBuffer<'ctx>, - next_state: &DeviceBuffer<'ctx>, - history: &[f32], + prior: OriginalGdnPromptState<'_, 'ctx>, ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Box<[f32]>)> { + let OriginalGdnPromptState { state, next_state, history } = prior; let t = read.rows(); self.admit(&read, workspace, history)?; let handles = self.admit_handles(read.lease(), (workspace, t), &weights, (state, next_state))?; 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/prompt_command_list.rs similarity index 95% rename from crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs rename to crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/prompt_command_list.rs index c44a0391..8ee40b4b 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_4.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/prompt_command_list.rs @@ -17,6 +17,13 @@ struct Cmds<'f, 'ctx> { list: Vec, } +/// A projection matrix: its GGUF format and the `(rows, depth)` shape. +#[derive(Clone, Copy)] +struct NativeMatrix { + format: GdnNativeFormat, + shape: (usize, usize), +} + /// Index offset of the element-parallel dequantization kernel of a format. fn dequant_offset(format: GdnNativeFormat) -> usize { match format { @@ -89,12 +96,12 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> { /// Dequantizes `weight` into the scratch and multiplies it with `input`. fn native( &mut self, - format: GdnNativeFormat, + matrix: NativeMatrix, input: ffi::BufferHandle, weight: ffi::BufferHandle, output: ffi::BufferHandle, - shape: (usize, usize), ) -> Result<()> { + let NativeMatrix { format, shape } = matrix; let (n, k) = shape; if self.fast_dequant { self.dequant_stage(format, weight, shape)?; @@ -149,11 +156,11 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> { } 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))?; + self.native(NativeMatrix { format: formats[0], shape: (C, N) }, hd.c.mixed, hd.w[0], hd.c.p.qkv)?; 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))?; + self.native(NativeMatrix { format: formats[1], shape: (ZV, N) }, hd.c.mixed, hd.w[1], hd.c.p.z)?; if !fused { self.scan(GdnBatchStage::Z, hd.c.p.z)?; } @@ -301,7 +308,7 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> { } else { self.out_norm()?; } - self.native(format, hd.c.p.yh, hd.w[2], hd.c.bo, (N, ZV))?; + self.native(NativeMatrix { format, shape: (N, ZV) }, hd.c.p.yh, hd.w[2], hd.c.bo)?; self.scan(GdnBatchStage::Bo, hd.c.bo) } fn out_norm_fused(&mut self) -> Result<()> { diff --git a/crates/cuda-driver/src/gr_batch_inject_workspace.rs b/crates/cuda-driver/src/gr_batch_inject_workspace.rs index b5c952de..fa93aaf5 100644 --- a/crates/cuda-driver/src/gr_batch_inject_workspace.rs +++ b/crates/cuda-driver/src/gr_batch_inject_workspace.rs @@ -26,6 +26,14 @@ impl GrBatchInjectShape { } } +/// The three host input streams of one injection: the streams, the blocks and the injects. +#[derive(Debug, Clone, Copy)] +pub struct GrInjectInputs<'a> { + pub streams: &'a [f32], + pub blocks: &'a [f32], + pub injects: &'a [f32], +} + /// Twelve eager whole owners; exclusive `&mut self` is the operation lease. pub struct GrBatchInjectWorkspace<'ctx> { context: &'ctx Context<'ctx>, @@ -177,10 +185,9 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { &mut self, context: &Context<'_>, shape: GrBatchInjectShape, - streams: &[f32], - blocks: &[f32], - injects: &[f32], + inputs: GrInjectInputs<'_>, ) -> Result> { + let GrInjectInputs { streams, blocks, injects } = inputs; if !std::ptr::eq(self.context, context) { return Err(Error::ContextMismatch); } diff --git a/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs b/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs index 8240daa2..d199e8a7 100644 --- a/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs +++ b/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs @@ -6,6 +6,9 @@ type Products = [Vec; 4]; fn check(ok: bool) -> Result<()> { if ok { Ok(()) } else { Err(Error::InvalidDriverValue("GR batch workspace proof")) } } +fn inputs_of(source: &[Vec; 3]) -> GrInjectInputs<'_> { + GrInjectInputs { streams: &source[0], blocks: &source[1], injects: &source[2] } +} fn bytes(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } @@ -68,10 +71,12 @@ fn launch_original(context: &Context<'_>, shape: GrBatchInjectShape, buffers: &m let (sources, output) = buffers.split_at_mut(3); context.gr_batch_inject_residual_f32( shape.tokens(), - sources[0].as_ref().ok_or(Error::ContextPoisoned)?, - sources[1].as_ref().ok_or(Error::ContextPoisoned)?, - sources[2].as_ref().ok_or(Error::ContextPoisoned)?, - output[0].as_mut().ok_or(Error::ContextPoisoned)?, + crate::GrInjectBuffers { + residual: sources[0].as_ref().ok_or(Error::ContextPoisoned)?, + output: sources[1].as_ref().ok_or(Error::ContextPoisoned)?, + inject: sources[2].as_ref().ok_or(Error::ContextPoisoned)?, + candidate: output[0].as_mut().ok_or(Error::ContextPoisoned)?, + }, ) } fn read_products(buffers: &Buffers<'_>, shape: GrBatchInjectShape) -> Result { @@ -96,7 +101,7 @@ fn original_first( ) -> Result { let expected = original(context, shape, source)?; let charged = context.allocated_bytes(); - let actual = workspace.inject(context, shape, &source[0], &source[1], &source[2])?; + let actual = workspace.inject(context, shape, inputs_of(source))?; check(context.allocated_bytes() == charged && !workspace.is_failed())?; let observed = products(workspace, shape)?; same_products(&observed, &expected, source)?; @@ -121,7 +126,7 @@ fn refuses_without_change( ) -> Result<()> { let previous = products(workspace, shape)?; let charged = context.allocated_bytes(); - let refusal = workspace.inject(context, shape, &source[0], &source[1], &source[2]); + let refusal = workspace.inject(context, shape, inputs_of(source)); check(refusal.err() == Some(expected))?; check(products(workspace, shape)? == previous && context.allocated_bytes() == charged && !workspace.is_failed()) } @@ -181,7 +186,7 @@ fn foreign_and_overflow( ) -> Result<()> { let previous = products(workspace, shape)?; let source = inputs(shape.tokens(), 0); - let refusal = workspace.inject(foreign, shape, &source[0], &source[1], &source[2]); + let refusal = workspace.inject(foreign, shape, inputs_of(&source)); check(refusal.err() == Some(Error::ContextMismatch))?; check(products(workspace, shape)? == previous && !workspace.is_failed())?; tally.guards += 1; diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs index 810f0317..ad7aab85 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread.rs @@ -5,7 +5,7 @@ use super::*; #[path = "impl_grmicrobatchread/impl_grmicrobatchread_2.rs"] mod impl_grmicrobatchread_2; -#[path = "impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs"] -mod impl_grmicrobatchread_2_2; #[path = "impl_grmicrobatchread/impl_grmicrobatchread_3.rs"] mod impl_grmicrobatchread_3; +#[path = "impl_grmicrobatchread/micro_stage_launch.rs"] +mod micro_stage_launch; diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/micro_stage_launch.rs similarity index 95% rename from crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs rename to crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/micro_stage_launch.rs index 6a3db58d..d564772b 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/micro_stage_launch.rs @@ -3,6 +3,13 @@ #[allow(unused_imports)] use super::*; +/// The six registered GR kernels and the finite-scan function of one micro-batch launch. +#[derive(Clone, Copy)] +struct MicroKernels<'a> { + kernels: &'a [FixedKernel], + finite: ffi::FunctionHandle, +} + impl<'ctx> GrMicrobatchRead<'ctx> { // Seven separate actual status words per row preserve complete ordered // Norm/Down/Silu/Up/products/mixed/inject refusal arbitration. The reused @@ -149,13 +156,14 @@ impl<'ctx> GrMicrobatchRead<'ctx> { mut commands: Result<()>, ) -> (Result<()>, usize) { let mut completed_scans = 0usize; + let launch = MicroKernels { kernels, finite }; for (row, row_args) in arguments.iter_mut().enumerate() { for stage in 0..6 { if commands.is_err() { break; } let args = (&mut row_args[stage], &mut *scans); - commands = self.micro_stage(kernels, finite, (row, stage), args, &mut completed_scans); + commands = self.micro_stage(launch, (row, stage), args, &mut completed_scans); } if commands.is_err() { break; @@ -167,12 +175,12 @@ impl<'ctx> GrMicrobatchRead<'ctx> { /// One kernel of a row and its finite scan (the products stage carries a second scan). fn micro_stage( &self, - kernels: &[FixedKernel], - finite: ffi::FunctionHandle, + launch: MicroKernels<'_>, (row, stage): (usize, usize), (args, scans): (&mut Arguments, &mut [ffi::MmqResidentArguments]), completed_scans: &mut usize, ) -> Result<()> { + let MicroKernels { kernels, finite } = launch; let mut commands = self.context.driver.api.launch_qwen(kernels[stage].function, OPS[stage], args); if commands.is_ok() { let scan_stage = if stage == 5 { 6 } else { stage }; diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs index 782ce8a6..0dbf7d85 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch.rs @@ -3,9 +3,9 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_grnativebatch/impl_grnativebatch_2.rs"] -mod impl_grnativebatch_2; -#[path = "impl_grnativebatch/impl_grnativebatch_2_2.rs"] -mod impl_grnativebatch_2_2; -#[path = "impl_grnativebatch/impl_grnativebatch_3.rs"] -mod impl_grnativebatch_3; +#[path = "impl_grnativebatch/native_command_drain.rs"] +mod native_command_drain; +#[path = "impl_grnativebatch/native_gemm_launch.rs"] +mod native_gemm_launch; +#[path = "impl_grnativebatch/native_inject.rs"] +mod native_inject; diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_command_drain.rs similarity index 92% rename from crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs rename to crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_command_drain.rs index 37935401..ec2b4216 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_command_drain.rs @@ -1,20 +1,27 @@ //! Moved out of the parent module by STRA-338: impl GrNativeBatch (2). +use super::native_gemm_launch::GemmRoles; #[allow(unused_imports)] use super::*; +/// The retained host ABI and staging of one drain: the eligible stages, the zeroed status words, the kernel +/// arguments and the status readback. +pub(in super::super) struct NativeDrain { + pub(in super::super) eligible: [bool; 8], + pub(in super::super) zero: Vec, + pub(in super::super) arguments: Vec, + pub(in super::super) readback: Vec, +} + impl<'ctx> GrNativeBatch<'ctx> { - #[allow(clippy::too_many_arguments)] // One complete retained command/drain ownership set. pub(in super::super) fn finish( &mut self, blas: &Blas, commands: Result<()>, - eligible: [bool; 8], - zero: Vec, - arguments: Vec, - mut readback: Vec, + drain: NativeDrain, guard: CurrentGuard<'_, 'ctx>, ) -> Result<()> { + let NativeDrain { eligible, zero, arguments, mut readback } = drain; let sync = blas.synchronize(); let status = self.native_status(sync.is_ok(), &mut readback); let pop = guard.finish(); @@ -111,7 +118,7 @@ impl<'ctx> GrNativeBatch<'ctx> { let guard = context.enter()?; let mut eligible = [false; 8]; let commands = self.native_commands(blas, (w, flags, scalars), (&zero, &mut args, &mut eligible)); - self.finish(blas, commands, eligible, zero, args, readback, guard)?; + self.finish(blas, commands, NativeDrain { eligible, zero, arguments: args, readback }, guard)?; self.native_values() } @@ -272,7 +279,6 @@ impl<'ctx> GrNativeBatch<'ctx> { (w, flags, scalars): ([ffi::BufferHandle; 4], ffi::BufferHandle, &[f32; 3]), (zero, args, eligible): (&[u8], &mut [KernelArguments], &mut [bool; 8]), ) -> Result<()> { - let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]); self.context.driver.api.copy_from(flags, zero)?; // The private vendor stream is NON_BLOCKING: drain all actual // legacy uploads/reset before any stream consumer is enqueued. @@ -287,7 +293,7 @@ impl<'ctx> GrNativeBatch<'ctx> { )?; self.launch(blas, 5, self.tokens * 10240, &mut args[1])?; eligible[0] = true; - self.gemm(blas, 2, 3, w[1], 4, 320, 10240, alpha, beta0, beta1)?; + self.gemm(blas, GemmRoles { input: 2, low: 3, weight: w[1], output: 4, n: 320, k: 10240 }, scalars)?; self.launch(blas, 4, self.tokens * 320, &mut args[2])?; eligible[1] = true; self.launch(blas, 1, self.tokens * 320, &mut args[3])?; @@ -303,12 +309,11 @@ impl<'ctx> GrNativeBatch<'ctx> { (w, scalars): ([ffi::BufferHandle; 4], &[f32; 3]), (args, eligible): (&mut [KernelArguments], &mut [bool; 8]), ) -> Result<()> { - let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]); - self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?; + self.gemm(blas, GemmRoles { input: 5, low: 6, weight: w[2], output: 7, n: 10240, k: 320 }, scalars)?; self.launch(blas, 4, self.tokens * 10240, &mut args[5])?; eligible[3] = true; // Literal Original executes inject GEMM BEFORE gr_mix_r. - self.gemm(blas, 2, 3, w[3], 12, 4, 10240, alpha, beta0, beta1)?; + self.gemm(blas, GemmRoles { input: 2, low: 3, weight: w[3], output: 12, n: 4, k: 10240 }, scalars)?; self.launch(blas, 4, self.tokens * 4, &mut args[6])?; eligible[6] = true; self.launch(blas, 2, self.tokens * 2560, &mut args[7])?; diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_gemm_launch.rs similarity index 90% rename from crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs rename to crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_gemm_launch.rs index 89e77ef8..8583469e 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_gemm_launch.rs @@ -3,6 +3,17 @@ #[allow(unused_imports)] use super::*; +/// The buffer slots, weight and `n` x `k` shape of one Original GEMM. +#[derive(Clone, Copy)] +pub(in super::super) struct GemmRoles { + pub(in super::super) input: usize, + pub(in super::super) low: usize, + pub(in super::super) weight: ffi::BufferHandle, + pub(in super::super) output: usize, + pub(in super::super) n: i32, + pub(in super::super) k: i32, +} + impl<'ctx> GrNativeBatch<'ctx> { pub fn prompt_device_bytes(tokens: usize) -> Result { if !(1..=8192).contains(&tokens) { @@ -184,20 +195,11 @@ impl<'ctx> GrNativeBatch<'ctx> { let stream = blas.stream(); module.launch(index, count.div_ceil(256) as u32, 256, stream, args) } - #[allow(clippy::too_many_arguments)] // Fixed Original GEMM roles and owned alpha/beta ABI. - pub(in super::super) fn gemm( - &self, - blas: &Blas, - input: usize, - low: usize, - weight: ffi::BufferHandle, - output: usize, - n: i32, - k: i32, - alpha: &f32, - beta0: &f32, - beta1: &f32, - ) -> Result<()> { + /// The Original GEMM over the high image (and the low image for `HighAndLow`); `scalars` is the owned + /// `[alpha, beta0, beta1]` ABI. + pub(in super::super) fn gemm(&self, blas: &Blas, roles: GemmRoles, scalars: &[f32; 3]) -> Result<()> { + let GemmRoles { input, low, weight, output, n, k } = roles; + let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]); blas.gemm_bf16(self.handle(input)?, weight, self.handle(output)?, self.tokens as i32, n, k, alpha, beta0)?; if self.profile == GrNativeProfile::HighAndLow { blas.gemm_bf16(self.handle(low)?, weight, self.handle(output)?, self.tokens as i32, n, k, alpha, beta1)?; diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_inject.rs similarity index 90% rename from crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs rename to crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_inject.rs index 156d4cbf..f2053e26 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_inject.rs @@ -1,8 +1,16 @@ //! Moved out of the parent module by STRA-338: impl GrNativeBatch (3). +use super::native_command_drain::NativeDrain; #[allow(unused_imports)] use super::*; +/// The status words of one command list: their device handle and the zero image that resets them. +#[derive(Clone, Copy)] +struct StatusReset<'a> { + flags: ffi::BufferHandle, + zero: &'a [u8], +} + impl<'ctx> GrNativeBatch<'ctx> { pub fn inject(&mut self, blocks: &[f32], workspace: &mut NativeBatchWorkspace<'ctx>) -> Result> { let blas = self.check_inject(blocks, workspace)?; @@ -14,12 +22,12 @@ impl<'ctx> GrNativeBatch<'ctx> { let context = self.context; let guard = context.enter()?; let mut eligible = [false; 8]; - let commands = self.inject_commands(blas, flags, &zero, &mut args, &mut eligible); + let commands = self.inject_commands(blas, StatusReset { flags, zero: &zero }, &mut args, &mut eligible); // Original writes the real R bank in place. Any attempted failure // retires this bank phase; no retry can add the same block twice. // Mere completed numerical refusal does not poison the Context. self.phase = 2; - self.finish(blas, commands, eligible, zero, args, readback, guard)?; + self.finish(blas, commands, NativeDrain { eligible, zero, arguments: args, readback }, guard)?; self.take_injected() } fn check_inject<'w>(&self, blocks: &[f32], workspace: &'w NativeBatchWorkspace<'ctx>) -> Result<&'w Blas> { @@ -58,11 +66,11 @@ impl<'ctx> GrNativeBatch<'ctx> { fn inject_commands( &self, blas: &Blas, - flags: ffi::BufferHandle, - zero: &[u8], + reset: StatusReset<'_>, args: &mut [KernelArguments], eligible: &mut [bool; 8], ) -> Result<()> { + let StatusReset { flags, zero } = reset; self.context.driver.api.copy_from(flags, zero)?; // The private vendor stream is NON_BLOCKING: drain all actual // legacy uploads/reset before any stream consumer is enqueued. diff --git a/crates/cuda-driver/src/grouped_down_columns_gpu.rs b/crates/cuda-driver/src/grouped_down_columns_gpu.rs index 5ecb234a..743afb2c 100644 --- a/crates/cuda-driver/src/grouped_down_columns_gpu.rs +++ b/crates/cuda-driver/src/grouped_down_columns_gpu.rs @@ -127,7 +127,7 @@ fn grouped_down( let mut column = context.allocate(10240).unwrap(); matrix.copy_from(literal).unwrap(); let charge = context.allocated_bytes(); - context.project_routed_down_columns(&matrix, hidden, &mut output, total, format).unwrap(); + context.project_routed_down_columns(&matrix, hidden, &mut output, DownColumns { total, format }).unwrap(); assert_eq!(context.allocated_bytes(), charge); let mut observed = vec![0; total * 10240]; output.copy_to(&mut observed).unwrap(); @@ -204,7 +204,7 @@ impl<'c> Refusals<'c> { } fn down(&mut self, context: &Context<'_>, total: usize, format: RoutedFormat) -> Result<()> { - context.project_routed_down_columns(&self.matrix, &self.input, &mut self.output, total, format) + context.project_routed_down_columns(&self.matrix, &self.input, &mut self.output, DownColumns { total, format }) } fn refuse_shapes(&mut self, device: &Device<'_>, context: &Context<'_>) { @@ -220,7 +220,12 @@ impl<'c> Refusals<'c> { ); let short = context.allocate(2556).unwrap(); assert_eq!( - context.project_routed_down_columns(&self.matrix, &short, &mut self.output, 1, RoutedFormat::IQ4_NL), + context.project_routed_down_columns( + &self.matrix, + &short, + &mut self.output, + DownColumns { total: 1, format: RoutedFormat::IQ4_NL } + ), Err(Error::InvalidProjectionShape) ); short.release().unwrap(); @@ -235,8 +240,7 @@ impl<'c> Refusals<'c> { &self.matrix, &foreign_input, &mut self.output, - 1, - RoutedFormat::IQ4_NL + DownColumns { total: 1, format: RoutedFormat::IQ4_NL } ), Err(Error::ContextMismatch) ); @@ -304,7 +308,10 @@ fn budget_failure(device: &Device<'_>, rig: &Refusals<'_>) { h.copy_from(&rig.valid).unwrap(); o.copy_from(&rig.sentinel).unwrap(); let charge = small.allocated_bytes(); - assert_eq!(small.project_routed_down_columns(&w, &h, &mut o, 1, RoutedFormat::IQ4_NL), Err(Error::BudgetExceeded)); + assert_eq!( + small.project_routed_down_columns(&w, &h, &mut o, DownColumns { total: 1, format: RoutedFormat::IQ4_NL }), + Err(Error::BudgetExceeded) + ); assert_eq!(small.allocated_bytes(), charge); let mut after = vec![0; 10240]; o.copy_to(&mut after).unwrap(); diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs b/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs index 5bdb747f..00426a35 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs @@ -102,10 +102,10 @@ fn original_first_gu21_gu23_full_products_refusals_reset_and_cleanup() { ); } -#[path = "grouped_gu21_gu23_gpu/numeric_fn.rs"] -mod numeric_fn; +#[path = "grouped_gu21_gu23_gpu/grouped_numeric_run.rs"] +mod grouped_numeric_run; #[allow(unused_imports)] -use numeric_fn::numeric; +use grouped_numeric_run::numeric; #[path = "grouped_gu21_gu23_gpu/guards_fn.rs"] mod guards_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_gpu/numeric_fn.rs b/crates/cuda-driver/src/grouped_gu21_gu23_gpu/grouped_numeric_run.rs similarity index 91% rename from crates/cuda-driver/src/grouped_gu21_gu23_gpu/numeric_fn.rs rename to crates/cuda-driver/src/grouped_gu21_gu23_gpu/grouped_numeric_run.rs index 69b09782..2542f779 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_gpu/numeric_fn.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_gpu/grouped_numeric_run.rs @@ -124,6 +124,15 @@ struct Grouped<'a> { down: DeviceBuffer<'a>, } +/// What the repeat run compares against: the prepared inputs and their sources, the first gate product and the +/// transient charge. +struct RepeatBaseline<'a> { + refs: &'a [&'a RoutedGateUpQ8<'a>], + inputs: &'a [DeviceBuffer<'a>], + first: &'a [u8], + charge: usize, +} + impl<'a> Grouped<'a> { fn new(context: &'a Context<'_>, total: usize, zero: bool) -> Result { let gate = upload(context, &vec![0xa5; total * 2560])?; @@ -148,7 +157,12 @@ impl<'a> Grouped<'a> { actual[2] = read(&self.hidden)?; for (index, down_format) in DOWN_FORMATS.into_iter().enumerate() { let weights = &rig.down_buffers[index]; - context.project_routed_down_columns(weights, &self.hidden, &mut self.down, self.total, down_format)?; + context.project_routed_down_columns( + weights, + &self.hidden, + &mut self.down, + DownColumns { total: self.total, format: down_format }, + )?; actual[index + 3] = read(&self.down)?; } Ok(actual) @@ -159,10 +173,10 @@ impl<'a> Grouped<'a> { mut self, context: &Context<'_>, rig: &GuRig<'_>, - (refs, inputs): (&[&RoutedGateUpQ8<'_>], &[DeviceBuffer<'_>]), - (first, charge): (&[u8], usize), + repeat: RepeatBaseline<'_>, checks: &mut Vec, ) -> Result<()> { + let RepeatBaseline { refs, inputs, first, charge } = repeat; self.gate.copy_from(&vec![0x5a; self.total * 2560])?; context.project_routed_gate_up_columns(&rig.gate_weights, refs, &mut self.gate, rig.format)?; checks.push(Comparison { @@ -223,7 +237,12 @@ fn corpus_case( let mut grouped = Grouped::new(context, total, zero)?; let charge = context.allocated_bytes(); let actual = grouped.products(context, rig, &refs)?; - grouped.verify_and_release(context, rig, (&refs, &inputs), (&actual[0], charge), checks)?; + grouped.verify_and_release( + context, + rig, + RepeatBaseline { refs: &refs, inputs: &inputs, first: &actual[0], charge }, + checks, + )?; drop(refs); close_owners(prepared)?; release_inputs(inputs)?; diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs index d9b2b6ec..a3be9263 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs @@ -51,20 +51,20 @@ fn original_first_gu21_gu23_nc4_full_products_tails_refusals_reset_and_cleanup() ); } -#[path = "grouped_gu21_gu23_nc4_gpu/upload_fn.rs"] -mod upload_fn; +#[path = "grouped_gu21_gu23_nc4_gpu/grouped_upload_run.rs"] +mod grouped_upload_run; #[allow(unused_imports)] -use upload_fn::down_weights; +use grouped_upload_run::down_weights; #[allow(unused_imports)] -use upload_fn::gu_weights; +use grouped_upload_run::gu_weights; #[allow(unused_imports)] -use upload_fn::input; +use grouped_upload_run::input; #[allow(unused_imports)] -use upload_fn::numeric; +use grouped_upload_run::numeric; #[allow(unused_imports)] -use upload_fn::read; +use grouped_upload_run::read; #[allow(unused_imports)] -use upload_fn::upload; +use grouped_upload_run::upload; #[path = "grouped_gu21_gu23_nc4_gpu/guards_fn.rs"] mod guards_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/grouped_upload_run.rs similarity index 93% rename from crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs rename to crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/grouped_upload_run.rs index b4cc382f..a6dcf517 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/grouped_upload_run.rs @@ -177,6 +177,15 @@ struct Grouped<'a> { down: DeviceBuffer<'a>, } +/// What the repeat run compares against: the prepared inputs and their sources, the first gate product and the +/// transient charge. +struct RepeatBaseline<'a> { + refs: &'a [&'a RoutedGateUpQ8<'a>], + inputs: &'a [DeviceBuffer<'a>], + first: &'a [u8], + charge: usize, +} + impl<'a> Grouped<'a> { fn new(context: &'a Context<'_>, total: usize, zero: bool) -> Result { let gate = upload(context, &vec![0xa5; total * 2560])?; @@ -201,7 +210,12 @@ impl<'a> Grouped<'a> { actual[2] = read(&self.hidden)?; for (index, down_format) in DOWN_FORMATS.into_iter().enumerate() { let weights = &rig.down_buffers[index]; - context.project_routed_down_columns(weights, &self.hidden, &mut self.down, self.total, down_format)?; + context.project_routed_down_columns( + weights, + &self.hidden, + &mut self.down, + DownColumns { total: self.total, format: down_format }, + )?; actual[index + 3] = read(&self.down)?; } Ok(actual) @@ -212,10 +226,10 @@ impl<'a> Grouped<'a> { mut self, context: &Context<'_>, rig: &GuRig<'_>, - (refs, inputs): (&[&RoutedGateUpQ8<'_>], &[DeviceBuffer<'_>]), - (first, charge): (&[u8], usize), + repeat: RepeatBaseline<'_>, checks: &mut Vec, ) -> Result<()> { + let RepeatBaseline { refs, inputs, first, charge } = repeat; self.gate.copy_from(&vec![0x5a; self.total * 2560])?; context.project_routed_gate_up_columns(&rig.gate_weights, refs, &mut self.gate, rig.format)?; checks.push(Comparison { @@ -276,7 +290,12 @@ fn corpus_case( let mut grouped = Grouped::new(context, total, zero)?; let charge = context.allocated_bytes(); let actual = grouped.products(context, rig, &refs)?; - grouped.verify_and_release(context, rig, (&refs, &inputs), (&actual[0], charge), checks)?; + grouped.verify_and_release( + context, + rig, + RepeatBaseline { refs: &refs, inputs: &inputs, first: &actual[0], charge }, + checks, + )?; drop(refs); close_owners(prepared)?; release_inputs(inputs)?; diff --git a/crates/cuda-driver/src/impl_context_2.rs b/crates/cuda-driver/src/impl_context_2.rs index 03e4f9ef..24f6da22 100644 --- a/crates/cuda-driver/src/impl_context_2.rs +++ b/crates/cuda-driver/src/impl_context_2.rs @@ -3,6 +3,13 @@ #[allow(unused_imports)] use super::*; +/// The row and column counts of a matrix-vector product. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MatvecDims { + pub rows: usize, + pub columns: usize, +} + impl Context<'_> { /// Compute each row's dot product in ascending column order with separate /// binary32 multiply/add rounding. All buffers are exact whole allocations; @@ -12,9 +19,9 @@ impl Context<'_> { matrix: &DeviceBuffer<'_>, vector: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, - rows: usize, - columns: usize, + dims: MatvecDims, ) -> Result<()> { + let MatvecDims { rows, columns } = dims; let (shape, handles) = self.matvec_admission([matrix, vector, output], rows, columns)?; let [matrix_handle, vector_handle, output_handle] = handles; let mut arguments = diff --git a/crates/cuda-driver/src/iq3_native_integer_mma.rs b/crates/cuda-driver/src/iq3_native_integer_mma.rs index 4789335e..a230395b 100644 --- a/crates/cuda-driver/src/iq3_native_integer_mma.rs +++ b/crates/cuda-driver/src/iq3_native_integer_mma.rs @@ -76,9 +76,7 @@ impl<'ctx> NativeInteger<'ctx> { pub(super) fn append( &self, commands: &mut Vec, - weights: ffi::BufferHandle, - packed: ffi::BufferHandle, - output: ffi::BufferHandle, + [weights, packed, output]: [ffi::BufferHandle; 3], l: Layout, ) -> Result<()> { self.check()?; diff --git a/crates/cuda-driver/src/kar_decode_levels_ffi.rs b/crates/cuda-driver/src/kar_decode_levels_ffi.rs index 988b929e..1087d0ee 100644 --- a/crates/cuda-driver/src/kar_decode_levels_ffi.rs +++ b/crates/cuda-driver/src/kar_decode_levels_ffi.rs @@ -107,7 +107,7 @@ impl Api { block: [u32; 3], arguments: &mut KarLevelsArgs, ) -> Result<()> { - self.launch_closed(function, grid, block, 0, arguments) + self.launch_closed(function, crate::closed_kernels_gpu::Geometry { grid, block, shared: 0 }, arguments) } /// The same closed launch with dynamic shared memory (`shared` bytes), for the legacy GEMV reductions. Every /// other precondition is `launch_kar_levels`'s: the facade has validated geometry, extents and aliases, and the @@ -115,11 +115,10 @@ impl Api { pub(crate) fn launch_closed( &self, function: FunctionHandle, - grid: [u32; 3], - block: [u32; 3], - shared: u32, + geometry: crate::closed_kernels_gpu::Geometry, arguments: &mut KarLevelsArgs, ) -> Result<()> { + let crate::closed_kernels_gpu::Geometry { grid, block, shared } = geometry; // SAFETY: function belongs to the current context's live module; the // facade has validated grid/block/shared size, buffer extents/aliases // and scalar geometry, and the parameter table is raw-owned until after diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu.rs b/crates/cuda-driver/src/kar_decode_levels_gpu.rs index b94bc0f5..d2164586 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu.rs @@ -42,6 +42,24 @@ struct Admitted { bytes: usize, } +/// The admitted weights window, input, output and status word of one multiply launch. +struct MultiplyOperands<'a> { + weights: &'a Admitted, + input: &'a Admitted, + output: &'a Admitted, + status: &'a Admitted, +} + +/// The device buffers of one decode-then-multiply: the staged packet, the weights window it decodes into, the input, +/// the output and the status word. +pub struct DecodeMultiplyBuffers<'a, 'b> { + pub packet: &'a DeviceBuffer<'b>, + pub weights: &'a mut DeviceBuffer<'b>, + pub input: &'a DeviceBuffer<'b>, + pub output: &'a mut DeviceBuffer<'b>, + pub status: &'a mut DeviceBuffer<'b>, +} + type Launch = (ffi::FunctionHandle, [u32; 3], [u32; 3], ffi::KarLevelsArgs); /// One expert matrix: its decode window, its multiply shape and its staged diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu/expert_mlp.rs b/crates/cuda-driver/src/kar_decode_levels_gpu/expert_mlp.rs index 9843de9c..9992f60a 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu/expert_mlp.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu/expert_mlp.rs @@ -172,12 +172,21 @@ impl<'c> KarDecodeLevels<'c> { // finishes reading it before the next decode overwrites it. Ok(vec![ self.decode_launch(a_gate_p, &a.weights, &a.status, &gate.geometry)?, - self.multiply_launch(&a.weights, &a.x, &a.gate_out, &a.status, &gate.shape)?, + self.multiply_launch( + MultiplyOperands { weights: &a.weights, input: &a.x, output: &a.gate_out, status: &a.status }, + &gate.shape, + )?, self.decode_launch(a_up_p, &a.weights, &a.status, &up.geometry)?, - self.multiply_launch(&a.weights, &a.x, &a.up_out, &a.status, &up.shape)?, + self.multiply_launch( + MultiplyOperands { weights: &a.weights, input: &a.x, output: &a.up_out, status: &a.status }, + &up.shape, + )?, swiglu, self.decode_launch(a_down_p, &a.weights, &a.status, &down.geometry)?, - self.multiply_launch(&a.weights, &a.act, &a.out, &a.status, &down.shape)?, + self.multiply_launch( + MultiplyOperands { weights: &a.weights, input: &a.act, output: &a.out, status: &a.status }, + &down.shape, + )?, ]) } diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs b/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs index 90e74ae6..dbaca68b 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs @@ -87,14 +87,8 @@ impl<'c> KarDecodeLevels<'c> { )) } - pub(super) fn multiply_launch( - &self, - weights: &Admitted, - input: &Admitted, - output: &Admitted, - status: &Admitted, - m: &MultiplyGeometry, - ) -> Result { + pub(super) fn multiply_launch(&self, operands: MultiplyOperands<'_>, m: &MultiplyGeometry) -> Result { + let MultiplyOperands { weights, input, output, status } = operands; Ok(( self.kernels.multiply, [m.rows, m.tokens, 1], @@ -126,17 +120,13 @@ impl<'c> KarDecodeLevels<'c> { /// Decode a whole-row window into `weights` and multiply it by `input` /// (`[tokens][columns]`) into `output` (`[tokens][rows]`), both kernels /// under one drain. `decode.count` must equal `columns * rows`. - #[allow(clippy::too_many_arguments)] // closed ABI operands, not caller-selected geometry pub fn decode_multiply( &self, - packet: &DeviceBuffer<'_>, - weights: &mut DeviceBuffer<'_>, - input: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - status: &mut DeviceBuffer<'_>, + buffers: DecodeMultiplyBuffers<'_, '_>, decode: &DecodeGeometry, multiply: &MultiplyGeometry, ) -> Result<()> { + let DecodeMultiplyBuffers { packet, weights, input, output, status } = buffers; Self::check_window(decode, multiply)?; let packet = self.admit(packet, decode.packet_len(), false)?; let weights = self.admit(weights, multiply.weights_len(), false)?; @@ -145,7 +135,10 @@ impl<'c> KarDecodeLevels<'c> { let status = self.admit(status, STATUS_BYTES, true)?; Self::disjoint(&[&packet, &weights, &input, &output, &status])?; let first = self.decode_launch(&packet, &weights, &status, decode)?; - let second = self.multiply_launch(&weights, &input, &output, &status, multiply)?; + let second = self.multiply_launch( + MultiplyOperands { weights: &weights, input: &input, output: &output, status: &status }, + multiply, + )?; self.launch_all(vec![first, second]) } @@ -270,15 +263,14 @@ impl<'c> KarDecodeLevels<'c> { decode: &DecodeGeometry, multiply: &MultiplyGeometry, ) -> Result<()> { - self.decode_multiply( - &buffers.packet, - &mut buffers.weights, - &buffers.input, - &mut buffers.output, - &mut buffers.status, - decode, - multiply, - ) + let operands = DecodeMultiplyBuffers { + packet: &buffers.packet, + weights: &mut buffers.weights, + input: &buffers.input, + output: &mut buffers.output, + status: &mut buffers.status, + }; + self.decode_multiply(operands, decode, multiply) } } diff --git a/crates/cuda-driver/src/kv_stream_gpu.rs b/crates/cuda-driver/src/kv_stream_gpu.rs index 7412e963..9043103e 100644 --- a/crates/cuda-driver/src/kv_stream_gpu.rs +++ b/crates/cuda-driver/src/kv_stream_gpu.rs @@ -48,8 +48,6 @@ mod stream_proof; #[allow(unused_imports)] use impl_rng::addr; #[allow(unused_imports)] -use impl_rng::expected; -#[allow(unused_imports)] use impl_rng::f32s; #[allow(unused_imports)] use impl_rng::group; @@ -63,3 +61,5 @@ use impl_rng::load; use impl_rng::selection; #[allow(unused_imports)] use impl_rng::upload; +#[allow(unused_imports)] +use impl_rng::{ImageLayout, KernelShape, expected}; diff --git a/crates/cuda-driver/src/kv_stream_gpu/append_proof.rs b/crates/cuda-driver/src/kv_stream_gpu/append_proof.rs index 7247e79a..d9b2ed31 100644 --- a/crates/cuda-driver/src/kv_stream_gpu/append_proof.rs +++ b/crates/cuda-driver/src/kv_stream_gpu/append_proof.rs @@ -44,7 +44,17 @@ impl Case { k.extend_from_slice(&group(rng, r)); v.extend_from_slice(&group(rng, r + 3)); } - let (ident, slots) = expected(&k, &v, POS0, ROWS, &table, IDENTITY_PAGES, RESIDENT_PAGES, 0x5a); + let (ident, slots) = expected( + &k, + &v, + (POS0, ROWS), + ImageLayout { + table: &table, + identity_pages: IDENTITY_PAGES, + resident_pages: RESIDENT_PAGES, + sentinel: 0x5a, + }, + ); Self { k, v, table, ident, slots } } @@ -86,7 +96,7 @@ fn prompt_append<'c>(c: &'c Context<'c>, w: &mut NativeBatchWorkspace<'c>, case: let mut args = vec![Arg::U64(addr(&kb)), Arg::U64(addr(&vb)), Arg::I64(POS0 as i64), Arg::U64(addr(&tb)), Arg::I64(4)]; args.extend(res.iter().chain(&stage).chain(&host).map(|b| Arg::U64(addr(b)))); - launch(c, &m, w, 1, [ROWS as u32, 2, 8], 64, args).expect("prompt append"); + launch(c, &m, w, KernelShape { index: 1, grid: [ROWS as u32, 2, 8], block: 64 }, args).expect("prompt append"); let compared = case.compare_prompt(&res, &stage, &host); close_module(c, m); for b in res.into_iter().chain(stage).chain(host).chain([kb, vb, tb]) { @@ -118,7 +128,7 @@ fn window_row(c: &Context<'_>, w: &mut NativeBatchWorkspace<'_>, m: &Module, row Arg::I32(4), ]); args.extend(b.host.iter().map(|x| Arg::U64(addr(x)))); - launch(c, m, w, 0, [2, 4, 2], 64, args).expect("window append"); + launch(c, m, w, KernelShape { index: 0, grid: [2, 4, 2], block: 64 }, args).expect("window append"); } /// 2. verify window (`mtp_original_append`, one launch per row at step[kStepPos]): resident slots + host copy diff --git a/crates/cuda-driver/src/kv_stream_gpu/impl_rng.rs b/crates/cuda-driver/src/kv_stream_gpu/impl_rng.rs index 18ba3b84..4ae9784d 100644 --- a/crates/cuda-driver/src/kv_stream_gpu/impl_rng.rs +++ b/crates/cuda-driver/src/kv_stream_gpu/impl_rng.rs @@ -34,15 +34,21 @@ pub(super) fn f32s(xs: &[f32]) -> Vec { pub(super) fn i32s(xs: &[i32]) -> Vec { xs.iter().flat_map(|x| x.to_le_bytes()).collect() } +/// One kernel of a module: its entry index and its grid and block shape. +#[derive(Clone, Copy)] +pub(super) struct KernelShape { + pub(super) index: usize, + pub(super) grid: [u32; 3], + pub(super) block: u32, +} pub(super) fn launch( c: &Context<'_>, m: &Module, w: &mut NativeBatchWorkspace<'_>, - index: usize, - grid: [u32; 3], - block: u32, + shape: KernelShape, args: Vec, ) -> Result<()> { + let KernelShape { index, grid, block } = shape; let mut a = Arguments::new(args)?; let g = c.enter()?; let op = m.launch(index, grid, block, 0, w.blas()?.stream(), &mut a); @@ -82,18 +88,25 @@ pub(super) fn group(rng: &mut Rng, kind: usize) -> [f32; 64] { x } +/// The page layout the expected images are built over: the resident `table`, the page counts of the identity and +/// the slot image and the `sentinel` byte everything else holds. +#[derive(Clone, Copy)] +pub(super) struct ImageLayout<'a> { + pub(super) table: &'a [i32], + pub(super) identity_pages: usize, + pub(super) resident_pages: usize, + pub(super) sentinel: u8, +} + /// Expected images after appending rows `pos0..pos0 + t` of `k`/`v` (`[t][2 heads][256]`): identity layout /// (host copy and stage) and slot layout through `table` (resident pool). `sentinel` everywhere else. pub(super) fn expected( k: &[f32], v: &[f32], - pos0: usize, - t: usize, - table: &[i32], - identity_pages: usize, - resident_pages: usize, - sentinel: u8, + (pos0, t): (usize, usize), + layout: ImageLayout<'_>, ) -> ([Vec; 4], [Vec; 4]) { + let ImageLayout { table, identity_pages, resident_pages, sentinel } = layout; let mut ident = PAGE.map(|n| vec![sentinel; n * identity_pages]); let mut slots = PAGE.map(|n| vec![sentinel; n * resident_pages]); for r in 0..t { diff --git a/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs b/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs index a7586298..54378196 100644 --- a/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs +++ b/crates/cuda-driver/src/kv_stream_gpu/stream_proof.rs @@ -147,9 +147,17 @@ impl<'c> Attention<'c> { fn attend(&self, w: &mut NativeBatchWorkspace<'_>, pools: [u64; 4], table: u64, n: usize) -> Vec { let args = self.chunk_args(pools, table); - launch(self.c, &self.module, w, 0, [self.chunks as u32, 2, n as u32], 256, args).expect("attention chunks"); + launch( + self.c, + &self.module, + w, + KernelShape { index: 0, grid: [self.chunks as u32, 2, n as u32], block: 256 }, + args, + ) + .expect("attention chunks"); let merge = self.merge_args(); - launch(self.c, &self.module, w, 1, [HEADS as u32, n as u32, 1], 256, merge).expect("attention merge"); + launch(self.c, &self.module, w, KernelShape { index: 1, grid: [HEADS as u32, n as u32, 1], block: 256 }, merge) + .expect("attention merge"); self.out.copy_to_owned(3 * HEADS * HD * 4).unwrap()[..n * HEADS * HD * 4].to_vec() } } diff --git a/crates/cuda-driver/src/mmq.rs b/crates/cuda-driver/src/mmq.rs index d92c9b8a..42469b50 100644 --- a/crates/cuda-driver/src/mmq.rs +++ b/crates/cuda-driver/src/mmq.rs @@ -4,6 +4,13 @@ use super::*; mod original_weights; use std::ffi::CStr; +/// One projection request: the numerical profile and the token count. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MmqRequest { + pub profile: MmqProfile, + pub tokens: u32, +} + /// Explicit numerical profiles; none is selected by serving. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MmqProfile { diff --git a/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs b/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs index 47b984b8..ae0ae310 100644 --- a/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs +++ b/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs @@ -75,8 +75,7 @@ impl<'ctx> MmqWeights<'ctx> { NativeWeights::Dual(self), hidden, out, - tokens as usize, - self.native_format(), + DownColumns { total: tokens as usize, format: self.native_format() }, ) } diff --git a/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs b/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs index a6705faf..d0a7b08e 100644 --- a/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs +++ b/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs @@ -3,6 +3,17 @@ #[allow(unused_imports)] use super::*; +/// One observed projection: the weights and output, the layout, the grid (with the stream-k fixup flag) and the +/// admitted `[weights, input, output]` handles. +struct ObservedRun<'a, 'b> { + weights: &'a MmqWeights<'b>, + output: &'a DeviceBuffer<'b>, + layout: Layout, + grid: u32, + fixup: bool, + handles: [ffi::BufferHandle; 3], +} + impl<'ctx> MmqExperiment<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { if context.is_poisoned() { @@ -77,24 +88,23 @@ impl<'ctx> MmqExperiment<'ctx> { /// Original D4 quantizer then original int8 MMA. Full finite readbacks retained. pub fn project( &self, - profile: MmqProfile, + request: MmqRequest, weights: &MmqWeights<'_>, input: &DeviceBuffer<'_>, - tokens: u32, output: &mut DeviceBuffer<'_>, ) -> Result> { - let (values, packed) = self.project_observed(profile, weights, input, tokens, output)?; + let (values, packed) = self.project_observed(request, weights, input, output)?; drop(packed); Ok(values) } pub(super) fn project_observed( &self, - profile: MmqProfile, + request: MmqRequest, weights: &MmqWeights<'_>, input: &DeviceBuffer<'_>, - tokens: u32, output: &mut DeviceBuffer<'_>, ) -> Result { + let MmqRequest { profile, tokens } = request; self.check()?; let l = weights.format.adaptive_layout(tokens, profile)?; let hs = self.observed_admit(weights, input, output, &l)?; @@ -103,7 +113,8 @@ impl<'ctx> MmqExperiment<'ctx> { let fixup = tiles % grid != 0; let mut temporary = None; let mut packed = self.context.allocate(l.packed)?; - let result = self.observed_run(weights, output, l, (grid, fixup), hs, (&mut packed, &mut temporary)); + let run = ObservedRun { weights, output, layout: l, grid, fixup, handles: hs }; + let result = self.observed_run(run, (&mut packed, &mut temporary)); if matches!(&result, Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext)) { self.context.poisoned.set(true) } @@ -192,13 +203,10 @@ impl<'ctx> MmqExperiment<'ctx> { fn observed_run( &self, - weights: &MmqWeights<'_>, - output: &DeviceBuffer<'_>, - l: Layout, - (grid, fixup): (u32, bool), - hs: [ffi::BufferHandle; 3], + run: ObservedRun<'_, '_>, (packed, temporary): (&mut DeviceBuffer<'ctx>, &mut Option>), ) -> Result { + let ObservedRun { weights, output, layout: l, grid, fixup, handles: hs } = run; let [wh, ih, oh] = hs; let ph = self.observed_prepare_packed(l, hs, packed)?; let q = self.observed_quantize(l, (ih, ph), packed)?; diff --git a/crates/cuda-driver/src/mmq_ffi.rs b/crates/cuda-driver/src/mmq_ffi.rs index 4506680d..0da500cb 100644 --- a/crates/cuda-driver/src/mmq_ffi.rs +++ b/crates/cuda-driver/src/mmq_ffi.rs @@ -24,6 +24,36 @@ pub(crate) struct MmqOriginalSwigluArguments(Owned); pub(crate) struct MmqOriginalGatherArguments(Owned); +/// The buffers of one grouped Original projection: weights, packed activation, output and the optional fixup scratch. +#[derive(Clone, Copy)] +pub(crate) struct MmqGroupBuffers { + pub(crate) weights: BufferHandle, + pub(crate) packed: BufferHandle, + pub(crate) output: BufferHandle, + pub(crate) tmp: Option, +} +/// The row ids and the per-expert bounds that route rows to experts. +#[derive(Clone, Copy)] +pub(crate) struct MmqGroupRouting { + pub(crate) ids: BufferHandle, + pub(crate) bounds: BufferHandle, +} +/// The grouped geometry shared by the producer and the fixup: experts, the largest per-expert row count and the tile +/// width. +#[derive(Clone, Copy)] +pub(crate) struct MmqGroupShape { + pub(crate) experts: u32, + pub(crate) max_rows: u32, + pub(crate) width: u32, +} +/// The element counts of one gather: the total rows, the group size and the block count. +#[derive(Clone, Copy)] +pub(crate) struct MmqGatherShape { + pub(crate) total: u32, + pub(crate) group: u32, + pub(crate) blocks: u32, +} + #[path = "mmq_ffi/impl_owned.rs"] mod impl_owned; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs b/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs index 65935caa..3d7c8302 100644 --- a/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs +++ b/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs @@ -56,14 +56,8 @@ impl MmqResidentArguments { } Self(owner) } - pub(crate) fn gather( - source: BufferHandle, - ids: BufferHandle, - out: BufferHandle, - total: u32, - group: u32, - blocks: u32, - ) -> Self { + pub(crate) fn gather(source: BufferHandle, ids: BufferHandle, out: BufferHandle, shape: MmqGatherShape) -> Self { + let MmqGatherShape { total, group, blocks } = shape; let owner = Owned::new(); // SAFETY: fixed six-param ABI and closed checked row/block layout, stable Box. unsafe { @@ -132,19 +126,15 @@ impl MmqQuantArguments { } } impl MmqArguments { - #[allow(clippy::too_many_arguments)] pub(crate) fn original_group( - weights: BufferHandle, - packed: BufferHandle, - ids: BufferHandle, - bounds: BufferHandle, - output: BufferHandle, - tmp: Option, + buffers: MmqGroupBuffers, + routing: MmqGroupRouting, l: Layout, - experts: u32, - max_rows: u32, - width: u32, + shape: MmqGroupShape, ) -> Self { + let MmqGroupBuffers { weights, packed, output, tmp } = buffers; + let MmqGroupRouting { ids, bounds } = routing; + let MmqGroupShape { experts, max_rows, width } = shape; let owner = Self::new(weights, packed, output, tmp, l); // SAFETY: literal Original Product -> mmq_args, channel expert stride // includes Gate followed by Up; no per-expert padding. Stable exact ABI. @@ -164,17 +154,15 @@ impl MmqArguments { } } impl MmqFixupArguments { - #[allow(clippy::too_many_arguments)] pub(crate) fn original_group( - ids: BufferHandle, - bounds: BufferHandle, + routing: MmqGroupRouting, output: BufferHandle, tmp: BufferHandle, l: Layout, - experts: u32, - max_rows: u32, - width: u32, + shape: MmqGroupShape, ) -> Self { + let MmqGroupRouting { ids, bounds } = routing; + let MmqGroupShape { experts, max_rows, width } = shape; let owner = Self::new(output, tmp, l); // SAFETY: same ids/bounds, channel count and ntx as the exact preceding // Original stream-K producer. Both destination channel/sample strides0. diff --git a/crates/cuda-driver/src/mmq_native_activation.rs b/crates/cuda-driver/src/mmq_native_activation.rs index 639d4412..8334cd46 100644 --- a/crates/cuda-driver/src/mmq_native_activation.rs +++ b/crates/cuda-driver/src/mmq_native_activation.rs @@ -69,9 +69,7 @@ impl<'ctx> NativeActivation<'ctx> { pub(super) fn append( &self, commands: &mut Vec, - input: ffi::BufferHandle, - packed: ffi::BufferHandle, - status: ffi::BufferHandle, + [input, packed, status]: [ffi::BufferHandle; 3], l: Layout, ) -> Result<()> { self.check()?; diff --git a/crates/cuda-driver/src/mmq_numeric_gpu.rs b/crates/cuda-driver/src/mmq_numeric_gpu.rs index 434a49ac..5f66a67c 100644 --- a/crates/cuda-driver/src/mmq_numeric_gpu.rs +++ b/crates/cuda-driver/src/mmq_numeric_gpu.rs @@ -67,7 +67,10 @@ impl Rig<'_, '_> { ) { output.copy_from(&vec![0xff; reference.len()]).unwrap(); let charge = self.context.allocated_bytes(); - let (values, q8) = self.experiment.project_observed(profile, self.weights, input, case.tokens, output).unwrap(); + let (values, q8) = self + .experiment + .project_observed(MmqRequest { profile, tokens: case.tokens }, self.weights, input, output) + .unwrap(); assert_eq!(&*q8, case.q8.as_slice(), "complete original D4Q8 bytes"); compare(&values, reference, "MMQ exact original profile"); let mut actual = vec![0; reference.len()]; @@ -134,7 +137,7 @@ fn format_inputs(receipt: &Receipt) -> Vec<(MmqFormat, (Vec, Vec))> { (20, MmqFormat::Iq4NlDown, 2560, 640, 921600, 216), (42, MmqFormat::Q2Down, 2560, 640, 460800, 108), ] - .map(|(kind, format, rows, columns, raw, tail)| (format, cases(receipt, kind, rows, columns, raw, tail))) + .map(|(kind, format, rows, columns, raw, tail)| (format, cases(receipt, (kind, rows, columns, raw, tail)))) .into() } @@ -182,7 +185,7 @@ use digest_fn::hex; use digest_fn::integer; #[allow(unused_imports)] use digest_fn::read_regular; -#[path = "mmq_numeric_gpu/cases_fn.rs"] -mod cases_fn; +#[path = "mmq_numeric_gpu/format_cases.rs"] +mod format_cases; #[allow(unused_imports)] -use cases_fn::cases; +use format_cases::cases; diff --git a/crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs b/crates/cuda-driver/src/mmq_numeric_gpu/format_cases.rs similarity index 95% rename from crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs rename to crates/cuda-driver/src/mmq_numeric_gpu/format_cases.rs index dce15eb8..bc09516d 100644 --- a/crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs +++ b/crates/cuda-driver/src/mmq_numeric_gpu/format_cases.rs @@ -6,14 +6,8 @@ use super::*; /// (kind, rows, columns, raw weight bytes, zero tail bytes) of one format. type Shape = (u32, usize, usize, usize, usize); -pub(super) fn cases( - receipt: &Receipt, - kind: u32, - rows: usize, - columns: usize, - raw: usize, - tail: usize, -) -> (Vec, Vec) { +pub(super) fn cases(receipt: &Receipt, shape: Shape) -> (Vec, Vec) { + let (kind, rows, columns, raw, tail) = shape; let weights = receipt.read(&format!("type{kind}-t4/weights.bin")); assert_eq!(weights.len(), raw); let mut cases = Vec::new(); diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream.rs b/crates/cuda-driver/src/mmq_original_chunk_stream.rs index 08698610..f9194e88 100644 --- a/crates/cuda-driver/src/mmq_original_chunk_stream.rs +++ b/crates/cuda-driver/src/mmq_original_chunk_stream.rs @@ -92,3 +92,4 @@ mod impl_core; pub(crate) use impl_core::prefetch_point; #[path = "mmq_original_chunk_stream/impl_chunkstream.rs"] mod impl_chunkstream; +pub(crate) use impl_chunkstream::CoreParts; diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs b/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs index 830540bc..678b3413 100644 --- a/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs +++ b/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs @@ -8,16 +8,16 @@ fn env_number(name: &str) -> Option { } /// Everything `Core::new` takes besides the layer bounds, the first layer and the issue depth. -struct CoreParts { - api: Api, - entries: Vec, - targets: Vec<(BufferHandle, usize)>, - copied: Vec, - used: Vec, - starts: Vec, - copy: usize, - topup: usize, - context: usize, +pub(crate) struct CoreParts { + pub(crate) api: Api, + pub(crate) entries: Vec, + pub(crate) targets: Vec<(BufferHandle, usize)>, + pub(crate) copied: Vec, + pub(crate) used: Vec, + pub(crate) starts: Vec, + pub(crate) copy: usize, + pub(crate) topup: usize, + pub(crate) context: usize, } impl Stats { @@ -66,24 +66,11 @@ impl ChunkStream { /// `targets` the ring slots; `copied`/`used` one raw event per slot (created by the caller on this Context); /// `starts` the per-slot timing events of LELEKA_PREFILL_COPY_STATS (empty without it); `context` the raw /// context token for the issuer thread. - #[allow(clippy::too_many_arguments)] - pub(in super::super) fn start( - api: Api, - copy: usize, - first: u8, - entries: Vec, - targets: Vec<(BufferHandle, usize)>, - copied: Vec, - used: Vec, - starts: Vec, - topup: usize, - context: usize, - ) -> Result { - Self::check_shapes(first, (&targets, &copied, &used, &starts))?; - Self::check_entries(first, &entries)?; - let layer_start = Self::layer_starts(&entries); - let depth = Self::issue_depth(targets.len()); - let parts = CoreParts { api, entries, targets, copied, used, starts, copy, topup, context }; + pub(in super::super) fn start(first: u8, parts: CoreParts) -> Result { + Self::check_shapes(first, (&parts.targets, &parts.copied, &parts.used, &parts.starts))?; + Self::check_entries(first, &parts.entries)?; + let layer_start = Self::layer_starts(&parts.entries); + let depth = Self::issue_depth(parts.targets.len()); let core = Arc::new(Core::new(parts, layer_start, (first, depth))); let thread = Self::spawn_issuer(&core, depth)?; Ok(Self { core, thread }) diff --git a/crates/cuda-driver/src/mmq_original_group.rs b/crates/cuda-driver/src/mmq_original_group.rs index 0491238b..d998ed6f 100644 --- a/crates/cuda-driver/src/mmq_original_group.rs +++ b/crates/cuda-driver/src/mmq_original_group.rs @@ -78,6 +78,42 @@ pub struct OriginalMmqLayer<'lease, 'ctx> { formats: Option<[MmqFormat; 3]>, completed: bool, } +/// Which projection to run: the format, whether it is the Down projection, and the tile width. +#[derive(Clone, Copy)] +struct ProjectSpec { + format: MmqFormat, + down: bool, + width: u32, +} +/// The workspace slots one projection reads and writes: the weights, the packed activation and the output. +#[derive(Clone, Copy)] +struct ProjectSlots { + weights: usize, + packed: usize, + out: usize, +} +/// One finite scan: the scanned buffer, its element count, whether it is a Q8 image, and the refusal label. +#[derive(Clone, Copy)] +struct FiniteScan { + source: ffi::BufferHandle, + amount: usize, + q8: bool, + label: &'static str, +} +/// The workspace slots of one quantization: the input, the packed output and the optional row ids. +#[derive(Clone, Copy)] +struct QuantizeSlots { + input: usize, + packed: usize, + ids: Option, +} +/// The layer of one stream-all run: its id, the ascending expert ids and the three formats. +#[derive(Clone, Copy)] +pub struct OriginalStreamAllLayer<'a> { + pub layer: u8, + pub experts: &'a [u32], + pub formats: [MmqFormat; 3], +} pub struct OriginalMmqOutput<'lease, 'layer, 'ctx> { layer: &'lease mut OriginalMmqLayer<'layer, 'ctx>, } @@ -86,8 +122,9 @@ pub struct OriginalMmqOutput<'lease, 'layer, 'ctx> { // remain whole-byte unchanged, including their original default finite errors. #[path = "mmq_original_ring.rs"] mod copy_ring; -pub use copy_ring::OriginalMmqCopySchedule; +use copy_ring::GatherDest; pub(crate) use copy_ring::prefetch_point; +pub use copy_ring::{OriginalMmqCopySchedule, RingExperts}; // Closed global issuer consumer. Old per-layer/synchronous producers unchanged. #[path = "mmq_original_stream_all.rs"] @@ -116,11 +153,11 @@ use kind_fn::kind; use kind_fn::layout; #[allow(unused_imports)] use kind_fn::shared; +#[path = "mmq_original_group/copy_ring_layer.rs"] +mod copy_ring_layer; #[path = "mmq_original_group/impl_mmqworkspace.rs"] mod impl_mmqworkspace; #[path = "mmq_original_group/impl_originalmmqlayer.rs"] mod impl_originalmmqlayer; -#[path = "mmq_original_group/impl_originalmmqlayer_2.rs"] -mod impl_originalmmqlayer_2; #[path = "mmq_original_group/impl_originalmmqoutput.rs"] mod impl_originalmmqoutput; diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs b/crates/cuda-driver/src/mmq_original_group/copy_ring_layer.rs similarity index 90% rename from crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs rename to crates/cuda-driver/src/mmq_original_group/copy_ring_layer.rs index dae5496b..8fb57980 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs +++ b/crates/cuda-driver/src/mmq_original_group/copy_ring_layer.rs @@ -10,16 +10,13 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { pub fn execute_original_copy_ring( &mut self, read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, - layer: usize, schedule: &mut OriginalMmqCopySchedule<'ctx>, - bank: std::rc::Rc>, - formats: [MmqFormat; 3], - sources: &[[leleka_model_format::qwen4exp::ResidentExpertBankSpan; 3]], + experts: RingExperts<'_, 'ctx>, ) -> Result<()> { + let (formats, sources) = (experts.formats, experts.sources); 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 mut ring = copy_ring::Ring::new(self.workspace.context, read, schedule, experts, groups)?; let operation = self.stream_through_ring(&mut ring, read, formats, sources.len()); let close = ring.close(); if operation.is_err() || close.is_err() { @@ -101,7 +98,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { 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)?; + ring.gather(j, formats, b.gather.ok_or(Error::ContextPoisoned)?, GatherDest { gate_up: wh, down_out: dh })?; self.formats = Some(formats); self.staged += 1; Ok(()) @@ -114,7 +111,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { 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])?)?; + self.enqueue_ring_project( + ring, + ProjectSpec { format: formats[0], down: false, width: self.width(formats[0])? }, + ProjectSlots { weights: WG, packed: XQ, out: GU }, + )?; 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 @@ -197,7 +198,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { ) -> 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])?)?; + self.enqueue_ring_project( + ring, + ProjectSpec { format: formats[2], down: true, width: self.width(formats[2])? }, + ProjectSlots { weights: WD, packed: HQ, out: D }, + )?; let d = self.handle(D, 0, nr as usize * 2560 * 4, 4)?; let d_flag = ring.flag(group, 3)?; ring.enqueue(Command::Helper( @@ -282,13 +287,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { pub(super) fn enqueue_ring_project( &self, ring: &mut copy_ring::Ring<'_, 'ctx>, - format: MmqFormat, - weights: usize, - packed: usize, - out: usize, - down: bool, - width: u32, + spec: ProjectSpec, + slots: ProjectSlots, ) -> Result<()> { + let ProjectSpec { format, down, width } = spec; + let ProjectSlots { weights, packed, out } = slots; let b = self.bank()?; let experts = self.staged as u32; let nr = self.bounds[self.next + self.staged] - self.bounds[self.next]; @@ -301,7 +304,13 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let (grid, needs_fix) = self.ring_project_grid(&l, rows, (experts, maxr, width))?; let hs = self.ring_project_handles(&l, (weights, packed, out), (down, tokens, experts))?; let tmp = self.ring_project_tmp(needs_fix, grid, width)?; - Self::ring_project_commands(ring, functions, (l, grid), (hs, tmp), (experts, maxr, width)) + Self::ring_project_commands( + ring, + functions, + (l, grid), + (hs, tmp), + ffi::MmqGroupShape { experts, max_rows: maxr, width }, + ) } /// The projection and fixup function of `format` at tile `width`. @@ -359,21 +368,15 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { (f, fix): (ffi::FunctionHandle, ffi::FunctionHandle), (l, grid): (Layout, u32), ([wh, ph, oh, ids, bounds], tmp): ([ffi::BufferHandle; 5], Option), - (experts, maxr, width): (u32, u32, u32), + shape: ffi::MmqGroupShape, ) -> Result<()> { use crate::ffi::original_enqueue::Command; - ring.enqueue(Command::Project( - f, - l, - grid, - ffi::MmqArguments::original_group(wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width), - ))?; + let routing = ffi::MmqGroupRouting { ids, bounds }; + let buffers = ffi::MmqGroupBuffers { weights: wh, packed: ph, output: oh, tmp }; + ring.enqueue(Command::Project(f, l, grid, ffi::MmqArguments::original_group(buffers, routing, l, shape)))?; if let Some(tmp) = tmp { - ring.enqueue(Command::Fixup( - fix, - grid, - ffi::MmqFixupArguments::original_group(ids, bounds, oh, tmp, l, experts, maxr, width), - ))?; + let args = ffi::MmqFixupArguments::original_group(routing, oh, tmp, l, shape); + ring.enqueue(Command::Fixup(fix, grid, args))?; } Ok(()) } diff --git a/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs b/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs index 73ac4cb2..992e029c 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs @@ -66,7 +66,7 @@ impl<'ctx> MmqWorkspace<'ctx> { formats: None, completed: false, }; - layer.quantize(X, XQ, total, 2560, Some(ROW_IDS))?; + layer.quantize(QuantizeSlots { input: X, packed: XQ, ids: Some(ROW_IDS) }, total, 2560)?; Ok(layer) } diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs index 7584beb5..37b85eb6 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer.rs @@ -3,9 +3,9 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_originalmmqlayer/impl_originalmmqlayer_2.rs"] -mod impl_originalmmqlayer_2; +#[path = "impl_originalmmqlayer/finite_and_quantize.rs"] +mod finite_and_quantize; +#[path = "impl_originalmmqlayer/group_projection.rs"] +mod group_projection; #[path = "impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs"] mod impl_originalmmqlayer_2_2; -#[path = "impl_originalmmqlayer/impl_originalmmqlayer_3.rs"] -mod impl_originalmmqlayer_3; diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/finite_and_quantize.rs similarity index 93% rename from crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs rename to crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/finite_and_quantize.rs index 99a14c07..3e8abff2 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/finite_and_quantize.rs @@ -48,14 +48,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { } Ok(()) } - pub(in super::super) fn finite( - &self, - commands: Vec, - source: ffi::BufferHandle, - amount: usize, - q8: bool, - label: &'static str, - ) -> Result<()> { + pub(in super::super) fn finite(&self, commands: Vec, scan: FiniteScan) -> Result<()> { + let FiniteScan { source, amount, q8, label } = scan; let w = &*self.workspace; let status = w.handle(STATUS, 4, 4)?; let tail = if q8 { 128 * 144 } else { 0 }; @@ -81,14 +75,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { _ => Err(Error::InvalidDriverValue("Original grouped finite status")), } } - pub(in super::super) fn quantize( - &self, - input: usize, - packed: usize, - tokens: u32, - columns: u32, - ids: Option, - ) -> Result<()> { + pub(in super::super) fn quantize(&self, slots: QuantizeSlots, tokens: u32, columns: u32) -> Result<()> { + let QuantizeSlots { input, packed, ids } = slots; let b = self.bank()?; let (f, rows) = Self::quantize_format(columns); let l = layout(f, rows, tokens, 64)?; @@ -103,7 +91,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let id_handle = ids.map(|i| self.handle(i, 0, tokens as usize * 4, 4)).transpose()?; let args = ffi::MmqQuantArguments::original_indexed(ih, id_handle, qh, l); cmds.push(QueuedCommand::Quantize(self.quantizer()?, l, args)); - self.finite(cmds, qh, l.payload / 144, true, "Q8") + self.finite(cmds, FiniteScan { source: qh, amount: l.payload / 144, q8: true, label: "Q8" }) } /// The format and row count whose Q8 layout holds activations of `columns`. fn quantize_format(columns: u32) -> (MmqFormat, u32) { @@ -133,7 +121,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { l, ffi::MmqQuantArguments::original_indexed(input, Some(ids), qh, l), )); - self.finite(cmds, qh, l.payload / 144, true, "Q8") + self.finite(cmds, FiniteScan { source: qh, amount: l.payload / 144, q8: true, label: "Q8" }) } pub fn stage_expert(&mut self, formats: [MmqFormat; 3], raw: [&DeviceBuffer<'_>; 3]) -> Result<()> { self.check_stage_request(formats)?; diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/group_projection.rs similarity index 86% rename from crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs rename to crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/group_projection.rs index b5dc776f..6a9093ec 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/group_projection.rs @@ -27,21 +27,16 @@ pub(crate) struct ProjectHandles { } impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { - pub(in super::super) fn project( - &self, - format: MmqFormat, - weights: usize, - packed: usize, - out: usize, - down: bool, - width: u32, - ) -> Result<()> { + pub(in super::super) fn project(&self, spec: ProjectSpec, slots: ProjectSlots) -> Result<()> { + let ProjectSpec { format, down, width } = spec; + let ProjectSlots { weights, packed, out } = slots; let b = self.bank()?; let plan = self.project_plan(b, format, down, width)?; let h = self.project_handles(&plan, (weights, packed, out), (down, width))?; let cmds = Self::project_commands(&plan, &h, width)?; if down { - return self.finite(cmds, h.out, plan.nr as usize * 2560, false, "Down"); + let scan = FiniteScan { source: h.out, amount: plan.nr as usize * 2560, q8: false, label: "Down" }; + return self.finite(cmds, scan); } let source = self.handle(out, self.bounds[self.next] as usize * 1280 * 4, plan.nr as usize * 1280 * 4, 4)?; self.finish_gate_up(b, cmds, source, plan.nr) @@ -127,7 +122,9 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { } pub(crate) fn project_arguments(plan: &ProjectPlan, h: &ProjectHandles, width: u32) -> ffi::MmqArguments { let (l, experts, maxr) = (plan.layout, plan.experts, plan.maxr); - ffi::MmqArguments::original_group(h.weights, h.packed, h.ids, h.bounds, h.out, h.tmp, l, experts, maxr, width) + let buffers = ffi::MmqGroupBuffers { weights: h.weights, packed: h.packed, output: h.out, tmp: h.tmp }; + let routing = ffi::MmqGroupRouting { ids: h.ids, bounds: h.bounds }; + ffi::MmqArguments::original_group(buffers, routing, l, ffi::MmqGroupShape { experts, max_rows: maxr, width }) } pub(crate) fn fixup_arguments( plan: &ProjectPlan, @@ -136,7 +133,14 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { width: u32, ) -> ffi::MmqFixupArguments { let (l, experts, maxr) = (plan.layout, plan.experts, plan.maxr); - ffi::MmqFixupArguments::original_group(h.ids, h.bounds, h.out, tmp, l, experts, maxr, width) + let routing = ffi::MmqGroupRouting { ids: h.ids, bounds: h.bounds }; + ffi::MmqFixupArguments::original_group( + routing, + h.out, + tmp, + l, + ffi::MmqGroupShape { experts, max_rows: maxr, width }, + ) } /// Same complete exponent scan with separate role bits. Gate outranks Up /// after the one successful GU/fixup drain, without introducing a D2H failure @@ -195,7 +199,10 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let nr = self.bounds[self.next + self.staged] - self.bounds[self.next]; self.zero_weight_slots(formats)?; self.gate_up_phase(formats, nr)?; - self.project(formats[2], WD, HQ, D, true, self.width(formats[2])?)?; + self.project( + ProjectSpec { format: formats[2], down: true, width: self.width(formats[2])? }, + ProjectSlots { weights: WD, packed: HQ, out: D }, + )?; self.completed = true; Ok(OriginalMmqOutput { layer: self }) } @@ -218,7 +225,10 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { } /// Gate/Up projection, SwiGLU and the quantization of its hidden output. fn gate_up_phase(&self, formats: [MmqFormat; 3], nr: u32) -> Result<()> { - self.project(formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; + self.project( + ProjectSpec { format: formats[0], down: false, width: self.width(formats[0])? }, + ProjectSlots { weights: WG, packed: XQ, out: GU }, + )?; let b = self.bank()?; let gu = self.handle(GU, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)?; let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?; @@ -228,8 +238,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { nr, ffi::MmqOriginalSwigluArguments::new(gu, h, nr), )); - self.finite(cmds, h, nr as usize * 640, false, "SwiGLU")?; - self.quantize(H, HQ, nr, 640, None) + self.finite(cmds, FiniteScan { source: h, amount: nr as usize * 640, q8: false, label: "SwiGLU" })?; + self.quantize(QuantizeSlots { input: H, packed: HQ, ids: None }, nr, 640) } pub fn finish_group(&mut self) -> Result<()> { if !self.completed || self.staged != (self.counts.len() - self.next).min(16) || self.staged == 0 { diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 6db2007d..d241f69c 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -22,6 +22,20 @@ use chunk_stream::{ChunkStream, Entry as StreamEntry}; )))] struct ChunkStream; const COMMAND_CAP: usize = 2048; +/// The experts one layer streams through the copy ring: the layer, the registered bank, the three formats and the +/// per-expert bank spans. +pub struct RingExperts<'read, 'ctx> { + pub layer: usize, + pub bank: Rc>, + pub formats: [MmqFormat; 3], + pub sources: &'read [[ResidentExpertBankSpan; 3]], +} +/// The destinations of one gather: the gate/up weight slot and the down weight slot. +#[derive(Clone, Copy)] +pub(crate) struct GatherDest { + pub(crate) gate_up: ffi::BufferHandle, + pub(crate) down_out: ffi::BufferHandle, +} trait RingArena: GroupArena { fn stage_slots(&self) -> Result; fn stage_span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)>; diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs b/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs index 4d1f7fb5..71346433 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs @@ -5,6 +5,8 @@ use super::*; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod stream_start; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +use stream_start::StreamPlan; impl<'ctx> OriginalMmqCopySchedule<'ctx> { /// Byte accounting only: the real caller computes retained bank, source @@ -75,7 +77,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { let api = StagerApi::load()?; let events = self.stream_make_events(&api, ring)?; let _ = bytes_per_second; - self.stream_launch(api, bank, (first, ring), (entries, targets), events) + self.stream_launch(api, bank, StreamPlan { first, ring, entries, targets }, events) } /// End the chunk's expert stream: stop and join the issuer, drain the copy and compute streams, release the /// raw events. Idempotent; a failure poisons the schedule. diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs index 397fdb62..fb92884f 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs @@ -7,13 +7,11 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { pub(in super::super::super) fn new( context: &'ctx Context<'ctx>, read: &'read crate::OriginalDeviceGrRead<'_, '_, 'ctx>, - layer: usize, schedule: &'read mut OriginalMmqCopySchedule<'ctx>, - bank: Rc>, - formats: [MmqFormat; 3], - spans: &'read [[ResidentExpertBankSpan; 3]], + experts: RingExperts<'read, 'ctx>, groups: usize, ) -> Result { + let RingExperts { layer, bank, formats, sources: spans } = experts; Self::validate_new(context, read, &bank, (layer, groups, spans.len()), &formats)?; let (gu, down, blob) = Self::blob_geometry(&formats)?; let admitted: &dyn RingArena = read; diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs index 50221b9e..a8e6439d 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs @@ -9,9 +9,9 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { index: usize, formats: [MmqFormat; 3], f: ffi::FunctionHandle, - gate_up: ffi::BufferHandle, - down_out: ffi::BufferHandle, + dest: GatherDest, ) -> Result<()> { + let GatherDest { gate_up, down_out } = dest; let source = self.sources.get(index).ok_or(Error::InvalidProjectionShape)?; let gu = formats[0].layout(1)?.raw_weight; let down = formats[2].layout(1)?.raw_weight; diff --git a/crates/cuda-driver/src/mmq_original_ring/stream_start.rs b/crates/cuda-driver/src/mmq_original_ring/stream_start.rs index 32b645e5..3729599e 100644 --- a/crates/cuda-driver/src/mmq_original_ring/stream_start.rs +++ b/crates/cuda-driver/src/mmq_original_ring/stream_start.rs @@ -3,6 +3,14 @@ #[allow(unused_imports)] use super::*; +/// What the prompt stream copies: the first layer, the ring size, the entries in stream order and the ring slots. +pub(super) struct StreamPlan { + pub(super) first: u8, + pub(super) ring: usize, + pub(super) entries: Vec, + pub(super) targets: Vec<(ffi::BufferHandle, usize)>, +} + impl<'ctx> OriginalMmqCopySchedule<'ctx> { pub(super) fn stream_admit( &self, @@ -111,18 +119,31 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { &mut self, api: crate::ffi::original_stager::Api, bank: &Rc>, - (first, ring): (u8, usize), - (entries, targets): (Vec, Vec<(ffi::BufferHandle, usize)>), + plan: StreamPlan, events: Vec, ) -> Result<()> { use crate::ffi::original_stager::Api as StagerApi; + let StreamPlan { first, ring, entries, targets } = plan; let (copied, used, starts) = Self::split_events(&events, ring); let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(Ok)?; // the copies must follow everything the compute path queued so far on its own streams self.context.synchronize()?; let context_token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?); let topup = Self::prefill_topup(); - match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup, context_token) { + let context = context_token; + let parts = chunk_stream::CoreParts { api, entries, targets, copied, used, starts, copy, topup, context }; + self.start_stream(first, parts, (bank, events)) + } + + /// Starts the issuer thread over `parts`; on failure destroys the events. + fn start_stream( + &mut self, + first: u8, + parts: chunk_stream::CoreParts, + (bank, events): (&Rc>, Vec), + ) -> Result<()> { + let copy = parts.copy; + match ChunkStream::start(first, parts) { Ok(stream) => { self.adopt_stream(stream, bank, events, copy); Ok(()) diff --git a/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs b/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs index 65511f82..db69e76e 100644 --- a/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs +++ b/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs @@ -15,10 +15,20 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let gu = formats[0].layout(1)?.raw_weight; let down = formats[2].layout(1)?.raw_weight; self.enqueue_zeroes(transport, stream, group, (gu, down))?; - self.enqueue_global_project(transport, stream, formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; + self.enqueue_global_project( + transport, + stream, + ProjectSpec { format: formats[0], down: false, width: self.width(formats[0])? }, + ProjectSlots { weights: WG, packed: XQ, out: GU }, + )?; let h = self.enqueue_hidden_checks(transport, stream, (group, nr))?; self.enqueue_quantize_phase(transport, stream, (group, nr), h)?; - self.enqueue_global_project(transport, stream, formats[2], WD, HQ, D, true, self.width(formats[2])?)?; + self.enqueue_global_project( + transport, + stream, + ProjectSpec { format: formats[2], down: true, width: self.width(formats[2])? }, + ProjectSlots { weights: WD, packed: HQ, out: D }, + )?; self.enqueue_down_finite(transport, stream, (group, nr)) } /// Zero the four group flags and the gate/up and down weight slots. @@ -152,13 +162,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { &self, transport: &mut Transport<'ctx>, stream: &mut OriginalGpuStream<'ctx>, - format: MmqFormat, - weights: usize, - packed: usize, - out: usize, - down: bool, - width: u32, + spec: ProjectSpec, + slots: ProjectSlots, ) -> Result<()> { + let ProjectSpec { format, down, width } = spec; + let ProjectSlots { weights, packed, out } = slots; let b = self.bank()?; let plan = self.project_plan(b, format, down, width)?; let h = self.project_handles(&plan, (weights, packed, out), (down, width))?; @@ -174,11 +182,10 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { &mut self, read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, forward: &mut crate::OriginalStreamAllForward<'_, '_, '_, '_, 'ctx>, - layer: u8, - experts: &[u32], - formats: [MmqFormat; 3], + layer: OriginalStreamAllLayer<'_>, host_allowance: usize, ) -> Result<()> { + let OriginalStreamAllLayer { layer, experts, formats } = layer; self.check_stream_all_request(read, experts)?; let transport = Transport::new(self.workspace.context, experts.len().div_ceil(16), host_allowance)?; let mut producer = Producer { layer: self, transport, formats, experts, layer_id: layer }; diff --git a/crates/cuda-driver/src/mmq_resident.rs b/crates/cuda-driver/src/mmq_resident.rs index 0bb0d517..e52d37bd 100644 --- a/crates/cuda-driver/src/mmq_resident.rs +++ b/crates/cuda-driver/src/mmq_resident.rs @@ -85,5 +85,11 @@ pub(crate) use asset_fn::asset; use asset_fn::commands; #[path = "mmq_resident/impl_drop_for_mmqworkspace.rs"] mod impl_drop_for_mmqworkspace; +/// The workspace slots of one projection: the packed activation and the output. +#[derive(Clone, Copy)] +struct ProjectionSlots { + packed: usize, + out: usize, +} #[path = "mmq_resident/impl_mmqworkspace.rs"] mod impl_mmqworkspace; diff --git a/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs b/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs index 05d851a6..a8aac63c 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs @@ -31,7 +31,12 @@ impl<'ctx> MmqChunkActivation<'_, 'ctx> { commands.push(QueuedCommand::Helper( w.kernel(2)?, (l.payload / 4) as u32, - ffi::MmqResidentArguments::gather(source, ids, out, tokens, t, l.padded_columns / 128), + ffi::MmqResidentArguments::gather( + source, + ids, + out, + ffi::MmqGatherShape { total: tokens, group: t, blocks: l.padded_columns / 128 }, + ), )); w.finish_finite(commands, GROUP, l.payload / 144, true) } @@ -96,8 +101,8 @@ impl<'lease, 'ctx> MmqGroupActivation<'lease, 'ctx> { original: bool, ) -> Result<()> { if original { - w.project_with_operator(gate, GROUP, GATE, t, true)?; - w.project_with_operator(up, GROUP, UP, t, true)?; + w.project_with_operator(gate, ProjectionSlots { packed: GROUP, out: GATE }, t, true)?; + w.project_with_operator(up, ProjectionSlots { packed: GROUP, out: UP }, t, true)?; } else { w.project(gate, GROUP, GATE, t)?; w.project(up, GROUP, UP, t)?; @@ -140,7 +145,7 @@ impl<'lease, 'ctx> MmqHidden<'lease, 'ctx> { let l = weights.format.layout(t)?; if self.original { w.quantize_with_operator(HIDDEN, DOWN_Q8, l, true)?; - w.project_with_operator(weights, DOWN_Q8, DOWN, t, true) + w.project_with_operator(weights, ProjectionSlots { packed: DOWN_Q8, out: DOWN }, t, true) } else { w.quantize(HIDDEN, DOWN_Q8, l)?; if w.native_integer.is_some() { @@ -154,6 +159,12 @@ impl<'lease, 'ctx> MmqHidden<'lease, 'ctx> { Ok(FiniteMmqOutput { workspace: w, tokens: t }) } } +/// One Down column copy: the column, the destination packet and its slot. +struct DownCopyRequest<'a, 'b> { + column: u32, + destination: &'a DeviceBuffer<'b>, + slot: u32, +} impl FiniteMmqOutput<'_, '_> { pub fn tokens(&self) -> u32 { self.tokens @@ -180,7 +191,8 @@ impl FiniteMmqOutput<'_, '_> { handles.try_reserve_exact(copies.len()).map_err(|_| Error::HostAllocation)?; // No device operation occurs until every owner/span is admitted. for (column, destination, slot) in copies.iter() { - let entry = self.admit_down_copy(source, &handles, *column, destination, *slot)?; + let request = DownCopyRequest { column: *column, destination, slot: *slot }; + let entry = self.admit_down_copy(source, &handles, request)?; handles.push(entry); } Ok(handles) @@ -200,10 +212,9 @@ impl FiniteMmqOutput<'_, '_> { &self, source: ffi::BufferHandle, handles: &[DownCopyHandles], - column: u32, - destination: &DeviceBuffer<'_>, - slot: u32, + request: DownCopyRequest<'_, '_>, ) -> Result { + let DownCopyRequest { column, destination, slot } = request; let w = &*self.workspace; let target = self.down_target(column, destination, slot)?; if source.overlaps(w.buffer(DOWN)?.bytes, target, 102400) diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs index 46367ef9..5a6a79f7 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace.rs @@ -5,7 +5,7 @@ use super::*; #[path = "impl_mmqworkspace/impl_mmqworkspace_2.rs"] mod impl_mmqworkspace_2; -#[path = "impl_mmqworkspace/impl_mmqworkspace_2_2.rs"] -mod impl_mmqworkspace_2_2; #[path = "impl_mmqworkspace/impl_mmqworkspace_3.rs"] mod impl_mmqworkspace_3; +#[path = "impl_mmqworkspace/projection_plan.rs"] +mod projection_plan; diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/projection_plan.rs similarity index 93% rename from crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs rename to crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/projection_plan.rs index 907c0e94..f6215377 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/projection_plan.rs @@ -91,7 +91,7 @@ impl<'ctx> MmqWorkspace<'ctx> { ) -> Result> { let mut cmds = commands()?; cmds.push(self.zero_command(STATUS, 4)?); - n.append(&mut cmds, ih, qh, sh, l)?; + n.append(&mut cmds, [ih, qh, sh], l)?; // Preserve native status bits: never zero between native quantize and proof. cmds.push(QueuedCommand::Helper( self.kernel(1)?, @@ -136,21 +136,21 @@ impl<'ctx> MmqWorkspace<'ctx> { out: usize, tokens: u32, ) -> Result<()> { - self.project_with_operator(weights, packed, out, tokens, false) + self.project_with_operator(weights, ProjectionSlots { packed, out }, tokens, false) } pub(in super::super) fn project_with_operator( &self, weights: &MmqWeights<'_>, - packed: usize, - out: usize, + slots: ProjectionSlots, tokens: u32, original: bool, ) -> Result<()> { + let ProjectionSlots { packed, out } = slots; let plan = self.project_plan(weights, packed, out, tokens)?; self.check_project_alias(&plan, packed, out)?; if let Some(integer) = &self.native_integer && !original - && self.project_integer(integer, weights, packed, out, &plan)? + && self.project_integer(integer, weights, ProjectionSlots { packed, out }, &plan)? { return Ok(()); } @@ -186,10 +186,10 @@ impl<'ctx> MmqWorkspace<'ctx> { &self, integer: &native_integer::NativeInteger<'ctx>, weights: &MmqWeights<'_>, - packed: usize, - out: usize, + slots: ProjectionSlots, plan: &ProjectPlan, ) -> Result { + let ProjectionSlots { packed, out } = slots; if matches!(weights.format, MmqFormat::Iq2SGateUp) { return Err(Error::UnsupportedProjection); } @@ -201,7 +201,7 @@ impl<'ctx> MmqWorkspace<'ctx> { } self.check_integer_buffers(integer)?; let mut queued = commands()?; - integer.append(&mut queued, plan.wh, plan.ph, plan.oh, plan.l)?; + integer.append(&mut queued, [plan.wh, plan.ph, plan.oh], plan.l)?; self.finish_finite(queued, out, plan.l.output / 4, false)?; Ok(true) } @@ -222,7 +222,7 @@ impl<'ctx> MmqWorkspace<'ctx> { let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { e.sms }; let fixup = !tiles.is_multiple_of(grid); let temp = if fixup { Some(self.fixup_scratch(grid, plan, packed, out)?) } else { None }; - let commands = self.project_commands(e, weights.format, plan, grid, temp)?; + let commands = self.project_commands(e, weights.format, plan, StreamKLaunch { grid, temp })?; self.finish_finite(commands, out, l.output / 4, false) } fn fixup_scratch(&self, grid: u32, plan: &ProjectPlan, packed: usize, out: usize) -> Result { @@ -241,10 +241,10 @@ impl<'ctx> MmqWorkspace<'ctx> { e: &MmqExperiment<'ctx>, format: MmqFormat, plan: &ProjectPlan, - grid: u32, - temp: Option, + launch: StreamKLaunch, ) -> Result> { let ProjectPlan { l, wh, ph, oh, .. } = *plan; + let StreamKLaunch { grid, temp } = launch; let mut commands = commands()?; if temp.is_some() { commands.push(self.zero_command(SCRATCH, grid as usize * l.tile.width() as usize * 128 * 4)?); @@ -266,6 +266,12 @@ impl<'ctx> MmqWorkspace<'ctx> { } } +/// The launch grid of a stream-k projection and its optional fixup scratch. +#[derive(Clone, Copy)] +struct StreamKLaunch { + grid: u32, + temp: Option, +} /// Validated handles and layout of one projection; the weight allocation is `w_bytes` long. #[derive(Clone, Copy)] struct ProjectPlan { diff --git a/crates/cuda-driver/src/mmq_resident_gpu.rs b/crates/cuda-driver/src/mmq_resident_gpu.rs index 912edb5c..b2a5c2d7 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu.rs @@ -141,11 +141,11 @@ use native_owner_fn::direct; use native_owner_fn::gather; #[allow(unused_imports)] use native_owner_fn::native_owner; -#[path = "mmq_resident_gpu/chain_fn.rs"] -mod chain_fn; +#[path = "mmq_resident_gpu/resident_chain.rs"] +mod resident_chain; #[allow(unused_imports)] -use chain_fn::chain; +use resident_chain::chain; #[allow(unused_imports)] -use chain_fn::witness; +use resident_chain::witness; #[path = "mmq_resident_gpu/impl_drop_for_livepacketalias.rs"] mod impl_drop_for_livepacketalias; diff --git a/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs index 5122a5e5..bfc5514f 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs @@ -51,7 +51,8 @@ fn native_down_owner( input: &DeviceBuffer<'_>, [old, new]: [&mut DeviceBuffer<'_>; 2], ) { - c.project_routed_down_columns(raw_weight, input, old, 1, raw_format(dual.format)).unwrap(); + c.project_routed_down_columns(raw_weight, input, old, DownColumns { total: 1, format: raw_format(dual.format) }) + .unwrap(); dual.native_down_columns(input, 1, new).unwrap(); same(&download(new, 10240), &download(old, 10240), "dual grouped Down"); } diff --git a/crates/cuda-driver/src/mmq_resident_gpu/owner_proof_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/owner_proof_fn.rs index da4c64f7..8201b077 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/owner_proof_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/owner_proof_fn.rs @@ -61,7 +61,7 @@ pub(super) fn prove_gather_chain_abandon(receipt: &Receipt, w: &mut MmqWorkspace let gathered = gather(receipt, w); assert_eq!(gathered, 269568); let chain_words = - chain(receipt, w, 18, 4, &owners[0], &owners[2]) + chain(receipt, w, 22, 64, &owners[1], &owners[3]); + chain(receipt, w, (18, 4), (&owners[0], &owners[2])) + chain(receipt, w, (22, 64), (&owners[1], &owners[3])); assert_eq!(chain_words, 304640); // Abandon a completed group without publication, then next genuine invocation. { diff --git a/crates/cuda-driver/src/mmq_resident_gpu/queued_proof_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/queued_proof_fn.rs index 3c227ee3..caa0efe6 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/queued_proof_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/queued_proof_fn.rs @@ -47,11 +47,12 @@ pub(super) fn queued_baseline<'c>( data: &[u8], ) -> Baseline { let old = c.mmq_experiment().unwrap(); + let request = MmqRequest { profile: MmqProfile::OriginalAdaptive, tokens: QT }; let input = upload(c, data); let mut gate = c.allocate(GU_BYTES).unwrap(); let mut up = c.allocate(GU_BYTES).unwrap(); - let (gate_values, q8) = old.project_observed(MmqProfile::OriginalAdaptive, gu, &input, QT, &mut gate).unwrap(); - let (up_values, _) = old.project_observed(MmqProfile::OriginalAdaptive, gu, &input, QT, &mut up).unwrap(); + let (gate_values, q8) = old.project_observed(request, gu, &input, &mut gate).unwrap(); + let (up_values, _) = old.project_observed(request, gu, &input, &mut up).unwrap(); compare(&gate_values, &file(receipt, 18, QT, "reference_streamk.f32"), "original GU"); same(&q8, &file(receipt, 18, QT, "reference_q8.bin"), "original D4"); let mut hidden = c.allocate(GU_BYTES).unwrap(); @@ -59,8 +60,7 @@ pub(super) fn queued_baseline<'c>( let hidden_bytes = download(&hidden, GU_BYTES); finite(&hidden_bytes); let mut old_output = c.allocate(DOWN_BYTES).unwrap(); - let (down_values, down_q8) = - old.project_observed(MmqProfile::OriginalAdaptive, down, &hidden, QT, &mut old_output).unwrap(); + let (down_values, down_q8) = old.project_observed(request, down, &hidden, &mut old_output).unwrap(); let down_bytes = download(&old_output, DOWN_BYTES); compare(&down_values, &down_bytes, "qualified actual Down"); same(&download(&input, data.len()), data, "baseline source immutable"); diff --git a/crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/resident_chain.rs similarity index 94% rename from crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs rename to crates/cuda-driver/src/mmq_resident_gpu/resident_chain.rs index 3af3d370..827ae9ce 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/resident_chain.rs @@ -19,12 +19,12 @@ fn chain_baseline( (gu, down): (&MmqWeights<'_>, &MmqWeights<'_>), ) -> ChainBaseline { let old = c.mmq_experiment().unwrap(); + let request = MmqRequest { profile: MmqProfile::OriginalAdaptive, tokens: t }; let input_bytes = file(r, kind, t, "input.f32"); let input = upload(c, &input_bytes); - let mut gate = c.allocate(t as usize * 2560).unwrap(); - let mut up = c.allocate(t as usize * 2560).unwrap(); - let (gate_values, q8) = old.project_observed(MmqProfile::OriginalAdaptive, gu, &input, t, &mut gate).unwrap(); - let (up_values, _) = old.project_observed(MmqProfile::OriginalAdaptive, gu, &input, t, &mut up).unwrap(); + let (mut gate, mut up) = (c.allocate(t as usize * 2560).unwrap(), c.allocate(t as usize * 2560).unwrap()); + let (gate_values, q8) = old.project_observed(request, gu, &input, &mut gate).unwrap(); + let (up_values, _) = old.project_observed(request, gu, &input, &mut up).unwrap(); compare(&gate_values, &file(r, kind, t, "reference_streamk.f32"), "baseline GU original"); same(&q8, &file(r, kind, t, "reference_q8.bin"), "baseline original Q8"); let mut hidden = c.allocate(t as usize * 2560).unwrap(); @@ -32,7 +32,7 @@ fn chain_baseline( let hidden_values = download(&hidden, t as usize * 2560); finite(&hidden_values); let mut output = c.allocate(t as usize * 10240).unwrap(); - let (down_values, _) = old.project_observed(MmqProfile::OriginalAdaptive, down, &hidden, t, &mut output).unwrap(); + let (down_values, _) = old.project_observed(request, down, &hidden, &mut output).unwrap(); let down_bytes = download(&output, t as usize * 10240); finite(&down_bytes); compare(&down_values, &down_bytes, "baseline Down actual"); @@ -45,10 +45,8 @@ fn chain_baseline( pub(super) fn chain( r: &Receipt, w: &mut MmqWorkspace<'_>, - kind: u32, - t: u32, - gu: &MmqWeights<'_>, - down: &MmqWeights<'_>, + (kind, t): (u32, u32), + (gu, down): (&MmqWeights<'_>, &MmqWeights<'_>), ) -> usize { let c = w.context; let base = chain_baseline(r, c, (kind, t), (gu, down)); diff --git a/crates/cuda-driver/src/moe_group_down_columns.rs b/crates/cuda-driver/src/moe_group_down_columns.rs index 92c5a76e..d1737893 100644 --- a/crates/cuda-driver/src/moe_group_down_columns.rs +++ b/crates/cuda-driver/src/moe_group_down_columns.rs @@ -1,6 +1,24 @@ //! Closed grouped native SwiGLU/Down20/42; each column retains scalar arithmetic. use super::*; type NativeDownCopyHandles = (ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle); +/// The number of columns and the routed format of one grouped Down projection. +#[derive(Clone, Copy)] +pub struct DownColumns { + pub total: usize, + pub format: RoutedFormat, +} +/// The completed Down output a slot copy reads from: the buffer and its admitted handle. +#[derive(Clone, Copy)] +struct DownSource<'a, 'b> { + buffer: &'a DeviceBuffer<'b>, + handle: ffi::BufferHandle, +} +/// The device scratch of the grouped Down quantization: the Q8 image and the status word. +#[derive(Clone, Copy)] +struct QuantScratch { + q8: ffi::BufferHandle, + flag: ffi::BufferHandle, +} impl Context<'_> { /// Closed byte transport from completed native Down columns to whole /// disjoint ten-slot packets. Runtime owns the finite/route publication. @@ -30,8 +48,7 @@ impl Context<'_> { handles.try_reserve_exact(total).map_err(|_| Error::HostAllocation)?; for (index, (column, destination, slot)) in copies.iter().enumerate() { let entry = self.admit_down_slot_copy( - source, - source_handle, + DownSource { buffer: source, handle: source_handle }, &handles, (index, total), (*column, destination, *slot), @@ -42,12 +59,12 @@ impl Context<'_> { } fn admit_down_slot_copy( &self, - source: &DeviceBuffer<'_>, - source_handle: ffi::BufferHandle, + source: DownSource<'_, '_>, handles: &[NativeDownCopyHandles], (index, total): (usize, usize), (column, destination, slot): (u32, &DeviceBuffer<'_>, u32), ) -> Result { + let DownSource { buffer: source, handle: source_handle } = source; if column as usize != index || slot >= 10 || destination.bytes != 102400 { return Err(Error::InvalidProjectionShape); } @@ -131,19 +148,18 @@ impl Context<'_> { weights: &DeviceBuffer<'_>, hidden: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, - total: usize, - format: RoutedFormat, + columns: DownColumns, ) -> Result<()> { - self.project_routed_down_columns_weight(NativeWeights::Raw(weights), hidden, output, total, format) + self.project_routed_down_columns_weight(NativeWeights::Raw(weights), hidden, output, columns) } pub(super) fn project_routed_down_columns_weight( &self, weight_owner: NativeWeights<'_, '_>, hidden: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, - total: usize, - format: RoutedFormat, + columns: DownColumns, ) -> Result<()> { + let DownColumns { total, format } = columns; let weights = weight_owner.buffer()?; self.grouped_buffers(&[weights, hidden, output])?; let operation = match format { @@ -214,7 +230,7 @@ impl Context<'_> { plan.check_scratch_alias(q8, flag, scratch_bytes)?; status.copy_from(&[0; 4])?; let (quantizer, projector) = self.grouped_down_kernels(plan.operation)?; - self.quantize_grouped_down(plan, quantizer, q8, flag, status)?; + self.quantize_grouped_down(plan, quantizer, QuantScratch { q8, flag }, status)?; let mut args = ffi::ProjectionArguments::new(plan.handles[0], q8, plan.handles[2], 2560, 640); let guard = self.enter()?; let launch = self.driver.api.launch_grouped_projection(projector.function, 640, plan.total as u32, &mut args); @@ -231,10 +247,10 @@ impl Context<'_> { &self, plan: &GroupedDownPlan, quantizer: FixedKernel, - q8: ffi::BufferHandle, - flag: ffi::BufferHandle, + scratch: QuantScratch, status: &mut DeviceBuffer<'_>, ) -> Result<()> { + let QuantScratch { q8, flag } = scratch; let total = plan.total; // 640 is a multiple of32: flattening columns preserves every Q8 // block, lane schedule, scale/sum and per-column original order. diff --git a/crates/cuda-driver/src/moe_prefill_batch.rs b/crates/cuda-driver/src/moe_prefill_batch.rs index 52cd85ef..063f8ec3 100644 --- a/crates/cuda-driver/src/moe_prefill_batch.rs +++ b/crates/cuda-driver/src/moe_prefill_batch.rs @@ -249,6 +249,15 @@ use pinned_fn::linear; use pinned_fn::pinned; #[allow(unused_imports)] pub(crate) use pinned_fn::prefill_asset; +/// The three caller-lent combine inputs: the route weights `[t][10]`, the shared output `[t][2560]` and the scalar +/// gate logits `[t]`, all f32. +#[derive(Clone, Copy)] +pub struct MoeCombineInputs<'lease> { + pub route_weights: &'lease DeviceBuffer<'lease>, + pub shared: &'lease DeviceBuffer<'lease>, + pub sg: &'lease DeviceBuffer<'lease>, +} + #[path = "moe_prefill_batch/impl_moebatchprefix.rs"] mod impl_moebatchprefix; #[path = "moe_prefill_batch/impl_moeprefillbatch.rs"] diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs index 7e8f6d69..383f5329 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix.rs @@ -3,9 +3,9 @@ #[allow(unused_imports)] use super::*; +#[path = "impl_moebatchprefix/combine_stage.rs"] +mod combine_stage; #[path = "impl_moebatchprefix/impl_moebatchprefix_2.rs"] mod impl_moebatchprefix_2; -#[path = "impl_moebatchprefix/impl_moebatchprefix_2_2.rs"] -mod impl_moebatchprefix_2_2; -#[path = "impl_moebatchprefix/impl_moebatchprefix_3.rs"] -mod impl_moebatchprefix_3; +#[path = "impl_moebatchprefix/shared_expert_projections.rs"] +mod shared_expert_projections; diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/combine_stage.rs similarity index 98% rename from crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs rename to crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/combine_stage.rs index 705c2c80..c1204ce1 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/combine_stage.rs @@ -9,13 +9,12 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { /// exact `[t][2560]` f32 shared output and `sg` the exact `[t]` f32 scalar-gate logits. pub fn combine_from( &mut self, - route_weights: &'lease DeviceBuffer<'lease>, - shared: &'lease DeviceBuffer<'lease>, - sg: &'lease DeviceBuffer<'lease>, + inputs: MoeCombineInputs<'lease>, dm: &'lease DeviceBuffer<'lease>, slot: &[i32], bo: &'lease DeviceBuffer<'lease>, ) -> Result<()> { + let MoeCombineInputs { route_weights, shared, sg } = inputs; let result = (|| { if !self.combine_only { return Err(Error::InvalidQwenShape); diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/shared_expert_projections.rs similarity index 77% rename from crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs rename to crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/shared_expert_projections.rs index ac31b292..261e06bf 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/shared_expert_projections.rs @@ -3,22 +3,35 @@ #[allow(unused_imports)] use super::*; +/// The shape of one native projection: the GGUF `format`, the matrix `rows` x `depth` and the byte size of the f32 +/// output. +#[derive(Clone, Copy)] +pub(in super::super) struct NativeProjection { + pub(in super::super) format: GdnNativeFormat, + pub(in super::super) rows: usize, + pub(in super::super) depth: usize, + pub(in super::super) output_bytes: usize, +} + +/// The operands of one native projection: the weights, the FP16 scratch, the activation role and the output. +pub(in super::super) struct ProjectionOperands<'lease> { + pub(in super::super) weights: (Role, &'lease DeviceBuffer<'lease>), + pub(in super::super) scratch: &'lease DeviceBuffer<'lease>, + pub(in super::super) activation: Role, + pub(in super::super) output: (Role, &'lease DeviceBuffer<'lease>), +} + impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { // ---------------------------------------------------------------- shared expert /// Dequantize the exact GGUF matrix to FP16 scratch (one thread per 32-value group) and enqueue /// `Y[t][rows] = X . W^T` through the adapter. - #[allow(clippy::too_many_arguments)] // The fixed operands of one native projection. pub(in super::super) fn project_native( &mut self, - format: GdnNativeFormat, - weights: (Role, &'lease DeviceBuffer<'lease>), - scratch: &'lease DeviceBuffer<'lease>, - activation: Role, - output: (Role, &'lease DeviceBuffer<'lease>), - rows: usize, - depth: usize, - output_bytes: usize, + projection: NativeProjection, + operands: ProjectionOperands<'lease>, ) -> Result<()> { + let NativeProjection { format, rows, depth, output_bytes } = projection; + let ProjectionOperands { weights, scratch, activation, output } = operands; let t = self.tokens; let matrix = format.matrix_bytes(rows, depth)?; let half_bytes = rows * depth * F16; @@ -69,16 +82,14 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Gate)?; let bytes = self.tokens * FF * F32; - self.project_native( - format, - (Role::GateW, weights), + let projection = NativeProjection { format, rows: FF, depth: N, output_bytes: bytes }; + let operands = ProjectionOperands { + weights: (Role::GateW, weights), scratch, - Role::MixedH, - (Role::SGate, sgate), - FF, - N, - bytes, - )?; + activation: Role::MixedH, + output: (Role::SGate, sgate), + }; + self.project_native(projection, operands)?; self.scan(MoeBatchStage::SGate, Role::SGate)?; self.step = self.step.next(); Ok(()) @@ -96,7 +107,14 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Up)?; let bytes = self.tokens * FF * F32; - self.project_native(format, (Role::UpW, weights), scratch, Role::MixedH, (Role::SUp, sup), FF, N, bytes)?; + let projection = NativeProjection { format, rows: FF, depth: N, output_bytes: bytes }; + let operands = ProjectionOperands { + weights: (Role::UpW, weights), + scratch, + activation: Role::MixedH, + output: (Role::SUp, sup), + }; + self.project_native(projection, operands)?; self.scan(MoeBatchStage::SUp, Role::SUp)?; self.step = self.step.next(); Ok(()) @@ -138,16 +156,14 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Down)?; let bytes = self.tokens * N * F32; - self.project_native( - format, - (Role::DownW, weights), + let projection = NativeProjection { format, rows: N, depth: FF, output_bytes: bytes }; + let operands = ProjectionOperands { + weights: (Role::DownW, weights), scratch, - Role::ShH, - (Role::Shared, shared), - N, - FF, - bytes, - )?; + activation: Role::ShH, + output: (Role::Shared, shared), + }; + self.project_native(projection, operands)?; self.scan(MoeBatchStage::Shared, Role::Shared)?; self.step = self.step.next(); Ok(()) diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs index 322573cf..d51675df 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs @@ -149,7 +149,8 @@ impl Command<'_> { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { match self { Self::Kernel { function, stream, grid, block, args } => { - context.driver.api.launch_gdn_native(*function, *stream, *grid, *block, args) + let geometry = crate::GdnGeometry { grid: *grid, block: *block }; + context.driver.api.launch_gdn_native(*function, *stream, geometry, args) } Self::Gemm { gemm, bf16, x, w, y, shape } => { if *bf16 { diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu.rs index 3591e124..3998d1de 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu.rs @@ -111,12 +111,12 @@ use bytes_of_fn::words_of; #[path = "moe_prefill_batch_gpu/impl_fixture.rs"] mod impl_fixture; #[allow(unused_imports)] -use impl_fixture::run_case; +use impl_fixture::{Window, run_case}; #[path = "moe_prefill_batch_gpu/program_cases_fn.rs"] mod program_cases_fn; #[allow(unused_imports)] use program_cases_fn::run_program_cases; -#[path = "moe_prefill_batch_gpu/check_clean_fn.rs"] -mod check_clean_fn; +#[path = "moe_prefill_batch_gpu/clean_window_check.rs"] +mod clean_window_check; #[allow(unused_imports)] -use check_clean_fn::check_clean; +use clean_window_check::check_clean; diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs index 2b5c0e25..4399834b 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs @@ -99,14 +99,7 @@ pub(super) fn q8_0(rows: usize, cols: usize, salt: usize) -> (Vec, Vec) (blocks, half) } impl HostGemm { - pub(super) fn run( - &self, - bf16: bool, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + pub(super) fn run(&self, bf16: bool, [x, w, y]: [&DeviceBuffer<'_>; 3], shape: GemmShape) -> Result<()> { self.calls.set(self.calls.get() + 1); let mut xb = vec![0u8; x.len()]; x.copy_to(&mut xb)?; @@ -167,10 +160,10 @@ impl GdnGemm for HostGemm { GdnStream::default_stream() } fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { - self.run(false, x, w, y, shape) + self.run(false, [x, w, y], shape) } fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { - self.run(true, x, w, y, shape) + self.run(true, [x, w, y], shape) } } diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/clean_window_check.rs similarity index 98% rename from crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs rename to crates/cuda-driver/src/moe_prefill_batch_gpu/clean_window_check.rs index 72aa1eea..d3e7c4b5 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/clean_window_check.rs @@ -6,12 +6,11 @@ use super::*; pub(super) fn check_clean( f: &Fixture<'_>, gemm: &HostGemm, - tokens: usize, + window: Window, route: &MoeRouteBatch, - with_combine: bool, - with_lo: bool, slot: &[i32], ) -> Result<()> { + let Window { tokens, with_combine, with_lo, .. } = window; let captured = gemm.captured.borrow(); // router (hi [+ lo]), gate, up, down, scalar (hi [+ lo]) let expected_calls = 1 + usize::from(with_lo) + 3 + 1 + usize::from(with_lo); diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs index e51ca478..82295520 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs @@ -103,27 +103,30 @@ impl<'a> Products<'a> { pub(super) fn run_case( context: &Context<'_>, batch: &mut MoePrefillBatch<'_>, - tokens: usize, + window: Window, poison: Poison, - with_combine: bool, - with_lo: bool, - expect: Option, ) -> Result<()> { + let tokens = window.tokens; let fixture = Fixture::new(context, tokens, poison)?; let gemm = HostGemm { poison, captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; // A reversed permutation: the combine must follow the row map, not the identity. let slot: Vec = (0..(tokens * SELECTED) as i32).rev().collect(); - let window = Window { tokens, with_combine, with_lo, expect }; let result = run_window(batch, &fixture, &gemm, window, &slot); combine(result, fixture.release()) } /// Shape of one program run: its rows, the optional stages and the earliest refusal it must report. #[derive(Clone, Copy)] -struct Window { - tokens: usize, - with_combine: bool, - with_lo: bool, - expect: Option, +pub(super) struct Window { + pub(super) tokens: usize, + pub(super) with_combine: bool, + pub(super) with_lo: bool, + pub(super) expect: Option, +} +impl Window { + /// A window of `tokens` rows with the optional stages and the earliest refusal the run must report. + pub(super) fn new(tokens: usize, with_combine: bool, with_lo: bool, expect: Option) -> Self { + Self { tokens, with_combine, with_lo, expect } + } } fn run_window( batch: &mut MoePrefillBatch<'_>, @@ -150,7 +153,7 @@ fn run_window( }; } let route = route.map_err(|_| Error::InvalidDriverValue("clean window lost its route"))?; - check_clean(fixture, gemm, tokens, &route, with_combine, with_lo, slot) + check_clean(fixture, gemm, window, &route, slot) } fn enqueue_program<'l>( prefix: &mut MoeBatchPrefix<'l, '_>, diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/program_cases_fn.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/program_cases_fn.rs index de4a2b77..87ad0243 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/program_cases_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/program_cases_fn.rs @@ -15,16 +15,16 @@ pub(super) fn run_program_cases(context: &Context<'_>) -> Result<()> { } fn window_cases(context: &Context<'_>, batch: &mut MoePrefillBatch<'_>, clean: Poison) -> Result<()> { // Router only + shared, combine, lo passes, and the bounds of one window. - run_case(context, batch, 3, clean, true, false, None)?; - run_case(context, batch, 64, clean, false, false, None)?; - run_case(context, batch, 9, clean, true, true, None)?; - run_case(context, batch, 1, clean, true, false, None)?; + run_case(context, batch, Window::new(3, true, false, None), clean)?; + run_case(context, batch, Window::new(64, false, false, None), clean)?; + run_case(context, batch, Window::new(9, true, true, None), clean)?; + run_case(context, batch, Window::new(1, true, false, None), clean)?; // Earliest stage in program order wins and the owner stays usable. let logits_and_sg = Poison { logits: true, sg: true, ..clean }; - run_case(context, batch, 4, logits_and_sg, false, false, Some(MoeBatchStage::Logits))?; - run_case(context, batch, 4, Poison { sg: true, ..clean }, false, false, Some(MoeBatchStage::Sg))?; - run_case(context, batch, 4, Poison { dm: true, ..clean }, true, false, Some(MoeBatchStage::Bo))?; - run_case(context, batch, 3, clean, true, false, None) + run_case(context, batch, Window::new(4, false, false, Some(MoeBatchStage::Logits)), logits_and_sg)?; + run_case(context, batch, Window::new(4, false, false, Some(MoeBatchStage::Sg)), Poison { sg: true, ..clean })?; + run_case(context, batch, Window::new(4, true, false, Some(MoeBatchStage::Bo)), Poison { dm: true, ..clean })?; + run_case(context, batch, Window::new(3, true, false, None), clean) } /// Admission refusals leave nothing behind. fn admission_refusals(batch: &mut MoePrefillBatch<'_>, clean: Poison) -> Result<()> { diff --git a/crates/cuda-driver/src/mtp_dense_kv.rs b/crates/cuda-driver/src/mtp_dense_kv.rs index bd46513f..cd239fa5 100644 --- a/crates/cuda-driver/src/mtp_dense_kv.rs +++ b/crates/cuda-driver/src/mtp_dense_kv.rs @@ -179,12 +179,12 @@ pub use original_int8::MTP_ORIGINAL_WINDOW; pub(crate) use original_int8::session_assets_sealed; pub use original_int8::{ CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, MtpOriginalMixed, - MtpOriginalQuery, OriginalMtpSkippedPrefix, + MtpOriginalQuery, OriginalMtpSkipPrior, OriginalMtpSkippedPrefix, }; pub use original_int8::{ - CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, OriginalMtpPrefill, - OriginalMtpPrefillWeights, + CompletedDraftKv, CompressedEmbedding, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, + OriginalMtpPrefill, OriginalMtpPrefillWeights, }; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] diff --git a/crates/cuda-driver/src/mtp_original_int8.rs b/crates/cuda-driver/src/mtp_original_int8.rs index 022adc40..17efe65a 100644 --- a/crates/cuda-driver/src/mtp_original_int8.rs +++ b/crates/cuda-driver/src/mtp_original_int8.rs @@ -7,7 +7,7 @@ mod abi; #[path = "mtp_original_ring_state.rs"] mod ring_state; use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; -use abi::{Arg, Arguments, MappedOwner, Module}; +use abi::{Arg, Arguments, LaunchDims, MappedOwner, Module}; use std::{ cell::{Cell, Ref, RefCell, RefMut}, rc::Rc, @@ -57,7 +57,7 @@ pub struct MtpInt8OwnerId(Rc); #[path = "mtp_original_logical_prefix.rs"] mod logical_prefix; -pub use logical_prefix::OriginalMtpSkippedPrefix; +pub use logical_prefix::{OriginalMtpSkipPrior, OriginalMtpSkippedPrefix}; // The literal prefill producer is an MTP child because it borrows this // owner's private ring/state types. Its public contracts are re-exported by // the crate integration point below. @@ -65,7 +65,7 @@ pub use logical_prefix::OriginalMtpSkippedPrefix; mod prefill; pub(crate) use prefill::session_assets_sealed; pub use prefill::{ - CompletedDraftKv, CompletedOriginalMtpDraft, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, + CompletedDraftKv, CompletedOriginalMtpDraft, CompressedEmbedding, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpEmbedding, OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs index 182ff8b6..978a9b27 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs @@ -191,10 +191,10 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands: &mut Vec, asset: usize, index: usize, - grid: [u32; 3], - block: [u32; 3], + dims: LaunchDims, values: Vec, ) -> Result<()> { + let LaunchDims { grid, block } = dims; commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; commands.push(Command::Kernel { asset, index, grid, block, args: Arguments::new(values)? }); Ok(()) @@ -204,8 +204,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 0, 11, - [64, 1, 1], - [256, 1, 1], + LaunchDims { grid: [64, 1, 1], block: [256, 1, 1] }, vec![Arg::U64(a), Arg::I32(n as i32), Arg::U64(self.sub(10, status * 4, 4)?)], ) } diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs index b27525ad..dea21eb0 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs @@ -218,16 +218,14 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 0, 0, - [(rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], + LaunchDims { grid: [(rows * 2560).div_ceil(256) as u32, 1, 1], block: [256, 1, 1] }, vec![Arg::U64(mixed), Arg::U64(self.address(5)?), Arg::I32((rows * 2560) as i32)], )?; Self::push( commands, 0, 12, - [64, 1, 1], - [256, 1, 1], + LaunchDims { grid: [64, 1, 1], block: [256, 1, 1] }, vec![Arg::U64(self.address(5)?), Arg::I32((rows * 80) as i32), Arg::U64(self.sub(10, 4, 4)?)], ) } @@ -242,8 +240,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 0, rows, - [512, 1, 1], - [32, 4, 1], + LaunchDims { grid: [512, 1, 1], block: [32, 4, 1] }, vec![ Arg::U64(weight), Arg::U64(self.address(5)?), @@ -261,8 +258,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 0, 9, - [2, 1, 1], - [256, 1, 1], + LaunchDims { grid: [2, 1, 1], block: [256, 1, 1] }, vec![Arg::U64(k), Arg::U64(gamma), Arg::U64(k), Arg::I32(256), Arg::F32(1.0e-6)], )?; self.finite(commands, k, 512, 4 + 2 * t)?; @@ -270,8 +266,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 0, 10, - [1, 2, 1], - [128, 1, 1], + LaunchDims { grid: [1, 2, 1], block: [128, 1, 1] }, vec![ Arg::U64(k), Arg::U64(k), @@ -306,8 +301,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { &mut append, 1, 3, - [64, 1, 1], - [256, 1, 1], + LaunchDims { grid: [64, 1, 1], block: [256, 1, 1] }, vec![ Arg::U64(self.address(2)?), Arg::U64(self.address(3)?), @@ -323,8 +317,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { append, 1, 0, - [2, 4, 2], - [64, 1, 1], + LaunchDims { grid: [2, 4, 2], block: [64, 1, 1] }, vec![ Arg::U64(self.address(0)?), Arg::U64(self.address(1)?), diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs index dbb8dd90..d023082d 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs @@ -72,8 +72,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { &mut commands, 1, 2, - [8, 1, 1], - [256, 1, 1], + LaunchDims { grid: [8, 1, 1], block: [256, 1, 1] }, vec![Arg::U64(steps), Arg::I32(32768), Arg::U64(positions), Arg::I64(32768)], )?; let partials = self.partials()?; @@ -96,8 +95,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 2, 1, - [CHUNKS as u32, 2, 1], - [256, 1, 1], + LaunchDims { grid: [CHUNKS as u32, 2, 1], block: [256, 1, 1] }, vec![ Arg::U64(q), Arg::U64(a0), @@ -124,8 +122,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { commands, 2, 2, - [24, 1, 1], - [256, 1, 1], + LaunchDims { grid: [24, 1, 1], block: [256, 1, 1] }, vec![ Arg::U64(pa), Arg::U64(pm), diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi.rs b/crates/cuda-driver/src/mtp_original_int8_ffi.rs index 2680a28d..f3bedfb9 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi.rs @@ -12,6 +12,13 @@ pub(crate) struct Arguments { values: Box<[Arg]>, pointers: Vec<*mut c_void>, } +/// Grid and block shape of one kernel launch. +#[derive(Clone, Copy)] +pub(crate) struct LaunchDims { + pub(crate) grid: [u32; 3], + pub(crate) block: [u32; 3], +} + #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "mtp_original_int8_ffi/enabled.rs"] mod enabled; diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs b/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs index 5f30f545..8f15fdea 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs @@ -49,7 +49,12 @@ macro_rules! sym { unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } -type Dims = ([u32; 3], [u32; 3]); +/// Grid, block and dynamic shared memory of one launch. +#[derive(Clone, Copy)] +struct LaunchShape { + dims: LaunchDims, + shared: u32, +} fn open_libcuda() -> Library { // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and // null-checked next. @@ -173,10 +178,10 @@ impl Module { check_launch_geometry(grid, block, shared, stream)?; let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; rebuild_pointers(args); - self.launch_raw(f, (grid, block), shared, stream, args) + self.launch_raw(f, LaunchShape { dims: LaunchDims { grid, block }, shared }, stream, args) } - fn launch_raw(&self, f: usize, dims: Dims, shared: u32, stream: usize, args: &mut Arguments) -> Result<()> { - let (grid, block) = dims; + fn launch_raw(&self, f: usize, shape: LaunchShape, stream: usize, args: &mut Arguments) -> Result<()> { + let LaunchShape { dims: LaunchDims { grid, block }, shared } = shape; // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); // `stream` is a handle of a live stream owner that is synchronized before it is destroyed; every pointer // in `pointers` was rebuilt just above to point into the boxed, never-resized argument storage with the diff --git a/crates/cuda-driver/src/mtp_original_logical_prefix.rs b/crates/cuda-driver/src/mtp_original_logical_prefix.rs index 3a0807d6..e03548c0 100644 --- a/crates/cuda-driver/src/mtp_original_logical_prefix.rs +++ b/crates/cuda-driver/src/mtp_original_logical_prefix.rs @@ -13,6 +13,12 @@ pub struct OriginalMtpSkippedPrefix { first_needed: usize, lease: OriginalPromptLeaseIdentity, } +/// The prior state of a skip: the retained physical snapshot and the logical prefix already skipped, if any. +#[derive(Clone, Copy)] +pub struct OriginalMtpSkipPrior<'a> { + pub physical: &'a MtpInt8Snapshot, + pub logical: Option<&'a OriginalMtpSkippedPrefix>, +} impl OriginalMtpSkippedPrefix { /// `span` is the skipped `(start, logical_end)` cells and `prompt` the `(full_prompt_length, first_needed)` cutoff. fn new( @@ -80,11 +86,11 @@ impl MtpOriginalInt8<'_> { pub fn skip_original_prompt_prefix( &mut self, residual: &OriginalDeviceResidual<'_, '_, '_>, - physical_prior: &MtpInt8Snapshot, - logical_prior: Option<&OriginalMtpSkippedPrefix>, + prior: OriginalMtpSkipPrior<'_>, cell0: usize, full_prompt_length: usize, ) -> Result> { + let OriginalMtpSkipPrior { physical: physical_prior, logical: logical_prior } = prior; self.validate_snapshot(physical_prior)?; let end = self.check_skip_range(residual, cell0, full_prompt_length)?; let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64); diff --git a/crates/cuda-driver/src/mtp_original_prefill.rs b/crates/cuda-driver/src/mtp_original_prefill.rs index d2456f11..e17e6b62 100644 --- a/crates/cuda-driver/src/mtp_original_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill.rs @@ -8,7 +8,7 @@ use crate::{OriginalDeviceResidual, OriginalPromptRows}; #[allow(unsafe_code)] #[path = "mtp_original_prefill_ffi.rs"] mod prefill_abi; -use prefill_abi::{Arg as A, Arguments as Args, Module as Mod}; +use prefill_abi::{Arg as A, Arguments as Args, Geometry as PrefillGeometry, Module as Mod}; use std::ffi::CStr; const RESERVE_BYTES: usize = 128 << 20; const FLAG_WORDS: usize = 24; @@ -81,6 +81,15 @@ pub struct OriginalMtpEmbedding<'a, 'ctx> { table: &'a DeviceBuffer<'ctx>, kind: EmbeddingKind, } +/// The layout of a compressed embedding table: code width, bias, group size, vocabulary and whether offsets follow. +#[derive(Clone, Copy)] +pub struct CompressedEmbedding { + pub bits: i32, + pub bias: i32, + pub group: usize, + pub vocab: usize, + pub offsets: bool, +} enum EmbeddingKind { Native { kind: i32, row_bytes: usize, vocab: usize }, Compressed { bits: i32, bias: i32, group: usize, vocab: usize, codes: usize, scales: usize, offsets: bool }, diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs index 671c9c51..bf66de44 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs @@ -96,14 +96,8 @@ impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { } Ok(Self { table, kind: EmbeddingKind::Native { kind, row_bytes, vocab } }) } - pub fn compressed( - table: &'a DeviceBuffer<'ctx>, - bits: i32, - bias: i32, - group: usize, - vocab: usize, - offsets: bool, - ) -> Result { + pub fn compressed(table: &'a DeviceBuffer<'ctx>, layout: CompressedEmbedding) -> Result { + let CompressedEmbedding { bits, bias, group, vocab, offsets } = layout; if !matches!(bits, 2 | 4 | 8) || group == 0 || !2560usize.is_multiple_of(group) || vocab == 0 || vocab > 262144 { return Err(Error::InvalidProjectionShape); diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs index ada64a27..250293c8 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs @@ -3,19 +3,22 @@ #[allow(unused_imports)] use super::*; -#[path = "impl_originalmtpprefill/impl_originalmtpprefill_2.rs"] -mod impl_originalmtpprefill_2; -#[path = "impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs"] -mod impl_originalmtpprefill_2_2; -#[path = "impl_originalmtpprefill/impl_originalmtpprefill_3.rs"] -mod impl_originalmtpprefill_3; -#[path = "impl_originalmtpprefill/impl_originalmtpprefill_4.rs"] -mod impl_originalmtpprefill_4; +#[path = "impl_originalmtpprefill/block_commands.rs"] +mod block_commands; #[path = "impl_originalmtpprefill/impl_originalmtpprefill_5.rs"] mod impl_originalmtpprefill_5; -#[path = "impl_originalmtpprefill/impl_originalmtpprefill_6.rs"] -mod impl_originalmtpprefill_6; -#[path = "impl_originalmtpprefill/impl_originalmtpprefill_7.rs"] -mod impl_originalmtpprefill_7; +#[path = "impl_originalmtpprefill/kernel_commands.rs"] +mod kernel_commands; +#[path = "impl_originalmtpprefill/projection_commands.rs"] +mod projection_commands; +#[path = "impl_originalmtpprefill/record_operands.rs"] +mod record_operands; +#[path = "impl_originalmtpprefill/record_walk.rs"] +mod record_walk; +#[path = "impl_originalmtpprefill/run_and_settle.rs"] +mod run_and_settle; #[allow(unused_imports)] -use impl_originalmtpprefill_7::{Admit, Block, Call, GrBufs, PageRuns, Stage, Staged, WEIGHT_EXTENTS}; +use record_operands::{ + Admit, AppendBlock, Block, Call, GrBufs, KernelAt, KernelShape, PageRuns, ProjectionAddresses, ProjectionDims, + RecordRun, Stage, Staged, WEIGHT_EXTENTS, +}; diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/block_commands.rs similarity index 81% rename from crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs rename to crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/block_commands.rs index 0b1272f7..65a37a3f 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/block_commands.rs @@ -6,15 +6,8 @@ use super::*; impl<'ctx> OriginalMtpPrefill<'ctx> { /// `Self::kernel` for this program: no dynamic shared memory and `block` threads in x. - fn kernel1( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: u32, - args: Vec, - ) -> Result<()> { - Self::kernel(cmds, asset, index, grid, [block, 1, 1], 0, args) + fn kernel1(cmds: &mut Vec, at: KernelAt, grid: [u32; 3], block: u32, args: Vec) -> Result<()> { + Self::kernel(cmds, at, KernelShape { grid, block: [block, 1, 1], shared: 0 }, args) } fn gemm(x: BufferHandle, w: BufferHandle, y: BufferHandle, shape: [usize; 3]) -> Cmd { let [rows, n, k] = shape; @@ -63,7 +56,8 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { let (r, nb, wh) = (&blk.st.r, blk.nb, &blk.st.wh); let emb = self.embed_rows(cmds, blk, embedding)?; let e2 = r.address(1, nb * 10240)?; - self.project(cmds, r, emb, wh[1].qwen_address(), e2, nb, 2560, 0, 2)?; + let io = ProjectionAddresses { x: emb, w: wh[1].qwen_address(), y: e2 }; + self.project(cmds, r, io, ProjectionDims { rows: nb, out: 2560, bound_slot: 0, stage: 2 })?; self.finite(cmds, e2, nb * 2560, 2)?; Ok(e2) } @@ -75,13 +69,13 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { ) -> Result { let (r, nb, wh) = (&blk.st.r, blk.nb, &blk.st.wh); let iota = vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)]; - Self::kernel1(cmds, 0, 9, [(nb * 4).div_ceil(256) as u32, 1, 1], 256, iota)?; + Self::kernel1(cmds, KernelAt::new(0, 9), [(nb * 4).div_ceil(256) as u32, 1, 1], 256, iota)?; let emb = r.address(0, nb * 10240)?; let tok = r.address(16, nb * 4)?; Self::lookup(cmds, blk, &embedding.kind, (tok, emb))?; self.finite(cmds, emb, nb * 2560, 0)?; let norm = vec![A::U64(emb), A::U64(wh[0].qwen_address()), A::I64(2560), A::I64(2560), A::F32(1e-6)]; - Self::kernel1(cmds, 0, 0, [nb as u32, 1, 1], 256, norm)?; + Self::kernel1(cmds, KernelAt::new(0, 0), [nb as u32, 1, 1], 256, norm)?; self.finite(cmds, emb, nb * 2560, 1)?; Ok(emb) } @@ -105,14 +99,14 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { A::U64((2560 / group) as u64), A::U64(emb), ]; - Self::kernel1(cmds, 0, 5, [10, nb as u32, 1], 256, args) + Self::kernel1(cmds, KernelAt::new(0, 5), [10, nb as u32, 1], 256, args) } } } fn lookup_native(cmds: &mut Vec, nb: usize, format: (i32, usize), at: (u64, (u64, u64))) -> Result<()> { let ((kind, row_bytes), (eh, (tok, emb))) = (format, at); let args = vec![A::I32(kind), A::U64(eh), A::U64(row_bytes as u64), A::U64(tok), A::I64(2560), A::U64(emb)]; - Self::kernel1(cmds, 1, 0, [10, nb as u32, 1], 32, args) + Self::kernel1(cmds, KernelAt::new(1, 0), [10, nb as u32, 1], 32, args) } /// The hidden state of the main model: copied from the residual, normed and projected; returns the projection. fn hidden_phase(&self, cmds: &mut Vec, blk: &Block<'_>) -> Result { @@ -122,9 +116,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { let src = st.rh.checked_subspan(st.rbytes, blk.b0 * 40960, nb * 40960)?.qwen_address(); cmds.push(Cmd::Copy { dst: hn, src, bytes: nb * 40960 }); let norm = vec![A::U64(hn), A::U64(st.wh[2].qwen_address()), A::I64(10240), A::I64(10240), A::F32(1e-6)]; - Self::kernel1(cmds, 0, 0, [nb as u32, 1, 1], 256, norm)?; + Self::kernel1(cmds, KernelAt::new(0, 0), [nb as u32, 1, 1], 256, norm)?; self.finite(cmds, hn, nb * 10240, 3)?; - self.project(cmds, r, hn, st.wh[3].qwen_address(), h2, nb * 4, 2560, 1, 4)?; + let io = ProjectionAddresses { x: hn, w: st.wh[3].qwen_address(), y: h2 }; + self.project(cmds, r, io, ProjectionDims { rows: nb * 4, out: 2560, bound_slot: 1, stage: 4 })?; self.finite(cmds, h2, nb * 10240, 4)?; Ok(h2) } @@ -139,17 +134,17 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { fn gr_norm(&self, cmds: &mut Vec, blk: &Block<'_>, g: &GrBufs, hidden: (u64, u64)) -> Result<()> { let (nb, wh4) = (blk.nb, blk.st.wh[4].qwen_address()); let broadcast = vec![A::U64(hidden.0), A::U64(hidden.1), A::U64(g.rm), A::I64(2560), A::I32(4)]; - Self::kernel1(cmds, 0, 4, [40, nb as u32, 1], 256, broadcast)?; + Self::kernel1(cmds, KernelAt::new(0, 4), [40, nb as u32, 1], 256, broadcast)?; self.finite(cmds, g.rm, nb * 10240, 5)?; let norm = vec![A::U64(g.rm), A::U64(wh4), A::F32(1e-6), A::U64(g.grs), A::U64(g.xn), A::U64(0)]; - Self::kernel1(cmds, 0, 1, [(nb * 4) as u32, 1, 1], 256, norm)?; + Self::kernel1(cmds, KernelAt::new(0, 1), [(nb * 4) as u32, 1, 1], 256, norm)?; self.finite(cmds, g.grs, nb * 4, 6)?; let grid = [(nb * 10240).div_ceil(256) as u32, 1, 1]; let scan = vec![A::U64(g.rm), A::U64(g.grs), A::U64(wh4), A::U64(self.status(6)?.qwen_address()), A::I64(nb as i64)]; - Self::kernel1(cmds, 0, 12, grid, 256, scan)?; + Self::kernel1(cmds, KernelAt::new(0, 12), grid, 256, scan)?; let args = vec![A::U64(g.xn), A::I32((nb * 10240) as i32), A::U64(self.status(6)?.qwen_address())]; - Self::kernel1(cmds, 0, 14, grid, 256, args) + Self::kernel1(cmds, KernelAt::new(0, 14), grid, 256, args) } fn gr_down(&self, cmds: &mut Vec, blk: &Block<'_>, g: &GrBufs) -> Result<()> { let (r, nb) = (&blk.st.r, blk.nb); @@ -157,11 +152,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { self.finite(cmds, g.lo, nb * 320, 7)?; let grid = [(nb * 320).div_ceil(256) as u32, 1, 1]; let round = vec![A::U64(g.lo), A::U64(g.lo16), A::U64(0), A::I64((nb * 320) as i64)]; - Self::kernel1(cmds, 0, 2, grid, 256, round)?; + Self::kernel1(cmds, KernelAt::new(0, 2), grid, 256, round)?; let scan = vec![A::U64(g.lo), A::U64(self.status(8)?.qwen_address()), A::I64(nb as i64)]; - Self::kernel1(cmds, 0, 13, grid, 256, scan)?; + Self::kernel1(cmds, KernelAt::new(0, 13), grid, 256, scan)?; let args = vec![A::U64(g.lo16), A::I32((nb * 320) as i32), A::U64(self.status(8)?.qwen_address())]; - Self::kernel1(cmds, 0, 14, grid, 256, args) + Self::kernel1(cmds, KernelAt::new(0, 14), grid, 256, args) } fn gr_up(&self, cmds: &mut Vec, blk: &Block<'_>, g: &GrBufs) -> Result<()> { let (r, nb, wh4) = (&blk.st.r, blk.nb, blk.st.wh[4].qwen_address()); @@ -178,11 +173,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { A::U64(g.mixedh), A::U64(0), ]; - Self::kernel1(cmds, 0, 3, [(nb * 2560).div_ceil(256) as u32, 1, 1], 256, mix)?; + Self::kernel1(cmds, KernelAt::new(0, 3), [(nb * 2560).div_ceil(256) as u32, 1, 1], 256, mix)?; let grid = [(nb * 10240).div_ceil(256) as u32, 1, 1]; let status = A::U64(self.status(10)?.qwen_address()); let scan = vec![A::U64(g.rm), A::U64(g.grs), A::U64(wh4), A::U64(g.gated), status, A::I64(nb as i64)]; - Self::kernel1(cmds, 0, 15, grid, 256, scan)?; + Self::kernel1(cmds, KernelAt::new(0, 15), grid, 256, scan)?; self.finite(cmds, g.mixed, nb * 2560, 10) } /// K and V projections of the mixed state, K norm and rope; returns their addresses. @@ -190,9 +185,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { let (r, nb, wh) = (&blk.st.r, blk.nb, &blk.st.wh); let kc = r.address(14, nb * 2048)?; let vc = r.address(15, nb * 2048)?; - self.project(cmds, r, mixed, wh[7].qwen_address(), kc, nb, 512, 0, 11)?; + let io = ProjectionAddresses { x: mixed, w: wh[7].qwen_address(), y: kc }; + self.project(cmds, r, io, ProjectionDims { rows: nb, out: 512, bound_slot: 0, stage: 11 })?; self.finite(cmds, kc, nb * 512, 11)?; - self.project(cmds, r, mixed, wh[8].qwen_address(), vc, nb, 512, 0, 12)?; + let io = ProjectionAddresses { x: mixed, w: wh[8].qwen_address(), y: vc }; + self.project(cmds, r, io, ProjectionDims { rows: nb, out: 512, bound_slot: 0, stage: 12 })?; self.finite(cmds, vc, nb * 512, 12)?; self.k_norm_rope(cmds, blk, kc, policy)?; Ok((kc, vc)) @@ -200,7 +197,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { fn k_norm_rope(&self, cmds: &mut Vec, blk: &Block<'_>, kc: u64, policy: &DraftKvPolicy) -> Result<()> { let nb = blk.nb; let norm = vec![A::U64(kc), A::U64(blk.st.wh[9].qwen_address()), A::I64(256), A::I64(256), A::F32(1e-6)]; - Self::kernel1(cmds, 0, 0, [(nb * 2) as u32, 1, 1], 256, norm)?; + Self::kernel1(cmds, KernelAt::new(0, 0), [(nb * 2) as u32, 1, 1], 256, norm)?; self.finite(cmds, kc, nb * 512, 13)?; let rope = vec![ A::U64(kc), @@ -217,7 +214,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { A::U64(0), A::Words3([0; 3]), ]; - Self::kernel1(cmds, 0, 6, [(nb * 2) as u32, 1, 1], 32, rope)?; + Self::kernel1(cmds, KernelAt::new(0, 6), [(nb * 2) as u32, 1, 1], 32, rope)?; self.finite(cmds, kc, nb * 512, 14) } /// Appends the block's K and V to the real drafter KV ring and runs the append kernels. @@ -226,9 +223,9 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { rows: &mut OriginalPromptRows<'_, '_, '_>, workspace: &mut NativeBatchWorkspace<'ctx>, ring: &MtpOriginalInt8<'ctx>, - blk: &Block<'_>, - kv: (u64, u64), + appended: AppendBlock<'_>, ) -> Result<()> { + let AppendBlock { blk, kv } = appended; let mapped = ring.mapped()?; let mut host = [0u64; 8]; for (i, n) in HOST_RUNS.into_iter().enumerate() { @@ -248,7 +245,12 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { ) -> Result<()> { let (kv, ra, host) = operands; let args = Self::append_args(blk, kv, ra, host); - Self::kernel(append, 0, 7, [blk.nb as u32, 2, 8], [64, 1, 1], 0, args)?; + Self::kernel( + append, + KernelAt::new(0, 7), + KernelShape { grid: [blk.nb as u32, 2, 8], block: [64, 1, 1], shared: 0 }, + args, + )?; let status = self.status(15)?.qwen_address(); let commit = vec![ A::U64(ra[2]), @@ -258,7 +260,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { A::I32(blk.nb as i32), A::U64(status), ]; - Self::kernel1(append, 0, 10, [64, 1, 1], 256, commit) + Self::kernel1(append, KernelAt::new(0, 10), [64, 1, 1], 256, commit) } fn ring_addresses(ring: &MtpOriginalInt8<'ctx>) -> Result<[u64; 5]> { Ok([ring.address(0)?, ring.address(1)?, ring.address(2)?, ring.address(3)?, ring.address(4)?]) diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/kernel_commands.rs similarity index 94% rename from crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs rename to crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/kernel_commands.rs index a053a07f..449d9e28 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/kernel_commands.rs @@ -92,15 +92,9 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, i * 4, 4) } - pub(in super::super) fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { + pub(in super::super) fn kernel(cmds: &mut Vec, at: KernelAt, shape: KernelShape, args: Vec) -> Result<()> { + let KernelAt { asset, index } = at; + let KernelShape { grid, block, shared } = shape; cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; cmds.push(Cmd::Kernel { asset, index, grid, block, shared, args: Args::new(args)? }); Ok(()) @@ -108,11 +102,8 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { pub(in super::super) fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { Self::kernel( cmds, - 0, - 8, - [(words.div_ceil(256)) as u32, 1, 1], - [256, 1, 1], - 0, + KernelAt::new(0, 8), + KernelShape { grid: [(words.div_ceil(256)) as u32, 1, 1], block: [256, 1, 1], shared: 0 }, vec![A::U64(data), A::I32(words as i32), A::U64(self.status(stage)?.qwen_address())], ) } diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/projection_commands.rs similarity index 86% rename from crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs rename to crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/projection_commands.rs index b791f69d..a5f19a04 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/projection_commands.rs @@ -4,19 +4,15 @@ use super::*; impl<'ctx> OriginalMtpPrefill<'ctx> { - #[allow(clippy::too_many_arguments)] pub(in super::super) fn project( &self, cmds: &mut Vec, r: &Region, - x: u64, - w: u64, - y: u64, - rows: usize, - out: usize, - bound_slot: usize, - stage: usize, + io: ProjectionAddresses, + dims: ProjectionDims, ) -> Result<()> { + let ProjectionAddresses { x, w, y } = io; + let ProjectionDims { rows, out, bound_slot, stage } = dims; if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { return Err(Error::InvalidProjectionShape); } @@ -89,11 +85,8 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { fn project_quantize(&self, cmds: &mut Vec, (x, xq): (u64, u64), rows: usize, stage: usize) -> Result<()> { Self::kernel( cmds, - 2, - 0, - [rows as u32, 5, 1], - [128, 1, 1], - 0, + KernelAt::new(2, 0), + KernelShape { grid: [rows as u32, 5, 1], block: [128, 1, 1], shared: 0 }, vec![ A::U64(x), A::U64(0), @@ -116,20 +109,14 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { // tail before a literal vendor kernel can speculatively load it. Self::kernel( cmds, - 0, - 11, - [72, 1, 1], - [256, 1, 1], - 0, + KernelAt::new(0, 11), + KernelShape { grid: [72, 1, 1], block: [256, 1, 1], shared: 0 }, vec![A::U64(xq + (rows * 20 * 144) as u64), A::I32((128 * 144) as i32)], )?; Self::kernel( cmds, - 0, - 16, - [(rows * 20).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, + KernelAt::new(0, 16), + KernelShape { grid: [(rows * 20).div_ceil(256) as u32, 1, 1], block: [256, 1, 1], shared: 0 }, vec![A::U64(xq), A::I32((rows * 20) as i32), A::U64(self.status(stage)?.qwen_address())], ) } @@ -163,7 +150,12 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { args.extend([A::I32(out as i32), A::I32(rows as i32), A::I32(80), A::I32(rows as i32), A::I32(out as i32)]); args.extend([A::U3(fd(1)), A::U3(fd(1)), A::I32((out * 80) as i32), A::I32(0), A::I32(0), A::U3(fd(1))]); args.extend([A::U3(fd(1)), A::I32(0), A::I32(0), A::I32(0), A::U3(fd(ntx as u32))]); - Self::kernel(cmds, 3, index, [grid as u32, 1, 1], [32, 8, 1], shared as u32, args) + Self::kernel( + cmds, + KernelAt::new(3, index), + KernelShape { grid: [grid as u32, 1, 1], block: [32, 8, 1], shared: shared as u32 }, + args, + ) } fn project_fixup( @@ -177,6 +169,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { args.extend([A::U64(ids), A::U64(bound), A::U64(y), A::U64(tmp), A::U3(fd(80)), A::I32(out as i32)]); args.extend([A::I32(rows as i32), A::I32(out as i32), A::U3(fd(1)), A::I32(0), A::U3(fd(1)), A::I32(0)]); args.push(A::U3(fd(ntx as u32))); - Self::kernel(cmds, 4, index, [grid as u32, 4, 1], [32, 4, 1], 0, args) + Self::kernel( + cmds, + KernelAt::new(4, index), + KernelShape { grid: [grid as u32, 4, 1], block: [32, 4, 1], shared: 0 }, + args, + ) } } diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/record_operands.rs similarity index 64% rename from crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs rename to crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/record_operands.rs index 005702c4..a4847742 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/record_operands.rs @@ -21,7 +21,8 @@ pub(in super::super) const WEIGHT_EXTENTS: [usize; 10] = [ 1024, ]; -/// What the caller of `record` supplies besides the buffers. +/// What the caller of `record` supplies besides the buffers: the prior snapshot, the tokens, the cells, the policy, +/// and the weights and embedding table. #[derive(Clone, Copy)] pub(in super::super) struct Call<'a> { pub(in super::super) prior: &'a MtpInt8Snapshot, @@ -29,6 +30,59 @@ pub(in super::super) struct Call<'a> { pub(in super::super) cell0: usize, pub(in super::super) first_needed: usize, pub(in super::super) policy: &'a DraftKvPolicy, + pub(in super::super) weights: &'a OriginalMtpPrefillWeights<'a, 'a>, + pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'a>, +} + +/// The workspace and ring one `record` walk mutates, with its cancellation poll. +pub(in super::super) struct RecordRun<'a, 'ctx, C> { + pub(in super::super) workspace: &'a mut NativeBatchWorkspace<'ctx>, + pub(in super::super) ring: &'a mut MtpOriginalInt8<'ctx>, + pub(in super::super) cancelled: &'a mut C, +} + +/// A block and the addresses of its computed K and V. +pub(in super::super) struct AppendBlock<'a> { + pub(in super::super) blk: &'a Block<'a>, + pub(in super::super) kv: (u64, u64), +} + +/// A kernel of the program: its asset (module) and entry index. +#[derive(Clone, Copy)] +pub(in super::super) struct KernelAt { + pub(in super::super) asset: usize, + pub(in super::super) index: usize, +} +impl KernelAt { + /// The kernel `index` of module `asset`. + pub(in super::super) const fn new(asset: usize, index: usize) -> Self { + Self { asset, index } + } +} + +/// The launch shape of a kernel: grid, block and dynamic shared memory. +#[derive(Clone, Copy)] +pub(in super::super) struct KernelShape { + pub(in super::super) grid: [u32; 3], + pub(in super::super) block: [u32; 3], + pub(in super::super) shared: u32, +} + +/// The device addresses of one projection: the activation, the weight and the output. +#[derive(Clone, Copy)] +pub(in super::super) struct ProjectionAddresses { + pub(in super::super) x: u64, + pub(in super::super) w: u64, + pub(in super::super) y: u64, +} + +/// The shape of one projection: its rows and output width, the expert-bound slot and the finite-status stage. +#[derive(Clone, Copy)] +pub(in super::super) struct ProjectionDims { + pub(in super::super) rows: usize, + pub(in super::super) out: usize, + pub(in super::super) bound_slot: usize, + pub(in super::super) stage: usize, } /// The outcome of the checks that precede any device work: run from row `r0`, or finish with an outcome. diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/record_walk.rs similarity index 88% rename from crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs rename to crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/record_walk.rs index 1700cee3..716a4751 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/record_walk.rs @@ -1,5 +1,5 @@ //! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (4). `record` admits the call, stages the -//! weights and walks the blocks; the commands of one block are recorded in `impl_originalmtpprefill_6.rs`. +//! weights and walks the blocks; the commands of one block are recorded in `block_commands.rs`. #[allow(unused_imports)] use super::*; @@ -36,29 +36,26 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { policy: &DraftKvPolicy, mut cancelled: impl FnMut() -> bool, ) -> Result { - let call = Call { prior, tokens, cell0, first_needed, policy }; - self.record_call(residual, workspace, ring, &call, (&weights, &embedding), &mut cancelled) + let call = Call { prior, tokens, cell0, first_needed, policy, weights: &weights, embedding: &embedding }; + self.record_call(residual, RecordRun { workspace, ring, cancelled: &mut cancelled }, &call) } fn record_call( &mut self, residual: &mut OriginalDeviceResidual<'_, '_, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, + lane: RecordRun<'_, 'ctx, impl FnMut() -> bool>, call: &Call<'_>, - operands: (&OriginalMtpPrefillWeights<'_, '_>, &OriginalMtpEmbedding<'_, '_>), - cancelled: &mut impl FnMut() -> bool, ) -> Result { - let (weights, embedding) = operands; - let r0 = match self.admit(residual, workspace, ring, call, embedding)? { + let RecordRun { workspace, ring, cancelled } = lane; + let r0 = match self.admit(residual, workspace, ring, call)? { Admit::Run(r0) => r0, Admit::Done(outcome) => return Ok(outcome), }; let rows = residual.lease_mut(); - let staged = match self.stage(rows, workspace, ring, (call, r0), (weights, embedding))? { + let staged = match self.stage(rows, workspace, ring, (call, r0))? { Stage::Ready(staged) => staged, Stage::Done(outcome) => return Ok(outcome), }; - self.record_blocks(rows, workspace, ring, call, (&staged, embedding), cancelled) + self.record_blocks(rows, RecordRun { workspace, ring, cancelled }, call, &staged) } /// The fallbacks and refusals that precede any device work. fn admit( @@ -67,13 +64,12 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { workspace: &NativeBatchWorkspace<'ctx>, ring: &MtpOriginalInt8<'ctx>, call: &Call<'_>, - embedding: &OriginalMtpEmbedding<'_, '_>, ) -> Result { if let Some(fallback) = Self::fallback_for(call.policy, call.tokens) { return Ok(Admit::Done(DraftKvOutcome::Fallback(fallback))); } Self::reject_bad_rope(call.policy)?; - self.validate_inputs(residual, workspace, ring, call, embedding)?; + self.validate_inputs(residual, workspace, ring, call)?; let r0 = call.first_needed.saturating_sub(call.cell0); if r0 >= call.tokens.len() { return Ok(Admit::Done(DraftKvOutcome::Skipped)); @@ -115,8 +111,8 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { workspace: &NativeBatchWorkspace<'ctx>, ring: &MtpOriginalInt8<'ctx>, call: &Call<'_>, - embedding: &OriginalMtpEmbedding<'_, '_>, ) -> Result<()> { + let embedding = call.embedding; ring.validate_snapshot(call.prior)?; workspace.validate_context(self.context)?; ring.validate_context(self.context)?; @@ -147,9 +143,9 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { workspace: &NativeBatchWorkspace<'ctx>, ring: &MtpOriginalInt8<'ctx>, first: (&Call<'_>, usize), - operands: (&OriginalMtpPrefillWeights<'_, '_>, &OriginalMtpEmbedding<'_, '_>), ) -> Result { - let ((call, r0), (weights, embedding)) = (first, operands); + let (call, r0) = first; + let embedding = call.embedding; let (region, region_bytes) = rows.draft_kv_region()?; let Some(r) = Region::new(region, region_bytes, call.tokens.len(), r0)? else { return Ok(Stage::Done(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall))); @@ -158,8 +154,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { if !self.has_q8_tile() { return Ok(Stage::Done(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile))); } - let refs = weight_refs(weights); - let (wh, eh) = self.stage_operands(rows, workspace, &refs, embedding, region)?; + let (wh, eh) = self.stage_operands(rows, workspace, call, region)?; let (rh, rbytes) = Self::input_span(rows, region, region_bytes)?; let staged = Staged { r, r0, wh, eh, rh, rbytes, table_bytes: embedding.table.bytes }; staged.check_ring(ring, region, region_bytes)?; @@ -170,10 +165,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { &self, rows: &OriginalPromptRows<'_, '_, '_>, workspace: &NativeBatchWorkspace<'ctx>, - refs: &[&DeviceBuffer<'_>; 10], - embedding: &OriginalMtpEmbedding<'_, '_>, + call: &Call<'_>, region: BufferHandle, ) -> Result<([BufferHandle; 10], BufferHandle)> { + let (refs, embedding) = (&weight_refs(call.weights), call.embedding); let mut wh = [region; 10]; for i in 0..10 { wh[i] = self.weight(rows, workspace, refs[i], WEIGHT_EXTENTS[i]).map_err(|e| { @@ -244,13 +239,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { fn record_blocks( &mut self, rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, + lane: RecordRun<'_, 'ctx, impl FnMut() -> bool>, call: &Call<'_>, - operands: (&Staged, &OriginalMtpEmbedding<'_, '_>), - cancelled: &mut impl FnMut() -> bool, + staged: &Staged, ) -> Result { - let (staged, embedding) = operands; + let RecordRun { workspace, ring, cancelled } = lane; let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let (end, first) = (call.cell0 + call.tokens.len(), call.cell0 + staged.r0); let first_page = first / 4; @@ -259,7 +252,8 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { return Ok(DraftKvOutcome::Cancelled); } Self::restore_ring(workspace, ring, call.prior)?; - if let Some(outcome) = self.record_each(rows, workspace, ring, call, (staged, embedding), cancelled)? { + let each = RecordRun { workspace: &mut *workspace, ring: &mut *ring, cancelled: &mut *cancelled }; + if let Some(outcome) = self.record_each(rows, each, call, staged)? { return Ok(outcome); } Self::read_back(ring, &mut changed, first_page)?; @@ -268,13 +262,12 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { fn record_each( &mut self, rows: &mut OriginalPromptRows<'_, '_, '_>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, + lane: RecordRun<'_, 'ctx, impl FnMut() -> bool>, call: &Call<'_>, - operands: (&Staged, &OriginalMtpEmbedding<'_, '_>), - cancelled: &mut impl FnMut() -> bool, + staged: &Staged, ) -> Result> { - let (staged, embedding) = operands; + let RecordRun { workspace, ring, cancelled } = lane; + let embedding = call.embedding; let len = call.tokens.len(); for b0 in (staged.r0..len).step_by(staged.r.b) { let blk = Block { st: staged, nb: staged.r.b.min(len - b0), b0, c0: call.cell0 + b0 }; @@ -286,7 +279,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { if cancelled() { return Ok(Some(DraftKvOutcome::Cancelled)); } - self.append_block(rows, workspace, ring, &blk, (kc, vc))?; + self.append_block(rows, workspace, ring, AppendBlock { blk: &blk, kv: (kc, vc) })?; if cancelled() { return Ok(Some(DraftKvOutcome::Cancelled)); } diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/run_and_settle.rs similarity index 88% rename from crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs rename to crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/run_and_settle.rs index cffcdd32..f908a803 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/run_and_settle.rs @@ -5,6 +5,12 @@ use super::*; use crate::CurrentGuard; use crate::ple_batch_ffi::Blas; +/// The device status words and the host image they are read back into. +struct StatusRead<'a> { + status: BufferHandle, + readback: &'a mut [u8], +} + impl<'ctx> OriginalMtpPrefill<'ctx> { pub(in super::super) fn run( &mut self, @@ -21,7 +27,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { Err(e) => return Err(self.run_error(rows, w, e)), }; let operation = self.execute(status, &mut job, blas); - let settled = self.settle(g, blas, operation, status, &mut job.readback); + let settled = self.settle(g, blas, operation, StatusRead { status, readback: &mut job.readback }); if settled.failed() { self.mark_run_failed(rows, w); } @@ -69,9 +75,13 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } fn launch_cmd(&self, blas: &Blas, c: &mut Cmd) -> Result<()> { match c { - Cmd::Kernel { asset, index, grid, block, shared, args } => self.modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| m.launch(*index, *grid, *block, *shared, blas.stream(), args)), + Cmd::Kernel { asset, index, grid, block, shared, args } => { + self.modules[*asset].as_ref().map_or(Err(Error::ContextPoisoned), |m| { + let geometry = + PrefillGeometry { grid: *grid, block: *block, shared: *shared, stream: blas.stream() }; + m.launch(*index, geometry, args) + }) + } Cmd::Copy { dst, src, bytes } => self.modules[0] .as_ref() .map_or(Err(Error::ContextPoisoned), |m| m.copy(*dst, *src, *bytes, blas.stream())), @@ -83,9 +93,9 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { g: CurrentGuard<'_, '_>, blas: &Blas, mut operation: Result<()>, - status: BufferHandle, - readback: &mut [u8], + words: StatusRead<'_>, ) -> Settled { + let StatusRead { status, readback } = words; let stream = blas.synchronize(); if operation.is_ok() && stream.is_ok() { operation = self.context.driver.api.copy_to(status, readback); diff --git a/crates/cuda-driver/src/mtp_original_prefill_ffi.rs b/crates/cuda-driver/src/mtp_original_prefill_ffi.rs index c26e49d1..e0d2e71d 100644 --- a/crates/cuda-driver/src/mtp_original_prefill_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_prefill_ffi.rs @@ -22,6 +22,14 @@ impl Arguments { Ok(Self { values: values.into_boxed_slice(), pointers }) } } +/// Launch geometry as the caller supplied it; `validate` admits only the fixed shapes of the sealed kernels. +#[derive(Clone, Copy)] +pub(crate) struct Geometry { + pub(crate) grid: [u32; 3], + pub(crate) block: [u32; 3], + pub(crate) shared: u32, + pub(crate) stream: usize, +} impl Arguments { /// Rebuilds the pointer table over the boxed, never-resized argument storage. #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] @@ -92,14 +100,6 @@ mod enabled { unsafe { std::mem::transmute::<*mut c_void, $t>(p) } }}; } - /// Launch geometry as the caller supplied it; `validate` admits only the fixed shapes of the sealed kernels. - #[derive(Clone, Copy)] - struct Geometry { - grid: [u32; 3], - block: [u32; 3], - shared: u32, - stream: usize, - } impl Geometry { fn validate(&self) -> Result<()> { if self.grid.contains(&0) || !block_ok(self.block) || !shared_ok(self.shared) || self.stream == 0 { @@ -229,20 +229,11 @@ mod enabled { } Ok((crate::arch_ptx::forced_sms(sms as u32) as usize, shared as u32)) } - pub(crate) fn launch( - &self, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - stream: usize, - args: &mut Arguments, - ) -> Result<()> { - let geometry = Geometry { grid, block, shared, stream }; + pub(crate) fn launch(&self, index: usize, geometry: Geometry, args: &mut Arguments) -> Result<()> { geometry.validate()?; let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; args.fill_pointers(); - self.set_shared(f, shared)?; + self.set_shared(f, geometry.shared)?; self.submit(f, &geometry, args) } fn set_shared(&self, f: usize, shared: u32) -> Result<()> { @@ -334,7 +325,7 @@ impl Module { pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: Geometry, _: &mut Arguments) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> { diff --git a/crates/cuda-driver/src/mtp_original_scalar_weights.rs b/crates/cuda-driver/src/mtp_original_scalar_weights.rs index b75597ff..5ab78c6c 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_weights.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_weights.rs @@ -124,9 +124,10 @@ impl<'ctx> OriginalMtpRetainedScalarWeights<'ctx> { RetainedEmbedding::Native { i, row_bytes, vocab } => { OriginalMtpEmbedding::native(&self.embedding, i, row_bytes, vocab)? } - RetainedEmbedding::Compressed { bits, bias, group, vocab, offsets } => { - OriginalMtpEmbedding::compressed(&self.embedding, bits, bias, group, vocab, offsets)? - } + RetainedEmbedding::Compressed { bits, bias, group, vocab, offsets } => OriginalMtpEmbedding::compressed( + &self.embedding, + crate::CompressedEmbedding { bits, bias, group, vocab, offsets }, + )?, }; Ok((OriginalMtpScalarWeights { input, gr_inject: &r[10] }, embedding)) } diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs index 06ccfa2b..998e19ad 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/run_phases.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; use crate::CurrentGuard; +use crate::deferred_status::DeferredStatusCheck; use crate::ple_batch_ffi::Blas; /// The host buffers a run owns until the vendor stream and readback drain; leaked on an uncertain drain. @@ -110,14 +111,14 @@ impl<'ctx> OriginalPromptDevice<'ctx> { &mut self, (lease, workspace): (&mut OriginalPromptRows<'_, '_, '_>, &mut NativeBatchWorkspace<'ctx>), (guard, op, buffers): (CurrentGuard<'ctx, 'ctx>, Result<()>, RunBuffers), - (spec, order, labels): (StatusSpec, &[usize], &[&'static str]), + ((status, status_bytes, stride), order, labels): (StatusSpec, &[usize], &[&'static str]), ) -> Result<()> { - let (status, status_bytes, stride) = spec; // a poisoned workspace is a queueing failure like any other: the guard is popped and the buffers are kept let stream = workspace.blas().map(|blas| blas.stream()); let queued = match (op, stream) { (Ok(()), Ok(stream)) => { - crate::deferred_status::finish(self.context, status, status_bytes, stream, stride, order, labels) + let spec = DeferredStatusCheck { status, bytes: status_bytes, stride, order, labels }; + crate::deferred_status::finish(self.context, stream, spec) } (Err(error), _) | (Ok(()), Err(error)) => Err(error), }; diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs index 76600880..196bf38a 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs @@ -41,7 +41,11 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo self.upload_slot_table()?; let mut program = workspace.prepare_original_expert_layer_device(&self.read, &self.counts, &self.source_rows)?; - program.execute_original_copy_ring(&self.read, layer, schedule, bank, formats, sources)?; + program.execute_original_copy_ring( + &self.read, + schedule, + crate::RingExperts { layer, bank, formats, sources }, + )?; program.finish()?; self.completed_experts = self.order.len(); Ok(()) @@ -187,7 +191,8 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo } let mut program = workspace.prepare_original_expert_layer_device(&self.read, &self.counts, &self.source_rows)?; - program.execute_original_stream_all(&self.read, forward, layer, &self.order, formats, host_allowance)?; + let layer = crate::OriginalStreamAllLayer { layer, experts: &self.order, formats }; + program.execute_original_stream_all(&self.read, forward, layer, host_allowance)?; program.finish()?; self.completed_experts = self.order.len(); Ok(()) diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs index 6de3b0bc..43b62358 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs @@ -48,7 +48,12 @@ impl Old<'_> { self.context .driver .api - .launch_gdn_native(self.funcs.get(kernel), GdnStream::from_raw(self.stream), grid, block, &mut args) + .launch_gdn_native( + self.funcs.get(kernel), + GdnStream::from_raw(self.stream), + crate::GdnGeometry { grid, block }, + &mut args, + ) .expect("launch"); } self.context.driver.api.synchronize().expect("sync"); diff --git a/crates/cuda-driver/src/root_exports.rs b/crates/cuda-driver/src/root_exports.rs index e44b672d..5a885338 100644 --- a/crates/cuda-driver/src/root_exports.rs +++ b/crates/cuda-driver/src/root_exports.rs @@ -7,10 +7,11 @@ pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats}; pub use gdn_state_finite_guard::GdnStateFiniteGuard; pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace}; pub use mmq::resident::original_group::{ - OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes, + OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, OriginalStreamAllLayer, RingExperts, + original_mmq_group_bank_bytes, }; pub use mmq::resident::{FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace}; -pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqWeights}; +pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqRequest, MmqWeights}; pub use mtp_dense_kv::MTP_ORIGINAL_WINDOW; pub use mtp_dense_kv::MtpDenseKvRing; pub use mtp_dense_kv::{ @@ -58,34 +59,40 @@ pub use serving_context::{ #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::batch_gr_preview::GrBatchModule; +pub use qwen_dispatch::batch_gr_preview::{GrInjectBuffers, GrNormBuffers}; pub use qwen_dispatch::qwen_shared_tail::{ SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailCompletion, SharedTailRefusal, }; // Additive closed MTP input transport owners. -pub use qwen_dispatch::gdn_closed_queue::{GdnQueueStage, GdnRowCompletion, GdnRowPrefix, GdnRowQueue}; +pub use qwen_dispatch::gdn_closed_queue::{ + GdnConvBuffers, GdnOutNormBuffers, GdnQueueStage, GdnRecurrenceBuffers, GdnRowCompletion, GdnRowPrefix, GdnRowQueue, +}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::gdn_fused_t1::{ - GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnFusedCompletion, GdnFusedPrefix, GdnFusedStage, - GdnFusedT1, + GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnAbBuffers, GdnFusedCompletion, GdnFusedPrefix, + GdnFusedStage, GdnFusedT1, GdnReplayBuffers, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] +pub(crate) use qwen_dispatch::gdn_native_batch::GdnGeometry; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::gdn_native_batch::{ GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, GdnGemm, - GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, OriginalGdnPromptWeights, + GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, OriginalGdnPromptState, + OriginalGdnPromptWeights, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::moe_prefill_batch::{ - MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix, MoeBatchStage, MoePrefillBatch, - MoeRouteBatch, + MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix, MoeBatchStage, MoeCombineInputs, + MoePrefillBatch, MoeRouteBatch, }; pub use qwen_dispatch::mtp_input_workspace::{MtpInputCompletion, MtpInputPrefix, MtpInputRefusal, MtpInputWorkspace}; pub use async_owned_copy::{CompletedOwnedCopy, MAX_ASYNC_COPY_PAIRS, OwnedCopyPairs, OwnedCopyPoll, PendingOwnedCopy}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::gr_batch_inject_workspace::{ - GR_BATCH_INJECT_WORKSPACE_BYTES, GrBatchInjectShape, GrBatchInjectWorkspace, + GR_BATCH_INJECT_WORKSPACE_BYTES, GrBatchInjectShape, GrBatchInjectWorkspace, GrInjectInputs, }; pub use routed_resident_queue::{ RoutedResidentCompletion, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights, @@ -154,11 +161,9 @@ pub use qsa_prompt_kv::{ OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport, }; -#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -pub use mtp_dense_kv::OriginalMtpSkippedPrefix; pub use mtp_dense_kv::{ - CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, OriginalMtpPrefill, - OriginalMtpPrefillWeights, + CompletedDraftKv, CompressedEmbedding, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, + OriginalMtpPrefill, OriginalMtpPrefillWeights, }; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use mtp_dense_kv::{ @@ -167,6 +172,8 @@ pub use mtp_dense_kv::{ OriginalMtpStepOutput, }; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub use mtp_dense_kv::{OriginalMtpSkipPrior, OriginalMtpSkippedPrefix}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use native_parity::{ NativeParity, NativeParityExpert, native_parity_embed_supported, native_parity_iq_supported, native_parity_row_bytes, @@ -209,6 +216,8 @@ pub use original_verify::{ OriginalVerifyRow, OriginalVerifySpan, OriginalVerifyWindow, OriginalVerifyWindowResult, }; // Live verifier release/diagnostic owner, profile report and completed-logit readout. +#[allow(unused_imports)] +pub use impl_context_2::MatvecDims; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[allow(unused_imports)] pub use impl_devicebuffer::chain_selects_mtp; @@ -226,6 +235,7 @@ pub use impl_devicebuffer::chain_selects_mtp; )))] #[allow(unused_imports)] pub use impl_devicebuffer::set_chain_down_override; +pub use moe_group_down_columns::DownColumns; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_serve_assets::{ OriginalAssetKind, OriginalAssetStatus, original_serve_asset_status, original_serve_assets_sealed, diff --git a/crates/cuda-driver/src/routed_group_workspace_gpu/down_case.rs b/crates/cuda-driver/src/routed_group_workspace_gpu/down_case.rs index 038c06f1..07d62873 100644 --- a/crates/cuda-driver/src/routed_group_workspace_gpu/down_case.rs +++ b/crates/cuda-driver/src/routed_group_workspace_gpu/down_case.rs @@ -98,7 +98,12 @@ fn down_first( io: &mut DownIo<'_, '_>, report: &mut Report, ) -> Result { - context.project_routed_down_columns(io.matrix, io.hidden, io.reference, io.total, io.format)?; + context.project_routed_down_columns( + io.matrix, + io.hidden, + io.reference, + DownColumns { total: io.total, format: io.format }, + )?; let original = read(io.reference)?; let allocated = context.allocated_bytes(); workspace.q8.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0xa5; Q8_BYTES])?; @@ -138,7 +143,12 @@ fn down_fault( ) -> Result<()> { io.hidden.copy_from_range(valid.len() - 4, &bits.to_le_bytes())?; let before = read(io.output)?; - let old = context.project_routed_down_columns(io.matrix, io.hidden, io.reference, io.total, io.format); + let old = context.project_routed_down_columns( + io.matrix, + io.hidden, + io.reference, + DownColumns { total: io.total, format: io.format }, + ); let new = workspace.project_down_columns(io.matrix, io.hidden, io.output, io.total, io.format); report.guards += 1; report.refusals += @@ -161,7 +171,12 @@ fn down_recover( report: &mut Report, ) -> Result<()> { io.hidden.copy_from(valid)?; - context.project_routed_down_columns(io.matrix, io.hidden, io.reference, io.total, io.format)?; + context.project_routed_down_columns( + io.matrix, + io.hidden, + io.reference, + DownColumns { total: io.total, format: io.format }, + )?; let original = read(io.reference)?; workspace.project_down_columns(io.matrix, io.hidden, io.output, io.total, io.format)?; compare(&original, &read(io.output)?, report); diff --git a/crates/cuda-driver/src/routed_resident_queue_gpu/upload_fn.rs b/crates/cuda-driver/src/routed_resident_queue_gpu/upload_fn.rs index f97ebd27..a3d0b249 100644 --- a/crates/cuda-driver/src/routed_resident_queue_gpu/upload_fn.rs +++ b/crates/cuda-driver/src/routed_resident_queue_gpu/upload_fn.rs @@ -102,7 +102,8 @@ fn hidden_down_products( if stop.is_some() { return Ok(stop); } - match context.project_routed_down_columns(weights.down, hidden, down, columns.len(), weights.down_format) { + let down_columns = DownColumns { total: columns.len(), format: weights.down_format }; + match context.project_routed_down_columns(weights.down, hidden, down, down_columns) { Ok(()) => {} Err(Error::InvalidQ8Activation) => { return Ok(Some(RoutedResidentRefusal::DownQuant)); diff --git a/crates/cuda-driver/src/tests.rs b/crates/cuda-driver/src/tests.rs index d1023ff7..bcc14eb7 100644 --- a/crates/cuda-driver/src/tests.rs +++ b/crates/cuda-driver/src/tests.rs @@ -175,7 +175,10 @@ fn matvec_private_admission_refuses_without_cuda() { let matrix = make(Some(ffi::BufferHandle::synthetic(4))); let vector = make(Some(ffi::BufferHandle::synthetic(8))); let mut output = make(Some(ffi::BufferHandle::synthetic(12))); - assert_eq!(context.matvec_f32(&matrix, &vector, &mut output, 1, 1), Err(Error::ContextPoisoned)); + assert_eq!( + context.matvec_f32(&matrix, &vector, &mut output, MatvecDims { rows: 1, columns: 1 }), + Err(Error::ContextPoisoned) + ); // No native context exists in this test. Pure allocation identity and // extent instruments supply the remaining impossible-safe-call cases. assert_eq!(context.allocated_bytes(), 12); diff --git a/crates/cuda-driver/tests/gpu_driver.rs b/crates/cuda-driver/tests/gpu_driver.rs index 7560e94d..73393bad 100644 --- a/crates/cuda-driver/tests/gpu_driver.rs +++ b/crates/cuda-driver/tests/gpu_driver.rs @@ -1,6 +1,6 @@ #![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -use leleka_cuda_driver::{Context, Device, DeviceBuffer, Driver, Error}; +use leleka_cuda_driver::{Context, Device, DeviceBuffer, Driver, Error, MatvecDims}; // Recorded binary32 expectations, independent of wrapper code and PTX output. const ARITHMETIC: &[(&[u32], &[u32], u32)] = &[ @@ -128,7 +128,12 @@ fn launch_matvec( output: &mut DeviceBuffer<'_>, ) { context - .matvec_f32(inputs[0], inputs[1], output, case.matrix.len() / case.vector.len(), case.vector.len()) + .matvec_f32( + inputs[0], + inputs[1], + output, + MatvecDims { rows: case.matrix.len() / case.vector.len(), columns: case.vector.len() }, + ) .expect("installed-driver matvec launch, sync and restoration"); } @@ -175,7 +180,9 @@ fn shared_input(device: &Device<'_>) { let input = upload(&context, &[1.0, -2.0, 3.0]); let mut output = upload(&context, &[f32::NAN]); assert_eq!(context.allocated_bytes(), 16, "shared input charged once"); - context.matvec_f32(&input, &input, &mut output, 1, 3).expect("shared immutable input"); + context + .matvec_f32(&input, &input, &mut output, MatvecDims { rows: 1, columns: 3 }) + .expect("shared immutable input"); assert_output(&output, &[14.0]); assert_eq!(read(&input), bytes(&[1.0, -2.0, 3.0])); input.release().expect("shared input free"); @@ -188,8 +195,14 @@ fn foreign_refusal(first: &Context<'_>, second: &Context<'_>) { let matrix = upload(first, &[2.0]); let vector = upload(second, &[3.0]); let mut output = upload(second, &[-0.0]); - assert_eq!(second.matvec_f32(&matrix, &vector, &mut output, 1, 1), Err(Error::ContextMismatch)); - assert_eq!(second.matvec_f32(&vector, &vector, &mut output, 0, 1), Err(Error::InvalidMatvecShape)); + assert_eq!( + second.matvec_f32(&matrix, &vector, &mut output, MatvecDims { rows: 1, columns: 1 }), + Err(Error::ContextMismatch) + ); + assert_eq!( + second.matvec_f32(&vector, &vector, &mut output, MatvecDims { rows: 0, columns: 1 }), + Err(Error::InvalidMatvecShape) + ); assert_eq!(read(&output), bytes(&[-0.0]), "refusals preserve output"); assert_eq!(first.allocated_bytes(), 4); assert_eq!(second.allocated_bytes(), 8); diff --git a/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs b/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs index af1f935b..e0b05d86 100644 --- a/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/check_matvec_lengths_fn.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +use leleka_cuda_driver::MatvecDims; pub(super) fn check_matvec_lengths(f: &mut MatvecFixture<'_>) { for slot in 0..3 { @@ -17,9 +18,9 @@ pub(super) fn check_matvec_bad_length(f: &mut MatvecFixture<'_>, slot: usize, by let before = trace().len(); let charged = f.context.allocated_bytes(); let error = match slot { - 0 => f.context.matvec_f32(&bad, &f.b, &mut f.out, f.rows, f.columns), - 1 => f.context.matvec_f32(&f.a, &bad, &mut f.out, f.rows, f.columns), - _ => f.context.matvec_f32(&f.a, &f.b, &mut bad, f.rows, f.columns), + 0 => f.context.matvec_f32(&bad, &f.b, &mut f.out, MatvecDims { rows: f.rows, columns: f.columns }), + 1 => f.context.matvec_f32(&f.a, &bad, &mut f.out, MatvecDims { rows: f.rows, columns: f.columns }), + _ => f.context.matvec_f32(&f.a, &f.b, &mut bad, MatvecDims { rows: f.rows, columns: f.columns }), }; assert_eq!(error, Err(leleka_cuda_driver::Error::InvalidMatvecShape)); assert_eq!(trace().len(), before); @@ -104,7 +105,7 @@ pub(super) fn matvec_second_context(device: &leleka_cuda_driver::Device<'_>, f: let mut z = second.allocate(f.out.len()).unwrap(); x.copy_from(&f32_bytes(&f.matrix)).unwrap(); y.copy_from(&f32_bytes(&f.vector)).unwrap(); - second.matvec_f32(&x, &y, &mut z, f.rows, f.columns).unwrap(); + second.matvec_f32(&x, &y, &mut z, MatvecDims { rows: f.rows, columns: f.columns }).unwrap(); let mut actual = vec![0; f.rows * 4]; z.copy_to(&mut actual).unwrap(); check_f32_output(&actual, expected); diff --git a/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs b/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs index e33fbf87..f4c894a8 100644 --- a/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +use leleka_cuda_driver::MatvecDims; pub(super) fn vector_bounds(device: &leleka_cuda_driver::Device<'_>, f: &mut VectorFixture<'_>) { use leleka_cuda_driver::Error; @@ -37,7 +38,10 @@ pub(super) fn vector_poison_refusals(f: &mut VectorFixture<'_>) { use leleka_cuda_driver::Error; let before = trace().len(); assert!(vector_call(f).is_err()); - assert_eq!(f.context.matvec_f32(&f.a, &f.b, &mut f.out, 1, f.count), Err(Error::ContextPoisoned)); + assert_eq!( + f.context.matvec_f32(&f.a, &f.b, &mut f.out, MatvecDims { rows: 1, columns: f.count }), + Err(Error::ContextPoisoned) + ); assert!(f.context.allocate(4).is_err()); assert!(f.a.copy_from(&f32_bytes(&f.av)).is_err()); assert!(f.context.synchronize().is_err()); diff --git a/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs b/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs index fa914c36..59844a4c 100644 --- a/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/vector_module_context_trace_fn.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +use leleka_cuda_driver::MatvecDims; pub(super) fn vector_module_context_trace(rows: &[Row]) { for stage in ["load", "lookup", "unload", "launch"] { @@ -75,7 +76,7 @@ pub(super) fn check_arithmetic_fixture(device: &leleka_cuda_driver::Device<'_>, let mut out = context.allocate(4).unwrap(); a.copy_from(&f32_bytes(&matrix)).unwrap(); b.copy_from(&f32_bytes(&vector)).unwrap(); - context.matvec_f32(&a, &b, &mut out, 1, vector.len()).unwrap(); + context.matvec_f32(&a, &b, &mut out, MatvecDims { rows: 1, columns: vector.len() }).unwrap(); let mut bytes = [0u8; 4]; out.copy_to(&mut bytes).unwrap(); check_f32_output(&bytes, &expected); @@ -98,7 +99,8 @@ pub(super) fn matvec_fixture<'a>(context: &'a leleka_cuda_driver::Context<'a>, c MatvecFixture { context, case, a, b, out, matrix, vector, rows, columns } } pub(super) fn matvec_call(f: &mut MatvecFixture<'_>) -> leleka_cuda_driver::Result<()> { - f.context.matvec_f32(&f.a, if f.case == "matvec_same_input" { &f.a } else { &f.b }, &mut f.out, f.rows, f.columns) + let vector = if f.case == "matvec_same_input" { &f.a } else { &f.b }; + f.context.matvec_f32(&f.a, vector, &mut f.out, MatvecDims { rows: f.rows, columns: f.columns }) } pub(super) fn matvec_child(case: &str) { let driver = Driver::load().unwrap(); @@ -150,7 +152,7 @@ pub(super) fn check_matvec_dimensions(f: &mut MatvecFixture<'_>) { (f.rows, 1), ]; for (m, n) in dimensions { - assert!(f.context.matvec_f32(&f.a, &f.b, &mut f.out, m, n).is_err()); + assert!(f.context.matvec_f32(&f.a, &f.b, &mut f.out, MatvecDims { rows: m, columns: n }).is_err()); } assert_eq!(trace().len(), before); assert_eq!(f.context.allocated_bytes(), charged); @@ -162,9 +164,10 @@ pub(super) fn check_matvec_foreign(device: &leleka_cuda_driver::Device<'_>, f: & let b = foreign.allocate(f.b.len()).unwrap(); let mut out = foreign.allocate(f.out.len()).unwrap(); let before = trace().len(); - assert_eq!(f.context.matvec_f32(&a, &f.b, &mut f.out, f.rows, f.columns), Err(Error::ContextMismatch)); - assert_eq!(f.context.matvec_f32(&f.a, &b, &mut f.out, f.rows, f.columns), Err(Error::ContextMismatch)); - assert_eq!(f.context.matvec_f32(&f.a, &f.b, &mut out, f.rows, f.columns), Err(Error::ContextMismatch)); + let dims = MatvecDims { rows: f.rows, columns: f.columns }; + assert_eq!(f.context.matvec_f32(&a, &f.b, &mut f.out, dims), Err(Error::ContextMismatch)); + assert_eq!(f.context.matvec_f32(&f.a, &b, &mut f.out, dims), Err(Error::ContextMismatch)); + assert_eq!(f.context.matvec_f32(&f.a, &f.b, &mut out, dims), Err(Error::ContextMismatch)); assert_eq!(trace().len(), before); drop((a, b, out)); foreign.close().unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs index 90b00440..92e11ada 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs @@ -2,7 +2,7 @@ #[allow(unused_imports)] use super::*; -use leleka_cuda_driver::{GdnRowCompletion, GdnRowPrefix}; +use leleka_cuda_driver::{GdnConvBuffers, GdnOutNormBuffers, GdnRecurrenceBuffers, GdnRowCompletion, GdnRowPrefix}; fn check_distinct_slots(slots: &[usize; 4]) -> Result<()> { for (index, slot) in slots.iter().enumerate() { @@ -123,6 +123,22 @@ impl<'ctx> Chain<'ctx> { let normalized = self.operand_buffer(&slots.normalized, Role::Normalized)?; Ok(RowOutputBuffers { raw, next, h, qk, sigmoid, gate, readout, normalized }) } + /// The six convolution owners of one row over the given QKV owner. + fn conv_buffers<'l>( + ins: &RowInputBuffers<'l, 'ctx>, + inputs: &QueueInputs<'l, 'ctx>, + outs: &RowOutputBuffers<'l, 'ctx>, + qkv: &'l DeviceBuffer<'l>, + ) -> GdnConvBuffers<'l> { + GdnConvBuffers { + history: ins.history, + qkv, + weights: inputs.conv_weights, + next_history: outs.next, + raw: outs.raw, + h: outs.h, + } + } fn drain_row_inputs<'l>( prefix: &mut GdnRowPrefix<'l, 'ctx>, inputs: &QueueInputs<'l, 'ctx>, @@ -135,12 +151,12 @@ impl<'ctx> Chain<'ctx> { prefix.scan_alpha(ins.alpha).map_err(driver_error)?; prefix.scan_beta_raw(ins.beta_raw).map_err(driver_error)?; match (&inputs.qkv, ins.qkv) { - (QkvInput::Host(_), Some(qkv)) => prefix - .conv_silu(ins.history, qkv, inputs.conv_weights, outs.next, outs.raw, outs.h) - .map_err(driver_error)?, - (QkvInput::Columns { buffer, row }, None) => prefix - .conv_silu_columns(ins.history, buffer, *row, inputs.conv_weights, outs.next, outs.raw, outs.h) - .map_err(driver_error)?, + (QkvInput::Host(_), Some(qkv)) => { + prefix.conv_silu(Self::conv_buffers(ins, inputs, outs, qkv)).map_err(driver_error)? + } + (QkvInput::Columns { buffer, row }, None) => { + prefix.conv_silu_columns(Self::conv_buffers(ins, inputs, outs, buffer), *row).map_err(driver_error)? + } _ => return Err(Error::IdentityMismatch), } Ok(()) @@ -155,10 +171,20 @@ impl<'ctx> Chain<'ctx> { prefix.beta_sigmoid(ins.beta_raw, outs.sigmoid).map_err(driver_error)?; prefix.gate_softplus(ins.alpha, inputs.dt, inputs.a, outs.gate).map_err(driver_error)?; prefix - .recurrence(inputs.state, outs.qk, outs.h, outs.gate, outs.sigmoid, inputs.next_state, outs.readout) + .recurrence(GdnRecurrenceBuffers { + state: inputs.state, + qk: outs.qk, + h: outs.h, + gate: outs.gate, + beta: outs.sigmoid, + next_state: inputs.next_state, + readout: outs.readout, + }) .map_err(driver_error)?; prefix.scan_z(ins.z).map_err(driver_error)?; - prefix.out_norm(outs.readout, ins.z, inputs.gamma, outs.normalized, inputs.epsilon).map_err(driver_error)?; + let norm = + GdnOutNormBuffers { readout: outs.readout, z: ins.z, gamma: inputs.gamma, normalized: outs.normalized }; + prefix.out_norm(norm, inputs.epsilon).map_err(driver_error)?; prefix.fetch_next_history(outs.next).map_err(driver_error)?; prefix.finish().map_err(driver_error) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs index 0c5a4d24..f7ccebb9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs @@ -133,7 +133,15 @@ impl<'ctx> Chain<'ctx> { prefix.seed_state(resident, next_state).map_err(driver_error)?; prefix.conv_l2(bufs.next, inputs.conv_weights, bufs.h, inputs.epsilon).map_err(driver_error)?; prefix - .ab(inputs.mixed, inputs.w_alpha, inputs.w_beta, inputs.dt, inputs.a, bufs.gate, bufs.beta) + .ab(leleka_cuda_driver::GdnAbBuffers { + mixed: inputs.mixed, + w_alpha: inputs.w_alpha, + w_beta: inputs.w_beta, + dt: inputs.dt, + ssm_a: inputs.a, + gate: bufs.gate, + beta: bufs.beta, + }) .map_err(driver_error)?; prefix.step_norm(inputs.gamma, bufs.y, inputs.epsilon).map_err(driver_error)?; Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs index c771ff99..44156dca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs @@ -156,7 +156,8 @@ fn run_prompt_producer<'arena, 'loan, 'ctx>( (state, next, weights, history): PromptInputs<'_, 'ctx>, failed: &std::cell::Cell, ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Box<[f32]>)> { - let operation = producer.produce(read, workspace, weights, state, next, history).map_err(device_error); + let prior = leleka_cuda_driver::OriginalGdnPromptState { state, next_state: next, history }; + let operation = producer.produce(read, workspace, weights, prior).map_err(device_error); if producer.is_failed() { failed.set(true) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs index 5246e21c..47f3193d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs @@ -156,15 +156,15 @@ impl<'ctx> Workspace<'ctx> { (out, readout): (&DeviceBuffer<'ctx>, &Option>), ) -> Result { program - .replay_state_from_products( - state.as_ref().ok_or(Error::IdentityMismatch)?, - operands[0].as_ref().ok_or(Error::IdentityMismatch)?, - operands[1].as_ref().ok_or(Error::IdentityMismatch)?, - operands[2].as_ref().ok_or(Error::IdentityMismatch)?, - operands[3].as_ref().ok_or(Error::IdentityMismatch)?, - out, - readout.as_ref().ok_or(Error::IdentityMismatch)?, - ) + .replay_state_from_products(leleka_cuda_driver::GdnReplayBuffers { + state: state.as_ref().ok_or(Error::IdentityMismatch)?, + qk: operands[0].as_ref().ok_or(Error::IdentityMismatch)?, + h: operands[1].as_ref().ok_or(Error::IdentityMismatch)?, + gate: operands[2].as_ref().ok_or(Error::IdentityMismatch)?, + beta: operands[3].as_ref().ok_or(Error::IdentityMismatch)?, + next: out, + readout: readout.as_ref().ok_or(Error::IdentityMismatch)?, + }) .map_err(driver_error) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs index 31641df3..67dde0e1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/inject_batch_fns.rs @@ -85,10 +85,12 @@ pub(super) fn queued_inject( return Ok(None); }; let BatchOperands { streams, blocks, injects } = operands; - let result = workspace.inject(context, shape, streams, blocks, injects).map_err(|error| match error { - leleka_cuda_driver::Error::InvalidDriverValue("GR batch injection finite input") => Error::NonFinite, - other => driver_error(other), - }); + let result = workspace + .inject(context, shape, leleka_cuda_driver::GrInjectInputs { streams, blocks, injects }) + .map_err(|error| match error { + leleka_cuda_driver::Error::InvalidDriverValue("GR batch injection finite input") => Error::NonFinite, + other => driver_error(other), + }); if workspace.is_failed() || context.is_poisoned() { failed.set(true); } @@ -177,10 +179,12 @@ fn launch_gr_inject<'c>( .gr(context)? .inject( tokens, - residual.as_ref().ok_or(Error::CudaExecution)?, - output.as_ref().ok_or(Error::CudaExecution)?, - injection.as_ref().ok_or(Error::CudaExecution)?, - candidate.as_mut().ok_or(Error::CudaExecution)?, + leleka_cuda_driver::GrInjectBuffers { + residual: residual.as_ref().ok_or(Error::CudaExecution)?, + output: output.as_ref().ok_or(Error::CudaExecution)?, + inject: injection.as_ref().ok_or(Error::CudaExecution)?, + candidate: candidate.as_mut().ok_or(Error::CudaExecution)?, + }, ) .map_err(driver_error) } @@ -197,10 +201,12 @@ fn launch_gr_inject<'c>( context .gr_batch_inject_residual_f32( tokens, - residual.as_ref().ok_or(Error::CudaExecution)?, - output.as_ref().ok_or(Error::CudaExecution)?, - injection.as_ref().ok_or(Error::CudaExecution)?, - candidate.as_mut().ok_or(Error::CudaExecution)?, + leleka_cuda_driver::GrInjectBuffers { + residual: residual.as_ref().ok_or(Error::CudaExecution)?, + output: output.as_ref().ok_or(Error::CudaExecution)?, + inject: injection.as_ref().ok_or(Error::CudaExecution)?, + candidate: candidate.as_mut().ok_or(Error::CudaExecution)?, + }, ) .map_err(driver_error) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_shared_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_shared_fns.rs index 872fc6a1..c488fb85 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_shared_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_shared_fns.rs @@ -174,7 +174,12 @@ pub(super) fn launch_down_plain<'ctx>( format: RoutedFormat, ) -> Result> { Ok(match matrix { - CachedMoeMatrix::Raw(raw) => context.project_routed_down_columns(raw, input, out, columns, format), + CachedMoeMatrix::Raw(raw) => context.project_routed_down_columns( + raw, + input, + out, + leleka_cuda_driver::DownColumns { total: columns, format }, + ), CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs index 269d36bc..9fe30e57 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/route_micro_fns.rs @@ -276,7 +276,12 @@ pub(super) fn combine_on_device<'ctx>( let shared = products.shared.as_ref().ok_or(Error::IdentityMismatch)?; let sg = products.sg.as_ref().ok_or(Error::IdentityMismatch)?; let mut prefix = batch.begin_combine(tokens, gemm).map_err(driver_error)?; - let _ = prefix.combine_from(route_weights, shared, sg, combine.dm, combine.slot, bo); + let _ = prefix.combine_from( + leleka_cuda_driver::MoeCombineInputs { route_weights, shared, sg }, + combine.dm, + combine.slot, + bo, + ); let completion = prefix.finish().map_err(driver_error)?; if completion.numerical_refusal().is_some() { return Err(Error::NonFinite);