Merge claude/par-q02 (STRA-338 params: original_verify_* and expert cache/stager)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 12:59:32 +01:00
co-authored by Claude Sonnet 5.5
51 changed files with 773 additions and 417 deletions
@@ -221,7 +221,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
let RetainedFill::Mapped { bank, spans } = self.swap_sources.last().ok_or(Error::ContextPoisoned)? else {
return Err(Error::InvalidSize);
};
queue_span_copies(api, bank, spans, handle, capacity, stream)
queue_span_copies(api, bank, spans, SlotRegion { handle, capacity }, stream)
}
}
/// Where a swap moves a slot: the expert it holds now, the expert it receives, and the slot's bytes.
@@ -231,6 +231,12 @@ struct SwapPlan {
handle: ffi::BufferHandle,
capacity: usize,
}
/// The device bytes of one expert slot: its buffer handle and the capacity the three spans must fit.
#[derive(Clone, Copy)]
struct SlotRegion {
handle: ffi::BufferHandle,
capacity: usize,
}
/// The layer all three spans of one expert belong to.
pub(super) fn span_layer(spans: &[ResidentExpertBankSpan; 3]) -> Result<usize> {
match spans[0].role() {
@@ -259,10 +265,10 @@ fn queue_span_copies(
api: &api::AsyncApi,
bank: &MappedExpertBank<'_>,
spans: &[ResidentExpertBankSpan; 3],
handle: ffi::BufferHandle,
capacity: usize,
slot: SlotRegion,
stream: api::Stream,
) -> Result<()> {
let SlotRegion { handle, capacity } = slot;
let mut offset = 0usize;
for span in spans {
let source = bank.cache_source(span)?;
@@ -24,7 +24,9 @@ impl<'ctx> OriginalStagerBatch<'_, 'ctx> {
let event = self.stager.slots[slot].event;
let api = &self.stager.api;
let flight = self.stager.flight.as_mut().ok_or(Error::InvalidSize)?;
let result = flight.stream.with_enqueue(|stream| api.issue(target, host, raw.bytes(), stream, event));
let result = flight
.stream
.with_enqueue(|stream| api.issue(target, host, raw.bytes(), abi::StreamEvent { stream, event }));
if result.is_err() {
self.stager.shared.failed.store(true, Ordering::Release);
self.stager.context.poison();
@@ -44,6 +44,12 @@ pub(crate) struct WorkerSlot {
bytes: usize,
pub(crate) event: usize,
}
/// A stream handle and the event recorded on it right after the copy it carries.
#[derive(Clone, Copy)]
pub(crate) struct StreamEvent {
pub(crate) stream: usize,
pub(crate) event: usize,
}
#[derive(Clone, Copy)]
pub(crate) struct CopyJob {
source: [(usize, usize); 3],
@@ -185,9 +185,9 @@ impl Api {
destination: BufferHandle,
source: &HostBuffer,
bytes: usize,
stream: usize,
event: usize,
completion: StreamEvent,
) -> Result<()> {
let StreamEvent { stream, event } = completion;
destination.validate_extent(bytes)?;
if bytes == 0 || bytes > source.bytes || source.address == 0 {
return Err(Error::InvalidSize);
+9 -3
View File
@@ -49,8 +49,11 @@ pub use diag::{
write_original_verify_diagnostics,
};
pub use layout::{OriginalVerifyGeometry, OriginalVerifyLayout, OriginalVerifySpan};
pub use logits::{RowLogprob, analyse_row, logpos_topk_from_environment, top_k, write_row_line, write_window_logprobs};
use mapped::MappedAllocation;
pub use logits::{
LogitRows, LogprobReadout, RowLogprob, analyse_row, logpos_topk_from_environment, top_k, write_row_line,
write_window_logprobs,
};
use mapped::{MappedAllocation, MappedRouteOperands, RouteRowSpan};
pub use profile::{OriginalVerifyProfile, PROFILE_STAMPS_PER_LAYER, profile_stamp_slot, profile_stamp_words};
use std::{
cell::{Cell, RefCell},
@@ -219,7 +222,10 @@ pub use gpu_plan::{MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSo
mod expert_probe;
#[cfg(any(test, feature = "expert-tier-probe"))]
pub use expert_probe::{OriginalExpertTierProbe, expert_probe_geometry};
pub use schedule::{OriginalVerifier, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyWindowResult};
pub use schedule::{
OriginalVerifier, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyWindowResult,
OriginalVerifyWindowTokens,
};
#[path = "original_verify_window_ops.rs"]
mod window_ops;
pub use gr::{
@@ -179,9 +179,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
kernels::Launch::new(
&chain::CHAIN,
chain::E_DOORBELL,
[1, 1, 1],
[1024, 1, 1],
0,
kernels::LaunchExtent::new([1, 1, 1], [1024, 1, 1], 0),
vec![
kernels::A::P(a("mixed", begin * g.n * 4, n * g.n * 4)?),
kernels::A::P(a("ids", begin * g.k * 4, n * g.k * 4)?),
@@ -112,9 +112,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
kernels::Launch::new(
&chain::CHAIN,
chain::E_GDN_AB,
[96, 1, 1],
[32, 1, 1],
0,
kernels::LaunchExtent::new([96, 1, 1], [32, 1, 1], 0),
vec![
kernels::A::P(x),
kernels::A::P(admit(c, w.alpha, 48 * 2560 * 2)?),
@@ -245,9 +243,7 @@ impl FusedSpans {
kernels::Launch::new(
&draft::DRAFT_COMMIT,
draft::E_GDN,
[48 + 20, 36, 1],
[128, 4, 1],
0,
kernels::LaunchExtent::new([48 + 20, 36, 1], [128, 4, 1], 0),
vec![kernels::A::Words(vec![
self.state0,
LAYER_BYTES as u64,
@@ -198,8 +198,20 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> {
let arena = ProbeArena(&self.bank()?.physical);
Ok(GroupPlans {
quantize: moe::plan_quantize_expert_input(&arena, g, &knobs, group)?,
vram: moe::plan_expert_groups(&arena, g, &knobs, &self.formats, layer, group, ExpertTier::Vram)?,
pcie: moe::plan_expert_groups(&arena, g, &knobs, &self.formats, layer, group, ExpertTier::Pcie)?,
vram: moe::plan_expert_groups(
&arena,
g,
&knobs,
&self.formats,
moe::ExpertGroupSite { layer, rows: group, tier: ExpertTier::Vram },
)?,
pcie: moe::plan_expert_groups(
&arena,
g,
&knobs,
&self.formats,
moe::ExpertGroupSite { layer, rows: group, tier: ExpertTier::Pcie },
)?,
hit_add: moe::plan_hit_add(&arena, g, group)?,
})
}
@@ -235,13 +247,12 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> {
let (bank, copy) = self.bank_and_copy()?;
let (x, ids_m, w) = mapped_rows(physical)?;
MappedAllocation::with_cpu_rows(
x.as_ref().ok_or(Error::ContextPoisoned)?,
ids_m.as_ref().ok_or(Error::ContextPoisoned)?,
w.as_ref().ok_or(Error::ContextPoisoned)?,
0,
rows,
g.n,
g.k,
MappedRouteOperands {
activation: x.as_ref().ok_or(Error::ContextPoisoned)?,
ids: ids_m.as_ref().ok_or(Error::ContextPoisoned)?,
weights: w.as_ref().ok_or(Error::ContextPoisoned)?,
},
RouteRowSpan { first: 0, rows, hidden_width: g.n, top_k: g.k },
|activation, ids, route_weights| {
pool(
OriginalVerifyCpuRows { layer, group: 0, first_row: 0, activation, ids, route_weights },
@@ -55,9 +55,9 @@ mod tests;
#[path = "original_verify_gpu_plan/impl_originalverifygpuplan.rs"]
mod impl_originalverifygpuplan;
#[allow(unused_imports)]
pub(crate) use impl_originalverifygpuplan::encode_plan_block;
#[allow(unused_imports)]
use impl_originalverifygpuplan::span_layer;
#[allow(unused_imports)]
pub(crate) use impl_originalverifygpuplan::{PlanEntryShape, encode_plan_block};
#[path = "original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs"]
mod impl_schedule_originalverifycpusink;
#[path = "original_verify_gpu_plan/plan_phases.rs"]
@@ -28,18 +28,26 @@ impl OriginalVerifyGpuPlan {
}
}
/// The entry geometry of one group's plan block: the most entries the block holds (`cap`), the routed experts per row
/// (`k`) and the entries the group's rows route (`n_entries`).
#[derive(Clone, Copy, Debug)]
pub(crate) struct PlanEntryShape {
pub cap: usize,
pub k: usize,
pub n_entries: usize,
}
/// The literal `GpuPlanSink` writes of one group into a `layout.words` int32 block (little-endian bytes):
/// VRAM groups first (`ptr`, `start`), `start[groups] = entries`, then the PCIe groups (`ptr2`, `start2`),
/// `start2[fetches] = entries`, and the counts. `dst[e] = i`, `tok[e] = i / k`. Refuses an entry outside the
/// group's `n_entries`, a repeated entry, an empty group, and more groups or entries than the block holds.
pub(crate) fn encode_plan_block(
layout: &PlanLayout,
cap: usize,
k: usize,
n_entries: usize,
shape: PlanEntryShape,
vram: &[(u64, &[u16])],
pcie: &[(u64, &[u16])],
) -> Result<Vec<u8>> {
let PlanEntryShape { cap, k, n_entries } = shape;
if k == 0 || n_entries > cap || n_entries > 128 || vram.len() > cap || pcie.len() > cap.min(MAX_PCIE_FETCHES) {
return Err(Error::InvalidQwenShape);
}
@@ -49,7 +49,7 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
let staging = self.staging_base(plan)?;
let kernel = self.bank.pcie_mode == 2;
let aliases = self.kernel_aliases(plan, pcie.as_ref(), cap, kernel)?;
let block = self.build_plan_block(plan, &layout, cap, (&vram, &aliases), (kernel, staging, stride))?;
let block = self.build_plan_block(plan, &layout, (&vram, &aliases), (kernel, staging, stride))?;
self.publish_plan_block(&layout, &block)?;
self.raise_after_staging(plan, pcie, copy, (kernel, staging, stride))
}
@@ -164,18 +164,19 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
&self,
plan: &OriginalVerifyGpuPlan,
layout: &PlanLayout,
cap: usize,
(vram, aliases): (&[(u64, &[u16])], &[[u64; 3]]),
(kernel, staging, stride): (bool, u64, usize),
) -> Result<Vec<u8>> {
let k = self.bank.geometry().k;
let g = self.bank.geometry();
let (cap, k) = (g.max_t * g.k, g.k);
let pcie_ptrs: Vec<(u64, &[u16])> = plan
.pcie
.iter()
.enumerate()
.map(|(q, e)| (if kernel { aliases[q][0] } else { staging + (q * stride) as u64 }, e.as_slice()))
.collect();
let mut block = encode_plan_block(layout, cap, k, self.rows * k, vram, &pcie_ptrs)?;
let mut block =
encode_plan_block(layout, PlanEntryShape { cap, k, n_entries: self.rows * k }, vram, &pcie_ptrs)?;
for (q, a) in aliases.iter().enumerate() {
for (r, &alias) in a.iter().enumerate() {
let at = (layout.ptr2 + 2 * (3 * q + r)) * 4;
@@ -37,7 +37,7 @@ fn the_block_is_the_literal_gpu_plan_sink_carve() {
let layout = PlanLayout::new(40);
let vram: Vec<(u64, &[u16])> = vec![(0x1000, &[0, 13]), (0x2000, &[5])];
let pcie: Vec<(u64, &[u16])> = vec![(0x9000, &[2, 21, 27]), (0x9800, &[29])];
let w = words(&encode_plan_block(&layout, 40, 10, 30, &vram, &pcie).unwrap());
let w = words(&encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 30 }, &vram, &pcie).unwrap());
assert_eq!(w.len(), layout.words);
assert_eq!(&w[..4], &[2, 7, 2, 0], "vram groups, gpu entries, pcie groups");
assert_eq!(&w[layout.start..layout.start + 3], &[0, 2, 3]);
@@ -52,7 +52,7 @@ fn the_block_is_the_literal_gpu_plan_sink_carve() {
#[test]
fn an_empty_plan_is_the_run_loops_empty_plan() {
let layout = PlanLayout::new(80);
let w = words(&encode_plan_block(&layout, 80, 10, 80, &[], &[]).unwrap());
let w = words(&encode_plan_block(&layout, PlanEntryShape { cap: 80, k: 10, n_entries: 80 }, &[], &[]).unwrap());
assert!(w.iter().all(|&x| x == 0));
}
@@ -61,11 +61,13 @@ fn a_corrupt_plan_is_refused_not_repaired() {
let layout = PlanLayout::new(40);
let one = |e: &'static [u16]| vec![(0x1000u64, e)];
// entry outside the group's rows, repeated within and across groups, empty group, null pointer
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[20]), &[]).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3, 3]), &[]).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[3]), &one(&[3])).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &one(&[]), &[]).is_err());
assert!(encode_plan_block(&layout, 40, 10, 20, &[(0, &[1])], &[]).is_err());
assert!(encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 20 }, &one(&[20]), &[]).is_err());
assert!(encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 20 }, &one(&[3, 3]), &[]).is_err());
assert!(
encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 20 }, &one(&[3]), &one(&[3])).is_err()
);
assert!(encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 20 }, &one(&[]), &[]).is_err());
assert!(encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 20 }, &[(0, &[1])], &[]).is_err());
// more entries than the block holds
assert!(encode_plan_block(&layout, 40, 10, 50, &[], &[]).is_err());
assert!(encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 50 }, &[], &[]).is_err());
}
@@ -142,16 +142,31 @@ pub fn write_row_line(out: &mut dyn Write, r: &RowLogprob, topk: &[(i32, f64)])
writeln!(out)
}
/// Consecutive logit rows of one window: `values` holds rows of `vocabulary` floats.
#[derive(Clone, Copy, Debug)]
pub struct LogitRows<'a> {
pub values: &'a [f32],
pub vocabulary: usize,
}
/// What a logprob readout reports besides the target: the token to renormalize without (`extra_id`) and how many top
/// entries to print per row.
#[derive(Clone, Copy, Debug)]
pub struct LogprobReadout {
pub extra_id: i32,
pub topk: usize,
}
/// The whole readout over `rows` consecutive logit rows of width `vocab`.
pub fn write_window_logprobs(
out: &mut dyn Write,
logits: &[f32],
vocab: usize,
rows: LogitRows<'_>,
targets: &[i32],
first_position: i64,
extra_id: i32,
topk: usize,
readout: LogprobReadout,
) -> std::io::Result<()> {
let LogitRows { values: logits, vocabulary: vocab } = rows;
let LogprobReadout { extra_id, topk } = readout;
for (t, &target) in targets.iter().enumerate() {
let Some(row) = logits.get(t * vocab..(t + 1) * vocab) else { break };
let Some(r) = analyse_row(row, first_position + t as i64, target, extra_id) else { continue };
@@ -233,7 +248,14 @@ mod tests {
fn line_format_is_original_columns_with_nan_and_topk_tail() {
let row = [0.0f32, 1.0, 3.0, 2.0];
let mut out = Vec::new();
write_window_logprobs(&mut out, &row, 4, &[1], 7, -1, 2).unwrap();
write_window_logprobs(
&mut out,
LogitRows { values: &row, vocabulary: 4 },
&[1],
7,
LogprobReadout { extra_id: -1, topk: 2 },
)
.unwrap();
let line = String::from_utf8(out).unwrap();
let cols: Vec<&str> = line.trim_end().split('\t').collect();
assert_eq!(cols.len(), 8 + 2);
@@ -250,7 +272,14 @@ mod tests {
fn window_readout_stops_at_available_rows() {
let logits = [0.0f32, 1.0, 1.0, 0.0];
let mut out = Vec::new();
write_window_logprobs(&mut out, &logits, 2, &[1, 0, 1], 0, -1, 0).unwrap();
write_window_logprobs(
&mut out,
LogitRows { values: &logits, vocabulary: 2 },
&[1, 0, 1],
0,
LogprobReadout { extra_id: -1, topk: 0 },
)
.unwrap();
assert_eq!(String::from_utf8(out).unwrap().lines().count(), 2);
}
}
@@ -30,6 +30,23 @@ mod enabled {
unsafe { std::mem::transmute::<*mut c_void, $t>(p) }
}};
}
/// The three mapped buffers of one verify group read by the CPU pool: activations, routed expert ids and route
/// weights; they are borrowed together because they are published by the same doorbell.
#[derive(Clone, Copy)]
pub(crate) struct MappedRouteOperands<'a> {
pub(crate) activation: &'a MappedAllocation,
pub(crate) ids: &'a MappedAllocation,
pub(crate) weights: &'a MappedAllocation,
}
/// The rows `first..first + rows` of a group and the widths of one row (hidden size and routed experts per
/// row) that `with_cpu_rows` maps to slices.
#[derive(Clone, Copy)]
pub(crate) struct RouteRowSpan {
pub(crate) first: usize,
pub(crate) rows: usize,
pub(crate) hidden_width: usize,
pub(crate) top_k: usize,
}
/// Every value finite (no infinity, no NaN): the same predicate as `!any(|v| !v.is_finite())`, written as a
/// branch-free fold over the exponent bits so it vectorizes (the per-element early exit of `any` does not); it
/// runs over a whole verify group's CPU output (rows x top-10 x hidden floats) once per layer on the decode
@@ -178,17 +195,13 @@ mod enabled {
atomic.fetch_max(value, std::sync::atomic::Ordering::SeqCst);
Ok(())
}
#[allow(clippy::too_many_arguments)] // Exact borrowed mapped operand boundary.
pub(crate) fn with_cpu_rows<R>(
activation: &Self,
ids: &Self,
weights: &Self,
first: usize,
rows: usize,
n: usize,
k: usize,
operands: MappedRouteOperands<'_>,
span: RouteRowSpan,
consume: impl FnOnce(&[f32], &[i32], &[f32]) -> Result<R>,
) -> Result<R> {
let MappedRouteOperands { activation, ids, weights } = operands;
let RouteRowSpan { first, rows, hidden_width: n, top_k: k } = span;
let x = activation.rows_range(first, rows, n)?;
let i = ids.rows_range(first, rows, k)?;
let w = weights.rows_range(first, rows, k)?;
@@ -251,7 +264,7 @@ mod enabled {
}
}
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub(crate) use enabled::MappedAllocation;
pub(crate) use enabled::{MappedAllocation, MappedRouteOperands, RouteRowSpan};
#[cfg(not(all(
feature = "cuda-driver",
any(target_os = "linux", target_os = "windows"),
@@ -32,6 +32,14 @@ pub struct OriginalVerifyCpuSink<'a, 'ctx> {
pub(super) groups: usize,
pub(super) ring: u32,
}
/// The draft window `OriginalVerifier::run` verifies: its tokens, the position of the first token, and the
/// per-layer-embedding rows (`ple`, `tokens.len() * 2560` floats) when the model has a PLE block.
#[derive(Clone, Copy, Debug)]
pub struct OriginalVerifyWindowTokens<'a> {
pub tokens: &'a [i32],
pub position: usize,
pub ple: Option<&'a [f32]>,
}
pub struct OriginalVerifyWindowResult {
pub selection: NativeHeadSelection,
pub generation: u64,
@@ -9,9 +9,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
/// releases every wait and drains both streams before preserving that primary.
pub fn run(
&mut self,
tokens: &[i32],
position: usize,
ple: Option<&[f32]>,
window: OriginalVerifyWindowTokens<'_>,
sampling: NativeHeadSampling<'_, 'ctx>,
mut pool: impl FnMut(
OriginalVerifyCpuRows<'_>,
@@ -19,6 +17,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
&mut OriginalGpuStream<'ctx>,
) -> Result<()>,
) -> Result<OriginalVerifyWindowResult> {
let OriginalVerifyWindowTokens { tokens, position, ple } = window;
self.check_run_inputs(tokens, position, ple, sampling.position)?;
let t = tokens.len();
let generation = self.stage_window(tokens, position, ple)?;
@@ -80,8 +80,14 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
return Err(Error::InvalidQwenShape);
}
let values = self.read_logit_rows(logits, 0, targets.len(), vocabulary)?;
write_window_logprobs(out, &values, vocabulary, targets, first as i64, extra_id, topk)
.map_err(|_| Error::InvalidDriverValue("window_logprobs output"))
write_window_logprobs(
out,
LogitRows { values: &values, vocabulary },
targets,
first as i64,
LogprobReadout { extra_id, topk },
)
.map_err(|_| Error::InvalidDriverValue("window_logprobs output"))
})
}
/// Bring-up diagnostic: the final residual R (`hc*n` f32 per row, all rows) of the last completed window and its
@@ -190,13 +190,12 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
let ids = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
MappedAllocation::with_cpu_rows(
x.as_ref().ok_or(Error::ContextPoisoned)?,
ids.as_ref().ok_or(Error::ContextPoisoned)?,
w.as_ref().ok_or(Error::ContextPoisoned)?,
begin,
rows,
g.n,
g.k,
MappedRouteOperands {
activation: x.as_ref().ok_or(Error::ContextPoisoned)?,
ids: ids.as_ref().ok_or(Error::ContextPoisoned)?,
weights: w.as_ref().ok_or(Error::ContextPoisoned)?,
},
RouteRowSpan { first: begin, rows, hidden_width: g.n, top_k: g.k },
|activation, ids, route_weights| {
let cpu = OriginalVerifyCpuRows { layer, group, first_row: begin, activation, ids, route_weights };
self.invoke_pool(pool, cpu, (begin, rows, groups, want))
@@ -22,9 +22,12 @@
//! The Original selects the hc read variant per card (`fused_gr_check`, `STRATA_HC_SPLIT`) and
//! the down kernel's tile and token chunking from the device attributes (`down_chunk`);
//! `GrConfig` carries exactly those decisions and `GrConfig::from_device` replicates `down_chunk`.
use super::kernels::{A, ArenaMap, AssetSpec, Launch};
use super::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent};
use super::layout::OriginalVerifyGeometry;
use super::proj::{self, NativeWeight, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1, q8_1_row_bytes};
use super::proj::{
self, Bf16GemvExtents, MmvqExtents, NativeWeight, StridedRows, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1,
q8_1_row_bytes,
};
use super::window_record::{HcHalf, Rows};
use super::{OriginalVerifyGdnJournal, admit, handle};
use crate::native_head::native_head_row_bytes;
@@ -131,6 +134,16 @@ pub(crate) const ATTR_COMPUTE_CAPABILITY_MAJOR: i32 = 75;
pub(crate) const ATTR_COMPUTE_CAPABILITY_MINOR: i32 = 76;
pub(crate) const ATTR_MAX_SHARED_PER_BLOCK_OPTIN: i32 = 97;
/// The four `cuDeviceGetAttribute` values `down_chunk` reads: the compute capability and the dynamic shared memory
/// limits (opt-in and per block, in bytes).
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrDeviceAttributes {
pub cc_major: i32,
pub cc_minor: i32,
pub optin: i32,
pub per_block: i32,
}
/// The hc-read decisions: `fused_gr_variant()` plus the result of `down_chunk` on this card.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GrConfig {
@@ -152,6 +165,15 @@ pub(crate) struct GrConfig {
pub attr_staged: Option<u32>,
}
/// What every gated-residual (GR) planner reads: the arena the spans come from, the window geometry and the
/// device-derived GR configuration.
#[derive(Clone, Copy)]
pub(crate) struct GrWindow<'a> {
pub arena: &'a dyn ArenaMap,
pub geo: &'a OriginalVerifyGeometry,
pub cfg: &'a GrConfig,
}
/// PLE settings of the Original (`--native`: `ple_set_native_bf16` + `ple_set_native_postops`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PleConfig {
@@ -29,14 +29,8 @@ impl GrConfig {
/// Replicates the one-time per-device block of `down_chunk` from the four device attributes
/// (`ATTR_*`). An attribute call is only emitted when the card reports an opt-in (Original
/// issues it unconditionally but ignores its failure and drops the error).
pub(crate) fn from_device(
variant: GrVariant,
native_mmvf: bool,
cc_major: i32,
cc_minor: i32,
optin: i32,
per_block: i32,
) -> Self {
pub(crate) fn from_device(variant: GrVariant, native_mmvf: bool, attributes: GrDeviceAttributes) -> Self {
let GrDeviceAttributes { cc_major, cc_minor, optin, per_block } = attributes;
let optin = optin.max(0) as u32;
let per_block = per_block.max(0) as u32;
let tile: u32 = if cc_major * 10 + cc_minor == 75 { 1280 } else { 2560 };
@@ -68,10 +62,12 @@ impl GrConfig {
Ok(Self::from_device(
variant,
native_mmvf,
journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?,
journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?,
journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK_OPTIN)?,
journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK)?,
GrDeviceAttributes {
cc_major: journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?,
cc_minor: journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?,
optin: journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK_OPTIN)?,
per_block: journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK)?,
},
))
}
@@ -10,14 +10,13 @@ use super::*;
/// `rs = rs_ + t*HC`, `mixed = mixed_ + t*N`; the attention half reads `inj2_` and writes `inj_`, the
/// FFN half the reverse.
pub(crate) fn plan_hc_read(
arena: &dyn ArenaMap,
geo: &OriginalVerifyGeometry,
window: GrWindow<'_>,
w: &HcAddrs,
cfg: &GrConfig,
half: HcHalf,
apply: bool,
rows: Rows,
) -> Result<HcReadPlan> {
let GrWindow { arena, geo, cfg } = window;
check_rows(geo, rows)?;
let n = rows.len();
let per_row = hc_read_rows(arena, half, rows)?;
@@ -59,15 +58,23 @@ fn hc_read_norm(cfg: &GrConfig, chain_gr: bool, n: usize, full: &[u64]) -> Resul
Launch::new(
&super::super::chain::CHAIN,
super::super::chain::E_GR_SPLIT,
[n as u32, HC as u32, 1],
[THREADS, 1, 1],
0,
LaunchExtent::new([n as u32, HC as u32, 1], [THREADS, 1, 1], 0),
vec![A::Words(full.to_vec())],
)
} else if cfg.variant == GrVariant::Plain {
Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.to_vec())])
Launch::new(
&GR_FUSED,
E_NORM,
LaunchExtent::new([n as u32, 1, 1], [THREADS, 1, 1], 0),
vec![A::Words(full.to_vec())],
)
} else {
Launch::new(&GR_FUSED, E_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.to_vec())])
Launch::new(
&GR_FUSED,
E_SPLIT,
LaunchExtent::new([n as u32, HC as u32, 1], [THREADS, 1, 1], 0),
vec![A::Words(full.to_vec())],
)
}
}
@@ -102,29 +109,39 @@ fn hc_read_down_chunk(
(ct, shared): (usize, u32),
words: impl FnOnce() -> Vec<u64>,
) -> Result<Launch> {
use super::super::chain;
if chain_staged && chain::down_tiled() {
// same arithmetic as the staged kernel; blocks of 8 rows x 2 tokens (grid.y = ceil(ct / 2)) spread the work
// over the SMs, the whole weight row in registers, four tile buffers of two tokens in flight
let (grid, shared) = tiled_down_geometry(ct);
if shared > cfg.usable_shared {
return Err(Error::InvalidProjectionShape);
}
let entry = chain::E_GR_DOWN_T2W8;
return Launch::new(&chain::CHAIN, entry, grid, [THREADS, 1, 1], shared, vec![A::Words(words())]);
if chain_staged && super::super::chain::down_tiled() {
return hc_read_down_tiled(cfg, ct, words);
}
if chain_staged {
// same arithmetic as the staged kernel; the whole weight row in registers and three (two above six tokens)
// tile buffers in flight
let (entry, buffers) = if ct <= 6 { (chain::E_GR_DOWN_NB3, 3) } else { (chain::E_GR_DOWN_NB2, 2) };
let shared = buffers * ct as u32 * (STAGED_TILE * 4);
if shared > cfg.usable_shared {
return Err(Error::InvalidProjectionShape);
}
let blocks = [DOWN_BLOCKS, 1, 1];
return Launch::new(&chain::CHAIN, entry, blocks, [THREADS, 1, 1], shared, vec![A::Words(words())]);
return hc_read_down_buffered(cfg, ct, words);
}
Launch::new(&GR_FUSED, cfg.down_entry(), [DOWN_BLOCKS, 1, 1], [THREADS, 1, 1], shared, vec![A::Words(words())])
let extent = LaunchExtent::new([DOWN_BLOCKS, 1, 1], [THREADS, 1, 1], shared);
Launch::new(&GR_FUSED, cfg.down_entry(), extent, vec![A::Words(words())])
}
/// The tiled chain down kernel. Same arithmetic as the staged kernel; blocks of 8 rows x 2 tokens (grid.y = ceil(ct /
/// 2)) spread the work over the SMs, the whole weight row in registers, four tile buffers of two tokens in flight.
fn hc_read_down_tiled(cfg: &GrConfig, ct: usize, words: impl FnOnce() -> Vec<u64>) -> Result<Launch> {
use super::super::chain;
let (grid, shared) = tiled_down_geometry(ct);
if shared > cfg.usable_shared {
return Err(Error::InvalidProjectionShape);
}
let entry = chain::E_GR_DOWN_T2W8;
Launch::new(&chain::CHAIN, entry, LaunchExtent::new(grid, [THREADS, 1, 1], shared), vec![A::Words(words())])
}
/// The two/three-buffer chain down kernel. Same arithmetic as the staged kernel; the whole weight row in registers and
/// three (two above six tokens) tile buffers in flight.
fn hc_read_down_buffered(cfg: &GrConfig, ct: usize, words: impl FnOnce() -> Vec<u64>) -> Result<Launch> {
use super::super::chain;
let (entry, buffers) = if ct <= 6 { (chain::E_GR_DOWN_NB3, 3) } else { (chain::E_GR_DOWN_NB2, 2) };
let shared = buffers * ct as u32 * (STAGED_TILE * 4);
if shared > cfg.usable_shared {
return Err(Error::InvalidProjectionShape);
}
let blocks = [DOWN_BLOCKS, 1, 1];
Launch::new(&chain::CHAIN, entry, LaunchExtent::new(blocks, [THREADS, 1, 1], shared), vec![A::Words(words())])
}
fn hc_read_up(chain_gr: bool, full: Vec<u64>) -> Result<Launch> {
@@ -136,9 +153,14 @@ fn hc_read_up(chain_gr: bool, full: Vec<u64>) -> Result<Launch> {
} else {
(super::super::chain::E_GR_UP16, UP_BLOCKS)
};
Launch::new(&super::super::chain::CHAIN, entry, [blocks, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])
Launch::new(
&super::super::chain::CHAIN,
entry,
LaunchExtent::new([blocks, 1, 1], [THREADS, 1, 1], 0),
vec![A::Words(full)],
)
} else {
Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])
Launch::new(&GR_FUSED, E_UP, LaunchExtent::new([UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0), vec![A::Words(full)])
}
}
@@ -157,9 +179,7 @@ pub(super) fn write_row(arena: &dyn ArenaMap, cfg: &GrConfig, row: usize, produc
Launch::new(
&GR_POST,
"mtp_full_native_write",
[(D as u32).div_ceil(THREADS), 1, 1],
[THREADS, 1, 1],
0,
LaunchExtent::new([(D as u32).div_ceil(THREADS), 1, 1], [THREADS, 1, 1], 0),
vec![A::P(r), A::P(bo), A::P(inject), A::P(r), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)],
)
}
@@ -190,13 +210,12 @@ pub(crate) fn plan_final_write(
/// (xn, gated, lo) is carved from arena spans that are dead after the layers: `xn` slot `t`, `lo`
/// slot `t` and the first `HC*N` floats of `parts` slot `t`.
pub(crate) fn plan_head_mix(
arena: &dyn ArenaMap,
geo: &OriginalVerifyGeometry,
window: GrWindow<'_>,
w: &HeadAddrs,
cfg: &GrConfig,
mixed_out_base: u64,
rows: usize,
) -> Result<Vec<Launch>> {
let GrWindow { arena, geo, cfg } = window;
check_geometry(geo)?;
if !(1..=geo.max_t).contains(&rows) {
return Err(Error::InvalidQwenShape);
@@ -226,14 +245,18 @@ fn head_mix_row(
let mixed = mixed_base + (t * N * 4) as u64;
// native_gr_rms_norm_weighted(R, w_norm, xn, n_embd, hc, eps): n_cols >= 1024 -> <1024>, hc blocks
let norm_args = vec![A::P(r), A::P(w.norm), A::P(xn), A::I32(N as i32), A::F32(EPS)];
let norm = Launch::new(&GR_NORM, "mtp_full_gr_norm", [HC as u32, 1, 1], [1024, 1, 1], 0, norm_args)?;
let down = plan_bf16_gemv(xn, D, w.down, lo, LR, D, LR, 1)?;
let norm =
Launch::new(&GR_NORM, "mtp_full_gr_norm", LaunchExtent::new([HC as u32, 1, 1], [1024, 1, 1], 0), norm_args)?;
let down =
plan_bf16_gemv(StridedRows::new(xn, D), w.down, StridedRows::new(lo, LR), Bf16GemvExtents::new(D, LR, 1))?;
let silu_grid = [(LR as u32).div_ceil(THREADS), 1, 1];
let silu_args = vec![A::P(lo), A::I32(LR as i32), A::F32(QUARTER)];
let silu = Launch::new(&GR_POST, "mtp_full_down_silu", silu_grid, [THREADS, 1, 1], 0, silu_args)?;
let up = plan_bf16_gemv(lo, LR, w.up, gated, D, LR, D, 1)?;
let silu =
Launch::new(&GR_POST, "mtp_full_down_silu", LaunchExtent::new(silu_grid, [THREADS, 1, 1], 0), silu_args)?;
let up =
plan_bf16_gemv(StridedRows::new(lo, LR), w.up, StridedRows::new(gated, D), Bf16GemvExtents::new(LR, D, 1))?;
let pre_grid = [(N as u32).div_ceil(THREADS), 1, 1];
let pre_args = vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)];
let pre = Launch::new(&GR_POST, "mtp_full_pre_final", pre_grid, [THREADS, 1, 1], 0, pre_args)?;
let pre = Launch::new(&GR_POST, "mtp_full_pre_final", LaunchExtent::new(pre_grid, [THREADS, 1, 1], 0), pre_args)?;
Ok([norm, down, silu, up, pre])
}
@@ -23,14 +23,8 @@ use super::*;
/// from the workspace and performs the identical shift-and-append (pure data movement, same
/// 40x256 launch), so the memcpy node is not recorded. `native_ple_postops_batch`'s kernels at
/// `T = 1` have the single-token kernels' launch geometry and per-element arithmetic.
pub(crate) fn plan_ple_row(
arena: &dyn ArenaMap,
geo: &OriginalVerifyGeometry,
cfg: &GrConfig,
ple: &PleConfig,
a: &PleAddrs,
row: usize,
) -> Result<Vec<Launch>> {
pub(crate) fn plan_ple_row(window: GrWindow<'_>, ple: &PleConfig, a: &PleAddrs, row: usize) -> Result<Vec<Launch>> {
let GrWindow { arena, geo, cfg } = window;
check_ple_row(geo, ple, row)?;
let mut out = Vec::with_capacity(14);
out.push(write_row(arena, cfg, row, "ple_layer1")?);
@@ -39,9 +33,14 @@ pub(crate) fn plan_ple_row(
let emb = row_span(arena, "ple", row, N * 4)?;
let scratch = PleScratch::at(a.scratch);
plan_ple_key(arena, ple, a, emb, scratch.key, &mut out)?;
plan_ple_key(arena, ple, a, emb, &mut out)?;
// value = ple_value @ emb
out.push(plan_bf16_gemv(emb, N, a.value, scratch.value, N, N, N, 1)?);
out.push(plan_bf16_gemv(
StridedRows::new(emb, N),
a.value,
StridedRows::new(scratch.value, N),
Bf16GemvExtents::new(N, N, 1),
)?);
out.extend(plan_ple_postops(a, r, &scratch)?);
Ok(out)
}
@@ -83,23 +82,22 @@ impl PleScratch {
}
/// key = ple_key @ emb (BF16 MMVF, or q8_1 quantize + MMVQ for a native key).
fn plan_ple_key(
arena: &dyn ArenaMap,
ple: &PleConfig,
a: &PleAddrs,
emb: u64,
key: u64,
out: &mut Vec<Launch>,
) -> Result<()> {
fn plan_ple_key(arena: &dyn ArenaMap, ple: &PleConfig, a: &PleAddrs, emb: u64, out: &mut Vec<Launch>) -> Result<()> {
let key = PleScratch::at(a.scratch).key;
match a.key {
PleKey::Bf16(w) => out.push(plan_bf16_gemv(emb, N, w, key, D, N, D, 1)?),
PleKey::Bf16(w) => out.push(plan_bf16_gemv(
StridedRows::new(emb, N),
w,
StridedRows::new(key, D),
Bf16GemvExtents::new(N, D, 1),
)?),
PleKey::Native { ty, data } => {
if !matches!(ty, 42 | 18 | 23 | 8) {
return Err(Error::UnsupportedQwenOperation);
}
let q8 = arena.span("xq", 0, q8_1_row_bytes(N))?;
out.push(plan_quantize_q8_1(emb, q8, N, 1)?);
out.push(plan_mmvq(&NativeWeight { ty, data }, q8, key, N, D, 1, ple.dispatch)?);
out.push(plan_mmvq(&NativeWeight { ty, data }, q8, key, MmvqExtents::new(N, D, 1), ple.dispatch)?);
}
}
Ok(())
@@ -107,7 +105,7 @@ fn plan_ple_key(
fn ple_rms(input: u64, gamma: u64, output: u64) -> Result<Launch> {
let args = vec![A::P(input), A::P(gamma), A::P(output)];
Launch::new(&PLE_BATCH, "ple_rms", [HC as u32, 1, 1], [1024, 1, 1], 0, args)
Launch::new(&PLE_BATCH, "ple_rms", LaunchExtent::new([HC as u32, 1, 1], [1024, 1, 1], 0), args)
}
/// native_ple_postops(d_key, hidden, d_value, hist, w, {key=d_query, query=d_norm, gate=d_gate,
@@ -116,32 +114,36 @@ fn plan_ple_postops(a: &PleAddrs, r: u64, s: &PleScratch) -> Result<[Launch; 7]>
let rms_key = ple_rms(s.key, a.norm_key, s.query)?;
let rms_hidden = ple_rms(r, a.norm_query, s.norm)?;
let gate_args = vec![A::P(s.query), A::P(s.norm), A::P(s.gate), A::F32(1.0f32 / (N as f32).sqrt())];
let gate = Launch::new(&PLE_BATCH, "ple_gate", [HC as u32, 1, 1], [512, 1, 1], 0, gate_args)?;
let gate = Launch::new(&PLE_BATCH, "ple_gate", LaunchExtent::new([HC as u32, 1, 1], [512, 1, 1], 0), gate_args)?;
let blocks = (D as u32) / THREADS;
let broadcast_args = vec![A::P(s.value), A::P(s.gate), A::P(s.gated), A::I32(1)];
let broadcast = Launch::new(&PLE_BATCH, "ple_broadcast", [blocks, 1, 1], [THREADS, 1, 1], 0, broadcast_args)?;
let broadcast = Launch::new(
&PLE_BATCH,
"ple_broadcast",
LaunchExtent::new([blocks, 1, 1], [THREADS, 1, 1], 0),
broadcast_args,
)?;
let rms_gated = ple_rms(s.gated, a.norm_conv, s.norm)?;
let conv_args =
vec![A::P(a.history), A::P(s.norm), A::P(a.conv1d), A::P(r), A::P(s.gated), A::P(s.conv), A::I32(1)];
let conv = Launch::new(&PLE_BATCH, "ple_conv", [blocks, 1, 1], [THREADS, 1, 1], 0, conv_args)?;
let conv = Launch::new(&PLE_BATCH, "ple_conv", LaunchExtent::new([blocks, 1, 1], [THREADS, 1, 1], 0), conv_args)?;
// ple_history_advance(hist, normalized)
let history_args = vec![A::P(a.history), A::P(s.norm), A::I32(1)];
let history = Launch::new(&PLE_BATCH, "ple_history", [blocks, 1, 1], [THREADS, 1, 1], 0, history_args)?;
let history =
Launch::new(&PLE_BATCH, "ple_history", LaunchExtent::new([blocks, 1, 1], [THREADS, 1, 1], 0), history_args)?;
Ok([rms_key, rms_hidden, gate, broadcast, rms_gated, conv, history])
}
/// `pre(1, group)`'s PLE loop for the rows `[tb, te)`: one `(row, launches)` entry per row, to be
/// submitted in order, each followed by `capture_ple_snapshot(row)`.
pub(crate) fn plan_ple_layer1(
arena: &dyn ArenaMap,
geo: &OriginalVerifyGeometry,
cfg: &GrConfig,
window: GrWindow<'_>,
ple: &PleConfig,
a: &PleAddrs,
rows: Rows,
) -> Result<Vec<(usize, Vec<Launch>)>> {
check_rows(geo, rows)?;
(rows.begin..rows.end).map(|t| Ok((t, plan_ple_row(arena, geo, cfg, ple, a, t)?))).collect()
check_rows(window.geo, rows)?;
(rows.begin..rows.end).map(|t| Ok((t, plan_ple_row(window, ple, a, t)?))).collect()
}
impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
pub fn new(
@@ -23,9 +23,22 @@ fn words(l: &Launch) -> &[u64] {
fn rows(begin: usize, end: usize, group: usize) -> Rows {
Rows { begin, end, group }
}
/// The GR planners' inputs: the arena, the geometry and the device configuration.
fn window<'a>(arena: &'a dyn ArenaMap, geo: &'a OriginalVerifyGeometry, cfg: &'a GrConfig) -> GrWindow<'a> {
GrWindow { arena, geo, cfg }
}
/// A native-MMVF card of compute capability `cc` (major, minor) with the given dynamic shared memory limits.
fn from_card(variant: GrVariant, cc: (i32, i32), optin: i32, per_block: i32) -> GrConfig {
let attributes = GrDeviceAttributes { cc_major: cc.0, cc_minor: cc.1, optin, per_block };
GrConfig::from_device(variant, true, attributes)
}
/// RTX-class sm_120: 99 KiB opt-in, 48 KiB default per block.
fn sm120(variant: GrVariant) -> GrConfig {
GrConfig::from_device(variant, true, 12, 0, 101_376, 49_152)
GrConfig::from_device(
variant,
true,
GrDeviceAttributes { cc_major: 12, cc_minor: 0, optin: 101_376, per_block: 49_152 },
)
}
fn entry_declared(ptx: &str, e: &str) -> bool {
ptx.contains(&format!(".entry {e}(")) || ptx.contains(&format!(".visible .entry {e}("))
@@ -34,13 +34,13 @@ fn assert_head_mix_row(m: &LayoutMap, k: &[Launch], t: usize, mixed_base: u64) {
/// The whole window: 1..=8 rows; none beyond max_t; the non-native mmvf refuses.
fn assert_head_mix_row_bounds(m: &LayoutMap, w: &HeadAddrs, mixed_base: u64) {
let g = test_geometry();
assert!(plan_head_mix(m, &g, w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok());
assert!(plan_head_mix(m, &g, w, &sm120(GrVariant::Staged), mixed_base, 9).is_err());
assert!(plan_head_mix(m, &g, w, &sm120(GrVariant::Staged), mixed_base, 0).is_err());
assert!(plan_head_mix(window(m, &g, &sm120(GrVariant::Staged)), w, mixed_base, 8).is_ok());
assert!(plan_head_mix(window(m, &g, &sm120(GrVariant::Staged)), w, mixed_base, 9).is_err());
assert!(plan_head_mix(window(m, &g, &sm120(GrVariant::Staged)), w, mixed_base, 0).is_err());
let mut non_native = sm120(GrVariant::Staged);
non_native.native_mmvf = false;
assert!(matches!(
plan_head_mix(m, &g, w, &non_native, mixed_base, 1),
plan_head_mix(window(m, &g, &non_native), w, mixed_base, 1),
Err(Error::InvalidDriverValue(s)) if s.contains("head")
));
}
@@ -51,7 +51,7 @@ fn head_mix_is_the_native_unfused_gr_read_per_token() {
let g = test_geometry();
let w = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 };
let mixed_base = 0x9999_0000u64;
let l = plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 3).unwrap();
let l = plan_head_mix(window(&m, &g, &sm120(GrVariant::Staged)), &w, mixed_base, 3).unwrap();
assert_eq!(l.len(), 15);
for t in 0..3usize {
assert_head_mix_row(&m, &l[t * 5..t * 5 + 5], t, mixed_base);
@@ -141,7 +141,7 @@ fn ple_row_with_a_bf16_key_follows_ple_block_native_order() {
let m = arena();
let g = test_geometry();
let a = ple_addrs(PleKey::Bf16(0x7000_0000));
let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap();
let l = plan_ple_row(window(&m, &g, &sm120(GrVariant::Staged)), &PleConfig::mode17(), &a, 2).unwrap();
assert_ple_bf16_row_names(&l);
let r = at(&m, "R", 2 * 40_960);
let emb = at(&m, "ple", 2 * 10_240);
@@ -157,7 +157,7 @@ fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() {
let m = arena();
let g = test_geometry();
let a = ple_addrs(PleKey::Native { ty: 42, data: 0x7100_0000 });
let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 0).unwrap();
let l = plan_ple_row(window(&m, &g, &sm120(GrVariant::Staged)), &PleConfig::mode17(), &a, 0).unwrap();
let names: Vec<&str> = l.iter().map(|x| x.entry).collect();
assert_eq!(&names[..4], &["mtp_full_native_write", "head_quant", "head_n42_s1", "mtp_full_mmvf256"]);
assert_eq!(l.len(), 11);
@@ -170,7 +170,7 @@ fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() {
// an unsupported native key type fails closed
let bad = ple_addrs(PleKey::Native { ty: 14, data: 1 });
assert_eq!(
plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &bad, 0).unwrap_err(),
plan_ple_row(window(&m, &g, &sm120(GrVariant::Staged)), &PleConfig::mode17(), &bad, 0).unwrap_err(),
Error::UnsupportedQwenOperation
);
}
@@ -181,19 +181,19 @@ fn ple_layer1_walks_the_group_rows_in_order_and_fails_closed_on_policy() {
let g = test_geometry();
let a = ple_addrs(PleKey::Bf16(0x7000_0000));
let c = sm120(GrVariant::Staged);
let out = plan_ple_layer1(&m, &g, &c, &PleConfig::mode17(), &a, rows(4, 7, 1)).unwrap();
let out = plan_ple_layer1(window(&m, &g, &c), &PleConfig::mode17(), &a, rows(4, 7, 1)).unwrap();
assert_eq!(out.iter().map(|(t, _)| *t).collect::<Vec<_>>(), [4, 5, 6]);
assert!(out.iter().all(|(_, l)| l.len() == 10));
let mut legacy = PleConfig::mode17();
legacy.native_postops = false;
assert!(matches!(
plan_ple_layer1(&m, &g, &c, &legacy, &a, rows(0, 1, 0)),
plan_ple_layer1(window(&m, &g, &c), &legacy, &a, rows(0, 1, 0)),
Err(Error::InvalidDriverValue(s)) if s.contains("ple_layer1")
));
legacy = PleConfig::mode17();
legacy.native_value_bf16 = false;
assert!(plan_ple_row(&m, &g, &c, &legacy, &a, 0).is_err());
assert!(plan_ple_row(&m, &g, &c, &PleConfig::mode17(), &a, 8).is_err());
assert!(plan_ple_row(window(&m, &g, &c), &legacy, &a, 0).is_err());
assert!(plan_ple_row(window(&m, &g, &c), &PleConfig::mode17(), &a, 8).is_err());
}
// ---------------------------------------------------------------------------- byte sizes
@@ -68,7 +68,7 @@ fn down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens() {
#[test]
fn down_chunk_on_turing_slices_staged_tokens_and_uses_the_1280_tile() {
// sm_75: 64 KiB opt-in
let c = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152);
let c = from_card(GrVariant::Staged, (7, 5), 65_536, 49_152);
assert_eq!(c.tile, 1280);
assert_eq!(c.attr_down, Some(8 * 1280 * 4)); // 40960 fits
assert_eq!(c.attr_staged, Some(65_536)); // 81920 > opt-in -> opt-in
@@ -79,21 +79,22 @@ fn down_chunk_on_turing_slices_staged_tokens_and_uses_the_1280_tile() {
#[test]
fn down_chunk_below_volta_uses_the_per_block_limit_and_never_less_than_one_token() {
// sm_61 reports no usable opt-in: per-block limit 48 KiB
let c = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 49_152);
let c = from_card(GrVariant::Plain, (6, 1), 0, 49_152);
assert_eq!(c.tile, 2560);
assert_eq!((c.chunk_plain, c.chunk_staged), (4, 4)); // 49152 / 10240
assert_eq!((c.attr_down, c.attr_staged), (None, None));
// sm_60 answers a 64 KiB opt-in it does not keep: the limit is still per block
let c60 = GrConfig::from_device(GrVariant::Plain, true, 6, 0, 65_536, 49_152);
let c60 = from_card(GrVariant::Plain, (6, 0), 65_536, 49_152);
assert_eq!(c60.usable_shared, 49_152);
assert_eq!(c60.chunk_plain, 4);
assert_eq!((c60.attr_down, c60.attr_staged), (None, None));
// a card that cannot hold one token still reports a chunk of 1 (the launch is then refused)
let tiny = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 4096);
let tiny = from_card(GrVariant::Plain, (6, 1), 0, 4096);
assert_eq!((tiny.chunk_plain, tiny.chunk_staged), (1, 1));
let m = arena();
assert_eq!(
plan_hc_read(&m, &test_geometry(), &weights(), &tiny, HcHalf::Attention, false, rows(0, 2, 0)).unwrap_err(),
plan_hc_read(window(&m, &test_geometry(), &tiny), &weights(), HcHalf::Attention, false, rows(0, 2, 0))
.unwrap_err(),
Error::InvalidProjectionShape
);
}
@@ -105,7 +106,7 @@ fn shared_attributes_name_the_tile_kernel_of_the_card_and_the_staged_kernel() {
assert_eq!((big[0].1, big[0].2), (E_DOWN2560, 81_920));
assert_eq!((big[1].1, big[1].2), (E_STAGED, 81_920));
assert!(big.iter().all(|a| std::ptr::eq(a.0, &GR_FUSED)));
let turing = shared_attributes(&GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152));
let turing = shared_attributes(&from_card(GrVariant::Staged, (7, 5), 65_536, 49_152));
assert_eq!((turing[0].1, turing[0].2), (E_DOWN1280, 40_960));
assert_eq!((turing[1].1, turing[1].2), (E_STAGED, 65_536));
}
@@ -144,7 +145,8 @@ fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() {
let m = arena();
let g = test_geometry();
let w = weights();
let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap();
let plan =
plan_hc_read(window(&m, &g, &sm120(GrVariant::Staged)), &w, HcHalf::Attention, true, rows(0, 8, 0)).unwrap();
let full = assert_staged_read_launch_kinds(&plan);
assert_eq!(full.len(), 114);
// trailer: xn = xn_ + tb*HC*N*4, T = 8
@@ -171,7 +173,8 @@ fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() {
fn ffn_half_swaps_the_injection_buffers_and_apply_is_carried() {
let m = arena();
let g = test_geometry();
let plan = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, false, rows(0, 1, 0)).unwrap();
let plan =
plan_hc_read(window(&m, &g, &sm120(GrVariant::Staged)), &weights(), HcHalf::Ffn, false, rows(0, 1, 0)).unwrap();
let a = &words(&plan.norm)[..14];
assert_eq!(a[2], 0);
assert_eq!(a[4], at(&m, "inj", 0));
@@ -187,7 +190,8 @@ fn split_windows_read_their_own_rows_and_offset_the_scratch() {
let m = arena();
let g = test_geometry();
// T = 7 -> groups [0,4) and [4,7): (T+1)/2 = 4
let g1 = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, true, rows(4, 7, 1)).unwrap();
let g1 =
plan_hc_read(window(&m, &g, &sm120(GrVariant::Staged)), &weights(), HcHalf::Ffn, true, rows(4, 7, 1)).unwrap();
let w1 = words(&g1.norm);
assert_eq!(w1[112], at(&m, "xn", 4 * 40_960));
assert_eq!(w1[113], 3);
@@ -204,15 +208,17 @@ fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() {
let m = arena();
let g = test_geometry();
let plain =
plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap();
plan_hc_read(window(&m, &g, &sm120(GrVariant::Plain)), &weights(), HcHalf::Attention, false, rows(0, 5, 0))
.unwrap();
assert_eq!((plain.norm.entry, plain.norm.grid), (E_NORM, [5, 1, 1]));
assert_eq!((plain.down[0].entry, plain.down[0].shared), (E_DOWN2560, 5 * 2560 * 4));
let split =
plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap();
plan_hc_read(window(&m, &g, &sm120(GrVariant::Split)), &weights(), HcHalf::Attention, false, rows(0, 5, 0))
.unwrap();
assert_eq!((split.norm.entry, split.norm.grid), (E_SPLIT, [5, 4, 1]));
assert_eq!(split.down[0].entry, E_DOWN2560);
let turing = GrConfig::from_device(GrVariant::Plain, true, 7, 5, 65_536, 49_152);
let t = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, false, rows(0, 8, 0)).unwrap();
let turing = from_card(GrVariant::Plain, (7, 5), 65_536, 49_152);
let t = plan_hc_read(window(&m, &g, &turing), &weights(), HcHalf::Attention, false, rows(0, 8, 0)).unwrap();
assert_eq!((t.down[0].entry, t.down[0].shared), (E_DOWN1280, 8 * 1280 * 4));
}
@@ -220,8 +226,8 @@ fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() {
fn down_projection_is_chunked_by_the_card_capacity() {
let m = arena();
let g = test_geometry();
let turing = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152);
let plan = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, true, rows(0, 8, 0)).unwrap();
let turing = from_card(GrVariant::Staged, (7, 5), 65_536, 49_152);
let plan = plan_hc_read(window(&m, &g, &turing), &weights(), HcHalf::Attention, true, rows(0, 8, 0)).unwrap();
// 8 tokens, 6 per launch -> 6 + 2
assert_eq!(plan.down.len(), 2);
assert_eq!((plan.down[0].shared, plan.down[1].shared), (61_440, 20_480));
@@ -253,13 +259,13 @@ fn hc_read_validates_rows_and_geometry() {
let g = test_geometry();
let c = sm120(GrVariant::Staged);
let w = weights();
assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(3, 3, 0)).is_err());
assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(0, 9, 0)).is_err());
assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(7, 9, 1)).is_err());
assert!(plan_hc_read(window(&m, &g, &c), &w, HcHalf::Attention, false, rows(3, 3, 0)).is_err());
assert!(plan_hc_read(window(&m, &g, &c), &w, HcHalf::Attention, false, rows(0, 9, 0)).is_err());
assert!(plan_hc_read(window(&m, &g, &c), &w, HcHalf::Attention, false, rows(7, 9, 1)).is_err());
let mut odd = g;
odd.hc = 8;
assert_eq!(
plan_hc_read(&m, &odd, &w, &c, HcHalf::Attention, false, rows(0, 1, 0)).unwrap_err(),
plan_hc_read(window(&m, &odd, &c), &w, HcHalf::Attention, false, rows(0, 1, 0)).unwrap_err(),
Error::InvalidQwenShape
);
// every T = 1..=8 and both groups of the split window plan
@@ -267,7 +273,7 @@ fn hc_read_validates_rows_and_geometry() {
let first = (t + 1) / 2;
let groups = if t >= 2 { vec![(0, first), (first, t)] } else { vec![(0, t)] };
for (gi, (b, e)) in groups.into_iter().enumerate() {
let plan = plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, true, rows(b, e, gi)).unwrap();
let plan = plan_hc_read(window(&m, &g, &c), &w, HcHalf::Attention, true, rows(b, e, gi)).unwrap();
assert_eq!(words(&plan.up)[113], (e - b) as u64);
assert_eq!(plan.norm.grid[0], (e - b) as u32);
}
@@ -126,6 +126,22 @@ impl A {
}
}
/// The `<<<grid, block, shared>>>` extent of one window kernel launch: blocks per grid, threads per block and
/// dynamic shared memory bytes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LaunchExtent {
pub grid: [u32; 3],
pub block: [u32; 3],
pub shared: u32,
}
impl LaunchExtent {
/// The extent of `grid` blocks of `block` threads with `shared` bytes of dynamic shared memory.
#[inline]
pub(crate) const fn new(grid: [u32; 3], block: [u32; 3], shared: u32) -> Self {
Self { grid, block, shared }
}
}
/// One `cuLaunchKernel`: `<<<grid, block, shared>>>` of `entry` in `asset`.
#[derive(Clone, Debug)]
pub(crate) struct Launch {
@@ -154,11 +170,10 @@ impl Launch {
pub(crate) fn new(
asset: &'static AssetSpec,
entry: &'static str,
grid: [u32; 3],
block: [u32; 3],
shared: u32,
extent: LaunchExtent,
args: Vec<A>,
) -> Result<Self> {
let LaunchExtent { grid, block, shared } = extent;
if !asset.has_entry(entry) || grid.contains(&0) || block.contains(&0) {
return Err(Error::InvalidQwenShape);
}
@@ -246,10 +261,19 @@ mod tests {
#[test]
fn launch_refuses_foreign_entries_and_empty_geometry() {
assert!(Launch::new(&SPEC, "a", [1, 1, 1], [32, 1, 1], 0, vec![]).is_ok());
assert_eq!(Launch::new(&SPEC, "c", [1, 1, 1], [32, 1, 1], 0, vec![]).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(Launch::new(&SPEC, "a", [0, 1, 1], [32, 1, 1], 0, vec![]).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(Launch::new(&SPEC, "a", [1, 1, 1], [32, 0, 1], 0, vec![]).unwrap_err(), Error::InvalidQwenShape);
assert!(Launch::new(&SPEC, "a", LaunchExtent::new([1, 1, 1], [32, 1, 1], 0), vec![]).is_ok());
assert_eq!(
Launch::new(&SPEC, "c", LaunchExtent::new([1, 1, 1], [32, 1, 1], 0), vec![]).unwrap_err(),
Error::InvalidQwenShape
);
assert_eq!(
Launch::new(&SPEC, "a", LaunchExtent::new([0, 1, 1], [32, 1, 1], 0), vec![]).unwrap_err(),
Error::InvalidQwenShape
);
assert_eq!(
Launch::new(&SPEC, "a", LaunchExtent::new([1, 1, 1], [32, 0, 1], 0), vec![]).unwrap_err(),
Error::InvalidQwenShape
);
}
#[test]
@@ -281,7 +305,7 @@ mod tests {
#[test]
fn launch_label_names_asset_entry_and_geometry() {
let l = Launch::new(&SPEC, "b", [2, 3, 1], [32, 4, 1], 16, vec![A::I32(1)]).unwrap();
let l = Launch::new(&SPEC, "b", LaunchExtent::new([2, 3, 1], [32, 4, 1], 16), vec![A::I32(1)]).unwrap();
assert_eq!(l.label(), "demo:b <<<[2, 3, 1],[32, 4, 1],16>>>");
}
}
@@ -30,8 +30,10 @@
//! they live in the new source `original_verify_window_moe_experts.cu` (PTX compiled with nvcc 13.2.86 and sealed
//! on 2026-10-15). An asset whose bytes stop matching its pin makes the expert producers fail closed with the
//! asset's refusal text. GPU load is verified separately by the host smokes; no numerical claim.
use super::kernels::{A, ArenaMap, AssetSpec, Launch};
use super::proj::{self, NativeWeight, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1};
use super::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent};
use super::proj::{
self, Bf16GemvExtents, MmvqExtents, NativeWeight, StridedRows, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1,
};
use super::window_plan::{PlanLayout, WINDOW_LAYERS};
use super::window_record::{ExpertTier, Rows};
use super::{OriginalVerifyGeometry, admit, handle};
@@ -373,6 +375,8 @@ pub(crate) use pcie_fast_kernel_fn::shared_attributes;
#[path = "original_verify_window_moe/plan_f32_to_bf16_fn.rs"]
mod plan_f32_to_bf16_fn;
#[allow(unused_imports)]
pub(crate) use plan_f32_to_bf16_fn::BatchedRows;
#[allow(unused_imports)]
pub(crate) use plan_f32_to_bf16_fn::expert_scratch;
#[allow(unused_imports)]
use plan_f32_to_bf16_fn::plan_f32_to_bf16;
@@ -387,6 +391,8 @@ pub(crate) use plan_f32_to_bf16_fn::plan_shared_expert;
#[path = "original_verify_window_moe/plan_expert_groups_fn.rs"]
mod plan_expert_groups_fn;
#[allow(unused_imports)]
pub(crate) use plan_expert_groups_fn::ExpertGroupSite;
#[allow(unused_imports)]
pub(crate) use plan_expert_groups_fn::plan_combine;
#[allow(unused_imports)]
pub(crate) use plan_expert_groups_fn::plan_expert_groups;
@@ -6,6 +6,14 @@ use super::*;
/// The row arena the planners read, as a trait object (one place names the dyn).
type Arena<'a> = &'a dyn ArenaMap;
/// The routed experts one tier computes for a group: the layer, the group's rows and the tier.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ExpertGroupSite {
pub layer: usize,
pub rows: Rows,
pub tier: ExpertTier,
}
/// `grouped(gp, gs, gn)` of `post`: `native_expert_grouped(L, ...)` for one tier, `L` the layer's native
/// layout and `cap = n * K` groups / entries.
pub(crate) fn plan_expert_groups(
@@ -13,10 +21,9 @@ pub(crate) fn plan_expert_groups(
g: &OriginalVerifyGeometry,
knobs: &MoeKnobs,
formats: &OriginalVerifyExpertFormats,
layer: usize,
rows: Rows,
tier: ExpertTier,
site: ExpertGroupSite,
) -> Result<Vec<Launch>> {
let ExpertGroupSite { layer, rows, tier } = site;
let n = check_rows(g, rows)?;
if !knobs.native_experts {
return unavailable!(
@@ -117,13 +124,13 @@ impl GroupPlan {
if tiny {
let args = vec![A::P(gate), A::P(up), A::P(h), A::P(hq), A::I64(nh as i64)];
let (chain, entry) = (&super::super::chain::CHAIN, super::super::chain::E_SWIGLU_QUANT);
return Ok(vec![Launch::new(chain, entry, grid, [256, 1, 1], 0, args)?]);
return Ok(vec![Launch::new(chain, entry, LaunchExtent::new(grid, [256, 1, 1], 0), args)?]);
}
let swiglu_args = vec![A::P(gate), A::P(up), A::P(h), A::I64(nh as i64)];
let quant_args = vec![A::P(h), A::P(hq), A::I64(nh as i64)];
Ok(vec![
Launch::new(&HEAD_IQ_EXPERT, E_SWIGLU_ENTRIES, grid, [256, 1, 1], 0, swiglu_args)?,
Launch::new(&HEAD_IQ_EXPERT, E_QUANTIZE_Q8_1, grid, [256, 1, 1], 0, quant_args)?,
Launch::new(&HEAD_IQ_EXPERT, E_SWIGLU_ENTRIES, LaunchExtent::new(grid, [256, 1, 1], 0), swiglu_args)?,
Launch::new(&HEAD_IQ_EXPERT, E_QUANTIZE_Q8_1, LaunchExtent::new(grid, [256, 1, 1], 0), quant_args)?,
])
}
@@ -142,7 +149,7 @@ impl GroupPlan {
A::P(self.hq),
];
let grid = [(self.n_ff / 32) as u32, self.cap as u32, 1];
Launch::new(&super::super::sm120::GU_SWIGLU, entry, grid, [512, 1, 1], 0, args)
Launch::new(&super::super::sm120::GU_SWIGLU, entry, LaunchExtent::new(grid, [512, 1, 1], 0), args)
}
fn gate_up(&self, entry: &'static str, words: &[u64]) -> Result<Launch> {
@@ -157,7 +164,7 @@ impl GroupPlan {
A::P(self.up),
];
let grid = [(2 * self.n_ff).div_ceil(8) as u32, self.cap as u32, 1];
Launch::new(&EXPERTS, entry, grid, [256, 1, 1], 0, args)
Launch::new(&EXPERTS, entry, LaunchExtent::new(grid, [256, 1, 1], 0), args)
}
fn down(&self, entry: &'static str, words: Vec<u64>) -> Result<Launch> {
@@ -165,7 +172,7 @@ impl GroupPlan {
let args =
vec![A::P(ptr), A::P(start), A::P(groups), A::P(dst), A::P(self.hq), A::Words(words), A::P(self.out)];
let grid = [self.n_embd.div_ceil(8) as u32, self.cap as u32, 1];
Launch::new(&EXPERTS, entry, grid, [256, 1, 1], 0, args)
Launch::new(&EXPERTS, entry, LaunchExtent::new(grid, [256, 1, 1], 0), args)
}
}
@@ -183,9 +190,7 @@ pub(crate) fn plan_hit_add(arena: Arena<'_>, g: &OriginalVerifyGeometry, rows: R
Ok(vec![Launch::new(
&S2_HITS,
E_ADD_HITS,
[n_embd.div_ceil(256).min(8) as u32, cap as u32, 1],
[256, 1, 1],
0,
LaunchExtent::new([n_embd.div_ceil(256).min(8) as u32, cap as u32, 1], [256, 1, 1], 0),
vec![A::P(parts), A::P(hit_out), A::P(dst), A::P(count), A::I32(n_embd as i32)],
)?])
}
@@ -229,14 +234,19 @@ fn combine_row(arena: Arena<'_>, g: &OriginalVerifyGeometry, knobs: &MoeKnobs, t
fn combine_native(g: &OriginalVerifyGeometry, [parts, w, shared, bo]: [u64; 4], tokens: usize) -> Result<Launch> {
let (n_embd, k) = (g.n, g.k);
let args = vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I64(n_embd as i64), A::I32(k as i32)];
Launch::new(&COMBINE, E_COMBINE, [n_embd.div_ceil(256) as u32, tokens as u32, 1], [256, 1, 1], 0, args)
Launch::new(
&COMBINE,
E_COMBINE,
LaunchExtent::new([n_embd.div_ceil(256) as u32, tokens as u32, 1], [256, 1, 1], 0),
args,
)
}
/// The legacy double-precision `moe_combine` of one row.
fn combine_legacy(g: &OriginalVerifyGeometry, [parts, w, shared, bo]: [u64; 4]) -> Result<Launch> {
let (n_embd, k) = (g.n, g.k);
let args = vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I32(n_embd as i32), A::I32(k as i32), A::I32(1)];
Launch::new(&SHARED, E_MOE_COMBINE, [n_embd.div_ceil(128) as u32, 1, 1], [128, 1, 1], 0, args)
Launch::new(&SHARED, E_MOE_COMBINE, LaunchExtent::new([n_embd.div_ceil(128) as u32, 1, 1], [128, 1, 1], 0), args)
}
/// ONE `native_moe_combine_multi` launch over all rows of the group.
@@ -9,9 +9,7 @@ pub(super) fn plan_f32_to_bf16(x: u64, y: u64, count: usize) -> Result<Launch> {
Launch::new(
&ELEMENT,
E_TO_BF16,
[count.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
LaunchExtent::new([count.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0),
vec![A::P(x), A::P(y), A::I64(count as i64)],
)
}
@@ -22,7 +20,27 @@ pub(super) fn plan_f32_to_bf16(x: u64, y: u64, count: usize) -> Result<Launch> {
/// `route<<<tokens, (32, 8)>>>(logits, ids, weights)` (`native_router_top10(_multi)`).
pub(super) fn plan_route(logits: u64, ids: u64, weights: u64, tokens: usize) -> Result<Launch> {
Launch::new(&ROUTER, E_ROUTE, [tokens as u32, 1, 1], [32, 8, 1], 0, vec![A::P(logits), A::P(ids), A::P(weights)])
Launch::new(
&ROUTER,
E_ROUTE,
LaunchExtent::new([tokens as u32, 1, 1], [32, 8, 1], 0),
vec![A::P(logits), A::P(ids), A::P(weights)],
)
}
/// The rows of a group and whether the recorder plans them in the batched decode form (`dec_batch`; for the router
/// also `n > 1` and the native router).
#[derive(Clone, Copy, Debug)]
pub(crate) struct BatchedRows {
pub rows: Rows,
pub batched: bool,
}
impl BatchedRows {
/// The `rows` of a group planned batched or per row.
#[inline]
pub(crate) const fn new(rows: Rows, batched: bool) -> Self {
Self { rows, batched }
}
}
/// The router of a group: Router logits and top-10 for rows `[tb, te)`.
@@ -37,9 +55,9 @@ pub(crate) fn plan_router(
g: &OriginalVerifyGeometry,
knobs: &MoeKnobs,
router: u64,
rows: Rows,
batched: bool,
group: BatchedRows,
) -> Result<Vec<Launch>> {
let BatchedRows { rows, batched } = group;
let n = check_rows(g, rows)?;
let (n_embd, ne, k, tb) = (g.n, g.experts, g.k, rows.begin);
if ne != 512 || k != 10 {
@@ -98,7 +116,12 @@ fn router_batched(
let (n_embd, ne) = (spans.n_embd, spans.ne);
let (x, y) = (spans.mixed(tb, n)?, spans.logits(tb, n)?);
Ok(vec![
plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, n)?,
plan_bf16_gemv(
StridedRows::new(x, n_embd),
router,
StridedRows::new(y, ne),
Bf16GemvExtents::new(n_embd, ne, n),
)?,
plan_route(y, spans.ids(tb, n)?, spans.weights(tb, n)?, n)?,
])
}
@@ -107,7 +130,12 @@ fn router_batched(
fn router_row(spans: &RouterSpans<'_>, knobs: &MoeKnobs, router: u64, t: usize, out: &mut Vec<Launch>) -> Result<()> {
let (n_embd, ne) = (spans.n_embd, spans.ne);
let (x, y) = (spans.mixed(t, 1)?, spans.logits(t, 1)?);
out.push(plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, 1)?);
out.push(plan_bf16_gemv(
StridedRows::new(x, n_embd),
router,
StridedRows::new(y, ne),
Bf16GemvExtents::new(n_embd, ne, 1),
)?);
if knobs.native_router {
out.push(plan_route(y, spans.ids(t, 1)?, spans.weights(t, 1)?, 1)?);
} else {
@@ -125,7 +153,7 @@ fn router_top10_generic(spans: &RouterSpans<'_>, y: u64, t: usize) -> Result<Lau
let threads = ((ne.min(512) + 31) & !31) as u32;
let (ids, weights) = (spans.ids(t, 1)?, spans.weights(t, 1)?);
let args = vec![A::P(y), A::I32(1), A::I32(ne as i32), A::I32(k as i32), A::P(ids), A::P(weights)];
Launch::new(&ROUTER_LEGACY, E_ROUTER_TOP10, [1, 1, 1], [threads, 1, 1], smem as u32, args)
Launch::new(&ROUTER_LEGACY, E_ROUTER_TOP10, LaunchExtent::new([1, 1, 1], [threads, 1, 1], smem as u32), args)
}
// ---------------------------------------------------------------------------------------------
@@ -140,9 +168,9 @@ pub(crate) fn plan_shared_expert(
g: &OriginalVerifyGeometry,
knobs: &MoeKnobs,
w: &MoeLayerAddrs,
rows: Rows,
dec_batch: bool,
group: BatchedRows,
) -> Result<Vec<Launch>> {
let BatchedRows { rows, batched: dec_batch } = group;
let n = check_rows(g, rows)?;
let (n_embd, n_ff, tb) = (g.n, g.ff, rows.begin);
let xm = f32s(arena, "mixed", tb * n_embd, n * n_embd)?;
@@ -201,8 +229,8 @@ impl SharedExpert<'_> {
let gscalar = f32s(arena, "sh_g", tb, n)?;
let shared = f32s(arena, "shared", tb * n_embd, n * n_embd)?;
out.push(plan_quantize_q8_1(self.xm, xq, n_embd, n)?);
out.push(plan_mmvq(&w.gate_shexp, xq, gate, n_embd, n_ff, n, dispatch)?);
out.push(plan_mmvq(&w.up_shexp, xq, up, n_embd, n_ff, n, dispatch)?);
out.push(plan_mmvq(&w.gate_shexp, xq, gate, MmvqExtents::new(n_embd, n_ff, n), dispatch)?);
out.push(plan_mmvq(&w.up_shexp, xq, up, MmvqExtents::new(n_embd, n_ff, n), dispatch)?);
self.swiglu_down([gate, up, xq, shared], out)?;
Ok((gscalar, shared))
}
@@ -212,9 +240,14 @@ impl SharedExpert<'_> {
let (n, n_embd, n_ff) = (self.n, self.n_embd, self.n_ff);
let count = n_ff * n;
let args = vec![A::P(gate), A::P(up), A::P(gate), A::I32(count as i32)];
out.push(Launch::new(&SHARED, E_NATIVE_SWIGLU, [count.div_ceil(128) as u32, 1, 1], [128, 1, 1], 0, args)?);
out.push(Launch::new(
&SHARED,
E_NATIVE_SWIGLU,
LaunchExtent::new([count.div_ceil(128) as u32, 1, 1], [128, 1, 1], 0),
args,
)?);
out.push(plan_quantize_q8_1(gate, xq, n_ff, n)?);
out.push(plan_mmvq(&self.w.down_shexp, xq, shared, n_ff, n_embd, n, self.knobs.dispatch)?);
out.push(plan_mmvq(&self.w.down_shexp, xq, shared, MmvqExtents::new(n_ff, n_embd, n), self.knobs.dispatch)?);
Ok(())
}
@@ -222,9 +255,19 @@ impl SharedExpert<'_> {
let (n, n_embd) = (self.n, self.n_embd);
if self.knobs.native_bf16_extra && self.dec_batch && n > 1 {
// one GEMV for all rows (outputs identical), one sigmoid launch with thread t = token t
out.push(plan_bf16_gemv(self.xm, n_embd, self.w.gate_inp_shexp, gscalar, 1, n_embd, 1, n)?);
out.push(plan_bf16_gemv(
StridedRows::new(self.xm, n_embd),
self.w.gate_inp_shexp,
StridedRows::new(gscalar, 1),
Bf16GemvExtents::new(n_embd, 1, n),
)?);
if !self.tiny {
out.push(Launch::new(&SHARED, E_SIGMOID_MULTI, [1, 1, 1], [n as u32, 1, 1], 0, vec![A::P(gscalar)])?);
out.push(Launch::new(
&SHARED,
E_SIGMOID_MULTI,
LaunchExtent::new([1, 1, 1], [n as u32, 1, 1], 0),
vec![A::P(gscalar)],
)?);
}
return Ok(());
}
@@ -239,13 +282,18 @@ impl SharedExpert<'_> {
let g_t = f32s(self.arena, "sh_g", row, 1)?;
if self.knobs.native_bf16_extra {
let x_t = f32s(self.arena, "mixed", row * n_embd, n_embd)?;
out.push(plan_bf16_gemv(x_t, n_embd, self.w.gate_inp_shexp, g_t, 1, n_embd, 1, 1)?);
out.push(plan_bf16_gemv(
StridedRows::new(x_t, n_embd),
self.w.gate_inp_shexp,
StridedRows::new(g_t, 1),
Bf16GemvExtents::new(n_embd, 1, 1),
)?);
if !self.tiny {
out.push(Launch::new(&SHARED, E_SIGMOID, [1, 1, 1], [1, 1, 1], 0, vec![A::P(g_t)])?);
out.push(Launch::new(&SHARED, E_SIGMOID, LaunchExtent::new([1, 1, 1], [1, 1, 1], 0), vec![A::P(g_t)])?);
}
} else {
let args = vec![A::P(self.bf16(row, 1)?), A::P(self.w.gate_inp_shexp), A::P(g_t), A::I32(n_embd as i32)];
out.push(Launch::new(&SHARED, E_SCALAR_GATE, [1, 1, 1], [256, 1, 1], 0, args)?);
out.push(Launch::new(&SHARED, E_SCALAR_GATE, LaunchExtent::new([1, 1, 1], [256, 1, 1], 0), args)?);
}
Ok(())
}
@@ -257,9 +305,9 @@ impl SharedExpert<'_> {
let args = vec![A::P(shared), A::P(gscalar), A::I32(self.n_embd as i32)];
if self.tiny && self.knobs.native_bf16_extra {
let (chain, entry) = (&super::super::chain::CHAIN, super::super::chain::E_SCALE_SIGMOID);
out.push(Launch::new(chain, entry, grid, [128, 1, 1], 0, args)?);
out.push(Launch::new(chain, entry, LaunchExtent::new(grid, [128, 1, 1], 0), args)?);
} else {
out.push(Launch::new(&SHARED, E_SCALE_ROWS, grid, [128, 1, 1], 0, args)?);
out.push(Launch::new(&SHARED, E_SCALE_ROWS, LaunchExtent::new(grid, [128, 1, 1], 0), args)?);
}
Ok(())
}
@@ -292,9 +340,7 @@ pub(crate) fn plan_quantize_expert_input(
Ok(vec![Launch::new(
&HEAD_IQ_EXPERT,
E_QUANTIZE_Q8_1,
[total.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
LaunchExtent::new([total.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0),
vec![A::P(x), A::P(y), A::I64(total as i64)],
)?])
}
@@ -99,7 +99,7 @@ fn asset_list_names_every_module_once() {
fn batched_router_is_one_gemv_and_one_top10_over_the_groups_rows() {
let m = map();
let g = test_geometry();
let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(3, 8, 1), true).unwrap();
let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, BatchedRows::new(rows(3, 8, 1), true)).unwrap();
assert_eq!(l.len(), 2);
// bf16_gemv_fp32_mmvf_multi(mixed + 3*N, N, w, logits + 3*NE, NE, N, NE, 5): block 256, 5 rows -> 8-col kernel
assert!(l[0].entry.contains("ILi256ELi8EE"));
@@ -130,7 +130,7 @@ fn batched_router_uses_the_four_column_kernel_up_to_four_rows() {
let m = map();
let g = test_geometry();
for n in 2..=4usize {
let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(0, n, 0), true).unwrap();
let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, BatchedRows::new(rows(0, n, 0), true)).unwrap();
assert!(l[0].entry.contains("ILi256ELi4EE"), "{n}");
assert_eq!(l[1].grid, [n as u32, 1, 1]);
}
@@ -140,7 +140,7 @@ fn batched_router_uses_the_four_column_kernel_up_to_four_rows() {
fn per_row_router_follows_moe_route_for_every_row() {
let m = map();
let g = test_geometry();
let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(1, 3, 0), false).unwrap();
let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, BatchedRows::new(rows(1, 3, 0), false)).unwrap();
// row 1: bf16_gemv_fp32_mmvf(mixed + N, w, logits + NE, N, NE) + native_router_top10; then row 2
assert_eq!(entries(&l), ["mtp_full_mmvf256", "mtp_full_route", "mtp_full_mmvf256", "mtp_full_route"]);
assert_eq!(l[0].grid, [512, 1, 1]);
@@ -162,7 +162,7 @@ fn generic_router_is_the_original_router_top10_launch() {
let g = test_geometry();
let mut knobs = MoeKnobs::mode17();
knobs.native_router = false;
let l = plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 1, 0), false).unwrap();
let l = plan_router(&m, &g, &knobs, 0x9000_0000, BatchedRows::new(rows(0, 1, 0), false)).unwrap();
assert_eq!(l.len(), 2);
// threads = 512, smem = 512 (taken) + 512*8 (doubles) + 512*4 (floats) = 6656
assert_eq!((l[1].grid, l[1].block, l[1].shared), ([1, 1, 1], [512, 1, 1], 6656));
@@ -179,7 +179,10 @@ fn generic_router_is_the_original_router_top10_launch() {
);
assert_abi(&l);
// the batched launch needs the native router
assert_eq!(plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(
plan_router(&m, &g, &knobs, 0x9000_0000, BatchedRows::new(rows(0, 2, 0), true)).unwrap_err(),
Error::InvalidQwenShape
);
}
#[test]
@@ -188,7 +191,7 @@ fn router_fails_closed_precisely_without_native_bf16_and_on_bad_shapes() {
let g = test_geometry();
let mut knobs = MoeKnobs::mode17();
knobs.native_bf16 = false;
let e = plan_router(&m, &g, &knobs, 1, rows(0, 1, 0), false).unwrap_err();
let e = plan_router(&m, &g, &knobs, 1, BatchedRows::new(rows(0, 1, 0), false)).unwrap_err();
match e {
Error::InvalidDriverValue(s) => {
assert!(s.starts_with("Original verifier producer unavailable: router: "), "{s}")
@@ -196,13 +199,13 @@ fn router_fails_closed_precisely_without_native_bf16_and_on_bad_shapes() {
other => panic!("{other:?}"),
}
// the batched path never needs the bf16 conversion
assert!(plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).is_ok());
assert!(plan_router(&m, &g, &knobs, 0x9000_0000, BatchedRows::new(rows(0, 2, 0), true)).is_ok());
// batched with one row, empty rows, rows past the window, group C
let mode = MoeKnobs::mode17();
assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 0), true).is_err());
assert!(plan_router(&m, &g, &mode, 1, rows(2, 2, 0), false).is_err());
assert!(plan_router(&m, &g, &mode, 1, rows(0, 9, 0), false).is_err());
assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 2), false).is_err());
assert!(plan_router(&m, &g, &mode, 1, BatchedRows::new(rows(0, 1, 0), true)).is_err());
assert!(plan_router(&m, &g, &mode, 1, BatchedRows::new(rows(2, 2, 0), false)).is_err());
assert!(plan_router(&m, &g, &mode, 1, BatchedRows::new(rows(0, 9, 0), false)).is_err());
assert!(plan_router(&m, &g, &mode, 1, BatchedRows::new(rows(0, 1, 2), false)).is_err());
}
// ---- shared expert -----------------------------------------------------------------------
@@ -262,7 +265,7 @@ fn assert_shared_expert_down_and_gate(m: &LayoutMap, l: &[Launch]) {
fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() {
let m = map();
let g = test_geometry();
let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(2, 6, 1), true).unwrap();
let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), BatchedRows::new(rows(2, 6, 1), true)).unwrap();
// f32_to_bf16_bulk(4 rows), quantize x, MMVQ gate, MMVQ up, swiglu, quantize h, MMVQ down,
// gate GEMV (multi), sigmoid (multi), scale rows
assert_eq!(l.len(), 10);
@@ -275,7 +278,7 @@ fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() {
fn single_row_shared_expert_uses_the_per_token_gate_and_single_row_projections() {
let m = map();
let g = test_geometry();
let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, 1, 0), true).unwrap();
let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), BatchedRows::new(rows(0, 1, 0), true)).unwrap();
// bulk, quantize, gate, up, swiglu, quantize, down, [mmvf + sigmoid], scale
assert_eq!(l.len(), 10);
assert_eq!((l[2].entry, l[6].entry), ("head_n8_s0", "head_n8_s1"));
@@ -291,7 +294,8 @@ fn single_row_shared_expert_uses_the_per_token_gate_and_single_row_projections()
fn shared_expert_without_dec_batch_converts_and_gates_one_row_at_a_time() {
let m = map();
let g = test_geometry();
let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(1, 3, 0), false).unwrap();
let l =
plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), BatchedRows::new(rows(1, 3, 0), false)).unwrap();
// 2 conversions, the six projection / activation launches, 2 x (mmvf + sigmoid), scale
assert_eq!(l.len(), 2 + 6 + 4 + 1);
assert_eq!(
@@ -5,13 +5,22 @@
#[allow(unused_imports)]
use super::*;
/// The VRAM tier's group of `rows` in `layer`.
fn vram_site(layer: usize, rows: Rows) -> ExpertGroupSite {
ExpertGroupSite { layer, rows, tier: ExpertTier::Vram }
}
/// The PCIe tier's group of `rows` in `layer`.
fn pcie_site(layer: usize, rows: Rows) -> ExpertGroupSite {
ExpertGroupSite { layer, rows, tier: ExpertTier::Pcie }
}
#[test]
fn shared_gate_without_native_bf16_extra_reads_the_bf16_activation() {
let m = map();
let g = test_geometry();
let mut knobs = MoeKnobs::mode17();
knobs.native_bf16_extra = false;
let l = plan_shared_expert(&m, &g, &knobs, &weights(), rows(0, 2, 0), true).unwrap();
let l = plan_shared_expert(&m, &g, &knobs, &weights(), BatchedRows::new(rows(0, 2, 0), true)).unwrap();
// one scalar_gate_kernel<<<1, 256>>>(x_bf16 + t*N, w, g + t, N) per token, no GEMV / sigmoid
let gates: Vec<&Launch> = l.iter().filter(|x| x.entry.ends_with("scalar_gate_kernelEPKtS3_Pfi")).collect();
assert_eq!(gates.len(), 2);
@@ -29,7 +38,8 @@ fn shared_expert_covers_every_window_size() {
let m = map();
let g = test_geometry();
for n in 1..=8usize {
let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, n, 0), true).unwrap();
let l =
plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), BatchedRows::new(rows(0, n, 0), true)).unwrap();
assert_eq!(l.last().unwrap().grid, [20, n as u32, 1]);
assert_eq!(l[4].grid, [(640 * n).div_ceil(128) as u32, 1, 1]);
assert_abi(&l);
@@ -167,7 +177,7 @@ fn assert_vram_swiglu_quantize_down(m: &LayoutMap, l: &[Launch]) {
fn vram_tier_reads_the_first_plan_arrays() {
let m = map();
let g = test_geometry();
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 5, rows(0, 3, 0), ExpertTier::Vram);
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), vram_site(5, rows(0, 3, 0)));
// the plan itself is pure data
let l = l.unwrap();
assert_eq!(entries(&l).len(), 4);
@@ -181,7 +191,7 @@ fn pcie_tier_uses_the_second_pointer_start_and_count_of_the_group() {
let m = map();
let g = test_geometry();
// group B of a 5-row window: rows 3..5, plan block of group 1 (664 words further)
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(3, 5, 1), ExpertTier::Pcie).unwrap();
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), pcie_site(0, rows(3, 5, 1))).unwrap();
let plan = |word: usize| at(&m, "plan", (664 + word) * 4);
assert_eq!(
l[0].args[..5],
@@ -204,7 +214,7 @@ fn expert_groups_pick_the_kernels_of_the_layers_formats() {
fmts[9] = (13, 7);
let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap();
let pick = |layer: usize| {
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, layer, rows(0, 1, 0), ExpertTier::Vram).unwrap();
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, vram_site(layer, rows(0, 1, 0))).unwrap();
(l[0].entry, l[3].entry)
};
assert_eq!(pick(0), ("window_moe_gu_16", "window_moe_down_20"));
@@ -213,7 +223,7 @@ fn expert_groups_pick_the_kernels_of_the_layers_formats() {
assert_eq!(pick(9), ("window_moe_gu_13", "window_moe_down_7"));
// every launch names an entry of its asset
for t in 0..8usize {
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 7, rows(0, t + 1, 0), ExpertTier::Pcie).unwrap();
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, pcie_site(7, rows(0, t + 1, 0))).unwrap();
assert_eq!(l[0].grid[1], ((t + 1) * 10) as u32);
assert_eq!(l[3].grid[1], ((t + 1) * 10) as u32);
}
@@ -250,12 +260,9 @@ fn assert_gu_swiglu_layer_fallbacks(
on: &MoeKnobs,
f: &OriginalVerifyExpertFormats,
) {
assert_eq!(entries(&plan_expert_groups(m, g, on, f, vram_site(7, rows(0, 3, 0))).unwrap())[0], "window_moe_gu_12");
assert_eq!(
entries(&plan_expert_groups(m, g, on, f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0],
"window_moe_gu_12"
);
assert_eq!(
entries(&plan_expert_groups(m, g, on, f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0],
entries(&plan_expert_groups(m, g, on, f, pcie_site(8, rows(0, 3, 0))).unwrap())[0],
"sm120_moe_gu_swiglu_22"
);
}
@@ -270,8 +277,8 @@ fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_do
let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap();
let mut on = MoeKnobs::mode17();
on.gu_swiglu = true;
let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap();
let fused = plan_expert_groups(&m, &g, &on, &f, 0, rows(0, 3, 0), ExpertTier::Vram).unwrap();
let off = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, vram_site(0, rows(0, 3, 0))).unwrap();
let fused = plan_expert_groups(&m, &g, &on, &f, vram_site(0, rows(0, 3, 0))).unwrap();
assert_eq!(entries(&fused), ["sm120_moe_gu_swiglu_16", "window_moe_down_20"]);
assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0));
assert_gu_swiglu_arguments(&fused, &off);
@@ -286,29 +293,30 @@ fn expert_groups_refuse_s2_and_a_mismatched_geometry() {
let mut s2 = MoeKnobs::mode17();
s2.native_experts = false;
assert!(matches!(
plan_expert_groups(&m, &g, &s2, &formats(), 0, rows(0, 1, 0), ExpertTier::Vram),
plan_expert_groups(&m, &g, &s2, &formats(), vram_site(0, rows(0, 1, 0))),
Err(Error::InvalidDriverValue(s)) if s.contains("expert_groups")
));
let other = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 1280).unwrap();
assert_eq!(
plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &other, 0, rows(0, 1, 0), ExpertTier::Vram).unwrap_err(),
plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &other, vram_site(0, rows(0, 1, 0))).unwrap_err(),
Error::InvalidQwenShape
);
assert!(plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 48, rows(0, 1, 0), ExpertTier::Vram).is_err());
assert!(plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), vram_site(48, rows(0, 1, 0))).is_err());
}
#[test]
fn expert_launches_load_when_sealed_and_are_refused_on_a_corrupted_pin() {
let m = map();
let g = test_geometry();
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(0, 1, 0), ExpertTier::Vram).unwrap();
let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), vram_site(0, rows(0, 1, 0))).unwrap();
assert!(std::ptr::eq(l[0].asset, &EXPERTS));
assert!(l[0].asset.sealed().is_ok());
assert!(l[1].asset.sealed().is_ok());
// The same launch against a one-byte-corrupted copy of the asset (synthetic; the real PTX is untouched)
// is refused with the asset's refusal text, exactly as the unsealed placeholder was.
let bad = EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(EXPERTS.ptx), EXPERTS.sha);
let launch = Launch::new(bad, l[0].entry, l[0].grid, l[0].block, l[0].shared, l[0].args.clone()).unwrap();
let launch =
Launch::new(bad, l[0].entry, LaunchExtent::new(l[0].grid, l[0].block, l[0].shared), l[0].args.clone()).unwrap();
assert_eq!(launch.asset.sealed().unwrap_err(), Error::InvalidDriverValue(EXPERTS.unsealed));
assert!(launch.command().is_ok(), "the plan itself is pure data and unaffected");
}
@@ -23,7 +23,7 @@
//! lists them). A partially bound window can therefore never be recorded or replayed.
use super::chain;
use super::gr::{self, GrConfig, OriginalVerifyGrBinding};
use super::kernels::{A, AssetSpec, Launch};
use super::kernels::{A, AssetSpec, Launch, LaunchExtent};
use super::moe::{self, MoeLayerAddrs, OriginalVerifyExpertFormats, OriginalVerifyMoeBinding};
use super::planner::{Planner, WindowWeights};
use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs};
@@ -224,7 +224,12 @@ impl OriginalVerifyWindowOps<'_, '_, '_, '_> {
let flag = self.mapped_flag(11)?;
let (device, mapped) = self.plan_copy_addresses(rows)?;
let args = vec![A::P(flag), A::I32(ring as i32), A::P(device), A::P(mapped), A::I32(words as i32)];
self.launch(vec![Launch::new(&chain::CHAIN, chain::E_WAIT_COPY_I32, [1, 1, 1], [704, 1, 1], 0, args)?])
self.launch(vec![Launch::new(
&chain::CHAIN,
chain::E_WAIT_COPY_I32,
LaunchExtent::new([1, 1, 1], [704, 1, 1], 0),
args,
)?])
}
/// The CPU-hit rows copied back with the plan's hit list, in the chain glue launch.
@@ -235,7 +240,12 @@ impl OriginalVerifyWindowOps<'_, '_, '_, '_> {
let count = self.plan_word(rows.group, layout.counts + 1)?;
let args = vec![A::P(parts), A::P(mapped), A::I64((g.n / 4) as i64), A::P(hit_rows), A::P(count)];
let grid = [(rows.len() * g.k) as u32, 1, 1];
self.launch(vec![Launch::new(&chain::CHAIN, chain::E_COPY_ROWS, grid, [128, 1, 1], 0, args)?])
self.launch(vec![Launch::new(
&chain::CHAIN,
chain::E_COPY_ROWS,
LaunchExtent::new(grid, [128, 1, 1], 0),
args,
)?])
}
/// The CPU-hit rows copied back with the plan's hit list, as a plain kernel command.
@@ -267,9 +277,7 @@ fn pcie_fetch_launch(source: u64, count: u64, stage: u64, [gate, up, down]: [usi
Launch::new(
spec,
entry,
grid,
block,
0,
LaunchExtent::new(grid, block, 0),
vec![A::P(source), A::P(count), A::P(stage), words(gate), words(up), words(down)],
)
}
@@ -72,6 +72,10 @@ impl<'p> Planner<'p> {
dispatch: self.policy.dispatch,
}
}
/// The arena, geometry and GR configuration the GR planners read.
fn gr_window(&self) -> gr::GrWindow<'_> {
gr::GrWindow { arena: self.arena, geo: &self.geo, cfg: &self.gr }
}
fn qsa_window(&self) -> Result<QsaWindow<'p>> {
QsaWindow::new(self.arena, self.geo, self.policy.qsa, self.weights.rope()?)
}
@@ -79,7 +83,7 @@ impl<'p> Planner<'p> {
// ---- GR
pub(crate) fn hc_read(&self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result<Vec<Launch>> {
let w = self.weights.hc(layer, half)?;
Ok(gr::plan_hc_read(self.arena, &self.geo, &w, &self.gr, half, apply, rows)?.launches())
Ok(gr::plan_hc_read(self.gr_window(), &w, half, apply, rows)?.launches())
}
pub(crate) fn final_write(&self, rows: Rows) -> Result<Vec<Launch>> {
gr::plan_final_write(self.arena, &self.geo, &self.gr, rows)
@@ -87,14 +91,14 @@ impl<'p> Planner<'p> {
/// The per-token `lm_head_mix` launches writing the head rows' `mixed` buffer at `mixed_out_base`.
pub(crate) fn head_mix(&self, mixed_out_base: u64, rows: usize) -> Result<Vec<Launch>> {
let w = self.weights.head()?;
gr::plan_head_mix(self.arena, &self.geo, &w, &self.gr, mixed_out_base, rows)
gr::plan_head_mix(self.gr_window(), &w, mixed_out_base, rows)
}
/// One entry per window row: that row's launches, to be followed by the PLE history snapshot copy of the row.
pub(crate) fn ple_layer1(&self, rows: Rows) -> Result<Vec<(usize, Vec<Launch>)>> {
let ple = self.weights.ple()?.ok_or(Error::InvalidDriverValue(
"Original verifier producer unbound: ple_layer1: the model has a PLE block but no PLE weights are attached",
))?;
gr::plan_ple_layer1(self.arena, &self.geo, &self.gr, &self.ple_config(), &ple, rows)
gr::plan_ple_layer1(self.gr_window(), &self.ple_config(), &ple, rows)
}
// ---- projections
@@ -112,7 +116,13 @@ impl<'p> Planner<'p> {
self.weights.qsa_projections(q)?.get(projection)?
}
};
Ok(vec![proj::plan_window_mmvq(self.arena, &self.geo, layer, projection, &weight, rows, self.policy.dispatch)?])
Ok(vec![proj::plan_window_mmvq(
self.arena,
&self.geo,
proj::WindowProjectionSite { layer, projection, rows },
&weight,
self.policy.dispatch,
)?])
}
// ---- QSA (all take the QSA layer index)
@@ -147,11 +157,11 @@ impl<'p> Planner<'p> {
// ---- FFN
pub(crate) fn router(&self, layer: usize, rows: Rows, batched: bool) -> Result<Vec<Launch>> {
let w = self.weights.moe(layer)?;
moe::plan_router(self.arena, &self.geo, &self.moe_knobs(), w.router, rows, batched)
moe::plan_router(self.arena, &self.geo, &self.moe_knobs(), w.router, moe::BatchedRows::new(rows, batched))
}
pub(crate) fn shared_expert(&self, layer: usize, rows: Rows, dec_batch: bool) -> Result<Vec<Launch>> {
let w = self.weights.moe(layer)?;
moe::plan_shared_expert(self.arena, &self.geo, &self.moe_knobs(), &w, rows, dec_batch)
moe::plan_shared_expert(self.arena, &self.geo, &self.moe_knobs(), &w, moe::BatchedRows::new(rows, dec_batch))
}
pub(crate) fn quantize_expert_input(&self, rows: Rows) -> Result<Vec<Launch>> {
moe::plan_quantize_expert_input(self.arena, &self.geo, &self.moe_knobs(), rows)
@@ -162,9 +172,7 @@ impl<'p> Planner<'p> {
&self.geo,
&self.moe_knobs(),
self.weights.expert_formats()?,
layer,
rows,
tier,
moe::ExpertGroupSite { layer, rows, tier },
)
}
pub(crate) fn hit_add(&self, rows: Rows) -> Result<Vec<Launch>> {
@@ -3,7 +3,7 @@
use super::super::kernels::{LayoutMap, test_geometry};
use super::super::moe::MoeLayerAddrs;
use super::super::proj::NativeWeight;
use super::super::qsa::{OriginalVerifyQsaKvBinding, QsaWeightAddrs};
use super::super::qsa::{OriginalVerifyQsaKvBinding, QsaWeightAddrs, RopeCorrectionRange};
use super::super::window_plan::WINDOW_LAYERS;
use super::super::window_record::{WindowOps, record_window};
use super::*;
@@ -92,7 +92,7 @@ impl WindowWeights for Fake {
Ok(QsaLayerAddrs { weights: fake_qsa_weights(b), kv: fake_qsa_kv(b) })
}
fn rope(&self) -> Result<QsaRope> {
QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0)
QsaRope::new(0.7498942, 1.0, RopeCorrectionRange { low: 0.0, high: 0.0 }, 0.0, 1.0)
}
fn moe(&self, layer: usize) -> Result<MoeLayerAddrs> {
let b = 0x60_0000_0000u64 + layer as u64 * 0x1_0000_0000;
@@ -294,7 +294,11 @@ fn geometry_and_fake(ple: bool) -> (LayoutMap, Fake) {
(m, Fake { formats, ple })
}
fn sm120() -> GrConfig {
GrConfig::from_device(gr::GrVariant::Staged, true, 12, 0, 99 * 1024, 48 * 1024)
GrConfig::from_device(
gr::GrVariant::Staged,
true,
gr::GrDeviceAttributes { cc_major: 12, cc_minor: 0, optin: 99 * 1024, per_block: 48 * 1024 },
)
}
fn record(t: usize, groups: usize, ple: bool) -> Vec<String> {
let (m, fake) = geometry_and_fake(ple);
@@ -11,7 +11,7 @@
//! * bf16 gemv: `mtp_full_mmvf{B}` for one row, the `_multi_kernel<B, 4|8>` instantiation
//! for 2..=8 rows (the weight row read once, every row its single-row order).
use super::OriginalVerifyGeometry;
use super::kernels::{A, ArenaMap, AssetSpec, Launch};
use super::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent};
use super::window_plan::{gdn_index, qsa_index};
use super::window_record::{Projection, QuantSource, Rows};
use crate::native_head::native_head_row_bytes;
@@ -61,6 +61,8 @@ use q8_1_row_bytes_fn::quant_source_span;
pub(crate) use q8_1_row_bytes_fn::quant_source_width;
#[allow(unused_imports)]
use q8_1_row_bytes_fn::single_entry;
#[allow(unused_imports)]
pub(crate) use q8_1_row_bytes_fn::{Bf16GemvExtents, MmvqExtents, StridedRows, WindowProjectionSite};
#[path = "original_verify_window_proj/admit_matrix_fn.rs"]
mod admit_matrix_fn;
#[allow(unused_imports)]
@@ -31,24 +31,73 @@ pub(crate) fn plan_quantize_q8_1(x: u64, xq: u64, n_in: usize, rows: usize) -> R
Launch::new(
&HEAD_NATIVE,
"head_quant",
[total.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
LaunchExtent::new([total.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0),
vec![A::P(x), A::P(xq), A::I32(count)],
)
}
/// A device row-major operand: the address of its first row and the distance between consecutive rows, in elements.
#[derive(Clone, Copy, Debug)]
pub(crate) struct StridedRows {
pub address: u64,
pub stride: usize,
}
impl StridedRows {
/// The operand at `address` whose rows are `stride` elements apart.
#[inline]
pub(crate) const fn new(address: u64, stride: usize) -> Self {
Self { address, stride }
}
}
/// The extents of one BF16 GEMV: input width, output width and the number of token rows (1..=8).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Bf16GemvExtents {
pub n_in: usize,
pub n_out: usize,
pub n_tok: usize,
}
impl Bf16GemvExtents {
/// A GEMV of `n_tok` rows from `n_in` inputs to `n_out` outputs.
#[inline]
pub(crate) const fn new(n_in: usize, n_out: usize, n_tok: usize) -> Self {
Self { n_in, n_out, n_tok }
}
}
/// The extents of one native MMVQ: input width, output width and the number of activation rows (1..=8).
#[derive(Clone, Copy, Debug)]
pub(crate) struct MmvqExtents {
pub n_in: usize,
pub n_out: usize,
pub rows: usize,
}
impl MmvqExtents {
/// An MMVQ of `rows` activation rows from `n_in` inputs to `n_out` outputs.
#[inline]
pub(crate) const fn new(n_in: usize, n_out: usize, rows: usize) -> Self {
Self { n_in, n_out, rows }
}
}
/// The window projection to plan: which projection of which layer, over which rows.
#[derive(Clone, Copy, Debug)]
pub(crate) struct WindowProjectionSite {
pub layer: usize,
pub projection: Projection,
pub rows: Rows,
}
/// `native_mmvq(type, w, xq, y, n_in, n_out, rows)`. `y` rows are `n_out` floats apart, `xq` rows
/// `q8_1_row_bytes(n_in)` apart (the layout `plan_quantize_q8_1` writes).
pub(crate) fn plan_mmvq(
w: &NativeWeight,
xq: u64,
y: u64,
n_in: usize,
n_out: usize,
rows: usize,
extents: MmvqExtents,
dispatch: NativeHeadDispatch,
) -> Result<Launch> {
let MmvqExtents { n_in, n_out, rows } = extents;
let (n_in32, n_out32) = mmvq_extents(n_in, n_out, rows)?;
let (entry, grid, block, iq) = head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?;
let mut args = vec![A::P(w.data)];
@@ -59,7 +108,7 @@ pub(crate) fn plan_mmvq(
if iq {
args.push(A::I32(rows as i32));
}
Launch::new(mmvq_asset(w.ty), entry, grid, block, 0, args)
Launch::new(mmvq_asset(w.ty), entry, LaunchExtent::new(grid, block, 0), args)
}
/// The shape check of `plan_mmvq` and the `i32` kernel extents `(n_in, n_out)`.
@@ -100,17 +149,9 @@ fn bf16_gemv_shape_ok(x: u64, ldx: usize, (n_in, n_out): (usize, usize), n_tok:
/// `bf16_gemv_fp32_mmvf_multi(x, ldx, w, y, ldy, n_in, n_out, n_tok)` (1..=8 rows; one row with
/// `ldy >= n_out` is `bf16_gemv_fp32_mmvf`). Strides are in elements.
#[allow(clippy::too_many_arguments)]
pub(crate) fn plan_bf16_gemv(
x: u64,
ldx: usize,
w: u64,
y: u64,
ldy: usize,
n_in: usize,
n_out: usize,
n_tok: usize,
) -> Result<Launch> {
pub(crate) fn plan_bf16_gemv(x: StridedRows, w: u64, y: StridedRows, extents: Bf16GemvExtents) -> Result<Launch> {
let (StridedRows { address: x, stride: ldx }, StridedRows { address: y, stride: ldy }) = (x, y);
let Bf16GemvExtents { n_in, n_out, n_tok } = extents;
if !bf16_gemv_shape_ok(x, ldx, (n_in, n_out), n_tok) {
return Err(Error::InvalidQwenShape);
}
@@ -119,12 +160,12 @@ pub(crate) fn plan_bf16_gemv(
let block = mmvf_block_size(n_in);
if n_tok == 1 && ldy >= n_out {
let args = vec![A::P(x), A::P(w), A::P(y), A::I32(n_in32)];
return Launch::new(&BF16, single_entry(block)?, [grid, 1, 1], [block, 1, 1], 0, args);
return Launch::new(&BF16, single_entry(block)?, LaunchExtent::new([grid, 1, 1], [block, 1, 1], 0), args);
}
let nt = if n_tok <= 4 { 4 } else { 8 };
let (ldx, ldy, n_tok) = (A::I64(ldx as i64), A::I64(ldy as i64), A::I32(n_tok as i32));
let args = vec![A::P(x), ldx, A::P(w), A::P(y), ldy, A::I32(n_in32), n_tok];
Launch::new(&BF16, multi_entry(block, nt)?, [grid, 1, 1], [block, 1, 1], 0, args)
Launch::new(&BF16, multi_entry(block, nt)?, LaunchExtent::new([grid, 1, 1], [block, 1, 1], 0), args)
}
// ------------------------------------------------------------------------------------------------
@@ -230,12 +271,11 @@ pub(super) fn projection_first_row(
pub(crate) fn plan_window_mmvq(
arena: &dyn ArenaMap,
geo: &OriginalVerifyGeometry,
layer: usize,
projection: Projection,
site: WindowProjectionSite,
weight: &NativeWeight,
rows: Rows,
dispatch: NativeHeadDispatch,
) -> Result<Launch> {
let WindowProjectionSite { layer, projection, rows } = site;
let (n_in, n_out, y_span, stride) = projection_shape(geo, projection, layer)?;
let n = rows.len();
if rows.is_empty() || rows.end > geo.max_t {
@@ -244,7 +284,7 @@ pub(crate) fn plan_window_mmvq(
let first = projection_first_row(geo, projection, layer, rows.begin);
let y = arena.span(y_span, first * stride * 4, n * n_out * 4)?;
let xq = arena.span("xq", 0, n * q8_1_row_bytes(n_in))?;
plan_mmvq(weight, xq, y, n_in, n_out, n, dispatch)
plan_mmvq(weight, xq, y, MmvqExtents::new(n_in, n_out, n), dispatch)
}
impl GdnProjectionAddrs {
pub(crate) fn get(&self, projection: Projection) -> Result<NativeWeight> {
@@ -32,29 +32,29 @@ fn quantize_is_one_launch_over_all_rows() {
fn mmvq_follows_the_native_head_dispatch() {
let d = NativeHeadDispatch::default();
let q8 = NativeWeight { ty: 8, data: 0x1000 };
let one = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 1, d).unwrap();
let one = plan_mmvq(&q8, 0x2000, 0x3000, MmvqExtents::new(2560, 12288, 1), d).unwrap();
assert_eq!((one.entry, one.grid, one.block), ("head_n8_s0", [12288, 1, 1], [32, 4, 1]));
assert_eq!(one.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560), A::I32(12288)]);
let four = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 4, d).unwrap();
let four = plan_mmvq(&q8, 0x2000, 0x3000, MmvqExtents::new(2560, 12288, 4), d).unwrap();
assert_eq!((four.entry, four.grid), ("head_n8_t4_large", [12288, 1, 1]));
// 256-wide K quants, 3 rows
let q6 = NativeWeight { ty: 14, data: 0x1000 };
assert_eq!(plan_mmvq(&q6, 1, 2, 6144, 2560, 3, d).unwrap().entry, "head_n14_t3_large");
assert_eq!(plan_mmvq(&q6, 1, 2, MmvqExtents::new(6144, 2560, 3), d).unwrap().entry, "head_n14_t3_large");
// not exact: the upstream layout
let up = NativeHeadDispatch { multi_exact: false, old_iq: false };
assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 640, 3, up).unwrap().entry, "head_n8_t3_upstream");
assert_eq!(plan_mmvq(&q8, 1, 2, MmvqExtents::new(2560, 640, 3), up).unwrap().entry, "head_n8_t3_upstream");
assert_eq!(
plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, 2560, 64, 1, d).unwrap_err(),
plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, MmvqExtents::new(2560, 64, 1), d).unwrap_err(),
Error::UnsupportedQwenOperation
);
assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 0, 1, d).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(plan_mmvq(&q8, 1, 2, MmvqExtents::new(2560, 0, 1), d).unwrap_err(), Error::InvalidQwenShape);
}
#[test]
fn iq_kinds_use_the_iq_asset_with_row_bytes_and_columns() {
assert!(is_iq_kind(16) && !is_iq_kind(8) && !is_iq_kind(23));
let w = NativeWeight { ty: 16, data: 0x10 };
let l = plan_mmvq(&w, 0x20, 0x30, 2560, 1280, 3, NativeHeadDispatch::default()).unwrap();
let l = plan_mmvq(&w, 0x20, 0x30, MmvqExtents::new(2560, 1280, 3), NativeHeadDispatch::default()).unwrap();
assert!(std::ptr::eq(l.asset, &HEAD_IQ));
assert_eq!(l.entry, "head_i16_c4");
assert_eq!(l.args[1], A::U64(2560 / 256 * 66));
@@ -75,20 +75,38 @@ fn mmvf_block_matches_the_original_search() {
#[test]
fn bf16_gemv_is_single_for_one_row_and_multi_otherwise() {
let s = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 128, 2560, 128, 1).unwrap();
let s = plan_bf16_gemv(
StridedRows::new(0x1000, 2560),
0x2000,
StridedRows::new(0x3000, 128),
Bf16GemvExtents::new(2560, 128, 1),
)
.unwrap();
assert_eq!((s.entry, s.grid, s.block), ("mtp_full_mmvf256", [128, 1, 1], [256, 1, 1]));
assert_eq!(s.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560)]);
let m = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 512, 2560, 512, 4).unwrap();
let m = plan_bf16_gemv(
StridedRows::new(0x1000, 2560),
0x2000,
StridedRows::new(0x3000, 512),
Bf16GemvExtents::new(2560, 512, 4),
)
.unwrap();
assert!(m.entry.contains("ILi256ELi4EE"));
assert_eq!(m.args[1], A::I64(2560));
assert_eq!(m.args[4], A::I64(512));
assert_eq!(m.args[6], A::I32(4));
assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 5).unwrap().entry.contains("ILi256ELi8EE"));
assert!(gemv_at(0x1000, 512, Bf16GemvExtents::new(2560, 512, 5)).unwrap().entry.contains("ILi256ELi8EE"));
// one row whose output stride is narrower than the row goes through the multi kernel
assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 64, 2560, 512, 1).unwrap().entry.contains("ILi256ELi4EE"));
assert_eq!(plan_bf16_gemv(0x1004, 2560, 2, 3, 512, 2560, 512, 2).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2561, 512, 2).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 9).unwrap_err(), Error::InvalidQwenShape);
assert!(gemv_at(0x1000, 64, Bf16GemvExtents::new(2560, 512, 1)).unwrap().entry.contains("ILi256ELi4EE"));
assert_eq!(gemv_at(0x1004, 512, Bf16GemvExtents::new(2560, 512, 2)).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(gemv_at(0x1000, 512, Bf16GemvExtents::new(2561, 512, 2)).unwrap_err(), Error::InvalidQwenShape);
assert_eq!(gemv_at(0x1000, 512, Bf16GemvExtents::new(2560, 512, 9)).unwrap_err(), Error::InvalidQwenShape);
}
/// `plan_bf16_gemv` of an activation at `x_address` (rows 2560 apart) into an output at address 3 whose rows are
/// `y_stride` apart, with weight address 2.
fn gemv_at(x_address: u64, y_stride: usize, extents: Bf16GemvExtents) -> Result<Launch> {
plan_bf16_gemv(StridedRows::new(x_address, 2560), 2, StridedRows::new(3, y_stride), extents)
}
use super::super::kernels::{LayoutMap, test_geometry};
@@ -140,7 +158,13 @@ impl MmvqFixture {
fn plan(&self, layer: usize, projection: Projection, r: Rows) -> Result<Launch> {
let d = NativeHeadDispatch::default();
plan_window_mmvq(&self.m, &self.geo, layer, projection, &self.w, r, d)
plan_window_mmvq(
&self.m,
&self.geo,
WindowProjectionSite { layer: layer, projection: projection, rows: r },
&self.w,
d,
)
}
}
@@ -23,8 +23,8 @@
//! * scores / top-k / resolve / attention: `qsa_decode_scores` (Original
//! `block_scores_multi_kernel`, the Original dispatch for 1..=8 queries), `qsa_topk_ref`,
//! `leleka_qsa_resolve` + `leleka_qsa_miss_copy`, `leleka_qsa_decode_chunk` / `_merge`.
use super::kernels::{A, ArenaMap, AssetSpec, Launch};
use super::proj::{self, plan_bf16_gemv};
use super::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent};
use super::proj::{self, Bf16GemvExtents, StridedRows, plan_bf16_gemv};
use super::window_record::Rows;
use super::{OriginalVerifyGeometry, admit, handle};
use crate::qsa_index_ffi::{RopeAbi, rope_abi};
@@ -194,6 +194,21 @@ pub struct QsaRope {
pub mscale: f32,
}
/// The RoPE correction dimension range `[low, high]` of the scaling (`corr_low`, `corr_high` of `rope_scaling()`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RopeCorrectionRange {
pub low: f32,
pub high: f32,
}
/// The rows of `width` floats at device address `data` that one in-place RoPE rotates (and the RMS norm before it).
#[derive(Clone, Copy, Debug)]
pub(crate) struct RopeRows {
pub data: u64,
pub rows: usize,
pub width: usize,
}
/// Fixed device addresses of one layer's streamed INT8 KV and index keys (what Original reads from `QsaState`):
/// `st.k_q/v_q/k_scale/v_scale`, `st.page_table`, `st.host`, `st.map` and `st.idx_pooled/idx_dead`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -83,11 +83,11 @@ impl QsaRope {
pub fn new(
theta_scale: f32,
freq_scale: f32,
corr_low: f32,
corr_high: f32,
correction: RopeCorrectionRange,
ext_factor: f32,
mscale: f32,
) -> Result<Self> {
let RopeCorrectionRange { low: corr_low, high: corr_high } = correction;
for v in [theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale] {
if !v.is_finite() {
return Err(Error::InvalidQwenShape);
@@ -106,7 +106,8 @@ impl QsaRope {
if rope.angles.is_some() {
return Err(refuse!("STRATA_ROPE_TABLE angles need native_rope apply<true> (no sealed kernel)"));
}
Self::new(rope.theta_scale, rope.freq_scale, rope.corr_low, rope.corr_high, rope.ext_factor, rope.magnitude)
let correction = RopeCorrectionRange { low: rope.corr_low, high: rope.corr_high };
Self::new(rope.theta_scale, rope.freq_scale, correction, rope.ext_factor, rope.magnitude)
}
/// The identity constants `(1, 0, 0, 0, 1)` the frozen RoPE PTX bakes.
pub fn is_identity(&self) -> bool {
@@ -34,36 +34,27 @@ impl<'a> QsaWindow<'a> {
Launch::new(
&DECODE_POSTOPS,
"qsa_decode_rms",
[grid_u32(rows)?, 1, 1],
[256, 1, 1],
0,
LaunchExtent::new([grid_u32(rows)?, 1, 1], [256, 1, 1], 0),
vec![A::P(data), A::P(gamma), A::P(data), A::I32(declared_i32(cols)?), A::F32(EPS)],
)
}
pub(in super::super) fn rope_with(
&self,
abi: RopeAbi,
data: u64,
rows: usize,
width: usize,
positions: u64,
) -> Result<Launch> {
pub(in super::super) fn rope_with(&self, abi: RopeAbi, target: RopeRows, positions: u64) -> Result<Launch> {
let RopeRows { data, rows, width } = target;
if positions % 4 != 0 || rows == 0 || rows > 65535 || (width != 128 && width != 256) {
return Err(Error::InvalidQwenShape);
}
let args = self.rope_args(abi, data, rows, width, positions)?;
let args = self.rope_args(abi, target, positions)?;
// native_rope_apply: dim3 grid((head_dim / 2 + 127) / 128, rows), 128 threads
Launch::new(
&DECODE_POSTOPS,
"qsa_decode_rope",
[grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1],
[128, 1, 1],
0,
LaunchExtent::new([grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1], [128, 1, 1], 0),
args,
)
}
/// The kernel arguments of one RoPE launch; the frozen ABI refuses a scaled RoPE, the extended one appends it.
fn rope_args(&self, abi: RopeAbi, data: u64, rows: usize, width: usize, positions: u64) -> Result<Vec<A>> {
fn rope_args(&self, abi: RopeAbi, target: RopeRows, positions: u64) -> Result<Vec<A>> {
let RopeRows { data, rows, width } = target;
let r = &self.rope;
let mut args = vec![
A::P(data),
@@ -89,17 +80,11 @@ impl<'a> QsaWindow<'a> {
Ok(args)
}
pub(in super::super) fn rope(&self, data: u64, rows: usize, width: usize, positions: u64) -> Result<Launch> {
self.rope_with(rope_abi()?, data, rows, width, positions)
self.rope_with(rope_abi()?, RopeRows { data, rows, width }, positions)
}
/// `norm_rope` of verify.cpp: native RMS norm (in place) then native RoPE (in place).
pub(in super::super) fn norm_rope(
&self,
data: u64,
gamma: u64,
rows: usize,
cols: usize,
positions: u64,
) -> Result<[Launch; 2]> {
pub(in super::super) fn norm_rope(&self, target: RopeRows, gamma: u64, positions: u64) -> Result<[Launch; 2]> {
let RopeRows { data, rows, width: cols } = target;
Ok([self.rms(data, gamma, rows, cols)?, self.rope(data, rows, cols, positions)?])
}
@@ -111,7 +96,12 @@ impl<'a> QsaWindow<'a> {
let gemv = |from: usize, count: usize| -> Result<Launch> {
let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?;
let y = self.span("idx_raw_L", (q * g.max_t + from) * id * 4, count * id * 4)?;
plan_bf16_gemv(x, n_in, w.weights.index_k_proj, y, id, n_in, id, count)
plan_bf16_gemv(
StridedRows::new(x, n_in),
w.weights.index_k_proj,
StridedRows::new(y, id),
Bf16GemvExtents::new(n_in, id, count),
)
};
if batched {
return Ok(vec![gemv(s.tb, s.n)?]);
@@ -129,12 +119,12 @@ impl<'a> QsaWindow<'a> {
let data = self.span("kcur", s.tb * nkv * hd * 4, s.n * nkv * hd * 4)?;
// pos_k = pos_ + MT * NH; rows [t][NKV]
let pos = self.span("pos", (g.max_t * g.heads + s.tb * nkv) * 4, s.n * nkv * 4)?;
out.extend(self.norm_rope(data, w.weights.k_norm, s.n * nkv, hd, pos)?);
out.extend(self.norm_rope(RopeRows { data, rows: s.n * nkv, width: hd }, w.weights.k_norm, pos)?);
} else {
for t in s.tb..s.tb + s.n {
let data = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?;
let pos = self.span("pos", t * g.heads * 4, nkv * 4)?;
out.extend(self.norm_rope(data, w.weights.k_norm, nkv, hd, pos)?);
out.extend(self.norm_rope(RopeRows { data, rows: nkv, width: hd }, w.weights.k_norm, pos)?);
}
}
Ok(out)
@@ -165,7 +155,7 @@ impl<'a> QsaWindow<'a> {
let qcur = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?;
// `cudaMemcpy2DAsync(qcur, HD*4, qfull, HD*2*4, HD*4, count*NH)` as the sealed word copy
let args = vec![A::P(qfull), A::P(qcur), A::I64(count as i64)];
Launch::new(&SPLIT, "qsa_split_q", [grid_u32(count * nh)?, 1, 1], [256, 1, 1], 0, args)
Launch::new(&SPLIT, "qsa_split_q", LaunchExtent::new([grid_u32(count * nh)?, 1, 1], [256, 1, 1], 0), args)
}
/// `qsa_q_path`: q/gate split, q RMS norm with `attn_q_norm.weight`, RoPE with the query positions.
@@ -188,7 +178,7 @@ impl<'a> QsaWindow<'a> {
out.push(self.split_q(from, count)?);
let data = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?;
let pos = self.span("pos", from * nh * 4, count * nh * 4)?;
out.extend(self.norm_rope(data, w.weights.q_norm, count * nh, hd, pos)?);
out.extend(self.norm_rope(RopeRows { data, rows: count * nh, width: hd }, w.weights.q_norm, pos)?);
Ok(())
}
@@ -223,10 +213,15 @@ impl<'a> QsaWindow<'a> {
let (n_in, iq, id) = (g.n, g.index_heads, g.index_dim);
let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?;
let y = self.span("qidx", from * iq * id * 4, count * iq * id * 4)?;
out.push(plan_bf16_gemv(x, n_in, w.weights.index_q_proj, y, iq * id, n_in, iq * id, count)?);
out.push(plan_bf16_gemv(
StridedRows::new(x, n_in),
w.weights.index_q_proj,
StridedRows::new(y, iq * id),
Bf16GemvExtents::new(n_in, iq * id, count),
)?);
let data = self.span("qidx", from * iq * id * 4, count * iq * id * 4)?;
let pos = self.span("pos", pos.0, pos.1)?;
out.extend(self.norm_rope(data, w.weights.index_q_norm, count * iq, id, pos)?);
out.extend(self.norm_rope(RopeRows { data, rows: count * iq, width: id }, w.weights.index_q_norm, pos)?);
Ok(())
}
}
@@ -238,5 +233,5 @@ fn append_launch(kv: &OriginalVerifyQsaKvBinding, [step, k, v]: [u64; 3], (nkv,
args.extend([A::P(kv.table), A::P(step), A::P(k), A::P(v)]);
args.extend([A::I32(declared_i32(nkv)?), A::I32(declared_i32(hd)?), A::I32(PAGE_SIZE)]);
args.extend(kv.host.iter().map(|&a| A::P(a)));
Launch::new(&KV_APPEND, "mtp_original_append", grid, [64, 1, 1], 0, args)
Launch::new(&KV_APPEND, "mtp_original_append", LaunchExtent::new(grid, [64, 1, 1], 0), args)
}
@@ -35,11 +35,16 @@ impl<'a> QsaWindow<'a> {
A::I64(mb as i64),
A::P(scores),
];
return Launch::new(&SELECT, "qsa_decode_scores", [256, 1, 1], [256, 1, 1], 0, args);
return Launch::new(&SELECT, "qsa_decode_scores", LaunchExtent::new([256, 1, 1], [256, 1, 1], 0), args);
}
// block_scores_kernel<<<(ceil(max_blocks / 8), nq), 256>>>
let args = vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I64(mb as i64), A::P(scores)];
Launch::new(&SELECT, SCORE_SINGLE, [grid_u32(mb.div_ceil(8))?, grid_u32(n)?, 1], [256, 1, 1], 0, args)
Launch::new(
&SELECT,
SCORE_SINGLE,
LaunchExtent::new([grid_u32(mb.div_ceil(8))?, grid_u32(n)?, 1], [256, 1, 1], 0),
args,
)
}
/// The top-k of `n` queries over the block scores: the thread-block cluster kernel, or `qsa_topk_ref`.
@@ -50,10 +55,10 @@ impl<'a> QsaWindow<'a> {
// the same ids
let grid = [crate::qsa_cluster::CLUSTER_CTAS, grid_u32(n)?, 1];
let (block, smem) = ([crate::qsa_cluster::BLOCK, 1, 1], crate::qsa_cluster::dynamic_smem(mb));
let launch = Launch::new(&CLUSTER, CLUSTER_ENTRIES[0], grid, block, smem, args)?;
let launch = Launch::new(&CLUSTER, CLUSTER_ENTRIES[0], LaunchExtent::new(grid, block, smem), args)?;
return Ok(launch.clustered(crate::qsa_cluster::CLUSTER_CTAS));
}
Launch::new(&SELECT, "qsa_topk_ref", [grid_u32(n)?, 1, 1], [256, 1, 1], 0, args)
Launch::new(&SELECT, "qsa_topk_ref", LaunchExtent::new([grid_u32(n)?, 1, 1], [256, 1, 1], 0), args)
}
/// `qsa_kv_resolve`: the selections' blocks resident, device side (`kv_stream_resolve`).
@@ -73,8 +78,8 @@ impl<'a> QsaWindow<'a> {
let mut copy = vec![A::P(r[4]), A::P(r[5]), A::P(r[6])];
copy.extend(w.kv.host.iter().chain(&w.kv.resident).map(|&a| A::P(a)));
Ok(vec![
Launch::new(&RESOLVER, "leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1], 0, resolve)?,
Launch::new(&RESOLVER, "leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1], 0, copy)?,
Launch::new(&RESOLVER, "leleka_qsa_resolve", LaunchExtent::new([1, 1, 1], [1024, 1, 1], 0), resolve)?,
Launch::new(&RESOLVER, "leleka_qsa_miss_copy", LaunchExtent::new([96, 1, 1], [128, 1, 1], 0), copy)?,
])
}
@@ -119,7 +124,7 @@ impl<'a> QsaWindow<'a> {
args.extend([A::P(w.kv.table), A::P(a.ids), A::P(a.steps), A::I32(declared_i32(d.nkv)?), A::I32(PAGE_SIZE)]);
args.extend([A::F32(a.scale), A::P(a.acc), A::P(a.part_m), A::P(a.part_l)]);
args.extend([A::I32(declared_i32(d.chunks)?), A::I32(declared_i32(d.cap)?), A::I64(d.stride as i64)]);
Launch::new(chunk_asset, chunk_entry, grid, [256, 1, 1], 0, args)
Launch::new(chunk_asset, chunk_entry, LaunchExtent::new(grid, [256, 1, 1], 0), args)
}
/// The merge kernel (`[n_head, n]` grid): the chunk accumulators combined into the attention output.
@@ -131,10 +136,10 @@ impl<'a> QsaWindow<'a> {
if self.policy.attn_daily {
let (asset, entry) = (&super::super::super::sm120::ATTN_DAILY, super::super::super::sm120::E_ATTN_MERGE_V2);
let args = vec![A::P(a.acc), A::P(a.part_m), A::P(a.part_l), chunks, A::P(a.steps), A::P(a.attn), tail];
return Launch::new(asset, entry, grid, [256, 1, 1], 0, args);
return Launch::new(asset, entry, LaunchExtent::new(grid, [256, 1, 1], 0), args);
}
let args = vec![A::P(a.acc), A::P(a.part_m), A::P(a.part_l), chunks, A::P(a.attn), tail];
Launch::new(&ATTENTION, "leleka_qsa_decode_merge", grid, [256, 1, 1], 0, args)
Launch::new(&ATTENTION, "leleka_qsa_decode_merge", LaunchExtent::new(grid, [256, 1, 1], 0), args)
}
/// `qsa_gate`: `native_qsa_gate_apply(attn, qfull, attn32, heads, HD)`; batched = one launch over `n * NH` heads.
@@ -150,9 +155,7 @@ impl<'a> QsaWindow<'a> {
Launch::new(
&GATE,
"verify_window_qsa_gate",
[grid_u32((heads * hd).div_ceil(256))?, 1, 1],
[256, 1, 1],
0,
LaunchExtent::new([grid_u32((heads * hd).div_ceil(256))?, 1, 1], [256, 1, 1], 0),
vec![A::P(attn), A::P(qfull), A::P(out), A::I32(declared_i32(heads)?), A::I32(declared_i32(hd)?)],
)
};
@@ -26,7 +26,7 @@ fn layer() -> QsaLayerAddrs {
QsaLayerAddrs { weights: W, kv: KV }
}
fn identity() -> QsaRope {
QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0).unwrap()
QsaRope::new(0.7498942, 1.0, RopeCorrectionRange { low: 0.0, high: 0.0 }, 0.0, 1.0).unwrap()
}
fn rows(begin: usize, end: usize) -> Rows {
Rows { begin, end, group: if begin == 0 { 0 } else { 1 } }
@@ -105,11 +105,11 @@ fn policy_refuses_every_variant_without_a_sealed_owner() {
#[test]
fn rope_constants_refuse_tables_and_non_finite_values() {
assert!(QsaRope::new(f32::NAN, 1.0, 0.0, 0.0, 0.0, 1.0).is_err());
assert!(QsaRope::new(0.7, 0.0, 0.0, 0.0, 0.0, 1.0).is_err());
assert!(QsaRope::new(0.7, 1.0, 0.0, 0.0, -1.0, 1.0).is_err());
assert!(QsaRope::new(f32::NAN, 1.0, RopeCorrectionRange { low: 0.0, high: 0.0 }, 0.0, 1.0).is_err());
assert!(QsaRope::new(0.7, 0.0, RopeCorrectionRange { low: 0.0, high: 0.0 }, 0.0, 1.0).is_err());
assert!(QsaRope::new(0.7, 1.0, RopeCorrectionRange { low: 0.0, high: 0.0 }, -1.0, 1.0).is_err());
assert!(identity().is_identity());
assert!(!QsaRope::new(0.7, 0.5, 0.0, 0.0, 1.0, 1.1).unwrap().is_identity());
assert!(!QsaRope::new(0.7, 0.5, RopeCorrectionRange { low: 0.0, high: 0.0 }, 1.0, 1.1).unwrap().is_identity());
}
/// One multi-token gemv of `n` rows: x = mixed, ldx = 2560, w, y = idx_raw layer 2 row 0, ldy = 128, n_in = 2560,
@@ -214,21 +214,24 @@ fn k_norm_rope_per_token_uses_the_pos_rows_of_the_query_layout() {
#[test]
fn the_rope_entry_follows_the_declared_abi_and_refuses_scaling_on_frozen_ptx() {
let (m, g) = setup();
let scaled = QsaRope::new(0.7498942, 0.5, 1.0, 20.0, 1.0, 1.1).unwrap();
let scaled = QsaRope::new(0.7498942, 0.5, RopeCorrectionRange { low: 1.0, high: 20.0 }, 1.0, 1.1).unwrap();
let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), scaled).unwrap();
let frozen = w.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2000).unwrap_err();
let frozen = w.rope_with(RopeAbi::Frozen, RopeRows { data: 0x1000, rows: 4, width: 256 }, 0x2000).unwrap_err();
assert!(matches!(frozen, Error::InvalidDriverValue(msg) if msg.contains("ROPE-ARGS ABI 1")));
let ext = w.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap();
let ext = w.rope_with(RopeAbi::Extended, RopeRows { data: 0x1000, rows: 4, width: 256 }, 0x2000).unwrap();
assert_eq!(ext.args.len(), 11);
assert_eq!(ext.args[6..], [A::F32(0.5), A::F32(1.0), A::F32(20.0), A::F32(1.0), A::F32(1.1)]);
let id = window(&m, g);
let fro = id.rope_with(RopeAbi::Frozen, 0x1000, 128, 128, 0x2000).unwrap();
let fro = id.rope_with(RopeAbi::Frozen, RopeRows { data: 0x1000, rows: 128, width: 128 }, 0x2000).unwrap();
assert_eq!(fro.args.len(), 6);
assert_eq!(fro.grid, [1, 128, 1]);
assert_eq!(id.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap().args.len(), 11);
assert_eq!(
id.rope_with(RopeAbi::Extended, RopeRows { data: 0x1000, rows: 4, width: 256 }, 0x2000).unwrap().args.len(),
11
);
// positions are 4-byte aligned, widths 128/256 only
assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2002).is_err());
assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 64, 0x2000).is_err());
assert!(id.rope_with(RopeAbi::Frozen, RopeRows { data: 0x1000, rows: 4, width: 256 }, 0x2002).is_err());
assert!(id.rope_with(RopeAbi::Frozen, RopeRows { data: 0x1000, rows: 4, width: 64 }, 0x2000).is_err());
}
/// Row `1 + i` of the window appends through one launch driven by its own step word, with the host mirror.
@@ -61,9 +61,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
vec![crate::original_verify::kernels::Launch::new(
&crate::original_verify::draft::DRAFT_COMMIT_QSA,
crate::original_verify::draft::E_QSA,
[12, 1, 1],
[128, 4, 1],
0,
crate::original_verify::kernels::LaunchExtent::new([12, 1, 1], [128, 4, 1], 0),
vec![crate::original_verify::kernels::A::Words(words)],
)?],
)?;
+7 -5
View File
@@ -228,6 +228,7 @@ pub use original_verify::{
OriginalVerifyGdnStage, OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGpuPlan,
OriginalVerifyGraphResources, OriginalVerifyLayout, OriginalVerifyPcieSource, OriginalVerifyResources,
OriginalVerifyRow, OriginalVerifySpan, OriginalVerifyWindow, OriginalVerifyWindowResult,
OriginalVerifyWindowTokens,
};
// Live verifier release/diagnostic owner, profile report and completed-logit readout.
#[allow(unused_imports)]
@@ -257,11 +258,12 @@ pub use original_serve_assets::{
};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
pub use original_verify::{
ExpertTier, HcHalf, OriginalVerifyDiag, OriginalVerifyExpertLayout, OriginalVerifyProfile,
OriginalVerifyWindowResources, PROFILE_STAMPS_PER_LAYER, PlanLayout, Projection, QuantSource, RowLogprob,
Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS, WindowOps as OriginalVerifyWindowOps,
WindowPolicy as OriginalVerifyWindowPolicy, analyse_row, logpos_topk_from_environment, original_verify_diagnostics,
original_verify_live_count, original_verify_release_live, profile_stamp_slot, profile_stamp_words,
ExpertTier, HcHalf, LogitRows, LogprobReadout, OriginalVerifyDiag, OriginalVerifyExpertLayout,
OriginalVerifyProfile, OriginalVerifyWindowResources, PROFILE_STAMPS_PER_LAYER, PlanLayout, Projection,
QuantSource, RowLogprob, Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS,
WindowOps as OriginalVerifyWindowOps, WindowPolicy as OriginalVerifyWindowPolicy, analyse_row,
logpos_topk_from_environment, original_verify_diagnostics, original_verify_live_count,
original_verify_release_live, profile_stamp_slot, profile_stamp_words,
record_window as record_original_verify_window, top_k, write_original_verify_diagnostics, write_row_line,
write_window_logprobs,
};
@@ -84,13 +84,13 @@ impl<'ctx> Replay<'ctx> {
t: usize,
sampled: Option<SamplerPath>,
) -> Option<(NativeHeadSelection, Option<OriginalVerifyWindow<'ctx>>)> {
let position = self.position;
let tokens: Vec<i32> = (0..t).map(|i| 100 + i as i32).collect();
let ple = vec![0.0f32; t * 2560];
let sampling = self.sampling(sampled);
let (position, sampling) = (self.position, self.sampling(sampled));
let started = std::time::Instant::now();
let mut groups_seen = 0usize;
let result = verifier.run(&tokens, position, Some(&ple), sampling, |_rows, sink, _copy| {
let window_tokens = OriginalVerifyWindowTokens { tokens: &tokens, position, ple: Some(&ple) };
let result = verifier.run(window_tokens, sampling, |_rows, sink, _copy| {
groups_seen += 1;
sink.with_output(|out| {
out.fill(0.0);
@@ -7,13 +7,12 @@
//! evicted an earlier one), and `original_verify_moe` lends them. Nothing is copied or re-encoded: the
//! routed experts are not here (the verifier's expert tier is the pool callback).
use super::*;
use crate::qwen_forward::original_serve_verifier::VerifyWeights;
use crate::qwen_forward::{
contract::{Dimension, LayerId},
dense_weight_cache::DenseWeightCache,
};
use leleka_cuda_driver::{
OriginalVerifyExpertFormats, OriginalVerifyGeometry, OriginalVerifyMoeBinding, OriginalVerifyMoeLayerWeights,
};
use leleka_cuda_driver::{OriginalVerifyGeometry, OriginalVerifyMoeBinding, OriginalVerifyMoeLayerWeights};
/// Descriptors of one layer's shared gate, up, down and the shared scalar, in that order.
pub(in crate::qwen_forward) type SharedKeys = Vec<[MoeWeightDescriptor; 4]>;
@@ -71,25 +70,25 @@ impl<'ctx> MoeWeightCache<'ctx> {
down_shexp_type: keys[2].raw_kind,
})
}
}
impl<'a, 'ctx> VerifyWeights<'a, 'ctx> {
/// The router and shared-expert operands of the 48 layers plus the routed experts' formats.
pub(in crate::qwen_forward) fn original_verify_moe<'a>(
&'a self,
pub(in crate::qwen_forward) fn original_verify_moe(
&self,
binding: &ModelBinding,
dense: &'a DenseWeightCache<'ctx>,
geometry: &OriginalVerifyGeometry,
shared: &SharedKeys,
formats: OriginalVerifyExpertFormats,
) -> Result<OriginalVerifyMoeBinding<'a, 'ctx>> {
self.validate(binding, self.context)?;
let (moe, dense, shared) = (self.moe, self.dense, self.shared);
moe.validate(binding, moe.context)?;
if shared.len() != 48 {
return Err(Error::InvalidLayer);
}
let mut layers = Vec::new();
layers.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?;
for (layer, keys) in shared.iter().enumerate() {
layers.push(self.verify_moe_layer(binding, dense, layer, keys)?);
layers.push(moe.verify_moe_layer(binding, dense, layer, keys)?);
}
OriginalVerifyMoeBinding::new(self.context, geometry, layers, formats).map_err(driver_error)
OriginalVerifyMoeBinding::new(moe.context, geometry, layers, self.formats.clone()).map_err(driver_error)
}
}
@@ -6,7 +6,9 @@ use super::super::original_serve_pool::window_trace;
use super::super::output_native::{HeadSamplerChoice, SamplingWindow};
#[allow(unused_imports)]
use super::*;
use leleka_cuda_driver::{NativeHeadSampling, OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink};
use leleka_cuda_driver::{
NativeHeadSampling, OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyWindowTokens,
};
use std::time::Instant;
/// One layer group through the expert pool, with the pool's wall time in the window trace. A pool refusal is kept in
@@ -67,9 +69,11 @@ where
let (sampling, pool) = staged;
let _p = profile::span("window.verifier");
let verifier_clock = window_trace::now();
let ran = verifier.run(inputs, first, ple, sampling, |rows, sink, copy| {
run_pool_group(&mut *pool, (rows, sink, copy), &mut *cells.pool_error)
});
let ran = verifier.run(
OriginalVerifyWindowTokens { tokens: inputs, position: first, ple },
sampling,
|rows, sink, copy| run_pool_group(&mut *pool, (rows, sink, copy), &mut *cells.pool_error),
);
if let Some(c) = verifier_clock {
*cells.verifier_ms = c.elapsed().as_secs_f64() * 1e3;
}
@@ -112,7 +112,7 @@ fn with_qsa_moe<'a, 'ctx>(
let (binding, weights, geometry) = (env.binding, env.weights, &env.geometry);
let dense = weights.dense;
let window = window.with_qsa(dense.original_verify_qsa(binding, geometry)?)?;
let moe = weights.moe.original_verify_moe(binding, dense, geometry, weights.shared, weights.formats.clone())?;
let moe = weights.original_verify_moe(binding, geometry)?;
Ok(window.with_moe(moe)?)
}