Merge branch 'claude/par-h01' into claude/hexagonal-finish-14ee3a
This commit is contained in:
@@ -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<qwen_ffi::Layout> {
|
||||
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)?;
|
||||
|
||||
@@ -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],
|
||||
|
||||
+4
-4
@@ -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<Launch> {
|
||||
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;
|
||||
}
|
||||
|
||||
+20
-57
@@ -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<Vec<Operand<'a, 'b>>> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -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())));
|
||||
|
||||
@@ -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<()> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -254,15 +254,21 @@ fn resolve_inputs() -> (Vec<i32>, Vec<i32>) {
|
||||
(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();
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +115,40 @@ pub struct GdnRowPrefix<'lease, 'ctx> {
|
||||
fetch: Option<ffi::BufferHandle>,
|
||||
}
|
||||
|
||||
/// 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<GdnQueueStage>,
|
||||
|
||||
@@ -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;
|
||||
|
||||
+6
-20
@@ -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)?;
|
||||
+4
-19
@@ -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)?;
|
||||
@@ -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};
|
||||
|
||||
@@ -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<Self> {
|
||||
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()
|
||||
}
|
||||
|
||||
+33
-11
@@ -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);
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<GdnFusedStage>,
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-11
@@ -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])?;
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<bool> {
|
||||
pub fn replay_state_from_products(&mut self, buffers: GdnReplayBuffers<'_>) -> Result<bool> {
|
||||
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)?;
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
+22
-9
@@ -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)?;
|
||||
+17
-2
@@ -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(())
|
||||
+9
-1
@@ -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(())
|
||||
@@ -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
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -99,19 +99,15 @@ pub(super) fn q8_0(rows: usize, cols: usize, salt: usize) -> (Vec<u8>, Vec<u16>)
|
||||
}
|
||||
(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);
|
||||
|
||||
+7
-14
@@ -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<u8>, out: Vec<f32>) {
|
||||
/// 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<u8>, out: Vec<f32>) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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};
|
||||
|
||||
+1
-2
@@ -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 } => {
|
||||
|
||||
+3
-5
@@ -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))?;
|
||||
+12
-5
@@ -17,6 +17,13 @@ struct Cmds<'f, 'ctx> {
|
||||
list: Vec<DeviceCommand>,
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -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<Box<[f32]>> {
|
||||
let GrInjectInputs { streams, blocks, injects } = inputs;
|
||||
if !std::ptr::eq(self.context, context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ type Products = [Vec<u8>; 4];
|
||||
fn check(ok: bool) -> Result<()> {
|
||||
if ok { Ok(()) } else { Err(Error::InvalidDriverValue("GR batch workspace proof")) }
|
||||
}
|
||||
fn inputs_of(source: &[Vec<f32>; 3]) -> GrInjectInputs<'_> {
|
||||
GrInjectInputs { streams: &source[0], blocks: &source[1], injects: &source[2] }
|
||||
}
|
||||
fn bytes(values: &[f32]) -> Vec<u8> {
|
||||
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<Products> {
|
||||
@@ -96,7 +101,7 @@ fn original_first(
|
||||
) -> Result<usize> {
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+11
-3
@@ -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 };
|
||||
@@ -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;
|
||||
|
||||
+16
-11
@@ -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<u8>,
|
||||
pub(in super::super) arguments: Vec<KernelArguments>,
|
||||
pub(in super::super) readback: Vec<u8>,
|
||||
}
|
||||
|
||||
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<u8>,
|
||||
arguments: Vec<KernelArguments>,
|
||||
mut readback: Vec<u8>,
|
||||
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])?;
|
||||
+16
-14
@@ -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<usize> {
|
||||
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)?;
|
||||
+12
-4
@@ -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<Box<[f32]>> {
|
||||
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.
|
||||
@@ -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();
|
||||
|
||||
@@ -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)]
|
||||
|
||||
+23
-4
@@ -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<Self> {
|
||||
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<Comparison>,
|
||||
) -> 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)?;
|
||||
@@ -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)]
|
||||
|
||||
+23
-4
@@ -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<Self> {
|
||||
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<Comparison>,
|
||||
) -> 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)?;
|
||||
@@ -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 =
|
||||
|
||||
@@ -76,9 +76,7 @@ impl<'ctx> NativeInteger<'ctx> {
|
||||
pub(super) fn append(
|
||||
&self,
|
||||
commands: &mut Vec<QueuedCommand>,
|
||||
weights: ffi::BufferHandle,
|
||||
packed: ffi::BufferHandle,
|
||||
output: ffi::BufferHandle,
|
||||
[weights, packed, output]: [ffi::BufferHandle; 3],
|
||||
l: Layout,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
)?,
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Launch> {
|
||||
pub(super) fn multiply_launch(&self, operands: MultiplyOperands<'_>, m: &MultiplyGeometry) -> Result<Launch> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -34,15 +34,21 @@ pub(super) fn f32s(xs: &[f32]) -> Vec<u8> {
|
||||
pub(super) fn i32s(xs: &[i32]) -> Vec<u8> {
|
||||
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<Arg>,
|
||||
) -> 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<u8>; 4], [Vec<u8>; 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 {
|
||||
|
||||
@@ -147,9 +147,17 @@ impl<'c> Attention<'c> {
|
||||
|
||||
fn attend(&self, w: &mut NativeBatchWorkspace<'_>, pools: [u64; 4], table: u64, n: usize) -> Vec<u8> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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() },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Self> {
|
||||
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<Box<[f32]>> {
|
||||
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<MmqObservation> {
|
||||
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<DeviceBuffer<'ctx>>),
|
||||
) -> Result<MmqObservation> {
|
||||
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)?;
|
||||
|
||||
@@ -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<BufferHandle>,
|
||||
}
|
||||
/// 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)]
|
||||
|
||||
@@ -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<BufferHandle>,
|
||||
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.
|
||||
|
||||
@@ -69,9 +69,7 @@ impl<'ctx> NativeActivation<'ctx> {
|
||||
pub(super) fn append(
|
||||
&self,
|
||||
commands: &mut Vec<QueuedCommand>,
|
||||
input: ffi::BufferHandle,
|
||||
packed: ffi::BufferHandle,
|
||||
status: ffi::BufferHandle,
|
||||
[input, packed, status]: [ffi::BufferHandle; 3],
|
||||
l: Layout,
|
||||
) -> Result<()> {
|
||||
self.check()?;
|
||||
|
||||
@@ -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<u8>, Vec<Case>))> {
|
||||
(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;
|
||||
|
||||
+2
-8
@@ -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<u8>, Vec<Case>) {
|
||||
pub(super) fn cases(receipt: &Receipt, shape: Shape) -> (Vec<u8>, Vec<Case>) {
|
||||
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();
|
||||
@@ -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;
|
||||
|
||||
@@ -8,16 +8,16 @@ fn env_number(name: &str) -> Option<usize> {
|
||||
}
|
||||
|
||||
/// Everything `Core::new` takes besides the layer bounds, the first layer and the issue depth.
|
||||
struct CoreParts {
|
||||
api: Api,
|
||||
entries: Vec<Entry>,
|
||||
targets: Vec<(BufferHandle, usize)>,
|
||||
copied: Vec<usize>,
|
||||
used: Vec<usize>,
|
||||
starts: Vec<usize>,
|
||||
copy: usize,
|
||||
topup: usize,
|
||||
context: usize,
|
||||
pub(crate) struct CoreParts {
|
||||
pub(crate) api: Api,
|
||||
pub(crate) entries: Vec<Entry>,
|
||||
pub(crate) targets: Vec<(BufferHandle, usize)>,
|
||||
pub(crate) copied: Vec<usize>,
|
||||
pub(crate) used: Vec<usize>,
|
||||
pub(crate) starts: Vec<usize>,
|
||||
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<Entry>,
|
||||
targets: Vec<(BufferHandle, usize)>,
|
||||
copied: Vec<usize>,
|
||||
used: Vec<usize>,
|
||||
starts: Vec<usize>,
|
||||
topup: usize,
|
||||
context: usize,
|
||||
) -> Result<Self> {
|
||||
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> {
|
||||
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 })
|
||||
|
||||
@@ -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<usize>,
|
||||
}
|
||||
/// 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;
|
||||
|
||||
+31
-28
@@ -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<crate::MappedExpertBank<'ctx>>,
|
||||
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<ffi::BufferHandle>),
|
||||
(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(())
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+6
-18
@@ -48,14 +48,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(in super::super) fn finite(
|
||||
&self,
|
||||
commands: Vec<QueuedCommand>,
|
||||
source: ffi::BufferHandle,
|
||||
amount: usize,
|
||||
q8: bool,
|
||||
label: &'static str,
|
||||
) -> Result<()> {
|
||||
pub(in super::super) fn finite(&self, commands: Vec<QueuedCommand>, 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<usize>,
|
||||
) -> 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)?;
|
||||
+26
-16
@@ -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 {
|
||||
@@ -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<crate::MappedExpertBank<'ctx>>,
|
||||
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<usize>;
|
||||
fn stage_span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)>;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<crate::MappedExpertBank<'ctx>>,
|
||||
formats: [MmqFormat; 3],
|
||||
spans: &'read [[ResidentExpertBankSpan; 3]],
|
||||
experts: RingExperts<'read, 'ctx>,
|
||||
groups: usize,
|
||||
) -> Result<Self> {
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<StreamEntry>,
|
||||
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<crate::MappedExpertBank<'ctx>>,
|
||||
(first, ring): (u8, usize),
|
||||
(entries, targets): (Vec<StreamEntry>, Vec<(ffi::BufferHandle, usize)>),
|
||||
plan: StreamPlan,
|
||||
events: Vec<usize>,
|
||||
) -> 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<crate::MappedExpertBank<'ctx>>, Vec<usize>),
|
||||
) -> Result<()> {
|
||||
let copy = parts.copy;
|
||||
match ChunkStream::start(first, parts) {
|
||||
Ok(stream) => {
|
||||
self.adopt_stream(stream, bank, events, copy);
|
||||
Ok(())
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<DownCopyHandles> {
|
||||
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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
+17
-11
@@ -91,7 +91,7 @@ impl<'ctx> MmqWorkspace<'ctx> {
|
||||
) -> Result<Vec<QueuedCommand>> {
|
||||
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<bool> {
|
||||
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<ffi::BufferHandle> {
|
||||
@@ -241,10 +241,10 @@ impl<'ctx> MmqWorkspace<'ctx> {
|
||||
e: &MmqExperiment<'ctx>,
|
||||
format: MmqFormat,
|
||||
plan: &ProjectPlan,
|
||||
grid: u32,
|
||||
temp: Option<ffi::BufferHandle>,
|
||||
launch: StreamKLaunch,
|
||||
) -> Result<Vec<QueuedCommand>> {
|
||||
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<ffi::BufferHandle>,
|
||||
}
|
||||
/// Validated handles and layout of one projection; the weight allocation is `w_bytes` long.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ProjectPlan {
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
{
|
||||
|
||||
@@ -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");
|
||||
|
||||
+7
-9
@@ -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));
|
||||
@@ -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<NativeDownCopyHandles> {
|
||||
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.
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-3
@@ -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);
|
||||
+44
-28
@@ -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(())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user