Merge branch 'claude/par-h02' into claude/hexagonal-finish-14ee3a

# Conflicts:
#	crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/native_gemm_launch.rs
#	crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs
#	crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 01:35:23 +01:00
88 changed files with 909 additions and 572 deletions
+4 -12
View File
@@ -1,5 +1,6 @@
//! Stage-local Option-B GEMM loan of the ONE model-lifetime native workspace.
//! No vendor owner, allocation, synchronization or row authority is minted here.
use crate::ple_batch_ffi::{GdnGemmLayout, GemmDims, GemmOperands};
use crate::{DeviceBuffer, Error, GdnGemm, GdnStream, GemmShape, NativeBatchWorkspace, Result};
const DEQUANT_BYTES: usize = 10240 * 2560 * 2;
@@ -73,18 +74,9 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> {
admit_shape(bf16, &shape)?;
admit_bytes(bf16, &shape, [x, w, y])?;
let [xh, wh, yh] = self.admit_owners(context, [x, w, y])?;
self.workspace.blas()?.gemm_gdn(
bf16,
xh,
wh,
yh,
shape.tokens as i32,
shape.rows as i32,
shape.depth as i32,
shape.ldy as i32,
shape.y_offset,
&shape.beta,
)
let dims = GemmDims { tokens: shape.tokens as i32, outputs: shape.rows as i32, depth: shape.depth as i32 };
let layout = GdnGemmLayout { is_bf16: bf16, ldy: shape.ldy as i32, y_offset: shape.y_offset };
self.workspace.blas()?.gemm_gdn(GemmOperands { x: xh, w: wh, y: yh }, dims, layout, &shape.beta)
}
/// Validates WHOLE actual owners, including the unused dequantized tail; only the fixed matrix prefix is
@@ -5,6 +5,7 @@
#[allow(unused_imports)]
use super::*;
use crate::CurrentGuard;
use crate::ple_batch_ffi::{GdnGemmLayout, GemmDims, GemmOperands, LinearLaunch};
/// Host buffers of one run: the history upload, the status words and final history read back, and the decoded history.
struct Host {
@@ -161,11 +162,14 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
crate::GdnGeometry { grid: *grid, block: *block },
args,
),
DeviceCommand::Gemm { bf16, x, w, y, n, k, ldy, offset, beta } => {
blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta)
}
DeviceCommand::Gemm { bf16, x, w, y, n, k, ldy, offset, beta } => blas.gemm_gdn(
GemmOperands { x: *x, w: *w, y: *y },
GemmDims { tokens: t as i32, outputs: *n, depth: *k },
GdnGemmLayout { is_bf16: *bf16, ldy: *ldy, y_offset: *offset },
beta,
),
DeviceCommand::Stage { index, grid, block, args } => match self.stage.as_ref() {
Some(module) => module.launch(*index, *grid, *block, blas.stream(), args),
Some(module) => module.launch(*index, LinearLaunch::new(*grid, *block, blas.stream()), args),
None => Err(Error::ContextPoisoned),
},
}
@@ -3,6 +3,7 @@
use super::native_gemm_launch::GemmRoles;
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
/// The retained host ABI and staging of one drain: the eligible stages, the zeroed status words, the kernel
/// arguments and the status readback.
@@ -286,9 +287,7 @@ impl<'ctx> GrNativeBatch<'ctx> {
// Original gr_norm_rs block topology T*HC blocks, 256 threads.
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
(self.tokens * 4) as u32,
256,
blas.stream(),
LinearLaunch::new((self.tokens * 4) as u32, 256, blas.stream()),
&mut args[0],
)?;
self.launch(blas, 5, self.tokens * 10240, &mut args[1])?;
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars, LinearLaunch};
/// The buffer slots, weight and `n` x `k` shape of one Original GEMM.
#[derive(Clone, Copy)]
@@ -193,16 +194,19 @@ impl<'ctx> GrNativeBatch<'ctx> {
) -> Result<()> {
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
let stream = blas.stream();
module.launch(index, count.div_ceil(256) as u32, 256, stream, args)
module.launch(index, LinearLaunch::new(count.div_ceil(256) as u32, 256, stream), args)
}
/// 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)?;
let dims = GemmDims { tokens: self.tokens as i32, outputs: n, depth: k };
let first = GemmOperands { x: self.handle(input)?, w: weight, y: self.handle(output)? };
blas.gemm_bf16(first, dims, GemmScalars { alpha, beta: beta0 })?;
if self.profile == GrNativeProfile::HighAndLow {
blas.gemm_bf16(self.handle(low)?, weight, self.handle(output)?, self.tokens as i32, n, k, alpha, beta1)?;
let second = GemmOperands { x: self.handle(low)?, w: weight, y: self.handle(output)? };
blas.gemm_bf16(second, dims, GemmScalars { alpha, beta: beta1 })?;
}
Ok(())
}
@@ -4,6 +4,7 @@
use super::*;
use crate::CurrentGuard;
use crate::ple_batch_ffi::Blas;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars};
/// The device status words and the host image they are read back into.
struct StatusRead<'a> {
@@ -85,7 +86,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> {
Cmd::Copy { dst, src, bytes } => self.modules[0]
.as_ref()
.map_or(Err(Error::ContextPoisoned), |m| m.copy(*dst, *src, *bytes, blas.stream())),
Cmd::Gemm { x, w, y, rows, n, k, alpha, beta } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta),
Cmd::Gemm { x, w, y, rows, n, k, alpha, beta } => {
let dims = GemmDims { tokens: *rows, outputs: *n, depth: *k };
blas.gemm_bf16(GemmOperands { x: *x, w: *w, y: *y }, dims, GemmScalars { alpha, beta })
}
}
}
fn settle(
@@ -20,4 +20,4 @@ mod impl_originalmtpscalarprefill_7;
#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs"]
mod impl_originalmtpscalarprefill_8;
#[allow(unused_imports)]
use impl_originalmtpscalarprefill_6::{Cap, GroupIo, ScalarCall, ScalarStaged};
use impl_originalmtpscalarprefill_6::{Cap, ExternalOwners, GrRows, GroupIo, ScalarCall, ScalarStaged};
@@ -145,12 +145,11 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
}
pub(in super::super) fn external(
&self,
rows: &OriginalPromptRows<'_, '_, '_>,
w: &NativeBatchWorkspace<'_>,
ring: &MtpOriginalInt8<'_>,
owners: &ExternalOwners<'_, '_, '_, '_>,
b: &DeviceBuffer<'_>,
n: usize,
) -> Result<BufferHandle> {
let ExternalOwners { rows, workspace: w, ring } = *owners;
checked(self.context, b, n)?;
let h = b.handle.ok_or(Error::ContextPoisoned)?;
w.reject_alias(h, n)?;
@@ -22,17 +22,16 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
0,
vec![self.gr_args(0, t, wh, xn)?],
)?;
self.gr_chunks(cmds, t, wh, policy, xn)?;
self.gr_chunks(cmds, GrRows { row_count: t, weights: wh, normalised: xn }, policy)?;
Self::kernel(cmds, 4, 3, [160, 1, 1], [256, 1, 1], 0, vec![self.gr_args(0, t, wh, xn)?])
}
fn gr_chunks(
&self,
cmds: &mut Vec<ScalarCommand>,
t: usize,
wh: &[BufferHandle; 11],
rows: GrRows<'_>,
policy: &OriginalMtpScalarPolicy,
xn: u64,
) -> Result<()> {
let GrRows { row_count: t, weights: wh, normalised: xn } = rows;
let per_token = if policy.gr == OriginalMtpGrVariant::Staged { 2 * 1280 * 4 } else { self.plain_tile * 4 };
let capacity = (self.shared_limit / per_token).clamp(1, 8);
for c in (0..t).step_by(capacity) {
@@ -111,7 +111,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
}
fn stage_scalar(
&self,
rows: &OriginalPromptRows<'_, '_, '_>,
rows: &OriginalPromptRows<'_, '_, 'ctx>,
workspace: &NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
operands: (&OriginalMtpScalarWeights<'_, 'ctx>, &OriginalMtpEmbedding<'_, 'ctx>),
@@ -119,7 +119,8 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?;
self.reject_input_alias(rh, rbytes)?;
self.reject_state_aliases(workspace, ring)?;
let (wh, eh) = self.stage_weights(rows, workspace, ring, operands, rh)?;
let owners = ExternalOwners { rows, workspace, ring };
let (wh, eh) = self.stage_weights(&owners, operands, rh)?;
Ok(ScalarStaged { wh, eh, rh, rbytes })
}
fn reject_input_alias(&self, rh: BufferHandle, rbytes: usize) -> Result<()> {
@@ -149,9 +150,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
}
fn stage_weights(
&self,
rows: &OriginalPromptRows<'_, '_, '_>,
workspace: &NativeBatchWorkspace<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
owners: &ExternalOwners<'_, '_, '_, 'ctx>,
operands: (&OriginalMtpScalarWeights<'_, 'ctx>, &OriginalMtpEmbedding<'_, 'ctx>),
rh: BufferHandle,
) -> Result<([BufferHandle; 11], BufferHandle)> {
@@ -171,9 +170,9 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
];
let mut wh = [rh; 11];
for i in 0..11 {
wh[i] = self.external(rows, workspace, ring, wr[i], SCALAR_EXTENTS[i])?;
wh[i] = self.external(owners, wr[i], SCALAR_EXTENTS[i])?;
}
let eh = self.external(rows, workspace, ring, embedding.table, embedding.table.bytes)?;
let eh = self.external(owners, embedding.table, embedding.table.bytes)?;
Self::reject_overlapping_weights(&wh)?;
Ok((wh, eh))
}
@@ -49,6 +49,22 @@ pub(in super::super) struct Cap<'a, 'ctx> {
pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'ctx>,
}
/// The owners a buffer supplied from outside must not alias: the prompt rows, the batch workspace and the draft ring.
#[derive(Clone, Copy)]
pub(in super::super) struct ExternalOwners<'a, 'arena, 'loan, 'ctx> {
pub(in super::super) rows: &'a OriginalPromptRows<'arena, 'loan, 'ctx>,
pub(in super::super) workspace: &'a NativeBatchWorkspace<'ctx>,
pub(in super::super) ring: &'a MtpOriginalInt8<'ctx>,
}
/// The rows of one GR launch: their count, the eleven weight handles and the address of the normalised input.
#[derive(Clone, Copy)]
pub(in super::super) struct GrRows<'a> {
pub(in super::super) row_count: usize,
pub(in super::super) weights: &'a [BufferHandle; 11],
pub(in super::super) normalised: u64,
}
impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
/// The addresses of several scratch slots, resolved in the order given.
pub(in super::super) fn addresses<const N: usize>(&self, specs: [(usize, usize); N]) -> Result<[u64; N]> {
@@ -4,20 +4,39 @@
#[allow(unused_imports)]
use super::*;
/// How the session rope is computed: the table form and the six float constants of the rope scaling.
#[derive(Clone, Copy)]
pub(crate) struct OriginalMtpRopeSetting {
pub(crate) form: OriginalMtpRopeForm,
pub(crate) constants: [f32; 6],
}
/// The session owner's rope tables: the shared allocation, the byte offsets of the cos and sin tables inside it, and
/// the optional mrope table.
pub(crate) struct OriginalMtpRopeTables<'ctx> {
pub(crate) tables: Rc<DeviceBuffer<'ctx>>,
pub(crate) table_offsets: [usize; 2],
pub(crate) mrope: Option<Rc<DeviceBuffer<'ctx>>>,
}
/// A byte offset into a shared device buffer: where a rope operand (the rotated data or its position slots) starts.
pub(crate) struct OffsetBuffer<'ctx> {
pub(crate) buffer: Rc<DeviceBuffer<'ctx>>,
pub(crate) offset: usize,
}
impl<'ctx> OriginalMtpSessionResources<'ctx> {
/// Crate-private intake called only from the real SessionState owner. Tables
/// must be that owner's existing primary allocation, not newly generated data.
#[allow(clippy::too_many_arguments)]
pub(crate) fn retain_primary(
context: &'ctx Context<'ctx>,
plan: OriginalMtpSessionPlan,
primary: usize,
form: OriginalMtpRopeForm,
constants: [f32; 6],
tables: Rc<DeviceBuffer<'ctx>>,
table_offsets: [usize; 2],
mrope: Option<Rc<DeviceBuffer<'ctx>>>,
setting: OriginalMtpRopeSetting,
rope_tables: OriginalMtpRopeTables<'ctx>,
) -> Result<Self> {
let OriginalMtpRopeSetting { form, constants } = setting;
let OriginalMtpRopeTables { tables, table_offsets, mrope } = rope_tables;
Self::check_primary(primary, &constants)?;
Self::check_plan(&plan)?;
Self::check_tables(context, &plan, &tables, table_offsets, mrope.as_ref())?;
@@ -148,37 +167,34 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> {
}
pub(crate) fn plan_rope(
&self,
data: Rc<DeviceBuffer<'ctx>>,
offset: usize,
data: OffsetBuffer<'ctx>,
positions: OffsetBuffer<'ctx>,
heads: usize,
positions: Rc<DeviceBuffer<'ctx>>,
position_offset: usize,
) -> Result<OriginalMtpSessionRopePlan<'ctx>> {
let (dh, ph) = self.rope_spans(&data, offset, heads, &positions, position_offset)?;
let (dh, ph) = self.rope_spans(&data, heads, &positions)?;
let (data, positions) = (data.buffer, positions.buffer);
let (mt, cos, sin) = self.rope_tables()?;
let args = self.rope_args(dh.qwen_address(), ph.qwen_address(), heads, [mt, cos, sin])?;
Ok(OriginalMtpSessionRopePlan { session: Rc::clone(&self.inner), data, positions, args, heads })
}
fn rope_spans(
&self,
data: &Rc<DeviceBuffer<'ctx>>,
offset: usize,
data: &OffsetBuffer<'ctx>,
heads: usize,
positions: &Rc<DeviceBuffer<'ctx>>,
position_offset: usize,
positions: &OffsetBuffer<'ctx>,
) -> Result<(BufferHandle, BufferHandle)> {
let (dh, ph) = self.rope_handles(data, offset, heads, positions, position_offset)?;
let (dh, ph) = self.rope_handles(data, heads, positions)?;
self.reject_rope_alias(dh, ph, heads)?;
Ok((dh, ph))
}
fn rope_handles(
&self,
data: &Rc<DeviceBuffer<'ctx>>,
offset: usize,
data: &OffsetBuffer<'ctx>,
heads: usize,
positions: &Rc<DeviceBuffer<'ctx>>,
position_offset: usize,
positions: &OffsetBuffer<'ctx>,
) -> Result<(BufferHandle, BufferHandle)> {
let (data, offset) = (&data.buffer, data.offset);
let (positions, position_offset) = (&positions.buffer, positions.offset);
self.validate_context(self.inner.context)?;
if !matches!(heads, 2 | 24) {
return Err(Error::InvalidProjectionShape);
+2
View File
@@ -86,6 +86,8 @@ pub use native_asset_pin_types::NativeHeadDispatch;
#[allow(unused_imports)]
pub use native_asset_pin_types::NativeHeadFlight;
#[allow(unused_imports)]
pub use native_asset_pin_types::NativeHeadPayload;
#[allow(unused_imports)]
pub use native_asset_pin_types::NativeHeadSampling;
#[allow(unused_imports)]
pub use native_asset_pin_types::NativeHeadSelection;
@@ -89,12 +89,10 @@ impl Drop for HeadOwned<'_> {
impl<'ctx> Context<'ctx> {
pub fn original_native_head(
&'ctx self,
kind: u32,
n: usize,
vocab: usize,
payload: &[u8],
head: NativeHeadPayload<'_>,
dispatch: NativeHeadDispatch,
) -> Result<OriginalNativeHead<'ctx>> {
let NativeHeadPayload { kind, columns: n, vocabulary: vocab, bytes: payload } = head;
let bytes = head_payload_bytes(kind, n, vocab, payload)?;
// Unsealed assets refuse before admission/allocation; modules have a real owner
// before pop so an uncertain Context never drops their driver dependencies.
@@ -158,12 +158,11 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
stream: &mut OriginalGpuStream<'ctx>,
sampling: NativeHeadSampling<'_, 'ctx>,
) -> Result<NativeHeadSelection> {
let NativeHeadSampling { position: pos0, params, history, history_len, path, enabled: head_sampling } =
sampling;
let NativeHeadSampling { position: pos0, params, history, history_len, enabled: head_sampling, .. } = sampling;
self.check_sampling_request(stream, &params, history_len, pos0)?;
self.commands.borrow_mut().clear();
if head_sampling && sampling_needed(&params, history.is_some()) {
self.sample_on_stream(stream, params, pos0, history, history_len, path)?;
self.sample_on_stream(stream, sampling)?;
}
self.read_selection(pos0)
}
@@ -188,16 +187,14 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
fn sample_on_stream(
&mut self,
stream: &mut OriginalGpuStream<'ctx>,
params: SamplerParams,
pos0: u64,
history: Option<&DeviceBuffer<'ctx>>,
history_len: usize,
path: SamplerPath,
sampling: NativeHeadSampling<'_, 'ctx>,
) -> Result<()> {
let NativeHeadSampling { position: pos0, params, history, history_len, path, .. } = sampling;
let mut p = params;
p.counter = pos0;
let (history, history_len) = self.penalty_history(&p, history, history_len)?;
let mut commands = self.sample_commands(p, history, history_len, path, stream.native_head_stream_key()?)?;
let sampling = NativeHeadSampling { params: p, history, history_len, path, ..sampling };
let mut commands = self.sample_commands(sampling, stream.native_head_stream_key()?)?;
self.prepare_commands(&commands)?;
let span_sample = crate::host_profile::span("head.sample_sync");
let operation = stream.with_enqueue(|h| self.submit(h, std::mem::take(&mut commands)));
@@ -6,12 +6,10 @@ use super::*;
impl<'ctx> OriginalNativeHeadRows<'ctx> {
pub(in super::super) fn sample_commands(
&self,
p: SamplerParams,
history: Option<&DeviceBuffer<'ctx>>,
history_len: usize,
path: SamplerPath,
sampling: NativeHeadSampling<'_, 'ctx>,
stream_key: usize,
) -> Result<Vec<Command>> {
let NativeHeadSampling { params: p, history, history_len, path, .. } = sampling;
let a = self.sample_args(p, history, history_len)?;
let mut c = Vec::new();
c.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
@@ -37,6 +37,15 @@ pub struct NativeHeadSampling<'a, 'ctx> {
pub path: SamplerPath,
pub enabled: bool,
}
/// The bytes of a native output head as the model file stores them: its quantisation kind, the column count, the
/// vocabulary rows and the raw row payload.
#[derive(Clone, Copy)]
pub struct NativeHeadPayload<'a> {
pub kind: u32,
pub columns: usize,
pub vocabulary: usize,
pub bytes: &'a [u8],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NativeHeadDispatch {
pub multi_exact: bool,
@@ -12,21 +12,27 @@ pub(super) fn projection_commands(
) -> Result<Vec<Command>> {
head.validate(head.context)?;
let weights = head.weights.as_ref().ok_or(Error::ContextPoisoned)?;
admit_projection(head, weights, mixed, q8, logits, t)?;
admit_projection(head, weights, ProjectionBuffers { mixed, q8, logits }, t)?;
let mut commands = Vec::new();
commands.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?;
commands.push(quant_command(head, mixed, q8, t)?);
commands.push(head_command(head, weights, q8, logits, t)?);
Ok(commands)
}
/// The activation buffers one head projection touches: the mixed hidden state, its Q8 quantisation and the logits.
#[derive(Clone, Copy)]
struct ProjectionBuffers<'a> {
mixed: &'a DeviceBuffer<'a>,
q8: &'a DeviceBuffer<'a>,
logits: &'a DeviceBuffer<'a>,
}
fn admit_projection(
head: &HeadOwned<'_>,
weights: &DeviceBuffer<'_>,
mixed: &DeviceBuffer<'_>,
q8: &DeviceBuffer<'_>,
logits: &DeviceBuffer<'_>,
buffers: ProjectionBuffers<'_>,
t: usize,
) -> Result<()> {
let ProjectionBuffers { mixed, q8, logits } = buffers;
admit(head.context, mixed, t * head.n * 4)?;
admit(head.context, q8, t * head.n / 32 * 36)?;
admit(head.context, logits, t * head.vocab * 4)?;
@@ -103,6 +103,16 @@ use crate::prefill_stage::fused_scans;
mod impl_originaldeviceblock;
mod impl_originalplehistory;
#[allow(unused_imports)]
use impl_originalplehistory::GrNormRequest;
#[allow(unused_imports)]
use impl_originalplehistory::LaunchGeometry;
#[allow(unused_imports)]
use impl_originalplehistory::PhaseGuards;
#[allow(unused_imports)]
use impl_originalplehistory::ScanExtent;
#[allow(unused_imports)]
use impl_originalplehistory::WeightExtent;
#[allow(unused_imports)]
use impl_originalplehistory::bytes;
#[allow(unused_imports)]
use impl_originalplehistory::encode;
@@ -59,26 +59,78 @@ impl Drop for OriginalPleHistory<'_> {
let _ = self.close_inner();
}
}
pub(super) fn kernel(v: &mut Vec<C>, family: u8, index: usize, grid: usize, block: u32, args: Vec<A>) {
/// Grid and block size of one prompt-device kernel launch.
#[derive(Clone, Copy)]
pub(super) struct LaunchGeometry {
grid: usize,
block: u32,
}
impl LaunchGeometry {
/// A launch of `grid` blocks of `block` threads.
pub(super) const fn new(grid: usize, block: u32) -> Self {
Self { grid, block }
}
}
/// The tensor shape a finite scan covers: `width` values per row over `rows` rows.
#[derive(Clone, Copy)]
pub(super) struct ScanExtent {
width: usize,
rows: usize,
}
impl ScanExtent {
/// A scan over `rows` rows of `width` values.
pub(super) const fn new(width: usize, rows: usize) -> Self {
Self { width, rows }
}
}
/// The finite guards a command run is checked against: the rows scanned, the status words per row, the order the guard
/// slots are arbitrated in and the label of each slot for error messages.
#[derive(Clone, Copy)]
pub(super) struct PhaseGuards<'a> {
pub(super) rows: usize,
pub(super) stride: usize,
pub(super) order: &'a [usize],
pub(super) labels: &'a [&'static str],
}
/// The byte size and required alignment of a weight matrix.
#[derive(Clone, Copy)]
pub(super) struct WeightExtent {
pub(super) size: usize,
pub(super) alignment: u64,
}
impl WeightExtent {
/// A weight of `size` bytes that must be `alignment`-aligned.
pub(super) const fn new(size: usize, alignment: u64) -> Self {
Self { size, alignment }
}
}
/// How a GR read normalises: the RMS-norm epsilon and whether the preceding injection already normed the residual.
#[derive(Clone, Copy)]
pub(super) struct GrNormRequest {
pub(super) epsilon: f32,
pub(super) is_normed: bool,
}
pub(super) fn kernel(v: &mut Vec<C>, family: u8, index: usize, geometry: LaunchGeometry, args: Vec<A>) {
let LaunchGeometry { grid, block } = geometry;
v.push(C::Kernel { family, index, grid: grid as u32, block, args: KernelArguments::new(args) })
}
pub(super) fn scan_ple(v: &mut Vec<C>, data: BufferHandle, status: BufferHandle, width: usize, t: usize, role: i32) {
pub(super) fn scan_ple(v: &mut Vec<C>, data: BufferHandle, status: BufferHandle, extent: ScanExtent, role: i32) {
let ScanExtent { width, rows: t } = extent;
kernel(
v,
1,
5,
(width * t).div_ceil(256),
256,
LaunchGeometry::new((width * t).div_ceil(256), 256),
vec![A::Address(data), A::Address(status), A::I32(width as i32), A::I32(t as i32), A::I32(role)],
)
}
pub(super) fn scan_gr(v: &mut Vec<C>, data: BufferHandle, status: BufferHandle, width: usize, t: usize, role: u32) {
pub(super) fn scan_gr(v: &mut Vec<C>, data: BufferHandle, status: BufferHandle, extent: ScanExtent, role: u32) {
let ScanExtent { width, rows: t } = extent;
kernel(
v,
2,
4,
(width * t).div_ceil(256),
256,
LaunchGeometry::new((width * t).div_ceil(256), 256),
vec![A::Address(data), A::Address(status), A::I64(width as i64), A::I64(t as i64), A::U32(role)],
)
}
@@ -24,6 +24,14 @@ pub(super) struct GrReadPlan {
low_half: bool,
}
/// Which of the plan's spans a GEMM reads (the high half and its low half) and writes.
#[derive(Clone, Copy)]
struct ProjectionSlots {
input: usize,
low_input: usize,
output: usize,
}
impl GrReadPlan {
pub(super) fn new(
h: [BufferHandle; 15],
@@ -50,7 +58,8 @@ impl GrReadPlan {
if self.low_half { A::Address(self.h[i]) } else { A::NullAddress }
}
fn gemm(&self, v: &mut Vec<C>, (input, lo): (usize, usize), weight: BufferHandle, out: usize, (n, k): (i32, i32)) {
fn gemm(&self, v: &mut Vec<C>, slots: ProjectionSlots, weight: BufferHandle, (n, k): (i32, i32)) {
let ProjectionSlots { input, low_input: lo, output: out } = slots;
let (h, t) = (&self.h, self.t as i32);
v.push(C::Gemm { input: h[input], weight, output: h[out], t, n, k, alpha: 1., beta: 0. });
if self.low_half {
@@ -81,7 +90,7 @@ impl GrReadPlan {
self.low(3),
A::Address(self.flags),
];
kernel(v, 3, 3, self.t * 4, 256, args);
kernel(v, 3, 3, LaunchGeometry::new(self.t * 4, 256), args);
}
}
@@ -96,27 +105,33 @@ impl GrReadPlan {
A::Address(h[2]),
self.low(3),
];
kernel(v, 2, 0, t * 4, 256, args);
kernel(v, 2, 0, LaunchGeometry::new(t * 4, 256), args);
}
let scan = vec![A::Address(h[0]), A::Address(h[1]), A::Address(w[0]), A::Address(self.flags), A::I64(t as i64)];
kernel(v, 2, 5, (t * 10240).div_ceil(256), 256, scan);
kernel(v, 2, 5, LaunchGeometry::new((t * 10240).div_ceil(256), 256), scan);
}
/// Down projection, SiLU, up projection and the injection GEMM, each followed by its guard.
pub(super) fn push_projections(&self, v: &mut Vec<C>, fused: bool) {
let (h, w, t, flags) = (&self.h, &self.w, self.t, self.flags);
self.gemm(v, (2, 3), w[1], 4, (320, 10240));
scan_gr(v, h[4], flags, 320, t, 1);
self.gemm(v, ProjectionSlots { input: 2, low_input: 3, output: 4 }, w[1], (320, 10240));
scan_gr(v, h[4], flags, ScanExtent::new(320, t), 1);
let silu = vec![A::Address(h[4]), A::Address(h[5]), self.low(6), A::I64((t * 320) as i64)];
kernel(v, 2, 1, (t * 320).div_ceil(256), 256, silu);
kernel(v, 2, 6, (t * 320).div_ceil(256), 256, vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)]);
self.gemm(v, (5, 6), w[2], 7, (10240, 320));
kernel(v, 2, 1, LaunchGeometry::new((t * 320).div_ceil(256), 256), silu);
kernel(
v,
2,
6,
LaunchGeometry::new((t * 320).div_ceil(256), 256),
vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)],
);
self.gemm(v, ProjectionSlots { input: 5, low_input: 6, output: 7 }, w[2], (10240, 320));
if !fused {
scan_gr(v, h[7], flags, 10240, t, 3);
scan_gr(v, h[7], flags, ScanExtent::new(10240, t), 3);
}
// Original injection GEMM precedes mixed production.
self.gemm(v, (2, 3), w[3], 12, (4, 10240));
scan_gr(v, h[12], flags, 4, t, 6);
self.gemm(v, ProjectionSlots { input: 2, low_input: 3, output: 12 }, w[3], (4, 10240));
scan_gr(v, h[12], flags, ScanExtent::new(4, t), 6);
}
/// Mixed production; fused folds the gated, product and mixed-row guards into the mix kernel.
@@ -136,9 +151,9 @@ impl GrReadPlan {
if fused {
// mix + the guards of the gated tensor (3), the products (4) and the mixed row (5)
mix.push(A::Address(flags));
kernel(v, 3, 4, (t * 2560).div_ceil(256), 256, mix);
kernel(v, 3, 4, LaunchGeometry::new((t * 2560).div_ceil(256), 256), mix);
} else {
kernel(v, 2, 2, (t * 2560).div_ceil(256), 256, mix);
kernel(v, 2, 2, LaunchGeometry::new((t * 2560).div_ceil(256), 256), mix);
self.push_mix_guards(v);
}
}
@@ -153,7 +168,7 @@ impl GrReadPlan {
A::Address(flags),
A::I64(t as i64),
];
kernel(v, 2, 7, (t * 10240).div_ceil(256), 256, guard);
scan_gr(v, h[8], flags, 2560, t, 5);
kernel(v, 2, 7, LaunchGeometry::new((t * 10240).div_ceil(256), 256), guard);
scan_gr(v, h[8], flags, ScanExtent::new(2560, t), 5);
}
}
@@ -186,9 +186,9 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
rows: &OriginalPromptRows<'_, '_, '_>,
workspace: &NativeBatchWorkspace<'_>,
b: &DeviceBuffer<'_>,
size: usize,
alignment: u64,
extent: WeightExtent,
) -> Result<BufferHandle> {
let WeightExtent { size, alignment } = extent;
let h = self.weight_handle(b, size, alignment)?;
workspace.reject_alias(h, size)?;
if h.overlaps(size, self.status()?, self.capacity * 40) {
@@ -70,11 +70,9 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
lease: &mut OriginalPromptRows<'_, '_, '_>,
workspace: &mut NativeBatchWorkspace<'ctx>,
commands: Vec<C>,
t: usize,
stride: usize,
order: &[usize],
labels: &[&'static str],
guards: PhaseGuards<'_>,
) -> Result<()> {
let PhaseGuards { rows: t, stride, order, labels } = guards;
let status = self.status()?;
let mut buffers = RunBuffers::new(commands, t * stride * 4)?;
let blas = workspace.blas()?;
@@ -11,7 +11,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
weights: [&DeviceBuffer<'_>; 4],
epsilon: f32,
) -> Result<OriginalDeviceGrRead<'arena, 'loan, 'ctx>> {
self.read_gr_impl(residual, workspace, weights, epsilon, false)
self.read_gr_impl(residual, workspace, weights, GrNormRequest { epsilon, is_normed: false })
}
pub fn read_gr_normed<'weight, 'arena, 'loan>(
&mut self,
@@ -23,6 +23,6 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
if !std::ptr::eq(normed.gamma, weights[0]) || normed.epsilon.to_bits() != epsilon.to_bits() {
return Err(Error::InvalidQwenShape);
}
self.read_gr_impl(normed.residual, workspace, weights, epsilon, true)
self.read_gr_impl(normed.residual, workspace, weights, GrNormRequest { epsilon, is_normed: true })
}
}
@@ -10,9 +10,9 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
mut residual: OriginalDeviceResidual<'arena, 'loan, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
weights: [&DeviceBuffer<'_>; 4],
epsilon: f32,
normed: bool,
norm: GrNormRequest,
) -> Result<OriginalDeviceGrRead<'arena, 'loan, 'ctx>> {
let GrNormRequest { epsilon, is_normed: normed } = norm;
self.profile_tag = if normed { "readn" } else { "read" };
let lease = &mut residual.lease;
self.validate(lease, workspace)?;
@@ -22,7 +22,12 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
let t = lease.rows();
let plan = self.gr_read_plan(lease, workspace, weights)?;
let v = plan.commands(epsilon, normed)?;
self.run(lease, workspace, v, t, 8, &GR_READ_ORDER, &GR_READ_NAMES)?;
self.run(
lease,
workspace,
v,
PhaseGuards { rows: t, stride: 8, order: &GR_READ_ORDER, labels: &GR_READ_NAMES },
)?;
Ok(OriginalDeviceGrRead { lease: residual.lease })
}
/// The spans and weights of a GR read of the lease's rows.
@@ -35,7 +40,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
let h = self.gr_read_spans(lease)?;
let mut w = [h[0]; 4];
for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() {
w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?;
w[i] = self.weight(lease, workspace, weights[i], WeightExtent::new(n, if i == 0 { 4 } else { 2 }))?;
}
let low_half = self.profile == GrNativeProfile::HighAndLow;
Ok(GrReadPlan::new(h, w, self.status()?, lease.rows(), low_half))
@@ -35,7 +35,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
if !epsilon.is_finite() || epsilon < 0. {
return Err(Error::InvalidQwenShape);
}
let w = self.weight(lease, workspace, gamma, 40960, 4)?;
let w = self.weight(lease, workspace, gamma, WeightExtent::new(40960, 4))?;
let t = lease.rows();
let sp = self.inject_spans(lease)?;
let fs = self.fused_spans(lease, w)?;
@@ -55,8 +55,8 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
) -> Result<()> {
let mut check = Vec::new();
check.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?;
scan_gr(&mut check, b, flags, 2560, t, 7);
self.run(lease, workspace, check, t, 8, &[7], &BLOCK_NAMES)
scan_gr(&mut check, b, flags, ScanExtent::new(2560, t), 7);
self.run(lease, workspace, check, PhaseGuards { rows: t, stride: 8, order: &[7], labels: &BLOCK_NAMES })
}
pub(super) fn run_inject(
@@ -66,7 +66,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
v: Vec<C>,
t: usize,
) -> Result<()> {
self.run(lease, workspace, v, t, 8, &[7], &INJECT_NAMES)
self.run(lease, workspace, v, PhaseGuards { rows: t, stride: 8, order: &[7], labels: &INJECT_NAMES })
}
pub(super) fn run_inject_fused(
@@ -76,7 +76,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
v: Vec<C>,
t: usize,
) -> Result<()> {
self.run(lease, workspace, v, t, 8, &[7, 0], &FUSED_NAMES)
self.run(lease, workspace, v, PhaseGuards { rows: t, stride: 8, order: &[7, 0], labels: &FUSED_NAMES })
}
}
@@ -87,11 +87,11 @@ pub(super) fn inject_commands(sp: &InjectSpans, t: usize) -> Result<Vec<C>> {
v.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
if fused_scans() {
let args = vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64), A::Address(flags)];
kernel(&mut v, 3, 6, (t * 10240).div_ceil(256), 256, args);
kernel(&mut v, 3, 6, LaunchGeometry::new((t * 10240).div_ceil(256), 256), args);
} else {
let args = vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64)];
kernel(&mut v, 2, 3, (t * 10240).div_ceil(256), 256, args);
scan_gr(&mut v, r, flags, 10240, t, 7);
kernel(&mut v, 2, 3, LaunchGeometry::new((t * 10240).div_ceil(256), 256), args);
scan_gr(&mut v, r, flags, ScanExtent::new(10240, t), 7);
}
Ok(v)
}
@@ -116,12 +116,12 @@ pub(super) fn inject_fused_commands(sp: &InjectSpans, fs: &FusedSpans, epsilon:
if fused_scans() {
// write + the guards of R after the write (7) and of the next half's norm (0)
args.push(A::Address(flags));
kernel(&mut v, 3, 5, t * 4, 256, args);
kernel(&mut v, 3, 5, LaunchGeometry::new(t * 4, 256), args);
} else {
kernel(&mut v, 2, 8, t * 4, 256, args);
scan_gr(&mut v, r, flags, 10240, t, 7);
kernel(&mut v, 2, 8, LaunchGeometry::new(t * 4, 256), args);
scan_gr(&mut v, r, flags, ScanExtent::new(10240, t), 7);
let norm = vec![A::Address(r), A::Address(fs.rs), A::Address(fs.w), A::Address(flags), A::I64(t as i64)];
kernel(&mut v, 2, 5, (t * 10240).div_ceil(256), 256, norm);
kernel(&mut v, 2, 5, LaunchGeometry::new((t * 10240).div_ceil(256), 256), norm);
}
Ok(v)
}
@@ -75,12 +75,12 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
workspace: &NativeBatchWorkspace<'ctx>,
weights: &PleClosedWeights<'_, '_>,
) -> Result<PleWeights> {
let key = self.weight(lease, workspace, weights.key, 52428800, 2)?;
let value = self.weight(lease, workspace, weights.value, 13107200, 2)?;
let key = self.weight(lease, workspace, weights.key, WeightExtent::new(52428800, 2))?;
let value = self.weight(lease, workspace, weights.value, WeightExtent::new(13107200, 2))?;
let mut aux = [key; 4];
for (i, w) in weights.aux.iter().enumerate() {
let (bytes, alignment) = if i == 3 { (81920, 2) } else { (40960, 4) };
aux[i] = self.weight(lease, workspace, w, bytes, alignment)?;
aux[i] = self.weight(lease, workspace, w, WeightExtent::new(bytes, alignment))?;
}
Ok(PleWeights { key, value, aux })
}
@@ -152,7 +152,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
v: Vec<C>,
t: usize,
) -> Result<()> {
self.run(lease, workspace, v, t, 10, &PLE_ORDER, &PLE_NAMES)
self.run(lease, workspace, v, PhaseGuards { rows: t, stride: 10, order: &PLE_ORDER, labels: &PLE_NAMES })
}
}
@@ -169,16 +169,16 @@ pub(super) fn ple_commands(c: &PleChunk, pw: &PleWeights, hist: BufferHandle, t:
fn push_ple_projections(v: &mut Vec<C>, c: &PleChunk, pw: &PleWeights, hist: BufferHandle, t: usize) {
let [kh, _, _, val, _, packed] = c.roles;
// Candidate history is source bytes, never a caller finite witness.
scan_ple(v, hist, c.flags, 92160, 1, 8);
scan_ple(v, hist, c.flags, ScanExtent::new(92160, 1), 8);
let pack =
vec![A::Address(c.eh), A::Address(packed), c.low.map_or(A::NullAddress, A::Address), A::I64((t * 2560) as i64)];
kernel(v, 0, 0, (t * 2560).div_ceil(256), 256, pack);
kernel(v, 0, 0, LaunchGeometry::new((t * 2560).div_ceil(256), 256), pack);
for (out, n, w, role) in [(kh, 10240, pw.key, 0), (val, 2560, pw.value, 1)] {
v.push(C::Gemm { input: packed, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 0. });
if let Some(l) = c.low {
v.push(C::Gemm { input: l, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 1. })
}
scan_ple(v, out, c.flags, n as usize, t, role);
scan_ple(v, out, c.flags, ScanExtent::new(n as usize, t), role);
}
}
@@ -186,23 +186,23 @@ fn push_ple_projections(v: &mut Vec<C>, c: &PleChunk, pw: &PleWeights, hist: Buf
fn push_ple_norms(v: &mut Vec<C>, c: &PleChunk, pw: &PleWeights, t: usize) {
let [kh, qn, _, _, gate, _] = c.roles;
let (aux, flags, rh) = (&pw.aux, c.flags, c.rh);
kernel(v, 1, 0, t * 4, 1024, vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)]);
scan_ple(v, kh, flags, 10240, t, 2);
kernel(v, 1, 0, t * 4, 1024, vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)]);
scan_ple(v, qn, flags, 10240, t, 3);
kernel(v, 1, 0, LaunchGeometry::new(t * 4, 1024), vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)]);
scan_ple(v, kh, flags, ScanExtent::new(10240, t), 2);
kernel(v, 1, 0, LaunchGeometry::new(t * 4, 1024), vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)]);
scan_ple(v, qn, flags, ScanExtent::new(10240, t), 3);
let gate_args = vec![A::Address(kh), A::Address(qn), A::Address(gate), A::F32(1. / 2560.0f32.sqrt())];
kernel(v, 1, 1, t * 4, 512, gate_args);
scan_ple(v, gate, flags, 4, t, 4);
kernel(v, 1, 1, LaunchGeometry::new(t * 4, 512), gate_args);
scan_ple(v, gate, flags, ScanExtent::new(4, t), 4);
}
fn push_ple_tail(v: &mut Vec<C>, c: &PleChunk, pw: &PleWeights, hist: BufferHandle, t: usize) {
let [_, qn, gated, val, gate, _] = c.roles;
let (aux, flags, rh) = (&pw.aux, c.flags, c.rh);
let gated_args = vec![A::Address(val), A::Address(gate), A::Address(gated), A::I32(t as i32)];
kernel(v, 1, 2, t * 40, 256, gated_args);
scan_ple(v, gated, flags, 10240, t, 5);
kernel(v, 1, 0, t * 4, 1024, vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)]);
scan_ple(v, qn, flags, 10240, t, 6);
kernel(v, 1, 2, LaunchGeometry::new(t * 40, 256), gated_args);
scan_ple(v, gated, flags, ScanExtent::new(10240, t), 5);
kernel(v, 1, 0, LaunchGeometry::new(t * 4, 1024), vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)]);
scan_ple(v, qn, flags, ScanExtent::new(10240, t), 6);
let conv = vec![
A::Address(hist),
A::Address(qn),
@@ -212,8 +212,8 @@ fn push_ple_tail(v: &mut Vec<C>, c: &PleChunk, pw: &PleWeights, hist: BufferHand
A::Address(flags),
A::I32(t as i32),
];
kernel(v, 1, 3, t * 40, 256, conv);
kernel(v, 1, 4, 40, 256, vec![A::Address(hist), A::Address(qn), A::I32(t as i32)]);
scan_ple(v, hist, flags, 92160, 1, 8);
scan_ple(v, rh, flags, 10240, t, 9);
kernel(v, 1, 3, LaunchGeometry::new(t * 40, 256), conv);
kernel(v, 1, 4, LaunchGeometry::new(40, 256), vec![A::Address(hist), A::Address(qn), A::I32(t as i32)]);
scan_ple(v, hist, flags, ScanExtent::new(92160, 1), 8);
scan_ple(v, rh, flags, ScanExtent::new(10240, t), 9);
}
@@ -5,6 +5,7 @@ use super::*;
use crate::CurrentGuard;
use crate::deferred_status::DeferredStatusCheck;
use crate::ple_batch_ffi::Blas;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars, LinearLaunch};
/// The host buffers a run owns until the vendor stream and readback drain; leaked on an uncertain drain.
pub(super) struct RunBuffers {
@@ -80,10 +81,12 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
C::Kernel { family, index, grid, block, args } => {
let module = self.family_module(*family)?;
let label = if timed { kernel_label(*family, *index) } else { "gemm" };
Ok((module.launch(*index, *grid, *block, blas.stream(), args), label))
Ok((module.launch(*index, LinearLaunch::new(*grid, *block, blas.stream()), args), label))
}
C::Gemm { input, weight, output, t, n, k, alpha, beta } => {
Ok((blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta), "gemm"))
let operands = GemmOperands { x: *input, w: *weight, y: *output };
let dims = GemmDims { tokens: *t, outputs: *n, depth: *k };
Ok((blas.gemm_bf16(operands, dims, GemmScalars { alpha, beta }), "gemm"))
}
}
}
@@ -214,11 +214,11 @@ pub(super) fn stage_commands(sp: &StageSpans) -> Result<Vec<C>> {
v.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
if let Some(h) = sp.updates_h {
let update = vec![A::Address(sp.cache_h), A::Address(h), A::U32(sp.misses as u32)];
kernel(&mut v, 3, 0, (sp.misses * 64).div_ceil(256), 256, update);
kernel(&mut v, 3, 0, LaunchGeometry::new((sp.misses * 64).div_ceil(256), 256), update);
}
kernel(&mut v, 3, 1, (t * 16 * 160).div_ceil(256), 256, decode_arguments(sp));
kernel(&mut v, 3, 2, (t * 2560).div_ceil(256), 256, broadcast_arguments(sp));
scan_gr(&mut v, sp.rh, flags, 10240, t, 7);
kernel(&mut v, 3, 1, LaunchGeometry::new((t * 16 * 160).div_ceil(256), 256), decode_arguments(sp));
kernel(&mut v, 3, 2, LaunchGeometry::new((t * 2560).div_ceil(256), 256), broadcast_arguments(sp));
scan_gr(&mut v, sp.rh, flags, ScanExtent::new(10240, t), 7);
Ok(v)
}
@@ -257,6 +257,6 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
v: Vec<C>,
t: usize,
) -> Result<()> {
self.run(lease, workspace, v, t, 8, &STAGE_ORDER, &STAGE_NAMES)
self.run(lease, workspace, v, PhaseGuards { rows: t, stride: 8, order: &STAGE_ORDER, labels: &STAGE_NAMES })
}
}
@@ -1,6 +1,6 @@
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
use super::super::{OriginalSessionGeometry, OriginalSessionKvPolicy, OriginalSessionLayout};
use super::super::{OriginalLayerBounds, OriginalSessionGeometry, OriginalSessionKvPolicy, OriginalSessionLayout};
use super::*;
fn policy() -> OriginalSessionKvPolicy {
@@ -22,7 +22,8 @@ fn policy() -> OriginalSessionKvPolicy {
// whole = [117669888, 368640, 1536, 512, 4]).
#[test]
fn running_state_regions_match_the_original_conversation_sizes() {
let layout = OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap();
let whole = OriginalLayerBounds { lo: 0, hi: -1 };
let layout = OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, whole, policy()).unwrap();
let facts = layout.conversation_facts();
assert_eq!((facts.qsa_alloc, facts.gdn_alloc), (12, 36));
assert_eq!(facts.gdn_state_bytes, 117_669_888);
@@ -39,7 +40,8 @@ fn running_state_regions_match_the_original_conversation_sizes() {
#[test]
fn kv_regions_follow_the_state_format_and_streaming_mode() {
let layout = OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap();
let whole = OriginalLayerBounds { lo: 0, hi: -1 };
let layout = OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, whole, policy()).unwrap();
assert_owned_kv_pools_are_arena_spans(&layout);
assert_draft_kv_is_not_in_the_arena(&layout);
// Out-of-range owned layer is refused.
@@ -180,7 +180,7 @@ impl OriginalFileExpertSource<'_> {
let copies = stream.with_enqueue(|h| {
for (x, b, capacity) in candidates {
let b = b.checked_subspan(*capacity, 0, x.bytes)?;
api.exchange_copy(arena, x.q * self.maximum, b, x.bytes, h)?;
api.exchange_copy(arena, abi::ArenaSpan { offset: x.q * self.maximum, bytes: x.bytes }, b, h)?;
}
Ok(())
});
@@ -17,6 +17,19 @@ pub(super) struct Layout {
pub(super) physical: usize,
}
/// The ranked experts placed so far: each one's arena offset and the byte end of the last placement.
pub(super) struct RankedPlacement {
offsets: Vec<usize>,
end: usize,
}
/// What `fill_arena` copies into the arena: the layout, the residency options and the stack size of the fill workers.
pub(super) struct ArenaFillPlan<'a> {
pub(super) layout: &'a Layout,
pub(super) options: OriginalResidentOptions,
pub(super) stack: usize,
}
/// Marks the source failed and poisons the context (disjoint fields, so a live `api` borrow stays valid).
pub(super) fn poison_parts(failed: &mut bool, context: &Context<'_>) {
*failed = true;
@@ -160,19 +173,18 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
if layout.budget > (room as u64) {
layout.budget = room.saturating_sub(256 << 20) as u64;
}
let mut ranked = vec_filled(N, NONE)?;
let mut at = 0usize;
let mut placement = RankedPlacement { offsets: vec_filled(N, NONE)?, end: 0 };
let mut held = 0;
for &entry in rank.unwrap_or_default() {
if self.rank_one(entry, &layout.offsets, &mut ranked, &mut at, layout.budget)? {
if self.rank_one(entry, &layout.offsets, &mut placement, layout.budget)? {
held += 1;
}
}
if options.budget_bytes == u64::MAX && held == 0 {
return Err(Error::BudgetExceeded);
}
layout.offsets = ranked;
layout.bytes = at;
layout.offsets = placement.offsets;
layout.bytes = placement.end;
layout.lend = None;
Ok(())
}
@@ -181,18 +193,18 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
fn rank_one(
&self,
(l, e): (i32, i32),
offsets: &[usize],
ranked: &mut [usize],
at: &mut usize,
planned_offsets: &[usize],
placement: &mut RankedPlacement,
budget: u64,
) -> Result<bool> {
let RankedPlacement { offsets: ranked, end: at } = placement;
if l < 0 || e < 0 {
return Ok(false);
}
let Ok(i) = key(l as usize, e as usize) else {
return Ok(false);
};
if offsets[i] == NONE || ranked[i] != NONE {
if planned_offsets[i] == NONE || ranked[i] != NONE {
return Ok(false);
}
let b = self.layer_bytes[l as usize];
@@ -280,14 +292,8 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
}
/// Pins the arena as asked, then copies every planned expert from the mapped source with worker threads.
pub(super) fn fill_arena(
&self,
api: &abi::Api,
arena: &mut abi::Arena,
layout: &Layout,
options: OriginalResidentOptions,
stack: usize,
) -> Result<()> {
pub(super) fn fill_arena(&self, api: &abi::Api, arena: &mut abi::Arena, plan: ArenaFillPlan<'_>) -> Result<()> {
let ArenaFillPlan { layout, options, stack } = plan;
if options.pin && arena.pin_limit() == 0 {
if layout.budget > 0 && options.partial_pin {
self.pin_partial(api, arena, layout, options)?;
@@ -1,7 +1,7 @@
//! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (2).
#[allow(unused_imports)]
use super::build_phases::{alloc_failed, discard_arena, leak_arena, poison_parts};
use super::build_phases::{ArenaFillPlan, alloc_failed, discard_arena, leak_arena, poison_parts};
use super::*;
impl<'ctx> OriginalFileExpertSource<'ctx> {
@@ -24,7 +24,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
Ok(a) => a,
Err(primary) => return alloc_failed(&mut self.failed, self.context, guard, primary),
};
let prepare = self.fill_arena(api, &mut arena, &layout, options, stack);
let prepare = self.fill_arena(api, &mut arena, ArenaFillPlan { layout: &layout, options, stack });
let pop = guard.finish();
if pop.is_err() {
return leak_arena(&mut self.failed, self.context, arena, combine(prepare, pop));
@@ -20,6 +20,12 @@ pub(crate) struct Api {
alias: Alias,
dtoh: DtoH,
}
/// A byte range inside an `Arena`: where a copy lands and how long it is.
#[derive(Clone, Copy)]
pub(crate) struct ArenaSpan {
pub(crate) offset: usize,
pub(crate) bytes: usize,
}
/// Raw allocation is not readable until every retained fill job has joined.
/// No Drop CUDA call without a genuine entered Context; actor closes explicitly.
pub(crate) struct Arena {
@@ -126,11 +126,11 @@ impl Api {
pub(crate) fn exchange_copy(
&self,
arena: &Arena,
offset: usize,
span: ArenaSpan,
source: super::super::BufferHandle,
bytes: usize,
stream: usize,
) -> Result<()> {
let ArenaSpan { offset, bytes } = span;
source.validate_extent(bytes)?;
if bytes == 0 || offset.checked_add(bytes).is_none_or(|n| n > arena.bytes) || arena.address == 0 {
return Err(Error::InvalidSize);
@@ -5,7 +5,7 @@
//! until every routed expert and the complete final finite scan have drained.
use crate::ffi::BufferHandle;
use crate::original_prefill_arena::OriginalPromptSpan as S;
use crate::ple_batch_ffi::{BatchArg as A, KernelArguments, KernelModule};
use crate::ple_batch_ffi::{BatchArg as A, GemmOperands, KernelArguments, KernelModule};
use crate::{
Context, DeviceBuffer, Error, GdnNativeFormat, MappedExpertBank, MmqFormat, MmqWorkspace, NativeBatchWorkspace,
OriginalDeviceBlock, OriginalDeviceGrRead, OriginalPromptRows, PrefillPhase, Result, combine,
@@ -71,6 +71,62 @@ enum Command {
},
}
/// The expert sources of one layer's routed experts: the layer, the formats of the three matrices and one resident
/// source triple per routed expert, in order.
#[derive(Clone, Copy)]
pub struct OriginalLayerExpertSources<'a> {
pub layer: usize,
pub formats: [MmqFormat; 3],
pub sources: &'a [[ResidentExpertBankSpan; 3]],
}
/// The shared expert's matrix formats (gate, up, down) and whether the prompt keeps a low half next to the high one.
#[derive(Clone, Copy)]
pub struct SharedExpertLayout {
pub formats: [GdnNativeFormat; 3],
pub has_low_half: bool,
}
/// The layer a stream-all pass covers, the formats of its three matrices and the host bytes it may stage.
#[derive(Clone, Copy)]
pub struct ExpertStreamLayer {
pub layer: u8,
pub formats: [MmqFormat; 3],
pub host_allowance: usize,
}
/// A tensor the finite scan covers: its span, the element count and whether the elements are F16 (else F32).
#[derive(Clone, Copy)]
struct ScanTarget {
source: BufferHandle,
elements: usize,
is_half: bool,
}
impl ScanTarget {
/// A scan over `elements` F32 values at `source`.
const fn float32(source: BufferHandle, elements: usize) -> Self {
Self { source, elements, is_half: false }
}
/// A scan over `elements` F16 values at `source`.
const fn float16(source: BufferHandle, elements: usize) -> Self {
Self { source, elements, is_half: true }
}
}
/// The host buffers of one status run: the zeroed words uploaded first and the readback that receives the result.
struct StatusStaging<'a> {
zero: &'a [u8],
readback: &'a mut [u8],
}
/// Rows, output columns and depth of one prompt GEMM `y[tokens][outputs] = x[tokens][depth] * w[outputs][depth]^T`.
#[derive(Clone, Copy)]
struct GemmSize {
tokens: usize,
outputs: usize,
depth: usize,
}
mod blank_fn;
#[allow(unused_imports)]
use blank_fn::blank;
@@ -28,14 +28,12 @@ pub(super) fn kernel(
pub(super) fn gemm(
commands: &mut Vec<Command>,
bf16: bool,
input: BufferHandle,
weight: BufferHandle,
output: BufferHandle,
t: usize,
n: usize,
k: usize,
operands: GemmOperands,
size: GemmSize,
beta: f32,
) -> Result<()> {
let GemmOperands { x: input, w: weight, y: output } = operands;
let GemmSize { tokens: t, outputs: n, depth: k } = size;
commands.try_reserve(1).map_err(|_| Error::HostAllocation)?;
commands.push(Command::Gemm {
bf16,
@@ -32,11 +32,10 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
&mut self,
workspace: &mut MmqWorkspace<'ctx>,
schedule: &mut crate::OriginalMmqCopySchedule<'ctx>,
layer: usize,
bank: std::rc::Rc<MappedExpertBank<'ctx>>,
formats: [MmqFormat; 3],
sources: &[[ResidentExpertBankSpan; 3]],
layer_sources: OriginalLayerExpertSources<'_>,
) -> Result<()> {
let OriginalLayerExpertSources { layer, formats, sources } = layer_sources;
self.check_sources(&bank, layer, sources)?;
self.upload_slot_table()?;
let mut program =
@@ -53,17 +52,16 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
pub fn execute_mmq(
&mut self,
workspace: &mut MmqWorkspace<'ctx>,
layer: usize,
bank: &MappedExpertBank<'ctx>,
formats: [MmqFormat; 3],
sources: &[[ResidentExpertBankSpan; 3]],
layer_sources: OriginalLayerExpertSources<'_>,
) -> Result<()> {
let OriginalLayerExpertSources { layer, sources, .. } = layer_sources;
self.check_sources(bank, layer, sources)?;
let mut program =
workspace.prepare_original_expert_layer_device(&self.read, &self.counts, &self.source_rows)?;
for group in (0..self.order.len()).step_by(16) {
let end = (group + 16).min(self.order.len());
self.mmq_group(&mut program, group..end, layer, bank, formats, sources)?;
self.mmq_group(&mut program, group..end, bank, layer_sources)?;
program.finish_group()?;
}
program.finish()?;
@@ -93,11 +91,10 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
&self,
program: &mut crate::OriginalMmqLayer<'_, 'ctx>,
experts: std::ops::Range<usize>,
layer: usize,
bank: &MappedExpertBank<'ctx>,
formats: [MmqFormat; 3],
sources: &[[ResidentExpertBankSpan; 3]],
layer_sources: OriginalLayerExpertSources<'_>,
) -> Result<()> {
let OriginalLayerExpertSources { layer, formats, sources } = layer_sources;
for index in experts {
if !program.stage_expert_from_prompt_cache(&self.read, layer, self.order[index] as usize, formats)? {
program.stage_expert_retained(formats, bank, &sources[index])?;
@@ -144,7 +141,7 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
}
self.upload_slot_table()?;
let (mut commands, bo, t) = self.combine_commands()?;
self.program.scan(&mut commands, bo, t * 2560, false, 0)?;
self.program.scan(&mut commands, ScanTarget::float32(bo, t * 2560), 0)?;
self.program.run(workspace, commands, &["MoE combine"])?;
Ok(self.read.from_completed_block())
}
@@ -182,10 +179,9 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
&mut self,
workspace: &mut MmqWorkspace<'ctx>,
forward: &mut crate::OriginalStreamAllForward<'_, '_, '_, '_, 'ctx>,
layer: u8,
formats: [MmqFormat; 3],
host_allowance: usize,
stream_layer: ExpertStreamLayer,
) -> Result<()> {
let ExpertStreamLayer { layer, formats, host_allowance } = stream_layer;
if self.completed_experts != 0 {
return Err(Error::InvalidQwenShape);
}
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars, LinearLaunch};
impl<'ctx> OriginalMoePromptDevice<'ctx> {
pub(in super::super) fn new(context: &'ctx Context<'ctx>, capacity: usize) -> Result<Self> {
@@ -91,14 +92,8 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
}
Ok(())
}
pub(in super::super) fn scan(
&self,
commands: &mut Vec<Command>,
source: BufferHandle,
elements: usize,
half: bool,
slot: usize,
) -> Result<()> {
pub(in super::super) fn scan(&self, commands: &mut Vec<Command>, target: ScanTarget, slot: usize) -> Result<()> {
let ScanTarget { source, elements, is_half: half } = target;
let status = self.handle(&self.status, STATUS)?.checked_subspan(STATUS, slot * 4, 4)?;
kernel(
commands,
@@ -122,7 +117,8 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
let status = self.handle(&self.status, STATUS)?;
let zero = blank(STATUS)?;
let mut got = blank(STATUS)?;
let (outcome, retain) = self.run_device(workspace, status, &mut commands, &zero, &mut got)?;
let staging = StatusStaging { zero: &zero, readback: &mut got };
let (outcome, retain) = self.run_device(workspace, status, &mut commands, staging)?;
if retain {
std::mem::forget((commands, zero, got));
self.context.retain_driver();
@@ -139,9 +135,9 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
workspace: &mut NativeBatchWorkspace<'ctx>,
status: BufferHandle,
commands: &mut [Command],
zero: &[u8],
got: &mut [u8],
staging: StatusStaging<'_>,
) -> Result<(Result<()>, bool)> {
let StatusStaging { zero, readback: got } = staging;
let blas = workspace.blas()?;
let guard = self.context.enter()?;
let mut operation = self.issue(blas, status, zero, commands);
@@ -185,14 +181,17 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
match command {
Command::Kernel { dequant, index, grid, args } => {
let module = if *dequant { &self.dequant } else { &self.moe };
module.as_ref().ok_or(Error::ContextPoisoned)?.launch(*index, *grid, 256, blas.stream(), args)
module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
*index,
LinearLaunch::new(*grid, 256, blas.stream()),
args,
)
}
Command::Gemm { bf16, input, weight, output, t, n, k, beta } => {
if *bf16 {
blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, &1.0, beta)
} else {
blas.gemm_f16(*input, *weight, *output, *t, *n, *k, &1.0, beta)
}
let operands = GemmOperands { x: *input, w: *weight, y: *output };
let dims = GemmDims { tokens: *t, outputs: *n, depth: *k };
let scalars = GemmScalars { alpha: &1.0, beta };
if *bf16 { blas.gemm_bf16(operands, dims, scalars) } else { blas.gemm_f16(operands, dims, scalars) }
}
}
}
@@ -12,9 +12,9 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
workspace: &mut NativeBatchWorkspace<'ctx>,
weights: [&DeviceBuffer<'_>; 5],
formats: [GdnNativeFormat; 3],
low: bool,
layout: SharedExpertLayout,
) -> Result<OriginalMoePromptLayer<'program, 'arena, 'loan, 'ctx>> {
let SharedExpertLayout { formats, has_low_half: low } = layout;
if !read.context_matches(self.context) || read.rows() == 0 || read.rows() > self.capacity {
return Err(Error::ContextMismatch);
}
@@ -41,6 +41,30 @@ fn shared_spans(rows: &OriginalPromptRows<'_, '_, '_>) -> Result<([BufferHandle;
Ok(([gate, up, down], h, phase(rows, "sg", 4)?))
}
/// The BF16 GEMM of the mixed high half into `output` (beta 0) and, when the spans keep a low half, the low-half GEMM
/// accumulated into the same output (beta 1).
fn push_mixed_gemm(
commands: &mut Vec<Command>,
sp: &MoeSpans,
weight: BufferHandle,
(output, size): (BufferHandle, GemmSize),
) -> Result<()> {
gemm(commands, true, GemmOperands { x: sp.high, w: weight, y: output }, size, 0.0)?;
if let Some(lo) = sp.low {
gemm(commands, true, GemmOperands { x: lo, w: weight, y: output }, size, 1.0)?;
}
Ok(())
}
/// One shared expert stage: its index (gate, up, down), the format of its weight and the scratch span the weight is
/// dequantized into.
#[derive(Clone, Copy)]
pub(super) struct SharedStage {
index: usize,
format: GdnNativeFormat,
scratch: BufferHandle,
}
/// The router, scalar gate and three shared native weights.
pub(super) struct MoeWeights {
router: BufferHandle,
@@ -100,23 +124,17 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
commands.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?;
self.push_route(&mut commands, (sp, mw), t)?;
for index in 0..3 {
self.push_shared(&mut commands, (sp, mw), (index, formats[index]), scratch, t)?;
self.push_shared(&mut commands, (sp, mw), SharedStage { index, format: formats[index], scratch }, t)?;
}
gemm(&mut commands, true, sp.high, mw.scalar, sp.sg, t, 1, 2560, 0.0)?;
if let Some(lo) = sp.low {
gemm(&mut commands, true, lo, mw.scalar, sp.sg, t, 1, 2560, 1.0)?;
}
self.scan(&mut commands, sp.sg, t, false, 7)?;
push_mixed_gemm(&mut commands, sp, mw.scalar, (sp.sg, GemmSize { tokens: t, outputs: 1, depth: 2560 }))?;
self.scan(&mut commands, ScanTarget::float32(sp.sg, t), 7)?;
Ok(commands)
}
fn push_route(&self, commands: &mut Vec<Command>, (sp, mw): (&MoeSpans, &MoeWeights), t: usize) -> Result<()> {
self.scan(commands, sp.half, t * 2560, true, 0)?;
gemm(commands, true, sp.high, mw.router, sp.logits, t, 512, 2560, 0.0)?;
if let Some(lo) = sp.low {
gemm(commands, true, lo, mw.router, sp.logits, t, 512, 2560, 1.0)?;
}
self.scan(commands, sp.logits, t * 512, false, 1)?;
self.scan(commands, ScanTarget::float16(sp.half, t * 2560), 0)?;
push_mixed_gemm(commands, sp, mw.router, (sp.logits, GemmSize { tokens: t, outputs: 512, depth: 2560 }))?;
self.scan(commands, ScanTarget::float32(sp.logits, t * 512), 1)?;
// route_kernel<16>: one warp/token, eight token rows per256-thread CTA.
commands.push(Command::Kernel {
dequant: false,
@@ -129,7 +147,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
A::I64(t as i64),
]),
});
self.scan(commands, sp.w, t * 10, false, 2)
self.scan(commands, ScanTarget::float32(sp.w, t * 10), 2)
}
/// Shared expert stage `index` (gate, up, down): dequantize the weight, multiply, guard; SwiGLU after up.
@@ -137,10 +155,10 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
&self,
commands: &mut Vec<Command>,
(sp, mw): (&MoeSpans, &MoeWeights),
(index, format): (usize, GdnNativeFormat),
scratch: BufferHandle,
stage: SharedStage,
t: usize,
) -> Result<()> {
let SharedStage { index, format, scratch } = stage;
let (n, k) = DIMS[index];
let destination = sp.shared[index];
let dequant = vec![
@@ -152,12 +170,13 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
A::Address(scratch),
];
kernel(commands, true, dequant_index(format), n * (k / 32), dequant)?;
gemm(commands, false, if index == 2 { sp.h } else { sp.half }, scratch, destination, t, n, k, 0.0)?;
self.scan(commands, destination, t * n, false, [3, 4, 6][index])?;
let operands = GemmOperands { x: if index == 2 { sp.h } else { sp.half }, w: scratch, y: destination };
gemm(commands, false, operands, GemmSize { tokens: t, outputs: n, depth: k }, 0.0)?;
self.scan(commands, ScanTarget::float32(destination, t * n), [3, 4, 6][index])?;
if index == 1 {
let swiglu = vec![A::Address(sp.shared[0]), A::Address(sp.shared[1]), A::Address(sp.h), A::I64(t as i64)];
kernel(commands, false, 5, t * 640, swiglu)?;
self.scan(commands, sp.h, t * 640, true, 5)?;
self.scan(commands, ScanTarget::float16(sp.h, t * 640), 5)?;
}
Ok(())
}
+1 -1
View File
@@ -25,7 +25,7 @@
#[path = "original_mtp_actor_loaded.rs"]
mod loaded;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use loaded::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter};
pub use loaded::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter, OriginalMtpLoadedParts};
/// Original `load` default. It becomes an effective window only after actual
/// geometry/KV admission; storing this number does not select a ring.
@@ -44,6 +44,21 @@ pub struct OriginalMtpLoadEvidence {
draft_vocabulary: Option<usize>,
}
/// What `OriginalMtpActor::adopt` takes over from load and bind: the assembled drafter, the draft ring it was bound to
/// (only inspected) and the retained weights it reads.
pub struct OriginalMtpLoadedParts<'a, 'ctx> {
pub drafter: OriginalMtpDrafter<'ctx>,
pub ring: &'a MtpOriginalInt8<'ctx>,
pub weights: Rc<OriginalMtpRetainedFullWeights<'ctx>>,
}
/// The loaded owners `admit` checks against each other: the drafter (checked through `&mut`), the ring and weights.
struct LoadedOwners<'a, 'ctx> {
drafter: &'a mut OriginalMtpDrafter<'ctx>,
ring: &'a MtpOriginalInt8<'ctx>,
weights: &'a OriginalMtpRetainedFullWeights<'ctx>,
}
pub struct OriginalMtpActor<'ctx> {
// Field order is destructor order: the drafter (stream drain, graphs,
// scratch and mapped owners) goes before the weights it reads.
@@ -11,13 +11,13 @@ impl<'ctx> OriginalMtpActor<'ctx> {
pub fn adopt(
context: &'ctx Context<'ctx>,
plan: OriginalMtpLoadPlan,
drafter: OriginalMtpDrafter<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
weights: Rc<OriginalMtpRetainedFullWeights<'ctx>>,
parts: OriginalMtpLoadedParts<'_, 'ctx>,
evidence: OriginalMtpLoadEvidence,
) -> std::result::Result<Self, OriginalMtpLoadFailure> {
let OriginalMtpLoadedParts { drafter, ring, weights } = parts;
let mut drafter = drafter;
match Self::admit(context, &plan, &mut drafter, ring, &weights, evidence) {
let mut owners = LoadedOwners { drafter: &mut drafter, ring, weights: &weights };
match Self::admit(context, &plan, &mut owners, evidence) {
Ok((kv, disposition, coupled)) => Ok(Self {
drafter: Some(drafter),
weights,
@@ -41,13 +41,12 @@ impl<'ctx> OriginalMtpActor<'ctx> {
pub(in super::super) fn admit(
context: &'ctx Context<'ctx>,
plan: &OriginalMtpLoadPlan,
drafter: &mut OriginalMtpDrafter<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
weights: &OriginalMtpRetainedFullWeights<'ctx>,
owners: &mut LoadedOwners<'_, 'ctx>,
evidence: OriginalMtpLoadEvidence,
) -> std::result::Result<(KvPlan, SetupDisposition, CoupledDraftHost), OriginalMtpLoadFailure> {
let capture = *plan.capture();
Self::check_loaded(context, &capture, drafter, ring, weights, evidence)?;
Self::check_loaded(context, &capture, owners, evidence)?;
let LoadedOwners { drafter, ring, weights } = owners;
// The retained state's ACTUAL mode, not a configured one: window ring
// as planned, or the Original fully-resident retry.
let kv = plan
@@ -61,11 +60,10 @@ impl<'ctx> OriginalMtpActor<'ctx> {
fn check_loaded(
context: &'ctx Context<'ctx>,
capture: &crate::original_mtp_loader::OriginalMtpCapture,
drafter: &mut OriginalMtpDrafter<'ctx>,
ring: &MtpOriginalInt8<'ctx>,
weights: &OriginalMtpRetainedFullWeights<'ctx>,
owners: &mut LoadedOwners<'_, 'ctx>,
evidence: OriginalMtpLoadEvidence,
) -> std::result::Result<(), OriginalMtpLoadFailure> {
let LoadedOwners { drafter, ring, weights } = owners;
drafter.validate_context(context).map_err(inconsistent)?;
ring.validate_context(context).map_err(inconsistent)?;
weights.validate_context(context).map_err(inconsistent)?;
+21 -12
View File
@@ -4,6 +4,7 @@
//! loader's placement/ordering/refusal behaviour, not model quality.
use super::*;
use crate::Driver;
use crate::original_mtp_draft_head::OriginalMainHead;
use crate::original_mtp_rt::fixtures::{self as fx, TempDir};
const ENABLE: &str = "LELEKA_MTP_RT_BANK_GPU";
@@ -30,21 +31,27 @@ fn rt_bank_places_every_tensor_and_the_expert_chunks_exactly() {
fx::write(&dir, "experts.bin", &experts);
let baseline = context.allocated_bytes();
bank_places_tensors_and_chunks(&context, &dir, &text, &blob, &experts, baseline);
bank_places_tensors_and_chunks(
&context,
BankFixture { dir: &dir, text: &text, blob: &blob, experts: &experts },
baseline,
);
bank_refusals_leave_no_allocation(&context, &dir, &text, &experts, baseline);
// the budget refusal plays cudaMalloc's: Original text plus the sizes
let tight = device.create_context(blob.len() + 16).expect("tight context");
bank_budget_refusal(&tight, &dir, &experts);
}
fn bank_places_tensors_and_chunks(
context: &Context<'_>,
dir: &TempDir,
text: &str,
blob: &[u8],
experts: &[u8],
baseline: usize,
) {
/// The files of the fixture bank: its directory, the dense index text, the dense blob and the expert bytes.
struct BankFixture<'a> {
dir: &'a TempDir,
text: &'a str,
blob: &'a [u8],
experts: &'a [u8],
}
fn bank_places_tensors_and_chunks(context: &Context<'_>, fixture: BankFixture<'_>, baseline: usize) {
let BankFixture { dir, text, blob, experts } = fixture;
let bank = context.original_mtp_rt_bank(&dir.0, 3).expect("bank");
assert_eq!(bank.device(), 0);
assert_eq!(bank.vram_bytes(), (blob.len() + experts.len()) as u64);
@@ -141,9 +148,10 @@ fn gather_width_matches<'c>(
let mut head = context.allocate(host.len()).unwrap();
head.copy_from(&host).unwrap();
// absent file: Original ignores it
assert!(context.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary).unwrap().is_none());
let main = OriginalMainHead { weights: &head, kind: 8, columns, vocabulary };
assert!(context.original_mtp_draft_head(&dir.0, main).unwrap().is_none());
fx::write(dir, "draft_vocab.bin", &ids.iter().flat_map(|i| i.to_le_bytes()).collect::<Vec<_>>());
let draft = context.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary).unwrap().expect("subset head");
let draft = context.original_mtp_draft_head(&dir.0, main).unwrap().expect("subset head");
assert_eq!((draft.count(), draft.row_bytes()), (ids.len(), row_bytes));
let expected: Vec<u8> =
ids.iter().flat_map(|&id| host[id as usize * row_bytes..(id as usize + 1) * row_bytes].to_vec()).collect();
@@ -168,7 +176,8 @@ fn gather_rejects_ids_outside_the_vocabulary(
) {
// an id outside the vocabulary never reaches the kernel
fx::write(dir, "draft_vocab.bin", &50i32.to_le_bytes());
let error = context.original_mtp_draft_head(&dir.0, head, 8, columns, vocabulary).err().expect("range");
let main = OriginalMainHead { weights: head, kind: 8, columns, vocabulary };
let error = context.original_mtp_draft_head(&dir.0, main).err().expect("range");
assert!(error.message().contains("outside the vocabulary"));
std::fs::remove_file(dir.0.join("draft_vocab.bin")).unwrap();
}
@@ -65,18 +65,32 @@ impl<'ctx> OriginalMtpDraftHead<'ctx> {
}
}
/// The main native head the draft head is gathered from: its `NativeHead::weights()` allocation, the quantisation
/// kind, the column count and the vocabulary rows.
#[derive(Clone, Copy)]
pub struct OriginalMainHead<'a, 'ctx> {
pub weights: &'a DeviceBuffer<'ctx>,
pub kind: u32,
pub columns: usize,
pub vocabulary: usize,
}
/// The three device buffers of one row gather: the source rows, the row ids and the destination rows.
struct GatherBuffers<'a> {
source: &'a DeviceBuffer<'a>,
ids: &'a DeviceBuffer<'a>,
destination: &'a DeviceBuffer<'a>,
}
impl<'ctx> Context<'ctx> {
/// Returns `Ok(None)` exactly where Original ignores the file. `head` is the
/// main `NativeHead::weights()` allocation (`vocabulary` rows of
/// `columns` elements in `head_kind`).
/// Returns `Ok(None)` exactly where Original ignores the file. `main.weights` is the main
/// `NativeHead::weights()` allocation (`vocabulary` rows of `columns` elements in `kind`).
pub fn original_mtp_draft_head(
&'ctx self,
directory: &Path,
head: &DeviceBuffer<'ctx>,
head_kind: u32,
columns: usize,
vocabulary: usize,
main: OriginalMainHead<'_, 'ctx>,
) -> std::result::Result<Option<OriginalMtpDraftHead<'ctx>>, OriginalMtpLoadFailure> {
let OriginalMainHead { weights: head, kind: head_kind, columns, vocabulary } = main;
let ids = match rt::read_draft_vocab(directory)? {
DraftVocab::Absent => return Ok(None),
DraftVocab::Subset(ids) => ids,
@@ -130,7 +144,7 @@ impl<'ctx> Context<'ctx> {
.allocate(count.checked_mul(row_bytes).ok_or_else(|| head_refusal(Error::InvalidSize))?)
.map_err(head_refusal)?;
forward.copy_from(&id_bytes).map_err(head_refusal)?;
self.gather_rows(head, &forward, &rows, row_bytes, count)
self.gather_rows(GatherBuffers { source: head, ids: &forward, destination: &rows }, row_bytes, count)
.map_err(|cause| OriginalMtpLoadFailure::new("mtp: the draft head gather failed", Some(cause)))?;
Ok((forward, rows))
}
@@ -153,14 +167,8 @@ impl<'ctx> Context<'ctx> {
/// `strata::kernels::gather_rows(src, row_bytes, ids, n, dst, nullptr)` then
/// `cudaDeviceSynchronize`: one launch on the legacy stream, completed
/// before return. A launch or drain failure poisons the context.
fn gather_rows(
&self,
source: &DeviceBuffer<'_>,
ids: &DeviceBuffer<'_>,
destination: &DeviceBuffer<'_>,
row_bytes: usize,
rows: usize,
) -> Result<()> {
fn gather_rows(&self, buffers: GatherBuffers<'_>, row_bytes: usize, rows: usize) -> Result<()> {
let GatherBuffers { source, ids, destination } = buffers;
let (name, unit) = gather_kernel(row_bytes);
let mut command = Command::new(
name,
@@ -44,6 +44,14 @@ pub(crate) enum OriginalMtpPrefillAction {
/// Affine input borrow retained through the complete host schedule. No arbitrary
/// DeviceBuffer or host F32 slice can be substituted for the actual prompt R.
/// What a public prefill is planned from: the prompt residual, its tokens, the first cell and the sync mode.
#[derive(Clone, Copy)]
pub(crate) struct OriginalMtpPrefillRequest<'source, 'arena, 'loan, 'ctx> {
pub(crate) residual: Option<&'source OriginalDeviceResidual<'arena, 'loan, 'ctx>>,
pub(crate) tokens: &'source [i32],
pub(crate) cell0: usize,
pub(crate) sync: OriginalMtpPrefillSync,
}
pub(crate) struct OriginalMtpPrefillPlan<'source, 'arena, 'loan, 'ctx> {
residual: Option<&'source OriginalDeviceResidual<'arena, 'loan, 'ctx>>,
tokens: &'source [i32],
@@ -30,18 +30,15 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
/// Concrete genuine-source preparation for the literal public prefill host
/// loop. This returns NO successful-KV product and enqueues no CUDA work.
#[allow(clippy::too_many_arguments)]
pub(crate) fn plan_public_prefill<'source, 'arena, 'loan>(
&self,
residual: Option<&'source OriginalDeviceResidual<'arena, 'loan, 'ctx>>,
request: OriginalMtpPrefillRequest<'source, 'arena, 'loan, 'ctx>,
ring: &MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
tokens: &'source [i32],
cell0: usize,
settings: &DraftSettings,
sync: OriginalMtpPrefillSync,
) -> Result<OriginalMtpPrefillPlan<'source, 'arena, 'loan, 'ctx>> {
self.check_prefill_inputs(residual, ring, prior, tokens, cell0)?;
let OriginalMtpPrefillRequest { residual, tokens, cell0, sync } = request;
self.check_prefill_inputs(request, ring, prior)?;
// Loaded existing owner is the literal fixed-window branch. A future
// custom-window SessionState must expose its own authenticated geometry,
// not pass a guessed cutoff to this method.
@@ -62,12 +59,11 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
}
fn check_prefill_inputs(
&self,
residual: Option<&OriginalDeviceResidual<'_, '_, 'ctx>>,
request: OriginalMtpPrefillRequest<'_, '_, '_, 'ctx>,
ring: &MtpOriginalInt8<'ctx>,
prior: &MtpInt8Snapshot,
tokens: &[i32],
cell0: usize,
) -> Result<()> {
let OriginalMtpPrefillRequest { residual, tokens, cell0, .. } = request;
self.check_prefill_ring(ring, prior)?;
if cell0.checked_add(tokens.len()).is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) {
return Err(Error::InvalidProjectionShape);
@@ -71,7 +71,6 @@ fn run(batch: bool, memory: Memory) {
let driver = Driver::load().unwrap();
let ctx = driver.device(0).unwrap().create_context(64 << 20).unwrap();
let mut dest = ctx.allocate(DEST).unwrap();
let destination = dest.handle.expect("live buffer").qwen_address();
let mut stream = ctx.original_gpu_stream(OriginalStreamKind::NonBlocking).unwrap();
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
@@ -83,7 +82,7 @@ fn run(batch: bool, memory: Memory) {
let locked_end = memory.locked_end(base);
let api = register_locked(&ctx, base, locked_end);
let checked = run_rounds(&mut rng, source, (base, locked_end), destination, (&mut stream, &mut dest), batch);
let checked = run_rounds(&mut rng, source, (base, locked_end), (&mut stream, &mut dest), batch);
println!(
"pcie copy smoke: batch={batch} memory={} rounds={} pieces={checked}: all bytes exact",
memory.name(),
@@ -102,16 +101,16 @@ fn run_rounds(
rng: &mut Rng,
source: &[u8],
bounds: (usize, usize),
destination: u64,
(stream, dest): (&mut OriginalGpuStream<'_>, &mut DeviceBuffer<'_>),
batch: bool,
) -> usize {
let destination = dest.handle.expect("live buffer").qwen_address();
let mut expected = vec![0xA5u8; DEST];
dest.copy_from(&expected).unwrap();
let mut checked = 0usize;
for round in 0..rounds() {
let pieces = build_group(rng, source, bounds, destination, &mut expected);
check_round(round, stream, dest, &pieces, batch, &expected);
check_round(stream, dest, CopyRound { index: round, pieces: &pieces, uses_batch: batch }, &expected);
checked += pieces.len();
}
checked
@@ -179,14 +178,20 @@ fn build_group<'s>(
pieces
}
/// One round of the smoke: its index for failure messages, the pieces copied and whether they go as one batch.
struct CopyRound<'a> {
index: usize,
pieces: &'a [(u64, &'a [u8])],
uses_batch: bool,
}
fn check_round(
round: usize,
stream: &mut OriginalGpuStream<'_>,
dest: &DeviceBuffer<'_>,
pieces: &[(u64, &[u8])],
batch: bool,
copy_round: CopyRound<'_>,
expected: &[u8],
) {
let CopyRound { index: round, pieces, uses_batch: batch } = copy_round;
stream.enqueue_copy_h2d_many(pieces, batch).unwrap_or_else(|e| panic!("round {round}: enqueue failed: {e:?}"));
stream
.synchronize()
+17 -1
View File
@@ -1,6 +1,6 @@
//! Original sampler host dispatch and model-owned resources. This producer samples
//! actual logits; it does not mint model/session/accepted-prefix authority.
use crate::original_sampler_ffi::{Arg, Command, KernelModule};
use crate::original_sampler_ffi::{Arg, Command, KernelModule, SamplerLaunchShape};
use crate::original_sampler_mapped::MappedAllocation;
use crate::{Context, DeviceBuffer, Error, Result, combine};
use std::ffi::CStr;
@@ -40,6 +40,22 @@ struct Launch {
shared: u32,
args: Command,
}
/// One verify window to sample: the logits of all its rows, the row count and the per-row token histories.
#[derive(Clone, Copy)]
pub struct SampleWindow<'a, 'ctx> {
pub logits: &'a DeviceBuffer<'ctx>,
pub rows: usize,
pub histories: &'a [i32],
}
/// How the window is sampled: the sampler parameters, the kernel path and whether the launch is graph-captured.
#[derive(Clone, Copy)]
pub struct SampleRequest {
pub params: SamplerParams,
pub path: SamplerPath,
pub is_captured: bool,
}
pub struct OriginalSampler<'ctx> {
context: &'ctx Context<'ctx>,
module: Option<KernelModule>,
@@ -36,13 +36,9 @@ impl<'ctx> OriginalSampler<'ctx> {
let mut operation = Ok(());
for command in commands {
if operation.is_ok() {
operation = self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(
command.entry,
command.grid,
command.block,
command.shared,
&mut command.args,
);
let shape = SamplerLaunchShape { grid: command.grid, block: command.block, shared: command.shared };
operation =
self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(command.entry, shape, &mut command.args);
}
}
Ok(operation)
@@ -82,21 +78,15 @@ impl<'ctx> OriginalSampler<'ctx> {
}
/// One actual verify window. Histories are actual row-specific IDs from the
/// caller's consumed tail/window, not a capability or inferred accepted prefix.
pub fn sample(
&mut self,
logits: &DeviceBuffer<'_>,
rows: usize,
histories: &[i32],
params: SamplerParams,
path: SamplerPath,
captured: bool,
) -> Result<Box<[i32]>> {
pub fn sample(&mut self, window: SampleWindow<'_, '_>, request: SampleRequest) -> Result<Box<[i32]>> {
let SampleWindow { logits, rows, histories } = window;
let SampleRequest { params, path, is_captured: captured } = request;
params.validate()?;
self.check_sample_request(rows, histories, &params)?;
self.admit(logits, rows * self.vocab * 4)?;
let split = self.wants_split(rows, &params, path, captured)?;
self.upload_histories(histories)?;
let mut commands = self.sample_commands(logits, rows, params, path, split)?;
let mut commands = self.sample_commands(window, request, split)?;
let result = self.run(&mut commands, true, false);
if self.context.is_poisoned() {
std::mem::forget(commands);
@@ -136,12 +126,12 @@ impl<'ctx> OriginalSampler<'ctx> {
}
fn sample_commands(
&self,
logits: &DeviceBuffer<'_>,
rows: usize,
params: SamplerParams,
path: SamplerPath,
window: SampleWindow<'_, '_>,
request: SampleRequest,
split: bool,
) -> Result<Vec<Launch>> {
let SampleWindow { logits, rows, .. } = window;
let SampleRequest { params, path, .. } = request;
let source = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address();
let history = if self.history > 0 { Arg::Address(self.address(1)?) } else { Arg::NullAddress };
let output = self.address(2)?;
+10 -9
View File
@@ -8,6 +8,13 @@ pub(crate) enum Arg {
I32(i32),
Params(SamplerParams),
}
/// Grid `[x, y]`, `block` threads and dynamic shared bytes of one sampler kernel launch.
#[derive(Clone, Copy)]
pub(crate) struct SamplerLaunchShape {
pub(crate) grid: [u32; 2],
pub(crate) block: u32,
pub(crate) shared: u32,
}
pub(crate) struct Command {
values: Vec<Arg>,
null: u64,
@@ -147,14 +154,8 @@ mod enabled {
}
Ok(())
}
pub(crate) fn launch(
&self,
index: usize,
grid: [u32; 2],
block: u32,
shared: u32,
args: &mut Command,
) -> Result<()> {
pub(crate) fn launch(&self, index: usize, shape: SamplerLaunchShape, args: &mut Command) -> Result<()> {
let SamplerLaunchShape { grid, block, shared } = shape;
check_launch_shape(grid, block, shared)?;
let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
bind_arguments(args)?;
@@ -218,7 +219,7 @@ impl KernelModule {
pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch(&self, _: usize, _: [u32; 2], _: u32, _: u32, args: &mut Command) -> Result<()> {
pub(crate) fn launch(&self, _: usize, _: SamplerLaunchShape, args: &mut Command) -> Result<()> {
let _ = (&args.values, &args.null, &args.pointers, &args.addresses);
Err(Error::UnsupportedPlatform)
}
@@ -116,6 +116,13 @@ fn upload_identity_page_table<B: OriginalQsaInitBackend>(
backend.upload(layout.span("page_table")?, &bytes_i32(&identity))
}
/// How the QSA RoPE tables are built: the rotated dimension count and the scaling.
#[derive(Clone, Copy)]
struct OriginalRopeSetup {
n_rot: usize,
scaling: OriginalRopeScaling,
}
impl<'ctx> OriginalSessionState<'ctx> {
/// Initializes one pre-carved QSA state, preserving source order. `primary`
/// has `owns_rope`; all later states share its exact two device spans.
@@ -130,7 +137,7 @@ impl<'ctx> OriginalSessionState<'ctx> {
self.validate_context(self.context)?;
let layout = self.checked_qsa_layout(ordinal, n_rot)?;
let (host_step, host_pos, host_kv) = mapped_hosts(backend, &layout)?;
self.init_rope(backend, ordinal, &layout, n_rot, scaling)?;
self.init_rope(backend, ordinal, &layout, OriginalRopeSetup { n_rot, scaling })?;
init_page_table(backend, &layout)?;
backend.synchronize()?;
Ok(OriginalQsaInitResources { host_step, host_pos, host_kv })
@@ -159,9 +166,9 @@ impl<'ctx> OriginalSessionState<'ctx> {
backend: &mut B,
ordinal: usize,
layout: &OriginalSessionQsaLayout,
n_rot: usize,
scaling: OriginalRopeScaling,
rope: OriginalRopeSetup,
) -> Result<()> {
let OriginalRopeSetup { n_rot, scaling } = rope;
if ordinal == self.layout.qsa_ord0 {
self.upload_rope(backend, layout, n_rot, scaling)?;
self.layout.qsa[ordinal].as_mut().ok_or(Error::InvalidQwenShape)?.owns_rope = true;
@@ -98,6 +98,21 @@ struct QsaPrice {
charge: usize,
}
/// The layer range `[lo, hi)` a session holds; `hi == -1` means up to the last layer.
#[derive(Clone, Copy)]
pub(crate) struct OriginalLayerBounds {
pub lo: i64,
pub hi: i64,
}
/// What a QSA state is carved against: the model geometry, the cell count and the KV policy.
#[derive(Clone, Copy)]
pub(crate) struct OriginalSessionShape {
pub geometry: OriginalSessionGeometry,
pub cells: usize,
pub policy: OriginalSessionKvPolicy,
}
/// Two distinct Original counts: advertised session_bytes vs aligned init used.
/// Metadata describes actual byte layout; it does not certify initialized state.
pub(crate) struct OriginalSessionLayout {
@@ -12,11 +12,10 @@ impl OriginalSessionLayout {
g: OriginalSessionGeometry,
cells: usize,
k: usize,
lo: i64,
hi: i64,
layers: OriginalLayerBounds,
p: OriginalSessionKvPolicy,
) -> Result<Self> {
let r = Request { g, cells, k, bounds: (lo, hi), p };
let r = Request { g, cells, k, bounds: (layers.lo, layers.hi), p };
r.check()?;
let layers = r.layer_range()?;
let split = r.split(layers)?;
@@ -147,7 +147,8 @@ impl Request {
let price = if j == 0 { &s.first } else { &s.rest };
let share = rope_share(&qsa, split.qsa_ord0, j)?;
let at = split.qsa_ord0 + j;
qsa[at] = Some(qsa_carve(self.g, self.cells, self.p, at, arena.at(offset, price.charge)?, price, share)?);
let shape = OriginalSessionShape { geometry: self.g, cells: self.cells, policy: self.p };
qsa[at] = Some(qsa_carve(shape, at, arena.at(offset, price.charge)?, price, share)?);
}
Ok(qsa)
}
@@ -244,14 +244,13 @@ impl Carver {
}
pub(super) fn qsa_carve(
g: OriginalSessionGeometry,
cells: usize,
p: OriginalSessionKvPolicy,
shape: OriginalSessionShape,
ordinal: usize,
arena: OriginalSessionSpan,
price: &QsaPrice,
share: Option<(OriginalSessionSpan, OriginalSessionSpan)>,
) -> Result<OriginalSessionQsaLayout> {
let OriginalSessionShape { geometry: g, cells, policy: p } = shape;
let mut carver = Carver::new(arena.offset)?;
let flags = carver.take_kv(g, price, p)?;
carver.take_tables(g, price)?;
@@ -10,6 +10,19 @@ pub struct OriginalStreamAllOptions {
pub minimum_rows: usize,
pub issuer: bool,
}
/// The copy stream that moves expert blobs and the compute stream that consumes them in one stream-all pass.
pub struct OriginalStreamPair<'ctx> {
pub copy: OriginalGpuStream<'ctx>,
pub compute: OriginalGpuStream<'ctx>,
}
/// The layers `first..end` a stream-all pass covers, its options and the host bytes it may use.
#[derive(Clone, Copy)]
pub struct OriginalStreamAllPass {
pub first: u8,
pub end: u8,
pub options: OriginalStreamAllOptions,
pub host_allowance: usize,
}
#[derive(Clone, Copy)]
struct Entry {
layer: u8,
@@ -12,17 +12,14 @@ impl<'ctx> OriginalExpertStager<'ctx> {
pub fn run_stream_all_forward<'arena, 'loan, T>(
&mut self,
rows: OriginalPromptRows<'arena, 'loan, 'ctx>,
copy: OriginalGpuStream<'ctx>,
compute: OriginalGpuStream<'ctx>,
first: u8,
end: u8,
options: OriginalStreamAllOptions,
host_allowance: usize,
streams: OriginalStreamPair<'ctx>,
pass: OriginalStreamAllPass,
consumer: impl FnOnce(
&mut OriginalStreamAllForward<'_, '_, 'arena, 'loan, 'ctx>,
OriginalPromptRows<'arena, 'loan, 'ctx>,
) -> (Result<T>, Option<OriginalPromptRows<'arena, 'loan, 'ctx>>),
) -> Result<(T, OriginalStreamAllCompleted<'arena, 'loan, 'ctx>)> {
let OriginalStreamAllPass { first, end, options, host_allowance } = pass;
if first >= end || end > 48 {
return Err(Error::InvalidQwenShape);
}
@@ -35,7 +32,7 @@ impl<'ctx> OriginalExpertStager<'ctx> {
let resident = resident_spans(&rows, (first, end), count)?;
let lease = rows.lease_identity();
let row_count = rows.rows();
self.run_stream_all(rows, copy, compute, first, end, options, remaining, move |scope| {
self.run_stream_all(rows, streams, OriginalStreamAllPass { host_allowance: remaining, ..pass }, move |scope| {
run_forward_consumer(scope, (lease, row_count, resident), consumer)
})
}
@@ -11,14 +11,12 @@ impl<'ctx> OriginalExpertStager<'ctx> {
pub fn run_stream_all<'arena, 'loan, T>(
&mut self,
rows: OriginalPromptRows<'arena, 'loan, 'ctx>,
copy: OriginalGpuStream<'ctx>,
compute: OriginalGpuStream<'ctx>,
first: u8,
end: u8,
options: OriginalStreamAllOptions,
host_allowance: usize,
streams: OriginalStreamPair<'ctx>,
pass: OriginalStreamAllPass,
consumer: impl FnOnce(&mut OriginalStreamAll<'_, 'arena, 'loan, 'ctx>) -> Result<T>,
) -> Result<(T, OriginalStreamAllCompleted<'arena, 'loan, 'ctx>)> {
let OriginalStreamPair { copy, compute } = streams;
let OriginalStreamAllPass { first, end, options, host_allowance } = pass;
let ring = self.stream_preflight(&rows, (&copy, &compute), (first, end), options)?;
self.check_stream_budget(options, host_allowance)?;
let (mut entries, targets) = self.reserve_stream_targets(&rows, ring)?;
@@ -19,6 +19,13 @@ impl Streamed<'_> {
}
}
/// A layer of a stream-all walk and the end of its entries in the job list.
#[derive(Clone, Copy)]
struct WalkedLayer {
layer: u8,
end: usize,
}
/// One expert of a sorted layer list and its place in the 16-wide gather groups.
pub(crate) struct GroupStep<'a> {
expert: u32,
@@ -104,7 +111,7 @@ impl<'s, 'arena, 'loan, 'ctx> OriginalStreamAll<'s, 'arena, 'loan, 'ctx> {
) -> Result<()> {
let layer_end = self.layer_start[layer as usize + 1];
for &e in experts {
self.walk_expert(layer, layer_end, e, &mut producer, &mut resident)?;
self.walk_expert(WalkedLayer { layer, end: layer_end }, e, &mut producer, &mut resident)?;
}
self.release_unused(512, layer_end)?;
self.next_layer += 1;
@@ -112,12 +119,12 @@ impl<'s, 'arena, 'loan, 'ctx> OriginalStreamAll<'s, 'arena, 'loan, 'ctx> {
}
fn walk_expert(
&mut self,
layer: u8,
layer_end: usize,
walked: WalkedLayer,
e: u32,
producer: &mut impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'ctx>) -> Result<()>,
resident: &mut impl FnMut(&Self, u8, u32) -> Result<(BufferHandle, usize)>,
) -> Result<()> {
let WalkedLayer { layer, end: layer_end } = walked;
self.release_unused(e, layer_end)?;
self.healthy()?;
if self.streams_next(e, layer_end) {
@@ -146,7 +153,7 @@ impl<'s, 'arena, 'loan, 'ctx> OriginalStreamAll<'s, 'arena, 'loan, 'ctx> {
group_ids[slot] = expert;
let last = slot + 1 == ORIGINAL_MMQ_GROUP || j + 1 == experts.len();
let step = GroupStep { expert, ids: &group_ids[..slot + 1], j, slot, last };
self.group_step(layer, layer_end, &step, producer, &mut resident)?;
self.group_step(WalkedLayer { layer, end: layer_end }, &step, producer, &mut resident)?;
}
self.release_unused(512, layer_end)?;
self.next_layer += 1;
@@ -154,12 +161,12 @@ impl<'s, 'arena, 'loan, 'ctx> OriginalStreamAll<'s, 'arena, 'loan, 'ctx> {
}
fn group_step<P: OriginalStreamAllGroupProducer<'ctx>>(
&mut self,
layer: u8,
layer_end: usize,
walked: WalkedLayer,
step: &GroupStep<'_>,
producer: &mut P,
resident: &mut impl FnMut(&Self, u8, u32) -> Result<(BufferHandle, usize)>,
) -> Result<()> {
let WalkedLayer { layer, end: layer_end } = walked;
let context = self.stager.context;
if self.streams_next(step.expert, layer_end) {
return self.consume_streamed(layer, |st, compute| {
+55
View File
@@ -22,6 +22,61 @@ pub(crate) enum InputType {
Bf16,
F16,
}
/// The three device operands of one 16-bit GEMM `y = x * w^T`: activations, weight matrix and F32 output.
#[derive(Clone, Copy)]
pub(crate) struct GemmOperands {
pub(crate) x: BufferHandle,
pub(crate) w: BufferHandle,
pub(crate) y: BufferHandle,
}
/// Tokens, output columns and depth of a GEMM: `y[tokens][outputs] = x[tokens][depth] * w[outputs][depth]^T`.
#[derive(Clone, Copy)]
pub(crate) struct GemmDims {
pub(crate) tokens: i32,
pub(crate) outputs: i32,
pub(crate) depth: i32,
}
/// The scalars of `y = alpha * x * w^T + beta * y`; the admitted shapes accept only `alpha == 1`.
#[derive(Clone, Copy)]
pub(crate) struct GemmScalars<'a> {
pub(crate) alpha: &'a f32,
pub(crate) beta: &'a f32,
}
/// Element format and output placement of a GDN GEMM: BF16 or F16 inputs, the output row stride in F32 words and the
/// offset of the first output word.
#[derive(Clone, Copy)]
pub(crate) struct GdnGemmLayout {
pub(crate) is_bf16: bool,
pub(crate) ldy: i32,
pub(crate) y_offset: usize,
}
/// Grid, block and stream of a one-dimensional kernel launch.
#[derive(Clone, Copy)]
pub(crate) struct LinearLaunch {
pub(crate) grid: u32,
pub(crate) block: u32,
pub(crate) stream: usize,
}
impl LinearLaunch {
/// A launch of `grid` blocks of `block` threads on `stream`.
pub(crate) const fn new(grid: u32, block: u32, stream: usize) -> Self {
Self { grid, block, stream }
}
}
/// The grid `[x, y]`, `block` threads, cluster width and dynamic shared memory of one cluster launch.
#[derive(Clone, Copy)]
pub(crate) struct ClusterShape {
pub(crate) grid: [u32; 2],
pub(crate) block: u32,
pub(crate) cluster_x: u32,
pub(crate) smem: u32,
}
impl ClusterShape {
/// A cluster launch of `grid` blocks of `block` threads in clusters of `cluster_x` with `smem` shared bytes.
pub(crate) const fn new(grid: [u32; 2], block: u32, cluster_x: u32, smem: u32) -> Self {
Self { grid, block, cluster_x, smem }
}
}
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod enabled;
@@ -61,19 +61,16 @@ impl Blas {
pub(crate) fn stream(&self) -> usize {
self.stream.expect("private live stream")
}
#[allow(clippy::too_many_arguments)]
pub(super) fn gemm(
&self,
kind: InputType,
x: BufferHandle,
w: BufferHandle,
y: BufferHandle,
t: i32,
n: i32,
k: i32,
alpha: &f32,
beta: &f32,
operands: GemmOperands,
dims: GemmDims,
scalars: GemmScalars<'_>,
) -> Result<()> {
let GemmOperands { x, w, y } = operands;
let GemmDims { tokens: t, outputs: n, depth: k } = dims;
let GemmScalars { alpha, beta } = scalars;
if !gemm_shape_admitted((t, n, k), alpha, beta) {
return Err(Error::InvalidQwenShape);
}
@@ -88,47 +85,23 @@ impl Blas {
let call = GemmEx { x, w, y, dtype, dims: (t, n, k), ldy: n, alpha, beta };
self.gemm_ex(call) // OP_T/OP_N/F32/COMPUTE32F/DEFAULT
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_bf16(
&self,
x: BufferHandle,
w: BufferHandle,
y: BufferHandle,
t: i32,
n: i32,
k: i32,
alpha: &f32,
beta: &f32,
) -> Result<()> {
self.gemm(InputType::Bf16, x, w, y, t, n, k, alpha, beta)
pub(crate) fn gemm_bf16(&self, operands: GemmOperands, dims: GemmDims, scalars: GemmScalars<'_>) -> Result<()> {
self.gemm(InputType::Bf16, operands, dims, scalars)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_f16(
&self,
x: BufferHandle,
w: BufferHandle,
y: BufferHandle,
t: i32,
n: i32,
k: i32,
alpha: &f32,
beta: &f32,
) -> Result<()> {
self.gemm(InputType::F16, x, w, y, t, n, k, alpha, beta)
pub(crate) fn gemm_f16(&self, operands: GemmOperands, dims: GemmDims, scalars: GemmScalars<'_>) -> Result<()> {
self.gemm(InputType::F16, operands, dims, scalars)
}
// Only the original interleaved Alpha/Beta whole bank, N48/K2560/ldy96.
// Caller authenticates the actual whole bank and derives no public span.
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_bf16_interleaved_ab(
&self,
x: BufferHandle,
w: BufferHandle,
ab: BufferHandle,
operands: GemmOperands,
t: i32,
beta_role: bool,
alpha: &f32,
beta: &f32,
scalars: GemmScalars<'_>,
) -> Result<()> {
let GemmOperands { x, w, y: ab } = operands;
let GemmScalars { alpha, beta } = scalars;
if !(1..=8192).contains(&t) || *alpha != 1.0 || (*beta != 0.0 && *beta != 1.0) {
return Err(Error::InvalidQwenShape);
}
@@ -147,20 +120,16 @@ impl Blas {
/// NativeGdnGemm before these private admitted addresses reach cuBLAS.
/// F16 admits QKV/Z/Out and Original shared expert; BF16 admits
/// interleaved Alpha/Beta and the Original router/shared scalar.
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_gdn(
&self,
bf16: bool,
x: BufferHandle,
w: BufferHandle,
y: BufferHandle,
t: i32,
n: i32,
k: i32,
ldy: i32,
y_offset: usize,
operands: GemmOperands,
dims: GemmDims,
layout: GdnGemmLayout,
beta: &f32,
) -> Result<()> {
let GemmOperands { x, w, y } = operands;
let GemmDims { tokens: t, outputs: n, depth: k } = dims;
let GdnGemmLayout { is_bf16: bf16, ldy, y_offset } = layout;
gdn_shape_admitted(bf16, (t, n, k), (ldy, y_offset), beta)?;
x.validate_projection_extent(t as usize * k as usize * 2, 2)?;
w.validate_projection_extent(n as usize * k as usize * 2, 2)?;
@@ -78,14 +78,8 @@ impl KernelModule {
}
Ok(())
}
pub(crate) fn launch(
&self,
index: usize,
grid: u32,
block: u32,
stream: usize,
args: &mut KernelArguments,
) -> Result<()> {
pub(crate) fn launch(&self, index: usize, launch: LinearLaunch, args: &mut KernelArguments) -> Result<()> {
let LinearLaunch { grid, block, stream } = launch;
if grid == 0 || !matches!(block, 128 | 256 | 512 | 1024) || stream == 0 {
return Err(Error::InvalidQwenShape);
}
@@ -106,13 +100,11 @@ impl KernelModule {
pub(crate) fn launch_cluster(
&self,
index: usize,
grid: [u32; 2],
block: u32,
cluster_x: u32,
smem: u32,
shape: ClusterShape,
stream: usize,
args: &mut KernelArguments,
) -> Result<()> {
let ClusterShape { grid, block, cluster_x, smem } = shape;
if !cluster_launch_admitted(grid, block, cluster_x, stream) {
return Err(Error::InvalidQwenShape);
}
@@ -124,7 +116,6 @@ impl KernelModule {
check("cuFuncSetAttribute", unsafe {
set_attribute(function as *mut c_void, crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED, smem as c_int)
})?;
let shape = ClusterShape { grid, block, cluster_x, smem };
launch_cluster_kernel(launch_ex, function, (shape, stream), args)
}
pub(crate) fn close(mut self) -> Result<()> {
@@ -151,14 +142,6 @@ impl Drop for KernelModule {
}
}
/// The grid `[x, y]`, `block` threads, cluster width and dynamic shared memory of one cluster launch.
struct ClusterShape {
grid: [u32; 2],
block: u32,
cluster_x: u32,
smem: u32,
}
/// A cluster launch needs a non-empty grid whose x extent the cluster width divides, 1..=1024 threads and a stream.
fn cluster_launch_admitted(grid: [u32; 2], block: u32, cluster_x: u32, stream: usize) -> bool {
!(grid[0] == 0
@@ -20,61 +20,16 @@ impl Blas {
pub(crate) fn stream(&self) -> usize {
0
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_bf16(
&self,
_: BufferHandle,
_: BufferHandle,
_: BufferHandle,
_: i32,
_: i32,
_: i32,
_: &f32,
_: &f32,
) -> Result<()> {
pub(crate) fn gemm_bf16(&self, _: GemmOperands, _: GemmDims, _: GemmScalars<'_>) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_f16(
&self,
_: BufferHandle,
_: BufferHandle,
_: BufferHandle,
_: i32,
_: i32,
_: i32,
_: &f32,
_: &f32,
) -> Result<()> {
pub(crate) fn gemm_f16(&self, _: GemmOperands, _: GemmDims, _: GemmScalars<'_>) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_bf16_interleaved_ab(
&self,
_: BufferHandle,
_: BufferHandle,
_: BufferHandle,
_: i32,
_: bool,
_: &f32,
_: &f32,
) -> Result<()> {
pub(crate) fn gemm_bf16_interleaved_ab(&self, _: GemmOperands, _: i32, _: bool, _: GemmScalars<'_>) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn gemm_gdn(
&self,
_: bool,
_: BufferHandle,
_: BufferHandle,
_: BufferHandle,
_: i32,
_: i32,
_: i32,
_: i32,
_: usize,
_: &f32,
) -> Result<()> {
pub(crate) fn gemm_gdn(&self, _: GemmOperands, _: GemmDims, _: GdnGemmLayout, _: &f32) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn synchronize(&self) -> Result<()> {
@@ -93,21 +48,11 @@ impl KernelModule {
pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch(&self, _: usize, _: u32, _: u32, _: usize, args: &mut KernelArguments) -> Result<()> {
pub(crate) fn launch(&self, _: usize, _: LinearLaunch, args: &mut KernelArguments) -> Result<()> {
let _ = (&args.values, &args.null, &args.pointers, &args.addresses);
Err(Error::UnsupportedPlatform)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn launch_cluster(
&self,
_: usize,
_: [u32; 2],
_: u32,
_: u32,
_: u32,
_: usize,
_: &mut KernelArguments,
) -> Result<()> {
pub(crate) fn launch_cluster(&self, _: usize, _: ClusterShape, _: usize, _: &mut KernelArguments) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn close(self) -> Result<()> {
@@ -58,6 +58,13 @@ pub struct PleBatchQueue<'ctx> {
mode: PleBf16Mode,
failed: bool,
}
/// The three host sources of one PLE batch: the per-row embeddings, the residual streams and the committed history.
#[derive(Clone, Copy)]
pub struct PleBatchSources<'a> {
pub embedding: &'a [f32],
pub streams: &'a [f32],
pub history: &'a [f32],
}
pub struct PleBatchRow {
pub streams: Box<[f32]>,
pub history: Box<[f32]>,
@@ -79,6 +86,8 @@ use assets_fn::assets;
mod impl_drop_for_plebatchqueue;
mod impl_plebatchqueue;
#[allow(unused_imports)]
use impl_drop_for_plebatchqueue::ScanExtent;
#[allow(unused_imports)]
use impl_drop_for_plebatchqueue::decode;
#[allow(unused_imports)]
use impl_drop_for_plebatchqueue::float_owner;
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars, LinearLaunch};
impl Drop for PleBatchQueue<'_> {
fn drop(&mut self) {
@@ -14,13 +15,18 @@ impl Command {
match self {
Self::Kernel { index, grid, block, args } => {
if *index == 0 {
pack.launch(0, *grid, *block, blas.stream(), args)
pack.launch(0, LinearLaunch::new(*grid, *block, blas.stream()), args)
} else {
module.launch(*index - 1, *grid, *block, blas.stream(), args)
module.launch(*index - 1, LinearLaunch::new(*grid, *block, blas.stream()), args)
}
}
Self::Gemm { input, weight, output, rows, n, alpha, beta } => {
blas.gemm_bf16(*input, *weight, *output, *rows, *n, 2560, alpha, beta)
let operands = GemmOperands { x: *input, w: *weight, y: *output };
blas.gemm_bf16(
operands,
GemmDims { tokens: *rows, outputs: *n, depth: 2560 },
GemmScalars { alpha, beta },
)
}
}
}
@@ -28,14 +34,26 @@ impl Command {
pub(super) fn push(commands: &mut Vec<Command>, index: usize, grid: u32, block: u32, args: Vec<A>) {
commands.push(Command::Kernel { index, grid, block, args: Box::new(KernelArguments::new(args)) });
}
/// The tensor a finite scan covers: `words` values per row over `rows` rows.
#[derive(Clone, Copy)]
pub(super) struct ScanExtent {
words: i32,
rows: i32,
}
impl ScanExtent {
/// A scan over `rows` rows of `words` values.
pub(super) const fn new(words: i32, rows: i32) -> Self {
Self { words, rows }
}
}
pub(super) fn scan(
commands: &mut Vec<Command>,
data: BufferHandle,
status: BufferHandle,
words: i32,
rows: i32,
extent: ScanExtent,
role: i32,
) {
let ScanExtent { words, rows } = extent;
push(
commands,
7,
@@ -141,7 +141,7 @@ impl<'ctx> PleBatchQueue<'ctx> {
beta: 1.0,
});
}
scan(commands, h[out], h[14], n, t, if out == 3 { 0 } else { 1 });
scan(commands, h[out], h[14], ScanExtent::new(n, t), if out == 3 { 0 } else { 1 });
}
}
@@ -230,16 +230,16 @@ fn push_norms_and_mix(commands: &mut Vec<Command>, plan: &BatchPlan) {
let (h, rows, aux) = (&plan.h, plan.rows, &plan.aux);
let t = rows as i32;
push(commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])]);
scan(commands, h[5], h[14], 10240, t, 2);
scan(commands, h[5], h[14], ScanExtent::new(10240, t), 2);
push(commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])]);
scan(commands, h[6], h[14], 10240, t, 3);
scan(commands, h[6], h[14], ScanExtent::new(10240, t), 3);
let gate = vec![A::Address(h[5]), A::Address(h[6]), A::Address(h[7]), A::F32(1.0 / 2560.0f32.sqrt())];
push(commands, 2, (rows * 4) as u32, 512, gate);
scan(commands, h[7], h[14], 4, t, 4);
scan(commands, h[7], h[14], ScanExtent::new(4, t), 4);
push(commands, 3, (rows * 40) as u32, 256, vec![A::Address(h[4]), A::Address(h[7]), A::Address(h[8]), A::I32(t)]);
scan(commands, h[8], h[14], 10240, t, 5);
scan(commands, h[8], h[14], ScanExtent::new(10240, t), 5);
push(commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])]);
scan(commands, h[9], h[14], 10240, t, 6);
scan(commands, h[9], h[14], ScanExtent::new(10240, t), 6);
}
fn push_conv_and_history(commands: &mut Vec<Command>, plan: &BatchPlan) {
@@ -255,9 +255,9 @@ fn push_conv_and_history(commands: &mut Vec<Command>, plan: &BatchPlan) {
A::I32(t),
];
push(commands, 4, (rows * 40) as u32, 256, conv);
scan(commands, h[10], h[14], 10240, t, 7);
scan(commands, h[10], h[14], ScanExtent::new(10240, t), 7);
push(commands, 6, (rows * 360) as u32, 256, vec![A::Address(h[2]), A::Address(h[9]), A::Address(h[11]), A::I32(t)]);
scan(commands, h[11], h[14], 92160, t, 8);
scan(commands, h[11], h[14], ScanExtent::new(92160, t), 8);
push(commands, 5, 40, 256, vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)]);
scan(commands, h[1], h[14], 10240, t, 9);
scan(commands, h[1], h[14], ScanExtent::new(10240, t), 9);
}
@@ -12,10 +12,9 @@ impl<'ctx> PleBatchQueue<'ctx> {
&'loan mut self,
workspace: &mut NativeBatchWorkspace<'_>,
weights: PleClosedWeights<'_, '_>,
embedding: &[f32],
streams: &[f32],
history: &[f32],
sources: PleBatchSources<'_>,
) -> Result<PleBatchCompletion<'loan, 'ctx>> {
let PleBatchSources { embedding, streams, history } = sources;
workspace.validate_context(self.context)?;
let h = self.handles()?;
let (rows, mut commands, mut host) = self.stage_batch(workspace, &weights, h, (embedding, streams, history))?;
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
/// The device, the original kernels' launcher and the staged-kernel module shared by the GDN proofs.
pub(super) struct Rig<'a> {
@@ -143,7 +144,7 @@ fn rec_case(rig: &Rig<'_>, rng: &mut Rng, (case, t): (usize, usize)) {
let guard = context.enter().expect("enter");
let mut args = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn));
let started = std::time::Instant::now();
rig.stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut args).expect("launch");
rig.stage.launch(crate::prefill_stage::GDN_REC, LinearLaunch::new(192, 128, stream), &mut args).expect("launch");
context.driver.api.synchronize().expect("sync");
let new_ms = started.elapsed().as_secs_f64() * 1e3;
guard.finish().expect("finish");
@@ -187,7 +188,9 @@ fn kh_case(rig: &Rig<'_>, rng: &mut Rng, case: usize, (t, variant): (usize, u8))
rig.old.run(vec![b.old_launch(t, (&b.sout_o, &b.oc_o, &b.wo))]);
let guard = context.enter().expect("enter");
let mut args = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn));
rig.stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut args).expect("launch kh");
rig.stage
.launch(crate::prefill_stage::GDN_REC_KH, LinearLaunch::new(64, 128, stream), &mut args)
.expect("launch kh");
context.driver.api.synchronize().expect("sync");
guard.finish().expect("finish");
// compare the bytes as words: a NaN payload is a value too
@@ -209,28 +212,28 @@ fn kh_case(rig: &Rig<'_>, rng: &mut Rng, case: usize, (t, variant): (usize, u8))
/// Timing on warm data: 20 launches of each recurrence, drained once.
fn kh_timing(rig: &Rig<'_>, b: &RecBuffers<'_>, t: usize) {
let (context, stream) = (rig.context, rig.stream);
let reps = 20;
let (kh, rec) = (LinearLaunch::new(64, 128, rig.stream), LinearLaunch::new(192, 128, rig.stream));
let t0 = std::time::Instant::now();
rig.old.run((0..reps).map(|_| b.old_launch(t, (&b.sout_o, &b.oc_o, &b.wo))).collect());
let old_ms = t0.elapsed().as_secs_f64() * 1e3 / reps as f64;
let guard = context.enter().expect("enter");
let guard = rig.context.enter().expect("enter");
let mut keep = Vec::new();
let t1b = std::time::Instant::now();
for _ in 0..reps {
let mut a = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn));
rig.stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut a).expect("launch kh");
rig.stage.launch(crate::prefill_stage::GDN_REC_KH, kh, &mut a).expect("launch kh");
keep.push(a);
}
context.driver.api.synchronize().expect("sync");
rig.context.driver.api.synchronize().expect("sync");
let kh_ms = t1b.elapsed().as_secs_f64() * 1e3 / reps as f64;
let t2 = std::time::Instant::now();
for _ in 0..reps {
let mut a = b.new_args(t, (&b.sout_n, &b.oc_n, &b.wn));
rig.stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut a).expect("launch rec");
rig.stage.launch(crate::prefill_stage::GDN_REC, rec, &mut a).expect("launch rec");
keep.push(a);
}
context.driver.api.synchronize().expect("sync");
rig.context.driver.api.synchronize().expect("sync");
let rec_ms = t2.elapsed().as_secs_f64() * 1e3 / reps as f64;
guard.finish().expect("finish");
eprintln!(
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
impl Rng {
pub(super) fn next(&mut self) -> u64 {
@@ -70,7 +71,7 @@ pub(super) fn run_stage(
let mut keep = Vec::new();
for (index, grid, args) in launches {
let mut args = KernelArguments::new(args);
module.launch(index, grid, 256, stream, &mut args).expect("launch");
module.launch(index, LinearLaunch::new(grid, 256, stream), &mut args).expect("launch");
keep.push(args);
}
context.driver.api.synchronize().expect("sync");
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
/// Timing only (row "256k prefill gap"): the three hyper-connection kernels of the prompt at the real chunk size
/// (T = 8192 rows, a 335.5 MB residual R) against the bytes they must move, as achieved GB/s. Prints
@@ -82,7 +83,7 @@ struct Timer<'a> {
impl Timer<'_> {
fn launch(&mut self, (index, grid, args): (usize, usize, Vec<A>)) {
let mut a = KernelArguments::new(args);
self.stage.launch(index, grid as u32, 256, self.blas.stream(), &mut a).expect("launch");
self.stage.launch(index, LinearLaunch::new(grid as u32, 256, self.blas.stream()), &mut a).expect("launch");
self.keep.push(a);
}
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
impl Rng {
pub(super) fn next(&mut self) -> u64 {
@@ -38,7 +39,7 @@ pub(super) fn run_all(context: &Context<'_>, workspace: &NativeBatchWorkspace<'_
let mut keep = Vec::new();
for (module, index, grid, block, args) in launches {
let mut args = KernelArguments::new(args);
module.launch(index, grid as u32, block, blas.stream(), &mut args).expect("launch");
module.launch(index, LinearLaunch::new(grid as u32, block, blas.stream()), &mut args).expect("launch");
keep.push(args);
}
blas.synchronize().expect("sync");
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
impl Rng {
pub(super) fn next(&mut self) -> u64 {
@@ -122,11 +123,11 @@ pub(super) fn topk_matches_original(
let mut a_old = topk_args(rig.max_blocks, inputs, &ids_o);
let mut a_new = topk_args(rig.max_blocks, inputs, &ids_n);
let t0 = std::time::Instant::now();
rig.select.launch(0, rows as u32, 256, stream, &mut a_old).expect("old topk");
rig.select.launch(0, LinearLaunch::new(rows as u32, 256, stream), &mut a_old).expect("old topk");
context.driver.api.synchronize().expect("sync");
let old_ms = t0.elapsed().as_secs_f64() * 1e3;
let t1 = std::time::Instant::now();
rig.late.launch(TOPK_FAST, rows as u32, 256, stream, &mut a_new).expect("new topk");
rig.late.launch(TOPK_FAST, LinearLaunch::new(rows as u32, 256, stream), &mut a_new).expect("new topk");
context.driver.api.synchronize().expect("sync");
let new_ms = t1.elapsed().as_secs_f64() * 1e3;
guard.finish().expect("finish");
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::{ClusterShape, LinearLaunch};
/// The Original's score scan and the late fast scan over the same scores; returns both status buffers.
pub(super) fn scan_both<'c>(
@@ -17,12 +18,14 @@ pub(super) fn scan_both<'c>(
let guard = context.enter().expect("enter");
let old = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64), ad(&st_o), A::U32(1)];
let mut so = KernelArguments::new(old);
rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan");
rig.index
.launch(0, LinearLaunch::new((rows * max_blocks).div_ceil(256) as u32, 256, stream), &mut so)
.expect("old scan");
let mut new = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64)];
new.extend([A::I64(reach as i64), ad(&st_n), A::U32(1)]);
let mut sn = KernelArguments::new(new);
let grid = (rows * reach).div_ceil(256) as u32;
rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan");
rig.late.launch(SCORE_SCAN_FAST, LinearLaunch::new(grid, 256, stream), &mut sn).expect("new scan");
context.driver.api.synchronize().expect("sync");
guard.finish().expect("finish");
(st_o, st_n)
@@ -86,21 +89,26 @@ pub(super) fn topk_variants<'a>(rig: &'a BenchRig<'a>, n: u32) -> Vec<(&'static
let (select, late, cluster, stream) = (&rig.select, &rig.late, &rig.cluster, rig.stream);
let smem = crate::qsa_cluster::dynamic_smem(rig.max_blocks);
vec![
("ref", Box::new(move |a| select.launch(0, n, 256, stream, a).expect("ref"))),
("fast", Box::new(move |a| late.launch(TOPK_FAST, n, 256, stream, a).expect("fast"))),
("wide", Box::new(move |a| late.launch(TOPK_WIDE, n, 1024, stream, a).expect("wide"))),
("ref", Box::new(move |a| select.launch(0, LinearLaunch::new(n, 256, stream), a).expect("ref"))),
("fast", Box::new(move |a| late.launch(TOPK_FAST, LinearLaunch::new(n, 256, stream), a).expect("fast"))),
("wide", Box::new(move |a| late.launch(TOPK_WIDE, LinearLaunch::new(n, 1024, stream), a).expect("wide"))),
(
"sample+failed",
Box::new(move |a| {
late.launch(TOPK_SAMPLE, n, 1024, stream, a).expect("sample");
late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed");
late.launch(TOPK_SAMPLE, LinearLaunch::new(n, 1024, stream), a).expect("sample");
late.launch(TOPK_WIDE_FAILED, LinearLaunch::new(n, 1024, stream), a).expect("failed");
}),
),
(
"cluster",
Box::new(move |a| {
cluster
.launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a)
.launch_cluster(
crate::qsa_cluster::TOPK_CLUSTER,
ClusterShape::new([8, n], 1024, 8, smem),
stream,
a,
)
.expect("cluster")
}),
),
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
/// Times the decode scores kernel and the top-k at one `(pos, nq)` shape, 20 warm launches each.
pub(super) fn time_scores_and_topk(
@@ -20,9 +21,11 @@ pub(super) fn time_scores_and_topk(
let mut sa: Vec<A> = [&pooled_d, &dead_d, &qidx_d, &steps_d].into_iter().map(|b| ad(b)).collect();
sa.extend([nq_arg, blocks_arg, ad(&scores_d)]);
let mut sa = KernelArguments::new(sa);
let scores_us = time_warm(context, &mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores"));
let scores_us =
time_warm(context, &mut || select.launch(0, LinearLaunch::new(256, 256, stream), &mut sa).expect("scores"));
let mut ta = topk_args(max_blocks, (&scores_d, &steps_d), &ids_d);
let topk_us = time_warm(context, &mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk"));
let topk_us =
time_warm(context, &mut || select.launch(1, LinearLaunch::new(nq as u32, 256, stream), &mut ta).expect("topk"));
guard.finish().expect("finish");
eprintln!(
"QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, \
@@ -2,6 +2,8 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars};
impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
// Closed role shapes, not arbitrary GEMM.
@@ -49,13 +51,17 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
self.reset_status(args, io)?;
let module = self.launch_pack_and_scans(blas, args, ((t, k), kind, out_gate))?;
let [alpha, beta0, beta1] = self.scalars.as_ref();
let dims = GemmDims { tokens: t as i32, outputs: n as i32, depth: k as i32 };
if let Some(kind) = kind {
self.launch_quantized(module, blas, args, ((n, k), kind))?;
return blas.gemm_f16(io.packed, io.scratch, io.y, t as i32, n as i32, k as i32, alpha, beta0);
let operands = GemmOperands { x: io.packed, w: io.scratch, y: io.y };
return blas.gemm_f16(operands, dims, GemmScalars { alpha, beta: beta0 });
}
blas.gemm_bf16(io.high, weight, io.y, t as i32, n as i32, k as i32, alpha, beta0)?;
let high = GemmOperands { x: io.high, w: weight, y: io.y };
blas.gemm_bf16(high, dims, GemmScalars { alpha, beta: beta0 })?;
if self.packing == QsaNativePacking::HighAndLow {
blas.gemm_bf16(io.low, weight, io.y, t as i32, n as i32, k as i32, alpha, beta1)?;
let low = GemmOperands { x: io.low, w: weight, y: io.y };
blas.gemm_bf16(low, dims, GemmScalars { alpha, beta: beta1 })?;
}
Ok(())
}
@@ -76,10 +82,18 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
) -> Result<&KernelModule> {
let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?;
let pack = if out_gate { &mut args.gate } else { &mut args.pack };
module.launch(if out_gate { 1 } else { 0 }, (t * k).div_ceil(256) as u32, 256, blas.stream(), pack)?;
module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut args.input_scan)?;
module.launch(
if out_gate { 1 } else { 0 },
LinearLaunch::new((t * k).div_ceil(256) as u32, 256, blas.stream()),
pack,
)?;
module.launch(2, LinearLaunch::new((t * k).div_ceil(256) as u32, 256, blas.stream()), &mut args.input_scan)?;
if kind.is_none() && self.packing == QsaNativePacking::HighAndLow {
module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut args.low_scan)?;
module.launch(
2,
LinearLaunch::new((t * k).div_ceil(256) as u32, 256, blas.stream()),
&mut args.low_scan,
)?;
}
Ok(module)
}
@@ -93,12 +107,10 @@ impl<'ctx> QsaNativeBatchWorkspace<'ctx> {
) -> Result<()> {
self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch(
kind.entry(),
(n * k / 32).div_ceil(256) as u32,
256,
blas.stream(),
LinearLaunch::new((n * k / 32).div_ceil(256) as u32, 256, blas.stream()),
&mut args.dequant,
)?;
module.launch(2, (n * k).div_ceil(256) as u32, 256, blas.stream(), &mut args.weight_scan)
module.launch(2, LinearLaunch::new((n * k).div_ceil(256) as u32, 256, blas.stream()), &mut args.weight_scan)
}
/// Marks both owners failed on any error, keeps the operands alive when the stream or the legacy upload may still
/// use them, and refuses unknown, unused or non-finite status words.
@@ -136,7 +136,6 @@ impl<'ctx> QsaPromptAttention<'ctx> {
inputs: &QsaAttentionInputs<'_, '_>,
switches: SelectSwitches,
) -> Result<QsaPromptAttentionCompletion<'loan, 'ctx>> {
let QsaPromptSources { stage, kv, snapshot } = sources;
let caps = self.module.as_ref().ok_or(Error::ContextPoisoned)?.caps();
let device = DeviceCaps { cc_major: caps[0], cc_minor: caps[1], max_shared_optin: caps[2] };
let kernel = select(PoolPresence::int8(), Shapes::QWEN, QWEN_SELECTION, device, switches)
@@ -3,6 +3,8 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::Blas;
use crate::ple_batch_ffi::LinearLaunch;
use crate::ple_batch_ffi::{GemmDims, GemmOperands, GemmScalars};
/// Shape, handles and mode of one native projection.
#[derive(Clone, Copy)]
@@ -194,26 +196,27 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
fn launch_pack(&self, blas: &Blas, count: usize, args: &mut KernelArguments) -> Result<()> {
self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch(
2,
count.div_ceil(256) as u32,
256,
blas.stream(),
LinearLaunch::new(count.div_ceil(256) as u32, 256, blas.stream()),
args,
)
}
/// Quantized weights are dequantized to FP16 and multiplied in FP16; BF16 weights multiply directly.
fn project_weight(&self, blas: &Blas, job: &Projection, args: &mut ProjectArgs) -> Result<()> {
let (t, n, k) = (job.t as i32, job.n as i32, job.k as i32);
let dims = GemmDims { tokens: job.t as i32, outputs: job.n as i32, depth: job.k as i32 };
let Some(kind) = job.kind else {
blas.gemm_bf16(job.x, job.weight, job.output, t, n, k, &1., &0.)?;
let high = GemmOperands { x: job.x, w: job.weight, y: job.output };
blas.gemm_bf16(high, dims, GemmScalars { alpha: &1., beta: &0. })?;
if let Some(lower) = args.lower {
blas.gemm_bf16(lower, job.weight, job.output, t, n, k, &1., &1.)?;
let low = GemmOperands { x: lower, w: job.weight, y: job.output };
blas.gemm_bf16(low, dims, GemmScalars { alpha: &1., beta: &1. })?;
}
return Ok(());
};
self.launch_dequant(blas, job, kind, &mut args.dequant)?;
self.launch_pack(blas, job.n * job.k, &mut args.weight_scan)?;
blas.gemm_f16(job.x, job.scratch, job.output, t, n, k, &1., &0.)
let quantized = GemmOperands { x: job.x, w: job.scratch, y: job.output };
blas.gemm_f16(quantized, dims, GemmScalars { alpha: &1., beta: &0. })
}
fn launch_dequant(
@@ -232,9 +235,17 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
QsaNativeKind::Iq4Xs => 5,
};
let entry = crate::prefill_stage::DEQUANT_FIRST + offset;
return module.launch(entry, (job.n * job.k).div_ceil(256) as u32, 256, blas.stream(), args);
return module.launch(
entry,
LinearLaunch::new((job.n * job.k).div_ceil(256) as u32, 256, blas.stream()),
args,
);
}
module.launch(native_entry(kind), (job.n * job.k / 32).div_ceil(256) as u32, 256, blas.stream(), args)
module.launch(
native_entry(kind),
LinearLaunch::new((job.n * job.k / 32).div_ceil(256) as u32, 256, blas.stream()),
args,
)
}
/// The gate kernel under the context guard: packs the attention rows against the strided Qf into FP16.
@@ -257,7 +268,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
e
})?;
let gate = self.gate.as_ref().ok_or(Error::ContextPoisoned)?;
let op = gate.launch(0, (t * 6144).div_ceil(256) as u32, 256, blas.stream(), &mut args);
let op = gate.launch(0, LinearLaunch::new((t * 6144).div_ceil(256) as u32, 256, blas.stream()), &mut args);
let sync = blas.synchronize();
let pop = guard.finish();
self.settle_gate(ws, [op, sync, pop], args)?;
@@ -4,6 +4,7 @@
use super::impl_originalqsapromptdevice::lap;
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
use crate::qsa_prompt_attention::OriginalQsaAttendedKv;
impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
@@ -124,8 +125,11 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
e
})?;
let blocks = (self.rows() * 6144).div_ceil(256) as u32;
let op =
self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch(0, blocks, 256, blas.stream(), &mut args);
let op = self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch(
0,
LinearLaunch::new(blocks, 256, blas.stream()),
&mut args,
);
let sync = blas.synchronize();
let pop = guard.finish();
self.settle_gate(ws, (op, sync, pop), args)
@@ -2,6 +2,7 @@
#[allow(unused_imports)]
use super::*;
use crate::ple_batch_ffi::LinearLaunch;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
/// Runs the index program over device rows already in the arena (`is_decode`: the T1 decode step).
@@ -158,7 +159,11 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
while late.next < late.launches.len() && late.launches[late.next].0 <= upto {
let started = std::time::Instant::now();
let (_, grid, entry, block, args) = &mut late.launches[late.next];
self.late.as_ref().ok_or(Error::ContextPoisoned)?.launch(*entry, *grid, *block, blas.stream(), args)?;
self.late.as_ref().ok_or(Error::ContextPoisoned)?.launch(
*entry,
LinearLaunch::new(*grid, *block, blas.stream()),
args,
)?;
if timed {
blas.synchronize()?;
let topk = *entry != crate::qsa_late::SCORE_SCAN_FAST;
+11 -7
View File
@@ -24,16 +24,18 @@ pub use original_gpu_schedule::{
OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, OriginalStreamKind,
OriginalWait,
};
pub use original_moe_prompt_device::{OriginalMoePromptDevice, OriginalMoePromptLayer};
pub use original_moe_prompt_device::{
ExpertStreamLayer, OriginalLayerExpertSources, OriginalMoePromptDevice, OriginalMoePromptLayer, SharedExpertLayout,
};
pub use original_mtp_actor::{ActorRefusal as OriginalMtpActorRefusal, DraftSettings as OriginalMtpDraftSettings};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter};
pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter, OriginalMtpLoadedParts};
pub use original_mtp_bank::{
OriginalMtpLoadFailure, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind,
original_mtp_draft_vocab_bytes,
};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use original_mtp_draft_head::OriginalMtpDraftHead;
pub use original_mtp_draft_head::{OriginalMainHead, OriginalMtpDraftHead};
pub use original_mtp_loader::{
CoupledPlan as OriginalMtpCoupledPlan, KvFormat as OriginalMtpKvFormat, KvMode as OriginalMtpKvMode,
KvPlan as OriginalMtpKvPlan, LoaderError as OriginalMtpPlanError, OriginalMtpCapture, OriginalMtpKvStartup,
@@ -113,7 +115,9 @@ pub use qwen_dispatch::ple_closed_queue::{
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub use gdn_batch_gemm::NativeGdnGemm;
pub use native_batch_workspace::{NATIVE_BATCH_WORKSPACE_BYTES, NativeBatchWorkspace};
pub use ple_batch_queue::{PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBf16Mode};
pub use ple_batch_queue::{
PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBatchSources, PleBf16Mode,
};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub use qsa_native_batch::{
QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking, QsaNativeProjections,
@@ -145,7 +149,7 @@ pub use native_prompt_device::{
OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, OriginalDeviceResidual,
OriginalPleHistory, OriginalPromptDevice, PromptInputStage,
};
pub use original_sampler::{OriginalSampler, SamplerParams, SamplerPath};
pub use original_sampler::{OriginalSampler, SampleRequest, SampleWindow, SamplerParams, SamplerPath};
pub use prefill_stage::{
set_gdn_nostore_override as set_prefill_gdn_nostore_override, set_gdn_override as set_prefill_gdn_override,
};
@@ -198,8 +202,8 @@ pub use mtp_dense_kv::{
};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use native_head::{
NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadProjectionFlight, NativeHeadSampling,
NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows, OriginalNativeHead,
NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadPayload, NativeHeadProjectionFlight,
NativeHeadSampling, NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows, OriginalNativeHead,
OriginalNativeHeadGraphResources, OriginalNativeHeadRows, native_embed_supported, native_head_row_bytes,
native_head_supported,
};
@@ -290,10 +290,10 @@ fn adopt_actor<'ctx>(
let _ = ring.close();
return None;
};
let parts = OriginalMtpLoadedParts { drafter, ring: &ring, weights: std::rc::Rc::clone(&weights) };
let actor = step!(
"OriginalMtpActor::adopt",
OriginalMtpActor::adopt(context, plan, drafter, &ring, std::rc::Rc::clone(&weights), evidence)
.map_err(|e| e.message().to_owned())
OriginalMtpActor::adopt(context, plan, parts, evidence).map_err(|e| e.message().to_owned())
);
let Some(actor) = actor else {
let _ = ring.close();
@@ -83,10 +83,10 @@ impl<'ctx> Parts<'ctx> {
// ---- head rows and embedding rows
let head_bytes = step!("head bytes", size(sizes.head_kind, 2560, sizes.vocab))?;
let payload = vec![0u8; head_bytes];
let head = step!(
"original_native_head",
context.original_native_head(sizes.head_kind, 2560, sizes.vocab, &payload, NativeHeadDispatch::default())
)?;
let head_payload =
NativeHeadPayload { kind: sizes.head_kind, columns: 2560, vocabulary: sizes.vocab, bytes: &payload };
let head =
step!("original_native_head", context.original_native_head(head_payload, NativeHeadDispatch::default()))?;
let embed_bytes = step!("embed bytes", size(sizes.embed_kind, 2560, sizes.vocab))?;
let payload = vec![0u8; embed_bytes];
let embed = step!(
@@ -62,7 +62,8 @@ pub(super) fn run_prompt_layer<'arena, 'loan, 'ctx>(
begin_stream(io.schedule, scan.bank, io.layer, &read)?;
// High-only is the selected literal Original mixed BF16 policy.
let prepare_span = prof::span(PStage::MoePrepare, drain);
let mut layer_program = io.program.prepare(read, shared, weights, formats, false).map_err(driver_error)?;
let layout = leleka_cuda_driver::SharedExpertLayout { formats, has_low_half: false };
let mut layer_program = io.program.prepare(read, shared, weights, layout).map_err(driver_error)?;
drop(prepare_span);
record_routing(io.routing.as_deref_mut(), io.layer, layer_program.experts(), layer_program.counts());
let spans_span = prof::span(PStage::MoeSpans, None);
@@ -114,8 +115,9 @@ fn copy_ring<'program, 'arena, 'loan, 'ctx>(
) -> Result<()> {
let formats = routed.ok_or(Error::IdentityMismatch)?;
let layer = ring.layer.get() as usize;
let layer_sources = leleka_cuda_driver::OriginalLayerExpertSources { layer, formats, sources };
layer_program
.execute_original_copy_ring(ring.mmq, ring.schedule, layer, Rc::clone(ring.bank), formats, sources)
.execute_original_copy_ring(ring.mmq, ring.schedule, Rc::clone(ring.bank), layer_sources)
.map_err(driver_error)
}
@@ -263,8 +263,8 @@ fn compose_micro_rows(
let mut queue = cache.ple_batch_queue(binding, context)?.ok_or(Error::IdentityMismatch)?;
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
let weights = closed_ple_weights(cache, entry)?;
let completed =
queue.compose(&mut workspace, weights, embedding, streams, &prior.0.history).map_err(ple_driver_error)?;
let batch = leleka_cuda_driver::PleBatchSources { embedding, streams, history: &prior.0.history };
let completed = queue.compose(&mut workspace, weights, batch).map_err(ple_driver_error)?;
take_micro_rows(completed, sources.len())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -126,7 +126,7 @@ impl<'ctx> OriginalMtpFullOwner<'ctx> {
let draft_head: Option<OriginalMtpDraftHead<'ctx>> = match rt_directory {
Some(directory) => {
let weights = head.weights();
context.original_mtp_draft_head(directory, &weights, head.kind(), head.columns(), head.vocabulary())?
context.original_mtp_draft_head(directory, head.main_head(&weights))?
}
None => None,
};
@@ -183,7 +183,8 @@ impl<'ctx> OriginalMtpFullOwner<'ctx> {
return Err(primary.into());
}
};
match OriginalMtpActor::adopt(context, plan, drafter, &ring, weights, evidence) {
let parts = leleka_cuda_driver::OriginalMtpLoadedParts { drafter, ring: &ring, weights };
match OriginalMtpActor::adopt(context, plan, parts, evidence) {
Ok(actor) => Ok((actor, ring)),
Err(primary) => {
let _ = ring.close();
@@ -3,8 +3,8 @@
use super::contract::{Error, Result, Stage};
use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, NativeOutputRole};
use leleka_cuda_driver::{
Context, DeviceBuffer, NativeHeadDispatch, NativeHeadSampling, NativeHeadSelection, OriginalGpuGraph,
OriginalGpuStream, OriginalNativeEmbed, OriginalNativeHead, OriginalNativeHeadGraphResources,
Context, DeviceBuffer, NativeHeadDispatch, NativeHeadPayload, NativeHeadSampling, NativeHeadSelection,
OriginalGpuGraph, OriginalGpuStream, OriginalNativeEmbed, OriginalNativeHead, OriginalNativeHeadGraphResources,
OriginalNativeHeadRows,
};
use std::rc::Rc;
@@ -37,6 +37,14 @@ impl<'ctx> OriginalMtpNativeHead<'ctx> {
pub(in crate::qwen_forward) fn dispatch(&self) -> NativeHeadDispatch {
self.dispatch
}
/// This head as the main head the draft head is gathered from, over its own `weights` allocation.
pub(in crate::qwen_forward) fn main_head<'a>(
&self,
weights: &'a DeviceBuffer<'ctx>,
) -> leleka_cuda_driver::OriginalMainHead<'a, 'ctx> {
let (kind, columns, vocabulary) = (self.kind, self.columns, self.vocabulary);
leleka_cuda_driver::OriginalMainHead { weights, kind, columns, vocabulary }
}
}
pub(in crate::qwen_forward) struct OriginalNativeOutput<'ctx> {
binding: BindingIdentity,
@@ -92,8 +100,14 @@ impl<'ctx> OriginalNativeOutput<'ctx> {
if !weights.matches(&binding.identity()) {
return Err(Error::IdentityMismatch);
}
let head = NativeHeadPayload {
kind: weights.kind(),
columns: weights.columns(),
vocabulary: weights.vocabulary(),
bytes: weights.bytes(),
};
context
.original_native_head(weights.kind(), weights.columns(), weights.vocabulary(), weights.bytes(), dispatch)
.original_native_head(head, dispatch)
.map_err(|e| {
eprintln!("OriginalNativeOutput::load: native head refused: {e:?}");
driver(e)